Skip to content

Build your personal knowledge base with Trilium Notes

fix(llm): keep Antigravity's file tools out of its sign-in folder

Elian Doranc4d2fa96e17d
diff --git a/apps/server/src/services/llm/providers/acp_mcp_endpoint.spec.ts b/apps/server/src/services/llm/providers/acp_mcp_endpoint.spec.ts
index 061c6423e0..d236ecca18 100644
--- a/apps/server/src/services/llm/providers/acp_mcp_endpoint.spec.ts
+++ b/apps/server/src/services/llm/providers/acp_mcp_endpoint.spec.ts
@@ -16,7 +16,7 @@ vi.mock("@triliumnext/core", () => ({
const createMcpServerMock = vi.hoisted(() => vi.fn());
vi.mock("../../mcp/mcp_server.js", () => ({ createMcpServer: createMcpServerMock }));
-const { getAcpMcpEndpointUrl, resetAcpMcpEndpointForTests } =
+const { getAcpHookEndpointUrl, getAcpMcpEndpointUrl, resetAcpMcpEndpointForTests } =
await import("./acp_mcp_endpoint.js");
/** Loopback address, ephemeral port, 128-bit secret path. */
@@ -258,3 +258,39 @@ describe("ACP MCP endpoint", () => {
await vi.waitFor(() => expect(errorLogMock).toHaveBeenCalledWith(overLimit));
});
});
+
+describe("ACP hook endpoint", () => {
+ afterEach(async () => {
+ await resetAcpMcpEndpointForTests();
+ vi.restoreAllMocks();
+ });
+
+ it("shares the MCP listener under a secret path of its own and answers with the handler's decision", async () => {
+ const createServerSpy = vi.spyOn(http, "createServer");
+ const handler = vi.fn((_payload: unknown) => ({ decision: "deny", reason: "no" }));
+
+ const hookUrl = await getAcpHookEndpointUrl(handler);
+ const mcpUrl = await getAcpMcpEndpointUrl();
+ expect(hookUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/hook-[0-9a-f]{32}$/);
+ expect(new URL(hookUrl).port).toBe(new URL(mcpUrl).port);
+ expect(createServerSpy).toHaveBeenCalledTimes(1);
+
+ const payload = { toolCall: { name: "view_file", args: { AbsolutePath: "/x" } } };
+ const answer = await request(hookUrl, { method: "POST", body: JSON.stringify(payload) });
+ expect(answer).toEqual({ status: 200, body: JSON.stringify({ decision: "deny", reason: "no" }) });
+ expect(handler).toHaveBeenCalledWith(payload);
+ });
+
+ it("refuses anything but a POST from the bound host, so a failing hook denies the call", async () => {
+ const handler = vi.fn(() => ({ decision: "allow" }));
+ const hookUrl = await getAcpHookEndpointUrl(handler);
+ const { port } = new URL(hookUrl);
+
+ await expect(request(hookUrl)).resolves.toMatchObject({ status: 405 });
+ await expect(request(hookUrl, { method: "POST", headers: { host: `localhost:${port}` }, body: "{}" }))
+ .resolves.toMatchObject({ status: 403 });
+ await expect(request(hookUrl, { method: "POST", body: "not json" })).resolves.toMatchObject({ status: 500 });
+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("hook"));
+ expect(handler).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/llm/providers/acp_mcp_endpoint.ts b/apps/server/src/services/llm/providers/acp_mcp_endpoint.ts
index d12e131ed1..1d330513fb 100644
--- a/apps/server/src/services/llm/providers/acp_mcp_endpoint.ts
+++ b/apps/server/src/services/llm/providers/acp_mcp_endpoint.ts
@@ -15,6 +15,10 @@
* Access control: the listener binds to 127.0.0.1 on a random port, and the
* endpoint lives under an unguessable 128-bit secret path known only to the
* agent subprocess we spawn.
+ *
+ * The same listener answers the Antigravity file-access hook under a second
+ * secret path (see `antigravity_hook.ts`): the hook's `curl` posts each tool
+ * call there and prints the decision it gets back.
*/
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
@@ -24,29 +28,37 @@ import http from "http";
import { createMcpServer } from "../../mcp/mcp_server.js";
-let endpointUrl: Promise<string> | undefined;
+/** Decides one hook request from its JSON body; the result is sent back as JSON. */
+export type AcpHookHandler = (payload: unknown) => unknown;
+
+let endpoint: Promise<{ mcpUrl: string; hookUrl: string }> | undefined;
+let hookHandler: AcpHookHandler | undefined;
/**
* Start (once) and return the endpoint URL to hand to the agent's
* `session/new` MCP config. A failed start is not cached so a later chat
* turn retries.
*/
-export function getAcpMcpEndpointUrl(): Promise<string> {
- if (!endpointUrl) {
- endpointUrl = startEndpoint().catch((err: unknown) => {
- endpointUrl = undefined;
- throw err;
- });
- }
- return endpointUrl;
+export async function getAcpMcpEndpointUrl(): Promise<string> {
+ return (await startOnce()).mcpUrl;
+}
+
+/**
+ * Start (once) and return the URL the hook posts tool calls to, which
+ * `handler` answers from then on.
+ */
+export async function getAcpHookEndpointUrl(handler: AcpHookHandler): Promise<string> {
+ hookHandler = handler;
+ return (await startOnce()).hookUrl;
}
/** For tests: close the listener and forget it so the next call starts fresh. */
export async function resetAcpMcpEndpointForTests(): Promise<void> {
- if (endpointUrl) {
- const url = await endpointUrl.catch(() => undefined);
- endpointUrl = undefined;
- if (url) {
+ hookHandler = undefined;
+ if (endpoint) {
+ const started = await endpoint.catch(() => undefined);
+ endpoint = undefined;
+ if (started) {
await new Promise<void>(resolve => {
listener?.close(() => resolve());
listener = undefined;
@@ -57,14 +69,29 @@ export async function resetAcpMcpEndpointForTests(): Promise<void> {
let listener: http.Server | undefined;
-async function startEndpoint(): Promise<string> {
- const secretPath = `/mcp-${randomBytes(16).toString("hex")}`;
+function startOnce() {
+ if (!endpoint) {
+ endpoint = startEndpoint().catch((err: unknown) => {
+ endpoint = undefined;
+ throw err;
+ });
+ }
+ return endpoint;
+}
+
+async function startEndpoint(): Promise<{ mcpUrl: string; hookUrl: string }> {
+ const mcpPath = `/mcp-${randomBytes(16).toString("hex")}`;
+ const hookPath = `/hook-${randomBytes(16).toString("hex")}`;
// Filled in once the listener is bound. A request can only arrive after
- // that, so handleRequest always observes the real address.
+ // that, so the handlers always observe the real address.
let boundHost = "";
const server = http.createServer((req, res) => {
- void handleRequest(req, res, secretPath, boundHost);
+ if (req.url === hookPath && hookHandler) {
+ void handleHookRequest(req, res, hookHandler, boundHost);
+ } else {
+ void handleRequest(req, res, mcpPath, boundHost);
+ }
});
listener = server;
@@ -88,9 +115,35 @@ async function startEndpoint(): Promise<string> {
}
boundHost = `127.0.0.1:${address.port}`;
- const url = `http://${boundHost}${secretPath}`;
- getLog().info(`ACP agent providers: note-tools MCP endpoint listening on ${boundHost} (loopback only)`);
- return url;
+ getLog().info(`ACP agent providers: loopback endpoint for note tools and hooks listening on ${boundHost}`);
+ return { mcpUrl: `http://${boundHost}${mcpPath}`, hookUrl: `http://${boundHost}${hookPath}` };
+}
+
+/**
+ * Answer a hook request with the handler's decision. Any other response makes
+ * the hook's `curl --fail` exit non-zero, which the agent treats as a denial.
+ */
+async function handleHookRequest(
+ req: http.IncomingMessage,
+ res: http.ServerResponse,
+ handler: AcpHookHandler,
+ boundHost: string
+): Promise<void> {
+ try {
+ if (req.method !== "POST") {
+ res.writeHead(405).end();
+ return;
+ }
+ if (req.headers.host !== boundHost) {
+ res.writeHead(403).end();
+ return;
+ }
+ const decision = handler(await readJsonBody(req));
+ res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(decision));
+ } catch (err) {
+ getLog().error(`ACP hook endpoint error: ${err}`);
+ res.writeHead(500).end();
+ }
}
async function handleRequest(
@@ -147,7 +200,7 @@ async function readJsonBody(req: http.IncomingMessage): Promise<unknown> {
for await (const chunk of req) {
totalBytes += (chunk as Buffer).length;
if (totalBytes > MAX_BODY_BYTES) {
- throw new Error(`The MCP request body exceeds the ${MAX_BODY_BYTES}-byte limit.`);
+ throw new Error(`The request body exceeds the ${MAX_BODY_BYTES}-byte limit.`);
}
chunks.push(chunk as Buffer);
}
diff --git a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
index d4b26dcd80..1c1421309f 100644
--- a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
@@ -1,4 +1,5 @@
import type { LlmStreamChunk } from "@triliumnext/commons";
+import fs from "fs";
import os from "os";
import path from "path";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -18,7 +19,15 @@ vi.mock("../../data_dir.js", async () => {
});
vi.mock("./antigravity_binary.js", () => ({ resolveAntigravityBinaryPath: async () => "/opt/agy/agy_acp_server.par" }));
-vi.mock("./acp_mcp_endpoint.js", () => ({ getAcpMcpEndpointUrl: async () => "http://127.0.0.1:12345/mcp-secret" }));
+const getAcpHookEndpointUrlMock = vi.hoisted(() => vi.fn(async (_handler: (payload: unknown) => unknown) => "http://127.0.0.1:12345/hook-secret"));
+vi.mock("./acp_mcp_endpoint.js", () => ({
+ getAcpMcpEndpointUrl: async () => "http://127.0.0.1:12345/mcp-secret",
+ getAcpHookEndpointUrl: getAcpHookEndpointUrlMock
+}));
+vi.mock("./antigravity_hook.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./antigravity_hook.js")>(),
+ resolveCurlPath: async () => "/usr/bin/curl"
+}));
vi.mock("@triliumnext/core/src/services/llm/note_hint.js", () => ({ buildNoteHint: () => null }));
vi.mock("@triliumnext/core/src/services/llm/attachment_content.js", () => ({ resolveAttachmentPart: vi.fn() }));
@@ -175,6 +184,26 @@ describe("AntigravityAgentProvider", () => {
})).toEqual({ outcome: { outcome: "selected", optionId: "deny" } });
});
+ it("keeps the agent away from its sign-in with a hook that asks Trilium about every tool call", async () => {
+ const home = path.join(DATA_DIR, "antigravity-agent", "home");
+ fs.rmSync(path.join(home, "config"), { recursive: true, force: true });
+ getAcpHookEndpointUrlMock.mockClear();
+ await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));
+
+ const hooks = JSON.parse(fs.readFileSync(path.join(home, "config", "hooks.json"), "utf8"));
+ expect(hooks["trilium-file-access"].PreToolUse[0]).toMatchObject({
+ matcher: ".*",
+ hooks: [ { command: "\"/usr/bin/curl\" --silent --show-error --fail --max-time 8 --data-binary @- http://127.0.0.1:12345/hook-secret" } ]
+ });
+
+ const decide = getAcpHookEndpointUrlMock.mock.calls[0][0];
+ const tokenRead = { toolCall: { name: "view_file", args: { AbsolutePath: path.join(home, "antigravity-acp", "acp_token.json") } } };
+ expect(decide(tokenRead)).toMatchObject({ decision: "deny" });
+ expect(infoLogMock).toHaveBeenCalledWith(expect.stringContaining(`kept view_file out of the server's private folder`));
+ expect(decide({ toolCall: { name: "view_file", args: { AbsolutePath: path.join(DATA_DIR, "antigravity-agent", "workspace", "a.md") } } }))
+ .toEqual({ decision: "allow" });
+ });
+
it("signs in during the model probe, but reports a missing sign-in in the chat instead", async () => {
FakeAcpClient.signedIn = false;
const chunks = await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));
diff --git a/apps/server/src/services/llm/providers/antigravity_agent.ts b/apps/server/src/services/llm/providers/antigravity_agent.ts
index 59c182831a..c4bc26a07c 100644
--- a/apps/server/src/services/llm/providers/antigravity_agent.ts
+++ b/apps/server/src/services/llm/providers/antigravity_agent.ts
@@ -10,13 +10,16 @@
* - `GEMINI_HOME` points it at a directory of Trilium's own, so its sign-in,
* sessions, MCP servers and skills are Trilium's rather than those of the
* user's own Antigravity setup;
- * - its file tools are confined to the (empty) agent cwd and its own home;
+ * - its read tools are confined to the (empty) agent cwd and
+ * `<home>/antigravity-acp`, which also holds the sign-in, so a hook keeps
+ * 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.
*/
import { LLM_REASONING_EFFORTS, type LlmReasoningEffort } from "@triliumnext/commons";
+import { getLog } from "@triliumnext/core";
import type { LlmProviderConfig, ModelInfo } from "@triliumnext/core/src/services/llm/types.js";
import { existsSync } from "fs";
import path from "path";
@@ -24,7 +27,9 @@ import path from "path";
import dataDirs from "../../data_dir.js";
import { AcpAgentProvider, type AcpLaunchSpec, type AcpNewSessionParams, type AcpPermissionOutcome, type AcpPermissionRequest, type AcpSessionModelState, type AcpToolCallUpdate, denyPermission, describeError, NOTE_TOOLS_MCP_SERVER_NAME } from "./acp_agent.js";
import { type AcpClient, AcpError } from "./acp_client.js";
+import { getAcpHookEndpointUrl } from "./acp_mcp_endpoint.js";
import { resolveAntigravityBinaryPath } from "./antigravity_binary.js";
+import { type AntigravityDirs, type AntigravityHookDecision, buildHookCommand, decideAntigravityToolCall, resolveCurlPath, writeAntigravityHooks } from "./antigravity_hook.js";
/** The model id that leaves the session on the model the server picks. */
const DEFAULT_MODEL_ID = "default";
@@ -107,7 +112,14 @@ export class AntigravityAgentProvider extends AcpAgentProvider {
}
protected async launchSpec(): Promise<AcpLaunchSpec> {
- const binary = await resolveAntigravityBinaryPath();
+ const home = agentHome();
+ const dirs = { home, workspace: this.agentCwd() };
+ const [ binary, curl, hookUrl ] = await Promise.all([
+ resolveAntigravityBinaryPath(),
+ resolveCurlPath(),
+ getAcpHookEndpointUrl(payload => this.decideToolCall(payload, dirs))
+ ]);
+ writeAntigravityHooks(home, buildHookCommand(curl, hookUrl));
return {
binary,
// The ACP registry launches the Linux build with an empty `--uid=`.
@@ -125,6 +137,16 @@ export class AntigravityAgentProvider extends AcpAgentProvider {
return decideAntigravityPermission(request, this.logLabel);
}
+ /** Answer the file-access hook for one tool call, logging each denial. */
+ private decideToolCall(payload: unknown, dirs: AntigravityDirs): AntigravityHookDecision {
+ const answer = decideAntigravityToolCall(payload, dirs);
+ if (answer.decision === "deny") {
+ const tool = (payload as { toolCall?: { name?: unknown } }).toolCall?.name;
+ getLog().info(`${this.logLabel}: kept ${String(tool)} out of the server's private folder.`);
+ }
+ return answer;
+ }
+
/**
* The agent writes a description of every MCP tool to
* `<home>/antigravity-acp/brain/<session>/mcp/<server>/<tool>.json` and reads
diff --git a/apps/server/src/services/llm/providers/antigravity_hook.spec.ts b/apps/server/src/services/llm/providers/antigravity_hook.spec.ts
new file mode 100644
index 0000000000..7e0937898e
--- /dev/null
+++ b/apps/server/src/services/llm/providers/antigravity_hook.spec.ts
@@ -0,0 +1,109 @@
+import fs from "fs";
+import os from "os";
+import path from "path";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const findOnPathMock = vi.hoisted(() => vi.fn<(binary: string) => Promise<string | undefined>>());
+vi.mock("./binary_lookup.js", () => ({ findOnPath: findOnPathMock }));
+
+const { buildHookCommand, decideAntigravityToolCall, resetCurlCache, resolveCurlPath, writeAntigravityHooks } = await import("./antigravity_hook.js");
+
+const ROOT = path.join(os.tmpdir(), "trilium-antigravity-hook-spec");
+const HOME = path.join(ROOT, "home");
+const WORKSPACE = path.join(ROOT, "workspace");
+const PRIVATE = path.join(HOME, "antigravity-acp");
+const DIRS = { home: HOME, workspace: WORKSPACE };
+
+/** Canonical paths are the paths themselves, except for the aliases a test maps. */
+function realpathWith(aliases: Record<string, string> = {}) {
+ return (candidate: string) => aliases[candidate] ?? candidate;
+}
+
+function decide(name: string, args: unknown, aliases?: Record<string, string>, platform: NodeJS.Platform = process.platform) {
+ return decideAntigravityToolCall({ toolCall: { name, args } }, DIRS, { platform, realpath: realpathWith(aliases) }).decision;
+}
+
+describe("decideAntigravityToolCall", () => {
+ it("denies any path that reaches the server's private folder outside brain/", () => {
+ expect(decide("view_file", { AbsolutePath: path.join(PRIVATE, "acp_token.json") })).toBe("deny");
+ expect(decide("search_directory", { Query: "CANARY", SearchPath: PRIVATE })).toBe("deny");
+ expect(decide("list_directory", { DirectoryPath: path.join(PRIVATE, "conversations") })).toBe("deny");
+ // A folder above it, which a recursive search or listing would cover.
+ expect(decide("find_file", { Pattern: "*.json", SearchDirectory: HOME })).toBe("deny");
+ expect(decide("search_directory", { SearchPath: ROOT })).toBe("deny");
+ // Relative to the workspace, and climbing back out of brain/.
+ expect(decide("list_directory", { DirectoryPath: "../home/antigravity-acp" })).toBe("deny");
+ expect(decide("view_file", { AbsolutePath: path.join(PRIVATE, "brain", "..", "acp_token.json") })).toBe("deny");
+ // However deep the argument sits, and whatever tool carries it.
+ expect(decide("run_command", { CommandLine: "echo", Cwd: PRIVATE })).toBe("deny");
+ expect(decide("search_directory", { SearchPath: WORKSPACE, Includes: [ path.join(PRIVATE, "settings.json") ] })).toBe("deny");
+ });
+
+ it("sees through a link or a short name that leads into the private folder", () => {
+ const alias = path.join(WORKSPACE, "shortcut");
+ expect(decide("view_file", { AbsolutePath: path.join(alias, "acp_token.json") }, { [path.join(alias, "acp_token.json")]: path.join(PRIVATE, "acp_token.json") })).toBe("deny");
+ });
+
+ it("compares paths case-insensitively where the file system does", () => {
+ const shouted = path.join(HOME, "ANTIGRAVITY-ACP", "acp_token.json");
+ expect(decide("view_file", { AbsolutePath: shouted }, undefined, "win32")).toBe("deny");
+ expect(decide("view_file", { AbsolutePath: shouted }, undefined, "darwin")).toBe("deny");
+ });
+
+ it("allows the read tools elsewhere and leaves every other tool to the permission flow", () => {
+ // brain/ holds the note tools' descriptions and the output of long tool results.
+ expect(decide("view_file", { AbsolutePath: path.join(PRIVATE, "brain", "06ad", "mcp", "trilium", "search_notes.json") })).toBe("allow");
+ expect(decide("search_directory", { Query: "a/b", SearchPath: "." })).toBe("allow");
+ expect(decide("find_file", { Pattern: "*.md", SearchDirectory: WORKSPACE })).toBe("allow");
+ expect(decide("run_command", { CommandLine: "echo hello", Cwd: WORKSPACE })).toBe("ask");
+ expect(decide("search_notes", { Arguments: { query: "Trilium" }, ServerName: "trilium", ToolName: "search_notes" })).toBe("ask");
+ expect(decideAntigravityToolCall("not a tool call", DIRS).decision).toBe("ask");
+ });
+
+ it("tells the agent why it was refused", () => {
+ expect(decideAntigravityToolCall({ toolCall: { name: "view_file", args: { AbsolutePath: PRIVATE } } }, DIRS, { realpath: realpathWith() }))
+ .toEqual({ decision: "deny", reason: expect.stringContaining("note tools") });
+ });
+});
+
+describe("writeAntigravityHooks", () => {
+ beforeEach(() => fs.rmSync(ROOT, { recursive: true, force: true }));
+
+ it("writes a hook that runs the command for every tool, replacing any earlier file", () => {
+ writeAntigravityHooks(HOME, "old");
+ writeAntigravityHooks(HOME, "\"/usr/bin/curl\" --fail");
+
+ const written = JSON.parse(fs.readFileSync(path.join(HOME, "config", "hooks.json"), "utf8"));
+ expect(written).toEqual({
+ "trilium-file-access": {
+ PreToolUse: [ { matcher: ".*", hooks: [ { type: "command", command: "\"/usr/bin/curl\" --fail", timeout: 10 } ] } ]
+ }
+ });
+ });
+});
+
+describe("buildHookCommand", () => {
+ it("posts the tool call to Trilium and fails on anything but a decision", () => {
+ expect(buildHookCommand("C:\\Windows\\System32\\curl.exe", "http://127.0.0.1:5000/hook-abc"))
+ .toBe("\"C:\\Windows\\System32\\curl.exe\" --silent --show-error --fail --max-time 8 --data-binary @- http://127.0.0.1:5000/hook-abc");
+ expect(() => buildHookCommand("/opt/\"odd\"/curl", "http://127.0.0.1:5000/hook-abc")).toThrow(/quote/);
+ });
+});
+
+describe("resolveCurlPath", () => {
+ beforeEach(() => {
+ resetCurlCache();
+ findOnPathMock.mockReset();
+ });
+
+ it("finds curl once, and explains what to install when it is missing", async () => {
+ findOnPathMock.mockResolvedValueOnce(undefined);
+ await expect(resolveCurlPath()).rejects.toThrow(/Google Antigravity needs curl.*Install curl/s);
+
+ findOnPathMock.mockResolvedValue("/usr/bin/curl");
+ await expect(resolveCurlPath()).resolves.toBe("/usr/bin/curl");
+ await expect(resolveCurlPath()).resolves.toBe("/usr/bin/curl");
+ expect(findOnPathMock).toHaveBeenCalledTimes(2);
+ expect(findOnPathMock).toHaveBeenCalledWith("curl");
+ });
+});
diff --git a/apps/server/src/services/llm/providers/antigravity_hook.ts b/apps/server/src/services/llm/providers/antigravity_hook.ts
new file mode 100644
index 0000000000..23a7d0c266
--- /dev/null
+++ b/apps/server/src/services/llm/providers/antigravity_hook.ts
@@ -0,0 +1,171 @@
+/**
+ * Keeps Google's Antigravity ACP server away from its own sign-in.
+ *
+ * The server's read tools (`view_file`, `list_directory`, `search_directory`,
+ * `find_file`) run without asking permission, confined only to the agent cwd
+ * and `<home>/antigravity-acp`. That folder also holds `acp_token.json`, so a
+ * prompt injected through a note could have the agent read the token and copy
+ * it into a note.
+ *
+ * The server runs `PreToolUse` hooks from `<home>/config/hooks.json` before
+ * every tool call, and a hook's `deny` stops the call. A hook that fails also
+ * stops it. Trilium writes a hook there that posts each call to its own
+ * loopback listener (`getAcpHookEndpointUrl`) with `curl`, and
+ * {@link decideAntigravityToolCall} answers. A workspace's `.agents/hooks.json`
+ * would not do: the server asks the user to trust the workspace first.
+ */
+
+import { existsSync, mkdirSync, realpathSync, writeFileSync } from "fs";
+import path from "path";
+
+import { findOnPath } from "./binary_lookup.js";
+
+export interface AntigravityHookDecision {
+ decision: "allow" | "ask" | "deny";
+ reason?: string;
+}
+
+/** The server's home (`GEMINI_HOME`) and the agent cwd. */
+export interface AntigravityDirs {
+ home: string;
+ workspace: string;
+}
+
+/** The tools that read files without asking, by the names the hook receives. */
+const READ_TOOLS = new Set([ "view_file", "list_directory", "search_directory", "find_file" ]);
+
+const DENY_REASON = "Trilium does not allow access to this location. Use Trilium's note tools to read, search and edit the user's notes instead.";
+
+/** How long the server waits for the hook, in seconds; `curl` gives up first. */
+const HOOK_TIMEOUT_S = 10;
+const CURL_MAX_TIME_S = 8;
+
+/**
+ * The answer to one `PreToolUse` call. `deny` when any path in the call's
+ * arguments reaches `<home>/antigravity-acp` other than its `brain/` folder,
+ * or a folder that contains it. Otherwise `allow` for the read tools and
+ * `ask` for the rest: `ask` leaves a tool to the server's permission flow, so
+ * the shell and file edits still reach {@link decideAntigravityPermission}.
+ * `allow` cannot widen the server's own confinement.
+ *
+ * `brain/` stays readable because the agent reads the note tools'
+ * descriptions and the output of long tool results there.
+ */
+export function decideAntigravityToolCall(
+ payload: unknown,
+ dirs: AntigravityDirs,
+ { platform = process.platform, realpath = canonicalPath }: { platform?: NodeJS.Platform; realpath?: (candidate: string) => string } = {}
+): AntigravityHookDecision {
+ const toolCall = (payload as { toolCall?: { name?: unknown; args?: unknown } } | null)?.toolCall;
+ const name = typeof toolCall?.name === "string" ? toolCall.name : undefined;
+
+ const privateDir = realpath(path.join(dirs.home, "antigravity-acp"));
+ const brainDir = path.join(privateDir, "brain");
+ const reached = stringsIn(toolCall?.args)
+ .filter(looksLikePath)
+ .map(candidate => realpath(path.resolve(dirs.workspace, candidate)));
+ const isInside = (child: string, parent: string) => isInsideOn(platform, child, parent);
+ if (reached.some(candidate => (isInside(candidate, privateDir) && !isInside(candidate, brainDir)) || isInside(privateDir, candidate))) {
+ return { decision: "deny", reason: DENY_REASON };
+ }
+ return { decision: name && READ_TOOLS.has(name) ? "allow" : "ask" };
+}
+
+/** Write the hook to `<home>/config/hooks.json`, replacing what an earlier run wrote. */
+export function writeAntigravityHooks(home: string, command: string): void {
+ const configDir = path.join(home, "config");
+ mkdirSync(configDir, { recursive: true });
+ const hooks = {
+ "trilium-file-access": {
+ PreToolUse: [ { matcher: ".*", hooks: [ { type: "command", command, timeout: HOOK_TIMEOUT_S } ] } ]
+ }
+ };
+ writeFileSync(path.join(configDir, "hooks.json"), JSON.stringify(hooks, null, 2));
+}
+
+/**
+ * The hook command: `curl` posts the call (the hook's stdin) to Trilium and
+ * prints the decision. `--fail` turns an error response into a failed hook,
+ * which the server treats as a denial. The server runs it with `sh -c`, or
+ * `cmd /c` on Windows; the URL holds no character either shell reads.
+ */
+export function buildHookCommand(curl: string, hookUrl: string): string {
+ if (curl.includes("\"")) {
+ throw new Error(`Cannot quote the path of curl for the Antigravity hook: ${curl}`);
+ }
+ return `"${curl}" --silent --show-error --fail --max-time ${CURL_MAX_TIME_S} --data-binary @- ${hookUrl}`;
+}
+
+/** The in-flight or successful lookup; a failed one is forgotten so a later install is found. */
+let cachedCurl: Promise<string> | undefined;
+
+/** The absolute path of `curl`, which the hook runs. The path makes it independent of the server's PATH. */
+export function resolveCurlPath(): Promise<string> {
+ if (!cachedCurl) {
+ cachedCurl = findCurl().catch((err: unknown) => {
+ cachedCurl = undefined;
+ throw err;
+ });
+ }
+ return cachedCurl;
+}
+
+/** For tests: forget the found `curl`. */
+export function resetCurlCache(): void {
+ cachedCurl = undefined;
+}
+
+async function findCurl(): Promise<string> {
+ const curl = await findOnPath("curl");
+ if (!curl) {
+ throw new Error("Google Antigravity needs curl, which Trilium uses to control the agent's file access, and curl was not found. Install curl (it ships with Windows 10 and later and with macOS) and make sure it is on PATH.");
+ }
+ return curl;
+}
+
+function stringsIn(value: unknown): string[] {
+ if (typeof value === "string") {
+ return [ value ];
+ }
+ if (Array.isArray(value)) {
+ return value.flatMap(stringsIn);
+ }
+ if (value && typeof value === "object") {
+ return Object.values(value).flatMap(stringsIn);
+ }
+ return [];
+}
+
+function looksLikePath(value: string): boolean {
+ return path.isAbsolute(value) || value.startsWith(".") || /[\\/]/.test(value);
+}
+
+/** Whether `child` is `parent` or lies below it, ignoring case where the platform's file systems do by default. */
+function isInsideOn(platform: NodeJS.Platform, child: string, parent: string): boolean {
+ const fold = (candidate: string) => (platform === "win32" || platform === "darwin" ? candidate.toLowerCase() : candidate);
+ const relative = path.relative(fold(parent), fold(child));
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
+}
+
+/**
+ * The path with links and Windows short names (`ANTIGR~1`) resolved, so an
+ * alias cannot hide where it leads. The part that does not exist yet is kept
+ * as written below the nearest folder that does.
+ */
+function canonicalPath(candidate: string): string {
+ const rest: string[] = [];
+ let existing = candidate;
+ while (!existsSync(existing)) {
+ const parent = path.dirname(existing);
+ if (parent === existing) {
+ return candidate;
+ }
+ rest.unshift(path.basename(existing));
+ existing = parent;
+ }
+ try {
+ return path.join(realpathSync.native(existing), ...rest);
+ } catch {
+ return candidate;
+ }
+}