Skip to content

Build your personal knowledge base with Trilium Notes

feat(llm): add Google Antigravity as a subscription provider (closes #11631)

Elian Doran72f58280b48c
diff --git a/apps/client/src/services/llm_chat.spec.ts b/apps/client/src/services/llm_chat.spec.ts
index 9c2d5756de..165c8822ac 100644
--- a/apps/client/src/services/llm_chat.spec.ts
+++ b/apps/client/src/services/llm_chat.spec.ts
@@ -51,36 +51,37 @@ const config = {} as LlmChatConfig;
describe("fetchProviderModels", () => {
it("posts the provider credentials and returns the models array", async () => {
const models = [{ id: "gpt-4.1", name: "gpt", provider: "openai" }];
- server.post = vi.fn(async () => ({ models })) as typeof server.post;
+ server.postWithTimeout = vi.fn(async () => ({ models })) as typeof server.postWithTimeout;
const query = { provider: "openai", apiKey: "sk-test", baseURL: "http://localhost:11434/v1" };
await expect(fetchProviderModels(query)).resolves.toBe(models);
- expect(server.post).toHaveBeenCalledWith("llm-chat/provider-models", query);
+ // Long enough for a first Google Antigravity sign-in, which runs inside this request.
+ expect(server.postWithTimeout).toHaveBeenCalledWith("llm-chat/provider-models", 6 * 60_000, query);
});
it("defaults to an empty array when models is absent", async () => {
- server.post = vi.fn(async () => ({})) as typeof server.post;
+ server.postWithTimeout = vi.fn(async () => ({})) as typeof server.postWithTimeout;
await expect(fetchProviderModels({ provider: "openai" })).resolves.toEqual([]);
});
it("surfaces the server error message when the request fails", async () => {
// server.post rejects with the raw response body (a { message } JSON string).
- server.post = vi.fn(async () => { throw '{"message":"Authentication failed (HTTP 401) — check the API key."}'; }) as typeof server.post;
+ server.postWithTimeout = vi.fn(async () => { throw '{"message":"Authentication failed (HTTP 401) — check the API key."}'; }) as typeof server.postWithTimeout;
await expect(fetchProviderModels({ provider: "openai", apiKey: "bad" }))
.rejects.toThrow("Authentication failed (HTTP 401) — check the API key.");
});
it("falls back to the raw rejection when it isn't a JSON error body", async () => {
- server.post = vi.fn(async () => { throw "rejected by browser"; }) as typeof server.post;
+ server.postWithTimeout = vi.fn(async () => { throw "rejected by browser"; }) as typeof server.postWithTimeout;
await expect(fetchProviderModels({ provider: "openai" })).rejects.toThrow("rejected by browser");
});
it("uses an Error's message when the rejection is an Error object", async () => {
- server.post = vi.fn(async () => { throw new Error("network down"); }) as typeof server.post;
+ server.postWithTimeout = vi.fn(async () => { throw new Error("network down"); }) as typeof server.postWithTimeout;
await expect(fetchProviderModels({ provider: "openai" })).rejects.toThrow("network down");
});
it("stringifies a non-string, non-Error rejection", async () => {
- server.post = vi.fn(async () => { throw { code: 500 }; }) as typeof server.post;
+ server.postWithTimeout = vi.fn(async () => { throw { code: 500 }; }) as typeof server.postWithTimeout;
await expect(fetchProviderModels({ provider: "openai" })).rejects.toThrow("[object Object]");
});
});
diff --git a/apps/client/src/services/llm_chat.ts b/apps/client/src/services/llm_chat.ts
index 959dea54db..b7b72155bf 100644
--- a/apps/client/src/services/llm_chat.ts
+++ b/apps/client/src/services/llm_chat.ts
@@ -11,6 +11,13 @@ export interface ProviderModelsQuery {
baseURL?: string;
}
+/**
+ * How long the model list can take. Longer than the server's own 5-minute wait
+ * for a Google Antigravity sign-in (`SIGN_IN_TIMEOUT_MS`), which runs inside
+ * this request the first time the models are listed.
+ */
+const PROVIDER_MODELS_TIMEOUT_MS = 6 * 60_000;
+
/**
* Fetch the live model list for a provider from its credentials. Used by the
* model-selection screen while adding or editing a provider — the config need
@@ -19,7 +26,7 @@ export interface ProviderModelsQuery {
*/
export async function fetchProviderModels(query: ProviderModelsQuery): Promise<LlmModelInfo[]> {
try {
- const response = await server.post<{ models?: LlmModelInfo[] }>("llm-chat/provider-models", query);
+ const response = await server.postWithTimeout<{ models?: LlmModelInfo[] }>("llm-chat/provider-models", PROVIDER_MODELS_TIMEOUT_MS, query);
return response.models ?? [];
} catch (error) {
throw new Error(serverErrorMessage(error));
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 4643bb6cb0..acac138149 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4039,6 +4039,7 @@
"beta": "Beta",
"provider_desc_claude_agent": "Requires Claude Code on the machine running Trilium.",
"provider_desc_copilot_agent": "Requires the GitHub Copilot CLI on the machine running Trilium.",
+ "provider_desc_antigravity_agent": "Requires Google's Antigravity ACP server on the machine running Trilium.",
"provider_unavailable_standalone": "Unavailable in the browser version: this provider works by running a separate program on the machine, and there is no machine here to run it on.",
"actions": "Actions",
"delete_provider": "Delete",
@@ -4050,6 +4051,7 @@
"base_url_invalid": "Base URL must be a valid http:// or https:// URL",
"claude_agent_description": "Uses your Claude Pro/Max subscription through Claude Code, so no API key is needed. Claude Code must be installed on the machine running Trilium (the server when self-hosting, or this computer on desktop); sign in once by running \"claude /login\" there.",
"copilot_agent_description": "Uses your GitHub Copilot subscription through the GitHub Copilot CLI, so no API key is needed. The Copilot CLI must be installed on the machine running Trilium (the server when self-hosting, or this computer on desktop); sign in once by running \"copilot login\" there — an existing Copilot login from another editor is reused automatically.",
+ "antigravity_agent_description": "Uses the Gemini quota of your Google account (free, Google AI Pro or Ultra) through Google Antigravity, so no API key is needed. Google's Antigravity ACP server must be downloaded to the machine running Trilium (the server when self-hosting, or this computer on desktop). The first time the models are listed, the Google sign-in page opens in a browser on that machine.",
"add_provider_title_named": "Add {{- name}}",
"provider_group_cloud": "Cloud providers",
"provider_group_cloud_description": "Pay per use with an API key, billed separately from any subscription you already have. Your notes are sent to the provider's servers.",
diff --git a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
index ebb1a24524..609564e802 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
@@ -99,7 +99,7 @@ export interface ProviderType {
*/
const PROVIDER_GROUPS = [
{ id: "cloud", columns: 2, headingKey: "llm.provider_group_cloud", descriptionKey: "llm.provider_group_cloud_description" },
- { id: "subscription", columns: 2, headingKey: "llm.provider_group_subscription", descriptionKey: "llm.provider_group_subscription_description" },
+ { id: "subscription", columns: 3, headingKey: "llm.provider_group_subscription", descriptionKey: "llm.provider_group_subscription_description" },
{ id: "local", columns: 2, headingKey: "llm.provider_group_local", descriptionKey: "llm.provider_group_local_description" },
// Kept apart from the local runtimes: the same card reaches a hosted
// OpenAI-compatible service (OpenRouter, Groq, …), so neither "no usage cost"
@@ -123,6 +123,9 @@ export const PROVIDER_TYPES: ProviderType[] = [
// The same arrangement over the GitHub Copilot CLI, driven in its ACP mode;
// auth belongs to the CLI (`copilot login`).
{ id: "copilot-agent", name: "GitHub Copilot", group: "subscription", defaultBaseUrl: "", iconUrl: PROVIDER_ICONS["copilot-agent"], description: t("llm.provider_desc_copilot_agent"), connectionDescription: t("llm.copilot_agent_description"), beta: true, apiKey: "none", baseUrl: "none", needsHostProcess: true },
+ // Gemini on a Google account through Google's Antigravity ACP server; the server
+ // signs in itself, opening the Google sign-in page the first time models are listed.
+ { id: "antigravity-agent", name: "Google Antigravity", group: "subscription", defaultBaseUrl: "", iconUrl: PROVIDER_ICONS["antigravity-agent"], description: t("llm.provider_desc_antigravity_agent"), connectionDescription: t("llm.antigravity_agent_description"), beta: true, apiKey: "none", baseUrl: "none", needsHostProcess: true },
// The three self-hosted cards share one server-side provider; they differ only in
// the endpoint they prefill and the setup hint they show.
// No blurbs: the group heading already says local/self-hosted, and how to start
diff --git a/apps/client/src/widgets/type_widgets/options/llm/provider_icons.ts b/apps/client/src/widgets/type_widgets/options/llm/provider_icons.ts
index fac5d15a3f..d96834e002 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/provider_icons.ts
+++ b/apps/client/src/widgets/type_widgets/options/llm/provider_icons.ts
@@ -22,6 +22,7 @@ import openAiCompatibleIcon from "./icons/robot.svg?url";
export const PROVIDER_ICONS: Record<string, string> = {
anthropic: anthropicIcon,
+ "antigravity-agent": geminiIcon,
"claude-agent": claudeAgentIcon,
"copilot-agent": githubCopilotIcon,
deepseek: deepseekIcon,
diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.ts
index e63c8ee4b5..f7a4da05b1 100644
--- a/apps/server/src/services/llm/index.spec.ts
+++ b/apps/server/src/services/llm/index.spec.ts
@@ -23,6 +23,7 @@ vi.mock("@triliumnext/core/src/services/llm/tools/registration.js", () => ({
}));
import { registerServerLlmExtensions } from "./index.js";
+import { AntigravityAgentProvider } from "./providers/antigravity_agent.js";
import { ClaudeAgentProvider } from "./providers/claude_agent.js";
import { CopilotAgentProvider } from "./providers/copilot_agent.js";
import { helpTools } from "./tools/help_tools.js";
@@ -32,12 +33,13 @@ describe("registerServerLlmExtensions", () => {
registerServerLlmExtensions();
// The subscription providers, which shell out to the Claude Code and Copilot
- // CLIs, under the types core knows them by. Registered as async factories
+ // CLIs and to Google's Antigravity ACP server, under the types core knows them by. Registered as async factories
// that import their module on first use, so neither the provider nor its
// agent SDK loads until a chat asks for it.
- expect(registrations.hostProviders.map(p => p.type)).toEqual(["claude-agent", "copilot-agent"]);
+ expect(registrations.hostProviders.map(p => p.type)).toEqual(["claude-agent", "copilot-agent", "antigravity-agent"]);
expect(await registrations.hostProviders[0].factory()).toBeInstanceOf(ClaudeAgentProvider);
expect(await registrations.hostProviders[1].factory()).toBeInstanceOf(CopilotAgentProvider);
+ expect(await registrations.hostProviders[2].factory()).toBeInstanceOf(AntigravityAgentProvider);
// The User Guide reader, which core's note-content helper calls for doc notes.
expect(registrations.docNoteReader).toBeTypeOf("function");
// The skill sheets: core owns the catalog and the tool, the server only
diff --git a/apps/server/src/services/llm/index.ts b/apps/server/src/services/llm/index.ts
index 4f0a9d9592..8ada13aae2 100644
--- a/apps/server/src/services/llm/index.ts
+++ b/apps/server/src/services/llm/index.ts
@@ -4,7 +4,7 @@
* 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 providers that spawn the Claude Code and GitHub Copilot
- * CLIs, and the User Guide tools, which read pages off disk. Core exposes a seam
+ * CLIs and Google's Antigravity ACP server, 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.
*
@@ -34,6 +34,7 @@ import { getDocNoteHtml } from "./tools/doc_notes.js";
export function registerServerLlmExtensions() {
registerHostProvider("claude-agent", async () => new (await import("./providers/claude_agent.js")).ClaudeAgentProvider());
registerHostProvider("copilot-agent", async () => new (await import("./providers/copilot_agent.js")).CopilotAgentProvider());
+ registerHostProvider("antigravity-agent", async () => new (await import("./providers/antigravity_agent.js")).AntigravityAgentProvider());
registerDocNoteHtmlReader(getDocNoteHtml);
registerSkillReader(loadSkillSheet);
registerToolRegistryLoader(async () => (await import("./tools/help_tools.js")).helpTools);
diff --git a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
new file mode 100644
index 0000000000..e6fca4353d
--- /dev/null
+++ b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts
@@ -0,0 +1,216 @@
+import type { LlmStreamChunk } from "@triliumnext/commons";
+import os from "os";
+import path from "path";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const infoLogMock = vi.hoisted(() => vi.fn());
+vi.mock("@triliumnext/core", () => ({
+ getLog: () => ({ info: infoLogMock, error: vi.fn() }),
+ // buildSystemPrompt reads the workspace task states; none in this unit test.
+ task_states: { getTaskStates: () => [] }
+}));
+
+const DATA_DIR = path.join(os.tmpdir(), "trilium-antigravity-agent-spec");
+vi.mock("../../data_dir.js", async () => {
+ const os = await import("os");
+ const path = await import("path");
+ return { default: { TRILIUM_DATA_DIR: path.join(os.tmpdir(), "trilium-antigravity-agent-spec") } };
+});
+
+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" }));
+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() }));
+
+class FakeAcpError extends Error {
+ constructor(public readonly code: number, message: string) {
+ super(message);
+ }
+}
+
+const SIGN_IN_REQUIRED = new FakeAcpError(-32000, "Authentication required");
+
+/** Answers like `agy_acp_server`: `session/new` fails until `authenticate` has run, when `signedIn` is false. */
+class FakeAcpClient {
+ static current: FakeAcpClient | undefined;
+ static lastStart: { binary: string; opts: { args?: string[]; env?: Record<string, string>; cwd: string } } | undefined;
+ static signedIn = true;
+ static availableModels: unknown[] = [];
+
+ requests: { method: string; params: unknown }[] = [];
+ onAgentRequest?: (method: string, params: unknown) => unknown;
+
+ static start(binary: string, opts: { args?: string[]; env?: Record<string, string>; cwd: string; onAgentRequest?: (m: string, p: unknown) => unknown }) {
+ FakeAcpClient.lastStart = { binary, opts };
+ FakeAcpClient.current = new FakeAcpClient();
+ FakeAcpClient.current.onAgentRequest = opts.onAgentRequest;
+ return FakeAcpClient.current;
+ }
+
+ async request<T>(method: string, params: unknown): Promise<T> {
+ this.requests.push({ method, params });
+ if (method === "authenticate") {
+ FakeAcpClient.signedIn = true;
+ }
+ if (method === "session/new") {
+ if (!FakeAcpClient.signedIn) throw SIGN_IN_REQUIRED;
+ return { sessionId: "sess-1", models: { currentModelId: "gemini-3.7-flash-high", availableModels: FakeAcpClient.availableModels } } as T;
+ }
+ if (method === "session/prompt") return { stopReason: "end_turn" } as T;
+ return {} as T;
+ }
+
+ notify(): void {}
+ dispose(): void {}
+
+ methods(): string[] {
+ return this.requests.map(r => r.method);
+ }
+}
+
+vi.mock("./acp_client.js", () => ({ AcpClient: FakeAcpClient, AcpError: FakeAcpError }));
+
+const { resetAcpAgentStateForTests } = await import("./acp_agent.js");
+const { AntigravityAgentProvider, buildAntigravityEnv, buildAntigravityModelList, decideAntigravityPermission } = await import("./antigravity_agent.js");
+const { parseBuildLabel } = await vi.importActual<typeof import("./antigravity_binary.js")>("./antigravity_binary.js");
+
+async function collect(iterable: AsyncIterable<LlmStreamChunk>): Promise<LlmStreamChunk[]> {
+ const chunks: LlmStreamChunk[] = [];
+ for await (const chunk of iterable) {
+ chunks.push(chunk);
+ }
+ return chunks;
+}
+
+const REMOTE_MODELS = [
+ { modelId: "gemini-3.8-flash-high", name: "Gemini 3.8 Flash (High)" },
+ { modelId: "gemini-3.8-flash-low", name: "Gemini 3.8 Flash (Low)" },
+ { modelId: "gemini-3.7-flash-low", name: "Gemini 3.7 Flash (Low)" },
+ { modelId: "gemini-pro-agent", name: "Gemini 3.1 Pro (High)" }
+];
+
+const PERMISSION_OPTIONS = [
+ { optionId: "allow_always", name: "Allow Always", kind: "allow_always" },
+ { optionId: "allow", name: "Allow", kind: "allow_once" },
+ { optionId: "deny", name: "Deny", kind: "reject_once" }
+];
+
+beforeEach(() => {
+ resetAcpAgentStateForTests();
+ infoLogMock.mockReset();
+ FakeAcpClient.current = undefined;
+ FakeAcpClient.lastStart = undefined;
+ FakeAcpClient.signedIn = true;
+ FakeAcpClient.availableModels = REMOTE_MODELS;
+});
+
+describe("decideAntigravityPermission", () => {
+ // Shapes captured from agy_acp_server 1.1.1.
+ it("approves once a call to Trilium's note-tools MCP server", () => {
+ expect(decideAntigravityPermission({
+ toolCall: {
+ toolCallId: "fa53",
+ kind: "other",
+ title: "trilium_search_notes",
+ rawInput: { arguments: { query: "x" } },
+ _meta: { mcp: { tool: "search_notes", server: "trilium" }, is_mcp_tool_call: true }
+ },
+ options: PERMISSION_OPTIONS
+ }, "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", () => {
+ const denied = { outcome: { outcome: "selected", optionId: "deny" } };
+ // A shell command, as the server asks for it.
+ expect(decideAntigravityPermission({
+ toolCall: { toolCallId: "385f", kind: "execute", title: "id", rawInput: { CommandLine: "id" } },
+ options: PERMISSION_OPTIONS
+ }, "test")).toEqual(denied);
+ // A tool from an MCP server Trilium did not provide.
+ expect(decideAntigravityPermission({
+ toolCall: { kind: "other", title: "other_fetch", _meta: { mcp: { tool: "fetch", server: "other" }, is_mcp_tool_call: true } },
+ options: PERMISSION_OPTIONS
+ }, "test")).toEqual(denied);
+ // A built-in tool whose title and arguments the model filled with Trilium's name.
+ expect(decideAntigravityPermission({
+ toolCall: { kind: "fetch", title: "trilium_search_notes", rawInput: { Url: "https://example.com/?server=trilium" } },
+ options: PERMISSION_OPTIONS
+ }, "test")).toEqual(denied);
+ // A note-tool call with no one-shot allow on offer is not approved permanently.
+ expect(decideAntigravityPermission({
+ toolCall: { kind: "other", _meta: { mcp: { server: "trilium" }, is_mcp_tool_call: true } },
+ options: [PERMISSION_OPTIONS[0], PERMISSION_OPTIONS[2]]
+ }, "test")).toEqual(denied);
+ });
+});
+
+describe("AntigravityAgentProvider", () => {
+ it("launches the server with a home of Trilium's own and routes permission requests through the policy", async () => {
+ await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], { enableNoteTools: true }));
+
+ const start = FakeAcpClient.lastStart;
+ expect(start?.binary).toBe("/opt/agy/agy_acp_server.par");
+ expect(start?.opts.args).toEqual(process.platform === "linux" ? ["--uid="] : []);
+ expect(start?.opts.env?.GEMINI_HOME).toBe(path.join(DATA_DIR, "antigravity-agent", "home"));
+ expect(start?.opts.cwd).toBe(path.join(DATA_DIR, "antigravity-agent", "workspace"));
+
+ const sessionNew = FakeAcpClient.current?.requests.find(r => r.method === "session/new");
+ expect(sessionNew?.params).toMatchObject({ mcpServers: [{ name: "trilium", type: "http" }] });
+ expect(FakeAcpClient.current?.onAgentRequest?.("session/request_permission", {
+ toolCall: { kind: "execute", title: "rm -rf /" },
+ options: PERMISSION_OPTIONS
+ })).toEqual({ outcome: { outcome: "selected", optionId: "deny" } });
+ });
+
+ 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" }], {}));
+ expect(chunks).toEqual([{ type: "error", error: expect.stringContaining("not signed in") }]);
+ expect(FakeAcpClient.current?.methods()).not.toContain("authenticate");
+
+ const models = await new AntigravityAgentProvider().listModels();
+ expect(FakeAcpClient.current?.methods()).toEqual(["initialize", "session/new", "authenticate", "session/new"]);
+ expect(FakeAcpClient.current?.requests[2].params).toEqual({ methodId: "oauth-personal" });
+ expect(models.map(m => m.id)).toEqual(["default", "gemini-3.8-flash-high", "gemini-3.8-flash-low", "gemini-3.7-flash-low", "gemini-pro-agent"]);
+ });
+
+ it("leaves the default model to the server, selects any other, and titles on the newest Flash Low", async () => {
+ const provider = new AntigravityAgentProvider();
+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));
+ expect(FakeAcpClient.current?.methods()).not.toContain("session/set_model");
+
+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], { model: "gemini-pro-agent" }));
+ expect(FakeAcpClient.current?.requests.find(r => r.method === "session/set_model")?.params).toEqual({ sessionId: "sess-1", modelId: "gemini-pro-agent" });
+
+ await provider.listModels();
+ await provider.generateTitle("plan my week");
+ expect(FakeAcpClient.current?.requests.find(r => r.method === "session/set_model")?.params).toEqual({ sessionId: "sess-1", modelId: "gemini-3.8-flash-low" });
+ expect(provider.recommendedModelIds(await provider.listModels()).size).toBe(5);
+ });
+});
+
+describe("buildAntigravityModelList", () => {
+ it("leads with the server's own default and keeps the server's order and names", () => {
+ expect(buildAntigravityModelList({ availableModels: [{ modelId: "gemini-x" }, { modelId: "default" }, { modelId: "" }] })).toEqual([
+ { id: "default", name: "Default", pricing: { input: 0, output: 0 }, isDefault: true, isSubscription: true },
+ { id: "gemini-x", name: "gemini-x", pricing: { input: 0, output: 0 }, isSubscription: true }
+ ]);
+ });
+});
+
+describe("buildAntigravityEnv", () => {
+ it("points SSL_CERT_FILE at the first CA bundle on Linux, only when unset", () => {
+ const fedora = (file: string) => file === "/etc/pki/tls/certs/ca-bundle.crt";
+ expect(buildAntigravityEnv("/home", "linux", {}, fedora)).toEqual({ GEMINI_HOME: "/home", SSL_CERT_FILE: "/etc/pki/tls/certs/ca-bundle.crt" });
+ expect(buildAntigravityEnv("/home", "linux", { SSL_CERT_FILE: "/mine.pem" }, fedora)).toEqual({ GEMINI_HOME: "/home" });
+ expect(buildAntigravityEnv("/home", "linux", {}, () => false)).toEqual({ GEMINI_HOME: "/home" });
+ expect(buildAntigravityEnv("/home", "darwin", {}, () => true)).toEqual({ GEMINI_HOME: "/home" });
+ });
+});
+
+describe("parseBuildLabel", () => {
+ it("reads the build label, falling back to the first line", () => {
+ expect(parseBuildLabel("Built on Wed Sep 2 2026\nBuild label: agy_acp_server_1.1.1\nBuild tool: Blaze")).toBe("agy_acp_server_1.1.1");
+ expect(parseBuildLabel("agy 2.0\nmore")).toBe("agy 2.0");
+ });
+});
diff --git a/apps/server/src/services/llm/providers/antigravity_agent.ts b/apps/server/src/services/llm/providers/antigravity_agent.ts
new file mode 100644
index 0000000000..a5106e499f
--- /dev/null
+++ b/apps/server/src/services/llm/providers/antigravity_agent.ts
@@ -0,0 +1,202 @@
+/**
+ * Antigravity Agent provider — drives Google's Antigravity ACP server
+ * (`agy_acp_server`) as a subprocess. This lets users with a Google account —
+ * free, Google AI Pro or Ultra — use the in-app chat on Gemini without an API
+ * key: the server signs in with the Google account and bills the account's
+ * Antigravity quota.
+ *
+ * Unlike the Copilot CLI, the server has no command-line switches for its
+ * built-in tools, so the boundary is drawn differently:
+ * - `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;
+ * - every tool that writes, runs a command or reaches the network asks
+ * permission first, and {@link decideAntigravityPermission} approves only
+ * Trilium's note tools.
+ */
+
+import type { 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, denyPermission, describeError, NOTE_TOOLS_MCP_SERVER_NAME } from "./acp_agent.js";
+import { type AcpClient, AcpError } from "./acp_client.js";
+import { resolveAntigravityBinaryPath } from "./antigravity_binary.js";
+
+/** The model id that leaves the session on the model the server picks. */
+const DEFAULT_MODEL_ID = "default";
+
+/**
+ * The catalog available without asking the server. Gemini's line-up moves too
+ * fast to name here, so it holds only the entry that defers to the server's
+ * own default.
+ */
+const AVAILABLE_MODELS: ModelInfo[] = [
+ { id: DEFAULT_MODEL_ID, name: "Default", pricing: { input: 0, output: 0 }, isDefault: true, isSubscription: true }
+];
+
+/**
+ * The sign-in method for a personal Google account, which covers the free tier
+ * and Google AI Pro/Ultra alike. The server also offers `oauth-business`,
+ * `gemini-api-key` and `agent-platform`, which the API-key Gemini provider
+ * already serves better.
+ */
+const SIGN_IN_METHOD = "oauth-personal";
+
+/** How long the add-provider screen waits for the user to finish signing in in the browser. */
+export const SIGN_IN_TIMEOUT_MS = 5 * 60_000;
+
+/** CA bundle locations on common Linux distributions, in the order Go's crypto/x509 tries them. */
+const LINUX_CA_BUNDLES = [
+ "/etc/ssl/certs/ca-certificates.crt",
+ "/etc/pki/tls/certs/ca-bundle.crt",
+ "/etc/ssl/ca-bundle.pem",
+ "/etc/pki/tls/cacert.pem",
+ "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem",
+ "/etc/ssl/cert.pem"
+];
+
+/** The cheap model for the title turn, recorded from the last probe. */
+let titleModel: string | undefined;
+
+export class AntigravityAgentProvider extends AcpAgentProvider {
+ name = "antigravity-agent";
+ protected readonly logLabel = "Antigravity Agent provider";
+ protected readonly fallbackModels = AVAILABLE_MODELS;
+ protected readonly defaultModelId = DEFAULT_MODEL_ID;
+ protected readonly agentDirName = path.join("antigravity-agent", "workspace");
+
+ /** Every model the account is offered: the plan already limits the list, and none costs extra. */
+ recommendedModelIds(models: ModelInfo[]): Set<string> {
+ return new Set(models.map(m => m.id));
+ }
+
+ protected titleModelId(): string | undefined {
+ return titleModel;
+ }
+
+ protected async launchSpec(): Promise<AcpLaunchSpec> {
+ const binary = await resolveAntigravityBinaryPath();
+ return {
+ binary,
+ // The ACP registry launches the Linux build with an empty `--uid=`.
+ args: process.platform === "linux" ? ["--uid="] : [],
+ env: buildAntigravityEnv(path.resolve(dataDirs.TRILIUM_DATA_DIR, "antigravity-agent", "home"))
+ };
+ }
+
+ protected buildModelList(remote: AcpSessionModelState): ModelInfo[] {
+ const models = buildAntigravityModelList(remote);
+ titleModel = pickTitleModel(models);
+ return models;
+ }
+
+ protected decidePermission(request: AcpPermissionRequest): AcpPermissionOutcome {
+ return decideAntigravityPermission(request, this.logLabel);
+ }
+
+ /**
+ * Open a session, signing in first when the server has no saved sign-in and
+ * the user is on the add-provider screen to complete it. The server opens
+ * the Google sign-in page in a browser on the machine running Trilium and
+ * answers `authenticate` once the user has finished there; it keeps the
+ * sign-in under `GEMINI_HOME`, so later sessions need none.
+ */
+ protected async createSession(client: AcpClient, params: AcpNewSessionParams, interactive: boolean, timeoutMs: number) {
+ try {
+ return await super.createSession(client, params, interactive, timeoutMs);
+ } catch (err) {
+ if (!interactive || !isSignInRequired(err)) {
+ throw err;
+ }
+ }
+ await client.request("authenticate", { methodId: SIGN_IN_METHOD }, SIGN_IN_TIMEOUT_MS);
+ return await super.createSession(client, params, interactive, timeoutMs);
+ }
+
+ protected describeFailure(error: unknown): string {
+ const text = describeError(error);
+ if (isSignInRequired(error)) {
+ return "Google Antigravity is not signed in. Open this provider in the AI settings and go to the model selection, which opens the Google sign-in page in a browser on the machine running Trilium.";
+ }
+ if (/"authenticate" timed out/.test(text)) {
+ return "The Google sign-in was not completed in time. Try again, and finish signing in in the browser window that opens on the machine running Trilium.";
+ }
+ if (/ENOENT|spawn/i.test(text)) {
+ return `Failed to start Google's Antigravity ACP server: ${text}`;
+ }
+ return text;
+ }
+}
+
+/**
+ * Approve Trilium's own note tools 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
+ * MCP server's name and `is_mcp_tool_call` — which the server sets itself, so
+ * the model cannot forge them the way it controls a tool call's title and
+ * arguments. Built-in tools (shell, file edits, URL fetch, web search) carry no
+ * such marker and are denied.
+ */
+export function decideAntigravityPermission(request: AcpPermissionRequest, logLabel: string): AcpPermissionOutcome {
+ const meta = request.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;
+ const allowOnce = request.options?.find(o => o.kind === "allow_once");
+ if (isNoteTool && allowOnce) {
+ return { outcome: { outcome: "selected", optionId: allowOnce.optionId } };
+ }
+ return denyPermission(request, logLabel);
+}
+
+/**
+ * The server's catalog, led by the entry that defers to its own default. The
+ * server's order is kept: it is the picker Antigravity itself shows, newest
+ * first.
+ */
+export function buildAntigravityModelList(remote: AcpSessionModelState): ModelInfo[] {
+ const models = (remote.availableModels ?? [])
+ .filter(m => m.modelId && m.modelId !== DEFAULT_MODEL_ID)
+ .map<ModelInfo>(m => ({
+ id: m.modelId,
+ name: m.name ?? m.modelId,
+ pricing: { input: 0, output: 0 },
+ isSubscription: true
+ }));
+ return [...AVAILABLE_MODELS, ...models];
+}
+
+/**
+ * The environment the server runs in. `GEMINI_HOME` gives it a home of
+ * Trilium's own. On Linux, `SSL_CERT_FILE` points it at the system CA bundle
+ * when nothing else does: the server's bundled Python looks for one at a fixed
+ * path that some distributions (NixOS) lack, and every model request then
+ * fails certificate verification.
+ */
+export function buildAntigravityEnv(
+ geminiHome: string,
+ platform = process.platform,
+ env = process.env,
+ fileExists: (file: string) => boolean = existsSync
+): Record<string, string> {
+ const result: Record<string, string> = { GEMINI_HOME: geminiHome };
+ if (platform === "linux" && !env.SSL_CERT_FILE) {
+ const bundle = LINUX_CA_BUNDLES.find(candidate => fileExists(candidate));
+ if (bundle) {
+ result.SSL_CERT_FILE = bundle;
+ }
+ }
+ return result;
+}
+
+/** The newest low-effort Flash model, which the catalog lists first among its peers. */
+function pickTitleModel(models: ModelInfo[]): string | undefined {
+ return models.find(m => /flash-low$/.test(m.id))?.id;
+}
+
+function isSignInRequired(error: unknown): boolean {
+ return error instanceof AcpError && error.code === -32000 && /authentication required/i.test(error.message);
+}
diff --git a/apps/server/src/services/llm/providers/antigravity_binary.ts b/apps/server/src/services/llm/providers/antigravity_binary.ts
new file mode 100644
index 0000000000..0674903d7a
--- /dev/null
+++ b/apps/server/src/services/llm/providers/antigravity_binary.ts
@@ -0,0 +1,95 @@
+/**
+ * Resolves Google's Antigravity ACP server (`agy_acp_server`), which the
+ * Antigravity Agent provider drives.
+ *
+ * Bring-your-own-binary like the other agent providers: nothing is bundled. The
+ * server ships as a zip from Google (the ACP registry's `antigravity-acp`
+ * entry), whose executable is `agy_acp_server.par` on Linux and macOS and
+ * `agy_acp_server.exe` on Windows, next to the `localharness_external` helper it
+ * launches — so it is run from where it was unpacked rather than copied.
+ *
+ * Resolution order: the TRILIUM_ANTIGRAVITY_ACP_PATH override, then the
+ * executable on PATH (see `findOnPath`, which also asks the login shell). The
+ * resolved binary is probed with `--version` once so a broken or wrong-arch
+ * download surfaces as a clear error instead of an opaque spawn failure
+ * mid-chat.
+ */
+
+import { getLog } from "@triliumnext/core";
+import { execFile } from "child_process";
+import { existsSync } from "fs";
+import { promisify } from "util";
+
+import { findOnPath } from "./binary_lookup.js";
+
+const execFileAsync = promisify(execFile);
+
+/** Where the setup steps live; the error messages point there. */
+const SETUP_HINT = "See \"Google Antigravity\" in the AI section of the User Guide for how to download it.";
+
+/**
+ * The in-flight/successful resolution. Caching the promise lets concurrent
+ * first calls share one probe; a failed probe clears it so a later install is
+ * picked up without a restart.
+ */
+let cachedResolution: Promise<string> | undefined;
+
+export function resolveAntigravityBinaryPath(): Promise<string> {
+ if (!cachedResolution) {
+ cachedResolution = probeBinary().catch((err: unknown) => {
+ cachedResolution = undefined;
+ throw err;
+ });
+ }
+ return cachedResolution;
+}
+
+/** For tests: forget the probed binary so the next call re-resolves. */
+export function resetAntigravityBinaryCache(): void {
+ cachedResolution = undefined;
+}
+
+/**
+ * The version from `--version`, which prints the build stamp: its
+ * `Build label: agy_acp_server_1.1.1` line, or the first line when that is
+ * missing.
+ */
+export function parseBuildLabel(output: string): string {
+ return /^Build label:\s*(.+)$/m.exec(output)?.[1].trim() ?? output.split("\n")[0].trim();
+}
+
+async function probeBinary(): Promise<string> {
+ const binary = await locateBinary();
+
+ // Async on purpose — this runs on the first chat request, and a sync probe
+ // would freeze the whole server for up to the timeout.
+ let version: string;
+ try {
+ const { stdout } = await execFileAsync(binary, ["--version"], { timeout: 30000, encoding: "utf8" });
+ version = parseBuildLabel(stdout);
+ } catch (err) {
+ const detail = err instanceof Error ? err.message : String(err);
+ throw new Error(`Found Google's Antigravity ACP server at "${binary}" but it failed to run (${detail}). ${SETUP_HINT}`);
+ }
+
+ getLog().info(`Antigravity Agent provider: using the Antigravity ACP server at ${binary} (${version})`);
+ return binary;
+}
+
+async function locateBinary(): Promise<string> {
+ const override = process.env.TRILIUM_ANTIGRAVITY_ACP_PATH?.trim();
+ if (override) {
+ if (!existsSync(override)) {
+ throw new Error(`TRILIUM_ANTIGRAVITY_ACP_PATH is set to "${override}", but no file exists there.`);
+ }
+ return override;
+ }
+
+ // `findOnPath` appends the Windows extensions itself.
+ const onPath = await findOnPath(process.platform === "win32" ? "agy_acp_server" : "agy_acp_server.par");
+ if (onPath) {
+ return onPath;
+ }
+
+ throw new Error(`Google's Antigravity ACP server (agy_acp_server) was not found. Put the folder it was unpacked into on PATH, or set the TRILIUM_ANTIGRAVITY_ACP_PATH environment variable to the executable. ${SETUP_HINT}`);
+}
diff --git a/packages/trilium-core/src/services/llm/host_providers.ts b/packages/trilium-core/src/services/llm/host_providers.ts
index 452e7645a1..42ea607f1d 100644
--- a/packages/trilium-core/src/services/llm/host_providers.ts
+++ b/packages/trilium-core/src/services/llm/host_providers.ts
@@ -13,7 +13,7 @@ import type { LlmProvider } from "./types.js";
* knows it by.
*
* What they have in common is a dependency on the runtime around them rather
- * than on an API key: both are CLIs this process spawns, authenticating through
+ * than on an API key: each is a CLI this process spawns, authenticating through
* the host's own account plumbing rather than a key the user pastes in. Core
* runs in the browser too, where none of that exists, so the host that *can* do
* it registers a factory at startup with {@link registerHostProvider}. Where
@@ -28,7 +28,9 @@ export const HOST_PROVIDED_TYPES = {
/** Claude Pro/Max through the Claude Agent SDK, authenticated by `claude /login`. */
"claude-agent": "Claude Code",
/** GitHub Copilot through the Copilot CLI's ACP mode, authenticated by `copilot login`. */
- "copilot-agent": "GitHub Copilot"
+ "copilot-agent": "GitHub Copilot",
+ /** A Google account's Gemini quota through Google's Antigravity ACP server, signed in from the provider screen. */
+ "antigravity-agent": "Google Antigravity"
} as const;
/** A provider type from {@link HOST_PROVIDED_TYPES}. */
diff --git a/packages/trilium-core/src/services/llm/index.ts b/packages/trilium-core/src/services/llm/index.ts
index fef3eb46ad..c4aab8309d 100644
--- a/packages/trilium-core/src/services/llm/index.ts
+++ b/packages/trilium-core/src/services/llm/index.ts
@@ -26,7 +26,7 @@ export interface LlmProviderSetup {
}
/** Provider type identifiers that can be instantiated, for error messages. */
-const PROVIDER_TYPES = ["anthropic", "openai", "google", "deepseek", "claude-agent", "copilot-agent", "ollama", "lmstudio", "openai-compatible"];
+const PROVIDER_TYPES = ["anthropic", "openai", "google", "deepseek", "claude-agent", "copilot-agent", "antigravity-agent", "ollama", "lmstudio", "openai-compatible"];
/**
* Instantiate a provider from its type identifier.
@@ -65,6 +65,8 @@ async function createProviderInstance(provider: string, apiKey: string, baseURL?
return await createHostProvider("claude-agent");
case "copilot-agent":
return await createHostProvider("copilot-agent");
+ case "antigravity-agent":
+ return await createHostProvider("antigravity-agent");
// 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.