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
feat(llm): dynamically list Claude Code subscription models
Elian Doran9d038207ec93
diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.tsindex c2ddb5502d..5476edd74c 100644--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts@@ -42,7 +42,7 @@ vi.mock("./claude_binary.js", () => ({ resolveClaudeBinaryPath: resolveClaudeBinconst resolveAttachmentPartMock = vi.hoisted(() => vi.fn());vi.mock("./attachment_content.js", () => ({ resolveAttachmentPart: resolveAttachmentPartMock }));-const { buildSeededPrompt, ClaudeAgentProvider, hashTranscript, resetAgentCwdForTests } = await import("./claude_agent.js");+const { buildSeededPrompt, buildSubscriptionModelList, ClaudeAgentProvider, hashTranscript, resetAgentCwdForTests, resetSubscriptionModelCacheForTests } = await import("./claude_agent.js");/** Drain the query prompt into the single user message it streams (multimodal path). */async function drainPrompt(prompt: unknown): Promise<{ role: string; content: unknown[] }> {@@ -872,3 +872,103 @@ describe("transcript helpers", () => {expect(prompt.endsWith("q2")).toBe(true);});});++describe("buildSubscriptionModelList", () => {+ const curated = [+ { id: "claude-sonnet-5", name: "Claude Sonnet 5", pricing: { input: 0, output: 0 }, contextWindow: 1000000, isDefault: true, isSubscription: true, costMultiplier: 1 },+ { id: "claude-opus-4-6", name: "Claude Opus 4.6", pricing: { input: 0, output: 0 }, contextWindow: 1000000, isLegacy: true, isSubscription: true, costMultiplier: 1 },+ { id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5", pricing: { input: 0, output: 0 }, contextWindow: 200000, isSubscription: true, costMultiplier: 1 }+ ];++ it("resolves aliases to canonical ids, dedupes, and keeps curated metadata", () => {+ const merged = 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"]);+ // Curated name wins over the CLI's display name; flags/context window survive.+ expect(merged[0]).toMatchObject({ name: "Claude 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);+ });++ it("passes through unknown models with subscription invariants and no pricing/context window", () => {+ const merged = buildSubscriptionModelList([+ { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet 5" },+ { value: "claude-fable-9", displayName: "Claude Fable 9" }+ ], curated);++ 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 } });+ });+});++describe("ClaudeAgentProvider.listModels", () => {+ function scriptSupportedModels(models: unknown[] | (() => Promise<unknown[]>)) {+ queryMock.mockReturnValue({+ supportedModels: typeof models === "function" ? models : async () => models+ });+ }++ beforeEach(() => {+ queryMock.mockReset();+ resetSubscriptionModelCacheForTests();+ resolveClaudeBinaryMock.mockClear();+ });++ it("probes the live catalog without running a chat turn", async () => {+ scriptSupportedModels([+ { value: "sonnet", resolvedModel: "claude-sonnet-5", displayName: "Sonnet 5" },+ { value: "claude-fable-9", displayName: "Claude Fable 9" }+ ]);+ const provider = new ClaudeAgentProvider();+ const models = await provider.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 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.+ const { prompt, options } = queryMock.mock.calls[0][0];+ expect(typeof prompt).not.toBe("string");+ expect(prompt[Symbol.asyncIterator]).toBeTypeOf("function");+ expect(options.maxTurns).toBe(1);+ });++ it("serves the cached list on the next call without re-spawning", async () => {+ scriptSupportedModels([{ value: "claude-sonnet-5", displayName: "Sonnet 5" }]);+ const provider = new ClaudeAgentProvider();+ const first = await provider.listModels();+ // A fresh instance still hits the shared module-level cache.+ const second = await new ClaudeAgentProvider().listModels();++ expect(second).toBe(first);+ expect(queryMock).toHaveBeenCalledTimes(1);+ });++ it("falls back to the curated list when the probe fails, then honors the cooldown", async () => {+ scriptSupportedModels(async () => {+ throw new Error("Claude Code is not authenticated");+ });+ const provider = new ClaudeAgentProvider();++ const models = await provider.listModels();+ expect(models).toBe(provider.getAvailableModels());+ // Cooldown: the immediate retry returns curated without re-probing.+ expect(await provider.listModels()).toBe(provider.getAvailableModels());+ expect(queryMock).toHaveBeenCalledTimes(1);+ });++ it("falls back to the curated list when Claude Code isn't installed (no probe spawned)", async () => {+ resolveClaudeBinaryMock.mockRejectedValueOnce(new Error("Claude Code CLI not found"));+ const provider = new ClaudeAgentProvider();++ expect(await provider.listModels()).toBe(provider.getAvailableModels());+ expect(queryMock).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.tsindex 695050ab16..8c9213656e 100644--- a/apps/server/src/services/llm/providers/claude_agent.ts+++ b/apps/server/src/services/llm/providers/claude_agent.ts@@ -36,6 +36,7 @@ import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResimport { resolveAttachmentPart } from "./attachment_content.js";import { buildModelList } 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";@@ -44,10 +45,16 @@ type SupportedImageMime = "image/png" | "image/jpeg" | "image/gif" | "image/webpconst SUPPORTED_IMAGE_MIMES = new Set<string>(["image/png", "image/jpeg", "image/gif", "image/webp"]);/**- * Models offered under a Claude subscription, mirroring Claude Code's own `/model`+ * 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).*/const { models: AVAILABLE_MODELS, pricing: MODEL_PRICING } = buildModelList([// ===== Current Models =====@@ -127,6 +134,24 @@ const TITLE_MODEL = "claude-haiku-4-5-20251001";/** Upper bound on assistant↔tool round-trips within one chat turn. */const MAX_TURNS = 25;+/** How long a successfully probed subscription model list is served from cache. */+const SUBSCRIPTION_MODEL_TTL_MS = 60 * 60 * 1000;+/** After a failed probe, don't re-spawn Claude Code for this long. */+const SUBSCRIPTION_MODEL_FAILURE_COOLDOWN_MS = 60 * 1000;+/** Upper bound on how long the init handshake may take to surface the catalog. */+const SUBSCRIPTION_MODEL_PROBE_TIMEOUT_MS = 15_000;++/**+ * Cached dynamic model list. Deliberately module-level rather than per-instance:+ * the add/edit-provider flow ({@link listProviderModels}) builds a throwaway+ * provider on every call, so an instance cache would never hit — and there is+ * only ever one Claude Code install per host, so a single shared cache is both+ * correct and avoids re-spawning the CLI subprocess on each dropdown open.+ */+let subscriptionModelCache: { models: ModelInfo[]; fetchedAt: number } | undefined;+let subscriptionModelFailedAt: number | undefined;+let subscriptionModelInFlight: Promise<ModelInfo[]> | undefined;+/** Session mappings kept per chat note; bounded to avoid unbounded growth. */const MAX_TRACKED_SESSIONS = 200;@@ -167,6 +192,97 @@ export class ClaudeAgentProvider implements LlmProvider {return AVAILABLE_MODELS;}+ /**+ * Dynamically list the models Claude Code actually offers on this host,+ * enriched with curated metadata. 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}; falls back to the curated+ * list (with a cooldown) when Claude Code isn't installed, isn't logged in,+ * or the probe otherwise fails.+ */+ async listModels(): Promise<ModelInfo[]> {+ const now = Date.now();+ if (subscriptionModelCache && now - subscriptionModelCache.fetchedAt < SUBSCRIPTION_MODEL_TTL_MS) {+ return subscriptionModelCache.models;+ }+ if (subscriptionModelFailedAt && now - subscriptionModelFailedAt < SUBSCRIPTION_MODEL_FAILURE_COOLDOWN_MS) {+ return AVAILABLE_MODELS;+ }+ if (!subscriptionModelInFlight) {+ subscriptionModelInFlight = this.fetchAndMergeModels().finally(() => {+ subscriptionModelInFlight = undefined;+ });+ }+ return subscriptionModelInFlight;+ }++ private async fetchAndMergeModels(): Promise<ModelInfo[]> {+ try {+ const merged = buildSubscriptionModelList(await this.probeSupportedModels(), AVAILABLE_MODELS);+ subscriptionModelCache = { models: merged, fetchedAt: Date.now() };+ subscriptionModelFailedAt = undefined;+ return merged;+ } catch (error) {+ subscriptionModelFailedAt = Date.now();+ getLog().info(`Dynamic model listing failed for the Claude subscription provider, falling back to the curated list: ${describeAgentError(error)}`);+ return AVAILABLE_MODELS;+ }+ }++ /**+ * Read Claude Code's model catalog without running a chat turn. A streaming+ * prompt that never yields keeps stdin open so the session's `initialize`+ * handshake completes — that handshake carries the catalog, so no user+ * message is sent and no tokens are spent. The session is torn down as soon+ * as the catalog is read (or the probe times out).+ */+ private async probeSupportedModels(): Promise<SubscriptionModelSource[]> {+ const abortController = new AbortController();+ // An input stream that yields no user message: `next()` stays pending —+ // keeping the session's stdin open so the `initialize` handshake can+ // complete — and only resolves `done` when the probe is torn down. No+ // user turn is ever sent, so the probe spends no tokens.+ const noInput: AsyncIterable<SDKUserMessage> = {+ [Symbol.asyncIterator]: () => ({+ next: () => new Promise<IteratorResult<SDKUserMessage>>(resolve => {+ const finish = () => resolve({ done: true, value: undefined });+ if (abortController.signal.aborted) {+ finish();+ } else {+ abortController.signal.addEventListener("abort", finish, { once: true });+ }+ })+ })+ };++ const response = query({+ prompt: noInput,+ options: {+ ...await this.buildBaseOptions({ enableNoteTools: false }),+ maxTurns: 1,+ abortController+ }+ });++ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ return await Promise.race([+ response.supportedModels(),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error("Timed out reading the Claude Code model catalog")), SUBSCRIPTION_MODEL_PROBE_TIMEOUT_MS);+ })+ ]);+ } finally {+ if (timer) {+ clearTimeout(timer);+ }+ abortController.abort();+ }+ }+/** Not used — the route prefers {@link chatChunks} when implemented. */chat(): StreamResult {throw new Error("The Claude Agent provider streams chunks directly; use chatChunks().");@@ -541,6 +657,53 @@ export function resetAgentCwdForTests(): void {agentCwd = undefined;}+/** For tests: forget the cached/failed dynamic model list so the next call re-probes. */+export function resetSubscriptionModelCacheForTests(): void {+ subscriptionModelCache = undefined;+ subscriptionModelFailedAt = undefined;+ subscriptionModelInFlight = undefined;+}++/** The subset of the Agent SDK's model-catalog entries the merge consumes. */+interface SubscriptionModelSource {+ /** The picker value — a family alias (`sonnet`) or a full model id. */+ value: string;+ /** The canonical wire id an alias resolves to (`sonnet` → `claude-sonnet-5`). */+ resolvedModel?: string;+ /** Human-readable name Claude Code shows for the model. */+ displayName?: string;+}++/**+ * Merge Claude Code's live catalog with the curated subscription metadata.+ *+ * 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. Curated entries supply names, context windows and the legacy flag+ * for models they know; 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.+ */+export function buildSubscriptionModelList(sdkModels: SubscriptionModelSource[], curated: ModelInfo[]): ModelInfo[] {+ const remote: RemoteModel[] = [];+ const seen = new Set<string>();+ for (const model of sdkModels) {+ const id = model.resolvedModel ?? model.value;+ if (!id || seen.has(id)) {+ continue;+ }+ seen.add(id);+ remote.push({ id, name: model.displayName });+ }++ return mergeModelLists(curated, remote).map(model => ({+ ...model,+ isSubscription: true,+ pricing: model.pricing ?? { input: 0, output: 0 }+ }));+}+/*** Build the prompt for the current user turn. When the turn carries attachments* the model can consume natively, this returns a one-message stream of Anthropicdiff --git a/apps/server/src/services/llm/providers/model_listing.spec.ts b/apps/server/src/services/llm/providers/model_listing.spec.tsindex cdfbe04a10..72dee0497e 100644--- a/apps/server/src/services/llm/providers/model_listing.spec.ts+++ b/apps/server/src/services/llm/providers/model_listing.spec.ts@@ -233,6 +233,17 @@ describe("recommendedModelIds", () => {]);});+ 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");diff --git a/apps/server/src/services/llm/providers/model_listing.ts b/apps/server/src/services/llm/providers/model_listing.tsindex 0d0b6593e2..1f6becf69c 100644--- a/apps/server/src/services/llm/providers/model_listing.ts+++ b/apps/server/src/services/llm/providers/model_listing.ts@@ -138,10 +138,12 @@ export function isGoogleChatModel(id: string): boolean {* 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 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.+ * 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".*/@@ -149,7 +151,7 @@ export function recommendedModelIds(models: RecommendCandidate[], provider: striif (provider === "openai") {return openAiRecommendedIds(models);}- if (provider === "anthropic") {+ 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));