mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 23:06:17 +01:00
Address CI and code review findings for unified Antigravity agy 1.5.19 runtime
- Ordinary turns: wrap permission prompts as AcpPermissionRequest so normalizeAcpxPermission works in interactive approval flows; fail closed on unconfirmed model selection or read-only plan mode (and abort on mid-session plan-mode drift); preserve existing antigravity-session.json when startup or restore fails. - Runtime host & sandbox: stage managed Antigravity Google credentials for both ordinary and /swarm turns; apply schemaPatternDialect="re2" to all Antigravity CLI turns; persist AGY_CLI_FORCE_FILE_TOKEN_STORAGE and AGY_CLI_DISABLE_AUTO_UPDATE in runtime-sandbox allowlist. - Auth, credentials & model discovery: support verifying client-secret-less consumer credentials without a pre-existing antigravity-cli token file via prompt-free agy acp refresh with durable directory-synced writeback; include CLI token and cli.log in codex-credentials crash-scrub cleanup intent and quarantine; ensure model discovery durably saves rotated tokens before removing the temporary CLI token in both normal and delayed-cleanup paths. - Transport deduplication: extract shared AntigravityAcpConnection, EventQueue, and usage helpers into antigravity-acp-connection.ts with explicit timer cleanup on failure. - Update profile-compatibility.test.ts (PROFILE_VERSIONS.antigravity = 3), server/UI test expectations, and add regression tests for all fixes. Tested: - pnpm --filter @paperclipai/paperclip-runner typecheck (TS + Rust) - tsc -p packages/paperclip-runner/tsconfig.test.json --noEmit - 11 paperclip-runner vitest suites (556/556 passed) + codex-credentials (42/42) - server & UI vitest suites (antigravity-swarm.db 52/52, routes/qual/UI 110/110) - Live darwin-arm64 E2E against real agy 1.5.19 (login, credential staging, ordinary turn + HTTP MCP + setModel + resume, and /swarm with helper hand-in) Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
5f0fe4a597
commit
8a72a93ea1
20 files changed
+795
-391
No files matched your search
@@ -2122,7 +2122,7 @@ describe("qualified ACPX runtime sidecar", () => {
|
||||
const sidecar = startSidecar();
|
||||
const model = "caller-exact-model";
|
||||
const profile = resolveQualifiedAcpxProfile("antigravity", model);
|
||||
expect(profile.agentProfileVersion).toBe(2);
|
||||
expect(profile.agentProfileVersion).toBe(3);
|
||||
expect(profile.qualificationStatus).toBeUndefined();
|
||||
sidecar.write(initializeRequest(1, "antigravity", model));
|
||||
expect(await sidecar.next(frame => frame.id === 1)).toMatchObject({ id: 1, ok: true, result: { profile } });
|
||||
|
||||
@@ -291,7 +291,7 @@ describe("Codex ACPX runtime adapter", () => {
|
||||
created.spawnAgent?.({ command: "ignored", args: [], options: {} });
|
||||
const guard = created.protocolGuardFactory!();
|
||||
guard("outbound", { id: 0, method: "initialize", params: {} });
|
||||
guard("inbound", { id: 0, result: { agentInfo: { name: "antigravity-acp", version: "1.5.2" },
|
||||
guard("inbound", { id: 0, result: { agentInfo: { name: "antigravity-acp", version: "1.5.19" },
|
||||
agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 1 } } } } });
|
||||
const open = { id: 1, method: "session/new", params: { cwd: "/workspace" } as Record<string, any> };
|
||||
guard("outbound", open);
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import type { ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import type { AcpRuntimeEvent } from "acpx/runtime";
|
||||
|
||||
const EXIT_OUTPUT_GRACE_MS = 200;
|
||||
|
||||
export type Json = Record<string, unknown>;
|
||||
|
||||
export const jsonRecord = (value: unknown): Json =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {};
|
||||
|
||||
export class AntigravityRpcError extends Error {
|
||||
constructor(readonly method: string, readonly error: Json) {
|
||||
super(`${method} failed: ${typeof error.message === "string" ? error.message.slice(0, 500) : "provider error"}`);
|
||||
}
|
||||
}
|
||||
|
||||
export interface AntigravityAcpConnectionOptions {
|
||||
createProcessLostError: () => Error;
|
||||
createTimeoutError: (method: string) => Error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Newline-delimited JSON-RPC over the pinned Antigravity CLI's stdio.
|
||||
* Lines are handled one per macrotask so a response's awaiting caller
|
||||
* observes it before the updates that follow it.
|
||||
*/
|
||||
export class AntigravityAcpConnection {
|
||||
#next = 1;
|
||||
#pending = new Map<number, {
|
||||
method: string;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
resolve: (value: Json) => void;
|
||||
reject: (error: Error) => void;
|
||||
}>();
|
||||
#buffer = "";
|
||||
#queue: Promise<void> = Promise.resolve();
|
||||
#lost: Error | null = null;
|
||||
readonly #options: AntigravityAcpConnectionOptions;
|
||||
readonly exited: Promise<void>;
|
||||
onNotification: (method: string, params: Json) => void = () => {};
|
||||
onRequest: (method: string, params: Json) => Promise<unknown> = async () => { throw new Error("unsupported"); };
|
||||
onLost: () => void = () => {};
|
||||
|
||||
constructor(readonly child: ChildProcessWithoutNullStreams, options: AntigravityAcpConnectionOptions) {
|
||||
this.#options = options;
|
||||
// Exit, not close: helpers the CLI started inherit its output pipe and can
|
||||
// hold it open long after the CLI died. Output already written is read for
|
||||
// a short moment after exit; the lost CLI cannot answer anything later.
|
||||
this.exited = new Promise(resolve => child.once("exit", () => {
|
||||
if (child.stdout.readableEnded || child.stdout.destroyed) { resolve(); return; }
|
||||
const timer = setTimeout(resolve, EXIT_OUTPUT_GRACE_MS);
|
||||
child.stdout.once("close", () => { clearTimeout(timer); resolve(); });
|
||||
}));
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => {
|
||||
this.#buffer += chunk;
|
||||
if (this.#buffer.length > 16 * 1024 * 1024) {
|
||||
this.#fail(new Error("Antigravity CLI output exceeded its bound"));
|
||||
return;
|
||||
}
|
||||
for (let index = this.#buffer.indexOf("\n"); index >= 0; index = this.#buffer.indexOf("\n")) {
|
||||
const line = this.#buffer.slice(0, index);
|
||||
this.#buffer = this.#buffer.slice(index + 1);
|
||||
if (line.trim()) {
|
||||
this.#queue = this.#queue.then(() => new Promise<void>(resolve => setImmediate(() => {
|
||||
// A handler failure must never escape into the event loop and end the sidecar.
|
||||
try { this.#line(line); } catch (error) {
|
||||
this.#fail(error instanceof Error ? error : new Error("Antigravity CLI message could not be handled"));
|
||||
}
|
||||
resolve();
|
||||
})));
|
||||
}
|
||||
}
|
||||
});
|
||||
child.stderr.resume();
|
||||
child.stdin.on("error", () => undefined);
|
||||
void this.exited.then(() => { void this.#queue.then(() => this.#fail(this.#options.createProcessLostError())); });
|
||||
}
|
||||
|
||||
get lost(): Error | null { return this.#lost; }
|
||||
|
||||
/** Settle every message already received from the CLI. */
|
||||
async drain(): Promise<void> {
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await this.#queue;
|
||||
}
|
||||
|
||||
#fail(error: Error): void {
|
||||
if (this.#lost) return;
|
||||
this.#lost = error;
|
||||
for (const pending of this.#pending.values()) {
|
||||
if (pending.timer) clearTimeout(pending.timer);
|
||||
pending.reject(error);
|
||||
}
|
||||
this.#pending.clear();
|
||||
this.onLost();
|
||||
}
|
||||
|
||||
#line(line: string): void {
|
||||
let message: Json;
|
||||
try { message = jsonRecord(JSON.parse(line)); } catch { return; }
|
||||
const { id, method } = message;
|
||||
if (typeof method === "string") {
|
||||
if (id === undefined) { this.onNotification(method, jsonRecord(message.params)); return; }
|
||||
void this.onRequest(method, jsonRecord(message.params)).then(
|
||||
result => this.#write({ jsonrpc: "2.0", id, result }),
|
||||
() => this.#write({ jsonrpc: "2.0", id, error: { code: -32601, message: "Not supported by Paperclip" } }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (typeof id !== "number") return;
|
||||
const pending = this.#pending.get(id);
|
||||
if (!pending) return;
|
||||
this.#pending.delete(id);
|
||||
if (pending.timer) clearTimeout(pending.timer);
|
||||
if (message.error !== undefined) pending.reject(new AntigravityRpcError(pending.method, jsonRecord(message.error)));
|
||||
else pending.resolve(jsonRecord(message.result));
|
||||
}
|
||||
|
||||
#write(message: Json): void {
|
||||
if (this.#lost || this.child.stdin.destroyed) return;
|
||||
this.child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
request(method: string, params: Json, timeoutMs: number | null): Promise<Json> {
|
||||
if (this.#lost) return Promise.reject(this.#lost);
|
||||
const id = this.#next++;
|
||||
return new Promise<Json>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const entry: {
|
||||
method: string;
|
||||
timer?: ReturnType<typeof setTimeout>;
|
||||
resolve: (value: Json) => void;
|
||||
reject: (error: Error) => void;
|
||||
} = {
|
||||
method,
|
||||
resolve: value => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (entry.timer) clearTimeout(entry.timer);
|
||||
resolve(value);
|
||||
},
|
||||
reject: error => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (entry.timer) clearTimeout(entry.timer);
|
||||
reject(error);
|
||||
},
|
||||
};
|
||||
this.#pending.set(id, entry);
|
||||
if (timeoutMs !== null) {
|
||||
entry.timer = setTimeout(() => {
|
||||
this.#pending.delete(id);
|
||||
entry.reject(this.#options.createTimeoutError(method));
|
||||
}, timeoutMs);
|
||||
entry.timer.unref?.();
|
||||
}
|
||||
this.#write({ jsonrpc: "2.0", id, method, params });
|
||||
});
|
||||
}
|
||||
|
||||
notify(method: string, params: Json): void { this.#write({ jsonrpc: "2.0", method, params }); }
|
||||
}
|
||||
|
||||
export class AntigravityAcpEventQueue implements AsyncIterable<AcpRuntimeEvent> {
|
||||
#items: AcpRuntimeEvent[] = [];
|
||||
#waiter: (() => void) | null = null;
|
||||
#ended = false;
|
||||
push(event: AcpRuntimeEvent): void { if (this.#ended) return; this.#items.push(event); this.#waiter?.(); }
|
||||
end(): void { this.#ended = true; this.#waiter?.(); }
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<AcpRuntimeEvent> {
|
||||
for (;;) {
|
||||
const item = this.#items.shift();
|
||||
if (item) { yield item; continue; }
|
||||
if (this.#ended) return;
|
||||
await new Promise<void>(resolve => { this.#waiter = resolve; });
|
||||
this.#waiter = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function addAntigravityUsage(total: Json | null, usage: unknown): Json | null {
|
||||
const value = jsonRecord(usage);
|
||||
if (Object.keys(value).length === 0) return total;
|
||||
const next: Json = { ...(total ?? {}) };
|
||||
for (const key of ["inputTokens", "outputTokens", "cachedReadTokens", "cachedWriteTokens", "thoughtTokens", "totalTokens"]) {
|
||||
if (typeof value[key] === "number") next[key] = (typeof next[key] === "number" ? next[key] as number : 0) + (value[key] as number);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { normalizeAcpxPermission } from "./acp-permission-adapter.js";
|
||||
import { AntigravitySavedStateIncompatibleError } from "./antigravity-admission.js";
|
||||
import { AntigravityAcpError, openAntigravityAcpRuntime } from "./antigravity-acp-runtime.js";
|
||||
import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.js";
|
||||
@@ -92,6 +93,10 @@ rl.on('line', line => {
|
||||
return;
|
||||
}
|
||||
if (method === 'session/resume') {
|
||||
if (scenario === 'resume-auth-fail') {
|
||||
write({ jsonrpc: '2.0', id, error: { code: -32000, message: 'Authentication required' } });
|
||||
return;
|
||||
}
|
||||
if (scenario === 'resume-incompatible') {
|
||||
write({ jsonrpc: '2.0', id, error: { code: -32602, message: 'Session not found' } });
|
||||
return;
|
||||
@@ -110,12 +115,20 @@ rl.on('line', line => {
|
||||
return;
|
||||
}
|
||||
if (method === 'session/set_mode') {
|
||||
if (scenario === 'plan-unconfirmed') {
|
||||
write({ jsonrpc: '2.0', id, result: {} });
|
||||
return;
|
||||
}
|
||||
currentMode = params.modeId;
|
||||
write({ jsonrpc: '2.0', id, result: {} });
|
||||
write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: params.sessionId, update: { sessionUpdate: 'current_mode_update', currentModeId: currentMode } } });
|
||||
return;
|
||||
}
|
||||
if (method === 'session/set_model') {
|
||||
if (scenario === 'model-unconfirmed') {
|
||||
write({ jsonrpc: '2.0', id, result: {} });
|
||||
return;
|
||||
}
|
||||
const match = /^(.*)-(low|medium|high)$/.exec(params.modelId);
|
||||
if (!match) {
|
||||
write({ jsonrpc: '2.0', id, error: { code: -32602, message: 'Unsupported model' } });
|
||||
@@ -127,11 +140,23 @@ rl.on('line', line => {
|
||||
write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: params.sessionId, update: { sessionUpdate: 'config_option_update', configOptions: configOptions() } } });
|
||||
return;
|
||||
}
|
||||
if (method === 'session/set_config_option') {
|
||||
if (scenario === 'model-unconfirmed') {
|
||||
write({ jsonrpc: '2.0', id, result: {} });
|
||||
return;
|
||||
}
|
||||
write({ jsonrpc: '2.0', id, result: { configOptions: configOptions() } });
|
||||
return;
|
||||
}
|
||||
if (method === 'session/prompt') {
|
||||
const text = params.prompt?.[0]?.text ?? '';
|
||||
if (scenario === 'crash') {
|
||||
process.exit(9);
|
||||
}
|
||||
if (scenario === 'plan-drift') {
|
||||
write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: params.sessionId, update: { sessionUpdate: 'current_mode_update', currentModeId: 'default' } } });
|
||||
return;
|
||||
}
|
||||
if (scenario === 'cancel') {
|
||||
cancelPrompt = () => write({ jsonrpc: '2.0', id, result: { stopReason: 'cancelled', usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 } } });
|
||||
return;
|
||||
@@ -141,14 +166,17 @@ rl.on('line', line => {
|
||||
write({ jsonrpc: '2.0', id, result: { stopReason: 'end_turn' } });
|
||||
return;
|
||||
}
|
||||
if (scenario === 'plan-permission') {
|
||||
if (scenario === 'plan-permission' || scenario === 'interactive-permission') {
|
||||
const permPromise = new Promise(resolve => { pendingPerm = { id: 901, resolve }; });
|
||||
write({
|
||||
jsonrpc: '2.0', id: 901, method: 'session/request_permission',
|
||||
params: {
|
||||
sessionId: params.sessionId,
|
||||
toolCall: { toolCallId: 'tc_edit', title: 'Write file', kind: 'edit' },
|
||||
options: [{ optionId: 'allow', kind: 'allow_once' }, { optionId: 'deny', kind: 'reject_once' }],
|
||||
options: [
|
||||
{ optionId: 'allow', name: 'Allow once', kind: 'allow_once' },
|
||||
{ optionId: 'deny', name: 'Deny', kind: 'reject_once' },
|
||||
],
|
||||
},
|
||||
});
|
||||
permPromise.then(res => {
|
||||
@@ -176,12 +204,15 @@ rl.on('line', line => {
|
||||
stateDirectory,
|
||||
providerSessionKey: "sess-key-1",
|
||||
permissionMode: "approve-all",
|
||||
permissionPolicy: { defaultAction: "approve" },
|
||||
credentialFenceFds: null,
|
||||
activateCredentialFenceOwner: null,
|
||||
launchEnvironment: { PATH: process.env.PATH ?? "/usr/bin:/bin" },
|
||||
mcpServers: [{ name: "paperclip", url: "http://127.0.0.1:41234/mcp", bearerToken: "tok-123", runnerOwned: true }],
|
||||
paperclipTools: ["get_task_context"],
|
||||
systemInstructions: "Follow Paperclip instructions.",
|
||||
command: {
|
||||
spawn: (_args, opts) => spawn(process.execPath, [peer, scenario, logFile], { cwd: opts.cwd, env: opts.env, stdio: "pipe", detached: true }),
|
||||
spawn: (_args, opts) => spawn(process.execPath, [peer, scenario, logFile], { cwd: opts?.cwd, env: opts?.env, stdio: "pipe", detached: true }),
|
||||
close: async () => undefined,
|
||||
} as AcpxRuntimePortOpenOptions["command"],
|
||||
retainFailedAdmissionCleanup: () => undefined,
|
||||
@@ -209,7 +240,7 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", ()
|
||||
expect(chunks1.join("")).toContain("\u2060/swarm");
|
||||
expect(chunks1.join("")).toContain("model:gemini-4-argon-medium");
|
||||
|
||||
await runtime.setModel("gemini-3.8-flash-high");
|
||||
await runtime.setModel!("gemini-3.8-flash-high");
|
||||
const status = await runtime.getStatus();
|
||||
expect(status.models?.currentModelId).toBe("gemini-3.8-flash-high");
|
||||
expect(status.models?.availableModelIds).toContain("gemini-4-argon-medium");
|
||||
@@ -240,7 +271,7 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", ()
|
||||
headers: [{ name: "Authorization", value: "Bearer tok-123" }],
|
||||
}]);
|
||||
} finally {
|
||||
await runtime.close();
|
||||
await runtime.close({ reason: "test" });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -250,7 +281,7 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", ()
|
||||
openOptions({ launchEnvironment: { PATH: process.env.PATH ?? "/usr/bin:/bin", GEMINI_API_KEY: "AIza-test-key" } }),
|
||||
{ awaitProviderOwnership: async () => undefined },
|
||||
);
|
||||
await runtime.close();
|
||||
await runtime.close({ reason: "test" });
|
||||
const rpc = (await readFile(logFile, "utf8")).trim().split("\n").map(line => JSON.parse(line));
|
||||
expect(rpc.slice(0, 3).map(m => m.method)).toEqual(["initialize", "authenticate", "session/new"]);
|
||||
expect(rpc[1].params).toEqual({ methodId: "gemini-api-key" });
|
||||
@@ -259,11 +290,11 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", ()
|
||||
it("resumes saved sessions and rejects incompatible saved state", async () => {
|
||||
const { stateDirectory, logFile, openOptions } = await makeFixture("ok");
|
||||
const runtime1 = await openAntigravityAcpRuntime(openOptions(), { awaitProviderOwnership: async () => undefined });
|
||||
await runtime1.close();
|
||||
await runtime1.close({ reason: "test" });
|
||||
|
||||
const runtime2 = await openAntigravityAcpRuntime(openOptions({ restoringSession: true }), { awaitProviderOwnership: async () => undefined });
|
||||
expect((await runtime2.identity()).backendSessionId).toBe("sess-ordinary-1");
|
||||
await runtime2.close();
|
||||
await runtime2.close({ reason: "test" });
|
||||
|
||||
const rpc = (await readFile(logFile, "utf8")).trim().split("\n").map(line => JSON.parse(line));
|
||||
expect(rpc.some(m => m.method === "session/resume" && m.params.sessionId === "sess-ordinary-1")).toBe(true);
|
||||
@@ -299,7 +330,7 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", ()
|
||||
const rpc = (await readFile(logFile, "utf8")).trim().split("\n").map(line => JSON.parse(line));
|
||||
expect(rpc.some(m => m.method === "session/set_mode" && m.params.modeId === "plan")).toBe(true);
|
||||
} finally {
|
||||
await runtime.close();
|
||||
await runtime.close({ reason: "test" });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -312,7 +343,7 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", ()
|
||||
const quotaRes = await quotaTurn.result;
|
||||
expect(quotaRes.status).toBe("failed");
|
||||
expect(onTerminalSessionFailure).toHaveBeenCalledWith(expect.objectContaining({ category: "limit" }));
|
||||
await quotaRt.close();
|
||||
await quotaRt.close({ reason: "test" });
|
||||
|
||||
const cancelFx = await makeFixture("cancel");
|
||||
const cancelRt = await openAntigravityAcpRuntime(cancelFx.openOptions(), { awaitProviderOwnership: async () => undefined });
|
||||
@@ -320,13 +351,13 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", ()
|
||||
await cancelTurn.promptStarted;
|
||||
await cancelTurn.cancel();
|
||||
expect(await cancelTurn.result).toEqual({ status: "cancelled", stopReason: "cancelled" });
|
||||
await cancelRt.close();
|
||||
await cancelRt.close({ reason: "test" });
|
||||
|
||||
const crashFx = await makeFixture("crash");
|
||||
const crashRt = await openAntigravityAcpRuntime(crashFx.openOptions(), { awaitProviderOwnership: async () => undefined });
|
||||
const crashTurn = crashRt.startTurn({ requestId: "req-crash", text: "boom" });
|
||||
expect(await crashTurn.result).toMatchObject({ status: "failed", error: { code: "ACPX_PROVIDER_PROCESS_LOST", retryable: true } });
|
||||
await crashRt.close();
|
||||
await crashRt.close({ reason: "test" });
|
||||
});
|
||||
|
||||
it("fails closed on version mismatch, missing systemPrompt capability, or auth error during session/new", async () => {
|
||||
@@ -342,4 +373,74 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", ()
|
||||
await expect(openAntigravityAcpRuntime(authReq.openOptions(), { awaitProviderOwnership: async () => undefined }))
|
||||
.rejects.toMatchObject({ code: "ANTIGRAVITY_AUTH_REQUIRED" });
|
||||
});
|
||||
|
||||
it("wraps interactive approval requests as AcpPermissionRequest compatible with normalizeAcpxPermission", async () => {
|
||||
const { openOptions } = await makeFixture("interactive-permission");
|
||||
const runtime = await openAntigravityAcpRuntime(
|
||||
openOptions({ permissionMode: "approve-reads", permissionPolicy: { defaultAction: "escalate" } }),
|
||||
{ awaitProviderOwnership: async () => undefined },
|
||||
);
|
||||
try {
|
||||
const seenTitles: string[] = [];
|
||||
const turn = runtime.startTurn({
|
||||
requestId: "req-approve",
|
||||
text: "edit file",
|
||||
onPermissionRequest: async request => {
|
||||
const normalized = normalizeAcpxPermission(request, { provider: "antigravity" });
|
||||
seenTitles.push(normalized.title);
|
||||
return normalized.resolve({ action: "accept" });
|
||||
},
|
||||
});
|
||||
const chunks: string[] = [];
|
||||
for await (const event of turn.events) {
|
||||
if (event.type === "text_delta" && event.stream === "output") chunks.push(event.text);
|
||||
}
|
||||
expect(await turn.result).toEqual({ status: "completed", stopReason: "end_turn" });
|
||||
expect(seenTitles).toEqual(["Write file"]);
|
||||
expect(chunks.join("")).toBe("plan-checked:allow");
|
||||
} finally {
|
||||
await runtime.close({ reason: "test" });
|
||||
}
|
||||
});
|
||||
|
||||
it("fails closed when model selection or read-only plan mode is not confirmed, and aborts on plan-mode drift", async () => {
|
||||
const modelFx = await makeFixture("model-unconfirmed");
|
||||
await expect(openAntigravityAcpRuntime(
|
||||
modelFx.openOptions({ profile: { ...QUALIFIED_ACPX_PROFILES.antigravity, reportedModelId: "gemini-3.8-flash-high", qualificationModel: "gemini-3.8-flash-high" } }),
|
||||
{ awaitProviderOwnership: async () => undefined, readbackTimeoutMs: 100 },
|
||||
)).rejects.toMatchObject({ code: "ANTIGRAVITY_MODEL_UNAVAILABLE" });
|
||||
|
||||
const planFx = await makeFixture("plan-unconfirmed");
|
||||
await expect(openAntigravityAcpRuntime(
|
||||
planFx.openOptions({ readOnly: true }),
|
||||
{ awaitProviderOwnership: async () => undefined, readbackTimeoutMs: 100 },
|
||||
)).rejects.toMatchObject({ code: "ANTIGRAVITY_MODE_UNAVAILABLE" });
|
||||
|
||||
const driftFx = await makeFixture("plan-drift");
|
||||
const driftRt = await openAntigravityAcpRuntime(
|
||||
driftFx.openOptions({ readOnly: true }),
|
||||
{ awaitProviderOwnership: async () => undefined, readbackTimeoutMs: 500 },
|
||||
);
|
||||
try {
|
||||
const turn = driftRt.startTurn({ requestId: "req-drift", text: "inspect" });
|
||||
expect(await turn.result).toMatchObject({ status: "failed", error: { code: "ANTIGRAVITY_MODE_DRIFT", retryable: false } });
|
||||
} finally {
|
||||
await driftRt.close({ reason: "test" });
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves an existing saved antigravity-session.json when restore startup fails", async () => {
|
||||
const { openOptions, stateDirectory } = await makeFixture("resume-auth-fail");
|
||||
const saved = {
|
||||
sessionId: "sess-preserved-1",
|
||||
cwd: openOptions().cwd,
|
||||
model: "gemini-4-argon-medium",
|
||||
readOnly: false,
|
||||
};
|
||||
await writeFile(join(stateDirectory, "antigravity-session.json"), JSON.stringify(saved));
|
||||
await expect(openAntigravityAcpRuntime(openOptions({ restoringSession: true }), { awaitProviderOwnership: async () => undefined }))
|
||||
.rejects.toMatchObject({ code: "ANTIGRAVITY_AUTH_REQUIRED" });
|
||||
const after = JSON.parse(await readFile(join(stateDirectory, "antigravity-session.json"), "utf8"));
|
||||
expect(after).toEqual(saved);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,13 @@
|
||||
import type { ChildProcess, ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import type { AcpRuntimeEvent, AcpRuntimeTurnResult } from "acpx/runtime";
|
||||
import type { AcpPermissionRequest, AcpRuntimeTurnResult } from "acpx/runtime";
|
||||
import { createProviderFailure } from "../provider-failure.js";
|
||||
import { acpRuntimeEventFromValidatedSessionUpdate } from "./acp-session-update-event.js";
|
||||
import {
|
||||
AntigravityAcpConnection, AntigravityAcpEventQueue, AntigravityRpcError,
|
||||
addAntigravityUsage, jsonRecord, type Json,
|
||||
} from "./antigravity-acp-connection.js";
|
||||
import { AntigravitySavedStateIncompatibleError } from "./antigravity-admission.js";
|
||||
import { neutralizeAntigravityNativeCommands } from "./antigravity-native-commands.js";
|
||||
import { ANTIGRAVITY_PAPERCLIP_MCP_SERVER, antigravityPlanModeAllows } from "./antigravity-plan-mode.js";
|
||||
@@ -13,6 +17,7 @@ import { ANTIGRAVITY_CLI_AGENT_NAME, antigravitySelections, classifyAntigravityR
|
||||
import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.js";
|
||||
import { awaitVerifiedAcpxProviderOwnership } from "./installation-integrity.js";
|
||||
import type { AcpxModelStatus } from "./model-verification.js";
|
||||
import { decideAcpxPermission } from "./permission-policy.js";
|
||||
import type {
|
||||
AcpxMcpServerBinding, AcpxRuntimePort, AcpxRuntimePortIdentity, AcpxRuntimePortOpenOptions,
|
||||
AcpxRuntimeTurn, AcpxRuntimeTurnInput,
|
||||
@@ -20,19 +25,16 @@ import type {
|
||||
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
|
||||
const DEFAULT_CANCEL_GRACE_MS = 5_000;
|
||||
const EXIT_OUTPUT_GRACE_MS = 200;
|
||||
const DEFAULT_READBACK_TIMEOUT_MS = 5_000;
|
||||
const SESSION_RECORD_FILE = "antigravity-session.json";
|
||||
const PROCESS_LOST_CODE = "ACPX_PROVIDER_PROCESS_LOST";
|
||||
const PROCESS_LOST_MESSAGE = "The Antigravity process exited unexpectedly.";
|
||||
const WORD_JOINER = "\u2060";
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
const record = (value: unknown): Json =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {};
|
||||
|
||||
export interface AntigravityAcpRuntimeDependencies {
|
||||
requestTimeoutMs?: number;
|
||||
cancelGraceMs?: number;
|
||||
readbackTimeoutMs?: number;
|
||||
awaitProviderOwnership?: (child: ChildProcess) => Promise<void>;
|
||||
lineageSampleIntervalMs?: number;
|
||||
readProcessTable?: () => Promise<ProcessTableRead>;
|
||||
@@ -43,12 +45,6 @@ class ProcessLostError extends Error {
|
||||
constructor() { super(PROCESS_LOST_MESSAGE); }
|
||||
}
|
||||
|
||||
class RpcError extends Error {
|
||||
constructor(readonly method: string, readonly error: Json) {
|
||||
super(`${method} failed: ${typeof error.message === "string" ? error.message.slice(0, 500) : "provider error"}`);
|
||||
}
|
||||
}
|
||||
|
||||
export class AntigravityAcpError extends Error {
|
||||
readonly retryable = false;
|
||||
readonly providerFailure;
|
||||
@@ -63,122 +59,6 @@ export class AntigravityAcpError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
class Connection {
|
||||
#next = 1;
|
||||
#pending = new Map<number, { method: string; resolve: (value: Json) => void; reject: (error: Error) => void }>();
|
||||
#buffer = "";
|
||||
#queue: Promise<void> = Promise.resolve();
|
||||
#lost: Error | null = null;
|
||||
readonly exited: Promise<void>;
|
||||
onNotification: (method: string, params: Json) => void = () => {};
|
||||
onRequest: (method: string, params: Json) => Promise<unknown> = async () => { throw new Error("unsupported"); };
|
||||
onLost: () => void = () => {};
|
||||
|
||||
constructor(readonly child: ChildProcessWithoutNullStreams) {
|
||||
this.exited = new Promise(resolve => child.once("exit", () => {
|
||||
if (child.stdout.readableEnded || child.stdout.destroyed) { resolve(); return; }
|
||||
const timer = setTimeout(resolve, EXIT_OUTPUT_GRACE_MS);
|
||||
child.stdout.once("close", () => { clearTimeout(timer); resolve(); });
|
||||
}));
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => {
|
||||
this.#buffer += chunk;
|
||||
if (this.#buffer.length > 16 * 1024 * 1024) { this.#fail(new Error("Antigravity CLI output exceeded its bound")); return; }
|
||||
for (let index = this.#buffer.indexOf("\n"); index >= 0; index = this.#buffer.indexOf("\n")) {
|
||||
const line = this.#buffer.slice(0, index);
|
||||
this.#buffer = this.#buffer.slice(index + 1);
|
||||
if (line.trim()) {
|
||||
this.#queue = this.#queue.then(() => new Promise<void>(resolve => setImmediate(() => {
|
||||
try { this.#line(line); } catch (error) {
|
||||
this.#fail(error instanceof Error ? error : new Error("Antigravity CLI message could not be handled"));
|
||||
}
|
||||
resolve();
|
||||
})));
|
||||
}
|
||||
}
|
||||
});
|
||||
child.stderr.resume();
|
||||
child.stdin.on("error", () => undefined);
|
||||
void this.exited.then(() => { void this.#queue.then(() => this.#fail(new ProcessLostError())); });
|
||||
}
|
||||
|
||||
get lost(): Error | null { return this.#lost; }
|
||||
|
||||
async drain(): Promise<void> {
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await this.#queue;
|
||||
}
|
||||
|
||||
#fail(error: Error): void {
|
||||
if (this.#lost) return;
|
||||
this.#lost = error;
|
||||
for (const pending of this.#pending.values()) pending.reject(error);
|
||||
this.#pending.clear();
|
||||
this.onLost();
|
||||
}
|
||||
|
||||
#line(line: string): void {
|
||||
let message: Json;
|
||||
try { message = record(JSON.parse(line)); } catch { return; }
|
||||
const { id, method } = message;
|
||||
if (typeof method === "string") {
|
||||
if (id === undefined) { this.onNotification(method, record(message.params)); return; }
|
||||
void this.onRequest(method, record(message.params)).then(
|
||||
result => this.#write({ jsonrpc: "2.0", id, result }),
|
||||
() => this.#write({ jsonrpc: "2.0", id, error: { code: -32601, message: "Not supported by Paperclip" } }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (typeof id !== "number") return;
|
||||
const pending = this.#pending.get(id);
|
||||
if (!pending) return;
|
||||
this.#pending.delete(id);
|
||||
if (message.error !== undefined) pending.reject(new RpcError(pending.method, record(message.error)));
|
||||
else pending.resolve(record(message.result));
|
||||
}
|
||||
|
||||
#write(message: Json): void {
|
||||
if (this.#lost || this.child.stdin.destroyed) return;
|
||||
this.child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
request(method: string, params: Json, timeoutMs: number | null): Promise<Json> {
|
||||
if (this.#lost) return Promise.reject(this.#lost);
|
||||
const id = this.#next++;
|
||||
return new Promise<Json>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const settle = <T>(fn: (value: T) => void) => (value: T) => { if (timer) clearTimeout(timer); fn(value); };
|
||||
this.#pending.set(id, { method, resolve: settle(resolve), reject: settle(reject) });
|
||||
if (timeoutMs !== null) {
|
||||
timer = setTimeout(() => {
|
||||
this.#pending.delete(id);
|
||||
reject(new AntigravityAcpError("ANTIGRAVITY_RPC_TIMEOUT", `Antigravity did not answer ${method} in time.`));
|
||||
}, timeoutMs);
|
||||
}
|
||||
this.#write({ jsonrpc: "2.0", id, method, params });
|
||||
});
|
||||
}
|
||||
|
||||
notify(method: string, params: Json): void { this.#write({ jsonrpc: "2.0", method, params }); }
|
||||
}
|
||||
|
||||
class EventQueue implements AsyncIterable<AcpRuntimeEvent> {
|
||||
#items: AcpRuntimeEvent[] = [];
|
||||
#waiter: (() => void) | null = null;
|
||||
#ended = false;
|
||||
push(event: AcpRuntimeEvent): void { if (this.#ended) return; this.#items.push(event); this.#waiter?.(); }
|
||||
end(): void { this.#ended = true; this.#waiter?.(); }
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<AcpRuntimeEvent> {
|
||||
for (;;) {
|
||||
const item = this.#items.shift();
|
||||
if (item) { yield item; continue; }
|
||||
if (this.#ended) return;
|
||||
await new Promise<void>(resolve => { this.#waiter = resolve; });
|
||||
this.#waiter = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function formatMcpServers(servers: readonly AcpxMcpServerBinding[]): Json[] {
|
||||
return servers.map(server => {
|
||||
if ("url" in server) {
|
||||
@@ -206,10 +86,10 @@ function neutralizeOrdinaryAntigravityPrompt(text: string): string {
|
||||
}
|
||||
|
||||
function extractAvailableModelIds(sessionResult: Json): string[] {
|
||||
const available = record(sessionResult.models).availableModels;
|
||||
const available = jsonRecord(sessionResult.models).availableModels;
|
||||
if (!Array.isArray(available)) return [];
|
||||
return available.flatMap(entry => {
|
||||
const id = record(entry).modelId;
|
||||
const id = jsonRecord(entry).modelId;
|
||||
return typeof id === "string" && id ? [id] : [];
|
||||
});
|
||||
}
|
||||
@@ -222,14 +102,8 @@ function confirmedModelMatches(selections: Map<string, string>, requested: strin
|
||||
return typeof level === "string" && `${family}-${level}` === requested;
|
||||
}
|
||||
|
||||
function addUsage(total: Json | null, usage: unknown): Json | null {
|
||||
const value = record(usage);
|
||||
if (Object.keys(value).length === 0) return total;
|
||||
const next: Json = { ...(total ?? {}) };
|
||||
for (const key of ["inputTokens", "outputTokens", "cachedReadTokens", "cachedWriteTokens", "thoughtTokens", "totalTokens"]) {
|
||||
if (typeof value[key] === "number") next[key] = (typeof next[key] === "number" ? next[key] as number : 0) + (value[key] as number);
|
||||
}
|
||||
return next;
|
||||
function replyConfirmsModel(reply: Json | undefined, requested: string): boolean {
|
||||
return jsonRecord(jsonRecord(reply).models).currentModelId === requested;
|
||||
}
|
||||
|
||||
interface SavedAntigravitySession {
|
||||
@@ -241,7 +115,7 @@ interface SavedAntigravitySession {
|
||||
|
||||
async function readSavedSession(stateDirectory: string): Promise<SavedAntigravitySession | null> {
|
||||
try {
|
||||
const parsed = record(JSON.parse(await readFile(join(stateDirectory, SESSION_RECORD_FILE), "utf8")));
|
||||
const parsed = jsonRecord(JSON.parse(await readFile(join(stateDirectory, SESSION_RECORD_FILE), "utf8")));
|
||||
if (typeof parsed.sessionId !== "string" || !parsed.sessionId || typeof parsed.cwd !== "string") return null;
|
||||
return {
|
||||
sessionId: parsed.sessionId,
|
||||
@@ -262,11 +136,14 @@ async function writeSavedSession(stateDirectory: string, saved: SavedAntigravity
|
||||
}
|
||||
|
||||
async function applyModelSelection(
|
||||
connection: Connection,
|
||||
connection: AntigravityAcpConnection,
|
||||
sessionId: string,
|
||||
model: string,
|
||||
timeoutMs: number,
|
||||
readbackTimeoutMs: number,
|
||||
selections: Map<string, string>,
|
||||
mergeSelections: (source: unknown) => void,
|
||||
waitForSelection: (predicate: () => boolean, limitMs: number) => Promise<boolean>,
|
||||
): Promise<void> {
|
||||
let reply: Json | undefined;
|
||||
try {
|
||||
@@ -278,9 +155,13 @@ async function applyModelSelection(
|
||||
reply = undefined;
|
||||
}
|
||||
}
|
||||
if (reply) for (const [k, v] of antigravitySelections(reply)) selections.set(k, v);
|
||||
if (reply) mergeSelections(reply);
|
||||
await connection.drain();
|
||||
if (selections.size > 0 && !confirmedModelMatches(selections, model)) {
|
||||
const isConfirmed = () => confirmedModelMatches(selections, model) || replyConfirmsModel(reply, model);
|
||||
if (!isConfirmed() && reply !== undefined) {
|
||||
await waitForSelection(isConfirmed, readbackTimeoutMs);
|
||||
}
|
||||
if (!isConfirmed()) {
|
||||
// Some models may require setting family and thought_level separately.
|
||||
const cut = model.lastIndexOf("-");
|
||||
if (cut > 0) {
|
||||
@@ -288,16 +169,19 @@ async function applyModelSelection(
|
||||
const level = model.slice(cut + 1);
|
||||
try {
|
||||
const r1 = await connection.request("session/set_config_option", { sessionId, configId: "model", value: family }, timeoutMs);
|
||||
for (const [k, v] of antigravitySelections(r1)) selections.set(k, v);
|
||||
mergeSelections(r1);
|
||||
const r2 = await connection.request("session/set_config_option", { sessionId, configId: "thought_level", value: level }, timeoutMs);
|
||||
for (const [k, v] of antigravitySelections(r2)) selections.set(k, v);
|
||||
mergeSelections(r2);
|
||||
await connection.drain();
|
||||
if (!confirmedModelMatches(selections, model)) {
|
||||
await waitForSelection(() => confirmedModelMatches(selections, model), readbackTimeoutMs);
|
||||
}
|
||||
} catch {
|
||||
// Handled by confirmation check below.
|
||||
// Handled by fail-closed confirmation check below.
|
||||
}
|
||||
}
|
||||
}
|
||||
if (selections.size > 0 && !confirmedModelMatches(selections, model)) {
|
||||
if (!isConfirmed()) {
|
||||
throw new AntigravityAcpError(
|
||||
"ANTIGRAVITY_MODEL_UNAVAILABLE",
|
||||
`Antigravity could not select model ${model}. Choose an available model for this agent and try again.`,
|
||||
@@ -319,6 +203,7 @@ export async function openAntigravityAcpRuntime(
|
||||
}
|
||||
options.signal?.throwIfAborted();
|
||||
const requestTimeoutMs = dependencies.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||
const readbackTimeoutMs = dependencies.readbackTimeoutMs ?? DEFAULT_READBACK_TIMEOUT_MS;
|
||||
let currentModel = options.profile.reportedModelId?.trim() ?? "";
|
||||
if (!currentModel) {
|
||||
throw new AntigravityAcpError("ANTIGRAVITY_MODEL_REQUIRED", "Antigravity requires an explicit model.", "invalid_request");
|
||||
@@ -329,7 +214,10 @@ export async function openAntigravityAcpRuntime(
|
||||
? { credentialFenceFds: options.credentialFenceFds, activateCredentialFenceOwner: options.activateCredentialFenceOwner }
|
||||
: undefined;
|
||||
const child = options.command.spawn([], { cwd: options.cwd, env: { ...options.launchEnvironment } }, lifetime) as ChildProcessWithoutNullStreams;
|
||||
const connection = new Connection(child);
|
||||
const connection = new AntigravityAcpConnection(child, {
|
||||
createProcessLostError: () => new ProcessLostError(),
|
||||
createTimeoutError: method => new AntigravityAcpError("ANTIGRAVITY_RPC_TIMEOUT", `Antigravity did not answer ${method} in time.`),
|
||||
});
|
||||
const lineage = trackAntigravityProcessLineage(child.pid, {
|
||||
sampleIntervalMs: dependencies.lineageSampleIntervalMs,
|
||||
readTable: dependencies.readProcessTable,
|
||||
@@ -340,14 +228,52 @@ export async function openAntigravityAcpRuntime(
|
||||
.catch((error: unknown) => { retirement = null; throw error; });
|
||||
|
||||
const selections = new Map<string, string>();
|
||||
const selectionWaiters = new Set<() => void>();
|
||||
let readOnlyModeBound = false;
|
||||
let modeDriftError: AntigravityAcpError | null = null;
|
||||
let onModeDrift: ((error: AntigravityAcpError) => void) | null = null;
|
||||
const notifySelectionWaiters = () => { for (const waiter of selectionWaiters) waiter(); };
|
||||
const mergeSelections = (source: unknown) => {
|
||||
const updates = antigravitySelections(source);
|
||||
const currentModeId = jsonRecord(source).currentModeId;
|
||||
if (typeof currentModeId === "string" && currentModeId) updates.set("mode", currentModeId);
|
||||
for (const [k, v] of updates) selections.set(k, v);
|
||||
if (readOnlyModeBound && selections.get("mode") !== "plan" && !modeDriftError) {
|
||||
modeDriftError = new AntigravityAcpError("ANTIGRAVITY_MODE_DRIFT", "Antigravity left read-only plan mode.", "unknown");
|
||||
onModeDrift?.(modeDriftError);
|
||||
void retire().catch(() => undefined);
|
||||
}
|
||||
notifySelectionWaiters();
|
||||
};
|
||||
const waitForSelection = (predicate: () => boolean, limitMs: number): Promise<boolean> => {
|
||||
if (predicate()) return Promise.resolve(true);
|
||||
if (connection.lost || options.signal?.aborted) return Promise.resolve(false);
|
||||
return new Promise<boolean>(resolve => {
|
||||
let done = false;
|
||||
const finish = (matched: boolean) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
selectionWaiters.delete(check);
|
||||
options.signal?.removeEventListener("abort", onAbort);
|
||||
resolve(matched);
|
||||
};
|
||||
const check = () => { if (predicate()) finish(true); else if (connection.lost) finish(false); };
|
||||
const onAbort = () => finish(false);
|
||||
const timer = setTimeout(() => finish(predicate()), limitMs);
|
||||
timer.unref?.();
|
||||
selectionWaiters.add(check);
|
||||
options.signal?.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
};
|
||||
connection.onLost = notifySelectionWaiters;
|
||||
|
||||
let updateListener: ((params: Json) => void) | null = null;
|
||||
connection.onNotification = (method, params) => {
|
||||
if (method !== "session/update") return;
|
||||
const update = record(params.update);
|
||||
if (update.sessionUpdate === "config_option_update") {
|
||||
for (const [k, v] of antigravitySelections(update)) selections.set(k, v);
|
||||
} else if (update.sessionUpdate === "current_mode_update" && typeof update.currentModeId === "string") {
|
||||
selections.set("mode", update.currentModeId);
|
||||
const update = jsonRecord(params.update);
|
||||
if (update.sessionUpdate === "config_option_update" || update.sessionUpdate === "current_mode_update") {
|
||||
mergeSelections(update);
|
||||
}
|
||||
updateListener?.(params);
|
||||
};
|
||||
@@ -356,6 +282,8 @@ export async function openAntigravityAcpRuntime(
|
||||
paperclipServerOwned: options.mcpServers.some(server => server.runnerOwned && server.name === ANTIGRAVITY_PAPERCLIP_MCP_SERVER),
|
||||
paperclipTools: new Set(options.paperclipTools ?? []),
|
||||
};
|
||||
const runnerOwnedMcpServerNames = new Set(options.mcpServers.filter(server => server.runnerOwned).map(server => server.name));
|
||||
const allConfiguredMcpServersAreRunnerOwned = options.mcpServers.length > 0 && options.mcpServers.every(server => server.runnerOwned);
|
||||
|
||||
const abortAdmission = () => { void retire().catch(() => undefined); };
|
||||
options.signal?.addEventListener("abort", abortAdmission, { once: true });
|
||||
@@ -373,11 +301,11 @@ export async function openAntigravityAcpRuntime(
|
||||
clientInfo: { name: "paperclip-runner", version: "1" },
|
||||
}, requestTimeoutMs);
|
||||
options.signal?.throwIfAborted();
|
||||
const info = record(initialized.agentInfo);
|
||||
const info = jsonRecord(initialized.agentInfo);
|
||||
if (info.name !== ANTIGRAVITY_CLI_AGENT_NAME || info.version !== ANTIGRAVITY_RUNTIME_VERSION) {
|
||||
throw new AntigravityAcpError("ANTIGRAVITY_IDENTITY_MISMATCH", "Antigravity runtime did not report its pinned version.");
|
||||
}
|
||||
const appendCap = record(record(record(record(initialized.agentCapabilities)._meta).antigravity).systemPrompt).append;
|
||||
const appendCap = jsonRecord(jsonRecord(jsonRecord(jsonRecord(initialized.agentCapabilities)._meta).antigravity).systemPrompt).append;
|
||||
if (appendCap !== true) {
|
||||
throw new AntigravityAcpError("ANTIGRAVITY_CAPABILITY_MISMATCH", "Antigravity runtime does not support Paperclip system instructions.");
|
||||
}
|
||||
@@ -404,7 +332,7 @@ export async function openAntigravityAcpRuntime(
|
||||
}, requestTimeoutMs);
|
||||
sessionId = typeof opened.sessionId === "string" && opened.sessionId ? opened.sessionId : saved.sessionId;
|
||||
} catch (error) {
|
||||
if (error instanceof RpcError && (error.error.code === -32000 || /auth/i.test(String(error.error.message)))) {
|
||||
if (error instanceof AntigravityRpcError && (error.error.code === -32000 || /auth/i.test(String(error.error.message)))) {
|
||||
throw new AntigravityAcpError("ANTIGRAVITY_AUTH_REQUIRED", "Google Antigravity sign-in is required. Reconnect your Google account and try again.", "authentication");
|
||||
}
|
||||
throw new AntigravitySavedStateIncompatibleError("the saved Antigravity conversation could not be resumed");
|
||||
@@ -417,7 +345,7 @@ export async function openAntigravityAcpRuntime(
|
||||
...(sessionMeta ? { _meta: sessionMeta } : {}),
|
||||
}, requestTimeoutMs);
|
||||
} catch (error) {
|
||||
if (error instanceof RpcError && (error.error.code === -32000 || /auth/i.test(String(error.error.message)))) {
|
||||
if (error instanceof AntigravityRpcError && (error.error.code === -32000 || /auth/i.test(String(error.error.message)))) {
|
||||
throw new AntigravityAcpError("ANTIGRAVITY_AUTH_REQUIRED", "Google Antigravity sign-in is required. Reconnect your Google account and try again.", "authentication");
|
||||
}
|
||||
throw error;
|
||||
@@ -429,7 +357,7 @@ export async function openAntigravityAcpRuntime(
|
||||
}
|
||||
|
||||
options.signal?.throwIfAborted();
|
||||
for (const [k, v] of antigravitySelections(opened)) selections.set(k, v);
|
||||
mergeSelections(opened);
|
||||
availableModelIds = extractAvailableModelIds(opened);
|
||||
if (availableModelIds.length > 0 && !availableModelIds.includes(currentModel)) {
|
||||
throw new AntigravityAcpError(
|
||||
@@ -439,19 +367,32 @@ export async function openAntigravityAcpRuntime(
|
||||
);
|
||||
}
|
||||
if (options.readOnly === true) {
|
||||
await connection.request("session/set_mode", { sessionId, modeId: "plan" }, requestTimeoutMs);
|
||||
const modeReply = await connection.request("session/set_mode", { sessionId, modeId: "plan" }, requestTimeoutMs);
|
||||
mergeSelections(modeReply);
|
||||
await connection.drain();
|
||||
const confirmedPlan = await waitForSelection(() => selections.get("mode") === "plan", readbackTimeoutMs);
|
||||
if (!confirmedPlan || selections.get("mode") !== "plan") {
|
||||
throw new AntigravityAcpError(
|
||||
"ANTIGRAVITY_MODE_UNAVAILABLE",
|
||||
"Antigravity could not enter read-only plan mode.",
|
||||
"unknown",
|
||||
);
|
||||
}
|
||||
readOnlyModeBound = true;
|
||||
}
|
||||
await applyModelSelection(connection, sessionId, currentModel, requestTimeoutMs, selections);
|
||||
await applyModelSelection(
|
||||
connection, sessionId, currentModel, requestTimeoutMs, readbackTimeoutMs,
|
||||
selections, mergeSelections, waitForSelection,
|
||||
);
|
||||
options.signal?.throwIfAborted();
|
||||
await writeSavedSession(options.stateDirectory, {
|
||||
sessionId,
|
||||
cwd: options.cwd,
|
||||
model: currentModel,
|
||||
readOnly: options.readOnly === true,
|
||||
}).catch(() => undefined);
|
||||
options.signal?.throwIfAborted();
|
||||
} catch (error) {
|
||||
options.signal?.removeEventListener("abort", abortAdmission);
|
||||
await rm(join(options.stateDirectory, SESSION_RECORD_FILE), { force: true }).catch(() => undefined);
|
||||
const cleanup = retire();
|
||||
options.retainFailedAdmissionCleanup(cleanup);
|
||||
await cleanup.catch(() => undefined);
|
||||
@@ -465,21 +406,22 @@ export async function openAntigravityAcpRuntime(
|
||||
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> => {
|
||||
const runTurn = async (input: AcpxRuntimeTurnInput, events: AntigravityAcpEventQueue, started: () => void): Promise<AcpRuntimeTurnResult> => {
|
||||
let cancelled = false;
|
||||
let wake: (() => void) | null = null;
|
||||
active!.cancel = async () => { cancelled = true; connection.notify("session/cancel", { sessionId }); wake?.(); };
|
||||
status.lastRequestId = input.requestId;
|
||||
let transcript = "";
|
||||
let streamedUsage: Json | null = null;
|
||||
onModeDrift = () => { wake?.(); };
|
||||
|
||||
updateListener = params => {
|
||||
if (params.sessionId !== sessionId) return;
|
||||
const update = record(params.update);
|
||||
const update = jsonRecord(params.update);
|
||||
const event = acpRuntimeEventFromValidatedSessionUpdate({ method: "session/update", params });
|
||||
if (!event) return;
|
||||
if (update.sessionUpdate === "usage_update") {
|
||||
const breakdown = record(record(event).breakdown);
|
||||
const breakdown = jsonRecord(jsonRecord(event).breakdown);
|
||||
if (Object.keys(breakdown).length > 0) streamedUsage = breakdown;
|
||||
}
|
||||
if (event.type === "text_delta" && event.stream === "output") transcript += event.text;
|
||||
@@ -488,36 +430,55 @@ export async function openAntigravityAcpRuntime(
|
||||
|
||||
connection.onRequest = async (method, params) => {
|
||||
if (method !== "session/request_permission" || params.sessionId !== sessionId) throw new Error("unsupported");
|
||||
const choices = Array.isArray(params.options) ? params.options.map(record) : [];
|
||||
const choices = Array.isArray(params.options) ? params.options.map(jsonRecord) : [];
|
||||
const pick = (outcome: "allow_once" | "reject_once" | "allow_always" | "reject_always") => {
|
||||
const fallbackKind = outcome.startsWith("allow") ? "allow_once" : "reject_once";
|
||||
const option = choices.find(choice => choice.kind === outcome) ?? choices.find(choice => choice.kind === fallbackKind);
|
||||
return option ? { outcome: { outcome: "selected", optionId: option.optionId } } : { outcome: { outcome: "cancelled" } };
|
||||
};
|
||||
const toolCall = jsonRecord(params.toolCall);
|
||||
const inferredKind = typeof toolCall.kind === "string"
|
||||
? toolCall.kind as AcpPermissionRequest["inferredKind"]
|
||||
: undefined;
|
||||
const permissionRequest: AcpPermissionRequest = {
|
||||
sessionId,
|
||||
raw: params as unknown as AcpPermissionRequest["raw"],
|
||||
inferredKind,
|
||||
};
|
||||
if (options.readOnly === true) {
|
||||
return pick(antigravityPlanModeAllows({ raw: params }, planPolicy) ? "allow_once" : "reject_once");
|
||||
return pick(antigravityPlanModeAllows(permissionRequest, planPolicy) ? "allow_once" : "reject_once");
|
||||
}
|
||||
const disposition = decideAcpxPermission("antigravity", options.permissionMode, permissionRequest, {
|
||||
runnerOwnedMcpServerNames,
|
||||
allConfiguredMcpServersAreRunnerOwned,
|
||||
});
|
||||
if (disposition === "allow_once") return pick("allow_once");
|
||||
if (disposition === "reject_once") return pick("reject_once");
|
||||
if (input.onPermissionRequest) {
|
||||
try {
|
||||
const permAbort = new AbortController();
|
||||
const decision = await input.onPermissionRequest(
|
||||
params as Parameters<NonNullable<AcpxRuntimeTurnInput["onPermissionRequest"]>>[0],
|
||||
permissionRequest,
|
||||
{ signal: input.signal ?? permAbort.signal, responseDelivery: Promise.resolve() },
|
||||
);
|
||||
const outcome = decision?.outcome;
|
||||
const choiceKind = outcome === "allow_once" || outcome === "allow_always" || outcome === "reject_once" || outcome === "reject_always"
|
||||
? outcome : "reject_once";
|
||||
return pick(choiceKind);
|
||||
if (!decision || decision.outcome === "cancel") {
|
||||
return { outcome: { outcome: "cancelled" } };
|
||||
}
|
||||
if (decision.outcome === "selected") {
|
||||
const matched = choices.find(choice => choice.optionId === decision.optionId);
|
||||
return matched ? { outcome: { outcome: "selected", optionId: matched.optionId } } : { outcome: { outcome: "cancelled" } };
|
||||
}
|
||||
return pick(decision.outcome);
|
||||
} catch {
|
||||
return pick("reject_once");
|
||||
}
|
||||
}
|
||||
return pick(options.permissionMode === "approve-all" ? "allow_once" : "reject_once");
|
||||
return pick("reject_once");
|
||||
};
|
||||
|
||||
const keepUsage = (reported: unknown) => {
|
||||
const answered = record(reported);
|
||||
const usage = Object.keys(answered).length > 0 ? addUsage(null, answered) : streamedUsage ? addUsage(null, streamedUsage) : null;
|
||||
const answered = jsonRecord(reported);
|
||||
const usage = Object.keys(answered).length > 0 ? addAntigravityUsage(null, answered) : streamedUsage ? addAntigravityUsage(null, streamedUsage) : null;
|
||||
if (usage) {
|
||||
status.terminalPromptUsage = {
|
||||
requestId: input.requestId,
|
||||
@@ -529,12 +490,14 @@ export async function openAntigravityAcpRuntime(
|
||||
|
||||
const dispatch = input.dispatchJournal?.markReceived() ? input.dispatchJournal : null;
|
||||
try {
|
||||
if (modeDriftError) throw modeDriftError;
|
||||
dispatch?.markDispatched();
|
||||
const promptText = neutralizeOrdinaryAntigravityPrompt(input.text);
|
||||
const response = connection.request("session/prompt", { sessionId, prompt: [{ type: "text", text: promptText }] }, null);
|
||||
started();
|
||||
const interrupted = new Promise<"interrupted">(resolve => { wake = () => resolve("interrupted"); });
|
||||
const outcome = await Promise.race([response, interrupted]);
|
||||
if (modeDriftError) throw modeDriftError;
|
||||
if (outcome === "interrupted") {
|
||||
const grace = dependencies.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS;
|
||||
const settled = await Promise.race([
|
||||
@@ -560,6 +523,9 @@ export async function openAntigravityAcpRuntime(
|
||||
return { status: "completed", stopReason };
|
||||
} catch (error) {
|
||||
keepUsage(undefined);
|
||||
if (modeDriftError) {
|
||||
return { status: "failed", error: { code: modeDriftError.code, message: modeDriftError.message, retryable: false } };
|
||||
}
|
||||
if (connection.lost instanceof ProcessLostError || error instanceof ProcessLostError) {
|
||||
return cancelled
|
||||
? { status: "cancelled", stopReason: "cancelled" }
|
||||
@@ -575,6 +541,7 @@ export async function openAntigravityAcpRuntime(
|
||||
};
|
||||
} finally {
|
||||
updateListener = null;
|
||||
onModeDrift = null;
|
||||
wake = null;
|
||||
}
|
||||
};
|
||||
@@ -600,7 +567,10 @@ export async function openAntigravityAcpRuntime(
|
||||
async setModel(nextModel: string): Promise<void> {
|
||||
const normalized = nextModel.trim();
|
||||
if (!normalized || normalized === currentModel) return;
|
||||
await applyModelSelection(connection, sessionId, normalized, requestTimeoutMs, selections);
|
||||
await applyModelSelection(
|
||||
connection, sessionId, normalized, requestTimeoutMs, readbackTimeoutMs,
|
||||
selections, mergeSelections, waitForSelection,
|
||||
);
|
||||
currentModel = normalized;
|
||||
await writeSavedSession(options.stateDirectory, {
|
||||
sessionId,
|
||||
@@ -612,7 +582,7 @@ export async function openAntigravityAcpRuntime(
|
||||
startTurn(input: AcpxRuntimeTurnInput): AcpxRuntimeTurn {
|
||||
if (closed) throw new Error("The Antigravity session is closed");
|
||||
if (active) throw new Error("An Antigravity turn is already running");
|
||||
const events = new EventQueue();
|
||||
const events = new AntigravityAcpEventQueue();
|
||||
let markStarted!: () => void;
|
||||
const promptStarted = new Promise<void>(resolve => { markStarted = resolve; });
|
||||
const turn = { cancel: async (_reason?: string) => {}, result: Promise.resolve() as unknown as Promise<AcpRuntimeTurnResult> };
|
||||
|
||||
@@ -7,6 +7,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
const setup = vi.hoisted(() => ({ spawn: vi.fn(), close: vi.fn(async () => undefined), verify: vi.fn(), spec: vi.fn((..._args: unknown[]) => ({ pinned: true })) }));
|
||||
vi.mock("./antigravity-installation.js", () => ({ antigravityNativeDistributionSpec: setup.spec }));
|
||||
vi.mock("./installation-integrity.js", () => ({ verifyNativeAcpxInstallation: setup.verify }));
|
||||
import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.js";
|
||||
import {
|
||||
ANTIGRAVITY_CLI_TOKEN_DIR,
|
||||
ANTIGRAVITY_CLI_TOKEN_FILE,
|
||||
@@ -192,6 +193,70 @@ describe("Antigravity setup-only Google authentication (agy acp --login)", () =>
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("verifies and persists rotated consumer credentials without a pre-existing antigravity-cli directory", async () => {
|
||||
const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-consumer-verify-")));
|
||||
roots.push(home);
|
||||
await mkdir(join(home, "antigravity-acp"), { mode: 0o700 });
|
||||
const token = join(home, "antigravity-acp", "acp_token.json");
|
||||
await writeFile(token, JSON.stringify(CONSUMER_CREDENTIAL), { mode: 0o600 });
|
||||
|
||||
// Fake `agy acp` peer that refreshes the staged CLI token on `session/new` without running any prompt.
|
||||
const peer = join(home, "refresh-peer.cjs");
|
||||
await writeFile(peer, `
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const readline = require('node:readline');
|
||||
const home = process.argv[2];
|
||||
const rl = readline.createInterface({ input: process.stdin });
|
||||
rl.on('line', line => {
|
||||
if (!line.trim()) return;
|
||||
const msg = JSON.parse(line);
|
||||
if (msg.method === 'initialize') {
|
||||
process.stdout.write(JSON.stringify({
|
||||
jsonrpc: '2.0', id: msg.id,
|
||||
result: { protocolVersion: 1, agentInfo: { name: 'Antigravity ACP Server', version: ${JSON.stringify(ANTIGRAVITY_RUNTIME_VERSION)} } },
|
||||
}) + '\\n');
|
||||
return;
|
||||
}
|
||||
if (msg.method === 'session/new') {
|
||||
const cliTokenPath = path.join(home, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_DIR)}, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_FILE)});
|
||||
const staged = JSON.parse(fs.readFileSync(cliTokenPath, 'utf8'));
|
||||
if (staged.token.refresh_token !== 'fixture-cli-refresh-token') process.exit(2);
|
||||
fs.writeFileSync(cliTokenPath, JSON.stringify({
|
||||
token: {
|
||||
access_token: 'fixture-refreshed-access-token',
|
||||
token_type: 'Bearer',
|
||||
refresh_token: 'fixture-rotated-consumer-refresh',
|
||||
expiry: '2099-01-01T00:00:00Z',
|
||||
},
|
||||
auth_method: 'consumer',
|
||||
}), { mode: 0o600 });
|
||||
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id, result: { sessionId: 'sess-refresh' } }) + '\\n');
|
||||
return;
|
||||
}
|
||||
});
|
||||
`);
|
||||
setup.verify.mockResolvedValue({ openCommand: async () => ({ spawn: setup.spawn, close: setup.close }) });
|
||||
setup.spawn.mockImplementation((_args, options) => {
|
||||
const child = spawn(process.execPath, [peer, home], { ...options, detached: true });
|
||||
children.push(child);
|
||||
return child;
|
||||
});
|
||||
const fetch = googleUserinfo(true, "fixture-refreshed-access-token");
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
|
||||
const verified = await verifyAntigravityCredential(home);
|
||||
expect(verified.accountEmail).toBe("person@example.test");
|
||||
expect(JSON.parse(verified.credential)).toEqual({
|
||||
...CONSUMER_CREDENTIAL,
|
||||
refresh_token: "fixture-rotated-consumer-refresh",
|
||||
});
|
||||
expect(JSON.parse(await readFile(token, "utf8")).refresh_token).toBe("fixture-rotated-consumer-refresh");
|
||||
await expect(access(join(home, ANTIGRAVITY_CLI_TOKEN_DIR, ANTIGRAVITY_CLI_TOKEN_FILE))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
expect(setup.close).toHaveBeenCalledOnce();
|
||||
}, 15_000);
|
||||
|
||||
it("relays a validated callback URL to agy acp --login, converts the CLI token to canonical acp_token.json, and caches verification", async () => {
|
||||
const stateToken = `callback_state_${Date.now()}`;
|
||||
const home = await fixture("success", stateToken);
|
||||
|
||||
@@ -7,6 +7,7 @@ import { StringDecoder } from "node:string_decoder";
|
||||
import { antigravityPrivateEnvironment, checkAntigravityPrivateHome, retireAntigravityProcess } from "./antigravity-process.js";
|
||||
import { antigravityNativeDistributionSpec } from "./antigravity-installation.js";
|
||||
import { AntigravityRuntimeUnavailableError } from "./antigravity-runtime-unavailable.js";
|
||||
import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.js";
|
||||
import { verifyNativeAcpxInstallation, type VerifiedAcpxCommandLease } from "./installation-integrity.js";
|
||||
|
||||
const CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
|
||||
@@ -217,6 +218,10 @@ async function writeCanonicalCredentialFile(home: string, credential: string): P
|
||||
catch (error) { await handle.close(); await rm(tmp, { force: true }); throw error; }
|
||||
await handle.close();
|
||||
await rename(tmp, join(parent, "acp_token.json"));
|
||||
if (process.platform !== "win32") {
|
||||
const dirHandle = await open(parent, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
||||
try { await dirHandle.sync(); } finally { await dirHandle.close(); }
|
||||
}
|
||||
}
|
||||
|
||||
async function googleJson(url: string, options: RequestInit): Promise<Record<string, unknown>> {
|
||||
@@ -248,6 +253,136 @@ async function fetchGoogleAccountEmail(accessToken: string, signal?: AbortSignal
|
||||
return email;
|
||||
}
|
||||
|
||||
/** Refresh a client-secret-less consumer credential via the pinned `agy acp` binary
|
||||
* without calling any model API (`initialize` + `session/new` only), verify Google
|
||||
* account identity via userinfo, persist any rotated refresh token durably to
|
||||
* `acp_token.json`, and scrub the temporary CLI token file. */
|
||||
async function refreshConsumerCredentialWithAgy(
|
||||
home: string,
|
||||
credential: string,
|
||||
outerSignal?: AbortSignal,
|
||||
): Promise<{ credential: string; accountEmail: string }> {
|
||||
const deadline = new AbortController();
|
||||
const deadlineTimer = setTimeout(() => deadline.abort(), 30_000);
|
||||
const signal = outerSignal ? AbortSignal.any([outerSignal, deadline.signal]) : deadline.signal;
|
||||
const cliDir = join(home, ANTIGRAVITY_CLI_TOKEN_DIR);
|
||||
const cliTokenPath = join(cliDir, ANTIGRAVITY_CLI_TOKEN_FILE);
|
||||
let lease: VerifiedAcpxCommandLease | undefined;
|
||||
let child: ChildProcessWithoutNullStreams | undefined;
|
||||
let closed: Promise<void> | undefined;
|
||||
let stagedTemporary = false;
|
||||
let rotationSaved = false;
|
||||
try {
|
||||
signal.throwIfAborted();
|
||||
await mkdir(cliDir, { recursive: true, mode: 0o700 });
|
||||
const dirStat = await lstat(cliDir);
|
||||
if (!dirStat.isDirectory() || dirStat.isSymbolicLink() || dirStat.uid !== process.getuid?.() || (dirStat.mode & 0o077) !== 0) {
|
||||
throw new Error("Invalid Antigravity credential");
|
||||
}
|
||||
await rm(cliTokenPath, { force: true });
|
||||
await writeFile(cliTokenPath, antigravityCliStoredTokenFromCanonical(credential), { flag: "wx", mode: 0o600 });
|
||||
stagedTemporary = true;
|
||||
signal.throwIfAborted();
|
||||
let installation;
|
||||
try {
|
||||
installation = await verifyNativeAcpxInstallation(
|
||||
antigravityNativeDistributionSpec(process.platform, process.arch, ["--gemini-dir", home, "--disable-telemetry"]),
|
||||
);
|
||||
} catch {
|
||||
throw new AntigravityRuntimeUnavailableError();
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
lease = await installation.openCommand({ signal });
|
||||
const environment = await antigravityPrivateEnvironment(home);
|
||||
const workspace = join(home, "tmp");
|
||||
signal.throwIfAborted();
|
||||
child = lease.spawn([], { cwd: workspace, stdio: "pipe", detached: process.platform !== "win32", env: environment }) as ChildProcessWithoutNullStreams;
|
||||
const peer = child;
|
||||
closed = new Promise(resolve => peer.once("close", () => resolve()));
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let phase = 1, stdout = "", outputBytes = 0, errorBytes = 0, settled = false;
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
const fail = () => { if (!settled) { settled = true; reject(new Error(LOGIN_ERROR)); } };
|
||||
const done = () => { if (!settled) { settled = true; resolve(); } };
|
||||
const onAbort = () => fail();
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
const send = (id: 1 | 2) => peer.stdin.write(`${JSON.stringify(id === 1
|
||||
? { jsonrpc: "2.0", id, method: "initialize", params: { protocolVersion: 1, clientInfo: { name: "paperclip-runner", version: "1" }, clientCapabilities: {} } }
|
||||
: { jsonrpc: "2.0", id, method: "session/new", params: { cwd: workspace, mcpServers: [] } })}\n`);
|
||||
peer.stdout.on("data", (chunk: Buffer) => {
|
||||
outputBytes += chunk.length;
|
||||
if (outputBytes > 2 * 1024 * 1024) { fail(); return; }
|
||||
try { stdout += decoder.decode(chunk, { stream: true }); } catch { fail(); return; }
|
||||
while (stdout.includes("\n") && !settled) {
|
||||
const end = stdout.indexOf("\n"), line = stdout.slice(0, end); stdout = stdout.slice(end + 1);
|
||||
if (!line.trim()) continue;
|
||||
let message: Record<string, unknown>;
|
||||
try { message = record(JSON.parse(line)); } catch { fail(); return; }
|
||||
if ("method" in message) {
|
||||
if ("id" in message && message.id !== undefined) {
|
||||
peer.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "unsupported" } })}\n`);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (phase > 2 || message.jsonrpc !== "2.0" || message.id !== phase || "error" in message || !Object.hasOwn(message, "result")) { fail(); return; }
|
||||
if (phase === 1) {
|
||||
const initialized = record(message.result), info = record(initialized.agentInfo);
|
||||
if (initialized.protocolVersion !== 1 || info.name !== "Antigravity ACP Server" || info.version !== ANTIGRAVITY_RUNTIME_VERSION) {
|
||||
fail();
|
||||
return;
|
||||
}
|
||||
phase = 2;
|
||||
send(2);
|
||||
} else {
|
||||
phase = 3;
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
done();
|
||||
}
|
||||
}
|
||||
});
|
||||
peer.stderr.on("data", (chunk: Buffer) => { errorBytes += chunk.length; if (errorBytes > 2 * 1024 * 1024) fail(); });
|
||||
peer.once("error", fail);
|
||||
peer.once("close", () => { signal.removeEventListener("abort", onAbort); if (phase !== 3) fail(); });
|
||||
peer.stdin.on("error", () => { if (phase !== 3) fail(); });
|
||||
if (signal.aborted) fail(); else send(1);
|
||||
});
|
||||
await retireAntigravityProcess(peer, closed); child = undefined;
|
||||
await lease.close(); lease = undefined;
|
||||
const rawCli = await readPrivateTokenFile(cliDir, ANTIGRAVITY_CLI_TOKEN_FILE);
|
||||
const parsedCli = canonicalAntigravityCredentialFromCliToken(rawCli, credential);
|
||||
if (parsedCli.credential !== credential) {
|
||||
await writeCanonicalCredentialFile(home, parsedCli.credential);
|
||||
}
|
||||
rotationSaved = true;
|
||||
await rm(cliTokenPath, { force: true });
|
||||
stagedTemporary = false;
|
||||
if (!parsedCli.accessToken || parsedCli.accessToken === "expired") throw new Error(LOGIN_ERROR);
|
||||
const accountEmail = await fetchGoogleAccountEmail(parsedCli.accessToken, outerSignal);
|
||||
return { credential: parsedCli.credential, accountEmail };
|
||||
} finally {
|
||||
clearTimeout(deadlineTimer);
|
||||
if (child && closed) await retireAntigravityProcess(child, closed).catch(() => undefined);
|
||||
if (lease) await lease.close().catch(() => undefined);
|
||||
if (stagedTemporary) {
|
||||
// If `agy` rotated the refresh token before failing later, preserve it durably before scrubbing.
|
||||
try {
|
||||
const rawCli = await readPrivateTokenFile(cliDir, ANTIGRAVITY_CLI_TOKEN_FILE);
|
||||
const parsedCli = canonicalAntigravityCredentialFromCliToken(rawCli, credential);
|
||||
if (parsedCli.credential !== credential && !rotationSaved) {
|
||||
await writeCanonicalCredentialFile(home, parsedCli.credential);
|
||||
}
|
||||
await rm(cliTokenPath, { force: true }).catch(() => undefined);
|
||||
} catch (cleanupError) {
|
||||
if ((cleanupError as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
// Already absent.
|
||||
} else if (rotationSaved) {
|
||||
await rm(cliTokenPath, { force: true }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Refresh and check Google identity privately; this never calls a model API. */
|
||||
export async function verifyAntigravityCredential(home: string, options: { signal?: AbortSignal } = {}): Promise<{ credential: string; accountEmail: string }> {
|
||||
options.signal?.throwIfAborted();
|
||||
@@ -255,12 +390,31 @@ export async function verifyAntigravityCredential(home: string, options: { signa
|
||||
if (cached?.credential === credential) return { ...cached };
|
||||
const value = record(JSON.parse(credential));
|
||||
if (typeof value.client_secret !== "string" || !value.client_secret) {
|
||||
// `agy acp --login` writes a token without exposing client_secret; verify via CLI token file if still staged.
|
||||
const rawCli = await readPrivateTokenFile(join(home, ANTIGRAVITY_CLI_TOKEN_DIR), ANTIGRAVITY_CLI_TOKEN_FILE);
|
||||
const parsedCli = canonicalAntigravityCredentialFromCliToken(rawCli, credential);
|
||||
if (!parsedCli.accessToken || parsedCli.accessToken === "expired") throw new Error(LOGIN_ERROR);
|
||||
const accountEmail = await fetchGoogleAccountEmail(parsedCli.accessToken, options.signal);
|
||||
const verified = { credential: parsedCli.credential, accountEmail };
|
||||
// `agy acp --login` writes a consumer token without exposing client_secret.
|
||||
// Fast path: verify directly if a live CLI token is still staged in this home.
|
||||
let rawCli: string | null = null;
|
||||
try {
|
||||
rawCli = await readPrivateTokenFile(join(home, ANTIGRAVITY_CLI_TOKEN_DIR), ANTIGRAVITY_CLI_TOKEN_FILE);
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
}
|
||||
if (rawCli !== null) {
|
||||
const parsedCli = canonicalAntigravityCredentialFromCliToken(rawCli, credential);
|
||||
if (parsedCli.accessToken && parsedCli.accessToken !== "expired") {
|
||||
try {
|
||||
const accountEmail = await fetchGoogleAccountEmail(parsedCli.accessToken, options.signal);
|
||||
if (parsedCli.credential !== credential) {
|
||||
await writeCanonicalCredentialFile(home, parsedCli.credential);
|
||||
}
|
||||
const verified = { credential: parsedCli.credential, accountEmail };
|
||||
if (activeBrowserHomes.has(home)) verifiedCredentials.set(home, verified);
|
||||
return { ...verified };
|
||||
} catch {
|
||||
// Fall through to prompt-free `agy` refresh when the cached access token expired.
|
||||
}
|
||||
}
|
||||
}
|
||||
const verified = await refreshConsumerCredentialWithAgy(home, credential, options.signal);
|
||||
if (activeBrowserHomes.has(home)) verifiedCredentials.set(home, verified);
|
||||
return { ...verified };
|
||||
}
|
||||
|
||||
@@ -34,19 +34,21 @@ export async function stageManagedAntigravityCredential(input: {
|
||||
const canonical = inline ? sanitizeAntigravityCredential(inline) : undefined;
|
||||
const acpDirectory = join(input.agentHomeDirectory, "antigravity-acp");
|
||||
const cliDirectory = join(input.agentHomeDirectory, ANTIGRAVITY_CLI_TOKEN_DIR);
|
||||
const cliToken = join(cliDirectory, ANTIGRAVITY_CLI_TOKEN_FILE);
|
||||
const legacyToken = join(acpDirectory, "acp_token.json");
|
||||
const cliLog = join(input.agentHomeDirectory, "cli.log");
|
||||
const refresh = join(acpDirectory, "auth-refresh.json");
|
||||
await ensurePrivateSubdir(acpDirectory);
|
||||
await ensurePrivateSubdir(cliDirectory);
|
||||
// Reuse the established crash scrub, cleanup intent, and inherited quorum.
|
||||
// The extra native token filename is scrubbed while that quorum is held.
|
||||
// Reuse the established crash scrub, durable cleanup intent, crash quarantine,
|
||||
// and inherited quorum, extending them to cover the CLI token and log paths.
|
||||
const lease = await stageManagedCodexCredential({
|
||||
agentHomeDirectory: acpDirectory,
|
||||
environment: canonical ? { PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET: canonical } : { OPENAI_API_KEY: key },
|
||||
additionalCleanupPaths: [cliToken, legacyToken, cliLog],
|
||||
});
|
||||
const cliToken = join(cliDirectory, ANTIGRAVITY_CLI_TOKEN_FILE);
|
||||
const legacyToken = join(acpDirectory, "acp_token.json");
|
||||
const refresh = join(acpDirectory, "auth-refresh.json");
|
||||
try {
|
||||
for (const filename of [cliToken, legacyToken, refresh, `${refresh}.tmp`]) await rm(filename, { force: true });
|
||||
for (const filename of [cliToken, legacyToken, cliLog, refresh, `${refresh}.tmp`]) await rm(filename, { force: true });
|
||||
if (canonical) {
|
||||
await writeFile(cliToken, antigravityCliStoredTokenFromCanonical(canonical), { flag: "wx", mode: 0o600 });
|
||||
}
|
||||
@@ -100,6 +102,7 @@ export async function stageManagedAntigravityCredential(input: {
|
||||
}
|
||||
await rm(cliToken, { force: true });
|
||||
await rm(legacyToken, { force: true });
|
||||
await rm(cliLog, { force: true });
|
||||
await rm(join(acpDirectory, "logs"), { recursive: true, force: true });
|
||||
await lease.close();
|
||||
closed = true;
|
||||
|
||||
@@ -35,7 +35,13 @@ export class AntigravityModelDiscoveryCleanupError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
function retainCatalogCleanup(child: ChildProcessWithoutNullStreams | undefined, closed: Promise<void> | undefined, lease: VerifiedAcpxCommandLease): Promise<void> {
|
||||
function retainCatalogCleanup(
|
||||
child: ChildProcessWithoutNullStreams | undefined,
|
||||
closed: Promise<void> | undefined,
|
||||
lease: VerifiedAcpxCommandLease,
|
||||
home: string,
|
||||
staged: { canonical: string; cliTokenPath: string } | null,
|
||||
): Promise<void> {
|
||||
let observedClose = child === undefined;
|
||||
void closed?.then(() => { observedClose = true; });
|
||||
return (async () => {
|
||||
@@ -43,6 +49,7 @@ function retainCatalogCleanup(child: ChildProcessWithoutNullStreams | undefined,
|
||||
try {
|
||||
if (child && closed) await retireAntigravityProcess(child, closed);
|
||||
await lease.close();
|
||||
await syncAndCleanCliToken(home, staged);
|
||||
return;
|
||||
} catch {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -94,26 +101,33 @@ async function stageCliTokenFromAcpHome(home: string): Promise<{ canonical: stri
|
||||
return { canonical, cliTokenPath };
|
||||
}
|
||||
|
||||
/** Copy back any rotated refresh token from `antigravity-oauth-token` to `acp_token.json` and remove the CLI token. */
|
||||
/** Copy back any rotated refresh token from `antigravity-oauth-token` to `acp_token.json`
|
||||
* durably before removing the temporary CLI token. Never deletes the CLI token if saving
|
||||
* a rotated refresh token fails. */
|
||||
async function syncAndCleanCliToken(home: string, staged: { canonical: string; cliTokenPath: string } | null): Promise<void> {
|
||||
if (!staged) return;
|
||||
let raw: string | null = null;
|
||||
try {
|
||||
const raw = await readFile(staged.cliTokenPath, "utf8").catch(() => null);
|
||||
if (raw) {
|
||||
const refreshed = canonicalAntigravityCredentialFromCliToken(raw, staged.canonical).credential;
|
||||
if (refreshed !== staged.canonical) {
|
||||
const acpDir = join(home, "antigravity-acp");
|
||||
const tmp = join(acpDir, `acp_token.json.${randomUUID()}.tmp`);
|
||||
const handle = await open(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
||||
try { await handle.writeFile(refreshed); await handle.sync(); }
|
||||
catch (error) { await handle.close(); await rm(tmp, { force: true }); throw error; }
|
||||
await handle.close();
|
||||
await rename(tmp, join(acpDir, "acp_token.json"));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await rm(staged.cliTokenPath, { force: true }).catch(() => undefined);
|
||||
raw = await readFile(staged.cliTokenPath, "utf8");
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
|
||||
throw error;
|
||||
}
|
||||
const refreshed = canonicalAntigravityCredentialFromCliToken(raw, staged.canonical).credential;
|
||||
if (refreshed !== staged.canonical) {
|
||||
const acpDir = join(home, "antigravity-acp");
|
||||
const tmp = join(acpDir, `acp_token.json.${randomUUID()}.tmp`);
|
||||
const handle = await open(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
||||
try { await handle.writeFile(refreshed); await handle.sync(); }
|
||||
catch (error) { await handle.close(); await rm(tmp, { force: true }); throw error; }
|
||||
await handle.close();
|
||||
await rename(tmp, join(acpDir, "acp_token.json"));
|
||||
if (process.platform !== "win32") {
|
||||
const dirHandle = await open(acpDir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
|
||||
try { await dirHandle.sync(); } finally { await dirHandle.close(); }
|
||||
}
|
||||
}
|
||||
await rm(staged.cliTokenPath, { force: true });
|
||||
}
|
||||
|
||||
/** Read-only account catalog discovery through the pinned `agy acp` binary.
|
||||
@@ -201,13 +215,17 @@ export async function discoverAntigravityModels(
|
||||
await lease?.close();
|
||||
} catch (error) {
|
||||
if (lease) cleanupError = new AntigravityModelDiscoveryCleanupError(
|
||||
retainCatalogCleanup(child, closed, lease), failure,
|
||||
retainCatalogCleanup(child, closed, lease, home, staged), failure,
|
||||
error instanceof Error ? error : new Error("Antigravity process retirement or command lease release could not be confirmed"),
|
||||
);
|
||||
else failure ??= new Error(ERROR);
|
||||
}
|
||||
if (!cleanupError) {
|
||||
await syncAndCleanCliToken(home, staged).catch(() => undefined);
|
||||
try {
|
||||
await syncAndCleanCliToken(home, staged);
|
||||
} catch (error) {
|
||||
failure ??= error instanceof Error ? error : new Error(ERROR);
|
||||
}
|
||||
}
|
||||
clearTimeout(timer);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,10 @@ import { lstat, open as openFile, readdir } from "node:fs/promises";
|
||||
import { join, relative, sep } from "node:path";
|
||||
import type { AcpRuntimeEvent, AcpRuntimeTurnResult } from "acpx/runtime";
|
||||
import { userInfo } from "node:os";
|
||||
import {
|
||||
AntigravityAcpConnection, AntigravityAcpEventQueue as EventQueue, AntigravityRpcError as RpcError,
|
||||
addAntigravityUsage as addUsage, jsonRecord as record, type Json,
|
||||
} from "./antigravity-acp-connection.js";
|
||||
import { AntigravitySavedStateIncompatibleError } from "./antigravity-admission.js";
|
||||
import { retireAntigravityProcess } from "./antigravity-process.js";
|
||||
import { trackAntigravityProcessLineage, type ProcessTableRead } from "./antigravity-process-lineage.js";
|
||||
@@ -51,7 +55,6 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
|
||||
const DEFAULT_HELPER_WAIT_TIMEOUT_MS = 20 * 60_000;
|
||||
const DEFAULT_CANCEL_GRACE_MS = 5_000;
|
||||
const READBACK_TIMEOUT_MS = 5_000;
|
||||
const EXIT_OUTPUT_GRACE_MS = 200;
|
||||
const RETIREMENT_ATTEMPTS = 3;
|
||||
const CLEANUP_UNPROVEN_MESSAGE = "The swarm stopped, but Paperclip could not confirm that all of its helpers stopped, so it did not continue the task on its own. Files the helpers wrote stay in the task folder. Check them before you send /swarm again.";
|
||||
const SNAPSHOT_LIMIT = 20_000;
|
||||
@@ -80,10 +83,6 @@ export interface AntigravitySwarmRuntimeDependencies {
|
||||
readProcessTable?: () => Promise<ProcessTableRead>;
|
||||
}
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
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
|
||||
@@ -95,130 +94,6 @@ class ProcessLostError extends Error {
|
||||
constructor() { super(PROCESS_LOST_MESSAGE); }
|
||||
}
|
||||
|
||||
class RpcError extends Error {
|
||||
constructor(readonly method: string, readonly error: Json) {
|
||||
super(`${method} failed: ${typeof error.message === "string" ? error.message.slice(0, 500) : "provider error"}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Newline-delimited JSON-RPC over the CLI's stdio. Lines are handled one per macrotask
|
||||
* so a response's awaiting caller observes it before the updates that follow it. */
|
||||
class Connection {
|
||||
#next = 1;
|
||||
#pending = new Map<number, { method: string; resolve: (value: Json) => void; reject: (error: Error) => void }>();
|
||||
#buffer = "";
|
||||
#queue: Promise<void> = Promise.resolve();
|
||||
#lost: Error | null = null;
|
||||
readonly exited: Promise<void>;
|
||||
onNotification: (method: string, params: Json) => void = () => {};
|
||||
onRequest: (method: string, params: Json) => Promise<unknown> = async () => { throw new Error("unsupported"); };
|
||||
onLost: () => void = () => {};
|
||||
|
||||
constructor(readonly child: ChildProcessWithoutNullStreams) {
|
||||
// Exit, not close: helpers the CLI started inherit its output pipe and can
|
||||
// hold it open long after the CLI died. Output already written is read for
|
||||
// a short moment after exit; the lost CLI cannot answer anything later.
|
||||
this.exited = new Promise(resolve => child.once("exit", () => {
|
||||
if (child.stdout.readableEnded || child.stdout.destroyed) { resolve(); return; }
|
||||
const timer = setTimeout(resolve, EXIT_OUTPUT_GRACE_MS);
|
||||
child.stdout.once("close", () => { clearTimeout(timer); resolve(); });
|
||||
}));
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => {
|
||||
this.#buffer += chunk;
|
||||
if (this.#buffer.length > 16 * 1024 * 1024) { this.#fail(new Error("Antigravity CLI output exceeded its bound")); return; }
|
||||
for (let index = this.#buffer.indexOf("\n"); index >= 0; index = this.#buffer.indexOf("\n")) {
|
||||
const line = this.#buffer.slice(0, index); this.#buffer = this.#buffer.slice(index + 1);
|
||||
if (line.trim()) this.#queue = this.#queue.then(() => new Promise<void>(resolve => setImmediate(() => {
|
||||
// A handler failure must never escape into the event loop and end the sidecar.
|
||||
try { this.#line(line); } catch (error) { this.#fail(error instanceof Error ? error : new Error("Antigravity CLI message could not be handled")); }
|
||||
resolve();
|
||||
})));
|
||||
}
|
||||
});
|
||||
child.stderr.resume();
|
||||
child.stdin.on("error", () => undefined);
|
||||
void this.exited.then(() => { void this.#queue.then(() => this.#fail(new ProcessLostError())); });
|
||||
}
|
||||
|
||||
get lost(): Error | null { return this.#lost; }
|
||||
|
||||
/** Settle every message already received from the CLI. */
|
||||
async drain(): Promise<void> {
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await this.#queue;
|
||||
}
|
||||
|
||||
#fail(error: Error): void {
|
||||
if (this.#lost) return;
|
||||
this.#lost = error;
|
||||
for (const pending of this.#pending.values()) pending.reject(error);
|
||||
this.#pending.clear();
|
||||
this.onLost();
|
||||
}
|
||||
|
||||
#line(line: string): void {
|
||||
let message: Json;
|
||||
try { message = record(JSON.parse(line)); } catch { return; }
|
||||
const { id, method } = message;
|
||||
if (typeof method === "string") {
|
||||
if (id === undefined) { this.onNotification(method, record(message.params)); return; }
|
||||
void this.onRequest(method, record(message.params)).then(
|
||||
result => this.#write({ jsonrpc: "2.0", id, result }),
|
||||
() => this.#write({ jsonrpc: "2.0", id, error: { code: -32601, message: "Not supported by Paperclip" } }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (typeof id !== "number") return;
|
||||
const pending = this.#pending.get(id);
|
||||
if (!pending) return;
|
||||
this.#pending.delete(id);
|
||||
if (message.error !== undefined) pending.reject(new RpcError(pending.method, record(message.error)));
|
||||
else pending.resolve(record(message.result));
|
||||
}
|
||||
|
||||
#write(message: Json): void {
|
||||
if (this.#lost || this.child.stdin.destroyed) return;
|
||||
this.child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
request(method: string, params: Json, timeoutMs: number | null): Promise<Json> {
|
||||
if (this.#lost) return Promise.reject(this.#lost);
|
||||
const id = this.#next++;
|
||||
return new Promise<Json>((resolve, reject) => {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const settle = <T>(fn: (value: T) => void) => (value: T) => { if (timer) clearTimeout(timer); fn(value); };
|
||||
this.#pending.set(id, { method, resolve: settle(resolve), reject: settle(reject) });
|
||||
if (timeoutMs !== null) {
|
||||
timer = setTimeout(() => {
|
||||
this.#pending.delete(id);
|
||||
reject(new AntigravitySwarmError("ANTIGRAVITY_SWARM_RECEIPT_MISMATCH", `The Antigravity CLI did not answer ${method} in time.`));
|
||||
}, timeoutMs);
|
||||
}
|
||||
this.#write({ jsonrpc: "2.0", id, method, params });
|
||||
});
|
||||
}
|
||||
|
||||
notify(method: string, params: Json): void { this.#write({ jsonrpc: "2.0", method, params }); }
|
||||
}
|
||||
|
||||
class EventQueue implements AsyncIterable<AcpRuntimeEvent> {
|
||||
#items: AcpRuntimeEvent[] = [];
|
||||
#waiter: (() => void) | null = null;
|
||||
#ended = false;
|
||||
push(event: AcpRuntimeEvent): void { if (this.#ended) return; this.#items.push(event); this.#waiter?.(); }
|
||||
end(): void { this.#ended = true; this.#waiter?.(); }
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<AcpRuntimeEvent> {
|
||||
for (;;) {
|
||||
const item = this.#items.shift();
|
||||
if (item) { yield item; continue; }
|
||||
if (this.#ended) return;
|
||||
await new Promise<void>(resolve => { this.#waiter = resolve; });
|
||||
this.#waiter = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Snapshot = { files: Map<string, string>; complete: boolean };
|
||||
/**
|
||||
* Bounded, asynchronous listing of the task folder. The limit counts every
|
||||
@@ -253,16 +128,6 @@ function changedFiles(before: Map<string, string>, after: Map<string, string>):
|
||||
return [...changed, ...removed].sort();
|
||||
}
|
||||
|
||||
function addUsage(total: Json | null, usage: unknown): Json | null {
|
||||
const value = record(usage);
|
||||
if (Object.keys(value).length === 0) return total;
|
||||
const next: Json = { ...(total ?? {}) };
|
||||
for (const key of ["inputTokens", "outputTokens", "cachedReadTokens", "cachedWriteTokens", "thoughtTokens", "totalTokens"]) {
|
||||
if (typeof value[key] === "number") next[key] = (typeof next[key] === "number" ? next[key] as number : 0) + (value[key] as number);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Per counter, the larger of two usage readings. */
|
||||
function largerUsage(total: Json, reading: Json): Json {
|
||||
const next: Json = { ...total };
|
||||
@@ -386,7 +251,10 @@ export async function openAntigravitySwarmRuntime(
|
||||
const lifetime = options.credentialFenceFds && options.activateCredentialFenceOwner
|
||||
? { credentialFenceFds: options.credentialFenceFds, activateCredentialFenceOwner: options.activateCredentialFenceOwner } : undefined;
|
||||
const child = options.command.spawn([], { cwd: options.cwd, env: { ...options.launchEnvironment } }, lifetime) as ChildProcessWithoutNullStreams;
|
||||
const connection = new Connection(child);
|
||||
const connection = new AntigravityAcpConnection(child, {
|
||||
createProcessLostError: () => new ProcessLostError(),
|
||||
createTimeoutError: method => new AntigravitySwarmError("ANTIGRAVITY_SWARM_RECEIPT_MISMATCH", `The Antigravity CLI did not answer ${method} in time.`),
|
||||
});
|
||||
// Helpers lead their own process groups, so stopping the launcher's group is
|
||||
// not enough: everything the CLI started is recorded while it runs and is
|
||||
// stopped with it (see antigravity-process-lineage.ts).
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { createServer, type Server } from "node:net";
|
||||
import { isAbsolute, join, resolve } from "node:path";
|
||||
import { dirname, isAbsolute, join, resolve } from "node:path";
|
||||
|
||||
import { verifiedRuntimeExecutableHandoff } from "./verified-runtime-executable.js";
|
||||
|
||||
@@ -56,6 +56,7 @@ interface CredentialHomeLock {
|
||||
|
||||
interface QuarantinedCredentialCleanup {
|
||||
path: string;
|
||||
additionalCleanupPaths: readonly string[];
|
||||
home: string;
|
||||
intentPath: string;
|
||||
ownerGeneration: CredentialLeaseGeneration;
|
||||
@@ -180,6 +181,8 @@ export async function stageManagedCodexCredential(input: {
|
||||
agentHomeDirectory: string;
|
||||
environment?: NodeJS.ProcessEnv;
|
||||
sourcePath?: string;
|
||||
/** Extra sibling credential/log paths covered by this lease's durable cleanup intent and crash quarantine. */
|
||||
additionalCleanupPaths?: readonly string[];
|
||||
}): Promise<ManagedCodexCredentialLease> {
|
||||
const home = await resolvePrivateAgentHome(input.agentHomeDirectory);
|
||||
// Join an older failed close before claiming the next generation. This
|
||||
@@ -229,6 +232,7 @@ async function stageClaimedManagedCodexCredential(
|
||||
input: {
|
||||
environment?: NodeJS.ProcessEnv;
|
||||
sourcePath?: string;
|
||||
additionalCleanupPaths?: readonly string[];
|
||||
},
|
||||
home: string,
|
||||
ownerGeneration: CredentialLeaseGeneration,
|
||||
@@ -237,10 +241,12 @@ async function stageClaimedManagedCodexCredential(
|
||||
const destination = join(home, "auth.json");
|
||||
const stagingPath = join(home, CREDENTIAL_STAGING_FILE);
|
||||
const intentPath = join(home, CREDENTIAL_CLEANUP_INTENT);
|
||||
const additionalCleanupPaths = [...(input.additionalCleanupPaths ?? [])];
|
||||
lock.assertHeld();
|
||||
await recoverPersistedCredentialCleanup(
|
||||
destination,
|
||||
stagingPath,
|
||||
additionalCleanupPaths,
|
||||
home,
|
||||
intentPath,
|
||||
);
|
||||
@@ -248,7 +254,7 @@ async function stageClaimedManagedCodexCredential(
|
||||
// installed credential and the deterministic staging pathname before every
|
||||
// admission, even when a prior cleanup-intent entry was lost with a runner
|
||||
// crash. Only after their absence is durable may a new intent be created.
|
||||
await removeCredentialArtifacts([destination, stagingPath], home);
|
||||
await removeCredentialArtifacts([destination, stagingPath, ...additionalCleanupPaths], home);
|
||||
const environment = input.environment ?? {};
|
||||
const hasApiKey = Boolean(
|
||||
environment.CODEX_API_KEY || environment.OPENAI_API_KEY,
|
||||
@@ -290,6 +296,7 @@ async function stageClaimedManagedCodexCredential(
|
||||
await createCredentialCleanupIntent(intentPath, home);
|
||||
return credentialLease(
|
||||
destination,
|
||||
additionalCleanupPaths,
|
||||
home,
|
||||
intentPath,
|
||||
"api_key",
|
||||
@@ -314,6 +321,7 @@ async function stageClaimedManagedCodexCredential(
|
||||
// intent so later staging must recover both before admission.
|
||||
quarantineCredentialCleanup(
|
||||
destination,
|
||||
additionalCleanupPaths,
|
||||
home,
|
||||
intentPath,
|
||||
ownerGeneration,
|
||||
@@ -326,6 +334,7 @@ async function stageClaimedManagedCodexCredential(
|
||||
}
|
||||
return credentialLease(
|
||||
destination,
|
||||
additionalCleanupPaths,
|
||||
home,
|
||||
intentPath,
|
||||
hasInlineJson ? "inline_json" : "managed_file",
|
||||
@@ -538,6 +547,7 @@ async function closeCredentialLeaseServer(server: Server): Promise<void> {
|
||||
}
|
||||
function quarantineCredentialCleanup(
|
||||
path: string,
|
||||
additionalCleanupPaths: readonly string[],
|
||||
home: string,
|
||||
intentPath: string,
|
||||
ownerGeneration: CredentialLeaseGeneration,
|
||||
@@ -547,6 +557,7 @@ function quarantineCredentialCleanup(
|
||||
if (existing !== undefined) return;
|
||||
const cleanup: QuarantinedCredentialCleanup = {
|
||||
path,
|
||||
additionalCleanupPaths,
|
||||
home,
|
||||
intentPath,
|
||||
ownerGeneration,
|
||||
@@ -572,12 +583,16 @@ function startCredentialCleanupRecovery(
|
||||
// Never let a stale cleanup callback mutate a successor's credential
|
||||
// after kernel ownership has been lost.
|
||||
assertCredentialCleanupAuthority(cleanup);
|
||||
await removeReplaceableCredential(cleanup.path);
|
||||
await removeReplaceableCredential(
|
||||
const artifacts = [
|
||||
cleanup.path,
|
||||
join(cleanup.home, CREDENTIAL_STAGING_FILE),
|
||||
);
|
||||
...cleanup.additionalCleanupPaths,
|
||||
];
|
||||
for (const artifact of artifacts) {
|
||||
await removeReplaceableCredential(artifact);
|
||||
}
|
||||
assertCredentialCleanupAuthority(cleanup);
|
||||
await syncDirectory(cleanup.home);
|
||||
await syncDirectoriesForArtifacts(artifacts, cleanup.home);
|
||||
assertCredentialCleanupAuthority(cleanup);
|
||||
await removeCredentialCleanupIntent(cleanup.intentPath, cleanup.home);
|
||||
assertCredentialCleanupAuthority(cleanup);
|
||||
@@ -638,16 +653,18 @@ async function recoverQuarantinedCredentialCleanup(
|
||||
async function recoverPersistedCredentialCleanup(
|
||||
path: string,
|
||||
stagingPath: string,
|
||||
additionalCleanupPaths: readonly string[],
|
||||
home: string,
|
||||
intentPath: string,
|
||||
): Promise<void> {
|
||||
if (!(await pathExists(intentPath))) return;
|
||||
await removeCredentialArtifacts([path, stagingPath], home);
|
||||
await removeCredentialArtifacts([path, stagingPath, ...additionalCleanupPaths], home);
|
||||
await removeCredentialCleanupIntent(intentPath, home);
|
||||
}
|
||||
|
||||
function credentialLease(
|
||||
path: string,
|
||||
additionalCleanupPaths: readonly string[],
|
||||
home: string,
|
||||
intentPath: string,
|
||||
mode: ManagedCodexCredentialMode,
|
||||
@@ -698,13 +715,14 @@ function credentialLease(
|
||||
}
|
||||
try {
|
||||
lock.assertHeld();
|
||||
await removeCredential(path, home);
|
||||
await removeCredentialArtifacts([path, ...additionalCleanupPaths], home);
|
||||
await removeCredentialCleanupIntent(intentPath, home);
|
||||
await lock.release();
|
||||
closed = true;
|
||||
} catch (error) {
|
||||
quarantineCredentialCleanup(
|
||||
path,
|
||||
additionalCleanupPaths,
|
||||
home,
|
||||
intentPath,
|
||||
ownerGeneration,
|
||||
@@ -922,8 +940,18 @@ async function removeReplaceableCredential(path: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function removeCredential(path: string, home: string): Promise<void> {
|
||||
await removeCredentialArtifacts([path], home);
|
||||
async function syncDirectoriesForArtifacts(
|
||||
paths: readonly string[],
|
||||
home: string,
|
||||
): Promise<void> {
|
||||
const dirs = new Set<string>([home]);
|
||||
for (const artifact of paths) {
|
||||
const parent = dirname(artifact);
|
||||
if (parent !== home && await pathExists(parent)) dirs.add(parent);
|
||||
}
|
||||
for (const dir of dirs) {
|
||||
await syncDirectoryDurably(dir);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeCredentialArtifacts(
|
||||
@@ -936,7 +964,7 @@ async function removeCredentialArtifacts(
|
||||
// Sync even after ENOENT: a previous unlink may have succeeded before its
|
||||
// directory sync failed. Never report cleanup or finish preflight while the
|
||||
// removal can still be rolled back by a crash.
|
||||
await syncDirectoryDurably(home);
|
||||
await syncDirectoriesForArtifacts(paths, home);
|
||||
}
|
||||
|
||||
async function syncDirectoryDurably(directory: string): Promise<void> {
|
||||
|
||||
@@ -8,8 +8,9 @@ import { isSupportedAcpxProfileVersion } from "./profile-compatibility.js";
|
||||
// release changes the commandDigest and keeps the version; a new provider starts
|
||||
// at 1. Update this table, with the reason, only for a deliberate reset.
|
||||
const PROFILE_VERSIONS: Readonly<Record<string, number>> = {
|
||||
// Released Antigravity uses revision 2 to refuse saved pending-candidate sessions.
|
||||
antigravity: 2, claude: 1, codex: 1, copilot: 92, cursor: 17, grok: 20, pi: 37,
|
||||
// Revision 3 intentionally resets saved legacy 1.5.2 Python ACP sessions when
|
||||
// migrating to the unified `agy` 1.5.19 CLI runtime.
|
||||
antigravity: 3, claude: 1, codex: 1, copilot: 92, cursor: 17, grok: 20, pi: 37,
|
||||
// Released Kimi uses revision 17 to refuse saved pending-candidate sessions.
|
||||
// The upstream-only attestation migration retains that existing revision.
|
||||
kimi: 17,
|
||||
|
||||
@@ -583,7 +583,7 @@ export class AcpxRuntimeHost {
|
||||
reportFailure: (failure) =>
|
||||
dependencies.reportRetainedCleanupFailure(failure),
|
||||
});
|
||||
} else if (options.agent === "antigravity" && !swarmRoute) {
|
||||
} else if (options.agent === "antigravity") {
|
||||
credential = await acquireAbortableAdmissionResource({
|
||||
signal: options.signal,
|
||||
acquire: () => stageManagedAntigravityCredential({ agentHomeDirectory: sandbox.agentHomeDirectory,
|
||||
@@ -723,7 +723,7 @@ export class AcpxRuntimeHost {
|
||||
preserveToolNames: options.assignedMcpTransport === "prp",
|
||||
preloadClaudeTaskTools: options.agent === "claude",
|
||||
// The Antigravity CLI checks tool schemas with RE2 and refuses its whole toolbox otherwise.
|
||||
...(swarmRoute ? { schemaPatternDialect: "re2" as const } : {}),
|
||||
...(options.agent === "antigravity" ? { schemaPatternDialect: "re2" as const } : {}),
|
||||
}),
|
||||
resource: "tool_bridge",
|
||||
releaseLate: (lateToolBridge) => lateToolBridge.close(),
|
||||
|
||||
@@ -788,7 +788,7 @@ function isPersistableEnvironmentName(name: string): boolean {
|
||||
/^(?:PI_CODING_AGENT_DIR|PI_SKIP_VERSION_CHECK|PI_TELEMETRY)$/.test(name) ||
|
||||
/^(?:CURSOR_CONFIG_DIR|CURSOR_DATA_DIR|AGENT_CLI_CREDENTIAL_STORE|NO_OPEN_BROWSER|NODE_DISABLE_COMPILE_CACHE)$/.test(name) ||
|
||||
/^(?:COPILOT_HOME|COPILOT_CACHE_HOME|COPILOT_AUTO_UPDATE|COPILOT_ALLOW_ALL|COPILOT_DISABLE_TERMINAL_TITLE|NO_COLOR)$/.test(name) ||
|
||||
/^(?:GEMINI_HOME|AGY_ACP_FORCE_FILE_STORAGE)$/.test(name) ||
|
||||
/^(?:GEMINI_HOME|AGY_ACP_FORCE_FILE_STORAGE|AGY_CLI_FORCE_FILE_TOKEN_STORAGE|AGY_CLI_DISABLE_AUTO_UPDATE)$/.test(name) ||
|
||||
/^(?:CLAUDE_CONFIG_DIR|CODEX_HOME|NO_BROWSER|DEFAULT_AUTH_REQUEST|PAPERCLIP_RUNNER_PREPARED_HARNESS_HOME)$/.test(
|
||||
name,
|
||||
)
|
||||
|
||||
@@ -378,7 +378,7 @@ describe("agent routes adapter validation", () => {
|
||||
|
||||
it("creates a qualified Google Antigravity agent without an operator candidate grant or experimental Runner flag", async () => {
|
||||
const { QUALIFIED_ACPX_PROFILES } = await import("../vendor/paperclip-runner/index.js");
|
||||
expect(QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion).toBe(2);
|
||||
expect(QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion).toBe(3);
|
||||
expect(QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus).toBeUndefined();
|
||||
const adapterConfig = { provider: "acpx", acpxAgent: "antigravity", model: "exact-antigravity-model" };
|
||||
vi.stubEnv("PAPERCLIP_ACPX_CANDIDATE_ADMISSION", undefined);
|
||||
|
||||
@@ -574,11 +574,17 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", (
|
||||
expect((receipt!.payload as Record<string, unknown>)._paperclipWakeContext).toMatchObject({ antigravitySwarmCommentId: f.comment.id });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a remote environment", { remote: true }, /this computer/],
|
||||
["Plan mode", { planning: true }, /Plan mode/],
|
||||
])("refuses in plain language in %s instead of running an ordinary request", async (_name, overrides, message) => {
|
||||
await expect(resolve(await seed(), overrides)).rejects.toMatchObject({ code: "antigravity_swarm_unavailable", message: expect.stringMatching(message) });
|
||||
it("accepts a /swarm request in a remote environment", async () => {
|
||||
const f = await seed();
|
||||
const run = await insertRun(f, {});
|
||||
expect(await resolve(f, { remote: true, runId: run.id })).toMatchObject({ request: "two helpers" });
|
||||
});
|
||||
|
||||
it("refuses in plain language in Plan mode instead of running an ordinary request", async () => {
|
||||
await expect(resolve(await seed(), { planning: true })).rejects.toMatchObject({
|
||||
code: "antigravity_swarm_unavailable",
|
||||
message: expect.stringMatching(/Plan mode/),
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@@ -29,7 +29,7 @@ describe("host ACPX qualification admission", () => {
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, host);
|
||||
vi.stubEnv(ACPX_QUALIFICATION_ENV, host);
|
||||
const config = { provider: "acpx", acpxAgent: "antigravity", model: "exact-model" };
|
||||
expect(QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion).toBe(2);
|
||||
expect(QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion).toBe(3);
|
||||
expect(QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus).not.toBe("pending");
|
||||
expect(resolvePaperclipRunnerProviderProfile(config, { companyId: "candidate-company" })).toMatchObject(config);
|
||||
expect(resolvePaperclipRunnerNativeProviderInput({ companyId: "candidate-company", backend: "acpx_runtime", adapterConfig: config }))
|
||||
|
||||
@@ -186,10 +186,10 @@ it("immediately triggers check after submitting a hosted Google redirect URL", a
|
||||
.mockResolvedValueOnce({ status: "sign_in_required", authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=hosted" })
|
||||
.mockResolvedValueOnce({ status: "ready", accountLabel: "hosted.user@example.test" });
|
||||
flushSync(() => root.render(<Harness provider="google" hostedRedirect />));
|
||||
await vi.waitFor(() => expect(host.querySelector('input[aria-label="Antigravity redirect URL"]')).not.toBeNull());
|
||||
await vi.waitFor(() => expect(host.querySelector('input[aria-label="Antigravity authorization code or callback URL"]')).not.toBeNull());
|
||||
expect(api.checkLocalLogin).toHaveBeenCalledTimes(1);
|
||||
|
||||
const input = host.querySelector('input[aria-label="Antigravity redirect URL"]') as HTMLInputElement;
|
||||
const input = host.querySelector('input[aria-label="Antigravity authorization code or callback URL"]') as HTMLInputElement;
|
||||
flushSync(() => {
|
||||
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "http://127.0.0.1:41234/?state=hosted&code=abc123");
|
||||
input.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
|
||||
@@ -110,12 +110,12 @@ describe("AgentProviderConnection hosted Google sign-in gating", () => {
|
||||
renderConnection("antigravity_runtime", false);
|
||||
|
||||
await vi.waitFor(() => expect(mocks.startLocalLogin).toHaveBeenCalledTimes(1));
|
||||
await vi.waitFor(() => expect(host.querySelector('input[aria-label="Antigravity redirect URL"]')).not.toBeNull());
|
||||
await vi.waitFor(() => expect(host.querySelector('input[aria-label="Antigravity authorization code or callback URL"]')).not.toBeNull());
|
||||
expect(host.querySelector('a[href="https://accounts.google.com/o/oauth2/v2/auth?state=hosted-ui-state"]')).not.toBeNull();
|
||||
expect(host.querySelector('img[src="/brands/apps/antigravity.svg"]')).not.toBeNull();
|
||||
expect(host.textContent).toContain("Antigravity");
|
||||
expect(host.textContent).toContain("Sign in to Antigravity");
|
||||
expect(host.textContent).toContain("127.0.0.1");
|
||||
expect(host.textContent).toContain("authorization code or full callback URL");
|
||||
|
||||
const openSpy = vi.spyOn(window, "open").mockReturnValue(null);
|
||||
try {
|
||||
@@ -216,7 +216,7 @@ describe("AgentProviderConnection hosted Google sign-in gating", () => {
|
||||
renderConnection("antigravity_runtime", true);
|
||||
|
||||
await vi.waitFor(() => expect(mocks.startLocalLogin).toHaveBeenCalledTimes(1));
|
||||
await vi.waitFor(() => expect(host.querySelector('input[aria-label="Antigravity redirect URL"]')).not.toBeNull());
|
||||
await vi.waitFor(() => expect(host.querySelector('input[aria-label="Antigravity authorization code or callback URL"]')).not.toBeNull());
|
||||
expect(host.textContent).toContain("another machine");
|
||||
expect(host.textContent).toContain("127.0.0.1");
|
||||
});
|
||||
|
||||
@@ -135,7 +135,7 @@ describe("AppsConnect Antigravity routing and branding", () => {
|
||||
expect(host.querySelector("h2")?.textContent).toBe("Connect Antigravity");
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(host.querySelector('input[aria-label="Antigravity redirect URL"]')).not.toBeNull();
|
||||
expect(host.querySelector('input[aria-label="Antigravity authorization code or callback URL"]')).not.toBeNull();
|
||||
});
|
||||
expect(host.querySelector('img[src="/brands/apps/antigravity.svg"]')).not.toBeNull();
|
||||
expect(host.textContent).toContain("Sign in to Antigravity");
|
||||
|
||||
Reference in new issue
Block a user