mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
wip(antigravity): swarm guard, presentation and fake CLI fixture
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b6f1b7b4af
commit
67fde37fe9
5 files changed
+619
No files matched your search
@@ -0,0 +1,125 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
antigravitySwarmWorkspaceEscape, classifyAntigravityRefusalText, createAntigravitySwarmGuard,
|
||||
} from "./antigravity-swarm-guard.js";
|
||||
|
||||
const WORKSPACE = "/work/task";
|
||||
const INSTRUCTIONS = "Paperclip instructions";
|
||||
const SESSION = "s-1";
|
||||
|
||||
function initializeResult(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { _meta: { antigravity: { systemPrompt: { append: true } } } },
|
||||
agentInfo: { name: "Antigravity ACP Server", version: "1.5.15" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function sessionResult(modes = ["default", "accept-edits", "auto", "plan"]) {
|
||||
return {
|
||||
sessionId: SESSION,
|
||||
modes: { currentModeId: "default", availableModes: modes.map(id => ({ id })) },
|
||||
models: { currentModelId: "gemini-4-argon-medium", availableModels: [{ modelId: "gemini-4-argon-medium" }, { modelId: "gemini-3.8-flash-low" }] },
|
||||
configOptions: [
|
||||
{ id: "model", currentValue: "gemini-4-argon" }, { id: "thought_level", currentValue: "medium" }, { id: "mode", currentValue: "default" },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const sessionRequest = (overrides: Record<string, unknown> = {}) => ({
|
||||
cwd: WORKSPACE,
|
||||
mcpServers: [{ type: "http", name: "paperclip", url: "http://127.0.0.1:1/mcp", headers: [] }],
|
||||
_meta: { antigravity: { systemPrompt: { append: INSTRUCTIONS } } },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const config = (model: string, level: string, mode = "auto") => ({
|
||||
sessionId: SESSION,
|
||||
update: { sessionUpdate: "config_option_update", configOptions: [
|
||||
{ id: "model", currentValue: model }, { id: "thought_level", currentValue: level }, { id: "mode", currentValue: mode },
|
||||
] },
|
||||
});
|
||||
|
||||
function admitted() {
|
||||
const guard = createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE });
|
||||
guard.initialize(initializeResult());
|
||||
guard.sessionRequest(sessionRequest());
|
||||
guard.sessionResult(sessionResult());
|
||||
guard.observe({ sessionId: SESSION, update: { sessionUpdate: "current_mode_update", currentModeId: "auto" } });
|
||||
guard.bindMode();
|
||||
guard.observe(config("gemini-3.8-flash", "low"));
|
||||
guard.bindModel();
|
||||
return guard;
|
||||
}
|
||||
|
||||
describe("Antigravity CLI swarm guard (replaces the registry admission receipt)", () => {
|
||||
it("records a receipt when identity, workspace, tools, instructions, auto mode and model all read back", () => {
|
||||
expect(admitted().receipt()).toMatchObject({
|
||||
agentName: "Antigravity ACP Server", agentVersion: "1.5.15", sessionId: SESSION, workspace: WORKSPACE,
|
||||
mode: "auto", model: "gemini-3.8-flash-low", modelFamily: "gemini-3.8-flash", thoughtLevel: "low", mcpServers: ["paperclip"],
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses a CLI that is not the pinned identity or cannot take Paperclip's instructions", () => {
|
||||
const guard = () => createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE });
|
||||
expect(() => guard().initialize(initializeResult({ agentInfo: { name: "Antigravity ACP Server", version: "1.5.16" } })))
|
||||
.toThrow(expect.objectContaining({ code: "ANTIGRAVITY_SWARM_RECEIPT_MISMATCH" }));
|
||||
expect(() => guard().initialize(initializeResult({ agentInfo: { name: "antigravity-acp", version: "1.5.15" } }))).toThrow(/pinned version/);
|
||||
expect(() => guard().initialize(initializeResult({ agentCapabilities: {} }))).toThrow(/instructions/);
|
||||
});
|
||||
|
||||
it("refuses a session outside the task folder, with extra tool servers, or without the instructions", () => {
|
||||
const fresh = () => {
|
||||
const guard = createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE });
|
||||
guard.initialize(initializeResult());
|
||||
return guard;
|
||||
};
|
||||
expect(() => fresh().sessionRequest(sessionRequest({ cwd: "/elsewhere" }))).toThrow(/task folder/);
|
||||
expect(() => fresh().sessionRequest(sessionRequest({ mcpServers: [
|
||||
{ type: "http", name: "paperclip", url: "u", headers: [] }, { name: "extra", command: "/bin/x", args: [], env: [] },
|
||||
] }))).toThrow(/Paperclip's own tools/);
|
||||
expect(() => fresh().sessionRequest(sessionRequest({ _meta: {} }))).toThrow(/instructions/);
|
||||
});
|
||||
|
||||
it("names a sign-in without auto mode as unavailable instead of running without helper writes", () => {
|
||||
const guard = createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE });
|
||||
guard.initialize(initializeResult());
|
||||
guard.sessionRequest(sessionRequest());
|
||||
expect(() => guard.sessionResult(sessionResult(["default", "accept-edits", "plan"])))
|
||||
.toThrow(expect.objectContaining({ code: "ANTIGRAVITY_SWARM_UNAVAILABLE" }));
|
||||
});
|
||||
|
||||
it("fails closed when mode or model does not read back, or changes afterwards", () => {
|
||||
const base = () => {
|
||||
const guard = createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE });
|
||||
guard.initialize(initializeResult());
|
||||
guard.sessionRequest(sessionRequest());
|
||||
guard.sessionResult(sessionResult());
|
||||
return guard;
|
||||
};
|
||||
expect(() => base().bindMode()).toThrow(/auto mode/);
|
||||
const wrongLevel = base();
|
||||
wrongLevel.observe(config("gemini-3.8-flash", "high"));
|
||||
expect(() => wrongLevel.bindModel()).toThrow(/gemini-3.8-flash-low/);
|
||||
expect(() => admitted().observe(config("gemini-3.8-flash", "high"))).toThrow(/changed/);
|
||||
expect(() => admitted().observe({ sessionId: SESSION, update: { sessionUpdate: "current_mode_update", currentModeId: "default" } })).toThrow(/changed/);
|
||||
});
|
||||
|
||||
it("refuses a helper that would get its own copy of the workspace", () => {
|
||||
const add = (workspace?: string) => ({ sessionUpdate: "tool_call", name: "swarm",
|
||||
args: { action: "add", name: "writer-a", ...(workspace === undefined ? {} : { workspace }) } });
|
||||
expect(antigravitySwarmWorkspaceEscape(add())).toBeNull();
|
||||
expect(antigravitySwarmWorkspaceEscape(add("inherit"))).toBeNull();
|
||||
expect(antigravitySwarmWorkspaceEscape(add("branch"))).toBe("writer-a");
|
||||
expect(antigravitySwarmWorkspaceEscape(add("share"))).toBe("writer-a");
|
||||
});
|
||||
|
||||
it("treats provider refusals that arrive as ordinary text as failures", () => {
|
||||
expect(classifyAntigravityRefusalText("⚠ agent executor error: Error 402 Your prepayment credits are depleted. Status: RESOURCE_EXHAUSTED"))
|
||||
.toMatchObject({ kind: "quota_exhausted", httpStatus: 402 });
|
||||
expect(classifyAntigravityRefusalText("\n⚠ RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n"))
|
||||
.toMatchObject({ kind: "rate_limit", httpStatus: 429 });
|
||||
expect(classifyAntigravityRefusalText("Both files are written.")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,231 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { ANTIGRAVITY_CLI_DISTRIBUTION } from "./antigravity-cli-pins.js";
|
||||
|
||||
/**
|
||||
* Google Antigravity CLI route (`agy acp`), used only for a turn the signed-in
|
||||
* user started with a trusted `/swarm`. The registry server's owned admission
|
||||
* patch does not exist here (the CLI is a signed binary with no patch point),
|
||||
* so this guard verifies what the connection itself reports instead, and fails
|
||||
* closed on any difference:
|
||||
*
|
||||
* - agent identity and version from `initialize` equal the pinned CLI;
|
||||
* - the CLI accepts Paperclip's instructions through `systemPrompt.append`;
|
||||
* - the session's working directory is the task workspace, and the only MCP
|
||||
* server is the runner-owned Paperclip bridge;
|
||||
* - session mode reads back as `auto` after `session/set_mode`;
|
||||
* - model family and thinking level read back as the agent's configured model;
|
||||
* - none of those change later in the session;
|
||||
* - helpers share the task workspace (`inherit`); `share` and `branch` are refused.
|
||||
*/
|
||||
export const ANTIGRAVITY_SWARM_MODE = "swarm";
|
||||
export const ANTIGRAVITY_CLI_AGENT_NAME = "Antigravity ACP Server";
|
||||
export const ANTIGRAVITY_CLI_SESSION_MODE = "auto";
|
||||
/** Google's stable endpoint; the CLI's default is the daily one. */
|
||||
export const ANTIGRAVITY_CLI_STABLE_ENDPOINT = "https://cloudcode-pa.googleapis.com";
|
||||
export const ANTIGRAVITY_SWARM_MCP_SERVER = "paperclip";
|
||||
|
||||
export type AntigravitySwarmErrorCode =
|
||||
| "ANTIGRAVITY_SWARM_UNAVAILABLE"
|
||||
| "ANTIGRAVITY_SWARM_SIGN_IN_REQUIRED"
|
||||
| "ANTIGRAVITY_SWARM_RECEIPT_MISMATCH"
|
||||
| "ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE"
|
||||
| "ANTIGRAVITY_SWARM_HELPERS_TIMEOUT"
|
||||
| "ANTIGRAVITY_SWARM_RESULT_MISMATCH";
|
||||
|
||||
/** `message` is written for the person who asked for the swarm. */
|
||||
export class AntigravitySwarmError extends Error {
|
||||
readonly retryable = false;
|
||||
constructor(readonly code: AntigravitySwarmErrorCode, message: string) {
|
||||
super(message);
|
||||
this.name = "AntigravitySwarmError";
|
||||
}
|
||||
}
|
||||
|
||||
const mismatch = (detail: string): never => {
|
||||
throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_RECEIPT_MISMATCH",
|
||||
`Swarm stopped before it started: ${detail}. Nothing was changed.`);
|
||||
};
|
||||
|
||||
/** What the driver verified in place of the registry server's admission receipt. */
|
||||
export interface AntigravitySwarmReceipt {
|
||||
agentName: string;
|
||||
agentVersion: string;
|
||||
sessionId: string;
|
||||
workspace: string;
|
||||
mode: typeof ANTIGRAVITY_CLI_SESSION_MODE;
|
||||
model: string;
|
||||
modelFamily: string;
|
||||
thoughtLevel: string | null;
|
||||
instructionDigest: string;
|
||||
mcpServers: string[];
|
||||
}
|
||||
|
||||
export interface AntigravitySwarmGuardOptions {
|
||||
model: string;
|
||||
instructions: string;
|
||||
workspace: string;
|
||||
}
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
const record = (value: unknown): Json =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {};
|
||||
|
||||
export function antigravitySwarmInstructionDigest(content: string): string {
|
||||
return `sha256:${createHash("sha256").update(content, "utf8").digest("hex")}`;
|
||||
}
|
||||
|
||||
/** The `model` / `thought_level` / `mode` selections in a config option list. */
|
||||
export function antigravitySelections(value: unknown): Map<string, string> {
|
||||
const selections = new Map<string, string>();
|
||||
const options = record(value).configOptions;
|
||||
if (!Array.isArray(options)) return selections;
|
||||
for (const entry of options) {
|
||||
const option = record(entry);
|
||||
if (typeof option.id === "string" && typeof option.currentValue === "string"
|
||||
&& ["model", "thought_level", "mode"].includes(option.id)) selections.set(option.id, option.currentValue);
|
||||
}
|
||||
return selections;
|
||||
}
|
||||
|
||||
export function createAntigravitySwarmGuard(options: AntigravitySwarmGuardOptions) {
|
||||
const model = options.model.trim();
|
||||
if (!model || model.length > 512 || /[\u0000-\u001f]/.test(model)) mismatch("the agent has no exact model");
|
||||
const instructionDigest = antigravitySwarmInstructionDigest(options.instructions);
|
||||
const state = {
|
||||
agentName: "", agentVersion: "", sessionId: "", modeBound: false, modelBound: false,
|
||||
selections: new Map<string, string>(), commands: null as string[] | null, mcpServers: [] as string[],
|
||||
};
|
||||
const assertStable = (next: Map<string, string>) => {
|
||||
for (const [id, value] of next) {
|
||||
const bound = id === "mode" ? state.modeBound : state.modelBound;
|
||||
if (bound && state.selections.get(id) !== value) mismatch("the provider changed the confirmed model, thinking level, or permission mode");
|
||||
state.selections.set(id, value);
|
||||
}
|
||||
};
|
||||
return {
|
||||
instructionDigest,
|
||||
/** `initialize` result: exact pinned identity and the instruction channel. */
|
||||
initialize(result: unknown): void {
|
||||
const value = record(result);
|
||||
const info = record(value.agentInfo);
|
||||
if (info.name !== ANTIGRAVITY_CLI_AGENT_NAME || info.version !== ANTIGRAVITY_CLI_DISTRIBUTION.version) {
|
||||
mismatch("the Antigravity CLI did not report its pinned version");
|
||||
}
|
||||
const append = record(record(record(record(value.agentCapabilities)._meta).antigravity).systemPrompt).append;
|
||||
if (append !== true) mismatch("the Antigravity CLI cannot receive Paperclip's instructions");
|
||||
state.agentName = info.name as string;
|
||||
state.agentVersion = info.version as string;
|
||||
},
|
||||
/** The exact `session/new` request this route sends; refuses anything else. */
|
||||
sessionRequest(params: Json): void {
|
||||
if (params.cwd !== options.workspace) mismatch("the session is not in the task folder");
|
||||
const servers = Array.isArray(params.mcpServers) ? params.mcpServers.map(record) : [];
|
||||
if (servers.length !== 1 || servers[0]!.name !== ANTIGRAVITY_SWARM_MCP_SERVER || servers[0]!.type !== "http") {
|
||||
mismatch("the session must use only Paperclip's own tools");
|
||||
}
|
||||
const appended = record(record(record(params._meta).antigravity).systemPrompt).append;
|
||||
if (typeof appended !== "string" || antigravitySwarmInstructionDigest(appended) !== instructionDigest) {
|
||||
mismatch("Paperclip's instructions are missing from the session");
|
||||
}
|
||||
state.mcpServers = [ANTIGRAVITY_SWARM_MCP_SERVER];
|
||||
},
|
||||
sessionResult(result: unknown): string {
|
||||
if (!state.agentName) mismatch("the provider was not identified");
|
||||
if (state.mcpServers.length === 0) mismatch("the session request was not checked");
|
||||
const value = record(result);
|
||||
if (typeof value.sessionId !== "string" || !value.sessionId || value.sessionId.length > 256) mismatch("the provider did not open a session");
|
||||
const modes = record(value.modes).availableModes;
|
||||
if (!Array.isArray(modes) || !modes.some(mode => record(mode).id === ANTIGRAVITY_CLI_SESSION_MODE)) {
|
||||
throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE",
|
||||
"Swarm is not available with this Google connection: helpers can only change files in Antigravity's auto mode, which this sign-in does not offer.");
|
||||
}
|
||||
const available = record(value.models).availableModels;
|
||||
if (!Array.isArray(available) || !available.some(entry => record(entry).modelId === model)) {
|
||||
mismatch(`the model ${model} is not offered to this sign-in`);
|
||||
}
|
||||
state.sessionId = value.sessionId as string;
|
||||
assertStable(antigravitySelections(value));
|
||||
return state.sessionId;
|
||||
},
|
||||
/** Every inbound `session/update`; throws on a change to a confirmed setting. */
|
||||
observe(params: unknown): void {
|
||||
const value = record(params);
|
||||
if (!state.sessionId || value.sessionId !== state.sessionId) return;
|
||||
const update = record(value.update);
|
||||
if (update.sessionUpdate === "current_mode_update") {
|
||||
if (typeof update.currentModeId !== "string") mismatch("the provider reported an invalid permission mode");
|
||||
assertStable(new Map([["mode", update.currentModeId as string]]));
|
||||
} else if (update.sessionUpdate === "config_option_update") {
|
||||
assertStable(antigravitySelections(update));
|
||||
} else if (update.sessionUpdate === "available_commands_update" && Array.isArray(update.availableCommands)) {
|
||||
state.commands = update.availableCommands.map(command => String(record(command).name));
|
||||
}
|
||||
},
|
||||
/** After `session/set_mode auto`: the read-back must say `auto`. */
|
||||
bindMode(): void {
|
||||
if (state.selections.get("mode") !== ANTIGRAVITY_CLI_SESSION_MODE) mismatch("the provider did not confirm auto mode");
|
||||
state.modeBound = true;
|
||||
},
|
||||
/** After `session/set_model <concrete>`: family plus thinking level must read back as that model. */
|
||||
bindModel(): void {
|
||||
const family = state.selections.get("model");
|
||||
const level = state.selections.get("thought_level");
|
||||
if (!family || (family !== model && `${family}-${level}` !== model)) mismatch(`the provider did not confirm the model ${model}`);
|
||||
state.modelBound = true;
|
||||
},
|
||||
/** `/swarm` must be one of the pinned CLI's own commands for this session. */
|
||||
assertSwarmCommand(): void {
|
||||
if (state.commands !== null && !state.commands.includes("swarm")) {
|
||||
throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "Swarm is not offered by this Antigravity CLI session.");
|
||||
}
|
||||
},
|
||||
receipt(): AntigravitySwarmReceipt {
|
||||
if (!state.sessionId || !state.modeBound || !state.modelBound) mismatch("the session settings were not confirmed");
|
||||
const family = state.selections.get("model")!;
|
||||
return {
|
||||
agentName: state.agentName, agentVersion: state.agentVersion, sessionId: state.sessionId,
|
||||
workspace: options.workspace, mode: ANTIGRAVITY_CLI_SESSION_MODE, model, modelFamily: family,
|
||||
thoughtLevel: family === model ? null : state.selections.get("thought_level") ?? null,
|
||||
instructionDigest, mcpServers: [...state.mcpServers],
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type AntigravitySwarmGuard = ReturnType<typeof createAntigravitySwarmGuard>;
|
||||
|
||||
/** A helper started with its own copy of the workspace would write outside the task folder. */
|
||||
export function antigravitySwarmWorkspaceEscape(update: unknown): string | null {
|
||||
const value = record(update);
|
||||
if ((value.sessionUpdate !== "tool_call" && value.sessionUpdate !== "tool_call_update") || value.name !== "swarm") return null;
|
||||
const args = { ...record(value.rawInput), ...record(value.args) };
|
||||
if (args.action !== "add" || args.workspace === undefined || args.workspace === "inherit") return null;
|
||||
return typeof args.name === "string" ? args.name : "a helper";
|
||||
}
|
||||
|
||||
export interface AntigravityRefusal {
|
||||
kind: "quota_exhausted" | "rate_limit" | "authentication";
|
||||
httpStatus?: number;
|
||||
status?: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The CLI reports some provider refusals as assistant text and then ends the
|
||||
* turn normally (seen live with 402 credits and 429 quota). These are failures.
|
||||
*/
|
||||
export function classifyAntigravityRefusalText(text: string): AntigravityRefusal | null {
|
||||
const sample = text.slice(0, 4_000);
|
||||
if (/prepayment credits are depleted|\bError 402\b|\bcode 402\b/i.test(sample)) {
|
||||
return { kind: "quota_exhausted", httpStatus: 402, status: "RESOURCE_EXHAUSTED",
|
||||
message: "Google refused the swarm: this account has no credits left." };
|
||||
}
|
||||
if (/⚠\s*RESOURCE_EXHAUSTED|\bcode 429\b|\bError 429\b/i.test(sample)) {
|
||||
return { kind: "rate_limit", httpStatus: 429, status: "RESOURCE_EXHAUSTED",
|
||||
message: "Google refused the swarm: this account is out of quota for now. Try again later." };
|
||||
}
|
||||
if (/⚠.*Authentication required/i.test(sample)) {
|
||||
return { kind: "authentication", message: "The Antigravity CLI on this computer is not signed in to Google." };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { antigravitySwarmEvent, stripAntigravityTerminalHints } from "./antigravity-swarm-presentation.js";
|
||||
|
||||
const WORKSPACE = "/work/task";
|
||||
const tool = (name: string, args: Record<string, unknown>, sessionUpdate = "tool_call", status = "in_progress") =>
|
||||
({ sessionUpdate, toolCallId: "call_14003112185197785061", name, args, rawInput: args, status, kind: "other", title: `Run ${name}` });
|
||||
|
||||
describe("Antigravity swarm activity, in plain language", () => {
|
||||
it("names helpers by role and what they were asked to do, never by id", () => {
|
||||
const event = antigravitySwarmEvent(tool("swarm", { action: "add", name: "writer-a", workspace: "inherit",
|
||||
brief: `Write a.txt containing exactly 'A' in ${WORKSPACE}. Once done, post to the board: '@verifier [done] a.txt written'.` }), WORKSPACE);
|
||||
expect(event).toMatchObject({ type: "tool_call", title: "Started helper writer-a: Write a.txt containing exactly 'A' in the task folder" });
|
||||
expect(event?.title).not.toMatch(/call_|@verifier/);
|
||||
expect(event).not.toHaveProperty("rawInput");
|
||||
expect(antigravitySwarmEvent(tool("swarm", { action: "add", name: "monitor", brief: "You are this swarm's stall monitor. Load the swarm_monitor skill." }), WORKSPACE))
|
||||
.toMatchObject({ title: "Started a helper that watches for stalls" });
|
||||
});
|
||||
|
||||
it("describes board activity without the provider's tool names", () => {
|
||||
expect(antigravitySwarmEvent(tool("read_board", { since: 5 }), WORKSPACE)).toMatchObject({ title: "Checked on the helpers" });
|
||||
expect(antigravitySwarmEvent(tool("post_message", { text: "@verifier [done] Verification verified: checked 2 files" }), WORKSPACE))
|
||||
.toMatchObject({ title: "Coordinator: Verification verified: checked 2 files" });
|
||||
expect(antigravitySwarmEvent(tool("swarm", { action: "title", title: "Two writers and a verifier" }), WORKSPACE))
|
||||
.toMatchObject({ title: "Swarm: Two writers and a verifier" });
|
||||
});
|
||||
|
||||
it("keeps the opening title on later updates of the same call", () => {
|
||||
expect(antigravitySwarmEvent(tool("read_board", { since: 5 }, "tool_call_update", "completed"), WORKSPACE))
|
||||
.toMatchObject({ type: "tool_call", tag: "tool_call_update", status: "completed", title: "Checked on the helpers" });
|
||||
});
|
||||
|
||||
it("drops terminal-only hints from the coordinator's text", () => {
|
||||
expect(stripAntigravityTerminalHints("Launched.\n\nRun /swarm board (default shortcut alt+s) to open the live board."))
|
||||
.toBe("Launched.\n");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { AcpRuntimeEvent } from "acpx/runtime";
|
||||
|
||||
/**
|
||||
* The Antigravity CLI coordinator reports its swarm through its own tools
|
||||
* (`swarm`, `read_board`, `post_message`, `swarm_wait`). Helper conversations
|
||||
* never reach the client. Turn those calls into short readable steps, and keep
|
||||
* provider ids, tool names and terminal hints out of what users see.
|
||||
*/
|
||||
type Json = Record<string, unknown>;
|
||||
const record = (value: unknown): Json =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {};
|
||||
|
||||
const SWARM_TOOLS = new Set(["swarm", "read_board", "post_message", "swarm_wait"]);
|
||||
const TERMINAL_HINT = /\n?Run \/swarm board \(default shortcut [^)]*\) to open the live board\.?/g;
|
||||
|
||||
export function stripAntigravityTerminalHints(text: string): string {
|
||||
return text.replace(TERMINAL_HINT, "");
|
||||
}
|
||||
|
||||
function plain(text: string, workspace: string, limit = 120): string {
|
||||
let value = text.split(workspace).join("the task folder")
|
||||
.replace(/@[a-z0-9_-]+\s*/gi, "").replace(/\[(?:done|blocked|update)\]\s*/gi, "").replace(/\s+/g, " ").trim();
|
||||
// First sentence only: briefs carry board protocol after it.
|
||||
const sentence = /^(.+?[.!?])(\s|$)/.exec(value)?.[1];
|
||||
if (sentence) value = sentence.replace(/[.!?]$/, "");
|
||||
return value.length > limit ? `${value.slice(0, limit - 1)}…` : value;
|
||||
}
|
||||
|
||||
function swarmTitle(name: string, args: Json, workspace: string): string | null {
|
||||
if (name === "read_board") return "Checked on the helpers";
|
||||
if (name === "swarm_wait") return "Waiting for the helpers";
|
||||
if (name === "post_message") return typeof args.text === "string" && args.text.trim() ? `Coordinator: ${plain(args.text, workspace)}` : "Coordinator posted an update";
|
||||
if (name !== "swarm") return null;
|
||||
const helper = typeof args.name === "string" ? args.name.replace(/[^a-zA-Z0-9 _.-]/g, "").slice(0, 40) : "";
|
||||
switch (args.action) {
|
||||
case "add":
|
||||
if (/^monitor$/i.test(helper)) return "Started a helper that watches for stalls";
|
||||
return typeof args.brief === "string" && args.brief.trim()
|
||||
? `Started helper ${helper || "(unnamed)"}: ${plain(args.brief, workspace)}`
|
||||
: `Started helper ${helper || "(unnamed)"}`;
|
||||
case "title": return typeof args.title === "string" ? `Swarm: ${plain(args.title, workspace)}` : "Named the swarm";
|
||||
case "remove": case "kill": case "stop": return helper ? `Stopped helper ${helper}` : "Stopped a helper";
|
||||
case "status": return "Checked on the helpers";
|
||||
default: return "Coordinated the helpers";
|
||||
}
|
||||
}
|
||||
|
||||
/** One ACP `session/update` as a runtime event, or null when it carries nothing to show. */
|
||||
export function antigravitySwarmEvent(update: unknown, workspace: string): AcpRuntimeEvent | null {
|
||||
const value = record(update);
|
||||
const kind = value.sessionUpdate;
|
||||
if (kind === "agent_message_chunk" || kind === "agent_thought_chunk") {
|
||||
const content = record(value.content);
|
||||
if (content.type !== "text" || typeof content.text !== "string") return null;
|
||||
const text = kind === "agent_message_chunk" ? stripAntigravityTerminalHints(content.text) : content.text;
|
||||
if (!text) return null;
|
||||
return { type: "text_delta", text, stream: kind === "agent_thought_chunk" ? "thought" : "output", tag: kind };
|
||||
}
|
||||
if (kind !== "tool_call" && kind !== "tool_call_update") return null;
|
||||
if (typeof value.toolCallId !== "string" || !value.toolCallId) return null;
|
||||
const name = typeof value.name === "string" ? value.name : "";
|
||||
const args = { ...record(value.rawInput), ...record(value.args) };
|
||||
const status = typeof value.status === "string" ? value.status : undefined;
|
||||
if (SWARM_TOOLS.has(name)) {
|
||||
const title = swarmTitle(name, args, workspace) ?? "Coordinated the helpers";
|
||||
return { type: "tool_call", tag: kind, toolCallId: value.toolCallId, text: title, title, kind: "other", ...(status ? { status } : {}) };
|
||||
}
|
||||
const title = typeof value.title === "string" ? value.title.split(workspace).join(".") : name || "Tool call";
|
||||
return {
|
||||
type: "tool_call", tag: kind, toolCallId: value.toolCallId, text: title, title,
|
||||
...(typeof value.kind === "string" ? { kind: value.kind as never } : {}),
|
||||
...(status ? { status } : {}),
|
||||
...(value.rawInput !== undefined ? { rawInput: value.rawInput } : {}),
|
||||
...(value.rawOutput !== undefined ? { rawOutput: value.rawOutput } : {}),
|
||||
...(Array.isArray(value.content) ? { content: value.content as never } : {}),
|
||||
...(Array.isArray(value.locations) ? { locations: value.locations as never } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
#!/usr/bin/env node
|
||||
// Deterministic stand-in for `agy acp` 1.5.15 (Google Antigravity CLI), replaying
|
||||
// the message shapes recorded in the 2026-11-24 spike (transcripts a1-a4, b1, d1,
|
||||
// d2). It never touches the network. FAKE_AGY_SCENARIO selects the behaviour:
|
||||
// success two writers and a verifier; files land in the workspace
|
||||
// live-helpers the coordinator ends its first turn while helpers still run;
|
||||
// the files appear only after the follow-up wait prompt
|
||||
// blocked a helper is blocked outside the workspace; the coordinator
|
||||
// also asks the client to approve an outside write
|
||||
// misreport writer-b is reported done but b.txt was never written
|
||||
// escape a helper is started on its own branch workspace
|
||||
// cancel helpers keep running (a real child process) until session/cancel
|
||||
// die the CLI exits in the middle of the swarm
|
||||
// refusal the provider refusal arrives as ordinary text with end_turn
|
||||
// quota the 429 quota refusal, as seen live on 2026-11-24
|
||||
// wrong-version | no-auto | wrong-mode | wrong-model receipt mismatches
|
||||
// hang-helpers the follow-up wait never ends
|
||||
// FAKE_AGY_LOG (optional) appends every client message, one JSON per line.
|
||||
import { spawn } from "node:child_process";
|
||||
import { appendFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const scenario = process.env.FAKE_AGY_SCENARIO ?? "success";
|
||||
const log = message => { if (process.env.FAKE_AGY_LOG) appendFileSync(process.env.FAKE_AGY_LOG, `${JSON.stringify(message)}\n`); };
|
||||
const write = message => process.stdout.write(`${JSON.stringify(message)}\n`);
|
||||
const update = (sessionId, value) => write({ jsonrpc: "2.0", method: "session/update", params: { sessionId, update: value } });
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
const MODELS = ["gemini-4-argon-medium", "gemini-4-argon-low", "gemini-3.8-flash-high", "gemini-3.8-flash-medium", "gemini-3.8-flash-low"];
|
||||
const COMMANDS = ["goal", "compact", "schedule", "browser", "plan", "grill-me", "teamwork", "learn", "boost", "agy-customizations", "antigravity-guide", "run-workflow", "swarm"];
|
||||
|
||||
const state = { sessionId: "", cwd: "", model: "gemini-4-argon", level: "medium", mode: "default", prompts: 0, cancel: null, worker: null };
|
||||
const configOptions = () => [
|
||||
{ id: "model", name: "Model", category: "model", type: "select", currentValue: state.model, options: [{ value: "gemini-4-argon" }, { value: "gemini-3.8-flash" }] },
|
||||
{ id: "thought_level", name: "Thinking Level", category: "thought_level", type: "select", currentValue: state.level, options: [{ value: "low" }, { value: "medium" }, { value: "high" }] },
|
||||
{ id: "mode", name: "Mode", category: "mode", type: "select", currentValue: state.mode, options: [{ value: "default" }, { value: "accept-edits" }, { value: "auto" }, { value: "plan" }] },
|
||||
];
|
||||
let call = 1000;
|
||||
const tool = async (name, args, status = "completed") => {
|
||||
const toolCallId = `call_${++call}`;
|
||||
update(state.sessionId, { sessionUpdate: "tool_call", toolCallId, name, args, status: "in_progress", kind: "other", title: `Run ${name}`, rawInput: args });
|
||||
await sleep(2);
|
||||
update(state.sessionId, { sessionUpdate: "tool_call_update", toolCallId, name, args, status, kind: "other", title: `Run ${name}`, rawInput: args });
|
||||
};
|
||||
const say = text => update(state.sessionId, { sessionUpdate: "agent_message_chunk", content: { type: "text", text } });
|
||||
const usage = { inputTokens: 49646, outputTokens: 1421, cachedReadTokens: 81968, cachedWriteTokens: 0, thoughtTokens: 0, totalTokens: 133035 };
|
||||
const addWriters = async () => {
|
||||
await tool("swarm", { action: "title", title: "Two writers and a verifier" });
|
||||
await tool("swarm", { action: "add", name: "writer-a", workspace: "inherit", brief: "Write a.txt containing exactly 'A' in the current workspace directory. Once done, post to the board: '@verifier [done] a.txt written'." });
|
||||
await tool("swarm", { action: "add", name: "writer-b", workspace: "inherit", brief: "Write b.txt containing exactly 'B' in the current workspace directory. Once done, post to the board: '@verifier [done] b.txt written'." });
|
||||
await tool("swarm", { action: "add", name: "verifier", workspace: "inherit", brief: "Wait for writer-a and writer-b, then read a.txt and b.txt and report." });
|
||||
await tool("swarm", { action: "add", name: "monitor", workspace: "inherit", brief: "You are this swarm's stall monitor. Load the swarm_monitor skill and follow it." });
|
||||
};
|
||||
const writeFiles = () => {
|
||||
writeFileSync(join(state.cwd, "a.txt"), "A");
|
||||
writeFileSync(join(state.cwd, "b.txt"), "B");
|
||||
};
|
||||
|
||||
async function prompt(id, params) {
|
||||
state.prompts += 1;
|
||||
const text = params.prompt?.[0]?.text ?? "";
|
||||
if (state.prompts > 1) {
|
||||
// Paperclip's follow-up: wait for the helpers, then confirm.
|
||||
if (scenario === "hang-helpers") { await new Promise(resolve => { state.cancel = resolve; }); return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } }); }
|
||||
await tool("read_board", { since: 5 });
|
||||
if (scenario === "live-helpers") writeFiles();
|
||||
say("All helpers have finished. a.txt contains A and b.txt contains B.");
|
||||
return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn", usage: { ...usage, totalTokens: 1000, inputTokens: 900, outputTokens: 100, cachedReadTokens: 0 } } });
|
||||
}
|
||||
if (!text.startsWith("/swarm ")) { say("not a swarm"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); }
|
||||
update(state.sessionId, { sessionUpdate: "session_info_update", title: "Swarm" });
|
||||
if (scenario === "refusal") { say("\n⚠ agent executor error: Error 402 Your prepayment credits are depleted. Status: RESOURCE_EXHAUSTED\n"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); }
|
||||
if (scenario === "quota") { say("\n⚠ RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); }
|
||||
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" } }); }
|
||||
await addWriters();
|
||||
say("I have configured and launched the swarm.\n\nRun /swarm board (default shortcut alt+s) to open the live board.");
|
||||
if (scenario === "cancel" || scenario === "die") {
|
||||
// A helper is a real descendant in the CLI's process group.
|
||||
state.worker = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
||||
if (process.env.FAKE_AGY_WORKER_PID_FILE) writeFileSync(process.env.FAKE_AGY_WORKER_PID_FILE, String(state.worker.pid));
|
||||
if (scenario === "die") { await sleep(50); process.exit(3); }
|
||||
await new Promise(resolve => { state.cancel = resolve; });
|
||||
return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } });
|
||||
}
|
||||
if (scenario === "live-helpers" || scenario === "hang-helpers") return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn", usage } });
|
||||
if (scenario === "misreport") writeFileSync(join(state.cwd, "a.txt"), "A"); else writeFiles();
|
||||
if (scenario === "blocked") {
|
||||
await tool("swarm", { action: "add", name: "writer-c", workspace: "inherit", brief: "Try once to write /outside/c.txt containing 'C'." });
|
||||
const permissionId = 77;
|
||||
write({ jsonrpc: "2.0", id: permissionId, method: "session/request_permission", params: { sessionId: state.sessionId,
|
||||
toolCall: { toolCallId: "call_perm", title: "Write /outside/c.txt", kind: "edit" },
|
||||
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }, { optionId: "deny", name: "Deny", kind: "reject_once" }] } });
|
||||
await new Promise(resolve => { state.permission = resolve; });
|
||||
say("writer-c: the write outside the workspace failed (sandbox permission check timed out waiting for user response).\n");
|
||||
}
|
||||
await tool("read_board", { since: 5 });
|
||||
await tool("post_message", { text: "[done] Verification verified and tasks finished successfully." });
|
||||
say("\n\nThe swarm has completed its work. a.txt contains A and b.txt contains B.");
|
||||
write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn", usage } });
|
||||
}
|
||||
|
||||
let buffer = "";
|
||||
process.stdin.on("data", chunk => {
|
||||
buffer += chunk;
|
||||
for (let index = buffer.indexOf("\n"); index >= 0; index = buffer.indexOf("\n")) {
|
||||
const line = buffer.slice(0, index); buffer = buffer.slice(index + 1);
|
||||
if (!line.trim()) continue;
|
||||
const message = JSON.parse(line);
|
||||
log(message);
|
||||
void handle(message);
|
||||
}
|
||||
});
|
||||
process.stdin.on("end", () => process.exit(0));
|
||||
|
||||
async function handle(message) {
|
||||
const { id, method, params = {} } = message;
|
||||
if (method === undefined) { if (id === 77) { log({ permissionAnswer: message.result }); state.permission?.(); } return; }
|
||||
if (method === "initialize") {
|
||||
return write({ jsonrpc: "2.0", id, result: { protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true, promptCapabilities: { image: true, embeddedContext: true }, _meta: { antigravity: { tier: true, systemPrompt: { append: true } } } },
|
||||
agentInfo: { name: "Antigravity ACP Server", version: scenario === "wrong-version" ? "1.5.16" : "1.5.15" },
|
||||
authMethods: [{ id: "oauth-personal" }, { id: "gemini-api-key" }] } });
|
||||
}
|
||||
if (method === "session/new") {
|
||||
state.sessionId = "e6536314-e108-4ecd-a0cf-efa59061510d"; state.cwd = params.cwd;
|
||||
write({ jsonrpc: "2.0", id, result: { sessionId: state.sessionId,
|
||||
models: { availableModels: MODELS.map(modelId => ({ modelId })), currentModelId: "gemini-4-argon-medium" },
|
||||
modes: { currentModeId: "default", availableModes: (scenario === "no-auto" ? ["default", "accept-edits", "plan"] : ["default", "accept-edits", "auto", "plan"]).map(id => ({ id })) },
|
||||
configOptions: configOptions() } });
|
||||
await sleep(5);
|
||||
update(state.sessionId, { sessionUpdate: "available_commands_update", availableCommands: COMMANDS.map(name => ({ name })) });
|
||||
return;
|
||||
}
|
||||
if (method === "session/set_mode") {
|
||||
write({ jsonrpc: "2.0", id, result: {} });
|
||||
if (scenario === "wrong-mode") return;
|
||||
state.mode = params.modeId;
|
||||
update(state.sessionId, { sessionUpdate: "current_mode_update", currentModeId: state.mode });
|
||||
return update(state.sessionId, { sessionUpdate: "config_option_update", configOptions: configOptions() });
|
||||
}
|
||||
if (method === "session/set_model") {
|
||||
write({ jsonrpc: "2.0", id, result: {} });
|
||||
const match = /^(.*)-(low|medium|high)$/.exec(params.modelId);
|
||||
state.model = match[1]; state.level = scenario === "wrong-model" ? "high" : match[2];
|
||||
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 (id !== undefined) write({ jsonrpc: "2.0", id, error: { code: -32601, message: "Method not found" } });
|
||||
}
|
||||
Reference in new issue
Block a user