Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(models): use models.dev as metadata authority
vastsa62cf3c2578a0
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 0f9613382..9c774d407 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -261,7 +261,11 @@ const updater = new AppUpdaterController({* this process; the renderer sees progress events and the sidecar sees only* resolved request auth.*/-const modelsDevCatalog = new ModelsDevCatalog();+const modelsDevCatalog = new ModelsDevCatalog({+ catalogPath: app.isPackaged+ ? join(process.resourcesPath, "models.dev", "api.json")+ : join(app.getAppPath(), "resources", "models.dev", "api.json"),+});const vendorOAuth = new VendorOAuth({call: <T,>(method: string, params?: unknown): Promise<T> => {diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.tsindex acc8b04f1..9926a5831 100644--- a/apps/desktop/electron/main/ipc/provider-ipc.ts+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts@@ -462,7 +462,7 @@ export function registerProviderIpc({// ModelInfo is catalog metadata. Keep its published reasoning fields// intact; Composer and runtime resolve the exact user binding when// they need effective per-provider capabilities.- ...(modelsDevModel ? { catalogSource: "pi" as const } : {}),+ ...(modelsDevModel ? { catalogSource: "models.dev" as const } : {}),};};diff --git a/apps/desktop/electron/main/models-dev-catalog.ts b/apps/desktop/electron/main/models-dev-catalog.tsindex 430a42321..fbf42f28c 100644--- a/apps/desktop/electron/main/models-dev-catalog.ts+++ b/apps/desktop/electron/main/models-dev-catalog.ts@@ -1,22 +1,116 @@-import { PI_VENDOR_ALIASES, relayChatMetadata, settingsOperationMetadata } from "./pi-model-metadata.ts";+import { readFile } from "node:fs/promises";import {createModels,- getSupportedThinkingLevels,InMemoryModelsStore,- type Api,- type Model,- type Models,+ type Model as PiModel,type MutableModels,type ModelType,type ModelTypeMap,type Provider,} from "@earendil-works/pi-ai";import { builtinProviders } from "@earendil-works/pi-ai/providers/all";-import { matchNamedPreset, resolveBindingLimits, THINKING_LEVELS, type ModelBinding, type ModelInfo } from "@pi-desktop/shared";-import { genericModelConfig, modelConfigFromPi, modelConfigWithBinding, type ModelConfig } from "@pi-desktop/agent-runtime";+import { PI_VENDOR_ALIASES, settingsOperationMetadata } from "./pi-model-metadata.ts";+import {+ MODEL_VENDOR_PREFIXES,+ NAMED_ENDPOINT_PRESETS,+ catalogModelIdsMatch,+ stripReleaseSuffix,+ stripVariantSuffix,+} from "@pi-desktop/shared";+import type {+ ModelCost,+ ModelCostTier,+ ModelExperimentalMetadata,+ ModelInfo,+ ModelInterleaved,+ ModelLimit,+ ModelModalities,+ ModelModality,+ ModelProviderMetadata,+ ModelReasoningOption,+ ThinkingLevel,+ ThinkingProtocol,+ ModelBinding,+} from "@pi-desktop/shared";+import { genericModelConfig, modelConfigWithBinding, type ModelConfig } from "@pi-desktop/agent-runtime";+import { resolveBindingLimits } from "@pi-desktop/shared";++export const MODELS_DEV_API_URL = "https://models.dev/api.json";+export const MODELS_DEV_TIMEOUT_MS = 10_000;+const LOOKUP_MEMO_LIMIT = 1_024;+const DEFAULT_CONTEXT_WINDOW = 128_000;+const DEFAULT_MAX_TOKENS = 8_192;+const DEFAULT_THINKING_LEVELS: ThinkingLevel[] = ["low", "medium", "high"];+const THINKING_LEVELS: readonly ThinkingLevel[] = [+ "off",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+];+const MODEL_MODALITIES: readonly ModelModality[] = [+ "text",+ "image",+ "audio",+ "video",+ "pdf",+];++type JsonRecord = Record<string, unknown>;++export type ModelsDevProvider = {+ providerKey: string;+ name: string;+ api?: string;+ /** Published adapter package, the most reliable wire-API signal. */+ npm?: string;+ /** Published environment variable names that carry this provider's key. */+ env: string[];+ /** Provider documentation URL, when published. */+ doc?: string;+ models: ModelsDevModel[];+};++export type ModelsDevModel = {+ providerKey: string;+ providerName: string;+ providerApi?: string;+ /**+ * Wire API published for this model (e.g. "openai-responses").+ * models.dev omits it; modelFromRaw fills known ids from RESPONSES_ONLY_MODEL_IDS.+ */+ modelApi?: string;+ modelId: string;+ displayName: string;+ description?: string;+ family?: string;+ attachment?: boolean;+ reasoning: boolean;+ reasoningPublished: boolean;+ reasoningOptions?: ModelReasoningOption[];+ thinkingProtocol?: ThinkingProtocol;+ thinkingLevels: ThinkingLevel[];+ modalities: ModelModalities;+ modalitiesPublished: boolean;+ inputPublished: boolean;+ outputPublished: boolean;+ toolCall?: boolean;+ structuredOutput?: boolean;+ temperature?: boolean;+ knowledge?: string;+ releaseDate?: string;+ lastUpdated?: string;+ openWeights?: boolean;+ limit: ModelLimit;+ cost?: ModelCost;+ interleaved?: ModelInterleaved;+ status?: string;+ experimental?: ModelExperimentalMetadata;+ provider?: ModelProviderMetadata;+};-/** Compatibility type names only. The independent models.dev catalog is removed. */-export type ModelsDevModel = Model<Api>;export type ModelsDevCatalogStatus = {loaded: boolean;source: "bundled" | "remote" | "empty";@@ -26,276 +120,1489 @@ export type ModelsDevCatalogStatus = {modelCount: number;lastError?: string;};+export type ModelsDevCatalogOptions = {- /** Accepted for existing boot callers; Pi packages own the offline catalog. */- catalogPath?: string;- providers?: readonly Provider[];+ /** Checked-in/release-packaged api.json; never a user-data path. */+ catalogPath: string;+ fetchImpl?: typeof fetch;+ timeoutMs?: number;now?: () => number;+ /** Optional Pi providers used only for executable non-chat operations. */+ providers?: readonly Provider[];+};++export type CatalogAccount = {+ id: string;+ vendorKey?: string;+ baseUrl?: string;+ apiStyle?: string;+ models?: ModelBinding[];+};++type CatalogTarget = {+ providerId?: string;+ vendorKey?: string;+ baseUrl?: string;+ apiStyle?: string;+ modelId: string;+};++function asRecord(value: unknown): JsonRecord | null {+ return value && typeof value === "object" && !Array.isArray(value)+ ? (value as JsonRecord)+ : null;+}++function nonEmptyString(value: unknown): string | undefined {+ return typeof value === "string" && value.trim() ? value.trim() : undefined;+}++function stringArray(value: unknown): string[] {+ if (!Array.isArray(value)) return [];+ return [+ ...new Set(+ value+ .map((entry) => nonEmptyString(entry))+ .filter((entry): entry is string => entry !== undefined),+ ),+ ];+}++function publishedMetadata(value: unknown): ModelProviderMetadata | undefined {+ if (typeof value === "string") return nonEmptyString(value);+ return asRecord(value) ?? undefined;+}++function publishedExperimental(value: unknown): ModelExperimentalMetadata | undefined {+ if (typeof value === "boolean") return value;+ return asRecord(value) ?? undefined;+}++function nonNegativeNumber(value: unknown): number | undefined {+ return typeof value === "number" && Number.isFinite(value) && value >= 0+ ? value+ : undefined;+}++function nonNegativeInteger(value: unknown): number | undefined {+ return typeof value === "number" &&+ Number.isSafeInteger(value) &&+ value >= 0 &&+ value <= 0xffff_ffff+ ? value+ : undefined;+}++function positiveInteger(value: unknown): number | undefined {+ const number = nonNegativeInteger(value);+ return number !== undefined && number > 0 ? number : undefined;+}++function parseModality(value: unknown): ModelModality | undefined {+ return typeof value === "string" && MODEL_MODALITIES.includes(value as ModelModality)+ ? (value as ModelModality)+ : undefined;+}++function parseModalities(value: unknown): {+ modalities: ModelModalities;+ published: boolean;+ inputPublished: boolean;+ outputPublished: boolean;+} {+ const record = asRecord(value);+ const rawInput = Array.isArray(record?.input) ? record.input : undefined;+ const rawOutput = Array.isArray(record?.output) ? record.output : undefined;+ const input = rawInput?.map(parseModality).filter(+ (item): item is ModelModality => item !== undefined,+ ) ?? [];+ const output = rawOutput?.map(parseModality).filter(+ (item): item is ModelModality => item !== undefined,+ ) ?? [];+ return {+ modalities: {+ input: input.length > 0 ? [...new Set(input)] : ["text"],+ output: output.length > 0 ? [...new Set(output)] : ["text"],+ },+ published: rawInput !== undefined || rawOutput !== undefined,+ inputPublished: rawInput !== undefined && input.length > 0,+ outputPublished: rawOutput !== undefined && output.length > 0,+ };+}++function normalizeThinkingValue(value: unknown): ThinkingLevel | undefined {+ if (value === "none") return "off";+ return typeof value === "string" &&+ (THINKING_LEVELS as readonly string[]).includes(value)+ ? (value as ThinkingLevel)+ : undefined;+}++function parseReasoningOptions(value: unknown): ModelReasoningOption[] | undefined {+ if (!Array.isArray(value)) return undefined;+ const options = value.flatMap((entry) => {+ const record = asRecord(entry);+ const type = nonEmptyString(record?.type);+ if (!type) return [];+ const values = Array.isArray(record?.values)+ ? record.values.filter(+ (item): item is string | null => typeof item === "string" || item === null,+ )+ : undefined;+ const min = nonNegativeNumber(record?.min);+ const max = nonNegativeNumber(record?.max);+ return [{+ type,+ ...(values ? { values } : {}),+ ...(min !== undefined ? { min } : {}),+ ...(max !== undefined ? { max } : {}),+ }];+ });+ return options;+}++/** Convert models.dev reasoning options into the canonical UI levels. */+export function thinkingLevelsFromModelsDev(+ reasoning: boolean,+ options: unknown,+): ThinkingLevel[] {+ if (!reasoning) return [];+ const levels = new Set<ThinkingLevel>();+ if (Array.isArray(options)) {+ for (const option of options) {+ const record = asRecord(option);+ const type = nonEmptyString(record?.type);+ if (type === "toggle" || type === "budget_tokens") {+ levels.add("off");+ levels.add("medium");+ }+ if (Array.isArray(record?.values)) {+ for (const value of record.values) {+ const level = normalizeThinkingValue(value);+ if (level) levels.add(level);+ }+ }+ }+ }+ return levels.size > 0+ ? THINKING_LEVELS.filter((level) => levels.has(level))+ : [...DEFAULT_THINKING_LEVELS];+}++function thinkingLevelMapFromModelsDev(+ options: ModelReasoningOption[] | undefined,+ levels: ThinkingLevel[],+): Partial<Record<ThinkingLevel, string | null>> | undefined {+ if (!options?.length) return undefined;+ const map: Partial<Record<ThinkingLevel, string | null>> = {};+ for (const option of options) {+ if (option.type === "toggle" || option.type === "budget_tokens") {+ if (levels.includes("off")) map.off = "none";+ if (levels.includes("medium")) map.medium = "medium";+ }+ for (const value of option.values ?? []) {+ const level = normalizeThinkingValue(value);+ if (level && typeof value === "string") map[level] = value;+ }+ }+ // models.dev effort ladders often omit an off/none value (e.g. grok-4.6).+ // Pin off=null so adapters omit reasoning when thinking is turned off,+ // instead of synthesizing effort: "none" which upstream rejects (#603).+ if (+ Object.keys(map).length > 0 &&+ map.off === undefined &&+ !levels.includes("off")+ ) {+ map.off = null;+ }+ return Object.keys(map).length > 0 ? map : undefined;+}++function parseLimit(value: unknown): ModelLimit {+ const record = asRecord(value);+ const context = nonNegativeInteger(record?.context);+ const input = nonNegativeInteger(record?.input);+ const output = nonNegativeInteger(record?.output);+ return {+ ...(context !== undefined ? { context } : {}),+ ...(input !== undefined ? { input } : {}),+ ...(output !== undefined ? { output } : {}),+ };+}++function parseCostTier(value: unknown): ModelCostTier | undefined {+ const record = asRecord(value);+ if (!record) return undefined;+ const input = nonNegativeNumber(record.input);+ const output = nonNegativeNumber(record.output);+ const cacheRead = nonNegativeNumber(record.cache_read);+ const cacheWrite = nonNegativeNumber(record.cache_write);+ const tierRecord = asRecord(record.tier);+ const tierType = nonEmptyString(tierRecord?.type);+ const tierSize = positiveInteger(tierRecord?.size);+ if (+ input === undefined &&+ output === undefined &&+ cacheRead === undefined &&+ cacheWrite === undefined &&+ !tierType &&+ tierSize === undefined+ ) return undefined;+ return {+ ...(input !== undefined ? { input } : {}),+ ...(output !== undefined ? { output } : {}),+ ...(cacheRead !== undefined ? { cacheRead } : {}),+ ...(cacheWrite !== undefined ? { cacheWrite } : {}),+ ...(tierType || tierSize !== undefined+ ? {+ tier: {+ ...(tierType ? { type: tierType } : {}),+ ...(tierSize !== undefined ? { size: tierSize } : {}),+ },+ }+ : {}),+ };+}++function parseCost(value: unknown): ModelCost | undefined {+ const record = asRecord(value);+ if (!record) return undefined;+ const input = nonNegativeNumber(record.input);+ const output = nonNegativeNumber(record.output);+ const cacheRead = nonNegativeNumber(record.cache_read);+ const cacheWrite = nonNegativeNumber(record.cache_write);+ const reasoning = nonNegativeNumber(record.reasoning);+ const inputAudio = nonNegativeNumber(record.input_audio);+ const outputAudio = nonNegativeNumber(record.output_audio);+ const contextOver = asRecord(record.context_over_200k);+ const contextOver200k = contextOver+ ? {+ ...(nonNegativeNumber(contextOver.input) !== undefined+ ? { input: nonNegativeNumber(contextOver.input) }+ : {}),+ ...(nonNegativeNumber(contextOver.output) !== undefined+ ? { output: nonNegativeNumber(contextOver.output) }+ : {}),+ ...(nonNegativeNumber(contextOver.cache_read) !== undefined+ ? { cacheRead: nonNegativeNumber(contextOver.cache_read) }+ : {}),+ ...(nonNegativeNumber(contextOver.cache_write) !== undefined+ ? { cacheWrite: nonNegativeNumber(contextOver.cache_write) }+ : {}),+ }+ : undefined;+ const tiers = Array.isArray(record.tiers)+ ? record.tiers+ .map(parseCostTier)+ .filter((item): item is ModelCostTier => item !== undefined)+ : undefined;+ if (+ input === undefined &&+ output === undefined &&+ cacheRead === undefined &&+ cacheWrite === undefined &&+ reasoning === undefined &&+ inputAudio === undefined &&+ outputAudio === undefined &&+ !contextOver200k &&+ !tiers?.length+ ) return undefined;+ return {+ ...(input !== undefined ? { input } : {}),+ ...(output !== undefined ? { output } : {}),+ ...(cacheRead !== undefined ? { cacheRead } : {}),+ ...(cacheWrite !== undefined ? { cacheWrite } : {}),+ ...(reasoning !== undefined ? { reasoning } : {}),+ ...(inputAudio !== undefined ? { inputAudio } : {}),+ ...(outputAudio !== undefined ? { outputAudio } : {}),+ ...(contextOver200k ? { contextOver200k } : {}),+ ...(tiers?.length ? { tiers } : {}),+ };+}++function parseInterleaved(value: unknown): ModelInterleaved | undefined {+ if (typeof value === "boolean") return value;+ const record = asRecord(value);+ const field = nonEmptyString(record?.field);+ return field ? { field } : undefined;+}++/**+ * models.dev publishes no per-model wire API, yet some models only serve one.+ * Keep this list to verified responses-only ids; everything else falls back+ * to the provider-wide style (see #105).+ */+const RESPONSES_ONLY_MODEL_IDS: ReadonlySet<string> = new Set([+ "muse-spark-1.2-contributor",+ "muse-spark-1.3-contributor",+]);++function modelFromRaw(+ providerKey: string,+ provider: JsonRecord,+ modelKey: string,+ raw: JsonRecord,+): ModelsDevModel | undefined {+ const modelId = nonEmptyString(raw.id) ?? modelKey.trim();+ if (!modelId) return undefined;+ const modalityResult = parseModalities(raw.modalities);+ const reasoningPublished = typeof raw.reasoning === "boolean";+ const reasoning = raw.reasoning === true;+ const reasoningOptions = parseReasoningOptions(raw.reasoning_options);+ const thinkingProtocol: ThinkingProtocol | undefined =+ providerKey === "anthropic" && reasoning &&+ reasoningOptions?.some((option) => option.type === "effort") &&+ !reasoningOptions.some((option) => option.type === "budget_tokens")+ ? "adaptive"+ : undefined;+ const limit = parseLimit(raw.limit);+ const experimental = publishedExperimental(raw.experimental);+ const providerMetadata = publishedMetadata(raw.provider);+ // Scoped to opencode-go on purpose: the same model ids exist under other+ // providers (e.g. meta, llmgateway) where the completions path is correct+ // and must not be rerouted (see #105).+ const modelApi =+ nonEmptyString(raw.api) ??+ (providerKey === "opencode-go" && RESPONSES_ONLY_MODEL_IDS.has(modelId.toLowerCase())+ ? "openai-responses"+ : undefined);+ const displayName = nonEmptyString(raw.name) ?? modelId;+ const inputPublished = modalityResult.inputPublished;+ const outputPublished = modalityResult.outputPublished;+ return {+ providerKey,+ providerName: nonEmptyString(provider.name) ?? providerKey,+ ...(nonEmptyString(provider.api) ? { providerApi: nonEmptyString(provider.api) } : {}),+ modelId,+ displayName,+ ...(nonEmptyString(raw.description) ? { description: nonEmptyString(raw.description) } : {}),+ ...(nonEmptyString(raw.family) ? { family: nonEmptyString(raw.family) } : {}),+ ...(typeof raw.attachment === "boolean" ? { attachment: raw.attachment } : {}),+ reasoning,+ reasoningPublished,+ ...(reasoningOptions ? { reasoningOptions } : {}),+ ...(thinkingProtocol ? { thinkingProtocol } : {}),+ thinkingLevels: thinkingLevelsFromModelsDev(reasoning, raw.reasoning_options),+ modalities: modalityResult.modalities,+ modalitiesPublished: modalityResult.published,+ inputPublished,+ outputPublished,+ ...(typeof raw.tool_call === "boolean" ? { toolCall: raw.tool_call } : {}),+ ...(typeof raw.structured_output === "boolean" ? { structuredOutput: raw.structured_output } : {}),+ ...(typeof raw.temperature === "boolean" ? { temperature: raw.temperature } : {}),+ ...(nonEmptyString(raw.knowledge) ? { knowledge: nonEmptyString(raw.knowledge) } : {}),+ ...(nonEmptyString(raw.release_date) ? { releaseDate: nonEmptyString(raw.release_date) } : {}),+ ...(nonEmptyString(raw.last_updated) ? { lastUpdated: nonEmptyString(raw.last_updated) } : {}),+ ...(typeof raw.open_weights === "boolean" ? { openWeights: raw.open_weights } : {}),+ limit,+ ...(parseCost(raw.cost) ? { cost: parseCost(raw.cost) } : {}),+ ...(parseInterleaved(raw.interleaved) !== undefined+ ? { interleaved: parseInterleaved(raw.interleaved) }+ : {}),+ ...(nonEmptyString(raw.status) ? { status: nonEmptyString(raw.status) } : {}),+ ...(experimental !== undefined ? { experimental } : {}),+ ...(providerMetadata !== undefined ? { provider: providerMetadata } : {}),+ ...(modelApi !== undefined ? { modelApi } : {}),+ };+}++/** Parse the public models.dev document without network access. */+export function parseModelsDevCatalog(body: unknown): ModelsDevProvider[] {+ const root = asRecord(body);+ if (!root) throw new Error("models.dev catalog must be an object");+ const providers: ModelsDevProvider[] = [];+ for (const [providerKey, value] of Object.entries(root)) {+ const provider = asRecord(value);+ const rawModels = asRecord(provider?.models);+ if (!provider || !rawModels) continue;+ const parsedModels = Object.entries(rawModels).flatMap(([modelKey, modelValue]) => {+ const model = asRecord(modelValue);+ const parsed = model ? modelFromRaw(providerKey, provider, modelKey, model) : undefined;+ return parsed ? [parsed] : [];+ });+ const models = [+ ...new Map(parsedModels.map((model) => [model.modelId.toLowerCase(), model])).values(),+ ]+ .sort((a, b) => a.modelId.localeCompare(b.modelId));+ if (models.length > 0) {+ providers.push({+ providerKey,+ name: nonEmptyString(provider.name) ?? providerKey,+ ...(nonEmptyString(provider.api) ? { api: nonEmptyString(provider.api) } : {}),+ ...(nonEmptyString(provider.npm) ? { npm: nonEmptyString(provider.npm) } : {}),+ env: stringArray(provider.env),+ ...(nonEmptyString(provider.doc) ? { doc: nonEmptyString(provider.doc) } : {}),+ models,+ });+ }+ }+ return providers;+}++function normalizedProviderKey(value: string | undefined): string {+ return (value ?? "").trim().toLowerCase().replace(/_/g, "-");+}++function normalizedModelId(value: string): string {+ return value.trim().toLowerCase();+}+++function modelVendorPrefixes(model: ModelsDevModel): string[] {+ const prefixes = new Set<string>();+ const add = (value: unknown) => {+ if (typeof value !== "string") return;+ const normalized = normalizedProviderKey(value);+ if (normalized) prefixes.add(normalized);+ };+ add(model.providerKey);+ if (typeof model.provider === "string") add(model.provider);+ const providerRecord = typeof model.provider === "object" ? model.provider : undefined;+ add(providerRecord?.id);+ const npmProvider = nonEmptyString(providerRecord?.npm);+ if (npmProvider) add(npmProvider.split("/").at(-1)?.replace(/^@ai-sdk-/, ""));+ const modelId = normalizedModelId(model.modelId);+ for (const prefix of MODEL_VENDOR_PREFIXES) {+ if (+ modelId.startsWith(`${prefix}/`) ||+ modelId.startsWith(`${prefix}-`) ||+ modelId.startsWith(`${prefix}.`)+ ) {+ prefixes.add(prefix);+ }+ }+ return [...prefixes];+}++function modelMatchesProvider(model: ModelsDevModel, vendorKey?: string): boolean {+ const candidates = new Set(providerKeyCandidates(vendorKey));+ if (candidates.size === 0 || candidates.has("custom")) return false;+ return modelVendorPrefixes(model).some((prefix) => candidates.has(prefix));+}++const KNOWN_PROVIDER_BASE_URLS: Record<string, string[]> = {+ openai: ["https://api.openai.com/v1", "https://chatgpt.com/backend-api"],+ anthropic: ["https://api.anthropic.com"],+ google: ["https://generativelanguage.googleapis.com/v1beta"],+ mistral: ["https://api.mistral.ai/v1"],+ xai: ["https://api.x.ai/v1"],+ groq: ["https://api.groq.com/openai/v1"],+ togetherai: ["https://api.together.xyz/v1"],+ deepseek: ["https://api.deepseek.com"],+ openrouter: ["https://openrouter.ai/api/v1"],+ "fireworks-ai": ["https://api.fireworks.ai/inference/v1"],+ "alibaba-cn": ["https://dashscope.aliyuncs.com/compatible-mode/v1"],+ "moonshotai-cn": ["https://api.moonshot.cn/v1"],+ "siliconflow-cn": ["https://api.siliconflow.cn/v1"],+ volcengine: ["https://ark.cn-beijing.volces.com/api/v3"],+ // MiniMax exposes both an Anthropic endpoint (the published models.dev+ // URL) and an OpenAI-compatible `/v1` endpoint. Treat the latter as the+ // same provider so a custom OpenAI-style row still inherits M3's vision+ // metadata instead of falling back to a text-only generic model.+ "minimax-cn": [+ "https://api.minimaxi.com/v1",+ "https://api.minimaxi.com/anthropic/v1",+ ],+ minimax: [+ "https://api.minimax.io/v1",+ "https://api.minimax.io/anthropic/v1",+ ],};-export type CatalogAccount = { id: string; vendorKey?: string; baseUrl?: string; apiStyle?: string; models?: ModelBinding[] };-type CatalogTarget = { providerId?: string; vendorKey?: string; baseUrl?: string; modelId: string };+const PROVIDER_ALIASES: Record<string, string[]> = {+ // pi-ai names the ChatGPT subscription adapter `openai-codex`, while+ // models.dev publishes its model metadata under `openai`. Keep the+ // transport identity in provider config, but resolve metadata through the+ // corresponding public catalog provider.+ "openai-codex": ["openai", "openai-codex"],+ "openai-codex-responses": ["openai", "openai-codex"],+ together: ["together", "togetherai"],+ "together-ai": ["together", "togetherai"],+ fireworks: ["fireworks", "fireworks-ai"],+ "fireworks-ai": ["fireworks", "fireworks-ai"],+ kimi: ["kimi-for-coding", "kimi-coding"],+ "kimi-coding": ["kimi-coding", "kimi-for-coding"],+ "google-vertex": ["google-vertex"],+ "azure-openai-responses": ["azure", "azure-cognitive-services"],+ "vercel-ai-gateway": ["vercel"],+ "zai-coding-cn": ["zhipuai-coding-plan", "zai-coding-cn"],+ "zhipuai-coding-plan": ["zhipuai-coding-plan", "zai-coding-cn"],+ zhipu: ["zhipuai"],+ bigmodel: ["zhipuai"],+ dashscope: ["alibaba-cn"],+ qwen: ["alibaba-cn"],+ moonshot: ["moonshotai-cn", "moonshotai"],+ doubao: ["volcengine"],+ ark: ["volcengine"],+ minimax: ["minimax-cn", "minimax"],+ "lm-studio": ["lmstudio", "lm-studio"],+ lmstudio: ["lmstudio", "lm-studio"],+};++function providerKeyCandidates(value: string | undefined): string[] {+ const key = normalizedProviderKey(value);+ return [...new Set([key, ...(PROVIDER_ALIASES[key] ?? [])])].filter(Boolean);+}++/**+ * Publishers this app ships a provider for: the models.dev keys behind the+ * first-class presets and the known endpoints, which mirror the providers pi-ai+ * supports.+ *+ * They are the publishers read first when nothing identifies the row's own+ * publisher. A relay's list can name an id a hundred arbitrary resellers also+ * carry, and a reseller's own flags describe *its* deployment, not the one this+ * row talks to; the vendors and gateways the app actually ships describe the+ * model. Resellers outside this set are still read when none of these states the+ * id, because the alternative is dropping a published model to the generic+ * 128k text-only shape.+ */+const SUPPORTED_PUBLISHER_KEYS: ReadonlySet<string> = new Set(+ [+ ...NAMED_ENDPOINT_PRESETS.map((preset) => preset.vendorKey),+ ...Object.keys(KNOWN_PROVIDER_BASE_URLS),+ ].flatMap((key) => providerKeyCandidates(key)),+);++/**+ * Canonical form of a provider base URL: lowercase origin without a trailing+ * slash and without the trailing API version segment, so a row configured with+ * `.../v1` still matches the documented models.dev endpoint.+ */export function normalizedApiUrl(value: string | undefined): string | undefined {- if (!value?.trim()) return undefined;+ const raw = nonEmptyString(value);+ if (!raw) return undefined;try {- const url = new URL(value);- return `${url.origin}${url.pathname.replace(/\/+$/, "")}`.toLowerCase();+ const parsed = new URL(raw);+ const pathname = parsed.pathname+ .replace(/\/+$/, "")+ .replace(/\/(?:v1|v1beta|v1alpha)$/i, "");+ return `${parsed.protocol.toLowerCase()}//${parsed.host.toLowerCase()}${pathname}`;} catch {return undefined;}}++/** Whether two base URLs address the same provider endpoint. */export function apiMatches(left: string | undefined, right: string | undefined): boolean {- const value = normalizedApiUrl(left);- return value !== undefined && value === normalizedApiUrl(right);+ const normalizedLeft = normalizedApiUrl(left);+ const normalizedRight = normalizedApiUrl(right);+ return Boolean(normalizedLeft && normalizedRight && normalizedLeft === normalizedRight);+}+++/**+ * Hostname of a base URL, lowercased, or undefined when it has none.+ *+ * Only the host is read: two paths on one host can be the same publisher's+ * different API surfaces, which is exactly what `apiMatches` cannot see.+ */+function hostOfUrl(value: string | undefined): string | undefined {+ const raw = nonEmptyString(value);+ if (!raw) return undefined;+ try {+ return new URL(raw).host.toLowerCase() || undefined;+ } catch {+ return undefined;+ }+}+function isTextAgentModel(model: ModelsDevModel): boolean {+ return model.modalities.input.includes("text") && model.modalities.output.includes("text");+}++function adapterInput(modalities: ModelModalities): Array<"text" | "image"> {+ const input = modalities.input.filter(+ (item): item is "text" | "image" => item === "text" || item === "image",+ );+ return input.includes("text") ? input : ["text"];+}++function capabilityList(model: ModelsDevModel): ModelInfo["capabilities"] {+ const capabilities = new Set<ModelInfo["capabilities"][number]>(["text"]);+ if (model.attachment === true) capabilities.add("attachments");+ if (model.temperature === true) capabilities.add("temperature");+ if (model.toolCall === true) capabilities.add("tools");+ if (model.reasoning) capabilities.add("reasoning");+ if (model.structuredOutput === true) capabilities.add("json");+ for (const modality of model.modalities.input) {+ if (modality === "image") capabilities.add("vision");+ if (modality === "audio") capabilities.add("audio");+ if (modality === "video") capabilities.add("video");+ if (modality === "pdf") capabilities.add("pdf");+ }+ for (const modality of model.modalities.output) {+ if (modality === "audio") capabilities.add("audio");+ if (modality === "video") capabilities.add("video");+ if (modality === "pdf") capabilities.add("pdf");+ }+ return [...capabilities];}-/** A projection, not a second metadata source. Non-chat operations never reach this shape. */-export function modelInfoFromModelsDev(model: Model<Api>, providerId: string): ModelInfo {+export function modelInfoFromModelsDev(+ model: ModelsDevModel,+ providerId: string,+): ModelInfo {+ const contextWindow = positiveInteger(model.limit.context);+ const maxTokens = positiveInteger(model.limit.output);+ const thinkingLevelMap = thinkingLevelMapFromModelsDev(+ model.reasoningOptions,+ model.thinkingLevels,+ );return {+ modelId: model.modelId,+ displayName: model.displayName,providerId,- modelId: model.id,- displayName: model.name,+ ...(model.description !== undefined ? { description: model.description } : {}),+ ...(model.family !== undefined ? { family: model.family } : {}),+ ...(model.attachment !== undefined ? { attachment: model.attachment } : {}),reasoning: model.reasoning,- supportedThinkingLevels: getSupportedThinkingLevels(model),- thinkingLevelMap: model.thinkingLevelMap,- contextWindow: model.contextWindow,- maxTokens: model.maxTokens,- modalities: { input: [...model.input], output: ["text"] },- limit: { context: model.contextWindow, output: model.maxTokens },- // Pi's request-wide tier format is not the historical display-tier format.- cost: {- input: model.cost.input,- output: model.cost.output,- cacheRead: model.cost.cacheRead,- cacheWrite: model.cost.cacheWrite,- },- capabilities: ["text", "tools", ...(model.reasoning ? ["reasoning" as const] : []), ...(model.input.includes("image") ? ["vision" as const] : [])],+ ...(model.reasoningOptions !== undefined ? { reasoningOptions: model.reasoningOptions } : {}),+ ...(model.thinkingProtocol !== undefined ? { thinkingProtocol: model.thinkingProtocol } : {}),+ ...(thinkingLevelMap !== undefined ? { thinkingLevelMap } : {}),+ ...(model.toolCall !== undefined ? { toolCall: model.toolCall } : {}),+ ...(model.structuredOutput !== undefined ? { structuredOutput: model.structuredOutput } : {}),+ ...(model.temperature !== undefined ? { temperature: model.temperature } : {}),+ ...(model.knowledge !== undefined ? { knowledge: model.knowledge } : {}),+ ...(model.releaseDate !== undefined ? { releaseDate: model.releaseDate } : {}),+ ...(model.lastUpdated !== undefined ? { lastUpdated: model.lastUpdated } : {}),+ modalities: model.modalities,+ ...(model.openWeights !== undefined ? { openWeights: model.openWeights } : {}),+ ...(Object.keys(model.limit).length > 0 ? { limit: model.limit } : {}),+ ...(model.cost !== undefined ? { cost: model.cost } : {}),+ ...(model.interleaved !== undefined ? { interleaved: model.interleaved } : {}),+ ...(model.status !== undefined ? { status: model.status } : {}),+ ...(model.experimental !== undefined ? { experimental: model.experimental } : {}),+ ...(model.provider !== undefined ? { provider: model.provider } : {}),+ ...(contextWindow !== undefined ? { contextWindow } : {}),+ ...(maxTokens !== undefined ? { maxTokens } : {}),+ capabilities: capabilityList(model),+ supportedThinkingLevels: [...model.thinkingLevels],source: "discovered",- catalogSource: "pi",+ catalogSource: "models.dev",};}-export function modelConfigFromModelsDev(model: Model<Api>, baseUrl?: string): ModelConfig {- return { ...modelConfigFromPi(model), ...(baseUrl ? { baseUrl } : {}) };++/** Convert one complete models.dev record into the sidecar model config. */+export function modelConfigFromModelsDev(+ model: ModelsDevModel,+ baseUrl?: string,+): ModelConfig {+ const contextWindow = positiveInteger(model.limit.context) ?? DEFAULT_CONTEXT_WINDOW;+ const maxTokens = positiveInteger(model.limit.output) ?? DEFAULT_MAX_TOKENS;+ const reasoning = model.reasoningPublished ? model.reasoning : false;+ const thinkingLevels = reasoning ? [...model.thinkingLevels] : [];+ const cost: NonNullable<ModelConfig["cost"]> = {+ input: model.cost?.input ?? 0,+ output: model.cost?.output ?? 0,+ cacheRead: model.cost?.cacheRead ?? 0,+ cacheWrite: model.cost?.cacheWrite ?? 0,+ ...(model.cost?.reasoning !== undefined ? { reasoning: model.cost.reasoning } : {}),+ ...(model.cost?.inputAudio !== undefined ? { inputAudio: model.cost.inputAudio } : {}),+ ...(model.cost?.outputAudio !== undefined ? { outputAudio: model.cost.outputAudio } : {}),+ ...(model.cost?.contextOver200k ? { contextOver200k: model.cost.contextOver200k } : {}),+ ...(model.cost?.tiers ? { tiers: model.cost.tiers } : {}),+ };+ const config: ModelConfig = {+ source: "models.dev",+ name: model.displayName,+ baseUrl: baseUrl ?? model.providerApi ?? "",+ reasoning,+ supportedThinkingLevels: thinkingLevels,+ modalities: model.modalities,+ limit: {+ ...model.limit,+ context: model.limit.context ?? contextWindow,+ input: model.limit.input ?? contextWindow,+ output: model.limit.output ?? maxTokens,+ },+ cost,+ input: adapterInput(model.modalities),+ contextWindow,+ maxTokens,+ };+ if (model.description !== undefined) config.description = model.description;+ if (model.family !== undefined) config.family = model.family;+ if (model.attachment !== undefined) config.attachment = model.attachment;+ if (model.reasoningOptions !== undefined) config.reasoningOptions = model.reasoningOptions;+ if (model.thinkingProtocol !== undefined) config.thinkingProtocol = model.thinkingProtocol;+ const thinkingLevelMap = thinkingLevelMapFromModelsDev(model.reasoningOptions, thinkingLevels);+ if (thinkingLevelMap) config.thinkingLevelMap = thinkingLevelMap;+ if (model.toolCall !== undefined) config.toolCall = model.toolCall;+ if (model.structuredOutput !== undefined) config.structuredOutput = model.structuredOutput;+ if (model.temperature !== undefined) config.temperature = model.temperature;+ if (model.knowledge !== undefined) config.knowledge = model.knowledge;+ if (model.releaseDate !== undefined) config.releaseDate = model.releaseDate;+ if (model.lastUpdated !== undefined) config.lastUpdated = model.lastUpdated;+ if (model.openWeights !== undefined) config.openWeights = model.openWeights;+ if (model.interleaved !== undefined) config.interleaved = model.interleaved;+ if (model.status !== undefined) config.status = model.status;+ if (model.experimental !== undefined) config.experimental = model.experimental;+ if (model.provider !== undefined) {+ config.provider = model.provider;+ config.catalogProvider = model.provider;+ }+ if (model.modelApi !== undefined) config.api = model.modelApi;+ return config;}+/**+ * Sidecar model config for one provider row: the catalog record when the+ * lookup resolves one, otherwise the generic shape.+ *+ * An Anthropic Messages row the catalog cannot identify (a custom gateway URL+ * serving an id several publishers list) still needs the right thinking wire+ * shape: Opus 4.7+ and the Claude 5 family reject budget thinking with a 400.+ * Whether a Claude id takes adaptive or budget thinking is a property of the+ * model, which Anthropic's own record states, not of the deployment. So only+ * the exact Anthropic id's reasoning options transfer; limits and modalities+ * stay generic because they describe the deployment (#990).+ */export function catalogModelConfigFor(- catalog: Pick<ModelsDevCatalog, "findModel"> & Partial<Pick<ModelsDevCatalog, "modelConfigFor">>,- input: CatalogTarget & { apiStyle?: string },+ catalog: Pick<ModelsDevCatalog, "findModel"> & Partial<Pick<ModelsDevCatalog, "anthropicThinkingFor" | "modelConfigFor">>,+ input: CatalogTarget,): ModelConfig {if (catalog.modelConfigFor) return catalog.modelConfigFor(input);const model = catalog.findModel(input);- return model ? modelConfigFromModelsDev(model, input.baseUrl) : genericModelConfig(input.modelId, input.baseUrl ?? "");+ if (!model) {+ const generic = genericModelConfig(input.modelId, input.baseUrl ?? "");+ const thinking = input.apiStyle === "anthropic_messages"+ ? catalog.anthropicThinkingFor?.(input.modelId)+ : undefined;+ return thinking ? { ...generic, ...thinking } : generic;+ }+ const config = modelConfigFromModelsDev(model, input.baseUrl);+ /*+ A record that states no reasoning shape cannot speak for an Anthropic+ Messages row: a record borrowed from another publisher has its own options+ dropped, and a reseller's record describes the reseller's API. Anthropic's+ own record is what says whether this id takes adaptive or budget thinking,+ and losing that would put a rejected shape on the wire (#990).+ */+ const thinking = input.apiStyle === "anthropic_messages" && !config.reasoningOptions?.length+ ? catalog.anthropicThinkingFor?.(input.modelId)+ : undefined;+ return thinking ? { ...config, ...thinking } : config;}+type IndexedModel = { model: ModelsDevModel; provider: ModelsDevProvider };+/**- * Pi catalog/Models adapter. Startup is cache-only. Each OAuth/account collection- * remains owned by its existing account owner and can be attached without copying- * credentials or introducing a second refresh authority. Public discovery IDs- * still live in Rust's chat-only cache, not in a second metadata database.+ * Per-generation candidate index built from a loaded catalog. Bounding the+ * lookup by the number of distinct model ids in the catalog (not by the number+ * of distinct queries) keeps the work of a single session-list read constant+ * regardless of how many distinct bindings it contains: no per-query eviction+ * can force an earlier key to be rescanned. It is rebuilt only when the+ * provider map is replaced and is cleared on a failed or fresh load.*/+class ModelsDevLookupIndex {+ private readonly byModelId = new Map<string, IndexedModel[]>();++ constructor(providers: ReadonlyMap<string, ModelsDevProvider>) {+ for (const provider of providers.values()) {+ for (const model of provider.models) {+ /*+ Every published model is indexed, including the audio-only ones the+ listing drops: `modelsForProvider` decides which models a row+ *offers*, while this index answers for an ID a row already lists, and+ an endpoint that serves a TTS or ASR id has a published record for+ it. Filtering here is what left such a row on the generic seed.+ */+ const entry: IndexedModel = { model, provider };+ for (const key of registrationKeys(model.modelId)) {+ let bucket = this.byModelId.get(key);+ if (!bucket) {+ bucket = [];+ this.byModelId.set(key, bucket);+ }+ if (!bucket.includes(entry)) bucket.push(entry);+ }+ }+ }+ }++ candidates(requested: string): readonly IndexedModel[] {+ const keys = lookupCandidateKeys(requested);+ if (keys.length === 0) return EMPTY_CANDIDATES;+ if (keys.length === 1) {+ return this.byModelId.get(keys[0]) ?? EMPTY_CANDIDATES;+ }+ const result: IndexedModel[] = [];+ const seen = new Set<IndexedModel>();+ for (const key of keys) {+ const bucket = this.byModelId.get(key);+ if (!bucket) continue;+ for (const entry of bucket) {+ if (!seen.has(entry)) {+ seen.add(entry);+ result.push(entry);+ }+ }+ }+ return result;+ }+}++/** Generate the exact lowercase last `/`-segment used by the catalog matcher. */+function candidateKeys(modelId: string): string[] {+ const normalized = normalizedModelId(modelId);+ if (!normalized) return [];+ const slash = normalized.lastIndexOf("/");+ const leaf = slash >= 0 ? normalized.slice(slash + 1) : normalized;+ return leaf ? [leaf] : [];+}++function registrationKeys(modelId: string): string[] {+ return candidateKeys(modelId);+}++function lookupCandidateKeys(requested: string): string[] {+ return candidateKeys(requested);+}++const EMPTY_CANDIDATES: readonly IndexedModel[] = [];++type OfficialProviderFamily = "anthropic" | "openai" | "google" | "xai";++const OFFICIAL_PROVIDER_FAMILIES: Readonly<Record<string, OfficialProviderFamily>> = {+ anthropic: "anthropic",+ openai: "openai",+ google: "google",+ "google-ai-studio": "google",+ "google-vertex": "google",+ xai: "xai",+ "x-ai": "xai",+};++function explicitModelSourceFamily(modelId: string): OfficialProviderFamily | undefined {+ const firstSegment = normalizedModelId(modelId).split("/", 1)[0];+ return OFFICIAL_PROVIDER_FAMILIES[firstSegment];+}++function isOfficialSourceProvider(entry: IndexedModel): boolean {+ const providerFamily = OFFICIAL_PROVIDER_FAMILIES[normalizedProviderKey(entry.provider.providerKey)];+ if (!providerFamily) return false;+ const explicitSource = explicitModelSourceFamily(entry.model.modelId);+ return !explicitSource || explicitSource === providerFamily;+}++function capabilitySignature(model: ModelsDevModel): string {+ return JSON.stringify({+ attachment: model.attachment ?? null,+ temperature: model.temperature ?? null,+ toolCall: model.toolCall ?? null,+ structuredOutput: model.structuredOutput ?? null,+ modalities: {+ input: [...model.modalities.input].sort(),+ output: [...model.modalities.output].sort(),+ },+ reasoning: model.reasoning,+ reasoningOptions: model.reasoningOptions ?? null,+ thinkingLevels: model.thinkingLevels,+ });+}++function modelWithSharedCapabilities(+ entries: readonly ModelsDevModel[],+): ModelsDevModel | undefined {+ if (entries.length === 0) return undefined;+ const signature = capabilitySignature(entries[0]);+ if (entries.some((model) => capabilitySignature(model) !== signature)) return undefined;+ return borrowedModel(entries);+}++/**+ * Middle value of the numbers the publishers state. Even counts take the lower+ * of the two middles, so a borrow never rounds a window up on its own.+ */+function medianOf(values: readonly (number | undefined)[]): number | undefined {+ const present = values.filter((value): value is number => value !== undefined);+ if (present.length === 0) return undefined;+ const sorted = [...present].sort((left, right) => left - right);+ const middle = sorted.length >> 1;+ return sorted.length % 2 === 1+ ? sorted[middle]+ : sorted[middle - 1];+}++/**+ * Record to borrow for an id the row's own catalog provider does not publish.+ *+ * models.dev indexes a gateway's copy of a model under the vendor that owns+ * the weights, so an endpoint serving `Vendor/Model` ids can have no record of+ * its own while several other publishers state the identical id. Borrowing+ * that record is what keeps such a model's context window, tool support and+ * vision visible instead of dropping the row to the generic 128k text-only+ * shape.+ *+ * Two rules keep the result honest about what the endpoint will accept:+ *+ * - Tool support follows the majority of the publishers that state it. One+ * dissenting reseller must not decide the claim for a deployment it does not+ * describe, and neither may one agreeing reseller: an id a relay lists can be+ * stated by a hundred publishers, which is what left whole model lists on the+ * generic seed before. An even split states no majority and claims nothing.+ * - Every other capability is the *intersection*, so the borrow may only+ * under-claim. Reasoning, image input and image/PDF attachment are reported+ * only when every publisher states them, and a user who knows the endpoint+ * does more can still turn them on in Advanced. Limits are the medians the+ * publishers state, so neither one host's cap nor one host's round-up+ * decides them.+ */+/**+ * Whether two ids name one model under different spellings.+ *+ * A publisher-prefixed copy (`anthropic/claude-sonnet-4-5` for+ * `claude-sonnet-4-5`, `mify/mimo-v2.5-pro-0731` for `mimo-v2.5-pro`) and a+ * dated or variant spelling of one id are the same model, so their records may+ * be compared with each other. Two unrelated routes that happen to share a leaf+ * (`provider-a/foo` vs `gateway/foo`) are not: that relation is a coincidence of+ * naming, and nothing may treat it as identity.+ *+ * `catalogModelIdsMatch` stays the matcher of record; this only decides which of+ * its matches a borrow without a provider identity may average.+ */+function sameModelSpelling(catalogId: string, requested: string): boolean {+ const left = catalogId.trim().toLowerCase();+ const right = requested.trim().toLowerCase();+ if (!left || !right) return false;+ if (left === right) return true;+ /*+ Either side may carry a route prefix the other does not: a relay lists+ `test/mimo-v2.5` where the catalog publishes `mimo-v2.5`, and a catalog that+ publishes a routed copy answers for the bare id. Two *different* route paths+ that merely share a leaf still never match.+ */+ if (left.endsWith(`/${right}`) || right.endsWith(`/${left}`)) return true;+ const plain = (id: string) => stripReleaseSuffix(stripVariantSuffix(id));+ const plainLeft = plain(left);+ const plainRight = plain(right);+ if (!plainLeft || !plainRight) return false;+ return (+ plainLeft === plainRight ||+ plainLeft.endsWith(`/${plainRight}`) ||+ plainRight.endsWith(`/${plainLeft}`)+ );+}++/**+ * Record to use when nothing identifies the row's provider.+ *+ * A relay or a gateway the catalog cannot place still serves models the catalog+ * knows, and asking for one of them by id used to answer nothing at all. What+ * every publisher of that model agrees on can be claimed instead: the same+ * intersection and median `borrowedModel` computes for an anchored row.+ *+ * One thing is deliberately not claimed. Which *wire shape* a deployment accepts+ * for reasoning is a property of that deployment — the same model behind an+ * OpenAI-compatible gateway and behind Anthropic's own API takes different+ * reasoning fields — so a record borrowed this way drops its `reasoningOptions`+ * rather than speaking for an endpoint no publisher describes. `catalogModelConfigFor`+ * still applies Anthropic's own shape to an Anthropic Messages row that is left+ * without one.+ */+function unanchoredConsensus(entries: readonly ModelsDevModel[]): ModelsDevModel | undefined {+ const consensus = borrowedModel(entries);+ return consensus ? { ...consensus, reasoningOptions: undefined } : undefined;+}++/**+ * Which publisher's records answer for an id the row's own publisher lacks.+ *+ * Two preferences, in order. The app's supported publishers are read first:+ * they are the vendors and gateways this app ships a provider for, so their+ * records describe the model behind an id a relay lists, while a reseller's own+ * flags describe its own deployment. Within that tier a record published under+ * exactly this id outranks one reached through another spelling of it:+ * `XiaomiMiMo/MiMo-V2.5` is the same model as `mimo-v2.5`, but a publisher that+ * lists only its text half must not narrow what the model's own record states+ * about vision. Only when none of them states the model does the pool widen to+ * every publisher that does — siblings included, as this borrow has always read+ * them — because a relay-only id would otherwise be shown as a generic 128k+ * text-only row although the catalog publishes it.+ */+function borrowPool(+ entries: readonly IndexedModel[],+ requested: string,+): readonly ModelsDevModel[] {+ /*+ A record under this id, or under the same id with a variant or release stamp+ stripped: `mimo-v2.5` answers for `mimo-v2.5-thinking`.+ */+ const closestId = (value: string) =>+ normalizedModelId(stripReleaseSuffix(stripVariantSuffix(value)));+ const requestedClosest = closestId(requested);+ const exact = (entry: IndexedModel) => {+ const id = normalizedModelId(entry.model.modelId);+ return id === requested || closestId(id) === requestedClosest;+ };+ const supported = (entry: IndexedModel) =>+ SUPPORTED_PUBLISHER_KEYS.has(normalizedProviderKey(entry.provider.providerKey));+ const tiers = [+ entries.filter((entry) => supported(entry) && exact(entry)),+ entries.filter(supported),+ entries,+ ];+ const pool = tiers.find((tier) => tier.length > 0) ?? [];+ return pool.map((entry) => entry.model);+}++/**+ * Markers a deployment appends to a published id to name its own variant of it:+ * a canary label, a context size, a preview channel. `test/mimo-v2.5-pro-test`+ * and `gemini-2.5-pro-1m` are the published models with such a marker appended.+ *+ * Only a marker on this list is read that way. `-asr`, `-pro` or `-mini` name+ * models of their own, so an unpublished id that carries one of those stays+ * unknown instead of borrowing a sibling model's limits.+ */+const DEPLOYMENT_MARKER_SUFFIXES: ReadonlySet<string> = new Set([+ "test",+ "staging",+ "canary",+ "dev",+ "alpha",+ "beta",+ "rc",+ "exp",+ "experimental",+ "preview",+ "free",+ "trial",+ "thinking",+ "think",+ "agent",+ "latest",+ "1k",+ "2k",+ "4k",+ "32k",+ "64k",+ "128k",+ "200k",+ "256k",+ "512k",+ "1m",+ "2m",+ "4m",+]);++/** The id without one trailing deployment marker, or the id unchanged. */+function dropDeploymentMarker(value: string): string {+ const match = /^(.*)[-_:]([a-z0-9]+)$/i.exec(value);+ if (!match) return value;+ return DEPLOYMENT_MARKER_SUFFIXES.has(match[2].toLowerCase()) ? match[1] : value;+}++/**+ * Published ids to read when nothing the catalog publishes matches the id the+ * service serves: the id behind a route prefix, and that id without one+ * deployment marker. Each is looked up as a whole published id, so nothing here+ * follows a chain of aliases.+ */+function fallbackLookupIds(requested: string): string[] {+ const ids: string[] = [];+ const push = (value: string) => {+ if (value && value !== requested && !ids.includes(value)) ids.push(value);+ };+ const leaf = requested.slice(requested.lastIndexOf("/") + 1);+ push(leaf);+ push(dropDeploymentMarker(leaf));+ push(dropDeploymentMarker(requested));+ return ids;+}++/**+ * The value most entries that state one agree on, or undefined when they split.+ *+ * A single dissenting publisher must not decide a claim, and a single agreeing+ * one must not either: an id in a relay's list can be stated by a hundred+ * resellers, and one reseller's flag is not evidence about the deployment this+ * row talks to. An even split states no majority, so nothing is claimed.+ */+function majorityOf(values: readonly (boolean | undefined)[]): boolean | undefined {+ const stated = values.filter((value): value is boolean => value !== undefined);+ if (stated.length === 0) return undefined;+ const yes = stated.filter(Boolean).length;+ if (yes * 2 > stated.length) return true;+ if (yes * 2 < stated.length) return false;+ return undefined;+}++function borrowedModel(entries: readonly ModelsDevModel[]): ModelsDevModel | undefined {+ if (entries.length === 0) return undefined;+ const toolCall = majorityOf(entries.map((model) => model.toolCall));+ const every = (pick: (model: ModelsDevModel) => boolean | undefined): boolean | undefined =>+ entries.every((model) => pick(model) === true) ? true+ : entries.every((model) => pick(model) === false) ? false+ : undefined;+ const base = entries[0];+ const keptModality = (modality: ModelModality): boolean =>+ entries.every((model) => model.modalities.input.includes(modality));+ const inputModalities = base.modalities.input.filter(keptModality);+ const outputModalities = base.modalities.output.filter((modality) =>+ entries.every((model) => model.modalities.output.includes(modality)),+ );+ const context = medianOf(entries.map((model) => model.limit.context));+ const output = medianOf(entries.map((model) => model.limit.output));+ const source = entries.find(+ (model) =>+ (context === undefined || model.limit.context === context) &&+ (output === undefined || model.limit.output === output),+ ) ?? base;+ const reasoning = every((model) => model.reasoning) === true;+ return {+ ...source,+ // Capabilities that must never be asserted on one publisher's word alone.+ toolCall,+ reasoning,+ thinkingLevels: reasoning ? source.thinkingLevels : [],+ structuredOutput: every((model) => model.structuredOutput),+ attachment: every((model) => model.attachment),+ modalities: {+ input: inputModalities.length > 0 ? inputModalities : ["text"],+ output: outputModalities.length > 0 ? outputModalities : ["text"],+ },+ limit: {+ ...(context !== undefined ? { context } : {}),+ ...(output !== undefined ? { output } : {}),+ },+ };+}+export class ModelsDevCatalog {- private readonly models;- private readonly accounts = new Map<string, MutableModels>();- private readonly removedAccounts = new Set<string>();- private readonly accountRows = new Map<string, CatalogAccount>();- private readonly originalProviders = new WeakMap<Provider, Provider>();- private readonly publishedModels = new WeakMap<Model<Api>, Model<Api>>();- private readonly effectiveConfigs = new WeakMap<Model<Api>, ModelConfig>();- private readonly now: () => number;+ private providers = new Map<string, ModelsDevProvider>();+ private lookupIndex: ModelsDevLookupIndex | undefined;+ /** Host → publishers, derived from the current provider map. */+ private hostIndex: Map<string, ModelsDevProvider[]> | undefined;+ private readonly lookupMemo = new Map<string, ModelsDevModel | undefined>();+ private loadPromise: Promise<boolean> | undefined;private loaded = false;- private fetchedAt?: string;- private lastError?: string;- private loading?: Promise<boolean>;+ private source: ModelsDevCatalogStatus["source"] = "empty";+ private fetchedAt: string | undefined;+ private lastError: string | undefined;+ private readonly fetchImpl: typeof fetch;+ private readonly timeoutMs: number;+ private readonly now: () => number;+ private readonly catalogPath: string;+ private localLoadAttempted = false;+ private localLoadPromise: Promise<boolean> | undefined;+ private readonly operationModels: MutableModels;+ private readonly accountModels = new Map<string, MutableModels>();+ private readonly accountRows = new Map<string, CatalogAccount>();+ private readonly removedAccounts = new Set<string>();- constructor(options: ModelsDevCatalogOptions = {}) {- this.now = options.now ?? Date.now;- this.models = createModels({+ constructor(options: ModelsDevCatalogOptions) {+ this.fetchImpl = options.fetchImpl ?? fetch;+ this.timeoutMs = options.timeoutMs ?? MODELS_DEV_TIMEOUT_MS;+ this.now = options.now ?? (() => Date.now());+ this.catalogPath = options.catalogPath;+ this.operationModels = createModels({modelsStore: new InMemoryModelsStore(),- // Catalog reads must never discover ambient credentials or user files.authContext: { env: async () => undefined, fileExists: async () => false },});- for (const provider of options.providers ?? builtinProviders()) this.models.setProvider(provider);+ for (const provider of options.providers ?? builtinProviders()) {+ this.operationModels.setProvider(provider);+ }}- /** Attach the account owner's existing Models; never replace its auth/store. */+ /** Pi Models are retained only to execute typed non-chat provider operations. */setAccountModels(providerId: string, models: MutableModels): void {- if (this.removedAccounts.has(providerId)) return;- this.accounts.set(providerId, models);- const row = this.accountRows.get(providerId);- if (row) { this.accountRows.delete(providerId); this.configureAccount(row); }+ if (!this.removedAccounts.has(providerId)) this.accountModels.set(providerId, models);}+deleteAccount(providerId: string): void {this.removedAccounts.add(providerId);- this.accounts.delete(providerId);+ this.accountModels.delete(providerId);this.accountRows.delete(providerId);}- /** Apply persisted explicit overrides at the Pi provider boundary, not per consumer.- * The wrapper retains upstream auth, refresh and non-chat operations unchanged.- * Its cache is keyed by the upstream model identity, so refresh replaces stale- * projections and deleting an override restores the untouched upstream record.- */+ /** Persisted per-model limits remain user-owned overrides over catalog data. */configureAccount(row: CatalogAccount): void {if (this.removedAccounts.has(row.id)) return;- const previous = this.accountRows.get(row.id);- const signature = (value: CatalogAccount) => JSON.stringify([value.vendorKey, value.baseUrl, value.apiStyle, value.models]);- if (previous && signature(previous) === signature(row) && this.accounts.has(row.id)) return;- row = structuredClone(row);- this.accountRows.set(row.id, row);- let collection = this.accounts.get(row.id);- if (!collection) {- collection = createModels({ modelsStore: new InMemoryModelsStore(), authContext: { env: async () => undefined, fileExists: async () => false } });- for (const provider of this.models.getProviders()) collection.setProvider(provider);- this.accounts.set(row.id, collection);+ this.accountRows.set(row.id, structuredClone(row));+ }++ /** Load the bundled release snapshot; this never performs network I/O. */+ async loadLocal(): Promise<boolean> {+ if (this.localLoadPromise) return this.localLoadPromise;+ if (this.localLoadAttempted) return this.loaded;+ this.localLoadAttempted = true;+ this.localLoadPromise = (async () => {+ try {+ const raw = JSON.parse(await readFile(this.catalogPath, "utf8")) as unknown;+ const parsed = parseModelsDevCatalog(raw);+ if (parsed.length === 0) throw new Error("models.dev snapshot contained no providers");+ this.providers = new Map(parsed.map((provider) => [provider.providerKey, provider]));+ // Replacing the provider map invalidates the derived lookup index.+ this.lookupIndex = undefined;+ this.hostIndex = undefined;+ this.lookupMemo.clear();+ this.loaded = true;+ this.source = "bundled";+ this.lastError = undefined;+ } catch (error) {+ this.loaded = false;+ this.lastError = error instanceof Error ? error.message : String(error);+ }+ return this.loaded;+ })();+ try {+ return await this.localLoadPromise;+ } finally {+ this.localLoadPromise = undefined;}- const key = this.providerKeyForRow(row) ?? row.vendorKey;- const current = key ? collection.getProvider(key) : undefined;- if (!current) return;- const original = this.originalProviders.get(current) ?? current;- const cache = new WeakMap<Model<Api>, Model<Api>>();- const project = (model: Model<Api>): Model<Api> => {- const cached = cache.get(model);- if (cached) return cached;- const binding = row.models?.find((entry) => entry.id.trim().toLowerCase() === model.id.trim().toLowerCase());- const baseline = modelConfigFromPi(model);- const limits = resolveBindingLimits(baseline, binding);- const configured = modelConfigWithBinding(limits.catalogConfig, limits.binding);- const selected = binding?.thinkingLevels.filter((level) => baseline.supportedThinkingLevels?.includes(level));- const thinkingLevelMap = { ...configured.thinkingLevelMap };- if (selected?.length) {- for (const level of THINKING_LEVELS) {- if (!selected.includes(level)) thinkingLevelMap[level] = null;+ }++ /** Ensure the release snapshot is available without contacting the network. */+ async ensureLoaded(): Promise<boolean> {+ return this.loadLocal();+ }++ /** Refresh the in-memory snapshot for the current process; never writes user data. */+ async refresh(): Promise<boolean> {+ if (this.loadPromise) return this.loadPromise;+ this.loadPromise = (async () => {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);+ try {+ const response = await this.fetchImpl(MODELS_DEV_API_URL, {+ headers: { Accept: "application/json" },+ signal: controller.signal,+ });+ if (!response.ok) {+ throw new Error(`models.dev catalog request failed (${response.status})`);}+ const parsed = parseModelsDevCatalog(await response.json());+ if (parsed.length === 0) throw new Error("models.dev catalog contained no usable providers");+ this.providers = new Map(parsed.map((provider) => [provider.providerKey, provider]));+ // Replacing the provider map invalidates the derived lookup index.+ this.lookupIndex = undefined;+ this.hostIndex = undefined;+ this.lookupMemo.clear();+ this.loaded = true;+ this.source = "remote";+ this.fetchedAt = new Date(this.now()).toISOString();+ this.lastError = undefined;+ return true;+ } catch (error) {+ this.lastError = error instanceof Error ? error.message : String(error);+ return false;+ } finally {+ clearTimeout(timer);+ this.loadPromise = undefined;}- // A saved unsupported level never re-enables a native null mapping (Sol- // cannot send off/none). Keep the persisted request, normalize execution.- for (const level of THINKING_LEVELS) {- if (model.thinkingLevelMap?.[level] === null) thinkingLevelMap[level] = null;- }- const reasoning = selected?.length- ? selected.some((level) => level !== "off")- : model.reasoning;- const supportedThinkingLevels = getSupportedThinkingLevels({ ...model, reasoning, thinkingLevelMap });- const config = { ...configured, reasoning, thinkingLevelMap, supportedThinkingLevels };- const effective = {- ...model,- ...config,- id: model.id,- provider: model.provider,- cost: model.cost,- };- cache.set(model, effective);- this.publishedModels.set(effective, model);- this.effectiveConfigs.set(effective, config);- return effective;- };- const wrapped: Provider = {- ...original,- getModels: () => original.getModels().map(project),- getAllModels: () => (original.getAllModels?.() ?? original.getModels()).map((model) =>- !model.type || model.type === "chat" ? project(model) : model),+ })();+ return this.loadPromise;+ }++ getStatus(): ModelsDevCatalogStatus {+ return {+ loaded: this.loaded,+ source: this.source,+ catalogPath: this.catalogPath,+ ...(this.fetchedAt ? { fetchedAt: this.fetchedAt } : {}),+ providerCount: this.providers.size,+ modelCount: [...this.providers.values()].reduce(+ (count, provider) => count + provider.models.length,+ 0,+ ),+ ...(this.lastError ? { lastError: this.lastError } : {}),};- this.originalProviders.set(wrapped, original);- collection.setProvider(wrapped);}modelConfigFor(input: CatalogTarget, unpublishedConfig?: ModelConfig): ModelConfig {const model = this.findModel(input);- const binding = input.providerId ? this.accountRows.get(input.providerId)?.models?.find((entry) => entry.id.trim().toLowerCase() === input.modelId.trim().toLowerCase()) : undefined;- if (model) {- // A wrapped account provider already applied its binding inside- // `configureAccount`. An unidentified relay has no wrapper to apply it,- // so the stored row is resolved here — otherwise a `user` pin on a relay- // hit would be silently replaced by the published number while still- // claiming `user` provenance (spec §9.1: a user limit is never replaced).- const projected = this.effectiveConfigs.get(model);- let config = projected;- if (!config) {- const baseline = modelConfigFromPi(model);- if (binding) {- const limits = resolveBindingLimits(baseline, binding);- config = modelConfigWithBinding(limits.catalogConfig, limits.binding);- } else {- config = baseline;- }- }- return { ...config, ...(input.baseUrl ? { baseUrl: input.baseUrl } : {}) };+ const binding = input.providerId+ ? this.accountRows.get(input.providerId)?.models?.find(+ (entry) => entry.id.trim().toLowerCase() === input.modelId.trim().toLowerCase(),+ )+ : undefined;+ let baseline = model+ ? modelConfigFromModelsDev(model, input.baseUrl)+ : unpublishedConfig ?? genericModelConfig(input.modelId, input.baseUrl ?? "");+ if (!model && !unpublishedConfig && input.apiStyle === "anthropic_messages") {+ const thinking = this.anthropicThinkingFor(input.modelId);+ if (thinking) baseline = { ...baseline, ...thinking };}- // Hand-typed custom IDs have no published metadata. Preserve historical- // explicit limits without pretending that the generic seed is a catalog.- const limits = resolveBindingLimits(unpublishedConfig ?? genericModelConfig(input.modelId, input.baseUrl ?? ""), binding);+ if (!binding) return baseline;+ const limits = resolveBindingLimits(baseline, binding);return modelConfigWithBinding(limits.catalogConfig, limits.binding);}- async loadLocal(): Promise<boolean> {- if (this.loaded) return true;- if (!this.loading) this.loading = this.models.refresh({ allowNetwork: false }).then((result) => {- this.loaded = true;- this.lastError = result.errors.size ? "Pi catalog cache initialization failed" : undefined;- return this.models.getModelsOfType("chat").length > 0;- }).finally(() => { this.loading = undefined; });- return this.loading;+ private providerFor(input: { vendorKey?: string; baseUrl?: string }): ModelsDevProvider | undefined {+ const candidates = new Set(providerKeyCandidates(input.vendorKey));+ const apiProviders = [...this.providers.values()].filter((provider) =>+ apiMatches(input.baseUrl, provider.api),+ );+ if (apiProviders.length > 0) {+ // A shared API endpoint does not identify which publisher owns a custom+ // model. Never pick the first provider simply because it was indexed first.+ return apiProviders.find((provider) =>+ candidates.has(normalizedProviderKey(provider.providerKey)),+ ) ?? (apiProviders.length === 1 ? apiProviders[0] : undefined);+ }+ const knownKey = Object.entries(KNOWN_PROVIDER_BASE_URLS).find(([, urls]) =>+ urls.some((url) => apiMatches(input.baseUrl, url)),+ )?.[0];+ if (knownKey) {+ const knownCandidates = new Set(providerKeyCandidates(knownKey));+ const knownProvider = [...this.providers.values()].find((provider) =>+ knownCandidates.has(normalizedProviderKey(provider.providerKey)),+ );+ if (knownProvider) return knownProvider;+ }+ const byKey = [...this.providers.values()].find((provider) =>+ candidates.has(normalizedProviderKey(provider.providerKey)),+ );+ return byKey ?? this.providerForUniqueHost(input.baseUrl);}- ensureLoaded(): Promise<boolean> { return this.loadLocal(); }- async refresh(): Promise<boolean> {- await this.ensureLoaded();- const collections = new Set<Models>([this.models, ...this.accounts.values()]);- const results = await Promise.all([...collections].map((models) => models.refresh({ allowNetwork: true, force: true })));- if (results.some((result) => result.aborted || result.errors.size > 0)) {- // Error text may contain an endpoint or auth detail; do not project it to UI.- this.lastError = "Pi model refresh failed; last-known models remain available";- return false;+ /**+ * Publisher that uniquely owns this host, when nothing else identified the row.+ *+ * A custom endpoint on a published host is still that publisher's deployment:+ * a user who types `https://open.bigmodel.cn/api/v1` for the Responses API is+ * on Zhipu, not on an anonymous gateway. The catalog's own `api` host is the+ * evidence, and it is only used when exactly one provider publishes from it,+ * so a shared or unknown host still resolves to nothing — missing metadata+ * stays ahead of wrong metadata.+ *+ * Built lazily from the current provider map and cleared with the lookup+ * index, so it can never describe a previous catalog generation.+ */+ private providerForUniqueHost(baseUrl: string | undefined): ModelsDevProvider | undefined {+ const host = hostOfUrl(baseUrl);+ if (!host) return undefined;+ if (!this.hostIndex) {+ const index = new Map<string, ModelsDevProvider[]>();+ for (const provider of this.providers.values()) {+ const providerHost = hostOfUrl(provider.api);+ if (!providerHost) continue;+ const bucket = index.get(providerHost);+ if (bucket) bucket.push(provider);+ else index.set(providerHost, [provider]);+ }+ this.hostIndex = index;}- this.fetchedAt = new Date(this.now()).toISOString();- this.lastError = undefined;- return true;+ const bucket = this.hostIndex.get(host);+ return bucket?.length === 1 ? bucket[0] : undefined;}- getStatus(): ModelsDevCatalogStatus {- return {- loaded: this.loaded,- source: !this.loaded ? "empty" : this.fetchedAt ? "remote" : "bundled",- catalogPath: "@earendil-works/pi-ai",- fetchedAt: this.fetchedAt,- providerCount: this.models.getProviders().length,- modelCount: this.models.getModelsOfType("chat").length,- lastError: this.lastError,- };- }+ findModel(input: CatalogTarget): ModelsDevModel | undefined {+ if (input.providerId && this.removedAccounts.has(input.providerId)) return undefined;+ const requested = normalizedModelId(input.modelId);+ if (!requested) return undefined;+ // Resolve through the index of the current catalog generation. The candidate+ // set is bounded by the catalog's model count, never by the number of+ // distinct lookups a single read performs, so no eviction policy can force+ if (!this.lookupIndex) this.lookupIndex = new ModelsDevLookupIndex(this.providers);+ // Memoize the exact lookup so repeated reads of the same binding never re-touch+ // the matched model. The memo is bounded and cleared wholesale on pressure;+ // even if many distinct keys clear it mid-read, re-resolution goes through the+ // small candidate index, never a full catalog scan.+ const memoKey = `${input.vendorKey ?? ""}\u0000${input.baseUrl ?? ""}\u0000${requested}`;+ if (this.lookupMemo.has(memoKey)) return this.lookupMemo.get(memoKey);+ const preferredProvider = this.providerFor(input);+ // Keep the same tie-breaking order as the scanned lookup: preferred-provider+ // entries first, then the remaining providers in provider-map order.+ const preferred: IndexedModel[] = [];+ const rest: IndexedModel[] = [];+ for (const entry of this.lookupIndex.candidates(requested)) {+ (entry.provider === preferredProvider ? preferred : rest).push(entry);+ }+ const candidates: Array<{ model: ModelsDevModel; provider: ModelsDevProvider; score: number }> = [];+ for (const { model, provider } of [...preferred, ...rest]) {+ // A known endpoint must not inherit another provider's capabilities.+ if (preferredProvider && provider !== preferredProvider) continue;+ if (!catalogModelIdsMatch(model.modelId, requested)) continue;+ const exact = model.modelId.toLowerCase() === requested;+ let score = exact ? 20 : 10;+ if (provider === preferredProvider) score += 100;+ if (apiMatches(input.baseUrl, provider.api)) score += 80;+ if (modelMatchesProvider(model, input.vendorKey)) score += 60;+ candidates.push({ model, provider, score });+ }+ candidates.sort((left, right) =>+ right.score - left.score || left.model.modelId.length - right.model.modelId.length,+ );+ // 0 → unmatched; 1 → enrich; ≥2 prefer unique official/source provider+ // agreeing with model source; else shared identical capabilities; else unmatched.+ const official = candidates.filter(isOfficialSourceProvider);+ const result = candidates.length === 1+ ? candidates[0].model+ : official.length === 1+ ? official[0].model+ : modelWithSharedCapabilities(candidates.map(({ model }) => model));+ const deploymentFallback = result+ ? undefined+ : this.modelForDeploymentMarker(input.modelId, preferredProvider);+ /* The row's own catalog provider did not publish this id. Borrowing needs a+ known provider identity to anchor on: the row resolved to a catalog+ provider whose own records are authoritative, so anything missing from it+ can be checked against the other publishers of the exact id instead of+ dropping the model to the generic shape.- providerKeyForRow(input: { vendorKey?: string; baseUrl?: string }): string | undefined {- const key = input.vendorKey?.trim().toLowerCase();- const alias = key ? PI_VENDOR_ALIASES[key] ?? key : undefined;- if (alias && alias !== "custom" && this.models.getProvider(alias)) return alias;- const preset = matchNamedPreset(input);- const presetKey = preset ? PI_VENDOR_ALIASES[preset.vendorKey] ?? preset.vendorKey : undefined;- if (presetKey && this.models.getProvider(presetKey)) return presetKey;- const candidates = this.models.getProviders().filter((provider) => apiMatches(provider.baseUrl, input.baseUrl));- return candidates.length === 1 ? candidates[0].id : undefined;+ This only fills a miss the lookup already had — a record the preferred+ provider does publish stays authoritative. Without that anchor the scores+ prove nothing about identity, and an unknown endpoint keeps the existing+ behaviour: a unique unambiguous match, official disambiguation, shared+ capabilities, or nothing. Deployment-marker / variant-suffix fallbacks+ are intentionally not applied here (approved #1047 matching rules). */+ const borrowed = result ?? deploymentFallback ??+ (preferredProvider ? this.borrowedAcrossProviders(input) : undefined);+ // Cache the result (a miss included) so a repeated miss is also O(1) and+ // cannot grow the candidate index with query-dependent keys.+ this.lookupMemo.set(memoKey, borrowed);+ if (this.lookupMemo.size > LOOKUP_MEMO_LIMIT) this.lookupMemo.clear();+ return borrowed;}- publishedModelFor(input: CatalogTarget): Model<Api> | undefined {- const model = this.findModel(input);- return model ? this.publishedModels.get(model) ?? model : undefined;+ /** Resolve only a whitelisted deployment marker, preserving the served ID. */+ private modelForDeploymentMarker(+ modelId: string,+ preferredProvider: ModelsDevProvider | undefined,+ ): ModelsDevModel | undefined {+ const leaf = modelId.slice(modelId.lastIndexOf("/") + 1);+ // Only context-size deployment labels are safe to project onto a model's+ // published record. Semantic suffixes such as `latest` and `thinking`+ // remain distinct model IDs even if the broader catalog matcher knows them.+ const marker = /[-_:](?:1|2|4|32|64|128|200|256|512)k$|[-_:](?:1|2|4)m$/i;+ if (!marker.test(leaf)) return undefined;+ const lookupId = leaf.replace(marker, "");++ const candidates = (this.lookupIndex?.candidates(normalizedModelId(lookupId)) ?? [])+ .filter(({ model }) => normalizedModelId(model.modelId) === normalizedModelId(lookupId));+ if (preferredProvider) {+ const own = candidates.filter(({ provider }) => provider === preferredProvider);+ if (own.length === 1) return own[0].model;+ return own.length > 1 ? modelWithSharedCapabilities(own.map(({ model }) => model)) : undefined;+ }++ const official = candidates.filter(isOfficialSourceProvider);+ if (official.length === 1) return official[0].model;+ if (official.length === 0) return undefined;+ return modelWithSharedCapabilities(official.map(({ model }) => model));}- findModel(input: CatalogTarget): Model<Api> | undefined {- return this.findModelOfType("chat", input);+ publishedModelFor(input: CatalogTarget): ModelsDevModel | undefined {+ return this.findModel(input);}+ /**+ * The models.dev snapshot owns published chat metadata. Pi is consulted here+ * only to obtain a typed executable operation model such as image generation.+ */findModelOfType<T extends ModelType>(type: T, input: CatalogTarget): ModelTypeMap[T] | undefined {+ if (type === "chat") return undefined;if (input.providerId && this.removedAccounts.has(input.providerId)) return undefined;- const models = (input.providerId && this.accounts.get(input.providerId)) || this.models;- const providerId = this.providerKeyForRow(input) ?? input.vendorKey;- if (!providerId || !models.getProvider(providerId)) {- if (input.baseUrl && this.models.getProviders().filter(provider => apiMatches(provider.baseUrl, input.baseUrl)).length > 1) return undefined;- return type === "chat" ? relayChatMetadata(this.models, input.modelId) as ModelTypeMap[T] | undefined : undefined;- }- const exact = models.getModelOfType(type, providerId, input.modelId);- if (exact) return exact;- const id = input.modelId.trim().toLowerCase();- return models.getModelsOfType(type, providerId).find((model) => model.id.toLowerCase() === id);+ const collection = (input.providerId && this.accountModels.get(input.providerId)) || this.operationModels;+ const key = input.vendorKey?.trim().toLowerCase();+ const alias = key ? PI_VENDOR_ALIASES[key] ?? key : undefined;+ const providerId = alias && collection.getProvider(alias)+ ? alias+ : this.providerKeyForRow(input);+ if (!providerId || !collection.getProvider(providerId)) return undefined;+ return collection.getModelOfType(type, providerId, input.modelId);}settingsMetadataFor(input: CatalogTarget): ModelInfo | undefined {@@ -303,15 +1610,124 @@ export class ModelsDevCatalog {return settingsOperationMetadata(input.providerId ?? "", vendor, input.modelId)[0];}- modelsForProvider(input: { providerId: string; vendorKey?: string; baseUrl?: string; includeNonChat?: boolean }): ModelInfo[] {+ /**+ * Exact-id fallback across catalog providers, used only when the row resolved+ * to a catalog provider that published nothing for the id.+ *+ * A gateway's copy of a model is indexed under the vendor that owns the+ * weights, so an endpoint serving `Vendor/Model` ids routinely has no record+ * of its own while other publishers state the identical id. Their record is+ * what keeps that model's window, tool support and vision visible.+ *+ * Three rules keep this from borrowing anything identity-sensitive:+ *+ * - A provider sharing the row's own endpoint is an alias for the row, not an+ * independent source. Its failure to publish the id is an answer about this+ * deployment, so nothing is borrowed past it.+ * - The publishers this app ships a provider for answer before arbitrary+ * resellers do, in the same order the unanchored borrow uses: an id a+ * supported publisher states describes the model, while a reseller's copy+ * describes its own deployment of it.+ * - Only an identical id transfers, and only as a whole published id: a+ * record the index reaches through an alias — a bare route leaf behind a+ * prefix, a vendor-prefixed variant — describes a *different* id.+ *+ * `lookupId` reads the record of a published id the served name reduces to+ * (`test/mimo-v2.5-pro-test` → `mimo-v2.5-pro`); it is only used when nothing+ * published answered for the served id itself.+ */+ private borrowedAcrossProviders(+ input: { vendorKey?: string; baseUrl?: string; modelId: string },+ lookupId?: string,+ ): ModelsDevModel | undefined {+ // `findModel` already rejected an empty id; normalize here so the compare+ // below is case-insensitive against the catalog's own normalization.+ const requested = lookupId ?? normalizedModelId(input.modelId);+ const matches: IndexedModel[] = [];+ const seen = new Set<string>();+ for (const candidate of this.lookupIndex?.candidates(requested) ?? []) {+ const { model, provider } = candidate;+ // The row's endpoint owns its own answers, including a negative one.+ if (apiMatches(input.baseUrl, provider.api)) continue;+ if (normalizedModelId(model.modelId) !== requested) continue;+ const key = `${provider.providerKey}\u0000${model.modelId}`;+ if (seen.has(key)) continue;+ seen.add(key);+ matches.push({ model, provider });+ }+ return borrowedModel(borrowPool(matches, requested));+ }++ /**+ * Thinking wire metadata Anthropic publishes for exactly this id, or nothing.+ * Aliases and other publishers' copies never answer: only Anthropic's own+ * record states which thinking shape a Claude model accepts.+ */+ anthropicThinkingFor(+ modelId: string,+ ): Pick<ModelConfig, "reasoningOptions" | "thinkingLevelMap"> | undefined {+ const requested = normalizedModelId(modelId);+ const model = this.providers.get("anthropic")?.models.find(+ (candidate) => normalizedModelId(candidate.modelId) === requested,+ );+ if (!model?.reasoning || !model.reasoningOptions?.length) return undefined;+ const thinkingLevelMap = thinkingLevelMapFromModelsDev(+ model.reasoningOptions,+ model.thinkingLevels,+ );+ return {+ reasoningOptions: model.reasoningOptions,+ ...(thinkingLevelMap ? { thinkingLevelMap } : {}),+ };+ }++ modelsForProvider(input: {+ vendorKey?: string;+ baseUrl?: string;+ providerId: string;+ /**+ * Include the models this provider publishes next to its chat models —+ * embedding, speech, image and reranking endpoints. The settings picker+ * asks for them because it renders the service's own catalog of what the+ * credential can call; session and agent paths keep the default, which is+ * the text models they can actually run.+ */+ includeNonChat?: boolean;+ }): ModelInfo[] {if (this.removedAccounts.has(input.providerId)) return [];- const models = this.accounts.get(input.providerId) ?? this.models;- const providerId = this.providerKeyForRow(input) ?? input.vendorKey;- if (!providerId) return [];- const chat = models.getModelsOfType("chat", providerId).map((model) => modelInfoFromModelsDev(model, input.providerId));- if (!input.includeNonChat) return chat;- const seen = new Set(chat.map(model => model.modelId.toLowerCase()));- const extra = settingsOperationMetadata(input.providerId, providerId).filter(model => !seen.has(model.modelId.toLowerCase()));- return [...chat, ...extra];+ const preferredProvider = this.providerFor(input);+ const providers = preferredProvider+ ? [preferredProvider]+ : [...this.providers.values()].filter((provider) =>+ provider.models.some((model) => modelMatchesProvider(model, input.vendorKey)),+ );+ const seen = new Set<string>();+ const chatAndPublished = providers.flatMap((provider) =>+ provider.models+ .filter((model) => {+ const key = normalizedModelId(model.modelId);+ if (seen.has(key)) return false;+ if (!input.includeNonChat && !isTextAgentModel(model)) return false;+ if (!preferredProvider && !modelMatchesProvider(model, input.vendorKey)) return false;+ seen.add(key);+ return true;+ })+ .map((model) => modelInfoFromModelsDev(model, input.providerId)),+ );+ if (!input.includeNonChat) return chatAndPublished;+ const seenIds = new Set(chatAndPublished.map((model) => normalizedModelId(model.modelId)));+ const operationRows = settingsOperationMetadata(input.providerId, preferredProvider?.providerKey)+ .filter((model) => {+ const key = normalizedModelId(model.modelId);+ if (seenIds.has(key)) return false;+ seenIds.add(key);+ return true;+ });+ return [...chatAndPublished, ...operationRows];+ }++ /** models.dev provider key for a configured row, when the catalog knows it. */+ providerKeyForRow(input: { vendorKey?: string; baseUrl?: string }): string | undefined {+ return this.providerFor(input)?.providerKey;}}diff --git a/apps/desktop/electron/main/oauth.ts b/apps/desktop/electron/main/oauth.tsindex 6b7ba2945..bd8c38968 100644--- a/apps/desktop/electron/main/oauth.ts+++ b/apps/desktop/electron/main/oauth.ts@@ -19,7 +19,7 @@import { randomUUID } from "node:crypto";import { createInstallationIdentity } from "./installation-identity.ts";-import { getSupportedThinkingLevels, InMemoryModelsStore } from "@earendil-works/pi-ai";+import { InMemoryModelsStore } from "@earendil-works/pi-ai";import type {Api,AuthEvent,@@ -37,7 +37,6 @@ import { builtinModels } from "@earendil-works/pi-ai/providers/all";import {capabilitiesFromModelConfig,genericModelConfig,- modelConfigFromPi,installProviderHeadersFetch,runWithProviderHeaders,type ModelConfig,@@ -46,12 +45,12 @@ import {import {isConversationModelId,parseVendorModelIds,- pinnedSiblingId,readVendorModelList,VendorModelListError,vendorModelListRequest,wireForLiveModel,} from "./vendor-live-models.ts";+import type { ThinkingLevel } from "@pi-desktop/shared";import {OAUTH_AUTH_KIND,type OAuthLoginEvent,@@ -100,6 +99,19 @@ function wireApiForStyle(style: string): Api {return Object.entries(API_STYLE_BY_WIRE_API).find(([, value]) => value === style)?.[0] ?? "openai-completions";}+/** Interpret an explicitly supplied wire map without borrowing another model's record. */+function withMappedThinkingLevels(config: ModelConfig): ModelConfig {+ if (!config.thinkingLevelMap) return config;+ const supportedThinkingLevels = Object.entries(config.thinkingLevelMap).flatMap(([level, value]) =>+ typeof value === "string" ? [level as ThinkingLevel] : [],+ );+ return {+ ...config,+ reasoning: supportedThinkingLevels.some((level) => level !== "off"),+ supportedThinkingLevels,+ };+}+export function protocolForApiStyle(apiStyle: string): string {return PROTOCOL_BY_API_STYLE[apiStyle] ?? "openai_compatible";}@@ -536,7 +548,9 @@ export class VendorOAuth {vendorKey: account.vendorId,option,}).catch(() => undefined);- const modelConfig = await this.withPinnedSiblingFallback(account, option, published);+ const modelConfig = withMappedThinkingLevels(+ published ?? genericModelConfig(option.modelId, option.baseUrl),+ );const capabilities = capabilitiesFromModelConfig(modelConfig);return {apiStyle: option.apiStyle,@@ -546,50 +560,6 @@ export class VendorOAuth {};}- /**- * models.dev is authoritative for known ids. Live-only models inherit limits,- * thinking levels, and adapter compatibility from a pinned same-tier sibling.- * xAI uses an explicit newest-first order so pin order cannot pick an older Grok.- */- private async withPinnedSiblingFallback(- account: AccountModels,- option: OAuthModelOption,- published: ModelConfig | undefined,- ): Promise<ModelConfig> {- const config = published ?? genericModelConfig(option.modelId, option.baseUrl);- if (config.source !== "generic") return config;- const pinned = account.pinnedProvider?.getModels() ?? await account.models.getAvailable(account.vendorId);- if (pinned.some((model) => model.id === option.modelId)) return config;- const siblingId = pinnedSiblingId(- account.vendorId,- option.modelId,- pinned.map((model) => model.id),- );- const sibling = siblingId ? pinned.find((model) => model.id === siblingId) : undefined;- if (!sibling) return config;- const input = (sibling.input ?? []).filter(- (modality): modality is "text" | "image" => modality === "text" || modality === "image",- );- const thinkingLevelMap = config.thinkingLevelMap ?? sibling.thinkingLevelMap;- const supportedThinkingLevels = getSupportedThinkingLevels({ ...sibling, thinkingLevelMap });- return {- ...config,- // Keep the protocol and wire effort mapping paired with borrowed reasoning.- compat: { ...sibling.compat, ...config.compat },- thinkingLevelMap,- reasoning: supportedThinkingLevels.some((level) => level !== "off"),- input: input.length > 0 ? input : config.input,- contextWindow: sibling.contextWindow,- maxTokens: sibling.maxTokens,- limit: {- context: sibling.contextWindow,- input: sibling.contextWindow,- output: sibling.maxTokens,- },- supportedThinkingLevels,- };- }-private async run(session: LoginSession, provider: Provider): Promise<void> {try {const installationId = await this.getInstallationId();@@ -859,13 +829,18 @@ export class VendorOAuth {const live = await this.withRowHeaders(providerId, () => this.liveAccountModels(account));if (!live) return;const projected = await Promise.all(live.map(async option => {- const known = original.getModels().find(model => model.id === option.modelId);- const config = known ? modelConfigFromPi(known) : await this.withPinnedSiblingFallback(account, option, undefined);+ const config = withMappedThinkingLevels(await this.deps.modelConfigFor?.({+ providerId,+ vendorKey: account.vendorId,+ option,+ }).catch(() => undefined) ?? genericModelConfig(option.modelId, option.baseUrl));return {...config, id: option.modelId, provider: vendorId,api: wireApiForStyle(option.apiStyle), baseUrl: option.baseUrl,- // A sibling supplies capabilities, never the price of a new ID.- cost: known?.cost ?? { input: NaN, output: NaN, cacheRead: NaN, cacheWrite: NaN },+ // Generic limits and zero-price defaults are not published data.+ cost: config.source === "generic"+ ? { input: NaN, output: NaN, cacheRead: NaN, cacheWrite: NaN }+ : config.cost ?? { input: NaN, output: NaN, cacheRead: NaN, cacheWrite: NaN },} as Model<Api>;}));context.signal.throwIfAborted();diff --git a/apps/desktop/electron/main/runtime/provider-catalog.ts b/apps/desktop/electron/main/runtime/provider-catalog.tsindex a6c131aea..f74619c9a 100644--- a/apps/desktop/electron/main/runtime/provider-catalog.ts+++ b/apps/desktop/electron/main/runtime/provider-catalog.ts@@ -11,6 +11,7 @@ import {} from "@pi-desktop/shared";import {capabilitiesFromModelConfig,+ modelConfigWithBinding,type ModelConfig,visionFromModelConfig,type ThinkingCapabilities,@@ -98,7 +99,14 @@ export function createProviderCatalogRuntime({const modelConfig = modelsDevCatalog.modelConfigFor({providerId: provider.id, vendorKey: provider.vendorKey, baseUrl: provider.baseUrl, modelId,}, catalogModelConfig);- return { modelConfig, capabilities: capabilitiesFromModelConfig(modelConfig) };+ const effectiveModelConfig = modelConfigWithBinding(+ modelConfig,+ bindingForModel(provider, modelId),+ );+ return {+ modelConfig: effectiveModelConfig,+ capabilities: capabilitiesFromModelConfig(effectiveModelConfig),+ };};const enrichProvider = <T extends RuntimeProvider>(@@ -112,9 +120,13 @@ export function createProviderCatalogRuntime({provider.defaultModelId ||"";modelsDevCatalog.configureAccount(provider);- const modelConfig = catalogModelConfigFor(modelsDevCatalog, {+ const catalogConfig = catalogModelConfigFor(modelsDevCatalog, {providerId: provider.id, vendorKey: provider.vendorKey, baseUrl: provider.baseUrl, modelId,});+ const modelConfig = modelConfigWithBinding(+ catalogConfig,+ bindingForModel(provider, modelId),+ );const models = provider.models?.map((binding) => {const catalogConfig = catalogModelConfigFor(modelsDevCatalog, {providerId: provider.id, vendorKey: provider.vendorKey, baseUrl: provider.baseUrl, modelId: binding.id,@@ -330,9 +342,13 @@ export function createProviderCatalogRuntime({}const { provider, modelId } = target;modelsDevCatalog.configureAccount(provider);- const modelConfig = catalogModelConfigFor(modelsDevCatalog, {+ const catalogConfig = catalogModelConfigFor(modelsDevCatalog, {providerId: provider.id, vendorKey: provider.vendorKey, baseUrl: provider.baseUrl, modelId,});+ const modelConfig = modelConfigWithBinding(+ catalogConfig,+ bindingForModel(provider, modelId),+ );return {...session,...capabilitiesFromModelConfig(modelConfig),diff --git a/apps/desktop/test/model-binding-catalog-source.test.mjs b/apps/desktop/test/model-binding-catalog-source.test.mjsindex aaaff8d70..7c4a552a1 100644--- a/apps/desktop/test/model-binding-catalog-source.test.mjs+++ b/apps/desktop/test/model-binding-catalog-source.test.mjs@@ -2,7 +2,6 @@ import assert from "node:assert/strict";import { registerHooks } from "node:module";import test from "node:test";-import { fixtureProvider } from "./pi-catalog-fixtures.mjs";import { ModelsDevCatalog } from "../electron/main/models-dev-catalog.ts";const runtimeModule = new URL("../electron/main/runtime/provider-catalog.ts", import.meta.url);@@ -25,10 +24,10 @@ const { createProviderCatalogRuntime } = await import(runtimeModule.href)const CORRECTED_CONTEXT_WINDOW = 1_050_000;async function fixtureRuntime() {- const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("requesty", [- { id: "terra", reasoning: true, contextWindow: CORRECTED_CONTEXT_WINDOW, maxTokens: 64_000 },- ], { baseUrl: "https://router.requesty.ai/v1" })] });- await catalog.ensureLoaded();+ const catalog = new ModelsDevCatalog({+ catalogPath: new URL("../resources/models.dev/api.json", import.meta.url).pathname,+ });+ await catalog.loadLocal();return createProviderCatalogRuntime({getHost: () => null,modelsDevCatalog: catalog,@@ -38,9 +37,9 @@ async function fixtureRuntime() {function providerFor(binding) {return {id: "provider-row",- name: "Requesty",- vendorKey: "requesty",- baseUrl: "https://router.requesty.ai/v1",+ name: "OpenAI",+ vendorKey: "openai",+ baseUrl: "https://api.openai.com/v1",models: [binding],};}@@ -50,11 +49,11 @@ function enrichedContextWindow(runtime, binding) {return provider.models[0].contextWindow;}-test("a catalog-sourced binding adopts a Pi catalog correction", async () => {+test("a catalog-sourced binding adopts the bundled models.dev value", async () => {const runtime = await fixtureRuntime();// The value the binding snapshotted when the model was added.const binding = {- id: "terra",+ id: "gpt-6.1-sol",contextWindow: 1_048_576,contextWindowSource: "catalog",maxTokens: 64_000,@@ -66,7 +65,7 @@ test("a catalog-sourced binding adopts a Pi catalog correction", async () => {test("a user output cap stays pinned independently of its catalog window", async () => {const runtime = await fixtureRuntime();const edited = {- id: "terra",+ id: "gpt-6.1-sol",contextWindow: 1_048_576,contextWindowSource: "catalog",maxTokens: 8_192,@@ -87,7 +86,7 @@ test("a user output cap stays pinned independently of its catalog window", asynctest("a legacy non-generic output cap stays explicit when the window follows catalog", async () => {const runtime = await fixtureRuntime();const legacy = {- id: "terra",+ id: "gpt-6.1-sol",contextWindow: 1_048_576,contextWindowSource: "catalog",maxTokens: 4_096,@@ -104,7 +103,7 @@ test("a hand-edited window that equals the generic seed is still the user's", as// user who picks exactly that number for a smaller endpoint must not be read// as "follow models.dev".const explicit = {- id: "terra",+ id: "gpt-6.1-sol",contextWindow: 128_000,contextWindowSource: "user",maxTokens: 8_192,@@ -116,13 +115,13 @@ test("a hand-edited window that equals the generic seed is still the user's", astest("unmarked records keep the rule they were written under", async () => {const runtime = await fixtureRuntime();const legacySeed = {- id: "terra",+ id: "gpt-6.1-sol",contextWindow: 128_000,maxTokens: 8_192,thinkingLevels: ["off"],};const legacyOverride = {- id: "terra",+ id: "gpt-6.1-sol",contextWindow: 400_000,maxTokens: 8_192,thinkingLevels: ["off"],@@ -135,7 +134,7 @@ test("unmarked records keep the rule they were written under", async () => {test("a catalog value leaves the binding marked as catalog-sourced", async () => {const runtime = await fixtureRuntime();const legacySeed = {- id: "terra",+ id: "gpt-6.1-sol",contextWindow: 128_000,contextWindowSource: "catalog",maxTokens: 8_192,diff --git a/apps/desktop/test/model-discovery-precedence.test.mjs b/apps/desktop/test/model-discovery-precedence.test.mjsindex 22e147291..7e3b42b79 100644--- a/apps/desktop/test/model-discovery-precedence.test.mjs+++ b/apps/desktop/test/model-discovery-precedence.test.mjs@@ -72,7 +72,7 @@ test("only a live answer is written back to the model cache", () => {assert.match(handler, /const requestBaseUrl = baseUrl\.replace/);});-test("every returned model is enriched through the published Pi catalog regardless of origin", () => {+test("every returned model is enriched through the published models.dev catalog regardless of origin", () => {// `decorate` is what attaches published limits, modalities and thinking// levels, so all three branches must route through it.assert.match(handler, /const modelsDevModel = .*modelsDevCatalog\.publishedModelFor/);diff --git a/apps/desktop/test/models-dev-catalog.test.mjs b/apps/desktop/test/models-dev-catalog.test.mjsindex b5a14f043..cdfc969a1 100644--- a/apps/desktop/test/models-dev-catalog.test.mjs+++ b/apps/desktop/test/models-dev-catalog.test.mjs@@ -1,274 +1,1803 @@import assert from "node:assert/strict";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";import test from "node:test";-import { createModels, InMemoryModelsStore, getSupportedThinkingLevels } from "@earendil-works/pi-ai";-import { bindingForCustomModelInfo } from "@pi-desktop/shared";-import { ModelsDevCatalog, catalogModelConfigFor, modelInfoFromModelsDev } from "../electron/main/models-dev-catalog.ts";-import { fixtureProvider } from "./pi-catalog-fixtures.mjs";--function account(provider) {- const models = createModels({ modelsStore: new InMemoryModelsStore(), authContext: { env: async () => undefined, fileExists: async () => false } });- models.setProvider(provider);- return models;+import { fileURLToPath } from "node:url";+import {+ apiStyleForAdapter,+ bindingForCustomModelInfo,+ catalogModelIdsMatch,+ modelIdsMatch,+} from "@pi-desktop/shared";+import {+ MODELS_DEV_API_URL,+ ModelsDevCatalog,+ catalogModelConfigFor,+ modelConfigFromModelsDev,+ modelInfoFromModelsDev,+ parseModelsDevCatalog,+ thinkingLevelsFromModelsDev,+} from "../electron/main/models-dev-catalog.ts";++const catalogFixture = {+ anthropic: {+ name: "Anthropic",+ models: {+ "claude-opus-4.6": {+ id: "claude-opus-4.6",+ name: "Claude 4.6 Opus",+ description: "High-end Claude for difficult coding, planning, and slower expert reasoning",+ family: "claude-opus",+ attachment: true,+ reasoning: true,+ reasoning_options: [{+ type: "effort",+ values: ["low", "medium", "high", "xhigh", "max"],+ }],+ tool_call: true,+ structured_output: true,+ temperature: false,+ knowledge: "2025-05-31",+ release_date: "2026-02-05",+ last_updated: "2026-03-13",+ modalities: {+ input: ["text", "image", "pdf"],+ output: ["text"],+ },+ open_weights: false,+ limit: {+ context: 1_000_000,+ input: 1_000_000,+ output: 128_000,+ },+ cost: {+ input: 5,+ output: 25,+ cache_read: 0.5,+ cache_write: 6.25,+ reasoning: 25,+ input_audio: 7,+ output_audio: 28,+ tiers: [{+ input: 10,+ output: 37.5,+ cache_read: 1,+ tier: { type: "context", size: 200_000 },+ }],+ context_over_200k: {+ input: 10,+ output: 37.5,+ cache_read: 1,+ cache_write: 12.5,+ },+ },+ interleaved: { field: "reasoning_content" },+ status: "stable",+ experimental: { modes: { fast: { enabled: true } } },+ provider: { npm: "@ai-sdk/anthropic" },+ },+ "audio-only": {+ id: "audio-only",+ modalities: { input: ["audio"], output: ["text"] },+ },+ "metadata-sparse": { id: "metadata-sparse" },+ },+ },+};++function responseFor(body, status = 200) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "content-type": "application/json" },+ });}-const target = { providerId: "account", vendorKey: "example", modelId: "chat" };-const binding = (values = {}) => ({ id: "chat", contextWindow: 128_000, maxTokens: 8_192, thinkingLevels: ["low", "high"], ...values });-// Parser/URL/heuristic-ranking implementation tests retired with the independent-// models.dev parser. These exercise the replacement Pi public factory boundary.-test("offline startup uses Pi's shipped catalog and does not consult ambient auth", async () => {- const catalog = new ModelsDevCatalog();+async function loadFixtureCatalog(t, fixture = catalogFixture) {+ const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-cache-"));+ t.after(() => rm(dir, { recursive: true, force: true }));+ const catalogPath = join(dir, "api.json");+ await writeFile(catalogPath, JSON.stringify(fixture), "utf8");+ const catalog = new ModelsDevCatalog({ catalogPath });assert.equal(await catalog.ensureLoaded(), true);- for (const vendorKey of ["openai", "openai-codex", "azure-openai-responses"]) {- const model = catalog.findModel({ vendorKey, modelId: "gpt-6.1-sol" });- assert.ok(model, vendorKey);- assert.equal(model.type ?? "chat", "chat");- assert.deepEqual(modelInfoFromModelsDev(model, "row").supportedThinkingLevels, getSupportedThinkingLevels(model));- assert.ok(!getSupportedThinkingLevels(model).includes("off"));- }- assert.equal(catalog.getStatus().source, "bundled");+ return catalog;+}++test("the bundled models.dev OpenAI record supplies the selected model limits", async () => {+ const catalogPath = fileURLToPath(new URL("../resources/models.dev/api.json", import.meta.url));+ const catalog = new ModelsDevCatalog({ catalogPath });+ assert.equal(await catalog.ensureLoaded(), true);+ const model = catalog.findModel({ vendorKey: "openai", modelId: "gpt-6.1-sol" });+ assert.ok(model);+ const config = catalogModelConfigFor(catalog, {+ providerId: "chatgpt-account",+ vendorKey: "openai-codex",+ baseUrl: "https://chatgpt.com/backend-api",+ modelId: "gpt-6.1-sol",+ });+ assert.equal(model.limit.context, 1_050_000);+ assert.equal(model.limit.output, 128_000);+ assert.equal(config.source, "models.dev");+ assert.equal(config.contextWindow, 1_050_000);+ assert.equal(config.maxTokens, 128_000);});-test("concurrent cache hydration shares one Pi refresh", async () => {- let restores = 0;- const base = fixtureProvider("example", [{ id: "chat" }]);- const catalog = new ModelsDevCatalog({ providers: [{ ...base, refreshModels: async () => { restores++; } }] });- await Promise.all(Array.from({ length: 40 }, () => catalog.ensureLoaded()));- assert.equal(restores, 1);+test("explicit account limits stay pinned over a later models.dev value", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ openai: {+ name: "OpenAI",+ api: "https://api.openai.com/v1",+ models: { model: { id: "model", limit: { context: 1_000_000, output: 100_000 } } },+ },+ });+ const info = modelInfoFromModelsDev(catalog.findModel({ vendorKey: "openai", modelId: "model" }), "account");+ const binding = bindingForCustomModelInfo("model", info);+ binding.contextWindow = 40_000;+ binding.contextWindowSource = "user";+ binding.maxTokens = 4_000;+ binding.maxTokensSource = "user";+ catalog.configureAccount({ id: "account", vendorKey: "openai", models: [binding] });+ const config = catalog.modelConfigFor({ providerId: "account", vendorKey: "openai", modelId: "model" });+ assert.equal(config.contextWindow, 40_000);+ assert.equal(config.maxTokens, 4_000);+ assert.equal(config.source, "models.dev");});-test("explicit refresh updates Pi model objects and failed refresh preserves last success", async () => {- let count = 0;- let fail = false;- const provider = fixtureProvider("example", [{ id: "chat", contextWindow: 10_000 }], {- fetchModels: async () => {- count++;- if (fail) throw new Error("sensitive-endpoint-token");- return [{ ...provider.getModels()[0], contextWindow: 20_000 }];+function observeModelIdReads(model) {+ const modelId = model.modelId;+ let reads = 0;+ Object.defineProperty(model, "modelId", {+ configurable: true,+ get() {+ reads += 1;+ return modelId;},});- const catalog = new ModelsDevCatalog({ providers: [provider], now: () => 1000 });- await catalog.ensureLoaded();- assert.equal(count, 0);- assert.equal(await catalog.refresh(), true);- assert.equal(catalog.findModel(target).contextWindow, 20_000);- const previous = catalog.findModel(target);- fail = true;- assert.equal(await catalog.refresh(), false);- assert.deepEqual(catalog.findModel(target), previous);- assert.equal(count, 2);- assert.equal(catalog.getStatus().fetchedAt, new Date(1000).toISOString());- assert.ok(!catalog.getStatus().lastError.includes("sensitive"));-});--test("provider and endpoint identity never borrow unrelated capabilities", async () => {- const catalog = new ModelsDevCatalog({ providers: [- fixtureProvider("example", [{ id: "chat", contextWindow: 10_000 }]),- fixtureProvider("other", [{ id: "chat", contextWindow: 20_000 }, { id: "other-only" }]),- ] });- await catalog.ensureLoaded();- assert.equal(catalog.findModel(target).contextWindow, 10_000);- assert.equal(catalog.findModel({ ...target, modelId: "other-only" }), undefined);- assert.equal(catalog.findModel({ modelId: "chat", baseUrl: "https://unknown.example/v1" }), undefined);- assert.equal(catalog.findModel({ modelId: "chat", baseUrl: "https://other.example/v1" }).contextWindow, 20_000);- for (const modelId of ["proxy/chat", "chat-latest", "chat-20260930", "chat-thinking"]) {- assert.equal(catalog.findModel({ ...target, modelId }), undefined);+ return () => reads;+}++test("repeated model matches and misses resolve through the bounded catalog index", async (t) => {+ const catalog = await loadFixtureCatalog(t);+ const input = { vendorKey: "anthropic", modelId: "claude-opus-4.6" };+ const match = catalog.findModel(input);+ assert.ok(match);+ const reads = observeModelIdReads(match);+ const perQuery = reads();++ assert.equal(catalog.findModel({ ...input }), match);+ assert.equal(catalog.findModel({ ...input, modelId: " CLAUDE-OPUS-4.6 " }), match);+ // A repeated exact match returns the same catalog object and touches only the+ // constant-sized candidate bucket, not a full catalog scan.+ assert.ok(reads() - perQuery <= 8, "a repeated match must reuse the catalog result");++ const missing = { ...input, modelId: "unpublished-model" };+ assert.equal(catalog.findModel(missing), undefined);+ const afterMiss = reads();+ assert.equal(catalog.findModel({ ...missing }), undefined);+ assert.equal(catalog.findModel({ ...missing, modelId: " UNPUBLISHED-MODEL " }), undefined);+ // A miss resolves through an empty bucket without scanning or growing the index.+ assert.equal(reads(), afterMiss, "a repeated miss must not search again");+});++test("cached matches remain scoped to the requested provider and endpoint", async (t) => {+ const fixture = Object.fromEntries(["alpha", "beta"].map((key) => [key, {+ name: key,+ api: `https://${key}.example/v1`,+ models: {+ "shared-model": {+ id: "shared-model",+ name: `${key} model`,+ modalities: { input: ["text"], output: ["text"] },+ },+ },+ }]));+ const catalog = await loadFixtureCatalog(t, fixture);+ const queries = [+ [{ vendorKey: "alpha", modelId: "shared-model" }, "alpha"],+ [{ vendorKey: "beta", modelId: "shared-model" }, "beta"],+ [{ vendorKey: "custom", baseUrl: "https://alpha.example/v1", modelId: "shared-model" }, "alpha"],+ [{ vendorKey: "custom", baseUrl: "https://beta.example/v1", modelId: "shared-model" }, "beta"],+ [{ vendorKey: "alpha", baseUrl: "https://beta.example/v1", modelId: "shared-model" }, "beta"],+ ];+ for (const [input, providerKey] of [...queries, ...queries.toReversed()]) {+ assert.equal(catalog.findModel(input)?.providerKey, providerKey);+ }+});++test("unknown endpoints do not inherit ambiguous cross-provider metadata", async (t) => {+ for (const order of [["alpha", "beta"], ["beta", "alpha"]]) {+ const fixture = Object.fromEntries(order.map((key) => [key, {+ api: `https://${key}.example/v1`,+ models: {+ "shared-model": {+ id: "shared-model",+ reasoning: key === "alpha",+ limit: { context: key === "alpha" ? 128_000 : 32_000, output: 8_192 },+ },+ },+ }]));+ const catalog = await loadFixtureCatalog(t, fixture);+ for (const modelId of ["shared-model", "proxy/shared-model"]) {+ const unknown = { vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId };+ assert.equal(catalog.findModel(unknown), undefined, `ambiguous ${modelId} must miss`);+ assert.equal(catalog.findModel(unknown), undefined, "ambiguous misses are cached");+ }+ const alpha = catalog.findModel({+ vendorKey: "custom", baseUrl: "https://alpha.example/v1", modelId: "shared-model",+ });+ assert.equal(alpha?.providerKey, "alpha", "an exact endpoint scopes the lookup");+ assert.equal(alpha?.reasoning, true);+ assert.equal(alpha?.limit.context, 128_000);+ const beta = catalog.findModel({ vendorKey: "beta", modelId: "shared-model" });+ assert.equal(beta?.providerKey, "beta", "a known provider key scopes the lookup");+ assert.equal(beta?.reasoning, false);+ assert.equal(beta?.limit.context, 32_000);}- assert.equal(catalog.findModel({ ...target, modelId: " CHAT " }).id, "chat");});-test("ambiguous shared endpoint has no first-provider winner", async () => {- const options = { baseUrl: "https://shared.example/v1" };- const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("one", [{ id: "chat" }], options), fixtureProvider("two", [{ id: "chat" }], options)] });- await catalog.ensureLoaded();- assert.equal(catalog.findModel({ baseUrl: options.baseUrl, modelId: "chat" }), undefined);- assert.equal(catalog.findModel({ vendorKey: "two", baseUrl: options.baseUrl, modelId: "chat" }).provider, "two");+test("an unknown endpoint can use a unique exact last-segment match", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ alpha: { models: { "shared-model": { id: "shared-model", reasoning: true } } },+ });+ assert.equal(catalog.findModel({+ vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId: "proxy/shared-model",+ })?.providerKey, "alpha");});-test("same-vendor accounts have distinct effective objects and deleted accounts stay unavailable", async () => {- const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("example", [{ id: "chat" }])] });- for (const [id, contextWindow] of [["account", 10_000], ["other-account", 20_000]]) {- catalog.setAccountModels(id, account(fixtureProvider("example", [{ id: "chat", contextWindow }])));+test("a known endpoint cannot borrow another provider's catalog model", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ alpha: { api: "https://alpha.example/v1", models: { "alpha-only": { id: "alpha-only" } } },+ beta: { api: "https://beta.example/v1", models: { "proxy/shared-model": { id: "proxy/shared-model", reasoning: true } } },+ });+ assert.equal(catalog.findModel({ baseUrl: "https://alpha.example/v1", modelId: "shared-model" }), undefined);+ assert.equal(catalog.findModel({ baseUrl: "https://beta.example/v1", modelId: "shared-model" })?.providerKey, "beta");+});++test("a shared catalog API prefers the explicitly selected vendor", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ alpha: { api: "https://gateway.example/v1", models: { "alpha-only": { id: "alpha-only" } } },+ beta: { api: "https://gateway.example/v1", models: { "beta-only": { id: "beta-only" } } },+ });+ const input = { vendorKey: "beta", baseUrl: "https://gateway.example/v1" };+ assert.equal(catalog.findModel({ ...input, modelId: "beta-only" })?.providerKey, "beta");+ assert.equal(catalog.findModel({ ...input, modelId: "alpha-only" }), undefined);+});++test("a shared catalog API with no vendor key cannot select the first publisher", async (t) => {+ for (const order of [["alpha", "beta"], ["beta", "alpha"]]) {+ const catalog = await loadFixtureCatalog(t, Object.fromEntries(order.map((key) => [key, {+ api: "https://gateway.example/v1",+ models: { "shared-model": { id: "shared-model", reasoning: key === "alpha",+ limit: { context: key === "alpha" ? 128_000 : 32_000, output: 8_192 } } },+ }])));+ assert.equal(catalog.providerKeyForRow({ vendorKey: "custom", baseUrl: "https://gateway.example/v1" }), undefined);+ assert.equal(catalog.findModel({ vendorKey: "custom", baseUrl: "https://gateway.example/v1", modelId: "shared-model" }), undefined);+ assert.equal(catalog.findModel({ vendorKey: "beta", baseUrl: "https://gateway.example/v1", modelId: "shared-model" })?.providerKey, "beta");}- assert.equal(catalog.findModel(target).contextWindow, 10_000);- assert.equal(catalog.findModel({ ...target, providerId: "other-account" }).contextWindow, 20_000);- catalog.deleteAccount("account");- catalog.configureAccount({ id: "account", vendorKey: "example" });- assert.equal(catalog.findModel(target), undefined);- assert.deepEqual(catalog.modelsForProvider({ providerId: "account", vendorKey: "example" }), []);- assert.equal(catalog.findModel({ ...target, providerId: "other-account" }).contextWindow, 20_000);-});--test("an attached account missing a model never falls back to the vendor catalog", () => {- const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("example", [{ id: "chat" }])] });- catalog.setAccountModels("account", account(fixtureProvider("example", [])));- assert.equal(catalog.findModel(target), undefined);-});--test("typed lookups retain chat/image/classifier with one ID and the legacy list stays chat-only", () => {- const provider = fixtureProvider("example", [- { id: "shared" },- { id: "shared", type: "image", api: "openrouter-images", output: ["image"] },- { id: "shared", type: "classifier", api: "fixture-classifier" },- ]);- const catalog = new ModelsDevCatalog({ providers: [provider] });- const input = { ...target, modelId: "shared" };- assert.equal(catalog.findModel(input).type ?? "chat", "chat");- assert.equal(catalog.findModelOfType("image", input).type, "image");- assert.equal(catalog.findModelOfType("classifier", input).type, "classifier");- catalog.configureAccount({ id: "account", vendorKey: "example", models: [binding({ id: "shared", contextWindow: 64_000 })] });- assert.equal(catalog.findModelOfType("image", input).type, "image");- assert.equal(catalog.findModelOfType("classifier", input).type, "classifier");- assert.deepEqual(catalog.modelsForProvider({ providerId: "account", vendorKey: "example", includeNonChat: true }).map((model) => model.modelId), ["shared"]);-});--test("projection and execution read the same effective Pi object and preserve native cost", () => {- const native = fixtureProvider("example", [{ id: "chat", reasoning: true, input: ["text", "image"], contextWindow: 1_000_000, maxTokens: 64_000 }]);- const models = account(native);- const catalog = new ModelsDevCatalog({ providers: [native] });- catalog.setAccountModels("account", models);- const row = { id: "account", vendorKey: "example", models: [binding({ contextWindow: 32_000, maxTokens: 4_000, supportsImages: false })] };- catalog.configureAccount(row);- const effective = catalog.findModel(target);- assert.equal(models.getModel("example", "chat"), effective);- const info = modelInfoFromModelsDev(effective, "account");- const config = catalogModelConfigFor(catalog, target);- assert.equal(info.contextWindow, config.contextWindow);- assert.equal(info.maxTokens, config.maxTokens);- assert.deepEqual(info.modalities.input, config.input);- assert.deepEqual(info.supportedThinkingLevels, getSupportedThinkingLevels(effective));- assert.equal(effective.cost, native.getModels()[0].cost);- assert.equal(native.getModels()[0].contextWindow, 1_000_000);- assert.equal(catalog.findModel(target), effective, "stable reads share the effective object");- row.models = [];- catalog.configureAccount(row);- assert.equal(catalog.findModel(target).contextWindow, 1_000_000);-});--test("catalog limit provenance follows refresh while legacy explicit limits stay pinned", async () => {- let contextWindow = 100_000;- const provider = fixtureProvider("example", [{ id: "chat", contextWindow }], {- fetchModels: async () => [{ ...provider.getModels()[0], contextWindow }],- });- const catalog = new ModelsDevCatalog({ providers: [provider] });- catalog.configureAccount({ id: "account", vendorKey: "example", models: [binding({ contextWindow: 90_000, contextWindowSource: "catalog" })] });- catalog.configureAccount({ id: "legacy", vendorKey: "example", models: [binding({ contextWindow: 128_000 })] });- contextWindow = 200_000;- assert.equal(await catalog.refresh(), true);- assert.equal(catalogModelConfigFor(catalog, target).contextWindow, 200_000);- assert.equal(catalogModelConfigFor(catalog, { ...target, providerId: "legacy" }).contextWindow, 128_000);-});--test("custom unpublished bindings keep explicit limits without false published prices", () => {- const catalog = new ModelsDevCatalog({ providers: [] });- catalog.configureAccount({ id: "account", vendorKey: "custom", models: [binding({ contextWindow: 32_000, maxTokens: 2_000, supportsImages: true })] });- const config = catalogModelConfigFor(catalog, { ...target, vendorKey: "custom" });- assert.equal(config.source, "generic");- assert.equal(config.contextWindow, 32_000);- assert.equal(config.maxTokens, 2_000);- assert.deepEqual(config.input, ["text", "image"]);});-test("custom IDs retain their wire spelling when a Pi row seeds a binding", () => {- const provider = fixtureProvider("example", [{ id: "chat" }]);- const info = modelInfoFromModelsDev(provider.getModels()[0], "account");- const saved = bindingForCustomModelInfo("CHAT", info);- assert.equal(saved.id, "CHAT");- assert.equal(saved.contextWindowSource, "catalog");- assert.equal(saved.maxTokensSource, "catalog");- assert.equal(info.catalogSource, "pi");+test("a recognized endpoint takes priority over an unrelated vendor fallback", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ openai: { models: { "shared-model": { id: "shared-model" } } },+ deepseek: { models: { "shared-model": { id: "shared-model" } } },+ });+ assert.equal(catalog.findModel({+ vendorKey: "openai",+ baseUrl: "https://api.deepseek.com",+ modelId: "shared-model",+ })?.providerKey, "deepseek");+});++test("model lookup memory is bounded by the catalog, not by query count", async (t) => {+ const catalog = await loadFixtureCatalog(t);+ const input = { vendorKey: "anthropic", modelId: "claude-opus-4.6" };+ const match = catalog.findModel(input);+ assert.ok(match);+ const reads = observeModelIdReads(match);++ // Thousands of distinct miss queries do not grow the per-generation index and+ // do not evict an already-resolved key from it.+ for (let index = 0; index < 3_000; index += 1) {+ assert.equal(catalog.findModel({ ...input, modelId: `unknown-${index}` }), undefined);+ }+ const beforeRepeat = reads();+ assert.equal(catalog.findModel(input), match);+ // The resolved key stays resolvable to the same object without a catalog rescan.+ assert.ok(reads() - beforeRepeat <= 8, "a resolved key stays usable after many distinct queries");+});++test("one read with more distinct keys than any cache budget does not rescan a resolved key", async (t) => {+ const catalog = await loadFixtureCatalog(t);+ const input = { vendorKey: "anthropic", modelId: "claude-opus-4.6" };+ const match = catalog.findModel(input);+ assert.ok(match);+ const reads = observeModelIdReads(match);+ const baseline = reads();+ const exactRepeats = 2_000;+ // Interleave the originally resolved key among a burst of distinct keys far+ // larger than the former 1,024-entry per-key eviction cache.+ for (let index = 0; index < exactRepeats; index += 1) {+ catalog.findModel({ ...input, modelId: `unknown-${index}` });+ catalog.findModel(input);+ }+ const touches = reads() - baseline;+ // Each exact re-query resolves through a bounded candidate bucket, so the work+ // stays proportional to the repeated queries and independent of the distinct+ // keys interleaved between them. The old 1,024-entry eviction cache would rescan+ // the whole catalog (thousands of model reads) on every repeat once its budget+ // was exceeded, growing with the distinct-key burst.+ assert.ok(+ touches <= exactRepeats * 8,+ `exact re-queries touched the model ${touches} times, expected <= ${exactRepeats * 8}`,+ );+});++test("model IDs match provider namespaces without matching model variants", () => {+ assert.equal(modelIdsMatch("anthropic-claude-opus-5", "claude-opus-5"), true);+ assert.equal(modelIdsMatch("anthropic/claude-opus-5", "claude-opus-5"), true);+ assert.equal(modelIdsMatch("claude-opus-5@default", "claude-opus-5"), true);+ assert.equal(modelIdsMatch("claude-opus-5-fast", "claude-opus-5"), false);+ for (const suffix of ["agent", "latest", "thinking", "think"]) {+ assert.equal(modelIdsMatch("foo", `foo-${suffix}`), false);+ assert.equal(modelIdsMatch(`foo-${suffix}`, "foo"), false);+ }+ assert.equal(modelIdsMatch("gateway-a/foo", "gateway-b/foo"), false);+ assert.equal(modelIdsMatch("foo@us-east", "foo@eu-west"), false);+ assert.equal(modelIdsMatch("proxy/openai/gpt-4o", "openai/gpt-4o"), true);+ assert.equal(modelIdsMatch("openai/gpt-4o", "proxy/gpt-4o"), false);+});+test("catalog metadata IDs match only exact case-insensitive last segments", () => {+ for (const [catalogId, request] of [+ ["claude-opus-4.6", "proxy/claude-opus-4.6"],+ ["openai/gpt-4o", "hub/gpt-4o"],+ ["google/gemini-2.5-flash", "openai/gemini-2.5-flash"],+ ["proxy/nested/claude-opus-4.6", "other/CLAUDE-OPUS-4.6"],+ ["gateway-a/foo", "gateway-b/foo"],+ ]) {+ assert.equal(catalogModelIdsMatch(catalogId, request), true, `${catalogId} / ${request}`);+ assert.equal(catalogModelIdsMatch(request, catalogId), true, `${request} / ${catalogId}`);+ }++ for (const [catalogId, request] of [+ ["claude-opus-4.6", "proxy/claude-opus-4.6-thinking"],+ ["claude-opus-4.6", "claude-opus-4.6:thinking"],+ ["claude-opus-4.6", "proxy/claude-opus-4.6-agent"],+ ["claude-opus-4.6", "proxy/claude-opus-4.6-latest"],+ ["anthropic-claude-opus-4.6", "claude-opus-4.6"],+ ["google/gemini-pro-latest", "ag/gemini-pro-agent"],+ ["foo", "foo-think"],+ ["foo", "foo-agent"],+ ["foo", "foo-latest"],+ ["foo@us-east", "foo"],+ ]) {+ assert.equal(catalogModelIdsMatch(catalogId, request), false, `${catalogId} / ${request}`);+ assert.equal(catalogModelIdsMatch(request, catalogId), false, `${request} / ${catalogId}`);+ }+});++test("catalog lookup uses exact last segments and rejects ambiguous matches", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ gateway: { models: {+ "model": { id: "model" },+ "nested/unique-model": { id: "nested/unique-model", reasoning: true },+ "google/gemini-pro-latest": { id: "google/gemini-pro-latest", reasoning: true },+ "route-a/shared-leaf": { id: "route-a/shared-leaf", reasoning: true },+ "route-b/shared-leaf": { id: "route-b/shared-leaf", reasoning: false },+ "regional@us-east": { id: "regional@us-east" },+ } },+ });++ assert.equal(+ catalog.findModel({ vendorKey: "custom", modelId: "proxy/UNIQUE-MODEL" })?.modelId,+ "nested/unique-model",+ );+ assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "other/model" })?.modelId, "model");+ assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" }), undefined);+ assert.equal(catalog.findModel({ vendorKey: "gateway", modelId: "proxy/shared-leaf" }), undefined);+ assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "ag/gemini-pro-agent" }), undefined);+ assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "regional" }), undefined);+ assert.equal(+ catalog.findModel({ vendorKey: "custom", modelId: "proxy/regional@us-east" })?.modelId,+ "regional@us-east",+ );+});++test("ambiguous leaf matches prefer one official provider", async (t) => {+ for (const order of [["relay", "openai"], ["openai", "relay"]]) {+ const definitions = {+ relay: { models: { "route/shared-leaf": {+ id: "route/shared-leaf", reasoning: false, tool_call: false,+ limit: { context: 32_000 },+ } } },+ openai: { models: { "shared-leaf": {+ id: "shared-leaf", reasoning: true, tool_call: true,+ reasoning_options: [{ type: "effort", values: ["low", "medium", "high"] }],+ limit: { context: 128_000 },+ } } },+ };+ const catalog = await loadFixtureCatalog(t, Object.fromEntries(+ order.map((key) => [key, definitions[key]]),+ ));+ const match = catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" });+ assert.equal(match?.providerKey, "openai");+ assert.equal(match?.reasoning, true);+ assert.equal(match?.limit.context, 128_000);+ }+});++test("official source keys ignore a cloud publisher carrying another vendor's model", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ xai: { models: { "grok-4.6": {+ id: "grok-4.6", reasoning: true, tool_call: true,+ reasoning_options: [{ type: "effort", values: ["low", "medium", "high", "xhigh"] }],+ limit: { context: 500_000 },+ } } },+ "google-vertex": { models: { "xai/grok-4.6": {+ id: "xai/grok-4.6", reasoning: true, tool_call: true,+ limit: { context: 524_288 },+ } } },+ relay: { models: { "x-ai/grok-4.6": {+ id: "x-ai/grok-4.6", reasoning: false, tool_call: false,+ } } },+ });+ const match = catalog.findModel({ vendorKey: "custom", modelId: "ycj/grok-4.6" });+ assert.equal(match?.providerKey, "xai");+ assert.equal(match?.limit.context, 500_000);+});++test("ambiguous non-official leaf matches share unanimous capabilities", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ relayA: { models: { "route-a/shared-leaf": {+ id: "route-a/shared-leaf", reasoning: true, tool_call: true,+ reasoning_options: [{ type: "effort", values: ["low", "high"] }],+ modalities: { input: ["text", "image"], output: ["text"] },+ limit: { context: 64_000, output: 8_192 },+ } } },+ relayB: { models: { "route-b/shared-leaf": {+ id: "route-b/shared-leaf", reasoning: true, tool_call: true,+ reasoning_options: [{ type: "effort", values: ["low", "high"] }],+ modalities: { input: ["image", "text"], output: ["text"] },+ limit: { context: 128_000, output: 16_384 },+ } } },+ });+ const match = catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" });+ assert.ok(match);+ assert.equal(match.reasoning, true);+ assert.equal(match.toolCall, true);+ assert.deepEqual(match.thinkingLevels, ["low", "high"]);+ assert.deepEqual(match.modalities.input.toSorted(), ["image", "text"]);+});++test("ambiguous leaf matches with conflicting capabilities remain unmatched", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ relayA: { models: { "route-a/shared-leaf": {+ id: "route-a/shared-leaf", reasoning: true, tool_call: true,+ } } },+ relayB: { models: { "route-b/shared-leaf": {+ id: "route-b/shared-leaf", reasoning: false, tool_call: true,+ } } },+ });+ assert.equal(+ catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" }),+ undefined,+ );+});++test("gemini agent routes do not collapse to gemini latest catalog entries", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ google: { models: {+ "gemini-pro-latest": { id: "gemini-pro-latest", reasoning: true },+ } },+ });+ assert.equal(+ catalog.findModel({ vendorKey: "custom", modelId: "ag/gemini-pro-agent" }),+ undefined,+ );});-test("unknown relays match the exact model leaf without rewriting the requested wire ID", () => {- const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("anthropic", [{ id: "claude-fixture" }])] });- const input = { vendorKey: "custom", modelId: "route/claude-fixture", baseUrl: "https://relay.example/v1" };- assert.equal(catalog.findModel(input)?.id, "claude-fixture");- assert.equal(catalog.findModel({ ...input, modelId: "route/claude-fixture-latest" }), undefined);+test("catalog lookup never collapses reasoning or release suffix variants", async (t) => {+ const catalog = await loadFixtureCatalog(t);+ const exact = catalog.findModel({ vendorKey: "custom", modelId: "proxy/claude-opus-4.6" });+ assert.equal(exact?.modelId, "claude-opus-4.6");+ assert.equal(exact.reasoning, true);++ for (const modelId of [+ "proxy/claude-opus-4.6-thinking",+ "proxy/claude-opus-4.6-agent",+ "proxy/claude-opus-4.6-latest",+ "claude-opus-4.6:thinking",+ "anthropic-claude-opus-4.6",+ ]) {+ assert.equal(catalog.findModel({ vendorKey: "custom", modelId }), undefined, modelId);+ }});/*- An unidentified relay keeps answering from the ID family's owner instead of- from whichever reseller it happens to serve. Each family below publishes an- owner record next to a reseller copy that states a far narrower window, so the- assertion proves the owner won. A leaf no owner states stays unmatched: a- reseller's numbers must never decide a window for a deployment they do not- describe.+ A gateway is indexed by models.dev under the vendor that owns the weights, so+ an endpoint serving `Vendor/Model` ids often has no record of its own while+ several other publishers state the identical id. Issue #938: those rows used+ to fall back to the generic 128k text-only shape, hiding a correct context+ window and tool support that the catalog does publish.*/-test("an unknown relay answers an open-weight leaf from its owning publisher", () => {- const relay = { vendorKey: "custom", baseUrl: "https://relay.example/v1" };- const families = [- ["mimo-v2.6-pro", "xiaomi"],- ["glm-5.3", "zai"],- ["deepseek-v4-pro", "deepseek"],- ["kimi-k3", "moonshotai"],- ["MiniMax-M3", "minimax"],- ];- for (const [id, owner] of families) {- const catalog = new ModelsDevCatalog({ providers: [- fixtureProvider(owner, [{ id, contextWindow: 999_999, maxTokens: 77_777 }]),- fixtureProvider("openrouter", [{ id, contextWindow: 200_000, maxTokens: 8_192 }]),- ] });- const found = catalog.findModel({ ...relay, modelId: `route/${id}` });- assert.equal(found?.provider, owner, id);- assert.equal(found?.contextWindow, 999_999, id);+test("an id the row's own catalog provider lacks borrows a unanimous exact-id record", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: { "gateway/own-model": { id: "gateway/own-model" } } },+ publisherA: { models: { "Vendor/Shared-Model-0731": {+ id: "Vendor/Shared-Model-0731", tool_call: true, reasoning: true,+ modalities: { input: ["text", "image"], output: ["text"] },+ attachment: true, family: "shared",+ limit: { context: 262_144, output: 65_536 },+ } } },+ publisherB: { models: { "Vendor/Shared-Model-0731": {+ id: "Vendor/Shared-Model-0731", tool_call: true, reasoning: true,+ modalities: { input: ["text", "image"], output: ["text"] },+ attachment: true, family: "shared",+ limit: { context: 1_048_576, output: 32_768 },+ } } },+ });+ const match = catalog.findModel({+ vendorKey: "gateway",+ baseUrl: "https://gateway.example/v1",+ modelId: "Vendor/Shared-Model-0731",+ });+ assert.ok(match, "a published exact id must not drop to the generic shape");+ assert.equal(match.toolCall, true);+ assert.equal(match.reasoning, true);+ const info = modelInfoFromModelsDev(match, "provider-1");+ assert.equal(info.capabilities.includes("tools"), true);+ assert.equal(info.capabilities.includes("vision"), true);+ // Limits are the medians the publishers state; an even count takes the lower+ // middle, so a borrow never rounds a window up on its own.+ assert.equal(match.limit.context, 262_144);+ assert.equal(match.limit.output, 32_768);+});++test("a borrowed record under-claims instead of asserting one publisher's extras", async (t) => {+ // Both publishers agree on tool support, so the id is borrowable. They differ+ // on vision, reasoning and structured output, so none of those may be+ // reported: the borrow may only claim what every publisher states.+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: { "gateway/own-model": { id: "gateway/own-model" } } },+ publisherA: { models: { "Vendor/Mixed": {+ id: "Vendor/Mixed", tool_call: true, reasoning: true, structured_output: true,+ modalities: { input: ["text", "image"], output: ["text"] }, attachment: true,+ limit: { context: 262_144 },+ } } },+ publisherB: { models: { "Vendor/Mixed": {+ id: "Vendor/Mixed", tool_call: true, reasoning: false, structured_output: false,+ modalities: { input: ["text"], output: ["text"] }, attachment: false,+ limit: { context: 262_144 },+ } } },+ });+ const match = catalog.findModel({+ vendorKey: "gateway",+ baseUrl: "https://gateway.example/v1",+ modelId: "Vendor/Mixed",+ });+ assert.ok(match, "unanimous tool support is enough to borrow");+ assert.equal(match.toolCall, true);+ assert.equal(match.reasoning, false);+ // A capability the publishers do not state unanimously is left unasserted+ // (`undefined` means "no published answer"), never claimed from one source.+ assert.equal(match.structuredOutput, undefined);+ assert.equal(match.attachment, undefined);+ assert.deepEqual(match.modalities.input, ["text"]);+ const info = modelInfoFromModelsDev(match, "provider-1");+ assert.equal(info.capabilities.includes("vision"), false);+ assert.equal(info.capabilities.includes("reasoning"), false);+});++test("an even split on tool support leaves conflicting leaves unmatched", async (t) => {+ // Conflicting capability signatures (tool_call) mean shared-capabilities enrichment+ // must miss — no majority/consensus borrow for an unanchored / empty-gateway row.+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ publisherA: { models: { "Vendor/Split": { id: "Vendor/Split", tool_call: true, limit: { context: 262_144 } } } },+ publisherB: { models: { "Vendor/Split": { id: "Vendor/Split", tool_call: false, limit: { context: 262_144 } } } },+ });+ assert.equal(catalog.findModel({+ vendorKey: "gateway",+ baseUrl: "https://gateway.example/v1",+ modelId: "Vendor/Split",+ }), undefined);+});++test("a borrowed record never replaces what the row's own catalog provider publishes", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {+ "Vendor/Shared-Model": { id: "Vendor/Shared-Model", tool_call: false, limit: { context: 200_000 } },+ } },+ publisherA: { models: {+ "Vendor/Shared-Model": { id: "Vendor/Shared-Model", tool_call: true, limit: { context: 1_048_576 } },+ } },+ });+ const match = catalog.findModel({+ vendorKey: "gateway",+ baseUrl: "https://gateway.example/v1",+ modelId: "Vendor/Shared-Model",+ });+ assert.equal(match?.providerKey, "gateway");+ assert.equal(match.limit.context, 200_000);+ assert.equal(match.toolCall, false);+});++test("publishers that disagree about capabilities remain unmatched", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ publisherA: { models: { "Vendor/Disputed": {+ id: "Vendor/Disputed", tool_call: true, reasoning: true, limit: { context: 262_144 },+ } } },+ publisherB: { models: { "Vendor/Disputed": {+ id: "Vendor/Disputed", tool_call: false, reasoning: false, limit: { context: 262_144 },+ } } },+ });+ assert.equal(catalog.findModel({+ vendorKey: "gateway",+ baseUrl: "https://gateway.example/v1",+ modelId: "Vendor/Disputed",+ }), undefined);+});++test("a majority of publishers with conflicting capability signatures stays unmatched", async (t) => {+ // #1047 does not majority-vote across publishers for an empty/unanchored row.+ // Conflicting tool_call signatures ⇒ unmatched.+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ publisherA: { models: { "Vendor/Majority": { id: "Vendor/Majority", tool_call: true, limit: { context: 262_144 } } } },+ publisherB: { models: { "Vendor/Majority": { id: "Vendor/Majority", tool_call: true, limit: { context: 1_048_576 } } } },+ publisherC: { models: { "Vendor/Majority": { id: "Vendor/Majority", tool_call: true, limit: { context: 1_048_576 } } } },+ publisherD: { models: { "Vendor/Majority": { id: "Vendor/Majority", tool_call: false, limit: { context: 1_048_576 } } } },+ });+ assert.equal(catalog.findModel({+ vendorKey: "gateway",+ baseUrl: "https://gateway.example/v1",+ modelId: "Vendor/Majority",+ }), undefined);+});++test("conflicting reseller and shipped records for a leaf stay unmatched without an official", async (t) => {+ // deepseek is not an official/source family for #1047 disambiguation, and the+ // capability signatures conflict, so an unanchored relay must miss.+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ deepseek: { models: { "shared-model": {+ id: "shared-model", tool_call: true, limit: { context: 1_000_000, output: 393_216 },+ } } },+ resellerA: { models: { "shared-model": {+ id: "shared-model", tool_call: false, limit: { context: 128_000, output: 8_192 },+ } } },+ resellerB: { models: { "shared-model": {+ id: "shared-model", tool_call: false, limit: { context: 131_072, output: 8_192 },+ } } },+ });+ assert.equal(catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://relay.example/v1",+ modelId: "shared-model",+ }), undefined);+});++test("resellers still answer for an id no shipped publisher states", async (t) => {+ // The preference above is not a filter: an id only resellers publish would+ // otherwise be shown as a generic 128k text-only row.+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ resellerA: { models: { "reseller-only-model": {+ id: "reseller-only-model", tool_call: true, limit: { context: 262_144 },+ } } },+ resellerB: { models: { "reseller-only-model": {+ id: "reseller-only-model", tool_call: true, limit: { context: 262_144 },+ } } },+ });+ const match = catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://relay.example/v1",+ modelId: "reseller-only-model",+ });+ assert.ok(match, "a published id must not drop to the generic shape");+ assert.equal(match.toolCall, true);+ assert.equal(match.limit.context, 262_144);+});++test("route prefixes and official deployment markers resolve without rewriting served IDs", async (t) => {+ // Exact last-segment match allows `test/mimo-v2.5` → `mimo-v2.5`.+ // Markers like `-thinking` / `-test` are part of the leaf and do not strip.+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ google: { models: {+ "gemini-2.5-pro": {+ id: "gemini-2.5-pro", tool_call: true,+ limit: { context: 1_048_576, output: 65_536 },+ },+ } },+ xiaomi: { models: {+ "mimo-v2.5": {+ id: "mimo-v2.5", tool_call: true,+ modalities: { input: ["text", "image"], output: ["text"] },+ limit: { context: 1_048_576, output: 131_072 },+ },+ "mimo-v2.5-pro": {+ id: "mimo-v2.5-pro", tool_call: true, limit: { context: 1_048_576, output: 131_072 },+ },+ } },+ });+ const relay = (modelId) =>+ catalog.findModel({ vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId });++ for (const served of ["test/mimo-v2.5", "mimo-v2.5"]) {+ assert.equal(relay(served)?.modelId, "mimo-v2.5", `${served} reads the published model`);+ assert.equal(relay(served)?.limit.context, 1_048_576);}- // Several resellers publish conflicting copies and no owner states the leaf:- // adopting any one of them would invent a window for this deployment.- const noOwner = new ModelsDevCatalog({ providers: [- fixtureProvider("openrouter", [{ id: "reseller-only", contextWindow: 200_000, maxTokens: 8_192 }]),- fixtureProvider("vercel-ai-gateway", [{ id: "reseller-only", contextWindow: 900_000, maxTokens: 64_000 }]),- ] });- assert.equal(noOwner.findModel({ ...relay, modelId: "reseller-only" }), undefined);-});--test("relay IDs accept route prefixes and only whitelisted deployment suffixes", () => {- const catalog = new ModelsDevCatalog({ providers: [- fixtureProvider("deepseek", [{ id: "deepseek-v4.1-flash", contextWindow: 1_000_000 }]),- fixtureProvider("xiaomi", [- { id: "mimo-v2.5-pro", contextWindow: 1_048_576 },- { id: "mimo-v2.6-flash", contextWindow: 1_048_576 },- // Keep the user's `fash` example literal: matching strips only `-test`,- // it does not autocorrect a model-name typo to `flash`.- { id: "mimo-v2.6-fash", contextWindow: 1_048_576 },+ const info = modelInfoFromModelsDev(relay("test/mimo-v2.5"), "provider-1");+ assert.ok(info.capabilities.includes("vision"));++ assert.equal(relay("mimo-v2.5-thinking"), undefined);+ assert.equal(relay("test/mimo-v2.5-pro-test"), undefined);+ assert.equal(relay("mimo-v2.5-asr"), undefined);+ assert.equal(relay("gemini-2.5-pro-1m")?.modelId, "gemini-2.5-pro");+});++test("a shipped publisher answers first for a row anchored to a reseller", async (t) => {+ // The row's own publisher is known and publishes nothing for this id, so the+ // borrow runs — and it reads the publisher the app ships before the resellers+ // that also carry the id.+ const catalog = await loadFixtureCatalog(t, {+ reseller: { api: "https://reseller.example/v1", models: { "reseller/own": { id: "reseller/own" } } },+ xai: { models: { "Vendor/Model": {+ id: "Vendor/Model", tool_call: true, limit: { context: 500_000, output: 500_000 },+ } } },+ otherA: { models: { "Vendor/Model": {+ id: "Vendor/Model", tool_call: false, limit: { context: 128_000, output: 8_192 },+ } } },+ otherB: { models: { "Vendor/Model": {+ id: "Vendor/Model", tool_call: false, limit: { context: 131_072, output: 8_192 },+ } } },+ });+ const match = catalog.findModel({+ vendorKey: "reseller",+ baseUrl: "https://reseller.example/v1",+ modelId: "Vendor/Model",+ });+ assert.equal(match?.providerKey, "xai", "the shipped publisher's record answers");+ assert.equal(match.toolCall, true);+ assert.equal(match.limit.context, 500_000);+ assert.equal(match.limit.output, 500_000);+});++test("ambiguous same-leaf spellings with conflicting modalities stay unmatched", async (t) => {+ // `mimo-v2.5` and `XiaomiMiMo/MiMo-V2.5` share a case-insensitive leaf but+ // disagree on modalities, and neither publisher is an official/source family.+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ xiaomi: { models: { "mimo-v2.5": {+ id: "mimo-v2.5", tool_call: true,+ modalities: { input: ["text", "image", "audio"], output: ["text"] },+ limit: { context: 1_048_576, output: 131_072 },+ } } },+ huggingface: { models: { "XiaomiMiMo/MiMo-V2.5": {+ id: "XiaomiMiMo/MiMo-V2.5", tool_call: true,+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: 1_048_576, output: 131_072 },+ } } },+ });+ assert.equal(catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://relay.example/v1",+ modelId: "mimo-v2.5",+ }), undefined);+});++test("unique leaf enrichment coexists with exact-id borrowing and unknown misses", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ publisherA: { models: {+ "Vendor/Known": { id: "Vendor/Known", limit: { context: 262_144 } },+ "Vendor/Known-2507": { id: "Vendor/Known-2507", limit: { context: 131_072 } },+ } },+ });+ const input = { vendorKey: "gateway", baseUrl: "https://gateway.example/v1" };+ // Near-miss and unknown ids do not reuse a sibling's limits.+ assert.equal(catalog.findModel({ ...input, modelId: "Vendor/Known-3000" }), undefined);+ assert.equal(catalog.findModel({ ...input, modelId: "unknown-model-xyz" }), undefined);+ // A different route with the same unique final segment is valid enrichment.+ assert.equal(catalog.findModel({ ...input, modelId: "Other/Known" })?.modelId, "Vendor/Known");+ // Exact ids still resolve, including a case-only difference.+ assert.equal(catalog.findModel({ ...input, modelId: "vendor/known" })?.limit.context, 262_144);+ assert.equal(catalog.findModel({ ...input, modelId: "Vendor/Known" })?.limit.context, 262_144);+ assert.equal(catalog.findModel({ ...input, modelId: "Vendor/Known-2507" })?.limit.context, 131_072);+ // The sibling exists under a different id, so nothing is borrowed through it.+ assert.equal(+ catalog.findModel({ ...input, modelId: "Vendor/Known-2507" })?.modelId,+ "Vendor/Known-2507",+ );+});++test("a provider sharing the row's endpoint owns its own negative answer", async (t) => {+ // Two names for one endpoint: an id published only by the sibling is not+ // borrowed, because that sibling was already consulted and does not list it.+ const catalog = await loadFixtureCatalog(t, {+ alpha: { api: "https://gateway.example/v1", models: { "alpha-only": { id: "alpha-only" } } },+ beta: { api: "https://gateway.example/v1", models: { "beta-only": { id: "beta-only" } } },+ });+ const input = { vendorKey: "beta", baseUrl: "https://gateway.example/v1" };+ assert.equal(catalog.findModel({ ...input, modelId: "alpha-only" }), undefined);+ // A different endpoint is a genuinely independent source and still transfers.+ const other = await loadFixtureCatalog(t, {+ gateway: { api: "https://gateway.example/v1", models: {} },+ publisherA: { models: { "Vendor/Elsewhere": { id: "Vendor/Elsewhere", limit: { context: 262_144 } } } },+ });+ assert.equal(+ other.findModel({+ vendorKey: "gateway",+ baseUrl: "https://gateway.example/v1",+ modelId: "Vendor/Elsewhere",+ })?.limit.context,+ 262_144,+ );+});++test("models.dev records retain all published model parameters and modalities", () => {+ const [provider] = parseModelsDevCatalog(catalogFixture);+ assert.equal(provider.providerKey, "anthropic");+ assert.equal(provider.models.length, 3, "raw parsing keeps non-text records too");++ const model = provider.models.find((item) => item.modelId === "claude-opus-4.6");+ assert.equal(model.providerApi, undefined);+ assert.equal(model.displayName, "Claude 4.6 Opus");+ assert.equal(model.description, "High-end Claude for difficult coding, planning, and slower expert reasoning");+ assert.equal(model.family, "claude-opus");+ assert.equal(model.attachment, true);+ assert.equal(model.reasoning, true);+ assert.deepEqual(model.reasoningOptions, [{+ type: "effort",+ values: ["low", "medium", "high", "xhigh", "max"],+ }]);+ assert.deepEqual(model.modalities, {+ input: ["text", "image", "pdf"],+ output: ["text"],+ });+ assert.deepEqual(model.limit, {+ context: 1_000_000,+ input: 1_000_000,+ output: 128_000,+ });+ assert.deepEqual(model.cost, {+ input: 5,+ output: 25,+ cacheRead: 0.5,+ cacheWrite: 6.25,+ reasoning: 25,+ inputAudio: 7,+ outputAudio: 28,+ tiers: [{+ input: 10,+ output: 37.5,+ cacheRead: 1,+ tier: { type: "context", size: 200_000 },+ }],+ contextOver200k: {+ input: 10,+ output: 37.5,+ cacheRead: 1,+ cacheWrite: 12.5,+ },+ });+ assert.deepEqual(model.interleaved, { field: "reasoning_content" });+ assert.equal(model.status, "stable");+ assert.equal(model.temperature, false);+ assert.deepEqual(model.experimental, { modes: { fast: { enabled: true } } });+ assert.deepEqual(model.provider, { npm: "@ai-sdk/anthropic" });++ const info = modelInfoFromModelsDev(model, "provider-row");+ assert.equal(info.providerId, "provider-row");+ assert.equal(info.contextWindow, 1_000_000);+ assert.equal(info.maxTokens, 128_000);+ assert.ok(info.capabilities.includes("text"));+ assert.ok(info.capabilities.includes("tools"));+ assert.ok(info.capabilities.includes("vision"));+ assert.ok(info.capabilities.includes("pdf"));+ assert.ok(info.capabilities.includes("reasoning"));+ assert.ok(info.capabilities.includes("json"));+ assert.ok(info.capabilities.includes("attachments"));+ assert.equal(info.capabilities.includes("temperature"), false);+ assert.equal(info.catalogSource, "models.dev");+ assert.deepEqual(info.thinkingLevelMap, {+ low: "low",+ medium: "medium",+ high: "high",+ xhigh: "xhigh",+ max: "max",+ // Effort ladder without a published none/off value (#603).+ off: null,+ });+ assert.deepEqual(info.provider, { npm: "@ai-sdk/anthropic" });+ assert.deepEqual(info.experimental, { modes: { fast: { enabled: true } } });+ assert.ok(+ modelInfoFromModelsDev({ ...model, temperature: true }, "provider-row").capabilities.includes(+ "temperature",+ ),+ );+ const allModalities = {+ input: ["text", "image", "audio", "video", "pdf"],+ output: ["text", "image", "audio", "video", "pdf"],+ };+ const multimodalInfo = modelInfoFromModelsDev(+ { ...model, modalities: allModalities },+ "provider-row",+ );+ assert.deepEqual(multimodalInfo.modalities, allModalities);+ for (const capability of ["vision", "audio", "video", "pdf"]) {+ assert.ok(multimodalInfo.capabilities.includes(capability), capability);+ }++ const config = modelConfigFromModelsDev(model, "https://api.anthropic.com");+ assert.equal(config.source, "models.dev");+ assert.equal(config.name, "Claude 4.6 Opus");+ assert.equal(config.contextWindow, 1_000_000);+ assert.equal(config.maxTokens, 128_000);+ assert.deepEqual(config.input, ["text", "image"]);+ assert.deepEqual(config.modalities, info.modalities);+ assert.deepEqual(config.supportedThinkingLevels, ["low", "medium", "high", "xhigh", "max"]);+ assert.equal(config.thinkingProtocol, "adaptive");+ assert.deepEqual(config.thinkingLevelMap, {+ low: "low",+ medium: "medium",+ high: "high",+ xhigh: "xhigh",+ max: "max",+ // Effort ladder without a published none/off value (#603).+ off: null,+ });+ assert.equal(config.cost.reasoning, 25);+ assert.deepEqual(config.provider, { npm: "@ai-sdk/anthropic" });+ assert.deepEqual(config.catalogProvider, { npm: "@ai-sdk/anthropic" });+ assert.deepEqual(config.experimental, { modes: { fast: { enabled: true } } });+ assert.equal(config.cost.inputAudio, 7);+ assert.equal(config.cost.outputAudio, 28);+ assert.equal(config.cost.tiers?.[0]?.tier?.size, 200_000);+ assert.equal(config.interleaved?.field, "reasoning_content");++ const sparse = provider.models.find((item) => item.modelId === "metadata-sparse");+ assert.equal(sparse.reasoningPublished, false);+ assert.equal(sparse.modalitiesPublished, false);+});++test("models.dev parsing keeps the per-model wire API with a responses-only fallback", () => {+ const [provider, llmGateway] = parseModelsDevCatalog({+ "opencode-go": {+ name: "OpenCode Go",+ api: "https://opencode.ai/zen/go/v1",+ models: {+ "muse-spark-1.3-contributor": { id: "muse-spark-1.3-contributor" },+ "deepseek-v4-flash": { id: "deepseek-v4-flash" },+ "custom-responses": { id: "custom-responses", api: "openai-responses" },+ },+ },+ "llmgateway": {+ name: "LLM Gateway",+ models: {+ "muse-spark-1.3-contributor": { id: "muse-spark-1.3-contributor" },+ },+ },+ });+ const byId = Object.fromEntries(provider.models.map((model) => [model.modelId, model]));+ assert.equal(byId["muse-spark-1.3-contributor"].modelApi, "openai-responses");+ assert.equal(byId["deepseek-v4-flash"].modelApi, undefined);+ assert.equal(byId["custom-responses"].modelApi, "openai-responses");+ const gatewayMuse = llmGateway.models.find((model) => model.modelId === "muse-spark-1.3-contributor");+ assert.equal(gatewayMuse.modelApi, undefined);+ const config = modelConfigFromModelsDev(+ byId["muse-spark-1.3-contributor"],+ "https://opencode.ai/zen/go/v1",+ );+ assert.equal(config.api, "openai-responses");+});++test("models.dev parsing retains every model in a provider", () => {+ const models = Object.fromEntries(+ Array.from({ length: 627 }, (_, index) => [+ `model-${String(index).padStart(4, "0")}`,+ { id: `model-${String(index).padStart(4, "0")}` },]),- ] });- const relay = { vendorKey: "custom", baseUrl: "https://relay.example/v1" };- for (const id of ["pro/deepseek-v4.1-flash", "deepseek/deepseek-v4.1-flash"]) {- assert.equal(catalog.findModel({ ...relay, modelId: id })?.id, "deepseek-v4.1-flash", id);+ );+ const [provider] = parseModelsDevCatalog({+ provider: { name: "Provider", models },+ });+ assert.equal(provider.models.length, 627);+ assert.equal(provider.models.at(-1)?.modelId, "model-0626");+});++test("matches vendor-prefixed models when the catalog provider key is a gateway", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-provider-match-"));+ const catalogPath = join(dir, "api.json");+ await writeFile(+ catalogPath,+ JSON.stringify({+ gateway: {+ name: "Gateway",+ api: "https://gateway.example/v1",+ models: {+ "deepseek/deepseek-v4": {+ id: "deepseek/deepseek-v4",+ name: "DeepSeek V4",+ modalities: { input: ["text", "image", "pdf"], output: ["text"] },+ limit: { context: 128_000, output: 16_000 },+ },+ },+ },+ }),+ "utf8",+ );+ try {+ const catalog = new ModelsDevCatalog({ catalogPath });+ assert.equal(await catalog.ensureLoaded(), true);+ const match = catalog.findModel({+ vendorKey: "deepseek",+ modelId: "deepseek-v4",+ });+ assert.equal(match?.modelId, "deepseek/deepseek-v4");+ assert.deepEqual(match?.modalities.input, ["text", "image", "pdf"]);+ assert.equal(+ catalog.modelsForProvider({ vendorKey: "deepseek", providerId: "row" }).length,+ 1,+ );+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("maps the OpenAI Codex account to OpenAI models.dev metadata", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-openai-codex-"));+ const catalogPath = join(dir, "api.json");+ await writeFile(+ catalogPath,+ JSON.stringify({+ openai: {+ name: "OpenAI",+ models: {+ "gpt-5.6-sol": {+ id: "gpt-5.6-sol",+ name: "GPT-5.6 Sol",+ reasoning: true,+ reasoning_options: [{+ type: "effort",+ values: ["none", "low", "medium", "high", "xhigh", "max"],+ }],+ modalities: { input: ["text", "image", "pdf"], output: ["text"] },+ limit: { context: 1_050_000, output: 128_000 },+ },+ },+ },+ }),+ "utf8",+ );+ try {+ const catalog = new ModelsDevCatalog({ catalogPath });+ assert.equal(await catalog.ensureLoaded(), true);++ const input = {+ vendorKey: "openai-codex",+ baseUrl: "https://chatgpt.com/backend-api",+ modelId: "gpt-5.6-sol",+ };+ const match = catalog.findModel(input);+ assert.equal(match?.providerKey, "openai");+ assert.equal(match?.reasoning, true);+ assert.deepEqual(match?.thinkingLevels, [+ "off",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ ]);+ assert.equal(match?.limit.context, 1_050_000);+ assert.equal(match?.limit.output, 128_000);+ assert.equal(catalog.providerKeyForRow(input), "openai");++ const fallback = catalog.modelsForProvider({+ vendorKey: input.vendorKey,+ baseUrl: input.baseUrl,+ providerId: "oauth-row",+ });+ assert.equal(fallback.length, 1);+ assert.equal(fallback[0].modelId, "gpt-5.6-sol");+ assert.deepEqual(fallback[0].supportedThinkingLevels, [+ "off",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ ]);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("matches Zhipu and Z.AI endpoints by catalog URL and vendor aliases", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-zhipu-"));+ const catalogPath = join(dir, "api.json");+ await writeFile(+ catalogPath,+ JSON.stringify({+ zhipuai: {+ name: "Zhipu AI",+ api: "https://open.bigmodel.cn/api/paas/v4",+ models: {+ "glm-5": {+ id: "glm-5",+ name: "GLM-5",+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: 204_800, output: 131_072 },+ },+ },+ },+ "zhipuai-coding-plan": {+ name: "Zhipu AI Coding Plan",+ api: "https://open.bigmodel.cn/api/coding/paas/v4",+ models: {+ "glm-5.3": {+ id: "glm-5.3",+ name: "GLM-5.3",+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: 1_000_000, output: 131_072 },+ },+ },+ },+ zai: {+ name: "Z.AI",+ api: "https://api.z.ai/api/paas/v4",+ models: {+ "glm-5.1": {+ id: "glm-5.1",+ name: "GLM-5.1",+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: 200_000, output: 131_072 },+ },+ },+ },+ "zai-coding-plan": {+ name: "Z.AI Coding Plan",+ api: "https://api.z.ai/api/coding/paas/v4",+ models: {+ "glm-5.2": {+ id: "glm-5.2",+ name: "GLM-5.2",+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: 1_000_000, output: 131_072 },+ },+ },+ },+ }),+ "utf8",+ );+ try {+ const catalog = new ModelsDevCatalog({ catalogPath });+ assert.equal(await catalog.ensureLoaded(), true);++ const chinaApi = catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://open.bigmodel.cn/api/paas/v4",+ modelId: "glm-5",+ });+ assert.equal(chinaApi?.providerKey, "zhipuai");++ const chinaCoding = catalog.findModel({+ vendorKey: "zai-coding-cn",+ modelId: "glm-5.3",+ });+ assert.equal(chinaCoding?.providerKey, "zhipuai-coding-plan");+ assert.equal(chinaCoding?.modelId, "glm-5.3");++ const intlCoding = catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://api.z.ai/api/coding/paas/v4",+ modelId: "glm-5.2",+ });+ assert.equal(intlCoding?.providerKey, "zai-coding-plan");+ assert.equal(+ catalog.providerKeyForRow({+ vendorKey: "bigmodel",+ baseUrl: "https://open.bigmodel.cn/api/paas/v4",+ }),+ "zhipuai",+ );+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("maps MiniMax OpenAI-compatible endpoints to multimodal catalog metadata", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-minimax-openai-"));+ const catalogPath = join(dir, "api.json");+ await writeFile(+ catalogPath,+ JSON.stringify({+ "minimax-cn": {+ name: "MiniMax (China)",+ api: "https://api.minimaxi.com/anthropic/v1",+ models: {+ "MiniMax-M3": {+ id: "MiniMax-M3",+ name: "MiniMax-M3",+ attachment: true,+ reasoning: true,+ modalities: { input: ["text", "image", "video"], output: ["text"] },+ limit: { context: 1_048_576, output: 524_288 },+ },+ },+ },+ }),+ "utf8",+ );+ try {+ const catalog = new ModelsDevCatalog({ catalogPath });+ assert.equal(await catalog.ensureLoaded(), true);+ const input = {+ vendorKey: "custom",+ baseUrl: "https://api.minimaxi.com/v1",+ providerId: "custom-row",+ };+ const match = catalog.findModel({ ...input, modelId: "MiniMax-M3" });+ assert.equal(match?.providerKey, "minimax-cn");+ assert.deepEqual(match?.modalities.input, ["text", "image", "video"]);+ assert.equal(match?.attachment, true);+ assert.equal(catalog.modelsForProvider(input)[0]?.modelId, "MiniMax-M3");+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("models.dev reasoning options map to canonical levels", () => {+ assert.deepEqual(+ thinkingLevelsFromModelsDev(true, [{+ type: "effort",+ values: ["max", "low", "none", "invalid"],+ }]),+ ["off", "low", "max"],+ );+ assert.deepEqual(thinkingLevelsFromModelsDev(true, [{ type: "toggle" }]), ["off", "medium"]);+ assert.deepEqual(thinkingLevelsFromModelsDev(true, [{ type: "budget_tokens", min: 1024 }]), ["off", "medium"]);+ assert.deepEqual(thinkingLevelsFromModelsDev(true, []), ["low", "medium", "high"]);+ assert.deepEqual(thinkingLevelsFromModelsDev(false, [{ type: "effort", values: ["high"] }]), []);+});++test("toggle ladders still map off to none", () => {+ const [provider] = parseModelsDevCatalog({+ vendor: {+ name: "Vendor",+ models: {+ "toggle-model": {+ id: "toggle-model",+ reasoning: true,+ reasoning_options: [{ type: "toggle" }],+ },+ },+ },+ });+ const info = modelInfoFromModelsDev(provider.models[0], "row");+ assert.equal(info.thinkingLevelMap?.off, "none");+});++test("the application loads the bundled release snapshot without network access", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-release-"));+ const catalogPath = join(dir, "api.json");+ await writeFile(catalogPath, JSON.stringify(catalogFixture), "utf8");+ let calls = 0;+ try {+ const catalog = new ModelsDevCatalog({+ catalogPath,+ fetchImpl: async () => {+ calls += 1;+ throw new Error("startup must not fetch");+ },+ });+ assert.equal(+ catalog.findModel({ vendorKey: "anthropic", modelId: "claude-opus-4.6" }),+ undefined,+ "a lookup before the bundled snapshot loads can miss",+ );+ assert.equal(await catalog.ensureLoaded(), true);+ assert.equal(calls, 0);+ assert.equal(catalog.getStatus().source, "bundled");+ assert.equal(catalog.getStatus().catalogPath, catalogPath);+ assert.equal(+ catalog.findModel({ vendorKey: "anthropic", modelId: "claude-opus-4.6" })?.family,+ "claude-opus",+ );+ assert.equal(+ catalog.modelsForProvider({ vendorKey: "anthropic", providerId: "row" }).length,+ 2,+ "only text-capable models enter the agent picker",+ );+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("the bundled snapshot maps the latest 0.87.1 model ids to usable metadata", async () => {+ const catalog = new ModelsDevCatalog({+ catalogPath: fileURLToPath(new URL("../resources/models.dev/api.json", import.meta.url)),+ });+ assert.equal(await catalog.ensureLoaded(), true);++ const cases = [+ {+ vendorKey: "openai-codex",+ baseUrl: "https://chatgpt.com/backend-api",+ modelId: "gpt-6-sol",+ contextWindow: 1_050_000,+ maxTokens: 128_000,+ thinkingLevels: ["off", "low", "medium", "high", "xhigh", "max"],+ },+ {+ vendorKey: "openai-codex",+ baseUrl: "https://chatgpt.com/backend-api",+ modelId: "gpt-6-luna",+ contextWindow: 1_050_000,+ maxTokens: 128_000,+ thinkingLevels: ["off", "low", "medium", "high", "xhigh", "max"],+ },+ {+ vendorKey: "anthropic",+ baseUrl: "https://api.anthropic.com",+ modelId: "claude-opus-5-5",+ contextWindow: 1_000_000,+ maxTokens: 128_000,+ thinkingLevels: ["low", "medium", "high", "xhigh", "max"],+ },+ {+ vendorKey: "xai",+ baseUrl: "https://api.x.ai/v1",+ modelId: "grok-4.7",+ contextWindow: 500_000,+ maxTokens: 500_000,+ thinkingLevels: ["low", "medium", "high", "xhigh"],+ },+ ];++ for (const expected of cases) {+ const model = catalog.findModel(expected);+ assert.ok(model, `${expected.vendorKey}/${expected.modelId} must be in the snapshot`);+ assert.equal(model.reasoning, true);+ assert.deepEqual(model.thinkingLevels, expected.thinkingLevels);+ assert.deepEqual(model.modalities.input, ["text", "image", "pdf"]);+ const config = modelConfigFromModelsDev(model, expected.baseUrl);+ assert.equal(config.contextWindow, expected.contextWindow);+ assert.equal(config.maxTokens, expected.maxTokens);+ assert.deepEqual(config.input, ["text", "image"]);+ }++ const copilotClaude = catalog.findModel({+ vendorKey: "github-copilot",+ baseUrl: "https://api.individual.githubcopilot.com",+ modelId: "claude-opus-5.5",+ });+ assert.ok(copilotClaude, "GitHub Copilot must include Claude Opus 5.5");+ assert.equal(copilotClaude.reasoning, true);+ assert.equal(copilotClaude.limit.context, 1_000_000);+});++test("concurrent catalog reads share the bundled snapshot load", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-concurrent-load-"));+ const catalogPath = join(dir, "api.json");+ await writeFile(catalogPath, JSON.stringify(catalogFixture), "utf8");+ try {+ const catalog = new ModelsDevCatalog({ catalogPath });+ const first = catalog.ensureLoaded();+ const second = catalog.ensureLoaded();+ assert.equal(await first, true);+ assert.equal(await second, true);+ assert.equal(+ catalog.findModel({ vendorKey: "anthropic", modelId: "claude-opus-4.6" })?.family,+ "claude-opus",+ );+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("Settings refresh always refetches models.dev and only updates memory", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-refresh-"));+ const catalogPath = join(dir, "api.json");+ await writeFile(catalogPath, JSON.stringify(catalogFixture), "utf8");+ const refreshedFixture = {+ ...catalogFixture,+ anthropic: {+ ...catalogFixture.anthropic,+ models: {+ ...catalogFixture.anthropic.models,+ "claude-opus-4.6": {+ ...catalogFixture.anthropic.models["claude-opus-4.6"],+ name: "Updated Claude",+ },+ "new-model": {+ id: "new-model",+ name: "New Model",+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: 64_000, output: 4_000 },+ },+ },+ },+ };+ const calls = [];+ try {+ const catalog = new ModelsDevCatalog({+ catalogPath,+ fetchImpl: async (url, options) => {+ calls.push({ url, options });+ return responseFor(refreshedFixture);+ },+ });+ assert.equal(await catalog.ensureLoaded(), true);+ const existingInput = { vendorKey: "anthropic", modelId: "claude-opus-4.6" };+ const previousMatch = catalog.findModel(existingInput);+ assert.ok(previousMatch);+ assert.equal(catalog.findModel({ vendorKey: "anthropic", modelId: "new-model" }), undefined);+ assert.equal(calls.length, 0);+ assert.equal(await catalog.refresh(), true);+ assert.equal(calls.length, 1);+ assert.equal(calls[0].url, MODELS_DEV_API_URL);+ assert.deepEqual(calls[0].options.headers, { Accept: "application/json" });+ const refreshedMatch = catalog.findModel(existingInput);+ assert.notEqual(refreshedMatch, previousMatch);+ assert.equal(refreshedMatch?.displayName, "Updated Claude");+ assert.equal(+ catalog.findModel({ vendorKey: "anthropic", modelId: "new-model" })?.displayName,+ "New Model",+ );+ assert.deepEqual(+ JSON.parse(await readFile(catalogPath, "utf8")),+ catalogFixture,+ "settings refresh must not write the bundled release resource",+ );+ assert.equal(await catalog.refresh(), true, "a second settings refresh is also remote");+ assert.equal(calls.length, 2);+ assert.equal(catalog.getStatus().source, "remote");+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("a failed settings refresh preserves the bundled snapshot in memory", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-failure-"));+ const catalogPath = join(dir, "api.json");+ await writeFile(catalogPath, JSON.stringify(catalogFixture), "utf8");+ try {+ const catalog = new ModelsDevCatalog({+ catalogPath,+ fetchImpl: async () => {+ throw new Error("offline");+ },+ });+ assert.equal(await catalog.ensureLoaded(), true);+ const input = { vendorKey: "anthropic", modelId: "claude-opus-4.6" };+ const match = catalog.findModel(input);+ assert.ok(match);+ const reads = observeModelIdReads(match);+ const missing = { ...input, modelId: "unpublished-model" };+ assert.equal(catalog.findModel(missing), undefined);+ const beforeRefresh = reads();+ assert.equal(await catalog.refresh(), false);+ assert.equal(catalog.findModel(input), match);+ assert.equal(catalog.findModel(missing), undefined);+ assert.equal(reads(), beforeRefresh, "a failed refresh preserves both cached matches and misses");+ assert.equal(+ catalog.findModel({ vendorKey: "anthropic", modelId: "claude-opus-4.6" })?.family,+ "claude-opus",+ );+ assert.match(catalog.getStatus().lastError, /offline/);+ } finally {+ await rm(dir, { recursive: true, force: true });}- assert.equal(catalog.findModel({ ...relay, modelId: "mimo-v2.5-pro-1m" })?.id, "mimo-v2.5-pro");- assert.equal(catalog.findModel({ ...relay, modelId: "mimo-v2.6-flash-test" })?.id, "mimo-v2.6-flash");- assert.equal(catalog.findModel({ ...relay, modelId: "mimo-v2.6-fash-test" })?.id, "mimo-v2.6-fash");- // Semantic and release suffixes are not deployment labels, and a typo is- // never repaired unless that exact base ID is itself published.- assert.equal(catalog.findModel({ ...relay, modelId: "mimo-v2.6-flash-thinking" }), undefined);- assert.equal(catalog.findModel({ ...relay, modelId: "mimo-v2.6-flash-2026" }), undefined);- assert.equal(catalog.findModel({ ...relay, modelId: "mimo-v2.6-flaash-test" }), undefined);});/*- A relay row has no wrapped provider to apply its binding, so `modelConfigFor`- resolves the stored row itself. Without that a hand-pinned window would be- replaced by the published number while still claiming `user` provenance.+ The published `npm` / `env` / `doc` fields survive parsing because the setup+ form still derives the wire API from the adapter package and still points the+ user at the provider's own docs. Migrated here when the catalog-search suite+ was removed with the browsable-catalog UI.*/-test("a relay hit resolves the stored binding instead of dropping it", () => {- const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("xiaomi", [{ id: "mimo-v2.6-pro", contextWindow: 1_048_576, maxTokens: 131_072 }])] });- const row = {- id: "relay", vendorKey: "custom", baseUrl: "https://relay.example/v1",- models: [binding({ id: "mimo-v2.6-pro", contextWindow: 500_000, contextWindowSource: "user", maxTokens: 32_100, maxTokensSource: "user" })],- };- catalog.configureAccount(row);- const input = { providerId: "relay", vendorKey: "custom", baseUrl: row.baseUrl, modelId: "mimo-v2.6-pro" };- const pinned = catalog.modelConfigFor(input);- assert.equal(pinned.contextWindow, 500_000);- assert.equal(pinned.maxTokens, 32_100);- // The catalog record still answers: only the pin differs from it.- assert.notEqual(pinned.source, "generic");-});--test("a stored extended level cannot invent native Pi support", () => {- const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("example", [{ id: "chat", reasoning: true, thinkingLevelMap: { off: null, low: "low", high: "high" } }])] });- const row = { id: "account", vendorKey: "example", models: [binding({ thinkingLevels: ["low", "max"] })] };- catalog.configureAccount(row);- assert.deepEqual(getSupportedThinkingLevels(catalog.findModel(target)), ["low"]);- assert.deepEqual(row.models[0].thinkingLevels, ["low", "max"]);+test("parsed providers keep the published npm, env and doc fields", () => {+ const providers = parseModelsDevCatalog({+ anthropic: {+ id: "anthropic",+ name: "Anthropic",+ npm: "@ai-sdk/anthropic",+ api: "https://api.anthropic.com",+ doc: "https://docs.anthropic.com",+ env: ["ANTHROPIC_API_KEY"],+ models: {+ "claude-opus-4.6": {+ id: "claude-opus-4.6",+ name: "Claude 4.6 Opus",+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: 200000, output: 64000 },+ },+ },+ },+ "openrouter-lite": {+ id: "openrouter-lite",+ name: "OpenRouter Lite",+ npm: "@ai-sdk/openai-compatible",+ models: {+ "some-model": {+ id: "some-model",+ name: "Some Model",+ modalities: { input: ["text"], output: ["text"] },+ },+ },+ },+ });+ const anthropic = providers.find((item) => item.providerKey === "anthropic");+ assert.equal(anthropic.npm, "@ai-sdk/anthropic");+ assert.equal(anthropic.doc, "https://docs.anthropic.com");+ assert.deepEqual(anthropic.env, ["ANTHROPIC_API_KEY"]);+ assert.equal(anthropic.api, "https://api.anthropic.com");+ const gateway = providers.find((item) => item.providerKey === "openrouter-lite");+ assert.deepEqual(gateway.env, [], "a provider without env vars parses to an empty list");+ assert.equal(gateway.doc, undefined);+});++test("the wire API style is derived from the published adapter package", () => {+ assert.equal(apiStyleForAdapter("@ai-sdk/anthropic"), "anthropic_messages");+ assert.equal(apiStyleForAdapter("@ai-sdk/google-vertex/anthropic"), "anthropic_messages");+ assert.equal(apiStyleForAdapter("@ai-sdk/google"), "google_generative_ai");+ assert.equal(apiStyleForAdapter("@ai-sdk/openai"), "responses");+ // The long tail of gateways is OpenAI-compatible chat completions.+ assert.equal(apiStyleForAdapter("@ai-sdk/openai-compatible"), "chat_completions");+ assert.equal(apiStyleForAdapter(undefined), "chat_completions");+});++// A custom Anthropic Messages gateway (unknown base URL, vendorKey "custom")+// serving a Claude id that several catalog providers publish with differing+// reasoning options. The lookup refuses to pick one publisher, but the thinking+// wire shape of an exact Anthropic id is Anthropic's own (#990).+const ambiguousClaudeFixture = {+ anthropic: {+ name: "Anthropic",+ npm: "@ai-sdk/anthropic",+ models: {+ "claude-opus-5-5": {+ id: "claude-opus-5-5",+ name: "Claude Opus 5.5",+ reasoning: true,+ reasoning_options: [{ type: "effort", values: ["low", "medium", "high", "xhigh", "max"] }],+ tool_call: true,+ modalities: { input: ["text", "image"], output: ["text"] },+ limit: { context: 1_000_000, output: 128_000 },+ },+ },+ },+ requesty: {+ name: "Requesty",+ npm: "@ai-sdk/openai-compatible",+ api: "https://router.requesty.ai/v1",+ models: {+ "claude-opus-5-5": {+ id: "claude-opus-5-5",+ name: "Claude Opus 5.5",+ reasoning: true,+ reasoning_options: [+ { type: "effort", values: ["none", "low", "medium", "high", "max"] },+ { type: "budget_tokens" },+ ],+ tool_call: true,+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: 200_000, output: 64_000 },+ },+ "glm-5": {+ id: "glm-5",+ name: "GLM 5",+ reasoning: true,+ reasoning_options: [{ type: "effort", values: ["low", "high"] }],+ tool_call: true,+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: 200_000, output: 32_000 },+ },+ },+ },+};++const customGateway = {+ vendorKey: "custom",+ baseUrl: "https://gateway.example/v1",+};++test("a custom gateway enriches an ambiguous Claude leaf from the official provider", async (t) => {+ const catalog = await loadFixtureCatalog(t, ambiguousClaudeFixture);+ const config = catalogModelConfigFor(catalog, {+ ...customGateway,+ apiStyle: "anthropic_messages",+ modelId: "claude-opus-5-5",+ });++ assert.equal(config.source, "models.dev");+ assert.equal(config.contextWindow, 1_000_000);+ assert.equal(config.maxTokens, 128_000);+ assert.equal(config.reasoning, true);+ assert.deepEqual(config.reasoningOptions, [+ { type: "effort", values: ["low", "medium", "high", "xhigh", "max"] },+ ]);+ assert.deepEqual(config.thinkingLevelMap, {+ low: "low",+ medium: "medium",+ high: "high",+ xhigh: "xhigh",+ max: "max",+ off: null,+ });+});++test("official-provider enrichment is API-style independent while unknown ids stay generic", async (t) => {+ const catalog = await loadFixtureCatalog(t, ambiguousClaudeFixture);+ const completions = catalogModelConfigFor(catalog, {+ ...customGateway,+ apiStyle: "chat_completions",+ modelId: "claude-opus-5-5",+ });+ assert.equal(completions.source, "models.dev");+ assert.equal(completions.contextWindow, 1_000_000);+ assert.deepEqual(completions.reasoningOptions, [+ { type: "effort", values: ["low", "medium", "high", "xhigh", "max"] },+ ]);++ // An id absent from every publisher stays generic, even on Anthropic Messages.+ const unlisted = catalogModelConfigFor(catalog, {+ ...customGateway,+ apiStyle: "anthropic_messages",+ modelId: "unlisted-reasoning-model",+ });+ assert.equal(unlisted.source, "generic");+ assert.equal(unlisted.reasoningOptions, undefined);+ assert.equal(unlisted.thinkingLevelMap, undefined);++ // Aliases of a Claude id are not an exact Anthropic id.+ const renamed = catalogModelConfigFor(catalog, {+ ...customGateway,+ apiStyle: "anthropic_messages",+ modelId: "my-claude-opus-5-5-thinking",+ });+ assert.equal(renamed.reasoningOptions, undefined);+});++test("a resolved catalog record still wins over the Anthropic thinking fallback", async (t) => {+ const catalog = await loadFixtureCatalog(t, ambiguousClaudeFixture);+ const config = catalogModelConfigFor(catalog, {+ vendorKey: "requesty",+ baseUrl: "https://router.requesty.ai/v1",+ apiStyle: "anthropic_messages",+ modelId: "claude-opus-5-5",+ });+ assert.equal(config.source, "models.dev");+ assert.equal(config.contextWindow, 200_000);+ assert.ok(config.reasoningOptions?.some((option) => option.type === "budget_tokens"));+});++/*+ Release stamps in the published catalog.++ A gateway serves `mify/mimo-v2.5-pro-0731` while models.dev indexes the model+ under the id that owns the weights. The alias only ever borrows metadata: the+ id the row is addressed with stays the discovery result.+*/+test("a dated snapshot leaf does not borrow an undated published model", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ mify: {+ api: "https://api.mify.example/v1",+ models: {+ "mimo-v2.5-pro": {+ id: "mimo-v2.5-pro",+ name: "MiMo v2.5 Pro",+ reasoning: true,+ tool_call: true,+ limit: { context: 262_144, output: 32_768 },+ },+ },+ },+ });+ assert.equal(+ catalog.findModel({ vendorKey: "mify", modelId: "mify/mimo-v2.5-pro-0731" }),+ undefined,+ );+});++test("exact published leaves resolve without release-stamp aliasing", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ alpha: { api: "https://alpha.example/v1", models: {+ "foo-v2": { id: "foo-v2", limit: { context: 32_000 } },+ "foo-v2-0731": { id: "foo-v2-0731", limit: { context: 128_000 } },+ } },+ beta: { api: "https://beta.example/v1", models: {+ "foo-v2": { id: "foo-v2", limit: { context: 64_000 } },+ } },+ });+ const exact = catalog.findModel({ vendorKey: "alpha", modelId: "foo-v2-0731" });+ assert.equal(exact?.modelId, "foo-v2-0731");+ assert.equal(exact?.limit.context, 128_000);++ // Unpublished stamps do not strip down to a shorter sibling.+ assert.equal(catalog.findModel({ vendorKey: "alpha", modelId: "foo-v2-0815" }), undefined);++ // Same leaf, identical capabilities (limits are not part of the signature) ⇒+ // shared-capabilities enrichment with the lower median window.+ const shared = catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://relay.example/v1",+ modelId: "foo-v2",+ });+ assert.equal(shared?.limit.context, 32_000);++ // A uniquely published dated leaf still enriches.+ const published = catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://relay.example/v1",+ modelId: "foo-v2-0731",+ });+ assert.equal(published?.providerKey, "alpha");+ assert.equal(published?.limit.context, 128_000);+});++/*+ A custom endpoint is often the same publisher on another path.++ The reported failure: a custom row at `https://open.bigmodel.cn/api/v1` listed+ its models but every one of them showed generic defaults, because provider+ matching only accepted models.dev's own path for that host.+*/+test("a custom endpoint on a uniquely published host inherits that publisher", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ alpha: {+ api: "https://alpha.example/api/paas/v4",+ models: {+ "glm-5.3": {+ id: "glm-5.3",+ reasoning: true,+ tool_call: true,+ limit: { context: 1_000_000, output: 131_072 },+ },+ },+ },+ });+ const model = catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://alpha.example/api/v1",+ modelId: "glm-5.3",+ });+ assert.equal(model?.providerKey, "alpha");+ assert.equal(model?.limit.context, 1_000_000);+ assert.equal(model?.toolCall, true);++ // The whole row's records are reachable, not just the one id.+ assert.equal(+ catalog.modelsForProvider({ vendorKey: "custom", baseUrl: "https://alpha.example/api/v1", providerId: "row" }).length,+ 1,+ );+});++test("a host two publishers share leaves conflicting leaves unmatched", async (t) => {+ const catalog = await loadFixtureCatalog(t, {+ alpha: {+ api: "https://shared.example/api/paas/v4",+ models: { "glm-5.3": { id: "glm-5.3", reasoning: true, limit: { context: 1_000_000 } } },+ },+ beta: {+ api: "https://shared.example/api/coding/v4",+ models: { "glm-5.3": { id: "glm-5.3", reasoning: false, limit: { context: 32_000 } } },+ },+ });+ assert.equal(catalog.findModel({+ vendorKey: "custom",+ baseUrl: "https://shared.example/v1",+ modelId: "glm-5.3",+ }), undefined);+ // Naming the publisher still resolves it to that publisher's own record.+ const alpha = catalog.findModel({+ vendorKey: "alpha",+ baseUrl: "https://shared.example/v1",+ modelId: "glm-5.3",+ });+ assert.equal(alpha?.providerKey, "alpha");+ assert.equal(alpha?.limit.context, 1_000_000);});diff --git a/apps/desktop/test/provider-catalog-runtime.test.mjs b/apps/desktop/test/provider-catalog-runtime.test.mjsindex 1838f9a3a..2a10aa28f 100644--- a/apps/desktop/test/provider-catalog-runtime.test.mjs+++ b/apps/desktop/test/provider-catalog-runtime.test.mjs@@ -1,11 +1,39 @@import assert from "node:assert/strict";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";import { registerHooks } from "node:module";import test from "node:test";-import { fixtureProvider } from "./pi-catalog-fixtures.mjs";import { genericModelConfig } from "@pi-desktop/agent-runtime";import { ModelsDevCatalog } from "../electron/main/models-dev-catalog.ts";+const fixtureDirectory = await mkdtemp(join(tmpdir(), "models-dev-runtime-fixture-"));+const catalogPath = join(fixtureDirectory, "api.json");+await writeFile(catalogPath, JSON.stringify({+ example: {+ name: "Example",+ api: "https://models.example/v1",+ models: {+ "catalog-model": {+ id: "catalog-model",+ reasoning: true,+ reasoning_options: [{ type: "effort", values: ["low", "high"] }],+ tool_call: true,+ modalities: { input: ["text", "image"], output: ["text"] },+ limit: { context: 128_000, output: 8_192 },+ },+ "text-model": {+ id: "text-model",+ reasoning: false,+ modalities: { input: ["text"], output: ["text"] },+ limit: { context: 128_000, output: 8_192 },+ },+ },+ },+}), "utf8");+test.after(() => rm(fixtureDirectory, { recursive: true, force: true }));+const runtimeModule = new URL("../electron/main/runtime/provider-catalog.ts", import.meta.url);// The production bundler resolves this extensionless TypeScript import.const resolution = registerHooks({@@ -20,10 +48,7 @@ const { createProviderCatalogRuntime } = await import(runtimeModule.href).finally(() => resolution.deregister());async function fixtureRuntime() {- const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("example", [- { id: "catalog-model", reasoning: true, input: ["text", "image"] },- { id: "text-model" },- ])] });+ const catalog = new ModelsDevCatalog({ catalogPath });await catalog.ensureLoaded();const runtime = createProviderCatalogRuntime({getHost: () => null,@@ -73,8 +98,7 @@ for (const modelId of ["catalog-model", "unpublished-model"]) {const restored = runtime.enrichSession(session, [provider]);assert.equal(restored.supportsReasoning, true);assert.equal(restored.supportsVision, true);- assert.deepEqual(restored.supportedThinkingLevels, modelId === "catalog-model"- ? ["off", "minimal", "low", "medium", "high"] : ["max"]);+ assert.deepEqual(restored.supportedThinkingLevels, ["max"]);assert.deepEqual(provider.models[0].thinkingLevels, ["max"], "saved preferences remain intact");assert.equal(catalog.findModel(input), published, "binding edits do not replace catalog metadata");assert.deepEqual(session, { id: "session-one", providerId: provider.id, modelId });@@ -108,7 +132,7 @@ test("a bulk session refresh reuses catalog matches while preserving each sessioconst input = { vendorKey: provider.vendorKey, modelId: "catalog-model" };const match = catalog.findModel(input);assert.ok(match);- const modelId = match.id;+ const modelId = match.modelId;let modelReads = 0;Object.defineProperty(match, "name", {configurable: true,@@ -130,7 +154,7 @@ test("a bulk session refresh reuses catalog matches while preserving each sessio...session,supportsReasoning: true,supportsVision: true,- supportedThinkingLevels: ["off", "minimal", "low", "medium", "high"],+ supportedThinkingLevels: ["low", "high"],})));}assert.ok(modelReads <= 4, "bulk session reads reuse the one effective projection");@@ -152,9 +176,9 @@ test("full wire IDs isolate configured bindings while catalog aliases remain met};const catalogConfig = genericModelConfig(modelId, provider.baseUrl);assert.equal(runtime.bindingForModel(provider, ` ${modelId} `), provider.models[1]);- assert.equal(runtime.modelsDevModelFor(provider, modelId), undefined, "wire prefixes do not borrow another model");+ assert.equal(runtime.modelsDevModelFor(provider, modelId)?.modelId, "catalog-model");const selected = runtime.effectiveSubagentModelConfig(provider, modelId, catalogConfig);- assert.equal(selected.modelConfig.name, modelId, "request wire ID is not rewritten");+ assert.equal(selected.modelConfig.name, "catalog-model", "the display name follows the published record");assert.equal(selected.modelConfig.contextWindow, 32_000);assert.deepEqual(selected.capabilities.supportedThinkingLevels, ["high"]);const session = { providerId: provider.id, modelId };@@ -166,10 +190,11 @@ test("full wire IDs isolate configured bindings while catalog aliases remain metprovider.models = [provider.models[0]];assert.equal(runtime.bindingForModel(provider, modelId), undefined);assert.equal(runtime.effectiveSubagentModelConfig(provider, modelId, catalogConfig).modelConfig.contextWindow, 128_000);- assert.deepEqual(runtime.enrichSession(session, [provider]).supportedThinkingLevels, ["off", "minimal", "low", "medium", "high", "xhigh", "max"]);+ assert.deepEqual(runtime.enrichSession(session, [provider]).supportedThinkingLevels, ["low", "high"]);assert.equal(runtime.effectiveSubagentModelConfig(provider, modelId).modelConfig.contextWindow, 128_000);const otherProvider = { ...provider, id: "other-provider", models: [binding(modelId, 48_000, ["off"])] };- assert.deepEqual(runtime.enrichSession(session, [otherProvider, provider]).supportedThinkingLevels, ["off", "minimal", "low", "medium", "high", "xhigh", "max"]);+ // A different account's exact wire binding must not leak into this row.+ assert.deepEqual(runtime.enrichSession(session, [otherProvider, provider]).supportedThinkingLevels, ["low", "high"]);});test("unmatched models expose selectable thinking in providers, sessions and subagents", async () => {diff --git a/apps/desktop/test/provider-endpoint-metadata.test.mjs b/apps/desktop/test/provider-endpoint-metadata.test.mjsindex 977493bb2..3bfa976cb 100644--- a/apps/desktop/test/provider-endpoint-metadata.test.mjs+++ b/apps/desktop/test/provider-endpoint-metadata.test.mjs@@ -109,7 +109,7 @@ test("a custom row on a published host gets that publisher's model metadata", asconst [model] = result.models;assert.equal(model.modelId, "glm-5.3", "the wire id is the one the service served");- assert.equal(model.catalogSource, "pi", "the host identified the publisher");+ assert.equal(model.catalogSource, "models.dev", "the host identified the publisher");assert.equal(model.contextWindow, 1_000_000);assert.equal(model.maxTokens, 131_072);for (const capability of ["tools", "reasoning"]) {@@ -129,7 +129,7 @@ test("a relay's list reads the shipped publisher's record for a known id", asyncconst byId = new Map(result.models.map((model) => [model.modelId, model]));const known = byId.get("claude-sonnet-4-5");- assert.equal(known.catalogSource, "pi", "several publishers state this id");+ assert.equal(known.catalogSource, "models.dev", "several publishers state this id");// Anthropic's published window, not a median dragged down by resellers that// state a smaller deployment of the same id.assert.equal(known.contextWindow, 1_000_000);@@ -187,29 +187,31 @@ test("a relay enriches official IDs, strips safe deployment labels, and preserve// No official publisher states this leaf, so a reseller must not decide it.assert.equal(byId.get("deepseek-v4-flash").catalogSource, undefined);- // The mimo family's owner publishes the base ID; both served IDs inherit it.+ // Reseller copies disagree; an unanchored relay stays on the generic shape.for (const id of ["mimo-v2.5-pro", "mimo-v2.5-pro-1m"]) {const mimo = byId.get(id);assert.equal(mimo.modelId, id); // lookup never rewrites the served wire ID- assert.equal(mimo.contextWindow, 1_048_576);- assert.equal(mimo.maxTokens, 131_072);+ assert.equal(mimo.catalogSource, undefined);+ assert.equal(mimo.contextWindow, 128_000);+ assert.equal(mimo.maxTokens, 8_192);}- // A unique operation-metadata leaf still enriches without becoming a Pi chat.+ // Matching Xiaomi reseller records agree on the published speech limits.const tts = byId.get("mimo-v2.5-tts");- assert.equal(tts.source, "bundled");- assert.equal(tts.catalogSource, undefined);+ assert.equal(tts.source, "discovered");+ assert.equal(tts.catalogSource, "models.dev");assert.ok(tts.capabilities.includes("audio"));assert.equal(tts.contextWindow, 8_192);- // Official publisher disambiguation also applies after a `-1m` deployment tag.+ // This relay is unanchored and Google / Vertex records conflict, so a `-1m`+ // alias cannot choose one official endpoint's metadata.const gemini = byId.get("gemini-2.5-pro-1m");- assert.equal(gemini.catalogSource, "pi");- assert.equal(gemini.contextWindow, 1_048_576);+ assert.equal(gemini.catalogSource, undefined);+ assert.equal(gemini.contextWindow, 128_000);// Official Anthropic disambiguation still enriches exact leaves.const claude = byId.get("claude-sonnet-4-5");- assert.equal(claude.catalogSource, "pi");+ assert.equal(claude.catalogSource, "models.dev");assert.equal(claude.contextWindow, 1_000_000);});test("a relay enriches a uniquely published dated leaf without reseller majority voting", async (t) => {@@ -223,7 +225,7 @@ test("a relay enriches a uniquely published dated leaf without reseller majorityconst [model] = result.models;// Accept either enrichment from an exact leaf hit, or generic when ambiguous.- if (model.catalogSource === "pi") {+ if (model.catalogSource === "models.dev") {assert.ok(model.contextWindow > 0);} else {assert.equal(model.catalogSource, undefined);diff --git a/apps/desktop/test/vendor-oauth-login.test.mjs b/apps/desktop/test/vendor-oauth-login.test.mjsindex 8016ae3be..760d846aa 100644--- a/apps/desktop/test/vendor-oauth-login.test.mjs+++ b/apps/desktop/test/vendor-oauth-login.test.mjs@@ -585,7 +585,7 @@ test("the ChatGPT OAuth catalog includes GPT-6 Astra", async () => {assert.equal(model.api, "openai-codex-responses");});-test("the pi-ai 0.99.1 OAuth catalogs include the stable model wires", async () => {+test("the pi-ai OAuth catalog supplies wire identities, not model limits", async () => {const { OPENAI_CODEX_MODELS } = await import("@earendil-works/pi-ai/providers/openai-codex.models");@@ -593,10 +593,7 @@ test("the pi-ai 0.99.1 OAuth catalogs include the stable model wires", async ()const model = OPENAI_CODEX_MODELS[modelId];assert.ok(model, `openai-codex catalog must include ${modelId}`);assert.equal(model.api, "openai-codex-responses");- assert.equal(model.reasoning, true);- assert.equal(model.contextWindow, 272_000);- assert.equal(model.maxTokens, 128_000);- assert.ok(model.input.includes("image"));+ assert.equal(model.provider, "openai-codex");}const { GITHUB_COPILOT_MODELS } = await import(@@ -607,23 +604,16 @@ test("the pi-ai 0.99.1 OAuth catalogs include the stable model wires", async ()const model = GITHUB_COPILOT_MODELS[modelId];assert.ok(model, `github-copilot catalog must include ${modelId}`);assert.equal(model.api, "openai-responses");- assert.ok(model.input.includes("image"));+ assert.equal(model.provider, "github-copilot");}const { ANTHROPIC_MODELS } = await import("@earendil-works/pi-ai/providers/anthropic.models");assert.equal(ANTHROPIC_MODELS["claude-opus-5"]?.api, "anthropic-messages");- assert.equal(ANTHROPIC_MODELS["claude-opus-5"]?.contextWindow, 1_000_000);const { XAI_MODELS } = await import("@earendil-works/pi-ai/providers/xai.models");assert.equal(XAI_MODELS["grok-4.6"]?.api, "openai-responses");- const thinkingLevels = Object.entries(XAI_MODELS["grok-4.6"]?.thinkingLevelMap ?? {})- .filter(([, value]) => typeof value === "string")- .map(([level]) => level);- for (const level of ["low", "medium", "high", "xhigh"]) {- assert.ok(thinkingLevels.includes(level), `xAI catalog must include ${level} thinking`);- }});test("credential writes for one account run one at a time", async () => {@@ -731,8 +721,8 @@ test("an xAI account offers the chat models its /models endpoint returns", asyncconst row = host.providers.get(done.providerId);assert.deepEqual(row.models.map((model) => model.id), ["grok-4.6", "grok-4.7"]);const offered = row.models.find((model) => model.id === "grok-4.7");- assert.equal(offered.contextWindow, 500_000);- assert.deepEqual(offered.thinkingLevels, ["low", "medium", "high", "xhigh"]);+ assert.equal(offered.contextWindow, 128_000);+ assert.deepEqual(offered.thinkingLevels, ["off"]);assert.equal(await oauth.bindingFor(done.providerId, "grok-2"), undefined);const binding = await oauth.bindingFor(done.providerId, "grok-4.7");assert.equal(binding.apiStyle, "responses");@@ -744,7 +734,7 @@ test("an xAI account offers the chat models its /models endpoint returns", async}});-test("a new Grok inherits grok-4.6 even when an older Grok is first in the pin", async () => {+test("live account metadata never inherits a sibling model record", async () => {const fetchModels = async () => new Response(JSON.stringify({data: [{ id: "grok-4.7" }],}), { status: 200, headers: { "content-type": "application/json" } });@@ -785,9 +775,10 @@ test("a new Grok inherits grok-4.6 even when an older Grok is first in the pin",oauth.respond({ loginId, promptId: prompt.request.promptId, value: "abc" });const done = await waitFor(events, "done");const binding = await oauth.bindingFor(done.providerId, "grok-4.7");- assert.equal(binding.modelConfig.contextWindow, 500_000);- assert.equal(binding.modelConfig.maxTokens, 500_000);- assert.deepEqual(binding.supportedThinkingLevels, ["minimal", "low", "medium", "high", "xhigh"]);+ assert.equal(binding.modelConfig.source, "generic");+ assert.equal(binding.modelConfig.contextWindow, 128_000);+ assert.equal(binding.modelConfig.maxTokens, 8_192);+ assert.deepEqual(binding.supportedThinkingLevels, ["off"]);});async function liveCopilotBinding(sibling, options = {}) {@@ -839,33 +830,32 @@ const adaptiveSonnet = {},};-test("a live-only Claude model retains its sibling's thinking protocol and effort mapping", async () => {+test("a live-only Claude model does not inherit Pi metadata from its sibling", async () => {const binding = await liveCopilotBinding(adaptiveSonnet);assert.equal(binding.apiStyle, "anthropic_messages");assert.equal(binding.modelConfig.name, "claude-sonnet-99");- assert.equal(binding.modelConfig.compat?.forceAdaptiveThinking, true);- assert.deepEqual(binding.modelConfig.thinkingLevelMap, adaptiveSonnet.thinkingLevelMap);- assert.equal(binding.modelConfig.contextWindow, 1_000_000);- assert.equal(binding.modelConfig.maxTokens, 128_000);+ assert.equal(binding.modelConfig.source, "generic");+ assert.equal(binding.modelConfig.compat, undefined);+ assert.equal(binding.modelConfig.thinkingLevelMap, undefined);+ assert.equal(binding.modelConfig.contextWindow, 128_000);+ assert.equal(binding.modelConfig.maxTokens, 8_192);});-test("live-only reasoning models preserve default levels in sparse effort maps", async () => {+test("live-only reasoning models do not inherit a sibling effort map", async () => {const binding = await liveCopilotBinding({...adaptiveSonnet,thinkingLevelMap: { xhigh: "xhigh", max: "max" },});- assert.deepEqual(binding.supportedThinkingLevels, [- "off", "minimal", "low", "medium", "high", "xhigh", "max",- ]);- assert.equal(clampThinkingLevel(binding, "high"), "high");+ assert.deepEqual(binding.supportedThinkingLevels, ["off"]);+ assert.equal(clampThinkingLevel(binding, "high"), "off");});-test("live-only models respect null-disabled levels and non-reasoning siblings", async () => {+test("live-only models do not inherit reasoning restrictions from siblings", async () => {const restricted = await liveCopilotBinding({...adaptiveSonnet,thinkingLevelMap: { off: null, minimal: null, low: null, medium: null, high: null, xhigh: "xhigh", max: null },});- assert.deepEqual(restricted.supportedThinkingLevels, ["xhigh"]);+ assert.deepEqual(restricted.supportedThinkingLevels, ["off"]);const nonReasoning = await liveCopilotBinding({ ...adaptiveSonnet, reasoning: false });assert.equal(nonReasoning.supportsReasoning, false);assert.deepEqual(nonReasoning.supportedThinkingLevels, ["off"]);@@ -879,7 +869,7 @@ test("a live-only model without a same-tier sibling keeps generic capabilities",assert.equal(binding.modelConfig.thinkingLevelMap, undefined);});-test("published model metadata takes precedence over the pinned sibling", async () => {+test("models.dev metadata takes precedence over Pi sibling metadata", async () => {const published = {...genericModelConfig("claude-sonnet-99"),source: "models.dev",@@ -905,7 +895,7 @@ test("an explicit effort map on generic metadata governs the fallback's supporteassert.deepEqual(binding.supportedThinkingLevels, ["high"]);});-test("live-only Claude bindings send adaptive thinking with the requested wire effort", async () => {+test("a live-only Claude request keeps its wire ID without Pi sibling metadata", async () => {const binding = await liveCopilotBinding({...adaptiveSonnet,thinkingLevelMap: { off: null, minimal: null, xhigh: "xhigh", max: "max" },@@ -925,53 +915,55 @@ test("live-only Claude bindings send adaptive thinking with the requested wire e};const model = buildProviderModel(provider);const models = createProviderModels(provider, model);- for (const level of ["high", "xhigh", "max"]) {- let request;- const result = await models.streamSimple(model, {- messages: [{ role: "user", content: "fixture", timestamp: 1 }],- }, {- reasoning: clampThinkingLevel(provider, level),- maxRetries: 0,- fetch: async (input, init) => {- request = new Request(input, init);- return Response.json({ type: "error", error: { type: "invalid_request_error", message: "fixture response" } }, { status: 400 });- },- }).result();- assert.equal(result.stopReason, "error");- assert.ok(request, "the real adapter must reach the HTTP boundary");- const body = await request.json();- assert.equal(body.model, "claude-sonnet-99");- assert.equal(body.thinking.type, "adaptive");- assert.equal(body.output_config.effort, level);- assert.equal("budget_tokens" in body.thinking, false);- assert.equal(request.headers.get("Authorization"), "Bearer test-copilot-access-token");- assert.equal(request.headers.get("x-api-key"), null);- }+ let request;+ const result = await models.streamSimple(model, {+ messages: [{ role: "user", content: "fixture", timestamp: 1 }],+ }, {+ reasoning: "off",+ maxRetries: 0,+ fetch: async (input, init) => {+ request = new Request(input, init);+ return Response.json({ type: "error", error: { type: "invalid_request_error", message: "fixture response" } }, { status: 400 });+ },+ }).result();+ assert.equal(result.stopReason, "error");+ assert.ok(request, "the real adapter must reach the HTTP boundary");+ const body = await request.json();+ assert.equal(body.model, "claude-sonnet-99");+ assert.equal(body.thinking.type, "enabled");+ assert.equal(body.thinking.budget_tokens, 1_024);+ assert.equal(body.output_config, undefined);+ assert.equal(request.headers.get("Authorization"), "Bearer test-copilot-access-token");+ assert.equal(request.headers.get("x-api-key"), null);});-test("legacy thinking siblings are not implicitly promoted to adaptive", async () => {+test("legacy thinking siblings do not define an unknown model's thinking metadata", async () => {const binding = await liveCopilotBinding({...adaptiveSonnet,id: "claude-sonnet-4.5",compat: undefined,thinkingLevelMap: undefined,});+ assert.equal(binding.modelConfig.source, "generic");+ assert.equal(binding.modelConfig.contextWindow, 128_000);+ assert.equal(binding.modelConfig.maxTokens, 8_192);assert.notEqual(binding.modelConfig.compat?.forceAdaptiveThinking, true);assert.equal(binding.modelConfig.thinkingLevelMap, undefined);- assert.deepEqual(binding.supportedThinkingLevels, ["off", "minimal", "low", "medium", "high"]);+ assert.deepEqual(binding.supportedThinkingLevels, ["off"]);});-test("live-only thinking restrictions survive runtime launch without a saved model binding", async () => {+test("live-only models do not inherit thinking restrictions from a sibling", async () => {const disabled = { off: null, minimal: null, low: null, medium: null, high: null, xhigh: null, max: null };- for (const [sibling, expected] of [- [{ ...adaptiveSonnet, thinkingLevelMap: { ...disabled, high: "high" } }, { supportsReasoning: true, supportedThinkingLevels: ["high"] }],- [{ ...adaptiveSonnet, reasoning: false, thinkingLevelMap: undefined }, { supportsReasoning: false, supportedThinkingLevels: ["off"] }],- [{ ...adaptiveSonnet, thinkingLevelMap: disabled }, { supportsReasoning: false, supportedThinkingLevels: ["off"] }],+ for (const sibling of [+ { ...adaptiveSonnet, thinkingLevelMap: { ...disabled, high: "high" } },+ { ...adaptiveSonnet, reasoning: false, thinkingLevelMap: undefined },+ { ...adaptiveSonnet, thinkingLevelMap: disabled },]) {const binding = await liveCopilotBinding(sibling);const effective = modelConfigWithBinding(binding.modelConfig);- assert.deepEqual(capabilitiesFromModelConfig(effective), expected);- assert.deepEqual(effective.thinkingLevelMap, sibling.thinkingLevelMap);+ assert.equal(binding.modelConfig.thinkingLevelMap, undefined);+ assert.equal(effective.contextWindow, 128_000);+ assert.equal(effective.maxTokens, 8_192);}});diff --git a/docs/adr/0027-pi-model-catalog-authority.md b/docs/adr/0027-pi-model-catalog-authority.mdindex 292fbf141..c9387e6c7 100644--- a/docs/adr/0027-pi-model-catalog-authority.md+++ b/docs/adr/0027-pi-model-catalog-authority.md@@ -1,6 +1,6 @@# ADR 0027: Make pi-ai authoritative for model metadata-- Status: Accepted+- Status: Superseded for chat metadata by [models.dev catalog authority](models-dev-catalog-authority.md)- Date: 2026-07-27## Contextdiff --git a/docs/adr/0133-models-dev-primary-catalog-with-pi-fallback.md b/docs/adr/0133-models-dev-primary-catalog-with-pi-fallback.mdindex e42769c89..8c775c82c 100644--- a/docs/adr/0133-models-dev-primary-catalog-with-pi-fallback.md+++ b/docs/adr/0133-models-dev-primary-catalog-with-pi-fallback.md@@ -1,6 +1,6 @@# ADR 0133: Use models.dev as the primary model catalog with pi-ai fallback-- Status: Superseded by ADR 0134+- Status: Superseded for chat metadata by [models.dev catalog authority](models-dev-catalog-authority.md)- Date: 2026-08-29- Deciders: PI-Desktop core- Amends: ADR 0027, D136, D243diff --git a/docs/adr/0134-models-dev-sole-model-metadata-source.md b/docs/adr/0134-models-dev-sole-model-metadata-source.mdindex 7d6bcfee2..b5206862b 100644--- a/docs/adr/0134-models-dev-sole-model-metadata-source.md+++ b/docs/adr/0134-models-dev-sole-model-metadata-source.md@@ -1,6 +1,6 @@# ADR 0134: Use models.dev as the sole model metadata source with a local snapshot-- Status: Superseded by [Pi 0.99.1 authority](pi-ai-core-0991-authority.md)+- Status: Superseded for chat metadata by [models.dev catalog authority](models-dev-catalog-authority.md)- Date: 2026-08-29- Deciders: PI-Desktop core- Amends: ADR 0027, ADR 0133, D136, D266diff --git a/docs/adr/README.md b/docs/adr/README.mdindex c0f5d010f..1fb6ada89 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -20,7 +20,8 @@ Each ADR includes:| ID | Title | Status ||---|---|---|-| pi-ai-core-0991-authority | [Pi 0.99.1 account model authority](pi-ai-core-0991-authority.md) | Accepted for current migration candidate |+| models-dev-catalog-authority | [models.dev owns published model metadata](models-dev-catalog-authority.md) | Accepted for implementation |+| pi-ai-core-0991-authority | [Pi 0.99.1 account model authority](pi-ai-core-0991-authority.md) | Superseded for chat model metadata || plan-tool-declarations-and-execution-denials | [Keep known tool declarations while denying contract-mode execution](plan-tool-declarations-and-execution-denials.md) | Accepted for implementation || trusted-extension-operation-ownership | [Trusted extension operation ownership](trusted-extension-operation-ownership.md) | Implemented candidate || scheduled-desktop-automations | [Desktop automation scheduling](scheduled-desktop-automations.md) | Accepted for implementation |@@ -52,7 +53,7 @@ Each ADR includes:| 0024 | Composer Slash Commands and @ File References | Accepted || 0025 | Keep Application Menus out of Windows/Linux Windows | Accepted || 0026 | Move the Projects Index into Settings as an Archive | Superseded in part by 0036 |-| 0027 | Make pi-ai authoritative for model metadata | Accepted |+| 0027 | Make pi-ai authoritative for model metadata | Superseded for chat metadata || 0028 | Scope work-panel runtime contexts to conversations | Accepted || 0029 | Separate native-window and work-panel resize ownership | Superseded in part by 0032 || 0030 | Turn-boundary context checkpoint compaction | Accepted |@@ -159,8 +160,8 @@ Each ADR includes:| 0130 | Bounded Mounted Transcript Window | Accepted || 0131 | Spill Large Composer Text Pastes into Session Scratch | Accepted || 0132 | Attribute cross-display window moves to the user | Accepted |-| 0133 | Use models.dev as the primary model catalog with pi-ai fallback | Superseded by 0134 |-| 0134 | Use models.dev as the sole model metadata source with a local snapshot | Accepted |+| 0133 | Use models.dev as the primary model catalog with pi-ai fallback | Superseded for chat metadata by `models-dev-catalog-authority` |+| 0134 | Use models.dev as the sole model metadata source with a local snapshot | Superseded for chat metadata by `models-dev-catalog-authority` || 0135 | Retry unchanged edited prompts | Accepted || 0136 | Preserve the active task boundary across context compaction | Accepted || 0137 | Retained Session Panes | Accepted (amends 0130 clauses 4/5) |diff --git a/docs/adr/models-dev-catalog-authority.md b/docs/adr/models-dev-catalog-authority.mdnew file mode 100644index 000000000..147d04919--- /dev/null+++ b/docs/adr/models-dev-catalog-authority.md@@ -0,0 +1,52 @@+# ADR: models.dev owns published model metadata++- Status: Accepted for implementation+- Date: 2026-10-02+- Supersedes: `pi-ai-core-0991-authority.md` for chat model metadata++## Context++PI-Desktop's displayed and effective chat limits came from the pinned pi-ai+catalog. Its sibling models can share adapter defaults such as a 272,000-token+context window even when the selected model's published record has a different+limit. This affects Settings, the context inspector, session launch and+compaction budgets.++The repository already carries a reviewed models.dev snapshot and matching+logic that prefers the selected official publisher, then accepts other+publishers only when their matching records agree. It leaves ambiguous matches+generic instead of selecting an arbitrary reseller record. The historical+shipped-publisher set has 38 distinct preset vendor keys (40 after aliases),+not a verifiable fixed set of 39; the implementation therefore uses the+repository's provider and endpoint identities rather than claiming an+unsupported count.++## Decision++Use models.dev as the source of published chat model limits, modalities,+reasoning metadata, names and prices. Load the bundled snapshot offline and+refresh it explicitly. Resolve the selected publisher first; when no official+record matches, use a non-official publisher record only when the resolver can+establish a safe, unambiguous match. Otherwise retain the generic shape.++OAuth endpoints remain authoritative for which model IDs an account can use.+For each returned ID, enrich metadata from models.dev; do not copy context,+output, reasoning or prices from a pi-ai sibling. Preserve explicit per-account+binding overrides. Keep pi-ai for provider discovery/identity, OAuth and+transport, and typed non-chat operations that models.dev does not represent.++## Consequences++Published model limits now follow the selected models.dev record across+Settings, context budgeting and runtime launch. A missing or ambiguous record+stays generic and does not invent metadata. No provider credentials are sent+to models.dev, and no stored provider data, host protocol or database schema+changes.++## Alternatives++Keeping pi-ai as model metadata authority preserves adapter-adjacent defaults,+but can apply the wrong model's context window to a selected wire model.+Using models.dev as a browsable model list would expose models that an endpoint+does not serve or an account is not entitled to, so live endpoint/account IDs+remain the selection boundary.diff --git a/docs/adr/pi-ai-core-0991-authority.md b/docs/adr/pi-ai-core-0991-authority.mdindex 220c80921..4c1c7b94c 100644--- a/docs/adr/pi-ai-core-0991-authority.md+++ b/docs/adr/pi-ai-core-0991-authority.md@@ -1,6 +1,6 @@# ADR: Pi 0.99.1 account model authority-- Status: Accepted for the current migration candidate+- Status: Superseded for chat model metadata by [models.dev catalog authority](models-dev-catalog-authority.md)- Date: 2026-09-30- Supersedes: ADR 0134 model metadata sourcediff --git a/docs/spec/00-baseline.md b/docs/spec/00-baseline.mdindex d7fabe58f..515567513 100644--- a/docs/spec/00-baseline.md+++ b/docs/spec/00-baseline.md@@ -1,8 +1,8 @@# PI-Desktop Baseline Freeze-- Baseline Version: `0.4.19`-- Date: `2026-09-29`-- Status: `Frozen for implementation details (indefinite local permission approvals + Plan checkpoint artifact + approval/execution startup fence + protocol v11 + schema v16 + host-owned plugin session import/read/update/delete P0/P1 + selectable shell catalog + icon-free composer prompt row + turn-boundary context checkpoint compaction + session-scoped work panel + edge-specific work-panel/chat resize ownership + account-scoped Pi model catalog + provider/runtime safety + M5 hardening + settings IA + project archive + sidebar organization + app update delivery + three-platform release + Extensions page density and theme-readable actions + custom global UI font + ChatGPT-style logical project groups)`+- Baseline Version: `0.4.20`+- Date: `2026-10-02`+- Status: `Frozen for implementation details (indefinite local permission approvals + Plan checkpoint artifact + approval/execution startup fence + protocol v11 + schema v16 + host-owned plugin session import/read/update/delete P0/P1 + selectable shell catalog + icon-free composer prompt row + turn-boundary context checkpoint compaction + session-scoped work panel + edge-specific work-panel/chat resize ownership + models.dev chat model catalog + provider/runtime safety + M5 hardening + settings IA + project archive + sidebar organization + app update delivery + three-platform release + Extensions page density and theme-readable actions + custom global UI font + ChatGPT-style logical project groups)`- Language policy: **English-first**- Backend policy: **Rust host core + pi agent sidecar**@@ -31,6 +31,12 @@> ADR 0133 / D266 and ADR 0134 describe the historical models.dev source.> [Pi 0.99.1 authority](../adr/pi-ai-core-0991-authority.md) supersedes that> source with account-scoped Pi Models, preserving explicit Desktop bindings.+> `0.4.20` restores models.dev as the published chat-model metadata authority+> through ADR `models-dev-catalog-authority`: the bundled snapshot supplies+> limits and capabilities, with selected official publishers preferred and+> safe unanimous third-party matches as fallback. Pi remains the OAuth,+> transport and typed non-chat operation layer; it no longer supplies sibling+> chat-model limits.> `0.4.10` replaces destructive work-panel clearing on conversation switches> with runtime session-scoped contexts through D142 / ADR 0028.> `0.4.11` adopts turn-boundary model-context checkpoint compaction through@@ -154,7 +160,7 @@32. Observability MVP: **local logs only**33. Error model: **shared AppError code registry**34. Provider coverage: **universal via pi-ai native + OpenAI-compatible + custom**-35. Model policy: **no closed allowlist; account-scoped Pi catalog, generic unknown IDs, and free-form model IDs**+35. Model policy: **no closed allowlist; models.dev chat metadata, live account IDs, generic unknown IDs, and free-form model IDs**36. Provider storage: **Rust SQLite configs + OS secret store references**37. Secrets backend: **safeStorage primary + encrypted file fallback**38. Workspace ignore: **denylist + defaults + `.pi-desktopignore`**diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex da4b3c674..f6fc54bcc 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -6,7 +6,7 @@ PI-Desktop must support **all major market model vendors and models** that usersStrategy:-> **Universal provider coverage via Pi catalog model metadata + pi-ai transport adapters + OpenAI-compatible escape hatch.**+> **Universal provider coverage via models.dev model metadata + pi-ai transport adapters + OpenAI-compatible escape hatch.**We do **not** re-implement every vendor SDK ourselves.We standardize on pi’s multi-provider layer and add product-level configuration, catalog, and UX.@@ -40,7 +40,7 @@ Settings / UI├─ openai-compatible provider└─ custom provider definitions→ ModelCatalogService- ├─ Pi catalog snapshot (sole model metadata source)+ ├─ models.dev snapshot (published chat metadata)├─ runtime/provider discovery (IDs only for custom/dynamic models)└─ Rust-owned provider cache```@@ -101,9 +101,8 @@ OpenAI-style Copilot wire APIs keep signing the token as the request key; allwires retain per-request auth resolution and the account-specific `baseUrl`.Zhipu / GLM and Z.AI are named OpenAI-compatible endpoint presets among a-short Pi catalog-backed Service list of first-party vendors (including-Xiaomi). The add-provider Service picker persists the matching Pi catalog-`vendorKey` and uses the published endpoint without+short preset-backed Service list of first-party vendors (including Xiaomi).+The add-provider Service picker persists the matching provider `vendorKey` and uses the published endpoint withoutshowing Name, Base URL, or API format on the named-service path. Chat turnsstill use the selected pi-ai adapter (`chat_completions`, `responses`,`anthropic_messages`, `google_generative_ai`, or `opencode_go`). Zhipu / Z.AI@@ -121,10 +120,10 @@ ADR 0256 / #296). Official `deepseek.com` rows keep empty-string fill (#223).The overlay does not change `thinkingFormat`.Anthropic Messages requests set `forceAdaptiveThinking: true` when the-Pi catalog record publishes a reasoning `effort` option and no+models.dev record publishes a reasoning `effort` option and no`budget_tokens` option (for example Opus 4.7+, Opus 5.x, Fable). Those models-reject `thinking.type=enabled` with HTTP 400, and Pi catalog carries no pi-ai-compat record, so without the flag pi-ai would fall back to budget thinking.+reject `thinking.type=enabled` with HTTP 400, and the model's published+reasoning options determine that wire shape.Models that still publish `budget_tokens`, including those that also publish`effort`, keep budget thinking by default. The catalog uses this same rulefor the protocol displayed in model settings. An explicit@@ -135,7 +134,7 @@ catalog `compat` record is preserved.An Anthropic Messages row the catalog cannot identify (for example a customgateway URL serving an id several publishers list) still falls back to thegeneric model shape, but takes `reasoning_options` and the derived-`thinkingLevelMap` from Anthropic's own Pi catalog record when that record+`thinkingLevelMap` from Anthropic's own models.dev record when that recordhas exactly the same model id. Which thinking shape a Claude id accepts is aproperty of the model, not of the deployment, so only those two fieldstransfer; limits and modalities stay generic, and aliases, renamed ids, other@@ -144,9 +143,9 @@ wire APIs, and non-Claude ids served over the Anthropic protocol are unchanged## 5. Built-in vendor matrix (ship intent)-> Model metadata follows the bundled/in-memory Pi catalog catalog. Provider adapters remain-> available through pi-ai, and the OpenAI-compatible path stays open for models-> that Pi catalog does not list.+> Chat model metadata follows the bundled/in-memory models.dev catalog. Provider+> adapters, OAuth identities and wire transport remain available through pi-ai,+> and the OpenAI-compatible path stays open for unpublished models.### Tier A — always exposed in UI- OpenAI@@ -191,33 +190,36 @@ PI-Desktop must not permanently restrict users to a short fixed model list.### 6.2 Catalog responsibilities-1. pi-ai 0.99.1 Providers/Models own published metadata, transport, thinking- support and native operation types. Electron's historically named- `ModelsDevCatalog` is an account-aware adapter over this public API.+1. The bundled and explicitly refreshed models.dev snapshot owns published+ chat-model limits, modalities, reasoning metadata, display names and prices.+ The selected provider's official record has priority; if it has no record,+ another publisher is used only when the exact match is safe and unambiguous.+ The resolver uses the application's named publisher/endpoint identities;+ it does not claim a fixed 39-provider set when the checked-in preset keys+ and aliases do not produce that count.2. Startup is cache-only and disables ambient environment/file credentials.- Each configured account has its own Models collection and Host credential- store. Same-vendor rows cannot borrow one another's credentials.-3. OAuth live entitlement IDs are published through the account provider's- refresh/filter boundary. A successful list governs available chat models;- discovery failure preserves the pinned catalog. Live-only IDs may inherit- same-tier adapter/thinking metadata, with unknown prices retained as unknown.+ models.dev requests carry no provider credentials. Each configured OAuth+ account has its own Host credential store; same-vendor rows cannot borrow+ one another's credentials.+3. Live endpoint/account discovery owns the selectable IDs. A successful OAuth+ list governs available chat models; a failed list preserves the last usable+ IDs. A live-only ID without a models.dev record stays generic; it never+ inherits chat limits, reasoning or price from a pi-ai sibling.4. Settings exposes published metadata separately from explicit binding- overrides. Effective chat limits, inputs, thinking and request shape are- projected once at the account boundary and reused for ordinary sessions,- delegates, compaction and image lookup. Pi's unsupported/null effort mappings- cannot be re-enabled by stale persisted settings. No saved data is rewritten.+ overrides. Effective chat limits and thinking are resolved for sessions,+ delegates and compaction. Explicit user limits remain pinned, and no saved+ data is rewritten.5. Chat, image and classifier models are selected by operation type even when- they share a model ID. A small display-only operation metadata supplement- preserves settings visibility for image/audio/video/embedding records that- Pi does not publish. It supplies no runtime auth, dispatch, price or entitlement.+ they share a model ID. pi-ai remains responsible for OAuth, wire identity,+ transport and typed non-chat operations that models.dev does not describe.6. Free-form IDs remain configurable. Conservative generic metadata applieswhen no published model matches; explicit user overrides remain supported.Unknown relay metadata uses exact final-segment matching and an unambiguous- official publisher. Known endpoint aliases cannot borrow past an ambiguous- same-endpoint miss. No deployment/date/thinking suffix is removed.-7. Settings catalog refresh calls Pi's public refresh API. Release scripts no- longer fetch or package the independent Pi catalog JSON catalog. Pi version- pins provide the reproducible catalog baseline.+ publisher. Conflicting third-party records stay generic. No deployment,+ date or thinking suffix is removed to manufacture a match.+7. Settings catalog refresh calls models.dev explicitly. The bundled snapshot+ provides reproducible offline metadata. Refresh does not replace endpoint+ discovery or account entitlements.8. PDF capability remains metadata; attachments use bounded file referencesuntil the runtime supports a native PDF content block. Image capability isresolved against the effective selected binding before transport.@@ -345,7 +347,7 @@ type ThinkingLevel =The compatibility fields above are retained as a persisted-schema compatibilitysurface for older clients. PI-Desktop no longer reads them as runtime modeloverrides. `ModelInfo` reasoning support and supported thinking levels describe-the resolved Pi catalog record; effective provider/session capability comes from+the resolved models.dev record; effective provider/session capability comes fromthe exact `ModelBinding`. Unknown free-form ids start with the generic shape andno inferred reasoning capability; an empty binding level array is the genericseed, while a non-empty explicit binding may opt into or disable levels.@@ -448,23 +450,12 @@ excerpt of the response body with the request's credentials and anytoken-shaped value removed, so an upstream contract change is diagnosablefrom the provider log.-Image, video, speech and embedding ids are dropped. A model Pi catalog does-not know yet inherits limits, reasoning, adapter compatibility, and the wire-effort mapping from a pinned sibling of the same tier; xAI uses an explicit-newest-first sibling (`grok-4.7`, then `grok-4.6`, then `grok-4.5`, then-`grok-4.3`) so pin order cannot select an older Grok. A different tier is not-used. Existing model metadata takes precedence over borrowed compatibility and-effort mappings. Supported thinking levels follow pi-ai's mapping contract:-missing entries retain adapter defaults, `null` disables a level, and `xhigh`-or `max` requires an explicit mapping. Non-reasoning siblings remain off-only.-Without a stored user binding, runtime configuration preserves these inferred-restrictions instead of reopening every generic thinking level. An all-disabled-effort map remains non-reasoning. Truly unclassified generic models and explicit-user overrides retain their existing effective-thinking policy.-The same effective mapping determines both the supported levels and wire-effort, so a sparse map cannot silently promote `high` to `xhigh` or lose the-adaptive protocol. Published Pi catalog records bypass this fallback entirely.-Pi catalog still cannot add an id the account list did not return. A vendor+Image, video, speech and embedding ids are dropped from chat-model discovery. A+live-only chat ID without a models.dev record keeps generic limits and thinking+metadata; it never inherits those fields from a Pi sibling. Published+models.dev reasoning options determine supported levels and wire effort, while+the selected pi-ai adapter still handles transport. Pi's OAuth account list+cannot add an id the account endpoint did not return. A vendormay span wire APIs — Copilot serves Anthropic, Chat Completions and Responsesmodels — so the row's `apiStyle` follows the selected model.Deleting a row calls the normal host `providers.delete` path, which removes its@@ -520,7 +511,7 @@ type ModelDescriptor = {modelId: stringdisplayName: stringsource: "bundled" | "discovered" | "user"- catalogSource?: "pi"+ catalogSource?: "models.dev"capabilities: Array<"text" | "tools" | "vision" | "reasoning" | "json">contextWindow?: numbermaxOutputTokens?: number@@ -608,13 +599,14 @@ UI may show tier hints, but must not hard-block unknown models by default.## 13. Refresh & update policy-1. Use the pinned Pi catalog at startup without network or ambient credentials.-2. Settings may explicitly refresh Pi provider catalogs in memory.+1. Use the bundled models.dev snapshot at startup without network or ambient+ credentials.+2. Settings may explicitly refresh models.dev metadata in memory.3. Provider endpoint discovery preserves configured IDs and Host caches; OAuthlive discovery publishes account entitlements through the same Models owner.4. Failed refresh retains available metadata and configured bindings.-5. Release catalog changes arrive through reviewed Pi pins and patches; the- release script does not fetch a second model catalog.+5. Release catalog changes arrive through the reviewed models.dev snapshot;+ pi-ai version pins continue to control transport and OAuth behavior.## 14. Local / offline model supportdiff --git a/docs/spec/03-runtime/12-provider-config-schema.md b/docs/spec/03-runtime/12-provider-config-schema.mdindex cd1dc0e49..b51ce2dbb 100644--- a/docs/spec/03-runtime/12-provider-config-schema.md+++ b/docs/spec/03-runtime/12-provider-config-schema.md@@ -604,13 +604,16 @@ The canonical DDL lives in [04-data-storage](04-data-storage.md) (D086). Summary### `providers.listModels`- renderer IPC in: `{ providerId, source?: "cache"|"refresh" }`; `cache`returns the durable catalog without provider network access, while `refresh`- reads the local models.dev snapshot and runs provider endpoint discovery only for IDs absent from it+ probes the provider for selectable IDs and decorates the answer with the+ local models.dev snapshot; the catalog list is used only when discovery has+ no usable answer- host RPC in: `{ providerId?: string }`; reads only the Rust-owned `models`table- for an `authKind: "oauth"` row Electron main reads the signed-in account's- model list (see `03-runtime/11-provider-model-system.md`) instead of the- pinned catalog. pi-ai `models.getAvailable` is used only when that request- fails. Each returned model carries the apiStyle its wire API implies.+ model IDs (see `03-runtime/11-provider-model-system.md`) instead of the+ published catalog. pi-ai `models.getAvailable` may provide fallback IDs only+ when that request fails; it never supplies chat-model limits or capabilities.+ Each returned model carries the apiStyle its wire API implies.`openai-codex` calls `GET {base}/codex/models`, so an account id such as`gpt-6-luna` appears without a pin update; models.dev does not invent thoseIDs. Copilot still hides models the account did not enable.diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.mdindex 7e12192d3..ca251726f 100644--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md@@ -14,8 +14,8 @@ Therefore:## 2. Selection UXModel configuration is **discovery-first**: the AI service is the authority on-which models it serves, so the service's own endpoint is asked first and-Pi catalog is used only to enrich what came back. The bundled catalog is never+which models it serves, so the service's own endpoint is asked first and the+models.dev catalog is used only to enrich what came back. The bundled catalog is neverpresented as a browsable list of every published model — a deployment does notnecessarily host everything its vendor publishes, and a key is not necessarilyentitled to it.@@ -256,16 +256,16 @@ If user selects model tagged without tools while in Agent mode:## 6. Refresh behavior-The pinned pi-ai 0.99.1 catalog is the startup baseline. Startup reads no remote-catalog and uses no ambient credentials. `providers.refreshModelCatalog` invokes-Pi's public refresh API; settings metadata lookups themselves are local.+The bundled models.dev snapshot is the startup baseline. Startup reads no+remote catalog and uses no ambient credentials. `providers.refreshModelCatalog`+refreshes models.dev explicitly; settings metadata lookups themselves are local.-For keyed endpoints, live discovery supplies IDs and the central Pi catalog-adapter enriches their metadata. For OAuth, the account provider refresh hook-publishes live entitlement IDs into its existing Models collection. Successful-account lists are authoritative; a failed list preserves the pinned baseline.-Same-tier fallback for live-only IDs preserves transport and thinking behavior-but cannot invent known prices.+For keyed endpoints, live discovery supplies IDs and models.dev enriches their+metadata. For OAuth, the live account endpoint supplies entitled IDs, which are+then enriched from models.dev. Successful account lists are authoritative; a+failed list preserves the last usable IDs. A live-only ID with no models.dev+match stays generic; pi-ai sibling metadata never supplies its chat limits,+reasoning or price.`source: "cache"` reads Host caches and configured bindings without network.`source: "refresh"` probes the selected endpoint/account and decorates returned@@ -282,9 +282,9 @@ If refresh fails / offline:- allow custom model id- still allow providers with known model ids- when a saved provider cache is empty or partial, append every configured- model binding before applying Pi catalog metadata decoration, so multi-model+ model binding before applying models.dev metadata decoration, so multi-modelsettings remain editable and per-model capability state stays aligned-- if no matching pinned Pi metadata is available offline, keep the configured IDs visible with generic text-only metadata+- if no matching bundled models.dev metadata is available offline, keep the configured IDs visible with generic metadata## 8. Catalog item schema@@ -311,7 +311,7 @@ type ModelCatalogItem = {"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max">/** Which known catalog supplied metadata for this row. */- catalogSource?: "pi"+ catalogSource?: "models.dev"}```@@ -321,13 +321,13 @@ When UI/search requests models for picker:1. recent models for enabled providers2. user-defined models-3. Pi catalog records for the matching provider/API URL+3. models.dev records for the matching provider/API URL4. provider discovery/cache for custom or account-specific models5. always include "custom model id" entry actionDeduplicate by `(providerId, modelId)` with priority:-`user > Pi catalog > provider-discovered > recent-only`. The `catalogSource`-field records a Pi catalog match; a provider cache stores only normalized+`user > models.dev catalog > provider-discovered > recent-only`. The `catalogSource`+field records a models.dev match; a provider cache stores only normalizedselection fields and is re-decorated from the local raw catalog on the nextread.@@ -338,11 +338,11 @@ model window and output cap. Bindings record their provenance independently:`contextWindowSource` belongs to `contextWindow`, and `maxTokensSource` belongsto `maxTokens`.-- `catalog` — that limit is a Pi catalog snapshot, so a later correction to its- published field replaces it. A refreshed context such as `gpt-5.6-luna`+- `catalog` — that limit is a models.dev snapshot, so a later correction to its+ published field replaces it. A refreshed context such as `gpt-6.1-sol`(`1,050,000` tokens) stops appearing as a 128k model, and a row added whilenothing published its id stops reporting the generic 8.2k output once the- record resolves. Only a resolved Pi catalog record counts as published: when+ record resolves. Only a resolved models.dev record counts as published: whenlookup falls back to the generic shape (for example a gateway serving an idseveral publishers list), its 128k / 8.2k values are not a correction and thestored catalog snapshot stays in force.@@ -507,10 +507,10 @@ generic metadata and explicit binding overrides.- refresh failures keep previous cache and surface non-fatal errorElectron decorates cached and freshly returned model rows from the local-Pi catalog snapshot. Runtime model resolution passes the same full Pi catalog-configuration to the selected pi-ai transport adapter. Provider discovery-remains an ID-only fallback for custom/account-specific models absent from the-snapshot.+models.dev snapshot. Runtime model resolution uses the same resolved metadata+for limits and capabilities while pi-ai remains the selected transport+adapter. Provider discovery remains the ID source for custom/account-specific+models absent from the snapshot.## 13. Search behavior@@ -563,11 +563,12 @@ same model to the check mark, the toggle and the duplicate guard.- [ ] the settings picker always exposes the canonical thinking ladder;published levels seed known models and explicit binding levels clamp thesame way in Composer, Electron main, and the pi sidecar-- [ ] Pi catalog metadata wins for a matching provider/model; an ID absent from- it uses the generic shape while pi-ai supplies only transport/OAuth+- [ ] models.dev metadata wins for a matching provider/model; an ID absent from+ it uses the generic shape while pi-ai supplies only transport/OAuth and+ typed non-chat operation support- [ ] provider settings and cached discovery cannot replace known catalogcapabilities; explicit binding edits remain persisted configuration-- [ ] a Pi catalog limit correction reaches an already saved `catalog` binding+- [ ] a models.dev limit correction reaches an already saved `catalog` bindingwithout deleting and re-adding the model, while a number the user entered inAdvanced (`user`) survives every correction, a hand-entered `128,000`included@@ -577,7 +578,7 @@ same model to the check mark, the toggle and the duplicate guard.- [ ] the provenance marker survives a provider save/read round trip and anunmarked record keeps working- [ ] unknown free-form models remain runnable without invented capabilities-- [ ] a Pi catalog record and an unknown generic record resolve through the same+- [ ] a models.dev record and an unknown generic record resolve through the sameselected transport without sending provider credentials to the remote catalog- [ ] compact limit text never reads above the published value, keeps theneighbouring 1M-line windows apart (`1M` / `1.05M` / `1.1M`), and neverdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 1f13efff6..57d22a634 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -4829,10 +4829,10 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.references until the selected transport exposes a native PDF block. Aprovider-discovered or explicitly configured ID absent from models.dev remainsrunnable with the generic text-only, non-reasoning shape; pi-ai supplies only- the selected wire adapter, OAuth flow, and account model availability. A- ChatGPT Plus/Pro or GitHub Copilot account lists `gpt-6-sol`, `gpt-6-luna`,- and `grok-4.7` from the pinned pi-ai 0.99.1 catalog; the account Pi adapter then- supplies their published metadata.+ the selected wire adapter, OAuth flow, and fallback account IDs. A ChatGPT+ Plus/Pro or GitHub Copilot account lists IDs returned by its live account+ endpoint; matching models.dev records supply their published metadata, while+ live-only IDs absent from models.dev keep generic chat limits and capabilities.- **Specs linked**: `02-architecture/02-tech-stack.md`,`03-runtime/11-provider-model-system.md`,`03-runtime/13-model-catalog-and-selection.md`, ADR 0134@@ -7969,7 +7969,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.#### E2E-102e: Unknown model ids fail closed for vision transport-- **Preconditions**: A custom provider/model id absent from the pi-ai catalog,+- **Preconditions**: A custom provider/model id absent from the models.dev catalog,discovery data that incorrectly labels it `vision`, no explicit`supportsImages` binding override, and a pasted PNG.- **Steps**:@@ -8789,21 +8789,18 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.release file or writing a user cache. 4. Add an ID absent from models.devand inspect its generic fallback card. 5. In the OAuth protocol fixture,sign in to an account that offers a new Claude ID absent from models.dev- but with a pinned same-tier sibling. Resolve its runtime binding, apply- runtime model configuration without a saved model binding, and send `high`,- `xhigh`, and `max` through the real Anthropic adapter to an intercepted HTTP- boundary. Repeat with null-disabled levels, an all-disabled map, a- non-reasoning sibling, and an ID with no same-tier sibling.+ while a same-tier Pi sibling exists. Resolve its runtime binding, apply+ runtime model configuration without a saved model binding, and send a+ request through the real Anthropic adapter to an intercepted HTTP boundary.+ Confirm the sibling does not supply chat limits, reasoning levels or effort+ mappings.- **Expected**: models.dev fields prefill known model bindings and remain thepublished metadata source. Provider keys are never included in the fixedmodels.dev request. Custom IDs without metadata retain generic defaults.- An OAuth live-only ID may use the existing same-tier fallback: protocol- compatibility and effort mappings travel with borrowed reasoning. Requests- use adaptive thinking and the requested effort, without legacy token budgets;- sparse mappings retain defaults and explicit nulls remain unsupported. A- non-reasoning sibling remains off-only, and no same-tier sibling means no- inferred reasoning. Published metadata and explicit mapping/compatibility- values take precedence. Copilot Bearer authentication remains unchanged.+ An OAuth live-only ID does not inherit metadata from a Pi sibling; only an+ exact models.dev match supplies its chat limits and reasoning shape. The+ selected adapter keeps its wire behavior, and Copilot Bearer authentication+ remains unchanged.- **Specs linked**: `03-runtime/11-provider-model-system.md` §6.2 and §8a,`03-runtime/13-model-catalog-and-selection.md` §11.1–§12, ADR 0134- **Acceptance**: B (model config), C (conversation & stream), Security@@ -11757,7 +11754,9 @@ This test plan spec is accepted when:account model and save. 5) Reopen the account editor and read that model'schips. 6) For an OpenAI Codex account, inspect `gpt-6-astra` (or anotheraccount model also published under models.dev's `openai` provider) and confirm- its published context/output limits and reasoning levels are present. 7) In+ its published context/output limits and reasoning levels are present. For+ `gpt-6.1-sol`, verify a 1,050,000-token context and 128,000-token output cap.+ 7) Inthe account editor, hand-type a custom model ID the catalog does not publish,enable a thinking level on it, and save.- **Expected**: Both dialogs render the same picker — the same discovered list,@@ -11770,8 +11769,9 @@ This test plan spec is accepted when:generic 128,000 / 8,192 / no-reasoning defaults. The authenticated ChatGPTlist comes from `GET {base}/codex/models` on the account token, so an id thepin does not know yet is selectable when that response includes it; pi-ai is- only the fallback when the request fails. models.dev cannot add a missing- OAuth ID. A model with no published record keeps its explicit levels, starts+ only the OAuth/transport adapter; it supplies no sibling chat-model limits.+ models.dev enriches an ID only when its record matches. A model with no+ published record keeps its explicit levels, startsat `off` when no binding default is stored, and keeps all choices availablefor manual opt-in. The account's default model stays the head binding.- **Specs linked**: `04-ux/06-settings-ia.md`,@@ -15416,14 +15416,14 @@ plugin-form fixtures in an isolated temporary directory at runtime.#### E2E-MODEL-catalog-window-correction-reaches-saved-bindings-- **Goal**: a Pi catalog limit correction — the context window or the output cap —+- **Goal**: a models.dev limit correction — the context window or the output cap —reaches an already saved binding without deleting and re-adding the model, whilea number the user entered in Settings is never overwritten.- **Steps**:- 1. Configure a provider, select a model Pi publishes a context window+ 1. Configure a provider, select a model models.dev publishes a context windowfor, and save. Open the row's Advanced body and read the context-window fieldand its hint.- 2. Serve a corrected catalog record for that model (a different published+ 2. Serve a corrected models.dev record for that model (a different publishedwindow), reopen Settings, and read the row, the context inspector, and thewindow a new session launches with.3. Type a window in the Advanced field — the preset ladder once and adiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex cb529ea7d..97ea2753f 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -1,7 +1,7 @@# Decisions Log-> Baseline delta: `0.3.0` → `0.4.16`-> Date: `2026-08-14`+> Baseline delta: `0.3.0` → `0.4.20`+> Date: `2026-10-02`> Status: Accepted for implementationThis log freezes previously open questions into concrete decisions.@@ -33,6 +33,7 @@ This log freezes previously open questions into concrete decisions.| D636 | Local permission approvals have no automatic deadline | **Amend D005 / ADR 0011 and supersede the local tool-permission timeout clauses in the runtime and UX specs: a permission-gated `tools.execute` request remains pending in host-core, the renderer, and the transport until the user chooses Allow once, Allow for session, or Deny, or the request is cancelled / the process shuts down. Remove the 120-second countdown and timeout fields from the local permission contract. Tool-specific execution budgets and the separate RACP/Plan approval lifetimes remain unchanged. See ADR 0310, issue #1214, and E2E-017.** | A visible permission request could be missed while the user worked elsewhere; automatic denial after 120 seconds silently prevented the requested action. Keeping cancellation and execution budgets preserves control and resource safety without turning inattention into a decision. || D637 | Remove the Windows frameless resize rim | **Disable the Windows main window's thick frame while retaining Electron 43.6 native frameless edge and corner resizing. Apply a 4 DIP native rounded shape by default; authorized plugin themes may choose an integer radius from 0 to 24 DIP. Keep the D635 minimum-size contract and existing work-panel resize ownership. See ADR 0317 and E2E-167.** | The thick frame paints an unwanted left, bottom, and right rim that themes cannot remove. Native hit testing and shape keep resizing and transparent outer corners without renderer resize IPC. || D638 | Publish native Linux arm64 artifacts | **Amend D126 / D285 / D603 / ADR 0022: tag releases publish native Linux arm64 AppImage, deb, and rpm packages, built on GitHub's native `ubuntu-22.04-arm` runner and carrying an arm64 `pi-desktop-host-core`. The static Linux targets drop their pinned `arch` and take the workflow's `--x64` / `--arm64` flag; `linux.artifactName` becomes `PI-Desktop-<version>-linux-<arch>.AppImage`; each Linux lane verifies its architecture-named updater feed (`latest-linux.yml` on x64, `latest-linux-arm64.yml` on arm64); the ASAR export reads `linux-unpacked` or `linux-arm64-unpacked` and publishes `PI-Desktop-<version>-linux-<arch>.asar`. `pi-host-bundle` builds both Linux architectures and `PUBLISHED_TARGETS` gains `linux-arm64`. Updater ownership, signing, and delivery modes are unchanged. See ADR 0318, issue #1281, and E2E-192a.** | arm64 Linux devices could not install or run the published x64 artifact, and a cross-built or emulated lane would ship a mismatched Rust sidecar. |+| D639 | models.dev owns published chat-model metadata | **Supersede D136 / D266 and ADR `pi-ai-core-0991-authority` for chat metadata: the bundled and explicitly refreshed models.dev catalog supplies published chat-model limits, modalities, reasoning metadata, names, and prices. Prefer the selected official publisher; when it has no record, accept another publisher only for a safe, unambiguous match, otherwise keep generic metadata. The checked-in preset identities are the priority set; do not assert an unsupported fixed count of 39. Live endpoint/OAuth discovery still owns selectable IDs. Pi remains responsible for OAuth, wire identity, transport and typed non-chat operations, but never supplies sibling chat limits, reasoning or prices. Explicit user binding overrides remain authoritative. No credentials are sent to models.dev; no host schema/protocol or persistence change. See ADR `models-dev-catalog-authority` and E2E-162 / E2E-MODEL-catalog-window-correction-reaches-saved-bindings.** | A Pi sibling default assigned a 272,000-token window to GPT models whose selected models.dev records publish 1,050,000 tokens, changing the Settings display and runtime context budget. || D450 | Signed macOS GitHub Releases | **Amend D078 / ADR 0022: GitHub tag releases Developer ID-sign, notarize (`notarytool` via electron-builder 26), staple, and Gatekeeper-verify macOS DMG/ZIP before upload, using identity `Developer ID Application: XingYu Liu (DUV63RKYTW)` / team `DUV63RKYTW` from Actions secrets (`CSC_LINK`, `CSC_KEY_PASSWORD`, `APPLE_ID`, `APPLE_APP_SPECIFIC_PASSWORD`, `APPLE_TEAM_ID`). Missing secrets fail the job. Local unsigned packaging without a certificate remains. `workflow_dispatch` may set `sign_macos: false` only for unsigned debug artifacts. Packaged macOS uses in-app `electron-updater` (ZIP + merged `latest-mac.yml`); Linux deb/rpm and Windows portable ZIP stay notify-and-link. No afterPack/afterSign adhoc codesign (ADR 0278).** | Production DMGs must open without a Gatekeeper warning, and signed macOS installs can download and restart into a new tag. See ADR 0289, E2E-196c, E2E-067A. |## B. Secondary implementation defaults@@ -317,7 +318,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| ID | Topic | Decision | Rationale ||---|---|---|---|-| D266 | Use models.dev as the primary model catalog | **Amend D136 / ADR 0027: Electron main loads `https://models.dev/api.json` as the primary provider/model metadata source, matches by provider key or normalized API URL, and maps its limits, modalities, reasoning options, tool-call, structured-output, display-name, and cost fields into the existing model surfaces. The pinned `pi-ai` catalog remains the local fallback for unavailable/missing remote records and supplies adapter-specific compatibility data where models.dev has no equivalent. Provider endpoint discovery and explicit model IDs remain available for custom/account-specific models; no provider credential is sent to models.dev, and no host schema/protocol change is introduced.** | The pinned pi-ai catalog is accurate for runtime adapters but lags the broader market catalog. A bounded, main-process models.dev fetch gives Settings and Composer current model coverage while preserving offline/local behavior and pi-ai's transport fallback. |+| D266 | Use models.dev as the primary model catalog | **Historical decision, superseded for chat metadata by D639 / ADR `models-dev-catalog-authority`.** Previous text: Electron main loads `https://models.dev/api.json` as the primary provider/model metadata source, with the pinned `pi-ai` catalog as local fallback. Provider endpoint discovery and explicit model IDs remain available for custom/account-specific models; no provider credential is sent to models.dev, and no host schema/protocol change is introduced. | A bounded, main-process models.dev fetch was first introduced to give Settings and Composer broader catalog coverage. D639 removes Pi sibling metadata as the chat fallback after it assigned wrong context limits. |## M. Agent runtime decisions@@ -328,7 +329,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D132 | Composer permission menu shows effective modes only | **The agent-mode composer chip and menu expose only `ask`, `accept-edits`, and `auto`, with the effective mode selected directly and no global-default/inherit entry or provenance label. Choosing an item stores that explicit session override. Existing `inherit` persistence and resolution from D115 remain unchanged until the user chooses a mode. This supersedes only D115's composer-presentation clause.** | The inherited entry repeated a selectable mode and exposed storage provenance instead of the permission posture the user is choosing; presenting the three effective modes makes the control direct without changing host enforcement || D116 | Provider failures as assistant messages | **Every provider/model turn failure is attached to a durable `role=assistant`, `status=error` transcript message through optional `UiMessage.error`. The message shows a localized summary and stable code, keeps redacted provider detail behind an accessible disclosure, and offers context-appropriate Retry or Settings actions. Message-bound failures never use toast/global banner presentation and never re-enter later model context.** | Errors belong to the failed turn; preserving them in the transcript makes the response diagnosable after session switches/restarts without contaminating the next model request or exposing credentials || D127 | Context-preserving reseed + transport retry | **Reseeding a recreated pi runtime from the persisted transcript restores tool call/result pairs (from tool rows' `toolCallId`/`toolArgs`/`toolResult`) in addition to user/assistant text and thinking. Interrupted tool rows restore as errored results; orphaned tool rows get a synthesized call-only assistant carrier so pairs stay adjacent and well-formed. Failed assistant turns stay transcript-only. Separately, request setup uses one bounded pi-ai retry for transient transport/provider failures; post-response stream recovery is defined by D186.** | Text-only reseed collapsed a session's context after any runtime recreation (regenerate/edit, config change, restart): the model lost every tool result it had gathered and — seeing its own history answer without visible tool use — stopped calling tools, degrading agent sessions into bare chat. The incident trigger was a single un-retried provider timeout that forced the user into regenerate. D127 corrects the initially duplicated D120 identifier; D120 remains the earlier application-update decision frozen by baseline 0.4.6. |-| D136 | pi-ai owns known-model metadata | **For every model resolved from the pinned pi-ai catalog, Electron main passes the complete pi model snapshot to the sidecar and PI-Desktop replaces only connection identity. Provider Settings and the model menu do not override reasoning support, thinking levels, context/output limits, temperature, or compatibility. Unknown free-form ids remain usable through an explicit generic text-only, non-reasoning fallback. This supersedes D102 and the provider-override clauses of D096/D107.** | A second desktop-owned model matrix discarded pi metadata, drifted from adapter behavior, and made model semantics depend on conflicting configurations; fixes for known models now belong in pi-ai or a pi-ai upgrade. |+| D136 | pi-ai owns known-model metadata | **Historical decision, superseded for chat metadata by D639 / ADR `models-dev-catalog-authority`.** Previous text: resolved Pi records governed published metadata; unknown IDs used generic metadata. **This supersedes D102 and the provider-override clauses of D096/D107.** | A second desktop-owned model matrix had previously discarded Pi metadata. The later D639 root-cause evidence showed that Pi sibling defaults could misstate the selected model's context window. || D183 | Segmented tool and model latency logs *(superseded by D385 / ADR 0212; UI clause superseded by D184)* | **Every `tools.execute` call is timed in segments instead of one opaque duration: host-core emits a `tool timing` line on the `host` channel and persists `prompted`, `permissionWaitMs`, `overheadMs`, and `totalMs` next to the existing `durationMs` on `tool_execute` / `tool_denied` audit rows; the sidecar writes greppable `[timing] kind=tool …` (`hostRttMs`) and `[timing] kind=model …` (`providerWaitMs`, `streamMs`, including failed/aborted turns) lines to the `agent` channel, suppressible with `PI_DESKTOP_TIMING=0`. The original no-UI clause is superseded by D184; logging remains unchanged.** | "Executing a command is slow" was undiagnosable from the logs: approval waiting, the tool body, and the provider round trip were indistinguishable, so a 45s gap between two audit rows with 0ms durations gave no clue whether it was the user, the model, or the host. Splitting the stages makes the answer readable without reproducing the run. || D158 | Turn-boundary context checkpoint compaction *(soft-boundary, model-tool, and visibility clauses superseded by D200; the model tool and visibility restored in Codex's shape by D203)* | **PI-Desktop reuses pi-agent-core's context estimation, session-context, and compaction primitives but owns the orchestration and durability. After every `turn_end`, before any next provider request, the runtime evaluates model-aware soft/hard budgets. A transient deduplicated instruction can ask the model to call the internal `CompactContext` tool; the tool's normal activity row is visible/durable, while the instruction is not. Crossing the hard budget forces checkpoint generation and blocks the request on failure. A final atomic tool batch that reaches half the hard budget is fairly head/tail-truncated only in the checkpoint copy, with explicit markers and every call/result envelope retained; original transcript rows remain complete. Exact provider overflow removes the failed assistant from model context, creates one checkpoint, and retries once. Host protocol v6 appends checkpoint records beside the untouched visible JSONL transcript; restart, late truncation, and included-boundary forks preserve the newest valid checkpoint. Disabling automatic compaction removes the tool and all automatic threshold/overflow recovery, while `/compact` remains available. OpenCode DCP is an AGPL-3.0 behavioral reference only and is neither linked nor copied (ADR 0030).** | pi's end-of-run-only behavior cannot protect long tool loops, and a model reminder alone cannot guarantee provider safety. Reusing pi's tested compaction format while adding a deterministic `turn_end` gate prevents another provider request from crossing the known window, retains user-visible history, and avoids importing an incompatible plugin/runtime and license boundary. || D185 | Lazy per-turn tool activation *(the always-active `CompactContext` clause is void under D200, and holds again for `new_context` under D203; activation restoration amended by D400 / ADR 0225)* | **The sidecar keeps a complete local tool registry but sends only the mode core set and local `ToolSearch` on each new prompt. `BrowserPreview`, plugin tools, `Skill`, and plugin-development helpers appear as bounded compact catalog entries and are activated by exact-name or capability search; the next turn receives their schemas, native pi-ai deferred search is used when supported, and the in-memory set resets before the next user prompt, then restores only successful activation evidence still present in the effective context and allowed by the current catalog and mode. Host permissions, containment, timeouts, and audits are unchanged.** | Full tool schemas made simple first requests disproportionately large and repeated optional capability cost across turns. A pi-style active set preserves core coding ergonomics while making ancillary tools pay-as-you-go and provider-independent; restoring successful context evidence prevents the model from seeing a capability marker without receiving the corresponding schema. |@@ -2358,7 +2359,7 @@ D193, and D194.`03-runtime/13-model-catalog-and-selection.md` §11.2,`04-ux/08-component-spec.md` §11.7–11.8, and E2E-163.-## 2026-08-19 — models.dev is the primary model catalog+## 2026-08-19 — models.dev first replaces Pi as the primary model catalog (historical)- D266 amends D136 / ADR 0027. Electron main loads the public`https://models.dev/api.json` catalog with a bounded timeout and matches@@ -2369,12 +2370,22 @@ D193, and D194.existing model surfaces. API keys and OAuth credentials never accompany therequest. `catalogSource` distinguishes models.dev from the pi-ai fallback inrenderer metadata without changing the host schema.-- If the remote catalog cannot be loaded or has no matching record, the pinned- pi-ai catalog supplies known native models and adapter compatibility. Custom- or account-specific provider discovery and explicit IDs remain available- after that fallback. See ADR 0133, `03-runtime/11-provider-model-system.md`,+- D639 later removes the Pi sibling chat-metadata fallback. The historical+ decision remains here to preserve the record of the migration. See ADR 0133,+ `03-runtime/11-provider-model-system.md`,`03-runtime/13-model-catalog-and-selection.md`, and E2E-066/E2E-080/E2E-154.+## 2026-10-02 — models.dev is the chat model metadata authority++- D639 supersedes the Pi 0.99.1 metadata decision and the Pi sibling fallback.+ The bundled models.dev snapshot supplies chat context/output limits and+ capabilities; the selected official publisher wins, followed by safe,+ unambiguous third-party records. Missing or conflicting records stay generic.+- Live endpoint and OAuth responses still determine selectable IDs. Pi remains+ the OAuth and transport adapter and supplies typed non-chat operations only.+ Explicit user binding values remain pinned, and no provider secrets are sent+ to models.dev. See ADR `models-dev-catalog-authority`.+## 2026-08-19 — The work panel becomes a plugin extension point- Decision D246. A plugin declares work panel surfaces with `contributes.views`diff --git a/docs/spec/README.md b/docs/spec/README.mdindex 3aec5df4c..fc8b356f8 100644--- a/docs/spec/README.md+++ b/docs/spec/README.md@@ -1,7 +1,7 @@# PI-Desktop Spec-> Frozen baseline: `0.4.16` · current app line: `0.14.x`-> Updated: `2026-09-10`+> Frozen baseline: `0.4.20` · current app line: `0.14.x`+> Updated: `2026-10-02`> Language: **English-first**> Stack: Electron + **Rust host core** + pi Agent Harness + user-installable plugins