Skip to content

Build your personal knowledge base with Trilium Notes

fix(llm): stop hand-maintaining Claude Code's models

Elian Doran8e9b3318804d
diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.ts
index a99da476c2..736fe5cb28 100644
--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts
@@ -38,6 +38,10 @@ vi.mock("../../port.js", () => ({ default: 8080 }));
const buildNoteHintMock = vi.hoisted(() => vi.fn((noteId: string): string | null => `NOTE_META(${noteId})`));
vi.mock("@triliumnext/core/src/services/llm/note_hint.js", () => ({ buildNoteHint: buildNoteHintMock }));
+// The stored selection names the models a chat can use; no provider is configured here.
+const getSelectedModelMock = vi.hoisted(() => vi.fn((_providerId: string | undefined, _modelId: string): { id: string; name: string } | undefined => undefined));
+vi.mock("@triliumnext/core/src/services/llm/index.js", () => ({ getSelectedModel: getSelectedModelMock }));
+
// BYO binary resolution shells out to the user's `claude`; stub it so tests
// don't depend on a real install. Resolves a path by default; can be made to
// reject (missing binary) per-test.
@@ -283,7 +287,7 @@ describe("ClaudeAgentProvider.chatChunks", () => {
type: "usage",
// No cost even though the SDK result carries total_cost_usd: usage is
// covered by the subscription, so a per-turn dollar figure isn't shown.
- usage: { promptTokens: 100, completionTokens: 40, totalTokens: 140, model: "Claude Sonnet 5.5", provider: "claude-agent" }
+ usage: { promptTokens: 100, completionTokens: 40, totalTokens: 140, provider: "claude-agent" }
},
{ type: "done" }
]);
@@ -291,20 +295,34 @@ describe("ClaudeAgentProvider.chatChunks", () => {
it("reports the friendly model name in usage, falling back to the raw ID for unknown models", async () => {
const provider = new ClaudeAgentProvider();
- const usageModel = async (config: { model?: string }) => {
+ const usageModel = async (config: { providerId?: string; model?: string }) => {
scriptAgent([successResult()]);
const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], config));
const usage = chunks.find(c => c.type === "usage");
return usage?.type === "usage" ? usage.usage.model : undefined;
};
+ getSelectedModelMock.mockImplementation((providerId, modelId) =>
+ providerId === "claude-1" && modelId === "claude-opus-4-8[1m]" ? { id: modelId, name: "Opus 4.8 (1M context)" } : undefined);
+
+ try {
+ // The stored selection names the model (the chat pane renders it verbatim).
+ expect(await usageModel({ providerId: "claude-1", model: "claude-opus-4-8[1m]" })).toBe("Opus 4.8 (1M context)");
+ // An ID no selection names passes through unchanged rather than becoming undefined.
+ expect(await usageModel({ providerId: "claude-1", model: "some-unknown-model" })).toBe("some-unknown-model");
+ } finally {
+ getSelectedModelMock.mockReset();
+ }
+ });
- // A known model ID is mapped to its display name (the chat pane renders it verbatim).
- expect(await usageModel({ model: "claude-fable-5" })).toBe("Claude Fable 5");
- // A long-context ID is named after the model it varies, rather than falling
- // through to the raw `claude-opus-4-8[1m]`.
- expect(await usageModel({ model: "claude-opus-4-8[1m]" })).toBe("Claude Opus 4.8 (1M)");
- // An unrecognized ID passes through unchanged rather than becoming undefined.
- expect(await usageModel({ model: "some-unknown-model" })).toBe("some-unknown-model"); });
+ it("leaves the model to Claude Code when the chat names none, or names the default", async () => {
+ const provider = new ClaudeAgentProvider();
+ for (const config of [{}, { model: "default" }]) {
+ queryMock.mockClear();
+ scriptAgent([successResult()]);
+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], config));
+ expect(queryMock.mock.calls[0][0].options.model).toBeUndefined();
+ }
+ });
it("ignores subagent traffic (non-null parent_tool_use_id)", async () => {
scriptAgent([
@@ -739,17 +757,14 @@ describe("ClaudeAgentProvider.chatChunks", () => {
expect(queryMock).not.toHaveBeenCalled();
});
- it("exposes the subscription model list, zero pricing, and no chat() implementation", () => {
+ it("exposes only Claude Code's default offline, zero pricing, and no chat() implementation", () => {
const provider = new ClaudeAgentProvider();
- const models = provider.getAvailableModels();
- expect(models.some(m => m.id === "claude-sonnet-5-5" && m.isDefault)).toBe(true);
- // The current line-up leads the list; what it replaced is still listed, as legacy.
- expect(models.filter(m => !m.isLegacy).map(m => m.id)).toEqual([
- "claude-fable-5-1", "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5"
+ expect(provider.getAvailableModels()).toEqual([
+ { id: "default", name: "Default", pricing: { input: 0, output: 0 }, isDefault: true, isSubscription: true }
]);
- expect(models.find(m => m.id === "claude-fable-5")).toMatchObject({ isLegacy: true });
- expect(provider.getModelPricing("claude-sonnet-5-5"))
- .toEqual(expect.objectContaining({ input: 0, output: 0 }));
+ // Any model the price table knows is free on the subscription, as is the default.
+ expect(provider.getModelPricing("claude-sonnet-5-5")).toEqual({ input: 0, output: 0 });
+ expect(provider.getModelPricing("default")).toEqual({ input: 0, output: 0 });
// A long-context variant prices like its base model, not as an unknown.
expect(provider.getModelPricing("claude-opus-4-8[1m]")).toEqual(expect.objectContaining({ input: 0, output: 0 }));
expect(provider.getModelPricing("no-such-model")).toBeUndefined();
@@ -1420,64 +1435,43 @@ describe("transcript helpers", () => {
});
describe("buildSubscriptionModelList", () => {
- const curated = [
- { id: "claude-sonnet-5", name: "Claude Sonnet 5", pricing: { input: 0, output: 0 }, contextWindow: 1000000, isDefault: true, isSubscription: true },
- { id: "claude-opus-4-6", name: "Claude Opus 4.6", pricing: { input: 0, output: 0 }, contextWindow: 1000000, isLegacy: true, isSubscription: true },
- { id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5", pricing: { input: 0, output: 0 }, contextWindow: 200000, isSubscription: true }
- ];
+ const prices = {
+ "claude-opus-5-5": { input: 5, output: 25, ctx: 1000000 },
+ "claude-sonnet-5": { input: 3, output: 15, ctx: 1000000 },
+ "claude-haiku-4-5-20251001": { input: 1, output: 5, ctx: 200000 }
+ };
- it("resolves aliases to canonical ids, dedupes, and keeps curated metadata", () => {
- const merged = buildSubscriptionModelList([
+ it("resolves aliases to canonical ids, dedupes, and takes the context window from the price table", () => {
+ const models = buildSubscriptionModelList([
{ value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet 5" },
{ value: "claude-sonnet-5", displayName: "Sonnet 5 (again)" }, // dup of the resolved alias → dropped
- { value: "claude-opus-4-6", displayName: "Opus 4.6" }
- ], curated);
-
- expect(merged.map(m => m.id)).toEqual(["claude-sonnet-5", "claude-opus-4-6"]);
- // The CLI's display name wins; curated flags/context window survive.
- expect(merged[0]).toMatchObject({ name: "Sonnet 5", isDefault: true, isSubscription: true, contextWindow: 1000000, pricing: { input: 0, output: 0 } });
- expect(merged[1]).toMatchObject({ id: "claude-opus-4-6", isLegacy: true });
- // Haiku is curated but absent from the live catalog → dropped.
- expect(merged.some(m => m.id === "claude-haiku-4-5-20251001")).toBe(false);
+ { value: "claude-haiku-4-5-20251001", displayName: "Haiku 4.5" },
+ { value: "claude-fable-9" }
+ ], prices);
+
+ // Claude Code's order and names; the subscription makes every row free, whatever the API costs.
+ expect(models).toEqual([
+ { id: "claude-sonnet-5", name: "Sonnet 5", contextWindow: 1000000, pricing: { input: 0, output: 0 }, isSubscription: true, isDefault: true },
+ { id: "claude-haiku-4-5-20251001", name: "Haiku 4.5", contextWindow: 200000, pricing: { input: 0, output: 0 }, isSubscription: true },
+ // A model the price table has never heard of keeps its id as its name and has no context window.
+ { id: "claude-fable-9", name: "claude-fable-9", contextWindow: undefined, pricing: { input: 0, output: 0 }, isSubscription: true }
+ ]);
});
- it("passes through unknown models with subscription invariants and no pricing/context window", () => {
- const merged = buildSubscriptionModelList([
+ it("flags the model the `default` alias resolves to, without listing the alias itself", () => {
+ const models = buildSubscriptionModelList([
+ { value: "default", resolvedModel: "claude-opus-5-5", displayName: "Default (recommended)" },
{ value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet 5" },
- { value: "claude-fable-9", displayName: "Claude Fable 9" }
- ], curated);
+ { value: "opus", resolvedModel: "claude-opus-5-5", displayName: "Opus 5.5" }
+ ], prices);
- const fable = merged.find(m => m.id === "claude-fable-9");
- expect(fable).toEqual({ id: "claude-fable-9", name: "Claude Fable 9", contextWindow: undefined, isSubscription: true, pricing: { input: 0, output: 0 } });
+ expect(models.map(m => m.name)).toEqual(["Sonnet 5", "Opus 5.5"]);
+ expect(models.filter(m => m.isDefault).map(m => m.id)).toEqual(["claude-opus-5-5"]);
});
- it("drops the `default` alias so the concrete row it shadows keeps its own name", () => {
- // Claude Code lists `default` first, resolving to the same id as `opus[1m]`.
- // Kept, it would win the dedupe and label the row "Default (recommended)".
- const merged = buildSubscriptionModelList([
- { value: "default", resolvedModel: "claude-opus-4-6[1m]", displayName: "Default (recommended)" },
- { value: "opus[1m]", resolvedModel: "claude-opus-4-6[1m]", displayName: "Opus" },
- { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet" }
- ], curated);
-
- expect(merged.map(m => m.name)).toEqual(["Sonnet", "Opus"]);
- expect(merged.some(m => m.id === "claude-opus-4-6")).toBe(false);
- });
-
- it("treats a long-context id as a variant of its base model, next to it and without its default flag", () => {
- const merged = buildSubscriptionModelList([
- { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet" },
- { value: "sonnet[1m]", resolvedModel: "claude-sonnet-5[1m]" },
- { value: "claude-opus-4-6[1m]", displayName: "Opus" }
- ], curated);
-
- // Curated ordering survives: each variant sits directly after its base.
- expect(merged.map(m => m.id)).toEqual(["claude-sonnet-5", "claude-sonnet-5[1m]", "claude-opus-4-6[1m]"]);
- // Curated metadata is inherited, and the CLI's silence leaves the derived name.
- expect(merged[1]).toMatchObject({ name: "Claude Sonnet 5 (1M)", contextWindow: 1000000, isSubscription: true, isDefault: false });
- // ...including flags the base carries — but never a second default.
- expect(merged[2]).toMatchObject({ name: "Opus", contextWindow: 1000000, isLegacy: true, isDefault: false });
- expect(merged.filter(m => m.isDefault)).toHaveLength(1);
+ it("gives a long-context id the context window of its base model when the table lacks the variant", () => {
+ const [variant] = buildSubscriptionModelList([{ value: "sonnet[1m]", resolvedModel: "claude-sonnet-5[1m]" }], prices);
+ expect(variant).toMatchObject({ id: "claude-sonnet-5[1m]", contextWindow: 1000000, isDefault: true });
});
});
@@ -1504,8 +1498,8 @@ describe("ClaudeAgentProvider.listModels", () => {
expect(models.map(m => m.id)).toEqual(["claude-sonnet-5", "claude-fable-9"]);
expect(models.every(m => m.isSubscription)).toBe(true);
- // Curated models the CLI didn't report are gone (unlike getAvailableModels).
- expect(models.some(m => m.id === "claude-haiku-4-5-20251001")).toBe(false);
+ // The committed price table supplies the context window.
+ expect(models[0].contextWindow).toBe(1000000);
// The probe uses a streaming prompt that yields nothing — never a string,
// so no user turn (and no tokens) is sent — capped at a single turn.
diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.ts
index c2edef9f0f..bc25edc49a 100644
--- a/apps/server/src/services/llm/providers/claude_agent.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.ts
@@ -25,9 +25,10 @@ import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";
import type { LlmMessage, LlmMessagePart, LlmStreamChunk } from "@triliumnext/commons";
import { getLog } from "@triliumnext/core";
import { attachmentPlaceholder, resolveAttachmentPart } from "@triliumnext/core/src/services/llm/attachment_content.js";
+import { getSelectedModel } from "@triliumnext/core/src/services/llm/index.js";
import { buildNoteHint } from "@triliumnext/core/src/services/llm/note_hint.js";
import { anthropicRecommendedIds } from "@triliumnext/core/src/services/llm/providers/anthropic.js";
-import { buildModelList, mergeModelLists, type RemoteModel } from "@triliumnext/core/src/services/llm/providers/base_provider.js";
+import { getProviderPrices, type ProviderPrices } from "@triliumnext/core/src/services/llm/providers/base_provider.js";
import { buildSystemPrompt } from "@triliumnext/core/src/services/llm/system_prompt.js";
import { TOOL_CALL_DECLINED_REASON, type ToolApprovals } from "@triliumnext/core/src/services/llm/tool_approval.js";
import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "@triliumnext/core/src/services/llm/types.js";
@@ -58,122 +59,20 @@ type SupportedImageMime = "image/png" | "image/jpeg" | "image/gif" | "image/webp
const SUPPORTED_IMAGE_MIMES = new Set<string>(["image/png", "image/jpeg", "image/gif", "image/webp"]);
/**
- * Curated Claude subscription models, mirroring Claude Code's own `/model`
- * picker (the Agent SDK accepts any of these). Pricing is zero because usage is
- * covered by the subscription — the per-turn `usage` chunk still reports the
- * API-equivalent cost as informational metadata from the agent's result.
- *
- * This is now the *metadata + fallback* list: {@link ClaudeAgentProvider.listModels}
- * discovers the actually-available models live from the CLI and enriches them
- * against these entries (context windows, legacy flags), falling back to this
- * list wholesale when the probe can't run (Claude Code not installed / not
- * logged in).
+ * Claude Code's own picker value for the model it recommends to this account. A chat
+ * on it sends no model, so Claude Code chooses.
*/
-const { models: AVAILABLE_MODELS, pricing: MODEL_PRICING } = buildModelList([
- // ===== Current Models =====
- {
- id: "claude-fable-5-1",
- name: "Claude Fable 5.1",
- pricing: { input: 0, output: 0 },
- contextWindow: 1000000,
- isSubscription: true
- },
- {
- id: "claude-opus-5-5",
- name: "Claude Opus 5.5",
- pricing: { input: 0, output: 0 },
- contextWindow: 1000000,
- isSubscription: true
- },
- {
- id: "claude-sonnet-5-5",
- name: "Claude Sonnet 5.5",
- pricing: { input: 0, output: 0 },
- contextWindow: 1000000,
- isDefault: true,
- isSubscription: true
- },
- {
- id: "claude-haiku-5-5",
- name: "Claude Haiku 5.5",
- pricing: { input: 0, output: 0 },
- contextWindow: 1000000,
- isSubscription: true
- },
- // ===== Legacy Models =====
- {
- id: "claude-fable-5",
- name: "Claude Fable 5",
- pricing: { input: 0, output: 0 },
- contextWindow: 1000000,
- isLegacy: true,
- isSubscription: true
- },
- {
- id: "claude-opus-4-8",
- name: "Claude Opus 4.8",
- pricing: { input: 0, output: 0 },
- contextWindow: 1000000,
- isLegacy: true,
- isSubscription: true
- },
- {
- id: "claude-opus-4-7",
- name: "Claude Opus 4.7",
- pricing: { input: 0, output: 0 },
- contextWindow: 1000000,
- isLegacy: true,
- isSubscription: true
- },
- {
- id: "claude-sonnet-5",
- name: "Claude Sonnet 5",
- pricing: { input: 0, output: 0 },
- contextWindow: 1000000,
- isLegacy: true,
- isSubscription: true
- },
- {
- id: "claude-haiku-4-5-20251001",
- name: "Claude Haiku 4.5",
- pricing: { input: 0, output: 0 },
- contextWindow: 200000,
- isLegacy: true,
- isSubscription: true
- },
- {
- id: "claude-sonnet-4-6",
- name: "Claude Sonnet 4.6",
- pricing: { input: 0, output: 0 },
- contextWindow: 1000000,
- isLegacy: true,
- isSubscription: true
- },
- {
- id: "claude-opus-4-6",
- name: "Claude Opus 4.6",
- pricing: { input: 0, output: 0 },
- contextWindow: 1000000,
- isLegacy: true,
- isSubscription: true
- },
- {
- id: "claude-sonnet-4-5-20250929",
- name: "Claude Sonnet 4.5",
- pricing: { input: 0, output: 0 },
- contextWindow: 200000,
- isLegacy: true,
- isSubscription: true
- },
- {
- id: "claude-opus-4-5-20251101",
- name: "Claude Opus 4.5",
- pricing: { input: 0, output: 0 },
- contextWindow: 200000,
- isLegacy: true,
- isSubscription: true
- }
-]);
+const DEFAULT_MODEL = "default";
+
+/**
+ * The catalog available without asking Claude Code anything. `chat.ts` needs a
+ * synchronous default for a chat that stores no model, and {@link DEFAULT_MODEL}
+ * is the one id that never goes out of date. {@link ClaudeAgentProvider.listModels}
+ * reads the real line-up from the CLI.
+ */
+const FALLBACK_MODELS: ModelInfo[] = [
+ { id: DEFAULT_MODEL, name: "Default", pricing: { input: 0, output: 0 }, isDefault: true, isSubscription: true }
+];
const TITLE_MODEL = "claude-haiku-4-5-20251001";
@@ -247,15 +146,20 @@ function rememberSession(chatNoteId: string, entry: SessionEntry) {
export class ClaudeAgentProvider implements LlmProvider {
name = "claude-agent";
+ /**
+ * Free for every model the subscription covers: Claude Code's default, the
+ * models its catalog listed, and any Claude model the price table knows.
+ * Long-context variants (`claude-opus-4-8[1m]`) are looked up by their base id.
+ */
getModelPricing(model: string): ModelPricing | undefined {
- // Long-context variants (`claude-opus-4-8[1m]`) are the same model on the
- // same plan, so they price like their base id rather than as unknowns.
- const base = parseContextVariant(model)?.base;
- return MODEL_PRICING[model] ?? (base ? MODEL_PRICING[base] : undefined);
+ const known = model === DEFAULT_MODEL
+ || subscriptionModelCache?.models.some(m => m.id === model)
+ || Object.hasOwn(getProviderPrices("anthropic"), baseModelId(model));
+ return known ? { input: 0, output: 0 } : undefined;
}
getAvailableModels(): ModelInfo[] {
- return AVAILABLE_MODELS;
+ return FALLBACK_MODELS;
}
/**
@@ -271,7 +175,7 @@ export class ClaudeAgentProvider implements LlmProvider {
recommendedModelIds(models: ModelInfo[]): Set<string> {
const idsByBase = new Map<string, string[]>();
for (const model of models) {
- const base = parseContextVariant(model.id)?.base ?? model.id;
+ const base = baseModelId(model.id);
idsByBase.set(base, [...(idsByBase.get(base) ?? []), model.id]);
}
const bases = anthropicRecommendedIds([...idsByBase.keys()].map(id => ({ id, name: id })));
@@ -279,17 +183,16 @@ export class ClaudeAgentProvider implements LlmProvider {
}
/**
- * Dynamically list the models Claude Code actually offers on this host,
- * enriched with curated metadata. Unlike the API providers there is no
+ * Dynamically list the models Claude Code actually offers on this host, with
+ * context windows from the committed price table. Unlike the API providers there is no
* `/models` endpoint: the catalog is whatever the installed CLI reports for
* the logged-in account (tier, version, any managed `availableModels`
* allowlist), which the Agent SDK hands over via the `initialize` handshake.
*
* Cached for {@link SUBSCRIPTION_MODEL_TTL_MS}. A probe *failure* (Claude
* Code not installed, not logged in, or timed out) propagates so the
- * add/edit-provider screen surfaces an actionable error rather than masking
- * it as success with the curated defaults. The curated list stays available
- * via {@link getAvailableModels} as the static catalog used elsewhere.
+ * add/edit-provider screen surfaces an actionable error. There is no offline
+ * line-up to fall back to: {@link getAvailableModels} holds only Claude Code's default.
*/
async listModels(): Promise<ModelInfo[]> {
const now = Date.now();
@@ -297,14 +200,14 @@ export class ClaudeAgentProvider implements LlmProvider {
return subscriptionModelCache.models;
}
if (!subscriptionModelInFlight) {
- subscriptionModelInFlight = this.fetchAndMergeModels().finally(() => {
+ subscriptionModelInFlight = this.fetchModels().finally(() => {
subscriptionModelInFlight = undefined;
});
}
return subscriptionModelInFlight;
}
- private async fetchAndMergeModels(): Promise<ModelInfo[]> {
+ private async fetchModels(): Promise<ModelInfo[]> {
let sdkModels: SubscriptionModelSource[];
try {
sdkModels = await this.probeSupportedModels();
@@ -313,9 +216,9 @@ export class ClaudeAgentProvider implements LlmProvider {
// so the caller can show an actionable message.
throw new Error(describeAgentError(error));
}
- const merged = buildSubscriptionModelList(sdkModels, AVAILABLE_MODELS);
- subscriptionModelCache = { models: merged, fetchedAt: Date.now() };
- return merged;
+ const models = buildSubscriptionModelList(sdkModels, getProviderPrices("anthropic"));
+ subscriptionModelCache = { models, fetchedAt: Date.now() };
+ return models;
}
/**
@@ -427,10 +330,11 @@ export class ClaudeAgentProvider implements LlmProvider {
const onAbort = () => abortController.abort();
signal?.addEventListener("abort", onAbort, { once: true });
- const model = config.model || AVAILABLE_MODELS.find(m => m.isDefault)?.id;
+ // A chat without a model, or on the default, sends none, so Claude Code chooses.
+ const model = config.model && config.model !== DEFAULT_MODEL ? config.model : undefined;
// Report the friendly name in usage metadata (the chat pane renders it
// verbatim); `model` itself must stay the raw ID for the query() call.
- const modelDisplayName = describeModel(model);
+ const modelDisplayName = describeModel(model, config.providerId);
let sessionId: string | undefined;
let assistantText = "";
/** The session this turn is driving, released (not closed) at the end. */
@@ -913,121 +817,65 @@ interface SubscriptionModelSource {
}
/**
- * Merge Claude Code's live catalog with the curated subscription metadata.
+ * Turn Claude Code's live catalog into Trilium's model list.
*
* The canonical wire id (`resolvedModel`) is preferred over the picker alias
- * (`value`) so a chat stores a stable, concrete model id that matches the
- * metered Anthropic provider's ids; aliases resolving to the same model are
- * deduped. The CLI's display name wins; curated entries supply the context
- * window and legacy flag for models they know, and unknown models come through
- * with whatever the CLI reported. Every row is a subscription model, so the
- * plan-covered invariants (zero pricing, no metered cost) are re-asserted
- * across the merged list.
+ * (`value`) so a chat stores a concrete model id that matches the metered
+ * Anthropic provider's ids; aliases resolving to the same model are deduped.
+ * Names and order are Claude Code's. `prices` (the price table's `anthropic`
+ * slice) supplies the context window, by the base id for a long-context variant
+ * it doesn't list. The subscription covers every model, so every row is free.
+ *
+ * {@link DEFAULT_MODEL} is not listed: it would win the dedupe and label its model
+ * "Default (recommended)". The model it resolves to is flagged as the default
+ * instead, or the first one when the catalog has no default.
*/
-export function buildSubscriptionModelList(sdkModels: SubscriptionModelSource[], curated: ModelInfo[]): ModelInfo[] {
- const remote: RemoteModel[] = [];
+export function buildSubscriptionModelList(sdkModels: SubscriptionModelSource[], prices: ProviderPrices): ModelInfo[] {
+ const defaultId = sdkModels.find(m => m.value === DEFAULT_MODEL)?.resolvedModel;
+ const models: ModelInfo[] = [];
const seen = new Set<string>();
for (const model of sdkModels) {
- // `default` is an account-level alias rather than a model: it resolves to
- // whatever Claude Code currently recommends, and picking it would freeze
- // that resolution into the chat under the unhelpful label "Default
- // (recommended)". Worse, it sorts first, so the dedupe below would drop
- // the concrete row pointing at the same model (`opus[1m]` → "Opus") and
- // keep the alias's label instead. Trilium marks its own default via
- // `isDefault`, so nothing is lost by skipping it.
- if (model.value === "default") {
- continue;
- }
const id = model.resolvedModel ?? model.value;
- if (!id || seen.has(id)) {
+ if (model.value === DEFAULT_MODEL || !id || seen.has(id)) {
continue;
}
seen.add(id);
- remote.push({ id, name: model.displayName });
+ models.push({
+ id,
+ name: model.displayName ?? id,
+ contextWindow: prices[id]?.ctx ?? prices[baseModelId(id)]?.ctx,
+ pricing: { input: 0, output: 0 },
+ isSubscription: true
+ });
}
- return mergeModelLists(withContextVariants(curated, remote), remote).map(model => ({
- ...model,
- isSubscription: true,
- pricing: model.pricing ?? { input: 0, output: 0 }
- }));
-}
-
-/** A long-context model id: `claude-opus-4-8[1m]` → base `claude-opus-4-8`, label `1M`. */
-const CONTEXT_VARIANT = /\[([^\]]+)\]$/;
-
-function parseContextVariant(id: string): { base: string; label: string } | null {
- const match = CONTEXT_VARIANT.exec(id);
- if (!match) {
- return null;
+ const defaultIndex = Math.max(models.findIndex(m => m.id === defaultId), 0);
+ if (models.length > 0) {
+ models[defaultIndex] = { ...models[defaultIndex], isDefault: true };
}
- return { base: id.slice(0, match.index), label: match[1].toUpperCase() };
+ return models;
}
-/**
- * Re-key curated metadata onto the long-context ids the CLI reports.
- *
- * Claude Code offers extended-context variants under a suffixed id
- * (`claude-opus-4-8[1m]`) that no curated entry carries, so the merge would file
- * them as unknown models — losing the context window and legacy flag, and leaving
- * anything that looks a model up by id (pricing, the usage row's display name)
- * with nothing but the raw id to show. A synthetic entry per variant, inserted
- * next to the model it varies so the curated ordering survives, makes them known.
- * The suffix stays part of the id: it is what selects the larger window when the
- * id is handed back to the SDK.
- */
-function withContextVariants(curated: ModelInfo[], remote: RemoteModel[]): ModelInfo[] {
- const curatedIds = new Set(curated.map(m => m.id));
- const variantsByBase = new Map<string, string[]>();
- for (const model of remote) {
- if (curatedIds.has(model.id)) {
- continue;
- }
- const variant = parseContextVariant(model.id);
- if (!variant || !curatedIds.has(variant.base)) {
- continue;
- }
- variantsByBase.set(variant.base, [...(variantsByBase.get(variant.base) ?? []), model.id]);
- }
- if (variantsByBase.size === 0) {
- return curated;
- }
-
- return curated.flatMap(entry => [
- entry,
- // A variant is a distinct row, so it must not inherit the base entry's
- // default flag — that would leave two models claiming to be the default.
- ...(variantsByBase.get(entry.id) ?? []).map(id => ({ ...entry, id, name: variantName(entry.name, id), isDefault: false }))
- ]);
-}
+/** The suffix of a long-context model id, such as `[1m]` in `claude-opus-4-8[1m]`. */
+const CONTEXT_VARIANT = /\[[^\]]+\]$/;
-/** Offline fallback name for a variant row: `Claude Opus 4.8` + `[1m]` → `Claude Opus 4.8 (1M)`. */
-function variantName(baseName: string, id: string): string {
- const variant = parseContextVariant(id);
- return variant ? `${baseName} (${variant.label})` : baseName;
+/** The model a long-context id varies (`claude-opus-4-8[1m]` → `claude-opus-4-8`); other ids unchanged. */
+function baseModelId(id: string): string {
+ return id.replace(CONTEXT_VARIANT, "");
}
/**
- * Friendly name for the model id a chat turn was answered by, for the usage row.
- *
- * The live catalog is consulted first: it is the only source that names models
- * the curated list has never heard of, and it carries the CLI's own wording. It
- * is a cache though, so a chat sent before any model picker was opened falls
- * back to the curated list — by exact id, then by the base of a long-context id
- * — and finally to the raw id, which at least says which model answered.
+ * Friendly name for the model a chat turn ran on, for the usage row: the live
+ * catalog's, then the stored selection's (for a chat sent before this process
+ * listed the models), then the raw id. A turn on Claude Code's default has no id.
*/
-function describeModel(model: string | undefined): string | undefined {
+function describeModel(model: string | undefined, providerId: string | undefined): string | undefined {
if (!model) {
return undefined;
}
- const listed = subscriptionModelCache?.models.find(m => m.id === model)
- ?? AVAILABLE_MODELS.find(m => m.id === model);
- if (listed) {
- return listed.name;
- }
- const base = parseContextVariant(model)?.base;
- const curated = base ? AVAILABLE_MODELS.find(m => m.id === base) : undefined;
- return curated ? variantName(curated.name, model) : model;
+ return subscriptionModelCache?.models.find(m => m.id === model)?.name
+ ?? getSelectedModel(providerId, model)?.name
+ ?? model;
}
/**
diff --git a/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts b/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts
index d9aeaa2eb1..5806985141 100644
--- a/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts
@@ -47,7 +47,6 @@ vi.mock("../tools/index.js", () => ({
import {
BaseProvider,
- buildModelList,
buildModelMessage,
mergeModelLists,
type ProviderPrices,
@@ -59,14 +58,6 @@ import { installGlobalFetchAsApiTransport } from "../../../test/request_provider
// the specs that stub that global need one installed which leads back to it.
beforeEach(installGlobalFetchAsApiTransport);
-const TEST_MODELS: Parameters<typeof buildModelList>[0] = [
- { id: "cheap", name: "Cheap", pricing: { input: 1, output: 2 } },
- { id: "mid", name: "Mid", pricing: { input: 2, output: 4 }, isDefault: true },
- { id: "spendy", name: "Spendy", pricing: { input: 10, output: 30 } }
-];
-
-const { pricing: BUILT_PRICING } = buildModelList(TEST_MODELS);
-
/** Injected price-table slice — the base class reads this instead of the JSON file. */
const TEST_PRICES: ProviderPrices = {
cheap: { input: 1, output: 2 },
@@ -128,16 +119,6 @@ function makeAttachment(over: Partial<Record<string, unknown>> = {}) {
} as any;
}
-describe("buildModelList", () => {
- it("maps each model id to its pricing", () => {
- expect(BUILT_PRICING).toMatchObject({
- cheap: { input: 1, output: 2 },
- mid: { input: 2, output: 4 },
- spendy: { input: 10, output: 30 }
- });
- });
-});
-
describe("getAvailableModels / getModelPricing (from the price table)", () => {
it("builds the model list from the price table, sorted, with the default flagged", () => {
const models = new TestProvider().getAvailableModels();
diff --git a/packages/trilium-core/src/services/llm/providers/base_provider.ts b/packages/trilium-core/src/services/llm/providers/base_provider.ts
index 525f85360f..be229f126c 100644
--- a/packages/trilium-core/src/services/llm/providers/base_provider.ts
+++ b/packages/trilium-core/src/services/llm/providers/base_provider.ts
@@ -142,22 +142,11 @@ export function buildModelMessage(m: LlmMessage, accepts: AttachmentFilter = ()
}
/**
- * A hard-coded model definition that always carries pricing. Used only by the
- * Claude Agent (subscription) provider, whose fixed catalog and zero pricing
- * come from the CLI rather than the metered LiteLLM price table.
+ * One provider's slice of the committed price table, keyed by model id. The Claude
+ * Agent provider reads the `anthropic` slice for context windows.
*/
-type CuratedModel = ModelInfo & { pricing: ModelPricing };
-
-/**
- * Split a curated model array into the `{ models, pricing }` pair the subscription
- * provider needs (the model list plus an id → pricing lookup).
- */
-export function buildModelList(baseModels: CuratedModel[]): {
- models: ModelInfo[];
- pricing: Record<string, ModelPricing>;
-} {
- const pricing = Object.fromEntries(baseModels.map(m => [m.id, m.pricing]));
- return { models: baseModels, pricing };
+export function getProviderPrices(provider: string): ProviderPrices {
+ return MODEL_PRICES[provider] ?? {};
}
/**
@@ -171,9 +160,6 @@ export function buildModelList(baseModels: CuratedModel[]): {
* 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
@@ -493,7 +479,7 @@ export abstract class BaseProvider implements LlmProvider {
* can inject a table without a real JSON file.
*/
protected getProviderPrices(): ProviderPrices {
- return MODEL_PRICES[this.name] ?? {};
+ return getProviderPrices(this.name);
}
/**