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): key the host-provided providers by type
Elian Doran131109cdda80
diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.tsindex 99715641db..ecb14c4efc 100644--- a/apps/server/src/services/llm/index.spec.ts+++ b/apps/server/src/services/llm/index.spec.ts@@ -1,14 +1,14 @@import { describe, expect, it, vi } from "vitest";const registrations = vi.hoisted(() => ({- claudeAgentFactory: undefined as (() => unknown) | undefined,+ hostProviders: [] as { type: string; factory: () => unknown }[],docNoteReader: undefined as ((note: unknown) => string | null) | undefined,skillReader: undefined as ((file: string) => string | null) | undefined,toolRegistries: [] as unknown[]}));vi.mock("@triliumnext/core/src/services/llm/index.js", () => ({- registerClaudeAgentProvider: (factory: () => unknown) => { registrations.claudeAgentFactory = factory; }+ registerHostProvider: (type: string, factory: () => unknown) => { registrations.hostProviders.push({ type, factory }); }}));vi.mock("@triliumnext/core/src/services/llm/skills.js", () => ({registerSkillReader: (reader: (file: string) => string | null) => { registrations.skillReader = reader; }@@ -28,9 +28,11 @@ describe("registerServerLlmExtensions", () => {it("hands core every piece of the stack that needs Node", () => {registerServerLlmExtensions();- // The subscription provider, which shells out to the Claude Code CLI.- // Registered as a factory, so nothing is constructed until a chat asks for it.- expect(registrations.claudeAgentFactory?.()).toBeInstanceOf(ClaudeAgentProvider);+ // The subscription provider, which shells out to the Claude Code CLI, under+ // the type core knows it by. Registered as a factory, so nothing is+ // constructed until a chat asks for it.+ expect(registrations.hostProviders.map(p => p.type)).toEqual(["claude-agent"]);+ expect(registrations.hostProviders[0].factory()).toBeInstanceOf(ClaudeAgentProvider);// The User Guide reader, which core's note-content helper calls for doc notes.expect(registrations.docNoteReader).toBeTypeOf("function");// The skill sheets: core owns the catalog and the tool, the server onlydiff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.tsindex 8db59995f8..cd037d2259 100644--- a/apps/server/src/services/llm/index.ts+++ b/apps/server/src/services/llm/index.ts@@ -3,13 +3,17 @@** The stack itself lives in `@triliumnext/core`, so the browser-hosted* (standalone) build can run it too. What could not follow it there is anything- * that needs Node: the Claude Agent provider, which spawns the Claude Code CLI,- * and the User Guide tools, which read pages off disk. Core exposes a seam for- * each; this is where the server fills them in — including the skill sheets,- * whose catalog is core's while the reading is per-runtime.+ * that needs Node: the provider that spawns the Claude Code CLI, and the User+ * Guide tools, which read pages off disk. Core exposes a seam for each; this is+ * where the server fills them in — including the skill sheets, whose catalog is+ * core's while the reading is per-runtime.+ *+ * Each seam is keyed rather than bespoke, so the next host-provided provider+ * (GitHub Copilot and the like) is one more line here and one more entry in+ * core's HOST_PROVIDED_TYPES.*/-import { registerClaudeAgentProvider } from "@triliumnext/core/src/services/llm/index.js";+import { registerHostProvider } from "@triliumnext/core/src/services/llm/index.js";import { registerSkillReader } from "@triliumnext/core/src/services/llm/skills.js";import { registerDocNoteHtmlReader } from "@triliumnext/core/src/services/llm/tools/helpers.js";import { registerToolRegistry } from "@triliumnext/core/src/services/llm/tools/index.js";@@ -26,7 +30,7 @@ import { helpTools } from "./tools/help_tools.js";* whether some module that happens to import this one was loaded first.*/export function registerServerLlmExtensions() {- registerClaudeAgentProvider(() => new ClaudeAgentProvider());+ registerHostProvider("claude-agent", () => new ClaudeAgentProvider());registerDocNoteHtmlReader(getDocNoteHtml);registerSkillReader(loadSkillSheet);registerToolRegistry(helpTools);diff --git a/packages/trilium-core/src/services/llm/index.spec.ts b/packages/trilium-core/src/services/llm/index.spec.tsindex 87b3ddf11e..772e40018d 100644--- a/packages/trilium-core/src/services/llm/index.spec.ts+++ b/packages/trilium-core/src/services/llm/index.spec.ts@@ -45,13 +45,15 @@ vi.mock("./providers/deepseek.js", () => ({ DeepSeekProvider: makeProviderMock("vi.mock("./providers/local.js", () => ({ LocalProvider: makeProviderMock("local") }));import {+ clearHostProviders,clearProviderCache,getProvider,getProviderByType,getSelectedModel,hasConfiguredProviders,+ HOST_PROVIDED_TYPES,listProviderModels,- registerClaudeAgentProvider+ registerHostProvider} from "./index.js";// Mocked module → this is the makeProviderMock("google") stand-in class, whose// prototype we can strip listModels from to exercise the curated-list fallback.@@ -67,17 +69,22 @@ const TWO = [];/**- * The Claude Agent provider is not part of core — it spawns the Claude Code CLI,- * so hosts that can run it register a factory. Stand one in for the same reason- * the other provider modules are mocked: to observe the constructor arguments.+ * Host-provided types are not part of core — the Claude Agent one spawns the+ * Claude Code CLI — so whichever host can run them registers a factory. Stand one+ * in per type, for the same reason the other provider modules are mocked: to+ * observe what reaches the constructor.*/-const ClaudeAgentProviderMock = makeProviderMock("claude-agent");+const hostProviderMocks = Object.fromEntries(+ Object.keys(HOST_PROVIDED_TYPES).map((type) => [ type, makeProviderMock(type) ])+);describe("llm/index provider registry", () => {beforeEach(() => {clearProviderCache();vi.clearAllMocks();- registerClaudeAgentProvider(() => new ClaudeAgentProviderMock() as never);+ for (const [ type, Mock ] of Object.entries(hostProviderMocks)) {+ registerHostProvider(type as keyof typeof HOST_PROVIDED_TYPES, () => new Mock() as never);+ }});afterEach(() => {clearProviderCache();@@ -141,6 +148,27 @@ describe("llm/index provider registry", () => {expect(() => getProvider("x")).toThrow(/Unknown LLM provider type: mystery/);});+ it("builds every host-provided type through the factory its host registered", () => {+ // The catalog and the switch have to agree: a type listed in+ // HOST_PROVIDED_TYPES with no branch of its own falls through to the+ // default and reads as a typo, in a build that can in fact serve it.+ const types = Object.keys(HOST_PROVIDED_TYPES);+ setProviders(types.map((provider, index) => ({ id: `h${index}`, name: provider, provider, apiKey: "" })));++ types.forEach((type, index) => {+ expect(getProvider(`h${index}`)).toBeInstanceOf(hostProviderMocks[type]);+ });+ });++ it("names the provider when no host in this build can build it", () => {+ // What standalone hits for Claude Code: the type is real and the branch is+ // there, but nothing registered a factory. Better than "unknown type",+ // which would send the user looking for a typo.+ clearHostProviders();+ setProviders([{ id: "c", name: "C", provider: "claude-agent", apiKey: "" }]);+ expect(() => getProvider("c")).toThrow("The Claude Code provider is not available in this build.");+ });+it("drops cached instances when the llmProviders option changes", () => {setProviders(TWO);const p1 = getProvider("a1");diff --git a/packages/trilium-core/src/services/llm/index.ts b/packages/trilium-core/src/services/llm/index.tsindex fabc14f721..749bee1e43 100644--- a/packages/trilium-core/src/services/llm/index.ts+++ b/packages/trilium-core/src/services/llm/index.ts@@ -31,19 +31,59 @@ export interface LlmProviderSetup {const PROVIDER_TYPES = ["anthropic", "openai", "google", "deepseek", "claude-agent", "ollama", "lmstudio", "openai-compatible"];/**- * Factory for the Claude Agent provider, supplied by hosts that can run it.+ * Provider types core cannot build for itself, each mapped to the name the user+ * knows it by.*- * It drives the Claude Code CLI — a spawned process reading the filesystem — so- * it cannot live here: core also runs in the browser (standalone), where there- * is no process to spawn. The server and desktop builds register it at startup- * via {@link registerClaudeAgentProvider}; where nothing registers it, selecting- * the provider fails with the same "unknown provider type" error as a typo.+ * What they have in common is a dependency on the runtime around them rather+ * than on an API key: Claude Code is a CLI this process spawns, and the+ * subscription services lined up behind it authenticate through the host's own+ * account plumbing. Core runs in the browser too, where none of that exists, so+ * the host that *can* do it registers a factory at startup with+ * {@link registerHostProvider}. Where nothing registers one, selecting the+ * provider fails with a message naming it rather than a bare "unknown type".+ *+ * Adding one means an entry here, a literal branch in+ * {@link createProviderInstance} (see the note there on why it must be literal),+ * and a registration in whichever hosts can serve it.+ */+export const HOST_PROVIDED_TYPES = {+ /** Claude Pro/Max through the Claude Agent SDK, authenticated by `claude /login`. */+ "claude-agent": "Claude Code"+} as const;++/** A provider type from {@link HOST_PROVIDED_TYPES}. */+export type HostProvidedType = keyof typeof HOST_PROVIDED_TYPES;++const hostProviderFactories = new Map<string, () => LlmProvider>();++/**+ * Register the host's implementation of a provider core cannot construct.+ * Called once at startup, before any chat can ask for it.+ */+export function registerHostProvider(type: HostProvidedType, factory: () => LlmProvider) {+ hostProviderFactories.set(type, factory);+}++/**+ * Forget every registered factory, putting the registry back to how a build that+ * supplies none starts. For a runtime that re-initialises core (tests, an+ * Electron reload), which registers again on the way back up.*/-let claudeAgentFactory: (() => LlmProvider) | null = null;+export function clearHostProviders() {+ hostProviderFactories.clear();+}-/** Register the host's Claude Agent provider factory. See {@link claudeAgentFactory}. */-export function registerClaudeAgentProvider(factory: () => LlmProvider) {- claudeAgentFactory = factory;+/**+ * Build a host-provided provider, or explain that this build has no one to build+ * it. The type is always a literal from the call site — see+ * {@link createProviderInstance} — never the string the user's config carried.+ */+function createHostProvider(type: HostProvidedType): LlmProvider {+ const factory = hostProviderFactories.get(type);+ if (!factory) {+ throw new Error(`The ${HOST_PROVIDED_TYPES[type]} provider is not available in this build.`);+ }+ return factory();}/**@@ -55,8 +95,9 @@ export function registerClaudeAgentProvider(factory: () => LlmProvider) {* untrusted input, which is exactly what CodeQL's* `js/unvalidated-dynamic-method-call` flags. Here every branch calls a* statically known constructor, so no dynamic dispatch is possible at all.- * The one registered factory is likewise reached from a literal branch, never- * looked up by the untrusted string.+ * The host-provided factories are looked up too, but only ever under a literal+ * spelled out in their branch below — the untrusted string picks the branch and+ * goes no further.*/function createProviderInstance(provider: string, apiKey: string, baseURL?: string): LlmProvider {switch (provider) {@@ -70,13 +111,11 @@ function createProviderInstance(provider: string, apiKey: string, baseURL?: stri// custom endpoint so its models resolve against the committed price table.case "deepseek":return new DeepSeekProvider(apiKey, baseURL);- // Claude Pro/Max subscription via the Claude Agent SDK — no API key;- // authentication is handled by Claude Code itself (`claude /login`).+ // Subscription providers, whose credentials belong to the host rather than+ // to a key the user pastes in — so the host builds them. One branch each,+ // naming its own type: see HOST_PROVIDED_TYPES.case "claude-agent":- if (!claudeAgentFactory) {- throw new Error("The Claude Code provider is not available in this build.");- }- return claudeAgentFactory();+ return createHostProvider("claude-agent");// Self-hosted endpoints. The three cards differ only in the URL and setup// hint the UI prefills; they all speak the OpenAI-compatible API, with// Ollama and LM Studio additionally offering a richer native listing.