feat(antigravity): verified CLI swarm route, inert until selected

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-23 22:39:42 -06:00
1 parent a8d7c1b379
commit 55267905fc
9 files changed
+834 -8

No files matched your search

@@ -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) ||
@@ -10,7 +10,7 @@ describe("Antigravity swarm activity, in plain language", () => {
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?.title).not.toMatch(/call_|@verifier/);
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" });
@@ -0,0 +1,61 @@
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 { 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("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" });
});
});
@@ -0,0 +1,74 @@
import { userInfo } from "node:os";
import { join } from "node:path";
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<AntigravityCliLaunchOptions, "arguments"> = {},
): Promise<VerifiedAcpxInstallation> {
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<NodeJS.ProcessEnv>,
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 };
}
@@ -0,0 +1,165 @@
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 } 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<AcpxRuntimePortOpenOptions> = {}) {
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<string, unknown> = {}) => 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>) => 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("does not accept a result the task folder does not contain", async () => {
const run = await runTurn("misreport");
expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_RESULT_MISMATCH" } });
expect((run.result as { error: { message: string } }).error.message).toContain("b.txt");
});
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);
});
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" });
});
});
@@ -0,0 +1,488 @@
import type { ChildProcess, ChildProcessWithoutNullStreams } from "node:child_process";
import { existsSync, lstatSync, readdirSync } from "node:fs";
import { isAbsolute, join, relative, sep } from "node:path";
import type { AcpRuntimeEvent, AcpRuntimeTurnResult } from "acpx/runtime";
import { retireAntigravityProcess } from "./antigravity-process.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"]);
const BLOCKED_TEXT = /timed out waiting for user response|permission check failed/i;
export const ANTIGRAVITY_SWARM_PROCESS_LOST = "ACPX_PROVIDER_PROCESS_LOST";
export interface AntigravitySwarmRuntimeDependencies {
helperWaitTimeoutMs?: number;
requestTimeoutMs?: number;
cancelGraceMs?: number;
readbackTimeoutMs?: number;
awaitProviderOwnership?: (child: ChildProcess) => Promise<void>;
}
type Json = Record<string, unknown>;
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<number, { method: string; resolve: (value: Json) => void; reject: (error: Error) => void }>();
#buffer = "";
#queue: Promise<void> = Promise.resolve();
#lost: Error | null = null;
readonly exited: Promise<void>;
onNotification: (method: string, params: Json) => void = () => {};
onRequest: (method: string, params: Json) => Promise<unknown> = 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<void>(resolve => setImmediate(() => { this.#line(line); 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; }
#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<Json> {
if (this.#lost) return Promise.reject(this.#lost);
const id = this.#next++;
return new Promise<Json>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | undefined;
const settle = <T>(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<AcpRuntimeEvent> {
#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<AcpRuntimeEvent> {
for (;;) {
const item = this.#items.shift();
if (item) { yield item; continue; }
if (this.#ended) return;
await new Promise<void>(resolve => { this.#waiter = resolve; });
this.#waiter = null;
}
}
}
type Snapshot = Map<string, string>;
function snapshotWorkspace(root: string): Snapshot {
const files: Snapshot = new Map();
const walk = (directory: string) => {
for (const entry of readdirSync(directory, { withFileTypes: true })) {
if (files.size >= SNAPSHOT_LIMIT) return;
const path = join(directory, entry.name);
if (entry.isDirectory()) { if (!SKIPPED_DIRECTORIES.has(entry.name)) walk(path); continue; }
const stat = lstatSync(path);
files.set(relative(root, path).split(sep).join("/"), `${stat.size}:${stat.mtimeMs}`);
}
};
walk(root);
return files;
}
function changedFiles(before: Snapshot, after: Snapshot): 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();
}
/** Files a helper's brief told it to write inside the task folder. */
function claimedFiles(brief: string, workspace: string): string[] {
const claims: string[] = [];
for (const match of brief.matchAll(/\b(?:write|create|save)s?\s+[`'"]?([A-Za-z0-9_/.][\w./-]*\.[A-Za-z0-9]{1,10})\b/gi)) {
let path = match[1]!;
if (isAbsolute(path)) {
const inside = relative(workspace, path);
if (!inside || inside.startsWith("..") || isAbsolute(inside)) continue;
path = inside;
}
if (path.split("/").includes("..")) continue;
claims.push(path.replace(/^\.\//, ""));
}
return claims;
}
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<AcpxRuntimePort> {
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();
const requestTimeoutMs = dependencies.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const model = options.profile.reportedModelId;
const bridge = options.mcpServers.find((server): server is Extract<typeof server, { url: string }> =>
"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 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<void> | null = null;
const retire = () => retirement ??= retireAntigravityProcess(child, connection.exited);
let updateListener: ((params: Json) => void) | null = null;
let readback: (() => void) | null = null;
connection.onNotification = (method, params) => {
if (method !== "session/update") return;
if (updateListener) updateListener(params);
else guard.observe(params);
readback?.();
};
const waitForReadback = async (check: () => void): Promise<void> => {
const deadline = Date.now() + (dependencies.readbackTimeoutMs ?? READBACK_TIMEOUT_MS);
for (;;) {
try { check(); return; } catch (error) {
if (Date.now() >= deadline || connection.lost) throw error;
await new Promise<void>(resolve => {
const timer = setTimeout(resolve, Math.max(0, deadline - Date.now()));
readback = () => { clearTimeout(timer); resolve(); };
});
readback = null;
}
}
};
let sessionId: string;
let receipt: AntigravitySwarmReceipt;
try {
await (dependencies.awaitProviderOwnership ?? awaitVerifiedAcpxProviderOwnership)(child);
const initialized = await connection.request("initialize", {
protocolVersion: 1,
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
clientInfo: { name: "paperclip-runner", version: "1" },
}, requestTimeoutMs);
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;
}
sessionId = guard.sessionResult(opened);
await connection.request("session/set_mode", { sessionId, modeId: ANTIGRAVITY_CLI_SESSION_MODE }, requestTimeoutMs);
await waitForReadback(() => guard.bindMode());
await connection.request("session/set_model", { sessionId, modelId: model }, requestTimeoutMs);
await waitForReadback(() => guard.bindModel());
guard.assertSwarmCommand();
receipt = guard.receipt();
options.signal?.throwIfAborted();
} catch (error) {
const cleanup = retire();
options.retainFailedAdmissionCleanup(cleanup);
await cleanup.catch(() => undefined);
throw error;
}
const status: Json = { antigravitySwarmReceipt: receipt };
let turns = 0;
let active: { cancel(reason?: string): Promise<void>; result: Promise<AcpRuntimeTurnResult> } | null = null;
let closed = false;
const runTurn = async (input: AcpxRuntimeTurnInput, events: EventQueue, started: () => void): Promise<AcpRuntimeTurnResult> => {
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 = snapshotWorkspace(workspace);
const helpers = new Map<string, string>();
let blocked = 0;
let waitedAfterLastAdd = false;
let transcript = "";
let stop: AntigravitySwarmError | null = null;
let wake: (() => void) | 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 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;
let cancelled = false;
const prompt = async (text: string, timeoutMs: number | null): Promise<string> => {
const response = connection.request("session/prompt", { sessionId, prompt: [{ type: "text", text }] }, null);
started();
let timer: ReturnType<typeof setTimeout> | 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<boolean>(resolve => setTimeout(() => resolve(false), grace))]);
if (!settled) await retire().catch(() => undefined);
return "cancelled";
}
usage = addUsage(usage, outcome.usage);
return typeof outcome.stopReason === "string" ? outcome.stopReason : "end_turn";
} finally {
if (timer) clearTimeout(timer);
wake = null;
}
};
active!.cancel = async () => { cancelled = true; connection.notify("session/cancel", { sessionId }); wake?.(); };
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";
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 { status: "cancelled", stopReason: "cancelled" };
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);
}
const changed = changedFiles(before, snapshotWorkspace(workspace));
events.push(line("files", changed.length ? `Files changed in the task folder: ${changed.slice(0, 20).join(", ")}${changed.length > 20 ? ", …" : ""}` : "No files changed in the task folder"));
const missing = [...helpers].flatMap(([name, brief]) => claimedFiles(brief, workspace)
.filter(path => !existsSync(join(workspace, path))).map(path => `helper ${name} was asked to write ${path}`));
if (missing.length) {
return failed("ANTIGRAVITY_SWARM_RESULT_MISMATCH", `The swarm reported success, but the task folder does not contain what it claims: ${missing.join("; ")}.`);
}
if (usage) {
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 } };
events.push(line("usage", "Token usage is the coordinator's total and includes the helpers; Google does not report it per helper"));
}
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;
}
};
const port: AcpxRuntimePort = {
async identity(): Promise<AcpxRuntimePortIdentity> {
return { mode: ANTIGRAVITY_SWARM_MODE, acpxRecordId: `antigravity-cli-${sessionId}`, backendSessionId: sessionId, agentSessionId: sessionId };
},
async getStatus(): Promise<AcpxModelStatus> {
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<void>(resolve => { markStarted = resolve; });
const turn = { cancel: async (_reason?: string) => {}, result: Promise.resolve() as unknown as Promise<AcpRuntimeTurnResult> };
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<void> {
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;
}
@@ -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<Record<string, ProviderModeAdapter | undefined>> = {
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 {
@@ -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 { antigravitySwarmLaunchEnvironment, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js";
import type {
AcpRuntimeOptions,
@@ -445,15 +447,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 +556,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 +606,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
@@ -70,7 +70,7 @@ async function prompt(id, params) {
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" } }); }
if (scenario === "escape") { await tool("swarm", { action: "add", name: "writer-a", workspace: "branch", brief: "Write a.txt." }); await sleep(5000); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); }
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") {
@@ -78,7 +78,8 @@ async function prompt(id, params) {
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); }
await new Promise(resolve => { state.cancel = resolve; });
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 } });
@@ -144,6 +145,6 @@ async function handle(message) {
return update(state.sessionId, { sessionUpdate: "config_option_update", configOptions: configOptions() });
}
if (method === "session/prompt") return prompt(id, params);
if (method === "session/cancel") { state.worker?.kill("SIGTERM"); state.cancel?.(); return; }
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" } });
}