mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
Merge branch 'feat/antigravity-cli-swarm-driver' into feat/antigravity-swarm-command
This commit is contained in:
commit
c83f18280c
8 files changed
+283
-38
No files matched your search
@@ -0,0 +1,46 @@
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { antigravityOutsideChange, shellWriteTargets } from "./antigravity-swarm-paths.js";
|
||||
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), "agy-paths-")));
|
||||
const workspace = join(root, "task");
|
||||
const home = join(root, "home");
|
||||
mkdirSync(workspace); mkdirSync(home);
|
||||
symlinkSync(home, join(workspace, "to-home"));
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }));
|
||||
|
||||
const shell = (command: string) => ({ sessionUpdate: "tool_call", kind: "execute", name: "run_command", args: { CommandLine: command } });
|
||||
const edit = (path: string) => ({ sessionUpdate: "tool_call", kind: "edit", name: "write_file", args: { TargetFile: path } });
|
||||
|
||||
describe("changes outside the task folder in visible tool calls", () => {
|
||||
it("finds the write targets of shell commands", () => {
|
||||
expect(shellWriteTargets("printf E > /tmp/e.txt")).toEqual(["/tmp/e.txt"]);
|
||||
expect(shellWriteTargets("echo x >>../log.txt && cat /etc/hosts")).toEqual(["../log.txt"]);
|
||||
expect(shellWriteTargets("cp /etc/hosts ./copy.txt; mv a.txt ~/b.txt")).toEqual(["./copy.txt", "~/b.txt"]);
|
||||
expect(shellWriteTargets("ls | tee /var/tmp/out.txt")).toEqual(["/var/tmp/out.txt"]);
|
||||
expect(shellWriteTargets("sed -i 's/a/b/' $HOME/.profile")).toEqual(["$HOME/.profile"]);
|
||||
expect(shellWriteTargets("dd if=/dev/zero of=/tmp/z bs=1")).toEqual(["/tmp/z"]);
|
||||
expect(shellWriteTargets("cat a.txt 2>/dev/null")).toEqual(["/dev/null"]);
|
||||
});
|
||||
|
||||
it("flags absolute, parent, home and symlink escapes, and allows the task folder", () => {
|
||||
expect(antigravityOutsideChange(shell("printf E > /tmp/agy-e.txt"), workspace, home)).toBe("/tmp/agy-e.txt");
|
||||
expect(antigravityOutsideChange(edit("../escape.txt"), workspace, home)).toBe("../escape.txt");
|
||||
expect(antigravityOutsideChange(edit("~/notes.txt"), workspace, home)).toBe("~/notes.txt");
|
||||
expect(antigravityOutsideChange(shell("echo hi > $HOME/x"), workspace, home)).toBe("$HOME/x");
|
||||
expect(antigravityOutsideChange(edit("to-home/x.txt"), workspace, home)).toBe("to-home/x.txt");
|
||||
expect(antigravityOutsideChange(edit(join(workspace, "a.txt")), workspace, home)).toBeNull();
|
||||
expect(antigravityOutsideChange(edit("..notes.txt"), workspace, home)).toBeNull();
|
||||
expect(antigravityOutsideChange(edit(join(workspace, "..notes.txt")), workspace, home)).toBeNull();
|
||||
expect(antigravityOutsideChange(edit(".."), workspace, home)).toBe("..");
|
||||
expect(antigravityOutsideChange(shell("cp /etc/hosts ./hosts.txt && cat /etc/hosts > out.txt 2>/dev/null"), workspace, home)).toBeNull();
|
||||
});
|
||||
|
||||
it("does not treat reads, URLs or prose as changes", () => {
|
||||
expect(antigravityOutsideChange({ sessionUpdate: "tool_call", kind: "read", name: "read_file", args: { Path: "/etc/hosts" } }, workspace, home)).toBeNull();
|
||||
expect(antigravityOutsideChange(edit("https://docs.google.com/a.txt"), workspace, home)).toBeNull();
|
||||
expect(antigravityOutsideChange({ sessionUpdate: "agent_message_chunk", content: { text: "write /etc/x" } }, workspace, home)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import { realpathSync } from "node:fs";
|
||||
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
|
||||
/**
|
||||
* Finds a change outside the task folder in a tool call the coordinator
|
||||
* reports. It reads file-tool locations and path arguments, and the write
|
||||
* targets of shell commands (redirects, tee, cp/mv/ln destinations, rm, mkdir,
|
||||
* touch, sed -i, dd of=). Paths are resolved like the OS would: relative to the
|
||||
* task folder, `..`, `~` and `$HOME`, and symlinks of existing parents.
|
||||
*
|
||||
* What it cannot see: helper tool calls never reach the ACP client, and a
|
||||
* shell command can hide its target (variables, subshells, scripts). Those
|
||||
* stay confined only by the CLI's own auto mode and sandbox.
|
||||
*/
|
||||
type Json = Record<string, unknown>;
|
||||
const record = (value: unknown): Json =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {};
|
||||
|
||||
const PATH_KEY = /path|file|target|dest|directory|dir$/i;
|
||||
const COMMAND_KEY = /command|cmd|script/i;
|
||||
const DEVICES = new Set(["/dev/null", "/dev/stdout", "/dev/stderr", "/dev/tty"]);
|
||||
const ALL_ARGUMENTS = new Set(["tee", "rm", "rmdir", "mkdir", "touch", "chmod", "chown", "truncate", "unlink", "shred"]);
|
||||
const LAST_ARGUMENT = new Set(["cp", "mv", "ln", "install", "rsync"]);
|
||||
|
||||
function realResolved(path: string): string {
|
||||
// Resolve symlinks through the deepest existing ancestor.
|
||||
let current = path;
|
||||
const rest: string[] = [];
|
||||
for (let depth = 0; depth < 64; depth++) {
|
||||
try { return join(realpathSync(current), ...rest.reverse()); } catch {
|
||||
const parent = dirname(current);
|
||||
if (parent === current) return path;
|
||||
rest.push(basename(current));
|
||||
current = parent;
|
||||
}
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
function expand(path: string, workspace: string, home: string): string | null {
|
||||
let value = path.trim().replace(/^['"]|['"]$/g, "");
|
||||
if (!value || DEVICES.has(value) || value.startsWith("/dev/fd/")) return null;
|
||||
value = value.replace(/^~(?=\/|$)/, home).replace(/^\$\{?HOME\}?(?=\/|$)/, home);
|
||||
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value) || value.includes("$")) return null;
|
||||
return realResolved(isAbsolute(value) ? resolve(value) : resolve(workspace, value));
|
||||
}
|
||||
|
||||
function outside(path: string, workspace: string): boolean {
|
||||
const inside = relative(workspace, path);
|
||||
return inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside);
|
||||
}
|
||||
|
||||
function tokens(segment: string): string[] {
|
||||
return (segment.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map(token => token.replace(/^['"]|['"]$/g, ""));
|
||||
}
|
||||
|
||||
/** Paths a shell command writes, as far as its text shows them. */
|
||||
export function shellWriteTargets(command: string): string[] {
|
||||
const targets: string[] = [];
|
||||
for (const segment of command.split(/;|&&|\|\||\|(?!\|)|\n/)) {
|
||||
const words = tokens(segment);
|
||||
for (let index = 0; index < words.length; index++) {
|
||||
const redirect = /^(?:\d|&)?>>?(.*)$/.exec(words[index]!);
|
||||
if (redirect) {
|
||||
const target = redirect[1] || words[index + 1];
|
||||
if (target) targets.push(target);
|
||||
}
|
||||
}
|
||||
const plain = words.filter(word => !/^(?:\d|&)?>>?/.test(word));
|
||||
let start = 0;
|
||||
while (start < plain.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(plain[start]!) || ["sudo", "env", "command", "exec"].includes(plain[start]!))) start++;
|
||||
const name = plain[start] ? basename(plain[start]!) : "";
|
||||
const args = plain.slice(start + 1).filter(word => !word.startsWith("-"));
|
||||
// Drop the source side of a redirect pair already counted above.
|
||||
const redirectTargets = new Set(words.flatMap((word, index) => /^(?:\d|&)?>>?$/.test(word) ? [words[index + 1]] : []));
|
||||
const operands = args.filter(word => !redirectTargets.has(word));
|
||||
if (ALL_ARGUMENTS.has(name)) targets.push(...operands);
|
||||
else if (LAST_ARGUMENT.has(name) && operands.length > 1) targets.push(operands.at(-1)!);
|
||||
else if (name === "sed" && plain.some(word => /^-i/.test(word)) && operands.length) targets.push(operands.at(-1)!);
|
||||
else if (name === "dd") targets.push(...args.flatMap(word => word.startsWith("of=") ? [word.slice(3)] : []));
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
/** The first path outside the task folder that a visible tool call would change, or null. */
|
||||
export function antigravityOutsideChange(update: unknown, workspace: string, home: string): string | null {
|
||||
const value = record(update);
|
||||
if (value.sessionUpdate !== "tool_call" && value.sessionUpdate !== "tool_call_update") return null;
|
||||
const kind = String(value.kind ?? "");
|
||||
const args = { ...record(value.rawInput), ...record(value.args) };
|
||||
const candidates: string[] = [];
|
||||
if (["edit", "delete", "move"].includes(kind)) {
|
||||
const locations = Array.isArray(value.locations) ? value.locations.map(record) : [];
|
||||
candidates.push(...locations.flatMap(location => typeof location.path === "string" ? [location.path] : []));
|
||||
candidates.push(...Object.entries(args).flatMap(([key, entry]) => PATH_KEY.test(key) && typeof entry === "string" ? [entry] : []));
|
||||
}
|
||||
if (kind === "execute" || /command|shell|terminal/i.test(String(value.name ?? ""))) {
|
||||
for (const [key, entry] of Object.entries(args)) {
|
||||
if (COMMAND_KEY.test(key) && typeof entry === "string") candidates.push(...shellWriteTargets(entry));
|
||||
}
|
||||
}
|
||||
let root = workspace;
|
||||
try { root = realpathSync(workspace); } catch { /* keep the given path */ }
|
||||
for (const candidate of candidates) {
|
||||
const resolved = expand(candidate, workspace, home);
|
||||
if (resolved && outside(resolved, root)) return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js";
|
||||
import { antigravitySwarmTools, antigravitySwarmArguments, antigravitySwarmLaunchEnvironment, antigravitySwarmRouteRefusal, isAntigravitySwarmRoute } from "./antigravity-swarm-route.js";
|
||||
import { antigravityRouteChangeRefusal, antigravitySwarmTools, antigravitySwarmArguments, antigravitySwarmLaunchEnvironment, antigravitySwarmRouteRefusal, isAntigravitySwarmRoute } from "./antigravity-swarm-route.js";
|
||||
import { createAcpxModeBinding, resolveAcpxProviderMode } from "./provider-mode.js";
|
||||
import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js";
|
||||
|
||||
@@ -49,6 +49,13 @@ describe("Antigravity swarm route selection", () => {
|
||||
expect(antigravitySwarmTools(tools).map(tool => tool.name)).toEqual(["paperclip_finish_task", "paperclip_block_task", "paperclip_read_task", "paperclip_call_assigned_tool", "paperclip_search_assigned_tools"]);
|
||||
});
|
||||
|
||||
it("lets the server open a fresh conversation when a saved one belongs to the other route", () => {
|
||||
expect(antigravityRouteChangeRefusal("antigravity", "swarm", undefined)).toMatchObject({ code: "ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE" });
|
||||
expect(antigravityRouteChangeRefusal("antigravity", undefined, "swarm")).toMatchObject({ code: "ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE" });
|
||||
expect(antigravityRouteChangeRefusal("antigravity", undefined, undefined)).toBeNull();
|
||||
expect(antigravityRouteChangeRefusal("cursor", "plan", undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it("routes a swarm turn to the CLI runtime instead of ACPX", async () => {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), "agy-route-")));
|
||||
roots.push(root);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { userInfo } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { AntigravitySavedStateIncompatibleError } from "./antigravity-admission.js";
|
||||
import { ANTIGRAVITY_CLI_DISTRIBUTION } from "./antigravity-cli-pins.js";
|
||||
import { resolveAntigravityCliLaunch, type AntigravityCliLaunchOptions } from "./antigravity-cli-installation.js";
|
||||
import { ANTIGRAVITY_CLI_STABLE_ENDPOINT, ANTIGRAVITY_SWARM_MODE, AntigravitySwarmError } from "./antigravity-swarm-guard.js";
|
||||
@@ -80,3 +81,15 @@ const DELEGATION_TOOL = /^paperclip_(?:create_(?:task|issue|subtask|agent)|hire|
|
||||
export function antigravitySwarmTools<T extends Readonly<Record<string, unknown>>>(tools: readonly T[]): T[] {
|
||||
return tools.filter(tool => !(typeof tool.name === "string" && DELEGATION_TOOL.test(tool.name)));
|
||||
}
|
||||
|
||||
/**
|
||||
* A saved conversation from the other Antigravity route (swarm on the CLI, or
|
||||
* an ordinary turn on the registry server) cannot be reopened by this one. The
|
||||
* typed refusal makes the server start a fresh conversation, so the task keeps
|
||||
* accepting messages after a swarm and a later /swarm starts cleanly.
|
||||
*/
|
||||
export function antigravityRouteChangeRefusal(agent: string, savedMode: string | undefined, requestedMode: string | undefined): AntigravitySavedStateIncompatibleError | null {
|
||||
if (agent !== "antigravity") return null;
|
||||
if (isAntigravitySwarmRoute(agent, savedMode) === isAntigravitySwarmRoute(agent, requestedMode)) return null;
|
||||
return new AntigravitySavedStateIncompatibleError("the saved conversation belongs to a different Antigravity route");
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { AcpRuntimeEvent } from "acpx/runtime";
|
||||
import { openAntigravitySwarmRuntime } from "./antigravity-swarm-runtime.js";
|
||||
import { openAntigravitySwarmRuntime, type AntigravitySwarmStage } from "./antigravity-swarm-runtime.js";
|
||||
import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js";
|
||||
import type { AcpxTerminalSessionFailure } from "./provider-failure.js";
|
||||
|
||||
@@ -132,8 +132,7 @@ describe("Antigravity CLI swarm runtime", () => {
|
||||
expect(clientMessages()).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses to resume a saved swarm session and extra tool servers it would have to drop", async () => {
|
||||
await expect(openAntigravitySwarmRuntime(setup("success", { restoringSession: true }).options)).rejects.toThrow(/fresh swarm/);
|
||||
it("refuses extra tool servers it would have to drop", async () => {
|
||||
const extra = setup("success");
|
||||
(extra.options as unknown as { mcpServers: unknown[] }).mcpServers.push({ name: "github", command: "/bin/x", args: [], env: {}, runnerOwned: false });
|
||||
await expect(openAntigravitySwarmRuntime(extra.options)).rejects.toThrow(/other tool servers/);
|
||||
@@ -158,9 +157,19 @@ describe("Antigravity CLI swarm runtime", () => {
|
||||
await runtime.close({ reason: "done" });
|
||||
});
|
||||
|
||||
it("stops the swarm when a visible edit targets a file outside the task folder", async () => {
|
||||
const run = await runTurn("outside-edit");
|
||||
expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE" } });
|
||||
it.each(["outside-edit", "dotdot-edit", "symlink-edit", "shell-escape"])("stops the swarm on a visible change outside the task folder: %s", async scenario => {
|
||||
const run = await runTurn(scenario);
|
||||
expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE", message: expect.stringMatching(/outside the task folder/) } });
|
||||
});
|
||||
|
||||
it("allows reading outside the task folder when the change lands inside it", async () => {
|
||||
const run = await runTurn("shell-read");
|
||||
expect(run.result).toMatchObject({ status: "completed" });
|
||||
});
|
||||
|
||||
it("treats a saved conversation as one a swarm cannot reopen, so the server starts a fresh one", async () => {
|
||||
await expect(openAntigravitySwarmRuntime(setup("success", { restoringSession: true }).options))
|
||||
.rejects.toMatchObject({ code: "ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE" });
|
||||
});
|
||||
|
||||
it("keeps a stable record identity while the CLI session id is per run", async () => {
|
||||
@@ -201,6 +210,39 @@ describe("Antigravity CLI swarm runtime", () => {
|
||||
expect(alive(worker)).toBe(false);
|
||||
});
|
||||
|
||||
const trackPid = (options: AcpxRuntimePortOpenOptions) => {
|
||||
const tracked = { pid: 0 };
|
||||
const spawnChild = options.command.spawn;
|
||||
(options.command as { spawn: typeof spawnChild }).spawn = (...args) => { const child = spawnChild(...args); tracked.pid = child.pid!; return child; };
|
||||
return tracked;
|
||||
};
|
||||
|
||||
it.each<AntigravitySwarmStage>(["spawned", "initialized", "session", "mode", "model"])("a Stop at %s ends admission, sends no prompt and stops the CLI", async stage => {
|
||||
const { options, clientMessages } = setup("success");
|
||||
const tracked = trackPid(options);
|
||||
const stop = new AbortController();
|
||||
await expect(openAntigravitySwarmRuntime({ ...options, signal: stop.signal } as AcpxRuntimePortOpenOptions,
|
||||
{ onStage: current => { if (current === stage) stop.abort(new Error("Stop")); } })).rejects.toThrow();
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
expect(clientMessages().some(message => message.method === "session/prompt")).toBe(false);
|
||||
expect(alive(tracked.pid)).toBe(false);
|
||||
});
|
||||
|
||||
it.each<[AntigravitySwarmStage, number]>([["snapshot", 0], ["helpers", 1]])("a Stop at %s starts no further billable prompt and stops the CLI", async (stage, prompts) => {
|
||||
const { options, clientMessages } = setup("live-helpers");
|
||||
const tracked = trackPid(options);
|
||||
let cancel: () => Promise<void> = async () => {};
|
||||
const runtime = await openAntigravitySwarmRuntime(options, { helperWaitTimeoutMs: 5_000, cancelGraceMs: 500,
|
||||
onStage: async current => { if (current === stage) await cancel(); } });
|
||||
const turn = runtime.startTurn({ text: "go", requestId: "r:1" });
|
||||
cancel = () => turn.cancel();
|
||||
for await (const _ of turn.events) { /* drain */ }
|
||||
expect(await turn.result).toMatchObject({ status: "cancelled" });
|
||||
await runtime.close({ reason: "Stop" });
|
||||
expect(clientMessages().filter(message => message.method === "session/prompt")).toHaveLength(prompts);
|
||||
expect(alive(tracked.pid)).toBe(false);
|
||||
});
|
||||
|
||||
it("runs at most one swarm per run", async () => {
|
||||
const { options } = setup("success");
|
||||
const runtime = await openAntigravitySwarmRuntime(options);
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import type { ChildProcess, ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { lstat, readdir } from "node:fs/promises";
|
||||
import { isAbsolute, join, relative, sep } from "node:path";
|
||||
import { join, relative, sep } from "node:path";
|
||||
import type { AcpRuntimeEvent, AcpRuntimeTurnResult } from "acpx/runtime";
|
||||
import { userInfo } from "node:os";
|
||||
import { AntigravitySavedStateIncompatibleError } from "./antigravity-admission.js";
|
||||
import { retireAntigravityProcess } from "./antigravity-process.js";
|
||||
import { antigravityOutsideChange } from "./antigravity-swarm-paths.js";
|
||||
import {
|
||||
ANTIGRAVITY_CLI_SESSION_MODE, ANTIGRAVITY_SWARM_MCP_SERVER, ANTIGRAVITY_SWARM_MODE, AntigravitySwarmError,
|
||||
antigravitySwarmWorkspaceEscape, classifyAntigravityRefusalText, createAntigravitySwarmGuard,
|
||||
@@ -43,11 +46,15 @@ const SKIPPED_DIRECTORIES = new Set([".git", "node_modules", ".venv", "__pycache
|
||||
const BLOCKED_TEXT = /timed out waiting for user response|permission check failed/i;
|
||||
export const ANTIGRAVITY_SWARM_PROCESS_LOST = "ACPX_PROVIDER_PROCESS_LOST";
|
||||
|
||||
export type AntigravitySwarmStage = "spawned" | "initialized" | "session" | "mode" | "model" | "snapshot" | "helpers";
|
||||
|
||||
export interface AntigravitySwarmRuntimeDependencies {
|
||||
helperWaitTimeoutMs?: number;
|
||||
requestTimeoutMs?: number;
|
||||
cancelGraceMs?: number;
|
||||
readbackTimeoutMs?: number;
|
||||
/** Test seam: runs at every await point between launch and settle. */
|
||||
onStage?: (stage: AntigravitySwarmStage) => void | Promise<void>;
|
||||
awaitProviderOwnership?: (child: ChildProcess) => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -211,23 +218,6 @@ function changedFiles(before: Map<string, string>, after: Map<string, string>):
|
||||
return [...changed, ...removed].sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* A visible edit, delete or move whose location is outside the task folder.
|
||||
* Only the coordinator's calls reach the client; helper calls are confined by
|
||||
* the CLI's auto mode and are not visible here.
|
||||
*/
|
||||
function outsideEdit(update: Json, workspace: string): string | null {
|
||||
if (update.sessionUpdate !== "tool_call" && update.sessionUpdate !== "tool_call_update") return null;
|
||||
if (!["edit", "delete", "move"].includes(String(update.kind))) return null;
|
||||
const locations = Array.isArray(update.locations) ? update.locations.map(record) : [];
|
||||
for (const location of locations) {
|
||||
if (typeof location.path !== "string" || !isAbsolute(location.path)) continue;
|
||||
const inside = relative(workspace, location.path);
|
||||
if (inside.startsWith("..") || isAbsolute(inside)) return location.path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function addUsage(total: Json | null, usage: unknown): Json | null {
|
||||
const value = record(usage);
|
||||
if (Object.keys(value).length === 0) return total;
|
||||
@@ -258,7 +248,9 @@ export async function openAntigravitySwarmRuntime(
|
||||
throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "Swarm is not available while planning: helpers change files, and a planning run must not. Approve the plan first, then send /swarm.");
|
||||
}
|
||||
if (options.restoringSession === true) {
|
||||
throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "A swarm cannot be resumed after an interruption. Retry starts a fresh swarm in the same task folder.");
|
||||
// Typed so the server starts a fresh conversation instead of showing Retry:
|
||||
// a swarm's helpers are gone after an interruption and reload resets mode and model.
|
||||
throw new AntigravitySavedStateIncompatibleError("a swarm always starts in a fresh session");
|
||||
}
|
||||
if (options.mcpServers.some(server => !(server.runnerOwned && server.name === ANTIGRAVITY_SWARM_MCP_SERVER))) {
|
||||
throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "Swarm is not available for this agent: it has other tool servers assigned, and a swarm uses only Paperclip's own tools.");
|
||||
@@ -268,6 +260,7 @@ export async function openAntigravitySwarmRuntime(
|
||||
const bridge = options.mcpServers.find((server): server is Extract<typeof server, { url: string }> =>
|
||||
"url" in server && server.runnerOwned && server.name === ANTIGRAVITY_SWARM_MCP_SERVER);
|
||||
if (!bridge) throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "Swarm needs Paperclip's own tools, which are not available for this run.");
|
||||
const home = options.launchEnvironment.HOME ?? userInfo().homedir;
|
||||
const instructions = [options.systemInstructions, ANTIGRAVITY_SWARM_INSTRUCTIONS].filter(Boolean).join("\n\n");
|
||||
const guard = createAntigravitySwarmGuard({ model, instructions, workspace: options.cwd });
|
||||
|
||||
@@ -313,13 +306,22 @@ export async function openAntigravitySwarmRuntime(
|
||||
|
||||
let sessionId: string;
|
||||
let receipt: AntigravitySwarmReceipt;
|
||||
// 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 });
|
||||
const stage = async (name: AntigravitySwarmStage) => {
|
||||
await dependencies.onStage?.(name);
|
||||
options.signal?.throwIfAborted();
|
||||
};
|
||||
try {
|
||||
await (dependencies.awaitProviderOwnership ?? awaitVerifiedAcpxProviderOwnership)(child);
|
||||
await stage("spawned");
|
||||
const initialized = await connection.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
||||
clientInfo: { name: "paperclip-runner", version: "1" },
|
||||
}, requestTimeoutMs);
|
||||
await stage("initialized");
|
||||
guard.initialize(initialized);
|
||||
const sessionParams: Json = {
|
||||
cwd: options.cwd,
|
||||
@@ -335,43 +337,54 @@ export async function openAntigravitySwarmRuntime(
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
await stage("session");
|
||||
sessionId = guard.sessionResult(opened);
|
||||
await connection.request("session/set_mode", { sessionId, modeId: ANTIGRAVITY_CLI_SESSION_MODE }, requestTimeoutMs);
|
||||
await waitForReadback(() => guard.bindMode());
|
||||
await stage("mode");
|
||||
await connection.request("session/set_model", { sessionId, modelId: model }, requestTimeoutMs);
|
||||
await waitForReadback(() => guard.bindModel());
|
||||
await stage("model");
|
||||
await connection.drain();
|
||||
guard.assertSwarmCommand();
|
||||
receipt = guard.receipt();
|
||||
if (protocolFailure) throw protocolFailure;
|
||||
options.signal?.throwIfAborted();
|
||||
} catch (error) {
|
||||
options.signal?.removeEventListener("abort", abortAdmission);
|
||||
const cleanup = retire();
|
||||
options.retainFailedAdmissionCleanup(cleanup);
|
||||
await cleanup.catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
|
||||
options.signal?.removeEventListener("abort", abortAdmission);
|
||||
const status: Json = { antigravitySwarmReceipt: receipt };
|
||||
let turns = 0;
|
||||
let active: { cancel(reason?: string): Promise<void>; result: Promise<AcpRuntimeTurnResult> } | null = null;
|
||||
let closed = false;
|
||||
|
||||
const runTurn = async (input: AcpxRuntimeTurnInput, events: EventQueue, started: () => void): Promise<AcpRuntimeTurnResult> => {
|
||||
// Stop is installed before the first await, so no later await can miss it.
|
||||
const listing = new AbortController();
|
||||
let cancelled = false;
|
||||
let wake: (() => void) | null = null;
|
||||
active!.cancel = async () => { cancelled = true; listing.abort(); connection.notify("session/cancel", { sessionId }); wake?.(); };
|
||||
const stopped = (): AcpRuntimeTurnResult => ({ status: "cancelled", stopReason: "cancelled" });
|
||||
if (protocolFailure) { started(); return failed(protocolFailure.code, protocolFailure.message); }
|
||||
if (turns++ > 0) {
|
||||
started();
|
||||
return failed("ANTIGRAVITY_SWARM_UNAVAILABLE", "At most one swarm runs per task run. Send another /swarm message to start a new one.");
|
||||
}
|
||||
const workspace = options.cwd;
|
||||
const listing = new AbortController();
|
||||
const before = await snapshotWorkspace(workspace, listing.signal);
|
||||
await dependencies.onStage?.("snapshot");
|
||||
if (cancelled) { started(); return stopped(); }
|
||||
const helpers = new Map<string, string>();
|
||||
let blocked = 0;
|
||||
let waitedAfterLastAdd = false;
|
||||
let transcript = "";
|
||||
let stop: AntigravitySwarmError | null = null;
|
||||
let wake: (() => void) | null = null;
|
||||
const halt = (error: AntigravitySwarmError) => { stop ??= error; connection.notify("session/cancel", { sessionId }); wake?.(); };
|
||||
events.push(line("setup", `Swarm started in the task folder with ${receipt.model}. Helper changes inside the task folder are approved automatically; anything else is blocked.`));
|
||||
|
||||
@@ -388,7 +401,7 @@ export async function openAntigravitySwarmRuntime(
|
||||
`Swarm stopped: helper ${escaped} was asked to work on its own copy of the task folder, which Paperclip does not allow.`));
|
||||
return;
|
||||
}
|
||||
const outside = outsideEdit(update, workspace);
|
||||
const outside = antigravityOutsideChange(update, workspace, home);
|
||||
if (outside) {
|
||||
halt(new AntigravitySwarmError("ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE",
|
||||
`Swarm stopped: it tried to change ${outside}, which is outside the task folder.`));
|
||||
@@ -430,8 +443,8 @@ export async function openAntigravitySwarmRuntime(
|
||||
};
|
||||
|
||||
let usage: Json | null = null;
|
||||
let cancelled = false;
|
||||
const prompt = async (text: string, timeoutMs: number | null): Promise<string> => {
|
||||
if (cancelled || stop) return "cancelled";
|
||||
const response = connection.request("session/prompt", { sessionId, prompt: [{ type: "text", text }] }, null);
|
||||
started();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -462,8 +475,6 @@ export async function openAntigravitySwarmRuntime(
|
||||
wake = null;
|
||||
}
|
||||
};
|
||||
active!.cancel = async () => { cancelled = true; listing.abort(); connection.notify("session/cancel", { sessionId }); wake?.(); };
|
||||
|
||||
const dispatch = input.dispatchJournal?.markReceived() ? input.dispatchJournal : null;
|
||||
try {
|
||||
dispatch?.markDispatched();
|
||||
@@ -471,11 +482,12 @@ export async function openAntigravitySwarmRuntime(
|
||||
if (stopReason === "end_turn" && !stop && !cancelled && helpers.size > 0 && !waitedAfterLastAdd && !classifyAntigravityRefusalText(transcript)) {
|
||||
events.push(line("wait", "Waiting for the helpers to finish"));
|
||||
transcript += "\n";
|
||||
await dependencies.onStage?.("helpers");
|
||||
stopReason = await prompt(HELPER_WAIT_PROMPT, dependencies.helperWaitTimeoutMs ?? DEFAULT_HELPER_WAIT_TIMEOUT_MS);
|
||||
}
|
||||
const halted = stop as AntigravitySwarmError | null;
|
||||
if (halted) return failed(halted.code, halted.message);
|
||||
if (cancelled || stopReason === "cancelled") return { status: "cancelled", stopReason: "cancelled" };
|
||||
if (cancelled || stopReason === "cancelled") return stopped();
|
||||
const refusal = classifyAntigravityRefusalText(transcript);
|
||||
if (refusal) {
|
||||
input.onTerminalSessionFailure?.({ category: refusal.kind === "authentication" ? "access" : "limit", title: refusal.message,
|
||||
|
||||
@@ -23,7 +23,7 @@ import { stageManagedGrokCredential } from "./grok-credentials.js";
|
||||
import { stageManagedAntigravityCredential } from "./antigravity-credentials.js";
|
||||
import { claudeNativeSkillPrompt } from "./native-skill-prompt.js";
|
||||
import { prepareStdioMcpBindings } from "../stdio-mcp.js";
|
||||
import { antigravitySwarmLaunchEnvironment, antigravitySwarmTools, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js";
|
||||
import { antigravityRouteChangeRefusal, antigravitySwarmLaunchEnvironment, antigravitySwarmTools, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js";
|
||||
|
||||
import type {
|
||||
AcpRuntimeOptions,
|
||||
@@ -435,6 +435,8 @@ export class AcpxRuntimeHost {
|
||||
dependencies.retainAdmissionCleanup,
|
||||
).catch(error => { throw recordAcpxAdmissionFailure(error, "binding"); });
|
||||
if (options.expectedIdentity) {
|
||||
const routeChange = antigravityRouteChangeRefusal(options.agent, options.expectedIdentity.mode, binding.mode);
|
||||
if (routeChange) throw routeChange;
|
||||
verifyExpectedAcpxIdentity(options.expectedIdentity, binding, null);
|
||||
}
|
||||
options.assertWorkspaceHeld?.();
|
||||
|
||||
@@ -17,7 +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
|
||||
// outside-edit the coordinator edits a file outside the workspace
|
||||
// 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
|
||||
// shell-escape the coordinator runs `printf E > /tmp/...` (the CLI's shell sandbox allows temp dirs)
|
||||
// shell-read the coordinator reads outside the workspace and copies into it (allowed)
|
||||
// cautious-brief a helper brief says "Do not create debug.log"; the run is correct
|
||||
// FAKE_AGY_LOG (optional) appends every client message, one JSON per line.
|
||||
import { spawn } from "node:child_process";
|
||||
@@ -52,7 +56,7 @@ const addWriters = async () => {
|
||||
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: scenario === "cautious-brief"
|
||||
? "Wait for writer-a and writer-b, then read a.txt and b.txt. Do not create debug.log or any other file." : "Wait for writer-a and writer-b, then read a.txt and b.txt and report." });
|
||||
? "Wait for writer-a and writer-b, then read a.txt and b.txt. Do not create debug.log or any other file. Write docs.google.com links only if v1.2 asks." : "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 = () => {
|
||||
@@ -75,8 +79,18 @@ async function prompt(id, params) {
|
||||
update(state.sessionId, { sessionUpdate: "session_info_update", title: "Swarm" });
|
||||
if (scenario === "refusal") { say("\n⚠ agent executor error: Error 402 Your prepayment credits are depleted. Status: RESOURCE_EXHAUSTED\n"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); }
|
||||
if (scenario === "quota") { say("\n⚠ RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).\n"); return write({ jsonrpc: "2.0", id, result: { stopReason: "end_turn" } }); }
|
||||
if (scenario === "outside-edit") {
|
||||
update(state.sessionId, { sessionUpdate: "tool_call", toolCallId: "call_out", name: "write_file", kind: "edit", status: "in_progress", title: "Write /etc/elsewhere.txt", locations: [{ path: "/etc/elsewhere.txt" }] });
|
||||
const outside = {
|
||||
"outside-edit": { name: "write_file", kind: "edit", title: "Write /etc/elsewhere.txt", locations: [{ path: "/etc/elsewhere.txt" }] },
|
||||
"dotdot-edit": { name: "write_file", kind: "edit", title: "Write file", args: { TargetFile: `${state.cwd}/../escape.txt` } },
|
||||
"symlink-edit": { name: "write_file", kind: "edit", title: "Write file", locations: [{ path: `${state.cwd}/link/x.txt` }] },
|
||||
"shell-escape": { name: "run_command", kind: "execute", title: "Run command", args: { CommandLine: "printf E > /tmp/agy-escape-e.txt" } },
|
||||
}[scenario];
|
||||
if (scenario === "symlink-edit") (await import("node:fs")).symlinkSync("/etc", `${state.cwd}/link`);
|
||||
if (scenario === "shell-read") {
|
||||
await tool("run_command", { CommandLine: "cat /etc/hosts > ./hosts-copy.txt && cp /etc/hosts ./hosts2.txt" });
|
||||
}
|
||||
if (outside) {
|
||||
update(state.sessionId, { sessionUpdate: "tool_call", toolCallId: "call_out", status: "in_progress", rawInput: outside.args, ...outside });
|
||||
if (!state.cancelled) await new Promise(resolve => { state.cancel = resolve; });
|
||||
return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } });
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user