diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts index 4f4cd78dffd..617faa315c7 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts @@ -54,6 +54,8 @@ import { createCursorInstructionAdmission } from "./cursor-instructions.js"; import { antigravitySavedStateIncompatible, createAntigravityAdmission } from "./antigravity-admission.js"; import { ANTIGRAVITY_PAPERCLIP_MCP_SERVER, antigravityPlanModeAllows } from "./antigravity-plan-mode.js"; import { createAcpxModeBinding } from "./provider-mode.js"; +import { openAntigravitySwarmRuntime } from "./antigravity-swarm-runtime.js"; +import { isAntigravitySwarmRoute } from "./antigravity-swarm-route.js"; import { isAcpPromptRequest, type AcpxTurnDispatchJournal } from "./turn-dispatch-journal.js"; import { assertCopilotPromptPolicy, createCopilotPolicyEnforcement, type CopilotPolicyEnforcement } from "./copilot-policy.js"; import { acpxElicitationHandler, createAcpxPermissionReplyConfirmations, withReturnedResponseDelivery, type AcpxHostExtensionRequestHandler, type AcpxHostPermissionHandler } from "./interaction-delivery.js"; @@ -224,6 +226,9 @@ export async function openQualifiedAcpxRuntime( // tree when Node cannot safely signal a verified provider process group. assertVerifiedAcpxProviderPlatform(dependencies.platform ?? process.platform); options.signal?.throwIfAborted(); + // A trusted /swarm turn runs the pinned Antigravity CLI through its own + // verified ACP client (antigravity-swarm-runtime.ts), never through ACPX. + if (isAntigravitySwarmRoute(options.profile.agent, options.mode)) return openAntigravitySwarmRuntime(options); const credentialFenceFds = options.credentialFenceFds; if ( !Array.isArray(credentialFenceFds) || 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 new file mode 100644 index 00000000000..41333920785 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from "vitest"; +import { + antigravitySwarmWorkspaceEscape, classifyAntigravityRefusalText, createAntigravitySwarmGuard, +} from "./antigravity-swarm-guard.js"; + +const WORKSPACE = "/work/task"; +const INSTRUCTIONS = "Paperclip instructions"; +const SESSION = "s-1"; + +function initializeResult(overrides: Record = {}) { + return { + protocolVersion: 1, + agentCapabilities: { _meta: { antigravity: { systemPrompt: { append: true } } } }, + agentInfo: { name: "Antigravity ACP Server", version: "1.5.15" }, + ...overrides, + }; +} + +function sessionResult(modes = ["default", "accept-edits", "auto", "plan"]) { + return { + sessionId: SESSION, + modes: { currentModeId: "default", availableModes: modes.map(id => ({ id })) }, + models: { currentModelId: "gemini-4-argon-medium", availableModels: [{ modelId: "gemini-4-argon-medium" }, { modelId: "gemini-3.8-flash-low" }] }, + configOptions: [ + { id: "model", currentValue: "gemini-4-argon" }, { id: "thought_level", currentValue: "medium" }, { id: "mode", currentValue: "default" }, + ], + }; +} + +const sessionRequest = (overrides: Record = {}) => ({ + cwd: WORKSPACE, + mcpServers: [{ type: "http", name: "paperclip", url: "http://127.0.0.1:1/mcp", headers: [] }], + _meta: { antigravity: { systemPrompt: { append: INSTRUCTIONS } } }, + ...overrides, +}); + +const config = (model: string, level: string, mode = "auto") => ({ + sessionId: SESSION, + update: { sessionUpdate: "config_option_update", configOptions: [ + { id: "model", currentValue: model }, { id: "thought_level", currentValue: level }, { id: "mode", currentValue: mode }, + ] }, +}); + +function admitted() { + const guard = createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE }); + guard.initialize(initializeResult()); + guard.sessionRequest(sessionRequest()); + guard.sessionResult(sessionResult()); + guard.observe({ sessionId: SESSION, update: { sessionUpdate: "current_mode_update", currentModeId: "auto" } }); + guard.bindMode(); + guard.observe(config("gemini-3.8-flash", "low")); + guard.bindModel(); + return guard; +} + +describe("Antigravity CLI swarm guard (replaces the registry admission receipt)", () => { + it("records a receipt when identity, workspace, tools, instructions, auto mode and model all read back", () => { + expect(admitted().receipt()).toMatchObject({ + agentName: "Antigravity ACP Server", agentVersion: "1.5.15", sessionId: SESSION, workspace: WORKSPACE, + mode: "auto", model: "gemini-3.8-flash-low", modelFamily: "gemini-3.8-flash", thoughtLevel: "low", mcpServers: ["paperclip"], + }); + }); + + it("refuses a CLI that is not the pinned identity or cannot take Paperclip's instructions", () => { + const guard = () => createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE }); + expect(() => guard().initialize(initializeResult({ agentInfo: { name: "Antigravity ACP Server", version: "1.5.16" } }))) + .toThrow(expect.objectContaining({ code: "ANTIGRAVITY_SWARM_RECEIPT_MISMATCH" })); + expect(() => guard().initialize(initializeResult({ agentInfo: { name: "antigravity-acp", version: "1.5.15" } }))).toThrow(/pinned version/); + expect(() => guard().initialize(initializeResult({ agentCapabilities: {} }))).toThrow(/instructions/); + }); + + it("refuses a session outside the task folder, with extra tool servers, or without the instructions", () => { + const fresh = () => { + const guard = createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE }); + guard.initialize(initializeResult()); + return guard; + }; + expect(() => fresh().sessionRequest(sessionRequest({ cwd: "/elsewhere" }))).toThrow(/task folder/); + expect(() => fresh().sessionRequest(sessionRequest({ mcpServers: [ + { type: "http", name: "paperclip", url: "u", headers: [] }, { name: "extra", command: "/bin/x", args: [], env: [] }, + ] }))).toThrow(/Paperclip's own tools/); + expect(() => fresh().sessionRequest(sessionRequest({ _meta: {} }))).toThrow(/instructions/); + }); + + it("names a sign-in without auto mode as unavailable instead of running without helper writes", () => { + const guard = createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE }); + guard.initialize(initializeResult()); + guard.sessionRequest(sessionRequest()); + expect(() => guard.sessionResult(sessionResult(["default", "accept-edits", "plan"]))) + .toThrow(expect.objectContaining({ code: "ANTIGRAVITY_SWARM_UNAVAILABLE" })); + }); + + it("fails closed when mode or model does not read back, or changes afterwards", () => { + const base = () => { + const guard = createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE }); + guard.initialize(initializeResult()); + guard.sessionRequest(sessionRequest()); + guard.sessionResult(sessionResult()); + return guard; + }; + expect(() => base().bindMode()).toThrow(/auto mode/); + const wrongLevel = base(); + wrongLevel.observe(config("gemini-3.8-flash", "high")); + expect(() => wrongLevel.bindModel()).toThrow(/gemini-3.8-flash-low/); + expect(() => admitted().observe(config("gemini-3.8-flash", "high"))).toThrow(/changed/); + expect(() => admitted().observe({ sessionId: SESSION, update: { sessionUpdate: "current_mode_update", currentModeId: "default" } })).toThrow(/changed/); + }); + + it("refuses a helper that would get its own copy of the workspace", () => { + const add = (workspace?: string) => ({ sessionUpdate: "tool_call", name: "swarm", + args: { action: "add", name: "writer-a", ...(workspace === undefined ? {} : { workspace }) } }); + expect(antigravitySwarmWorkspaceEscape(add())).toBeNull(); + expect(antigravitySwarmWorkspaceEscape(add("inherit"))).toBeNull(); + expect(antigravitySwarmWorkspaceEscape(add("branch"))).toBe("writer-a"); + expect(antigravitySwarmWorkspaceEscape(add("share"))).toBe("writer-a"); + }); + + it("treats provider refusals that arrive as ordinary text as failures", () => { + expect(classifyAntigravityRefusalText("⚠ agent executor error: Error 402 Your prepayment credits are depleted. Status: RESOURCE_EXHAUSTED")) + .toMatchObject({ kind: "quota_exhausted", httpStatus: 402 }); + expect(classifyAntigravityRefusalText("\n⚠ RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n")) + .toMatchObject({ kind: "rate_limit", httpStatus: 429 }); + expect(classifyAntigravityRefusalText("Both files are written.")).toBeNull(); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts new file mode 100644 index 00000000000..a0c980ff9c8 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts @@ -0,0 +1,230 @@ +import { createHash } from "node:crypto"; +import { ANTIGRAVITY_CLI_DISTRIBUTION } from "./antigravity-cli-pins.js"; + +/** + * Google Antigravity CLI route (`agy acp`), used only for a turn the signed-in + * user started with a trusted `/swarm`. The registry server's owned admission + * patch does not exist here (the CLI is a signed binary with no patch point), + * so this guard verifies what the connection itself reports instead, and fails + * closed on any difference: + * + * - agent identity and version from `initialize` equal the pinned CLI; + * - the CLI accepts Paperclip's instructions through `systemPrompt.append`; + * - the session's working directory is the task workspace, and the only MCP + * server is the runner-owned Paperclip bridge; + * - session mode reads back as `auto` after `session/set_mode`; + * - model family and thinking level read back as the agent's configured model; + * - none of those change later in the session; + * - helpers share the task workspace (`inherit`); `share` and `branch` are refused. + */ +export const ANTIGRAVITY_SWARM_MODE = "swarm"; +export const ANTIGRAVITY_CLI_AGENT_NAME = "Antigravity ACP Server"; +export const ANTIGRAVITY_CLI_SESSION_MODE = "auto"; +/** Google's stable endpoint; the CLI's default is the daily one. */ +export const ANTIGRAVITY_CLI_STABLE_ENDPOINT = "https://cloudcode-pa.googleapis.com"; +export const ANTIGRAVITY_SWARM_MCP_SERVER = "paperclip"; + +export type AntigravitySwarmErrorCode = + | "ANTIGRAVITY_SWARM_UNAVAILABLE" + | "ANTIGRAVITY_SWARM_SIGN_IN_REQUIRED" + | "ANTIGRAVITY_SWARM_RECEIPT_MISMATCH" + | "ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE" + | "ANTIGRAVITY_SWARM_HELPERS_TIMEOUT"; + +/** `message` is written for the person who asked for the swarm. */ +export class AntigravitySwarmError extends Error { + readonly retryable = false; + constructor(readonly code: AntigravitySwarmErrorCode, message: string) { + super(message); + this.name = "AntigravitySwarmError"; + } +} + +const mismatch = (detail: string): never => { + throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_RECEIPT_MISMATCH", + `Swarm stopped before it started: ${detail}. Nothing was changed.`); +}; + +/** What the driver verified in place of the registry server's admission receipt. */ +export interface AntigravitySwarmReceipt { + agentName: string; + agentVersion: string; + sessionId: string; + workspace: string; + mode: typeof ANTIGRAVITY_CLI_SESSION_MODE; + model: string; + modelFamily: string; + thoughtLevel: string | null; + instructionDigest: string; + mcpServers: string[]; +} + +export interface AntigravitySwarmGuardOptions { + model: string; + instructions: string; + workspace: string; +} + +type Json = Record; +const record = (value: unknown): Json => + value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {}; + +export function antigravitySwarmInstructionDigest(content: string): string { + return `sha256:${createHash("sha256").update(content, "utf8").digest("hex")}`; +} + +/** The `model` / `thought_level` / `mode` selections in a config option list. */ +export function antigravitySelections(value: unknown): Map { + const selections = new Map(); + const options = record(value).configOptions; + if (!Array.isArray(options)) return selections; + for (const entry of options) { + const option = record(entry); + if (typeof option.id === "string" && typeof option.currentValue === "string" + && ["model", "thought_level", "mode"].includes(option.id)) selections.set(option.id, option.currentValue); + } + return selections; +} + +export function createAntigravitySwarmGuard(options: AntigravitySwarmGuardOptions) { + const model = options.model.trim(); + if (!model || model.length > 512 || /[\u0000-\u001f]/.test(model)) mismatch("the agent has no exact model"); + const instructionDigest = antigravitySwarmInstructionDigest(options.instructions); + const state = { + agentName: "", agentVersion: "", sessionId: "", modeBound: false, modelBound: false, + selections: new Map(), commands: null as string[] | null, mcpServers: [] as string[], + }; + const assertStable = (next: Map) => { + for (const [id, value] of next) { + const bound = id === "mode" ? state.modeBound : state.modelBound; + if (bound && state.selections.get(id) !== value) mismatch("the provider changed the confirmed model, thinking level, or permission mode"); + state.selections.set(id, value); + } + }; + return { + instructionDigest, + /** `initialize` result: exact pinned identity and the instruction channel. */ + initialize(result: unknown): void { + const value = record(result); + const info = record(value.agentInfo); + if (info.name !== ANTIGRAVITY_CLI_AGENT_NAME || info.version !== ANTIGRAVITY_CLI_DISTRIBUTION.version) { + mismatch("the Antigravity CLI did not report its pinned version"); + } + const append = record(record(record(record(value.agentCapabilities)._meta).antigravity).systemPrompt).append; + if (append !== true) mismatch("the Antigravity CLI cannot receive Paperclip's instructions"); + state.agentName = info.name as string; + state.agentVersion = info.version as string; + }, + /** The exact `session/new` request this route sends; refuses anything else. */ + sessionRequest(params: Json): void { + if (params.cwd !== options.workspace) mismatch("the session is not in the task folder"); + const servers = Array.isArray(params.mcpServers) ? params.mcpServers.map(record) : []; + if (servers.length !== 1 || servers[0]!.name !== ANTIGRAVITY_SWARM_MCP_SERVER || servers[0]!.type !== "http") { + mismatch("the session must use only Paperclip's own tools"); + } + const appended = record(record(record(params._meta).antigravity).systemPrompt).append; + if (typeof appended !== "string" || antigravitySwarmInstructionDigest(appended) !== instructionDigest) { + mismatch("Paperclip's instructions are missing from the session"); + } + state.mcpServers = [ANTIGRAVITY_SWARM_MCP_SERVER]; + }, + sessionResult(result: unknown): string { + if (!state.agentName) mismatch("the provider was not identified"); + if (state.mcpServers.length === 0) mismatch("the session request was not checked"); + const value = record(result); + if (typeof value.sessionId !== "string" || !value.sessionId || value.sessionId.length > 256) mismatch("the provider did not open a session"); + const modes = record(value.modes).availableModes; + if (!Array.isArray(modes) || !modes.some(mode => record(mode).id === ANTIGRAVITY_CLI_SESSION_MODE)) { + throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", + "Swarm is not available with this Google connection: helpers can only change files in Antigravity's auto mode, which this sign-in does not offer."); + } + const available = record(value.models).availableModels; + if (!Array.isArray(available) || !available.some(entry => record(entry).modelId === model)) { + mismatch(`the model ${model} is not offered to this sign-in`); + } + state.sessionId = value.sessionId as string; + assertStable(antigravitySelections(value)); + return state.sessionId; + }, + /** Every inbound `session/update`; throws on a change to a confirmed setting. */ + observe(params: unknown): void { + const value = record(params); + if (!state.sessionId || value.sessionId !== state.sessionId) return; + const update = record(value.update); + if (update.sessionUpdate === "current_mode_update") { + if (typeof update.currentModeId !== "string") mismatch("the provider reported an invalid permission mode"); + assertStable(new Map([["mode", update.currentModeId as string]])); + } else if (update.sessionUpdate === "config_option_update") { + assertStable(antigravitySelections(update)); + } else if (update.sessionUpdate === "available_commands_update" && Array.isArray(update.availableCommands)) { + state.commands = update.availableCommands.map(command => String(record(command).name)); + } + }, + /** After `session/set_mode auto`: the read-back must say `auto`. */ + bindMode(): void { + if (state.selections.get("mode") !== ANTIGRAVITY_CLI_SESSION_MODE) mismatch("the provider did not confirm auto mode"); + state.modeBound = true; + }, + /** After `session/set_model `: family plus thinking level must read back as that model. */ + bindModel(): void { + const family = state.selections.get("model"); + const level = state.selections.get("thought_level"); + if (!family || (family !== model && `${family}-${level}` !== model)) mismatch(`the provider did not confirm the model ${model}`); + state.modelBound = true; + }, + /** `/swarm` must be one of the pinned CLI's own commands for this session. */ + assertSwarmCommand(): void { + if (state.commands !== null && !state.commands.includes("swarm")) { + throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "Swarm is not offered by this Antigravity CLI session."); + } + }, + receipt(): AntigravitySwarmReceipt { + if (!state.sessionId || !state.modeBound || !state.modelBound) mismatch("the session settings were not confirmed"); + const family = state.selections.get("model")!; + return { + agentName: state.agentName, agentVersion: state.agentVersion, sessionId: state.sessionId, + workspace: options.workspace, mode: ANTIGRAVITY_CLI_SESSION_MODE, model, modelFamily: family, + thoughtLevel: family === model ? null : state.selections.get("thought_level") ?? null, + instructionDigest, mcpServers: [...state.mcpServers], + }; + }, + }; +} + +export type AntigravitySwarmGuard = ReturnType; + +/** A helper started with its own copy of the workspace would write outside the task folder. */ +export function antigravitySwarmWorkspaceEscape(update: unknown): string | null { + const value = record(update); + if ((value.sessionUpdate !== "tool_call" && value.sessionUpdate !== "tool_call_update") || value.name !== "swarm") return null; + const args = { ...record(value.rawInput), ...record(value.args) }; + if (args.action !== "add" || args.workspace === undefined || args.workspace === "inherit") return null; + return typeof args.name === "string" ? args.name : "a helper"; +} + +export interface AntigravityRefusal { + kind: "quota_exhausted" | "rate_limit" | "authentication"; + httpStatus?: number; + status?: string; + message: string; +} + +/** + * The CLI reports some provider refusals as assistant text and then ends the + * turn normally (seen live with 402 credits and 429 quota). These are failures. + */ +export function classifyAntigravityRefusalText(text: string): AntigravityRefusal | null { + const sample = text.slice(0, 4_000); + if (/prepayment credits are depleted|\bError 402\b|\bcode 402\b/i.test(sample)) { + return { kind: "quota_exhausted", httpStatus: 402, status: "RESOURCE_EXHAUSTED", + message: "Google refused the swarm: this account has no credits left." }; + } + if (/⚠\s*RESOURCE_EXHAUSTED|\bcode 429\b|\bError 429\b/i.test(sample)) { + return { kind: "rate_limit", httpStatus: 429, status: "RESOURCE_EXHAUSTED", + message: "Google refused the swarm: this account is out of quota for now. Try again later." }; + } + if (/⚠.*Authentication required/i.test(sample)) { + return { kind: "authentication", message: "The Antigravity CLI on this computer is not signed in to Google." }; + } + return null; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-paths.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-paths.test.ts new file mode 100644 index 00000000000..fc0b1b383f6 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-paths.test.ts @@ -0,0 +1,65 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { antigravityOutsideChange, shellWriteTargets } from "./antigravity-swarm-paths.js"; + +const root = realpathSync(mkdtempSync(join(tmpdir(), "agy-paths-"))); +const workspace = join(root, "task"); +const home = join(root, "home"); +mkdirSync(workspace); mkdirSync(home); +symlinkSync(home, join(workspace, "to-home")); +afterAll(() => rmSync(root, { recursive: true, force: true })); + +const shell = (command: string) => ({ sessionUpdate: "tool_call", kind: "execute", name: "run_command", args: { CommandLine: command } }); +const edit = (path: string) => ({ sessionUpdate: "tool_call", kind: "edit", name: "write_file", args: { TargetFile: path } }); + +describe("changes outside the task folder in visible tool calls", () => { + it("finds the write targets of shell commands", () => { + expect(shellWriteTargets("printf E > /tmp/e.txt")).toEqual(["/tmp/e.txt"]); + expect(shellWriteTargets("echo x >>../log.txt && cat /etc/hosts")).toEqual(["../log.txt"]); + expect(shellWriteTargets("cp /etc/hosts ./copy.txt; mv a.txt ~/b.txt")).toEqual(["./copy.txt", "~/b.txt"]); + expect(shellWriteTargets("ls | tee /var/tmp/out.txt")).toEqual(["/var/tmp/out.txt"]); + expect(shellWriteTargets("sed -i 's/a/b/' $HOME/.profile")).toEqual(["$HOME/.profile"]); + expect(shellWriteTargets("dd if=/dev/zero of=/tmp/z bs=1")).toEqual(["/tmp/z"]); + expect(shellWriteTargets("cat a.txt 2>/dev/null")).toEqual(["/dev/null"]); + }); + + it.each<[string, string[]]>([ + ["grep '>' /tmp/report.html", []], + ['echo "a > /tmp/x" | wc -c', []], + ["ls 2>&1 | head", []], + ["cat a.txt >/dev/null 2>&1", ["/dev/null"]], + ["wc -l <<< 'x > /tmp/y'", []], + ["printf A >> '/tmp/quoted target.txt'", ["/tmp/quoted target.txt"]], + ["cp ./a.txt /tmp/out.txt", ["/tmp/out.txt"]], + ["cp /etc/hosts ./in.txt", ["./in.txt"]], + ["echo $(date) > /tmp/sub.txt", []], + ["cat < /tmp/h.txt\nx\nEOF", []], + ["eval 'echo x > /tmp/e'", []], + ["python3 -c 'open(\"/tmp/p\",\"w\")'", []], + ["cd /tmp && echo x > rel.txt", []], + ["echo x > $OUT_DIR/f", []], + ])("detects only visible, unambiguous write targets: %s", (command, targets) => { + expect(shellWriteTargets(command)).toEqual(targets); + }); + + it("flags absolute, parent, home and symlink escapes, and allows the task folder", () => { + expect(antigravityOutsideChange(shell("printf E > /tmp/agy-e.txt"), workspace, home)).toBe("/tmp/agy-e.txt"); + expect(antigravityOutsideChange(edit("../escape.txt"), workspace, home)).toBe("../escape.txt"); + expect(antigravityOutsideChange(edit("~/notes.txt"), workspace, home)).toBe("~/notes.txt"); + expect(antigravityOutsideChange(shell("echo hi > $HOME/x"), workspace, home)).toBe("$HOME/x"); + expect(antigravityOutsideChange(edit("to-home/x.txt"), workspace, home)).toBe("to-home/x.txt"); + expect(antigravityOutsideChange(edit(join(workspace, "a.txt")), workspace, home)).toBeNull(); + expect(antigravityOutsideChange(edit("..notes.txt"), workspace, home)).toBeNull(); + expect(antigravityOutsideChange(edit(join(workspace, "..notes.txt")), workspace, home)).toBeNull(); + expect(antigravityOutsideChange(edit(".."), workspace, home)).toBe(".."); + expect(antigravityOutsideChange(shell("cp /etc/hosts ./hosts.txt && cat /etc/hosts > out.txt 2>/dev/null"), workspace, home)).toBeNull(); + }); + + it("does not treat reads, URLs or prose as changes", () => { + expect(antigravityOutsideChange({ sessionUpdate: "tool_call", kind: "read", name: "read_file", args: { Path: "/etc/hosts" } }, workspace, home)).toBeNull(); + expect(antigravityOutsideChange(edit("https://docs.google.com/a.txt"), workspace, home)).toBeNull(); + expect(antigravityOutsideChange({ sessionUpdate: "agent_message_chunk", content: { text: "write /etc/x" } }, workspace, home)).toBeNull(); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-paths.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-paths.ts new file mode 100644 index 00000000000..33e603b345c --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-paths.ts @@ -0,0 +1,157 @@ +import { realpathSync } from "node:fs"; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; + +/** + * Finds a change outside the task folder in a tool call the coordinator + * reports. It reads file-tool locations and path arguments, and the write + * targets of shell commands (redirects, tee, cp/mv/ln destinations, rm, mkdir, + * touch, sed -i, dd of=). Paths are resolved like the OS would: relative to the + * task folder, `..`, `~` and `$HOME`, and symlinks of existing parents. + * + * Role: a best-effort detector that turns visible, unambiguous outside writes + * into a clear failure. It is not a confinement boundary and does not prove + * one: helper tool calls never reach the ACP client, and a shell command can + * hide its target (variables, subshells, scripts, interpreters). Ambiguous + * constructs yield no finding, so a correct swarm is never stopped by a guess. + */ +type Json = Record; +const record = (value: unknown): Json => + value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {}; + +const PATH_KEY = /path|file|target|dest|directory|dir$/i; +const COMMAND_KEY = /command|cmd|script/i; +const DEVICES = new Set(["/dev/null", "/dev/stdout", "/dev/stderr", "/dev/tty"]); +const ALL_ARGUMENTS = new Set(["tee", "rm", "rmdir", "mkdir", "touch", "chmod", "chown", "truncate", "unlink", "shred"]); +const LAST_ARGUMENT = new Set(["cp", "mv", "ln", "install", "rsync"]); + +function realResolved(path: string): string { + // Resolve symlinks through the deepest existing ancestor. + let current = path; + const rest: string[] = []; + for (let depth = 0; depth < 64; depth++) { + try { return join(realpathSync(current), ...rest.reverse()); } catch { + const parent = dirname(current); + if (parent === current) return path; + rest.push(basename(current)); + current = parent; + } + } + return path; +} + +function expand(path: string, workspace: string, home: string): string | null { + let value = path.trim().replace(/^['"]|['"]$/g, ""); + if (!value || DEVICES.has(value) || value.startsWith("/dev/fd/")) return null; + value = value.replace(/^~(?=\/|$)/, home).replace(/^\$\{?HOME\}?(?=\/|$)/, home); + if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value) || value.includes("$")) return null; + return realResolved(isAbsolute(value) ? resolve(value) : resolve(workspace, value)); +} + +function outside(path: string, workspace: string): boolean { + const inside = relative(workspace, path); + return inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside); +} + +type Lexeme = { kind: "word"; text: string } | { kind: "op"; text: string }; + +/** Quote-aware shell lexer. Returns null for constructs whose writes cannot be read from the text. */ +function lex(command: string): Lexeme[] | null { + const out: Lexeme[] = []; + let word = ""; + let inWord = false; + const flush = () => { if (inWord) out.push({ kind: "word", text: word }); word = ""; inWord = false; }; + for (let index = 0; index < command.length; index++) { + const char = command[index]!; + if (char === "'") { + const close = command.indexOf("'", index + 1); + if (close < 0) return null; + word += command.slice(index + 1, close); inWord = true; index = close; continue; + } + if (char === '"') { + let close = index + 1; + while (close < command.length && command[close] !== '"') { if (command[close] === "\\") close++; close++; } + if (close >= command.length) return null; + const inner = command.slice(index + 1, close); + if (/\$\(|`/.test(inner)) return null; + word += inner; inWord = true; index = close; continue; + } + if (char === "`" || (char === "$" && command[index + 1] === "(")) return null; + if (char === "\\") { word += command[index + 1] ?? ""; inWord = true; index++; continue; } + if (/\s/.test(char) && char !== "\n") { flush(); continue; } + const operator = /^(?:\n|;|&&|\|\||\||<<<|<<|<|&>>?|\d*>>?&\d+|\d*>>?)/.exec(command.slice(index))?.[0]; + // A digit only opens a redirect at the start of a word. + if (operator && !(/^\d/.test(operator) && inWord)) { + flush(); out.push({ kind: "op", text: operator }); index += operator.length - 1; continue; + } + word += char; inWord = true; + } + flush(); + return out; +} + +const AMBIGUOUS_COMMANDS = new Set(["eval", "cd", "pushd", "popd", "source", ".", "exec", "xargs", "find"]); +const INTERPRETERS = new Set(["sh", "bash", "zsh", "dash", "python", "python3", "node", "perl", "ruby"]); + +/** + * Write targets a shell command shows plainly. A best-effort detector, not a + * boundary: anything ambiguous (command substitution, heredocs, eval, cd, + * interpreters, unknown variables) yields no finding, never a stop. + */ +export function shellWriteTargets(command: string): string[] { + const lexemes = lex(command); + if (!lexemes || lexemes.some(item => item.kind === "op" && item.text === "<<")) return []; + const targets: string[] = []; + const segments: Lexeme[][] = [[]]; + for (const item of lexemes) { + if (item.kind === "op" && ["\n", ";", "&&", "||", "|"].includes(item.text)) segments.push([]); + else segments.at(-1)!.push(item); + } + for (const segment of segments) { + const words: string[] = []; + for (let index = 0; index < segment.length; index++) { + const item = segment[index]!; + if (item.kind === "word") { words.push(item.text); continue; } + const next = segment[index + 1]; + if (/^\d*>>?&\d+$/.test(item.text)) continue; + if (item.text.includes(">")) { if (next?.kind === "word") { targets.push(next.text); index++; } continue; } + if (next?.kind === "word") index++; + } + let start = 0; + while (start < words.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(words[start]!) || ["sudo", "env", "command", "nohup", "time"].includes(words[start]!))) start++; + const name = words[start] ? basename(words[start]!) : ""; + if (AMBIGUOUS_COMMANDS.has(name) || INTERPRETERS.has(name)) return []; + const operands = words.slice(start + 1).filter(word => !word.startsWith("-")); + if (ALL_ARGUMENTS.has(name)) targets.push(...operands); + else if (LAST_ARGUMENT.has(name) && operands.length > 1) targets.push(operands.at(-1)!); + else if (name === "sed" && words.some(word => /^-i/.test(word)) && operands.length) targets.push(operands.at(-1)!); + else if (name === "dd") targets.push(...operands.flatMap(word => word.startsWith("of=") ? [word.slice(3)] : [])); + } + // An unknown variable makes the target unreadable: no finding. + return targets.filter(target => !/\$(?!\{?HOME\}?(?:\/|$))/.test(target)); +} + +/** The first path outside the task folder that a visible tool call would change, or null. */ +export function antigravityOutsideChange(update: unknown, workspace: string, home: string): string | null { + const value = record(update); + if (value.sessionUpdate !== "tool_call" && value.sessionUpdate !== "tool_call_update") return null; + const kind = String(value.kind ?? ""); + const args = { ...record(value.rawInput), ...record(value.args) }; + const candidates: string[] = []; + if (["edit", "delete", "move"].includes(kind)) { + const locations = Array.isArray(value.locations) ? value.locations.map(record) : []; + candidates.push(...locations.flatMap(location => typeof location.path === "string" ? [location.path] : [])); + candidates.push(...Object.entries(args).flatMap(([key, entry]) => PATH_KEY.test(key) && typeof entry === "string" ? [entry] : [])); + } + if (kind === "execute" || /command|shell|terminal/i.test(String(value.name ?? ""))) { + for (const [key, entry] of Object.entries(args)) { + if (COMMAND_KEY.test(key) && typeof entry === "string") candidates.push(...shellWriteTargets(entry)); + } + } + let root = workspace; + try { root = realpathSync(workspace); } catch { /* keep the given path */ } + for (const candidate of candidates) { + const resolved = expand(candidate, workspace, home); + if (resolved && outside(resolved, root)) return candidate; + } + return null; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts new file mode 100644 index 00000000000..ba377e1eb47 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "vitest"; +import { antigravitySwarmEvent, stripAntigravityTerminalHints } from "./antigravity-swarm-presentation.js"; + +const WORKSPACE = "/work/task"; +const tool = (name: string, args: Record, sessionUpdate = "tool_call", status = "in_progress") => + ({ sessionUpdate, toolCallId: "call_14003112185197785061", name, args, rawInput: args, status, kind: "other", title: `Run ${name}` }); + +describe("Antigravity swarm activity, in plain language", () => { + it("names helpers by role and what they were asked to do, never by id", () => { + const event = antigravitySwarmEvent(tool("swarm", { action: "add", name: "writer-a", workspace: "inherit", + brief: `Write a.txt containing exactly 'A' in ${WORKSPACE}. Once done, post to the board: '@verifier [done] a.txt written'.` }), WORKSPACE); + expect(event).toMatchObject({ type: "tool_call", title: "Started helper writer-a: Write a.txt containing exactly 'A' in the task folder" }); + expect((event as { title?: string } | null)?.title).not.toMatch(/call_|@verifier/); + expect(event).not.toHaveProperty("rawInput"); + expect(antigravitySwarmEvent(tool("swarm", { action: "add", name: "monitor", brief: "You are this swarm's stall monitor. Load the swarm_monitor skill." }), WORKSPACE)) + .toMatchObject({ title: "Started a helper that watches for stalls" }); + }); + + it("describes board activity without the provider's tool names", () => { + expect(antigravitySwarmEvent(tool("read_board", { since: 5 }), WORKSPACE)).toMatchObject({ title: "Checked on the helpers" }); + expect(antigravitySwarmEvent(tool("post_message", { text: "@verifier [done] Verification verified: checked 2 files" }), WORKSPACE)) + .toMatchObject({ title: "Coordinator: Verification verified: checked 2 files" }); + expect(antigravitySwarmEvent(tool("swarm", { action: "title", title: "Two writers and a verifier" }), WORKSPACE)) + .toMatchObject({ title: "Swarm: Two writers and a verifier" }); + }); + + it("keeps the opening title on later updates of the same call", () => { + expect(antigravitySwarmEvent(tool("read_board", { since: 5 }, "tool_call_update", "completed"), WORKSPACE)) + .toMatchObject({ type: "tool_call", tag: "tool_call_update", status: "completed", title: "Checked on the helpers" }); + }); + + it("drops terminal-only hints from the coordinator's text", () => { + expect(stripAntigravityTerminalHints("Launched.\n\nRun /swarm board (default shortcut alt+s) to open the live board.")) + .toBe("Launched.\n"); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts new file mode 100644 index 00000000000..f66d3dec49a --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts @@ -0,0 +1,78 @@ +import type { AcpRuntimeEvent } from "acpx/runtime"; + +/** + * The Antigravity CLI coordinator reports its swarm through its own tools + * (`swarm`, `read_board`, `post_message`, `swarm_wait`). Helper conversations + * never reach the client. Turn those calls into short readable steps, and keep + * provider ids, tool names and terminal hints out of what users see. + */ +type Json = Record; +const record = (value: unknown): Json => + value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {}; + +const SWARM_TOOLS = new Set(["swarm", "read_board", "post_message", "swarm_wait"]); +const TERMINAL_HINT = /\n?Run \/swarm board \(default shortcut [^)]*\) to open the live board\.?/g; + +export function stripAntigravityTerminalHints(text: string): string { + return text.replace(TERMINAL_HINT, ""); +} + +function plain(text: string, workspace: string, limit = 120): string { + let value = text.split(workspace).join("the task folder") + .replace(/@[a-z0-9_-]+\s*/gi, "").replace(/\[(?:done|blocked|update)\]\s*/gi, "").replace(/\s+/g, " ").trim(); + // First sentence only: briefs carry board protocol after it. + const sentence = /^(.+?[.!?])(\s|$)/.exec(value)?.[1]; + if (sentence) value = sentence.replace(/[.!?]$/, ""); + return value.length > limit ? `${value.slice(0, limit - 1)}…` : value; +} + +function swarmTitle(name: string, args: Json, workspace: string): string | null { + if (name === "read_board") return "Checked on the helpers"; + if (name === "swarm_wait") return "Waiting for the helpers"; + if (name === "post_message") return typeof args.text === "string" && args.text.trim() ? `Coordinator: ${plain(args.text, workspace)}` : "Coordinator posted an update"; + if (name !== "swarm") return null; + const helper = typeof args.name === "string" ? args.name.replace(/[^a-zA-Z0-9 _.-]/g, "").slice(0, 40) : ""; + switch (args.action) { + case "add": + if (/^monitor$/i.test(helper)) return "Started a helper that watches for stalls"; + return typeof args.brief === "string" && args.brief.trim() + ? `Started helper ${helper || "(unnamed)"}: ${plain(args.brief, workspace)}` + : `Started helper ${helper || "(unnamed)"}`; + case "title": return typeof args.title === "string" ? `Swarm: ${plain(args.title, workspace)}` : "Named the swarm"; + case "remove": case "kill": case "stop": return helper ? `Stopped helper ${helper}` : "Stopped a helper"; + case "status": return "Checked on the helpers"; + default: return "Coordinated the helpers"; + } +} + +/** One ACP `session/update` as a runtime event, or null when it carries nothing to show. */ +export function antigravitySwarmEvent(update: unknown, workspace: string): AcpRuntimeEvent | null { + const value = record(update); + const kind = value.sessionUpdate; + if (kind === "agent_message_chunk" || kind === "agent_thought_chunk") { + const content = record(value.content); + if (content.type !== "text" || typeof content.text !== "string") return null; + const text = kind === "agent_message_chunk" ? stripAntigravityTerminalHints(content.text) : content.text; + if (!text) return null; + return { type: "text_delta", text, stream: kind === "agent_thought_chunk" ? "thought" : "output", tag: kind }; + } + if (kind !== "tool_call" && kind !== "tool_call_update") return null; + if (typeof value.toolCallId !== "string" || !value.toolCallId) return null; + const name = typeof value.name === "string" ? value.name : ""; + const args = { ...record(value.rawInput), ...record(value.args) }; + const status = typeof value.status === "string" ? value.status : undefined; + if (SWARM_TOOLS.has(name)) { + const title = swarmTitle(name, args, workspace) ?? "Coordinated the helpers"; + return { type: "tool_call", tag: kind, toolCallId: value.toolCallId, text: title, title, kind: "other", ...(status ? { status } : {}) }; + } + const title = typeof value.title === "string" ? value.title.split(workspace).join(".") : name || "Tool call"; + return { + type: "tool_call", tag: kind, toolCallId: value.toolCallId, text: title, title, + ...(typeof value.kind === "string" ? { kind: value.kind as never } : {}), + ...(status ? { status } : {}), + ...(value.rawInput !== undefined ? { rawInput: value.rawInput } : {}), + ...(value.rawOutput !== undefined ? { rawOutput: value.rawOutput } : {}), + ...(Array.isArray(value.content) ? { content: value.content as never } : {}), + ...(Array.isArray(value.locations) ? { locations: value.locations as never } : {}), + }; +} 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 new file mode 100644 index 00000000000..1d31b0a44b3 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts @@ -0,0 +1,68 @@ +import { spawn } from "node:child_process"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js"; +import { antigravityRouteChangeRefusal, antigravitySwarmArguments, antigravitySwarmLaunchEnvironment, antigravitySwarmRouteRefusal, isAntigravitySwarmRoute } from "./antigravity-swarm-route.js"; +import { createAcpxModeBinding, resolveAcpxProviderMode } from "./provider-mode.js"; +import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; + +const FIXTURE = new URL("../../../test-fixtures/antigravity-cli/fake-agy-acp.mjs", import.meta.url).pathname; +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); + +describe("Antigravity swarm route selection", () => { + it("is reachable only through the trusted swarm provider mode; every other turn keeps the registry server", () => { + expect(resolveAcpxProviderMode("antigravity", undefined)).toBeUndefined(); + expect(createAcpxModeBinding("antigravity", undefined)).toBeNull(); + expect(resolveAcpxProviderMode("antigravity", "swarm")).toBe("swarm"); + expect(() => resolveAcpxProviderMode("antigravity", "auto")).toThrow(/only the swarm/); + expect(() => resolveAcpxProviderMode("claude", "swarm")).toThrow(); + expect(isAntigravitySwarmRoute("antigravity", "swarm")).toBe(true); + expect(isAntigravitySwarmRoute("antigravity", undefined)).toBe(false); + expect(isAntigravitySwarmRoute("cursor", "swarm")).toBe(false); + }); + + it("says in plain language why a swarm cannot run here", () => { + const signIn = { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "x" }; + expect(antigravitySwarmRouteRefusal({ environment: signIn, platform: "darwin", architecture: "arm64" })).toBeNull(); + expect(antigravitySwarmRouteRefusal({ environment: signIn, platform: "win32", architecture: "x64" })?.message).toMatch(/not available on this computer/); + expect(antigravitySwarmRouteRefusal({ environment: { GEMINI_API_KEY: "k" }, platform: "darwin", architecture: "arm64" })) + .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", () => { + expect(antigravitySwarmArguments("/home/run/antigravity-cli")).toEqual([ + "--gemini-dir", "/home/run/antigravity-cli", "--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" }, + { agentHomeDirectory: "/private", platform: "linux" }); + expect(environment).toEqual({ HOME: "/private/home", PATH: "/usr/bin", AGY_CLI_DISABLE_AUTO_UPDATE: "1" }); + expect(antigravitySwarmLaunchEnvironment({ HOME: "/private/home" }, { agentHomeDirectory: "/private", platform: "darwin", realHome: "/Users/owner" }).HOME).toBe("/Users/owner"); + }); + + it("lets the server open a fresh conversation when a saved one belongs to the other route", () => { + expect(antigravityRouteChangeRefusal("antigravity", "swarm", undefined)).toMatchObject({ code: "ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE" }); + expect(antigravityRouteChangeRefusal("antigravity", undefined, "swarm")).toMatchObject({ code: "ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE" }); + expect(antigravityRouteChangeRefusal("antigravity", undefined, undefined)).toBeNull(); + expect(antigravityRouteChangeRefusal("cursor", "plan", undefined)).toBeNull(); + }); + + it("routes a swarm turn to the CLI runtime instead of ACPX", async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "agy-route-"))); + roots.push(root); + const cwd = join(root, "workspace"); + mkdirSync(cwd); + const runtime = await openQualifiedAcpxRuntime({ + command: { spawn: () => spawn(process.execPath, [FIXTURE], { cwd, detached: true, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, FAKE_AGY_SCENARIO: "success" } }), close: async () => {} }, + profile: { agent: "antigravity", reportedModelId: "gemini-3.8-flash-low", qualificationModel: "gemini-3.8-flash-low" }, + cwd, stateDirectory: root, providerSessionKey: "key", permissionMode: "approve-reads", mode: "swarm", + permissionPolicy: {}, launchEnvironment: {}, credentialFenceFds: null, activateCredentialFenceOwner: null, systemInstructions: "x", + mcpServers: [{ name: "paperclip", url: "http://127.0.0.1:9/mcp", bearerToken: "t", runnerOwned: true }], retainFailedAdmissionCleanup: () => {}, + } as unknown as AcpxRuntimePortOpenOptions); + expect(await runtime.identity()).toMatchObject({ mode: "swarm" }); + await runtime.close({ reason: "done" }); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts new file mode 100644 index 00000000000..6d51791ccfa --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts @@ -0,0 +1,87 @@ +import { userInfo } from "node:os"; +import { join } from "node:path"; +import { AntigravitySavedStateIncompatibleError } from "./antigravity-admission.js"; +import { ANTIGRAVITY_CLI_DISTRIBUTION } from "./antigravity-cli-pins.js"; +import { resolveAntigravityCliLaunch, type AntigravityCliLaunchOptions } from "./antigravity-cli-installation.js"; +import { ANTIGRAVITY_CLI_STABLE_ENDPOINT, ANTIGRAVITY_SWARM_MODE, AntigravitySwarmError } from "./antigravity-swarm-guard.js"; +import type { VerifiedAcpxInstallation } from "./installation-integrity.js"; + +/** The Antigravity CLI route is selected only by the trusted `swarm` provider mode. */ +export function isAntigravitySwarmRoute(agent: string, mode: string | undefined): boolean { + return agent === "antigravity" && mode === ANTIGRAVITY_SWARM_MODE; +} + +/** Private CLI state (settings, skills, conversations) under the run's credential home. */ +export function antigravitySwarmStateDirectory(agentHomeDirectory: string): string { + 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"]; +} + +/** + * Plain-language refusal when this host or connection cannot run a swarm. + * Helpers write only in the CLI's auto mode, which API-key connections lack. + */ +export function antigravitySwarmRouteRefusal(input: { environment: NodeJS.ProcessEnv; platform?: string; architecture?: string }): AntigravitySwarmError | null { + const target = `${input.platform ?? process.platform}-${input.architecture ?? process.arch}`; + if (!Object.hasOwn(ANTIGRAVITY_CLI_DISTRIBUTION.platforms, target)) { + return new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", `Swarm is not available on this computer: the Antigravity CLI has no pinned build for ${target}.`); + } + if (!input.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET) { + return new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", + "Swarm is not available with a Gemini API key: helpers can only change files in Antigravity's auto mode, which needs a Google sign-in."); + } + return null; +} + +/** + * The pinned CLI as an ACPX installation. Its per-run `--gemini-dir` is known only + * after the sandbox exists, so the launch arguments are bound when the command opens. + */ +export async function verifyAntigravitySwarmInstallation( + stateDirectory: () => string, + options: Omit = {}, +): Promise { + const pinned = await resolveAntigravityCliLaunch(options); + return Object.freeze({ + commandDigest: pinned.commandDigest, + agentServerPackageJsonPath: null, + agentRuntimePackageJsonPath: null, + async openCommand(open?: { signal?: AbortSignal }) { + const launch = await resolveAntigravityCliLaunch({ ...options, arguments: antigravitySwarmArguments(stateDirectory()) }); + if (launch.commandDigest !== pinned.commandDigest) throw new Error("Antigravity CLI installation changed during admission"); + return launch.installation.openCommand(open); + }, + }); +} + +/** + * Launch environment for the CLI: the sandbox's private environment without the + * registry server's credential plumbing. On macOS the CLI keeps its Google + * sign-in in the login keychain, which it finds through the real HOME, so HOME is + * the OS user's home there; all CLI state still lives in the private `--gemini-dir`. + */ +export function antigravitySwarmLaunchEnvironment( + sandbox: Readonly, + input: { agentHomeDirectory: string; platform?: NodeJS.Platform; realHome?: string }, +): NodeJS.ProcessEnv { + const environment: NodeJS.ProcessEnv = { ...sandbox }; + for (const name of ["GEMINI_HOME", "AGY_ACP_FORCE_FILE_STORAGE", "GEMINI_API_KEY", "GOOGLE_API_KEY", "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"]) delete environment[name]; + if ((input.platform ?? process.platform) === "darwin") environment.HOME = input.realHome ?? userInfo().homedir; + return { ...environment, ...ANTIGRAVITY_CLI_DISTRIBUTION.environment }; +} + +/** + * A saved conversation from the other Antigravity route (swarm on the CLI, or + * an ordinary turn on the registry server) cannot be reopened by this one. The + * typed refusal makes the server start a fresh conversation, so the task keeps + * accepting messages after a swarm and a later /swarm starts cleanly. + */ +export function antigravityRouteChangeRefusal(agent: string, savedMode: string | undefined, requestedMode: string | undefined): AntigravitySavedStateIncompatibleError | null { + if (agent !== "antigravity") return null; + if (isAntigravitySwarmRoute(agent, savedMode) === isAntigravitySwarmRoute(agent, requestedMode)) return null; + return new AntigravitySavedStateIncompatibleError("the saved conversation belongs to a different Antigravity route"); +} 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 new file mode 100644 index 00000000000..23161ef29bd --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts @@ -0,0 +1,257 @@ +import { spawn } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } 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 type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; +import type { AcpxTerminalSessionFailure } from "./provider-failure.js"; + +const FIXTURE = new URL("../../../test-fixtures/antigravity-cli/fake-agy-acp.mjs", import.meta.url).pathname; +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); + +function setup(scenario: string, overrides: Partial = {}) { + const root = realpathSync(mkdtempSync(join(tmpdir(), "agy-swarm-"))); + roots.push(root); + const log = join(root, "client.jsonl"); + const workerPidFile = join(root, "worker.pid"); + const cwd = join(root, "workspace"); + mkdirSync(cwd); + const options = { + command: { + spawn: (_args: readonly string[] = [], spawnOptions: Record = {}) => spawn(process.execPath, [FIXTURE], { + ...spawnOptions, detached: true, stdio: ["pipe", "pipe", "pipe"], + env: { ...process.env, FAKE_AGY_SCENARIO: scenario, FAKE_AGY_LOG: log, FAKE_AGY_WORKER_PID_FILE: workerPidFile }, + }), + close: async () => {}, + }, + profile: { agent: "antigravity", reportedModelId: "gemini-3.8-flash-low", qualificationModel: "gemini-3.8-flash-low" }, + cwd, stateDirectory: root, providerSessionKey: "key", permissionMode: "approve-reads", mode: "swarm", + permissionPolicy: {}, launchEnvironment: {}, credentialFenceFds: null, activateCredentialFenceOwner: null, + systemInstructions: "Paperclip instructions", + mcpServers: [{ name: "paperclip", url: "http://127.0.0.1:9/mcp", bearerToken: "bridge-secret", runnerOwned: true }], + retainFailedAdmissionCleanup: () => {}, + ...overrides, + } as unknown as AcpxRuntimePortOpenOptions; + const clientMessages = () => existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").map(line => JSON.parse(line)) : []; + return { root, cwd, options, clientMessages, workerPidFile }; +} + +async function runTurn(scenario: string, extra: { helperWaitTimeoutMs?: number; onEvent?: (event: AcpRuntimeEvent, cancel: () => Promise) => void } = {}) { + const context = setup(scenario); + const runtime = await openAntigravitySwarmRuntime(context.options, { helperWaitTimeoutMs: extra.helperWaitTimeoutMs ?? 5_000, cancelGraceMs: 500 }); + const failures: AcpxTerminalSessionFailure[] = []; + const turn = runtime.startTurn({ text: "two helpers write a.txt and b.txt", requestId: "run-1:turn-1", onTerminalSessionFailure: failure => failures.push(failure) }); + const events: AcpRuntimeEvent[] = []; + for await (const event of turn.events) { events.push(event); extra.onEvent?.(event, () => turn.cancel({ reason: "Stop" })); } + const result = await turn.result; + const status = await runtime.getStatus(); + await runtime.close({ reason: "done" }); + const titles = events.flatMap(event => event.type === "tool_call" && event.title ? [event.title] : []); + const text = events.flatMap(event => event.type === "text_delta" ? [event.text] : []).join(""); + return { ...context, runtime, result, events, titles, text, failures, status }; +} + +const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } }; + +describe("Antigravity CLI swarm runtime", () => { + it("opens with a verified receipt: pinned identity, task folder, Paperclip tools only, auto mode, exact model", async () => { + const { options, clientMessages, cwd } = setup("success"); + const runtime = await openAntigravitySwarmRuntime(options); + expect((await runtime.getStatus()).models?.currentModelId).toBe("gemini-3.8-flash-low"); + expect(await runtime.identity()).toMatchObject({ mode: "swarm", backendSessionId: "e6536314-e108-4ecd-a0cf-efa59061510d" }); + expect((await runtime.getStatus()).antigravitySwarmReceipt).toMatchObject({ mode: "auto", modelFamily: "gemini-3.8-flash", thoughtLevel: "low", workspace: cwd, mcpServers: ["paperclip"] }); + await runtime.close({ reason: "done" }); + const sent = clientMessages(); + const sessionNew = sent.find(message => message.method === "session/new"); + expect(sessionNew.params).toMatchObject({ cwd, mcpServers: [{ type: "http", name: "paperclip", headers: [{ name: "Authorization", value: "Bearer bridge-secret" }] }] }); + expect(sessionNew.params._meta.antigravity.systemPrompt.append).toContain("Paperclip instructions"); + expect(sent.map(message => message.method)).toEqual(expect.arrayContaining(["session/set_mode", "session/set_model"])); + expect(sent.some(message => message.method === "session/load")).toBe(false); + }); + + it.each([ + ["wrong-version", /pinned version/], ["wrong-mode", /auto mode/], ["wrong-model", /gemini-3.8-flash-low/], ["no-auto", /auto mode, which this sign-in does not offer/], + ])("fails closed on %s", async (scenario, message) => { + const { options } = setup(scenario); + await expect(openAntigravitySwarmRuntime(options, { readbackTimeoutMs: 200 })).rejects.toThrow(message); + }); + + 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" }); + expect(readFileSync(join(run.cwd, "a.txt"), "utf8")).toBe("A"); + expect(run.titles).toEqual(expect.arrayContaining([ + "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.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 /); + expect(run.status.terminalPromptUsage).toMatchObject({ requestId: "run-1:turn-1", event: { breakdown: { totalTokens: 133035 } } }); + expect(run.titles.some(title => /includes the helpers/.test(title))).toBe(true); + }); + + it("does not settle on the first end_turn while helpers still run", async () => { + const run = await runTurn("live-helpers"); + expect(run.result).toMatchObject({ status: "completed" }); + expect(run.clientMessages().filter(message => message.method === "session/prompt")).toHaveLength(2); + expect(readFileSync(join(run.cwd, "b.txt"), "utf8")).toBe("B"); + expect(run.status.terminalPromptUsage).toMatchObject({ event: { breakdown: { totalTokens: 134035 } } }); + }); + + it("fails with a clear timeout when helpers never finish", async () => { + const run = await runTurn("hang-helpers", { helperWaitTimeoutMs: 200 }); + expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_HELPERS_TIMEOUT" } }); + }); + + it("surfaces blocked helper actions and refuses the coordinator's outside write", async () => { + const run = await runTurn("blocked"); + expect(run.result).toMatchObject({ status: "completed" }); + expect(run.clientMessages().find(message => message.permissionAnswer)?.permissionAnswer).toEqual({ outcome: { outcome: "selected", optionId: "deny" } }); + expect(run.titles).toEqual(expect.arrayContaining(["Blocked: Write /outside/c.txt", "A helper was blocked from changing something outside the task folder"])); + }); + + it("shows what actually changed in the task folder when a helper misreports, and keeps its usage", async () => { + const run = await runTurn("misreport"); + expect(run.result).toMatchObject({ status: "completed" }); + expect(run.titles).toContain("Files changed in the task folder: a.txt"); + expect(run.status.terminalPromptUsage).toMatchObject({ event: { breakdown: { totalTokens: 133035 } } }); + }); + + it("never turns free-form brief wording into a required file", async () => { + const run = await runTurn("cautious-brief"); + expect(run.result).toMatchObject({ status: "completed" }); + }); + + it("refuses a swarm in a read-only (planning) run before the CLI starts", async () => { + const { options, clientMessages } = setup("success", { readOnly: true }); + await expect(openAntigravitySwarmRuntime(options)).rejects.toMatchObject({ code: "ANTIGRAVITY_SWARM_UNAVAILABLE", message: expect.stringMatching(/planning/) }); + expect(clientMessages()).toEqual([]); + }); + + it("refuses extra tool servers it would have to drop", async () => { + const extra = setup("success"); + (extra.options as unknown as { mcpServers: unknown[] }).mcpServers.push({ name: "github", command: "/bin/x", args: [], env: {}, runnerOwned: false }); + await expect(openAntigravitySwarmRuntime(extra.options)).rejects.toThrow(/other tool servers/); + }); + + it("turns a provider mode change during admission into a typed failure, stops the CLI, and keeps the caller alive", async () => { + const { options } = setup("mode-flip"); + let pid = 0; + const spawn = options.command.spawn; + (options.command as { spawn: typeof spawn }).spawn = (...args) => { const child = spawn(...args); pid = child.pid!; return child; }; + await expect(openAntigravitySwarmRuntime(options, { readbackTimeoutMs: 500 })).rejects.toMatchObject({ code: "ANTIGRAVITY_SWARM_RECEIPT_MISMATCH" }); + expect(alive(pid)).toBe(false); + }); + + it("fails the next turn and stops the CLI when settings change between turns", async () => { + const { options } = setup("mode-flip-idle"); + const runtime = await openAntigravitySwarmRuntime(options); + await new Promise(resolve => setTimeout(resolve, 300)); + const turn = runtime.startTurn({ text: "go", requestId: "r:1" }); + for await (const _ of turn.events) { /* drain */ } + expect(await turn.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_RECEIPT_MISMATCH" } }); + await runtime.close({ reason: "done" }); + }); + + it.each(["outside-edit", "dotdot-edit", "symlink-edit", "shell-escape"])("stops the swarm on a visible change outside the task folder: %s", async scenario => { + const run = await runTurn(scenario); + expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE", message: expect.stringMatching(/outside the task folder/) } }); + }); + + it("allows reading outside the task folder when the change lands inside it", async () => { + const run = await runTurn("shell-read"); + expect(run.result).toMatchObject({ status: "completed" }); + }); + + it("treats a saved conversation as one a swarm cannot reopen, so the server starts a fresh one", async () => { + await expect(openAntigravitySwarmRuntime(setup("success", { restoringSession: true }).options)) + .rejects.toMatchObject({ code: "ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE" }); + }); + + it("keeps a stable record identity while the CLI session id is per run", async () => { + const { options } = setup("success"); + const runtime = await openAntigravitySwarmRuntime(options); + expect((await runtime.identity()).acpxRecordId).toBe("antigravity-cli:key"); + await runtime.close({ reason: "done" }); + }); + + it("refuses a helper on its own workspace copy", async () => { + const run = await runTurn("escape"); + expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE" } }); + }); + + it.each(["refusal", "quota"])("classifies a %s that arrives as text as a typed failure", async scenario => { + const run = await runTurn(scenario); + expect(run.result).toMatchObject({ status: "failed" }); + expect(run.failures[0]?.provider?.kind).toBe(scenario === "refusal" ? "quota_exhausted" : "rate_limit"); + }); + + it("stops every helper on Stop and leaves no process behind", async () => { + let cancelled = false; + const run = await runTurn("cancel", { onEvent: (event, cancel) => { + if (!cancelled && event.type === "tool_call" && /verifier/.test(event.title ?? "")) { cancelled = true; void cancel(); } + } }); + expect(run.result).toMatchObject({ status: "cancelled" }); + expect(run.clientMessages().some(message => message.method === "session/cancel")).toBe(true); + const worker = Number(readFileSync(run.workerPidFile, "utf8")); + await new Promise(resolve => setTimeout(resolve, 200)); + expect(alive(worker)).toBe(false); + }); + + it("names a lost CLI process so Retry starts a fresh swarm", async () => { + const run = await runTurn("die"); + expect(run.result).toMatchObject({ status: "failed", error: { code: "ACPX_PROVIDER_PROCESS_LOST" } }); + const worker = Number(readFileSync(run.workerPidFile, "utf8")); + await new Promise(resolve => setTimeout(resolve, 200)); + expect(alive(worker)).toBe(false); + }); + + const trackPid = (options: AcpxRuntimePortOpenOptions) => { + const tracked = { pid: 0 }; + const spawnChild = options.command.spawn; + (options.command as { spawn: typeof spawnChild }).spawn = (...args) => { const child = spawnChild(...args); tracked.pid = child.pid!; return child; }; + return tracked; + }; + + it.each(["spawned", "initialized", "session", "mode", "model"])("a Stop at %s ends admission, sends no prompt and stops the CLI", async stage => { + const { options, clientMessages } = setup("success"); + const tracked = trackPid(options); + const stop = new AbortController(); + await expect(openAntigravitySwarmRuntime({ ...options, signal: stop.signal } as AcpxRuntimePortOpenOptions, + { onStage: current => { if (current === stage) stop.abort(new Error("Stop")); } })).rejects.toThrow(); + await new Promise(resolve => setTimeout(resolve, 100)); + expect(clientMessages().some(message => message.method === "session/prompt")).toBe(false); + expect(alive(tracked.pid)).toBe(false); + }); + + it.each<[AntigravitySwarmStage, number]>([["snapshot", 0], ["helpers", 1]])("a Stop at %s starts no further billable prompt and stops the CLI", async (stage, prompts) => { + const { options, clientMessages } = setup("live-helpers"); + const tracked = trackPid(options); + let cancel: () => Promise = async () => {}; + const runtime = await openAntigravitySwarmRuntime(options, { helperWaitTimeoutMs: 5_000, cancelGraceMs: 500, + onStage: async current => { if (current === stage) await cancel(); } }); + const turn = runtime.startTurn({ text: "go", requestId: "r:1" }); + cancel = () => turn.cancel(); + for await (const _ of turn.events) { /* drain */ } + expect(await turn.result).toMatchObject({ status: "cancelled" }); + await runtime.close({ reason: "Stop" }); + expect(clientMessages().filter(message => message.method === "session/prompt")).toHaveLength(prompts); + expect(alive(tracked.pid)).toBe(false); + }); + + it("runs at most one swarm per run", async () => { + const { options } = setup("success"); + const runtime = await openAntigravitySwarmRuntime(options); + const first = runtime.startTurn({ text: "go", requestId: "r:1" }); + for await (const _ of first.events) { /* drain */ } + await first.result; + const second = runtime.startTurn({ text: "again", requestId: "r:2" }); + for await (const _ of second.events) { /* drain */ } + expect(await second.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_UNAVAILABLE" } }); + await runtime.close({ reason: "done" }); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts new file mode 100644 index 00000000000..3618c538441 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts @@ -0,0 +1,555 @@ +import type { ChildProcess, ChildProcessWithoutNullStreams } from "node:child_process"; +import { lstat, 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 { + ANTIGRAVITY_CLI_SESSION_MODE, ANTIGRAVITY_SWARM_MCP_SERVER, ANTIGRAVITY_SWARM_MODE, AntigravitySwarmError, + antigravitySwarmWorkspaceEscape, classifyAntigravityRefusalText, createAntigravitySwarmGuard, + type AntigravitySwarmReceipt, +} from "./antigravity-swarm-guard.js"; +import { antigravitySwarmEvent } from "./antigravity-swarm-presentation.js"; +import { awaitVerifiedAcpxProviderOwnership } from "./installation-integrity.js"; +import type { AcpxModelStatus } from "./model-verification.js"; +import type { AcpxRuntimePort, AcpxRuntimePortIdentity, AcpxRuntimePortOpenOptions, AcpxRuntimeTurn, AcpxRuntimeTurnInput } from "./runtime-host.js"; + +/** + * Runtime port for the Antigravity CLI route (`agy acp`), used only for a turn + * the signed-in user started with `/swarm`. It speaks ACP directly instead of + * through ACPX because the CLI's model selector, auto mode and swarm turn shape + * need driver-owned verification (see antigravity-swarm-guard.ts). + * + * One port is one fresh CLI session: it never calls `session/load` (a reload + * resets mode and model, and the helpers are gone), so Retry after a lost + * process always starts a fresh swarm in the same task folder. + */ +export const ANTIGRAVITY_SWARM_INSTRUCTIONS = [ + "## Paperclip swarm rules", + "This turn runs Antigravity's native swarm for one Paperclip task. All helpers belong to this one Paperclip run.", + "- Start every helper with workspace \"inherit\". Never use \"share\" or \"branch\".", + "- Helpers change files only inside the current workspace (the task folder). Never write anywhere else.", + "- Do not use Paperclip tools that create tasks, assign work, or hire agents while the swarm runs.", + "- Wait until every helper and the verifier have finished before you end your turn.", + "- When the work is verified, hand in the result once through Paperclip's finish tool and name the files that were written.", +].join("\n"); + +const HELPER_WAIT_PROMPT = "Paperclip: wait until every helper has finished (use the swarm tools to wait; do not start new helpers), then confirm the result in one or two sentences. If you have not yet handed in through Paperclip's finish tool, do it now; if you already did, do not call it again."; +const DEFAULT_REQUEST_TIMEOUT_MS = 60_000; +const DEFAULT_HELPER_WAIT_TIMEOUT_MS = 20 * 60_000; +const DEFAULT_CANCEL_GRACE_MS = 5_000; +const READBACK_TIMEOUT_MS = 5_000; +const SNAPSHOT_LIMIT = 20_000; +const SKIPPED_DIRECTORIES = new Set([".git", "node_modules", ".venv", "__pycache__"]); +const BLOCKED_TEXT = /timed out waiting for user response|permission check failed/i; +export const ANTIGRAVITY_SWARM_PROCESS_LOST = "ACPX_PROVIDER_PROCESS_LOST"; + +export type AntigravitySwarmStage = "spawned" | "initialized" | "session" | "mode" | "model" | "snapshot" | "helpers"; + +export interface AntigravitySwarmRuntimeDependencies { + helperWaitTimeoutMs?: number; + requestTimeoutMs?: number; + cancelGraceMs?: number; + readbackTimeoutMs?: number; + /** Test seam: runs at every await point between launch and settle. */ + onStage?: (stage: AntigravitySwarmStage) => void | Promise; + awaitProviderOwnership?: (child: ChildProcess) => Promise; +} + +type Json = Record; +const record = (value: unknown): Json => + value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {}; + +class ProcessLostError extends Error { + readonly code = ANTIGRAVITY_SWARM_PROCESS_LOST; + constructor() { super("The swarm stopped unexpectedly because the Antigravity CLI exited. Retry starts a fresh swarm in the same task folder."); } +} + +class RpcError extends Error { + constructor(readonly method: string, readonly error: Json) { + super(`${method} failed: ${typeof error.message === "string" ? error.message.slice(0, 500) : "provider error"}`); + } +} + +/** Newline-delimited JSON-RPC over the CLI's stdio. Lines are handled one per macrotask + * so a response's awaiting caller observes it before the updates that follow it. */ +class Connection { + #next = 1; + #pending = new Map void; reject: (error: Error) => void }>(); + #buffer = ""; + #queue: Promise = Promise.resolve(); + #lost: Error | null = null; + readonly exited: Promise; + onNotification: (method: string, params: Json) => void = () => {}; + onRequest: (method: string, params: Json) => Promise = async () => { throw new Error("unsupported"); }; + onLost: () => void = () => {}; + + constructor(readonly child: ChildProcessWithoutNullStreams) { + this.exited = new Promise(resolve => child.once("close", () => resolve())); + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + this.#buffer += chunk; + if (this.#buffer.length > 16 * 1024 * 1024) { this.#fail(new Error("Antigravity CLI output exceeded its bound")); return; } + for (let index = this.#buffer.indexOf("\n"); index >= 0; index = this.#buffer.indexOf("\n")) { + const line = this.#buffer.slice(0, index); this.#buffer = this.#buffer.slice(index + 1); + if (line.trim()) this.#queue = this.#queue.then(() => new Promise(resolve => setImmediate(() => { + // A handler failure must never escape into the event loop and end the sidecar. + try { this.#line(line); } catch (error) { this.#fail(error instanceof Error ? error : new Error("Antigravity CLI message could not be handled")); } + resolve(); + }))); + } + }); + child.stderr.resume(); + child.stdin.on("error", () => undefined); + void this.exited.then(() => { void this.#queue.then(() => this.#fail(new ProcessLostError())); }); + } + + get lost(): Error | null { return this.#lost; } + + /** Settle every message already received from the CLI. */ + async drain(): Promise { + await new Promise(resolve => setImmediate(resolve)); + await this.#queue; + } + + #fail(error: Error): void { + if (this.#lost) return; + this.#lost = error; + for (const pending of this.#pending.values()) pending.reject(error); + this.#pending.clear(); + this.onLost(); + } + + #line(line: string): void { + let message: Json; + try { message = record(JSON.parse(line)); } catch { return; } + const { id, method } = message; + if (typeof method === "string") { + if (id === undefined) { this.onNotification(method, record(message.params)); return; } + void this.onRequest(method, record(message.params)).then( + result => this.#write({ jsonrpc: "2.0", id, result }), + () => this.#write({ jsonrpc: "2.0", id, error: { code: -32601, message: "Not supported by Paperclip" } }), + ); + return; + } + if (typeof id !== "number") return; + const pending = this.#pending.get(id); + if (!pending) return; + this.#pending.delete(id); + if (message.error !== undefined) pending.reject(new RpcError(pending.method, record(message.error))); + else pending.resolve(record(message.result)); + } + + #write(message: Json): void { + if (this.#lost || this.child.stdin.destroyed) return; + this.child.stdin.write(`${JSON.stringify(message)}\n`); + } + + request(method: string, params: Json, timeoutMs: number | null): Promise { + if (this.#lost) return Promise.reject(this.#lost); + const id = this.#next++; + return new Promise((resolve, reject) => { + let timer: ReturnType | undefined; + const settle = (fn: (value: T) => void) => (value: T) => { if (timer) clearTimeout(timer); fn(value); }; + this.#pending.set(id, { method, resolve: settle(resolve), reject: settle(reject) }); + if (timeoutMs !== null) { + timer = setTimeout(() => { + this.#pending.delete(id); + reject(new AntigravitySwarmError("ANTIGRAVITY_SWARM_RECEIPT_MISMATCH", `The Antigravity CLI did not answer ${method} in time.`)); + }, timeoutMs); + } + this.#write({ jsonrpc: "2.0", id, method, params }); + }); + } + + notify(method: string, params: Json): void { this.#write({ jsonrpc: "2.0", method, params }); } +} + +class EventQueue implements AsyncIterable { + #items: AcpRuntimeEvent[] = []; + #waiter: (() => void) | null = null; + #ended = false; + push(event: AcpRuntimeEvent): void { if (this.#ended) return; this.#items.push(event); this.#waiter?.(); } + end(): void { this.#ended = true; this.#waiter?.(); } + async *[Symbol.asyncIterator](): AsyncIterator { + for (;;) { + const item = this.#items.shift(); + if (item) { yield item; continue; } + if (this.#ended) return; + await new Promise(resolve => { this.#waiter = resolve; }); + this.#waiter = null; + } + } +} + +type Snapshot = { files: Map; complete: boolean }; +/** + * Bounded, asynchronous listing of the task folder. The limit counts every + * visited entry, and the walk yields between directories and stops when the + * turn is stopped, so a large workspace never blocks Stop or provider messages. + */ +async function snapshotWorkspace(root: string, signal: AbortSignal): Promise { + const files = new Map(); + let visited = 0; + const pending = [root]; + while (pending.length > 0) { + if (signal.aborted) return { files, complete: false }; + const directory = pending.pop()!; + let entries; + try { entries = await readdir(directory, { withFileTypes: true }); } catch { continue; } + for (const entry of entries) { + if (++visited > SNAPSHOT_LIMIT) return { files, complete: false }; + const path = join(directory, entry.name); + if (entry.isDirectory()) { if (!SKIPPED_DIRECTORIES.has(entry.name)) pending.push(path); continue; } + try { + const stat = await lstat(path); + files.set(relative(root, path).split(sep).join("/"), `${stat.size}:${stat.mtimeMs}`); + } catch { /* removed while listing */ } + } + } + return { files, complete: true }; +} + +function changedFiles(before: Map, after: Map): string[] { + const changed = [...after].filter(([path, identity]) => before.get(path) !== identity).map(([path]) => path); + const removed = [...before.keys()].filter(path => !after.has(path)).map(path => `${path} (removed)`); + return [...changed, ...removed].sort(); +} + +function addUsage(total: Json | null, usage: unknown): Json | null { + const value = record(usage); + if (Object.keys(value).length === 0) return total; + const next: Json = { ...(total ?? {}) }; + for (const key of ["inputTokens", "outputTokens", "cachedReadTokens", "cachedWriteTokens", "thoughtTokens", "totalTokens"]) { + if (typeof value[key] === "number") next[key] = (typeof next[key] === "number" ? next[key] as number : 0) + (value[key] as number); + } + return next; +} + +function failed(code: string, message: string): AcpRuntimeTurnResult { + return { status: "failed", error: { code, message, retryable: false } }; +} + +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 async function openAntigravitySwarmRuntime( + options: AcpxRuntimePortOpenOptions, + dependencies: AntigravitySwarmRuntimeDependencies = {}, +): Promise { + if (options.mode !== ANTIGRAVITY_SWARM_MODE || options.profile.agent !== "antigravity") { + throw new Error("The Antigravity CLI route serves only trusted swarm turns"); + } + options.signal?.throwIfAborted(); + // Host policy the registry route honours and this route cannot: refuse, never drop. + if (options.readOnly === true) { + throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "Swarm is not available while planning: helpers change files, and a planning run must not. Approve the plan first, then send /swarm."); + } + if (options.restoringSession === true) { + // Typed so the server starts a fresh conversation instead of showing Retry: + // a swarm's helpers are gone after an interruption and reload resets mode and model. + throw new AntigravitySavedStateIncompatibleError("a swarm always starts in a fresh session"); + } + if (options.mcpServers.some(server => !(server.runnerOwned && server.name === ANTIGRAVITY_SWARM_MCP_SERVER))) { + throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "Swarm is not available for this agent: it has other tool servers assigned, and a swarm uses only Paperclip's own tools."); + } + const requestTimeoutMs = dependencies.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS; + const model = options.profile.reportedModelId; + const bridge = options.mcpServers.find((server): server is Extract => + "url" in server && server.runnerOwned && server.name === ANTIGRAVITY_SWARM_MCP_SERVER); + 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 }); + + options.assertWorkspaceHeld?.(); + const lifetime = options.credentialFenceFds && options.activateCredentialFenceOwner + ? { credentialFenceFds: options.credentialFenceFds, activateCredentialFenceOwner: options.activateCredentialFenceOwner } : undefined; + const child = options.command.spawn([], { cwd: options.cwd, env: { ...options.launchEnvironment } }, lifetime) as ChildProcessWithoutNullStreams; + const connection = new Connection(child); + let retirement: Promise | null = null; + const retire = () => retirement ??= retireAntigravityProcess(child, connection.exited); + + let updateListener: ((params: Json) => void) | null = null; + let readback: (() => void) | null = null; + // A protocol failure outside a turn (for example a changed confirmed mode) + // is owned here: it fails admission or the next turn, and stops the CLI. + let protocolFailure: AntigravitySwarmError | null = null; + connection.onNotification = (method, params) => { + if (method !== "session/update") return; + try { + if (updateListener) updateListener(params); + else guard.observe(params); + } catch (error) { + protocolFailure ??= error instanceof AntigravitySwarmError ? error + : new AntigravitySwarmError("ANTIGRAVITY_SWARM_RECEIPT_MISMATCH", "The swarm settings changed. Nothing more was run."); + void retire().catch(() => undefined); + } + readback?.(); + }; + const waitForReadback = async (check: () => void): Promise => { + const deadline = Date.now() + (dependencies.readbackTimeoutMs ?? READBACK_TIMEOUT_MS); + for (;;) { + if (protocolFailure) throw protocolFailure; + try { check(); return; } catch (error) { + if (Date.now() >= deadline || connection.lost) throw error; + await new Promise(resolve => { + const timer = setTimeout(resolve, Math.max(0, deadline - Date.now())); + readback = () => { clearTimeout(timer); resolve(); }; + }); + readback = null; + } + } + }; + + let sessionId: string; + let receipt: AntigravitySwarmReceipt; + // 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 }); + const stage = async (name: AntigravitySwarmStage) => { + await dependencies.onStage?.(name); + options.signal?.throwIfAborted(); + }; + try { + await (dependencies.awaitProviderOwnership ?? awaitVerifiedAcpxProviderOwnership)(child); + await stage("spawned"); + const initialized = await connection.request("initialize", { + protocolVersion: 1, + clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, + clientInfo: { name: "paperclip-runner", version: "1" }, + }, requestTimeoutMs); + await stage("initialized"); + guard.initialize(initialized); + const sessionParams: Json = { + cwd: options.cwd, + mcpServers: [{ type: "http", name: ANTIGRAVITY_SWARM_MCP_SERVER, url: bridge.url, headers: [{ name: "Authorization", value: `Bearer ${bridge.bearerToken}` }] }], + _meta: { antigravity: { systemPrompt: { append: instructions } } }, + }; + guard.sessionRequest(sessionParams); + let opened: Json; + try { opened = await connection.request("session/new", sessionParams, requestTimeoutMs); } catch (error) { + if (error instanceof RpcError && (error.error.code === -32000 || /auth/i.test(String(error.error.message)))) { + throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_SIGN_IN_REQUIRED", + "The Antigravity CLI on this computer is not signed in to Google. Sign in to the CLI once, then retry."); + } + throw error; + } + await stage("session"); + sessionId = guard.sessionResult(opened); + await connection.request("session/set_mode", { sessionId, modeId: ANTIGRAVITY_CLI_SESSION_MODE }, requestTimeoutMs); + await waitForReadback(() => guard.bindMode()); + await stage("mode"); + await connection.request("session/set_model", { sessionId, modelId: model }, requestTimeoutMs); + await waitForReadback(() => guard.bindModel()); + await stage("model"); + await connection.drain(); + guard.assertSwarmCommand(); + receipt = guard.receipt(); + if (protocolFailure) throw protocolFailure; + options.signal?.throwIfAborted(); + } catch (error) { + options.signal?.removeEventListener("abort", abortAdmission); + const cleanup = retire(); + options.retainFailedAdmissionCleanup(cleanup); + await cleanup.catch(() => undefined); + throw error; + } + + options.signal?.removeEventListener("abort", abortAdmission); + const status: Json = { antigravitySwarmReceipt: receipt }; + let turns = 0; + let active: { cancel(reason?: string): Promise; result: Promise } | null = null; + let closed = false; + + const runTurn = async (input: AcpxRuntimeTurnInput, events: EventQueue, started: () => void): Promise => { + // Stop is installed before the first await, so no later await can miss it. + const listing = new AbortController(); + let cancelled = false; + let wake: (() => void) | null = null; + active!.cancel = async () => { cancelled = true; listing.abort(); connection.notify("session/cancel", { sessionId }); wake?.(); }; + const stopped = (): AcpRuntimeTurnResult => ({ status: "cancelled", stopReason: "cancelled" }); + if (protocolFailure) { started(); return failed(protocolFailure.code, protocolFailure.message); } + if (turns++ > 0) { + started(); + return failed("ANTIGRAVITY_SWARM_UNAVAILABLE", "At most one swarm runs per task run. Send another /swarm message to start a new one."); + } + const workspace = options.cwd; + const before = await snapshotWorkspace(workspace, listing.signal); + await dependencies.onStage?.("snapshot"); + if (cancelled) { started(); return stopped(); } + const helpers = new Map(); + let blocked = 0; + let waitedAfterLastAdd = false; + 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.model}. Helper changes inside the task folder are approved automatically; anything else is blocked.`)); + + updateListener = params => { + try { guard.observe(params); } catch (error) { + halt(error instanceof AntigravitySwarmError ? error : new AntigravitySwarmError("ANTIGRAVITY_SWARM_RECEIPT_MISMATCH", "The swarm settings changed.")); + return; + } + if (params.sessionId !== sessionId) return; + const update = record(params.update); + const escaped = antigravitySwarmWorkspaceEscape(update); + if (escaped) { + halt(new AntigravitySwarmError("ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE", + `Swarm stopped: helper ${escaped} was asked to work on its own copy of the task folder, which Paperclip does not allow.`)); + return; + } + const outside = antigravityOutsideChange(update, workspace, home); + if (outside) { + halt(new AntigravitySwarmError("ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE", + `Swarm stopped: it tried to change ${outside}, which is outside the task folder.`)); + return; + } + const args = { ...record(update.rawInput), ...record(update.args) }; + if (update.sessionUpdate === "tool_call" && update.name === "swarm" && args.action === "add" && typeof args.name === "string") { + helpers.set(args.name, typeof args.brief === "string" ? args.brief : ""); + waitedAfterLastAdd = false; + } + if (update.sessionUpdate === "tool_call_update" && update.status === "completed" && (update.name === "read_board" || update.name === "swarm_wait")) { + waitedAfterLastAdd = true; + } + const content = record(update.content); + const text = typeof content.text === "string" ? content.text : JSON.stringify(update.rawOutput ?? ""); + if (update.sessionUpdate === "agent_message_chunk" && typeof content.text === "string") transcript += content.text; + if (BLOCKED_TEXT.test(text)) { + blocked += 1; + events.push(line(`blocked-${blocked}`, "A helper was blocked from changing something outside the task folder")); + } + const event = antigravitySwarmEvent(update, workspace); + if (event) events.push(event); + }; + connection.onRequest = async (method, params) => { + if (method !== "session/request_permission" || params.sessionId !== sessionId) throw new Error("unsupported"); + const toolCall = record(params.toolCall); + const meta = record(record(toolCall._meta).mcp); + const choices = Array.isArray(params.options) ? params.options.map(record) : []; + // Only Paperclip's own tool server is approved here; auto mode already + // allows the task folder, so anything else that asks is outside it. + const paperclip = meta.server === ANTIGRAVITY_SWARM_MCP_SERVER; + const choice = choices.find(option => option.kind === (paperclip ? "allow_once" : "reject_once")); + if (!paperclip) { + blocked += 1; + const title = typeof toolCall.title === "string" ? toolCall.title.split(workspace).join(".") : "an action outside the task folder"; + events.push(line(`blocked-${blocked}`, `Blocked: ${title.slice(0, 160)}`)); + } + return choice ? { outcome: { outcome: "selected", optionId: choice.optionId } } : { outcome: { outcome: "cancelled" } }; + }; + + let usage: Json | null = null; + const prompt = async (text: string, timeoutMs: number | null): Promise => { + if (cancelled || stop) return "cancelled"; + const response = connection.request("session/prompt", { sessionId, prompt: [{ type: "text", text }] }, null); + started(); + let timer: ReturnType | undefined; + const interrupted = new Promise<"interrupted">(resolve => { + wake = () => resolve("interrupted"); + if (timeoutMs !== null) timer = setTimeout(() => resolve("interrupted"), timeoutMs); + }); + try { + const outcome = await Promise.race([response, interrupted]); + if (outcome === "interrupted") { + if (!stop && !cancelled) halt(new AntigravitySwarmError("ANTIGRAVITY_SWARM_HELPERS_TIMEOUT", + "The helpers did not finish in time, so Paperclip stopped the swarm. Files they already wrote stay in the task folder.")); + const grace = dependencies.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS; + const settled = await Promise.race([response.then(() => true, () => true), new Promise(resolve => setTimeout(() => resolve(false), grace))]); + if (!settled) await retire().catch(() => undefined); + return "cancelled"; + } + usage = addUsage(usage, outcome.usage); + if (usage) { + // Billable usage is kept whatever the turn's outcome turns out to be. + status.lastRequestId = input.requestId; + status.terminalPromptUsage = { requestId: input.requestId, promptId: `${input.requestId}:swarm`, + event: { type: "status", tag: "usage_update", text: "terminal prompt usage", breakdown: usage } }; + } + return typeof outcome.stopReason === "string" ? outcome.stopReason : "end_turn"; + } finally { + if (timer) clearTimeout(timer); + wake = null; + } + }; + const dispatch = input.dispatchJournal?.markReceived() ? input.dispatchJournal : null; + try { + dispatch?.markDispatched(); + let stopReason = await prompt(`/swarm ${input.text}`, null); + if (stopReason === "end_turn" && !stop && !cancelled && helpers.size > 0 && !waitedAfterLastAdd && !classifyAntigravityRefusalText(transcript)) { + events.push(line("wait", "Waiting for the helpers to finish")); + transcript += "\n"; + await dependencies.onStage?.("helpers"); + stopReason = await prompt(HELPER_WAIT_PROMPT, dependencies.helperWaitTimeoutMs ?? DEFAULT_HELPER_WAIT_TIMEOUT_MS); + } + const halted = stop as AntigravitySwarmError | null; + if (halted) return failed(halted.code, halted.message); + if (cancelled || stopReason === "cancelled") return stopped(); + const refusal = classifyAntigravityRefusalText(transcript); + if (refusal) { + input.onTerminalSessionFailure?.({ category: refusal.kind === "authentication" ? "access" : "limit", title: refusal.message, + provider: { kind: refusal.kind, ...(refusal.httpStatus ? { httpStatus: refusal.httpStatus } : {}), ...(refusal.status ? { status: refusal.status } : {}) } }); + return failed(refusal.kind === "authentication" ? "ANTIGRAVITY_SWARM_SIGN_IN_REQUIRED" : "ANTIGRAVITY_SWARM_PROVIDER_REFUSED", refusal.message); + } + // What the swarm changed is recorded from the task folder itself, never + // from what the coordinator or helpers say (helpers can misreport). + // Done still requires the hand-in through Paperclip's finish tool. + const after = await snapshotWorkspace(workspace, listing.signal); + const changed = changedFiles(before.files, after.files); + events.push(line("files", !before.complete || !after.complete ? "The task folder is too large to list every change" + : changed.length ? `Files changed in the task folder: ${changed.slice(0, 20).join(", ")}${changed.length > 20 ? ", …" : ""}` : "No files changed in the task folder")); + return { status: "completed", stopReason: "end_turn" }; + } catch (error) { + if (connection.lost instanceof ProcessLostError || error instanceof ProcessLostError) { + return cancelled ? { status: "cancelled", stopReason: "cancelled" } : failed(ANTIGRAVITY_SWARM_PROCESS_LOST, new ProcessLostError().message); + } + return failed(error instanceof AntigravitySwarmError ? error.code : "ANTIGRAVITY_SWARM_FAILED", + error instanceof Error ? error.message.slice(0, 1_000) : "The swarm failed."); + } finally { + updateListener = null; + if (usage) events.push(line("usage", "Token usage is the coordinator's total and includes the helpers; Google does not report it per helper")); + } + }; + + const port: AcpxRuntimePort = { + async identity(): Promise { + // The record is stable per provider session key; the CLI session id is per run and never reloaded. + return { mode: ANTIGRAVITY_SWARM_MODE, acpxRecordId: `antigravity-cli:${options.providerSessionKey}`, backendSessionId: sessionId, agentSessionId: sessionId }; + }, + async getStatus(): Promise { + return { ...structuredClone(status), models: { currentModelId: model, availableModelIds: [model] } }; + }, + startTurn(input: AcpxRuntimeTurnInput): AcpxRuntimeTurn { + if (closed) throw new Error("The Antigravity swarm session is closed"); + if (active) throw new Error("A swarm turn is already running"); + const events = new EventQueue(); + let markStarted!: () => void; + const promptStarted = new Promise(resolve => { markStarted = resolve; }); + const turn = { cancel: async (_reason?: string) => {}, result: Promise.resolve() as unknown as Promise }; + active = turn; + const onAbort = () => { void turn.cancel(); }; + input.signal?.addEventListener("abort", onAbort, { once: true }); + turn.result = runTurn(input, events, markStarted).finally(() => { + markStarted(); + events.end(); + input.signal?.removeEventListener("abort", onAbort); + if (active === turn) active = null; + }); + return { + requestId: input.requestId, promptStarted, events, result: turn.result, + cancel: async () => { await turn.cancel(); }, + closeStream: async () => { events.end(); }, + }; + }, + async close(): Promise { + closed = true; + const turn = active; + if (turn) { await turn.cancel(); await Promise.race([turn.result, new Promise(resolve => setTimeout(resolve, dependencies.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS))]); } + await retire(); + }, + }; + return port; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/provider-mode.ts b/packages/paperclip-runner/src/drivers/acpx/provider-mode.ts index 42b5c1c2a47..1da9a1b9baf 100644 --- a/packages/paperclip-runner/src/drivers/acpx/provider-mode.ts +++ b/packages/paperclip-runner/src/drivers/acpx/provider-mode.ts @@ -1,5 +1,6 @@ import { parseProviderMode } from "../../contracts/provider-mode.js"; import { createCursorModeAdmission, resolveCursorSessionMode } from "./cursor-mode.js"; +import { ANTIGRAVITY_SWARM_MODE } from "./antigravity-swarm-guard.js"; interface ModeAdmission { assertReady(): void; @@ -8,7 +9,7 @@ interface ModeAdmission { } interface ProviderModeAdapter { - resolve(mode: unknown): string; + resolve(mode: unknown): string | undefined; admit(mode: string): ModeAdmission; configKey: string; } @@ -21,6 +22,18 @@ const adapters: Readonly> = { admit: mode => createCursorModeAdmission(resolveCursorSessionMode(mode)), configKey: "mode", }, + // `swarm` is set by Paperclip only for a turn the signed-in user started with + // a trusted /swarm. It selects the Antigravity CLI route, whose own runtime + // sets and verifies the native mode (antigravity-swarm-runtime.ts). + antigravity: { + resolve: mode => { + if (mode === undefined) return undefined; + if (mode !== ANTIGRAVITY_SWARM_MODE) throw new Error("ACPX antigravity supports only the swarm provider mode"); + return mode; + }, + admit: () => { throw new Error("The Antigravity swarm route does not run through ACPX mode admission"); }, + configKey: "mode", + }, }; export function resolveAcpxProviderMode(agent: string, mode: unknown): string | undefined { diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index 5aeb084ecd9..e78d467f6a0 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts @@ -14,6 +14,7 @@ import type { ClaudeProviderCycleItem } from "./claude-provider-turns.js"; import { resolveAcpxProviderMode } from "./provider-mode.js"; import { resolvePiThinkingLevel, type PiThinkingLevel } from "./pi-thinking.js"; import { preparedHarnessHome, preconfiguredHomeEnvironment, usesPreconfiguredHome } from "../preconfigured-home.js"; +import { mkdir } from "node:fs/promises"; import { dirname, join } from "node:path"; import { bindAcpxAgentFiles } from "./agent-files-binding.js"; import { assertAcpxProfileEnvironment, assertAcpxProfileWorkspace, classifyAcpxProfileError, verifyAcpxProfileInstallation } from "./profile-installation.js"; @@ -22,6 +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, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js"; import type { AcpRuntimeOptions, @@ -433,6 +435,8 @@ export class AcpxRuntimeHost { dependencies.retainAdmissionCleanup, ).catch(error => { throw recordAcpxAdmissionFailure(error, "binding"); }); if (options.expectedIdentity) { + const routeChange = antigravityRouteChangeRefusal(options.agent, options.expectedIdentity.mode, binding.mode); + if (routeChange) throw routeChange; verifyExpectedAcpxIdentity(options.expectedIdentity, binding, null); } options.assertWorkspaceHeld?.(); @@ -445,15 +449,27 @@ export class AcpxRuntimeHost { ); } + const swarmRoute = isAntigravitySwarmRoute(options.agent, binding.mode); + if (swarmRoute) { + const refusal = antigravitySwarmRouteRefusal({ environment: options.environment ?? {} }); + if (refusal) throw refusal; + } + let swarmStateDirectory: string | null = null; const installation = await runAbortableAdmissionStage( options.signal, () => dependencies.verifyInstallation ? dependencies.verifyInstallation(profile) - : verifyAcpxProfileInstallation(profile, options.candidateAdmission), + : swarmRoute + // The trusted /swarm turn runs the pinned Antigravity CLI, not the registry server. + ? verifyAntigravitySwarmInstallation(() => { + if (swarmStateDirectory === null) throw new Error("Antigravity CLI state directory is not prepared"); + return swarmStateDirectory; + }) + : verifyAcpxProfileInstallation(profile, options.candidateAdmission), dependencies.retainAdmissionCleanup, ).catch(error => { throw recordAcpxAdmissionFailure(error, "installation"); }); - if (installation.commandDigest !== profile.commandDigest) { + if (!swarmRoute && installation.commandDigest !== profile.commandDigest) { throw new Error("Verified ACPX installation does not match its profile"); } let admissionSucceeded = false; @@ -542,7 +558,7 @@ export class AcpxRuntimeHost { reportFailure: (failure) => dependencies.reportRetainedCleanupFailure(failure), }); - } else if (options.agent === "antigravity") { + } else if (options.agent === "antigravity" && !swarmRoute) { credential = await acquireAbortableAdmissionResource({ signal: options.signal, acquire: () => stageManagedAntigravityCredential({ agentHomeDirectory: sandbox.agentHomeDirectory, @@ -592,6 +608,11 @@ export class AcpxRuntimeHost { if (options.agent !== "antigravity") assertAcpxProfileEnvironment(options.agent, sandbox.launchEnvironment); admissionStage = "configuration"; let launchEnvironment = sandbox.launchEnvironment; + if (swarmRoute) { + swarmStateDirectory = antigravitySwarmStateDirectory(sandbox.agentHomeDirectory); + await mkdir(swarmStateDirectory, { recursive: true, mode: 0o700 }); + launchEnvironment = Object.freeze(antigravitySwarmLaunchEnvironment(launchEnvironment, { agentHomeDirectory: sandbox.agentHomeDirectory })); + } // This copy is registered by the authenticated controller for its company, // agent and run. Environment/config values cannot widen the grant. Each // resumed process receives the newly registered copy; collection already diff --git a/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs new file mode 100644 index 00000000000..b9ca6852bb4 --- /dev/null +++ b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs @@ -0,0 +1,177 @@ +#!/usr/bin/env node +// Deterministic stand-in for `agy acp` 1.5.15 (Google Antigravity CLI), replaying +// the message shapes recorded in the 2026-11-24 spike (transcripts a1-a4, b1, d1, +// d2). It never touches the network. FAKE_AGY_SCENARIO selects the behaviour: +// success two writers and a verifier; files land in the workspace +// live-helpers the coordinator ends its first turn while helpers still run; +// the files appear only after the follow-up wait prompt +// blocked a helper is blocked outside the workspace; the coordinator +// also asks the client to approve an outside write +// misreport writer-b is reported done but b.txt was never written +// escape a helper is started on its own branch workspace +// cancel helpers keep running (a real child process) until session/cancel +// die the CLI exits in the middle of the swarm +// refusal the provider refusal arrives as ordinary text with end_turn +// quota the 429 quota refusal, as seen live on 2026-11-24 +// wrong-version | no-auto | wrong-mode | wrong-model receipt mismatches +// hang-helpers the follow-up wait never ends +// mode-flip the CLI switches back to default mode right after the model is set +// mode-flip-idle the CLI switches back to default mode after the session opened, between turns +// outside-edit the coordinator edits a file outside the workspace (absolute path) +// dotdot-edit the coordinator edits ../escape.txt through its path argument +// symlink-edit the coordinator edits link/x.txt where link points outside the workspace +// shell-escape the coordinator runs `printf E > /tmp/...` (the CLI's shell sandbox allows temp dirs) +// shell-read the coordinator reads outside the workspace and copies into it (allowed) +// cautious-brief a helper brief says "Do not create debug.log"; the run is correct +// FAKE_AGY_LOG (optional) appends every client message, one JSON per line. +import { spawn } from "node:child_process"; +import { appendFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +const scenario = process.env.FAKE_AGY_SCENARIO ?? "success"; +const log = message => { if (process.env.FAKE_AGY_LOG) appendFileSync(process.env.FAKE_AGY_LOG, `${JSON.stringify(message)}\n`); }; +const write = message => process.stdout.write(`${JSON.stringify(message)}\n`); +const update = (sessionId, value) => write({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update: value } }); +const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); +const MODELS = ["gemini-4-argon-medium", "gemini-4-argon-low", "gemini-3.8-flash-high", "gemini-3.8-flash-medium", "gemini-3.8-flash-low"]; +const COMMANDS = ["goal", "compact", "schedule", "browser", "plan", "grill-me", "teamwork", "learn", "boost", "agy-customizations", "antigravity-guide", "run-workflow", "swarm"]; + +const state = { sessionId: "", cwd: "", model: "gemini-4-argon", level: "medium", mode: "default", prompts: 0, cancel: null, worker: null }; +const configOptions = () => [ + { id: "model", name: "Model", category: "model", type: "select", currentValue: state.model, options: [{ value: "gemini-4-argon" }, { value: "gemini-3.8-flash" }] }, + { id: "thought_level", name: "Thinking Level", category: "thought_level", type: "select", currentValue: state.level, options: [{ value: "low" }, { value: "medium" }, { value: "high" }] }, + { id: "mode", name: "Mode", category: "mode", type: "select", currentValue: state.mode, options: [{ value: "default" }, { value: "accept-edits" }, { value: "auto" }, { value: "plan" }] }, +]; +let call = 1000; +const tool = async (name, args, status = "completed") => { + const toolCallId = `call_${++call}`; + update(state.sessionId, { sessionUpdate: "tool_call", toolCallId, name, args, status: "in_progress", kind: "other", title: `Run ${name}`, rawInput: args }); + await sleep(2); + update(state.sessionId, { sessionUpdate: "tool_call_update", toolCallId, name, args, status, kind: "other", title: `Run ${name}`, rawInput: args }); +}; +const say = text => update(state.sessionId, { sessionUpdate: "agent_message_chunk", content: { type: "text", text } }); +const usage = { inputTokens: 49646, outputTokens: 1421, cachedReadTokens: 81968, cachedWriteTokens: 0, thoughtTokens: 0, totalTokens: 133035 }; +const addWriters = async () => { + await tool("swarm", { action: "title", title: "Two writers and a verifier" }); + await tool("swarm", { action: "add", name: "writer-a", workspace: "inherit", brief: "Write a.txt containing exactly 'A' in the current workspace directory. Once done, post to the board: '@verifier [done] a.txt written'." }); + await tool("swarm", { action: "add", name: "writer-b", workspace: "inherit", brief: "Write b.txt containing exactly 'B' in the current workspace directory. Once done, post to the board: '@verifier [done] b.txt written'." }); + await tool("swarm", { action: "add", name: "verifier", workspace: "inherit", brief: scenario === "cautious-brief" + ? "Wait for writer-a and writer-b, then read a.txt and b.txt. Do not create debug.log or any other file. Write docs.google.com links only if v1.2 asks." : "Wait for writer-a and writer-b, then read a.txt and b.txt and report." }); + await tool("swarm", { action: "add", name: "monitor", workspace: "inherit", brief: "You are this swarm's stall monitor. Load the swarm_monitor skill and follow it." }); +}; +const writeFiles = () => { + writeFileSync(join(state.cwd, "a.txt"), "A"); + writeFileSync(join(state.cwd, "b.txt"), "B"); +}; + +async function prompt(id, params) { + state.prompts += 1; + const text = params.prompt?.[0]?.text ?? ""; + if (state.prompts > 1) { + // Paperclip's follow-up: wait for the helpers, then confirm. + if (scenario === "hang-helpers") { await new Promise(resolve => { state.cancel = resolve; }); return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } }); } + await tool("read_board", { since: 5 }); + if (scenario === "live-helpers") writeFiles(); + say("All helpers have finished. a.txt contains A and b.txt contains B."); + return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn", usage: { ...usage, totalTokens: 1000, inputTokens: 900, outputTokens: 100, cachedReadTokens: 0 } } }); + } + if (!text.startsWith("/swarm ")) { say("not a swarm"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); } + update(state.sessionId, { sessionUpdate: "session_info_update", title: "Swarm" }); + if (scenario === "refusal") { say("\n⚠ agent executor error: Error 402 Your prepayment credits are depleted. Status: RESOURCE_EXHAUSTED\n"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); } + if (scenario === "quota") { say("\n⚠ RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); } + const outside = { + "outside-edit": { name: "write_file", kind: "edit", title: "Write /etc/elsewhere.txt", locations: [{ path: "/etc/elsewhere.txt" }] }, + "dotdot-edit": { name: "write_file", kind: "edit", title: "Write file", args: { TargetFile: `${state.cwd}/../escape.txt` } }, + "symlink-edit": { name: "write_file", kind: "edit", title: "Write file", locations: [{ path: `${state.cwd}/link/x.txt` }] }, + "shell-escape": { name: "run_command", kind: "execute", title: "Run command", args: { CommandLine: "printf E > /tmp/agy-escape-e.txt" } }, + }[scenario]; + if (scenario === "symlink-edit") (await import("node:fs")).symlinkSync("/etc", `${state.cwd}/link`); + if (scenario === "shell-read") { + await tool("run_command", { CommandLine: "cat /etc/hosts > ./hosts-copy.txt && cp /etc/hosts ./hosts2.txt" }); + } + if (outside) { + update(state.sessionId, { sessionUpdate: "tool_call", toolCallId: "call_out", status: "in_progress", rawInput: outside.args, ...outside }); + if (!state.cancelled) await new Promise(resolve => { state.cancel = resolve; }); + return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } }); + } + if (scenario === "escape") { await tool("swarm", { action: "add", name: "writer-a", workspace: "branch", brief: "Write a.txt." }); if (!state.cancelled) await new Promise(resolve => { state.cancel = resolve; }); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); } + await addWriters(); + say("I have configured and launched the swarm.\n\nRun /swarm board (default shortcut alt+s) to open the live board."); + if (scenario === "cancel" || scenario === "die") { + // A helper is a real descendant in the CLI's process group. + state.worker = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" }); + if (process.env.FAKE_AGY_WORKER_PID_FILE) writeFileSync(process.env.FAKE_AGY_WORKER_PID_FILE, String(state.worker.pid)); + if (scenario === "die") { await sleep(50); process.exit(3); } + if (state.cancelled) return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } }); + if (!state.cancelled) await new Promise(resolve => { state.cancel = resolve; }); + return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } }); + } + if (scenario === "live-helpers" || scenario === "hang-helpers") return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn", usage } }); + if (scenario === "misreport") writeFileSync(join(state.cwd, "a.txt"), "A"); else writeFiles(); + if (scenario === "blocked") { + await tool("swarm", { action: "add", name: "writer-c", workspace: "inherit", brief: "Try once to write /outside/c.txt containing 'C'." }); + const permissionId = 77; + write({ jsonrpc: "2.0", id: permissionId, method: "session/request_permission", params: { sessionId: state.sessionId, + toolCall: { toolCallId: "call_perm", title: "Write /outside/c.txt", kind: "edit" }, + options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }, { optionId: "deny", name: "Deny", kind: "reject_once" }] } }); + await new Promise(resolve => { state.permission = resolve; }); + say("writer-c: the write outside the workspace failed (sandbox permission check timed out waiting for user response).\n"); + } + await tool("read_board", { since: 5 }); + await tool("post_message", { text: "[done] Verification verified and tasks finished successfully." }); + say("\n\nThe swarm has completed its work. a.txt contains A and b.txt contains B."); + write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn", usage } }); +} + +let buffer = ""; +process.stdin.on("data", chunk => { + buffer += chunk; + for (let index = buffer.indexOf("\n"); index >= 0; index = buffer.indexOf("\n")) { + const line = buffer.slice(0, index); buffer = buffer.slice(index + 1); + if (!line.trim()) continue; + const message = JSON.parse(line); + log(message); + void handle(message); + } +}); +process.stdin.on("end", () => process.exit(0)); + +async function handle(message) { + const { id, method, params = {} } = message; + if (method === undefined) { if (id === 77) { log({ permissionAnswer: message.result }); state.permission?.(); } return; } + if (method === "initialize") { + return write({ jsonrpc: "2.0", id, result: { protocolVersion: 1, + agentCapabilities: { loadSession: true, promptCapabilities: { image: true, embeddedContext: true }, _meta: { antigravity: { tier: true, systemPrompt: { append: true } } } }, + agentInfo: { name: "Antigravity ACP Server", version: scenario === "wrong-version" ? "1.5.16" : "1.5.15" }, + authMethods: [{ id: "oauth-personal" }, { id: "gemini-api-key" }] } }); + } + if (method === "session/new") { + state.sessionId = "e6536314-e108-4ecd-a0cf-efa59061510d"; state.cwd = params.cwd; + write({ jsonrpc: "2.0", id, result: { sessionId: state.sessionId, + models: { availableModels: MODELS.map(modelId => ({ modelId })), currentModelId: "gemini-4-argon-medium" }, + modes: { currentModeId: "default", availableModes: (scenario === "no-auto" ? ["default", "accept-edits", "plan"] : ["default", "accept-edits", "auto", "plan"]).map(id => ({ id })) }, + configOptions: configOptions() } }); + await sleep(5); + update(state.sessionId, { sessionUpdate: "available_commands_update", availableCommands: COMMANDS.map(name => ({ name })) }); + return; + } + if (method === "session/set_mode") { + write({ jsonrpc: "2.0", id, result: {} }); + if (scenario === "wrong-mode") return; + state.mode = params.modeId; + update(state.sessionId, { sessionUpdate: "current_mode_update", currentModeId: state.mode }); + return update(state.sessionId, { sessionUpdate: "config_option_update", configOptions: configOptions() }); + } + if (method === "session/set_model") { + write({ jsonrpc: "2.0", id, result: {} }); + const match = /^(.*)-(low|medium|high)$/.exec(params.modelId); + state.model = match[1]; state.level = scenario === "wrong-model" ? "high" : match[2]; + update(state.sessionId, { sessionUpdate: "config_option_update", configOptions: configOptions() }); + if (scenario === "mode-flip") update(state.sessionId, { sessionUpdate: "current_mode_update", currentModeId: "default" }); + if (scenario === "mode-flip-idle") setTimeout(() => update(state.sessionId, { sessionUpdate: "current_mode_update", currentModeId: "default" }), 100); + return; + } + if (method === "session/prompt") return prompt(id, params); + if (method === "session/cancel") { state.cancelled = true; state.worker?.kill("SIGTERM"); state.cancel?.(); return; } + if (id !== undefined) write({ jsonrpc: "2.0", id, error: { code: -32601, message: "Method not found" } }); +}