Files
PaperClipAI/packages/paperclip-runner/scripts/probe-antigravity-metadata.mjs
T
DottaandPaperclip 3df59a1853 Unify Antigravity runtime and remote /swarm onto agy acp 1.5.19 (#23168)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The Paperclip Runner executes Google Antigravity agents on local
hosts and remote sandboxes
> - Previously, Paperclip shipped two separate Google runtimes: an 853
MiB IDE-extension ACP bundle (`agy_acp_server.par` 1.5.2 +
`localharness_external` + Python admission monkey-patch) for ordinary
turns and a separate `agy` 1.5.15 CLI binary for local-only `/swarm`
turns
> - Because the legacy server lacked `/swarm` and the CLI path refused
remote targets and required macOS Keychain or Linux user namespaces
(`auto` mode), remote sandboxes could not run `/swarm` and carried 853
MiB of legacy binaries
> - This pull request unifies all Antigravity surfaces (ordinary turns,
`/swarm`, interactive sign-in, and model discovery) onto one pinned
`agy` 1.5.19 CLI binary (`1.5.19-4821414830800896`) with file-backed
OAuth isolation (`AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1`) and
`--dangerously-skip-permissions` support for remote sandboxes
> - The benefit is one 268 MiB Linux binary instead of 853 MiB (saving
~585 MiB in remote images), no Python runtime monkey-patching, full
`/swarm` support on both local and remote hosts, and a unified 25-model
catalog including Gemini 4 Neon, Carbon, Hydrogen, and Argon

## Linked Issues or Issue Description

**What existing behavior does this improve?**
The Google Antigravity Runner driver, provider pack materialization,
Google sign-in flow, model discovery, and `/swarm` execution in
`packages/paperclip-runner`, `packages/shared`, `server`, and `ui`.

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
Ordinary Antigravity turns use the legacy 1.5.2 IDE-extension ACP server
(`agy_acp_server.par` + `localharness_external` + Python monkey-patch)
at ~853 MiB on `linux-x64`. Native `/swarm` turns require a separate
`agy` 1.5.15 CLI binary, refuse remote execution targets
(`input.remote`), and fail on Linux sandboxes without user namespaces
(`auto` mode).

**Proposed behavior**
All Antigravity flows use one pinned `agy` 1.5.19 binary
(`1.5.19-4821414830800896`, ~268 MiB on `linux-x64`) across all four
platforms (`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`).
Ordinary turns speak ACP directly through `openAntigravityAcpRuntime`.
Both ordinary and `/swarm` turns stage file-backed OAuth tokens under
`<agentHomeDirectory>/antigravity-cli/antigravity-oauth-token` with
`AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1`, isolate from host keychains, and
allow `/swarm` on remote targets using `--dangerously-skip-permissions`.
Interactive Google sign-in runs `agy acp --login` with
`https://antigravity.google/oauth-callback`, pre-creates
`<home>/antigravity-cli` with mode `0700`, and prompts for the
authorization code in the UI.

**Reason and benefit**
Unifying onto `agy` 1.5.19 cuts the `linux-x64` provider-pack footprint
by ~585 MiB, removes Python bytecode patching from materialization,
enables `/swarm` in headless Linux sandboxes without user namespaces or
D-Bus, and aligns ordinary turns, model discovery, and `/swarm` on the
same 25-model catalog.

**Breaking changes**
- `acpx-profiles.json` bumps `antigravity` to `agentProfileVersion: 3`
(`native:antigravity-cli`, version `1.5.19`). Existing saved legacy
1.5.2 sessions fail closed as incompatible saved state and start fresh
cleanly.
- Existing Google OAuth connections carrying `client_secret` remain
fully backward-compatible; new `agy acp --login` connections store
canonical credentials with `auth_method: "consumer"` and no
`client_secret`.

## What Changed

- Pin `agy` `1.5.19-4821414830800896` across all four platforms
(`darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`) in
`antigravity-distributions.json`, `antigravity-cli-distributions.json`,
`antigravity-cli-pins.ts`, and `acpx-profiles.json`
(`agentProfileVersion: 3`), and regenerate TypeScript and Rust profile
artifacts.
- Replace ZIP + Python patch materialization with strict single-member
`tar.gz` verification (`materialize-antigravity-distribution.mjs`,
`provision-antigravity.mjs`, `probe-antigravity-metadata.mjs`,
`candidate-provider-pack.mjs`, `release-provider-pack.mjs`).
- Regenerate `packages/shared/src/antigravity-models.generated.ts` from
`agy` 1.5.19 (25 models across 8 families, including Gemini 4 Neon,
Carbon, Hydrogen, and Argon) and update
`packages/shared/src/antigravity-models.ts` and
`tests/runner-e2e/antigravity-qualification-cases.ts` for `xhigh`
thinking levels.
- Add direct ACP runtime
`packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.ts`
(`openAntigravityAcpRuntime`) for ordinary Antigravity turns with OAuth
and `GEMINI_API_KEY` support, `session/new` + `session/resume`,
`readOnly`/plan mode enforcement, HTTP and stdio MCP forwarding, live
`setModel`, slash-command neutralization, refusal classification,
cancellation, and lineage retirement; route ordinary Antigravity turns
unconditionally in `acpx-runtime-adapter.ts` without an ACPX fallback
seam.
- Update `antigravity-auth.ts`, `antigravity-credentials.ts`,
`antigravity-models.ts`, `antigravity-process.ts`, `runtime-host.ts`,
and `runtime-sandbox.ts` to run `agy acp --login`, pre-create
`<home>/antigravity-cli` with mode `0700` (preventing Go `os.MkdirAll`
`0755` readback failures), force file-backed token storage
(`AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1`), align `--gemini-dir` with
`agentHomeDirectory`, bound model-discovery token sync cleanup, and
scrub live CLI token files on cleanup.
- Enable remote `/swarm` by removing the `input.remote` refusal in
`server/src/services/antigravity-swarm.ts` and allowing
`--dangerously-skip-permissions` + `default` mode in
`antigravity-swarm-route.ts`, `antigravity-swarm-guard.ts`, and
`antigravity-swarm-runtime.ts` when `permissionMode === "approve-all"`.
- Update `ui/src/components/AdapterLoginChrome.tsx` copy to prompt for
an authorization code (`Submit code`) for
`https://antigravity.google/oauth-callback` while preserving callback
URL handling for loopback redirects.
- Add unit tests for `openAntigravityAcpRuntime`, direct Antigravity
routing, `0700` token directory pre-creation, and hosted
authorization-code login UX, and update Runner, script, shared, server,
Rust, UI, and runner-e2e test suites for `agy` 1.5.19.

## Verification

- Runner driver tests: `vitest run` across Antigravity driver test files
(`antigravity-auth.test.ts`, `antigravity-models.test.ts`,
`antigravity-acp-runtime.test.ts`, `antigravity-swarm-route.test.ts`,
`codex-credentials.test.ts`, `acpx-runtime-adapter.test.ts`,
`candidate-admission.test.ts`, `native-distribution-integrity.test.ts`)
— all passing.
- Runner script tests: `node --test` across all 7 Antigravity &
provider-pack script suites — 98/98 passed.
- Shared, UI, Server, and runner-e2e tests:
`antigravity-models.test.ts`, `AdapterLoginChrome.test.tsx` (23/23),
`antigravity-thread.test.tsx`, 23 server Antigravity/provider-pack
suites, and 7 `runner-e2e` Antigravity suites — all passing.
- Rust tests: `cargo test --manifest-path
packages/paperclip-runner/runner/Cargo.toml --locked -p
paperclip-runner-core -- acpx antigravity` — 145/145 passed.
- Typechecks & generators: `@paperclipai/shared`,
`@paperclipai/paperclip-runner` (TS + Rust), `@paperclipai/server` (all
layers), `@paperclipai/ui`, `generate-acpx-profiles.mjs --check`,
`generate-antigravity-models.mjs --check` — all passing.
- Live E2E against real pinned `agy` 1.5.19 binaries (macOS
`darwin-arm64`, headless Linux `linux-arm64` Docker with `--security-opt
no-new-privileges`, and a live remote test deployment):
- Verified `materialize-antigravity-distribution.mjs` on all 4 platform
archives and `probe-antigravity-metadata.mjs` on macOS and headless
Linux Docker.
- Verified live Google OAuth sign-in end-to-end via `agy acp --login` +
`https://antigravity.google/oauth-callback` authorization code exchange
on a live remote deployment, creating a working Antigravity connection.
- Verified `stageManagedAntigravityCredential` +
`AGY_CLI_FORCE_FILE_TOKEN_STORAGE=1` file-backed isolation and cleanup
scrub on macOS and headless Linux Docker.
- Verified live `openAntigravityAcpRuntime` ordinary turn + HTTP MCP
tool call + `_meta.antigravity.systemPrompt.append` +
`setModel(gemini-4-argon-low)` + `session/resume` on real `agy` 1.5.19.
- Verified live `openAntigravitySwarmRuntime` `/swarm` turn with
`--dangerously-skip-permissions` spawning a real helper, writing
workspace file, calling `paperclip_finish`, and retiring cleanly.

## Risks

- **Coordinated Cloud deployment**: Remote sandboxes use the companion
transition-safe Cloud update to expect
`provider-assets/antigravity/linux-x64/agy`, accept `auth_method:
"consumer"` credentials without `client_secret`, and scrub
`antigravity-cli/antigravity-oauth-token`.
- **Saved session continuity**: Existing saved 1.5.2 sessions fail
closed as `ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE` and start fresh cleanly
on 1.5.19.

## Model Used

- Google Gemini (Antigravity agentic coding assistant,
reasoning/tool-use/code-execution enabled)

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-01 22:01:25 +00:00

218 lines
13 KiB
JavaScript

#!/usr/bin/env node
import { spawn, spawnSync } from "node:child_process";
import { mkdir, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { StringDecoder } from "node:string_decoder";
import { pathToFileURL } from "node:url";
import { antigravityRuntimeCachePath } from "./antigravity-provisioner-layout.mjs";
import { antigravityDistribution, verifyAntigravityDistribution } from "./materialize-antigravity-distribution.mjs";
const MAX_WIRE_BYTES = 1024 * 1024;
const CLIENT_INFO = Object.freeze({ name: "paperclip-runner", title: "Paperclip Runner", version: "1" });
const AUTH_METHOD_IDS = ["oauth-personal", "oauth-business", "gemini-api-key", "agent-platform"];
const plainObject = value => value !== null && typeof value === "object" && !Array.isArray(value);
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
function probeLimits(options) {
const limits = { startupTimeoutMs: options.startupTimeoutMs ?? 25_000, maxBytes: options.maxBytes ?? MAX_WIRE_BYTES,
eofTimeoutMs: options.eofTimeoutMs ?? 500, terminateTimeoutMs: options.terminateTimeoutMs ?? 500, killTimeoutMs: options.killTimeoutMs ?? 500 };
for (const [name, maximum] of [["startupTimeoutMs", 30_000], ["maxBytes", MAX_WIRE_BYTES], ["eofTimeoutMs", 5_000], ["terminateTimeoutMs", 5_000], ["killTimeoutMs", 5_000]]) {
if (!Number.isSafeInteger(limits[name]) || limits[name] < 1 || limits[name] > maximum) throw new Error("Invalid Antigravity metadata probe limits");
}
return limits;
}
/** No ambient credentials, proxy, hooks, Python, Node, or configuration variables. */
export function antigravityMetadataEnvironment(root, _runtimeDirectory) {
return {
PATH: "/usr/bin:/bin", HOME: join(root, "home"), GEMINI_HOME: join(root, "gemini"),
XDG_CONFIG_HOME: join(root, "config"), XDG_DATA_HOME: join(root, "data"), XDG_CACHE_HOME: join(root, "cache"),
TMPDIR: join(root, "tmp"), AGY_CLI_FORCE_FILE_TOKEN_STORAGE: "1", AGY_CLI_DISABLE_AUTO_UPDATE: "1",
NO_COLOR: "1", LANG: "en_US.UTF-8",
};
}
/** One closed protocol exchange. Provider-authored text never enters diagnostics. */
export function createAntigravityMetadataRpc(child, { startupTimeoutMs = 25_000, maxBytes = MAX_WIRE_BYTES } = {}) {
if (!Number.isSafeInteger(startupTimeoutMs) || startupTimeoutMs < 1 || startupTimeoutMs > 30_000 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > MAX_WIRE_BYTES) throw new Error("Invalid Antigravity metadata probe limits");
const decoder = new StringDecoder("utf8");
const utf8Validator = new TextDecoder("utf-8", { fatal: true });
let buffer = "", bytes = 0, stderrBytes = 0, started = false, settled = false, failure, timer;
let resolveInitialization, rejectInitialization;
const initialized = new Promise((resolve, reject) => { resolveInitialization = resolve; rejectInitialization = reject; });
// Failures before initialize() still have an owned rejection handler.
initialized.catch(() => {});
function fail(code) {
failure ??= new Error(code);
clearTimeout(timer);
if (!settled) { settled = true; rejectInitialization(failure); }
}
function parse(line) {
if (!line.trim()) return;
let message;
try { message = JSON.parse(line); } catch { fail("antigravity_malformed_json"); return; }
if (!plainObject(message) || message.jsonrpc !== "2.0" || message.id !== 1 || "method" in message || settled) { fail("antigravity_unexpected_message"); return; }
if ("error" in message) { fail("antigravity_initialize_rejected"); return; }
if (!plainObject(message.result)) { fail("antigravity_malformed_initialize_result"); return; }
clearTimeout(timer);
settled = true;
resolveInitialization(message.result);
}
child.stdout.on("data", chunk => {
bytes += chunk.length;
if (bytes > maxBytes) { fail("antigravity_stdout_limit"); return; }
try { utf8Validator.decode(chunk, { stream: true }); }
catch { fail("antigravity_malformed_utf8"); return; }
buffer += decoder.write(chunk);
while (!failure && buffer.includes("\n")) {
const end = buffer.indexOf("\n");
const line = buffer.slice(0, end);
buffer = buffer.slice(end + 1);
parse(line);
}
});
child.stdout.once("end", () => {
try { utf8Validator.decode(); }
catch { fail("antigravity_malformed_utf8"); return; }
buffer += decoder.end();
if (buffer.trim()) fail("antigravity_truncated_stream");
});
child.stderr.on("data", chunk => {
stderrBytes += chunk.length;
if (stderrBytes > maxBytes) fail("antigravity_stderr_limit");
});
child.once("error", () => fail("antigravity_spawn_failure"));
child.once("close", () => { if (!settled) fail("antigravity_exited_before_initialize"); });
child.stdin.on("error", () => { if (!settled) fail("antigravity_stdin_failure"); });
return {
initialize() {
if (started) throw new Error("Antigravity metadata initialization can only be sent once");
started = true;
timer = setTimeout(() => fail("antigravity_initialize_timeout"), startupTimeoutMs);
if (!failure) child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: 1, clientInfo: CLIENT_INFO, clientCapabilities: {} } })}\n`);
return initialized;
},
assertHealthy() { if (failure) throw failure; },
close() { clearTimeout(timer); },
};
}
function ownedGroupAlive(child) {
if (!child.pid) return false;
try { process.kill(-child.pid, 0); return true; }
catch (error) {
if (error.code === "ESRCH") return false;
// Darwin can report EPERM for a group containing only an orphaned zombie.
// Inspect numeric state only; never read process commands or environments.
if (error.code === "EPERM" && process.platform === "darwin") {
const snapshot = spawnSync("/bin/ps", ["-axo", "pid=,pgid=,stat="], { encoding: "utf8", timeout: 1_000, maxBuffer: 1024 * 1024, env: { PATH: "/usr/bin:/bin", LANG: "C" } });
if (snapshot.status === 0) {
const rows = snapshot.stdout.trim().split("\n").filter(Boolean).map(line => line.trim().split(/\s+/));
if (rows.every(row => row.length === 3 && /^\d+$/.test(row[0]) && /^\d+$/.test(row[1]) && /^[A-Za-z+<>NLsWX-]+$/.test(row[2]))) return rows.some(row => Number(row[1]) === child.pid && !row[2].startsWith("Z"));
}
}
throw new Error(`antigravity_process_group_check_failed:${error.code}`);
}
}
function signalOwnedGroup(child, signal) {
if (!child.pid) return;
try { process.kill(-child.pid, signal); }
catch (error) { if (error.code !== "ESRCH") throw new Error(`antigravity_process_group_signal_failed:${error.code}`); }
}
/** Finite shutdown stages also retire descendants after their parent exits. */
export async function stopAntigravityMetadataChild(child, { eofTimeoutMs = 500, terminateTimeoutMs = 500, killTimeoutMs = 500 } = {}) {
if (!child) return { method: "not-started", exitCode: null, signal: null };
for (const limit of [eofTimeoutMs, terminateTimeoutMs, killTimeoutMs]) if (!Number.isSafeInteger(limit) || limit < 1 || limit > 5_000) throw new Error("Invalid Antigravity shutdown limits");
const closed = child.exitCode !== null || child.signalCode !== null ? Promise.resolve() : new Promise(resolve => child.once("close", resolve));
let cleanupUncertainty;
const groupMayBeAlive = () => {
try { return ownedGroupAlive(child); }
catch (error) { cleanupUncertainty = error; return true; }
};
child.stdin?.end();
for (const [method, signal, timeout] of [["eof", null, eofTimeoutMs], ["sigterm", "SIGTERM", terminateTimeoutMs], ["sigkill", "SIGKILL", killTimeoutMs]]) {
if (!groupMayBeAlive()) return { method, exitCode: child.exitCode, signal: child.signalCode };
if (signal) {
try { signalOwnedGroup(child, signal); }
catch (error) { cleanupUncertainty = error; }
}
const deadline = Date.now() + timeout;
let timer;
try { await Promise.race([closed, new Promise(resolve => { timer = setTimeout(resolve, timeout); })]); }
finally { clearTimeout(timer); }
if (!groupMayBeAlive()) return { method, exitCode: child.exitCode, signal: child.signalCode };
// A descendant may have closed its inherited pipes. One deadline per stage
// gives that owned process group time to exit without an idle poll loop.
const remaining = deadline - Date.now();
if (remaining > 0) await delay(remaining);
if (!groupMayBeAlive()) return { method, exitCode: child.exitCode, signal: child.signalCode };
}
if (cleanupUncertainty) throw cleanupUncertainty;
throw new Error("antigravity_process_tree_cleanup_unconfirmed");
}
function safeMetadata(result, distribution) {
if (result.protocolVersion !== 1 || !plainObject(result.agentInfo) || result.agentInfo.name !== "Antigravity ACP Server") throw new Error("antigravity_initialize_identity_mismatch");
if (result.agentInfo.version !== distribution.version) throw new Error("antigravity_initialize_version_mismatch");
if (!plainObject(result.agentCapabilities) || !Array.isArray(result.authMethods)) throw new Error("antigravity_malformed_initialize_capabilities");
const capabilities = result.agentCapabilities;
const flag = (object, key) => plainObject(object) && object[key] === true;
const present = (object, key) => plainObject(object) && Object.hasOwn(object, key) && plainObject(object[key]);
return {
schema: "paperclip.antigravity_metadata_probe.v1", version: distribution.version, build: distribution.build,
platform: distribution.platform, architecture: distribution.architecture, archiveSha256: distribution.archiveSha256,
closureSha256: distribution.closureSha256,
protocolVersion: 1, agentInfo: { name: "Antigravity ACP Server", title: "Google Antigravity", version: distribution.version },
agentCapabilities: {
loadSession: flag(capabilities, "loadSession"),
promptCapabilities: Object.fromEntries(["image", "audio", "embeddedContext"].map(key => [key, flag(capabilities.promptCapabilities, key)])),
mcpCapabilities: Object.fromEntries(["http", "sse"].map(key => [key, flag(capabilities.mcpCapabilities, key)])),
sessionCapabilities: Object.fromEntries(["list", "resume"].map(key => [key, present(capabilities.sessionCapabilities, key)])),
logout: present(capabilities.auth, "logout"),
antigravity: { tier: flag(capabilities._meta?.antigravity, "tier"), systemPromptAppend: flag(capabilities._meta?.antigravity?.systemPrompt, "append") },
},
authMethodIds: AUTH_METHOD_IDS.filter(id => result.authMethods.some(method => plainObject(method) && method.id === id)),
requestsSent: ["initialize"], authenticateRequestsSent: 0, sessionRequestsSent: 0, promptRequestsSent: 0,
inferenceVerified: false, qualification: "qualified",
};
}
/** Credential-free cache probe. Installation is always a separate explicit action. */
export async function probeAntigravityMetadata(options = {}) {
const limits = probeLimits(options);
const distribution = await antigravityDistribution(options.platform, options.architecture);
const runtimeDirectory = antigravityRuntimeCachePath(distribution.closureSha256, distribution.platform, distribution.architecture, options.home);
await verifyAntigravityDistribution(runtimeDirectory, distribution);
const root = await mkdtemp(join(tmpdir(), "paperclip-antigravity-metadata-"));
let child, rpc, result, shutdown, failure, cleanupFailure;
try {
const env = antigravityMetadataEnvironment(root, runtimeDirectory);
for (const key of ["HOME", "GEMINI_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "TMPDIR"]) await mkdir(env[key], { mode: 0o700 });
child = spawn(join(runtimeDirectory, distribution.executable), [...distribution.args, "--gemini-dir", env.GEMINI_HOME, "--disable-telemetry"], { cwd: root, env, stdio: "pipe", detached: true });
rpc = createAntigravityMetadataRpc(child, limits);
result = safeMetadata(await rpc.initialize(), distribution);
} catch (error) {
failure = error;
} finally {
try { shutdown = await stopAntigravityMetadataChild(child, limits); }
catch (error) { cleanupFailure = error; }
finally { rpc?.close(); await rm(root, { recursive: true, force: true }); }
}
if (failure && cleanupFailure) throw new AggregateError([failure, cleanupFailure], `${failure.message}; ${cleanupFailure.message}`);
if (failure) throw failure;
if (cleanupFailure) {
try { rpc?.assertHealthy(); }
catch (error) { throw new AggregateError([error, cleanupFailure], `${error.message}; ${cleanupFailure.message}`); }
throw cleanupFailure;
}
rpc.assertHealthy();
return { ...result, shutdown };
}
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
probeAntigravityMetadata().then(result => console.log(JSON.stringify(result, null, 2))).catch(error => { console.error(error.message); process.exitCode = 1; });
}