Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(llm): move model listing logic into the providers that own it
Elian Doran71f4487866ca
diff --git a/apps/server/scripts/update-model-prices.ts b/apps/server/scripts/update-model-prices.tsindex 3742f8b58f..cabdcd02ff 100644--- a/apps/server/scripts/update-model-prices.ts+++ b/apps/server/scripts/update-model-prices.ts@@ -18,7 +18,7 @@import { writeFileSync } from "node:fs";import { fileURLToPath } from "node:url";-import type { ModelPrice, ModelPriceTable, ProviderPrices } from "../src/services/llm/providers/model_listing.js";+import type { ModelPrice, ModelPriceTable, ProviderPrices } from "../src/services/llm/providers/base_provider.js";const SOURCE_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.tsindex 7f4179af79..15379c17b8 100644--- a/apps/server/src/services/llm/index.spec.ts+++ b/apps/server/src/services/llm/index.spec.ts@@ -25,13 +25,15 @@ function makeProviderMock(tag: string) {return [{ id: `${tag}-model`, name: `${tag} Model` }];}listModels() {- // A current model plus a preview one — the fallback recommendation- // rule (non-openai) keeps the former and drops the latter.return Promise.resolve([{ id: `${tag}-model`, name: `${tag} Model` },{ id: `${tag}-preview`, name: `${tag} Preview` }]);}+ /** Stands in for the provider's own rule — index only forwards to it. */+ recommendedModelIds(models: { id: string }[]) {+ return new Set(models.filter(m => !m.id.endsWith("-preview")).map(m => m.id));+ }};}@@ -164,8 +166,8 @@ describe("llm/index provider registry", () => {describe("listProviderModels", () => {it("lists models for ad-hoc credentials, tagged with the recommended flag", async () => {// No saved config needed — the add/edit flow passes raw credentials.- // Uses "google" to exercise the generic non-preview fallback rule;- // provider-specific recommendation rules are covered in model_listing.spec.+ // Only the delegation is asserted here; each provider's own rule is+ // covered in its spec (openai/anthropic/google/claude_agent).const models = await listProviderModels("google", "k");expect(models).toEqual([{ id: "google-model", name: "google Model", recommended: true },diff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.tsindex e6ac89d1fc..3ff5e0be71 100644--- a/apps/server/src/services/llm/index.ts+++ b/apps/server/src/services/llm/index.ts@@ -3,7 +3,6 @@ import { getLog, options as optionService } from "@triliumnext/core";import { AnthropicProvider } from "./providers/anthropic.js";import { ClaudeAgentProvider } from "./providers/claude_agent.js";import { GoogleProvider } from "./providers/google.js";-import { recommendedModelIds } from "./providers/model_listing.js";import { OpenAiProvider } from "./providers/openai.js";import type { LlmProvider, ModelInfo } from "./types.js";@@ -146,8 +145,9 @@ export async function listProviderModels(provider: string, apiKey: string, baseUconst instance = factory(apiKey, baseURL);const models = await (instance.listModels?.() ?? instance.getAvailableModels());// Tag the default-selected set here so the recommendation rule lives on the- // server (next to the model metadata) rather than in the client picker.- const recommended = recommendedModelIds(models, provider);+ // server — in the provider that owns its model id shape — rather than in the+ // client picker.+ const recommended = instance.recommendedModelIds(models);return models.map(model => ({ ...model, recommended: recommended.has(model.id) }));}diff --git a/apps/server/src/services/llm/providers/anthropic.spec.ts b/apps/server/src/services/llm/providers/anthropic.spec.tsindex 1bdd99712d..8c1c90c3c1 100644--- a/apps/server/src/services/llm/providers/anthropic.spec.ts+++ b/apps/server/src/services/llm/providers/anthropic.spec.ts@@ -347,3 +347,30 @@ describe("AnthropicProvider model listing", () => {await expect(provider.listModels()).rejects.toThrow(/Unexpected \/models response shape/);});});++describe("AnthropicProvider recommendedModelIds", () => {+ const recommend = (ids: string[]) =>+ new AnthropicProvider("sk-ant").recommendedModelIds(ids.map(id => ({ id, name: id })));++ it("recommends the newest version of each Claude family", () => {+ const ids = recommend([+ "claude-fable-5",+ "claude-opus-4-8", "claude-opus-4-7", "claude-opus-4-6", "claude-opus-4-20250514",+ "claude-sonnet-5", "claude-sonnet-4-6", "claude-sonnet-4-20250514",+ "claude-haiku-4-5-20251001"+ ]);+ // One per family, newest each — Fable 5, Opus 4.8, Sonnet 5, Haiku 4.5.+ expect([...ids].sort()).toEqual([+ "claude-fable-5", "claude-haiku-4-5-20251001", "claude-opus-4-8", "claude-sonnet-5"+ ]);+ });++ it("treats a snapshot date as the version, not a minor bump", () => {+ // sonnet-4-20250514 is 4.0, so sonnet-4-6 (4.6) must outrank it.+ expect([...recommend(["claude-sonnet-4-20250514", "claude-sonnet-4-6"])]).toEqual(["claude-sonnet-4-6"]);+ });++ it("ignores ids that don't match the claude-<family>-<version> shape", () => {+ expect(recommend(["some-proxy-model", "claude-instant"]).size).toBe(0);+ });+});diff --git a/apps/server/src/services/llm/providers/anthropic.ts b/apps/server/src/services/llm/providers/anthropic.tsindex 2119634ecd..af22aaea56 100644--- a/apps/server/src/services/llm/providers/anthropic.ts+++ b/apps/server/src/services/llm/providers/anthropic.ts@@ -2,9 +2,8 @@ import { type AnthropicProvider as AnthropicSDKProvider,createAnthropic } from "import type { LlmMessage } from "@triliumnext/commons";import { type ModelMessage, stepCountIs, streamText, type SystemModelMessage, type ToolSet } from "ai";-import type { LlmProviderConfig, StreamResult } from "../types.js";-import { BaseProvider, buildModelMessage } from "./base_provider.js";-import type { RemoteModel } from "./model_listing.js";+import type { LlmProviderConfig, ModelInfo, StreamResult } from "../types.js";+import { BaseProvider, buildModelMessage, type RemoteModel } from "./base_provider.js";const OFFICIAL_BASE_URL = "https://api.anthropic.com/v1";@@ -60,6 +59,10 @@ export class AnthropicProvider extends BaseProvider {});}+ override recommendedModelIds(models: ModelInfo[]): Set<string> {+ return anthropicRecommendedIds(models);+ }+/*** Override buildSystemMessage to add an Anthropic cache control breakpoint* on the system prompt.@@ -146,3 +149,55 @@ export class AnthropicProvider extends BaseProvider {return streamText(streamOptions);}}++/**+ * Anthropic model id shape: `claude-<family>-<major>[-<minor>][-<YYYYMMDD>]`.+ * The optional trailing 8-digit snapshot date is not part of the version —+ * `claude-sonnet-4-20250514` is Sonnet 4.0, not 4.20250514 — so the minor+ * group is capped at two digits to force the date into the snapshot group.+ */+const ANTHROPIC_MODEL = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?$/;++/**+ * Recommend the newest version within each Claude family (Opus, Sonnet, Haiku,+ * Fable, and any future one) — one model per family, so today's Opus 4.8,+ * Sonnet 5, Haiku 4.5 and Fable 5. Older revisions and dated snapshots stay in+ * the picker, unchecked.+ *+ * Exported because the Claude Code subscription provider serves the same+ * `claude-*` catalog and must apply the same rule, without inheriting from+ * {@link AnthropicProvider} (it runs the Agent SDK, not the AI SDK).+ */+export function anthropicRecommendedIds(models: ModelInfo[]): Set<string> {+ const byFamily = new Map<string, ModelInfo[]>();+ for (const model of models) {+ const family = anthropicFamily(model.id);+ if (!family) {+ continue;+ }+ const members = byFamily.get(family) ?? [];+ members.push(model);+ byFamily.set(family, members);+ }+ const recommended = new Set<string>();+ for (const members of byFamily.values()) {+ const newest = members.reduce((best, m) => (anthropicVersion(m.id) > anthropicVersion(best.id) ? m : best));+ recommended.add(newest.id);+ }+ return recommended;+}++/** `claude-opus-4-8` → "opus"; null for ids that aren't `claude-<family>-<version>`. */+function anthropicFamily(id: string): string | null {+ return ANTHROPIC_MODEL.exec(id)?.[1] ?? null;+}++/** `claude-opus-4-8` → 4.8, `claude-sonnet-5` → 5, `claude-sonnet-4-20250514` → 4 (the trailing date is not a minor). */+function anthropicVersion(id: string): number {+ const match = ANTHROPIC_MODEL.exec(id);+ if (!match) {+ return 0;+ }+ const [, , major, minor] = match;+ return parseFloat(minor ? `${major}.${minor}` : major);+}diff --git a/apps/server/src/services/llm/providers/base_provider.spec.ts b/apps/server/src/services/llm/providers/base_provider.spec.tsindex 75615e951d..22c6749b17 100644--- a/apps/server/src/services/llm/providers/base_provider.spec.ts+++ b/apps/server/src/services/llm/providers/base_provider.spec.ts@@ -3,7 +3,7 @@ import { encodeUtf8 } from "@triliumnext/core/src/services/utils/binary.js";import type { LanguageModel } from "ai";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { LlmProviderConfig } from "../types.js";+import type { LlmProviderConfig, ModelInfo } from "../types.js";const { streamTextMock, generateTextMock, noteMetaMock, errorLogMock, beccaStub } = vi.hoisted(() => ({streamTextMock: vi.fn((..._args: any[]) => ({}) as any),@@ -43,8 +43,14 @@ vi.mock("../tools/index.js", () => ({allToolRegistries: [{ toToolSet: () => ({ fake_tool: { description: "x" } }) }]}));-import { BaseProvider, buildModelList, buildModelMessage } from "./base_provider.js";-import type { ProviderPrices, RemoteModel } from "./model_listing.js";+import {+ BaseProvider,+ buildModelList,+ buildModelMessage,+ mergeModelLists,+ type ProviderPrices,+ type RemoteModel+} from "./base_provider.js";const TEST_MODELS: Parameters<typeof buildModelList>[0] = [{ id: "cheap", name: "Cheap", pricing: { input: 1, output: 2 } },@@ -137,6 +143,75 @@ describe("getAvailableModels / getModelPricing (from the price table)", () => {});});+describe("mergeModelLists", () => {+ const CURATED: ModelInfo[] = [+ { id: "gpt-4.1", name: "GPT-4.1", pricing: { input: 2, output: 8 }, contextWindow: 1047576, isDefault: true },+ { id: "gpt-4.1-mini", name: "GPT-4.1 Mini", pricing: { input: 0.4, output: 1.6 }, contextWindow: 1047576 },+ { id: "gpt-4o", name: "GPT-4o", pricing: { input: 2.5, output: 10 }, contextWindow: 128000, isLegacy: true }+ ];++ it("keeps base metadata for known models and appends unknown ones alphabetically", () => {+ const merged = mergeModelLists(CURATED, [+ { id: "gpt-9" },+ { id: "gpt-4.1-mini" },+ { id: "gpt-5" },+ { id: "gpt-4.1" }+ ]);+ expect(merged.map(m => m.id)).toEqual(["gpt-4.1", "gpt-4.1-mini", "gpt-5", "gpt-9"]);+ // Base entries keep their pricing/default metadata...+ expect(merged[0]).toMatchObject({ name: "GPT-4.1", pricing: { input: 2, output: 8 }, isDefault: true });+ // ...unknown ones carry no pricing.+ expect(merged[2]).toEqual({ id: "gpt-5", name: "gpt-5", contextWindow: undefined });+ });++ it("prefers the endpoint's display name over the base list's for known models", () => {+ const merged = mergeModelLists(+ [{ id: "gpt-4.1", name: "gpt-4.1", pricing: { input: 2, output: 8 } }],+ [{ id: "gpt-4.1", name: "GPT-4.1 (from endpoint)" }]+ );+ expect(merged[0].name).toBe("GPT-4.1 (from endpoint)");+ });++ it("drops curated models absent from the remote list", () => {+ expect(mergeModelLists(CURATED, [{ id: "gpt-4.1" }]).map(m => m.id)).toEqual(["gpt-4.1"]);+ });++ it("uses the remote display name and context window when provided", () => {+ const merged = mergeModelLists([], [{ id: "llama3.2", name: "Llama 3.2", contextWindow: 131072 }]);+ expect(merged[0]).toMatchObject({ id: "llama3.2", name: "Llama 3.2", contextWindow: 131072, isDefault: true });+ });++ it("fills a curated model's missing context window from the remote data", () => {+ const curated: ModelInfo[] = [{ id: "m", name: "M", pricing: { input: 1, output: 1 } }];+ expect(mergeModelLists(curated, [{ id: "m", contextWindow: 32000 }])[0].contextWindow).toBe(32000);+ });++ it("promotes the first model to default when the curated default is unavailable", () => {+ const merged = mergeModelLists(CURATED, [{ id: "gpt-4o" }, { id: "custom-model" }]);+ expect(merged.map(m => [m.id, m.isDefault ?? false])).toEqual([+ ["gpt-4o", true],+ ["custom-model", false]+ ]);+ });++ it("returns an empty list when the remote list shares nothing and is empty", () => {+ expect(mergeModelLists(CURATED, [])).toEqual([]);+ });+});++describe("recommendedModelIds (generic rule)", () => {+ it("recommends every model that is neither a preview nor legacy", () => {+ // Providers whose id shape carries no recency signal (e.g. Google) keep+ // this default; OpenAI/Anthropic override it in their own modules.+ const ids = new TestProvider().recommendedModelIds([+ { id: "gemini-2.5-flash", name: "Gemini 2.5 Flash" },+ { id: "gemini-3-flash-preview", name: "Gemini 3 Flash Preview" },+ { id: "gemini-2.0-flash", name: "Gemini 2.0 Flash", isLegacy: true }+ ]);+ expect([...ids]).toEqual(["gemini-2.5-flash"]);+ });+});+describe("listModels", () => {it("returns the price-table list when the provider has no dynamic listing", async () => {const models = await new TestProvider().listModels();diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.tsindex c58f4621d1..92ae3e3c19 100644--- a/apps/server/src/services/llm/providers/base_provider.ts+++ b/apps/server/src/services/llm/providers/base_provider.ts@@ -9,7 +9,6 @@ import { type FilePart, generateText, type ImagePart, type LanguageModel, type Mimport { allToolRegistries } from "../tools/index.js";import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";import { resolveAttachmentPart } from "./attachment_content.js";-import { mergeModelLists, type ModelPriceTable, type ProviderPrices, type RemoteModel } from "./model_listing.js";import MODEL_PRICES_JSON from "./model_prices.json" with { type: "json" };import { buildNoteHint } from "./note_hint.js";import { buildSystemPrompt as composeSystemPrompt } from "./system_prompt.js";@@ -17,6 +16,40 @@ import { buildSystemPrompt as composeSystemPrompt } from "./system_prompt.js";const DEFAULT_MAX_TOKENS = 8096;const TITLE_MAX_TOKENS = 30;+/**+ * A model as reported by a provider's models endpoint. Only what the listing+ * APIs actually return — pricing is never part of it.+ */+export interface RemoteModel {+ id: string;+ /** Human-readable name, when the API provides one (e.g. Anthropic's `display_name`). */+ name?: string;+ /** Context window in tokens, when the API provides one (e.g. Google's `inputTokenLimit`). */+ contextWindow?: number;+}++/**+ * Per-model pricing/metadata, sourced from the committed `model_prices.json`+ * (pruned from LiteLLM — see `scripts/update-model-prices.ts`). This is the+ * single source of truth for cost/context data now that the hand-curated+ * per-provider model arrays are gone; the endpoint (dynamic listing) remains the+ * source of truth for which models exist and their display names.+ */+export interface ModelPrice {+ /** USD per million input tokens. */+ input: number;+ /** USD per million output tokens. */+ output: number;+ /** Context window in tokens, when known. */+ ctx?: number;+}++/** One provider's pricing, keyed by model id. */+export type ProviderPrices = Record<string, ModelPrice>;++/** The whole committed price table: provider name → model id → pricing. */+export type ModelPriceTable = Record<string, ProviderPrices>;+/*** The committed pricing/context table — the single source of truth for cost* metadata now that per-provider model arrays are gone. Keyed by provider name@@ -89,6 +122,58 @@ export function buildModelList(baseModels: CuratedModel[]): {return { models: baseModels, pricing };}+/**+ * Merge a live-fetched model list with a base metadata list (the provider's+ * price-table slice, see {@link BaseProvider.getAvailableModels}).+ *+ * The remote list is the source of truth for *availability* and *display name*:+ * base entries absent from it are dropped, remote models unknown to the base+ * list are included with whatever metadata the endpoint reported (no pricing).+ * The base list supplies pricing and context window (and, offline, a fallback+ * name) for the models it knows; the endpoint's display name always wins when+ * present.+ *+ * Shared by {@link BaseProvider.listModels} and the Claude Agent provider, which+ * merges the CLI's catalog rather than an HTTP endpoint's but needs the same rules.+ *+ * Ordering: base-known models first (in base order), then unknown remote models+ * alphabetically. An existing default keeps its flag; otherwise the first merged+ * model becomes the default so callers relying on `find(m => m.isDefault)` keep+ * working.+ */+export function mergeModelLists(curated: ModelInfo[], remote: RemoteModel[]): ModelInfo[] {+ const remoteById = new Map(remote.map(m => [m.id, m]));++ const known = curated+ .filter(m => remoteById.has(m.id))+ .map(m => {+ const remoteModel = remoteById.get(m.id);+ return {+ ...m,+ // The endpoint is authoritative for display names (e.g. Anthropic's+ // `display_name`); the base name is only an offline fallback.+ name: remoteModel?.name ?? m.name,+ contextWindow: m.contextWindow ?? remoteModel?.contextWindow+ };+ });++ const curatedIds = new Set(curated.map(m => m.id));+ const unknown = remote+ .filter(m => !curatedIds.has(m.id))+ .sort((a, b) => a.id.localeCompare(b.id))+ .map<ModelInfo>(m => ({+ id: m.id,+ name: m.name ?? m.id,+ contextWindow: m.contextWindow+ }));++ const merged = [...known, ...unknown];+ if (merged.length > 0 && !merged.some(m => m.isDefault)) {+ merged[0] = { ...merged[0], isDefault: true };+ }+ return merged;+}+export abstract class BaseProvider implements LlmProvider {abstract name: string;@@ -331,6 +416,16 @@ export abstract class BaseProvider implements LlmProvider {.sort((a, b) => a.id.localeCompare(b.id));}+ /**+ * The ids pre-selected by default when adding or resetting this provider.+ * The generic rule — everything that is neither a preview nor a legacy model+ * — is overridden by providers whose id shape carries a usable recency+ * signal (see {@link OpenAiProvider} and {@link AnthropicProvider}).+ */+ recommendedModelIds(models: ModelInfo[]): Set<string> {+ return new Set(models.filter(m => !m.isLegacy && !/preview/i.test(m.id)).map(m => m.id));+ }+async generateTitle(firstMessage: string): Promise<string> {const { text } = await generateText({model: this.createModel(this.titleModel),diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.tsindex 46e02165c7..67e0c2a272 100644--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts@@ -1085,3 +1085,17 @@ describe("Windows .cmd spawn shim", () => {expect(queryMock.mock.calls[0][0].options.spawnClaudeCodeProcess).toBeUndefined();});});++describe("ClaudeAgentProvider.recommendedModelIds", () => {+ it("applies Anthropic's per-family newest-version rule, not the generic default", () => {+ // The subscription catalog shares Anthropic's id shape, so it recommends+ // one model per family rather than every non-preview, non-legacy model.+ const ids = new ClaudeAgentProvider().recommendedModelIds(+ ["claude-fable-5", "claude-opus-4-8", "claude-opus-4-7", "claude-sonnet-5", "claude-haiku-4-5-20251001"]+ .map(id => ({ id, name: id }))+ );+ expect([...ids].sort()).toEqual([+ "claude-fable-5", "claude-haiku-4-5-20251001", "claude-opus-4-8", "claude-sonnet-5"+ ]);+ });+});diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.tsindex e0b663c4f6..e8a7987c2b 100644--- a/apps/server/src/services/llm/providers/claude_agent.ts+++ b/apps/server/src/services/llm/providers/claude_agent.ts@@ -33,10 +33,10 @@ import path from "path";import dataDirs from "../../data_dir.js";import { createMcpServer } from "../../mcp/mcp_server.js";import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";+import { anthropicRecommendedIds } from "./anthropic.js";import { resolveAttachmentPart } from "./attachment_content.js";-import { buildModelList } from "./base_provider.js";+import { buildModelList, mergeModelLists, type RemoteModel } from "./base_provider.js";import { resolveClaudeBinaryPath } from "./claude_binary.js";-import { mergeModelLists, type RemoteModel } from "./model_listing.js";import { buildNoteHint } from "./note_hint.js";import { buildSystemPrompt } from "./system_prompt.js";@@ -189,6 +189,15 @@ export class ClaudeAgentProvider implements LlmProvider {return AVAILABLE_MODELS;}+ /**+ * The subscription catalog shares Anthropic's `claude-*` id shape, so it+ * reuses the metered provider's per-family newest-version rule rather than+ * the generic non-preview/non-legacy default.+ */+ recommendedModelIds(models: ModelInfo[]): Set<string> {+ return anthropicRecommendedIds(models);+ }+/*** Dynamically list the models Claude Code actually offers on this host,* enriched with curated metadata. Unlike the API providers there is nodiff --git a/apps/server/src/services/llm/providers/google.spec.ts b/apps/server/src/services/llm/providers/google.spec.tsindex 83030ce234..2958d5c61c 100644--- a/apps/server/src/services/llm/providers/google.spec.ts+++ b/apps/server/src/services/llm/providers/google.spec.ts@@ -22,7 +22,7 @@ vi.mock("ai", async (importOriginal) => {return { ...actual, streamText: streamTextMock };});-import { GoogleProvider } from "./google.js";+import { GoogleProvider, isGoogleChatModel } from "./google.js";describe("GoogleProvider construction", () => {beforeEach(() => {@@ -218,3 +218,60 @@ describe("GoogleProvider model listing", () => {await expect(provider.listModels()).rejects.toThrow(/Unexpected \/models response shape/);});});++describe("isGoogleChatModel", () => {+ it("keeps Gemini chat models, including unknown future ones", () => {+ for (const id of [+ "gemini-2.5-pro",+ "gemini-2.5-flash",+ "gemini-2.5-flash-lite",+ "gemini-3-flash-preview",+ "gemini-3.1-pro-preview",+ "gemini-3.5-flash",+ "gemini-3.6-flash",+ "gemini-2.0-flash-exp"+ ]) {+ expect(isGoogleChatModel(id), id).toBe(true);+ }+ });++ it("drops non-Gemini families wholesale", () => {+ for (const id of [+ "text-embedding-004",+ "aqa",+ "imagen-3.0-generate-002",+ "veo-3.1-generate-preview",+ "lyria-3-pro-preview",+ "gemma-4-26b-a4b-it",+ "deep-research-preview-04-2026",+ "antigravity-preview-05-2026",+ "learnlm-2.0-flash-experimental"+ ]) {+ expect(isGoogleChatModel(id), id).toBe(false);+ }+ });++ it("drops non-conversational gemini-* variants (media, robotics, computer use)", () => {+ for (const id of [+ "gemini-embedding-001",+ "gemini-2.5-flash-image", // Nano Banana+ "gemini-3-pro-image", // Nano Banana Pro+ "gemini-3.1-flash-lite-image", // Nano Banana 2 Lite+ "gemini-2.5-flash-preview-tts",+ "gemini-3.1-flash-live-preview",+ "gemini-2.5-flash-native-audio-preview-12-2025",+ "gemini-omni-flash",+ "gemini-robotics-er-1.6-preview",+ "gemini-2.5-computer-use-preview-10-2025",+ "gemini-3.1-pro-preview-customtools" // real id — no hyphen in "customtools"+ ]) {+ expect(isGoogleChatModel(id), id).toBe(false);+ }+ });++ it("drops rolling aliases and pinned revisions that duplicate stable ids", () => {+ for (const id of ["gemini-flash-latest", "gemini-pro-latest", "gemini-flash-lite-latest", "gemini-2.0-flash-lite-001"]) {+ expect(isGoogleChatModel(id), id).toBe(false);+ }+ });+});diff --git a/apps/server/src/services/llm/providers/google.ts b/apps/server/src/services/llm/providers/google.tsindex 708c23d2cc..d7359d3c4e 100644--- a/apps/server/src/services/llm/providers/google.ts+++ b/apps/server/src/services/llm/providers/google.ts@@ -4,8 +4,7 @@ import { getLog } from "@triliumnext/core";import { stepCountIs, streamText, type ToolSet } from "ai";import type { LlmProviderConfig, StreamResult } from "../types.js";-import { BaseProvider } from "./base_provider.js";-import { isGoogleChatModel, type RemoteModel } from "./model_listing.js";+import { BaseProvider, type RemoteModel } from "./base_provider.js";const OFFICIAL_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";@@ -124,3 +123,26 @@ export class GoogleProvider extends BaseProvider {return streamText(streamOptions);}}++/**+ * Chat-model filter for the Gemini API. The endpoint's `supportedGenerationMethods`+ * is not enough: image (Nano Banana), robotics, computer-use, and speech models+ * all advertise `generateContent` too. Filter by id shape instead:+ *+ * - Only `gemini-*` ids are chat candidates — this drops the non-Gemini+ * families wholesale (`lyria-*` music, `veo-*` video, `imagen-*`, `gemma-*`+ * open models, `deep-research-*`, `antigravity-*` agents, embeddings, AQA).+ * - Within `gemini-*`, drop non-conversational variants by token: image+ * generation, speech (tts/live/native-audio), video (omni), robotics,+ * computer use, embeddings, and tool-variant builds (custom-tools).+ * - Drop `-latest` rolling aliases and `-NNN` pinned revisions — both are+ * duplicates of a stable id that is also in the list.+ */+const GOOGLE_NON_CHAT = /image|tts|live|audio|dialog|robotics|computer-use|embedding|omni|custom-?tools/i;++export function isGoogleChatModel(id: string): boolean {+ return /^gemini-/.test(id)+ && !GOOGLE_NON_CHAT.test(id)+ && !/-latest$/.test(id)+ && !/-\d{3}$/.test(id);+}diff --git a/apps/server/src/services/llm/providers/model_listing.spec.ts b/apps/server/src/services/llm/providers/model_listing.spec.tsdeleted file mode 100644index 304ce4e140..0000000000--- a/apps/server/src/services/llm/providers/model_listing.spec.ts+++ /dev/null@@ -1,269 +0,0 @@-import { describe, expect, it } from "vitest";--import type { ModelInfo } from "../types.js";-import { isGoogleChatModel, isOpenAiChatModel, mergeModelLists, openAiModelName, recommendedModelIds } from "./model_listing.js";--const CURATED: ModelInfo[] = [- { id: "gpt-4.1", name: "GPT-4.1", pricing: { input: 2, output: 8 }, contextWindow: 1047576, isDefault: true },- { id: "gpt-4.1-mini", name: "GPT-4.1 Mini", pricing: { input: 0.4, output: 1.6 }, contextWindow: 1047576 },- { id: "gpt-4o", name: "GPT-4o", pricing: { input: 2.5, output: 10 }, contextWindow: 128000, isLegacy: true }-];--describe("mergeModelLists", () => {- it("keeps base metadata for known models and appends unknown ones alphabetically", () => {- const merged = mergeModelLists(CURATED, [- { id: "gpt-9" },- { id: "gpt-4.1-mini" },- { id: "gpt-5" },- { id: "gpt-4.1" }- ]);- expect(merged.map(m => m.id)).toEqual(["gpt-4.1", "gpt-4.1-mini", "gpt-5", "gpt-9"]);- // Base entries keep their pricing/default metadata...- expect(merged[0]).toMatchObject({ name: "GPT-4.1", pricing: { input: 2, output: 8 }, isDefault: true });- // ...unknown ones carry no pricing.- expect(merged[2]).toEqual({ id: "gpt-5", name: "gpt-5", contextWindow: undefined });- });-- it("prefers the endpoint's display name over the base list's for known models", () => {- const merged = mergeModelLists(- [{ id: "gpt-4.1", name: "gpt-4.1", pricing: { input: 2, output: 8 } }],- [{ id: "gpt-4.1", name: "GPT-4.1 (from endpoint)" }]- );- expect(merged[0].name).toBe("GPT-4.1 (from endpoint)");- });-- it("drops curated models absent from the remote list", () => {- const merged = mergeModelLists(CURATED, [{ id: "gpt-4.1" }]);- expect(merged.map(m => m.id)).toEqual(["gpt-4.1"]);- });-- it("uses the remote display name and context window when provided", () => {- const merged = mergeModelLists([], [{ id: "llama3.2", name: "Llama 3.2", contextWindow: 131072 }]);- expect(merged[0]).toMatchObject({ id: "llama3.2", name: "Llama 3.2", contextWindow: 131072, isDefault: true });- });-- it("fills a curated model's missing context window from the remote data", () => {- const curated: ModelInfo[] = [{ id: "m", name: "M", pricing: { input: 1, output: 1 } }];- const merged = mergeModelLists(curated, [{ id: "m", contextWindow: 32000 }]);- expect(merged[0].contextWindow).toBe(32000);- });-- it("promotes the first model to default when the curated default is unavailable", () => {- const merged = mergeModelLists(CURATED, [{ id: "gpt-4o" }, { id: "custom-model" }]);- expect(merged.map(m => [m.id, m.isDefault ?? false])).toEqual([- ["gpt-4o", true],- ["custom-model", false]- ]);- });-- it("returns an empty list when the remote list shares nothing and is empty", () => {- expect(mergeModelLists(CURATED, [])).toEqual([]);- });-});--describe("isOpenAiChatModel", () => {- it("keeps chat model families, including unknown future ones", () => {- for (const id of ["gpt-4.1", "gpt-5", "gpt-5.6-sol", "o3", "o4-mini", "chatgpt-4o-latest"]) {- expect(isOpenAiChatModel(id), id).toBe(true);- }- });-- it("drops non-chat families", () => {- for (const id of [- "text-embedding-3-large",- "whisper-1",- "tts-1-hd",- "dall-e-3",- "omni-moderation-latest",- "gpt-4o-realtime-preview",- "gpt-4o-audio-preview",- "gpt-4o-transcribe",- "gpt-image-1",- "sora-2",- "computer-use-preview",- "codex-mini-latest",- "gpt-3.5-turbo-instruct",- "o3-deep-research",- "babbage-002",- "davinci-002",- "gpt-4o-search-preview",- "chat-latest" // bare rolling alias, dropped; versioned gpt-*-chat-latest are kept- ]) {- expect(isOpenAiChatModel(id), id).toBe(false);- }- });-- it("drops pinned snapshots that duplicate a rolling base id", () => {- for (const id of [- "gpt-4o-2024-05-13",- "gpt-5-2025-08-07",- "gpt-4.1-mini-2025-04-14",- "gpt-4-turbo-2024-04-09",- "o3-2025-04-16",- "o4-mini-2025-04-16",- "gpt-3.5-turbo-0125",- "gpt-3.5-turbo-1106",- "gpt-4-0613"- ]) {- expect(isOpenAiChatModel(id), id).toBe(false);- }- // ...but the rolling base ids and non-snapshot suffixes survive.- for (const id of ["gpt-4o", "gpt-5", "gpt-4.1-mini", "gpt-3.5-turbo-16k", "gpt-5-chat-latest"]) {- expect(isOpenAiChatModel(id), id).toBe(true);- }- });-});--describe("openAiModelName", () => {- it("prettifies gpt-* ids into friendly names", () => {- expect(openAiModelName("gpt-4.1")).toBe("GPT-4.1");- expect(openAiModelName("gpt-4.1-mini")).toBe("GPT-4.1 Mini");- expect(openAiModelName("gpt-4o")).toBe("GPT-4o");- expect(openAiModelName("gpt-4o-mini")).toBe("GPT-4o Mini");- expect(openAiModelName("gpt-5.6-sol")).toBe("GPT-5.6 Sol");- expect(openAiModelName("gpt-3.5-turbo")).toBe("GPT-3.5 Turbo");- expect(openAiModelName("gpt-5-chat-latest")).toBe("GPT-5 Chat Latest");- });-- it("leaves the o-series in OpenAI's canonical lowercase-hyphenated form", () => {- // Kept distinct from "GPT-4o Mini"; only the GPT family is reshaped.- expect(openAiModelName("o1")).toBe("o1");- expect(openAiModelName("o3")).toBe("o3");- expect(openAiModelName("o3-mini")).toBe("o3-mini");- expect(openAiModelName("o4-mini")).toBe("o4-mini");- expect(openAiModelName("o1-pro")).toBe("o1-pro");- });-- it("leaves non-OpenAI ids untouched", () => {- expect(openAiModelName("llama3.2")).toBe("llama3.2"); // self-hosted endpoint- expect(openAiModelName("chatgpt-4o-latest")).toBe("chatgpt-4o-latest");- });-});--describe("isGoogleChatModel", () => {- it("keeps Gemini chat models, including unknown future ones", () => {- for (const id of [- "gemini-2.5-pro",- "gemini-2.5-flash",- "gemini-2.5-flash-lite",- "gemini-3-flash-preview",- "gemini-3.1-pro-preview",- "gemini-3.5-flash",- "gemini-3.6-flash",- "gemini-2.0-flash-exp"- ]) {- expect(isGoogleChatModel(id), id).toBe(true);- }- });-- it("drops non-Gemini families wholesale", () => {- for (const id of [- "text-embedding-004",- "aqa",- "imagen-3.0-generate-002",- "veo-3.1-generate-preview",- "lyria-3-pro-preview",- "gemma-4-26b-a4b-it",- "deep-research-preview-04-2026",- "antigravity-preview-05-2026",- "learnlm-2.0-flash-experimental"- ]) {- expect(isGoogleChatModel(id), id).toBe(false);- }- });-- it("drops non-conversational gemini-* variants (media, robotics, computer use)", () => {- for (const id of [- "gemini-embedding-001",- "gemini-2.5-flash-image", // Nano Banana- "gemini-3-pro-image", // Nano Banana Pro- "gemini-3.1-flash-lite-image", // Nano Banana 2 Lite- "gemini-2.5-flash-preview-tts",- "gemini-3.1-flash-live-preview",- "gemini-2.5-flash-native-audio-preview-12-2025",- "gemini-omni-flash",- "gemini-robotics-er-1.6-preview",- "gemini-2.5-computer-use-preview-10-2025",- "gemini-3.1-pro-preview-customtools" // real id — no hyphen in "customtools"- ]) {- expect(isGoogleChatModel(id), id).toBe(false);- }- });-- it("drops rolling aliases and pinned revisions that duplicate stable ids", () => {- for (const id of ["gemini-flash-latest", "gemini-pro-latest", "gemini-flash-lite-latest", "gemini-2.0-flash-lite-001"]) {- expect(isGoogleChatModel(id), id).toBe(false);- }- });-});--describe("recommendedModelIds", () => {- // A representative slice of a live OpenAI /models response.- const OPENAI = [- "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", "gpt-4o", "gpt-4", "gpt-3.5-turbo",- "gpt-5", "gpt-5-mini", "gpt-5-chat-latest", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro",- "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna",- "o1", "o1-pro", "o3", "o3-mini", "o4-mini"- ].map(id => ({ id }));-- it("recommends only the newest generation of each OpenAI line, core tiers only", () => {- const ids = recommendedModelIds(OPENAI, "openai");- // Newest GPT generation (5.6) + newest o-series (o4) — nothing older.- expect([...ids].sort()).toEqual(["gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "o4-mini"]);- });-- it("excludes -pro and -chat-latest even within the newest generation", () => {- const ids = recommendedModelIds([- { id: "gpt-9-sol" }, { id: "gpt-9-pro" }, { id: "gpt-9-chat-latest" }- ], "openai");- expect([...ids]).toEqual(["gpt-9-sol"]);- });-- it("degrades to the newest available generation for an older-only endpoint", () => {- const ids = recommendedModelIds([{ id: "gpt-4" }, { id: "gpt-4.1" }, { id: "gpt-4o" }], "openai");- expect([...ids]).toEqual(["gpt-4.1"]); // 4.1 > 4o (4.0) > 4- });-- it("recommends nothing for an OpenAI-compatible endpoint with no gpt/o models", () => {- expect(recommendedModelIds([{ id: "llama3.2" }, { id: "qwen2.5" }], "openai").size).toBe(0);- });-- it("recommends the newest version of each Claude family for Anthropic", () => {- const ids = recommendedModelIds([- "claude-fable-5",- "claude-opus-4-8", "claude-opus-4-7", "claude-opus-4-6", "claude-opus-4-20250514",- "claude-sonnet-5", "claude-sonnet-4-6", "claude-sonnet-4-20250514",- "claude-haiku-4-5-20251001"- ].map(id => ({ id })), "anthropic");- // One per family, newest each — Fable 5, Opus 4.8, Sonnet 5, Haiku 4.5.- expect([...ids].sort()).toEqual([- "claude-fable-5", "claude-haiku-4-5-20251001", "claude-opus-4-8", "claude-sonnet-5"- ]);- });-- it("uses the same per-family newest-version rule for the Claude Code subscription provider", () => {- // The claude-agent provider shares Anthropic's id shape, so it recommends- // one model per family — not the generic non-legacy default.- const ids = recommendedModelIds([- "claude-fable-5", "claude-opus-4-8", "claude-opus-4-7", "claude-sonnet-5", "claude-haiku-4-5-20251001"- ].map(id => ({ id })), "claude-agent");- expect([...ids].sort()).toEqual([- "claude-fable-5", "claude-haiku-4-5-20251001", "claude-opus-4-8", "claude-sonnet-5"- ]);- });-- it("treats an Anthropic snapshot date as the version, not a minor bump", () => {- // sonnet-4-20250514 is 4.0, so sonnet-4-6 (4.6) must outrank it.- const ids = recommendedModelIds([{ id: "claude-sonnet-4-20250514" }, { id: "claude-sonnet-4-6" }], "anthropic");- expect([...ids]).toEqual(["claude-sonnet-4-6"]);- });-- it("falls back to non-preview, non-legacy models for other providers", () => {- const ids = recommendedModelIds([- { id: "gemini-2.5-flash" },- { id: "gemini-3-flash-preview" },- { id: "gemini-2.0-flash", isLegacy: true }- ], "google");- expect([...ids]).toEqual(["gemini-2.5-flash"]);- });-});diff --git a/apps/server/src/services/llm/providers/model_listing.ts b/apps/server/src/services/llm/providers/model_listing.tsdeleted file mode 100644index 37e82899d9..0000000000--- a/apps/server/src/services/llm/providers/model_listing.ts+++ /dev/null@@ -1,269 +0,0 @@-/**- * Pure logic for dynamic model listing: merging a live-fetched model list with- * the curated (hard-coded) metadata, and filtering provider noise. Kept free of- * I/O so it can be unit-tested in isolation — the fetching itself lives in the- * individual providers.- */--import type { ModelInfo } from "../types.js";--/**- * A model as reported by a provider's models endpoint. Only what the listing- * APIs actually return — pricing is never part of it.- */-export interface RemoteModel {- id: string;- /** Human-readable name, when the API provides one (e.g. Anthropic's `display_name`). */- name?: string;- /** Context window in tokens, when the API provides one (e.g. Google's `inputTokenLimit`). */- contextWindow?: number;-}--/**- * Per-model pricing/metadata, sourced from the committed `model_prices.json`- * (pruned from LiteLLM — see `scripts/update-model-prices.ts`). This is the- * single source of truth for cost/context data now that the hand-curated- * per-provider model arrays are gone; the endpoint (dynamic listing) remains the- * source of truth for which models exist and their display names.- */-export interface ModelPrice {- /** USD per million input tokens. */- input: number;- /** USD per million output tokens. */- output: number;- /** Context window in tokens, when known. */- ctx?: number;-}--/** One provider's pricing, keyed by model id. */-export type ProviderPrices = Record<string, ModelPrice>;--/** The whole committed price table: provider name → model id → pricing. */-export type ModelPriceTable = Record<string, ProviderPrices>;--/**- * Merge a live-fetched model list with a base metadata list (the provider's- * price-table slice, see {@link BaseProvider.getAvailableModels}).- *- * The remote list is the source of truth for *availability* and *display name*:- * base entries absent from it are dropped, remote models unknown to the base- * list are included with whatever metadata the endpoint reported (no pricing).- * The base list supplies pricing and context window (and, offline, a fallback- * name) for the models it knows; the endpoint's display name always wins when- * present.- *- * Ordering: base-known models first (in base order), then unknown remote models- * alphabetically. An existing default keeps its flag; otherwise the first merged- * model becomes the default so callers relying on `find(m => m.isDefault)` keep- * working.- */-export function mergeModelLists(curated: ModelInfo[], remote: RemoteModel[]): ModelInfo[] {- const remoteById = new Map(remote.map(m => [m.id, m]));-- const known = curated- .filter(m => remoteById.has(m.id))- .map(m => {- const remoteModel = remoteById.get(m.id);- return {- ...m,- // The endpoint is authoritative for display names (e.g. Anthropic's- // `display_name`); the base name is only an offline fallback.- name: remoteModel?.name ?? m.name,- contextWindow: m.contextWindow ?? remoteModel?.contextWindow- };- });-- const curatedIds = new Set(curated.map(m => m.id));- const unknown = remote- .filter(m => !curatedIds.has(m.id))- .sort((a, b) => a.id.localeCompare(b.id))- .map<ModelInfo>(m => ({- id: m.id,- name: m.name ?? m.id,- contextWindow: m.contextWindow- }));-- const merged = [...known, ...unknown];- if (merged.length > 0 && !merged.some(m => m.isDefault)) {- merged[0] = { ...merged[0], isDefault: true };- }- return merged;-}--/**- * Model-id families returned by the official OpenAI `/models` endpoint that are- * not chat models (embeddings, audio/speech, image, video, moderation,- * computer-use, coding agents, legacy completions). Only applied on the- * official endpoint — custom base URLs (Ollama, vLLM, LiteLLM, LM Studio) list- * exactly what the user installed, so nothing is filtered there.- */-const OPENAI_NON_CHAT = /embedding|whisper|tts|dall-e|moderation|realtime|audio|transcribe|image|sora|computer-use|codex|instruct|deep-research|babbage|davinci|search/i;--/**- * Pinned-snapshot suffixes that duplicate a rolling base id — `-2024-05-13`- * (dated) and `-0125` / `-1106` (legacy MMDD). Dropped so the list shows- * `gpt-4o`, not `gpt-4o` plus five of its dated revisions.- */-const OPENAI_SNAPSHOT = /-\d{4}(-\d{2}-\d{2})?$/;--export function isOpenAiChatModel(id: string): boolean {- // `chat-latest` is a bare rolling alias (current ChatGPT Instant model) —- // redundant with the versioned `gpt-*-chat-latest` handles and uninformative- // on its own, so it's dropped.- return id !== "chat-latest" && !OPENAI_NON_CHAT.test(id) && !OPENAI_SNAPSHOT.test(id);-}--/**- * Friendly display name for an OpenAI model id, since the `/models` endpoint- * returns none. Only the GPT family is reshaped — `gpt-4.1-mini` →- * "GPT-4.1 Mini", `gpt-5.6-sol` → "GPT-5.6 Sol". The o-series keeps OpenAI's- * canonical lowercase-hyphenated form (`o4-mini`, `o1-pro`), which is both its- * proper style and what keeps it visually distinct from "GPT-4o Mini".- * Non-OpenAI ids (self-hosted `llama3.2`) are left untouched.- */-export function openAiModelName(id: string): string {- const gptMatch = /^gpt-([^-]+)(?:-(.+))?$/.exec(id);- if (!gptMatch) {- return id;- }- const [, version, suffix] = gptMatch;- const suffixName = suffix- ? ` ${suffix.split("-").map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(" ")}`- : "";- return `GPT-${version}${suffixName}`;-}--/**- * Chat-model filter for the Gemini API. The endpoint's `supportedGenerationMethods`- * is not enough: image (Nano Banana), robotics, computer-use, and speech models- * all advertise `generateContent` too. Filter by id shape instead:- *- * - Only `gemini-*` ids are chat candidates — this drops the non-Gemini- * families wholesale (`lyria-*` music, `veo-*` video, `imagen-*`, `gemma-*`- * open models, `deep-research-*`, `antigravity-*` agents, embeddings, AQA).- * - Within `gemini-*`, drop non-conversational variants by token: image- * generation, speech (tts/live/native-audio), video (omni), robotics,- * computer use, embeddings, and tool-variant builds (custom-tools).- * - Drop `-latest` rolling aliases and `-NNN` pinned revisions — both are- * duplicates of a stable id that is also in the list.- */-const GOOGLE_NON_CHAT = /image|tts|live|audio|dialog|robotics|computer-use|embedding|omni|custom-?tools/i;--export function isGoogleChatModel(id: string): boolean {- return /^gemini-/.test(id)- && !GOOGLE_NON_CHAT.test(id)- && !/-latest$/.test(id)- && !/-\d{3}$/.test(id);-}--/**- * The ids pre-selected by default when adding/resetting a provider. Derived- * purely from the model ids the endpoint returns — no curated list, no- * hardcoded model names.- *- * For OpenAI the recency signal is the version number, across two parallel- * lines (the GPT line `gpt-<version>` and the reasoning o-series `o<n>`): we- * recommend only the newest generation of each line, core tiers only — so- * today's `gpt-5.6-{sol,terra,luna}` and `o4-mini`, not the dozens of older- * gpt-4 through 5.5 and o1/o3 models (which stay in the picker, unchecked).- * When gpt-5.7 / o5 ship they win automatically.- *- * For Anthropic — both the metered API (`anthropic`) and the Claude Code- * subscription (`claude-agent`), which share the same `claude-*` id shape — we- * recommend the newest version within each Claude family (Opus, Sonnet, Haiku,- * Fable, and any future one) — one model per family, so today's Opus 4.8,- * Sonnet 5, Haiku 4.5 and Fable 5. Older revisions and dated snapshots stay in- * the picker, unchecked.- *- * Other providers fall back to "everything that isn't a preview or legacy".- */-export function recommendedModelIds(models: RecommendCandidate[], provider: string): Set<string> {- if (provider === "openai") {- return openAiRecommendedIds(models);- }- if (provider === "anthropic" || provider === "claude-agent") {- return anthropicRecommendedIds(models);- }- return new Set(models.filter(m => !m.isLegacy && !/preview/i.test(m.id)).map(m => m.id));-}--interface RecommendCandidate {- id: string;- isLegacy?: boolean;-}--/** Newest generation of each OpenAI line (GPT + o-series), excluding -pro/-chat-latest variants. */-function openAiRecommendedIds(models: RecommendCandidate[]): Set<string> {- // Premium (`-pro`) and rolling-alias (`-chat-latest`) variants are never a- // default; drop them before picking the newest generation.- const core = models.filter(m => !/-pro$/.test(m.id) && !/-chat-latest$/.test(m.id));- return new Set([- ...newestOfLine(core, /^gpt-/, gptVersion),- ...newestOfLine(core, /^o\d/, oSeriesVersion)- ]);-}--/** Ids in `models` matching `line` whose parsed version equals the line's maximum. */-function newestOfLine(models: RecommendCandidate[], line: RegExp, version: (id: string) => number): string[] {- const family = models.filter(m => line.test(m.id));- if (family.length === 0) {- return [];- }- const max = Math.max(...family.map(m => version(m.id)));- return family.filter(m => version(m.id) === max).map(m => m.id);-}--/** `gpt-5.6-sol` → 5.6, `gpt-4.1` → 4.1, `gpt-4o` → 4. */-function gptVersion(id: string): number {- const match = /^gpt-(\d+(?:\.\d+)?)/.exec(id);- return match ? parseFloat(match[1]) : 0;-}--/** `o4-mini` → 4, `o3` → 3. */-function oSeriesVersion(id: string): number {- const match = /^o(\d+)/.exec(id);- return match ? parseInt(match[1], 10) : 0;-}--/**- * Anthropic model id shape: `claude-<family>-<major>[-<minor>][-<YYYYMMDD>]`.- * The optional trailing 8-digit snapshot date is not part of the version —- * `claude-sonnet-4-20250514` is Sonnet 4.0, not 4.20250514 — so the minor- * group is capped at two digits to force the date into the snapshot group.- */-const ANTHROPIC_MODEL = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?$/;--/** Newest version within each Claude family (opus/sonnet/haiku/fable, and any future one) — one id per family. */-function anthropicRecommendedIds(models: RecommendCandidate[]): Set<string> {- const byFamily = new Map<string, RecommendCandidate[]>();- for (const model of models) {- const family = anthropicFamily(model.id);- if (!family) {- continue;- }- const members = byFamily.get(family) ?? [];- members.push(model);- byFamily.set(family, members);- }- const recommended = new Set<string>();- for (const members of byFamily.values()) {- const newest = members.reduce((best, m) => (anthropicVersion(m.id) > anthropicVersion(best.id) ? m : best));- recommended.add(newest.id);- }- return recommended;-}--/** `claude-opus-4-8` → "opus"; null for ids that aren't `claude-<family>-<version>`. */-function anthropicFamily(id: string): string | null {- return ANTHROPIC_MODEL.exec(id)?.[1] ?? null;-}--/** `claude-opus-4-8` → 4.8, `claude-sonnet-5` → 5, `claude-sonnet-4-20250514` → 4 (the trailing date is not a minor). */-function anthropicVersion(id: string): number {- const match = ANTHROPIC_MODEL.exec(id);- if (!match) {- return 0;- }- const [, , major, minor] = match;- return parseFloat(minor ? `${major}.${minor}` : major);-}diff --git a/apps/server/src/services/llm/providers/openai.spec.ts b/apps/server/src/services/llm/providers/openai.spec.tsindex 9b79d64978..8cda1b9c4c 100644--- a/apps/server/src/services/llm/providers/openai.spec.ts+++ b/apps/server/src/services/llm/providers/openai.spec.ts@@ -22,7 +22,7 @@ vi.mock("ai", async (importOriginal) => {return { ...actual, streamText: streamTextMock };});-import { OpenAiProvider } from "./openai.js";+import { isOpenAiChatModel, openAiModelName, OpenAiProvider } from "./openai.js";describe("OpenAiProvider construction", () => {beforeEach(() => {@@ -148,3 +148,111 @@ describe("OpenAiProvider model listing", () => {await expect(provider.listModels()).rejects.toThrow(/Unexpected .* response shape/);});});++describe("isOpenAiChatModel", () => {+ it("keeps chat model families, including unknown future ones", () => {+ for (const id of ["gpt-4.1", "gpt-5", "gpt-5.6-sol", "o3", "o4-mini", "chatgpt-4o-latest"]) {+ expect(isOpenAiChatModel(id), id).toBe(true);+ }+ });++ it("drops non-chat families", () => {+ for (const id of [+ "text-embedding-3-large",+ "whisper-1",+ "tts-1-hd",+ "dall-e-3",+ "omni-moderation-latest",+ "gpt-4o-realtime-preview",+ "gpt-4o-audio-preview",+ "gpt-4o-transcribe",+ "gpt-image-1",+ "sora-2",+ "computer-use-preview",+ "codex-mini-latest",+ "gpt-3.5-turbo-instruct",+ "o3-deep-research",+ "babbage-002",+ "davinci-002",+ "gpt-4o-search-preview",+ "chat-latest" // bare rolling alias, dropped; versioned gpt-*-chat-latest are kept+ ]) {+ expect(isOpenAiChatModel(id), id).toBe(false);+ }+ });++ it("drops pinned snapshots that duplicate a rolling base id", () => {+ for (const id of [+ "gpt-4o-2024-05-13",+ "gpt-5-2025-08-07",+ "gpt-4.1-mini-2025-04-14",+ "gpt-4-turbo-2024-04-09",+ "o3-2025-04-16",+ "o4-mini-2025-04-16",+ "gpt-3.5-turbo-0125",+ "gpt-3.5-turbo-1106",+ "gpt-4-0613"+ ]) {+ expect(isOpenAiChatModel(id), id).toBe(false);+ }+ // ...but the rolling base ids and non-snapshot suffixes survive.+ for (const id of ["gpt-4o", "gpt-5", "gpt-4.1-mini", "gpt-3.5-turbo-16k", "gpt-5-chat-latest"]) {+ expect(isOpenAiChatModel(id), id).toBe(true);+ }+ });+});++describe("openAiModelName", () => {+ it("prettifies gpt-* ids into friendly names", () => {+ expect(openAiModelName("gpt-4.1")).toBe("GPT-4.1");+ expect(openAiModelName("gpt-4.1-mini")).toBe("GPT-4.1 Mini");+ expect(openAiModelName("gpt-4o")).toBe("GPT-4o");+ expect(openAiModelName("gpt-4o-mini")).toBe("GPT-4o Mini");+ expect(openAiModelName("gpt-5.6-sol")).toBe("GPT-5.6 Sol");+ expect(openAiModelName("gpt-3.5-turbo")).toBe("GPT-3.5 Turbo");+ expect(openAiModelName("gpt-5-chat-latest")).toBe("GPT-5 Chat Latest");+ });++ it("leaves the o-series in OpenAI's canonical lowercase-hyphenated form", () => {+ // Kept distinct from "GPT-4o Mini"; only the GPT family is reshaped.+ expect(openAiModelName("o1")).toBe("o1");+ expect(openAiModelName("o3")).toBe("o3");+ expect(openAiModelName("o3-mini")).toBe("o3-mini");+ expect(openAiModelName("o4-mini")).toBe("o4-mini");+ expect(openAiModelName("o1-pro")).toBe("o1-pro");+ });++ it("leaves non-OpenAI ids untouched", () => {+ expect(openAiModelName("llama3.2")).toBe("llama3.2"); // self-hosted endpoint+ expect(openAiModelName("chatgpt-4o-latest")).toBe("chatgpt-4o-latest");+ });+});++describe("OpenAiProvider recommendedModelIds", () => {+ const recommend = (ids: string[]) =>+ new OpenAiProvider("sk-test").recommendedModelIds(ids.map(id => ({ id, name: id })));++ it("recommends only the newest generation of each OpenAI line, core tiers only", () => {+ // A representative slice of a live OpenAI /models response.+ const ids = recommend([+ "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", "gpt-4o", "gpt-4", "gpt-3.5-turbo",+ "gpt-5", "gpt-5-mini", "gpt-5-chat-latest", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro",+ "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna",+ "o1", "o1-pro", "o3", "o3-mini", "o4-mini"+ ]);+ // Newest GPT generation (5.6) + newest o-series (o4) — nothing older.+ expect([...ids].sort()).toEqual(["gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "o4-mini"]);+ });++ it("excludes -pro and -chat-latest even within the newest generation", () => {+ expect([...recommend(["gpt-9-sol", "gpt-9-pro", "gpt-9-chat-latest"])]).toEqual(["gpt-9-sol"]);+ });++ it("degrades to the newest available generation for an older-only endpoint", () => {+ expect([...recommend(["gpt-4", "gpt-4.1", "gpt-4o"])]).toEqual(["gpt-4.1"]); // 4.1 > 4o (4.0) > 4+ });++ it("recommends nothing for an OpenAI-compatible endpoint with no gpt/o models", () => {+ expect(recommend(["llama3.2", "qwen2.5"]).size).toBe(0);+ });+});diff --git a/apps/server/src/services/llm/providers/openai.ts b/apps/server/src/services/llm/providers/openai.tsindex e6968a771a..99b00ca1ba 100644--- a/apps/server/src/services/llm/providers/openai.ts+++ b/apps/server/src/services/llm/providers/openai.ts@@ -1,8 +1,8 @@import { createOpenAI, type OpenAIProvider as OpenAISDKProvider } from "@ai-sdk/openai";import type { ToolSet } from "ai";-import { BaseProvider } from "./base_provider.js";-import { isOpenAiChatModel, openAiModelName, type RemoteModel } from "./model_listing.js";+import type { ModelInfo } from "../types.js";+import { BaseProvider, type RemoteModel } from "./base_provider.js";const OFFICIAL_BASE_URL = "https://api.openai.com/v1";@@ -57,4 +57,89 @@ export class OpenAiProvider extends BaseProvider {protected override addWebSearchTool(tools: ToolSet): void {tools.web_search = this.openai.tools.webSearch();}++ /**+ * Recommend only the newest generation of each OpenAI line, core tiers only.+ *+ * The recency signal is the version number, across two parallel lines (the+ * GPT line `gpt-<version>` and the reasoning o-series `o<n>`) — so today's+ * `gpt-5.6-{sol,terra,luna}` and `o4-mini`, not the dozens of older gpt-4+ * through 5.5 and o1/o3 models (which stay in the picker, unchecked). When+ * gpt-5.7 / o5 ship they win automatically. A self-hosted endpoint serving+ * neither line recommends nothing.+ */+ override recommendedModelIds(models: ModelInfo[]): Set<string> {+ // Premium (`-pro`) and rolling-alias (`-chat-latest`) variants are never a+ // default; drop them before picking the newest generation.+ const core = models.filter(m => !/-pro$/.test(m.id) && !/-chat-latest$/.test(m.id));+ return new Set([+ ...newestOfLine(core, /^gpt-/, gptVersion),+ ...newestOfLine(core, /^o\d/, oSeriesVersion)+ ]);+ }+}++/**+ * Model-id families returned by the official OpenAI `/models` endpoint that are+ * not chat models (embeddings, audio/speech, image, video, moderation,+ * computer-use, coding agents, legacy completions). Only applied on the+ * official endpoint — custom base URLs (Ollama, vLLM, LiteLLM, LM Studio) list+ * exactly what the user installed, so nothing is filtered there.+ */+const OPENAI_NON_CHAT = /embedding|whisper|tts|dall-e|moderation|realtime|audio|transcribe|image|sora|computer-use|codex|instruct|deep-research|babbage|davinci|search/i;++/**+ * Pinned-snapshot suffixes that duplicate a rolling base id — `-2024-05-13`+ * (dated) and `-0125` / `-1106` (legacy MMDD). Dropped so the list shows+ * `gpt-4o`, not `gpt-4o` plus five of its dated revisions.+ */+const OPENAI_SNAPSHOT = /-\d{4}(-\d{2}-\d{2})?$/;++export function isOpenAiChatModel(id: string): boolean {+ // `chat-latest` is a bare rolling alias (current ChatGPT Instant model) —+ // redundant with the versioned `gpt-*-chat-latest` handles and uninformative+ // on its own, so it's dropped.+ return id !== "chat-latest" && !OPENAI_NON_CHAT.test(id) && !OPENAI_SNAPSHOT.test(id);+}++/**+ * Friendly display name for an OpenAI model id, since the `/models` endpoint+ * returns none. Only the GPT family is reshaped — `gpt-4.1-mini` →+ * "GPT-4.1 Mini", `gpt-5.6-sol` → "GPT-5.6 Sol". The o-series keeps OpenAI's+ * canonical lowercase-hyphenated form (`o4-mini`, `o1-pro`), which is both its+ * proper style and what keeps it visually distinct from "GPT-4o Mini".+ * Non-OpenAI ids (self-hosted `llama3.2`) are left untouched.+ */+export function openAiModelName(id: string): string {+ const gptMatch = /^gpt-([^-]+)(?:-(.+))?$/.exec(id);+ if (!gptMatch) {+ return id;+ }+ const [, version, suffix] = gptMatch;+ const suffixName = suffix+ ? ` ${suffix.split("-").map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(" ")}`+ : "";+ return `GPT-${version}${suffixName}`;+}++/** Ids in `models` matching `line` whose parsed version equals the line's maximum. */+function newestOfLine(models: ModelInfo[], line: RegExp, version: (id: string) => number): string[] {+ const family = models.filter(m => line.test(m.id));+ if (family.length === 0) {+ return [];+ }+ const max = Math.max(...family.map(m => version(m.id)));+ return family.filter(m => version(m.id) === max).map(m => m.id);+}++/** `gpt-5.6-sol` → 5.6, `gpt-4.1` → 4.1, `gpt-4o` → 4. */+function gptVersion(id: string): number {+ const match = /^gpt-(\d+(?:\.\d+)?)/.exec(id);+ return match ? parseFloat(match[1]) : 0;+}++/** `o4-mini` → 4, `o3` → 3. */+function oSeriesVersion(id: string): number {+ const match = /^o(\d+)/.exec(id);+ return match ? parseInt(match[1], 10) : 0;}diff --git a/apps/server/src/services/llm/types.ts b/apps/server/src/services/llm/types.tsindex 20ffdc9e75..308560e947 100644--- a/apps/server/src/services/llm/types.ts+++ b/apps/server/src/services/llm/types.ts@@ -111,6 +111,15 @@ export interface LlmProvider {*/listModels?(): Promise<ModelInfo[]>;+ /**+ * Of a listed model set, the ids pre-selected by default when the provider+ * is added or its selection reset. Lives on the provider because the rule is+ * provider-specific (OpenAI and Anthropic read a recency signal out of their+ * id shapes; everything else falls back to non-preview, non-legacy), and so+ * the model picker can stay rule-free and just honour the flag.+ */+ recommendedModelIds(models: ModelInfo[]): Set<string>;+/*** Generate a short title summarizing a message.* Used for auto-renaming chat notes. Should use a fast, cheap model.