fix(antigravity): approve the swarm's own Paperclip tools as the CLI names them, and never auto-retry a swarm that ended without a result

Live run6 (2026-11-24): the coordinator's first call was Paperclip's own
get_task_context. CLI 1.5.15 names a client MCP call mcp_<server>_<tool> with
no _meta (recorded payload now in test-fixtures), but the swarm handler only
approved _meta.mcp.server, so it refused the call; the CLI then cancelled its
whole turn on the denial (cli.log: approved=false, then CancelCascadeInvocation).
The turn ended without a result, became native_session_interrupted with the
Runner's raw continuation text, and recovery started two more billed swarms.

- Approve a permission request only for a tool the run's Paperclip bridge
  admits, by the CLI's own tool name (fails closed otherwise); the fake CLI
  replays the recorded request and hands in through paperclip_finish.
- Report a refused Paperclip tool as such; the CLI echoing Paperclip's own
  denial is not 'a helper blocked outside the task folder'.
- A swarm turn without a hand-in fails as ANTIGRAVITY_SWARM_NO_RESULT with a
  plain reason. The server settles any swarm-route failure code as
  antigravity_swarm_unavailable (terminal, no continuation recovery), and run
  selection never starts another swarm automatically after one; the person's
  Retry still does. A lost CLI process still recovers on its own.
- Record whether the CLI's sign-in matches the connection account in the run
  history every time, with the reason when it cannot tell.
- Scope usage-limit evidence by the executed provider mode, so limits from
  swarms started before scopes existed (and their retries) hold only swarms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-24 18:17:59 -06:00
1 parent 74454a17f3
commit ea2753c3d7
13 files changed
+395 -27

No files matched your search

