fix(antigravity): serve the swarm CLI RE2-portable tool schemas

Live /swarm (run c49211c7, after the session.open fix) opened the pinned
CLI, which then refused its whole toolbox before any prompt:
"tool mcp_paperclip_list_document_revisions advertises an invalid
parameter schema". The CLI checks schemas with RE2, and the task document
key pattern uses ECMAScript \uXXXX escapes, which RE2 does not accept.

- The tool bridge can serve a client RE2-portable patterns (\x{...});
  the swarm route turns it on. Calls are still validated against the
  original schemas, so accepted inputs do not change.
- The CLI reports such failures as "agent executor error" text and ends
  the turn normally; the swarm turn now fails in plain words instead of
  completing with no result (which the server retried as an interruption).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-24 14:29:39 -06:00
1 parent fc81774086
commit 0f2d40e464
7 files changed
+155 -1

No files matched your search

@@ -211,6 +211,13 @@ describe("Antigravity CLI swarm runtime", () => {
expect(run.failures[0]?.provider?.kind).toBe(scenario === "refusal" ? "quota_exhausted" : "rate_limit");
});
it("fails a turn the CLI ended with an internal executor error, in plain words", async () => {
const run = await runTurn("executor-error");
expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_FAILED",
message: expect.stringMatching(/^The Antigravity CLI stopped with an internal error/) } });
expect(JSON.stringify(run.result)).not.toContain("toolbox");
});
it("stops every helper on Stop and leaves no process behind", async () => {
let cancelled = false;
const run = await runTurn("cancel", { onEvent: (event, cancel) => {
@@ -516,6 +516,11 @@ 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);
}
// The CLI reports its own failures (for example a toolbox it could not build)
// as text and ends the turn normally. The detail is internal; say it plainly.
if (/⚠\s*agent executor error:/i.test(transcript.slice(0, 8_000))) {
return failed("ANTIGRAVITY_SWARM_FAILED", "The Antigravity CLI stopped with an internal error, so the swarm did not finish. Send /swarm again to retry.");
}
// 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.
@@ -697,6 +697,8 @@ export class AcpxRuntimeHost {
...(swarmRoute && options.semanticTools!.tools ? { tools: antigravitySwarmTools(options.semanticTools!.tools) } : {}),
preserveToolNames: options.assignedMcpTransport === "prp",
preloadClaudeTaskTools: options.agent === "claude",
// The Antigravity CLI checks tool schemas with RE2 and refuses its whole toolbox otherwise.
...(swarmRoute ? { schemaPatternDialect: "re2" as const } : {}),
}),
resource: "tool_bridge",
releaseLate: (lateToolBridge) => lateToolBridge.close(),
@@ -0,0 +1,57 @@
import { afterEach, expect, it } from "vitest";
import { taskDocumentKeySchema } from "../protocol-actions/task-document-key-schema.js";
import { re2PortableSchema } from "./re2-schema-patterns.js";
import { startRunnerToolBridge, type RunnerToolBridge } from "./runner-tool-bridge.js";
const bridges: RunnerToolBridge[] = [];
afterEach(async () => { await Promise.all(bridges.splice(0).map(bridge => bridge.close())); });
async function rpc(bridge: RunnerToolBridge, body: Record<string, unknown>) {
const response = await fetch(bridge.url, {
method: "POST",
headers: { Authorization: `Bearer ${bridge.secret}`, "Content-Type": "application/json" },
body: JSON.stringify({ jsonrpc: "2.0", ...body }),
});
return await response.json() as { result: { tools?: Array<{ name: string; inputSchema: Record<string, unknown> }>; isError?: boolean } };
}
it("rewrites ECMAScript \\u escapes in patterns to the RE2 form the Antigravity CLI's validator compiles", () => {
const schema = { type: "object", properties: {
key: taskDocumentKeySchema,
escaped: { type: "string", pattern: "^a\\\\u0041$" },
emoji: { type: "string", pattern: "^\\ud83d\\ude00$" },
lone: { type: "string", pattern: "^\\ud83d$" },
braced: { type: "string", pattern: "^\\u{1F600}$" },
}, patternProperties: { ["^x\\u0041$"]: { type: "string" } } };
const portable = re2PortableSchema(schema) as { properties: Record<string, { pattern?: string }>; patternProperties: Record<string, unknown> };
// The live failure: the CLI refused the whole toolbox for this one pattern.
expect(portable.properties.key.pattern).not.toMatch(/(^|[^\\])(\\\\)*\\u/);
expect(portable.properties.key.pattern).toContain(String.raw`\x{212a}`);
expect(portable.properties.key.pattern).toContain(String.raw`[\x{0009}-\x{000d}`);
// An escaped backslash followed by "u" is literal text, not an escape.
expect(portable.properties.escaped.pattern).toBe(String.raw`^a\\u0041$`);
expect(portable.properties.emoji.pattern).toBe(String.raw`^\x{1f600}$`);
expect(portable.properties.braced.pattern).toBe(String.raw`^\x{1f600}$`);
// A lone surrogate has no RE2 form: the pattern is left out (the bridge still validates it).
expect(portable.properties.lone).toEqual({ type: "string" });
expect(Object.keys(portable.patternProperties)).toEqual([String.raw`^x\x{0041}$`]);
// The source schema is unchanged.
expect(schema.properties.key.pattern).toBe(taskDocumentKeySchema.pattern);
});
it("serves RE2 patterns to the CLI while validating calls with the original schema", async () => {
const calls: unknown[] = [];
const bridge = await startRunnerToolBridge({
preserveToolNames: true, schemaPatternDialect: "re2",
tools: [{ name: "read_document", inputSchema: { type: "object", properties: { key: taskDocumentKeySchema }, required: ["key"], additionalProperties: false } }],
handler: async call => { calls.push(call.arguments); return { ok: true }; },
});
bridges.push(bridge);
const listed = (await rpc(bridge, { id: 1, method: "tools/list" })).result.tools!;
const served = (listed.find(tool => tool.name === "read_document")!.inputSchema.properties as Record<string, { pattern: string }>).key.pattern;
expect(served).toContain(String.raw`\x{212a}`);
expect(JSON.stringify(listed)).not.toMatch(/\\\\u[0-9a-fA-F]{4}/);
expect((await rpc(bridge, { id: 2, method: "tools/call", params: { name: "read_document", arguments: { key: "plan" } } })).result.isError).not.toBe(true);
expect((await rpc(bridge, { id: 3, method: "tools/call", params: { name: "read_document", arguments: { key: "x{212a}" } } })).result.isError).toBe(true);
expect(calls).toEqual([{ key: "plan" }]);
});
@@ -0,0 +1,74 @@
/**
* Tool input schemas use ECMAScript regular expressions. A client that checks
* schemas with RE2 (the Antigravity CLI, a Go program) refuses `\uXXXX`
* escapes and with them its whole toolbox. This rewrites those escapes to the
* equivalent RE2 form `\x{...}` in a copy of the schema served to such a
* client. Calls are still validated by the Runner against the original schema.
*/
type Json = unknown;
const HEX4 = /^[0-9a-fA-F]{4}$/;
/** The RE2 form of an ECMAScript pattern, or null when it has none (a lone surrogate). */
export function re2PortablePattern(pattern: string): string | null {
let output = "";
for (let index = 0; index < pattern.length; index++) {
const character = pattern[index]!;
if (character !== "\\") { output += character; continue; }
const next = pattern[index + 1];
if (next !== "u") {
// Copy any other escape whole, so an escaped backslash never starts a new one.
output += character + (next ?? "");
index++;
continue;
}
let codePoint: number;
let consumed: number;
const braced = /^\{([0-9a-fA-F]{1,6})\}/.exec(pattern.slice(index + 2));
if (braced) {
codePoint = Number.parseInt(braced[1]!, 16);
consumed = 2 + braced[0].length;
} else if (HEX4.test(pattern.slice(index + 2, index + 6))) {
codePoint = Number.parseInt(pattern.slice(index + 2, index + 6), 16);
consumed = 6;
if (codePoint >= 0xd800 && codePoint <= 0xdbff) {
const low = pattern.slice(index + 6, index + 12);
const lowCode = /^\\u[0-9a-fA-F]{4}$/.test(low) ? Number.parseInt(low.slice(2), 16) : NaN;
if (!(lowCode >= 0xdc00 && lowCode <= 0xdfff)) return null;
codePoint = 0x10000 + ((codePoint - 0xd800) << 10) + (lowCode - 0xdc00);
consumed = 12;
} else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) {
return null;
}
} else {
return null;
}
output += `\\x{${codePoint.toString(16).padStart(4, "0")}}`;
index += consumed - 1;
}
return output;
}
/** A copy of `schema` whose `pattern` values and `patternProperties` keys are RE2-portable. */
export function re2PortableSchema(schema: Json): Json {
if (Array.isArray(schema)) return schema.map(re2PortableSchema);
if (schema === null || typeof schema !== "object") return schema;
const result: Record<string, Json> = {};
for (const [key, value] of Object.entries(schema as Record<string, Json>)) {
if (key === "pattern" && typeof value === "string") {
const portable = re2PortablePattern(value);
if (portable !== null) result[key] = portable;
} else if (key === "patternProperties" && value !== null && typeof value === "object" && !Array.isArray(value)) {
const properties: Record<string, Json> = {};
for (const [pattern, subschema] of Object.entries(value as Record<string, Json>)) {
const portable = re2PortablePattern(pattern);
if (portable !== null) properties[portable] = re2PortableSchema(subschema);
}
result[key] = properties;
} else {
result[key] = re2PortableSchema(value);
}
}
return result;
}
@@ -1,4 +1,5 @@
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { re2PortableSchema } from "./re2-schema-patterns.js";
import { appendSemanticToolReceipt, semanticCanonicalJson as canonicalJson, semanticInputSha256, type SemanticToolReceipt } from "./semantic-tool-receipt.js";
import {
createServer,
@@ -67,6 +68,9 @@ export interface RunnerToolBridgeOptions {
scopeToken?: () => string | null;
/** Receives one JSON diagnostic per call accepted after input coercion. */
onDiagnostic?: (message: string) => void;
/** Regex dialect of the client reading tools/list. "re2" serves RE2-portable
* patterns (Antigravity CLI); calls are still validated with the originals. */
schemaPatternDialect?: "ecma" | "re2";
}
export interface RunnerToolBridge {
@@ -167,12 +171,15 @@ export async function startRunnerToolBridge(
}
}
const admittedTools = [...visibleTools, ...privateTools];
const servedTools = options.schemaPatternDialect === "re2"
? visibleTools.map(tool => ({ ...tool, inputSchema: re2PortableSchema(tool.inputSchema) as Record<string, unknown> }))
: visibleTools;
const calls = new Map<string, AdmittedCall>();
const controllers = new Map<string, AbortController>();
const context = {
secret,
preserveToolNames: options.preserveToolNames === true,
visibleTools,
visibleTools: servedTools,
admittedTools: new Map(admittedTools.map((tool) => [tool.name, tool])),
validators,
rejections: new RepeatedToolInputRejectionGuard(),
@@ -113,6 +113,8 @@ async function prompt(id, params) {
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" } }); }
// Seen live: the CLI refuses its whole toolbox when a tool schema does not compile, then ends the turn.
if (scenario === "executor-error") { say("\n⚠ agent executor error: building toolbox: tool \"mcp_paperclip_read_document\" advertises an invalid parameter schema\n"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); }
if (scenario === "quota") { say("\n⚠ RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); }
const outside = {
"outside-edit": { name: "write_file", kind: "edit", title: "Write /etc/elsewhere.txt", locations: [{ path: "/etc/elsewhere.txt" }] },