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): make the skill sheets available to the standalone build
Elian Doran431f901667f6
diff --git a/apps/desktop/scripts/build.ts b/apps/desktop/scripts/build.tsindex b4935c276c..1dd3161b15 100644--- a/apps/desktop/scripts/build.ts+++ b/apps/desktop/scripts/build.ts@@ -22,6 +22,9 @@ async function main() {build.copy("src/assets", "assets/");build.copy("/apps/server/src/assets", "assets/");build.copy("/packages/trilium-core/src/assets/schema.sql", "assets/schema.sql");+ // The LLM skill sheets moved to core with the rest of the stack, but the+ // Node hosts still read them from RESOURCE_DIR. See server core_assets.ts.+ build.copy("/packages/trilium-core/src/assets/llm/skills", "assets/llm/skills/");build.triggerBuildAndCopyTo("packages/share-theme", "share-theme/assets/");build.copy("/packages/share-theme/src/templates", "share-theme/templates/");diff --git a/apps/server/scripts/build.ts b/apps/server/scripts/build.tsindex d2f32d8e4a..2a636d7d57 100644--- a/apps/server/scripts/build.ts+++ b/apps/server/scripts/build.ts@@ -16,6 +16,9 @@ async function main() {// alongside the server's own assets and read it via RESOURCE_DIR at// runtime. See main.ts.build.copy("/packages/trilium-core/src/assets/schema.sql", "assets/schema.sql");+ // Same story for the LLM skill sheets: core owns them, the server reads them+ // from RESOURCE_DIR at runtime. See core_assets.ts.+ build.copy("/packages/trilium-core/src/assets/llm/skills", "assets/llm/skills/");build.triggerBuildAndCopyTo("packages/share-theme", "share-theme/assets/");build.copy("/packages/share-theme/src/templates", "share-theme/templates/");diff --git a/apps/server/src/core_assets.spec.ts b/apps/server/src/core_assets.spec.tsindex 602ada4230..b70482da91 100644--- a/apps/server/src/core_assets.spec.ts+++ b/apps/server/src/core_assets.spec.ts@@ -10,7 +10,7 @@ const mockFs = {vi.mock("fs", () => ({ default: mockFs, ...mockFs }));vi.mock("./services/resource_dir.js", () => ({ RESOURCE_DIR: "/test/res" }));-const { loadCoreSchema } = await import("./core_assets.js");+const { loadCoreSchema, loadSkillSheet } = await import("./core_assets.js");afterEach(() => vi.clearAllMocks());@@ -35,3 +35,40 @@ describe("loadCoreSchema", () => {expect(String(resolvedPath)).toContain("trilium-core");});});++describe("loadSkillSheet", () => {+ it("reads the bundled sheet from the resource dir in production", () => {+ mockFs.existsSync.mockReturnValue(true);+ mockFs.readFileSync.mockReturnValue("# Search syntax");++ expect(loadSkillSheet("search_syntax.md")).toBe("# Search syntax");+ expect(mockFs.readFileSync)+ .toHaveBeenCalledWith(path.join("/test/res", "llm", "skills", "search_syntax.md"), "utf-8");+ });++ it("falls back to the core package sheet in dev, where nothing has been copied", () => {+ mockFs.existsSync.mockReturnValue(false);+ mockFs.readFileSync.mockReturnValue("# Search syntax");++ expect(loadSkillSheet("search_syntax.md")).toBe("# Search syntax");+ const [resolvedPath] = mockFs.readFileSync.mock.calls[0];+ expect(String(resolvedPath)).toContain(path.join("trilium-core", "src", "assets", "llm", "skills"));+ });++ it("refuses a name that could climb out of the skills directory", () => {+ // The name comes from core's catalog rather than from a user, but it is+ // interpolated into a path, so it is checked where it is used.+ for (const name of [ "../../../etc/passwd", "nested/sheet.md", "..\\windows.md" ]) {+ expect(loadSkillSheet(name), name).toBeNull();+ }+ expect(mockFs.readFileSync).not.toHaveBeenCalled();+ });++ it("answers with nothing rather than throwing when the sheet cannot be read", () => {+ // One missing sheet costs the model a tool call; it must not fail the chat.+ mockFs.existsSync.mockReturnValue(true);+ mockFs.readFileSync.mockImplementation(() => { throw new Error("EACCES"); });++ expect(loadSkillSheet("search_syntax.md")).toBeNull();+ });+});diff --git a/apps/server/src/core_assets.ts b/apps/server/src/core_assets.tsindex 6528a3f970..a4f1b8b301 100644--- a/apps/server/src/core_assets.ts+++ b/apps/server/src/core_assets.ts@@ -22,3 +22,29 @@ export function loadCoreSchema(): string {}return fs.readFileSync(require.resolve("@triliumnext/core/src/assets/schema.sql"), "utf-8");}++/**+ * Reads one of the LLM skill sheets, by the file name core's catalog gives, on+ * the same two paths as {@link loadCoreSchema}: copied under RESOURCE_DIR by the+ * build, resolved through the workspace symlink when running from source.+ *+ * Returns null rather than throwing — a missing sheet costs the model one tool+ * call, and is not worth failing a chat over.+ */+export function loadSkillSheet(file: string): string | null {+ // The name comes from core's own catalog, but it is interpolated into a path,+ // so anything that could climb out of the directory is refused outright.+ if (file.includes("/") || file.includes("\\") || file.includes("..")) {+ return null;+ }++ const productionPath = path.join(RESOURCE_DIR, "llm", "skills", file);+ try {+ if (fs.existsSync(productionPath)) {+ return fs.readFileSync(productionPath, "utf-8");+ }+ return fs.readFileSync(require.resolve(`@triliumnext/core/src/assets/llm/skills/${file}`), "utf-8");+ } catch {+ return null;+ }+}diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.tsindex f458eda7a2..99715641db 100644--- a/apps/server/src/services/llm/index.spec.ts+++ b/apps/server/src/services/llm/index.spec.ts@@ -3,12 +3,16 @@ import { describe, expect, it, vi } from "vitest";const registrations = vi.hoisted(() => ({claudeAgentFactory: undefined as (() => unknown) | undefined,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; }}));+vi.mock("@triliumnext/core/src/services/llm/skills.js", () => ({+ registerSkillReader: (reader: (file: string) => string | null) => { registrations.skillReader = reader; }+}));vi.mock("@triliumnext/core/src/services/llm/tools/helpers.js", () => ({registerDocNoteHtmlReader: (reader: (note: unknown) => string | null) => { registrations.docNoteReader = reader; }}));@@ -18,7 +22,6 @@ vi.mock("@triliumnext/core/src/services/llm/tools/index.js", () => ({import { registerServerLlmExtensions } from "./index.js";import { ClaudeAgentProvider } from "./providers/claude_agent.js";-import { skillTools } from "./skills/index.js";import { helpTools } from "./tools/help_tools.js";describe("registerServerLlmExtensions", () => {@@ -30,7 +33,10 @@ describe("registerServerLlmExtensions", () => {expect(registrations.claudeAgentFactory?.()).toBeInstanceOf(ClaudeAgentProvider);// The User Guide reader, which core's note-content helper calls for doc notes.expect(registrations.docNoteReader).toBeTypeOf("function");- // The two tool registries backed by files on disk.- expect(registrations.toolRegistries).toEqual([helpTools, skillTools]);+ // The skill sheets: core owns the catalog and the tool, the server only+ // knows how to get a sheet off disk.+ expect(registrations.skillReader?.("search_syntax.md")).toContain("#");+ // The one registry still backed by files this build alone carries.+ expect(registrations.toolRegistries).toEqual([helpTools]);});});diff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.tsindex 98470ba623..8db59995f8 100644--- a/apps/server/src/services/llm/index.ts+++ b/apps/server/src/services/llm/index.ts@@ -4,16 +4,18 @@* 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 two tool registries that read off disk (the User Guide and the skill- * sheets). Core exposes a seam for each; this is where the server fills them in.+ * 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.*/import { registerClaudeAgentProvider } 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";+import { loadSkillSheet } from "../../core_assets.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";@@ -26,6 +28,6 @@ import { helpTools } from "./tools/help_tools.js";export function registerServerLlmExtensions() {registerClaudeAgentProvider(() => new ClaudeAgentProvider());registerDocNoteHtmlReader(getDocNoteHtml);+ registerSkillReader(loadSkillSheet);registerToolRegistry(helpTools);- registerToolRegistry(skillTools);}diff --git a/apps/server/src/services/llm/skills/index.spec.ts b/apps/server/src/services/llm/skills/index.spec.tsdeleted file mode 100644index 65b1553ec2..0000000000--- a/apps/server/src/services/llm/skills/index.spec.ts+++ /dev/null@@ -1,41 +0,0 @@-import type { ToolDefinition } from "@triliumnext/core/src/services/llm/tools/tool_registry.js";-import { describe, expect, it } from "vitest";--import { getSkillsSummary, skillTools } from "./index.js";--function loadSkillTool(): ToolDefinition {- for (const [name, def] of skillTools) {- if (name === "load_skill") return def;- }- throw new Error("load_skill tool not registered");-}--describe("llm skills", () => {- it("getSkillsSummary lists each skill name inline (no bullets)", () => {- const summary = getSkillsSummary();- // Inline prose, not a bulleted catalog (bullets confuse some models).- expect(summary).not.toContain("\n");- expect(summary).toContain('"search_syntax"');- expect(summary).toContain('"backend_scripting"');- expect(summary).toContain('"frontend_scripting"');- expect(summary).toContain('"dashboards"');- });-- describe("load_skill tool", () => {- it.each([ "search_syntax", "backend_scripting", "frontend_scripting", "dashboards" ])("loads the markdown content of the '%s' skill", (name) => {- const result = loadSkillTool().execute({ name }) as {- skill: string;- instructions: string;- };- expect(result.skill).toBe(name);- expect(typeof result.instructions).toBe("string");- expect(result.instructions.length).toBeGreaterThan(0);- });-- it("returns an error listing available skills for an unknown name", () => {- const result = loadSkillTool().execute({ name: "no_such_skill" }) as { error: string };- expect(result.error).toContain("Unknown skill: 'no_such_skill'");- expect(result.error).toContain("search_syntax");- });- });-});diff --git a/apps/standalone/src/lightweight/llm_skills.spec.ts b/apps/standalone/src/lightweight/llm_skills.spec.tsnew file mode 100644index 0000000000..75458ad989--- /dev/null+++ b/apps/standalone/src/lightweight/llm_skills.spec.ts@@ -0,0 +1,24 @@+import { readSkill, SKILLS } from "@triliumnext/core/src/services/llm/skills.js";+import { describe, expect, it } from "vitest";++import { registerStandaloneLlmExtensions } from "./llm_skills.js";++describe("standalone skill sheets", () => {+ it("inlines a sheet for every skill core catalogues", () => {+ registerStandaloneLlmExtensions();++ // The failure this guards against is a catalog entry added in core without+ // its `?raw` import here: on the server the tool keeps working, and only+ // this build answers "unknown skill" for something it advertises.+ for (const skill of SKILLS) {+ const sheet = readSkill(skill.name);+ expect(sheet, `no inlined sheet for ${skill.name}`).toBeTruthy();+ expect(sheet?.length).toBeGreaterThan(100);+ }+ });++ it("answers with nothing for a file it does not carry", () => {+ registerStandaloneLlmExtensions();+ expect(readSkill("no_such_skill")).toBeNull();+ });+});diff --git a/apps/standalone/src/lightweight/llm_skills.ts b/apps/standalone/src/lightweight/llm_skills.tsnew file mode 100644index 0000000000..f9af0db073--- /dev/null+++ b/apps/standalone/src/lightweight/llm_skills.ts@@ -0,0 +1,31 @@+import backendScripting from "@triliumnext/core/src/assets/llm/skills/backend_scripting.md?raw";+import dashboards from "@triliumnext/core/src/assets/llm/skills/dashboards.md?raw";+import frontendScripting from "@triliumnext/core/src/assets/llm/skills/frontend_scripting.md?raw";+import searchSyntax from "@triliumnext/core/src/assets/llm/skills/search_syntax.md?raw";+import { registerSkillReader } from "@triliumnext/core/src/services/llm/skills.js";++/**+ * The skill sheets, inlined by the bundler.+ *+ * The server reads them from RESOURCE_DIR; there is no disk here, and no useful+ * moment to fetch them either — a tool's `execute` is synchronous by contract,+ * so the sheets have to already be in memory when the model asks. `?raw` settles+ * that at build time, the same way this build already takes core's schema.sql,+ * and costs ~44 KB of markdown in an app that ships a SQLite engine.+ *+ * Keyed by file name, which is what core's catalog asks a reader for.+ */+const SKILL_SHEETS: Record<string, string> = {+ "search_syntax.md": searchSyntax,+ "backend_scripting.md": backendScripting,+ "frontend_scripting.md": frontendScripting,+ "dashboards.md": dashboards+};++/**+ * The standalone build's contribution to the LLM stack, alongside the server's+ * {@link registerServerLlmExtensions}. Called once from worker startup.+ */+export function registerStandaloneLlmExtensions() {+ registerSkillReader((file) => SKILL_SHEETS[file] ?? null);+}diff --git a/apps/standalone/src/local-server-worker.ts b/apps/standalone/src/local-server-worker.tsindex a757ea0579..cca72c340c 100644--- a/apps/standalone/src/local-server-worker.ts+++ b/apps/standalone/src/local-server-worker.ts@@ -326,6 +326,12 @@ async function initialize(): Promise<void> {});coreModule.ws.init();+ // This build's half of the LLM stack, mirroring what the server+ // contributes in registerServerLlmExtensions. Imported here rather than+ // at the top of the file so the skill sheets it inlines travel in a+ // chunk of their own instead of the worker's startup bundle.+ (await import("./lightweight/llm_skills.js")).registerStandaloneLlmExtensions();+logService.info(`[Worker] Supported routes: ${Object.keys(coreModule.routes).join(", ")}`);// Create and configure the routerdiff --git a/apps/server/src/assets/llm/skills/backend_scripting.md b/packages/trilium-core/src/assets/llm/skills/backend_scripting.mdsimilarity index 100%rename from apps/server/src/assets/llm/skills/backend_scripting.mdrename to packages/trilium-core/src/assets/llm/skills/backend_scripting.mddiff --git a/apps/server/src/assets/llm/skills/dashboards.md b/packages/trilium-core/src/assets/llm/skills/dashboards.mdsimilarity index 100%rename from apps/server/src/assets/llm/skills/dashboards.mdrename to packages/trilium-core/src/assets/llm/skills/dashboards.mddiff --git a/apps/server/src/assets/llm/skills/frontend_scripting.md b/packages/trilium-core/src/assets/llm/skills/frontend_scripting.mdsimilarity index 100%rename from apps/server/src/assets/llm/skills/frontend_scripting.mdrename to packages/trilium-core/src/assets/llm/skills/frontend_scripting.mddiff --git a/apps/server/src/assets/llm/skills/search_syntax.md b/packages/trilium-core/src/assets/llm/skills/search_syntax.mdsimilarity index 100%rename from apps/server/src/assets/llm/skills/search_syntax.mdrename to packages/trilium-core/src/assets/llm/skills/search_syntax.mddiff --git a/packages/trilium-core/src/services/llm/skills.spec.ts b/packages/trilium-core/src/services/llm/skills.spec.tsnew file mode 100644index 0000000000..3878863f2e--- /dev/null+++ b/packages/trilium-core/src/services/llm/skills.spec.ts@@ -0,0 +1,57 @@+import { existsSync } from "fs";+import { fileURLToPath } from "url";+import { afterEach, describe, expect, it } from "vitest";++import { getSkillsSummary, readSkill, registerSkillReader, SKILLS } from "./skills.js";++/** Restore the "no host has registered anything" state the module starts in. */+function clearReader() {+ registerSkillReader(() => null);+}++afterEach(clearReader);++describe("llm skill sheets", () => {+ it("ships a markdown sheet for every catalogued skill", () => {+ // The catalog is the contract between core and both readers: an entry with+ // no file behind it is a tool call that fails at the far end of a chat.+ for (const skill of SKILLS) {+ const path = fileURLToPath(new URL(`../../assets/llm/skills/${skill.file}`, import.meta.url));+ expect(existsSync(path), `missing sheet: ${skill.file}`).toBe(true);+ }+ });++ it("asks the host's reader for the catalogued file name", () => {+ const asked: string[] = [];+ registerSkillReader((file) => {+ asked.push(file);+ return file === "search_syntax.md" ? "SHEET" : null;+ });++ expect(readSkill("search_syntax")).toBe("SHEET");+ expect(asked).toEqual(["search_syntax.md"]);+ });++ it("answers with nothing for a skill outside the catalog, without troubling the reader", () => {+ let asked = false;+ registerSkillReader(() => { asked = true; return "SHEET"; });++ expect(readSkill("no_such_skill")).toBeNull();+ expect(asked).toBe(false);+ });++ it("answers with nothing where no host has registered a reader", () => {+ clearReader();+ expect(readSkill("search_syntax")).toBeNull();+ });++ it("summarises the skills inline, never as a bulleted list", () => {+ // Bullets of `- name: description` read as a tool catalog to some models+ // (notably Gemini), which then invent calls to the skill names.+ const summary = getSkillsSummary();+ expect(summary).not.toContain("\n");+ for (const skill of SKILLS) {+ expect(summary).toContain(`"${skill.name}"`);+ }+ });+});diff --git a/apps/server/src/services/llm/skills/index.ts b/packages/trilium-core/src/services/llm/skills.tssimilarity index 53%rename from apps/server/src/services/llm/skills/index.tsrename to packages/trilium-core/src/services/llm/skills.tsindex 014b1947c5..ae39065b7b 100644--- a/apps/server/src/services/llm/skills/index.ts+++ b/packages/trilium-core/src/services/llm/skills.ts@@ -1,28 +1,28 @@/**- * LLM skills — on-demand instruction sets that an LLM can load when it needs- * specialized knowledge (e.g. search syntax). Only names and descriptions are- * included in the system prompt; full content is fetched via the load_skill tool.+ * The skill sheets: instruction sets an LLM loads on demand when a question+ * needs knowledge the system prompt has no room for (search syntax, the+ * scripting APIs, how a dashboard is put together).+ *+ * The sheets themselves are markdown under `src/assets/llm/skills`, and how a+ * host gets at them differs by runtime — the server reads them off disk, the+ * browser build has them inlined by its bundler — so this module carries only+ * the catalog and the seam. Kept apart from {@link ../tools/skill_tools.js} so+ * that registering a reader costs a host nothing but this file: the tool module+ * reaches the AI SDK through the tool registry, which the standalone build goes+ * to some length to keep out of its startup path.*/-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";--const SKILLS_DIR = join(resourceDir.RESOURCE_DIR, "llm", "skills");-interface SkillDefinition {name: string;/** Long description shown in the load_skill tool's listing. */description: string;/** Short noun phrase for inline use in the system prompt. */summary: string;+ /** Markdown file under `src/assets/llm/skills`, which is what a reader is asked for. */file: string;}-const SKILLS: SkillDefinition[] = [+export const SKILLS: SkillDefinition[] = [{name: "search_syntax",description: "Trilium search query syntax reference — labels, relations, note properties, boolean logic, ordering, and more.",@@ -49,12 +49,31 @@ const SKILLS: SkillDefinition[] = [}];-function loadSkillContent(name: string): string | null {+/** Host-provided reader for the sheets. See {@link registerSkillReader}. */+let skillReader: ((file: string) => string | null) | null = null;++/**+ * Register the host's reader for skill sheets, keyed by the file name in+ * {@link SKILLS}.+ *+ * Must answer synchronously, because a tool's `execute` does — so a host that+ * cannot read on demand (no filesystem) inlines or preloads the sheets and+ * answers from memory.+ */+export function registerSkillReader(reader: (file: string) => string | null) {+ skillReader = reader;+}++/**+ * The sheet's markdown, or null when the skill is unknown to the catalog or the+ * host cannot produce it.+ */+export function readSkill(name: string): string | null {const skill = SKILLS.find((s) => s.name === name);- if (!skill) {+ if (!skill || !skillReader) {return null;}- return readFileSync(join(SKILLS_DIR, skill.file), "utf-8");+ return skillReader(skill.file);}/**@@ -66,20 +85,3 @@ function loadSkillContent(name: string): string | null {export function getSkillsSummary(): string {return SKILLS.map((s) => `"${s.name}" for ${s.summary}`).join(", ");}--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")}`,- inputSchema: z.object({- name: z.string().describe("The skill name to load")- }),- execute: ({ name }) => {- const content = loadSkillContent(name);- if (!content) {- return { error: `Unknown skill: '${name}'. Available: ${SKILLS.map((s) => s.name).join(", ")}` };- }- return { skill: name, instructions: content };- }- }-});diff --git a/packages/trilium-core/src/services/llm/tools/index.ts b/packages/trilium-core/src/services/llm/tools/index.tsindex 5401f38dec..15b56af2d3 100644--- a/packages/trilium-core/src/services/llm/tools/index.ts+++ b/packages/trilium-core/src/services/llm/tools/index.ts@@ -8,6 +8,7 @@ export { attributeTools } from "./attribute_tools.js";export { hierarchyTools } from "./hierarchy_tools.js";export { iconTools } from "./icon_tools.js";export { noteTools } from "./note_tools.js";+export { skillTools } from "./skill_tools.js";export type { ToolDefinition } from "./tool_registry.js";export { ToolRegistry } from "./tool_registry.js";@@ -16,22 +17,26 @@ import { attributeTools } from "./attribute_tools.js";import { hierarchyTools } from "./hierarchy_tools.js";import { iconTools } from "./icon_tools.js";import { noteTools } from "./note_tools.js";+import { skillTools } from "./skill_tools.js";import type { ToolRegistry } from "./tool_registry.js";/*** 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.+ * The skill sheets are listed here even though their markdown reaches each+ * runtime differently: the catalog is core's, and every host registers a reader+ * for it (see {@link ../skills.js}). What is still contributed from outside is+ * the help tools, which read the User Guide off disk — a guide the browser build+ * does not carry at all — so that registry arrives via+ * {@link registerToolRegistry} and standalone simply runs without it.*/export const allToolRegistries: ToolRegistry[] = [noteTools,attributeTools,attachmentTools,hierarchyTools,- iconTools+ iconTools,+ skillTools];/**diff --git a/packages/trilium-core/src/services/llm/tools/skill_tools.spec.ts b/packages/trilium-core/src/services/llm/tools/skill_tools.spec.tsnew file mode 100644index 0000000000..24034dbf1b--- /dev/null+++ b/packages/trilium-core/src/services/llm/tools/skill_tools.spec.ts@@ -0,0 +1,49 @@+import { afterEach, describe, expect, it } from "vitest";++import { registerSkillReader, SKILLS } from "../skills.js";+import type { ToolDefinition } from "./tool_registry.js";+import { skillTools } from "./skill_tools.js";++function loadSkillTool(): ToolDefinition {+ for (const [name, def] of skillTools) {+ if (name === "load_skill") return def;+ }+ throw new Error("load_skill tool not registered");+}++afterEach(() => registerSkillReader(() => null));++describe("load_skill", () => {+ it("hands back the sheet the host produced", () => {+ registerSkillReader((file) => `contents of ${file}`);++ expect(loadSkillTool().execute({ name: "search_syntax" }))+ .toEqual({ skill: "search_syntax", instructions: "contents of search_syntax.md" });+ });++ it("lists what is on offer when asked for something else", () => {+ registerSkillReader(() => "SHEET");++ const result = loadSkillTool().execute({ name: "no_such_skill" }) as { error: string };+ expect(result.error).toContain("Unknown skill: 'no_such_skill'");+ for (const skill of SKILLS) {+ expect(result.error).toContain(skill.name);+ }+ });++ it("says the same when the host cannot produce the sheet, rather than returning an empty one", () => {+ // A build with no reader, or one whose file went missing: the model gets a+ // refusal it can act on instead of instructions that say nothing.+ registerSkillReader(() => null);++ expect(loadSkillTool().execute({ name: "search_syntax" }))+ .toHaveProperty("error", expect.stringContaining("Unknown skill: 'search_syntax'"));+ });++ it("names every catalogued skill in its description, which is all the model sees up front", () => {+ const description = loadSkillTool().description;+ for (const skill of SKILLS) {+ expect(description).toContain(`- ${skill.name}: ${skill.description}`);+ }+ });+});diff --git a/packages/trilium-core/src/services/llm/tools/skill_tools.ts b/packages/trilium-core/src/services/llm/tools/skill_tools.tsnew file mode 100644index 0000000000..548d7cd3a9--- /dev/null+++ b/packages/trilium-core/src/services/llm/tools/skill_tools.ts@@ -0,0 +1,27 @@+/**+ * The tool that hands a skill sheet to the model. Only the names and+ * descriptions travel in the tool listing; the sheet itself is fetched here, so+ * the system prompt stays small.+ */++import { z } from "zod";++import { readSkill, SKILLS } from "../skills.js";+import { defineTools } from "./tool_registry.js";++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")}`,+ inputSchema: z.object({+ name: z.string().describe("The skill name to load")+ }),+ execute: ({ name }) => {+ const instructions = readSkill(name);+ if (!instructions) {+ return { error: `Unknown skill: '${name}'. Available: ${SKILLS.map((s) => s.name).join(", ")}` };+ }+ return { skill: name, instructions };+ }+ }+});