diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts index 3c06fbfe9da..a0c980ff9c8 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts @@ -29,8 +29,7 @@ export type AntigravitySwarmErrorCode = | "ANTIGRAVITY_SWARM_SIGN_IN_REQUIRED" | "ANTIGRAVITY_SWARM_RECEIPT_MISMATCH" | "ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE" - | "ANTIGRAVITY_SWARM_HELPERS_TIMEOUT" - | "ANTIGRAVITY_SWARM_RESULT_MISMATCH"; + | "ANTIGRAVITY_SWARM_HELPERS_TIMEOUT"; /** `message` is written for the person who asked for the swarm. */ export class AntigravitySwarmError extends Error { diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts index 0ff007d02e8..518bb1acf8f 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts @@ -114,10 +114,48 @@ describe("Antigravity CLI swarm runtime", () => { 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 () => { + 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: "failed", error: { code: "ANTIGRAVITY_SWARM_RESULT_MISMATCH" } }); - expect((run.result as { error: { message: string } }).error.message).toContain("b.txt"); + 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 to resume a saved swarm session and extra tool servers it would have to drop", async () => { + await expect(openAntigravitySwarmRuntime(setup("success", { restoringSession: true }).options)).rejects.toThrow(/fresh swarm/); + 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("refuses a helper on its own workspace copy", async () => { diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts index fb1108c6695..48a32161314 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts @@ -1,6 +1,6 @@ import type { ChildProcess, ChildProcessWithoutNullStreams } from "node:child_process"; -import { existsSync, lstatSync, readdirSync } from "node:fs"; -import { isAbsolute, join, relative, sep } from "node:path"; +import { lstat, readdir } from "node:fs/promises"; +import { join, relative, sep } from "node:path"; import type { AcpRuntimeEvent, AcpRuntimeTurnResult } from "acpx/runtime"; import { retireAntigravityProcess } from "./antigravity-process.js"; import { @@ -39,7 +39,7 @@ 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 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"; @@ -87,7 +87,11 @@ class Connection { 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(() => { this.#line(line); resolve(); }))); + 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(); @@ -97,6 +101,12 @@ class Connection { 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; @@ -167,44 +177,40 @@ class EventQueue implements AsyncIterable { } } -type Snapshot = Map; -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; +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)) walk(path); continue; } - const stat = lstatSync(path); - files.set(relative(root, path).split(sep).join("/"), `${stat.size}:${stat.mtimeMs}`); + 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 */ } } - }; - walk(root); - return files; + } + return { files, complete: true }; } -function changedFiles(before: Snapshot, after: Snapshot): string[] { +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(); } -/** 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; @@ -230,6 +236,16 @@ export async function openAntigravitySwarmRuntime( 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) { + throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "A swarm cannot be resumed after an interruption. Retry starts a fresh swarm in the same task folder."); + } + 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 => @@ -248,15 +264,25 @@ export async function openAntigravitySwarmRuntime( 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; - if (updateListener) updateListener(params); - else guard.observe(params); + 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 => { @@ -297,8 +323,10 @@ export async function openAntigravitySwarmRuntime( await waitForReadback(() => guard.bindMode()); await connection.request("session/set_model", { sessionId, modelId: model }, requestTimeoutMs); await waitForReadback(() => guard.bindModel()); + await connection.drain(); guard.assertSwarmCommand(); receipt = guard.receipt(); + if (protocolFailure) throw protocolFailure; options.signal?.throwIfAborted(); } catch (error) { const cleanup = retire(); @@ -313,12 +341,14 @@ export async function openAntigravitySwarmRuntime( let closed = false; const runTurn = async (input: AcpxRuntimeTurnInput, events: EventQueue, started: () => void): Promise => { + 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 = snapshotWorkspace(workspace); + const listing = new AbortController(); + const before = await snapshotWorkspace(workspace, listing.signal); const helpers = new Map(); let blocked = 0; let waitedAfterLastAdd = false; @@ -397,13 +427,19 @@ export async function openAntigravitySwarmRuntime( 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; } }; - active!.cancel = async () => { cancelled = true; connection.notify("session/cancel", { sessionId }); wake?.(); }; + active!.cancel = async () => { cancelled = true; listing.abort(); connection.notify("session/cancel", { sessionId }); wake?.(); }; const dispatch = input.dispatchJournal?.markReceived() ? input.dispatchJournal : null; try { @@ -423,19 +459,13 @@ export async function openAntigravitySwarmRuntime( 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")); - } + // 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) { @@ -445,6 +475,7 @@ export async function openAntigravitySwarmRuntime( 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")); } }; 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 index 2196cf4bab7..49d4b028d7a 100644 --- a/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs +++ b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs @@ -15,6 +15,9 @@ // 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 +// 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"; @@ -47,7 +50,8 @@ 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: "Wait for writer-a and writer-b, then read a.txt and b.txt and report." }); + 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." : "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 = () => { @@ -142,7 +146,10 @@ async function handle(message) { 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]; - return update(state.sessionId, { sessionUpdate: "config_option_update", configOptions: configOptions() }); + 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; }