Skip to content

Build your personal knowledge base with Trilium Notes

refactor(llm): move the LLM stack into trilium-core

Elian Doranaaa33b3f696e
diff --git a/apps/server/src/routes/api/llm_chat.spec.ts b/apps/server/src/routes/api/llm_chat.spec.ts
index 8c68a08c88..c90f23a44d 100644
--- a/apps/server/src/routes/api/llm_chat.spec.ts
+++ b/apps/server/src/routes/api/llm_chat.spec.ts
@@ -47,13 +47,13 @@ vi.mock("../../services/llm/index.js", () => {
// Only the stream itself is faked; `formatStreamError` (used for the log line) is a pure
// function and stays real, so the logged text is asserted against the production format.
-vi.mock("../../services/llm/stream.js", async (importOriginal) => ({
- ...await importOriginal<typeof import("../../services/llm/stream.js")>(),
+vi.mock("@triliumnext/core/src/services/llm/stream.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("@triliumnext/core/src/services/llm/stream.js")>(),
async *streamToChunks () { for (const c of state.chunks) yield c; }
}));
const generateChatTitle = vi.fn(async (..._args: unknown[]) => {});
-vi.mock("../../services/llm/chat_title.js", () => ({ generateChatTitle: (...args: unknown[]) => generateChatTitle(...args) }));
+vi.mock("@triliumnext/core/src/services/llm/chat_title.js", () => ({ generateChatTitle: (...args: unknown[]) => generateChatTitle(...args) }));
import llmChatRoute from "./llm_chat.js";
diff --git a/apps/server/src/routes/api/llm_chat.ts b/apps/server/src/routes/api/llm_chat.ts
index bca605b4db..ad0c9e172d 100644
--- a/apps/server/src/routes/api/llm_chat.ts
+++ b/apps/server/src/routes/api/llm_chat.ts
@@ -2,9 +2,9 @@ import type { LlmMessage, LlmStreamChunk } from "@triliumnext/commons";
import { getLog, ValidationError } from "@triliumnext/core";
import type { Request, Response } from "express";
-import { generateChatTitle } from "../../services/llm/chat_title.js";
+import { generateChatTitle } from "@triliumnext/core/src/services/llm/chat_title.js";
import { getProvider, getProviderByType, getSelectedModel, hasConfiguredProviders, listProviderModels, type LlmProviderConfig } from "../../services/llm/index.js";
-import { formatStreamError, streamToChunks } from "../../services/llm/stream.js";
+import { formatStreamError, streamToChunks } from "@triliumnext/core/src/services/llm/stream.js";
import { safeExtractMessageAndStackFromError } from "../../services/utils.js";
interface ChatRequest {
diff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.ts
index 13ce5ddb98..64279b3b61 100644
--- a/apps/server/src/services/llm/index.ts
+++ b/apps/server/src/services/llm/index.ts
@@ -1,194 +1,40 @@
-import { getLog, options as optionService } from "@triliumnext/core";
-
-import { AnthropicProvider } from "./providers/anthropic.js";
-import { ClaudeAgentProvider } from "./providers/claude_agent.js";
-import { DeepSeekProvider } from "./providers/deepseek.js";
-import { GoogleProvider } from "./providers/google.js";
-import { LocalProvider } from "./providers/local.js";
-import { OpenAiProvider } from "./providers/openai.js";
-import type { LlmProvider, ModelInfo } from "./types.js";
-
-/**
- * Configuration for a single LLM provider instance.
- * This matches the structure stored in the llmProviders option.
- */
-export interface LlmProviderSetup {
- id: string;
- name: string;
- provider: string;
- apiKey: string;
- /** Optional override for the SDK's default API endpoint (e.g. for self-hosted Ollama, vLLM, or proxies). */
- baseURL?: string;
- /**
- * Models the user selected for this provider, with full metadata denormalized
- * so the chat picker renders them without a live fetch. Absent in configs
- * saved before model selection existed.
- */
- selectedModels?: ModelInfo[];
-}
-
-/** Provider type identifiers that can be instantiated, for error messages. */
-const PROVIDER_TYPES = ["anthropic", "openai", "google", "deepseek", "claude-agent", "ollama", "lmstudio", "openai-compatible"];
-
/**
- * Instantiate a provider from its type identifier.
+ * The server's entry point into the LLM stack.
*
- * Deliberately a switch over literal cases rather than a lookup table: the
- * provider type is user-controlled, and looking a factory up by it — with a
- * plain object *or* a Map — makes the invoked function a value derived from
- * 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.
- */
-function createProviderInstance(provider: string, apiKey: string, baseURL?: string): LlmProvider {
- switch (provider) {
- case "anthropic":
- return new AnthropicProvider(apiKey, baseURL);
- case "openai":
- return new OpenAiProvider(apiKey, baseURL);
- case "google":
- return new GoogleProvider(apiKey, baseURL);
- // OpenAI-compatible on the wire, but carded separately from the generic
- // 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`).
- case "claude-agent":
- return new ClaudeAgentProvider();
- // 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.
- case "ollama":
- case "lmstudio":
- case "openai-compatible":
- return new LocalProvider(provider, apiKey, baseURL);
- default:
- throw new Error(`Unknown LLM provider type: ${provider}. Available: ${PROVIDER_TYPES.join(", ")}`);
- }
-}
-
-/** Cache of instantiated providers by their config ID */
-let cachedProviders: Record<string, LlmProvider> = {};
-
-/**
- * The raw llmProviders JSON the cache was built from. When the option changes
- * (provider added/edited/removed in the settings), the cache self-invalidates
- * so stale instances — and their dynamic model-list caches — are dropped.
- */
-let cachedProvidersSource: string | null = null;
-
-/**
- * Get configured providers from the options.
- */
-function getConfiguredProviders(): LlmProviderSetup[] {
- try {
- const providersJson = optionService.getOptionOrNull("llmProviders");
- if (providersJson !== cachedProvidersSource) {
- cachedProviders = {};
- cachedProvidersSource = providersJson;
- }
- if (!providersJson) {
- return [];
- }
- return JSON.parse(providersJson) as LlmProviderSetup[];
- } catch (e) {
- getLog().error(`Failed to parse llmProviders option: ${e}`);
- return [];
- }
-}
-
-/**
- * Get a provider instance by its configuration ID.
- * If no ID is provided, returns the first configured provider.
+ * The stack itself lives in `@triliumnext/core` so the browser-hosted
+ * (standalone) build can run it too. What stays here is everything that needs
+ * Node: the Claude Agent provider, which spawns the Claude Code CLI, and the
+ * two tool registries that read off disk (the User Guide and the skill sheets).
+ * Importing this module contributes them to core; it is the only supported way
+ * in, so nothing can reach a half-registered stack.
*/
-export function getProvider(providerId?: string): LlmProvider {
- const configs = getConfiguredProviders();
-
- if (configs.length === 0) {
- throw new Error("No LLM providers configured. Please add a provider in Options → AI / LLM.");
- }
-
- // Find the requested provider or use the first one
- const config = providerId
- ? configs.find(c => c.id === providerId)
- : configs[0];
-
- if (!config) {
- throw new Error(`LLM provider not found: ${providerId}`);
- }
- // Check cache
- if (cachedProviders[config.id]) {
- return cachedProviders[config.id];
- }
+import { registerClaudeAgentProvider } from "@triliumnext/core/src/services/llm/index.js";
+import { registerDocNoteHtmlReader } from "@triliumnext/core/src/services/llm/tools/helpers.js";
+import { registerToolRegistry } from "@triliumnext/core/src/services/llm/tools/index.js";
- // Create new provider instance
- const provider = createProviderInstance(config.provider, config.apiKey, config.baseURL);
- cachedProviders[config.id] = provider;
- return provider;
-}
-
-/**
- * Get the first configured provider of a specific type (e.g., "anthropic").
- */
-export function getProviderByType(providerType: string): LlmProvider {
- const configs = getConfiguredProviders();
- const config = configs.find(c => c.provider === providerType);
-
- if (!config) {
- throw new Error(`No ${providerType} provider configured. Please add one in Options → AI / LLM.`);
- }
-
- return getProvider(config.id);
-}
-
-/**
- * Check if any providers are configured.
- */
-export function hasConfiguredProviders(): boolean {
- return getConfiguredProviders().length > 0;
-}
-
-/**
- * List the models available for a provider described by raw credentials —
- * used by the model-selection screen during the add/edit flow, where the
- * provider config isn't necessarily persisted yet. Instantiates the provider
- * ad-hoc (bypassing the config cache) and queries it live — a listing failure
- * (bad credentials, unreachable endpoint) propagates so the caller can surface
- * it — falling back to the curated list only when the provider doesn't support
- * dynamic listing.
- */
-export async function listProviderModels(provider: string, apiKey: string, baseURL?: string): Promise<ModelInfo[]> {
- const instance = createProviderInstance(provider, apiKey, baseURL);
- const models = await (instance.listModels?.() ?? instance.getAvailableModels());
- // Tag the default-selected set here so the recommendation rule lives on the
- // 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) }));
-}
-
-/**
- * Find the model a chat is targeting within its provider config's stored
- * selection — the denormalized source of display name and pricing for the
- * response's usage/cost, working even for dynamically discovered models the
- * curated list doesn't know. Returns undefined when the model isn't stored.
- */
-export function getSelectedModel(providerId: string | undefined, modelId: string): ModelInfo | undefined {
- if (!providerId) {
- return undefined;
- }
- const config = getConfiguredProviders().find(c => c.id === providerId);
- return config?.selectedModels?.find(m => m.id === modelId);
-}
-
-/**
- * Clear the provider cache. Call this when provider configurations change.
- */
-export function clearProviderCache(): void {
- cachedProviders = {};
- cachedProvidersSource = null;
-}
-
-export type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing } from "./types.js";
+import { ClaudeAgentProvider } from "./providers/claude_agent.js";
+import { skillTools } from "./skills/index.js";
+import { getDocNoteHtml } from "./tools/doc_notes.js";
+import { helpTools } from "./tools/help_tools.js";
+
+export {
+ clearProviderCache,
+ getProvider,
+ getProviderByType,
+ getSelectedModel,
+ hasConfiguredProviders,
+ listProviderModels,
+ type LlmProvider,
+ type LlmProviderConfig,
+ type LlmProviderSetup,
+ type ModelInfo,
+ type ModelPricing
+} from "@triliumnext/core/src/services/llm/index.js";
+export { allToolRegistries } from "@triliumnext/core/src/services/llm/tools/index.js";
+export type { ToolDefinition } from "@triliumnext/core/src/services/llm/tools/tool_registry.js";
+
+registerClaudeAgentProvider(() => new ClaudeAgentProvider());
+registerDocNoteHtmlReader(getDocNoteHtml);
+registerToolRegistry(helpTools);
+registerToolRegistry(skillTools);
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 a780be9fbd..1c2301f23f 100644
--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts
@@ -9,12 +9,13 @@ vi.mock("@anthropic-ai/claude-agent-sdk", () => ({
}));
vi.mock("@triliumnext/core", () => ({
- getLog: () => ({ info: vi.fn(), error: errorLogMock }),
- // buildSystemPrompt (reached via composeSystemPrompt) reads the workspace
- // task states; no custom states in this unit test.
- task_states: { getTaskStates: () => [] }
+ getLog: () => ({ info: vi.fn(), error: errorLogMock })
}));
+// buildSystemPrompt (reached via composeSystemPrompt) reads the workspace task
+// states; no custom states in this unit test.
+vi.mock("@triliumnext/core/src/services/task_states.js", () => ({ getTaskStates: () => [] }));
+
// In-process MCP: the provider hands the agent Trilium's own MCP server
// instance; stub the factory so tests don't build the real tool registry.
const createMcpServerMock = vi.hoisted(() => vi.fn(() => ({ mcpServerInstance: true })));
@@ -29,7 +30,7 @@ vi.mock("../../data_dir.js", async () => {
vi.mock("../../port.js", () => ({ default: 8080 }));
const buildNoteHintMock = vi.hoisted(() => vi.fn((noteId: string): string | null => `NOTE_META(${noteId})`));
-vi.mock("../note_hint.js", () => ({ buildNoteHint: buildNoteHintMock }));
+vi.mock("@triliumnext/core/src/services/llm/note_hint.js", () => ({ buildNoteHint: buildNoteHintMock }));
// 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
@@ -40,7 +41,7 @@ vi.mock("./claude_binary.js", () => ({ resolveClaudeBinaryPath: resolveClaudeBin
// Attachment resolution reads bytes out of Becca, which the core mock above
// omits — stub it so the multimodal tests drive block construction directly.
const resolveAttachmentPartMock = vi.hoisted(() => vi.fn());
-vi.mock("../attachment_content.js", () => ({ resolveAttachmentPart: resolveAttachmentPartMock }));
+vi.mock("@triliumnext/core/src/services/llm/attachment_content.js", () => ({ resolveAttachmentPart: resolveAttachmentPartMock }));
// The Windows `.cmd` shim delegates to child_process.spawn; the provider never
// spawns otherwise, so mocking the whole module is safe.
diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.ts
index 7e0faa5a04..6c25323417 100644
--- a/apps/server/src/services/llm/providers/claude_agent.ts
+++ b/apps/server/src/services/llm/providers/claude_agent.ts
@@ -24,6 +24,12 @@ import { type Options as AgentOptions, query, type SDKAssistantMessage, type SDK
import type { ContentBlockParam } from "@anthropic-ai/sdk/resources";
import type { LlmFilePart, LlmImagePart, LlmMessage, LlmMessagePart, LlmStreamChunk, LlmTextAttachmentPart } from "@triliumnext/commons";
import { getLog } from "@triliumnext/core";
+import { resolveAttachmentPart } from "@triliumnext/core/src/services/llm/attachment_content.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 { buildSystemPrompt } from "@triliumnext/core/src/services/llm/system_prompt.js";
+import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "@triliumnext/core/src/services/llm/types.js";
import { encodeBase64 } from "@triliumnext/core/src/services/utils/binary.js";
import { spawn as nodeSpawn } from "child_process";
import { createHash } from "crypto";
@@ -32,12 +38,6 @@ import path from "path";
import dataDirs from "../../data_dir.js";
import { createMcpServer } from "../../mcp/mcp_server.js";
-import { resolveAttachmentPart } from "../attachment_content.js";
-import { buildNoteHint } from "../note_hint.js";
-import { buildSystemPrompt } from "../system_prompt.js";
-import type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing, StreamResult } from "../types.js";
-import { anthropicRecommendedIds } from "./anthropic.js";
-import { buildModelList, mergeModelLists, type RemoteModel } from "./base_provider.js";
import { resolveClaudeBinaryPath } from "./claude_binary.js";
/** Image media types Anthropic accepts as a base64 image block. */
diff --git a/apps/server/src/services/llm/skills/index.spec.ts b/apps/server/src/services/llm/skills/index.spec.ts
index e71d43c3b1..65b1553ec2 100644
--- a/apps/server/src/services/llm/skills/index.spec.ts
+++ b/apps/server/src/services/llm/skills/index.spec.ts
@@ -1,6 +1,6 @@
+import type { ToolDefinition } from "@triliumnext/core/src/services/llm/tools/tool_registry.js";
import { describe, expect, it } from "vitest";
-import type { ToolDefinition } from "../tools/tool_registry.js";
import { getSkillsSummary, skillTools } from "./index.js";
function loadSkillTool(): ToolDefinition {
diff --git a/apps/server/src/services/llm/skills/index.ts b/apps/server/src/services/llm/skills/index.ts
index b9a113e151..014b1947c5 100644
--- a/apps/server/src/services/llm/skills/index.ts
+++ b/apps/server/src/services/llm/skills/index.ts
@@ -4,13 +4,12 @@
* included in the system prompt; full content is fetched via the load_skill tool.
*/
+import { defineTools } from "@triliumnext/core/src/services/llm/tools/tool_registry.js";
import { readFileSync } from "fs";
import { join } from "path";
-
import { z } from "zod";
import resourceDir from "../../resource_dir.js";
-import { defineTools } from "../tools/tool_registry.js";
const SKILLS_DIR = join(resourceDir.RESOURCE_DIR, "llm", "skills");
@@ -70,8 +69,8 @@ export function getSkillsSummary(): string {
export const skillTools = defineTools({
load_skill: {
- description: "Load a skill to get specialized instructions. Available skills:\n"
- + SKILLS.map((s) => `- ${s.name}: ${s.description}`).join("\n"),
+ description: `Load a skill to get specialized instructions. Available skills:\n${
+ SKILLS.map((s) => `- ${s.name}: ${s.description}`).join("\n")}`,
inputSchema: z.object({
name: z.string().describe("The skill name to load")
}),
diff --git a/apps/server/src/services/llm/tools/doc_notes.spec.ts b/apps/server/src/services/llm/tools/doc_notes.spec.ts
new file mode 100644
index 0000000000..7a47520b45
--- /dev/null
+++ b/apps/server/src/services/llm/tools/doc_notes.spec.ts
@@ -0,0 +1,53 @@
+import type { BNote } from "@triliumnext/core";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+/** Fake on-disk help pages: path suffix → HTML content. */
+const docFiles = vi.hoisted(() => new Map<string, string>());
+
+// Doc notes read their HTML from disk — serve them from the docFiles fixture
+// map and pass every other path through to the real fs.
+vi.mock("fs", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("fs")>();
+ const readFileSync = ((filePath: unknown, ...rest: unknown[]) => {
+ const pathStr = String(filePath);
+ for (const [suffix, content] of docFiles) {
+ if (pathStr.endsWith(suffix)) return content;
+ }
+ if (pathStr.includes("doc_notes")) {
+ throw new Error(`ENOENT: ${pathStr}`);
+ }
+ return (actual.readFileSync as (...args: unknown[]) => unknown)(filePath, ...rest);
+ }) as typeof actual.readFileSync;
+ const mocked = { ...actual, readFileSync };
+ return { ...mocked, default: mocked };
+});
+
+import { getDocNoteHtml } from "./doc_notes.js";
+
+/** Minimal BNote stub exposing only the label lookup the reader performs. */
+function docNoteStub(docName: string | null) {
+ return {
+ noteId: "n1",
+ type: "doc",
+ getLabelValue: (name: string) => (name === "docName" ? docName : null)
+ } as unknown as BNote;
+}
+
+describe("getDocNoteHtml", () => {
+ beforeEach(() => docFiles.clear());
+
+ it("reads the page HTML from disk under doc_notes/en", () => {
+ docFiles.set("Cloning Notes.html", "<h2>Cloning</h2>");
+ expect(getDocNoteHtml(docNoteStub("User Guide/User Guide/Cloning Notes"))).toBe("<h2>Cloning</h2>");
+ });
+
+ it("returns null without a docName label, on a missing file, and on path traversal attempts", () => {
+ expect(getDocNoteHtml(docNoteStub(null))).toBeNull();
+ expect(getDocNoteHtml(docNoteStub("User Guide/Nonexistent Page"))).toBeNull();
+ // Traversal attempts must be rejected before touching the filesystem —
+ // register a catch-all fixture so any read would be visible.
+ docFiles.set(".html", "<p>leaked</p>");
+ expect(getDocNoteHtml(docNoteStub("../../../../etc/passwd"))).toBeNull();
+ expect(getDocNoteHtml(docNoteStub("/etc/passwd"))).toBeNull();
+ });
+});
diff --git a/apps/server/src/services/llm/tools/doc_notes.ts b/apps/server/src/services/llm/tools/doc_notes.ts
new file mode 100644
index 0000000000..6c1924ed95
--- /dev/null
+++ b/apps/server/src/services/llm/tools/doc_notes.ts
@@ -0,0 +1,39 @@
+/**
+ * Filesystem-backed resolution of in-app help pages, for the help tools.
+ *
+ * Kept out of `@triliumnext/core`'s LLM code because it is the one tool helper
+ * that reads from `RESOURCE_DIR`: the User Guide ships as static HTML on disk,
+ * which the browser-hosted (standalone) build has no way to read synchronously.
+ */
+
+import type { BNote } from "@triliumnext/core";
+import { readFileSync } from "fs";
+import path from "path";
+
+import resourceDir from "../../resource_dir.js";
+
+/**
+ * Resolve the on-disk HTML of a `doc` note (in-app help / User Guide pages,
+ * identified by their `#docName` label), or null if it cannot be resolved.
+ * The User Guide ships in English only, so the `en` tree is always used
+ * (mirroring the client's doc_renderer behaviour).
+ */
+export function getDocNoteHtml(note: BNote): string | null {
+ const docName = note.getLabelValue("docName");
+ if (!docName) {
+ return null;
+ }
+
+ const docNotesDir = path.resolve(resourceDir.RESOURCE_DIR, "doc_notes");
+ const filePath = path.resolve(docNotesDir, "en", `${docName}.html`);
+ if (!filePath.startsWith(docNotesDir + path.sep)) {
+ // Path traversal guard — the docName label is note data, not trusted input.
+ return null;
+ }
+
+ try {
+ return readFileSync(filePath, "utf-8");
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/server/src/services/llm/tools/help_tools.spec.ts b/apps/server/src/services/llm/tools/help_tools.spec.ts
index d7ea1d78ca..4fa7ce9464 100644
--- a/apps/server/src/services/llm/tools/help_tools.spec.ts
+++ b/apps/server/src/services/llm/tools/help_tools.spec.ts
@@ -1,8 +1,15 @@
import { becca, becca_easy_mocking } from "@triliumnext/core";
+import { registerDocNoteHtmlReader } from "@triliumnext/core/src/services/llm/tools/helpers.js";
+import type { ToolDefinition } from "@triliumnext/core/src/services/llm/tools/tool_registry.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
+import { getDocNoteHtml } from "./doc_notes.js";
import { helpTools, resetHelpIndex } from "./help_tools.js";
-import type { ToolDefinition } from "./tool_registry.js";
+
+// Doc-note HTML reaches core through a host-registered reader — the server's is
+// filesystem-backed. Registering it here mirrors what services/llm/index.ts
+// does in production.
+registerDocNoteHtmlReader(getDocNoteHtml);
const { buildNote } = becca_easy_mocking;
diff --git a/apps/server/src/services/llm/tools/help_tools.ts b/apps/server/src/services/llm/tools/help_tools.ts
index c77aa2a207..977e93a399 100644
--- a/apps/server/src/services/llm/tools/help_tools.ts
+++ b/apps/server/src/services/llm/tools/help_tools.ts
@@ -11,11 +11,10 @@
*/
import { becca, type BNote } from "@triliumnext/core";
+import { getContentPreview, getDocNoteHtml } from "@triliumnext/core/src/services/llm/tools/helpers.js";
+import { defineTools } from "@triliumnext/core/src/services/llm/tools/tool_registry.js";
import { z } from "zod";
-import { getContentPreview, getDocNoteHtml } from "./helpers.js";
-import { defineTools } from "./tool_registry.js";
-
const HELP_ROOT_NOTE_ID = "_help";
const DEFAULT_SEARCH_LIMIT = 10;
/** The User Guide is only a few levels deep; bound traversal defensively. */
diff --git a/apps/server/src/services/mcp/mcp_server.spec.ts b/apps/server/src/services/mcp/mcp_server.spec.ts
index 2e02ffcfd3..9fe978be0a 100644
--- a/apps/server/src/services/mcp/mcp_server.spec.ts
+++ b/apps/server/src/services/mcp/mcp_server.spec.ts
@@ -52,7 +52,7 @@ const mutateRegistry: any = [
["mutate_tool", { description: "m", inputSchema: {}, mutates: true, execute: mutateExecute }]
];
-vi.mock("../llm/tools/index.js", () => ({
+vi.mock("../llm/index.js", () => ({
allToolRegistries: [readRegistry, mutateRegistry]
}));
diff --git a/apps/server/src/services/mcp/mcp_server.ts b/apps/server/src/services/mcp/mcp_server.ts
index 766e12bbb0..1e33e5d9f3 100644
--- a/apps/server/src/services/mcp/mcp_server.ts
+++ b/apps/server/src/services/mcp/mcp_server.ts
@@ -8,10 +8,9 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { app_info as appInfo } from "@triliumnext/core";
-
import { cls } from "@triliumnext/core";
-import { allToolRegistries } from "../llm/tools/index.js";
-import type { ToolDefinition } from "../llm/tools/tool_registry.js";
+
+import { allToolRegistries, type ToolDefinition } from "../llm/index.js";
import sql from "../sql.js";
/**
diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.json
index 8e98e5381e..e987456f65 100644
--- a/packages/trilium-core/package.json
+++ b/packages/trilium-core/package.json
@@ -7,9 +7,13 @@
"test": "echo \"Note: Core tests are run either through apps/server or apps/standalone, since they have different runtime environments.\""
},
"dependencies": {
+ "@ai-sdk/anthropic": "4.0.30",
+ "@ai-sdk/google": "4.0.34",
+ "@ai-sdk/openai": "4.0.30",
"@braintree/sanitize-url": "7.1.2",
"@triliumnext/commons": "workspace:*",
"@triliumnext/turndown-plugin-gfm": "workspace:*",
+ "ai": "7.0.52",
"async-mutex": "0.5.0",
"chardet": "2.2.0",
"color": "5.0.3",
@@ -26,7 +30,8 @@
"striptags": "3.2.0",
"sucrase": "3.35.1",
"turnish": "1.12.2",
- "xml2js": "0.6.2"
+ "xml2js": "0.6.2",
+ "zod": "4.4.3"
},
"devDependencies": {
"@types/escape-html": "1.0.4",
diff --git a/apps/server/src/services/llm/attachment_content.ts b/packages/trilium-core/src/services/llm/attachment_content.ts
similarity index 95%
rename from apps/server/src/services/llm/attachment_content.ts
rename to packages/trilium-core/src/services/llm/attachment_content.ts
index 6acf896ce5..5ad1284365 100644
--- a/apps/server/src/services/llm/attachment_content.ts
+++ b/packages/trilium-core/src/services/llm/attachment_content.ts
@@ -10,8 +10,9 @@
*/
import type { LlmMessagePart } from "@triliumnext/commons";
-import { becca, getLog } from "@triliumnext/core";
-import { decodeUtf8 } from "@triliumnext/core/src/services/utils/binary.js";
+import becca from "../../becca/becca.js";
+import { getLog } from "../../services/log.js";
+import { decodeUtf8 } from "../../services/utils/binary.js";
export type ResolvedAttachment =
| { kind: "text"; text: string }
diff --git a/apps/server/src/services/llm/chat_title.spec.ts b/packages/trilium-core/src/services/llm/chat_title.spec.ts
similarity index 85%
rename from apps/server/src/services/llm/chat_title.spec.ts
rename to packages/trilium-core/src/services/llm/chat_title.spec.ts
index d46d56de48..03ec45a4d1 100644
--- a/apps/server/src/services/llm/chat_title.spec.ts
+++ b/packages/trilium-core/src/services/llm/chat_title.spec.ts
@@ -7,13 +7,14 @@ const { getNoteMock, getProviderMock, generateTitleMock } = vi.hoisted(() => ({
generateTitleMock: vi.fn()
}));
-vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- return {
- ...actual,
- becca: { ...actual.becca, getNote: getNoteMock },
- getLog: () => ({ info: vi.fn(), error: vi.fn(), warn: vi.fn() })
- };
+vi.mock("../../becca/becca.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../becca/becca.js")>();
+ return { default: { ...actual.default, getNote: getNoteMock } };
+});
+
+vi.mock("../../services/log.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../services/log.js")>();
+ return { ...actual, getLog: () => ({ info: vi.fn(), error: vi.fn(), warn: vi.fn() }) };
});
vi.mock("./index.js", () => ({
diff --git a/apps/server/src/services/llm/chat_title.ts b/packages/trilium-core/src/services/llm/chat_title.ts
similarity index 92%
rename from apps/server/src/services/llm/chat_title.ts
rename to packages/trilium-core/src/services/llm/chat_title.ts
index 2f45bd5385..4a6e81968a 100644
--- a/apps/server/src/services/llm/chat_title.ts
+++ b/packages/trilium-core/src/services/llm/chat_title.ts
@@ -1,4 +1,5 @@
-import { becca, getLog } from "@triliumnext/core";
+import becca from "../../becca/becca.js";
+import { getLog } from "../../services/log.js";
import { t } from "i18next";
import { getProvider } from "./index.js";
diff --git a/apps/server/src/services/llm/index.spec.ts b/packages/trilium-core/src/services/llm/index.spec.ts
similarity index 91%
rename from apps/server/src/services/llm/index.spec.ts
rename to packages/trilium-core/src/services/llm/index.spec.ts
index 1ae37f2a39..87b3ddf11e 100644
--- a/apps/server/src/services/llm/index.spec.ts
+++ b/packages/trilium-core/src/services/llm/index.spec.ts
@@ -5,13 +5,14 @@ const { getOptionOrNullMock, errorMock } = vi.hoisted(() => ({
errorMock: vi.fn()
}));
-vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- return {
- ...actual,
- options: { ...actual.options, getOptionOrNull: getOptionOrNullMock },
- getLog: () => ({ error: errorMock, info: vi.fn(), warn: vi.fn() })
- };
+vi.mock("../../services/options.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../services/options.js")>();
+ return { default: { ...actual.default, getOptionOrNull: getOptionOrNullMock } };
+});
+
+vi.mock("../../services/log.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../services/log.js")>();
+ return { ...actual, getLog: () => ({ error: errorMock, info: vi.fn(), warn: vi.fn() }) };
});
/** Each provider stub records its constructor args and exposes a tagged model list. */
@@ -41,7 +42,6 @@ vi.mock("./providers/anthropic.js", () => ({ AnthropicProvider: makeProviderMock
vi.mock("./providers/openai.js", () => ({ OpenAiProvider: makeProviderMock("openai") }));
vi.mock("./providers/google.js", () => ({ GoogleProvider: makeProviderMock("google") }));
vi.mock("./providers/deepseek.js", () => ({ DeepSeekProvider: makeProviderMock("deepseek") }));
-vi.mock("./providers/claude_agent.js", () => ({ ClaudeAgentProvider: makeProviderMock("claude-agent") }));
vi.mock("./providers/local.js", () => ({ LocalProvider: makeProviderMock("local") }));
import {
@@ -50,7 +50,8 @@ import {
getProviderByType,
getSelectedModel,
hasConfiguredProviders,
- listProviderModels
+ listProviderModels,
+ registerClaudeAgentProvider
} 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.
@@ -65,10 +66,18 @@ const TWO = [
{ id: "o1", name: "My GPT", provider: "openai", apiKey: "k2" }
];
+/**
+ * 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.
+ */
+const ClaudeAgentProviderMock = makeProviderMock("claude-agent");
+
describe("llm/index provider registry", () => {
beforeEach(() => {
clearProviderCache();
vi.clearAllMocks();
+ registerClaudeAgentProvider(() => new ClaudeAgentProviderMock() as never);
});
afterEach(() => {
clearProviderCache();
diff --git a/packages/trilium-core/src/services/llm/index.ts b/packages/trilium-core/src/services/llm/index.ts
new file mode 100644
index 0000000000..fabc14f721
--- /dev/null
+++ b/packages/trilium-core/src/services/llm/index.ts
@@ -0,0 +1,215 @@
+import { getLog } from "../../services/log.js";
+import optionService from "../../services/options.js";
+
+import { AnthropicProvider } from "./providers/anthropic.js";
+import { DeepSeekProvider } from "./providers/deepseek.js";
+import { GoogleProvider } from "./providers/google.js";
+import { LocalProvider } from "./providers/local.js";
+import { OpenAiProvider } from "./providers/openai.js";
+import type { LlmProvider, ModelInfo } from "./types.js";
+
+/**
+ * Configuration for a single LLM provider instance.
+ * This matches the structure stored in the llmProviders option.
+ */
+export interface LlmProviderSetup {
+ id: string;
+ name: string;
+ provider: string;
+ apiKey: string;
+ /** Optional override for the SDK's default API endpoint (e.g. for self-hosted Ollama, vLLM, or proxies). */
+ baseURL?: string;
+ /**
+ * Models the user selected for this provider, with full metadata denormalized
+ * so the chat picker renders them without a live fetch. Absent in configs
+ * saved before model selection existed.
+ */
+ selectedModels?: ModelInfo[];
+}
+
+/** Provider type identifiers that can be instantiated, for error messages. */
+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.
+ *
+ * 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.
+ */
+let claudeAgentFactory: (() => LlmProvider) | null = null;
+
+/** Register the host's Claude Agent provider factory. See {@link claudeAgentFactory}. */
+export function registerClaudeAgentProvider(factory: () => LlmProvider) {
+ claudeAgentFactory = factory;
+}
+
+/**
+ * Instantiate a provider from its type identifier.
+ *
+ * Deliberately a switch over literal cases rather than a lookup table: the
+ * provider type is user-controlled, and looking a factory up by it — with a
+ * plain object *or* a Map — makes the invoked function a value derived from
+ * 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.
+ */
+function createProviderInstance(provider: string, apiKey: string, baseURL?: string): LlmProvider {
+ switch (provider) {
+ case "anthropic":
+ return new AnthropicProvider(apiKey, baseURL);
+ case "openai":
+ return new OpenAiProvider(apiKey, baseURL);
+ case "google":
+ return new GoogleProvider(apiKey, baseURL);
+ // OpenAI-compatible on the wire, but carded separately from the generic
+ // 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`).
+ case "claude-agent":
+ if (!claudeAgentFactory) {
+ throw new Error("The Claude Code provider is not available in this build.");
+ }
+ return claudeAgentFactory();
+ // 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.
+ case "ollama":
+ case "lmstudio":
+ case "openai-compatible":
+ return new LocalProvider(provider, apiKey, baseURL);
+ default:
+ throw new Error(`Unknown LLM provider type: ${provider}. Available: ${PROVIDER_TYPES.join(", ")}`);
+ }
+}
+
+/** Cache of instantiated providers by their config ID */
+let cachedProviders: Record<string, LlmProvider> = {};
+
+/**
+ * The raw llmProviders JSON the cache was built from. When the option changes
+ * (provider added/edited/removed in the settings), the cache self-invalidates
+ * so stale instances — and their dynamic model-list caches — are dropped.
+ */
+let cachedProvidersSource: string | null = null;
+
+/**
+ * Get configured providers from the options.
+ */
+function getConfiguredProviders(): LlmProviderSetup[] {
+ try {
+ const providersJson = optionService.getOptionOrNull("llmProviders");
+ if (providersJson !== cachedProvidersSource) {
+ cachedProviders = {};
+ cachedProvidersSource = providersJson;
+ }
+ if (!providersJson) {
+ return [];
+ }
+ return JSON.parse(providersJson) as LlmProviderSetup[];
+ } catch (e) {
+ getLog().error(`Failed to parse llmProviders option: ${e}`);
+ return [];
+ }
+}
+
+/**
+ * Get a provider instance by its configuration ID.
+ * If no ID is provided, returns the first configured provider.
+ */
+export function getProvider(providerId?: string): LlmProvider {
+ const configs = getConfiguredProviders();
+
+ if (configs.length === 0) {
+ throw new Error("No LLM providers configured. Please add a provider in Options → AI / LLM.");
+ }
+
+ // Find the requested provider or use the first one
+ const config = providerId
+ ? configs.find(c => c.id === providerId)
+ : configs[0];
+
+ if (!config) {
+ throw new Error(`LLM provider not found: ${providerId}`);
+ }
+
+ // Check cache
+ if (cachedProviders[config.id]) {
+ return cachedProviders[config.id];
+ }
+
+ // Create new provider instance
+ const provider = createProviderInstance(config.provider, config.apiKey, config.baseURL);
+ cachedProviders[config.id] = provider;
+ return provider;
+}
+
+/**
+ * Get the first configured provider of a specific type (e.g., "anthropic").
+ */
+export function getProviderByType(providerType: string): LlmProvider {
+ const configs = getConfiguredProviders();
+ const config = configs.find(c => c.provider === providerType);
+
+ if (!config) {
+ throw new Error(`No ${providerType} provider configured. Please add one in Options → AI / LLM.`);
+ }
+
+ return getProvider(config.id);
+}
+
+/**
+ * Check if any providers are configured.
+ */
+export function hasConfiguredProviders(): boolean {
+ return getConfiguredProviders().length > 0;
+}
+
+/**
+ * List the models available for a provider described by raw credentials —
+ * used by the model-selection screen during the add/edit flow, where the
+ * provider config isn't necessarily persisted yet. Instantiates the provider
+ * ad-hoc (bypassing the config cache) and queries it live — a listing failure
+ * (bad credentials, unreachable endpoint) propagates so the caller can surface
+ * it — falling back to the curated list only when the provider doesn't support
+ * dynamic listing.
+ */
+export async function listProviderModels(provider: string, apiKey: string, baseURL?: string): Promise<ModelInfo[]> {
+ const instance = createProviderInstance(provider, apiKey, baseURL);
+ const models = await (instance.listModels?.() ?? instance.getAvailableModels());
+ // Tag the default-selected set here so the recommendation rule lives on the
+ // 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) }));
+}
+
+/**
+ * Find the model a chat is targeting within its provider config's stored
+ * selection — the denormalized source of display name and pricing for the
+ * response's usage/cost, working even for dynamically discovered models the
+ * curated list doesn't know. Returns undefined when the model isn't stored.
+ */
+export function getSelectedModel(providerId: string | undefined, modelId: string): ModelInfo | undefined {
+ if (!providerId) {
+ return undefined;
+ }
+ const config = getConfiguredProviders().find(c => c.id === providerId);
+ return config?.selectedModels?.find(m => m.id === modelId);
+}
+
+/**
+ * Clear the provider cache. Call this when provider configurations change.
+ */
+export function clearProviderCache(): void {
+ cachedProviders = {};
+ cachedProvidersSource = null;
+}
+
+export type { LlmProvider, LlmProviderConfig, ModelInfo, ModelPricing } from "./types.js";
diff --git a/apps/server/src/services/llm/note_hint.ts b/packages/trilium-core/src/services/llm/note_hint.ts
similarity index 97%
rename from apps/server/src/services/llm/note_hint.ts
rename to packages/trilium-core/src/services/llm/note_hint.ts
index 8687ec9bc4..95dcfdc6ee 100644
--- a/apps/server/src/services/llm/note_hint.ts
+++ b/packages/trilium-core/src/services/llm/note_hint.ts
@@ -6,7 +6,7 @@
* to the prompt text).
*/
-import { becca } from "@triliumnext/core";
+import becca from "../../becca/becca.js";
import { dump } from "js-yaml";
import { getNoteMeta, SYSTEM_PROMPT_LIMITS } from "./tools/helpers.js";
diff --git a/apps/server/src/services/llm/providers/anthropic.spec.ts b/packages/trilium-core/src/services/llm/providers/anthropic.spec.ts
similarity index 98%
rename from apps/server/src/services/llm/providers/anthropic.spec.ts
rename to packages/trilium-core/src/services/llm/providers/anthropic.spec.ts
index 8c1c90c3c1..369f47bcc0 100644
--- a/apps/server/src/services/llm/providers/anthropic.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/anthropic.spec.ts
@@ -26,12 +26,9 @@ vi.mock("ai", async (importOriginal) => {
// The note hint embeds live note metadata into the system prompt. Partial-mock
// core so the becca lookup returns a deterministic stub note while the rest of
// core keeps its real implementation.
-vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- return {
- ...actual,
- becca: { ...actual.becca, getNote: (noteId: string) => ({ noteId } as any) }
- };
+vi.mock("../../../becca/becca.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../../becca/becca.js")>();
+ return { default: { ...actual.default, getNote: (noteId: string) => ({ noteId } as any) } };
});
vi.mock("../tools/helpers.js", async (importOriginal) => {
diff --git a/apps/server/src/services/llm/providers/anthropic.ts b/packages/trilium-core/src/services/llm/providers/anthropic.ts
similarity index 100%
rename from apps/server/src/services/llm/providers/anthropic.ts
rename to packages/trilium-core/src/services/llm/providers/anthropic.ts
diff --git a/apps/server/src/services/llm/providers/base_provider.spec.ts b/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts
similarity index 97%
rename from apps/server/src/services/llm/providers/base_provider.spec.ts
rename to packages/trilium-core/src/services/llm/providers/base_provider.spec.ts
index 34d9bef0fd..c1c94c9950 100644
--- a/apps/server/src/services/llm/providers/base_provider.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts
@@ -1,5 +1,5 @@
import type { LlmMessage, LlmMessagePart } from "@triliumnext/commons";
-import { encodeUtf8 } from "@triliumnext/core/src/services/utils/binary.js";
+import { encodeUtf8 } from "../../../services/utils/binary.js";
import type { LanguageModel } from "ai";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -23,14 +23,15 @@ vi.mock("ai", async (importOriginal) => {
return { ...actual, streamText: streamTextMock, generateText: generateTextMock };
});
-vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- return {
- ...actual,
- becca: { ...actual.becca, ...beccaStub },
- // Spreading the real logger loses prototype methods (e.g. info), so stub it too.
- getLog: () => ({ ...actual.getLog(), error: errorLogMock, info: vi.fn() })
- };
+vi.mock("../../../becca/becca.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../../becca/becca.js")>();
+ return { default: { ...actual.default, ...beccaStub } };
+});
+
+vi.mock("../../../services/log.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../../services/log.js")>();
+ // Spreading the real logger loses prototype methods (e.g. info), so stub it too.
+ return { ...actual, getLog: () => ({ ...actual.getLog(), error: errorLogMock, info: vi.fn() }) };
});
vi.mock("../tools/helpers.js", async (importOriginal) => {
diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/packages/trilium-core/src/services/llm/providers/base_provider.ts
similarity index 100%
rename from apps/server/src/services/llm/providers/base_provider.ts
rename to packages/trilium-core/src/services/llm/providers/base_provider.ts
diff --git a/apps/server/src/services/llm/providers/deepseek.spec.ts b/packages/trilium-core/src/services/llm/providers/deepseek.spec.ts
similarity index 100%
rename from apps/server/src/services/llm/providers/deepseek.spec.ts
rename to packages/trilium-core/src/services/llm/providers/deepseek.spec.ts
diff --git a/apps/server/src/services/llm/providers/deepseek.ts b/packages/trilium-core/src/services/llm/providers/deepseek.ts
similarity index 100%
rename from apps/server/src/services/llm/providers/deepseek.ts
rename to packages/trilium-core/src/services/llm/providers/deepseek.ts
diff --git a/apps/server/src/services/llm/providers/google.spec.ts b/packages/trilium-core/src/services/llm/providers/google.spec.ts
similarity index 100%
rename from apps/server/src/services/llm/providers/google.spec.ts
rename to packages/trilium-core/src/services/llm/providers/google.spec.ts
diff --git a/apps/server/src/services/llm/providers/google.ts b/packages/trilium-core/src/services/llm/providers/google.ts
similarity index 99%
rename from apps/server/src/services/llm/providers/google.ts
rename to packages/trilium-core/src/services/llm/providers/google.ts
index d7359d3c4e..6201738a50 100644
--- a/apps/server/src/services/llm/providers/google.ts
+++ b/packages/trilium-core/src/services/llm/providers/google.ts
@@ -1,6 +1,6 @@
import { createGoogleGenerativeAI, type GoogleGenerativeAIProvider } from "@ai-sdk/google";
import type { LlmMessage } from "@triliumnext/commons";
-import { getLog } from "@triliumnext/core";
+import { getLog } from "../../../services/log.js";
import { stepCountIs, streamText, type ToolSet } from "ai";
import type { LlmProviderConfig, StreamResult } from "../types.js";
diff --git a/apps/server/src/services/llm/providers/local.spec.ts b/packages/trilium-core/src/services/llm/providers/local.spec.ts
similarity index 98%
rename from apps/server/src/services/llm/providers/local.spec.ts
rename to packages/trilium-core/src/services/llm/providers/local.spec.ts
index e697fb10ba..96ed95d0da 100644
--- a/apps/server/src/services/llm/providers/local.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/local.spec.ts
@@ -1,11 +1,8 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- return {
- ...actual,
- getLog: () => ({ info: vi.fn(), error: vi.fn(), warn: vi.fn() })
- };
+vi.mock("../../../services/log.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../../services/log.js")>();
+ return { ...actual, getLog: () => ({ info: vi.fn(), error: vi.fn(), warn: vi.fn() }) };
});
const createOpenAiMock = vi.fn();
diff --git a/apps/server/src/services/llm/providers/local.ts b/packages/trilium-core/src/services/llm/providers/local.ts
similarity index 99%
rename from apps/server/src/services/llm/providers/local.ts
rename to packages/trilium-core/src/services/llm/providers/local.ts
index 06e71750ef..4cf1485f4f 100644
--- a/apps/server/src/services/llm/providers/local.ts
+++ b/packages/trilium-core/src/services/llm/providers/local.ts
@@ -15,7 +15,7 @@
*/
import { createOpenAI, type OpenAIProvider as OpenAISDKProvider } from "@ai-sdk/openai";
-import { getLog } from "@triliumnext/core";
+import { getLog } from "../../../services/log.js";
import type { ModelInfo, ModelPricing } from "../types.js";
import { BaseProvider, type RemoteModel } from "./base_provider.js";
diff --git a/apps/server/src/services/llm/providers/model_prices.json b/packages/trilium-core/src/services/llm/providers/model_prices.json
similarity index 100%
rename from apps/server/src/services/llm/providers/model_prices.json
rename to packages/trilium-core/src/services/llm/providers/model_prices.json
diff --git a/apps/server/src/services/llm/providers/openai.spec.ts b/packages/trilium-core/src/services/llm/providers/openai.spec.ts
similarity index 100%
rename from apps/server/src/services/llm/providers/openai.spec.ts
rename to packages/trilium-core/src/services/llm/providers/openai.spec.ts
diff --git a/apps/server/src/services/llm/providers/openai.ts b/packages/trilium-core/src/services/llm/providers/openai.ts
similarity index 100%
rename from apps/server/src/services/llm/providers/openai.ts
rename to packages/trilium-core/src/services/llm/providers/openai.ts
diff --git a/apps/server/src/services/llm/stream.spec.ts b/packages/trilium-core/src/services/llm/stream.spec.ts
similarity index 100%
rename from apps/server/src/services/llm/stream.spec.ts
rename to packages/trilium-core/src/services/llm/stream.spec.ts
diff --git a/apps/server/src/services/llm/stream.ts b/packages/trilium-core/src/services/llm/stream.ts
similarity index 100%
rename from apps/server/src/services/llm/stream.ts
rename to packages/trilium-core/src/services/llm/stream.ts
diff --git a/apps/server/src/services/llm/system_prompt.spec.ts b/packages/trilium-core/src/services/llm/system_prompt.spec.ts
similarity index 92%
rename from apps/server/src/services/llm/system_prompt.spec.ts
rename to packages/trilium-core/src/services/llm/system_prompt.spec.ts
index 6635d1ce84..30c3da6e12 100644
--- a/apps/server/src/services/llm/system_prompt.spec.ts
+++ b/packages/trilium-core/src/services/llm/system_prompt.spec.ts
@@ -4,10 +4,10 @@ import { describe, expect, it, vi } from "vitest";
// to inject custom task states (the namespace re-export is frozen, so a plain
// spy can't patch it).
const getTaskStatesMock = vi.hoisted(() => vi.fn());
-vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- getTaskStatesMock.mockImplementation(actual.task_states.getTaskStates);
- return { ...actual, task_states: { ...actual.task_states, getTaskStates: getTaskStatesMock } };
+vi.mock("../../services/task_states.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../services/task_states.js")>();
+ getTaskStatesMock.mockImplementation(actual.getTaskStates);
+ return { ...actual, getTaskStates: getTaskStatesMock };
});
import { buildSystemPrompt } from "./system_prompt.js";
diff --git a/apps/server/src/services/llm/system_prompt.ts b/packages/trilium-core/src/services/llm/system_prompt.ts
similarity index 99%
rename from apps/server/src/services/llm/system_prompt.ts
rename to packages/trilium-core/src/services/llm/system_prompt.ts
index 877baea305..6cf2b74d56 100644
--- a/apps/server/src/services/llm/system_prompt.ts
+++ b/packages/trilium-core/src/services/llm/system_prompt.ts
@@ -10,7 +10,7 @@
*/
import { isAnchorState, type LlmMessage } from "@triliumnext/commons";
-import { task_states } from "@triliumnext/core";
+import * as task_states from "../../services/task_states.js";
import type { LlmProviderConfig } from "./types.js";
diff --git a/apps/server/src/services/llm/tools/attachment_tools.spec.ts b/packages/trilium-core/src/services/llm/tools/attachment_tools.spec.ts
similarity index 94%
rename from apps/server/src/services/llm/tools/attachment_tools.spec.ts
rename to packages/trilium-core/src/services/llm/tools/attachment_tools.spec.ts
index e96a986fda..ecae0e25f2 100644
--- a/apps/server/src/services/llm/tools/attachment_tools.spec.ts
+++ b/packages/trilium-core/src/services/llm/tools/attachment_tools.spec.ts
@@ -7,12 +7,9 @@ const { getAttachmentMock, getBlobMock } = vi.hoisted(() => ({
// Attachment + blob lookups go through SQL in the real becca; partial-mock core
// so these two return deterministic stubs while the rest of core is untouched.
-vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- return {
- ...actual,
- becca: { ...actual.becca, getAttachment: getAttachmentMock, getBlob: getBlobMock }
- };
+vi.mock("../../../becca/becca.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../../becca/becca.js")>();
+ return { default: { ...actual.default, getAttachment: getAttachmentMock, getBlob: getBlobMock } };
});
import { attachmentTools } from "./attachment_tools.js";
diff --git a/apps/server/src/services/llm/tools/attachment_tools.ts b/packages/trilium-core/src/services/llm/tools/attachment_tools.ts
similarity index 95%
rename from apps/server/src/services/llm/tools/attachment_tools.ts
rename to packages/trilium-core/src/services/llm/tools/attachment_tools.ts
index a69e259ff4..e5d57681a1 100644
--- a/apps/server/src/services/llm/tools/attachment_tools.ts
+++ b/packages/trilium-core/src/services/llm/tools/attachment_tools.ts
@@ -2,10 +2,10 @@
* LLM tools for attachment operations.
*/
-import { unwrapStringOrBuffer } from "@triliumnext/core/src/services/utils/binary.js";
+import { unwrapStringOrBuffer } from "../../../services/utils/binary.js";
import { z } from "zod";
-import { becca } from "@triliumnext/core";
+import becca from "../../../becca/becca.js";
import { defineTools } from "./tool_registry.js";
export const attachmentTools = defineTools({
diff --git a/apps/server/src/services/llm/tools/attribute_tools.spec.ts b/packages/trilium-core/src/services/llm/tools/attribute_tools.spec.ts
similarity index 97%
rename from apps/server/src/services/llm/tools/attribute_tools.spec.ts
rename to packages/trilium-core/src/services/llm/tools/attribute_tools.spec.ts
index a0f10d03a0..7ab0a1070f 100644
--- a/apps/server/src/services/llm/tools/attribute_tools.spec.ts
+++ b/packages/trilium-core/src/services/llm/tools/attribute_tools.spec.ts
@@ -1,4 +1,6 @@
-import { becca, cls, note_service as noteService } from "@triliumnext/core";
+import becca from "../../../becca/becca.js";
+import * as cls from "../../../services/context.js";
+import noteService from "../../../services/notes.js";
import { beforeAll, describe, expect, it } from "vitest";
import { attributeTools } from "./attribute_tools.js";
diff --git a/apps/server/src/services/llm/tools/attribute_tools.ts b/packages/trilium-core/src/services/llm/tools/attribute_tools.ts
similarity index 97%
rename from apps/server/src/services/llm/tools/attribute_tools.ts
rename to packages/trilium-core/src/services/llm/tools/attribute_tools.ts
index 25d8db5ecf..2eb4f54614 100644
--- a/apps/server/src/services/llm/tools/attribute_tools.ts
+++ b/packages/trilium-core/src/services/llm/tools/attribute_tools.ts
@@ -2,7 +2,8 @@
* LLM tools for attribute operations (get, set, delete labels/relations).
*/
-import { attributes as attributeService, becca } from "@triliumnext/core";
+import attributeService from "../../../services/attributes.js";
+import becca from "../../../becca/becca.js";
import { z } from "zod";
import { flag } from "./helpers.js";
diff --git a/apps/server/src/services/llm/tools/helpers.spec.ts b/packages/trilium-core/src/services/llm/tools/helpers.spec.ts
similarity index 83%
rename from apps/server/src/services/llm/tools/helpers.spec.ts
rename to packages/trilium-core/src/services/llm/tools/helpers.spec.ts
index fb8ecf796b..054d7d3c51 100644
--- a/apps/server/src/services/llm/tools/helpers.spec.ts
+++ b/packages/trilium-core/src/services/llm/tools/helpers.spec.ts
@@ -1,4 +1,5 @@
-import type { BAttachment, BNote } from "@triliumnext/core";
+import type BAttachment from "../../../becca/entities/battachment.js";
+import type BNote from "../../../becca/entities/bnote.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
const getBlobMock = vi.hoisted(() => vi.fn());
@@ -6,33 +7,9 @@ const getBlobMock = vi.hoisted(() => vi.fn());
// getContentPreview / getNoteContentForLlm consult becca.getBlob (SQL-backed);
// partial-mock core so it returns deterministic blobs while markdown
// import/export services keep their real implementations.
-vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- return {
- ...actual,
- becca: { ...actual.becca, getBlob: getBlobMock }
- };
-});
-
-/** Fake on-disk help pages for getDocNoteHtml: path suffix → HTML content. */
-const docFiles = vi.hoisted(() => new Map<string, string>());
-
-// Doc notes read their HTML from disk — serve them from the docFiles fixture
-// map and pass every other path through to the real fs.
-vi.mock("fs", async (importOriginal) => {
- const actual = await importOriginal<typeof import("fs")>();
- const readFileSync = ((filePath: unknown, ...rest: unknown[]) => {
- const pathStr = String(filePath);
- for (const [suffix, content] of docFiles) {
- if (pathStr.endsWith(suffix)) return content;
- }
- if (pathStr.includes("doc_notes")) {
- throw new Error(`ENOENT: ${pathStr}`);
- }
- return (actual.readFileSync as (...args: unknown[]) => unknown)(filePath, ...rest);
- }) as typeof actual.readFileSync;
- const mocked = { ...actual, readFileSync };
- return { ...mocked, default: mocked };
+vi.mock("../../../becca/becca.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../../becca/becca.js")>();
+ return { default: { ...actual.default, getBlob: getBlobMock } };
});
import {
@@ -43,6 +20,7 @@ import {
getDocNoteHtml,
getNoteContentForLlm,
getNoteMeta,
+ registerDocNoteHtmlReader,
setNoteContentFromLlm
} from "./helpers.js";
@@ -131,34 +109,25 @@ describe("getNoteContentForLlm", () => {
});
});
-describe("getDocNoteHtml / doc notes", () => {
- beforeEach(() => docFiles.clear());
-
- it("reads the page HTML from disk under doc_notes/en", () => {
- docFiles.set("Cloning Notes.html", "<h2>Cloning</h2>");
- expect(getDocNoteHtml(docNoteStub("User Guide/User Guide/Cloning Notes"))).toBe("<h2>Cloning</h2>");
- });
+describe("doc notes", () => {
+ beforeEach(() => registerDocNoteHtmlReader(() => null));
- it("returns null without a docName label, on a missing file, and on path traversal attempts", () => {
+ it("resolves a doc note's HTML through the registered reader", () => {
+ registerDocNoteHtmlReader(note => (note.getLabelValue("docName") ? "<h2>Cloning</h2>" : null));
+ expect(getDocNoteHtml(docNoteStub("User Guide/Cloning Notes"))).toBe("<h2>Cloning</h2>");
expect(getDocNoteHtml(docNoteStub(null))).toBeNull();
- expect(getDocNoteHtml(docNoteStub("User Guide/Nonexistent Page"))).toBeNull();
- // Traversal attempts must be rejected before touching the filesystem —
- // register a catch-all fixture so any read would be visible.
- docFiles.set(".html", "<p>leaked</p>");
- expect(getDocNoteHtml(docNoteStub("../../../../etc/passwd"))).toBeNull();
- expect(getDocNoteHtml(docNoteStub("/etc/passwd"))).toBeNull();
});
- it("getNoteContentForLlm converts doc-note HTML to Markdown", () => {
- docFiles.set("Cloning Notes.html", "<h2>Cloning</h2><p>Place a note in two locations.</p>");
- const content = getNoteContentForLlm(docNoteStub("User Guide/User Guide/Cloning Notes"));
+ it("getNoteContentForLlm converts the reader's HTML to Markdown", () => {
+ registerDocNoteHtmlReader(() => "<h2>Cloning</h2><p>Place a note in two locations.</p>");
+ const content = getNoteContentForLlm(docNoteStub("User Guide/Cloning Notes"));
expect(content).toContain("## Cloning");
expect(content).toContain("Place a note in two locations.");
});
- it("getNoteContentForLlm and getContentPreview degrade gracefully for unresolvable doc notes", () => {
+ it("degrades gracefully when no reader is registered — as in the browser build", () => {
getBlobMock.mockReturnValue(null);
- const note = docNoteStub(null);
+ const note = docNoteStub("User Guide/Cloning Notes");
expect(getNoteContentForLlm(note)).toBe("[doc content not available]");
expect(getContentPreview(note)).toBeNull();
});
diff --git a/apps/server/src/services/llm/tools/helpers.ts b/packages/trilium-core/src/services/llm/tools/helpers.ts
similarity index 87%
rename from apps/server/src/services/llm/tools/helpers.ts
rename to packages/trilium-core/src/services/llm/tools/helpers.ts
index 43ca1bff9f..5bc1fb3bb6 100644
--- a/apps/server/src/services/llm/tools/helpers.ts
+++ b/packages/trilium-core/src/services/llm/tools/helpers.ts
@@ -2,12 +2,12 @@
* Shared helpers for LLM tools — content conversion, metadata building, and previews.
*/
-import { type BAttachment, becca, type BNote, markdownExportService as markdownExport, markdownImportService as markdownImport } from "@triliumnext/core";
-import { unwrapStringOrBuffer } from "@triliumnext/core/src/services/utils/binary.js";
-import { readFileSync } from "fs";
-import path from "path";
-
-import resourceDir from "../../resource_dir.js";
+import type BAttachment from "../../../becca/entities/battachment.js";
+import becca from "../../../becca/becca.js";
+import type BNote from "../../../becca/entities/bnote.js";
+import markdownExport from "../../../services/export/markdown.js";
+import markdownImport from "../../../services/import/markdown.js";
+import { unwrapStringOrBuffer } from "../../../services/utils/binary.js";
const CONTENT_PREVIEW_MAX_LENGTH = 500;
const ATTACHMENT_PREVIEW_MAX_LENGTH = 200;
@@ -17,6 +17,29 @@ const CONTENT_PREVIEW_SIZE_THRESHOLD = 10_000;
/** Note IDs that must not be deleted, moved, or cloned by the LLM. */
export const PROTECTED_SYSTEM_NOTES = new Set(["root", "_hidden", "_share", "_lbRoot", "_globalNoteMap"]);
+/** Host-provided reader for doc-note HTML. See {@link registerDocNoteHtmlReader}. */
+let docNoteHtmlReader: ((note: BNote) => string | null) | null = null;
+
+/**
+ * Register the host's reader for in-app help pages.
+ *
+ * `doc` notes (the User Guide) keep no content in the database — their HTML
+ * ships as static files, which the server reads off disk. The browser-hosted
+ * build has no synchronous way to do that, so hosts that can supply it register
+ * a reader here and the rest simply report the content as unavailable.
+ */
+export function registerDocNoteHtmlReader(reader: (note: BNote) => string | null) {
+ docNoteHtmlReader = reader;
+}
+
+/**
+ * Resolve the HTML of a `doc` note via the registered reader, or null when no
+ * reader is registered or it cannot resolve the page.
+ */
+export function getDocNoteHtml(note: BNote): string | null {
+ return docNoteHtmlReader?.(note) ?? null;
+}
+
/**
* Return `true` if the value is truthy, otherwise `undefined`.
* Since `undefined` values are omitted from JSON serialization,
@@ -54,32 +77,6 @@ export function getNoteContentForLlm(note: BNote) {
return content;
}
-/**
- * Resolve the on-disk HTML of a `doc` note (in-app help / User Guide pages,
- * identified by their `#docName` label), or null if it cannot be resolved.
- * The User Guide ships in English only, so the `en` tree is always used
- * (mirroring the client's doc_renderer behaviour).
- */
-export function getDocNoteHtml(note: BNote): string | null {
- const docName = note.getLabelValue("docName");
- if (!docName) {
- return null;
- }
-
- const docNotesDir = path.resolve(resourceDir.RESOURCE_DIR, "doc_notes");
- const filePath = path.resolve(docNotesDir, "en", `${docName}.html`);
- if (!filePath.startsWith(docNotesDir + path.sep)) {
- // Path traversal guard — the docName label is note data, not trusted input.
- return null;
- }
-
- try {
- return readFileSync(filePath, "utf-8");
- } catch {
- return null;
- }
-}
-
/**
* Convert LLM-provided content to a format suitable for storage.
* For text notes, converts Markdown to HTML.
diff --git a/apps/server/src/services/llm/tools/hierarchy_tools.spec.ts b/packages/trilium-core/src/services/llm/tools/hierarchy_tools.spec.ts
similarity index 98%
rename from apps/server/src/services/llm/tools/hierarchy_tools.spec.ts
rename to packages/trilium-core/src/services/llm/tools/hierarchy_tools.spec.ts
index 2b65cd08f5..26bd5a470c 100644
--- a/apps/server/src/services/llm/tools/hierarchy_tools.spec.ts
+++ b/packages/trilium-core/src/services/llm/tools/hierarchy_tools.spec.ts
@@ -1,4 +1,5 @@
-import { cls, note_service as noteService } from "@triliumnext/core";
+import * as cls from "../../../services/context.js";
+import noteService from "../../../services/notes.js";
import { describe, expect, it } from "vitest";
import { hierarchyTools } from "./hierarchy_tools.js";
diff --git a/apps/server/src/services/llm/tools/hierarchy_tools.ts b/packages/trilium-core/src/services/llm/tools/hierarchy_tools.ts
similarity index 97%
rename from apps/server/src/services/llm/tools/hierarchy_tools.ts
rename to packages/trilium-core/src/services/llm/tools/hierarchy_tools.ts
index fd06b27863..e6cf4c6450 100644
--- a/apps/server/src/services/llm/tools/hierarchy_tools.ts
+++ b/packages/trilium-core/src/services/llm/tools/hierarchy_tools.ts
@@ -2,7 +2,9 @@
* LLM tools for navigating the note hierarchy (tree structure, branches).
*/
-import { becca, type BNote, cloning as cloningService } from "@triliumnext/core";
+import becca from "../../../becca/becca.js";
+import type BNote from "../../../becca/entities/bnote.js";
+import cloningService from "../../../services/cloning.js";
import { z } from "zod";
import branchService from "../../branches.js";
diff --git a/apps/server/src/services/llm/tools/icon_tools.spec.ts b/packages/trilium-core/src/services/llm/tools/icon_tools.spec.ts
similarity index 100%
rename from apps/server/src/services/llm/tools/icon_tools.spec.ts
rename to packages/trilium-core/src/services/llm/tools/icon_tools.spec.ts
diff --git a/apps/server/src/services/llm/tools/icon_tools.ts b/packages/trilium-core/src/services/llm/tools/icon_tools.ts
similarity index 98%
rename from apps/server/src/services/llm/tools/icon_tools.ts
rename to packages/trilium-core/src/services/llm/tools/icon_tools.ts
index 1a2859e4e7..eff7c4c8ac 100644
--- a/apps/server/src/services/llm/tools/icon_tools.ts
+++ b/packages/trilium-core/src/services/llm/tools/icon_tools.ts
@@ -2,7 +2,7 @@
* LLM tools for finding note icons across the available icon packs.
*/
-import { icon_packs } from "@triliumnext/core";
+import * as icon_packs from "../../../services/icon_packs.js";
import { z } from "zod";
import { defineTools } from "./tool_registry.js";
diff --git a/apps/server/src/services/llm/tools/index.ts b/packages/trilium-core/src/services/llm/tools/index.ts
similarity index 50%
rename from apps/server/src/services/llm/tools/index.ts
rename to packages/trilium-core/src/services/llm/tools/index.ts
index 2c0f6001e6..5401f38dec 100644
--- a/apps/server/src/services/llm/tools/index.ts
+++ b/packages/trilium-core/src/services/llm/tools/index.ts
@@ -3,32 +3,45 @@
* These reuse the same logic as ETAPI without any HTTP overhead.
*/
-export { skillTools } from "../skills/index.js";
export { attachmentTools } from "./attachment_tools.js";
export { attributeTools } from "./attribute_tools.js";
-export { helpTools } from "./help_tools.js";
export { hierarchyTools } from "./hierarchy_tools.js";
export { iconTools } from "./icon_tools.js";
export { noteTools } from "./note_tools.js";
export type { ToolDefinition } from "./tool_registry.js";
export { ToolRegistry } from "./tool_registry.js";
-import { skillTools } from "../skills/index.js";
import { attachmentTools } from "./attachment_tools.js";
import { attributeTools } from "./attribute_tools.js";
-import { helpTools } from "./help_tools.js";
import { hierarchyTools } from "./hierarchy_tools.js";
import { iconTools } from "./icon_tools.js";
import { noteTools } from "./note_tools.js";
import type { ToolRegistry } from "./tool_registry.js";
-/** All tool registries, for consumers that need to iterate every tool (e.g. MCP). */
+/**
+ * All tool registries, for consumers that need to iterate every tool (e.g. MCP).
+ *
+ * Registries whose tools depend on a runtime core cannot provide — currently
+ * the help and skill tools, which read the User Guide and the skill sheets off
+ * disk — are contributed by the host via {@link registerToolRegistry} rather
+ * than listed here, so the browser-hosted build simply runs without them.
+ */
export const allToolRegistries: ToolRegistry[] = [
noteTools,
attributeTools,
attachmentTools,
hierarchyTools,
- helpTools,
- iconTools,
- skillTools
+ iconTools
];
+
+/**
+ * Add a host-provided tool registry. Must be called before the first chat turn
+ * or MCP tool listing, both of which read {@link allToolRegistries} eagerly.
+ * Registering the same registry twice is a no-op, so a host that initialises
+ * more than once (tests, Electron reloads) does not duplicate its tools.
+ */
+export function registerToolRegistry(registry: ToolRegistry) {
+ if (!allToolRegistries.includes(registry)) {
+ allToolRegistries.push(registry);
+ }
+}
diff --git a/apps/server/src/services/llm/tools/note_tools.spec.ts b/packages/trilium-core/src/services/llm/tools/note_tools.spec.ts
similarity index 95%
rename from apps/server/src/services/llm/tools/note_tools.spec.ts
rename to packages/trilium-core/src/services/llm/tools/note_tools.spec.ts
index c07a1983f6..6882f404b0 100644
--- a/apps/server/src/services/llm/tools/note_tools.spec.ts
+++ b/packages/trilium-core/src/services/llm/tools/note_tools.spec.ts
@@ -1,4 +1,5 @@
-import { becca, becca_easy_mocking } from "@triliumnext/core";
+import becca from "../../../becca/becca.js";
+import * as becca_easy_mocking from "../../../test/becca_easy_mocking.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { noteTools } from "./note_tools.js";
@@ -8,18 +9,14 @@ const { buildNote } = becca_easy_mocking;
const findResultsMock = vi.hoisted(() => vi.fn());
-vi.mock("@triliumnext/core", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@triliumnext/core")>();
- return {
- ...actual,
- note_service: {
- createNewNote: vi.fn()
- },
- search: {
- ...actual.search,
- findResultsWithQuery: findResultsMock
- }
- };
+vi.mock("../../../services/notes.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../../services/notes.js")>();
+ return { ...actual, default: { createNewNote: vi.fn() } };
+});
+
+vi.mock("../../../services/search/services/search.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../../services/search/services/search.js")>();
+ return { default: { ...actual.default, findResultsWithQuery: findResultsMock } };
});
function getTool(name: string): ToolDefinition {
@@ -212,7 +209,7 @@ describe("note_tools — write tools return post-write content", () => {
const newNote = buildNote({ id: "new1", type: "code", mime: "text/plain", content: "hello" });
withMutableContent(newNote, "hello");
- const { note_service: noteService } = await import("@triliumnext/core");
+ const { default: noteService } = await import("../../../services/notes.js");
vi.mocked(noteService.createNewNote).mockReturnValue({ note: newNote } as ReturnType<typeof noteService.createNewNote>);
const result = getTool("create_note").execute({
@@ -246,7 +243,7 @@ describe("note_tools — write tools return post-write content", () => {
it("renders Markdown to HTML for text notes and surfaces creation errors", async () => {
buildNote({ id: "tparent", title: "TParent" });
- const { note_service: noteService } = await import("@triliumnext/core");
+ const { default: noteService } = await import("../../../services/notes.js");
const created = buildNote({ id: "tnew", type: "text", content: "<h2>Hi</h2>" });
withMutableContent(created, "<h2>Hi</h2>");
diff --git a/apps/server/src/services/llm/tools/note_tools.ts b/packages/trilium-core/src/services/llm/tools/note_tools.ts
similarity index 97%
rename from apps/server/src/services/llm/tools/note_tools.ts
rename to packages/trilium-core/src/services/llm/tools/note_tools.ts
index c2eec8fd66..0cfa4a585f 100644
--- a/apps/server/src/services/llm/tools/note_tools.ts
+++ b/packages/trilium-core/src/services/llm/tools/note_tools.ts
@@ -2,7 +2,12 @@
* LLM tools for note operations (search, read, create, update, append).
*/
-import { becca, markdownImportService as markdownImport, note_service as noteService, search as searchService, SearchContext, TaskContext } from "@triliumnext/core";
+import becca from "../../../becca/becca.js";
+import markdownImport from "../../../services/import/markdown.js";
+import noteService from "../../../services/notes.js";
+import searchService from "../../../services/search/services/search.js";
+import SearchContext from "../../../services/search/search_context.js";
+import TaskContext from "../../../services/task_context.js";
import { z } from "zod";
import { applyTextEdits, getContentPreview, getNoteContentForLlm, getNoteMeta, PROTECTED_SYSTEM_NOTES, setNoteContentFromLlm,TOOL_LIMITS } from "./helpers.js";
diff --git a/apps/server/src/services/llm/tools/tool_registry.spec.ts b/packages/trilium-core/src/services/llm/tools/tool_registry.spec.ts
similarity index 96%
rename from apps/server/src/services/llm/tools/tool_registry.spec.ts
rename to packages/trilium-core/src/services/llm/tools/tool_registry.spec.ts
index 1d958188fe..4f6a6b7ad6 100644
--- a/apps/server/src/services/llm/tools/tool_registry.spec.ts
+++ b/packages/trilium-core/src/services/llm/tools/tool_registry.spec.ts
@@ -5,8 +5,8 @@ const transactionalMock = vi.hoisted(() => vi.fn(<T>(cb: () => T) => cb()));
// toToolSet wraps mutating tools in sql.transactional; stub it to just run the
// callback so we can assert the wrapping happens without a real transaction.
-vi.mock("../../sql.js", () => ({
- default: { transactional: transactionalMock }
+vi.mock("../../sql/index.js", () => ({
+ getSql: () => ({ transactional: transactionalMock })
}));
import { allToolRegistries } from "./index.js";
diff --git a/apps/server/src/services/llm/tools/tool_registry.ts b/packages/trilium-core/src/services/llm/tools/tool_registry.ts
similarity index 95%
rename from apps/server/src/services/llm/tools/tool_registry.ts
rename to packages/trilium-core/src/services/llm/tools/tool_registry.ts
index 35fc225182..e585ab7e60 100644
--- a/apps/server/src/services/llm/tools/tool_registry.ts
+++ b/packages/trilium-core/src/services/llm/tools/tool_registry.ts
@@ -12,7 +12,7 @@ import { tool } from "ai";
import type { z } from "zod";
import type { ToolSet } from "ai";
-import sql from "../../sql.js";
+import { getSql } from "../../sql/index.js";
/**
* Type constraint that rejects Promises at compile time.
@@ -63,7 +63,7 @@ export class ToolRegistry implements Iterable<[string, ToolDefinition]> {
const set: ToolSet = {};
for (const [name, def] of this) {
const execute = def.mutates
- ? (args: unknown) => sql.transactional(() => def.execute(args))
+ ? (args: unknown) => getSql().transactional(() => def.execute(args))
: def.execute;
set[name] = tool({
diff --git a/apps/server/src/services/llm/types.ts b/packages/trilium-core/src/services/llm/types.ts
similarity index 100%
rename from apps/server/src/services/llm/types.ts
rename to packages/trilium-core/src/services/llm/types.ts
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 36e0e1b375..7e0e035910 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1374,6 +1374,15 @@ importers:
packages/trilium-core:
dependencies:
+ '@ai-sdk/anthropic':
+ specifier: 4.0.30
+ version: 4.0.30([email protected])
+ '@ai-sdk/google':
+ specifier: 4.0.34
+ version: 4.0.34([email protected])
+ '@ai-sdk/openai':
+ specifier: 4.0.30
+ version: 4.0.30([email protected])
'@braintree/sanitize-url':
specifier: 7.1.2
version: 7.1.2
@@ -1383,6 +1392,9 @@ importers:
'@triliumnext/turndown-plugin-gfm':
specifier: workspace:*
version: link:../turndown-plugin-gfm
+ ai:
+ specifier: 7.0.52
+ version: 7.0.52([email protected])
async-mutex:
specifier: 0.5.0
version: 0.5.0
@@ -1434,6 +1446,9 @@ importers:
xml2js:
specifier: 0.6.2
version: 0.6.2
+ zod:
+ specifier: '>=4.0.0'
+ version: 4.4.3
devDependencies:
'@types/escape-html':
specifier: 1.0.4