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): never ask before a lookup in what ships with Trilium
Elian Doranfbf030804a11
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.htmlindex 9c27ec0cfc..11d07d9ffc 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI.html@@ -295,10 +295,12 @@<p>A new chat starts in the mode you picked last, in any chat, or in <em>Ask before changes</em> untilyou pick one. Picking <em>Don't ask</em> therefore carries over to the nextchat too.</p>-<p>A tool allowed for the chat runs without asking in every mode. A model's- built-in web search runs on the provider's side and never asks.</p>-<aside-class="admonition important">+<p>A tool allowed for the chat runs without asking in every mode. So does+ looking something up in what ships with Trilium (its User Guide, the skill+ sheets that teach the AI Trilium's search syntax and note types, and the+ icons), since it reads none of your notes. A model's built-in web search+ runs on the provider's side and never asks.</p>+<aside class="admonition important"><p>Among the <a class="reference-link" href="#root/_help_eFhxp9laTW1S">Subscription-based providers</a>,Claude Code and Google Antigravity ask like any other provider. GitHubCopilot and OpenAI Codex don't ask yet: their tool calls run without approval.</p>diff --git a/apps/server/src/services/llm/tools/help_tools.spec.ts b/apps/server/src/services/llm/tools/help_tools.spec.tsindex 4fa7ce9464..83f91d89cc 100644--- a/apps/server/src/services/llm/tools/help_tools.spec.ts+++ b/apps/server/src/services/llm/tools/help_tools.spec.ts@@ -80,6 +80,14 @@ describe("help_tools", () => {vi.clearAllMocks();});+ it("reads only the User Guide, which ships with Trilium, never the user's data", () => {+ const readsUserData = (name: string) => {+ const definition = getTool(name);+ return definition.mutates ? true : definition.readsUserData;+ };+ expect([ "search_help", "get_help_toc" ].map(readsUserData)).toEqual([ false, false ]);+ });+describe("search_help", () => {it("matches page bodies (which live on disk, invisible to regular search) and returns breadcrumb paths", () => {buildHelpTree();diff --git a/apps/server/src/services/llm/tools/help_tools.ts b/apps/server/src/services/llm/tools/help_tools.tsindex 977e93a399..825f06d2b1 100644--- a/apps/server/src/services/llm/tools/help_tools.ts+++ b/apps/server/src/services/llm/tools/help_tools.ts@@ -31,6 +31,7 @@ export const helpTools = defineTools({"If a query finds nothing, retry with synonyms or browse get_help_toc — the guide may name the concept differently (e.g. placing a note in two locations is 'cloning').","Read a found page with get_note_content."].join(" "),+ readsUserData: false,inputSchema: z.object({query: z.string().describe("Keyword search query (a few plain words, not a full question)"),limit: z.number().int().positive().optional().describe("Maximum number of results to return. Defaults to 10.")@@ -80,6 +81,7 @@ export const helpTools = defineTools({"Use this when search_help does not find the right page (the guide may name the concept differently than the user), or to get an overview of a documentation area.","Read a page with get_note_content."].join(" "),+ readsUserData: false,inputSchema: z.object({}),execute: () => {if (!isHelpAvailable()) {diff --git a/docs/User Guide/User Guide/AI.md b/docs/User Guide/User Guide/AI.mdindex 96e706e40c..1a972e1b1b 100644--- a/docs/User Guide/User Guide/AI.md+++ b/docs/User Guide/User Guide/AI.md@@ -175,7 +175,7 @@ Which calls ask depends on the chat's permission mode, chosen in the <span classA new chat starts in the mode you picked last, in any chat, or in _Ask before changes_ until you pick one. Picking _Don't ask_ therefore carries over to the next chat too.-A tool allowed for the chat runs without asking in every mode. A model's built-in web search runs on the provider's side and never asks.+A tool allowed for the chat runs without asking in every mode. So does looking something up in what ships with Trilium (its User Guide, the skill sheets that teach the AI Trilium's search syntax and note types, and the icons), since it reads none of your notes. A model's built-in web search runs on the provider's side and never asks.> [!IMPORTANT]> Among the <a class="reference-link" href="AI/Providers/Subscription-based%20providers.md">Subscription-based providers</a>, Claude Code and Google Antigravity ask like any other provider. GitHub Copilot and OpenAI Codex don't ask yet: their tool calls run without approval.diff --git a/packages/trilium-core/src/services/llm/chat.ts b/packages/trilium-core/src/services/llm/chat.tsindex c540786420..77df2c079a 100644--- a/packages/trilium-core/src/services/llm/chat.ts+++ b/packages/trilium-core/src/services/llm/chat.ts@@ -15,7 +15,7 @@ import { generateChatTitle } from "./chat_title.js";import { getProvider, getProviderByType, getSearchProviderSetup, getSelectedModel, hasConfiguredProviders, type LlmProvider, type LlmProviderConfig } from "./index.js";import { formatStreamError, streamToChunks } from "./stream.js";import { closeToolApprovals, openToolApprovals, type ToolApprovals } from "./tool_approval.js";-import { isReadOnlyTool, resolveToolRegistries } from "./tools/index.js";+import { resolveToolRegistries, toolKind } from "./tools/index.js";/*** Stream one assistant turn, yielding the chunks as the provider produces them.@@ -46,7 +46,7 @@ export async function* runChat(const toolApprovals = openToolApprovals(streamId, abortSignal, {allowedTools,mode,- isReadOnly: isReadOnlyTool+ kindOf: toolKind});if (!toolApprovals) {yield { type: "error", error: `Stream '${streamId}' is already running.` };diff --git a/packages/trilium-core/src/services/llm/tool_approval.spec.ts b/packages/trilium-core/src/services/llm/tool_approval.spec.tsindex 5d7fa3e408..5cbc01a788 100644--- a/packages/trilium-core/src/services/llm/tool_approval.spec.ts+++ b/packages/trilium-core/src/services/llm/tool_approval.spec.ts@@ -7,7 +7,7 @@ import { z } from "zod";import { BaseProvider } from "./providers/base_provider.js";import { streamToChunks } from "./stream.js";import { TOOL_CALL_DECLINED_REASON, ToolApprovals } from "./tool_approval.js";-import { isReadOnlyTool } from "./tools/index.js";+import { toolKind, type ToolKind } from "./tools/index.js";const USAGE = {inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },@@ -166,29 +166,34 @@ describe("ToolApprovals allowed for the chat", () => {});describe("ToolApprovals permission modes", () => {- const isReadOnly = (toolName: string) => toolName === "get_note";- /** Which of a read and a change ask in `mode`. */+ const kindOf = (toolName: string): ToolKind => {+ if (toolName === "load_skill") return "app_content";+ return toolName === "get_note" ? "read" : "change";+ };+ /** Which of a lookup in Trilium's own content, a read and a change ask in `mode`. */function asked(mode: "always_ask" | "ask_before_changes" | "dont_ask") {- const approvals = new ToolApprovals(undefined, { mode, isReadOnly });+ const approvals = new ToolApprovals(undefined, { mode, kindOf });const requests: string[] = [];approvals.onRequest = (request) => requests.push(request.toolName);+ void approvals.request({ toolCallId: "c0", toolName: "load_skill", toolInput: {} });void approvals.request({ toolCallId: "c1", toolName: "get_note", toolInput: {} });void approvals.request({ toolCallId: "c2", toolName: "delete_note", toolInput: {} });approvals.declineAll();return requests;}- it("asks about every call, only about changes, or about none", async () => {+ it("asks about every call, only about changes, or about none, and never about Trilium's own content", async () => {expect(asked("always_ask")).toEqual([ "get_note", "delete_note" ]);expect(asked("ask_before_changes")).toEqual([ "delete_note" ]);expect(asked("dont_ask")).toEqual([]);- const approvals = new ToolApprovals(undefined, { mode: "ask_before_changes", isReadOnly });- await expect(approvals.request({ toolCallId: "c1", toolName: "get_note", toolInput: {} })).resolves.toBe(true);+ const approvals = new ToolApprovals(undefined, { mode: "always_ask", kindOf });+ await expect(approvals.request({ toolCallId: "c1", toolName: "load_skill", toolInput: {} })).resolves.toBe(true);});- it("counts a note tool that does not mutate and the web tools as reads, and anything unknown as a change", () => {- expect([ "get_note", "search_notes", "web_search", "read_web_page" ].map(isReadOnlyTool)).toEqual([ true, true, true, true ]);- expect([ "create_note", "delete_attribute", "some_mcp_tool" ].map(isReadOnlyTool)).toEqual([ false, false, false ]);+ it("tells Trilium's own content, reads and changes apart, and counts anything unknown as a change", () => {+ expect([ "load_skill", "search_icons" ].map(toolKind)).toEqual([ "app_content", "app_content" ]);+ expect([ "get_note", "search_notes", "web_search", "read_web_page" ].map(toolKind)).toEqual([ "read", "read", "read", "read" ]);+ expect([ "create_note", "delete_attribute", "some_mcp_tool" ].map(toolKind)).toEqual([ "change", "change", "change" ]);});});diff --git a/packages/trilium-core/src/services/llm/tool_approval.ts b/packages/trilium-core/src/services/llm/tool_approval.tsindex 11d2a2fc2b..d686eab910 100644--- a/packages/trilium-core/src/services/llm/tool_approval.ts+++ b/packages/trilium-core/src/services/llm/tool_approval.ts@@ -11,6 +11,8 @@import type { LlmPermissionMode, LlmToolApprovalAnswer, LlmToolApprovalRequest } from "@triliumnext/commons";+import type { ToolKind } from "./tools/index.js";+/** The reason the model is given for a call the user declined. */export const TOOL_CALL_DECLINED_REASON = "The user declined this tool call.";@@ -20,8 +22,11 @@ export interface ToolApprovalPolicy {allowedTools?: Iterable<string>;/** Absent means `"always_ask"`. */mode?: LlmPermissionMode;- /** Whether a tool only reads, which `"ask_before_changes"` lets run. Absent, every tool changes. */- isReadOnly?: (toolName: string) => boolean;+ /**+ * What a tool's calls touch. `"app_content"` never asks, and `"ask_before_changes"` lets+ * `"read"` run too. Absent, every tool counts as a change.+ */+ kindOf?: (toolName: string) => ToolKind;}/** The tool calls of one turn that wait for the user's answer. */@@ -30,14 +35,14 @@ export class ToolApprovals {/** The tools whose calls run without asking. */private readonly allowedTools: Set<string>;private readonly mode: LlmPermissionMode;- private readonly isReadOnly: (toolName: string) => boolean;+ private readonly kindOf: (toolName: string) => ToolKind;/** Called with every request, so the turn can pass it on to the client. */onRequest?: (request: LlmToolApprovalRequest) => void;constructor(private readonly abortSignal?: AbortSignal, policy: ToolApprovalPolicy = {}) {this.allowedTools = new Set(policy.allowedTools);this.mode = policy.mode ?? "always_ask";- this.isReadOnly = policy.isReadOnly ?? (() => false);+ this.kindOf = policy.kindOf ?? (() => "change");}/**@@ -89,9 +94,11 @@ export class ToolApprovals {}private runsUnasked(toolName: string): boolean {- return this.mode === "dont_ask"- || this.allowedTools.has(toolName)- || (this.mode === "ask_before_changes" && this.isReadOnly(toolName));+ if (this.mode === "dont_ask" || this.allowedTools.has(toolName)) {+ return true;+ }+ const kind = this.kindOf(toolName);+ return kind === "app_content" || (kind === "read" && this.mode === "ask_before_changes");}/** Decline every call that still waits. */diff --git a/packages/trilium-core/src/services/llm/tools/icon_tools.ts b/packages/trilium-core/src/services/llm/tools/icon_tools.tsindex 08d98f233e..70818dab69 100644--- a/packages/trilium-core/src/services/llm/tools/icon_tools.ts+++ b/packages/trilium-core/src/services/llm/tools/icon_tools.ts@@ -17,6 +17,7 @@ export const iconTools = defineTools({"To give a note an icon, assign the icon class to the note's 'iconClass' label via set_attribute.","ALWAYS use this instead of prepending an emoji to a note's title."].join(" "),+ readsUserData: false,inputSchema: z.object({query: z.string().describe("One or more keywords describing the desired icon, e.g. 'rocket' or 'building landmark monument'. Keywords are matched individually, so listing several synonyms is safe: icons matching more of them rank first."),limit: z.number().optional().describe("Maximum number of icons to return. Defaults to 20.")diff --git a/packages/trilium-core/src/services/llm/tools/index.ts b/packages/trilium-core/src/services/llm/tools/index.tsindex ed7eece074..4ed7e40e98 100644--- a/packages/trilium-core/src/services/llm/tools/index.ts+++ b/packages/trilium-core/src/services/llm/tools/index.ts@@ -100,19 +100,27 @@ export function resolveToolRegistries(): Promise<void> {const WEB_READ_TOOLS = new Set([ "web_search", "read_web_page" ]);/**- * Whether a tool only reads: a registered tool not marked `mutates`, or a web search tool. A tool+ * What a tool's calls touch, which decides when they wait for approval: only what ships with Trilium+ * (`"app_content"`), the user's data without changing it (`"read"`), or the user's data to change+ * it (`"change"`).+ */+export type ToolKind = "app_content" | "read" | "change";++/**+ * The {@link ToolKind} of a tool, from its registry definition; the web search tools are reads. A tool* none of them names, such as one a future integration adds, counts as a change.*/-export function isReadOnlyTool(toolName: string): boolean {+export function toolKind(toolName: string): ToolKind {if (WEB_READ_TOOLS.has(toolName)) {- return true;+ return "read";}for (const registry of allToolRegistries) {for (const [ name, definition ] of registry) {if (name === toolName) {- return !definition.mutates;+ if (definition.mutates) return "change";+ return definition.readsUserData === false ? "app_content" : "read";}}}- return false;+ return "change";}diff --git a/packages/trilium-core/src/services/llm/tools/skill_tools.ts b/packages/trilium-core/src/services/llm/tools/skill_tools.tsindex 548d7cd3a9..89b6e506ef 100644--- a/packages/trilium-core/src/services/llm/tools/skill_tools.ts+++ b/packages/trilium-core/src/services/llm/tools/skill_tools.ts@@ -13,6 +13,7 @@ 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")}`,+ readsUserData: false,inputSchema: z.object({name: z.string().describe("The skill name to load")}),diff --git a/packages/trilium-core/src/services/llm/tools/tool_registry.ts b/packages/trilium-core/src/services/llm/tools/tool_registry.tsindex e585ab7e60..4c97093326 100644--- a/packages/trilium-core/src/services/llm/tools/tool_registry.ts+++ b/packages/trilium-core/src/services/llm/tools/tool_registry.ts@@ -36,6 +36,11 @@ interface ReadOnlyToolDefinition {description: string;inputSchema: z.ZodType;mutates?: false;+ /**+ * `false` for a tool that reads only what ships with Trilium (its User Guide, skill sheets,+ * icons), never the user's notes, so its calls never wait for approval.+ */+ readsUserData?: false;/** Execute the tool synchronously. Kept sync for consistency with MCP. */execute: (args: any) => NotAPromise<object>;}