From 48caed2d3af7b1e4551e26d40cbaf16feb6af4b9 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 24 Nov 2026 16:44:02 -0600 Subject: [PATCH] feat(antigravity): swarms use the CLI's own default channel, and say which Google account they run on Google's app and CLI use Google's default channel, where Gemini 4 Neon is offered; Paperclip forced the stable endpoint, which offers no Neon and bills a separately exhausted pool. The swarm route now passes no endpoint override by default. The deployment can pin Google's stable channel with the server env PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL (provider_default | stable); a Neon refusal on stable names that fix. The start step names the channel, and the Runner compares the CLI's own sign-in (from its log) with the agent's connection as digests only, showing a plain notice when they differ. Also: a resent accepted /swarm returns its original receipt before any availability check, and the request text is used verbatim (the composer removes the one /swarm the user typed). Co-Authored-By: Claude Opus 5.5 --- .../2026-11-22-antigravity-qualification.md | 20 +++++++ docs/api/issues.md | 12 ++-- .../acpx/antigravity-swarm-guard.test.ts | 8 +++ .../drivers/acpx/antigravity-swarm-guard.ts | 8 ++- .../acpx/antigravity-swarm-route.test.ts | 23 +++++++- .../drivers/acpx/antigravity-swarm-route.ts | 58 +++++++++++++++++-- .../acpx/antigravity-swarm-runtime.test.ts | 20 ++++++- .../drivers/acpx/antigravity-swarm-runtime.ts | 45 ++++++++++++-- .../src/drivers/acpx/runtime-host.ts | 8 ++- .../antigravity-swarm-request-path.test.ts | 6 +- .../issue-comment-reopen-routes.test.ts | 17 ++++++ server/src/routes/issues.ts | 8 ++- server/src/services/ai-connection-runtime.ts | 2 + .../src/services/antigravity-swarm.db.test.ts | 16 +++-- server/src/services/antigravity-swarm.ts | 11 +++- .../services/heartbeat/runtime-execution.ts | 2 + .../antigravity-runner-credentials.test.ts | 31 ++++++++-- .../antigravity-runner-credentials.ts | 28 ++++++++- .../native-runtime/native-session-executor.ts | 6 +- 19 files changed, 284 insertions(+), 45 deletions(-) diff --git a/doc/plans/2026-11-22-antigravity-qualification.md b/doc/plans/2026-11-22-antigravity-qualification.md index aa5b5845db4..15c0d749fff 100644 --- a/doc/plans/2026-11-22-antigravity-qualification.md +++ b/doc/plans/2026-11-22-antigravity-qualification.md @@ -97,6 +97,26 @@ It is the route for native `/swarm` (experimental, off by default; see environment `AGY_CLI_DISABLE_AUTO_UPDATE=1`. The endpoint, `--gemini-dir`, modes and other flags are driver policy and are not pinned here. +## Swarm channel (2026-11-24) + +The swarm route runs Google's Antigravity CLI (`agy acp`). On one paid sign-in, +the CLI's default channel (`daily-cloudcode-pa`, the one Google's app and CLI +use) offered 27 models, including Gemini 4 Neon at four levels, and answered a +Neon prompt. Google's stable endpoint (`cloudcode-pa`) offered 13 models and +no Neon, and its CLI quota pool (project `default-cli-project`, consumer +sign-in) was exhausted while the same account's ordinary route answered. + +- The deployment chooses the channel with the server environment variable + `PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL`: `provider_default` (default; no + endpoint override, so the pinned CLI uses Google's default channel, which is + not Google's stable channel and can change with less notice) or `stable`. +- The swarm's start step names the channel, and the run's diagnostics record + it and whether the CLI's own sign-in is the agent's Google connection + (`matches`, `does_not_match` or `unknown`). The CLI shows its account only in + its own log; the Runner compares digests and never records the account. +- A usage limit on the swarm route holds only further swarms (quota scope + `antigravity_cli`); ordinary work on the same account continues. + ## Routes to Neon State as of the end of 2026-11-22. "Admitted" means the patched server returned diff --git a/docs/api/issues.md b/docs/api/issues.md index 19c0df9b8db..604fe472d44 100644 --- a/docs/api/issues.md +++ b/docs/api/issues.md @@ -261,10 +261,12 @@ Agent @-mentions are context only and do not trigger heartbeats. Normal comment ``` POST /api/issues/{issueId}/comments -{ "body": "/swarm write the tests for the parser", "nativeCommand": "swarm" } +{ "body": "write the tests for the parser", "nativeCommand": "swarm", "clientRequestId": "" } ``` -The optional `nativeCommand` field accepts only `"swarm"`. It asks the task's Google Antigravity assignee to run the comment as a swarm with helpers. The swarm's only instruction is the comment text, without a leading `/swarm`. Comment text alone is never read as a command: without `nativeCommand`, `/swarm` is ordinary text. +The optional `nativeCommand` field accepts only `"swarm"`. It asks the task's Google Antigravity assignee to run the comment as a swarm with helpers. With `nativeCommand`, `body` is the request itself, used verbatim (trimmed) as the swarm's only instruction: do not include the `/swarm` command (the board composer removes the one the user typed). Nothing strips another one, so a body of `/swarm explain this` asks the swarm about `/swarm explain this`. Comment text alone is never read as a command: without `nativeCommand`, `/swarm` is ordinary text. + +A resend with the same `clientRequestId` returns the original comment, even if the checks below would now refuse a new request (for example after the setting was turned off). Nothing is posted or started twice. Only a signed-in board user can send `nativeCommand`. Any other caller, such as an agent, gets `403` with `Only a signed-in user can start a swarm`. @@ -276,10 +278,10 @@ The endpoint refuses these requests with `422` and `{ "error": "", "cod | The instance setting is off | `Swarm is not turned on for this Paperclip. An instance admin can turn on "Google Antigravity swarm" in Settings, Experimental.` | | The assignee is not a Google Antigravity agent | `Swarm works only for tasks assigned to a Google Antigravity agent.` | | The task is in Plan mode | `Swarm is not available while the task is in Plan mode: helpers change files. Approve the plan first, then send /swarm.` | -| Nothing follows `/swarm` | `This swarm has no request to run. Send /swarm followed by what the swarm should do.` | -| More than 16,000 characters follow `/swarm` | `This swarm request is too long. Keep what follows /swarm under 16,000 characters.` | +| `body` is empty | `This swarm has no request to run. Send /swarm followed by what the swarm should do.` | +| `body` is longer than 16,000 characters | `This swarm request is too long. Keep what follows /swarm under 16,000 characters.` | -A later `/swarm` on the same task replaces an earlier request that has not completed. The earlier request never runs, neither as a swarm nor as ordinary work. Other comments sent in the meantime reach the agent in an ordinary turn, never inside the swarm's request. +Deleting a request comment withdraws it: the swarm does not run and later work is ordinary. A later `/swarm` on the same task replaces an earlier request that has not completed. The earlier request never runs, neither as a swarm nor as ordinary work. Other comments sent in the meantime reach the agent in an ordinary turn, never inside the swarm's request. ### Discard a Queued Comment diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.test.ts index 44f81214376..8a5881fff9c 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.test.ts @@ -164,6 +164,14 @@ describe("Antigravity CLI swarm guard (replaces the registry admission receipt)" expect(error.diagnostic).toContain("gpt-oss-120b-medium"); }); + it("names the fix when the deployment pinned Google's stable channel", () => { + const guard = createAntigravitySwarmGuard({ model: "gemini-4-neon-low", instructions: INSTRUCTIONS, workspace: WORKSPACE, channel: "stable" }); + guard.initialize(initializeResult()); + guard.sessionRequest(sessionRequest()); + expect(() => guard.sessionResult(STABLE_ENDPOINT_SESSION)).toThrow( + "Swarm is not available with Gemini 4 Neon (Low) on Google's stable channel, so nothing was changed: an admin can switch swarms to Google's default channel, or choose another model for this agent, such as Gemini 4 Argon, and send /swarm again."); + }); + it("admits every Neon level the daily endpoint lists, reading family and thinking level back separately", () => { for (const [level, cliLevel] of [["low", "low"], ["medium", "medium"], ["high", "high"], ["xhigh", "xhigh"]]) { const guard = open(`gemini-4-neon-${level}`, DAILY_ENDPOINT_SESSION); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts index 35f0c3a3793..6c7d7c350c4 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts @@ -126,6 +126,8 @@ export interface AntigravitySwarmReceipt { export interface AntigravitySwarmGuardOptions { model: string; + /** The Google channel the CLI was launched on; a refusal on `stable` names the fix. */ + channel?: "provider_default" | "stable"; instructions: string; workspace: string; } @@ -210,8 +212,10 @@ export function createAntigravitySwarmGuard(options: AntigravitySwarmGuardOption // model, so a missing entry means the CLI does not serve it (seen live: Google's // stable endpoint, which this route uses, offers no Gemini 4 Neon). const suggestion = defaultFamilyName(value); - throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", - `Swarm is not available with ${antigravitySwarmModelName(model)} yet, so nothing was changed: choose another model for this agent${suggestion ? `, such as ${suggestion},` : ""} and send /swarm again.`, + const another = `choose another model for this agent${suggestion ? `, such as ${suggestion},` : ""} and send /swarm again`; + throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", options.channel === "stable" + ? `Swarm is not available with ${antigravitySwarmModelName(model)} on Google's stable channel, so nothing was changed: an admin can switch swarms to Google's default channel, or ${another}.` + : `Swarm is not available with ${antigravitySwarmModelName(model)} yet, so nothing was changed: ${another}.`, { category: "model_unavailable", diagnostic: `The Antigravity CLI offered ${offered.length} models and not ${model}: ${offered.slice(0, MAX_DIAGNOSTIC_MODELS).map(entry => entry.id).join(", ") || "none"}` }); } diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts index dfc504e4533..bf5b9b6d58b 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts @@ -5,7 +5,7 @@ import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js"; import { PRP_BLOCK_TOOL_NAME, PRP_COMPLETION_TOOL_NAME } from "../../contracts/completion-result.js"; -import { antigravityRouteChangeRefusal, antigravitySwarmTools, antigravitySwarmArguments, antigravitySwarmLaunchEnvironment, antigravitySwarmRouteRefusal, isAntigravitySwarmRoute } from "./antigravity-swarm-route.js"; +import { antigravityAccountDigest, antigravityRouteChangeRefusal, antigravitySwarmBinding, antigravitySwarmTools, antigravitySwarmArguments, antigravitySwarmLaunchEnvironment, antigravitySwarmRouteRefusal, isAntigravitySwarmRoute } from "./antigravity-swarm-route.js"; import { createAcpxModeBinding, resolveAcpxProviderMode } from "./provider-mode.js"; import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; @@ -33,9 +33,14 @@ describe("Antigravity swarm route selection", () => { .toMatchObject({ code: "ANTIGRAVITY_SWARM_UNAVAILABLE", message: expect.stringMatching(/Gemini API key/) }); }); - it("launches with private CLI state, the stable endpoint, self-update off and no registry credentials", () => { + it("launches on the CLI's own default channel unless the deployment pins stable, with private state and log, self-update off and no registry credentials", () => { + // Google's default channel is what Google's app and CLI use; on 2026-11-24 only it offered Gemini 4 Neon. expect(antigravitySwarmArguments("/home/run/antigravity-cli")).toEqual([ - "--gemini-dir", "/home/run/antigravity-cli", "--cloud_code_endpoint", "https://cloudcode-pa.googleapis.com", "--disable-telemetry", + "--gemini-dir", "/home/run/antigravity-cli", "--log-file", "/home/run/antigravity-cli/cli.log", "--disable-telemetry", + ]); + expect(antigravitySwarmArguments("/home/run/antigravity-cli", "stable")).toEqual([ + "--gemini-dir", "/home/run/antigravity-cli", "--log-file", "/home/run/antigravity-cli/cli.log", + "--cloud_code_endpoint", "https://cloudcode-pa.googleapis.com", "--disable-telemetry", ]); const environment = antigravitySwarmLaunchEnvironment( { HOME: "/private/home", GEMINI_HOME: "/private", AGY_ACP_FORCE_FILE_STORAGE: "1", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "s", GEMINI_API_KEY: "k", PATH: "/usr/bin" }, @@ -44,6 +49,18 @@ describe("Antigravity swarm route selection", () => { expect(antigravitySwarmLaunchEnvironment({ HOME: "/private/home" }, { agentHomeDirectory: "/private", platform: "darwin", realHome: "/Users/owner" }).HOME).toBe("/Users/owner"); }); + it("reads the channel and the connection account digest the controller bound to the credential, defaulting safely", () => { + const digest = antigravityAccountDigest("Owner@Example.test"); + expect(digest).toBe(antigravityAccountDigest(" owner@example.test ")); + // Pinned: the server's antigravityAccountDigest pins the same value for the connection account. + expect(antigravityAccountDigest("owner@example.test")).toBe("0fde1d32467703827f511884b66298187e2944f4bfe260303f893a0af908f81e"); + const bound = (paperclip: unknown) => ({ PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: JSON.stringify({ refresh_token: "r", paperclip }) }); + expect(antigravitySwarmBinding(bound({ swarmChannel: "stable", accountSha256: digest }))).toEqual({ channel: "stable", accountDigest: digest }); + expect(antigravitySwarmBinding(bound({ swarmChannel: "daily", accountSha256: "nope" }))).toEqual({ channel: "provider_default", accountDigest: null }); + expect(antigravitySwarmBinding({ PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "not json" })).toEqual({ channel: "provider_default", accountDigest: null }); + expect(antigravitySwarmBinding({})).toEqual({ channel: "provider_default", accountDigest: null }); + }); + it("keeps every Paperclip operation that creates or hands off work out of a swarm turn, as the production catalog names them", () => { const delegating = ["create_task", "reassign_task", "set_dependencies", "hire_agent", "call_api", "create_project", "create_case", "update_case", "handoff_case", "create_workflow", "update_workflow", "update_routine", "create_area", "create_responsibility"]; diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts index 85d8cd813f4..c1e87497739 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { userInfo } from "node:os"; import { join } from "node:path"; import { canonicalRunnerToolName } from "../runner-tool-bridge.js"; @@ -17,9 +18,53 @@ export function antigravitySwarmStateDirectory(agentHomeDirectory: string): stri return join(agentHomeDirectory, "antigravity-cli"); } -/** Driver-owned CLI flags: private state, stable endpoint, no telemetry. Self-update is off through the pinned environment. */ -export function antigravitySwarmArguments(stateDirectory: string): string[] { - return ["--gemini-dir", stateDirectory, "--cloud_code_endpoint", ANTIGRAVITY_CLI_STABLE_ENDPOINT, "--disable-telemetry"]; +/** + * Which Google channel the CLI talks to. `provider_default` passes no endpoint, + * so the pinned CLI uses its own default (Google's daily channel, the one + * Google's own app and CLI use, which can change with less notice); `stable` + * pins Google's stable endpoint (which, on 2026-11-24, offered no Gemini 4 Neon). + * The deployment chooses it (server env PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL). + */ +export type AntigravitySwarmChannel = "provider_default" | "stable"; + +/** Plain words for the channel, for the swarm's start step and diagnostics. */ +export function antigravitySwarmChannelLabel(channel: AntigravitySwarmChannel): string { + return channel === "stable" ? "Google's stable channel" : "Google's default channel"; +} + +/** The CLI's own log inside its private state; it records which Google account the CLI signed in with. */ +export function antigravitySwarmLogFile(stateDirectory: string): string { + return join(stateDirectory, "cli.log"); +} + +/** Driver-owned CLI flags: private state and log, the channel, no telemetry. Self-update is off through the pinned environment. */ +export function antigravitySwarmArguments(stateDirectory: string, channel: AntigravitySwarmChannel = "provider_default"): string[] { + return ["--gemini-dir", stateDirectory, "--log-file", antigravitySwarmLogFile(stateDirectory), + ...(channel === "stable" ? ["--cloud_code_endpoint", ANTIGRAVITY_CLI_STABLE_ENDPOINT] : []), "--disable-telemetry"]; +} + +/** A one-way, non-identifying form of a Google account for comparing the CLI's sign-in with the connection. */ +export function antigravityAccountDigest(email: string): string { + return createHash("sha256").update(`paperclip.antigravity-account.v1:${email.trim().toLowerCase()}`, "utf8").digest("hex"); +} + +/** + * Run facts the controller binds to the selected Google credential (the + * `paperclip` member of the credential document; the credential sanitizer drops + * it before anything is written): the swarm channel and the connection + * account's digest. Absent or malformed facts fall back to the provider default + * channel and an unknown account. + */ +export function antigravitySwarmBinding(environment: NodeJS.ProcessEnv): { channel: AntigravitySwarmChannel; accountDigest: string | null } { + let facts: Record = {}; + try { + const parsed = JSON.parse(environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET ?? "{}") as Record; + if (parsed?.paperclip && typeof parsed.paperclip === "object" && !Array.isArray(parsed.paperclip)) facts = parsed.paperclip as Record; + } catch { /* the route refusal reports a missing credential */ } + return { + channel: facts.swarmChannel === "stable" ? "stable" : "provider_default", + accountDigest: typeof facts.accountSha256 === "string" && /^[a-f0-9]{64}$/.test(facts.accountSha256) ? facts.accountSha256 : null, + }; } /** @@ -44,9 +89,10 @@ export function antigravitySwarmRouteRefusal(input: { environment: NodeJS.Proces */ export async function verifyAntigravitySwarmInstallation( stateDirectory: () => string, - options: Omit = {}, + options: Omit & { channel?: AntigravitySwarmChannel } = {}, ): Promise { - const pinned = await resolveAntigravityCliLaunch(options).catch((error: unknown) => { + const { channel, ...launchOptions } = options; + const pinned = await resolveAntigravityCliLaunch(launchOptions).catch((error: unknown) => { // The runtime-missing and unsupported-platform messages are written for people; keep them visible. if (error instanceof AntigravityCliRuntimeError) throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", `Swarm is not available on this computer: ${error.message}`); throw error; @@ -56,7 +102,7 @@ export async function verifyAntigravitySwarmInstallation( agentServerPackageJsonPath: null, agentRuntimePackageJsonPath: null, async openCommand(open?: { signal?: AbortSignal }) { - const launch = await resolveAntigravityCliLaunch({ ...options, arguments: antigravitySwarmArguments(stateDirectory()) }); + const launch = await resolveAntigravityCliLaunch({ ...launchOptions, arguments: antigravitySwarmArguments(stateDirectory(), channel) }); if (launch.commandDigest !== pinned.commandDigest) throw new Error("Antigravity CLI installation changed during admission"); return launch.installation.openCommand(open); }, diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts index ed3a1540307..8f892e0cbd0 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts @@ -1,10 +1,11 @@ import { spawn } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import type { AcpRuntimeEvent } from "acpx/runtime"; -import { openAntigravitySwarmRuntime, type AntigravitySwarmStage } from "./antigravity-swarm-runtime.js"; +import { antigravityCliAccountMatch, openAntigravitySwarmRuntime, type AntigravitySwarmStage } from "./antigravity-swarm-runtime.js"; +import { antigravityAccountDigest } from "./antigravity-swarm-route.js"; import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; import type { AcpxTerminalSessionFailure } from "./provider-failure.js"; @@ -99,6 +100,19 @@ describe("Antigravity CLI swarm runtime", () => { expect(clientMessages().map(message => message.method)).not.toEqual(expect.arrayContaining(["session/set_mode"])); }); + it("tells whether the CLI's own sign-in is the agent's Google connection, comparing digests only", async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "agy-account-"))); + roots.push(root); + const log = join(root, "cli.log"); + writeFileSync(log, "I1124 15:50:23.723290 24 server_oauth.go:221] applyAuthResult: email=owner@example.test, authMethod=consumer, quotaProject=\n"); + expect(await antigravityCliAccountMatch(log, antigravityAccountDigest("Owner@Example.test"))).toBe("matches"); + expect(await antigravityCliAccountMatch(log, antigravityAccountDigest("someone-else@example.test"))).toBe("does_not_match"); + expect(await antigravityCliAccountMatch(log, null)).toBe("unknown"); + expect(await antigravityCliAccountMatch(join(root, "missing.log"), antigravityAccountDigest("owner@example.test"))).toBe("unknown"); + writeFileSync(log, "no sign-in yet\n"); + expect(await antigravityCliAccountMatch(log, antigravityAccountDigest("owner@example.test"))).toBe("unknown"); + }); + it("runs a native swarm whose files land in the task folder, in plain steps, with coordinator-reported usage", async () => { const run = await runTurn("success"); expect(run.result).toMatchObject({ status: "completed" }); @@ -107,7 +121,7 @@ describe("Antigravity CLI swarm runtime", () => { "Started helper writer-a: Write a.txt containing exactly 'A' in the current workspace directory", "Checked on the helpers", "Files changed in the task folder: a.txt, b.txt", ])); - expect(run.titles).toContainEqual(expect.stringMatching(/^Swarm started in the task folder with Gemini 3\.8 Flash \(Low\) \(Antigravity CLI 1\.5\.15\)\. /)); + expect(run.titles).toContainEqual(expect.stringMatching(/^Swarm started in the task folder with Gemini 3\.8 Flash \(Low\) on Google's default channel \(Antigravity CLI 1\.5\.15\)\. /)); expect(run.titles.some(title => /approved automatically/.test(title))).toBe(true); expect(run.text).not.toContain("/swarm board"); expect(run.clientMessages().find(message => message.method === "session/prompt").params.prompt[0].text).toMatch(/^\/swarm /); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts index 349ee036117..31641023f99 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts @@ -1,11 +1,12 @@ import type { ChildProcess, ChildProcessWithoutNullStreams } from "node:child_process"; -import { lstat, readdir } from "node:fs/promises"; +import { lstat, open as openFile, readdir } from "node:fs/promises"; import { join, relative, sep } from "node:path"; import type { AcpRuntimeEvent, AcpRuntimeTurnResult } from "acpx/runtime"; import { userInfo } from "node:os"; import { AntigravitySavedStateIncompatibleError } from "./antigravity-admission.js"; import { retireAntigravityProcess } from "./antigravity-process.js"; import { antigravityOutsideChange } from "./antigravity-swarm-paths.js"; +import { antigravityAccountDigest, antigravitySwarmChannelLabel, antigravitySwarmLogFile } from "./antigravity-swarm-route.js"; import { ANTIGRAVITY_CLI_SESSION_MODE, ANTIGRAVITY_SWARM_MCP_SERVER, ANTIGRAVITY_SWARM_MODE, AntigravitySwarmError, antigravitySwarmWorkspaceEscape, classifyAntigravityRefusalText, createAntigravitySwarmGuard, @@ -252,6 +253,33 @@ function failed(code: string, message: string): AcpRuntimeTurnResult { const line = (id: string, title: string): AcpRuntimeEvent => ({ type: "tool_call", tag: "tool_call", toolCallId: `paperclip-swarm-${id}`, text: title, title, kind: "other", status: "completed" }); +export type AntigravityCliAccountMatch = "matches" | "does_not_match" | "unknown"; +const CLI_LOG_TAIL_BYTES = 512 * 1024; + +/** + * Whether the Google account the CLI signed in with is the agent's connection + * account. The CLI exposes its sign-in only in its own log (`applyAuthResult: + * email=…`; ACP `initialize` carries no account). Both sides are compared as + * digests inside the Runner; neither account is returned, logged or stored. + */ +export async function antigravityCliAccountMatch(logFile: string, connectionDigest: string | null): Promise { + if (!connectionDigest) return "unknown"; + let text = ""; + try { + const file = await openFile(logFile, "r"); + try { + const { size } = await file.stat(); + const length = Math.min(size, CLI_LOG_TAIL_BYTES); + const buffer = Buffer.alloc(length); + await file.read(buffer, 0, length, size - length); + text = buffer.toString("utf8"); + } finally { await file.close(); } + } catch { return "unknown"; } + const signedIn = [...text.matchAll(/applyAuthResult: email=([^\s,]+@[^\s,]+),/g)].at(-1)?.[1]; + if (!signedIn) return "unknown"; + return antigravityAccountDigest(signedIn) === connectionDigest ? "matches" : "does_not_match"; +} + export async function openAntigravitySwarmRuntime( options: AcpxRuntimePortOpenOptions, dependencies: AntigravitySwarmRuntimeDependencies = {}, @@ -279,7 +307,8 @@ export async function openAntigravitySwarmRuntime( if (!bridge) throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "Swarm needs Paperclip's own tools, which are not available for this run."); const home = options.launchEnvironment.HOME ?? userInfo().homedir; const instructions = [options.systemInstructions, ANTIGRAVITY_SWARM_INSTRUCTIONS].filter(Boolean).join("\n\n"); - const guard = createAntigravitySwarmGuard({ model, instructions, workspace: options.cwd }); + const channel = options.antigravitySwarm?.channel ?? "provider_default"; + const guard = createAntigravitySwarmGuard({ model, instructions, workspace: options.cwd, channel }); options.assertWorkspaceHeld?.(); const lifetime = options.credentialFenceFds && options.activateCredentialFenceOwner @@ -323,6 +352,7 @@ export async function openAntigravitySwarmRuntime( let sessionId: string; let receipt: AntigravitySwarmReceipt; + let cliAccount: AntigravityCliAccountMatch = "unknown"; // A Stop during admission retires the CLI at once; every await re-checks it. const abortAdmission = () => { void retire().catch(() => undefined); }; options.signal?.addEventListener("abort", abortAdmission, { once: true }); @@ -365,6 +395,9 @@ export async function openAntigravitySwarmRuntime( await connection.drain(); guard.assertSwarmCommand(); receipt = guard.receipt(); + cliAccount = options.antigravityStateDirectory + ? await antigravityCliAccountMatch(antigravitySwarmLogFile(options.antigravityStateDirectory), options.antigravitySwarm?.accountDigest ?? null) + : "unknown"; if (protocolFailure) throw protocolFailure; options.signal?.throwIfAborted(); } catch (error) { @@ -376,7 +409,8 @@ export async function openAntigravitySwarmRuntime( } options.signal?.removeEventListener("abort", abortAdmission); - const status: Json = { antigravitySwarmReceipt: receipt }; + // Diagnostics only: the channel and whether the CLI's own sign-in is the agent's connection account (never the account itself). + const status: Json = { antigravitySwarmReceipt: { ...receipt, channel, cliAccountMatchesConnection: cliAccount } }; let turns = 0; let active: { cancel(reason?: string): Promise; result: Promise } | null = null; let closed = false; @@ -408,7 +442,10 @@ export async function openAntigravitySwarmRuntime( let transcript = ""; let stop: AntigravitySwarmError | null = null; const halt = (error: AntigravitySwarmError) => { stop ??= error; connection.notify("session/cancel", { sessionId }); wake?.(); }; - events.push(line("setup", `Swarm started in the task folder with ${receipt.modelName} (Antigravity CLI ${receipt.agentVersion}). Helper changes inside the task folder are approved automatically; anything else is blocked.`)); + events.push(line("setup", `Swarm started in the task folder with ${receipt.modelName} on ${antigravitySwarmChannelLabel(channel)} (Antigravity CLI ${receipt.agentVersion}). Helper changes inside the task folder are approved automatically; anything else is blocked.`)); + if (cliAccount === "does_not_match") { + events.push(line("account", "This swarm runs on the Google account signed in to this computer, which is different from this agent's Google connection.")); + } updateListener = params => { try { guard.observe(params); } catch (error) { diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index 9b68fa1864b..b15c34bca4a 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts @@ -23,7 +23,7 @@ import { stageManagedGrokCredential } from "./grok-credentials.js"; import { stageManagedAntigravityCredential } from "./antigravity-credentials.js"; import { claudeNativeSkillPrompt } from "./native-skill-prompt.js"; import { prepareStdioMcpBindings } from "../stdio-mcp.js"; -import { antigravityRouteChangeRefusal, antigravitySwarmLaunchEnvironment, antigravitySwarmTools, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js"; +import { antigravityRouteChangeRefusal, antigravitySwarmBinding, antigravitySwarmLaunchEnvironment, type AntigravitySwarmChannel, antigravitySwarmTools, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js"; import type { AcpRuntimeOptions, @@ -209,6 +209,8 @@ export interface AcpxRuntimePortOpenOptions { stateDirectory: string; /** The Antigravity CLI's private `--gemini-dir` for this run (swarm route only). */ antigravityStateDirectory?: string; + /** Swarm route only: the Google channel and the connection account's digest (antigravitySwarmBinding). */ + antigravitySwarm?: { channel: AntigravitySwarmChannel; accountDigest: string | null }; providerSessionKey: string; permissionMode: NativeAcpxPermissionMode; readOnly?: boolean; @@ -456,6 +458,7 @@ export class AcpxRuntimeHost { const refusal = antigravitySwarmRouteRefusal({ environment: options.environment ?? {} }); if (refusal) throw refusal; } + const swarmBinding = swarmRoute ? antigravitySwarmBinding(options.environment ?? {}) : null; let swarmStateDirectory: string | null = null; const installation = await runAbortableAdmissionStage( options.signal, @@ -467,7 +470,7 @@ export class AcpxRuntimeHost { ? verifyAntigravitySwarmInstallation(() => { if (swarmStateDirectory === null) throw new Error("Antigravity CLI state directory is not prepared"); return swarmStateDirectory; - }) + }, { channel: swarmBinding!.channel }) : verifyAcpxProfileInstallation(profile, options.candidateAdmission), dependencies.retainAdmissionCleanup, ).catch(error => { throw recordAcpxAdmissionFailure(error, "installation"); }); @@ -728,6 +731,7 @@ export class AcpxRuntimeHost { cwd: binding.workspacePath, stateDirectory: sandbox.stateDirectory, ...(swarmStateDirectory === null ? {} : { antigravityStateDirectory: swarmStateDirectory }), + ...(swarmBinding === null ? {} : { antigravitySwarm: swarmBinding }), providerSessionKey: binding.profileSessionKey, restoringSession: options.expectedIdentity !== undefined, permissionMode: binding.permissionMode, diff --git a/server/src/__tests__/antigravity-swarm-request-path.test.ts b/server/src/__tests__/antigravity-swarm-request-path.test.ts index 1701b099c7a..1e442ec9074 100644 --- a/server/src/__tests__/antigravity-swarm-request-path.test.ts +++ b/server/src/__tests__/antigravity-swarm-request-path.test.ts @@ -30,7 +30,7 @@ describe.skipIf(!support.supported)("the /swarm request path to the CLI", () => }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); - it("sends byte for byte the recorded comment minus the command, never a merged wake's agent comment or the description", async () => { + it("sends byte for byte the recorded comment (the request the composer sent), never a merged wake's agent comment or the description", async () => { const [company] = await db.insert(companies).values({ name: "Swarm", issuePrefix: `P${randomUUID().slice(0, 4)}` }).returning(); const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Gemma", adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low" } }).returning(); @@ -38,7 +38,7 @@ describe.skipIf(!support.supported)("the /swarm request path to the CLI", () => status: "todo", assigneeAgentId: agent!.id }).returning(); const request = "two helpers write a.txt and b.txt\n\n- keep the spacing\n- then verify"; const [comment] = await db.insert(issueComments).values({ companyId: company!.id, issueId: issue!.id, authorType: "user", - authorUserId: USER, body: `/swarm ${request}` }).returning(); + authorUserId: USER, body: request }).returning(); await recordAntigravitySwarmRequest(db, { companyId: company!.id, issueId: issue!.id, commentId: comment!.id, userId: USER }); const [agentComment] = await db.insert(issueComments).values({ companyId: company!.id, issueId: issue!.id, authorType: "agent", authorAgentId: agent!.id, body: AGENT_COMMENT, createdAt: new Date(Date.now() + 1000) }).returning(); @@ -76,7 +76,7 @@ describe.skipIf(!support.supported)("the /swarm request path to the CLI", () => // What the Runner adds to the prompt before the turn: handoff, wake attachments, queued messages. modelEnvelope.task.prompt = `Earlier session handoff.\n\n${modelEnvelope.task.prompt}\n\nQueued: ${AGENT_COMMENT}`; const sent = `/swarm ${antigravitySwarmRequestText(JSON.stringify(modelEnvelope))}`; - expect(sent).toBe(comment!.body); + expect(sent).toBe(`/swarm ${comment!.body}`); expect(sent).not.toContain(AGENT_COMMENT); expect(sent).not.toContain(DESCRIPTION); }); diff --git a/server/src/__tests__/issue-comment-reopen-routes.test.ts b/server/src/__tests__/issue-comment-reopen-routes.test.ts index d41262c478f..133e1b31ebd 100644 --- a/server/src/__tests__/issue-comment-reopen-routes.test.ts +++ b/server/src/__tests__/issue-comment-reopen-routes.test.ts @@ -1357,6 +1357,23 @@ describe("issue comment reopen routes", () => { expect(mockSwarm.record).not.toHaveBeenCalled(); }); + it("returns the original receipt for an accepted /swarm resent after the setting was turned off, starting nothing twice", async () => { + // The first send committed but its response was lost; then the swarm setting was turned off. + mockSwarm.refusal.mockResolvedValue("Swarm is not turned on for this Paperclip."); + const issue = makeIssue("todo"); + mockIssueService.getById.mockResolvedValue(issue); + const selectFrom = mockDbSelectFrom.getMockImplementation()!; + mockDbSelectFrom.mockImplementation((table) => getTableName(table as Parameters[0]) === "issue_comments" + ? { where: vi.fn(() => Object.assign(Promise.resolve([{ id: "comment-1" }]), { for: async () => [{ id: "comment-1" }] })) } as any + : getTableName(table as Parameters[0]) === "activity_log" ? { where: async () => [{ id: "activity-1" }] } as any : selectFrom(table)); + const response = await request(await installActor(createApp())).post(`/api/issues/${issue.id}/comments`) + .send({ body: "two helpers", nativeCommand: "swarm", clientRequestId: "77777777-7777-4777-8777-777777777777" }); + expect(response.status).toBe(201); + expect(response.body.id).toBe("comment-1"); + expect(mockSwarm.record).not.toHaveBeenCalled(); + expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled(); + }); + it("accepts a swarm request only from a signed-in user", async () => { mockIssueService.getById.mockResolvedValue(makeIssue("todo")); const res = await request(await installActor(createApp(), { type: "agent", agentId: "33333333-3333-4333-8333-333333333333", companyId: "company-1" })) diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 3ab19fe35b3..76652e0992d 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -19365,7 +19365,13 @@ export function issueRoutes( const swarmRequested = req.body.nativeCommand === ANTIGRAVITY_SWARM_COMMAND; if (swarmRequested) { if (req.actor.type !== "board" || !req.actor.userId) throw forbidden("Only a signed-in user can start a swarm"); - const refusal = issue.conversationAgentId + // A resend of an already accepted request returns its original receipt below; availability + // applies only to new requests (the setting may have changed since the first send). + const [accepted] = req.body.clientRequestId ? await db.select({ id: issueComments.id }).from(issueComments).where(and( + eq(issueComments.companyId, issue.companyId), eq(issueComments.issueId, issue.id), + eq(issueComments.authorUserId, req.actor.userId), eq(issueComments.clientRequestId, req.body.clientRequestId), + )) : []; + const refusal = accepted ? null : issue.conversationAgentId ? "Swarm works in task comments, not in chats." : await antigravitySwarmCommentRefusal(db, issue) ?? antigravitySwarmRequestRefusal(antigravitySwarmRequestFromComment(String(req.body.body ?? ""))); diff --git a/server/src/services/ai-connection-runtime.ts b/server/src/services/ai-connection-runtime.ts index 9ac8f911e05..2a4c2991b69 100644 --- a/server/src/services/ai-connection-runtime.ts +++ b/server/src/services/ai-connection-runtime.ts @@ -593,6 +593,8 @@ export async function prepareManagedAiRuntime( attribution, accountName: selection.connection.name, accountOwnerUserId: selection.grant.subjectUserId, + // The Google account a subscription grant signs in with; the Runner compares only its digest. + ...(antigravitySubscription && selection.grant.providerTenant?.name ? { accountEmail: selection.grant.providerTenant.name } : {}), identity, home, cleanup: cleanupRuntime, diff --git a/server/src/services/antigravity-swarm.db.test.ts b/server/src/services/antigravity-swarm.db.test.ts index 5c2e1651548..3300bb870e4 100644 --- a/server/src/services/antigravity-swarm.db.test.ts +++ b/server/src/services/antigravity-swarm.db.test.ts @@ -374,10 +374,14 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", ( expect(await automatic(f, run.id, "issue_commented")).toEqual({ commentId: f.comment.id, request: "two helpers" }); }); - it("strips a /swarm prefix the request comment may still carry", async () => { + it("uses the recorded comment as the request verbatim: the composer already removed the one /swarm the user typed", async () => { + // `/swarm /swarm explain this command` arrives as the body `/swarm explain this command`. const f = await seed(); - await db.update(issueComments).set({ body: "/swarm write a.txt" }).where(eq(issueComments.id, f.comment.id)); - expect(await resolve(f, { runId: (await insertRun(f, {})).id })).toMatchObject({ request: "write a.txt" }); + await db.update(issueComments).set({ body: "/swarm explain this command" }).where(eq(issueComments.id, f.comment.id)); + expect(await resolve(f, { runId: (await insertRun(f, {})).id })).toMatchObject({ request: "/swarm explain this command" }); + const g = await seed(); + await db.update(issueComments).set({ body: "/swarm" }).where(eq(issueComments.id, g.comment.id)); + expect(await resolve(g, { runId: (await insertRun(g, {})).id })).toMatchObject({ request: "/swarm" }); }); it("lets a later user /swarm replace the request with its own text", async () => { @@ -484,7 +488,7 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", ( const ids: Record = {}; for (const [index, label] of order.entries()) { const [comment] = await db.insert(issueComments).values({ companyId: f.company.id, issueId: f.issue.id, authorType: "user", - authorUserId: USER, body: label.startsWith("S") ? `/swarm request ${label}` : `ordinary ${label}`, + authorUserId: USER, body: label.startsWith("S") ? `request ${label}` : `ordinary ${label}`, createdAt: new Date(base + index * 1000) }).returning(); ids[label] = comment!.id; if (label.startsWith("S")) await recordAntigravitySwarmRequest(db, { companyId: f.company.id, issueId: f.issue.id, commentId: comment!.id, userId: USER }); @@ -537,8 +541,8 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", ( it.each([ ["no request", " ", /no request/], - ["only the command", "/swarm ", /no request/], - ["a request longer than the swarm accepts", `/swarm ${"x".repeat(16_001)}`, /too long/], + ["no request after the command", " ", /no request/], + ["a request longer than the swarm accepts", "x".repeat(16_001), /too long/], ])("refuses a recorded /swarm with %s instead of running ordinary work", async (_name, body, message) => { const f = await seed(); await db.update(issueComments).set({ body }).where(eq(issueComments.id, f.comment.id)); diff --git a/server/src/services/antigravity-swarm.ts b/server/src/services/antigravity-swarm.ts index 0b52677fdd9..8bfb875a87a 100644 --- a/server/src/services/antigravity-swarm.ts +++ b/server/src/services/antigravity-swarm.ts @@ -1,5 +1,5 @@ import { and, desc, eq, gt, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm"; -import { parseLeadingUserCommand, SWARM_REQUEST_MAX_CHARS } from "@paperclipai/shared"; +import { SWARM_REQUEST_MAX_CHARS } from "@paperclipai/shared"; import { activityLog, agentWakeupRequests, agents, heartbeatRuns, issueComments, issues, type Db } from "@paperclipai/db"; import { logActivity } from "./activity-log.js"; import { instanceSettingsService } from "./instance-settings.js"; @@ -55,9 +55,14 @@ export function requestedAntigravitySwarmCommentId(context: unknown): string | n return typeof value === "string" && /^[0-9a-f-]{36}$/i.test(value) ? value : null; } -/** The swarm's instruction from a recorded request comment: its text, without a leading /swarm it may still carry. */ +/** + * The swarm's instruction from a recorded request comment: its text, verbatim. + * With `nativeCommand: "swarm"` the comment body IS the request; the composer + * removes the one leading `/swarm` the user typed, and nothing strips another + * (`/swarm /swarm explain this` asks the swarm about `/swarm explain this`). + */ export function antigravitySwarmRequestFromComment(body: string): string { - return (parseLeadingUserCommand(body, ["swarm"])?.argument ?? body).trim(); + return body.trim(); } /** A request the swarm cannot run: nothing to do, or longer than the swarm accepts. */ diff --git a/server/src/services/heartbeat/runtime-execution.ts b/server/src/services/heartbeat/runtime-execution.ts index e8f19f6b5c8..1ba8cbdf9cf 100644 --- a/server/src/services/heartbeat/runtime-execution.ts +++ b/server/src/services/heartbeat/runtime-execution.ts @@ -726,6 +726,8 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe billingIdentity: managedAiRuntime ? { provider: managedAiRuntime.attribution.provider, biller: managedAiRuntime.attribution.provider === "openai" ? resolveManagedOpenAiBilling(managedAiRuntime.config.managedAiRouting)?.biller ?? managedAiRuntime.attribution.provider : managedAiRuntime.attribution.provider, billingType: managedAiRuntime.attribution.method === "subscription" ? "subscription_included" : "metered_api" } : undefined, managedAiCredentialIdentity: managedAiRuntime?.identity, managedAiAccountIdentity: managedAiRuntime?.sessionIdentity, + ...(managedAiRuntime && "accountEmail" in managedAiRuntime && typeof managedAiRuntime.accountEmail === "string" + ? { managedAiAccountEmail: managedAiRuntime.accountEmail } : {}), managedAiCredentialWriteback: managedAiRuntime?.credentialWriteback, managedAiCredentialHome: managedAiRuntime ? String((managedAiRuntime.config.env as Record).CODEX_HOME) : undefined, outputSecrets: [...identityRedactor.secretSources, ...observabilitySecretValues(observability)], diff --git a/server/src/services/native-runtime/antigravity-runner-credentials.test.ts b/server/src/services/native-runtime/antigravity-runner-credentials.test.ts index 366ff2ba184..d64150ea818 100644 --- a/server/src/services/native-runtime/antigravity-runner-credentials.test.ts +++ b/server/src/services/native-runtime/antigravity-runner-credentials.test.ts @@ -3,7 +3,8 @@ import { constants } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { antigravityCredentialTurn, bindAntigravityCredentialTurn, bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js"; +import { antigravityAccountDigest, antigravityCredentialTurn, antigravitySwarmChannel, bindAntigravityCredentialTurn, bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js"; +import { sanitizeAntigravityCredential } from "../../vendor/paperclip-runner/index.js"; import { completeManagedNativeCredentialTurn } from "./managed-native-credentials.js"; import type { NativeSession, createRunnerdCodexTransport } from "../../vendor/paperclip-runner/index.js"; import { bindRetainedGoogleCredentialHome } from "../retained-google-credential-cleanup.js"; @@ -99,12 +100,34 @@ describe("Antigravity managed Runner credentials", () => { GOOGLE_CLOUD_ACCESS_TOKEN: "ambient", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "spoofed", } })).toEqual({ home: null, environment: { GEMINI_API_KEY: "fixture-selected" } }); }); + it("binds the deployment's swarm channel and only a digest of the connection account to the credential", async () => { + const managedHome = await home(); + await writeFile(join(managedHome, "antigravity-acp", "acp_token.json"), credential("fixture-selected"), { mode: 0o600 }); + const previous = process.env.PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL; + process.env.PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL = "stable"; + try { + const { environment } = await prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: {}, accountEmail: "Owner@Example.test" }); + const secret = environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET!; + expect(JSON.parse(secret).paperclip).toEqual({ swarmChannel: "stable", accountSha256: antigravityAccountDigest("owner@example.test") }); + expect(secret).not.toMatch(/example\.test/i); + // Pinned: the Runner's antigravityAccountDigest pins the same value for the CLI's sign-in. + expect(antigravityAccountDigest("OWNER@example.test")).toBe("0fde1d32467703827f511884b66298187e2944f4bfe260303f893a0af908f81e"); + } finally { + if (previous === undefined) delete process.env.PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL; else process.env.PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL = previous; + } + expect(antigravitySwarmChannel({})).toBe("provider_default"); + expect(antigravitySwarmChannel({ PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL: "daily" })).toBe("provider_default"); + }); it("projects only the selected private token and rejects remote subscription delivery", async () => { const managedHome = await home(); await writeFile(join(managedHome, "antigravity-acp", "acp_token.json"), credential("fixture-selected"), { mode: 0o600 }); - expect(await prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: { GEMINI_HOME: "/untrusted" } })).toEqual({ - home: managedHome, credential: credential("fixture-selected"), environment: { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: credential("fixture-selected") }, - }); + const projected = await prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: { GEMINI_HOME: "/untrusted" } }); + expect(projected).toMatchObject({ home: managedHome, credential: credential("fixture-selected") }); + expect(Object.keys(projected.environment)).toEqual(["PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"]); + // The selected token, plus the swarm route's run facts, which the Runner's sanitizer drops before any write. + expect(JSON.parse(projected.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET!)).toEqual({ + ...JSON.parse(credential("fixture-selected")), paperclip: { swarmChannel: "provider_default" } }); + expect(sanitizeAntigravityCredential(projected.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET!)).toBe(credential("fixture-selected")); for (const [input, code] of [[{ remote: true, environment: {} }, "antigravity_remote_sign_in_unsupported"], [{ remote: false, lifecycleMode: "warm" as const, environment: {} }, "antigravity_warm_unsupported"], [{ remote: false, lifecycleMode: "warm" as const, environment: { GEMINI_API_KEY: "fixture-selected" } }, "antigravity_warm_unsupported"]] as const) { diff --git a/server/src/services/native-runtime/antigravity-runner-credentials.ts b/server/src/services/native-runtime/antigravity-runner-credentials.ts index 6580b0ad991..25fe4964908 100644 --- a/server/src/services/native-runtime/antigravity-runner-credentials.ts +++ b/server/src/services/native-runtime/antigravity-runner-credentials.ts @@ -1,5 +1,5 @@ import { constants } from "node:fs"; -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { mkdir, mkdtemp, realpath, rename, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -35,12 +35,30 @@ export function bindAntigravityTransportRetirement(bundle: RunnerdTransport): Ru return bundle.transport; } +/** + * The Google channel a trusted /swarm's Antigravity CLI talks to, owned by the + * deployment: `provider_default` (the default; Google's daily channel, which + * Google's own app and CLI use and which can change with less notice) or + * `stable` (Google's stable endpoint, which may offer fewer models). + */ +export const ANTIGRAVITY_SWARM_CHANNEL_ENV = "PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL"; +export function antigravitySwarmChannel(env: NodeJS.ProcessEnv = process.env): "provider_default" | "stable" { + return env[ANTIGRAVITY_SWARM_CHANNEL_ENV]?.trim().toLowerCase() === "stable" ? "stable" : "provider_default"; +} + +/** Same digest as the Runner's antigravityAccountDigest: a one-way, non-identifying account comparison. */ +export function antigravityAccountDigest(email: string): string { + return createHash("sha256").update(`paperclip.antigravity-account.v1:${email.trim().toLowerCase()}`, "utf8").digest("hex"); +} + /** Only explicit run credentials may enter Antigravity's isolated runtime. */ export async function prepareAntigravityRunnerCredentials(input: { environment: NodeJS.ProcessEnv; remote: boolean; managedHome?: string; lifecycleMode?: "per_turn" | "warm"; + /** The connection's Google account; only its digest reaches the Runner. */ + accountEmail?: string; }): Promise<{ environment: NodeJS.ProcessEnv; home: string | null; credential?: string }> { const environment = { ...input.environment }; for (const key of [AUTH_SECRET, "GEMINI_HOME", "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_ACCESS_TOKEN"]) delete environment[key]; @@ -59,7 +77,13 @@ export async function prepareAntigravityRunnerCredentials(input: { } catch { throw new Error("The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry."); } - environment[AUTH_SECRET] = credential; + // Run facts bound to this credential for the swarm route (channel, account + // digest). The Runner's credential sanitizer drops them before any write, so + // the staged token and its writeback comparison are unchanged. + environment[AUTH_SECRET] = JSON.stringify({ ...JSON.parse(credential) as Record, paperclip: { + swarmChannel: antigravitySwarmChannel(), + ...(input.accountEmail ? { accountSha256: antigravityAccountDigest(input.accountEmail) } : {}), + } }); return { environment, home, credential }; } diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index ebb185180d3..c17230ccf6a 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -10662,6 +10662,8 @@ export async function executePaperclipNativeSession(input: { managedAiCredentialHome?: string; managedAiCredentialIdentity?: string; managedAiAccountIdentity?: string; + /** The Google account of an Antigravity subscription grant (Runner compares only its digest). */ + managedAiAccountEmail?: string; managedAiCredentialWriteback?: ManagedAiCredentialWritebackBinding; billingIdentity?: Pick; onTaskDispatched?: () => Promise | void; @@ -16487,6 +16489,8 @@ export async function createRunnerdBackend(input: { managedAiCredentialHome?: string; managedAiCredentialIdentity?: string; managedAiAccountIdentity?: string; + /** The Google account of an Antigravity subscription grant (Runner compares only its digest). */ + managedAiAccountEmail?: string; managedAiCredentialWriteback?: ManagedAiCredentialWritebackBinding; onTaskDispatched?: () => Promise | void; runnerExecutionTarget?: AdapterExecutionTarget | null; @@ -18615,7 +18619,7 @@ async function createRunnerdBackendWithinSessionClaim( if (grokCredential) effectiveRunnerEnvironmentBase = grokCredential.environment; const antigravityCredential = isAntigravity ? await prepareAntigravityRunnerCredentials({ environment: effectiveRunnerEnvironmentBase, remote: Boolean(remoteTarget), managedHome: input.managedAiCredentialHome, - lifecycleMode: input.execution.session.lifecyclePolicy.mode, + lifecycleMode: input.execution.session.lifecyclePolicy.mode, accountEmail: input.managedAiAccountEmail, }) : null; if (antigravityCredential) effectiveRunnerEnvironmentBase = antigravityCredential.environment; // The server-held tool authority owns this credential. Do not deliver a