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): ask the user before Antigravity calls a note tool
Elian Doraneddcc98689d0
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 1906807197..9c27ec0cfc 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@@ -300,8 +300,8 @@<asideclass="admonition important"><p>Among the <a class="reference-link" href="#root/_help_eFhxp9laTW1S">Subscription-based providers</a>,- Claude Code asks like any other provider. GitHub Copilot, Google Antigravity- and OpenAI Codex don't ask yet: their tool calls run without approval.</p>+ 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.</p></aside><aside class="admonition note"><p>Most changes you allow can be undone: a deleted note can be restored,diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.htmlindex a0a13ab779..9bf8166c91 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/AI/Privacy.html@@ -71,8 +71,8 @@the chat's permission mode lets reads or every call run on their own, oryou allowed that tool for the chat (and except with the <a class="reference-link"href="#root/_help_eFhxp9laTW1S">Subscription-based providers</a> other than- Claude Code). There is no per-note permission system, so the reachable- scope is your whole tree.</li>+ Claude Code and Google Antigravity). There is no per-note permission system,+ so the reachable scope is your whole tree.</li></ul></li><li><strong>Attachments and mentions</strong>, when you add them: images,diff --git a/apps/server/src/services/llm/providers/acp_agent.ts b/apps/server/src/services/llm/providers/acp_agent.tsindex 3d7f0eed0c..e67d2ed2cf 100644--- a/apps/server/src/services/llm/providers/acp_agent.ts+++ b/apps/server/src/services/llm/providers/acp_agent.ts@@ -24,6 +24,7 @@ import { getLog } from "@triliumnext/core";import { attachmentPlaceholder, resolveAttachmentPart } from "@triliumnext/core/src/services/llm/attachment_content.js";import { buildNoteHint } from "@triliumnext/core/src/services/llm/note_hint.js";import { buildSystemPrompt } from "@triliumnext/core/src/services/llm/system_prompt.js";+import type { ToolApprovals } from "@triliumnext/core/src/services/llm/tool_approval.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 fs from "fs";@@ -862,6 +863,39 @@ export abstract class AcpAgentProvider implements LlmProvider {}}+/**+ * Answer a permission request for a call to Trilium's note tools, which the caller has already+ * recognized as one, with the user's decision through the turn's `toolApprovals`. A declined call+ * is rejected once, so the agent asks again about the tool's next call. Without approvals (outside+ * a chat turn) the call is allowed, as the API providers run tools unasked there.+ */+export async function askNoteToolPermission(+ request: AcpPermissionRequest,+ logLabel: string,+ toolApprovals: ToolApprovals | undefined+): Promise<AcpPermissionOutcome> {+ const toolCall = request.toolCall;+ const toolName = toolCall ? mcpToolCall(toolCall)?.tool : undefined;+ const allowOnce = request.options?.find(o => o.kind === "allow_once");+ if (!allowOnce || !toolCall?.toolCallId || !toolName) {+ return denyPermission(request, logLabel);+ }++ const approved = !toolApprovals || await toolApprovals.request({+ toolCallId: toolCall.toolCallId,+ toolName,+ toolInput: unwrapMcpArguments(toolCall.rawInput) as Record<string, unknown>+ });+ if (approved) {+ return { outcome: { outcome: "selected", optionId: allowOnce.optionId } };+ }+ getLog().info(`${logLabel}: the user declined the call to "${toolName}".`);+ const rejectOnce = request.options?.find(o => o.kind === "reject_once");+ return rejectOnce+ ? { outcome: { outcome: "selected", optionId: rejectOnce.optionId } }+ : { outcome: { outcome: "cancelled" } };+}+/*** Deny a permission request, preferring a persistent "reject always" so a* retrying agent stops re-asking, then a one-shot reject, then cancelling the@@ -1122,7 +1156,7 @@ function wrapSystemInstructions(systemPrompt: string): string | null {* (`<server>_<tool>`, `mcp.<server>.<tool>`) matches none of the tool labels the* chat has.*/-function mcpToolCall(update: AcpToolCallUpdate): { server?: string; tool?: string } | undefined {+function mcpToolCall(update: { _meta?: unknown; rawInput?: unknown }): { server?: string; tool?: string } | undefined {const meta = update._meta as { is_mcp_tool_call?: unknown; mcp?: { server?: unknown; tool?: unknown } } | undefined;if (meta?.is_mcp_tool_call !== true) {return undefined;diff --git a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts b/apps/server/src/services/llm/providers/antigravity_agent.spec.tsindex 8c4b4bde5f..6db67f76ff 100644--- a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts+++ b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts@@ -104,6 +104,7 @@ vi.mock("./acp_client.js", () => ({ AcpClient: FakeAcpClient, AcpError: FakeAcpEconst { createUpdateCollector, resetAcpAgentStateForTests } = await import("./acp_agent.js");const { AntigravityAgentProvider, buildAntigravityEnv, buildAntigravityModelList, decideAntigravityPermission } = await import("./antigravity_agent.js");+const { ToolApprovals } = await import("@triliumnext/core/src/services/llm/tool_approval.js");const { parseBuildLabel } = await vi.importActual<typeof import("./antigravity_binary.js")>("./antigravity_binary.js");/** The reply chunks of a turn, without the status that precedes a cold start (see {@link collectAll}). */@@ -162,8 +163,8 @@ async function decideDuringTurn(config: Record<string, unknown>, requests: Recordescribe("decideAntigravityPermission", () => {// Shapes captured from agy_acp_server 1.1.1.- it("approves once a call to Trilium's note-tools MCP server", () => {- expect(decideAntigravityPermission({+ it("approves once a call to Trilium's note-tools MCP server", async () => {+ expect(await decideAntigravityPermission({toolCall: {toolCallId: "fa53",kind: "other",@@ -175,7 +176,7 @@ describe("decideAntigravityPermission", () => {}, "test")).toEqual({ outcome: { outcome: "selected", optionId: "allow" } });});- it("denies built-in tools, other MCP servers, and calls that only name Trilium in model-controlled fields", () => {+ it("denies built-in tools, other MCP servers, and calls that only name Trilium in model-controlled fields", async () => {const denied = { outcome: { outcome: "selected", optionId: "deny" } };// A shell command, as the server asks for it.expect(decideAntigravityPermission({@@ -193,7 +194,7 @@ describe("decideAntigravityPermission", () => {options: PERMISSION_OPTIONS}, "test")).toEqual(denied);// A note-tool call with no one-shot allow on offer is not approved permanently.- expect(decideAntigravityPermission({+ expect(await decideAntigravityPermission({toolCall: { kind: "other", _meta: { mcp: { server: "trilium" }, is_mcp_tool_call: true } },options: [PERMISSION_OPTIONS[0], PERMISSION_OPTIONS[2]]}, "test")).toEqual(denied);@@ -272,6 +273,38 @@ describe("AntigravityAgentProvider", () => {.toEqual({ outcome: { outcome: "selected", optionId: "deny" } });});+ it("asks the turn's approvals about a note-tool call, and rejects only that call when the user declines", async () => {+ const request = {+ toolCall: {+ toolCallId: "fa53",+ kind: "other",+ title: "trilium_rename_note",+ rawInput: { arguments: { noteId: "n", newTitle: "New" } },+ _meta: { mcp: { tool: "rename_note", server: "trilium" }, is_mcp_tool_call: true }+ },+ options: [ ...PERMISSION_OPTIONS, { optionId: "deny_always", name: "Deny Always", kind: "reject_always" } ]+ };+ const approvalsAnswering = (approved: boolean) => {+ const approvals = new ToolApprovals();+ approvals.onRequest = (asked) => {+ requests.push(asked);+ queueMicrotask(() => approvals.answer(asked.toolCallId, approved));+ };+ return approvals;+ };+ const requests: unknown[] = [];++ expect(await decideDuringTurn({ enableNoteTools: true, toolApprovals: approvalsAnswering(true) }, [request]))+ .toEqual([{ outcome: { outcome: "selected", optionId: "allow" } }]);+ // A declined call is rejected once: "reject always" would stop the agent asking about the tool again.+ expect(await decideDuringTurn({ enableNoteTools: true, toolApprovals: approvalsAnswering(false) }, [request]))+ .toEqual([{ outcome: { outcome: "selected", optionId: "deny" } }]);+ expect(requests).toEqual([+ { toolCallId: "fa53", toolName: "rename_note", toolInput: { noteId: "n", newTitle: "New" } },+ { toolCallId: "fa53", toolName: "rename_note", toolInput: { noteId: "n", newTitle: "New" } }+ ]);+ });+it("lets the agent read a public web page only when the chat allows web access", async () => {// Shape captured from agy_acp_server 1.2.1. IP literals need no DNS.const readUrl = (url: string) => ({diff --git a/apps/server/src/services/llm/providers/antigravity_agent.ts b/apps/server/src/services/llm/providers/antigravity_agent.tsindex 9991f87d8b..3042910f3f 100644--- a/apps/server/src/services/llm/providers/antigravity_agent.ts+++ b/apps/server/src/services/llm/providers/antigravity_agent.ts@@ -15,17 +15,18 @@* them out of that folder (see `antigravity_hook.ts`);* - every tool that writes, runs a command or reaches the network asks* permission first, and {@link decideAntigravityPermission} approves only- * Trilium's note tools.+ * Trilium's note tools, after asking the user about each call.*/import type { LlmReasoningEffort } from "@triliumnext/commons";import { getLog } from "@triliumnext/core";+import type { ToolApprovals } from "@triliumnext/core/src/services/llm/tool_approval.js";import type { LlmProviderConfig, ModelInfo } from "@triliumnext/core/src/services/llm/types.js";import { existsSync } from "fs";import path from "path";import dataDirs from "../../data_dir.js";-import { AcpAgentProvider, type AcpLaunchSpec, type AcpNewSessionParams, type AcpPermissionOutcome, type AcpPermissionRequest, type AcpSessionModelState, type AcpToolCallUpdate, type BuiltInToolDisplay, denyPermission, describeError, nearestEffort, NOTE_TOOLS_MCP_SERVER_NAME, sortEfforts } from "./acp_agent.js";+import { AcpAgentProvider, type AcpLaunchSpec, type AcpNewSessionParams, type AcpPermissionOutcome, type AcpPermissionRequest, type AcpSessionModelState, type AcpToolCallUpdate, type BuiltInToolDisplay, askNoteToolPermission, denyPermission, describeError, nearestEffort, NOTE_TOOLS_MCP_SERVER_NAME, sortEfforts } from "./acp_agent.js";import type { AcpClient } from "./acp_client.js";import { getAcpHookEndpointUrl } from "./acp_mcp_endpoint.js";import { resolveAntigravityBinaryPath } from "./antigravity_binary.js";@@ -145,7 +146,7 @@ export class AntigravityAgentProvider extends AcpAgentProvider {if (webSearch && isUrlRead(request.toolCall)) {return decideAntigravityUrlRead(request, this.logLabel);}- return decideAntigravityPermission(request, this.logLabel, { webSearch });+ return decideAntigravityPermission(request, this.logLabel, { webSearch, toolApprovals: config?.toolApprovals });}/** Answer the file-access hook for one tool call, logging each denial. */@@ -205,8 +206,8 @@ export class AntigravityAgentProvider extends AcpAgentProvider {}/**- * Approve Trilium's own note tools, and the web search in a chat that allows- * it; deny everything else.+ * Ask the user about a call to Trilium's own note tools through the turn's `toolApprovals`, approve+ * the web search in a chat that allows it, and deny everything else.** The server asks before every MCP tool call, including those of the note-tools* server Trilium hands it. It marks those requests in `toolCall._meta` — the@@ -222,14 +223,17 @@ export class AntigravityAgentProvider extends AcpAgentProvider {export function decideAntigravityPermission(request: AcpPermissionRequest,logLabel: string,- { webSearch = false }: { webSearch?: boolean } = {}-): AcpPermissionOutcome {+ { webSearch = false, toolApprovals }: { webSearch?: boolean; toolApprovals?: ToolApprovals } = {}+): AcpPermissionOutcome | Promise<AcpPermissionOutcome> {const toolCall = request.toolCall;const meta = toolCall?._meta;const mcp = meta?.mcp as { server?: unknown } | undefined;const isNoteTool = meta?.is_mcp_tool_call === true && mcp?.server === NOTE_TOOLS_MCP_SERVER_NAME;+ if (isNoteTool) {+ return askNoteToolPermission(request, logLabel, toolApprovals);+ }const allowOnce = request.options?.find(o => o.kind === "allow_once");- if ((isNoteTool || (webSearch && isWebSearch(toolCall))) && allowOnce) {+ if (webSearch && isWebSearch(toolCall) && allowOnce) {return { outcome: { outcome: "selected", optionId: allowOnce.optionId } };}return denyPermission(request, logLabel);diff --git a/docs/User Guide/User Guide/AI.md b/docs/User Guide/User Guide/AI.mdindex c0e011a54e..96e706e40c 100644--- a/docs/User Guide/User Guide/AI.md+++ b/docs/User Guide/User Guide/AI.md@@ -178,7 +178,7 @@ A new chat starts in the mode you picked last, in any chat, or in _Ask before chA 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.> [!IMPORTANT]-> Among the <a class="reference-link" href="AI/Providers/Subscription-based%20providers.md">Subscription-based providers</a>, Claude Code asks like any other provider. GitHub Copilot, Google Antigravity and OpenAI Codex don't ask yet: their tool calls run without approval.+> 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.> [!NOTE]> Most changes you allow can be undone: a deleted note can be restored, and an edit reverted from its revision. Setting an attribute is harder to undo, since attributes have no history.diff --git a/docs/User Guide/User Guide/AI/Privacy.md b/docs/User Guide/User Guide/AI/Privacy.mdindex de2b58e1dd..847e19c5e6 100644--- a/docs/User Guide/User Guide/AI/Privacy.md+++ b/docs/User Guide/User Guide/AI/Privacy.md@@ -28,7 +28,7 @@ This is the reason the provider list is grouped this way, and why Trilium pre-se* Notes above a size threshold send a size hint instead of the text, and the model must call a tool to read further.* **Any note the model asks for, when note access is enabled.*** Tools let the model search your tree and read notes, attributes and attachments beyond the current one.- * It decides what to fetch, and each call waits for you to allow it, unless the chat's permission mode lets reads or every call run on their own, or you allowed that tool for the chat (and except with the <a class="reference-link" href="Providers/Subscription-based%20providers.md">Subscription-based providers</a> other than Claude Code). There is no per-note permission system, so the reachable scope is your whole tree.+ * It decides what to fetch, and each call waits for you to allow it, unless the chat's permission mode lets reads or every call run on their own, or you allowed that tool for the chat (and except with the <a class="reference-link" href="Providers/Subscription-based%20providers.md">Subscription-based providers</a> other than Claude Code and Google Antigravity). There is no per-note permission system, so the reachable scope is your whole tree.* **Attachments and mentions**, when you add them: images, PDFs and text files are sent to the provider, and an `@` mention makes that note fetchable.* **Your search query**, when web search is enabled, the model's search terms reach the provider's own search infrastructure, or the search provider chosen in the _Tools_ menu (Brave Search, Tavily, Exa, Serper, Perplexity or your SearXNG instance).* **The pages the model reads**, when web search goes through a search provider: Trilium fetches each page the model asks for from the site itself, so the site sees a request from the machine running Trilium. The page's text is then sent to the model's provider.