diff --git a/doc/plans/2026-11-22-antigravity-qualification.md b/doc/plans/2026-11-22-antigravity-qualification.md index 15c0d749fff..ec1f7c659ce 100644 --- a/doc/plans/2026-11-22-antigravity-qualification.md +++ b/doc/plans/2026-11-22-antigravity-qualification.md @@ -126,7 +126,7 @@ evidence that Google serves inference for that model on that credential. | Route | State | Needs | | --- | --- | --- | | API key (exact-model admission in patch `1.5.2-paperclip.2`) | All four Neon levels admitted prompt-free with exact receipts on macOS and Linux x64; no `AGY_ACP_DEFAULT_MODEL` needed. No Neon prompt has completed: the only key is free tier (Neon quota 0) | A paid Gemini key, then one accepted prompt per level | -| Personal Google sign-in (subscription catalog) | Local macOS sign-in journey proven on 1.4.3 (October); not re-run on 1.5.2; never offered in a cloud sandbox | An entitled account and the attended sign-in journey on 1.5.2 | +| Personal Google sign-in (subscription catalog) | Local macOS sign-in journey proven on 1.4.3 (October). On 2026-11-25 (local darwin-arm64, subscription sign-in): ordinary tasks completed on Gemini 4 Neon at all four levels and a `/swarm` completed on Neon (Low), each with requested = effective model (see the acceptance ledger). Never offered in a cloud sandbox | The same in a cloud sandbox | | Agent Platform (Vertex/ADC) | Advertised by the server, never exercised here | A Google Cloud project and service credentials | ## Workstreams @@ -174,8 +174,8 @@ API-key route or Daytona remain NOT RUN, not failed and not passed. | Model admission | Every model ID admitted by exact-model admission, prompt-free | Passed: all 28 IDs (14 Gemini 3, 14 Gemini 4 including Neon at four levels) get exact receipts under an API key on both platforms, without `AGY_ACP_DEFAULT_MODEL` | | Kill and resume | Native process killed between turns; a new process resumes the session | Passed prompt-free on macOS and Linux x64 with exact receipts. With completed prompts (2026-11-23, local, sign-in): native process kill recovered and the task finished. No live `session/load` call was observed in the logs | | Launch cost | Run start to native initialize | Sealed verified store: 1.46 s (macOS) / 1.74 s (Linux x64), from 3.45 / 3.65 s. Measured before the launcher regained its streamed executable hash (below); that hash measured ~60 ms for the 179 MB macOS server and is not yet re-measured for the ~722 MB Linux launcher | -| Model lineup inference | Per model/level: one accepted prompt | Partial: `gemini-3.8-flash-low` accepted prompts over Google sign-in (local). The signed-in catalog listed only three Gemini 3.8 Flash levels, so the rest of the lineup is NOT RUN; the free API key still completes no prompt | -| Neon inference | Real task on `gemini-4-neon-*`, each level acknowledged | NOT RUN (free-tier Neon quota is 0; the signed-in catalog does not list Neon) | +| Model lineup inference | Per model/level: one accepted prompt | Partial: `gemini-3.8-flash-low` (2026-11-23) and Gemini 4 Neon at four levels (2026-11-25, below) accepted prompts over Google sign-in (local). The rest of the lineup and the lineup suites are NOT RUN; the free API key still completes no prompt | +| Neon inference | Real task on `gemini-4-neon-*`, each level acknowledged | Passed locally (darwin-arm64, Google subscription sign-in, commit 438ae60922, 2026-11-25): one ordinary task per level, each Done in one run with requested = effective model and no usage limit. Low 65.9 s; medium 50.7 s (30,978 in / 4,406 out tokens); high 53.8 s (31,176 / 4,711); xhigh 68.9 s (46,152 / 5,499). API-key route and cloud sandbox NOT RUN | | Ordinary task | File bytes, artifact, accepted result, Done after reload, local and Daytona | Local darwin-arm64 passed on 1.5.2 (sign-in, 2026-11-23), including a follow-up on the same task. Daytona NOT RUN | | Scoped tools | Semantic and MCP round trip; wrong-company and stale authority denied | NOT RUN | | Questions and permissions | Native identity, one continuation, denial holds | Question passed locally (asked, answered, task finished). Permissions NOT RUN | @@ -184,7 +184,7 @@ API-key route or Daytona remain NOT RUN, not failed and not passed. | Qualification suite | All 24 `antigravity-qualification` cells, local and Daytona | NOT RUN | | Evals under the native Runner | Applicable Product E2E and chat cases run with Antigravity; numbers recorded | NOT RUN | | Image pull and startup time | Daytona image with the Linux closure, measured cold | NOT RUN | -| Swarm (`/swarm`) | Native swarm starts from a task | Built on the Antigravity CLI route behind the off-by-default flag; fake-CLI tests pass. Live local proof pending (recipe below). The registry server 1.5.2 still has no swarm | +| Swarm (`/swarm`) | Native swarm starts from a task | Passed locally on the Antigravity CLI route behind the off-by-default flag (darwin-arm64, 2026-11-25): Gemini 3.8 Flash (Low) and Gemini 4 Neon (Low). See "/swarm live proof" below for what is and is not proven. Linux and cloud sandbox NOT RUN. The registry server 1.5.2 still has no swarm | ### First live tasks (2026-11-23, local, Google sign-in) @@ -383,8 +383,9 @@ this computer, and the experimental flag on. Then, on a task for that agent: containing B; a verifier checks both`: native swarm, both files in the task folder, task Done, activity log names the swarm. 2. The same, then Stop mid-swarm: run cancelled, no `agy` process left. -3. The same, then kill the `agy` process mid-swarm, then Retry: a fresh swarm - runs in the same folder; nothing posted twice. +3. The same, then kill the `agy` process mid-swarm: Paperclip recovers on its + own with a fresh swarm in the same folder (at most three attempts per + request); nothing posted twice. Retry starts one when recovery has stopped. 4. An ordinary follow-up comment after a swarm: runs normally (fresh session). 5. Flag off, `/swarm ...`: the composer shows "Swarm is not turned on ..." and nothing is posted or run. @@ -392,4 +393,20 @@ this computer, and the experimental flag on. Then, on a task for that agent: | Gate | Result | | --- | --- | | Unit and fake-CLI tests (driver, guard, paths, route, server, composer) | Passed | -| Live steps 1-5 | NOT RUN (pending) | +| 1. Swarm, Gemini 3.8 Flash (Low), Antigravity CLI 1.5.15, Google's default channel | Passed: a real swarm (two helpers and a verifier) Done in 49.5 s, files correct, nothing posted twice | +| 1. Swarm, Gemini 4 Neon (Low) | Passed: Done in 115 s (92,378 in / 6,733 out tokens), requested = effective model | +| 2. Stop with 7 helpers active (Flash) | Passed: every CLI and helper process gone in 0.7 s, no re-run. Gap: the stopped run recorded no usage (fixed in this pull request) | +| 3. Kill the CLI process mid-swarm (Flash) | Passed: recovered automatically with a fresh swarm, Done. Gaps: no usage recorded for the killed run, and the failure text asked for Retry while recovery continued on its own (both fixed in this pull request) | +| 4. Ordinary follow-up after a swarm | Passed: 41 s (Flash), 105 s (Neon). A completed swarm was not run again (checked 10 minutes later) | +| Refusals with the flag on | Passed: an empty request, Plan mode and Ask mode answer 422 in plain words and post nothing; a quoted `/swarm` runs as ordinary text | +| Thread text | Gaps found and fixed in this pull request: the CLI's terminal hint ("Run /swarm board …") and a stray "." reached the thread; replies linked task-folder files by absolute local `file://` path (also on ordinary Antigravity runs); the coordinator named Paperclip's swarm rules. The settings receipt now reaches the run record as a provider notice | +| 5. Flag off | NOT RUN live (unit tests only) | + +Not proven live: Stop or kill on a Neon swarm; pressing Retry on a swarm +(recovery never needed it); typing `/swarm` in the browser composer (the live +runs used the comments API with the composer's structured request); the Linux +and cloud sandbox routes; the paid qualification cells and lineup suites. The +profile stays **pending** until an operator grants the flip. + +Facts above: local darwin-arm64 instance at commit 438ae60922, 2026-11-25, +Google subscription sign-in. diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-activity.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-activity.ts new file mode 100644 index 00000000000..c895acd1625 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-activity.ts @@ -0,0 +1,47 @@ +import type { CanonicalProviderEvent } from "../../provider-events.js"; +import { antigravitySwarmChannelLabel } from "./antigravity-swarm-route.js"; +import type { AcpxActivityAdapter } from "./profile-activity.js"; + +const record = (value: unknown): Record => + value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +const text = (value: unknown): string | null => typeof value === "string" && value.trim() ? value.trim().slice(0, 240) : null; + +/** + * The swarm's settings receipt (antigravity-swarm-runtime.ts `antigravitySwarmReceipt`) + * as a run-record provider notice, through the same post-turn hook as Cursor's + * native receipt. Only diagnostics leave: the requested and confirmed model, + * mode, channel, CLI version and whether the CLI's own Google sign-in is the + * connection account. No account, path, session id or instruction text. + * Bound to this turn's request, so a receipt is never reported twice. + */ +export function antigravitySwarmReceiptNotice(before: unknown, after: unknown, requestId: string, itemId: string): CanonicalProviderEvent | null { + const current = record(after), prior = record(before); + if (current.lastRequestId !== requestId || prior.lastRequestId === requestId) return null; + const receipt = record(current.antigravitySwarmReceipt); + const requested = text(receipt.model), confirmed = text(receipt.modelName), version = text(receipt.agentVersion); + if (!requested || !confirmed || !version) return null; + const channel = receipt.channel === "stable" ? "stable" : "provider_default"; + const match = ["matches", "does_not_match"].includes(String(receipt.cliAccountMatchesConnection)) ? String(receipt.cliAccountMatchesConnection) : "unknown"; + const reason = match === "unknown" && ["no_connection_account", "cli_sign_in_not_found"].includes(String(receipt.cliAccountUnknownReason)) + ? String(receipt.cliAccountUnknownReason) : null; + const details = [ + { name: "Requested model", value: requested }, + { name: "Confirmed model", value: confirmed }, + ...(text(receipt.thoughtLevel) ? [{ name: "Thinking level", value: text(receipt.thoughtLevel)! }] : []), + { name: "Mode", value: text(receipt.mode) ?? "unknown" }, + { name: "Channel", value: channel }, + { name: "Antigravity CLI version", value: version }, + { name: "CLI account matches connection", value: match }, + ...(reason ? [{ name: "Account unknown reason", value: reason }] : []), + ]; + return { + eventType: "provider.notice.recorded", itemId, + payload: { schema: "paperclip.provider.notice.v1", noticeId: itemId, severity: "info", category: "antigravity_swarm_receipt", scope: "turn", + recoverable: true, userActionable: false, + summary: `Swarm ran with ${confirmed} on ${antigravitySwarmChannelLabel(channel)} (Antigravity CLI ${version}).`, details }, + }; +} + +export const antigravityActivityAdapter: AcpxActivityAdapter = Object.freeze({ + usageNotice: (before, after, requestId, turnId) => antigravitySwarmReceiptNotice(before, after, requestId, `${turnId}:antigravity-swarm-receipt`), +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-local-links.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-local-links.test.ts new file mode 100644 index 00000000000..1e131e8e908 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-local-links.test.ts @@ -0,0 +1,89 @@ +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import type { AcpRuntimeEvent } from "acpx/runtime"; +import { antigravityLocalLinkEvents, createAntigravityLocalLinkFilter } from "./antigravity-local-links.js"; + +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); +function workspace() { + const root = realpathSync(mkdtempSync(join(tmpdir(), "agy-links-"))); + roots.push(root); + const task = join(root, "isolated-workspaces", "bc0f4aed-5834-4e40-9cff-3851d2d27acb", "724073da-4387-4c54-bfde-254cde2b9a70"); + mkdirSync(task, { recursive: true }); + return { root, task }; +} +const pieces = (text: string, size: number) => Array.from({ length: Math.ceil(text.length / size) }, (_, index) => text.slice(index * size, (index + 1) * size)); +const through = (workspaces: string[], chunks: string[]) => { + const filter = createAntigravityLocalLinkFilter(workspaces); + return chunks.map(chunk => filter.push(chunk)).join("") + filter.flush(); +}; + +describe("Antigravity replies never link local task-folder paths", () => { + it("ordinary route (live run7 step 2): the file link becomes its task-folder name, the deliverable link stays", () => { + const { task } = workspace(); + const reply = `I have appended a new line with the word \`gamma\` to [a.txt](file://${task}/a.txt).\n\n### Verification\nThe contents of [a.txt](file://${task}/a.txt) are now:\n\`\`\`text\nalpha\ngamma\n\`\`\`\n\n### Deliverable:\n- [a.txt](/api/attachments/e1ba2d40-727c-468e-ad38-3df96ac11692/content)`; + const expected = "I have appended a new line with the word `gamma` to `a.txt`.\n\n### Verification\nThe contents of `a.txt` are now:\n```text\nalpha\ngamma\n```\n\n### Deliverable:\n- [a.txt](/api/attachments/e1ba2d40-727c-468e-ad38-3df96ac11692/content)"; + for (const size of [1, 3, 7, 16, 64, reply.length]) expect(through([task], pieces(reply, size))).toBe(expected); + }); + + it("swarm route (live run7 step 1): the same, across the CLI's own chunk boundaries", () => { + const { task } = workspace(); + const local = task.slice(0, 40), rest = task.slice(40); + const chunks = ["1. **`creator-a`** created [", `a.txt](file://${local}`, `${rest}/a.txt) with the content \`alpha\`.\n2. **`, "`creator-b`** created [b.txt", `](file://${task}/b`, ".txt) with the content `beta`.\n"]; + expect(through([task], chunks)).toBe("1. **`creator-a`** created `a.txt` with the content `alpha`.\n2. **`creator-b`** created `b.txt` with the content `beta`.\n"); + }); + + it("keeps a descriptive label beside the path, drops other local file links to their label, and strips bare local prefixes", () => { + const { root, task } = workspace(); + expect(through([task], [`See [the notes](file://${task}/notes/plan.md#L3).`])).toBe("See the notes (`notes/plan.md`)."); + expect(through([task], [`See [config](file://${root}/elsewhere/config.json).`])).toBe("See config."); + expect(through([task], [`Wrote file://${task}/b.txt and ${task}/c.txt.`])).toBe("Wrote `b.txt` and c.txt."); + expect(through([task], [`It ran in ${task}.`])).toBe("It ran in the task folder."); + expect(through([task], [`It ran in ${task}`])).toBe("It ran in the task folder"); + expect(through([task], [`It ran in ${task}/.`])).toBe("It ran in the task folder."); + expect(through([task], [`It ran in ${task}/`])).toBe("It ran in the task folder"); + expect(through([task], [`Wrote ${task}.`])).toBe("Wrote the task folder."); + for (const [reply, expected] of [ + [`Folder: **${task}**.`, "Folder: **the task folder**."], [`保存在 ${task}。`, "保存在 the task folder。"], + [`Wrote ${task}—done.`, "Wrote the task folder—done."], [`Saved in ${task}…`, "Saved in the task folder…"], + [`In ${task},and more`, "In the task folder,and more"], [`Copy ${task}.bak/x and ${task}-old`, `Copy ${task}.bak/x and ${task}-old`], + ]) for (let at = 0; at <= reply.length; at++) expect(through([task], [reply.slice(0, at), reply.slice(at)])).toBe(expected); + // Child names that start with a letter outside ASCII or with punctuation stay whole, whole or split. + for (const name of ["报告.txt", "(notes).md", "_draft.md", ".env.example"]) { + const reply = `Wrote ${task}/${name} now.`; + for (let at = 0; at <= reply.length; at++) expect(through([task], [reply.slice(0, at), reply.slice(at)])).toBe(`Wrote ${name} now.`); + } + expect(through([task], [`Wrote file://${task}/a.txt. Then file://${task}/b.txt, and file://${root}/x.json!`])).toBe("Wrote `a.txt`. Then `b.txt`, and `x.json`!"); + expect(through([task], ["Open [docs](https://example.test/a) or [run](/ANT/issues/ANT-1)."])).toBe("Open [docs](https://example.test/a) or [run](/ANT/issues/ANT-1)."); + }); + + it("strips a bare task-folder path wherever the reply is split", () => { + const { task } = workspace(); + const reply = `Wrote ${task}/notes/a.txt and ${task}/b.txt.`; + for (let at = 0; at <= reply.length; at++) expect(through([task], [reply.slice(0, at), reply.slice(at)])).toBe("Wrote notes/a.txt and b.txt."); + }); + + it("matches the task folder through a link to it", () => { + const { root, task } = workspace(); + const linked = join(root, "linked-task"); + symlinkSync(task, linked); + expect(through([linked], [`[a.txt](file://${task}/a.txt)`])).toBe("`a.txt`"); + }); + + it("keeps event order: held reply text is released before the next step", async () => { + const { task } = workspace(); + const source: AcpRuntimeEvent[] = [ + { type: "text_delta", text: "Created [a.txt](file://", stream: "output", tag: "agent_message_chunk" }, + { type: "tool_call", toolCallId: "t1", text: "Ran a tool", title: "Ran a tool", tag: "tool_call", status: "completed" }, + { type: "text_delta", text: "Thinking about file://", stream: "thought", tag: "agent_thought_chunk" }, + { type: "text_delta", text: `${task}/a.txt) done.`, stream: "output", tag: "agent_message_chunk" }, + ]; + const out: AcpRuntimeEvent[] = []; + for await (const event of antigravityLocalLinkEvents((async function* () { yield* source; })(), [task])) out.push(event); + expect(out.map(event => event.type === "text_delta" ? `${event.stream}:${event.text}` : event.type)).toEqual([ + "output:Created ", "output:[a.txt](file://", "tool_call", "thought:Thinking about file://", `output:${task}/a.txt) done.`.replace(`${task}/`, ""), + ]); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-local-links.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-local-links.ts new file mode 100644 index 00000000000..da6e618bed9 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-local-links.ts @@ -0,0 +1,135 @@ +import { realpathSync } from "node:fs"; +import { basename, isAbsolute, resolve, sep } from "node:path"; +import type { AcpRuntimeEvent } from "acpx/runtime"; +import { localTarget, workspaceRelativePath } from "../../live/workspace-file-reference.js"; + +/** + * Google Antigravity (the registry ACP server and the CLI's swarm alike) links + * the files it wrote as absolute local `file:///…///a.txt` URLs. + * The person reads that reply in the task thread, where a local path and its + * ids mean nothing and a file:// link opens nothing. Before the reply leaves + * the Runner, a link to a file in the task folder becomes its folder-relative + * path in code (`notes/a.txt`; the thread opens a nested path as a task-folder + * file, while a root-level name stays plain text beside its deliverable link), + * any other file:// link keeps only its label, and a bare task-folder path + * loses its local prefix. Other text, including `/api/...` links, is unchanged. + */ +const LINK = /\[([^\]\n]{0,300})\]\((<[^>\n]+>|[^)\s]+)\)/g; +const FILE_URL = /file:\/\/[^\s)\]>"'`]+/g; +const UNFINISHED_LINK = /^\[[^\]\n]{0,300}(?:\]\((?:<[^>\n]*|[^)\s]*))?\]?$/; +const UNFINISHED_FILE_URL = /(?:f(?:i(?:l(?:e(?::(?:\/(?:\/[^\s)\]>"'`]*)?)?)?)?)?)?)$/; +const HOLD_MAX = 4_096; + +/** A file:// or absolute link target, decoded with the shared workspace file-reference rules; null for anything else. */ +function decodeTarget(raw: string): { path: string; fileUrl: boolean } | null { + const fileUrl = /^ value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +const code = (path: string) => `\`${path}\``; + +export function neutralizeAntigravityLocalLinks(text: string, roots: readonly string[]): string { + let value = text.replace(LINK, (whole, label: string, target: string) => { + const decoded = decodeTarget(target); + if (!decoded) return whole; + const path = insideRoot(roots, decoded.path); + if (path === null) return decoded.fileUrl ? label : whole; + const name = label.replace(/^`|`$/g, "").trim(); + return name === path || name === basename(path) || !name ? code(path) : `${label} (${code(path)})`; + }); + value = value.replace(FILE_URL, match => { + // Sentence punctuation after a bare URL belongs to the sentence, not the file name. + const url = match.replace(/[.,;:!?]+$/, ""); + const decoded = decodeTarget(url); + if (!decoded) return match; + return code(insideRoot(roots, decoded.path) ?? basename(decoded.path)) + match.slice(url.length); + }); + for (const root of roots) { + // The task folder itself: not followed by more of its own name, or by a slash and a child name + // (a trailing slash counts only before the end, a break, or closing punctuation). Children are handled next. + value = value.replace(new RegExp(`${escapeRegExp(root)}(?:/(?=$|\\s|[${CLOSING}]+(?:\\s|$))|(?![\\w/-]|\\.\\w))`, "g"), "the task folder"); + value = value.split(`${root}/`).join(""); + } + return value; +} + +/** Where text that could still become a local link or path starts, or -1. */ +function holdFrom(value: string, roots: readonly string[]): number { + const floor = Math.max(0, value.length - HOLD_MAX); + let start = -1; + const keep = (index: number) => { if (index >= floor && (start < 0 || index < start)) start = index; }; + const open = value.lastIndexOf("["); + if (open >= 0 && UNFINISHED_LINK.test(value.slice(open))) keep(open); + const url = UNFINISHED_FILE_URL.exec(value); + if (url && url[0]) keep(url.index); + for (const root of roots) { + const prefix = `${root}/`; + // Held down to a lone "/", and also when complete: what follows decides between a child path and the folder itself. + for (let length = Math.min(prefix.length, value.length); length >= 1; length--) { + if (value.endsWith(prefix.slice(0, length))) { keep(value.length - length); break; } + } + // The folder then punctuation at the very end: a sentence end, or the start of a dot-file name. + const ending = new RegExp(`${escapeRegExp(root)}/?[${CLOSING}]+$`).exec(value); + if (ending) keep(ending.index); + } + return start; +} + +/** `workspaces`: the task folder as configured and as the provider was started in; each is also matched by its real path. */ +export function createAntigravityLocalLinkFilter(workspaces: readonly string[]): { push(text: string): string; flush(): string } { + const roots: string[] = []; + for (const workspace of workspaces) { + for (const root of [resolve(workspace), (() => { try { return realpathSync(workspace); } catch { return null; } })()]) { + if (root && root !== sep && !roots.includes(root)) roots.push(root); + } + } + let held = ""; + return { + push(text) { + const value = held + text; + const start = holdFrom(value, roots); + held = start < 0 ? "" : value.slice(start); + return neutralizeAntigravityLocalLinks(start < 0 ? value : value.slice(0, start), roots); + }, + flush() { + const value = neutralizeAntigravityLocalLinks(held, roots); + held = ""; + return value; + }, + }; +} + +/** The turn's events with every assistant reply chunk passed through the filter, in order. */ +export async function* antigravityLocalLinkEvents(events: AsyncIterable, workspaces: readonly string[]): AsyncIterable { + const filter = createAntigravityLocalLinkFilter(workspaces); + let template: Extract | null = null; + const release = function* (): Generator { + const held = filter.flush(); + if (held && template) yield { ...template, text: held }; + }; + for await (const event of events) { + if (event.type === "text_delta" && event.stream !== "thought") { + template = event; + const text = filter.push(event.text); + if (text) yield { ...event, text }; + continue; + } + yield* release(); + yield event; + } + yield* release(); +} diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts index ba377e1eb47..3ea3b82c3ad 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { antigravitySwarmEvent, stripAntigravityTerminalHints } from "./antigravity-swarm-presentation.js"; +import { antigravitySwarmEvent, createAntigravityTerminalHintFilter, stripAntigravityTerminalHints } from "./antigravity-swarm-presentation.js"; const WORKSPACE = "/work/task"; const tool = (name: string, args: Record, sessionUpdate = "tool_call", status = "in_progress") => @@ -33,4 +33,27 @@ describe("Antigravity swarm activity, in plain language", () => { expect(stripAntigravityTerminalHints("Launched.\n\nRun /swarm board (default shortcut alt+s) to open the live board.")) .toBe("Launched.\n"); }); + + const filtered = (chunks: string[]) => { + const filter = createAntigravityTerminalHintFilter(); + return chunks.map(chunk => filter.push(chunk)).join("") + filter.flush(); + }; + + it("drops a terminal hint the CLI streams in pieces, with its trailing period (live run7)", () => { + // ANT-35: the hint split after "(". + expect(filtered(["- `verifier`: Checks all five files.\n\nRun /swarm board (", "default shortcut alt+s) to open the live board."])) + .toBe("- `verifier`: Checks all five files.\n"); + // ANT-31: the period arrived alone, and left a stray "." line. + expect(filtered([" once notified by the creators.\n", "Run /swarm board (default shortcut alt+s) to open the live board", ".", "\n\nThe task has been completed"])) + .toBe(" once notified by the creators.\n\nThe task has been completed"); + }); + + it("drops the hint wherever the CLI splits it, and changes nothing else", () => { + const text = "Launched.\n\nRun /swarm board (default shortcut alt+s) to open the live board.\n\nDone. Run the tests (npm test)."; + for (let size = 1; size <= 12; size++) { + const chunks = Array.from({ length: Math.ceil(text.length / size) }, (_, index) => text.slice(index * size, (index + 1) * size)); + expect(filtered(chunks)).toBe("Launched.\n\n\nDone. Run the tests (npm test)."); + } + expect(filtered(["Run", " the build. R", "eady."])).toBe("Run the build. Ready."); + }); }); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts index f66d3dec49a..e67fe1d9f14 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-presentation.ts @@ -17,6 +17,49 @@ export function stripAntigravityTerminalHints(text: string): string { return text.replace(TERMINAL_HINT, ""); } +const HINT_PREFIX = "Run /swarm board (default shortcut "; +const HINT_SUFFIX = ") to open the live board."; +const HINT_SHORTCUT_MAX = 40; +const HINT_MAX = 1 + HINT_PREFIX.length + HINT_SHORTCUT_MAX + HINT_SUFFIX.length; + +/** Whether `tail` (after one optional line break) is the start of a terminal hint that more text could complete. */ +function unfinishedHint(tail: string): boolean { + const body = tail.startsWith("\n") ? tail.slice(1) : tail; + if (body.length <= HINT_PREFIX.length) return HINT_PREFIX.startsWith(body); + if (!body.startsWith(HINT_PREFIX)) return false; + const rest = body.slice(HINT_PREFIX.length); + const close = rest.indexOf(")"); + if (close < 0) return rest.length <= HINT_SHORTCUT_MAX && !rest.includes("\n"); + // A complete hint is held too, until the next text shows whether its closing period follows. + return close <= HINT_SHORTCUT_MAX && HINT_SUFFIX.startsWith(rest.slice(close)); +} + +/** + * The CLI streams its terminal hint in pieces (live: `Run /swarm board (`, then + * `default shortcut alt+s) to open the live board`, then `.`), so stripping each + * chunk alone misses it and leaves a stray period. Text that could still become + * a hint is held back until the hint completes or is ruled out. + */ +export function createAntigravityTerminalHintFilter(): { push(text: string): string; flush(): string } { + let held = ""; + return { + push(text) { + const value = held + text; + let start = -1; + for (let index = Math.max(0, value.length - HINT_MAX); index < value.length; index++) { + if ((value[index] === "\n" || value[index] === "R") && unfinishedHint(value.slice(index))) { start = index; break; } + } + held = start < 0 ? "" : value.slice(start); + return stripAntigravityTerminalHints(start < 0 ? value : value.slice(0, start)); + }, + flush() { + const value = stripAntigravityTerminalHints(held); + held = ""; + return value; + }, + }; +} + 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(); @@ -52,7 +95,8 @@ export function antigravitySwarmEvent(update: unknown, workspace: string): AcpRu 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; + // Raw: the hint can span chunks, so the runtime's streaming filter strips it (createAntigravityTerminalHintFilter). + const text = content.text; if (!text) return null; return { type: "text_delta", text, stream: kind === "agent_thought_chunk" ? "thought" : "output", tag: kind }; } diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts index 176cb7ee5d0..4dbe433b347 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts @@ -4,7 +4,9 @@ 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, antigravitySwarmPaperclipTool, openAntigravitySwarmRuntime, type AntigravitySwarmStage } from "./antigravity-swarm-runtime.js"; +import { ANTIGRAVITY_SWARM_INSTRUCTIONS, antigravityCliAccountMatch, antigravitySwarmPaperclipTool, openAntigravitySwarmRuntime, type AntigravitySwarmStage } from "./antigravity-swarm-runtime.js"; +import { acpxProfileActivity } from "./profile-activity.js"; +import { persistedAcpxTurnUsage } from "./usage-accounting.js"; import { antigravityAccountDigest } from "./antigravity-swarm-route.js"; import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; import { acpxTerminalResult, type AcpxTerminalSessionFailure } from "./provider-failure.js"; @@ -144,7 +146,9 @@ describe("Antigravity CLI swarm runtime", () => { ])); expect(run.titles).toContainEqual(expect.stringMatching(/^Swarm started in the task folder with Gemini 3\.8 Flash \(Low\) on Google's default channel \(Antigravity CLI 1\.5\.15\)\. /)); expect(run.titles.some(title => /approved automatically/.test(title))).toBe(true); - expect(run.text).not.toContain("/swarm board"); + // The CLI streams its terminal hint in pieces (live run7); none of it, nor its period, reaches the thread. + expect(run.text).not.toMatch(/swarm board|shortcut|live board/); + expect(run.text).toBe("I have configured and launched the swarm.\n\n\nThe swarm has completed its work. a.txt contains A and b.txt contains B."); expect(run.clientMessages().find(message => message.method === "session/prompt").params.prompt[0].text).toMatch(/^\/swarm /); expect(run.status.terminalPromptUsage).toMatchObject({ requestId: "run-1:turn-1", event: { breakdown: { totalTokens: 133035 } } }); expect(run.titles.some(title => /includes the helpers/.test(title))).toBe(true); @@ -196,6 +200,8 @@ describe("Antigravity CLI swarm runtime", () => { it("fails with a clear timeout when helpers never finish", async () => { const run = await runTurn("hang-helpers", { helperWaitTimeoutMs: 200 }); expect(run.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_SWARM_HELPERS_TIMEOUT" } }); + // The wait prompt is never answered; its streamed count may be session-wide, so it raises counters, never adds (not 133,035 + 140,000). + expect(run.status.terminalPromptUsage).toMatchObject({ event: { breakdown: { inputTokens: 52000, totalTokens: 140000, outputTokens: 1421 } } }); }); it("surfaces blocked helper actions and refuses the coordinator's outside write", async () => { @@ -372,6 +378,52 @@ describe("Antigravity CLI swarm runtime", () => { expect(JSON.stringify(run.result)).not.toContain("toolbox"); }); + it("records the usage the CLI answers a stopped swarm with, once, for the run", async () => { + let cancelled = false; + const run = await runTurn("cancel", { onEvent: (event, cancel) => { + if (!cancelled && event.type === "tool_call" && /verifier/.test(event.title ?? "")) { cancelled = true; void cancel(); } + } }); + expect(run.result).toMatchObject({ status: "cancelled" }); + // The answer to the stopped prompt wins over the count streamed before it. + expect(run.status.terminalPromptUsage).toMatchObject({ requestId: "run-1:turn-1", event: { breakdown: { inputTokens: 1200, outputTokens: 30, totalTokens: 1630 } } }); + expect(persistedAcpxTurnUsage({}, run.status, "run-1:turn-1", "antigravity")).toMatchObject({ tag: "usage_update", breakdown: { totalTokens: 1630 } }); + expect(run.titles.some(title => /includes the helpers/.test(title))).toBe(true); + }); + + it("records what the CLI streamed when it exits before answering, and leaves recovery to Paperclip", async () => { + const run = await runTurn("die"); + expect(run.status.terminalPromptUsage).toMatchObject({ event: { breakdown: { inputTokens: 700, outputTokens: 20, totalTokens: 720 } } }); + expect(run.result).toMatchObject({ status: "failed", error: { code: "ACPX_PROVIDER_PROCESS_LOST", retryable: true, + message: "The swarm stopped unexpectedly because the Antigravity CLI exited. Files the helpers already wrote stay in the task folder." } }); + expect(JSON.stringify(run.result)).not.toMatch(/Retry/); + }); + + it("records the swarm's settings receipt in the run record, without accounts, paths or session ids", async () => { + const run = await runTurn("success"); + // The post-turn notice hook the sidecar runs for every Antigravity turn (the run's status itself never leaves the sidecar). + const activity = acpxProfileActivity("antigravity"); + const notice = activity.usageNotice?.({}, run.status, "run-1:turn-1", "turn-1"); + expect(notice).toMatchObject({ eventType: "provider.notice.recorded", itemId: "turn-1:antigravity-swarm-receipt", payload: { + schema: "paperclip.provider.notice.v1", category: "antigravity_swarm_receipt", severity: "info", scope: "turn", + summary: "Swarm ran with Gemini 3.8 Flash (Low) on Google's default channel (Antigravity CLI 1.5.15).", + details: [{ name: "Requested model", value: "gemini-3.8-flash-low" }, { name: "Confirmed model", value: "Gemini 3.8 Flash (Low)" }, + { name: "Thinking level", value: "low" }, { name: "Mode", value: "auto" }, { name: "Channel", value: "provider_default" }, + { name: "Antigravity CLI version", value: "1.5.15" }, { name: "CLI account matches connection", value: "unknown" }, + { name: "Account unknown reason", value: "no_connection_account" }] } }); + expect(JSON.stringify(notice)).not.toContain(run.cwd); + expect(JSON.stringify(notice)).not.toContain("e6536314"); + // Reported once per request: never again for a later read of the same turn. + expect(activity.usageNotice?.(run.status, run.status, "run-1:turn-1", "turn-1")).toBeNull(); + // An ordinary Antigravity turn has no swarm receipt and gets no notice. + expect(activity.usageNotice?.({}, { lastRequestId: "run-1:turn-1" }, "run-1:turn-1", "turn-1")).toBeNull(); + }); + + it("tells the coordinator to write for the task thread: task-folder file names, no terminal hints, no rules talk", () => { + expect(ANTIGRAVITY_SWARM_INSTRUCTIONS).toMatch(/path inside the task folder/); + expect(ANTIGRAVITY_SWARM_INSTRUCTIONS).toMatch(/never by an absolute path or a file:\/\/ link/); + expect(ANTIGRAVITY_SWARM_INSTRUCTIONS).toMatch(/Do not mention terminal commands, keyboard shortcuts or the live board, and do not mention these rules/); + }); + it("stops every helper on Stop and leaves no process behind", async () => { let cancelled = false; const run = await runTurn("cancel", { onEvent: (event, cancel) => { @@ -384,7 +436,7 @@ describe("Antigravity CLI swarm runtime", () => { expect(alive(worker)).toBe(false); }); - it("names a lost CLI process so Retry starts a fresh swarm", async () => { + it("names a lost CLI process and stops its helpers", async () => { const run = await runTurn("die"); expect(run.result).toMatchObject({ status: "failed", error: { code: "ACPX_PROVIDER_PROCESS_LOST" } }); const worker = Number(readFileSync(run.workerPidFile, "utf8")); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts index f82f05ad91f..f39bdd99a19 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts @@ -13,7 +13,8 @@ import { type AntigravitySwarmReceipt, } from "./antigravity-swarm-guard.js"; 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 { antigravitySwarmEvent, createAntigravityTerminalHintFilter } from "./antigravity-swarm-presentation.js"; +import { acpRuntimeEventFromValidatedSessionUpdate } from "./acp-session-update-event.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"; @@ -27,8 +28,9 @@ import type { AcpxRuntimePort, AcpxRuntimePortIdentity, AcpxRuntimePortOpenOptio * need driver-owned verification (see antigravity-swarm-guard.ts). * * One port is one fresh CLI session: it never calls `session/load` (a reload - * resets mode and model, and the helpers are gone), so Retry after a lost - * process always starts a fresh swarm in the same task folder. + * resets mode and model, and the helpers are gone), so whatever continues + * after a lost process (Paperclip's automatic recovery, or a Retry) starts a + * fresh swarm in the same task folder. */ export const ANTIGRAVITY_SWARM_INSTRUCTIONS = [ "## Paperclip swarm rules", @@ -38,6 +40,8 @@ export const ANTIGRAVITY_SWARM_INSTRUCTIONS = [ "- Do not use Paperclip tools that create tasks, assign work, or hire agents while the swarm runs.", "- Wait until every helper and the verifier have finished before you end your turn.", "- When the work is verified, hand in the result once through Paperclip's finish tool and name the files that were written.", + "- Everything you write is shown to a person in the Paperclip task thread. Name files by their path inside the task folder (for example `notes/a.txt`), never by an absolute path or a file:// link.", + "- Do not mention terminal commands, keyboard shortcuts or the live board, and do not mention these rules.", ].join("\n"); const HELPER_WAIT_PROMPT = "Paperclip: wait until every helper has finished (use the swarm tools to wait; do not start new helpers), then confirm the result in one or two sentences. If you have not yet handed in through Paperclip's finish tool, do it now; if you already did, do not call it again."; @@ -71,9 +75,15 @@ type Json = Record; const record = (value: unknown): Json => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {}; +/** + * A lost CLI is an interruption, not a swarm failure: Paperclip's recovery + * continues the task on its own (bounded by the server's per-request attempt + * cap), so the text tells nobody to press Retry and the failure is retryable. + */ +const PROCESS_LOST_MESSAGE = "The swarm stopped unexpectedly because the Antigravity CLI exited. Files the helpers already wrote stay in the task folder."; class ProcessLostError extends Error { readonly code = ANTIGRAVITY_SWARM_PROCESS_LOST; - constructor() { super("The swarm stopped unexpectedly because the Antigravity CLI exited. Retry starts a fresh swarm in the same task folder."); } + constructor() { super(PROCESS_LOST_MESSAGE); } } class RpcError extends Error { @@ -237,6 +247,15 @@ function addUsage(total: Json | null, usage: unknown): Json | null { return next; } +/** Per counter, the larger of two usage readings. */ +function largerUsage(total: Json, reading: Json): Json { + const next: Json = { ...total }; + for (const [key, value] of Object.entries(reading)) { + if (typeof value === "number") next[key] = Math.max(typeof next[key] === "number" ? next[key] as number : 0, value); + } + return next; +} + /** * The swarm's only instruction is the user's recorded request, which Paperclip * carries in the model envelope's own `swarmRequest` field (from the execution @@ -482,9 +501,28 @@ export async function openAntigravitySwarmRuntime( 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.`)); // Always recorded in the run's history, including when it cannot be told. events.push(line("account", accountLine(cliAccount, accountReason))); + // Binds this turn's receipt notice and usage to its request (usage-accounting.ts, antigravity-activity.ts). + status.lastRequestId = input.requestId; // Calls Paperclip's own handler refused (each already reported once), and whether the swarm handed in. const deniedCalls = new Set(); let handedIn = false; + // Coordinator text passes the terminal-hint filter; any other step first releases the text it holds, so order is kept. + const hints = createAntigravityTerminalHintFilter(); + const releaseText = () => { + const held = hints.flush(); + if (held) events.push({ type: "text_delta", text: held, stream: "output", tag: "agent_message_chunk" }); + }; + const show = (event: AcpRuntimeEvent) => { + if (event.type === "text_delta" && event.stream === "output") { + const text = hints.push(event.text); + if (text) events.push({ ...event, text }); + return; + } + releaseText(); + events.push(event); + }; + // The token counts the CLI last streamed during the current prompt, kept only when that prompt's own answer never arrives. + let streamedUsage: Json | null = null; updateListener = params => { try { guard.observe(params); } catch (error) { @@ -493,6 +531,10 @@ export async function openAntigravitySwarmRuntime( } if (params.sessionId !== sessionId) return; const update = record(params.update); + if (update.sessionUpdate === "usage_update") { + const breakdown = record(record(acpRuntimeEventFromValidatedSessionUpdate({ method: "session/update", params })).breakdown); + if (Object.keys(breakdown).length > 0) streamedUsage = breakdown; + } const escaped = antigravitySwarmWorkspaceEscape(update); if (escaped) { halt(new AntigravitySwarmError("ANTIGRAVITY_SWARM_WORKSPACE_ESCAPE", @@ -522,10 +564,10 @@ export async function openAntigravitySwarmRuntime( if (update.sessionUpdate === "agent_message_chunk" && typeof content.text === "string") transcript += content.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")); + show(line(`blocked-${blocked}`, "A helper was blocked from changing something outside the task folder")); } const event = antigravitySwarmEvent(update, workspace); - if (event) events.push(event); + if (event) show(event); }; connection.onRequest = async (method, params) => { if (method !== "session/request_permission" || params.sessionId !== sessionId) throw new Error("unsupported"); @@ -543,14 +585,32 @@ export async function openAntigravitySwarmRuntime( 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)); + show(line(`blocked-${blocked}`, requested)); } return choice ? { outcome: { outcome: "selected", optionId: choice.optionId } } : { outcome: { outcome: "cancelled" } }; }; let usage: Json | null = null; + /** + * Billable usage is kept whatever the turn's outcome: the prompt's own answer + * (the CLI answers a stopped prompt too), or, when that answer never arrives + * (the CLI exited, or did not answer within the grace), what it streamed. + */ + const keepUsage = (reported: unknown) => { + const answered = record(reported); + if (Object.keys(answered).length > 0) usage = addUsage(usage, answered); + // Whether a streamed count covers this prompt or the whole session is not known, so + // after an answered prompt it can raise a counter but never adds to it (no double count). + else if (streamedUsage) usage = usage ? largerUsage(usage, streamedUsage) : addUsage(null, streamedUsage); + streamedUsage = null; + if (usage) { + status.terminalPromptUsage = { requestId: input.requestId, promptId: `${input.requestId}:swarm`, + event: { type: "status", tag: "usage_update", text: "terminal prompt usage", breakdown: usage } }; + } + }; const prompt = async (text: string, timeoutMs: number | null): Promise => { if (cancelled || stop) return "cancelled"; + streamedUsage = null; const response = connection.request("session/prompt", { sessionId, prompt: [{ type: "text", text }] }, null); started(); let timer: ReturnType | undefined; @@ -564,18 +624,18 @@ export async function openAntigravitySwarmRuntime( if (!stop && !cancelled) halt(new AntigravitySwarmError("ANTIGRAVITY_SWARM_HELPERS_TIMEOUT", "The helpers did not finish in time, so Paperclip stopped the swarm. Files they already wrote stay in the task folder.")); const grace = dependencies.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS; - const settled = await Promise.race([response.then(() => true, () => true), new Promise(resolve => setTimeout(() => resolve(false), grace))]); + const settled = await Promise.race([response.then(reply => ({ reply }), () => ({ reply: null })), + new Promise(resolve => setTimeout(() => resolve(null), grace))]); + keepUsage(settled?.reply?.usage); if (!settled) await retire().catch(() => undefined); return "cancelled"; } - usage = addUsage(usage, outcome.usage); - if (usage) { - // Billable usage is kept whatever the turn's outcome turns out to be. - status.lastRequestId = input.requestId; - status.terminalPromptUsage = { requestId: input.requestId, promptId: `${input.requestId}:swarm`, - event: { type: "status", tag: "usage_update", text: "terminal prompt usage", breakdown: usage } }; - } + keepUsage(outcome.usage); return typeof outcome.stopReason === "string" ? outcome.stopReason : "end_turn"; + } catch (error) { + // The CLI exited mid-prompt: its answer is lost, so what it streamed is what can be kept. + keepUsage(undefined); + throw error; } finally { if (timer) clearTimeout(timer); wake = null; @@ -586,7 +646,7 @@ export async function openAntigravitySwarmRuntime( dispatch?.markDispatched(); let stopReason = await prompt(`/swarm ${request}`, null); if (stopReason === "end_turn" && !stop && !cancelled && helpers.size > 0 && !waitedAfterLastAdd && !classifyAntigravityRefusalText(transcript)) { - events.push(line("wait", "Waiting for the helpers to finish")); + show(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); @@ -610,7 +670,7 @@ export async function openAntigravitySwarmRuntime( // Done still requires the hand-in through Paperclip's finish tool. const after = await snapshotWorkspace(workspace, listing.signal); const changed = changedFiles(before.files, after.files); - events.push(line("files", !before.complete || !after.complete ? "The task folder is too large to list every change" + show(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 @@ -634,12 +694,14 @@ export async function openAntigravitySwarmRuntime( return { status: "completed", stopReason: "end_turn" }; } catch (error) { if (connection.lost instanceof ProcessLostError || error instanceof ProcessLostError) { - return cancelled ? { status: "cancelled", stopReason: "cancelled" } : failed(ANTIGRAVITY_SWARM_PROCESS_LOST, new ProcessLostError().message); + return cancelled ? { status: "cancelled", stopReason: "cancelled" } + : { status: "failed", error: { code: ANTIGRAVITY_SWARM_PROCESS_LOST, message: PROCESS_LOST_MESSAGE, retryable: true } }; } return failed(error instanceof AntigravitySwarmError ? error.code : "ANTIGRAVITY_SWARM_FAILED", error instanceof Error ? error.message.slice(0, 1_000) : "The swarm failed."); } finally { updateListener = null; + releaseText(); if (usage) events.push(line("usage", "Token usage is the coordinator's total and includes the helpers; Google does not report it per helper")); } }; diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts b/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts index 58f956db47e..dad1e366508 100644 --- a/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts +++ b/packages/paperclip-runner/src/drivers/acpx/profile-activity.ts @@ -1,3 +1,4 @@ +import { antigravityActivityAdapter } from "./antigravity-activity.js"; import { createCopilotToolEvidence } from "./copilot-tool-evidence.js"; import { cursorActivityAdapter } from "./cursor-activity.js"; import type { CanonicalProviderEvent } from "../../provider-events.js"; @@ -23,11 +24,13 @@ export interface AcpxActivityAdapter { toolExecutionId?(nativeId: string): string; inputToolIdentity?(input: AcpxExtensionInput): string | undefined; createToolEvidence?(binding: AcpxToolEvidenceBinding): AcpxToolEvidence; + /** A post-turn diagnostic notice read from the provider's status: a usage or settings receipt bound to this request. */ usageNotice?(before: unknown, after: unknown, requestId: string, turnId: string): CanonicalProviderEvent | null; } const adapters: Readonly> = { cursor: cursorActivityAdapter, + antigravity: antigravityActivityAdapter, copilot: Object.freeze({ createToolEvidence: createCopilotToolEvidence }), }; const noActivity: AcpxActivityAdapter = Object.freeze({}); diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index b15c34bca4a..7c43b640d44 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts @@ -23,6 +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 { antigravityLocalLinkEvents } from "./antigravity-local-links.js"; import { antigravityRouteChangeRefusal, antigravitySwarmBinding, antigravitySwarmLaunchEnvironment, type AntigravitySwarmChannel, antigravitySwarmTools, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js"; import type { @@ -357,6 +358,7 @@ export class AcpxRuntimeHost { readonly #claudeSkillNames: readonly string[]; readonly #assertAgentFilesHeld: (() => void) | undefined; readonly #candidateAdmission: AcpxCandidateStartupAdmission | undefined; + readonly #shapeTurnEvents: ((events: AsyncIterable) => AsyncIterable) | undefined; #activeTurn: AcpxRuntimeTurn | null = null; #activeTurnInterruption: AcpxRuntimeTurn["cancel"] | null = null; #closingStarted = false; @@ -374,6 +376,8 @@ export class AcpxRuntimeHost { claudeSkillNames: readonly string[]; assertAgentFilesHeld?: () => void; candidateAdmission?: AcpxCandidateStartupAdmission; + /** Provider-owned projection of a turn's events before they leave the host. */ + shapeTurnEvents?: (events: AsyncIterable) => AsyncIterable; }) { this.#runtime = input.runtime; this.#binding = input.binding; @@ -385,6 +389,7 @@ export class AcpxRuntimeHost { this.#claudeSkillNames = [...input.claudeSkillNames]; this.#assertAgentFilesHeld = input.assertAgentFilesHeld; this.#candidateAdmission = input.candidateAdmission ? structuredClone(input.candidateAdmission) : undefined; + this.#shapeTurnEvents = input.shapeTurnEvents; } static async open( @@ -835,6 +840,9 @@ export class AcpxRuntimeHost { toolBridge, assertAgentFilesHeld: agentFiles?.assertHeld, candidateAdmission: options.candidateAdmission, + // Both Antigravity routes (registry server and swarm CLI) link the files they wrote by local path. + ...(options.agent === "antigravity" + ? { shapeTurnEvents: (events: AsyncIterable) => antigravityLocalLinkEvents(events, [options.workingDirectory, binding.workspacePath]) } : {}), claudeSkillNames: options.agent === "claude" ? (options.runtimeContext?.skills.map((skill) => skill.runtimeName) ?? []) : [], @@ -986,7 +994,7 @@ export class AcpxRuntimeHost { const text = claudeNativeSkillPrompt( boundedTurnText(input.text), this.#claudeSkillNames, ); - const turn = this.#runtime.startTurn({ + const raw = this.#runtime.startTurn({ text, requestId, ...(input.signal ? { signal: input.signal } : {}), @@ -998,6 +1006,11 @@ export class AcpxRuntimeHost { ...(input.onTerminalSessionFailure ? { onTerminalSessionFailure: input.onTerminalSessionFailure } : {}), ...(input.dispatchJournal ? { dispatchJournal: input.dispatchJournal } : {}), }); + const turn: AcpxRuntimeTurn = this.#shapeTurnEvents ? { + requestId: raw.requestId, promptStarted: raw.promptStarted, result: raw.result, + events: this.#shapeTurnEvents(raw.events), + cancel: input => raw.cancel(input), closeStream: input => raw.closeStream(input), + } : raw; this.#activeTurn = turn; const managed = withAcpxTurnCancellation(turn, reason => this.close({ reason }), ACPX_TURN_CANCELLATION_SHUTDOWN_BOUND_MS); this.#activeTurnInterruption = managed.cancel; diff --git a/packages/paperclip-runner/src/live/workspace-file-reference.ts b/packages/paperclip-runner/src/live/workspace-file-reference.ts index 043cf00742c..9496b88aa33 100644 --- a/packages/paperclip-runner/src/live/workspace-file-reference.ts +++ b/packages/paperclip-runner/src/live/workspace-file-reference.ts @@ -43,7 +43,8 @@ function safeLineNumber(value: string): number | null { : null; } -function localTarget(rawTarget: string): { target: string; line: number | null } | null { +/** A Markdown link target as a local path and line (file:// decoded), or null for another scheme. */ +export function localTarget(rawTarget: string): { target: string; line: number | null } | null { let target = rawTarget.trim(); if (target.startsWith("<") && target.endsWith(">")) target = target.slice(1, -1); if (/^[a-z][a-z0-9+.-]*:/i.test(target) && !target.startsWith("file:")) return null; @@ -67,7 +68,8 @@ function localTarget(rawTarget: string): { target: string; line: number | null } return target.length === 0 ? null : { target, line }; } -function workspaceRelativePath(root: string, target: string): string | null { +/** `target` as a `/`-separated path inside `root`, or null when it is outside. */ +export function workspaceRelativePath(root: string, target: string): string | null { const candidate = relative(root, target); if ( !candidate || diff --git a/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs index 475a4237baf..4566aac14b8 100644 --- a/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs +++ b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs @@ -9,8 +9,9 @@ // 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 +// cancel helpers keep running (a real child process) until session/cancel; the CLI +// streams a token count, then answers the stopped prompt with its usage so far +// die the CLI streams a token count, then 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 @@ -90,6 +91,9 @@ const paperclipCall = async tool => { }; const handIn = () => paperclipCall("paperclip_finish"); const say = text => update(state.sessionId, { sessionUpdate: "agent_message_chunk", content: { type: "text", text } }); +// Usage the CLI streams mid-prompt, and the usage it answers a stopped prompt with. +const streamedUsage = { inputTokens: 700, outputTokens: 20, cachedReadTokens: 0, cachedWriteTokens: 0, thoughtTokens: 0, totalTokens: 720 }; +const stoppedUsage = { inputTokens: 1200, outputTokens: 30, cachedReadTokens: 400, cachedWriteTokens: 0, thoughtTokens: 0, totalTokens: 1630 }; 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" }); @@ -136,6 +140,8 @@ async function prompt(id, params) { const text = params.prompt?.[0]?.text ?? ""; if (state.prompts > 1) { // Paperclip's follow-up: wait for the helpers, then confirm. + // A session-wide token count streamed while the wait hangs (larger than the first prompt's answer). + if (scenario === "hang-helpers") update(state.sessionId, { sessionUpdate: "usage_update", used: 60000, size: 1048576, _meta: { usage: { ...usage, inputTokens: 52000, totalTokens: 140000 } } }); 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(); await handIn(); } @@ -177,15 +183,16 @@ async function prompt(id, params) { } if (!await writePlan(planPath())) return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } }); } - say("I have configured and launched the swarm.\n\nRun /swarm board (default shortcut alt+s) to open the live board."); + // The terminal hint arrives in pieces, as recorded live: the hint complete without its period, then the period alone. + for (const chunk of ["I have configured and launched the swarm.\n", "\nRun /swarm board (default shortcut alt+s) to open the live board", "."]) say(chunk); if (scenario === "cancel" || scenario === "die") { + update(state.sessionId, { sessionUpdate: "usage_update", used: 52000, size: 1048576, _meta: { usage: streamedUsage } }); // 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); } - if (state.cancelled) return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } }); if (!state.cancelled) await new Promise(resolve => { state.cancel = resolve; }); - return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled" } }); + return write({ jsonrpc: "2.0", id, result: { stopReason: "cancelled", usage: stoppedUsage } }); } 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(); diff --git a/server/src/services/antigravity-swarm.db.test.ts b/server/src/services/antigravity-swarm.db.test.ts index 082e6654fdd..a8e10761130 100644 --- a/server/src/services/antigravity-swarm.db.test.ts +++ b/server/src/services/antigravity-swarm.db.test.ts @@ -182,6 +182,22 @@ 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("recovers a swarm whose CLI process was lost on its own, and stops after three billed attempts", async () => { + // What the server stores for a lost CLI (the runner's ACPX_PROVIDER_PROCESS_LOST): a generic terminal failure, not the swarm's own code. + const lost = { status: "failed", errorCode: "native_provider_terminal_failed", + error: "The swarm stopped unexpectedly because the Antigravity CLI exited. Files the helpers already wrote stay in the task folder." }; + const f = await seed(); + for (let attempt = 0; attempt < 3; attempt++) { + const run = await insertRun(f, {}); + expect(await automatic(f, run.id, attempt === 0 ? "issue_commented" : "issue_continuation_needed")).toMatchObject({ request: expect.any(String) }); + await db.update(heartbeatRuns).set(lost).where(eq(heartbeatRuns.id, run.id)); + } + for (const wakeReason of ["issue_continuation_needed", "issue_recovery_action_restored", "issue_assigned"]) { + await expect(automatic(f, (await insertRun(f, {})).id, wakeReason)).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, {}); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index d45726dfff7..287de1fd78a 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -519,8 +519,8 @@ "packages/shared/src/validators/instance.ts": "3cb2bc003d32a8f4f49f705a18a1c9343c243cee", "packages/shared/src/validators/issue-chat-bootstrap.test.ts": "e1ebb9aa94da22c825bc3ddd32ce2cfc98bfe645", "packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438", - "packages/shared/src/validators/issue.test.ts": "0dda20eec5eccf09985f3faef2a566f549765d0d", - "packages/shared/src/validators/issue.ts": "f9b02da405490191678fb9ea42b89648e4420322", + "packages/shared/src/validators/issue.test.ts": "7584bcce33a933ebcb02695b439767163e5ef61a", + "packages/shared/src/validators/issue.ts": "8d6325b771d4f893219312737351a0a9e8ce5bbc", "packages/shared/src/validators/json-schema.ts": "b6cba6a3f76b49afce1c7dc1c2f086ab946c6133", "packages/shared/src/validators/native-finalization.test.ts": "40c68bdd1d0e8a77cd70c4576fae53334fe5be0d", "packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830",