@@ -145,6 +145,7 @@ const STABLE_ACPX_SIDECAR_CODES = new Set([
"ANTIGRAVITY_SWARM_RECEIPT_MISMATCH",
"ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE",
"ANTIGRAVITY_SWARM_HELPERS_TIMEOUT",
"ANTIGRAVITY_SWARM_NO_RESULT",
"ACPX_CANDIDATE_ADMISSION_INVALID",
// The sidecar refused the request by its own parameter contract.
"ACPX_SIDECAR_REQUEST_INVALID",
@@ -32,7 +32,9 @@ export type AntigravitySwarmErrorCode =
| "ANTIGRAVITY_SWARM_SIGN_IN_REQUIRED"
| "ANTIGRAVITY_SWARM_RECEIPT_MISMATCH"
| "ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE"
| "ANTIGRAVITY_SWARM_HELPERS_TIMEOUT";
| "ANTIGRAVITY_SWARM_HELPERS_TIMEOUT"
/** The swarm turn ended without handing in (no helpers ran, or Paperclip blocked an action). */
| "ANTIGRAVITY_SWARM_NO_RESULT";
const CATEGORY: Record<AntigravitySwarmErrorCode, ProviderFailure["category"]> = {
// Each of these needs the person to change something; a plain Retry meets the same refusal.
@@ -41,6 +43,7 @@ const CATEGORY: Record<AntigravitySwarmErrorCode, ProviderFailure["category"]> =
ANTIGRAVITY_SWARM_RECEIPT_MISMATCH: "unknown",
ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE: "unknown",
ANTIGRAVITY_SWARM_HELPERS_TIMEOUT: "timeout",
ANTIGRAVITY_SWARM_NO_RESULT: "unknown",
};
/**
@@ -4,10 +4,10 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import type { AcpRuntimeEvent } from "acpx/runtime";
import { antigravityCliAccountMatch, openAntigravitySwarmRuntime, type AntigravitySwarmStage } from "./antigravity-swarm-runtime.js";
import { antigravityCliAccountMatch, antigravitySwarmPaperclipTool, openAntigravitySwarmRuntime, type AntigravitySwarmStage } from "./antigravity-swarm-runtime.js";
import { antigravityAccountDigest } from "./antigravity-swarm-route.js";
import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js";
import type { AcpxTerminalSessionFailure } from "./provider-failure.js";
import { acpxTerminalResult, type AcpxTerminalSessionFailure } from "./provider-failure.js";
import { nativeSystemInstructions } from "../../backends/runtime-context.js";
import { buildNativeModelEnvelope, NATIVE_EXECUTION_INPUT_SCHEMA, type NativeExecutionInput } from "../../contracts/native-execution.js";
import { validatePrpStructuredRunResult } from "../../protocol/replay-contract.js";
@@ -39,6 +39,8 @@ function setup(scenario: string, overrides: Partial<AcpxRuntimePortOpenOptions>
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 }],
// The bridge's admitted names for a swarm turn (runtime-host passes toolBridge.admittedToolNames).
paperclipTools: ["get_task_context", "read_document", "paperclip_finish", "paperclip_block"],
retainFailedAdmissionCleanup: () => {},
...overrides,
} as unknown as AcpxRuntimePortOpenOptions;
@@ -201,6 +203,70 @@ 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"]));
});
// Live run6 (2026-11-24): the coordinator's first call was Paperclip's own
// get_task_context; the handler expected `_meta.mcp.server`, which CLI 1.5.15
// never sends, refused it, and the CLI ended the whole turn on the denial.
it("approves the run's own Paperclip tools as the pinned CLI really names them, and hands in", async () => {
const run = await runTurn("context-read");
const answers = run.clientMessages().filter(message => message.permissionAnswer);
expect(answers.map(message => [message.tool, message.permissionAnswer.outcome.optionId])).toEqual([["get_task_context", "allow"], ["paperclip_finish", "allow"]]);
expect(run.result).toMatchObject({ status: "completed" });
expect(run.titles.some(title => /^Blocked:|^A helper was blocked|does not allow/.test(title))).toBe(false);
});
it("refuses a Paperclip tool the swarm does not admit, says so plainly, and fails the turn for the person to retry", async () => {
const run = await runTurn("denied-tool");
const answers = run.clientMessages().filter(message => message.permissionAnswer);
expect(answers.map(message => [message.tool, message.permissionAnswer.outcome.optionId])).toEqual([["create_task", "deny"]]);
expect(run.titles).toContain("Paperclip does not allow create_task during a swarm");
// Its own denial echoed back by the CLI is not a helper change outside the task folder.
expect(run.titles).not.toContain("A helper was blocked from changing something outside the task folder");
expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_NO_RESULT", retryable: false,
message: "The swarm stopped because Paperclip blocked an action it may not take during a swarm, so nothing was handed in. Send /swarm again to retry." } });
});
it("fails a swarm that ended without doing any work, plainly, instead of leaving it to automatic recovery", async () => {
const run = await runTurn("no-work");
expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_NO_RESULT", retryable: false,
message: "The swarm ended without doing any work. Send /swarm again to retry." } });
// What the Runner reports: the plain sentence as the provider failure, with Retry left to the person.
const terminal = acpxTerminalResult(run.result, "antigravity") as { error: { code: string; providerFailure: { message: string; retryability: string } } };
expect(terminal.error.code).toBe("ANTIGRAVITY_SWARM_NO_RESULT");
expect(terminal.error.providerFailure).toMatchObject({ message: "The swarm ended without doing any work. Send /swarm again to retry." });
expect(terminal.error.providerFailure.retryability).not.toBe("requires_action");
});
it("approves only admitted Paperclip tools, by the CLI's own tool name, and nothing else", () => {
const admitted = new Set(["get_task_context", "paperclip_finish"]);
const recorded = JSON.parse(readFileSync(new URL("../../../test-fixtures/antigravity-cli/paperclip-mcp-call.recorded.json", import.meta.url), "utf8"));
expect(antigravitySwarmPaperclipTool(recorded.requestPermission.params.toolCall, admitted)).toBe("get_task_context");
expect(antigravitySwarmPaperclipTool({ name: "mcp_paperclip_paperclip_finish" }, admitted)).toBe("paperclip_finish");
for (const toolCall of [
{ name: "mcp_paperclip_create_task" }, { name: "mcp_other_get_task_context" }, { name: "get_task_context" },
{ name: "run_command", title: "Run mcp_paperclip_get_task_context" }, { title: "Run mcp_paperclip_get_task_context" },
{ _meta: { mcp: { server: "paperclip", tool: "get_task_context" } } }, { name: "mcp_paperclip_" },
]) expect(antigravitySwarmPaperclipTool(toolCall, admitted)).toBeNull();
});
it("records whether the CLI's sign-in is the connection account, and why it could not tell", async () => {
const unknown = await runTurn("success");
expect(unknown.titles).toContain("Paperclip could not confirm which Google account this swarm runs on: this agent's Google connection names no account.");
expect(unknown.status.antigravitySwarmReceipt).toMatchObject({ cliAccountMatchesConnection: "unknown", cliAccountUnknownReason: "no_connection_account" });
const context = setup("success", { antigravitySwarm: { channel: "provider_default", accountDigest: antigravityAccountDigest("owner@example.test") } });
const runtime = await openAntigravitySwarmRuntime(context.options);
expect((await runtime.getStatus()).antigravitySwarmReceipt).toMatchObject({ cliAccountMatchesConnection: "unknown", cliAccountUnknownReason: "cli_sign_in_not_found" });
await runtime.close({ reason: "done" });
const signedIn = setup("success", { antigravitySwarm: { channel: "provider_default", accountDigest: antigravityAccountDigest("owner@example.test") } });
writeFileSync(join(signedIn.geminiDirectory, "cli.log"), "I1124 server_oauth.go:221] applyAuthResult: email=Owner@example.test, authMethod=consumer, quotaProject=\n");
const matched = await openAntigravitySwarmRuntime(signedIn.options);
const turn = matched.startTurn({ text: envelope("two helpers write a.txt and b.txt"), requestId: "run-1:turn-1" });
const titles: string[] = [];
for await (const event of turn.events) if (event.type === "tool_call" && event.title) titles.push(event.title);
await turn.result;
await matched.close({ reason: "done" });
expect(titles).toContain("This swarm runs on the Google account of this agent's Google connection.");
});
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" });
@@ -15,6 +15,8 @@ import {
import { GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL, GENERATED_ANTIGRAVITY_SWARM_ENVELOPE_SCHEMA, GENERATED_ANTIGRAVITY_SWARM_REQUEST_FIELD, GENERATED_ANTIGRAVITY_SWARM_REQUEST_MAX_CHARS } from "./generated-sidecar-contract.js";
import { antigravitySwarmEvent } from "./antigravity-swarm-presentation.js";
import { awaitVerifiedAcpxProviderOwnership } from "./installation-integrity.js";
import { canonicalRunnerToolName } from "../runner-tool-bridge.js";
import { PRP_BLOCK_TOOL_NAME, PRP_COMPLETION_TOOL_NAME } from "../../contracts/completion-result.js";
import type { AcpxModelStatus } from "./model-verification.js";
import type { AcpxRuntimePort, AcpxRuntimePortIdentity, AcpxRuntimePortOpenOptions, AcpxRuntimeTurn, AcpxRuntimeTurnInput } from "./runtime-host.js";
@@ -45,7 +47,12 @@ 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;
// The CLI's sandbox refusing a helper's change outside the task folder. A denial
// Paperclip itself answered (`permission check failed for mcp …`) is not one.
const BLOCKED_TEXT = /timed out waiting for user response|permission check failed(?! for mcp)/i;
/** How the pinned CLI (1.5.15) names a call to a client MCP server: `mcp_<server>_<tool>`, with no `_meta`. */
const PAPERCLIP_TOOL_PREFIX = `mcp_${ANTIGRAVITY_SWARM_MCP_SERVER}_`;
const HAND_IN_TOOLS: ReadonlySet<string> = new Set([PRP_COMPLETION_TOOL_NAME, PRP_BLOCK_TOOL_NAME]);
export const ANTIGRAVITY_SWARM_PROCESS_LOST = "ACPX_PROVIDER_PROCESS_LOST";
export type AntigravitySwarmStage = "spawned" | "initialized" | "session" | "mode" | "model" | "snapshot" | "helpers";
@@ -246,6 +253,31 @@ export function antigravitySwarmRequestText(turnText: string): string | null {
return typeof request === "string" && request.trim() && request.length <= GENERATED_ANTIGRAVITY_SWARM_REQUEST_MAX_CHARS ? request : null;
}
/**
* The Paperclip tool a CLI permission request or tool update names, when it is
* one the run's Paperclip bridge admits (its served catalog for a swarm turn plus
* the reserved finish and block tools). The swarm session has no other MCP
* server (admission refuses one), so the `mcp_paperclip_` prefix can only mean
* Paperclip's bridge; anything else, or a tool outside the admitted set, is null.
*/
export function antigravitySwarmPaperclipTool(toolCall: unknown, admitted: ReadonlySet<string>): string | null {
const name = record(toolCall).name;
if (typeof name !== "string" || !name.startsWith(PAPERCLIP_TOOL_PREFIX)) return null;
const tool = canonicalRunnerToolName(name.slice(PAPERCLIP_TOOL_PREFIX.length));
return tool && admitted.has(tool) ? tool : null;
}
export type AntigravityCliAccountReason = "no_connection_account" | "cli_sign_in_not_found";
/** One line for the run's history: whether the CLI's own Google sign-in is the agent's connection account. */
function accountLine(match: AntigravityCliAccountMatch, reason: AntigravityCliAccountReason | null): string {
if (match === "matches") return "This swarm runs on the Google account of this agent's Google connection.";
if (match === "does_not_match") return "This swarm runs on the Google account signed in to this computer, which is different from this agent's Google connection.";
return reason === "no_connection_account"
? "Paperclip could not confirm which Google account this swarm runs on: this agent's Google connection names no account."
: "Paperclip could not confirm which Google account this swarm runs on: the Antigravity CLI did not record its sign-in.";
}
function failed(code: string, message: string): AcpRuntimeTurnResult {
return { status: "failed", error: { code, message, retryable: false } };
}
@@ -353,6 +385,8 @@ export async function openAntigravitySwarmRuntime(
let sessionId: string;
let receipt: AntigravitySwarmReceipt;
let cliAccount: AntigravityCliAccountMatch = "unknown";
const accountDigest = options.antigravitySwarm?.accountDigest ?? null;
const paperclipTools: ReadonlySet<string> = new Set(options.paperclipTools ?? []);
// 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 });
@@ -396,7 +430,7 @@ export async function openAntigravitySwarmRuntime(
guard.assertSwarmCommand();
receipt = guard.receipt();
cliAccount = options.antigravityStateDirectory
? await antigravityCliAccountMatch(antigravitySwarmLogFile(options.antigravityStateDirectory), options.antigravitySwarm?.accountDigest ?? null)
? await antigravityCliAccountMatch(antigravitySwarmLogFile(options.antigravityStateDirectory), accountDigest)
: "unknown";
if (protocolFailure) throw protocolFailure;
options.signal?.throwIfAborted();
@@ -410,7 +444,10 @@ export async function openAntigravitySwarmRuntime(
options.signal?.removeEventListener("abort", abortAdmission);
// Diagnostics only: the channel and whether the CLI's own sign-in is the agent's connection account (never the account itself).
const status: Json = { antigravitySwarmReceipt: { ...receipt, channel, cliAccountMatchesConnection: cliAccount } };
const accountReason: AntigravityCliAccountReason | null = cliAccount !== "unknown" ? null
: accountDigest ? "cli_sign_in_not_found" : "no_connection_account";
const status: Json = { antigravitySwarmReceipt: { ...receipt, channel, cliAccountMatchesConnection: cliAccount,
...(accountReason ? { cliAccountUnknownReason: accountReason } : {}) } };
let turns = 0;
let active: { cancel(reason?: string): Promise<void>; result: Promise<AcpRuntimeTurnResult> } | null = null;
let closed = false;
@@ -443,9 +480,11 @@ export async function openAntigravitySwarmRuntime(
let stop: AntigravitySwarmError | null = null;
const halt = (error: AntigravitySwarmError) => { stop ??= error; connection.notify("session/cancel", { sessionId }); wake?.(); };
events.push(line("setup", `Swarm started in the task folder with ${receipt.modelName} on ${antigravitySwarmChannelLabel(channel)} (Antigravity CLI ${receipt.agentVersion}). Helper changes inside the task folder are approved automatically; anything else is blocked.`));
if (cliAccount === "does_not_match") {
events.push(line("account", "This swarm runs on the Google account signed in to this computer, which is different from this agent's Google connection."));
}
// Always recorded in the run's history, including when it cannot be told.
events.push(line("account", accountLine(cliAccount, accountReason)));
// Calls Paperclip's own handler refused (each already reported once), and whether the swarm handed in.
const deniedCalls = new Set<string>();
let handedIn = false;
updateListener = params => {
try { guard.observe(params); } catch (error) {
@@ -466,6 +505,10 @@ export async function openAntigravitySwarmRuntime(
`Swarm stopped: it tried to change ${outside}, which is outside the task folder.`));
return;
}
if (update.sessionUpdate === "tool_call_update" && update.status === "completed") {
const tool = antigravitySwarmPaperclipTool(update, paperclipTools);
if (tool && HAND_IN_TOOLS.has(tool)) handedIn = true;
}
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 : "");
@@ -477,7 +520,7 @@ export async function openAntigravitySwarmRuntime(
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)) {
if (BLOCKED_TEXT.test(text) && !(typeof update.toolCallId === "string" && deniedCalls.has(update.toolCallId))) {
blocked += 1;
events.push(line(`blocked-${blocked}`, "A helper was blocked from changing something outside the task folder"));
}
@@ -487,16 +530,20 @@ export async function openAntigravitySwarmRuntime(
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;
// Only the run's own Paperclip tools are approved here (the CLI asks before
// every client MCP call); auto mode already allows the task folder, so
// anything else that asks is outside it. The CLI ends the whole turn on a
// denial, so a refused call is reported once and ends the swarm plainly.
const paperclip = antigravitySwarmPaperclipTool(toolCall, paperclipTools) !== null;
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)}`));
if (typeof toolCall.toolCallId === "string") deniedCalls.add(toolCall.toolCallId);
const requested = typeof toolCall.name === "string" && toolCall.name.startsWith(PAPERCLIP_TOOL_PREFIX)
? `Paperclip does not allow ${toolCall.name.slice(PAPERCLIP_TOOL_PREFIX.length).slice(0, 80)} during a swarm`
: `Blocked: ${(typeof toolCall.title === "string" ? toolCall.title.split(workspace).join(".") : "an action outside the task folder").slice(0, 160)}`;
events.push(line(`blocked-${blocked}`, requested));
}
return choice ? { outcome: { outcome: "selected", optionId: choice.optionId } } : { outcome: { outcome: "cancelled" } };
};
@@ -565,6 +612,16 @@ export async function openAntigravitySwarmRuntime(
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"));
// A swarm that ended without handing in is a typed swarm failure the person
// retries, never an interruption Paperclip resumes or retries on its own
// (each attempt is a full, billed swarm).
if (!handedIn) {
return failed("ANTIGRAVITY_SWARM_NO_RESULT" satisfies AntigravitySwarmError["code"], deniedCalls.size > 0
? "The swarm stopped because Paperclip blocked an action it may not take during a swarm, so nothing was handed in. Send /swarm again to retry."
: helpers.size === 0
? "The swarm ended without doing any work. Send /swarm again to retry."
: "The swarm finished without handing in its result. Files its helpers wrote stay in the task folder. Send /swarm again to retry.");
}
return { status: "completed", stopReason: "end_turn" };
} catch (error) {
if (connection.lost instanceof ProcessLostError || error instanceof ProcessLostError) {
@@ -17,6 +17,11 @@
// 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
// context-read the coordinator first reads Paperclip's get_task_context (the live
// 2026-11-24 run6 opening), then runs the swarm and hands in
// no-work the coordinator ends its turn without helpers and without handing in
// denied-tool the coordinator calls a Paperclip tool the swarm does not admit
// (create_task); the CLI ends the whole turn on the denial, as live
// 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
@@ -30,7 +35,7 @@
// outside, and the real ~/.gemini; never written, the swarm must stop
// FAKE_AGY_LOG (optional) appends every client message, one JSON per line.
import { spawn } from "node:child_process";
import { appendFileSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs";
import { appendFileSync, mkdirSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
@@ -57,6 +62,32 @@ const tool = async (name, args, status = "completed") => {
await sleep(2);
update(state.sessionId, { sessionUpdate: "tool_call_update", toolCallId, name, args, status, kind: "other", title: `Run ${name}`, rawInput: args });
};
// A call to a client MCP server exactly as the pinned CLI (1.5.15) sends it, recorded
// live (paperclip-mcp-call.recorded.json): name `mcp_<server>_<tool>`, kind other,
// no _meta, and a string request id. The CLI asks before every such call in auto mode,
// and a denial ends its whole turn (live run6: `approved=false`, then the cascade is cancelled).
const RECORDED = JSON.parse(readFileSync(new URL("./paperclip-mcp-call.recorded.json", import.meta.url), "utf8"));
const permissionAnswers = new Map();
let permissionId = 0;
const paperclipCall = async tool => {
const name = `mcp_paperclip_${tool}`;
const toolCallId = `call_${++call}`;
const shape = update => ({ ...update, toolCallId, name, title: `Run ${name}` });
for (const recorded of RECORDED.toolCallUpdates) update(state.sessionId, shape(recorded.params.update));
const id = String(++permissionId);
const answered = new Promise(resolve => permissionAnswers.set(id, resolve));
write({ ...RECORDED.requestPermission, id, params: { ...RECORDED.requestPermission.params, sessionId: state.sessionId, toolCall: shape(RECORDED.requestPermission.params.toolCall) } });
const answer = await answered;
log({ permissionAnswer: answer.result, tool });
if (answer.result?.outcome?.optionId === "allow") {
for (const recorded of RECORDED.afterAllow) update(state.sessionId, shape(recorded.params.update));
return true;
}
update(state.sessionId, shape({ sessionUpdate: "tool_call_update", args: {}, status: "failed", kind: "other", rawInput: {},
rawOutput: `permission check failed for mcp "paperclip/${tool}": user denied permission for mcp(paperclip/${tool})` }));
return false;
};
const handIn = () => paperclipCall("paperclip_finish");
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 () => {
@@ -106,7 +137,7 @@ async function prompt(id, params) {
// 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();
if (scenario === "live-helpers") { writeFiles(); await handIn(); }
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 } } });
}
@@ -131,6 +162,9 @@ async function prompt(id, params) {
if (!state.cancelled) await new Promise(resolve => { state.cancel = resolve; });
return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } });
}
if (scenario === "no-work") { say("I looked at the request; there is nothing to do."); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn", usage } }); }
if (scenario === "denied-tool") { await paperclipCall("create_task"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn", usage } }); }
if (scenario === "context-read" && !await paperclipCall("get_task_context")) return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn", usage } });
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();
if (scenario.startsWith("plan")) {
@@ -164,6 +198,7 @@ async function prompt(id, params) {
}
await tool("read_board", { since: 5 });
await tool("post_message", { text: "[done] Verification verified and tasks finished successfully." });
await handIn();
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 } });
}
@@ -183,7 +218,11 @@ 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 === undefined) {
if (id === 77) { log({ permissionAnswer: message.result }); state.permission?.(); }
permissionAnswers.get(id)?.(message);
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 } } } },
@@ -0,0 +1,135 @@
{
"recorded": "agy acp 1.5.15 (pinned darwin-arm64), 2026-11-24, auto mode, gemini-3.8-flash-low; a session whose only MCP server is an http server named paperclip exposing get_task_context. Inbound messages for one call, verbatim except session ids.",
"toolCallUpdates": [
{
"jsonrpc": "2.0",
"method": "session/update",
"params": {
"sessionId": "s-1",
"update": {
"sessionUpdate": "tool_call",
"toolCallId": "call_8421575239314794650",
"name": "mcp_paperclip_get_task_context",
"args": {
"toolSummary": "Task context retrieval"
},
"status": "in_progress",
"kind": "other",
"title": "Run mcp_paperclip_get_task_context",
"rawInput": {
"toolSummary": "Task context retrieval"
}
}
}
},
{
"jsonrpc": "2.0",
"method": "session/update",
"params": {
"sessionId": "s-1",
"update": {
"sessionUpdate": "tool_call_update",
"toolCallId": "call_8421575239314794650",
"name": "mcp_paperclip_get_task_context",
"args": {
"toolSummary": "Task context retrieval"
},
"status": "pending",
"kind": "other",
"title": "Run mcp_paperclip_get_task_context",
"rawInput": {
"toolSummary": "Task context retrieval"
}
}
}
}
],
"requestPermission": {
"jsonrpc": "2.0",
"method": "session/request_permission",
"params": {
"sessionId": "s-1",
"toolCall": {
"sessionUpdate": "tool_call",
"toolCallId": "call_8421575239314794650",
"name": "mcp_paperclip_get_task_context",
"args": {
"toolSummary": "Task context retrieval"
},
"status": "pending",
"kind": "other",
"title": "Run mcp_paperclip_get_task_context",
"rawInput": {
"toolSummary": "Task context retrieval"
}
},
"options": [
{
"optionId": "allow",
"name": "Allow",
"kind": "allow_once"
},
{
"optionId": "deny",
"name": "Deny",
"kind": "reject_once"
}
]
},
"id": "1"
},
"afterAllow": [
{
"jsonrpc": "2.0",
"method": "session/update",
"params": {
"sessionId": "s-1",
"update": {
"sessionUpdate": "tool_call_update",
"toolCallId": "call_8421575239314794650",
"name": "mcp_paperclip_get_task_context",
"args": {
"toolSummary": "Task context retrieval"
},
"status": "in_progress",
"kind": "other",
"title": "Run mcp_paperclip_get_task_context",
"rawInput": {
"toolSummary": "Task context retrieval"
}
}
}
},
{
"jsonrpc": "2.0",
"method": "session/update",
"params": {
"sessionId": "s-1",
"update": {
"sessionUpdate": "tool_call_update",
"toolCallId": "call_8421575239314794650",
"name": "mcp_paperclip_get_task_context",
"args": {
"toolSummary": "Task context retrieval"
},
"status": "completed",
"kind": "other",
"title": "Run mcp_paperclip_get_task_context",
"rawInput": {
"toolSummary": "Task context retrieval"
}
}
}
}
],
"clientAnswer": {
"jsonrpc": "2.0",
"id": "1",
"result": {
"outcome": {
"outcome": "selected",
"optionId": "allow"
}
}
}
}
@@ -3,6 +3,7 @@ import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { agents, authUsers, companies, companyMemberships, createDb, heartbeatRuns, issues } from "@paperclipai/db";
import { createProviderLimitWait } from "../services/heartbeat/provider-limit-wait.js";
import { runProviderQuotaScope } from "../services/native-runtime/native-startup-retry.js";
import { recoveryPostgresSupport, startRecoveryPostgres } from "./helpers/recovery-postgres.js";
const describePostgres = recoveryPostgresSupport.supported ? describe : describe.skip;
@@ -98,4 +99,15 @@ describePostgres("quota-scoped provider limit holds for /swarm", () => {
expect(deferred).toBe(true);
expect((deps.setRunStatusIfRunning.mock.calls[0] as unknown as [string, string, { error: string }])[2].error).toMatch(/^This agent's provider usage limit/);
});
// Live: a Retry of a swarm started before scopes existed recorded unscoped
// evidence, which then held this agent's ordinary work for an hour.
it("scopes a swarm's limit by the route it executed, even when its context lacks the scope", async () => {
const executedSwarm = { nativeExecutionInput: { provider: { kind: "acpx", agent: "antigravity", model: "gemini-3.8-flash-low", mode: "swarm" } } };
expect(runProviderQuotaScope({ issueId: "issue" }, executedSwarm)).toBe("antigravity_cli");
expect(runProviderQuotaScope({ issueId: "issue" }, { nativeExecutionInput: { provider: { kind: "acpx", agent: "antigravity" } } })).toBeNull();
const oldSwarm = { ...swarmLimited(5), contextSnapshot: { antigravitySwarmCommentId: randomUUID() }, runnerProfileJson: executedSwarm };
expect((await defer(await seed([oldSwarm]), null)).deferred).toBe(false);
expect((await defer(await seed([oldSwarm]), "antigravity_cli")).deferred).toBe(true);
});
});
@@ -171,6 +171,20 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", (
await expect(automatic(f, (await insertRun(f, {})).id)).rejects.toMatchObject({ code: "antigravity_swarm_unavailable", message: expect.stringMatching(/three attempts/) });
});
it("never starts another swarm automatically after the route failed one; the person's Retry starts it", async () => {
const f = await seed();
const first = await insertRun(f, {});
expect(await automatic(f, first.id)).toMatchObject({ request: expect.any(String) });
await db.update(heartbeatRuns).set({ status: "failed", errorCode: "antigravity_swarm_unavailable" }).where(eq(heartbeatRuns.id, first.id));
// Recovery and continuations (which copy the request marker) do not run it again.
await expect(automatic(f, (await insertRun(f, {})).id, "issue_recovery_action_restored")).rejects
.toMatchObject({ code: "antigravity_swarm_unavailable", message: expect.stringMatching(/did not finish/) });
const retryContext = { issueId: f.issue.id, triggeredBy: "board", actorId: USER, responsibleUserId: USER, wakeReason: "task_retry" };
const retry = await insertRun(f, {});
await userRetry(f, {}, { runId: retry.id });
expect(await resolve(f, { runId: retry.id, context: retryContext })).toMatchObject({ request: expect.any(String) });
});
it("records the CLI's quota scope on the swarm it selects, and names it before dispatch while the request is unfulfilled", async () => {
const f = await seed();
const scope = (runId: string, context: Record<string, unknown> = { issueId: f.issue.id }) =>
@@ -1,5 +1,7 @@
import { describe, expect, it } from "vitest";
import { classifyContinuationFailure } from "./recovery/service.js";
import { NativeProviderTerminalFailure } from "../vendor/paperclip-runner/index.js";
import { nativeSessionFailureDisposition, nativeSessionFailureSourceCode, nativeStartupFailureMessage } from "./native-runtime/native-session-executor.js";
import { antigravitySwarmRefusal, isAntigravitySwarmExecution, requestedAntigravitySwarmCommentId } from "./antigravity-swarm.js";
const antigravity = { adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low" } };
@@ -33,4 +35,19 @@ describe("trusted /swarm for Google Antigravity", () => {
expect(classifyContinuationFailure({ errorCode: "antigravity_swarm_unavailable", resultJson: null } as never))
.toMatchObject({ kind: "non_retryable", maxAttempts: 0 });
});
// Live run6: a swarm turn that ended with no result became "native_session_interrupted",
// showed the Runner's raw continuation text, and recovery started two more billed swarms.
it("settles a swarm turn the route failed by its own code as a plain, person-retried failure", () => {
const message = "The swarm ended without doing any work. Send /swarm again to retry.";
const providerFailure = { schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "turn", category: "unknown", retryability: "unknown", message } as const;
const failure = new NativeProviderTerminalFailure("ANTIGRAVITY_SWARM_NO_RESULT", false, message, providerFailure as never);
const code = nativeSessionFailureSourceCode(failure);
expect(code).toBe("antigravity_swarm_unavailable");
expect(nativeSessionFailureDisposition(1, new Date(), code)).toMatchObject({ phase: "terminal_failure", failureCode: "antigravity_swarm_unavailable", nextAttemptAt: null });
expect(nativeStartupFailureMessage(code, `native_session_recovery_failed: ${message}`, providerFailure)).toBe(message);
expect(classifyContinuationFailure({ errorCode: code, resultJson: null } as never)).toMatchObject({ kind: "non_retryable", maxAttempts: 0 });
// A lost CLI process is an interruption and still recovers on its own.
expect(nativeSessionFailureSourceCode(new NativeProviderTerminalFailure("ACPX_PROVIDER_PROCESS_LOST", true, "lost"))).not.toBe("antigravity_swarm_unavailable");
});
});
+6 -1
View File
@@ -247,7 +247,7 @@ async function selectSwarm(tx: Db, input: Parameters<typeof resolveAntigravitySw
commentId: string; request: string; replacedCommentIds: string[];
}): Promise<SwarmDecision> {
const { commentId, request } = input;
const attempts = await tx.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, createdAt: heartbeatRuns.createdAt,
const attempts = await tx.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode, createdAt: heartbeatRuns.createdAt,
finishedAt: heartbeatRuns.finishedAt, updatedAt: heartbeatRuns.updatedAt }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, input.companyId), ne(heartbeatRuns.id, input.runId),
sql`${heartbeatRuns.contextSnapshot}->>'antigravitySwarmCommentId' = ${commentId}`,
@@ -272,6 +272,11 @@ async function selectSwarm(tx: Db, input: Parameters<typeof resolveAntigravitySw
if (!manual && attempts.some(run => run.status === "cancelled")) {
return { refusal: "The swarm for this request was stopped. Send /swarm again, or use Retry, to start it again." };
}
// A swarm the route itself failed (no result, helpers timed out, a blocked
// action) waits for the person: only interruptions are attempted again automatically.
if (!manual && attempts.some(run => run.status === "failed" && run.errorCode === ANTIGRAVITY_SWARM_UNAVAILABLE)) {
return { refusal: "The swarm for this request did not finish. Send /swarm again, or use Retry, to start it again." };
}
if (!manual && attempts.filter(run => ["failed", "timed_out"].includes(run.status)).length >= ANTIGRAVITY_SWARM_AUTOMATIC_ATTEMPTS) {
return { refusal: "The swarm did not finish after three attempts, so Paperclip stopped retrying it. Send /swarm again to start a new one." };
}
@@ -87,7 +87,7 @@ export function createProviderLimitWait(db: Db, deps: ProviderLimitWaitDependenc
companyId: run.companyId, agentId: run.agentId, runId: run.id, now,
}).then(async limited => {
if (!limited) return null;
quotaScope = deps.providerQuotaScope ? await deps.providerQuotaScope(agent, run) : runProviderQuotaScope(run.contextSnapshot);
quotaScope = deps.providerQuotaScope ? await deps.providerQuotaScope(agent, run) : runProviderQuotaScope(run.contextSnapshot, run.runnerProfileJson);
const ssh = options.sshAuthentication !== undefined ? options.sshAuthentication
: deps.sshAuthentication ? await deps.sshAuthentication(agent, run) : null;
// Dispatch checks again once the environment, and so the account, is known.
@@ -9327,6 +9327,11 @@ function classifyNativeSessionFailure(
if (error instanceof NativeProviderSideEffectPendingError) return NATIVE_PROVIDER_SIDE_EFFECT_PENDING;
if (error instanceof NativeProviderTerminalFailure) {
if (error.providerCode === "approval_required") return "native_provider_approval_required";
// A /swarm turn the swarm route failed by its own closed code (no result,
// helpers timed out, a blocked escape): each automatic attempt is a full,
// billed swarm, so the person decides whether to retry it. Interruptions
// (a lost CLI process) keep their own code and still recover on their own.
if (/^ANTIGRAVITY_SWARM_[A-Z_]+$/.test(error.providerCode)) return ANTIGRAVITY_SWARM_UNAVAILABLE;
// Failed terminals retain their security meaning across the provider facade.
// A stopped process is insufficient evidence to recover an integrity breach.
if (
@@ -5,6 +5,7 @@ import { readProviderFailure, type ProviderFailure } from "@paperclipai/shared";
import { logger } from "../../middleware/logger.js";
import { infrastructureRetryDelayMs, PROVIDER_LIMIT_DEFAULT_COOLDOWN_MS } from "../system-recovery-state.js";
import { isProviderQuotaActionRequired, parseProviderQuotaClockReset } from "../provider-quota-reset.js";
import { ANTIGRAVITY_CLI_QUOTA_SCOPE } from "../antigravity-swarm-refusal.js";
/** Categories that report an exhausted account or request allowance. */
const PROVIDER_LIMIT_CATEGORIES = ["rate_limit", "quota_exhausted"];
@@ -54,15 +55,28 @@ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
export const PROVIDER_QUOTA_SCOPE_CONTEXT_KEY = "providerQuotaScope";
const QUOTA_SCOPE_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
/** The quota scope a run recorded; null is the credential's default quota. */
export function runProviderQuotaScope(contextSnapshot: unknown): string | null {
/**
* The quota scope a run drew on; null is the credential's default quota. A run
* that executed the Antigravity swarm route draws on the CLI's own pool even
* when its context lacks the field (runs started before scopes existed, and
* their retries), so the executed provider mode in its runner profile decides.
*/
export function runProviderQuotaScope(contextSnapshot: unknown, runnerProfileJson?: unknown): string | null {
const value = contextSnapshot && typeof contextSnapshot === "object"
? (contextSnapshot as Record<string, unknown>)[PROVIDER_QUOTA_SCOPE_CONTEXT_KEY] : undefined;
return typeof value === "string" && QUOTA_SCOPE_PATTERN.test(value) ? value : null;
if (typeof value === "string" && QUOTA_SCOPE_PATTERN.test(value)) return value;
const profile = runnerProfileJson && typeof runnerProfileJson === "object" ? runnerProfileJson as Record<string, unknown> : {};
const input = profile.nativeExecutionInput && typeof profile.nativeExecutionInput === "object" ? profile.nativeExecutionInput as Record<string, unknown> : {};
const provider = input.provider && typeof input.provider === "object" ? input.provider as Record<string, unknown> : {};
return provider.kind === "acpx" && provider.agent === "antigravity" && provider.mode === "swarm" ? ANTIGRAVITY_CLI_QUOTA_SCOPE : null;
}
function quotaScopeEvidenceFilter(scope: string | null) {
const recorded = sql`${heartbeatRuns.contextSnapshot} ->> ${PROVIDER_QUOTA_SCOPE_CONTEXT_KEY}`;
// The same derivation as runProviderQuotaScope, in SQL, so old swarm evidence holds only swarms.
const executed = sql`${heartbeatRuns.runnerProfileJson} -> 'nativeExecutionInput' -> 'provider'`;
const recorded = sql`coalesce(${heartbeatRuns.contextSnapshot} ->> ${PROVIDER_QUOTA_SCOPE_CONTEXT_KEY},
case when ${executed} ->> 'kind' = 'acpx' and ${executed} ->> 'agent' = 'antigravity' and ${executed} ->> 'mode' = 'swarm'
then ${ANTIGRAVITY_CLI_QUOTA_SCOPE} end)`;
return scope === null ? sql`${recorded} is null` : sql`${recorded} = ${scope}`;
}
@@ -233,7 +247,7 @@ export async function planNativeStartupRetry(input: {
// Limit evidence only refines the schedule. A failed read must not stop the
// failure from settling, so the retry falls back to plain backoff.
const providerCooldownAt = await input.db
.select({ contextSnapshot: heartbeatRuns.contextSnapshot }).from(heartbeatRuns)
.select({ contextSnapshot: heartbeatRuns.contextSnapshot, runnerProfileJson: heartbeatRuns.runnerProfileJson }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.companyId, input.binding.companyId), eq(heartbeatRuns.id, input.binding.runId)))
.then(([run]) => agentProviderLimitCooldown(input.db, {
companyId: input.binding.companyId,
@@ -242,7 +256,7 @@ export async function planNativeStartupRetry(input: {
failure: input.failure,
// The failure was reported on the account this run started with.
credential: runProviderLimitCredential(run?.contextSnapshot),
quotaScope: runProviderQuotaScope(run?.contextSnapshot),
quotaScope: runProviderQuotaScope(run?.contextSnapshot, run?.runnerProfileJson),
now: input.now,
})).then((cooldown) => cooldown?.resetAt ?? null, (error: unknown) => {
logger.warn({ err: error, runId: input.binding.runId }, "native provider limit evidence unavailable");