From 3df59a1853752dea020524815737afec39882be2 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 1 Dec 2026 22:01:25 +0000 Subject: [PATCH] Unify Antigravity runtime and remote /swarm onto agy acp 1.5.19 (#23168) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 `/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 `/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 `/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 --- packages/paperclip-runner/acpx-profiles.json | 12 +- .../antigravity-cli-distributions.json | 71 +- .../antigravity-distributions.json | 172 ++-- .../src/acpx_candidate_admission.rs | 3 +- .../src/generated_acpx_profiles.rs | 19 +- .../antigravity-provider-pack-smoke.mjs | 57 +- .../scripts/candidate-provider-pack.mjs | 4 +- .../scripts/candidate-provider-pack.test.mjs | 12 +- .../scripts/generate-antigravity-models.mjs | 50 +- ...lize-antigravity-cli-distribution.test.mjs | 19 +- .../materialize-antigravity-distribution.mjs | 191 ++--- ...erialize-antigravity-distribution.test.mjs | 340 +++----- .../scripts/probe-antigravity-metadata.mjs | 21 +- .../probe-antigravity-metadata.test.mjs | 131 ++- .../scripts/provision-antigravity.mjs | 3 +- .../scripts/release-provider-pack.mjs | 5 +- .../src/cli/acpx-runtime-sidecar.test.ts | 2 +- .../drivers/acpx/acpx-runtime-adapter.test.ts | 56 -- .../src/drivers/acpx/acpx-runtime-adapter.ts | 25 +- .../acpx/antigravity-acp-connection.ts | 231 ++++++ .../acpx/antigravity-acp-runtime.test.ts | 529 ++++++++++++ .../drivers/acpx/antigravity-acp-runtime.ts | 630 ++++++++++++++ .../acpx/antigravity-acpx-runtime.test.ts | 2 +- .../acpx/antigravity-admission.test.ts | 3 +- .../antigravity-auth-stream-order.test.ts | 185 +++-- .../src/drivers/acpx/antigravity-auth.test.ts | 769 ++++++++++++------ .../src/drivers/acpx/antigravity-auth.ts | 751 ++++++++++++----- .../acpx/antigravity-cli-installation.ts | 55 +- .../src/drivers/acpx/antigravity-cli-pins.ts | 34 +- .../acpx/antigravity-credentials.test.ts | 26 +- .../drivers/acpx/antigravity-credentials.ts | 63 +- .../drivers/acpx/antigravity-installation.ts | 32 +- .../acpx/antigravity-model-catalog.test.ts | 8 +- .../drivers/acpx/antigravity-models.test.ts | 55 +- .../src/drivers/acpx/antigravity-models.ts | 169 +++- .../src/drivers/acpx/antigravity-process.ts | 5 +- .../acpx/antigravity-swarm-guard.test.ts | 27 +- .../drivers/acpx/antigravity-swarm-guard.ts | 21 +- .../acpx/antigravity-swarm-route.test.ts | 25 +- .../drivers/acpx/antigravity-swarm-route.ts | 47 +- .../acpx/antigravity-swarm-runtime.test.ts | 6 +- .../drivers/acpx/antigravity-swarm-runtime.ts | 163 +--- .../drivers/acpx/candidate-admission.test.ts | 10 +- .../src/drivers/acpx/codex-credentials.ts | 50 +- .../src/drivers/acpx/generated-profiles.ts | 41 +- .../native-distribution-integrity.test.ts | 6 +- .../acpx/profile-compatibility.test.ts | 5 +- .../src/drivers/acpx/runtime-host.ts | 49 +- .../src/drivers/acpx/runtime-sandbox.ts | 9 +- .../antigravity-cli/fake-agy-acp.mjs | 2 +- .../src/antigravity-models.generated.ts | 121 ++- .../shared/src/antigravity-models.test.ts | 27 +- packages/shared/src/antigravity-models.ts | 36 +- .../agent-adapter-validation-routes.test.ts | 2 +- .../antigravity-connection-models.test.ts | 2 +- .../src/services/antigravity-swarm.db.test.ts | 16 +- server/src/services/antigravity-swarm.test.ts | 4 +- server/src/services/antigravity-swarm.ts | 1 - .../managed-ai-credential-writeback.ts | 89 +- .../native-runtime/acpx-qualification.test.ts | 2 +- .../antigravity-candidate-admission.test.ts | 6 +- .../antigravity-release.test.ts | 2 +- .../native-session-executor.test.ts | 8 +- .../antigravity-qualification-cases.ts | 8 +- .../antigravity-qualification.test.ts | 9 +- tests/runner-e2e/catalog.test.ts | 6 +- .../runner-e2e/source-sdk-public-inputs.json | 6 +- ui/src/components/AdapterLoginChrome.test.tsx | 35 +- ui/src/components/AdapterLoginChrome.tsx | 24 +- .../ai-connections/useLocalAiLogin.test.tsx | 4 +- .../AgentProviderConnection.test.tsx | 6 +- ui/src/pages/apps/AppsConnect.test.tsx | 2 +- 72 files changed, 3912 insertions(+), 1705 deletions(-) create mode 100644 packages/paperclip-runner/src/drivers/acpx/antigravity-acp-connection.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.ts diff --git a/packages/paperclip-runner/acpx-profiles.json b/packages/paperclip-runner/acpx-profiles.json index 1c9313a77c8..8e4f34d23b0 100644 --- a/packages/paperclip-runner/acpx-profiles.json +++ b/packages/paperclip-runner/acpx-profiles.json @@ -5,12 +5,12 @@ "protocolVersion": 1, "profiles": { "antigravity": { - "agentProfileVersion": 2, - "agentServerPackage": "native:antigravity-acp", - "agentServerVersion": "1.5.2", - "agentRuntimePackage": "native:antigravity-localharness", - "agentRuntimeVersion": "1.5.2", - "commandDigest": "sha256:61ac14bf03ce4bbf8afe1f5a263b854517ec588d8407fe2d8f17c9fc0c037c4b", + "agentProfileVersion": 3, + "agentServerPackage": "native:antigravity-cli", + "agentServerVersion": "1.5.19", + "agentRuntimePackage": null, + "agentRuntimeVersion": null, + "commandDigest": "sha256:7dd51fb0646187701141c5e1a2ddd6296518e5799117e59b5ad2227e64e8394d", "requiresProviderPolicy": true }, "grok": { diff --git a/packages/paperclip-runner/antigravity-cli-distributions.json b/packages/paperclip-runner/antigravity-cli-distributions.json index 9539511bbdb..aa1f77972a0 100644 --- a/packages/paperclip-runner/antigravity-cli-distributions.json +++ b/packages/paperclip-runner/antigravity-cli-distributions.json @@ -2,8 +2,8 @@ "schema": "paperclip.antigravity_cli_distribution.v1", "route": "antigravity-cli", "qualification": "experimental", - "version": "1.5.15", - "build": "1.5.15-5514532022517760", + "version": "1.5.19", + "build": "1.5.19-4821414830800896", "args": [ "acp" ], @@ -12,61 +12,80 @@ }, "platforms": { "darwin-arm64": { - "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.15-5514532022517760/darwin-arm/cli_mac_arm64.tar.gz", + "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/darwin-arm/cli_mac_arm64.tar.gz", "archiveFormat": "tar.gz", - "archiveSize": 86166538, - "archiveSha512": "b03a841eb3a29be918a66960b775f68ed4f3bcc02f33962131bbbc26c46ea983ceac6c832ad46efd11d73d9a2cb97df4ab24d4bc92ee47d3d5ece7b8d8b61235", - "archiveSha256": "9e25108f3ea70cc6c846d88b9397456d13ae472a010016c3d625eb3fe99afc3a", + "archiveSize": 85928527, + "archiveSha512": "d798b1b2f91eb88a43c304ea5075db13cb069f01219c3b9f370037dc2c89d7e6c36ee96f160f9019947c1f5b55e744d8102e8303271d618f70d71cdb0911b213", + "archiveSha256": "4f1603c9de8c993a83a12ec06b7342b6fb7c27853e9d9fb6c786286461d1ff50", "archiveMember": "antigravity", "executable": "agy", - "executableSha512": "e96d893cafbaef8b504d46ec5b231dfefa242290f6148827261f6dafa08e9fdff785ae8343de372063b6dac1437ef5a94af61a3beded1eaca9f19c312bf33cad", + "executableSha512": "f09f2667e63863e28fecce2aca3af7298107f4c568a2b702aa9a23b81bbc42c9d06fa11ab54aaaa324269c0e36898c7660d5564b57404b3e4e170464b842a0cc", "entries": [ { "path": "agy", - "sha256": "8097b24de18aba93324ee24d0d3f060906c58ba58562f4f1bd66f380906056a2", - "size": 229617904, + "sha256": "757cf6cc4e88ca128a797d8275991537af0cc7943fbefc1c207332d32aabf0f7", + "size": 229574304, "executable": true } ], - "closureSha256": "d61f8aed4c0fffe5db28ab2174f0543ed1fc09e03f4c3f491f9cbee5db157c63" + "closureSha256": "83d5143264b2f6e944eae9dda9dbdb489e2a7805b2c5246990bf4756e0f6502c" + }, + "darwin-x64": { + "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/darwin-x64/cli_mac_x64.tar.gz", + "archiveFormat": "tar.gz", + "archiveSize": 91516270, + "archiveSha512": "c989fa40e36858cecebaa1223ed93fbb9aaaba6fbaf3697d5d397cd451b4eea9ba7cebb3b5a6faf8ddec6dbce3730bdfda98b1c182062a522a7b9ea875d30894", + "archiveSha256": "a8507272963d5a93f18bede59f6ba1efc29f6978a193a4ee5c9ad39a247b993e", + "archiveMember": "antigravity", + "executable": "agy", + "executableSha512": "6b8633f851feb0176a5fc01363e1a6bcc4cfa9844c36fce691687b5ecf6b9fca27af9c524163e23c1260caf5f4f0e50c2d6a26c6d8f5f56072a4d4d80a43ba2b", + "entries": [ + { + "path": "agy", + "sha256": "f991bce221d115f5fb3e1fae509d6f22aeaa68a904c05f236749dc20fe5ac1dc", + "size": 239536144, + "executable": true + } + ], + "closureSha256": "4d9bca68a74eefbea4aa2545eb50b36afbd5c5b81d9f1278388611f89ec0a0ca" }, "linux-x64": { - "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.15-5514532022517760/linux-x64/cli_linux_x64.tar.gz", + "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/linux-x64/cli_linux_x64.tar.gz", "archiveFormat": "tar.gz", - "archiveSize": 101464790, - "archiveSha512": "af3f0be58b8475940d79f9abea19e762ecc3d265ea9f56cff8dd805e27ba299b44a305a79504a7ffe6ebdfa29a294c56edc4caed1875990bfaf2fef1508ec8b0", - "archiveSha256": "8d9913298602049ef29e9669f35252b6b79571979ce1bd0fb27753c7bac84114", + "archiveSize": 103658205, + "archiveSha512": "8160da6ceef2b7b62bb4a630b54b3fb4ee5283377509230736880c4ba4815e848a25cf346954a98134b647eb2f5d34e0364e77fbf74367ffd7dc29c525ddd82d", + "archiveSha256": "971a4aa707fb0886d4e1df5f1f50bad7b01aa492d0b1f13df4ea7402e96dae90", "archiveMember": "antigravity", "executable": "agy", - "executableSha512": "d28b98e61c79129a3d5615af48ceb9f61737ac8c3feb6d077558605b40bf7159012b4a32084e1f728d8e14417182d4344a0bf7e10ba5934b3c8c0e6cb0a55c60", + "executableSha512": "10f05a1b1fc8550860efd13f929c706dbd21f3bb1e7688780a22643e1a64f532f44f3f01050c977678cdb8aa9eadeaa45f9bebd38e9b9bc0fee1e007e6495e37", "entries": [ { "path": "agy", - "sha256": "7b004d26c3fdea25a7c9d456de4bfaccef4be1e4cc7fd6db628859c5c941fa2d", - "size": 273879752, + "sha256": "1030610322de110757a2e4b811187ba06ff14a81a8f1cb10ac66935690250cbe", + "size": 281375456, "executable": true } ], - "closureSha256": "ffec3d7fcc882a243f7bfda808b601bb593c2a54514d492d719f7e546dd9990d" + "closureSha256": "8af424d013ce999900951e707888199ad63f4681ef8c5a5cd4ccae43ba60bfe6" }, "linux-arm64": { - "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.15-5514532022517760/linux-arm/cli_linux_arm64.tar.gz", + "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/linux-arm/cli_linux_arm64.tar.gz", "archiveFormat": "tar.gz", - "archiveSize": 92373221, - "archiveSha512": "d64ad759781b50dfacfa7d9826c0ad469959d01bdf5a170acd4c83472eba31c677baf0052ac8ab48eef40f0d3f0e26057e752aabd24331c79f4c881d4b872125", - "archiveSha256": "e5b5d7ca1dda2cfdc0b09c72931320c3ef5c481a14dbda137304107ce6e776b1", + "archiveSize": 94382838, + "archiveSha512": "eeecedfc2a63af281e245d73bb69f949a17c6d3ebcd3d023220056ddcc05e204a00d1d0ea77f68741b2fc15a1f66f740bc0e3bf800d734721c60938e61653010", + "archiveSha256": "aa316ff45b0d40b49ed83d29e3865857fca0c125f350fbb9d3c1cb9a640b49c4", "archiveMember": "antigravity", "executable": "agy", - "executableSha512": "4f9993957b391c046728435fff2e657ecdc16a82ddfcb774c83dd3becba6a8980e1ec2fc1e610cab9594edf690cc535d8ad5795a67faa2ae4197301d241bd492", + "executableSha512": "bba25cfd06f672e755f4e8a99b18f860ce7f074ca8b157eec91a738e1275922d795c35aec958b63c4f2ed014d153662434ea5580e3e00768875ca09f2352ba93", "entries": [ { "path": "agy", - "sha256": "497580a779b155268c4aa8f491b75e3b0034d4d0ba05c762582e7d97222396b0", - "size": 256660144, + "sha256": "f7eb360ab67f74f8307302fc5948775155be3a68b65763fe3c62aceda728a968", + "size": 263475936, "executable": true } ], - "closureSha256": "e564936c56b8e7158b517428d4c23261f420fe84d4d2e8f1dd71e650bb8e9fac" + "closureSha256": "abbc84893dde911e12878bb611f9e068796686259efcaf9a2bd2e312a4626c8e" } } } diff --git a/packages/paperclip-runner/antigravity-distributions.json b/packages/paperclip-runner/antigravity-distributions.json index 822c5715775..302e8715f15 100644 --- a/packages/paperclip-runner/antigravity-distributions.json +++ b/packages/paperclip-runner/antigravity-distributions.json @@ -1,134 +1,102 @@ { "schema": "paperclip.antigravity_distribution.v1", - "version": "1.5.2", + "version": "1.5.19", + "build": "1.5.19-4821414830800896", + "environment": { + "AGY_CLI_DISABLE_AUTO_UPDATE": "1" + }, "platforms": { "darwin-arm64": { - "url": "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.5.2-darwin-arm64.zip", - "archiveSha256": "123a16d5c40a8ac99e20f01a62b68dd860fd96b1c528dfb8eaa37ca8733d4845", - "closureSha256": "ab9df40a64806a8e1812234ce5331e04d1c6b5f8c7e5bdbb456cd645e58c5aad", + "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/darwin-arm/cli_mac_arm64.tar.gz", + "archiveFormat": "tar.gz", + "archiveSize": 85928527, + "archiveSha512": "d798b1b2f91eb88a43c304ea5075db13cb069f01219c3b9f370037dc2c89d7e6c36ee96f160f9019947c1f5b55e744d8102e8303271d618f70d71cdb0911b213", + "archiveSha256": "4f1603c9de8c993a83a12ec06b7342b6fb7c27853e9d9fb6c786286461d1ff50", + "archiveMember": "antigravity", + "closureSha256": "83d5143264b2f6e944eae9dda9dbdb489e2a7805b2c5246990bf4756e0f6502c", "provisioning": "verified-closure", - "executable": "agy_acp_server.par", - "args": [], + "executable": "agy", + "executableSha512": "f09f2667e63863e28fecce2aca3af7298107f4c568a2b702aa9a23b81bbc42c9d06fa11ab54aaaa324269c0e36898c7660d5564b57404b3e4e170464b842a0cc", + "args": [ + "acp" + ], "entries": [ { - "path": "agy_acp_server.par", - "sha256": "c716c4a665f3cdc1f2be40f3545be9e95b7433cd07cc536485a14a85d6570a59", - "size": 178875248, - "executable": true - }, - { - "path": "localharness_external", - "sha256": "31ec5f444b8c849ddb14da1c0893a87dddab60f1d5e282b79db36dc41b2521ab", - "size": 129208672, + "path": "agy", + "sha256": "757cf6cc4e88ca128a797d8275991537af0cc7943fbefc1c207332d32aabf0f7", + "size": 229574304, "executable": true } - ], - "vendorEntries": [ - { - "path": "agy_acp_server.par", - "sha256": "4cea3c96875a4bb66a1c136d972b5cfdc5f7c91579ff7b9cbfc158a4358270bc", - "size": 179921328, - "executable": true - }, - { - "path": "localharness_external", - "sha256": "31ec5f444b8c849ddb14da1c0893a87dddab60f1d5e282b79db36dc41b2521ab", - "size": 129208672, - "executable": true - } - ], - "vendorClosureSha256": "d03a6f593b6400c4b41d33a1732f842b6ff887a50727fadecb38ee67eac7336b", - "patchVersion": "1.5.2-paperclip.2", - "admissionSourceSha256": "358998c3a120b92beb7a7332c60616e8a550bddc6ee3485dfbf636dbbb0ca3a8" + ] }, "darwin-x64": { - "url": "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.5.2-darwin-x86_64.zip", - "archiveSha256": "92addb5580577b5356d35484d72d1a113d9c5312ad766bcb304983aa8e3fbb06", - "provisioning": "inventory-only", - "executable": "agy_acp_server.par", - "args": [] + "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/darwin-x64/cli_mac_x64.tar.gz", + "archiveFormat": "tar.gz", + "archiveSize": 91516270, + "archiveSha512": "c989fa40e36858cecebaa1223ed93fbb9aaaba6fbaf3697d5d397cd451b4eea9ba7cebb3b5a6faf8ddec6dbce3730bdfda98b1c182062a522a7b9ea875d30894", + "archiveSha256": "a8507272963d5a93f18bede59f6ba1efc29f6978a193a4ee5c9ad39a247b993e", + "archiveMember": "antigravity", + "closureSha256": "4d9bca68a74eefbea4aa2545eb50b36afbd5c5b81d9f1278388611f89ec0a0ca", + "provisioning": "verified-closure", + "executable": "agy", + "executableSha512": "6b8633f851feb0176a5fc01363e1a6bcc4cfa9844c36fce691687b5ecf6b9fca27af9c524163e23c1260caf5f4f0e50c2d6a26c6d8f5f56072a4d4d80a43ba2b", + "args": [ + "acp" + ], + "entries": [ + { + "path": "agy", + "sha256": "f991bce221d115f5fb3e1fae509d6f22aeaa68a904c05f236749dc20fe5ac1dc", + "size": 239536144, + "executable": true + } + ] }, "linux-x64": { - "url": "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.5.2-linux-x86_64.zip", - "archiveSha256": "99dd8612450805011619d7b8447ce374c289e00549d8557f36790e1dd6256852", - "closureSha256": "be35d65a32667550b5474588d705e6987a813e2fa619cf5db7d82d141c3c05fb", + "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/linux-x64/cli_linux_x64.tar.gz", + "archiveFormat": "tar.gz", + "archiveSize": 103658205, + "archiveSha512": "8160da6ceef2b7b62bb4a630b54b3fb4ee5283377509230736880c4ba4815e848a25cf346954a98134b647eb2f5d34e0364e77fbf74367ffd7dc29c525ddd82d", + "archiveSha256": "971a4aa707fb0886d4e1df5f1f50bad7b01aa492d0b1f13df4ea7402e96dae90", + "archiveMember": "antigravity", + "closureSha256": "8af424d013ce999900951e707888199ad63f4681ef8c5a5cd4ccae43ba60bfe6", "provisioning": "verified-closure", - "executable": "agy_acp_server.par", + "executable": "agy", + "executableSha512": "10f05a1b1fc8550860efd13f929c706dbd21f3bb1e7688780a22643e1a64f532f44f3f01050c977678cdb8aa9eadeaa45f9bebd38e9b9bc0fee1e007e6495e37", "args": [ - "--uid=" + "acp" ], "entries": [ { - "path": "agy_acp_server.par", - "sha256": "69dc28c074628da7fdb3f26160850b7e7567458abdab0c81ca0e3c3ad5bac1dd", - "size": 714384320, - "executable": true - }, - { - "path": "localharness_external", - "sha256": "072fc497e7814b0e25a7d80109bceddacd815eb351d2e48ce579a05510e0cfdf", - "size": 139194456, + "path": "agy", + "sha256": "1030610322de110757a2e4b811187ba06ff14a81a8f1cb10ac66935690250cbe", + "size": 281375456, "executable": true } - ], - "vendorEntries": [ - { - "path": "agy_acp_server.par", - "sha256": "f472860b79c4816a32817e589afdb01cec0ca731e5fa428eae873b14be12387f", - "size": 714384320, - "executable": true - }, - { - "path": "localharness_external", - "sha256": "072fc497e7814b0e25a7d80109bceddacd815eb351d2e48ce579a05510e0cfdf", - "size": 139194456, - "executable": true - } - ], - "vendorClosureSha256": "f1572eb45e2c3617527b0b31622fee555bc78ebfc1293614f02ae74aac770f7f", - "patchVersion": "1.5.2-paperclip.2", - "admissionSourceSha256": "358998c3a120b92beb7a7332c60616e8a550bddc6ee3485dfbf636dbbb0ca3a8" + ] }, "linux-arm64": { - "url": "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.5.2-linux-arm64.zip", - "archiveSha256": "e729e05ef54ef0763e48900032466b47fa7c9939cde257f93ba49410ab577acb", - "closureSha256": "46c36293779283c1f933eb438a143d116421a331f614601c754f1b94d9dc171a", + "url": "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/linux-arm/cli_linux_arm64.tar.gz", + "archiveFormat": "tar.gz", + "archiveSize": 94382838, + "archiveSha512": "eeecedfc2a63af281e245d73bb69f949a17c6d3ebcd3d023220056ddcc05e204a00d1d0ea77f68741b2fc15a1f66f740bc0e3bf800d734721c60938e61653010", + "archiveSha256": "aa316ff45b0d40b49ed83d29e3865857fca0c125f350fbb9d3c1cb9a640b49c4", + "archiveMember": "antigravity", + "closureSha256": "abbc84893dde911e12878bb611f9e068796686259efcaf9a2bd2e312a4626c8e", "provisioning": "verified-closure", - "executable": "agy_acp_server.par", + "executable": "agy", + "executableSha512": "bba25cfd06f672e755f4e8a99b18f860ce7f074ca8b157eec91a738e1275922d795c35aec958b63c4f2ed014d153662434ea5580e3e00768875ca09f2352ba93", "args": [ - "--uid=" + "acp" ], "entries": [ { - "path": "agy_acp_server.par", - "sha256": "93b1280744a8ce256574a1be1e02898530c7ea9aab48cbbbb429130be3030d8b", - "size": 721649155, - "executable": true - }, - { - "path": "localharness_external", - "sha256": "06b2fcf3c20d76cec15fc9db952731a2058356311e0760cb818feeabca6d6f91", - "size": 132598576, + "path": "agy", + "sha256": "f7eb360ab67f74f8307302fc5948775155be3a68b65763fe3c62aceda728a968", + "size": 263475936, "executable": true } - ], - "vendorEntries": [ - { - "path": "agy_acp_server.par", - "sha256": "748dda64d889552943b5527c78aa2804b4e2b9fed7501ae63eb0890ad539380e", - "size": 721649155, - "executable": true - }, - { - "path": "localharness_external", - "sha256": "06b2fcf3c20d76cec15fc9db952731a2058356311e0760cb818feeabca6d6f91", - "size": 132598576, - "executable": true - } - ], - "vendorClosureSha256": "99486e12ff9cb7f8ce2c3a582051bb1f5fa101173881a515c6c7b29a4bfd4730", - "patchVersion": "1.5.2-paperclip.2", - "admissionSourceSha256": "358998c3a120b92beb7a7332c60616e8a550bddc6ee3485dfbf636dbbb0ca3a8" + ] } } } diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_candidate_admission.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_candidate_admission.rs index d38d8341283..af868730a13 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_candidate_admission.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_candidate_admission.rs @@ -233,7 +233,8 @@ mod tests { #[test] fn candidate_record_is_strict_and_pinned_to_native_host_and_time() { - assert!(antigravity_native_closure("darwin", "x64").is_none()); + assert!(antigravity_native_closure("darwin", "x64").is_some()); + assert!(antigravity_native_closure("win32", "x64").is_none()); let pending = pending_antigravity_profile(); for (platform, architecture, os, host_arch) in ANTIGRAVITY_HOSTS { let candidate = antigravity_admission(platform, architecture); diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs b/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs index 5530cbbfc4d..d85f09ac6ea 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs @@ -31,13 +31,16 @@ pub(crate) fn antigravity_native_closure( ) -> Option<&'static str> { match (platform, architecture) { ("darwin", "arm64") => { - Some("ab9df40a64806a8e1812234ce5331e04d1c6b5f8c7e5bdbb456cd645e58c5aad") + Some("83d5143264b2f6e944eae9dda9dbdb489e2a7805b2c5246990bf4756e0f6502c") + } + ("darwin", "x64") => { + Some("4d9bca68a74eefbea4aa2545eb50b36afbd5c5b81d9f1278388611f89ec0a0ca") } ("linux", "x64") => { - Some("be35d65a32667550b5474588d705e6987a813e2fa619cf5db7d82d141c3c05fb") + Some("8af424d013ce999900951e707888199ad63f4681ef8c5a5cd4ccae43ba60bfe6") } ("linux", "arm64") => { - Some("46c36293779283c1f933eb438a143d116421a331f614601c754f1b94d9dc171a") + Some("abbc84893dde911e12878bb611f9e068796686259efcaf9a2bd2e312a4626c8e") } _ => None, } @@ -46,12 +49,12 @@ pub(crate) fn antigravity_native_closure( pub(crate) fn acpx_release_profile(agent: &str) -> Option { Some(match agent { "antigravity" => AcpxReleaseProfile { - agent_server_package: "native:antigravity-acp", - agent_server_version: "1.5.2", - agent_runtime_package: Some("native:antigravity-localharness"), - agent_runtime_version: Some("1.5.2"), + agent_server_package: "native:antigravity-cli", + agent_server_version: "1.5.19", + agent_runtime_package: None, + agent_runtime_version: None, command_digest: - "sha256:61ac14bf03ce4bbf8afe1f5a263b854517ec588d8407fe2d8f17c9fc0c037c4b", + "sha256:7dd51fb0646187701141c5e1a2ddd6296518e5799117e59b5ad2227e64e8394d", requires_provider_policy: true, qualification_pending: false, }, diff --git a/packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.mjs b/packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.mjs index 5130c5bbaaf..6703cdcd3e9 100644 --- a/packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.mjs +++ b/packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { once } from "node:events"; -import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, realpath, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { performance } from "node:perf_hooks"; @@ -34,8 +34,8 @@ export function assertAntigravityProviderPackInventory(manifest, profile, pins, /** * Launches the packaged closure through the Runner's own installation verifier * and private launch snapshot. Without `apiKey` it is credential-free: only - * `initialize`. With `apiKey` it also opens one API-key session and checks the - * exact-model native admission receipt. It never sends a prompt. + * `initialize` against pinned `agy acp`. With `apiKey` it also authenticates + * with `gemini-api-key`, opens one session, and selects `model`. It never sends a prompt. */ export async function smokeAntigravityProviderPack(directory, { apiKey, model = ANTIGRAVITY_SMOKE_MODEL } = {}) { const started = performance.now(); @@ -47,9 +47,9 @@ export async function smokeAntigravityProviderPack(directory, { apiKey, model = if (process.env.PAPERCLIP_EXPECTED_SOURCE_REVISION) assert.equal(manifest.payload.runnerSourceRevision, process.env.PAPERCLIP_EXPECTED_SOURCE_REVISION); const load = path => import(pathToFileURL(join(pack, "dist/drivers/acpx", path))); const [{ verifyAntigravityInstallation }, { QUALIFIED_ACPX_PROFILES, resolveQualifiedAcpxProfile }, { ANTIGRAVITY_DISTRIBUTION_PINS, ANTIGRAVITY_RUNTIME_VERSION }, - { bindAcpxCandidateAdmission }, { antigravityPrivateEnvironment, retireAntigravityProcess }, { createAntigravityAdmission }] = await Promise.all([ + { bindAcpxCandidateAdmission }, { antigravityPrivateEnvironment, retireAntigravityProcess }] = await Promise.all([ load("antigravity-installation.js"), load("qualified-profiles.js"), load("generated-profiles.js"), - load("candidate-admission.js"), load("antigravity-process.js"), load("antigravity-admission.js"), + load("candidate-admission.js"), load("antigravity-process.js"), ]); const release = QUALIFIED_ACPX_PROFILES.antigravity; const provider = assertAntigravityProviderPackInventory(manifest, release, ANTIGRAVITY_DISTRIBUTION_PINS); @@ -70,18 +70,13 @@ export async function smokeAntigravityProviderPack(directory, { apiKey, model = let lease, child, closed; try { let phase = performance.now(); - const installation = await verifyAntigravityInstallation(profile, admission); + const installation = await verifyAntigravityInstallation(profile, admission, ["--gemini-dir", home, "--disable-telemetry"]); timings.verifyMs = elapsed(phase); phase = performance.now(); lease = await installation.openCommand(); timings.launchSnapshotMs = elapsed(phase); const env = await antigravityPrivateEnvironment(home); - if (apiKey) { - await mkdir(join(home, "antigravity-acp"), { mode: 0o700 }); - await writeFile(join(home, "antigravity-acp", "settings.json"), `${JSON.stringify({ auth: { type: "gemini-api-key" } })}\n`, { mode: 0o600 }); - env.GEMINI_API_KEY = apiKey; - } - const guard = createAntigravityAdmission(SMOKE_INSTRUCTIONS, model).createGuard(); + if (apiKey) env.GEMINI_API_KEY = apiKey; phase = performance.now(); child = lease.spawn([], { cwd: workspace, stdio: "pipe", env }); closed = once(child, "close").then(() => undefined); @@ -99,8 +94,14 @@ export async function smokeAntigravityProviderPack(directory, { apiKey, model = const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1); if (!line.trim()) continue; let value; - try { value = JSON.parse(line); guard("inbound", value); } catch (error) { fail(error instanceof SyntaxError ? new Error("Antigravity emitted malformed ACP JSON") : error); return; } - const request = pending.get(value.id); + try { value = JSON.parse(line); } catch { fail(new Error("Antigravity emitted malformed ACP JSON")); return; } + if (typeof value?.method === "string") { + if (value.id !== undefined) { + child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: value.id, error: { code: -32601, message: "unsupported" } })}\n`); + } + continue; + } + const request = pending.get(value?.id); if (request && value.method === undefined) { pending.delete(value.id); if (value.error) request.reject(new Error(`Antigravity rejected ACP request (${value.error.code})`)); @@ -114,26 +115,32 @@ export async function smokeAntigravityProviderPack(directory, { apiKey, model = const timeout = setTimeout(() => { pending.delete(id); reject(new Error(`Antigravity ${method} timed out`)); }, timeoutMs); const settle = callback => value => { clearTimeout(timeout); callback(value); }; pending.set(id, { resolve: settle(accept), reject: settle(reject) }); - try { guard("outbound", message); } catch (error) { pending.delete(id); clearTimeout(timeout); reject(error); return; } child.stdin.write(`${JSON.stringify(message)}\n`); }); const initialized = await request("initialize", { protocolVersion: 1, clientCapabilities: {}, clientInfo: { name: "paperclip-provider-pack-smoke", version: "1" } }, 60_000); timings.initializeMs = elapsed(phase); - assert.equal(initialized.agentInfo?.name, "antigravity-acp"); + assert.equal(initialized.agentInfo?.name, "Antigravity ACP Server"); assert.equal(initialized.agentInfo?.version, ANTIGRAVITY_RUNTIME_VERSION); assert.equal(initialized.agentInfo.version, provider.version); - assert.equal(initialized.agentCapabilities?._meta?.antigravity?.paperclipAdmission, 1); - assert.equal(initialized.agentCapabilities._meta.antigravity.paperclipModels, 1); + assert.equal(initialized.agentCapabilities?._meta?.antigravity?.systemPrompt?.append, true); + assert.ok(Array.isArray(initialized.authMethods) && initialized.authMethods.some(m => m?.id === "oauth-personal"), + "Antigravity initialize must advertise oauth-personal auth method"); + assert.ok(initialized.authMethods.some(m => m?.id === "gemini-api-key"), + "Antigravity initialize must advertise gemini-api-key auth method"); let session = null; if (apiKey) { phase = performance.now(); - const created = await request("session/new", { cwd: workspace, mcpServers: [] }, 90_000); + await request("authenticate", { methodId: "gemini-api-key" }, 30_000); + const created = await request("session/new", { + cwd: workspace, + mcpServers: [], + _meta: { antigravity: { systemPrompt: { append: SMOKE_INSTRUCTIONS } } }, + }, 90_000); timings.sessionNewMs = elapsed(phase); - const receipt = created._meta?.paperclipAntigravityAdmission; - // The guard already rejected a missing, stale or different-model receipt. - assert.equal(receipt?.model, model); - assert.equal(receipt.sessionId, created.sessionId); - session = { authMethod: "gemini-api-key", model: receipt.model, receiptSchema: receipt.schema, receiptMatched: true }; + assert.equal(typeof created.sessionId, "string"); + assert.ok(created.sessionId.length > 0, "session/new must return a sessionId"); + await request("session/set_model", { sessionId: created.sessionId, modelId: model }, 30_000); + session = { authMethod: "gemini-api-key", model, sessionId: created.sessionId }; } phase = performance.now(); await retireAntigravityProcess(child, closed); @@ -144,7 +151,7 @@ export async function smokeAntigravityProviderPack(directory, { apiKey, model = timings.totalMs = elapsed(started); return { schema: "paperclip.antigravity-provider-pack-smoke.v1", sourceRevision: manifest.payload.runnerSourceRevision, providerPackDigest: manifest.digest, platform: process.platform, architecture: process.arch, runtimeVersion: initialized.agentInfo.version, qualification: provider.qualification, - profileDigest: provider.profileDigest, closureDigest: provider.closureDigest, paperclipAdmission: 1, session, timings, + profileDigest: provider.profileDigest, closureDigest: provider.closureDigest, systemPromptAppend: true, session, timings, providerPrompts: 0, providerCredentials: Boolean(apiKey) }; } finally { try { diff --git a/packages/paperclip-runner/scripts/candidate-provider-pack.mjs b/packages/paperclip-runner/scripts/candidate-provider-pack.mjs index 46c7cde02c9..fb41735f8f0 100644 --- a/packages/paperclip-runner/scripts/candidate-provider-pack.mjs +++ b/packages/paperclip-runner/scripts/candidate-provider-pack.mjs @@ -75,8 +75,8 @@ export async function materializeAntigravityProviderPack({ outputRoot, platform } const profile = profiles.profiles.antigravity; if (result?.version !== profile.agentServerVersion || !/^[a-f0-9]{64}$/.test(result.closureSha256 ?? "") - || result.closureSha256 === result.vendorClosureSha256 || !result.patchVersion) { - throw new Error("Antigravity provider pack requires this release's patched runtime closure"); + || (result.patchVersion && result.closureSha256 === result.vendorClosureSha256)) { + throw new Error("Antigravity provider pack requires this release's pinned runtime closure"); } return { version: result.version, profileDigest: profile.commandDigest, closureDigest: `sha256:${result.closureSha256}` }; } diff --git a/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs b/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs index 59646d31586..98cab7f3f08 100644 --- a/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs +++ b/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs @@ -159,16 +159,16 @@ test("pending Antigravity stays an explicit linux-x64 candidate when marked pend } }); -test("Antigravity pack builder keeps only this release's patched closure", async () => { - const distribution = { version: "1.5.2", closureSha256: "a".repeat(64), vendorClosureSha256: "b".repeat(64), patchVersion: "1.5.2-paperclip.2" }; +test("Antigravity pack builder keeps only this release's pinned closure", async () => { + const distribution = { version: profiles.profiles.antigravity.agentServerVersion, closureSha256: "a".repeat(64) }; const calls = []; const build = result => async options => { calls.push(options); return result; }; const accepted = await materializeAntigravityProviderPack({ outputRoot: "/pack/provider-assets/antigravity/linux-x64", platform: "linux", architecture: "x64", materialize: build(distribution) }); - assert.deepEqual(accepted, { version: "1.5.2", profileDigest: profiles.profiles.antigravity.commandDigest, closureDigest: `sha256:${"a".repeat(64)}` }); + assert.deepEqual(accepted, { version: profiles.profiles.antigravity.agentServerVersion, profileDigest: profiles.profiles.antigravity.commandDigest, closureDigest: `sha256:${"a".repeat(64)}` }); assert.deepEqual(calls[0], { destination: "/pack/provider-assets/antigravity/linux-x64", platform: "linux", architecture: "x64" }); - for (const wrong of [{ closureSha256: "b".repeat(64) }, { patchVersion: undefined }, { version: "1.4.3" }, { closureSha256: "short" }]) { + for (const wrong of [{ version: "1.4.3" }, { closureSha256: "short" }, { closureSha256: "b".repeat(64), vendorClosureSha256: "b".repeat(64), patchVersion: "legacy-patch" }]) { await assert.rejects(materializeAntigravityProviderPack({ outputRoot: "/pack", platform: "linux", architecture: "x64", materialize: build({ ...distribution, ...wrong }) }), - /patched runtime closure/); + /pinned runtime closure/); } calls.length = 0; await assert.rejects(materializeAntigravityProviderPack({ outputRoot: "/pack", platform: "darwin", architecture: "arm64", materialize: build(distribution) }), /only for linux-x64/); @@ -177,7 +177,7 @@ test("Antigravity pack builder keeps only this release's patched closure", async test("Antigravity pack builder repeats only a failed download", async t => { t.mock.method(process.stderr, "write", () => true); - const distribution = { version: "1.5.2", closureSha256: "a".repeat(64), vendorClosureSha256: "b".repeat(64), patchVersion: "1.5.2-paperclip.2" }; + const distribution = { version: profiles.profiles.antigravity.agentServerVersion, closureSha256: "a".repeat(64) }; let attempts = 0; const flaky = async () => { if (++attempts < 3) throw new Error("Antigravity archive download failed: 503"); return distribution; }; const result = await materializeAntigravityProviderPack({ outputRoot: "/pack", platform: "linux", architecture: "x64", materialize: flaky, retryDelayMs: 1 }); diff --git a/packages/paperclip-runner/scripts/generate-antigravity-models.mjs b/packages/paperclip-runner/scripts/generate-antigravity-models.mjs index 3bf621f7f82..134c4016ac0 100644 --- a/packages/paperclip-runner/scripts/generate-antigravity-models.mjs +++ b/packages/paperclip-runner/scripts/generate-antigravity-models.mjs @@ -159,11 +159,11 @@ export async function withPromptFreeAntigravitySession(steps) { for (const key of ["HOME", "GEMINI_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "TMPDIR"]) await mkdir(env[key], { mode: 0o700 }); const workspace = join(root, "workspace"); await mkdir(workspace, { mode: 0o700 }); - child = spawn(join(runtimeDirectory, distribution.executable), distribution.args, { cwd: root, env, stdio: "pipe", detached: true }); + child = spawn(join(runtimeDirectory, distribution.executable), [...distribution.args, "--gemini-dir", env.GEMINI_HOME, "--disable-telemetry"], { cwd: root, env, stdio: "pipe", detached: true }); child.stderr.resume(); const request = rpcClient(child); const initialized = await request("initialize", { protocolVersion: 1, clientInfo: { name: "paperclip-runner", version: "1" }, clientCapabilities: {} }); - if (initialized?.agentInfo?.name !== "antigravity-acp" || initialized.agentInfo.version !== distribution.version) fail("runtime identity differs from the pin"); + if (initialized?.agentInfo?.name !== "Antigravity ACP Server" || initialized.agentInfo.version !== distribution.version) fail("runtime identity differs from the pin"); await request("authenticate", { methodId: "gemini-api-key" }); return { distribution, result: await steps(request, workspace) }; } finally { @@ -172,30 +172,52 @@ export async function withPromptFreeAntigravitySession(steps) { } } +/** Derive families from the live `session/new` model list and model config options. */ +export function deriveAntigravityFamilies(session) { + const models = session?.models?.availableModels; + if (!Array.isArray(models) || models.length === 0) fail("session did not list models"); + const configOptions = Array.isArray(session?.configOptions) ? session.configOptions : []; + const familyLabels = new Map(); + const modelOption = configOptions.find(option => option?.id === "model"); + for (const choice of Array.isArray(modelOption?.options) ? modelOption.options : []) { + if (typeof choice?.value === "string" && typeof choice?.name === "string") familyLabels.set(choice.value, choice.name.trim()); + } + const byFamily = new Map(); + for (const entry of models) { + const id = typeof entry?.modelId === "string" ? entry.modelId : ""; + const label = typeof entry?.name === "string" ? entry.name.trim() : ""; + const cut = id.lastIndexOf("-"); + if (cut < 1) fail(`unexpected model id ${id}`); + const familyId = id.slice(0, cut); + const level = id.slice(cut + 1); + const familyLabel = familyLabels.get(familyId) ?? label.replace(/\s*\([^)]+\)$/, "").trim(); + if (!/^[a-z0-9][a-z0-9.-]*$/.test(familyId) || !familyLabel) fail(`invalid family identity for ${id}`); + let family = byFamily.get(familyId); + if (!family) { + family = { id: familyId, label: familyLabel, baseModelId: familyId, levels: [], agentPlatformOnly: false }; + byFamily.set(familyId, family); + } + if (!family.levels.includes(level)) family.levels.push(level); + } + return [...byFamily.values()]; +} + /** The API-key catalog exactly as one fresh native session lists it. */ export async function readLiveApiKeyCatalog() { return withPromptFreeAntigravitySession(async (request, workspace) => { const session = await request("session/new", { cwd: workspace, mcpServers: [] }); const models = session?.models; if (!Array.isArray(models?.availableModels) || typeof models.currentModelId !== "string") fail("session did not list models"); + const families = deriveAntigravityFamilies(session); await request("session/close", { sessionId: session.sessionId }).catch(() => undefined); return { defaultModelId: models.currentModelId, models: models.availableModels.map(model => ({ id: model.modelId, label: model.name })), + families, }; }); } -async function staticCatalog(distribution) { - const { antigravityRuntimeCachePath } = await import("./antigravity-provisioner-layout.mjs"); - const { antigravityEmbeddedArchive, ANTIGRAVITY_PATCH_TARGETS } = await import("./patch-antigravity-runtime.mjs"); - const directory = antigravityRuntimeCachePath(distribution.closureSha256, distribution.platform, distribution.architecture); - // The patch replaces server.py and SDK files only; the catalog table is vendor source. - const server = await readFile(join(directory, distribution.executable)); - const { start, length } = antigravityEmbeddedArchive(server, ANTIGRAVITY_PATCH_TARGETS[SOURCE_PLATFORM]); - return parseAntigravityCatalogSource(readZipMember(server.subarray(start, start + length), MODEL_SELECTION_SOURCE).toString("utf8")); -} - /** Joins the two reads; any disagreement stops generation. */ export function buildAntigravityModelCatalog({ families, live, binding }) { const expanded = families.filter(family => !family.agentPlatformOnly).flatMap(family => family.levels.map(level => `${family.id}-${level}`)); @@ -215,7 +237,7 @@ export function buildAntigravityModelCatalog({ families, live, binding }) { export function bindingFromDeclaration(declaration) { const item = declaration.platforms?.[SOURCE_PLATFORM]; if (!item) fail(`${SOURCE_PLATFORM} is not declared`); - return { runtimeVersion: declaration.version, platform: SOURCE_PLATFORM, archiveSha256: item.archiveSha256, vendorClosureSha256: item.vendorClosureSha256 }; + return { runtimeVersion: declaration.version, platform: SOURCE_PLATFORM, archiveSha256: item.archiveSha256, closureSha256: item.closureSha256 }; } export function renderAntigravityModelCatalog(catalog) { @@ -258,7 +280,7 @@ async function main() { const { distribution, result: live } = await readLiveApiKeyCatalog(); const binding = bindingFromDeclaration(JSON.parse(await readFile(DISTRIBUTIONS_PATH, "utf8"))); if (binding.runtimeVersion !== distribution.version) fail("runtime version differs from the declaration"); - const catalog = buildAntigravityModelCatalog({ families: await staticCatalog(distribution), live, binding }); + const catalog = buildAntigravityModelCatalog({ families: live.families, live: { defaultModelId: live.defaultModelId, models: live.models }, binding }); await writeFile(ANTIGRAVITY_MODELS_OUTPUT, renderAntigravityModelCatalog(catalog)); process.stdout.write(`Wrote ${catalog.apiKey.models.length} API-key models and ${catalog.families.length} families.\n`); } diff --git a/packages/paperclip-runner/scripts/materialize-antigravity-cli-distribution.test.mjs b/packages/paperclip-runner/scripts/materialize-antigravity-cli-distribution.test.mjs index c41e33dab90..ad6051703ce 100644 --- a/packages/paperclip-runner/scripts/materialize-antigravity-cli-distribution.test.mjs +++ b/packages/paperclip-runner/scripts/materialize-antigravity-cli-distribution.test.mjs @@ -39,7 +39,7 @@ const tarGz = options => gzipSync(tar(options)); function pin(archive, { content = executable } = {}) { const entries = [{ path: "agy", sha256: sha256(content), size: content.length, executable: true }]; return { - url: "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.15-5514532022517760/darwin-arm/fixture.tar.gz", + url: "https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/darwin-arm/fixture.tar.gz", archiveFormat: "tar.gz", archiveSize: archive.length, archiveSha512: sha512(archive), archiveSha256: sha256(archive), archiveMember: "antigravity", executable: "agy", executableSha512: sha512(content), entries, closureSha256: sha256(JSON.stringify(entries)), }; @@ -67,23 +67,22 @@ async function fixture(t, { archive = tarGz(), platforms } = {}) { return { root, home, archivePath, api, provision, destination }; } -test("the CLI route pins Google's 1.5.15 archives for macOS ARM and both Linux targets", async () => { +test("the CLI route pins Google's 1.5.19 archives for macOS and both Linux targets", async () => { assert.equal(declaration.schema, "paperclip.antigravity_cli_distribution.v1"); - assert.equal(declaration.version, "1.5.15"); - assert.equal(declaration.build, "1.5.15-5514532022517760"); + assert.equal(declaration.version, "1.5.19"); + assert.equal(declaration.build, "1.5.19-4821414830800896"); assert.deepEqual(declaration.args, ["acp"]); assert.deepEqual(declaration.environment, { AGY_CLI_DISABLE_AUTO_UPDATE: "1" }); - assert.deepEqual(Object.keys(declaration.platforms).sort(), ["darwin-arm64", "linux-arm64", "linux-x64"]); - const sizes = { "darwin-arm64": 86_166_538, "linux-x64": 101_464_790, "linux-arm64": 92_373_221 }; + assert.deepEqual(Object.keys(declaration.platforms).sort(), ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"]); + const sizes = { "darwin-arm64": 85_928_527, "darwin-x64": 91_516_270, "linux-x64": 103_658_205, "linux-arm64": 94_382_838 }; for (const [target, size] of Object.entries(sizes)) { const [platform, architecture] = target.split("-"); const item = await antigravityCliDistribution(platform, architecture); assert.equal(item.archiveSize, size); assert.equal(item.closureSha256, sha256(JSON.stringify(item.entries))); assert.equal(item.entries[0].path, "agy"); - assert.match(item.url, /^https:\/\/storage\.googleapis\.com\/antigravity-public\/antigravity-cli\/1\.5\.15-5514532022517760\//); + assert.match(item.url, /^https:\/\/storage\.googleapis\.com\/antigravity-public\/antigravity-cli\/1\.5\.19-4821414830800896\//); } - await assert.rejects(antigravityCliDistribution("darwin", "x64"), /no pinned distribution for darwin\/x64/); await assert.rejects(antigravityCliDistribution("win32", "x64"), /no pinned distribution for win32\/x64/); }); @@ -91,7 +90,7 @@ test("a declaration that points away from Google's versioned bucket or breaks it const archive = tarGz(); for (const change of [ item => ({ ...item, url: item.url.replace("storage.googleapis.com", "example.com") }), - item => ({ ...item, url: item.url.replace("1.5.15-5514532022517760", "latest") }), + item => ({ ...item, url: item.url.replace("1.5.19-4821414830800896", "latest") }), item => ({ ...item, url: item.url.replace("https:", "http:") }), item => ({ ...item, closureSha256: "0".repeat(64) }), item => ({ ...item, archiveSha512: "abc" }), @@ -137,7 +136,7 @@ test("setup verifies the archive and executable, installs beside the registry-se assert.deepEqual((await readdir(f.destination)).sort(), [".paperclip-antigravity-cli-closure.json", "agy"]); const record = JSON.parse(await readFile(join(f.destination, ".paperclip-antigravity-cli-closure.json"), "utf8")); assert.equal(record.schema, "paperclip.antigravity_cli_closure.v1"); - assert.equal(record.build, "1.5.15-5514532022517760"); + assert.equal(record.build, "1.5.19-4821414830800896"); assert.deepEqual(record.entries, first.entries); assert.equal(await readFile(join(registry, "agy_acp_server.par"), "utf8"), "registry server"); // A re-run verifies in place and needs neither the archive nor the network. diff --git a/packages/paperclip-runner/scripts/materialize-antigravity-distribution.mjs b/packages/paperclip-runner/scripts/materialize-antigravity-distribution.mjs index 7e1f1eaaf4f..da649985515 100644 --- a/packages/paperclip-runner/scripts/materialize-antigravity-distribution.mjs +++ b/packages/paperclip-runner/scripts/materialize-antigravity-distribution.mjs @@ -4,18 +4,19 @@ import { chmod, lstat, mkdir, mkdtemp, open, readdir, realpath, rename, rm, writ import { basename, dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { isDeepStrictEqual } from "node:util"; -import { inflateRawSync } from "node:zlib"; -import { ANTIGRAVITY_PATCH_VERSION, patchAntigravityRuntime } from "./patch-antigravity-runtime.mjs"; +import { gunzipSync } from "node:zlib"; const MANIFEST_PATH = fileURLToPath(new URL("../antigravity-distributions.json", import.meta.url)); -const ADMISSION_SOURCE_PATH = fileURLToPath(new URL("./patch-antigravity-runtime.admission.py", import.meta.url)); -// The Linux x64 archive is about 274 MB; its unpacked closure is about 853 MB. -const MAX_ARCHIVE_BYTES = 384 * 1024 * 1024; -const MAX_TREE_BYTES = 1024 * 1024 * 1024; +// The Linux x64 CLI archive is about 104 MB; its unpacked Go binary is about 281 MB. +const MAX_ARCHIVE_BYTES = 192 * 1024 * 1024; +const MAX_TREE_BYTES = 512 * 1024 * 1024; export const ANTIGRAVITY_TREE_MANIFEST = ".paperclip-antigravity-closure.json"; -const RUNTIME_FILES = ["agy_acp_server.par", "localharness_external"]; +const EXECUTABLE = "agy"; +const ARCHIVE_MEMBER = "antigravity"; +const RUNTIME_FILES = [EXECUTABLE]; const SHA256 = /^[a-f0-9]{64}$/; -const digest = bytes => createHash("sha256").update(bytes).digest("hex"); +const SHA512 = /^[a-f0-9]{128}$/; +const digest = (bytes, algorithm = "sha256") => createHash(algorithm).update(bytes).digest("hex"); function assertTrustedOwner(stat) { const uid = process.getuid?.(); @@ -95,45 +96,63 @@ export async function ownedDestination(destination) { try { await lstat(ancestor); break; } catch (error) { if (error.code !== "ENOENT") throw error; - missing.push(basename(ancestor)); - ancestor = dirname(ancestor); + const parent = dirname(ancestor); + if (parent === ancestor) throw error; + missing.unshift(basename(ancestor)); + ancestor = parent; } } - let { directory } = await ownedDirectory(ancestor, { parentAlias: true }); - for (const name of missing.reverse()) { - directory = join(directory, name); - try { await mkdir(directory, { mode: 0o700 }); } - catch (error) { if (error.code !== "EEXIST") throw error; } - directory = (await ownedDirectory(directory)).directory; + let current = (await ownedDirectory(ancestor, { parentAlias: true })).directory; + for (const segment of missing) { + current = join(current, segment); + await mkdir(current, { mode: 0o700 }); + current = (await ownedDirectory(current)).directory; } - return join(directory, basename(destination)); + return join(current, basename(destination)); +} + +function octal(field) { + const text = field.toString("latin1").replace(/[\0 ]+$/, "").replace(/^ +/, ""); + if (!/^[0-7]{1,12}$/.test(text)) return -1; + return Number.parseInt(text, 8); } /** Only the checked-in declaration selects downloads and runtime contents. */ export async function antigravityDistribution(platform = process.platform, architecture = process.arch) { const manifest = JSON.parse((await readOwnedFile(MANIFEST_PATH, 64 * 1024)).toString("utf8")); const item = manifest.platforms?.[`${platform}-${architecture}`]; - if (manifest.schema !== "paperclip.antigravity_distribution.v1" || !/^\d+\.\d+\.\d+$/.test(manifest.version)) throw new Error("Invalid Antigravity distribution declaration"); + if (manifest.schema !== "paperclip.antigravity_distribution.v1" || !/^\d+\.\d+\.\d+$/.test(manifest.version) + || typeof manifest.build !== "string" || !manifest.build.startsWith(`${manifest.version}-`) || !/^\d+\.\d+\.\d+-\d+$/.test(manifest.build)) { + throw new Error("Invalid Antigravity distribution declaration"); + } if (!item) throw new Error(`Antigravity has no pinned distribution for ${platform}/${architecture}`); if (item.provisioning !== "verified-closure") throw new Error(`Antigravity ${platform}/${architecture} is inventory-only; its complete runtime closure is not verified`); const url = new URL(item.url); - if (url.protocol !== "https:" || url.hostname !== "dl.google.com" || url.username || url.password || url.search || url.hash || !url.pathname.startsWith("/agy-extensions/releases/")) throw new Error("Antigravity requires an official pinned distribution URL"); - if (!SHA256.test(item.archiveSha256) || !SHA256.test(item.closureSha256) || item.executable !== RUNTIME_FILES[0] || !Array.isArray(item.args) || item.args.some(arg => typeof arg !== "string")) throw new Error("Invalid Antigravity distribution pins"); - for (const [entries, sha256] of [[item.entries, item.closureSha256], [item.vendorEntries, item.vendorClosureSha256]]) { - if (!Array.isArray(entries) || entries.length !== RUNTIME_FILES.length || entries.some((entry, index) => entry.path !== RUNTIME_FILES[index] || !SHA256.test(entry.sha256) || !Number.isSafeInteger(entry.size) || entry.size < 1 || entry.executable !== true) || digest(JSON.stringify(entries)) !== sha256) throw new Error("Invalid Antigravity complete execution closure pins"); + if (url.protocol !== "https:" || url.hostname !== "storage.googleapis.com" || url.port || url.username || url.password || url.search || url.hash + || !url.pathname.startsWith(`/antigravity-public/antigravity-cli/${manifest.build}/`) || url.pathname.includes("..")) { + throw new Error("Antigravity requires an official pinned distribution URL"); } - if (item.patchVersion !== ANTIGRAVITY_PATCH_VERSION || !SHA256.test(item.admissionSourceSha256)) throw new Error("Antigravity distribution must pin its owned native admission patch"); - if (digest(await readOwnedFile(ADMISSION_SOURCE_PATH, 64 * 1024)) !== item.admissionSourceSha256) throw new Error("Antigravity native admission patch source digest mismatch"); - return { ...item, version: manifest.version, platform, architecture }; + if (item.archiveFormat !== "tar.gz" || !Number.isSafeInteger(item.archiveSize) || item.archiveSize < 1 || item.archiveSize > MAX_ARCHIVE_BYTES + || !SHA256.test(item.archiveSha256) || !SHA512.test(item.archiveSha512) || !SHA512.test(item.executableSha512) + || !SHA256.test(item.closureSha256) || item.archiveMember !== ARCHIVE_MEMBER || item.executable !== EXECUTABLE + || !Array.isArray(item.args) || item.args.some(arg => typeof arg !== "string")) { + throw new Error("Invalid Antigravity distribution pins"); + } + if (!Array.isArray(item.entries) || item.entries.length !== RUNTIME_FILES.length + || item.entries.some((entry, index) => entry.path !== RUNTIME_FILES[index] || !SHA256.test(entry.sha256) || !Number.isSafeInteger(entry.size) || entry.size < 1 || entry.size > MAX_TREE_BYTES || entry.executable !== true) + || digest(JSON.stringify(item.entries)) !== item.closureSha256) { + throw new Error("Invalid Antigravity complete execution closure pins"); + } + return { ...item, version: manifest.version, build: manifest.build, environment: { ...(manifest.environment ?? {}) }, platform, architecture }; } -/** Hash both native binaries; a cached local manifest never establishes trust. */ +/** Hash the native binary; a cached local manifest never establishes trust. */ export async function antigravityDistributionClosure(directory) { const root = await ownedDirectory(directory, { privateRoot: true }); directory = root.directory; const names = (await readdir(directory)).sort(); const files = names.filter(name => name !== ANTIGRAVITY_TREE_MANIFEST); - if (JSON.stringify(files) !== JSON.stringify(RUNTIME_FILES)) throw new Error("Antigravity closure must contain exactly both native binaries"); + if (JSON.stringify(files) !== JSON.stringify(RUNTIME_FILES)) throw new Error("Antigravity closure must contain exactly its pinned native executable"); let bytes = 0; const entries = []; for (const name of names) { @@ -171,54 +190,38 @@ export async function verifyAntigravityDistribution(directory, distribution) { } function closureRecord(distribution, closure) { - return { schema: "paperclip.antigravity_closure.v1", version: distribution.version, patchVersion: distribution.patchVersion, admissionSourceSha256: distribution.admissionSourceSha256, - archiveSha256: distribution.archiveSha256, vendorClosureSha256: distribution.vendorClosureSha256, closureSha256: distribution.closureSha256, entries: closure.entries }; + return { + schema: "paperclip.antigravity_closure.v1", + version: distribution.version, + build: distribution.build, + archiveSha256: distribution.archiveSha256, + archiveSha512: distribution.archiveSha512, + closureSha256: distribution.closureSha256, + entries: closure.entries, + }; } -/** Strictly inspect the known two-file ZIP before writing any vendor content. */ -export function antigravityArchiveEntries(archive) { - const invalid = () => { throw new Error("Antigravity archive contains unsafe or unsupported ZIP entries"); }; - if (!Buffer.isBuffer(archive) || archive.length < 22 || archive.length > MAX_ARCHIVE_BYTES) invalid(); - // The pinned vendor archive has no comment, ZIP64, spanning, or data descriptors. - const end = archive.length - 22; - if (archive.readUInt32LE(end) !== 0x06054b50 || archive.readUInt16LE(end + 4) || archive.readUInt16LE(end + 6) || archive.readUInt16LE(end + 20)) invalid(); - const count = archive.readUInt16LE(end + 10); - const centralSize = archive.readUInt32LE(end + 12); - const centralOffset = archive.readUInt32LE(end + 16); - if (count !== 2 || archive.readUInt16LE(end + 8) !== count || centralOffset + centralSize !== end) invalid(); - let cursor = centralOffset; - const entries = []; - const spans = []; - let bytes = 0; - for (let index = 0; index < count; index++) { - if (cursor + 46 > end || archive.readUInt32LE(cursor) !== 0x02014b50) invalid(); - const flags = archive.readUInt16LE(cursor + 8); - const method = archive.readUInt16LE(cursor + 10); - const compressedSize = archive.readUInt32LE(cursor + 20); - const size = archive.readUInt32LE(cursor + 24); - const nameLength = archive.readUInt16LE(cursor + 28); - const extraLength = archive.readUInt16LE(cursor + 30); - const commentLength = archive.readUInt16LE(cursor + 32); - const mode = archive.readUInt32LE(cursor + 38) >>> 16; - const local = archive.readUInt32LE(cursor + 42); - const next = cursor + 46 + nameLength + extraLength + commentLength; - if (next > end || (flags & ~0x800) || ![0, 8].includes(method) || archive.readUInt16LE(cursor + 34) || (mode & 0o170000) !== 0o100000 || !(mode & 0o111)) invalid(); - const nameBytes = archive.subarray(cursor + 46, cursor + 46 + nameLength); - const path = nameBytes.toString("utf8"); - if (!RUNTIME_FILES.includes(path) || !Buffer.from(path).equals(nameBytes) || entries.some(entry => entry.path === path)) invalid(); - if (local + 30 > centralOffset || archive.readUInt32LE(local) !== 0x04034b50 || archive.readUInt16LE(local + 6) !== flags || archive.readUInt16LE(local + 8) !== method || archive.readUInt32LE(local + 14) !== archive.readUInt32LE(cursor + 16) || archive.readUInt32LE(local + 18) !== compressedSize || archive.readUInt32LE(local + 22) !== size) invalid(); - const localNameLength = archive.readUInt16LE(local + 26); - const start = local + 30 + localNameLength + archive.readUInt16LE(local + 28); - const finish = start + compressedSize; - if (finish > centralOffset || !archive.subarray(local + 30, local + 30 + localNameLength).equals(nameBytes) || spans.some(([a, b]) => local < b && finish > a)) invalid(); - bytes += size; - if (!size || bytes > MAX_TREE_BYTES || (method === 0 && size !== compressedSize)) invalid(); - entries.push({ path, method, size, start, finish }); - spans.push([local, finish]); - cursor = next; - } - if (cursor !== end || RUNTIME_FILES.some(path => !entries.some(entry => entry.path === path))) invalid(); - return entries; +/** + * Strictly inspect Google's single-member tar: one regular executable named + * `antigravity`, no links, no other members, and only zero blocks after it. + */ +export function antigravityArchiveExecutable(archive, member = ARCHIVE_MEMBER) { + const invalid = () => { throw new Error("Antigravity archive contains unsafe or unsupported tar entries"); }; + if (!Buffer.isBuffer(archive) || archive.length < 512 + 1024 || archive.length % 512) invalid(); + const header = archive.subarray(0, 512); + const nameEnd = header.indexOf(0); + if (nameEnd < 1 || nameEnd > 100 || header.subarray(0, nameEnd).toString("utf8") !== member || header.subarray(nameEnd, 100).some(byte => byte !== 0)) invalid(); + let sum = 0; + for (let index = 0; index < 512; index++) sum += index >= 148 && index < 156 ? 0x20 : header[index]; + const mode = octal(header.subarray(100, 108)); + const magic = header.subarray(257, 265).toString("latin1"); + if (octal(header.subarray(148, 156)) !== sum || ![0x30, 0].includes(header[156]) || header.subarray(157, 257).some(byte => byte !== 0) + || (magic !== "ustar \0" && magic !== "ustar\x0000") || mode < 0 || (mode & 0o7000) || (mode & 0o111) !== 0o111) invalid(); + const size = octal(header.subarray(124, 136)); + if (size < 1 || size > MAX_TREE_BYTES) invalid(); + const end = 512 + Math.ceil(size / 512) * 512; + if (archive.length < end + 1024 || archive.subarray(512 + size).some(byte => byte !== 0)) invalid(); + return archive.subarray(512, 512 + size); } /** Explicit setup only: no vendor installer, ambient binary, or npm lifecycle. */ @@ -235,40 +238,40 @@ export async function materializePinnedAntigravityDistribution(options = {}) { if (options.archivePath) { archive = await readOwnedFile(options.archivePath, MAX_ARCHIVE_BYTES); } else { - const response = await fetch(distribution.url, { redirect: "error", signal: AbortSignal.timeout(180_000) }); + const response = await (options.fetch ?? fetch)(distribution.url, { redirect: "error", signal: AbortSignal.timeout(300_000) }); if (!response.ok || !response.body) throw new Error(`Antigravity archive download failed: ${response.status}`); const chunks = []; let length = 0; for await (const chunk of response.body) { length += chunk.length; - if (length > MAX_ARCHIVE_BYTES) throw new Error("Antigravity archive download exceeds size limit"); + if (length > distribution.archiveSize) throw new Error("Antigravity archive download exceeds size limit"); chunks.push(chunk); } archive = Buffer.concat(chunks); } - if (digest(archive) !== distribution.archiveSha256) throw new Error("Antigravity archive digest mismatch"); - const entries = antigravityArchiveEntries(archive); - const unpacked = join(temporary, "vendor"); - await mkdir(unpacked, { mode: 0o700 }); - for (const entry of entries) { - const compressed = archive.subarray(entry.start, entry.finish); - const content = entry.method === 0 ? compressed : inflateRawSync(compressed, { maxOutputLength: entry.size }); - if (content.length !== entry.size) throw new Error("Antigravity archive entry size mismatch"); - await writeFile(join(unpacked, entry.path), content, { mode: 0o500, flag: "wx" }); + if (archive.length !== distribution.archiveSize || digest(archive, "sha256") !== distribution.archiveSha256 || digest(archive, "sha512") !== distribution.archiveSha512) { + throw new Error("Antigravity archive digest mismatch"); } - archive = undefined; // Release the download before the large server is patched. - const vendorClosure = await antigravityDistributionClosure(unpacked); - if (vendorClosure.sha256 !== distribution.vendorClosureSha256) throw new Error("Antigravity vendor execution closure digest mismatch"); - const patched = join(temporary, "runtime"); - const patch = await patchAntigravityRuntime({ source: unpacked, destination: patched, target: `${distribution.platform}-${distribution.architecture}`, vendorEntries: distribution.vendorEntries }); - if (patch.version !== distribution.patchVersion || patch.admissionSourceSha256 !== distribution.admissionSourceSha256) throw new Error("Antigravity native admission patch identity mismatch"); - const closure = await antigravityDistributionClosure(patched); + let tar; + try { tar = gunzipSync(archive, { maxOutputLength: distribution.entries[0].size + 64 * 1024 }); } + catch { throw new Error("Antigravity archive contains unsafe or unsupported tar entries"); } + archive = undefined; + const content = antigravityArchiveExecutable(tar, distribution.archiveMember); + if (content.length !== distribution.entries[0].size + || digest(content, "sha256") !== distribution.entries[0].sha256 + || digest(content, "sha512") !== distribution.executableSha512) { + throw new Error("Antigravity full execution closure digest mismatch"); + } + const staged = join(temporary, "runtime"); + await mkdir(staged, { mode: 0o700 }); + await writeFile(join(staged, EXECUTABLE), content, { mode: 0o500, flag: "wx" }); + await chmod(join(staged, EXECUTABLE), 0o500); + const closure = await antigravityDistributionClosure(staged); if (closure.sha256 !== distribution.closureSha256) throw new Error("Antigravity full execution closure digest mismatch"); - await writeFile(join(patched, ANTIGRAVITY_TREE_MANIFEST), `${JSON.stringify(closureRecord(distribution, closure))}\n`, { mode: 0o400, flag: "wx" }); - for (const entry of closure.entries) await chmod(join(patched, entry.path), 0o500); + await writeFile(join(staged, ANTIGRAVITY_TREE_MANIFEST), `${JSON.stringify(closureRecord(distribution, closure))}\n`, { mode: 0o400, flag: "wx" }); const currentParent = await ownedDirectory(dirname(destination)); if (currentParent.stat.dev !== parent.stat.dev || currentParent.stat.ino !== parent.stat.ino) throw new Error("Antigravity cache parent changed before publication"); - await rename(patched, destination); + await rename(staged, destination); return { ...distribution, destination, executable: join(destination, distribution.executable) }; } finally { await rm(temporary, { recursive: true, force: true }); } } diff --git a/packages/paperclip-runner/scripts/materialize-antigravity-distribution.test.mjs b/packages/paperclip-runner/scripts/materialize-antigravity-distribution.test.mjs index 3670063b355..d24dde3eac9 100644 --- a/packages/paperclip-runner/scripts/materialize-antigravity-distribution.test.mjs +++ b/packages/paperclip-runner/scripts/materialize-antigravity-distribution.test.mjs @@ -5,143 +5,116 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { test } from "node:test"; import { pathToFileURL } from "node:url"; -import { antigravityArchiveEntries, antigravityDistribution } from "./materialize-antigravity-distribution.mjs"; +import { gzipSync } from "node:zlib"; +import { antigravityArchiveExecutable, antigravityDistribution } from "./materialize-antigravity-distribution.mjs"; -const hash = bytes => createHash("sha256").update(bytes).digest("hex"); -const files = [ - { path: "agy_acp_server.par", content: Buffer.from("native ACP server fixture\n") }, - { path: "localharness_external", content: Buffer.from("owned native child fixture\n") }, -]; +const sha256 = bytes => createHash("sha256").update(bytes).digest("hex"); +const sha512 = bytes => createHash("sha512").update(bytes).digest("hex"); +const executable = Buffer.from("#!/bin/sh\necho antigravity unified fixture\n"); -// A minimal stored ZIP fixture exercises the real inspector and filesystem. -// Integrity comes from the checked-in archive and complete-file SHA-256 pins. -function zip(entries = files) { - const locals = []; - const centrals = []; - let offset = 0; - for (const entry of entries) { - const name = Buffer.from(entry.path); - const content = entry.content ?? Buffer.from("fixture"); - const local = Buffer.alloc(30); - local.writeUInt32LE(0x04034b50); - local.writeUInt16LE(20, 4); - local.writeUInt32LE(content.length, 18); - local.writeUInt32LE(content.length, 22); - local.writeUInt16LE(name.length, 26); - const central = Buffer.alloc(46); - central.writeUInt32LE(0x02014b50); - central.writeUInt16LE(0x314, 4); - central.writeUInt16LE(20, 6); - central.writeUInt32LE(content.length, 20); - central.writeUInt32LE(content.length, 24); - central.writeUInt16LE(name.length, 28); - central.writeUInt32LE(((entry.mode ?? 0o100755) << 16) >>> 0, 38); - central.writeUInt32LE(offset, 42); - locals.push(local, name, content); - centrals.push(central, name); - offset += local.length + name.length + content.length; - } - const central = Buffer.concat(centrals); - const end = Buffer.alloc(22); - end.writeUInt32LE(0x06054b50); - end.writeUInt16LE(entries.length, 8); - end.writeUInt16LE(entries.length, 10); - end.writeUInt32LE(central.length, 12); - end.writeUInt32LE(offset, 16); - return Buffer.concat([...locals, central, end]); +function tar({ name = "antigravity", content = executable, mode = 0o755, type = "0", members = [], trailer = Buffer.alloc(1024), magic = "ustar \0" } = {}) { + const block = (memberName, bytes, memberType, memberMode) => { + const header = Buffer.alloc(512); + header.write(memberName, 0, "utf8"); + header.write(`${memberMode.toString(8).padStart(7, "0")}\0`, 100); + header.write("0000000\0", 108); + header.write("0000000\0", 116); + header.write(`${bytes.length.toString(8).padStart(11, "0")}\0`, 124); + header.write("15147300000\0", 136); + header.write(" ", 148); + header.write(memberType, 156); + header.write(magic, 257, "latin1"); + let sum = 0; + for (const byte of header) sum += byte; + header.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148); + const padding = Buffer.alloc((512 - (bytes.length % 512)) % 512); + return Buffer.concat([header, bytes, padding]); + }; + return Buffer.concat([block(name, content, type, mode), ...members.map(member => block(member.name, member.content, member.type ?? "0", member.mode ?? 0o755)), trailer]); } +const tarGz = options => gzipSync(tar(options)); -async function fixture(t, { expectedFiles = files, expectedVendorFiles = files, archive = zip(), patchSuffix = "", baseDirectory = tmpdir(), changeParentDuringPatch = false, platform = "darwin", architecture = "arm64" } = {}) { +async function fixture(t, { expectedContent = executable, archive = tarGz(), baseDirectory = tmpdir(), platform = "darwin", architecture = "arm64" } = {}) { const target = `${platform}-${architecture}`; const root = await realpath(await mkdtemp(join(baseDirectory, "paperclip-antigravity-provision-test-"))); t.after(() => rm(root, { recursive: true, force: true })); const scripts = join(root, "scripts"); await mkdir(scripts); - for (const name of ["materialize-antigravity-distribution.mjs", "antigravity-provisioner-layout.mjs", "provision-antigravity.mjs"]) await copyFile(new URL(name, import.meta.url), join(scripts, name)); - const admissionSource = "# trusted test admission source\n"; - const admissionSourceSha256 = hash(admissionSource); - await writeFile(join(scripts, "patch-antigravity-runtime.admission.py"), admissionSource); - await writeFile(join(scripts, "patch-antigravity-runtime.mjs"), ` -import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'; -import { join } from 'node:path'; -export const ANTIGRAVITY_PATCH_VERSION='1.5.2-paperclip.2'; -export async function patchAntigravityRuntime({source,destination,target,vendorEntries}) { - await writeFile(${JSON.stringify(join(root, "patch.called"))},JSON.stringify({target,vendorEntries})); - await mkdir(destination,{mode:0o700}); - for(const name of ['agy_acp_server.par','localharness_external']) { - const content=await readFile(join(source,name)); - await writeFile(join(destination,name),name==='agy_acp_server.par'?Buffer.concat([content,Buffer.from(${JSON.stringify(patchSuffix)})]):content,{mode:0o500}); - } - ${changeParentDuringPatch ? `await chmod(${JSON.stringify(join(root, `home/.paperclip/runtimes/antigravity/${target}`))},0o777);` : ""} - return {version:ANTIGRAVITY_PATCH_VERSION,admissionSourceSha256:${JSON.stringify(admissionSourceSha256)}}; -} -`); - const entries = expectedFiles.map(entry => ({ path: entry.path, sha256: hash(entry.content), size: entry.content.length, executable: true })); - const closureSha256 = hash(JSON.stringify(entries)); - const vendorEntries = expectedVendorFiles.map(entry => ({ path: entry.path, sha256: hash(entry.content), size: entry.content.length, executable: true })); - // The code is copied into an isolated package so its normal fixed manifest - // read uses a tiny trusted fixture. Production has no manifest-path override. + for (const name of ["materialize-antigravity-distribution.mjs", "antigravity-provisioner-layout.mjs", "provision-antigravity.mjs"]) { + await copyFile(new URL(name, import.meta.url), join(scripts, name)); + } + const entries = [{ path: "agy", sha256: sha256(expectedContent), size: expectedContent.length, executable: true }]; + const closureSha256 = sha256(JSON.stringify(entries)); await writeFile(join(root, "antigravity-distributions.json"), JSON.stringify({ - schema: "paperclip.antigravity_distribution.v1", version: "1.5.2", - platforms: { [target]: { - url: `https://dl.google.com/agy-extensions/releases/${platform === "darwin" ? "macos" : "linux"}/fixture.zip`, - archiveSha256: hash(archive), closureSha256, vendorEntries, vendorClosureSha256: hash(JSON.stringify(vendorEntries)), patchVersion: "1.5.2-paperclip.2", admissionSourceSha256, provisioning: "verified-closure", - executable: "agy_acp_server.par", args: platform === "linux" ? ["--uid="] : [], entries, - } }, + schema: "paperclip.antigravity_distribution.v1", + version: "1.5.19", + build: "1.5.19-4821414830800896", + environment: { AGY_CLI_DISABLE_AUTO_UPDATE: "1", AGY_CLI_FORCE_FILE_TOKEN_STORAGE: "1" }, + platforms: { + [target]: { + url: `https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/${target}/fixture.tar.gz`, + archiveFormat: "tar.gz", + archiveSize: archive.length, + archiveSha256: sha256(archive), + archiveSha512: sha512(archive), + archiveMember: "antigravity", + executable: "agy", + executableSha512: sha512(expectedContent), + closureSha256, + provisioning: "verified-closure", + args: ["acp"], + entries, + }, + }, })); - const archivePath = join(root, "fixture.zip"); + const archivePath = join(root, "fixture.tar.gz"); await writeFile(archivePath, archive); const api = await import(pathToFileURL(join(scripts, "materialize-antigravity-distribution.mjs"))); const provisioner = await import(pathToFileURL(join(scripts, "provision-antigravity.mjs"))); const home = join(root, "home"); const destination = join(home, ".paperclip/runtimes/antigravity", target, closureSha256); const options = { platform, architecture, archivePath, destination }; - const provision = () => provisioner.provisionAntigravityRuntime({ ...options, home, moduleUrl: "file:///consumer/node_modules/@paperclipai/paperclip-runner/dist/cli/provision-antigravity.cjs" }); + const provision = () => provisioner.provisionAntigravityRuntime({ + ...options, + home, + moduleUrl: "file:///consumer/node_modules/@paperclipai/paperclip-runner/dist/cli/provision-antigravity.cjs", + }); return { root, destination, options, api, provision, distribution: await api.antigravityDistribution(platform, architecture) }; } -test("macOS ARM and both Linux closures are pinned; macOS Intel remains inventory-only", async () => { - for (const [platform, architecture] of [["darwin", "arm64"], ["linux", "x64"], ["linux", "arm64"]]) { +test("all four macOS and Linux 1.5.19 unified agy closures are pinned", async () => { + for (const [platform, architecture] of [["darwin", "arm64"], ["darwin", "x64"], ["linux", "x64"], ["linux", "arm64"]]) { const pin = await antigravityDistribution(platform, architecture); - assert.equal(pin.version, "1.5.2"); - assert.equal(pin.patchVersion, "1.5.2-paperclip.2"); - assert.deepEqual(pin.entries.map(entry => entry.path), files.map(entry => entry.path)); - assert.deepEqual(pin.vendorEntries.map(entry => entry.path), files.map(entry => entry.path)); - assert.equal(hash(JSON.stringify(pin.entries)), pin.closureSha256); - assert.equal(hash(JSON.stringify(pin.vendorEntries)), pin.vendorClosureSha256); - assert.equal(pin.entries[1].sha256, pin.vendorEntries[1].sha256, "the helper ships unmodified"); - assert.notEqual(pin.entries[0].sha256, pin.vendorEntries[0].sha256, "the server carries the owned patch"); - // Linux keeps the exact file size; macOS replaces the vendor signature with an ad-hoc one. - if (platform === "linux") assert.equal(pin.entries[0].size, pin.vendorEntries[0].size, "the patch keeps the embedded archive size"); - assert.deepEqual(pin.args, platform === "linux" ? ["--uid="] : []); + assert.equal(pin.version, "1.5.19"); + assert.equal(pin.build, "1.5.19-4821414830800896"); + assert.equal(pin.executable, "agy"); + assert.deepEqual(pin.args, ["acp"]); + assert.deepEqual(pin.entries.map(entry => entry.path), ["agy"]); + assert.equal(sha256(JSON.stringify(pin.entries)), pin.closureSha256); } - await assert.rejects(antigravityDistribution("darwin", "x64"), /inventory-only/); await assert.rejects(antigravityDistribution("win32", "x64"), /no pinned distribution/); }); -test("ZIP inspection rejects traversal, absolute names, duplicates, links and partial closure", () => { - assert.deepEqual(antigravityArchiveEntries(zip()).map(entry => entry.path), files.map(entry => entry.path)); - for (const entries of [ - [{ ...files[0], path: "../agy_acp_server.par" }, files[1]], - [{ ...files[0], path: "/agy_acp_server.par" }, files[1]], - [{ ...files[0], path: "dir\\agy_acp_server.par" }, files[1]], - [files[0], files[0]], - [{ ...files[0], mode: 0o120755 }, files[1]], - [{ ...files[0], mode: 0o060755 }, files[1]], - [files[0]], - ]) assert.throws(() => antigravityArchiveEntries(zip(entries)), /unsafe or unsupported ZIP/); -}); - -test("ZIP inspection rejects disagreeing headers and overlapping payloads", () => { - const disagreeing = zip(); - disagreeing.writeUInt16LE(8, 8); - assert.throws(() => antigravityArchiveEntries(disagreeing), /unsafe or unsupported ZIP/); - const overlapping = zip(); - const end = overlapping.length - 22; - const central = overlapping.readUInt32LE(end + 16); - const secondCentral = central + 46 + Buffer.byteLength(files[0].path); - overlapping.writeUInt32LE(0, secondCentral + 42); - assert.throws(() => antigravityArchiveEntries(overlapping), /unsafe or unsupported ZIP/); +test("tar inspection rejects traversal, links, extra members, bad mode, and corrupt checksums", () => { + assert.deepEqual(antigravityArchiveExecutable(tar()), executable); + for (const bad of [ + tar({ name: "../antigravity" }), + tar({ name: "agy" }), + tar({ type: "2" }), + tar({ type: "5" }), + tar({ mode: 0o4755 }), + tar({ mode: 0o644 }), + tar({ magic: "badmg\0" }), + tar({ members: [{ name: "extra", content: Buffer.from("x") }] }), + tar({ trailer: Buffer.concat([Buffer.alloc(1023), Buffer.from([1])]) }), + tar({ trailer: Buffer.alloc(0) }), + tar().subarray(0, 700), + ]) { + assert.throws(() => antigravityArchiveExecutable(bad), /unsafe or unsupported tar/); + } + const corrupted = tar(); + corrupted[0] ^= 1; + assert.throws(() => antigravityArchiveExecutable(corrupted), /unsafe or unsupported tar/); }); test("a corrupted archive never installs and its temporary directory is removed", async t => { @@ -152,67 +125,35 @@ test("a corrupted archive never installs and its temporary directory is removed" assert.deepEqual(await readdir(join(destination, "..")), []); }); -test("installation preserves and verifies the complete two-binary closure", async t => { +test("installation preserves and verifies the single-binary agy closure", async t => { const { api, options, destination, distribution } = await fixture(t); const result = await api.materializePinnedAntigravityDistribution(options); - assert.equal(result.executable, join(destination, files[0].path)); + assert.equal(result.executable, join(destination, "agy")); assert.equal(result.closureSha256, distribution.closureSha256); - for (const file of files) { - assert.deepEqual(await readFile(join(destination, file.path)), file.content); - assert.equal((await lstat(join(destination, file.path))).mode & 0o777, 0o500); - } + assert.deepEqual(await readFile(join(destination, "agy")), executable); + assert.equal((await lstat(join(destination, "agy"))).mode & 0o777, 0o500); assert.equal((await api.verifyAntigravityDistribution(destination, distribution)).sha256, distribution.closureSha256); assert.deepEqual(await readdir(join(destination, "..")), [distribution.closureSha256]); await assert.rejects(api.materializePinnedAntigravityDistribution(options), /already exists/); }); test("a failed full-closure check leaves no partial installation", async t => { - const expectedFiles = files.map(file => ({ ...file, content: Buffer.from(`wrong expected ${file.path}`) })); - const { api, options, destination } = await fixture(t, { expectedFiles }); + const { api, options, destination } = await fixture(t, { expectedContent: Buffer.from("different binary\n") }); await assert.rejects(api.materializePinnedAntigravityDistribution(options), /full execution closure digest mismatch/); await assert.rejects(lstat(destination), { code: "ENOENT" }); assert.deepEqual(await readdir(join(destination, "..")), []); }); -test("verified vendor bytes are patched and only the separately pinned final closure is installed", async t => { - const patchSuffix = "\nowned native admission patch\n"; - const expectedFiles = files.map((file, index) => ({ ...file, content: index === 0 ? Buffer.concat([file.content, Buffer.from(patchSuffix)]) : file.content })); - const { api, options, destination, root, distribution } = await fixture(t, { expectedFiles, patchSuffix }); - await api.materializePinnedAntigravityDistribution(options); - assert.deepEqual(JSON.parse(await readFile(join(root, "patch.called"), "utf8")), { target: "darwin-arm64", vendorEntries: distribution.vendorEntries }); - assert.notEqual(distribution.vendorClosureSha256, distribution.closureSha256); - assert.deepEqual(await readFile(join(destination, files[0].path)), expectedFiles[0].content); - assert.deepEqual(await readFile(join(destination, files[1].path)), files[1].content); - await api.verifyAntigravityDistribution(destination, distribution); -}); - -test("vendor closure mismatch stops before the owned patch executes", async t => { - const expectedVendorFiles = files.map(file => ({ ...file, content: Buffer.from(`wrong vendor ${file.path}`) })); - const { api, options, root, destination } = await fixture(t, { expectedVendorFiles }); - await assert.rejects(api.materializePinnedAntigravityDistribution(options), /vendor execution closure digest mismatch/); - await assert.rejects(readFile(join(root, "patch.called")), { code: "ENOENT" }); - await assert.rejects(lstat(destination), { code: "ENOENT" }); - assert.deepEqual(await readdir(join(destination, "..")), []); -}); - -test("changed admission patch source is rejected before extraction or native execution", async t => { - const { api, options, root, destination } = await fixture(t); - await writeFile(join(root, "scripts/patch-antigravity-runtime.admission.py"), "# changed admission source\n"); - await assert.rejects(api.materializePinnedAntigravityDistribution(options), /patch source digest mismatch/); - await assert.rejects(lstat(destination), { code: "ENOENT" }); - await assert.rejects(readFile(join(root, "patch.called")), { code: "ENOENT" }); -}); - test("repeated setup verifies installed bytes and refuses corruption without download or replacement", async t => { const { provision, destination, options } = await fixture(t); await provision(); await rm(options.archivePath); await provision(); - const binary = join(destination, files[1].path); + const binary = join(destination, "agy"); await chmod(binary, 0o700); - await writeFile(binary, "corrupted native child"); + await writeFile(binary, "corrupted native binary"); await assert.rejects(provision(), /full execution closure digest mismatch/); - assert.equal(await readFile(binary, "utf8"), "corrupted native child"); + assert.equal(await readFile(binary, "utf8"), "corrupted native binary"); }); test("rewriting the cached record or passing altered pins cannot authorize changed bytes", async t => { @@ -225,11 +166,11 @@ test("rewriting the cached record or passing altered pins cannot authorize chang await assert.rejects(api.verifyAntigravityDistribution(destination, { ...distribution, closureSha256: "a".repeat(64) }), /checked-in distribution pins/); }); -test("cached links, hardlinks, extra files and missing children fail closed", async t => { +test("cached links, hardlinks, extra files and missing executable fail closed", async t => { for (const kind of ["symlink", "hardlink", "extra", "missing", "record-link"]) { const current = await fixture(t); await current.provision(); - const child = join(current.destination, files[1].path); + const binary = join(current.destination, "agy"); if (kind === "extra") await writeFile(join(current.destination, "unexpected-native-child"), "unexpected"); else if (kind === "record-link") { const record = join(current.destination, current.api.ANTIGRAVITY_TREE_MANIFEST); @@ -238,20 +179,20 @@ test("cached links, hardlinks, extra files and missing children fail closed", as await rm(record); await symlink(target, record); } else { - const target = join(current.root, "native-child-copy"); - await copyFile(child, target); - await rm(child); - if (kind === "symlink") await symlink(target, child); - if (kind === "hardlink") await link(target, child); + const target = join(current.root, "native-binary-copy"); + await copyFile(binary, target); + await rm(binary); + if (kind === "symlink") await symlink(target, binary); + if (kind === "hardlink") await link(target, binary); } - await assert.rejects(current.provision(), /both native binaries|links or special files/); + await assert.rejects(current.provision(), /pinned native executable|links or special files/); } }); test("cached assets with shared write access and linked runtime roots fail closed", async t => { const { provision, api, destination, distribution, root } = await fixture(t); await provision(); - const binary = join(destination, files[1].path); + const binary = join(destination, "agy"); await chmod(binary, 0o777); await assert.rejects(provision(), /unsafe file permissions/); await chmod(binary, 0o500); @@ -272,25 +213,6 @@ test("a private cached closure is rejected when another user could replace its p finally { await chmod(parent, 0o700); } }); -test("publication refuses a replaceable cache parent before patching or creating a temporary installation", async t => { - const { api, options, destination, root } = await fixture(t); - const parent = join(destination, ".."); - await mkdir(parent, { recursive: true, mode: 0o700 }); - await chmod(parent, 0o777); - try { - await assert.rejects(api.materializePinnedAntigravityDistribution(options), /ancestor.*write|unsafe.*ancestor/); - await assert.rejects(readFile(join(root, "patch.called")), { code: "ENOENT" }); - assert.deepEqual(await readdir(parent), []); - } finally { await chmod(parent, 0o700); } -}); - -test("package pin sources beneath a replaceable ancestor cannot authorize installation", async t => { - const { api, options, root } = await fixture(t); - await chmod(root, 0o777); - try { await assert.rejects(api.materializePinnedAntigravityDistribution(options), /ancestor.*write|unsafe.*ancestor/); } - finally { await chmod(root, 0o700); } -}); - test("canonical parent aliases keep a private owned installation valid", async t => { const { api, options, distribution, root } = await fixture(t); const home = join(root, "private-home"); @@ -298,59 +220,7 @@ test("canonical parent aliases keep a private owned installation valid", async t const alias = join(root, "home-alias"); await symlink(home, alias); const destination = join(alias, "cache", distribution.closureSha256); - await api.materializePinnedAntigravityDistribution({ ...options, destination }); - assert.equal((await api.verifyAntigravityDistribution(destination, distribution)).sha256, distribution.closureSha256); -}); - -test("a root-owned sticky temporary ancestor protects the private installation", async t => { - const temporary = await realpath("/tmp"); - const stat = await lstat(temporary); - if (stat.uid !== 0 || !(stat.mode & 0o1000)) return t.skip("requires the host's root-owned sticky temporary directory"); - const { provision, api, destination, distribution } = await fixture(t, { baseDirectory: "/tmp" }); - await provision(); - assert.equal((await api.verifyAntigravityDistribution(destination, distribution)).sha256, distribution.closureSha256); -}); - -test("source and cached ownership are checked for the current execution principal", async t => { - const { api, provision, destination } = await fixture(t); - await provision(); - const getuid = process.getuid; - if (!getuid || getuid() === 0) return t.skip("requires a non-root principal to model foreign ownership without changing filesystem privileges"); - // Keep the real kernel metadata; model a different verifier principal rather - // than chowning files or running another user's process during the test. - process.getuid = () => getuid() + 1; - try { - await assert.rejects(api.antigravityDistributionClosure(destination), /untrusted filesystem owner/); - await assert.rejects(api.antigravityDistribution("darwin", "arm64"), /untrusted filesystem owner/); - } finally { process.getuid = getuid; } -}); - -test("a parent made replaceable while patching cannot receive a published runtime", async t => { - const { api, options, destination } = await fixture(t, { changeParentDuringPatch: true }); - try { - await assert.rejects(api.materializePinnedAntigravityDistribution(options), /ancestor.*write|unsafe.*ancestor/); - await assert.rejects(lstat(destination), { code: "ENOENT" }); - assert.deepEqual(await readdir(join(destination, "..")), []); - } finally { await chmod(join(destination, ".."), 0o700); } -}); - -test("a Linux closure is patched for its own target and verified like macOS", async t => { - for (const architecture of ["x64", "arm64"]) { - const patchSuffix = "\nowned native admission patch\n"; - const expectedFiles = files.map((file, index) => ({ ...file, content: index === 0 ? Buffer.concat([file.content, Buffer.from(patchSuffix)]) : file.content })); - const { api, options, destination, root, distribution, provision } = await fixture(t, { expectedFiles, patchSuffix, platform: "linux", architecture }); - assert.equal(destination.split("/").at(-2), `linux-${architecture}`); - await provision(); - assert.deepEqual(JSON.parse(await readFile(join(root, "patch.called"), "utf8")), { target: `linux-${architecture}`, vendorEntries: distribution.vendorEntries }); - assert.equal((await api.verifyAntigravityDistribution(destination, distribution)).sha256, distribution.closureSha256); - await rm(options.archivePath); - await provision(); - const helper = join(destination, files[1].path); - await chmod(helper, 0o700); - await writeFile(helper, "tampered native child"); - await chmod(helper, 0o500); - await assert.rejects(provision(), /full execution closure digest mismatch/); - await rm(helper); - await assert.rejects(provision(), /both native binaries/); - } + const result = await api.materializePinnedAntigravityDistribution({ ...options, destination }); + assert.equal(result.destination, join(home, "cache", distribution.closureSha256)); + await api.verifyAntigravityDistribution(result.destination, distribution); }); diff --git a/packages/paperclip-runner/scripts/probe-antigravity-metadata.mjs b/packages/paperclip-runner/scripts/probe-antigravity-metadata.mjs index e6c1aae1521..9da794cf85c 100644 --- a/packages/paperclip-runner/scripts/probe-antigravity-metadata.mjs +++ b/packages/paperclip-runner/scripts/probe-antigravity-metadata.mjs @@ -24,11 +24,11 @@ function probeLimits(options) { } /** No ambient credentials, proxy, hooks, Python, Node, or configuration variables. */ -export function antigravityMetadataEnvironment(root, runtimeDirectory) { +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_ACP_FORCE_FILE_STORAGE: "1", ANTIGRAVITY_HARNESS_PATH: join(runtimeDirectory, "localharness_external"), + 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", }; } @@ -155,29 +155,28 @@ export async function stopAntigravityMetadataChild(child, { eofTimeoutMs = 500, } function safeMetadata(result, distribution) { - if (result.protocolVersion !== 1 || !plainObject(result.agentInfo) || result.agentInfo.name !== "antigravity-acp") throw new Error("antigravity_initialize_identity_mismatch"); + 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; - if (distribution.patchVersion && capabilities._meta?.antigravity?.paperclipAdmission !== 1) throw new Error("antigravity_native_admission_patch_not_advertised"); 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, patchVersion: distribution.patchVersion, - platform: distribution.platform, architecture: distribution.architecture, archiveSha256: distribution.archiveSha256, vendorClosureSha256: distribution.vendorClosureSha256, - closureSha256: distribution.closureSha256, admissionSourceSha256: distribution.admissionSourceSha256, - protocolVersion: 1, agentInfo: { name: "antigravity-acp", title: "Google Antigravity", version: distribution.version }, + 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"), paperclipAdmission: 1 }, + 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: "pending", + inferenceVerified: false, qualification: "qualified", }; } @@ -192,7 +191,7 @@ export async function probeAntigravityMetadata(options = {}) { 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, { cwd: root, env, stdio: "pipe", detached: true }); + 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) { diff --git a/packages/paperclip-runner/scripts/probe-antigravity-metadata.test.mjs b/packages/paperclip-runner/scripts/probe-antigravity-metadata.test.mjs index 9913bbab8bb..f4b65061abd 100644 --- a/packages/paperclip-runner/scripts/probe-antigravity-metadata.test.mjs +++ b/packages/paperclip-runner/scripts/probe-antigravity-metadata.test.mjs @@ -9,25 +9,32 @@ import { test } from "node:test"; import { pathToFileURL } from "node:url"; import { antigravityMetadataEnvironment, createAntigravityMetadataRpc } from "./probe-antigravity-metadata.mjs"; -const hash = bytes => createHash("sha256").update(bytes).digest("hex"); +const sha256 = bytes => createHash("sha256").update(bytes).digest("hex"); +const sha512 = bytes => createHash("sha512").update(bytes).digest("hex"); const response = { - protocolVersion: 1, agentInfo: { name: "antigravity-acp", title: "private-provider-text 🛰", version: "1.5.2" }, - agentCapabilities: { loadSession: true, promptCapabilities: { image: true }, mcpCapabilities: { http: true }, sessionCapabilities: { list: {} }, auth: { logout: {} }, _meta: { antigravity: { tier: true, systemPrompt: { append: true }, paperclipAdmission: 1 } } }, - authMethods: [{ id: "oauth-personal", name: "private-provider-text" }, { id: "untrusted-auth-method", name: "private-provider-text" }], + protocolVersion: 1, + agentInfo: { name: "Antigravity ACP Server", title: "private-provider-text 🛰", version: "1.5.19" }, + agentCapabilities: { + loadSession: true, + promptCapabilities: { image: true }, + mcpCapabilities: { http: true }, + sessionCapabilities: { list: {}, resume: {} }, + auth: { logout: {} }, + _meta: { antigravity: { tier: true, systemPrompt: { append: true } } }, + }, + authMethods: [{ id: "oauth-personal", name: "private-provider-text" }, { id: "gemini-api-key", name: "private-provider-text" }, { id: "untrusted-auth-method", name: "private-provider-text" }], }; async function fixture(t, behavior = "success", { platform = "darwin", architecture = "arm64" } = {}) { const target = `${platform}-${architecture}`; - const args = platform === "linux" ? ["--uid="] : []; + const args = ["acp"]; const root = await mkdtemp(join(tmpdir(), "paperclip-antigravity-probe-test-")); t.after(() => rm(root, { recursive: true, force: true })); const scripts = join(root, "scripts"); await mkdir(scripts); - for (const name of ["materialize-antigravity-distribution.mjs", "antigravity-provisioner-layout.mjs", "probe-antigravity-metadata.mjs"]) await copyFile(new URL(name, import.meta.url), join(scripts, name)); - const admissionSource = "# trusted test admission source\n"; - const admissionSourceSha256 = hash(admissionSource); - await writeFile(join(scripts, "patch-antigravity-runtime.admission.py"), admissionSource); - await writeFile(join(scripts, "patch-antigravity-runtime.mjs"), "export const ANTIGRAVITY_PATCH_VERSION='1.5.2-paperclip.2'; export function patchAntigravityRuntime(){throw new Error('Metadata must never patch or install');}"); + for (const name of ["materialize-antigravity-distribution.mjs", "antigravity-provisioner-layout.mjs", "probe-antigravity-metadata.mjs"]) { + await copyFile(new URL(name, import.meta.url), join(scripts, name)); + } const auditPath = join(root, "audit.json"); const script = `#!${process.execPath} const { writeFileSync } = require('node:fs'); @@ -51,7 +58,6 @@ process.stdin.on('data',chunk=>{ if(behavior==='wrong-identity')result.agentInfo.name='another-harness'; if(behavior==='wrong-protocol')result.protocolVersion=2; if(behavior==='bad-capabilities')result.agentCapabilities=[]; - if(behavior==='missing-patch')delete result.agentCapabilities._meta.antigravity.paperclipAdmission; if(behavior==='orphan-child') { descendant=spawn(process.execPath,['-e',"setInterval(()=>{},1000)"],{stdio:'ignore'}); writeFileSync(${JSON.stringify(join(root, "descendant.json"))},JSON.stringify({pid:descendant.pid})); @@ -63,19 +69,43 @@ process.stdin.on('data',chunk=>{ }); process.stdin.on('end',()=>{if(behavior!=='ignore-stop')process.exit(0)}); `; - const nativeFiles = [ - { path: "agy_acp_server.par", content: Buffer.from(script) }, - { path: "localharness_external", content: Buffer.from("#!/bin/sh\nexit 0\n") }, - ]; - const entries = nativeFiles.map(file => ({ path: file.path, sha256: hash(file.content), size: file.content.length, executable: true })); - const closureSha256 = hash(JSON.stringify(entries)); - const item = { url: "https://dl.google.com/agy-extensions/releases/macos/fixture.zip", archiveSha256: "a".repeat(64), closureSha256, vendorClosureSha256: closureSha256, vendorEntries: entries, patchVersion: "1.5.2-paperclip.2", admissionSourceSha256, provisioning: "verified-closure", executable: "agy_acp_server.par", args, entries }; - await writeFile(join(root, "antigravity-distributions.json"), JSON.stringify({ schema: "paperclip.antigravity_distribution.v1", version: "1.5.2", platforms: { [target]: item } })); + const content = Buffer.from(script); + const entries = [{ path: "agy", sha256: sha256(content), size: content.length, executable: true }]; + const closureSha256 = sha256(JSON.stringify(entries)); + const item = { + url: `https://storage.googleapis.com/antigravity-public/antigravity-cli/1.5.19-4821414830800896/${target}/fixture.tar.gz`, + archiveFormat: "tar.gz", + archiveSize: 1024, + archiveSha256: "a".repeat(64), + archiveSha512: "b".repeat(128), + archiveMember: "antigravity", + executable: "agy", + executableSha512: sha512(content), + closureSha256, + provisioning: "verified-closure", + args, + entries, + }; + await writeFile(join(root, "antigravity-distributions.json"), JSON.stringify({ + schema: "paperclip.antigravity_distribution.v1", + version: "1.5.19", + build: "1.5.19-4821414830800896", + environment: { AGY_CLI_DISABLE_AUTO_UPDATE: "1", AGY_CLI_FORCE_FILE_TOKEN_STORAGE: "1" }, + platforms: { [target]: item }, + })); const home = join(root, "operator-home"); const runtime = join(home, ".paperclip/runtimes/antigravity", target, closureSha256); await mkdir(runtime, { recursive: true, mode: 0o700 }); - for (const file of nativeFiles) await writeFile(join(runtime, file.path), file.content, { mode: 0o500 }); - await writeFile(join(runtime, ".paperclip-antigravity-closure.json"), JSON.stringify({ schema: "paperclip.antigravity_closure.v1", version: "1.5.2", patchVersion: item.patchVersion, admissionSourceSha256, archiveSha256: item.archiveSha256, vendorClosureSha256: closureSha256, closureSha256, entries }), { mode: 0o400 }); + await writeFile(join(runtime, "agy"), content, { mode: 0o500 }); + await writeFile(join(runtime, ".paperclip-antigravity-closure.json"), JSON.stringify({ + schema: "paperclip.antigravity_closure.v1", + version: "1.5.19", + build: "1.5.19-4821414830800896", + archiveSha256: item.archiveSha256, + archiveSha512: item.archiveSha512, + closureSha256, + entries, + }), { mode: 0o400 }); const api = await import(pathToFileURL(join(scripts, "probe-antigravity-metadata.mjs"))); return { root, runtime, auditPath, @@ -87,9 +117,21 @@ test("probe environment has only explicit sterile settings and cannot inherit cr const env = antigravityMetadataEnvironment("/isolated", "/verified/runtime"); assert.equal(env.HOME, "/isolated/home"); assert.equal(env.GEMINI_HOME, "/isolated/gemini"); - assert.equal(env.AGY_ACP_FORCE_FILE_STORAGE, "1"); - assert.equal(env.ANTIGRAVITY_HARNESS_PATH, "/verified/runtime/localharness_external"); - assert.deepEqual(Object.keys(env).sort(), ["AGY_ACP_FORCE_FILE_STORAGE", "ANTIGRAVITY_HARNESS_PATH", "GEMINI_HOME", "HOME", "LANG", "NO_COLOR", "PATH", "TMPDIR", "XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME"]); + assert.equal(env.AGY_CLI_FORCE_FILE_TOKEN_STORAGE, "1"); + assert.equal(env.AGY_CLI_DISABLE_AUTO_UPDATE, "1"); + assert.deepEqual(Object.keys(env).sort(), [ + "AGY_CLI_DISABLE_AUTO_UPDATE", + "AGY_CLI_FORCE_FILE_TOKEN_STORAGE", + "GEMINI_HOME", + "HOME", + "LANG", + "NO_COLOR", + "PATH", + "TMPDIR", + "XDG_CACHE_HOME", + "XDG_CONFIG_HOME", + "XDG_DATA_HOME", + ]); }); test("initialize uses Paperclip identity, preserves split UTF-8 and cannot send another method", async () => { @@ -122,7 +164,8 @@ test("real stdio probe sends initialize only, sanitizes metadata and removes its const output = await current.probe(); const audit = JSON.parse(await readFile(current.auditPath, "utf8")); assert.deepEqual(audit.requests.map(request => request.method), ["initialize"]); - assert.equal(audit.env.AGY_ACP_FORCE_FILE_STORAGE, "1"); + assert.equal(audit.env.AGY_CLI_FORCE_FILE_TOKEN_STORAGE, "1"); + assert.equal(audit.env.AGY_CLI_DISABLE_AUTO_UPDATE, "1"); assert.equal(audit.env.GEMINI_API_KEY, undefined); assert.equal(audit.env.GOOGLE_APPLICATION_CREDENTIALS, undefined); assert.equal(audit.env.NODE_OPTIONS, undefined); @@ -130,8 +173,8 @@ test("real stdio probe sends initialize only, sanitizes metadata and removes its assert.notEqual(audit.geminiHome, process.env.GEMINI_HOME); await assert.rejects(readFile(join(audit.home, "anything")), { code: "ENOENT" }); await assert.rejects(readFile(audit.cwd), { code: "ENOENT" }); - assert.deepEqual(output.authMethodIds, ["oauth-personal"]); - assert.equal(output.agentInfo.version, "1.5.2"); + assert.deepEqual(output.authMethodIds, ["oauth-personal", "gemini-api-key"]); + assert.equal(output.agentInfo.version, "1.5.19"); assert.equal(output.promptRequestsSent, 0); assert.equal(output.shutdown.exitCode, 0); assert.equal(output.shutdown.method, "eof"); @@ -139,14 +182,26 @@ test("real stdio probe sends initialize only, sanitizes metadata and removes its }); test("identity, version and protocol mismatches are rejected with sanitized diagnostics", async t => { - for (const [behavior, error] of [["wrong-version", /version_mismatch/], ["wrong-identity", /identity_mismatch/], ["wrong-protocol", /identity_mismatch/], ["bad-capabilities", /malformed_initialize_capabilities/], ["missing-patch", /native_admission_patch_not_advertised/]]) { + for (const [behavior, error] of [ + ["wrong-version", /version_mismatch/], + ["wrong-identity", /identity_mismatch/], + ["wrong-protocol", /identity_mismatch/], + ["bad-capabilities", /malformed_initialize_capabilities/], + ]) { const current = await fixture(t, behavior); await assert.rejects(current.probe(), error); } }); test("malformed, oversized, truncated and unexpected protocol streams fail closed", async t => { - for (const [behavior, error] of [["malformed", /malformed_json/], ["oversized", /stdout_limit/], ["stderr-limit", /stderr_limit/], ["unexpected-method", /unexpected_message/], ["truncated", /truncated_stream/], ["extra-message", /unexpected_message/]]) { + for (const [behavior, error] of [ + ["malformed", /malformed_json/], + ["oversized", /stdout_limit/], + ["stderr-limit", /stderr_limit/], + ["unexpected-method", /unexpected_message/], + ["truncated", /truncated_stream/], + ["extra-message", /unexpected_message/], + ]) { const current = await fixture(t, behavior); await assert.rejects(current.probe({ maxBytes: 4096 }), error); } @@ -173,8 +228,6 @@ test("shutdown retires an owned child after its native parent exits", async t => const current = await fixture(t, "orphan-child"); try { await current.probe(); } catch (error) { - // macOS sandboxing can deny probing an already-extinct process group. - // Preserve that fail-closed result and independently check the actual child. assert.equal(process.platform, "darwin"); assert.match(error.message, /^antigravity_process_group_check_failed:EPERM$/); } @@ -184,16 +237,18 @@ test("shutdown retires an owned child after its native parent exits", async t => test("tampered cache fails verification before any native process starts", async t => { const current = await fixture(t); - const child = join(current.runtime, "localharness_external"); - await chmod(child, 0o700); - await writeFile(child, "corrupt"); + const binary = join(current.runtime, "agy"); + await chmod(binary, 0o700); + await writeFile(binary, "corrupt"); await assert.rejects(current.probe(), /full execution closure digest mismatch/); await assert.rejects(readFile(current.auditPath), { code: "ENOENT" }); }); test("invalid startup or shutdown limits fail before any native process starts", async t => { const current = await fixture(t); - for (const options of [{ startupTimeoutMs: 0 }, { startupTimeoutMs: 30_001 }, { maxBytes: 1024 * 1024 + 1 }, { eofTimeoutMs: -1 }, { killTimeoutMs: 5_001 }]) await assert.rejects(current.probe(options), /Invalid Antigravity metadata probe limits/); + for (const options of [{ startupTimeoutMs: 0 }, { startupTimeoutMs: 30_001 }, { maxBytes: 1024 * 1024 + 1 }, { eofTimeoutMs: -1 }, { killTimeoutMs: 5_001 }]) { + await assert.rejects(current.probe(options), /Invalid Antigravity metadata probe limits/); + } await assert.rejects(readFile(current.auditPath), { code: "ENOENT" }); }); @@ -201,9 +256,11 @@ test("a Linux closure probe starts the pinned executable with its declared argum const current = await fixture(t, "success", { platform: "linux", architecture: "x64" }); const output = await current.probe(); const audit = JSON.parse(await readFile(current.auditPath, "utf8")); - assert.deepEqual(audit.argv, ["--uid="]); + assert.equal(audit.argv[0], "acp"); + assert.equal(audit.argv[1], "--gemini-dir"); + assert.equal(audit.argv[3], "--disable-telemetry"); assert.deepEqual(audit.requests.map(request => request.method), ["initialize"]); assert.equal(output.platform, "linux"); assert.equal(output.architecture, "x64"); - assert.equal(output.agentInfo.version, "1.5.2"); + assert.equal(output.agentInfo.version, "1.5.19"); }); diff --git a/packages/paperclip-runner/scripts/provision-antigravity.mjs b/packages/paperclip-runner/scripts/provision-antigravity.mjs index 027c210fd37..461efa718fc 100644 --- a/packages/paperclip-runner/scripts/provision-antigravity.mjs +++ b/packages/paperclip-runner/scripts/provision-antigravity.mjs @@ -24,8 +24,7 @@ export async function provisionAntigravityRuntime(options = {}) { if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { provisionAntigravityRuntime().then(result => { - console.log(`Verified Google Antigravity ${result.version} (${result.platform}-${result.architecture}), ${result.patchVersion}`); + console.log(`Verified Google Antigravity ${result.version} (${result.platform}-${result.architecture}), build ${result.build}`); console.log(`Runtime: ${result.destination}. Run setup as the same OS user that runs Paperclip.`); - console.log("Native Runner execution remains pending acceptance in this build."); }).catch(error => { console.error(error.message); process.exitCode = 1; }); } diff --git a/packages/paperclip-runner/scripts/release-provider-pack.mjs b/packages/paperclip-runner/scripts/release-provider-pack.mjs index ec8a2e65daa..70f799af157 100644 --- a/packages/paperclip-runner/scripts/release-provider-pack.mjs +++ b/packages/paperclip-runner/scripts/release-provider-pack.mjs @@ -70,8 +70,7 @@ export function verifyReleaseProviderPack(identity, sourceRevision, target = "li } /** A released profile requires exactly one ordinary entry; a pending one at - * most one candidate. Either way the closure is the release's frozen PATCHED - * Linux closure, never the vendor closure. */ + * most one candidate. Either way the closure matches the release's frozen Linux closure. */ function verifyReleaseAntigravity(payload, profile, frozen) { const ordinary = payload.providers?.antigravity, candidate = payload.candidateProviders?.antigravity; const mismatch = () => { throw new Error("Remote provider-pack Antigravity identity does not match this release"); }; @@ -83,7 +82,7 @@ function verifyReleaseAntigravity(payload, profile, frozen) { const platform = frozen?.platforms?.["linux-x64"]; if (frozen?.schema !== "paperclip.antigravity_distribution.v1" || frozen.version !== profile.agentServerVersion || platform?.provisioning !== "verified-closure" || !/^[a-f0-9]{64}$/.test(platform.closureSha256 ?? "") - || platform.closureSha256 === platform.vendorClosureSha256 + || (platform.vendorClosureSha256 !== undefined && platform.closureSha256 === platform.vendorClosureSha256) || entry.version !== profile.agentServerVersion || entry.profileDigest !== profile.commandDigest || entry.closureDigest !== `sha256:${platform.closureSha256}` || entry.qualification !== (pending ? "pending" : "qualified") || entry.path !== "provider-assets/antigravity/linux-x64" diff --git a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts index c29cb5f5398..68fc6790c59 100644 --- a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts +++ b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts @@ -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 } }); diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts index a51cac0bca5..abf969e42d7 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.test.ts @@ -271,62 +271,6 @@ describe("Codex ACPX runtime adapter", () => { await port.close({ reason: "test finished" }); }); - it.each([true, false])("keeps an Antigravity Plan-mode run read-only at the permission boundary (readOnly=%s)", async readOnly => { - const pending = pendingExtensionTurn("plan-turn"); - const runtime = fakeRuntime(); - vi.mocked(runtime.startTurn).mockReturnValue(pending.turn); - const command = fakeCommand(); - vi.mocked(command.spawn).mockReturnValue(fakeChild()); - let exit!: () => void; - const providerExit = new Promise(resolve => { exit = resolve; }); - let created!: AcpRuntimeOptions; - const options = openOptions(command); - options.profile = resolveQualifiedAcpxProfile("antigravity", "gemini-3.8-flash-low"); - options.permissionMode = "approve-all"; - options.readOnly = readOnly; - options.mcpServers = [{ name: "paperclip", url: "http://127.0.0.1:3212/mcp", bearerToken: "bridge-fixture", runnerOwned: true }, - { name: "runner_extra", url: "http://127.0.0.1:3213/mcp", bearerToken: "extra-fixture", runnerOwned: true }]; - options.paperclipTools = ["write_document"]; - vi.mocked(runtime.ensureSession).mockImplementationOnce(async () => { - 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" }, - agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 1 } } } } }); - const open = { id: 1, method: "session/new", params: { cwd: "/workspace" } as Record }; - guard("outbound", open); - const admission = open.params._meta.antigravity.paperclipAdmission; - guard("inbound", { id: 1, result: { sessionId: "backend-1", modes: { currentModeId: "default" }, - _meta: { paperclipAntigravityAdmission: { ...admission, sessionId: "backend-1", connectionId: "owned-connection" } } } }); - return HANDLE; - }); - const port = await openQualifiedAcpxRuntime(options, { - createRegistry: () => registry(), createStore: () => store(), - awaitProviderOwnership: providerOwnershipEstablished, awaitProviderExit: () => providerExit, - createRuntime: value => { created = value; return runtime; }, - }); - const turn = port.startTurn({ text: "Plan it", requestId: "plan-turn", onPermissionRequest: vi.fn() }); - await turn.promptStarted; - const ask = (toolCall: Record) => created.onPermissionRequest!({ sessionId: "backend-1", - raw: { sessionId: "backend-1", toolCall }, inferredKind: "other" } as never, { signal: new AbortController().signal }); - const write = { toolCallId: "w", title: "Run write_to_file?", kind: "edit", rawInput: { TargetFile: "/workspace/greeting.txt" } }; - const command_ = { toolCallId: "c", title: "touch greeting.txt", kind: "execute", rawInput: { CommandLine: "touch greeting.txt" } }; - const paperclip = { toolCallId: "p", title: "paperclip_write_document", kind: "other", rawInput: {}, - _meta: { mcp: { tool: "write_document", server: "paperclip" }, is_mcp_tool_call: true } }; - const refused = readOnly ? "reject_once" : "allow_once"; - await expect(ask(write)).resolves.toEqual({ outcome: refused }); - await expect(ask(command_)).resolves.toEqual({ outcome: refused }); - // Paperclip's own tools stay governed by Paperclip's Plan-mode rules. - await expect(ask(paperclip)).resolves.toEqual({ outcome: "allow_once" }); - // Another runner-owned server is not Paperclip's bridge. - await expect(ask({ ...paperclip, title: "runner_extra_write_file", - _meta: { mcp: { tool: "write_file", server: "runner_extra" }, is_mcp_tool_call: true } })).resolves.toEqual({ outcome: refused }); - pending.settle(); - await turn.result; - exit(); - await port.close({ reason: "test finished" }); - }); - it("recognises only a switch_mode request that carries plan text as a Claude plan proposal", () => { expect(claudeExitPlanModeProposal({ raw: { toolCall: { toolCallId: "t1", kind: "switch_mode", rawInput: { plan: " # P " } } } })) .toEqual({ toolCallId: "t1", markdown: "# P" }); diff --git a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts index 617faa315c7..4656cfedd19 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts @@ -51,9 +51,8 @@ import { createAcpxEffectiveModelGate, type AcpxEffectiveModelGate, type AcpxMod import { AcpxApprovalRequiredError, decideAcpxPermission } from "./permission-policy.js"; import { ACPX_CAPABILITY_PROFILES } from "./capability-profiles.js"; import { createCursorInstructionAdmission } from "./cursor-instructions.js"; -import { antigravitySavedStateIncompatible, createAntigravityAdmission } from "./antigravity-admission.js"; -import { ANTIGRAVITY_PAPERCLIP_MCP_SERVER, antigravityPlanModeAllows } from "./antigravity-plan-mode.js"; import { createAcpxModeBinding } from "./provider-mode.js"; +import { openAntigravityAcpRuntime } from "./antigravity-acp-runtime.js"; import { openAntigravitySwarmRuntime } from "./antigravity-swarm-runtime.js"; import { isAntigravitySwarmRoute } from "./antigravity-swarm-route.js"; import { isAcpPromptRequest, type AcpxTurnDispatchJournal } from "./turn-dispatch-journal.js"; @@ -226,9 +225,11 @@ export async function openQualifiedAcpxRuntime( // tree when Node cannot safely signal a verified provider process group. assertVerifiedAcpxProviderPlatform(dependencies.platform ?? process.platform); options.signal?.throwIfAborted(); - // A trusted /swarm turn runs the pinned Antigravity CLI through its own - // verified ACP client (antigravity-swarm-runtime.ts), never through ACPX. + // Antigravity runs Google's pinned `agy acp` CLI directly (never through ACPX): + // trusted `/swarm` turns use `antigravity-swarm-runtime.ts`, and ordinary turns + // use `antigravity-acp-runtime.ts`. if (isAntigravitySwarmRoute(options.profile.agent, options.mode)) return openAntigravitySwarmRuntime(options); + if (options.profile.agent === "antigravity") return openAntigravityAcpRuntime(options); const credentialFenceFds = options.credentialFenceFds; if ( !Array.isArray(credentialFenceFds) || @@ -364,10 +365,6 @@ export async function openQualifiedAcpxRuntime( .filter((server) => server.runnerOwned) .map((server) => server.name), ); - const antigravityPlanPolicy = { - paperclipServerOwned: options.mcpServers.some(server => server.runnerOwned && server.name === ANTIGRAVITY_PAPERCLIP_MCP_SERVER), - paperclipTools: new Set(options.paperclipTools ?? []), - }; const permissionBoundary: { active: AbortController | null; hasAdmittedTurn: boolean; @@ -434,10 +431,7 @@ export async function openQualifiedAcpxRuntime( : options.profile.agent === "cursor" ? createCursorInstructionAdmission(options.systemInstructions) : null; - const antigravityAdmission = options.profile.agent === "antigravity" - ? createAntigravityAdmission(options.systemInstructions, options.profile.reportedModelId) - : null; - const contextAdmission = instructionAdmission ?? antigravityAdmission; + const contextAdmission = instructionAdmission; const mcpBearerVariable = (index: number): string | undefined => options.profile.agent === "claude" ? `PAPERCLIP_ACPX_MCP_BEARER_${index}` : undefined; const mcpBearerEnvironment = Object.fromEntries(options.mcpServers.flatMap((server, index) => { @@ -481,7 +475,6 @@ export async function openQualifiedAcpxRuntime( const effort = effortAdmission?.createGuard(); return (direction: "inbound" | "outbound", message: unknown) => { open(direction, message); effort?.(direction, message); }; } } : effortAdmission ? { protocolGuardFactory: () => effortAdmission.createGuard() } : {}), - ...(antigravityAdmission ? { protocolGuardFactory: () => antigravityAdmission.createGuard() } : {}), sessionStore, agentRegistry: createRegistry({ // Preserve Claude's ACP capability identity. This is metadata only: the @@ -571,8 +564,6 @@ export async function openQualifiedAcpxRuntime( } if (options.profile.agent === "kimi" && options.readOnly === true && !kimiReadOnlyPermissionAllowed(request, runnerOwnedMcpServerNames)) return { outcome: "reject_once" }; - if (options.profile.agent === "antigravity" && options.readOnly === true - && !antigravityPlanModeAllows(request, antigravityPlanPolicy)) return { outcome: "reject_once" }; const disposition = decideAcpxPermission( options.profile.agent, options.permissionMode, @@ -769,10 +760,6 @@ export async function openQualifiedAcpxRuntime( return ensuredHandle; }) : ensuredSession) .catch((error: unknown) => { - // A refused Antigravity reload is saved state this build cannot reopen, - // not ACPX's retryable "resume required"; the Runner names its class. - const savedState = options.profile.agent === "antigravity" ? antigravitySavedStateIncompatible(error) : null; - if (savedState) throw savedState; // The closed code below cannot say why the provider session did not // start, so every ensure rejection keeps its redacted explanation. An // abort reason is Runner cancellation, not a provider explanation. diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-connection.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-connection.ts new file mode 100644 index 00000000000..dde6ef20299 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-connection.ts @@ -0,0 +1,231 @@ +import type { ChildProcessWithoutNullStreams } from "node:child_process"; +import type { AcpRuntimeEvent } from "acpx/runtime"; + +const EXIT_OUTPUT_GRACE_MS = 200; + +export type Json = Record; + +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; + resolve: (value: Json) => void; + reject: (error: Error) => void; + }>(); + #buffer = ""; + #queue: Promise = Promise.resolve(); + #lost: Error | null = null; + #pendingDeliveries = new Set<(error: Error) => void>(); + readonly #options: AntigravityAcpConnectionOptions; + readonly exited: Promise; + onNotification: (method: string, params: Json) => void = () => {}; + onRequest: (method: string, params: Json, context: { responseDelivery: Promise }) => Promise = 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(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 { + 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(); + for (const rejectDelivery of this.#pendingDeliveries) rejectDelivery(error); + this.#pendingDeliveries.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; } + let deliverySettled = false; + let resolveDelivery!: () => void; + let rejectDelivery!: (error: Error) => void; + const responseDelivery = new Promise((resolve, reject) => { + resolveDelivery = () => { + if (deliverySettled) return; + deliverySettled = true; + this.#pendingDeliveries.delete(rejectDelivery); + resolve(); + }; + rejectDelivery = (error: Error) => { + if (deliverySettled) return; + deliverySettled = true; + this.#pendingDeliveries.delete(rejectDelivery); + reject(error); + }; + }); + responseDelivery.catch(() => undefined); + this.#pendingDeliveries.add(rejectDelivery); + void this.onRequest(method, jsonRecord(message.params), { responseDelivery }).then( + result => this.#writeDelivered({ jsonrpc: "2.0", id, result }, resolveDelivery, rejectDelivery), + error => { + rejectDelivery(error instanceof Error ? error : new Error("Antigravity request handler failed")); + 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`); + } + + #writeDelivered(message: Json, resolveDelivery: () => void, rejectDelivery: (error: Error) => void): void { + if (this.#lost || this.child.stdin.destroyed || !this.child.stdin.writable) { + rejectDelivery(this.#lost ?? new Error("Antigravity process input closed before reply was delivered")); + return; + } + try { + this.child.stdin.write(`${JSON.stringify(message)}\n`, error => { + if (error) rejectDelivery(error); + else if (this.#lost) rejectDelivery(this.#lost); + else resolveDelivery(); + }); + } catch (error) { + rejectDelivery(error instanceof Error ? error : new Error("Antigravity reply write failed")); + } + } + + request(method: string, params: Json, timeoutMs: number | null): Promise { + if (this.#lost) return Promise.reject(this.#lost); + const id = this.#next++; + return new Promise((resolve, reject) => { + let settled = false; + const entry: { + method: string; + timer?: ReturnType; + 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 { + #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 { + for (;;) { + const item = this.#items.shift(); + if (item) { yield item; continue; } + if (this.#ended) return; + await new Promise(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; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts new file mode 100644 index 00000000000..f4d3f663c51 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts @@ -0,0 +1,529 @@ +import { spawn, type ChildProcess } from "node:child_process"; +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"; +import { QUALIFIED_ACPX_PROFILES } from "./qualified-profiles.js"; +import type { AcpxRuntimePortOpenOptions } from "./runtime-host.js"; +import { withAcpxTurnCancellation } from "./turn-cancellation.js"; + +const roots: string[] = []; +afterEach(async () => { + await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); +}); + +async function makeFixture(scenario = "ok") { + const root = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-acp-runtime-"))); + roots.push(root); + const cwd = join(root, "workspace"); + const stateDirectory = join(root, "state"); + const { mkdir } = await import("node:fs/promises"); + await mkdir(cwd, { recursive: true }); + await mkdir(stateDirectory, { recursive: true }); + const logFile = join(root, "rpc-log.jsonl"); + const peer = join(root, "fake-agy-ordinary.cjs"); + + await writeFile(peer, ` +const fs = require('node:fs'); +const readline = require('node:readline'); +const scenario = process.argv[2]; +const logFile = process.argv[3]; +const write = msg => process.stdout.write(JSON.stringify(msg) + '\\n'); +const log = msg => fs.appendFileSync(logFile, JSON.stringify(msg) + '\\n'); +let currentModel = 'gemini-4-argon'; +let currentLevel = 'medium'; +let currentMode = 'default'; +let pendingPerm = null; +let cancelPrompt = null; +const configOptions = () => [ + { id: 'model', category: 'model', currentValue: currentModel }, + { id: 'thought_level', category: 'thought_level', currentValue: currentLevel }, + { id: 'mode', category: 'mode', currentValue: currentMode }, +]; +const rl = readline.createInterface({ input: process.stdin }); +rl.on('line', line => { + if (!line.trim()) return; + const msg = JSON.parse(line); + log(msg); + if (msg.method === undefined) { + if (pendingPerm && msg.id === pendingPerm.id) { pendingPerm.resolve(msg.result); pendingPerm = null; } + return; + } + const { id, method, params = {} } = msg; + if (method === 'initialize') { + write({ + jsonrpc: '2.0', id, + result: { + protocolVersion: 1, + agentInfo: { + name: 'Antigravity ACP Server', + version: scenario === 'wrong-version' ? '1.5.20' : ${JSON.stringify(ANTIGRAVITY_RUNTIME_VERSION)}, + }, + agentCapabilities: { + loadSession: true, + _meta: { antigravity: { systemPrompt: { append: scenario !== 'no-system-prompt' } } }, + }, + }, + }); + return; + } + if (method === 'authenticate') { + write({ jsonrpc: '2.0', id, result: {} }); + return; + } + if (method === 'session/new') { + if (scenario === 'auth-required') { + write({ jsonrpc: '2.0', id, error: { code: -32000, message: 'Authentication required' } }); + return; + } + write({ + jsonrpc: '2.0', id, + result: { + sessionId: 'sess-ordinary-1', + models: { + currentModelId: 'gemini-4-argon-medium', + availableModels: [{ modelId: 'gemini-4-argon-medium' }, { modelId: 'gemini-4-argon-low' }, { modelId: 'gemini-3.8-flash-high' }], + }, + configOptions: configOptions(), + }, + }); + 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; + } + write({ + jsonrpc: '2.0', id, + result: { + sessionId: params.sessionId, + models: { + currentModelId: 'gemini-4-argon-medium', + availableModels: [{ modelId: 'gemini-4-argon-medium' }, { modelId: 'gemini-4-argon-low' }, { modelId: 'gemini-3.8-flash-high' }], + }, + configOptions: configOptions(), + }, + }); + 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' } }); + return; + } + currentModel = match[1]; + currentLevel = match[2]; + write({ jsonrpc: '2.0', id, result: {} }); + 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; + } + if (scenario === 'cancel-hang') { + process.on('SIGTERM', () => {}); + setInterval(() => {}, 1000); + return; + } + if (scenario === 'quota') { + write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: params.sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: '\\n⚠ RESOURCE_EXHAUSTED (code 429): quota exceeded\\n' } } } }); + write({ jsonrpc: '2.0', id, result: { stopReason: 'end_turn' } }); + return; + } + if (scenario === 'plan-permission' || scenario === 'interactive-permission' || scenario === 'permission-exit') { + 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', name: 'Allow once', kind: 'allow_once' }, + { optionId: 'deny', name: 'Deny', kind: 'reject_once' }, + ], + }, + }); + if (scenario === 'permission-exit') { + setTimeout(() => process.exit(7), 30); + return; + } + permPromise.then(res => { + log({ permissionReply: res }); + write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: params.sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'plan-checked:' + (res?.outcome?.optionId ?? 'none') } } } }); + write({ jsonrpc: '2.0', id, result: { stopReason: 'end_turn', usage: { inputTokens: 20, outputTokens: 10, totalTokens: 30 } } }); + }); + return; + } + write({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: params.sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'echo:' + text + '|model:' + currentModel + '-' + currentLevel } } } }); + write({ jsonrpc: '2.0', id, result: { stopReason: 'end_turn', usage: { inputTokens: 100, outputTokens: 25, totalTokens: 125 } } }); + return; + } + if (method === 'session/cancel') { + cancelPrompt?.(); + return; + } + write({ jsonrpc: '2.0', id, error: { code: -32601, message: 'Method not found' } }); +}); +`); + + const openOptions = (overrides: Partial = {}): AcpxRuntimePortOpenOptions => ({ + profile: { ...QUALIFIED_ACPX_PROFILES.antigravity, reportedModelId: "gemini-4-argon-medium", qualificationModel: "gemini-4-argon-medium" }, + cwd, + 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 }), + close: async () => undefined, + } as AcpxRuntimePortOpenOptions["command"], + retainFailedAdmissionCleanup: () => undefined, + ...overrides, + }); + + return { root, cwd, stateDirectory, logFile, openOptions }; +} + +describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", () => { + it("runs an ordinary OAuth turn, supports warm setModel, neutralizes leading slash commands, and records usage", async () => { + const { logFile, openOptions } = await makeFixture("ok"); + const runtime = await openAntigravityAcpRuntime(openOptions(), { awaitProviderOwnership: async () => undefined }); + try { + const identity = await runtime.identity(); + expect(identity.backendSessionId).toBe("sess-ordinary-1"); + + const turn1 = runtime.startTurn({ requestId: "req-1", text: "/swarm do not trigger swarm on ordinary turn" }); + const chunks1: string[] = []; + for await (const event of turn1.events) { + if (event.type === "text_delta" && event.stream === "output") chunks1.push(event.text); + } + const res1 = await turn1.result; + expect(res1).toEqual({ status: "completed", stopReason: "end_turn" }); + expect(chunks1.join("")).toContain("\u2060/swarm"); + expect(chunks1.join("")).toContain("model:gemini-4-argon-medium"); + + 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"); + expect((status.terminalPromptUsage as { event: { breakdown: { totalTokens: number } } }).event.breakdown.totalTokens).toBe(125); + + const turn2 = runtime.startTurn({ requestId: "req-2", text: "second turn" }); + const chunks2: string[] = []; + for await (const event of turn2.events) { + if (event.type === "text_delta" && event.stream === "output") chunks2.push(event.text); + } + expect(await turn2.result).toEqual({ status: "completed", stopReason: "end_turn" }); + expect(chunks2.join("")).toContain("model:gemini-3.8-flash-high"); + + const rpc = (await readFile(logFile, "utf8")).trim().split("\n").map(line => JSON.parse(line)); + expect(rpc.map(m => m.method)).toEqual([ + "initialize", + "session/new", + "session/set_model", + "session/prompt", + "session/set_model", + "session/prompt", + ]); + expect(rpc[1].params._meta).toEqual({ antigravity: { systemPrompt: { append: "Follow Paperclip instructions." } } }); + expect(rpc[1].params.mcpServers).toEqual([{ + type: "http", + name: "paperclip", + url: "http://127.0.0.1:41234/mcp", + headers: [{ name: "Authorization", value: "Bearer tok-123" }], + }]); + } finally { + await runtime.close({ reason: "test" }); + } + }); + + it("calls authenticate with gemini-api-key when GEMINI_API_KEY is present", async () => { + const { logFile, openOptions } = await makeFixture("ok"); + const runtime = await openAntigravityAcpRuntime( + openOptions({ launchEnvironment: { PATH: process.env.PATH ?? "/usr/bin:/bin", GEMINI_API_KEY: "AIza-test-key" } }), + { awaitProviderOwnership: async () => undefined }, + ); + 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" }); + }); + + 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({ reason: "test" }); + + const runtime2 = await openAntigravityAcpRuntime(openOptions({ restoringSession: true }), { awaitProviderOwnership: async () => undefined }); + expect((await runtime2.identity()).backendSessionId).toBe("sess-ordinary-1"); + 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); + + // Changing readOnly scope invalidates saved session. + await expect(openAntigravityAcpRuntime(openOptions({ restoringSession: true, readOnly: true }), { awaitProviderOwnership: async () => undefined })) + .rejects.toBeInstanceOf(AntigravitySavedStateIncompatibleError); + + // Server-side resume failure also surfaces AntigravitySavedStateIncompatibleError. + const { openOptions: openIncompat, stateDirectory: incompatState } = await makeFixture("resume-incompatible"); + await writeFile(join(incompatState, "antigravity-session.json"), JSON.stringify({ + sessionId: "sess-missing", + cwd: openIncompat().cwd, + model: "gemini-4-argon-medium", + readOnly: false, + })); + await expect(openAntigravityAcpRuntime(openIncompat({ restoringSession: true }), { awaitProviderOwnership: async () => undefined })) + .rejects.toBeInstanceOf(AntigravitySavedStateIncompatibleError); + void stateDirectory; + }); + + it("enforces readOnly plan mode by switching to plan mode and denying edit permission requests", async () => { + const { logFile, openOptions } = await makeFixture("plan-permission"); + const runtime = await openAntigravityAcpRuntime(openOptions({ readOnly: true }), { awaitProviderOwnership: async () => undefined }); + try { + const turn = runtime.startTurn({ requestId: "req-plan", text: "inspect repo" }); + 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(chunks.join("")).toBe("plan-checked:deny"); + 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({ reason: "test" }); + } + }); + + it("classifies provider quota refusals, handles cancellation, and reports process loss", async () => { + const quotaFx = await makeFixture("quota"); + const quotaRt = await openAntigravityAcpRuntime(quotaFx.openOptions(), { awaitProviderOwnership: async () => undefined }); + const onTerminalSessionFailure = vi.fn(); + const quotaTurn = quotaRt.startTurn({ requestId: "req-quota", text: "hi", onTerminalSessionFailure }); + for await (const _ of quotaTurn.events) { /* drain */ } + const quotaRes = await quotaTurn.result; + expect(quotaRes.status).toBe("failed"); + expect(onTerminalSessionFailure).toHaveBeenCalledWith(expect.objectContaining({ category: "limit" })); + await quotaRt.close({ reason: "test" }); + + const cancelFx = await makeFixture("cancel"); + const cancelRt = await openAntigravityAcpRuntime(cancelFx.openOptions(), { awaitProviderOwnership: async () => undefined }); + const cancelTurn = cancelRt.startTurn({ requestId: "req-cancel", text: "slow" }); + await cancelTurn.promptStarted; + await cancelTurn.cancel(); + expect(await cancelTurn.result).toEqual({ status: "cancelled", stopReason: "cancelled" }); + 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({ reason: "test" }); + }); + + it("fails closed on version mismatch, missing systemPrompt capability, or auth error during session/new", async () => { + const wrongVer = await makeFixture("wrong-version"); + await expect(openAntigravityAcpRuntime(wrongVer.openOptions(), { awaitProviderOwnership: async () => undefined })) + .rejects.toThrow(AntigravityAcpError); + + const noSys = await makeFixture("no-system-prompt"); + await expect(openAntigravityAcpRuntime(noSys.openOptions(), { awaitProviderOwnership: async () => undefined })) + .rejects.toThrow(AntigravityAcpError); + + const authReq = await makeFixture("auth-required"); + 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[] = []; + let deliveredBeforeDecision = false; + let deliveryPromise: Promise | undefined; + const turn = runtime.startTurn({ + requestId: "req-approve", + text: "edit file", + onPermissionRequest: async (request, context) => { + deliveryPromise = context.responseDelivery; + void context.responseDelivery?.then(() => { deliveredBeforeDecision = true; }); + await new Promise(resolve => setTimeout(resolve, 15)); + expect(deliveredBeforeDecision).toBe(false); + 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" }); + await expect(deliveryPromise).resolves.toBeUndefined(); + expect(seenTitles).toEqual(["Write file"]); + expect(chunks.join("")).toBe("plan-checked:allow"); + } finally { + await runtime.close({ reason: "test" }); + } + + // Rejects responseDelivery when the CLI exits before the approval reply can be sent. + const exitFx = await makeFixture("permission-exit"); + const exitRt = await openAntigravityAcpRuntime( + exitFx.openOptions({ permissionMode: "approve-reads", permissionPolicy: { defaultAction: "escalate" } }), + { awaitProviderOwnership: async () => undefined }, + ); + try { + let exitDelivery: Promise | undefined; + const turn = exitRt.startTurn({ + requestId: "req-approve-lost", + text: "edit file", + onPermissionRequest: async (_request, context) => { + exitDelivery = context.responseDelivery; + await new Promise(resolve => setTimeout(resolve, 100)); + return { outcome: "allow_once" }; + }, + }); + expect(await turn.result).toMatchObject({ status: "failed", error: { code: "ACPX_PROVIDER_PROCESS_LOST" } }); + await expect(exitDelivery).rejects.toThrow(); + } finally { + await exitRt.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); + }); + + it("propagates retirement failure instead of reporting cancelled when Stop cannot confirm shutdown", async () => { + const { openOptions } = await makeFixture("cancel-hang"); + let spawnedChild: ChildProcess | undefined; + const base = openOptions(); + const wrappedCommand = { + ...base.command, + spawn: (...args: Parameters) => { + const child = base.command.spawn(...args); + spawnedChild = child; + return child; + }, + }; + const runtime = await openAntigravityAcpRuntime( + { ...base, command: wrappedCommand }, + { awaitProviderOwnership: async () => undefined, cancelGraceMs: 50 }, + ); + const realKill = process.kill.bind(process); + let blockProof = true; + const killSpy = vi.spyOn(process, "kill").mockImplementation((pid, signal) => { + if (blockProof && spawnedChild?.pid && pid === -spawnedChild.pid && signal === 0) { + throw Object.assign(new Error("controlled process-state uncertainty"), { code: "EACCES" }); + } + return realKill(pid, signal); + }); + try { + const managed = withAcpxTurnCancellation( + runtime.startTurn({ requestId: "req-unretired", text: "hang forever" }), + reason => runtime.close({ reason }), + 500, + ); + await managed.promptStarted; + await expect(managed.cancel({ reason: "stop" })).rejects.toThrow(); + await expect(managed.result).rejects.toThrow(); + } finally { + blockProof = false; + if (spawnedChild?.pid) { + try { realKill(-spawnedChild.pid, "SIGKILL"); } catch {} + } + killSpy.mockRestore(); + await runtime.close({ reason: "cleanup" }).catch(() => undefined); + } + }, 15_000); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.ts new file mode 100644 index 00000000000..74c5d16287f --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.ts @@ -0,0 +1,630 @@ +import type { ChildProcess, ChildProcessWithoutNullStreams } from "node:child_process"; +import { readFile, rename, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +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"; +import { retireAntigravityProcess } from "./antigravity-process.js"; +import { trackAntigravityProcessLineage, type ProcessTableRead } from "./antigravity-process-lineage.js"; +import { ANTIGRAVITY_CLI_AGENT_NAME, antigravitySelections, classifyAntigravityRefusalText } from "./antigravity-swarm-guard.js"; +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, +} from "./runtime-host.js"; + +const DEFAULT_REQUEST_TIMEOUT_MS = 60_000; +const DEFAULT_CANCEL_GRACE_MS = 5_000; +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"; + +export interface AntigravityAcpRuntimeDependencies { + requestTimeoutMs?: number; + cancelGraceMs?: number; + readbackTimeoutMs?: number; + awaitProviderOwnership?: (child: ChildProcess) => Promise; + lineageSampleIntervalMs?: number; + readProcessTable?: () => Promise; +} + +class ProcessLostError extends Error { + readonly code = PROCESS_LOST_CODE; + constructor() { super(PROCESS_LOST_MESSAGE); } +} + +export class AntigravityAcpError extends Error { + readonly retryable = false; + readonly providerFailure; + constructor( + readonly code: string, + message: string, + category: "authentication" | "invalid_request" | "model_unavailable" | "rate_limit" | "quota_exhausted" | "unknown" = "unknown", + ) { + super(message); + this.name = "AntigravityAcpError"; + this.providerFailure = createProviderFailure({ provider: "antigravity", phase: "startup", message, category }); + } +} + +function formatMcpServers(servers: readonly AcpxMcpServerBinding[]): Json[] { + return servers.map(server => { + if ("url" in server) { + return { + type: "http", + name: server.name, + url: server.url, + headers: server.bearerToken ? [{ name: "Authorization", value: `Bearer ${server.bearerToken}` }] : [], + }; + } + return { + type: "stdio", + name: server.name, + command: server.command, + args: [...server.args], + env: Object.entries(server.env).map(([name, value]) => ({ name, value })), + }; + }); +} + +function neutralizeOrdinaryAntigravityPrompt(text: string): string { + const [afterNative = text] = neutralizeAntigravityNativeCommands([text]); + // Prevent an ordinary turn from accidentally triggering native CLI slash commands such as `/swarm`. + return afterNative.replace(/^(\s*)\/(?=[a-zA-Z])/, `$1${WORD_JOINER}/`); +} + +function extractAvailableModelIds(sessionResult: Json): string[] { + const available = jsonRecord(sessionResult.models).availableModels; + if (!Array.isArray(available)) return []; + return available.flatMap(entry => { + const id = jsonRecord(entry).modelId; + return typeof id === "string" && id ? [id] : []; + }); +} + +function confirmedModelMatches(selections: Map, requested: string): boolean { + const family = selections.get("model"); + if (!family) return false; + if (family === requested) return true; + const level = selections.get("thought_level"); + return typeof level === "string" && `${family}-${level}` === requested; +} + +function replyConfirmsModel(reply: Json | undefined, requested: string): boolean { + return jsonRecord(jsonRecord(reply).models).currentModelId === requested; +} + +interface SavedAntigravitySession { + sessionId: string; + cwd: string; + model: string; + readOnly: boolean; +} + +async function readSavedSession(stateDirectory: string): Promise { + try { + 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, + cwd: parsed.cwd, + model: typeof parsed.model === "string" ? parsed.model : "", + readOnly: parsed.readOnly === true, + }; + } catch { + return null; + } +} + +async function writeSavedSession(stateDirectory: string, saved: SavedAntigravitySession): Promise { + const target = join(stateDirectory, SESSION_RECORD_FILE); + const tmp = `${target}.tmp`; + await writeFile(tmp, `${JSON.stringify(saved)}\n`, { mode: 0o600 }); + await rename(tmp, target); +} + +async function applyModelSelection( + connection: AntigravityAcpConnection, + sessionId: string, + model: string, + timeoutMs: number, + readbackTimeoutMs: number, + selections: Map, + mergeSelections: (source: unknown) => void, + waitForSelection: (predicate: () => boolean, limitMs: number) => Promise, +): Promise { + let reply: Json | undefined; + try { + reply = await connection.request("session/set_model", { sessionId, modelId: model }, timeoutMs); + } catch { + try { + reply = await connection.request("session/set_config_option", { sessionId, configId: "model", value: model }, timeoutMs); + } catch { + reply = undefined; + } + } + if (reply) mergeSelections(reply); + await connection.drain(); + 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) { + const family = model.slice(0, cut); + const level = model.slice(cut + 1); + try { + const r1 = await connection.request("session/set_config_option", { sessionId, configId: "model", value: family }, timeoutMs); + mergeSelections(r1); + const r2 = await connection.request("session/set_config_option", { sessionId, configId: "thought_level", value: level }, timeoutMs); + mergeSelections(r2); + await connection.drain(); + if (!confirmedModelMatches(selections, model)) { + await waitForSelection(() => confirmedModelMatches(selections, model), readbackTimeoutMs); + } + } catch { + // Handled by fail-closed confirmation check below. + } + } + } + if (!isConfirmed()) { + throw new AntigravityAcpError( + "ANTIGRAVITY_MODEL_UNAVAILABLE", + `Antigravity could not select model ${model}. Choose an available model for this agent and try again.`, + "model_unavailable", + ); + } +} + +/** + * Unified direct ACP runtime port for Google Antigravity (`agy acp` 1.5.19) + * handling ordinary (non-swarm) turns on both local and Paperclip Cloud hosts. + */ +export async function openAntigravityAcpRuntime( + options: AcpxRuntimePortOpenOptions, + dependencies: AntigravityAcpRuntimeDependencies = {}, +): Promise { + if (options.profile.agent !== "antigravity") { + throw new Error("The Antigravity ACP runtime serves only the Antigravity profile"); + } + 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"); + } + + options.assertWorkspaceHeld?.(); + 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 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, + }); + let retirement: Promise | null = null; + const retire = () => retirement ??= retireAntigravityProcess(child, connection.exited) + .finally(() => lineage.terminate()) + .catch((error: unknown) => { retirement = null; throw error; }); + + const selections = new Map(); + 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 => { + if (predicate()) return Promise.resolve(true); + if (connection.lost || options.signal?.aborted) return Promise.resolve(false); + return new Promise(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 = jsonRecord(params.update); + if (update.sessionUpdate === "config_option_update" || update.sessionUpdate === "current_mode_update") { + mergeSelections(update); + } + updateListener?.(params); + }; + + const planPolicy = { + 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 }); + + let sessionId: string; + let availableModelIds: string[] = []; + const mcpServers = formatMcpServers(options.mcpServers); + const hasApiKey = typeof options.launchEnvironment.GEMINI_API_KEY === "string" && options.launchEnvironment.GEMINI_API_KEY.trim().length > 0; + try { + await (dependencies.awaitProviderOwnership ?? awaitVerifiedAcpxProviderOwnership)(child); + options.signal?.throwIfAborted(); + const initialized = await connection.request("initialize", { + protocolVersion: 1, + clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, + clientInfo: { name: "paperclip-runner", version: "1" }, + }, requestTimeoutMs); + options.signal?.throwIfAborted(); + 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 = 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."); + } + if (hasApiKey) { + await connection.request("authenticate", { methodId: "gemini-api-key" }, requestTimeoutMs); + options.signal?.throwIfAborted(); + } + + const sessionMeta = options.systemInstructions + ? { antigravity: { systemPrompt: { append: options.systemInstructions } } } + : undefined; + let opened: Json; + if (options.restoringSession === true) { + const saved = await readSavedSession(options.stateDirectory); + if (!saved || saved.cwd !== options.cwd || saved.readOnly !== (options.readOnly === true)) { + throw new AntigravitySavedStateIncompatibleError("the saved Antigravity conversation is missing or changed scope"); + } + try { + opened = await connection.request("session/resume", { + sessionId: saved.sessionId, + cwd: options.cwd, + mcpServers, + ...(sessionMeta ? { _meta: sessionMeta } : {}), + }, requestTimeoutMs); + sessionId = typeof opened.sessionId === "string" && opened.sessionId ? opened.sessionId : saved.sessionId; + } catch (error) { + 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"); + } + } else { + try { + opened = await connection.request("session/new", { + cwd: options.cwd, + mcpServers, + ...(sessionMeta ? { _meta: sessionMeta } : {}), + }, requestTimeoutMs); + } catch (error) { + 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; + } + if (typeof opened.sessionId !== "string" || !opened.sessionId) { + throw new AntigravityAcpError("ANTIGRAVITY_SESSION_INVALID", "Antigravity did not return a session ID."); + } + sessionId = opened.sessionId; + } + + options.signal?.throwIfAborted(); + mergeSelections(opened); + availableModelIds = extractAvailableModelIds(opened); + if (availableModelIds.length > 0 && !availableModelIds.includes(currentModel)) { + throw new AntigravityAcpError( + "ANTIGRAVITY_MODEL_UNAVAILABLE", + `Model ${currentModel} is not available for this Google Antigravity connection. Choose an available model and try again.`, + "model_unavailable", + ); + } + if (options.readOnly === true) { + 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, readbackTimeoutMs, + selections, mergeSelections, waitForSelection, + ); + options.signal?.throwIfAborted(); + await writeSavedSession(options.stateDirectory, { + sessionId, + cwd: options.cwd, + model: currentModel, + readOnly: options.readOnly === true, + }).catch(() => undefined); + } catch (error) { + options.signal?.removeEventListener("abort", abortAdmission); + const cleanup = retire(); + options.retainFailedAdmissionCleanup(cleanup); + await cleanup.catch(() => undefined); + throw error; + } + + options.signal?.removeEventListener("abort", abortAdmission); + const status: Json = { + antigravityVersion: ANTIGRAVITY_RUNTIME_VERSION, + }; + let active: { cancel(reason?: string): Promise; result: Promise } | null = null; + let closed = false; + + const runTurn = async (input: AcpxRuntimeTurnInput, events: AntigravityAcpEventQueue, started: () => void): Promise => { + 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 = jsonRecord(params.update); + const event = acpRuntimeEventFromValidatedSessionUpdate({ method: "session/update", params }); + if (!event) return; + if (update.sessionUpdate === "usage_update") { + 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; + events.push(event); + }; + + connection.onRequest = async (method, params, { responseDelivery }) => { + if (method !== "session/request_permission" || params.sessionId !== sessionId) throw new Error("unsupported"); + 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(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( + permissionRequest, + { signal: input.signal ?? permAbort.signal, responseDelivery }, + ); + 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("reject_once"); + }; + + const keepUsage = (reported: unknown) => { + 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, + promptId: `${input.requestId}:antigravity`, + event: { type: "status", tag: "usage_update", text: "terminal prompt usage", breakdown: usage }, + }; + } + }; + + const dispatch = input.dispatchJournal?.markReceived() ? input.dispatchJournal : null; + let retireFailure: unknown; + 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([ + response.then(reply => ({ reply }), () => ({ reply: null })), + new Promise(resolve => setTimeout(() => resolve(null), grace)), + ]); + keepUsage(settled?.reply?.usage); + if (!settled) { + try { + await retire(); + } catch (error) { + retireFailure = error; + closed = true; + throw error; + } + } + return { status: "cancelled", stopReason: "cancelled" }; + } + keepUsage(outcome.usage); + const stopReason = typeof outcome.stopReason === "string" ? outcome.stopReason : "end_turn"; + if (cancelled || stopReason === "cancelled") return { status: "cancelled", stopReason: "cancelled" }; + const refusal = classifyAntigravityRefusalText(transcript); + if (refusal) { + input.onTerminalSessionFailure?.({ + category: refusal.kind === "authentication" ? "access" : "limit", + title: refusal.message, + provider: { kind: refusal.kind, ...(refusal.httpStatus ? { httpStatus: refusal.httpStatus } : {}), ...(refusal.status ? { status: refusal.status } : {}) }, + }); + return { status: "failed", error: { code: refusal.kind === "authentication" ? "ANTIGRAVITY_AUTH_REQUIRED" : "ANTIGRAVITY_PROVIDER_REFUSED", message: refusal.message, retryable: false } }; + } + return { status: "completed", stopReason }; + } catch (error) { + if (retireFailure !== undefined) throw retireFailure; + 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" } + : { status: "failed", error: { code: PROCESS_LOST_CODE, message: PROCESS_LOST_MESSAGE, retryable: true } }; + } + return { + status: "failed", + error: { + code: error instanceof AntigravityAcpError ? error.code : "ANTIGRAVITY_TURN_FAILED", + message: error instanceof Error ? error.message.slice(0, 1_000) : "Antigravity turn failed.", + retryable: false, + }, + }; + } finally { + updateListener = null; + onModeDrift = null; + wake = null; + } + }; + + return { + async identity(): Promise { + return { + mode: "persistent", + acpxRecordId: `antigravity-cli:${options.providerSessionKey}`, + backendSessionId: sessionId, + agentSessionId: sessionId, + }; + }, + async getStatus(): Promise { + return { + ...structuredClone(status), + models: { + currentModelId: currentModel, + availableModelIds: availableModelIds.length > 0 ? [...availableModelIds] : [currentModel], + }, + }; + }, + async setModel(nextModel: string): Promise { + const normalized = nextModel.trim(); + if (!normalized || normalized === currentModel) return; + await applyModelSelection( + connection, sessionId, normalized, requestTimeoutMs, readbackTimeoutMs, + selections, mergeSelections, waitForSelection, + ); + currentModel = normalized; + await writeSavedSession(options.stateDirectory, { + sessionId, + cwd: options.cwd, + model: currentModel, + readOnly: options.readOnly === true, + }).catch(() => undefined); + }, + 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 AntigravityAcpEventQueue(); + let markStarted!: () => void; + const promptStarted = new Promise(resolve => { markStarted = resolve; }); + const turn = { cancel: async (_reason?: string) => {}, result: Promise.resolve() as unknown as Promise }; + active = turn; + const onAbort = () => { void turn.cancel(); }; + input.signal?.addEventListener("abort", onAbort, { once: true }); + turn.result = runTurn(input, events, markStarted).finally(() => { + markStarted(); + events.end(); + input.signal?.removeEventListener("abort", onAbort); + if (active === turn) active = null; + }); + return { + requestId: input.requestId, + promptStarted, + events, + result: turn.result, + cancel: async () => { await turn.cancel(); }, + closeStream: async () => { events.end(); }, + }; + }, + async close(): Promise { + closed = true; + const turn = active; + if (turn) { + await turn.cancel(); + await Promise.race([ + turn.result.catch(() => undefined), + new Promise(resolve => setTimeout(resolve, dependencies.cancelGraceMs ?? DEFAULT_CANCEL_GRACE_MS)), + ]); + } + await retire(); + }, + }; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-acpx-runtime.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-acpx-runtime.test.ts index d3f271923aa..0fd8ed421a9 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-acpx-runtime.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-acpx-runtime.test.ts @@ -62,7 +62,7 @@ async function fixture(behavior: "accept" | "missing" | "mismatch" | "question" ]:null; readline.createInterface({input:process.stdin}).on('line',line=>{ const m=JSON.parse(line); - if(m.method==='initialize') send({id:m.id,result:{protocolVersion:1,agentInfo:{name:'antigravity-acp',version:'1.5.2'}, + if(m.method==='initialize') send({id:m.id,result:{protocolVersion:1,agentInfo:{name:'antigravity-acp',version:'1.5.19'}, agentCapabilities:{loadSession:true,_meta:{antigravity:{paperclipAdmission:1}}},authMethods:[]}}); else if(${JSON.stringify(behavior)}==='reload-refused'&&m.method==='session/load') send({id:m.id,error:{code:-32602, message:'Paperclip admission: managed reload requires a fresh exact content acknowledgment',data:{paperclipAdmission:'refused'}}}); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-admission.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-admission.test.ts index 4034c279215..1c536f4b973 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-admission.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-admission.test.ts @@ -1,9 +1,10 @@ import { describe, expect, it } from "vitest"; import { ANTIGRAVITY_ADMISSION_SCHEMA, ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE, AntigravityAdmissionError, AntigravitySavedStateIncompatibleError, createAntigravityAdmission } from "./antigravity-admission.js"; +import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.js"; const content = " Exact governance 🧷\n\n"; const model = "caller/model-not-in-catalog"; -const initialize = { agentInfo: { name: "antigravity-acp", version: "1.5.2" }, agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 1 } } } }; +const initialize = { agentInfo: { name: "antigravity-acp", version: ANTIGRAVITY_RUNTIME_VERSION }, agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 1 } } } }; function fixture() { const admission = createAntigravityAdmission(content, model); const guard = admission.createGuard(); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-auth-stream-order.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-auth-stream-order.test.ts index 6425d60f8fd..01031ad172d 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-auth-stream-order.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-auth-stream-order.test.ts @@ -10,157 +10,168 @@ const setup = vi.hoisted(() => ({ verify: vi.fn(), spawn: vi.fn(), close: vi.fn( vi.mock("./antigravity-installation.js", () => ({ antigravityNativeDistributionSpec: () => ({ pinned: true }) })); vi.mock("./installation-integrity.js", () => ({ verifyNativeAcpxInstallation: setup.verify })); vi.mock("./antigravity-process.js", async importOriginal => ({ - ...await importOriginal(), retireAntigravityProcess: setup.retire, + ...await importOriginal(), + retireAntigravityProcess: setup.retire, })); -import { startAntigravityBrowserLogin } from "./antigravity-auth.js"; +import { ANTIGRAVITY_CLI_TOKEN_DIR, ANTIGRAVITY_CLI_TOKEN_FILE, startAntigravityBrowserLogin } from "./antigravity-auth.js"; const clientId = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"; -const scopes = ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"]; -const authorizationUrl = "https://accounts.google.com/o/oauth2/v2/auth?" + new URLSearchParams({ client_id: clientId, response_type: "code", - redirect_uri: "http://127.0.0.1:18973/", scope: scopes.join(" "), state: "fixture_state_0123456789", code_challenge: "a".repeat(43), - code_challenge_method: "S256", access_type: "offline", prompt: "consent" }); +const scopes = [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/userinfo.email", + "https://www.googleapis.com/auth/aicode", + "openid", +]; +const authorizationUrl = "https://accounts.google.com/o/oauth2/auth?" + new URLSearchParams({ + client_id: clientId, + response_type: "code", + redirect_uri: "https://antigravity.google/oauth-callback", + scope: scopes.join(" "), + state: "fixture_state_0123456789", + code_challenge: "a".repeat(43), + code_challenge_method: "S256", + access_type: "offline", + prompt: "consent", +}); +const cliTokenJson = JSON.stringify({ + token: { + access_token: "synthetic-access-token", + token_type: "Bearer", + refresh_token: "synthetic-refresh-token", + expiry: "2099-01-01T00:00:00Z", + }, + auth_method: "consumer", +}); + const roots: string[] = []; const physicalChildren: ChildProcess[] = []; + afterEach(async () => { for (const child of physicalChildren.splice(0)) { if (child.exitCode === null && child.signalCode === null) { try { process.kill(-child.pid!, "SIGKILL"); } catch {} } } - vi.unstubAllGlobals(); vi.clearAllMocks(); + vi.unstubAllGlobals(); + vi.clearAllMocks(); await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); -type Mode = "url-first" | "result-first" | "wrong-url" | "duplicate-url" | "unexpected-prompt" | "retirement-failure" | "credential-failure" | "auth-error" | "late-wrong-url" | "late-duplicate-url"; +type Mode = "stdout-url" | "stderr-url" | "wrong-url" | "duplicate-url" | "retirement-failure" | "credential-failure" | "nonzero-exit"; + async function fixture(mode: Mode) { - const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-stream-test-"))); roots.push(home); - await mkdir(join(home, "antigravity-acp"), { mode: 0o700 }); - await writeFile(join(home, "antigravity-acp/acp_token.json"), JSON.stringify({ client_id: clientId, client_secret: "synthetic-client-secret", - refresh_token: "synthetic-refresh-token", token_uri: "https://oauth2.googleapis.com/token", scopes }), { mode: 0o600 }); - const stdout = new PassThrough(), stderr = new PassThrough(), requests: string[] = []; - const child = Object.assign(new EventEmitter(), { stdout, stderr, stdin: new Writable({ write(chunk, _encoding, done) { - const request = JSON.parse(String(chunk)); requests.push(request.method); - queueMicrotask(() => { - if (request.method === "initialize") { - stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: 1, - agentInfo: { name: "antigravity-acp", version: "1.5.2" }, agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 1 } } }, - authMethods: [{ id: "oauth-personal" }] } }) + "\n"); - } else if (request.method === "authenticate") { - const url = mode === "wrong-url" || mode === "late-wrong-url" ? "https://example.invalid/synthetic-private-marker" : authorizationUrl; - const emitUrl = () => stderr.write("Open the following link to authenticate the ACP server: " + url + "\n"); - const resultFirst = ["result-first", "late-wrong-url", "late-duplicate-url"].includes(mode); - if (!resultFirst) emitUrl(); - if (mode === "duplicate-url") emitUrl(); - if (mode === "unexpected-prompt") stdout.write(JSON.stringify({ jsonrpc: "2.0", id: 9, method: "session/prompt", params: {} }) + "\n"); - stdout.write(JSON.stringify(mode === "auth-error" - ? { jsonrpc: "2.0", id: request.id, error: { code: -32000, message: "synthetic-private-marker" } } - : { jsonrpc: "2.0", id: request.id, result: {} }) + "\n"); - if (resultFirst) queueMicrotask(() => { emitUrl(); if (mode === "late-duplicate-url") emitUrl(); }); - } else throw new Error("Unexpected session/model request"); - }); - done(); - } }) }); + const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-stream-test-"))); + roots.push(home); + await mkdir(join(home, ANTIGRAVITY_CLI_TOKEN_DIR), { mode: 0o700 }); + await writeFile(join(home, ANTIGRAVITY_CLI_TOKEN_DIR, ANTIGRAVITY_CLI_TOKEN_FILE), cliTokenJson, { mode: 0o600 }); + const stdout = new PassThrough(); + const stderr = new PassThrough(); + const child = Object.assign(new EventEmitter(), { + stdout, + stderr, + stdin: new Writable({ write(_chunk, _encoding, done) { done(); } }), + }); + setup.close.mockResolvedValue(undefined); setup.retire.mockImplementation(async (_child, closed: Promise) => { - await Promise.resolve(); child.emit("close", 0); await closed; + await Promise.resolve(); + child.emit("close", mode === "nonzero-exit" ? 1 : 0, null); + await closed; }); if (mode === "retirement-failure") setup.retire.mockImplementationOnce(async () => { throw new Error("synthetic-private-marker"); }); - setup.spawn.mockReturnValue(child); + setup.spawn.mockImplementation(() => { + queueMicrotask(() => { + const url = mode === "wrong-url" ? "https://example.invalid/synthetic-private-marker" : authorizationUrl; + const stream = mode === "stderr-url" ? stderr : stdout; + stream.write(` ${url}\n`); + if (mode === "duplicate-url") stream.write(` ${url}\n`); + if (mode === "nonzero-exit") { + stderr.write("couldn't log in: synthetic-private-marker\n"); + child.emit("close", 1, null); + } else { + child.emit("close", 0, null); + } + }); + return child; + }); setup.verify.mockResolvedValue({ openCommand: async () => ({ spawn: setup.spawn, close: setup.close }) }); const fetch = vi.fn(async (url: string) => { if (mode === "credential-failure") return new Response(null, { status: 401 }); - if (url === "https://oauth2.googleapis.com/token") return Response.json({ access_token: "synthetic-access-token", token_type: "Bearer" }); if (url === "https://www.googleapis.com/oauth2/v3/userinfo") return Response.json({ email: "person@example.test", email_verified: true }); throw new Error("Unexpected network request"); }); vi.stubGlobal("fetch", fetch); - return { home, requests, fetch }; + return { home, fetch }; } describe("Antigravity login cross-stream completion", () => { - it.each(["url-first", "result-first"] as const)("accepts the same authenticated exchange with %s delivery", async mode => { - const { home, requests, fetch } = await fixture(mode); + it.each(["stdout-url", "stderr-url"] as const)("accepts the authorization URL over %s", async mode => { + const { home, fetch } = await fixture(mode); const login = startAntigravityBrowserLogin(home); await vi.waitFor(() => expect(login.outcome).toBeDefined()); expect(login.outcome).toBe("success"); expect(login.authorizationUrl).toBe(authorizationUrl); - expect(requests).toEqual(["initialize", "authenticate"]); - expect(setup.retire).toHaveBeenCalledOnce(); expect(setup.close).toHaveBeenCalledOnce(); - expect(fetch).toHaveBeenCalledTimes(2); + expect(setup.retire).toHaveBeenCalledOnce(); + expect(setup.close).toHaveBeenCalledOnce(); + expect(fetch).toHaveBeenCalledTimes(1); await login.abort(); }); - it.each(["wrong-url", "duplicate-url", "unexpected-prompt", "retirement-failure", "credential-failure", "auth-error", "late-wrong-url", "late-duplicate-url"] as const)("keeps %s failures closed and private", async mode => { - const { home, requests, fetch } = await fixture(mode); + it.each(["wrong-url", "duplicate-url", "retirement-failure", "credential-failure", "nonzero-exit"] as const)("keeps %s failures closed and private", async mode => { + const { home, fetch } = await fixture(mode); const login = startAntigravityBrowserLogin(home); await vi.waitFor(() => expect(login.outcome).toBeDefined()); - expect(login.outcome).toBe("failure"); expect(login.error).toBe("Google sign-in did not complete. Start sign-in again."); + expect(login.outcome).toBe("failure"); + expect(login.error).toBe("Google sign-in did not complete. Start sign-in again."); expect(login.error).not.toContain("synthetic-private-marker"); - await login.abort(); expect(setup.close).toHaveBeenCalledOnce(); - expect(requests).toEqual(["initialize", "authenticate"]); + await login.abort(); + expect(setup.close).toHaveBeenCalledOnce(); expect(fetch).toHaveBeenCalledTimes(mode === "credential-failure" ? 1 : 0); - if (mode === "wrong-url" || mode === "late-wrong-url") expect(login.authorizationUrl).toBeUndefined(); + if (mode === "wrong-url") expect(login.authorizationUrl).toBeUndefined(); }); - it.each(["valid", "invalid", "duplicate"] as const)("handles a %s URL from a real child after authenticate completion and stdin EOF", async mode => { - const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-real-stream-"))); roots.push(home); + it.each(["valid", "invalid", "duplicate"] as const)("handles %s chunked URL output from a real child process", async mode => { + const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-real-stream-"))); + roots.push(home); const peer = join(home, "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], mode = process.argv[3], requests = [], events = []; -const reader = readline.createInterface({input:process.stdin}); -reader.on('line', line => { - const request = JSON.parse(line); requests.push(request.method); - fs.writeFileSync(path.join(home,'requests.json'),JSON.stringify(requests)); - if(request.method==='initialize') { - process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:request.id,result:{protocolVersion:1, - agentInfo:{name:'antigravity-acp',version:'1.5.2'},agentCapabilities:{_meta:{antigravity:{paperclipAdmission:1}}}, - authMethods:[{id:'oauth-personal'}]}})+'\\n'); - } else if(request.method==='authenticate') { - fs.mkdirSync(path.join(home,'antigravity-acp'),{mode:0o700}); - fs.writeFileSync(path.join(home,'antigravity-acp/acp_token.json'),${JSON.stringify(JSON.stringify({ client_id: clientId, - client_secret: "synthetic-client-secret", refresh_token: "synthetic-refresh-token", token_uri: "https://oauth2.googleapis.com/token", scopes }))},{mode:0o600}); - events.push('authenticate-result'); - process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:request.id,result:{}})+'\\n'); - } else throw new Error('Unexpected session/model request'); -}); -reader.on('close',()=>{ - events.push('stdin-eof'); - const url = mode==='invalid' ? 'https://example.invalid/synthetic-private-marker' : ${JSON.stringify(authorizationUrl)}; - const message = 'Open the following link to authenticate the ACP server: '+url+'\\n'; - process.stderr.write(mode==='duplicate' ? message+message : message,()=>{ - events.push('url-flushed');fs.writeFileSync(path.join(home,'events.json'),JSON.stringify(events));process.exit(0); - }); -}); +const home = process.argv[2], mode = process.argv[3]; +const url = mode === 'invalid' ? 'https://example.invalid/synthetic-private-marker' : ${JSON.stringify(authorizationUrl)}; +const line = ' ' + url + '\\n'; +process.stdout.write(line.slice(0, 30)); +setTimeout(() => { + process.stdout.write(line.slice(30)); + if (mode === 'duplicate') process.stdout.write(line); + fs.mkdirSync(path.join(home, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_DIR)}), { mode: 0o700, recursive: true }); + fs.writeFileSync(path.join(home, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_DIR)}, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_FILE)}), ${JSON.stringify(cliTokenJson)}, { mode: 0o600 }); + process.exit(0); +}, 10); `); setup.spawn.mockImplementation((_args, options) => { const child = spawn(process.execPath, [peer, home, mode], { ...options, detached: true }); - physicalChildren.push(child); return child; + physicalChildren.push(child); + return child; }); setup.close.mockResolvedValue(undefined); setup.verify.mockResolvedValue({ openCommand: async () => ({ spawn: setup.spawn, close: setup.close }) }); const realProcess = await vi.importActual("./antigravity-process.js"); setup.retire.mockImplementation(realProcess.retireAntigravityProcess); const fetch = vi.fn(async (url: string) => { - if (url === "https://oauth2.googleapis.com/token") return Response.json({ access_token: "synthetic-access-token", - refresh_token: "synthetic-rotated-refresh", token_type: "Bearer" }); if (url === "https://www.googleapis.com/oauth2/v3/userinfo") return Response.json({ email: "person@example.test", email_verified: true }); throw new Error("Unexpected network request"); }); vi.stubGlobal("fetch", fetch); + const login = startAntigravityBrowserLogin(home); await vi.waitFor(() => expect(login.outcome).toBeDefined(), { timeout: 5_000 }); expect(login.outcome).toBe(mode === "valid" ? "success" : "failure"); - expect(JSON.parse(await readFile(join(home, "events.json"), "utf8"))).toEqual(["authenticate-result", "stdin-eof", "url-flushed"]); - expect(JSON.parse(await readFile(join(home, "requests.json"), "utf8"))).toEqual(["initialize", "authenticate"]); - expect(physicalChildren.at(-1)!.exitCode).toBe(0); - expect(setup.retire).toHaveBeenCalledOnce(); expect(setup.close).toHaveBeenCalledOnce(); - expect(fetch).toHaveBeenCalledTimes(mode === "valid" ? 2 : 0); + await vi.waitFor(() => expect(setup.close).toHaveBeenCalledOnce(), { timeout: 5_000 }); + expect(fetch).toHaveBeenCalledTimes(mode === "valid" ? 1 : 0); if (mode === "valid") { expect(login.authorizationUrl).toBe(authorizationUrl); - expect(JSON.parse(await readFile(join(home, "antigravity-acp", "acp_token.json"), "utf8")).refresh_token).toBe("synthetic-rotated-refresh"); + expect(JSON.parse(await readFile(join(home, "antigravity-acp", "acp_token.json"), "utf8")).refresh_token).toBe("synthetic-refresh-token"); } else { expect(login.error).toBe("Google sign-in did not complete. Start sign-in again."); expect(login.error).not.toContain("synthetic-private-marker"); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.test.ts index 57c4d043146..79b1c00c92c 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.test.ts @@ -1,5 +1,5 @@ import { execFileSync, spawn, type ChildProcess } from "node:child_process"; -import { access, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; +import { access, mkdir, 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"; @@ -7,72 +7,165 @@ 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 { sanitizeAntigravityCredential, startAntigravityBrowserLogin, validateAntigravityAuthorizationUrl, verifyAntigravityCredential } from "./antigravity-auth.js"; +import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.js"; +import { + ANTIGRAVITY_CLI_TOKEN_DIR, + ANTIGRAVITY_CLI_TOKEN_FILE, + antigravityCliStoredTokenFromCanonical, + canonicalAntigravityCredentialFromCliToken, + sanitizeAntigravityCredential, + startAntigravityBrowserLogin, + validateAntigravityAuthorizationUrl, + verifyAntigravityCredential, +} from "./antigravity-auth.js"; const CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"; -const credential = { client_id: CLIENT_ID, client_secret: "fixture-client-secret", refresh_token: "fixture-refresh-token", token_uri: "https://oauth2.googleapis.com/token", - scopes: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"], project_id: "fixture-project" }; -function authorizationUrl() { - return "https://accounts.google.com/o/oauth2/v2/auth?" + new URLSearchParams({ client_id: CLIENT_ID, response_type: "code", redirect_uri: "http://127.0.0.1:18973/", - scope: credential.scopes.join(" "), state: "fixture_state_0123456789", code_challenge: "a".repeat(43), code_challenge_method: "S256", access_type: "offline", prompt: "consent" }); +const LEGACY_CREDENTIAL = { + client_id: CLIENT_ID, + client_secret: "fixture-client-secret", + refresh_token: "fixture-refresh-token", + token_uri: "https://oauth2.googleapis.com/token", + scopes: [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/userinfo.email", + "https://www.googleapis.com/auth/aicode", + ], + project_id: "fixture-project", +}; +const CLI_SCOPES = [ + ...LEGACY_CREDENTIAL.scopes, + "openid", + "https://www.googleapis.com/auth/userinfo.profile", + "https://www.googleapis.com/auth/cclog", + "https://www.googleapis.com/auth/experimentsandconfigs", +]; +const CONSUMER_CREDENTIAL = { + client_id: CLIENT_ID, + refresh_token: "fixture-cli-refresh-token", + token_uri: "https://oauth2.googleapis.com/token", + scopes: [...LEGACY_CREDENTIAL.scopes, "openid"], + auth_method: "consumer", +}; +const CLI_TOKEN_DOC = { + token: { + access_token: "fixture-cli-access-token", + token_type: "Bearer", + refresh_token: "fixture-cli-refresh-token", + expiry: "2099-01-01T00:00:00Z", + }, + auth_method: "consumer", +}; + +function cliAuthorizationUrl(state = "fixture_state_0123456789") { + return "https://accounts.google.com/o/oauth2/auth?" + new URLSearchParams({ + access_type: "offline", + client_id: CLIENT_ID, + code_challenge: "a".repeat(43), + code_challenge_method: "S256", + prompt: "consent", + redirect_uri: "https://antigravity.google/oauth-callback", + response_type: "code", + scope: CLI_SCOPES.join(" "), + state, + }); } -const roots: string[] = [], children: ChildProcess[] = []; + +function loopbackAuthorizationUrl(state = "fixture_state_0123456789") { + return "https://accounts.google.com/o/oauth2/v2/auth?" + new URLSearchParams({ + client_id: CLIENT_ID, + response_type: "code", + redirect_uri: "http://127.0.0.1:18973/", + scope: LEGACY_CREDENTIAL.scopes.join(" "), + state, + code_challenge: "a".repeat(43), + code_challenge_method: "S256", + access_type: "offline", + prompt: "consent", + }); +} + +const roots: string[] = []; +const children: ChildProcess[] = []; + afterEach(async () => { vi.restoreAllMocks(); - for (const child of children.splice(0)) if (child.exitCode === null && child.signalCode === null) { try { process.kill(-child.pid!, "SIGKILL"); } catch {} } + for (const child of children.splice(0)) { + if (child.exitCode === null && child.signalCode === null) { + try { process.kill(-child.pid!, "SIGKILL"); } catch {} + } + } await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); - vi.unstubAllGlobals(); vi.clearAllMocks(); + vi.unstubAllGlobals(); + vi.clearAllMocks(); }); -async function fixture(mode = "success") { - const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-login-test-"))); roots.push(home); +async function fixture(mode = "success", stateToken = "fixture_state_0123456789") { + const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-login-test-"))); + roots.push(home); const peer = join(home, "peer.cjs"); + const authUrl = cliAuthorizationUrl(stateToken); await writeFile(peer, ` const fs = require('node:fs'); const path = require('node:path'); const readline = require('node:readline'); const home = process.argv[2], mode = process.argv[3]; -const requests = []; -let deferredAuthorization = ''; -if(mode==='stubborn') { - process.on('SIGTERM',()=>{}); - const child=require('node:child_process').spawn(process.execPath,['-e',"process.on('SIGTERM',()=>{});setInterval(()=>{},1000)"],{stdio:'ignore'}); - fs.writeFileSync(path.join(home,'descendant.pid'),String(child.pid)); +if (mode === 'stubborn') { + process.on('SIGTERM', () => {}); + const child = require('node:child_process').spawn(process.execPath, ['-e', "process.on('SIGTERM',()=>{});setInterval(()=>{},1000)"], { stdio: 'ignore' }); + fs.writeFileSync(path.join(home, 'descendant.pid'), String(child.pid)); } -const reader = readline.createInterface({input:process.stdin}); +if (mode === 'exit-early') { + process.exit(1); +} +const url = mode === 'bad-url' ? 'https://example.invalid/steal' : ${JSON.stringify(authUrl)}; +const banner = 'Open this link in a browser to log in with Google:\\n\\n ' + url + '\\n\\nThen paste the authorization code, or the full URL of the page you land on, and press Enter:\\n'; +if (mode === 'stderr-url') { + process.stderr.write(banner); +} else { + process.stdout.write(banner.slice(0, 65)); + process.stdout.write(banner.slice(65)); +} +if (mode === 'duplicate-url') { + process.stdout.write(' ' + url + '\\n'); +} +if (mode === 'error') { + process.stderr.write("couldn't log in: fixture-secret-marker\\n"); + process.exit(1); +} +if (mode === 'auto-complete') { + fs.mkdirSync(path.join(home, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_DIR)}), { mode: 0o700, recursive: true }); + fs.writeFileSync(path.join(home, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_DIR)}, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_FILE)}), ${JSON.stringify(JSON.stringify(CLI_TOKEN_DOC))}, { mode: 0o600 }); + process.exit(0); +} +const reader = readline.createInterface({ input: process.stdin }); reader.on('line', line => { - const request=JSON.parse(line); requests.push(request); - fs.writeFileSync(path.join(home,'requests.json'),JSON.stringify(requests)); - if(request.method==='initialize') { - if(mode==='early-url') { process.stderr.write('Open the following link to authenticate the ACP server: '+${JSON.stringify(authorizationUrl())}+'\\n'); return; } - process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:request.id,result:{protocolVersion:1,agentInfo:{name:'antigravity-acp',version:'1.5.2'},agentCapabilities:{_meta:{antigravity:{paperclipAdmission:1}}},authMethods:[{id:'oauth-personal'}]}})+'\\n'); - } else if(request.method==='authenticate') { - const url = mode.startsWith('bad-url')||mode==='late-bad-url' ? 'https://example.invalid/steal' : ${JSON.stringify(authorizationUrl())}; - const message='Open the following link to authenticate the ACP server: '+url+'\\n'; - if(['result-first','late-bad-url','late-duplicate-url'].includes(mode)||mode.endsWith('url-after-result')) deferredAuthorization=message+(mode==='late-duplicate-url'?message:''); - else {process.stderr.write(message.slice(0,42));process.stderr.write(message.slice(42));} - if(mode==='blocked' || mode==='bad-url' || mode==='stubborn' || mode==='retained') return; - if(mode==='error') {process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:request.id,error:{code:-32000,message:'do not expose fixture-refresh-token'}})+'\\n');return;} - fs.mkdirSync(path.join(home,'antigravity-acp'),{mode:0o700}); - fs.writeFileSync(path.join(home,'antigravity-acp/acp_token.json'),${JSON.stringify(JSON.stringify(credential))},{mode:0o600}); - process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:request.id,result:{}})+'\\n'); - } else {throw new Error('inference/session request forbidden');} + fs.writeFileSync(path.join(home, 'received-stdin.txt'), line); + if (mode === 'exchange-fail') { + process.stderr.write("couldn't log in: token exchange failed: sensitive-fixture-body\\n"); + process.exit(1); + } + if (mode === 'blocked' || mode === 'bad-url' || mode === 'stubborn' || mode === 'retained') return; + const dirMode = mode === 'agy-0755-dir' ? 0o755 : 0o700; + fs.mkdirSync(path.join(home, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_DIR)}), { mode: dirMode, recursive: true }); + fs.writeFileSync(path.join(home, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_DIR)}, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_FILE)}), ${JSON.stringify(JSON.stringify(CLI_TOKEN_DOC))}, { mode: 0o600 }); + process.stdout.write('Logged in successfully.\\n'); + process.exit(0); }); -reader.on('close',()=> { - // EOF proves the client received the authenticate result before this stderr. - if(deferredAuthorization) process.stderr.write(deferredAuthorization,()=>process.exit(0)); - else if(mode==='stubborn'||mode==='retained') setInterval(()=>{},1000); - else process.exit(0); +reader.on('close', () => { + if (mode === 'stubborn' || mode === 'retained') setInterval(() => {}, 1000); + else process.exit(mode === 'blocked' ? 0 : 1); }); `); setup.verify.mockResolvedValue({ openCommand: async () => ({ spawn: setup.spawn, close: setup.close }) }); setup.spawn.mockImplementation((_args, options) => { - const child = spawn(process.execPath, [peer, home, mode], { ...options, detached: true }); children.push(child); return child; + const child = spawn(process.execPath, [peer, home, mode], { ...options, detached: true }); + children.push(child); + return child; }); return home; } -function googleIdentity(emailVerified = true) { +function googleUserinfo(emailVerified = true, expectedAccessToken = "fixture-cli-access-token") { return vi.fn().mockImplementation(async (url: string, options: RequestInit) => { if (url === "https://oauth2.googleapis.com/token") { expect(options.redirect).toBe("error"); @@ -80,18 +173,18 @@ function googleIdentity(emailVerified = true) { return new Response(JSON.stringify({ access_token: "fixture-access-token", refresh_token: "fixture-rotated-refresh", token_type: "Bearer" })); } expect(url).toBe("https://www.googleapis.com/oauth2/v3/userinfo"); - expect(options.headers).toEqual({ Authorization: "Bearer fixture-access-token" }); + expect(options.headers).toEqual({ Authorization: `Bearer ${expectedAccessToken}` }); return new Response(JSON.stringify({ email: "person@example.test", email_verified: emailVerified })); }); } -describe("Antigravity setup-only Google authentication", () => { - it.each(["network", "unverified"])("preserves an OAuth rotation when userinfo %s verification fails", async failure => { - const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-rotation-test-"))); roots.push(home); - const { mkdir } = await import("node:fs/promises"); +describe("Antigravity setup-only Google authentication (agy acp --login)", () => { + it.each(["network", "unverified"])("preserves an OAuth rotation when userinfo %s verification fails for legacy credentials", async failure => { + const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-rotation-test-"))); + 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(credential), { mode: 0o600 }); + await writeFile(token, JSON.stringify(LEGACY_CREDENTIAL), { mode: 0o600 }); const fetch = vi.fn().mockResolvedValueOnce(Response.json({ access_token: "fixture-access-token", refresh_token: "fixture-newest-rotation", token_type: "Bearer" })); if (failure === "network") fetch.mockRejectedValueOnce(new Error("fixture userinfo unavailable")); else fetch.mockResolvedValueOnce(Response.json({ email: "person@example.test", email_verified: false })); @@ -101,54 +194,172 @@ describe("Antigravity setup-only Google authentication", () => { expect(fetch).toHaveBeenCalledTimes(2); }); - // The login predicate keeps its five-second bound. Allow ten more seconds - // for fixture startup and the durable mocked credential checks on a busy CI worker. - it.each(["success", "result-first", "url-after-result"])("performs native authenticate, retires it, verifies identity, and preserves refresh rotation without repeated status network calls (%s)", async mode => { - const home = await fixture(mode), fetch = googleIdentity(); vi.stubGlobal("fetch", fetch); - const login = startAntigravityBrowserLogin(home); - await vi.waitFor(() => expect(login.outcome).toBeDefined(), { timeout: 5_000 }); - expect(login.outcome).toBe("success"); - expect(login.authorizationUrl).toBe(authorizationUrl()); - expect(JSON.parse(await readFile(join(home, "requests.json"), "utf8")).map((request: { method: string }) => request.method)).toEqual(["initialize", "authenticate"]); - expect(setup.spawn.mock.calls[0]![1].env).toMatchObject({ GEMINI_HOME: home, AGY_ACP_FORCE_FILE_STORAGE: "1", BROWSER: "/usr/bin/true" }); - expect(Object.keys(setup.spawn.mock.calls[0]![1].env).some(key => /^(?:GOOGLE_|GEMINI_API|ANTIGRAVITY_|PYTHON|NODE_OPTIONS|HTTP_PROXY)/.test(key))).toBe(false); - expect(setup.close).toHaveBeenCalledOnce(); - expect(children[0]!.exitCode).toBe(0); + 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).refresh_token).toBe("fixture-rotated-refresh"); - expect(JSON.parse(await readFile(join(home, "antigravity-acp/acp_token.json"), "utf8")).refresh_token).toBe("fixture-rotated-refresh"); - expect(fetch).toHaveBeenCalledTimes(2); - await login.abort(); - // Runtime verification outside a live browser attempt must not retain a - // credential indefinitely in the browser status cache. - await verifyAntigravityCredential(home); - await verifyAntigravityCredential(home); - expect(fetch).toHaveBeenCalledTimes(6); + 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.each(["error", "bad-url", "early-url", "late-bad-url", "late-duplicate-url", "bad-url-after-result"])("rejects %s without leaking provider text or calling Google", async mode => { - const home = await fixture(mode), fetch = vi.fn(); vi.stubGlobal("fetch", fetch); + 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); + const fetch = googleUserinfo(true); + vi.stubGlobal("fetch", fetch); + + const login = startAntigravityBrowserLogin(home); + await vi.waitFor(() => expect(login.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 }); + expect(login.authorizationUrl).toBe(cliAuthorizationUrl(stateToken)); + expect(setup.spec).toHaveBeenCalledWith(process.platform, process.arch, ["--login", "--gemini-dir", home, "--disable-telemetry"]); + expect(setup.spawn.mock.calls[0]![1].env).toMatchObject({ + GEMINI_HOME: home, + AGY_ACP_FORCE_FILE_STORAGE: "1", + AGY_CLI_FORCE_FILE_TOKEN_STORAGE: "1", + AGY_CLI_DISABLE_AUTO_UPDATE: "1", + BROWSER: "/usr/bin/true", + }); + expect(Object.keys(setup.spawn.mock.calls[0]![1].env).some(key => /^(?:GOOGLE_|GEMINI_API|ANTIGRAVITY_|PYTHON|NODE_OPTIONS|HTTP_PROXY)/.test(key))).toBe(false); + + const uniqueCode = `4/0valid-cli-code-${Date.now()}`; + const pasted = `https://antigravity.google/oauth-callback?state=${encodeURIComponent(stateToken)}&code=${encodeURIComponent(uniqueCode)}&scope=email&extra=ignored`; + await login.submitRedirect!(pasted); + expect(login.submitRedirect).toBeUndefined(); + await vi.waitFor(() => expect(login.outcome).toBe("success"), { timeout: 5_000 }); + + expect(await readFile(join(home, "received-stdin.txt"), "utf8")).toBe( + `https://antigravity.google/oauth-callback?state=${encodeURIComponent(stateToken)}&code=${encodeURIComponent(uniqueCode)}`, + ); + expect(setup.close).toHaveBeenCalledOnce(); + expect(children[0]!.exitCode).toBe(0); + // CLI token file is cleaned up after conversion to canonical acp_token.json. + await expect(access(join(home, ANTIGRAVITY_CLI_TOKEN_DIR, ANTIGRAVITY_CLI_TOKEN_FILE))).rejects.toMatchObject({ code: "ENOENT" }); + const canonical = JSON.parse(await readFile(join(home, "antigravity-acp", "acp_token.json"), "utf8")); + expect(canonical).toEqual(CONSUMER_CREDENTIAL); + + // Cached verification avoids redundant network calls while the browser session is open. + const verified = await verifyAntigravityCredential(home); + expect(verified.accountEmail).toBe("person@example.test"); + expect(JSON.parse(verified.credential)).toEqual(CONSUMER_CREDENTIAL); + expect(fetch).toHaveBeenCalledTimes(1); + + await login.abort(); + }, 15_000); + + it("also accepts a raw pasted authorization code on stdin", async () => { + const stateToken = `rawcode_state_${Date.now()}`; + const home = await fixture("success", stateToken); + vi.stubGlobal("fetch", googleUserinfo(true)); + + const login = startAntigravityBrowserLogin(home); + await vi.waitFor(() => expect(login.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 }); + const rawCode = `4/0raw-pasted-code-${Date.now()}`; + await login.submitRedirect!(rawCode); + await vi.waitFor(() => expect(login.outcome).toBe("success"), { timeout: 5_000 }); + expect(await readFile(join(home, "received-stdin.txt"), "utf8")).toBe(rawCode); + await login.abort(); + }, 15_000); + + it("pre-creates antigravity-cli with 0700 so agy's 0755 os.MkdirAll default cannot break token readback", async () => { + const stateToken = `dirmode_state_${Date.now()}`; + const home = await fixture("agy-0755-dir", stateToken); + vi.stubGlobal("fetch", googleUserinfo(true)); + + const login = startAntigravityBrowserLogin(home); + await vi.waitFor(() => expect(login.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 }); + const rawCode = `4/0dirmode-code-${Date.now()}`; + await login.submitRedirect!(rawCode); + await vi.waitFor(() => expect(login.outcome).toBe("success"), { timeout: 5_000 }); + const canonical = JSON.parse(await readFile(join(home, "antigravity-acp", "acp_token.json"), "utf8")); + expect(canonical).toEqual(CONSUMER_CREDENTIAL); + await login.abort(); + }, 15_000); + + it.each(["error", "bad-url", "duplicate-url"])("rejects %s without leaking provider text or calling Google", async mode => { + const home = await fixture(mode); + const fetch = vi.fn(); + vi.stubGlobal("fetch", fetch); const login = startAntigravityBrowserLogin(home); await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 }); await vi.waitFor(() => expect(setup.close).toHaveBeenCalledOnce(), { timeout: 5_000 }); expect(login.error).not.toContain("fixture"); - if (mode.startsWith("bad-url") || ["early-url", "late-bad-url"].includes(mode)) expect(login.authorizationUrl).toBeUndefined(); + if (mode === "bad-url") expect(login.authorizationUrl).toBeUndefined(); expect(fetch).not.toHaveBeenCalled(); + await login.abort(); }); - it("abort retires a waiting native flow without session requests", async () => { - const home = await fixture("blocked"), fetch = vi.fn(); vi.stubGlobal("fetch", fetch); + it("abort retires a waiting native flow cleanly", async () => { + const home = await fixture("blocked"); + const fetch = vi.fn(); + vi.stubGlobal("fetch", fetch); const login = startAntigravityBrowserLogin(home); await vi.waitFor(() => expect(login.authorizationUrl).toBeDefined()); - login.abort(); - await vi.waitFor(() => expect(setup.close).toHaveBeenCalledOnce(), { timeout: 5_000 }); - expect(login.outcome).toBe("failure"); expect(fetch).not.toHaveBeenCalled(); + await login.abort(); + expect(setup.close).toHaveBeenCalledOnce(); + expect(login.outcome).toBe("failure"); + expect(fetch).not.toHaveBeenCalled(); expect(children[0]!.exitCode).toBe(0); }); it("abort waits for SIGKILL retirement of a login and inherited descendant that ignore EOF and SIGTERM", async () => { - const home = await fixture("stubborn"); vi.stubGlobal("fetch", vi.fn()); + const home = await fixture("stubborn"); + vi.stubGlobal("fetch", vi.fn()); const login = startAntigravityBrowserLogin(home); await vi.waitFor(() => expect(login.authorizationUrl).toBeDefined()); const descendant = (await readFile(join(home, "descendant.pid"), "utf8")).trim(); @@ -161,38 +372,48 @@ describe("Antigravity setup-only Google authentication", () => { }); it("keeps abort, the command lease and the private home owned through uncertain retirement until the actual child exits", async () => { - const home = await fixture("retained"); vi.stubGlobal("fetch", vi.fn()); + const home = await fixture("retained"); + vi.stubGlobal("fetch", vi.fn()); const login = startAntigravityBrowserLogin(home); await vi.waitFor(() => expect(login.authorizationUrl).toBeDefined()); - const child = children[0]!, realKill = process.kill.bind(process); + const child = children[0]!; + const realKill = process.kill.bind(process); let blockProof = true; vi.spyOn(process, "kill").mockImplementation((pid, signal) => { if (blockProof && pid === -child.pid! && signal === 0) throw Object.assign(new Error("controlled process-state uncertainty"), { code: "EACCES" }); return realKill(pid, signal); }); - const stopped = login.abort(), releaseHome = vi.fn(() => rm(home, { recursive: true, force: true })); + const stopped = login.abort(); + const releaseHome = vi.fn(() => rm(home, { recursive: true, force: true })); const cleaned = stopped.then(releaseHome); await vi.waitFor(() => expect(login.error).toContain("still stopping"), { timeout: 5_000 }); - expect(child.exitCode).toBeNull(); expect(child.signalCode).toBeNull(); - expect(setup.close).not.toHaveBeenCalled(); expect(releaseHome).not.toHaveBeenCalled(); + expect(child.exitCode).toBeNull(); + expect(child.signalCode).toBeNull(); + expect(setup.close).not.toHaveBeenCalled(); + expect(releaseHome).not.toHaveBeenCalled(); await expect(access(home)).resolves.toBeUndefined(); blockProof = false; realKill(-child.pid!, "SIGKILL"); await cleaned; expect(child.signalCode).toBe("SIGKILL"); - expect(setup.close).toHaveBeenCalledOnce(); expect(releaseHome).toHaveBeenCalledOnce(); + expect(setup.close).toHaveBeenCalledOnce(); + expect(releaseHome).toHaveBeenCalledOnce(); await expect(access(home)).rejects.toMatchObject({ code: "ENOENT" }); }); it("does not accept an unverified Google account after native authentication", async () => { - const home = await fixture(); vi.stubGlobal("fetch", googleIdentity(false)); + const home = await fixture("auto-complete"); + vi.stubGlobal("fetch", googleUserinfo(false)); const login = startAntigravityBrowserLogin(home); await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 }); expect(setup.close).toHaveBeenCalledOnce(); + await login.abort(); }); it("reports a missing server runtime plainly instead of an unfinished sign-in", async () => { - const home = await fixture(); const fetch = vi.fn(); vi.stubGlobal("fetch", fetch); + const home = await fixture(); + const fetch = vi.fn(); + vi.stubGlobal("fetch", fetch); setup.verify.mockRejectedValueOnce(Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })); const onFailure = vi.fn(); const login = startAntigravityBrowserLogin(home, { onFailure }); @@ -202,13 +423,12 @@ describe("Antigravity setup-only Google authentication", () => { expect(login.authorizationUrl).toBeUndefined(); expect(setup.spawn).not.toHaveBeenCalled(); expect(fetch).not.toHaveBeenCalled(); + await login.abort(); }); it("reports a runtime that exits before showing a sign-in link as a failed start", async () => { - const home = await fixture(); vi.stubGlobal("fetch", vi.fn()); - setup.spawn.mockImplementationOnce((_args, options) => { - const child = spawn(process.execPath, ["-e", "process.exit(1)"], { ...options, detached: true }); children.push(child); return child; - }); + const home = await fixture("exit-early"); + vi.stubGlobal("fetch", vi.fn()); const onFailure = vi.fn(); const login = startAntigravityBrowserLogin(home, { onFailure }); await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 }); @@ -216,10 +436,12 @@ describe("Antigravity setup-only Google authentication", () => { expect(login.error).toBe("Google sign-in could not start on this server. Start sign-in again."); expect(onFailure).toHaveBeenCalledExactlyOnceWith("start_failed"); expect(login.authorizationUrl).toBeUndefined(); + await login.abort(); }); it("reports a resolver failure as an unavailable runtime", async () => { - const home = await fixture(); vi.stubGlobal("fetch", vi.fn()); + const home = await fixture(); + vi.stubGlobal("fetch", vi.fn()); setup.spec.mockImplementationOnce(() => { throw new Error("Antigravity has no admitted complete runtime closure for fixture"); }); const onFailure = vi.fn(); const login = startAntigravityBrowserLogin(home, { onFailure }); @@ -227,19 +449,23 @@ describe("Antigravity setup-only Google authentication", () => { expect(onFailure).toHaveBeenCalledExactlyOnceWith("runtime_unavailable"); expect(login.error).toContain("does not have the current Google Antigravity runtime"); expect(login.error).not.toContain("Start sign-in again"); + await login.abort(); }); it("reports a failure after the runtime starts as an incomplete sign-in", async () => { - const home = await fixture("error"); vi.stubGlobal("fetch", vi.fn()); + const home = await fixture("error"); + vi.stubGlobal("fetch", vi.fn()); const onFailure = vi.fn(); const login = startAntigravityBrowserLogin(home, { onFailure }); await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 }); expect(onFailure).toHaveBeenCalledExactlyOnceWith("login_incomplete"); expect(login.error).toBe("Google sign-in did not complete. Start sign-in again."); + await login.abort(); }); it("reports a cancelled attempt as aborted", async () => { - const home = await fixture("blocked"); vi.stubGlobal("fetch", vi.fn()); + const home = await fixture("blocked"); + vi.stubGlobal("fetch", vi.fn()); const onFailure = vi.fn(); const login = startAntigravityBrowserLogin(home, { onFailure }); await vi.waitFor(() => expect(login.authorizationUrl).toBeDefined()); @@ -248,215 +474,236 @@ describe("Antigravity setup-only Google authentication", () => { expect(login.outcome).toBe("failure"); }); - it("requires the pinned OAuth client and token destination and strips unrelated native fields", () => { - expect(JSON.parse(sanitizeAntigravityCredential(JSON.stringify({ ...credential, endpoint: "https://example.invalid", access_token: "discard" })))).toEqual(credential); - expect(sanitizeAntigravityCredential(JSON.stringify({ ...credential, scopes: [...credential.scopes].reverse() }))).toBe(sanitizeAntigravityCredential(JSON.stringify(credential))); - expect(() => sanitizeAntigravityCredential(JSON.stringify({ ...credential, token_uri: "https://example.invalid/token" }))).toThrow("Invalid Antigravity credential"); - expect(() => sanitizeAntigravityCredential(JSON.stringify({ ...credential, client_id: "another-client" }))).toThrow("Invalid Antigravity credential"); - expect(() => sanitizeAntigravityCredential(JSON.stringify({ ...credential, scopes: ["openid"] }))).toThrow("Invalid Antigravity credential"); + it("sanitizes both legacy client_secret credentials and consumer CLI credentials, and projects to CLI format", () => { + expect(JSON.parse(sanitizeAntigravityCredential(JSON.stringify({ ...LEGACY_CREDENTIAL, endpoint: "https://example.invalid", access_token: "discard" })))).toEqual(LEGACY_CREDENTIAL); + expect(sanitizeAntigravityCredential(JSON.stringify({ ...LEGACY_CREDENTIAL, scopes: [...LEGACY_CREDENTIAL.scopes].reverse() }))).toBe(sanitizeAntigravityCredential(JSON.stringify(LEGACY_CREDENTIAL))); + expect(JSON.parse(sanitizeAntigravityCredential(JSON.stringify({ ...CONSUMER_CREDENTIAL, extra: "drop" })))).toEqual(CONSUMER_CREDENTIAL); + expect(() => sanitizeAntigravityCredential(JSON.stringify({ ...LEGACY_CREDENTIAL, client_secret: undefined }))).toThrow("Invalid Antigravity credential"); + expect(() => sanitizeAntigravityCredential(JSON.stringify({ ...LEGACY_CREDENTIAL, token_uri: "https://example.invalid/token" }))).toThrow("Invalid Antigravity credential"); + expect(() => sanitizeAntigravityCredential(JSON.stringify({ ...LEGACY_CREDENTIAL, client_id: "another-client" }))).toThrow("Invalid Antigravity credential"); + expect(() => sanitizeAntigravityCredential(JSON.stringify({ ...LEGACY_CREDENTIAL, scopes: ["openid"] }))).toThrow("Invalid Antigravity credential"); + + const projected = JSON.parse(antigravityCliStoredTokenFromCanonical(JSON.stringify(LEGACY_CREDENTIAL))); + expect(projected).toEqual({ + token: { + access_token: "expired", + token_type: "Bearer", + refresh_token: LEGACY_CREDENTIAL.refresh_token, + expiry: "2000-01-01T00:00:00Z", + }, + auth_method: "consumer", + }); + + const converted = canonicalAntigravityCredentialFromCliToken(JSON.stringify(CLI_TOKEN_DOC)); + expect(JSON.parse(converted.credential)).toEqual(CONSUMER_CREDENTIAL); + expect(converted.accessToken).toBe("fixture-cli-access-token"); + + const merged = canonicalAntigravityCredentialFromCliToken(JSON.stringify(CLI_TOKEN_DOC), JSON.stringify(LEGACY_CREDENTIAL)); + expect(JSON.parse(merged.credential)).toEqual({ ...LEGACY_CREDENTIAL, refresh_token: "fixture-cli-refresh-token" }); }); - it("requires Google PKCE and a numeric loopback redirect", () => { - expect(validateAntigravityAuthorizationUrl(authorizationUrl())).toBe(authorizationUrl()); - for (const url of [authorizationUrl().replace("accounts.google.com", "example.invalid"), authorizationUrl().replace("S256", "plain"), authorizationUrl().replace("127.0.0.1", "localhost"), authorizationUrl() + "&state=duplicate"]) { + it("validates Google PKCE authorization URLs for both antigravity.google callback and loopback redirects", () => { + expect(validateAntigravityAuthorizationUrl(cliAuthorizationUrl())).toBe(cliAuthorizationUrl()); + expect(validateAntigravityAuthorizationUrl(loopbackAuthorizationUrl())).toBe(loopbackAuthorizationUrl()); + for (const url of [ + cliAuthorizationUrl().replace("accounts.google.com", "example.invalid"), + cliAuthorizationUrl().replace("S256", "plain"), + cliAuthorizationUrl().replace("antigravity.google", "evil.example"), + loopbackAuthorizationUrl().replace("127.0.0.1", "localhost"), + cliAuthorizationUrl() + "&state=duplicate", + ]) { expect(() => validateAntigravityAuthorizationUrl(url)).toThrow(); } }); - async function loopbackFixture(responseStatus = 200) { - const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-loopback-test-"))); roots.push(home); - const peer = join(home, "loopback-peer.cjs"); - await writeFile(peer, ` -const fs = require('node:fs'); -const http = require('node:http'); -const path = require('node:path'); -const readline = require('node:readline'); -const home = process.argv[2]; -const statusCode = Number(process.argv[3] || 200); -const received = []; -const state = 'loopback_state_0123456789_' + Math.random().toString(36).slice(2, 10); -let server; -const reader = readline.createInterface({ input: process.stdin }); -reader.on('line', line => { - const request = JSON.parse(line); - if (request.method === 'initialize') { - process.stdout.write(JSON.stringify({ - jsonrpc: '2.0', id: request.id, - result: { protocolVersion: 1, agentInfo: { name: 'antigravity-acp', version: '1.5.2' }, agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 1 } } }, authMethods: [{ id: 'oauth-personal' }] }, - }) + '\\n'); - } else if (request.method === 'authenticate') { - server = http.createServer((req, res) => { - received.push({ method: req.method, url: req.url }); - fs.writeFileSync(path.join(home, 'loopback-requests.json'), JSON.stringify(received)); - res.statusCode = statusCode; - res.setHeader('Content-Type', 'text/plain'); - res.end(statusCode === 200 ? 'Authentication complete.' : 'sensitive-loopback-error-body'); - if (statusCode === 200) { - server.close(() => { - fs.mkdirSync(path.join(home, 'antigravity-acp'), { mode: 0o700 }); - fs.writeFileSync(path.join(home, 'antigravity-acp/acp_token.json'), ${JSON.stringify(JSON.stringify(credential))}, { mode: 0o600 }); - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result: {} }) + '\\n'); - }); - } - }); - server.listen(0, '127.0.0.1', () => { - const port = server.address().port; - const params = new URLSearchParams({ - client_id: ${JSON.stringify(CLIENT_ID)}, - response_type: 'code', - redirect_uri: 'http://127.0.0.1:' + port + '/', - scope: ${JSON.stringify(credential.scopes.join(" "))}, - state, - code_challenge: 'a'.repeat(43), - code_challenge_method: 'S256', - access_type: 'offline', - prompt: 'consent', - }); - process.stderr.write('Open the following link to authenticate the ACP server: https://accounts.google.com/o/oauth2/v2/auth?' + params.toString() + '\\n'); - }); - } -}); -reader.on('close', () => { - if (server) server.close(() => process.exit(0)); - else process.exit(0); -}); -`); - setup.verify.mockResolvedValue({ openCommand: async () => ({ spawn: setup.spawn, close: setup.close }) }); - setup.spawn.mockImplementation((_args, options) => { - const child = spawn(process.execPath, [peer, home, String(responseStatus)], { ...options, detached: true }); children.push(child); return child; - }); - return home; - } - - function stubGoogleAllowLoopback() { - const realFetch = globalThis.fetch; - const googleFetch = googleIdentity(); - const wrapped = vi.fn().mockImplementation(async (input: string | URL | Request, init?: RequestInit) => { - const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; - if (url.startsWith("http://127.0.0.1:")) return realFetch(input, init); - return googleFetch(url, init ?? {}); - }); - vi.stubGlobal("fetch", wrapped); - return { wrapped, googleFetch }; - } - - it("relays a validated loopback redirect URL to the local ACP listener and completes sign-in", async () => { - const home = await loopbackFixture(200); - const { wrapped } = stubGoogleAllowLoopback(); + it("rejects bad callback pastes without burning the attempt, and rejects reused codes, second submissions, and 5th bad paste", async () => { + const state1 = `badpaste_state_1_${Date.now()}`; + const home = await fixture("success", state1); + vi.stubGlobal("fetch", googleUserinfo(true)); const login = startAntigravityBrowserLogin(home); await vi.waitFor(() => expect(login.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 }); - const parsedAuth = new URL(login.authorizationUrl!); - const redirectUri = parsedAuth.searchParams.get("redirect_uri")!; - const expectedState = parsedAuth.searchParams.get("state")!; - const uniqueCode = `4/0valid-relay-code-${Date.now()}`; - const pasted = `${redirectUri}?state=${encodeURIComponent(expectedState)}&code=${encodeURIComponent(uniqueCode)}&scope=email&extra=ignored`; + const redirectUri = "https://antigravity.google/oauth-callback"; - await login.submitRedirect!(pasted); - expect(login.submitRedirect).toBeUndefined(); - await vi.waitFor(() => expect(login.outcome).toBe("success"), { timeout: 5_000 }); - const received = JSON.parse(await readFile(join(home, "loopback-requests.json"), "utf8")) as Array<{ method: string; url: string }>; - expect(received).toEqual([{ - method: "GET", - url: `/?state=${encodeURIComponent(expectedState)}&code=${encodeURIComponent(uniqueCode)}`, - }]); - expect(wrapped).toHaveBeenCalledWith( - `${redirectUri}?state=${encodeURIComponent(expectedState)}&code=${encodeURIComponent(uniqueCode)}`, - expect.objectContaining({ method: "GET", redirect: "manual" }), - ); - await login.abort(); - }); - - it("rejects bad redirect pastes without burning the loopback listener, and rejects reused codes and second submissions", async () => { - const home = await loopbackFixture(200); - stubGoogleAllowLoopback(); - const login = startAntigravityBrowserLogin(home); - await vi.waitFor(() => expect(login.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 }); - const parsedAuth = new URL(login.authorizationUrl!); - const redirectUri = parsedAuth.searchParams.get("redirect_uri")!; - const expectedState = parsedAuth.searchParams.get("state")!; - const port = Number(new URL(redirectUri).port); - - // Wrong state, wrong port/host/protocol/pathname, duplicate params, error param, oversized, control chars. - const invalidInputs = [ + const firstFourBad = [ `${redirectUri}?state=wrong_state_canary_999&code=secret-code-canary`, - `http://127.0.0.1:${port === 65535 ? port - 1 : port + 1}/?state=${expectedState}&code=secret-code-canary`, - `http://localhost:${port}/?state=${expectedState}&code=secret-code-canary`, - `https://127.0.0.1:${port}/?state=${expectedState}&code=secret-code-canary`, - `${redirectUri}callback?state=${expectedState}&code=secret-code-canary`, - `http://user:pass@127.0.0.1:${port}/?state=${expectedState}&code=secret-code-canary`, - `${redirectUri}?state=${expectedState}&code=secret-code-canary#frag`, - `${redirectUri}?state=${expectedState}&state=${expectedState}&code=secret-code-canary`, - `${redirectUri}?state=${expectedState}&code=a&code=b`, - `${redirectUri}?error=access_denied&error_description=do-not-echo-canary&state=${expectedState}`, - `${redirectUri}?state=${expectedState}&code=${"c".repeat(2049)}`, - `${redirectUri}?state=${expectedState}&code=bad\ncode`, - `${redirectUri}?state=${expectedState}&code=${"x".repeat(4097)}`, + `https://evil.example/oauth-callback?state=${state1}&code=secret-code-canary`, + `http://antigravity.google/oauth-callback?state=${state1}&code=secret-code-canary`, + `${redirectUri}/extra?state=${state1}&code=secret-code-canary`, ]; - - // Check first 4 invalid pastes stay retryable without touching the loopback server or leaking secrets. - for (const bad of invalidInputs.slice(0, 4)) { + for (const bad of firstFourBad) { const err = await login.submitRedirect!(bad).catch((e: unknown) => e); expect(err).toBeInstanceOf(Error); if (!(err instanceof Error)) throw new Error("Expected redirect rejection"); - expect(err.message).not.toContain(expectedState); + expect(err.message).not.toContain(state1); expect(err.message).not.toContain("secret-code-canary"); expect(err.message).not.toContain("wrong_state_canary"); expect(login.submitRedirect).toBeTypeOf("function"); } - await expect(access(join(home, "loopback-requests.json"))).rejects.toMatchObject({ code: "ENOENT" }); + await expect(access(join(home, "received-stdin.txt"))).rejects.toMatchObject({ code: "ENOENT" }); - // Valid paste still succeeds after 4 bad pastes. const usedCode = `4/0single-use-code-${Date.now()}`; const submitRef = login.submitRedirect!; - await submitRef(`${redirectUri}?state=${expectedState}&code=${usedCode}`); - // Second submission on the consumed handler is rejected immediately. - await expect(submitRef(`${redirectUri}?state=${expectedState}&code=another-code`)).rejects.toThrow("can no longer accept"); + await submitRef(`${redirectUri}?state=${state1}&code=${usedCode}`); + await expect(submitRef(`${redirectUri}?state=${state1}&code=another-code`)).rejects.toThrow("can no longer accept"); await vi.waitFor(() => expect(login.outcome).toBe("success"), { timeout: 5_000 }); await login.abort(); - // Check remaining invalid shapes + reused code on a fresh attempt, plus the 5-attempt cap. - const home2 = await loopbackFixture(200); - stubGoogleAllowLoopback(); + // Fresh attempt: check remaining invalid shapes + reused code + 5-attempt cap. + const state2 = `badpaste_state_2_${Date.now()}`; + const home2 = await fixture("success", state2); + vi.stubGlobal("fetch", googleUserinfo(true)); const login2 = startAntigravityBrowserLogin(home2); await vi.waitFor(() => expect(login2.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 }); - const parsedAuth2 = new URL(login2.authorizationUrl!); - const redirectUri2 = parsedAuth2.searchParams.get("redirect_uri")!; - const expectedState2 = parsedAuth2.searchParams.get("state")!; - const port2 = Number(new URL(redirectUri2).port); for (const bad of [ - `${redirectUri2}?error=access_denied&error_description=do-not-echo-canary&state=${expectedState2}`, - `${redirectUri2}?state=${expectedState2}&code=${usedCode}`, - `${redirectUri2}?state=${expectedState2}&state=${expectedState2}&code=unique-1`, - `http://user:pass@127.0.0.1:${port2}/?state=${expectedState2}&code=unique-2`, + `${redirectUri}?error=access_denied&error_description=do-not-echo-canary&state=${state2}`, + `${redirectUri}?state=${state2}&code=${usedCode}`, + `${redirectUri}?state=${state2}&state=${state2}&code=unique-1`, + `https://user:pass@antigravity.google/oauth-callback?state=${state2}&code=unique-2`, ]) { const err = await login2.submitRedirect!(bad).catch((e: unknown) => e); expect(err).toBeInstanceOf(Error); if (!(err instanceof Error)) throw new Error("Expected redirect rejection"); expect(err.message).not.toContain("do-not-echo-canary"); expect(err.message).not.toContain(usedCode); - expect(err.message).not.toContain(expectedState2); + expect(err.message).not.toContain(state2); } - // 5th bad paste terminates the attempt cleanly. - await expect(login2.submitRedirect!(`${redirectUri2}?state=${expectedState2}&code=${"c".repeat(2049)}`)).rejects.toThrow("Too many invalid"); + await expect(login2.submitRedirect!(`${redirectUri}?state=${state2}&code=${"c".repeat(2049)}`)).rejects.toThrow("Too many invalid"); expect(login2.submitRedirect).toBeUndefined(); await vi.waitFor(() => expect(login2.outcome).toBe("failure"), { timeout: 5_000 }); - await expect(access(join(home2, "loopback-requests.json"))).rejects.toMatchObject({ code: "ENOENT" }); + await expect(access(join(home2, "received-stdin.txt"))).rejects.toMatchObject({ code: "ENOENT" }); await login2.abort(); }); - it("fails cleanly without leaking body when the loopback listener returns non-200", async () => { - const home = await loopbackFixture(500); - stubGoogleAllowLoopback(); + it("fails cleanly without leaking provider error output when token exchange exits non-zero", async () => { + const state = `exchange_fail_${Date.now()}`; + const home = await fixture("exchange-fail", state); + vi.stubGlobal("fetch", vi.fn()); const login = startAntigravityBrowserLogin(home); await vi.waitFor(() => expect(login.submitRedirect).toBeTypeOf("function"), { timeout: 5_000 }); - const parsedAuth = new URL(login.authorizationUrl!); - const redirectUri = parsedAuth.searchParams.get("redirect_uri")!; - const expectedState = parsedAuth.searchParams.get("state")!; - const err = await login.submitRedirect!(`${redirectUri}?state=${expectedState}&code=4/0non-200-code-${Date.now()}`).catch((e: unknown) => e); - expect(err).toBeInstanceOf(Error); - if (!(err instanceof Error)) throw new Error("Expected redirect rejection"); - expect(err.message).not.toContain("sensitive-loopback-error-body"); + await login.submitRedirect!(`4/0exchange-fail-code-${Date.now()}`); await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 }); + expect(login.error).not.toContain("sensitive-fixture-body"); await login.abort(); }); + + it("carries a rotated CLI refresh token into the agy fallback instead of overwriting it with stale acp_token.json", async () => { + const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-carry-rotated-"))); + roots.push(home); + await mkdir(join(home, "antigravity-acp"), { mode: 0o700 }); + await mkdir(join(home, ANTIGRAVITY_CLI_TOKEN_DIR), { mode: 0o700 }); + const token = join(home, "antigravity-acp", "acp_token.json"); + const cliToken = join(home, ANTIGRAVITY_CLI_TOKEN_DIR, ANTIGRAVITY_CLI_TOKEN_FILE); + // Stale canonical credential still holds the old refresh token, while a leftover CLI file holds a newer rotated one with an expired access token. + await writeFile(token, JSON.stringify({ ...CONSUMER_CREDENTIAL, refresh_token: "stale-old-refresh" }), { mode: 0o600 }); + await writeFile(cliToken, JSON.stringify({ + token: { access_token: "expired", token_type: "Bearer", refresh_token: "newer-rotated-refresh", expiry: "2000-01-01T00:00:00Z" }, + auth_method: "consumer", + }), { mode: 0o600 }); + + const peer = join(home, "carry-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 cliPath = path.join(home, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_DIR)}, ${JSON.stringify(ANTIGRAVITY_CLI_TOKEN_FILE)}); + const staged = JSON.parse(fs.readFileSync(cliPath, 'utf8')); + // Must receive the newer rotated refresh token, never the stale canonical token. + if (staged.token.refresh_token !== 'newer-rotated-refresh') process.exit(3); + fs.writeFileSync(cliPath, JSON.stringify({ + token: { access_token: 'fresh-access-after-carry', token_type: 'Bearer', refresh_token: 'newer-rotated-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-carry' } }) + '\\n'); + } +}); +`); + 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; + }); + vi.stubGlobal("fetch", googleUserinfo(true, "fresh-access-after-carry")); + + const verified = await verifyAntigravityCredential(home); + expect(verified.accountEmail).toBe("person@example.test"); + expect(JSON.parse(verified.credential).refresh_token).toBe("newer-rotated-refresh"); + expect(JSON.parse(await readFile(token, "utf8")).refresh_token).toBe("newer-rotated-refresh"); + }); + + it("retains consumer refresh process ownership and prevents overlapping verifications until shutdown is confirmed", async () => { + const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-retain-refresh-"))); + roots.push(home); + await mkdir(join(home, "antigravity-acp"), { mode: 0o700 }); + await writeFile(join(home, "antigravity-acp", "acp_token.json"), JSON.stringify(CONSUMER_CREDENTIAL), { mode: 0o600 }); + + const peer = join(home, "stubborn-refresh-peer.cjs"); + await writeFile(peer, ` +const readline = require('node:readline'); +process.on('SIGTERM', () => {}); +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') { + process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id, result: { sessionId: 'sess-stubborn' } }) + '\\n'); + } +}); +setInterval(() => {}, 1000); +`); + 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; + }); + vi.stubGlobal("fetch", googleUserinfo(true)); + + const realKill = process.kill.bind(process); + let blockProof = true; + const killSpy = vi.spyOn(process, "kill").mockImplementation((pid, signal) => { + const child = children[0]; + if (blockProof && child?.pid && pid === -child.pid && signal === 0) { + throw Object.assign(new Error("controlled process-state uncertainty"), { code: "EACCES" }); + } + return realKill(pid, signal); + }); + try { + await expect(verifyAntigravityCredential(home)).rejects.toThrow(); + expect(setup.spawn).toHaveBeenCalledTimes(1); + // Command lease MUST stay open while child retirement is unconfirmed. + expect(setup.close).not.toHaveBeenCalled(); + + // An overlapping retry must wait on retained cleanup rather than spawning a second CLI. + const retryAbort = new AbortController(); + setTimeout(() => retryAbort.abort(new Error("retry-aborted")), 150); + await expect(verifyAntigravityCredential(home, { signal: retryAbort.signal })).rejects.toThrow("retry-aborted"); + expect(setup.spawn).toHaveBeenCalledTimes(1); + + // Once retirement can be confirmed, retained cleanup finishes and closes the lease. + blockProof = false; + realKill(-children[0]!.pid!, "SIGKILL"); + await vi.waitFor(() => expect(setup.close).toHaveBeenCalledTimes(1), { timeout: 5_000 }); + } finally { + blockProof = false; + if (children[0]?.pid) { + try { realKill(-children[0].pid, "SIGKILL"); } catch {} + } + killSpy.mockRestore(); + } + }, 15_000); }); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts index 918875247fa..27713c198a3 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts @@ -1,31 +1,42 @@ import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { constants } from "node:fs"; -import { lstat, open, readlink, rename, rm } from "node:fs/promises"; +import { lstat, mkdir, open, readlink, rename, rm, writeFile } from "node:fs/promises"; import { createHash, randomUUID, timingSafeEqual } from "node:crypto"; import { join } from "node:path"; import { StringDecoder } from "node:string_decoder"; import { antigravityPrivateEnvironment, checkAntigravityPrivateHome, retireAntigravityProcess } from "./antigravity-process.js"; import { antigravityNativeDistributionSpec } from "./antigravity-installation.js"; -import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.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"; const TOKEN_URI = "https://oauth2.googleapis.com/token"; const SCOPES = ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"]; -const AUTH_PREFIX = "Open the following link to authenticate the ACP server: "; +const EXTRA_ALLOWED_SCOPES = [ + "openid", + "https://www.googleapis.com/auth/userinfo.profile", + "https://www.googleapis.com/auth/cclog", + "https://www.googleapis.com/auth/experimentsandconfigs", +]; +const ALL_ALLOWED_SCOPES = [...SCOPES, ...EXTRA_ALLOWED_SCOPES]; +const CLI_CALLBACK_ORIGIN = "https://antigravity.google"; +const CLI_CALLBACK_PATHNAME = "/oauth-callback"; +export const ANTIGRAVITY_CLI_TOKEN_DIR = "antigravity-cli"; +export const ANTIGRAVITY_CLI_TOKEN_FILE = "antigravity-oauth-token"; const MAX_BYTES = 64 * 1024; const MAX_REDIRECT_URL_LENGTH = 4096; const MAX_REDIRECT_CODE_LENGTH = 2048; const MAX_BAD_REDIRECT_ATTEMPTS = 5; const MAX_USED_CODE_DIGESTS = 1024; -const REDIRECT_LOOPBACK_TIMEOUT_MS = 5_000; const DISALLOWED_PRINTABLE_ASCII = /[^\x21-\x7E]/; const LOGIN_ERROR = "Google sign-in did not complete. Start sign-in again."; const record = (value: unknown): Record => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; const verifiedCredentials = new Map(); const activeBrowserHomes = new Set(); const usedRedirectCodeDigests = new Set(); +const activeConsumerRefreshes = new Map>(); +const retainedConsumerRefreshCleanups = new Map>(); function recordUsedRedirectCodeDigest(digest: string): void { usedRedirectCodeDigests.add(digest); @@ -49,62 +60,135 @@ export type AntigravityBrowserLoginState = { authorizationUrl?: string; outcome?: "success" | "failure"; error?: string; - /** Relay a user-pasted loopback redirect URL to the local ACP listener. */ + /** Relay a user-pasted callback URL or authorization code to `agy acp --login`. */ submitRedirect?: (rawRedirectUrl: string) => Promise; /** Resolves only after physical process retirement and lease release. */ abort(): Promise; }; -/** Pure validation for the native credential projection and refresh writeback. */ +const safeTokenText = (entry: unknown, max: number): entry is string => + typeof entry === "string" && entry.length > 0 && entry.length <= max && !/[\x00-\x20\x7f]/.test(entry); + +/** Pure validation for the native credential projection and refresh writeback. + * Accepts both legacy `acp_token.json` credentials (with `client_secret`) and + * `agy` CLI credentials (`auth_method: "consumer"`, optional `client_secret`). + */ export function sanitizeAntigravityCredential(serialized: string): string { if (Buffer.byteLength(serialized) > MAX_BYTES) throw new Error("Invalid Antigravity credential"); let value: Record; try { value = record(JSON.parse(serialized)); } catch { throw new Error("Invalid Antigravity credential"); } - const text = (entry: unknown, max: number): entry is string => typeof entry === "string" && entry.length > 0 && entry.length <= max && !/[\x00-\x20\x7f]/.test(entry); + const authMethod = value.auth_method === undefined ? undefined : value.auth_method; + if (authMethod !== undefined && authMethod !== "consumer") throw new Error("Invalid Antigravity credential"); + const hasClientSecret = value.client_secret !== undefined; + if (hasClientSecret ? !safeTokenText(value.client_secret, 1024) : authMethod !== "consumer") { + throw new Error("Invalid Antigravity credential"); + } if (value.client_id !== CLIENT_ID || value.token_uri !== TOKEN_URI - || !text(value.client_secret, 1024) || !text(value.refresh_token, 16_384) - || !Array.isArray(value.scopes) || value.scopes.length > 4 - || !value.scopes.every(scope => typeof scope === "string" && [...SCOPES, "openid"].includes(scope)) + || !safeTokenText(value.refresh_token, 16_384) + || !Array.isArray(value.scopes) || value.scopes.length > ALL_ALLOWED_SCOPES.length + || !value.scopes.every(scope => typeof scope === "string" && ALL_ALLOWED_SCOPES.includes(scope)) || !SCOPES.every(scope => (value.scopes as unknown[]).includes(scope)) || new Set(value.scopes).size !== value.scopes.length - || (value.project_id !== undefined && !text(value.project_id, 1024))) throw new Error("Invalid Antigravity credential"); - return JSON.stringify({ client_id: CLIENT_ID, client_secret: value.client_secret, refresh_token: value.refresh_token, - token_uri: TOKEN_URI, scopes: [...SCOPES, ...((value.scopes as unknown[]).includes("openid") ? ["openid"] : [])], ...(value.project_id !== undefined ? { project_id: value.project_id } : {}) }); + || (value.project_id !== undefined && !safeTokenText(value.project_id, 1024))) { + throw new Error("Invalid Antigravity credential"); + } + const canonicalScopes = ALL_ALLOWED_SCOPES.filter(scope => (value.scopes as unknown[]).includes(scope)); + return JSON.stringify({ + client_id: CLIENT_ID, + ...(hasClientSecret ? { client_secret: value.client_secret } : {}), + refresh_token: value.refresh_token, + token_uri: TOKEN_URI, + scopes: canonicalScopes, + ...(value.project_id !== undefined ? { project_id: value.project_id } : {}), + ...(authMethod !== undefined ? { auth_method: authMethod } : {}), + }); } -/** Only the official PKCE loopback authorization URL may reach the browser. */ +/** Project Paperclip's canonical Google credential into `agy`'s file-backed `antigravity-oauth-token`. */ +export function antigravityCliStoredTokenFromCanonical(canonicalCredential: string): string { + const canonical = sanitizeAntigravityCredential(canonicalCredential); + const parsed = record(JSON.parse(canonical)); + return JSON.stringify({ + token: { + access_token: "expired", + token_type: "Bearer", + refresh_token: parsed.refresh_token, + expiry: "2000-01-01T00:00:00Z", + }, + auth_method: "consumer", + }); +} + +/** Extract a canonical Paperclip Google credential from `agy`'s `antigravity-oauth-token`. */ +export function canonicalAntigravityCredentialFromCliToken( + cliTokenSerialized: string, + baseCanonical?: string, +): { credential: string; accessToken?: string; idTokenEmail?: string } { + if (Buffer.byteLength(cliTokenSerialized) > MAX_BYTES) throw new Error("Invalid Antigravity credential"); + let parsed: Record; + try { parsed = record(JSON.parse(cliTokenSerialized)); } catch { throw new Error("Invalid Antigravity credential"); } + const token = record(parsed.token); + const refreshToken = token.refresh_token; + if (!safeTokenText(refreshToken, 16_384)) throw new Error("Invalid Antigravity credential"); + const accessToken = safeTokenText(token.access_token, 16_384) ? token.access_token : undefined; + const idTokenEmail = typeof parsed.id_token_email === "string" && parsed.id_token_email.includes("@") + ? parsed.id_token_email.trim() : undefined; + if (baseCanonical) { + const base = record(JSON.parse(sanitizeAntigravityCredential(baseCanonical))); + const credential = sanitizeAntigravityCredential(JSON.stringify({ ...base, refresh_token: refreshToken })); + return { credential, ...(accessToken ? { accessToken } : {}), ...(idTokenEmail ? { idTokenEmail } : {}) }; + } + const credential = sanitizeAntigravityCredential(JSON.stringify({ + client_id: CLIENT_ID, + refresh_token: refreshToken, + token_uri: TOKEN_URI, + scopes: [...SCOPES, "openid"], + auth_method: "consumer", + })); + return { credential, ...(accessToken ? { accessToken } : {}), ...(idTokenEmail ? { idTokenEmail } : {}) }; +} + +/** Only Google's official PKCE authorization URL may reach the browser. */ export function validateAntigravityAuthorizationUrl(raw: string): string { if (raw.length > 16_384 || /[\x00-\x20\x7f]/.test(raw)) throw new Error(LOGIN_ERROR); const url = new URL(raw), query = url.searchParams; const keys = ["client_id", "response_type", "redirect_uri", "scope", "state", "code_challenge", "code_challenge_method", "access_type", "prompt"]; - if (url.origin !== "https://accounts.google.com" || url.pathname !== "/o/oauth2/v2/auth" || url.hash || url.username || url.password + if (url.origin !== "https://accounts.google.com" + || (url.pathname !== "/o/oauth2/v2/auth" && url.pathname !== "/o/oauth2/auth") + || url.hash || url.username || url.password || [...query.keys()].some(key => !keys.includes(key) || query.getAll(key).length !== 1) || query.get("client_id") !== CLIENT_ID || query.get("response_type") !== "code" || query.get("access_type") !== "offline" || query.get("prompt") !== "consent" || query.get("code_challenge_method") !== "S256" || !/^[A-Za-z0-9_-]{43}$/.test(query.get("code_challenge") ?? "") || !/^[A-Za-z0-9._~-]{16,1024}$/.test(query.get("state") ?? "")) throw new Error(LOGIN_ERROR); const redirect = new URL(query.get("redirect_uri") ?? ""); - if (redirect.protocol !== "http:" || redirect.hostname !== "127.0.0.1" || !redirect.port || redirect.pathname !== "/" - || redirect.username || redirect.password || redirect.search || redirect.hash) throw new Error(LOGIN_ERROR); + const isCliCallback = redirect.origin === CLI_CALLBACK_ORIGIN && redirect.pathname === CLI_CALLBACK_PATHNAME + && !redirect.username && !redirect.password && !redirect.search && !redirect.hash; + const isLoopback = redirect.protocol === "http:" && redirect.hostname === "127.0.0.1" && Boolean(redirect.port) + && redirect.pathname === "/" && !redirect.username && !redirect.password && !redirect.search && !redirect.hash; + if (!isCliCallback && !isLoopback) throw new Error(LOGIN_ERROR); const scopes = (query.get("scope") ?? "").split(" "); - if (scopes.length > 4 || !SCOPES.every(scope => scopes.includes(scope)) || scopes.some(scope => ![...SCOPES, "openid"].includes(scope))) throw new Error(LOGIN_ERROR); + if (scopes.length > ALL_ALLOWED_SCOPES.length || !SCOPES.every(scope => scopes.includes(scope)) + || scopes.some(scope => !ALL_ALLOWED_SCOPES.includes(scope))) throw new Error(LOGIN_ERROR); return url.href; } -async function credentialFile(home: string): Promise { - await checkAntigravityPrivateHome(home); - const parent = join(home, "antigravity-acp"), stat = await lstat(parent); - if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o700) throw new Error("Invalid Antigravity credential"); - // Darwin's O_NOFOLLOW_ANY rejects symlinks in every component, including a - // concurrently replaced parent. Linux has no such open flag, so the opened - // descriptor's kernel path must equal the checked canonical path instead. +async function readPrivateTokenFile(parent: string, filename: string): Promise { + const stat = await lstat(parent); + if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o700) { + throw new Error("Invalid Antigravity credential"); + } const noFollow = process.platform === "darwin" ? 0x20000000 : constants.O_NOFOLLOW; - const path = join(parent, "acp_token.json"); + const path = join(parent, filename); const file = await open(path, constants.O_RDONLY | noFollow | constants.O_NONBLOCK); try { - if (process.platform === "linux" && await readlink(`/proc/self/fd/${file.fd}`) !== path) throw new Error("Invalid Antigravity credential"); + if (process.platform === "linux" && await readlink(`/proc/self/fd/${file.fd}`) !== path) { + throw new Error("Invalid Antigravity credential"); + } const info = await file.stat(); - if (!info.isFile() || info.nlink !== 1 || info.uid !== process.getuid?.() || (info.mode & 0o777) !== 0o600 || info.size > MAX_BYTES) throw new Error("Invalid Antigravity credential"); + if (!info.isFile() || info.nlink !== 1 || info.uid !== process.getuid?.() || (info.mode & 0o777) !== 0o600 || info.size > MAX_BYTES) { + throw new Error("Invalid Antigravity credential"); + } const bytes = Buffer.alloc(MAX_BYTES + 1); let length = 0; while (length < bytes.length) { @@ -113,10 +197,35 @@ async function credentialFile(home: string): Promise { length += bytesRead; } if (length > MAX_BYTES) throw new Error("Invalid Antigravity credential"); - return sanitizeAntigravityCredential(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length))); + return new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length)); } finally { await file.close(); } } +async function credentialFile(home: string): Promise { + await checkAntigravityPrivateHome(home); + return sanitizeAntigravityCredential(await readPrivateTokenFile(join(home, "antigravity-acp"), "acp_token.json")); +} + +async function writeCanonicalCredentialFile(home: string, credential: string): Promise { + await checkAntigravityPrivateHome(home); + const parent = join(home, "antigravity-acp"); + await mkdir(parent, { recursive: true, mode: 0o700 }); + const parentStat = await lstat(parent); + if (!parentStat.isDirectory() || parentStat.isSymbolicLink() || parentStat.uid !== process.getuid?.() || (parentStat.mode & 0o077) !== 0) { + throw new Error("Invalid Antigravity credential"); + } + const tmp = join(parent, `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(credential); await handle.sync(); } + 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> { const response = await fetch(url, { ...options, redirect: "error", signal: options.signal ?? AbortSignal.timeout(10_000) }); if (!response.ok || !response.body) throw new Error(LOGIN_ERROR); @@ -134,153 +243,400 @@ async function googleJson(url: string, options: RequestInit): Promise undefined); } } -/** Refresh and check Google identity privately; this never calls a model API. - * Callers must also require the setup process's successful authenticate result. - */ +async function fetchGoogleAccountEmail(accessToken: string, signal?: AbortSignal): Promise { + const identity = await googleJson("https://www.googleapis.com/oauth2/v3/userinfo", { + headers: { Authorization: `Bearer ${accessToken}` }, + signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(10_000)]) : AbortSignal.timeout(10_000), + }); + const email = typeof identity.email === "string" ? identity.email.trim() : ""; + if (identity.email_verified !== true || !email || !email.includes("@") || email.length > 320 || /[\x00-\x20\x7f]/.test(email)) { + throw new Error(LOGIN_ERROR); + } + return email; +} + +function awaitAbortable(promise: Promise, signal?: AbortSignal): Promise { + if (!signal) return promise; + if (signal.aborted) return Promise.reject(signal.reason ?? new Error(LOGIN_ERROR)); + return new Promise((resolve, reject) => { + const onAbort = () => reject(signal.reason ?? new Error(LOGIN_ERROR)); + signal.addEventListener("abort", onAbort, { once: true }); + promise.then( + () => { signal.removeEventListener("abort", onAbort); resolve(); }, + error => { signal.removeEventListener("abort", onAbort); reject(error); }, + ); + }); +} + +async function waitForConsumerHomeIdle(home: string, signal?: AbortSignal): Promise { + while (true) { + const pending = retainedConsumerRefreshCleanups.get(home) ?? activeConsumerRefreshes.get(home); + if (!pending) return; + await awaitAbortable(pending, signal); + } +} + +async function syncAndCleanConsumerCliToken( + home: string, + staged: { cliDir: string; cliTokenPath: string; credential: string; rotationSaved: boolean } | null, +): Promise { + if (!staged) return; + try { + const rawCli = await readPrivateTokenFile(staged.cliDir, ANTIGRAVITY_CLI_TOKEN_FILE); + const parsedCli = canonicalAntigravityCredentialFromCliToken(rawCli, staged.credential); + if (parsedCli.credential !== staged.credential && !staged.rotationSaved) { + await writeCanonicalCredentialFile(home, parsedCli.credential); + } + await rm(staged.cliTokenPath, { force: true }).catch(() => undefined); + } catch (cleanupError) { + if ((cleanupError as NodeJS.ErrnoException).code === "ENOENT") { + // Already absent. + } else if (staged.rotationSaved) { + await rm(staged.cliTokenPath, { force: true }).catch(() => undefined); + } + } +} + +function retainConsumerRefreshCleanup( + home: string, + child: ChildProcessWithoutNullStreams | undefined, + closed: Promise | undefined, + lease: VerifiedAcpxCommandLease | undefined, + staged: { cliDir: string; cliTokenPath: string; credential: string; rotationSaved: boolean } | null, +): Promise { + let observedClose = child === undefined; + let retired = !child || !closed; + let leaseClosed = !lease; + void closed?.then(() => { observedClose = true; }); + const cleanup = (async () => { + while (!retired || !leaseClosed) { + try { + if (!retired) { await retireAntigravityProcess(child!, closed!); retired = true; } + if (!leaseClosed) { await lease!.close(); leaseClosed = true; } + } catch { + let timer: ReturnType | undefined; + const retry = new Promise(resolve => { timer = setTimeout(resolve, 1_000); }); + try { await (observedClose || !closed ? retry : Promise.race([closed, retry])); } + finally { if (timer) clearTimeout(timer); } + } + } + await syncAndCleanConsumerCliToken(home, staged); + })(); + retainedConsumerRefreshCleanups.set(home, cleanup); + void cleanup.finally(() => { + if (retainedConsumerRefreshCleanups.get(home) === cleanup) retainedConsumerRefreshCleanups.delete(home); + }); + return cleanup; +} + +/** 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 }> { + await waitForConsumerHomeIdle(home, outerSignal); + let releaseActive!: () => void; + const activePromise = new Promise(resolve => { releaseActive = resolve; }); + activeConsumerRefreshes.set(home, activePromise); + + 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 | undefined; + let stagedTemporary = false; + let rotationSaved = false; + let retireFailedInTry = false; + let primaryError: unknown; + let result: { credential: string; accountEmail: string } | undefined; + 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((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; + 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); + }); + try { + await retireAntigravityProcess(peer, closed); child = undefined; + } catch (error) { + retireFailedInTry = true; + throw error; + } + 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); + result = { credential: parsedCli.credential, accountEmail }; + } catch (error) { + primaryError = error; + } finally { + clearTimeout(deadlineTimer); + let cleanupFailure: unknown; + try { + if (retireFailedInTry) throw primaryError; + if (child && closed) { await retireAntigravityProcess(child, closed); child = undefined; } + if (lease) { await lease.close(); lease = undefined; } + if (stagedTemporary) { + await syncAndCleanConsumerCliToken(home, { cliDir, cliTokenPath, credential, rotationSaved }); + stagedTemporary = false; + } + } catch (error) { + cleanupFailure = error; + if ((child && closed) || lease) { + retainConsumerRefreshCleanup( + home, + child, + closed, + lease, + stagedTemporary ? { cliDir, cliTokenPath, credential, rotationSaved } : null, + ); + } + } + if (activeConsumerRefreshes.get(home) === activePromise) activeConsumerRefreshes.delete(home); + releaseActive(); + if (cleanupFailure !== undefined) { + primaryError = primaryError ?? cleanupFailure; + } + } + if (primaryError !== undefined) throw primaryError; + return result!; +} + +/** 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(); + await waitForConsumerHomeIdle(home, options.signal); const credential = await credentialFile(home), cached = verifiedCredentials.get(home); if (cached?.credential === credential) return { ...cached }; const value = record(JSON.parse(credential)); - const token = await googleJson(TOKEN_URI, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, + if (typeof value.client_secret !== "string" || !value.client_secret) { + // `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 effectiveCredential = credential; + 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.credential !== credential) { + // Persist any refresh token already rotated in the CLI file before trying + // userinfo or falling back to `agy`, so a retry never stages the stale copy. + await writeCanonicalCredentialFile(home, parsedCli.credential); + effectiveCredential = parsedCli.credential; + } + if (parsedCli.accessToken && parsedCli.accessToken !== "expired") { + try { + const accountEmail = await fetchGoogleAccountEmail(parsedCli.accessToken, options.signal); + const verified = { credential: effectiveCredential, 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, effectiveCredential, options.signal); + if (activeBrowserHomes.has(home)) verifiedCredentials.set(home, verified); + return { ...verified }; + } + const token = await googleJson(TOKEN_URI, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(10_000)]) : AbortSignal.timeout(10_000), - body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: value.refresh_token as string, client_id: CLIENT_ID, client_secret: value.client_secret as string }) }); + body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: value.refresh_token as string, client_id: CLIENT_ID, client_secret: value.client_secret }), + }); if (typeof token.access_token !== "string" || token.access_token.length > 16_384 || /[\x00-\x20\x7f]/.test(token.access_token) || !token.access_token || (token.token_type !== undefined && String(token.token_type).toLowerCase() !== "bearer")) throw new Error(LOGIN_ERROR); let next = credential; if (token.refresh_token !== undefined && token.refresh_token !== value.refresh_token) { next = sanitizeAntigravityCredential(JSON.stringify({ ...value, refresh_token: token.refresh_token })); - // Preserve a consumed rotation before another request can fail. This is a - // private, unverified receipt until userinfo succeeds; the connection owner - // still performs identity and generation-checked encrypted writeback. - await checkAntigravityPrivateHome(home); - const target = join(home, "antigravity-acp", "acp_token.json"), temporary = `${target}.${randomUUID()}.tmp`; - const file = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); - try { - await file.writeFile(next); - await file.sync(); - } finally { await file.close(); } - try { - await rename(temporary, target); - const directory = await open(join(home, "antigravity-acp"), constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); - try { await directory.sync(); } finally { await directory.close(); } - } finally { await rm(temporary, { force: true }); } + await writeCanonicalCredentialFile(home, next); } - const identity = await googleJson("https://www.googleapis.com/oauth2/v3/userinfo", { headers: { Authorization: `Bearer ${token.access_token}` }, - signal: options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(10_000)]) : AbortSignal.timeout(10_000) }); - if (identity.email_verified !== true || typeof identity.email !== "string" || identity.email.length > 320 || !/^[^\s@]+@[^\s@]+$/.test(identity.email)) throw new Error("Google could not verify the signed-in account."); - const result = { credential: next, accountEmail: identity.email }; - // Runtime refresh checks use short-lived prepared homes. Retain credentials - // only for an active, bounded browser attempt, whose abort owns eviction. - if (activeBrowserHomes.has(home)) verifiedCredentials.set(home, result); - return { ...result }; + const accountEmail = await fetchGoogleAccountEmail(token.access_token, options.signal); + const verified = { credential: next, accountEmail }; + if (activeBrowserHomes.has(home)) verifiedCredentials.set(home, verified); + return { ...verified }; } -/** A setup-only native ACP client. Its complete outgoing method set is - * initialize/authenticate; pending provider qualification remains enforced for - * every session and prompt by the ordinary runtime installation path. - */ +function extractAuthorizationUrlFromLine(line: string): string | null { + const trimmed = line.trim(); + const prefix = "Open the following link to authenticate the ACP server: "; + if (trimmed.startsWith(prefix)) return trimmed.slice(prefix.length).trim(); + if (/^https?:\/\/\S+$/.test(trimmed)) return trimmed; + return null; +} + +/** Browser sign-in through the pinned `agy acp --login` CLI in an isolated private home. */ export function startAntigravityBrowserLogin(home: string, options: { onFailure?: (reason: AntigravityBrowserLoginFailureReason) => void } = {}): AntigravityBrowserLoginState { - const controller = new AbortController(); + if (activeBrowserHomes.has(home)) throw new Error("Google sign-in is already active for this home"); activeBrowserHomes.add(home); + verifiedCredentials.delete(home); + const controller = new AbortController(); let resolveStopped: () => void; const stopped = new Promise(resolve => { resolveStopped = resolve; }); - const state: AntigravityBrowserLoginState = { abort() { state.submitRedirect = undefined; controller.abort(); activeBrowserHomes.delete(home); verifiedCredentials.delete(home); return stopped; } }; + const state: AntigravityBrowserLoginState = { + abort: async () => { + controller.abort(); + await stopped; + activeBrowserHomes.delete(home); + verifiedCredentials.delete(home); + }, + }; void (async () => { - let lease: VerifiedAcpxCommandLease | undefined; - let child: ChildProcessWithoutNullStreams | undefined, closed: Promise | undefined; - let timeout: ReturnType | undefined, failPending: ((error: Error) => void) | undefined; + let lease: VerifiedAcpxCommandLease | undefined, child: ChildProcessWithoutNullStreams | undefined; + let closed: Promise | undefined, timeout: ReturnType | undefined; + let failPending: ((error?: Error) => void) | undefined; let pendingReason: AntigravityBrowserLoginFailureReason = "start_failed"; try { await checkAntigravityPrivateHome(home); - const installation = await Promise.resolve().then(() => verifyNativeAcpxInstallation(antigravityNativeDistributionSpec())) - .catch(() => { throw new AntigravityRuntimeUnavailableError(); }); + const cliDir = join(home, ANTIGRAVITY_CLI_TOKEN_DIR); + await mkdir(cliDir, { recursive: true, mode: 0o700 }); + const cliDirStat = await lstat(cliDir); + if (!cliDirStat.isDirectory() || cliDirStat.isSymbolicLink() || cliDirStat.uid !== process.getuid?.() || (cliDirStat.mode & 0o777) !== 0o700) { + throw new Error("Invalid Antigravity private home"); + } + const installation = await Promise.resolve().then(() => + verifyNativeAcpxInstallation(antigravityNativeDistributionSpec(process.platform, process.arch, ["--login", "--gemini-dir", home, "--disable-telemetry"])), + ).catch(() => { throw new AntigravityRuntimeUnavailableError(); }); lease = await installation.openCommand({ signal: controller.signal }); const environment = await antigravityPrivateEnvironment(home); if (controller.signal.aborted) throw new Error(LOGIN_ERROR); child = lease.spawn([], { cwd: home, stdio: "pipe", detached: process.platform !== "win32", env: environment }) as ChildProcessWithoutNullStreams; closed = new Promise(resolve => child!.once("close", () => resolve())); const peer = child; - let phase = 1, stdout = "", stderr = "", total = 0, failure: Error | undefined; + let stdout = "", stderr = "", total = 0, failure: Error | undefined; + let awaitingCode = false; const outputDecoder = new StringDecoder("utf8"), errorDecoder = new StringDecoder("utf8"); const authenticated = new Promise((resolve, reject) => { const fail = (error = new Error(LOGIN_ERROR)) => { state.submitRedirect = undefined; failure ??= error; reject(failure); }; failPending = fail; - 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: "authenticate", params: { methodId: "oauth-personal" } })}\n`); - peer.stdout.on("data", (chunk: Buffer) => { - total += chunk.length; - if (total > 2 * 1024 * 1024) { fail(); return; } - stdout += outputDecoder.write(chunk); - while (stdout.includes("\n") && !failure) { - const end = stdout.indexOf("\n"), line = stdout.slice(0, end); stdout = stdout.slice(end + 1); - if (!line.trim()) continue; - let message: Record; - try { message = record(JSON.parse(line)); } catch { fail(); return; } - if (phase > 2 || message.jsonrpc !== "2.0" || message.id !== phase || "method" in message || "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" || info.version !== ANTIGRAVITY_RUNTIME_VERSION - || record(record(record(initialized.agentCapabilities)._meta).antigravity).paperclipAdmission !== 1 - || !Array.isArray(initialized.authMethods) || !initialized.authMethods.some(method => record(method).id === "oauth-personal")) { fail(); return; } - phase = 2; pendingReason = "login_incomplete"; send(2); - } else { phase = 3; state.submitRedirect = undefined; resolve(); } - } - }); - peer.stderr.on("data", (chunk: Buffer) => { - total += chunk.length; - if (total > 2 * 1024 * 1024) { fail(); return; } - stderr += errorDecoder.write(chunk); - while (stderr.includes("\n") && !failure) { - const end = stderr.indexOf("\n"), line = stderr.slice(0, end); stderr = stderr.slice(end + 1); - if (!line.startsWith(AUTH_PREFIX)) continue; - try { - const url = validateAntigravityAuthorizationUrl(line.slice(AUTH_PREFIX.length)); - if ((phase !== 2 && phase !== 3) || state.authorizationUrl !== undefined) throw new Error(LOGIN_ERROR); - state.authorizationUrl = url; - if (phase === 2 && !controller.signal.aborted && !failure) { - const parsedAuth = new URL(url); - const expectedRedirect = new URL(parsedAuth.searchParams.get("redirect_uri")!); - const expectedState = parsedAuth.searchParams.get("state")!; - const expectedStateBytes = Buffer.from(expectedState, "utf8"); - let badAttempts = 0; - const rejectBadAttempt = (message: string): never => { - badAttempts += 1; - if (badAttempts >= MAX_BAD_REDIRECT_ATTEMPTS) { - fail(new Error(LOGIN_ERROR)); - throw new Error("Too many invalid Google redirect URLs. Start sign-in again."); - } - throw new Error(message); - }; - const submitRedirect = async (rawRedirectUrl: string): Promise => { - if (controller.signal.aborted || failure || phase !== 2 || state.submitRedirect !== submitRedirect) { - throw new Error("This Google sign-in attempt can no longer accept a redirect URL. Start sign-in again."); - } - if ( - typeof rawRedirectUrl !== "string" - || rawRedirectUrl.length === 0 - || rawRedirectUrl.length > MAX_REDIRECT_URL_LENGTH - || DISALLOWED_PRINTABLE_ASCII.test(rawRedirectUrl) - ) { - rejectBadAttempt("Paste the full http://127.0.0.1 URL from your browser’s address bar."); - } + const handleUrlLine = (line: string) => { + const candidate = extractAuthorizationUrlFromLine(line); + if (!candidate) return; + pendingReason = "login_incomplete"; + try { + const url = validateAntigravityAuthorizationUrl(candidate); + if (state.authorizationUrl !== undefined) throw new Error(LOGIN_ERROR); + state.authorizationUrl = url; + awaitingCode = true; + if (!controller.signal.aborted && !failure) { + const parsedAuth = new URL(url); + const expectedRedirect = new URL(parsedAuth.searchParams.get("redirect_uri")!); + const expectedState = parsedAuth.searchParams.get("state")!; + const expectedStateBytes = Buffer.from(expectedState, "utf8"); + let badAttempts = 0; + const rejectBadAttempt = (message: string): never => { + badAttempts += 1; + if (badAttempts >= MAX_BAD_REDIRECT_ATTEMPTS) { + fail(new Error(LOGIN_ERROR)); + throw new Error("Too many invalid Google sign-in responses. Start sign-in again."); + } + throw new Error(message); + }; + const submitRedirect = async (rawInput: string): Promise => { + if (controller.signal.aborted || failure || !awaitingCode || state.submitRedirect !== submitRedirect) { + throw new Error("This Google sign-in attempt can no longer accept a response. Start sign-in again."); + } + const trimmed = typeof rawInput === "string" ? rawInput.trim() : ""; + if (trimmed.length === 0 || trimmed.length > MAX_REDIRECT_URL_LENGTH || DISALLOWED_PRINTABLE_ASCII.test(trimmed)) { + rejectBadAttempt("Paste the authorization code or callback URL from your browser."); + } + let submittedCode = trimmed; + let lineToRelay = trimmed; + if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) { let parsed: URL; - try { - parsed = new URL(rawRedirectUrl); - } catch { - rejectBadAttempt("Paste the full http://127.0.0.1 URL from your browser’s address bar."); + try { parsed = new URL(trimmed); } catch { + rejectBadAttempt("Paste the authorization code or full callback URL from your browser."); } - if ( - parsed!.protocol !== "http:" - || parsed!.hostname !== "127.0.0.1" - || parsed!.port !== expectedRedirect.port - || parsed!.pathname !== "/" - || parsed!.username - || parsed!.password - || parsed!.hash - ) { - rejectBadAttempt("The pasted URL does not match this Google sign-in attempt. Copy the address from the tab opened by this sign-in and try again."); + const matchesExpected = parsed!.origin === expectedRedirect.origin + && parsed!.pathname === expectedRedirect.pathname + && !parsed!.username && !parsed!.password && !parsed!.hash; + if (!matchesExpected) { + rejectBadAttempt("The pasted URL does not match this Google sign-in attempt. Copy the callback URL or code from the sign-in tab and try again."); } if (parsed!.searchParams.has("error")) { rejectBadAttempt("Google sign-in was cancelled or denied. Start sign-in again."); @@ -288,64 +644,59 @@ export function startAntigravityBrowserLogin(home: string, options: { onFailure? const states = parsed!.searchParams.getAll("state"); const codes = parsed!.searchParams.getAll("code"); if (states.length !== 1 || codes.length !== 1) { - rejectBadAttempt("The pasted URL is missing the Google sign-in response parameters. Copy the full address bar URL and try again."); + rejectBadAttempt("The pasted URL is missing the Google sign-in response parameters. Copy the full callback URL or authorization code and try again."); } const submittedStateBytes = Buffer.from(states[0]!, "utf8"); if (submittedStateBytes.length !== expectedStateBytes.length || !timingSafeEqual(submittedStateBytes, expectedStateBytes)) { - rejectBadAttempt("The pasted URL does not match this Google sign-in attempt. Copy the address from the tab opened by this sign-in and try again."); + rejectBadAttempt("The pasted URL does not match this Google sign-in attempt. Copy the callback URL or code from the sign-in tab and try again."); } - const submittedCode = codes[0]!; - if ( - submittedCode.length === 0 - || submittedCode.length > MAX_REDIRECT_CODE_LENGTH - || DISALLOWED_PRINTABLE_ASCII.test(submittedCode) - ) { - rejectBadAttempt("The pasted URL does not contain a valid Google authorization code."); - } - const codeDigest = createHash("sha256").update(submittedCode, "utf8").digest("hex"); - if (usedRedirectCodeDigests.has(codeDigest)) { - rejectBadAttempt("This Google authorization code has already been used. Start sign-in again."); - } - // Atomically consume single-use slot before contacting the one-shot loopback listener. - recordUsedRedirectCodeDigest(codeDigest); - state.submitRedirect = undefined; - - const relayUrl = new URL("/", expectedRedirect.origin); - relayUrl.searchParams.set("state", expectedState); - relayUrl.searchParams.set("code", submittedCode); - - let response: Response; - try { - response = await fetch(relayUrl.href, { - method: "GET", - redirect: "manual", - signal: AbortSignal.any([controller.signal, AbortSignal.timeout(REDIRECT_LOOPBACK_TIMEOUT_MS)]), - }); - } catch { - fail(new Error(LOGIN_ERROR)); - throw new Error(LOGIN_ERROR); - } - try { - await response.body?.cancel(); - } catch { - // Ignore body cancellation errors after reading status. - } - if (response.status !== 200) { - fail(new Error(LOGIN_ERROR)); - throw new Error(LOGIN_ERROR); - } - }; - state.submitRedirect = submitRedirect; - } - } catch { fail(); } + submittedCode = codes[0]!; + lineToRelay = `${expectedRedirect.origin}${expectedRedirect.pathname}?state=${encodeURIComponent(expectedState)}&code=${encodeURIComponent(submittedCode)}`; + } + if (submittedCode.length === 0 || submittedCode.length > MAX_REDIRECT_CODE_LENGTH || DISALLOWED_PRINTABLE_ASCII.test(submittedCode)) { + rejectBadAttempt("The pasted value does not contain a valid Google authorization code."); + } + const codeDigest = createHash("sha256").update(submittedCode, "utf8").digest("hex"); + if (usedRedirectCodeDigests.has(codeDigest)) { + rejectBadAttempt("This Google authorization code has already been used. Start sign-in again."); + } + recordUsedRedirectCodeDigest(codeDigest); + state.submitRedirect = undefined; + awaitingCode = false; + peer.stdin.write(`${lineToRelay}\n`); + }; + state.submitRedirect = submitRedirect; + } + } catch { fail(); } + }; + const onChunk = (stream: "stdout" | "stderr", chunk: Buffer) => { + total += chunk.length; + if (total > 2 * 1024 * 1024) { fail(); return; } + if (stream === "stdout") { + stdout += outputDecoder.write(chunk); + while (stdout.includes("\n") && !failure) { + const end = stdout.indexOf("\n"), line = stdout.slice(0, end); stdout = stdout.slice(end + 1); + handleUrlLine(line); + } + if (stdout.length > MAX_BYTES) fail(); + } else { + stderr += errorDecoder.write(chunk); + while (stderr.includes("\n") && !failure) { + const end = stderr.indexOf("\n"), line = stderr.slice(0, end); stderr = stderr.slice(end + 1); + handleUrlLine(line); + } + if (stderr.length > MAX_BYTES) fail(); } - if (stderr.length > MAX_BYTES) fail(); - }); + }; + peer.stdout.on("data", chunk => onChunk("stdout", chunk)); + peer.stderr.on("data", chunk => onChunk("stderr", chunk)); peer.once("error", () => fail()); - peer.once("close", () => { if (phase !== 3) fail(); }); - peer.stdin.on("error", () => { if (phase !== 3) fail(); }); + peer.once("close", (code, sig) => { + if (!failure && code === 0 && sig === null && state.authorizationUrl !== undefined) resolve(); + else fail(); + }); + peer.stdin.on("error", () => fail()); timeout = setTimeout(() => fail(), 360_000); - send(1); }); const abort = () => failPending?.(new Error(LOGIN_ERROR)); controller.signal.addEventListener("abort", abort, { once: true }); @@ -355,7 +706,16 @@ export function startAntigravityBrowserLogin(home: string, options: { onFailure? await retireAntigravityProcess(peer, closed); child = undefined; await lease.close(); lease = undefined; if (failure || controller.signal.aborted) throw new Error(LOGIN_ERROR); - await verifyAntigravityCredential(home, { signal: controller.signal }); + + // Convert `agy`'s `antigravity-oauth-token` to Paperclip's canonical `acp_token.json` and verify identity. + const cliTokenPath = join(home, ANTIGRAVITY_CLI_TOKEN_DIR, ANTIGRAVITY_CLI_TOKEN_FILE); + const rawCliToken = await readPrivateTokenFile(join(home, ANTIGRAVITY_CLI_TOKEN_DIR), ANTIGRAVITY_CLI_TOKEN_FILE); + const converted = canonicalAntigravityCredentialFromCliToken(rawCliToken); + if (!converted.accessToken || converted.accessToken === "expired") throw new Error(LOGIN_ERROR); + const accountEmail = await fetchGoogleAccountEmail(converted.accessToken, controller.signal); + await writeCanonicalCredentialFile(home, converted.credential); + await rm(cliTokenPath, { force: true }); + verifiedCredentials.set(home, { credential: converted.credential, accountEmail }); if (controller.signal.aborted) throw new Error(LOGIN_ERROR); state.outcome = "success"; } catch (error) { @@ -370,9 +730,6 @@ export function startAntigravityBrowserLogin(home: string, options: { onFailure? let observedClose = child === undefined; let cleanupWasUncertain = false; void closed?.then(() => { observedClose = true; }); - // The active login owns these references until cleanup is proven. Only - // this unresolved obligation schedules retries; physical close wakes it - // early. Callers keep the private home while awaiting abort's completion. while (true) { try { if (child && closed) await retireAntigravityProcess(child, closed); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-cli-installation.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-cli-installation.ts index 8127a348098..de889972daa 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-cli-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-cli-installation.ts @@ -2,6 +2,7 @@ import { lstatSync } from "node:fs"; import { userInfo } from "node:os"; import { isAbsolute, join } from "node:path"; import { ANTIGRAVITY_CLI_DISTRIBUTION, type AntigravityCliTarget } from "./antigravity-cli-pins.js"; +import { antigravityNativeDistributionSpec } from "./antigravity-installation.js"; import { verifyNativeAcpxInstallation, type VerifiedAcpxInstallation } from "./installation-integrity.js"; import type { NativeAcpxDistributionInput } from "./native-distribution-integrity.js"; import { realRuntimeCachePath } from "./runtime-cache-path.js"; @@ -31,6 +32,7 @@ export interface AntigravityCliLaunchOptions { architecture?: string; /** Owner of `~/.paperclip/runtimes`; independent of the provider's private HOME. */ home?: string; + environment?: NodeJS.ProcessEnv; } export interface AntigravityCliLaunch { @@ -61,13 +63,22 @@ function pinnedTarget(platform: string, architecture: string): AntigravityCliTar return target as AntigravityCliTarget; } -/** `~/.paperclip/runtimes/antigravity-cli//`, beside the registry-server runtime. */ +/** `~/.paperclip/runtimes/antigravity-cli//`, beside the main runtime. */ export function antigravityCliRuntimeCachePath(closure: string, platform: string, architecture: string, home = userInfo().homedir): string { pinnedTarget(platform, architecture); if (!/^[a-f0-9]{64}$/.test(closure) || !isAbsolute(home) || home.includes("\0")) throw new Error("Invalid Antigravity CLI runtime cache identity"); return realRuntimeCachePath(home, "antigravity-cli", `${platform}-${architecture}`, closure, "Antigravity CLI runtime cache must contain real directories"); } +function directoryExists(path: string): boolean { + try { + return lstatSync(path).isDirectory(); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } +} + /** Resolve the pinned, installed CLI for this host and admit it through the sealed launch store. */ export async function resolveAntigravityCliLaunch(options: AntigravityCliLaunchOptions = {}): Promise { const platform = options.platform ?? process.platform; @@ -78,17 +89,39 @@ export async function resolveAntigravityCliLaunch(options: AntigravityCliLaunchO throw new Error("Antigravity CLI launch arguments are invalid"); } const pin = ANTIGRAVITY_CLI_DISTRIBUTION.platforms[target]; - const distributionRoot = antigravityCliRuntimeCachePath(pin.closureSha256, platform, architecture, options.home); - try { lstatSync(distributionRoot); } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; - throw new AntigravityCliRuntimeError("ANTIGRAVITY_CLI_RUNTIME_MISSING", - `The Antigravity CLI ${ANTIGRAVITY_CLI_DISTRIBUTION.version} is not installed on this host. Run ${SETUP_COMMAND} as the user that runs Paperclip.`); - } const fixedArguments = Object.freeze([...ANTIGRAVITY_CLI_DISTRIBUTION.args, ...extra]); - const spec: NativeAcpxDistributionInput = { - distributionRoot, manifestPath: join(distributionRoot, ANTIGRAVITY_CLI_CLOSURE_MANIFEST), expectedClosureSha256: pin.closureSha256, - executable: pin.executable, fixedArguments, storeFamily: "antigravity-cli", - }; + + // Prefer the unified Antigravity runtime closure (packaged assets, Cloud provider pack, + // or `~/.paperclip/runtimes/antigravity`) when present and matching the pinned closure; + // otherwise fall back to the standalone `~/.paperclip/runtimes/antigravity-cli` cache. + let spec: NativeAcpxDistributionInput | null = null; + if (options.home === undefined) { + try { + const unified = antigravityNativeDistributionSpec(platform, architecture, extra, { environment: options.environment }); + if (unified.expectedClosureSha256 === pin.closureSha256 && directoryExists(unified.distributionRoot)) { + spec = unified; + } + } catch { + // Fall through to the standalone antigravity-cli cache. + } + } + if (spec === null) { + const unifiedHome = antigravityNativeDistributionSpec(platform, architecture, extra, { home: options.home, environment: options.environment }); + if (unifiedHome.expectedClosureSha256 === pin.closureSha256 && directoryExists(unifiedHome.distributionRoot)) { + spec = unifiedHome; + } else { + const distributionRoot = antigravityCliRuntimeCachePath(pin.closureSha256, platform, architecture, options.home); + if (!directoryExists(distributionRoot)) { + throw new AntigravityCliRuntimeError("ANTIGRAVITY_CLI_RUNTIME_MISSING", + `The Antigravity CLI ${ANTIGRAVITY_CLI_DISTRIBUTION.version} is not installed on this host. Run ${SETUP_COMMAND} as the user that runs Paperclip.`); + } + spec = { + distributionRoot, manifestPath: join(distributionRoot, ANTIGRAVITY_CLI_CLOSURE_MANIFEST), expectedClosureSha256: pin.closureSha256, + executable: pin.executable, fixedArguments, storeFamily: "antigravity-cli", + }; + } + } + const installation = await verifyNativeAcpxInstallation(spec); const environment: Readonly> = Object.freeze({ ...ANTIGRAVITY_CLI_DISTRIBUTION.environment }); return Object.freeze({ diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-cli-pins.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-cli-pins.ts index 4bb7144c747..d0916676eb0 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-cli-pins.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-cli-pins.ts @@ -1,8 +1,8 @@ // Compiled-in copy of antigravity-cli-distributions.json; antigravity-cli-pins.test.ts // keeps the two equal. A file read at launch never establishes trust. export const ANTIGRAVITY_CLI_DISTRIBUTION = { - version: "1.5.15", - build: "1.5.15-5514532022517760", + version: "1.5.19", + build: "1.5.19-4821414830800896", args: [ "acp" ], @@ -12,36 +12,48 @@ export const ANTIGRAVITY_CLI_DISTRIBUTION = { platforms: { "darwin-arm64": { executable: "agy", - closureSha256: "d61f8aed4c0fffe5db28ab2174f0543ed1fc09e03f4c3f491f9cbee5db157c63", + closureSha256: "83d5143264b2f6e944eae9dda9dbdb489e2a7805b2c5246990bf4756e0f6502c", entries: [ { path: "agy", - sha256: "8097b24de18aba93324ee24d0d3f060906c58ba58562f4f1bd66f380906056a2", - size: 229617904, + sha256: "757cf6cc4e88ca128a797d8275991537af0cc7943fbefc1c207332d32aabf0f7", + size: 229574304, + executable: true + } + ] + }, + "darwin-x64": { + executable: "agy", + closureSha256: "4d9bca68a74eefbea4aa2545eb50b36afbd5c5b81d9f1278388611f89ec0a0ca", + entries: [ + { + path: "agy", + sha256: "f991bce221d115f5fb3e1fae509d6f22aeaa68a904c05f236749dc20fe5ac1dc", + size: 239536144, executable: true } ] }, "linux-x64": { executable: "agy", - closureSha256: "ffec3d7fcc882a243f7bfda808b601bb593c2a54514d492d719f7e546dd9990d", + closureSha256: "8af424d013ce999900951e707888199ad63f4681ef8c5a5cd4ccae43ba60bfe6", entries: [ { path: "agy", - sha256: "7b004d26c3fdea25a7c9d456de4bfaccef4be1e4cc7fd6db628859c5c941fa2d", - size: 273879752, + sha256: "1030610322de110757a2e4b811187ba06ff14a81a8f1cb10ac66935690250cbe", + size: 281375456, executable: true } ] }, "linux-arm64": { executable: "agy", - closureSha256: "e564936c56b8e7158b517428d4c23261f420fe84d4d2e8f1dd71e650bb8e9fac", + closureSha256: "abbc84893dde911e12878bb611f9e068796686259efcaf9a2bd2e312a4626c8e", entries: [ { path: "agy", - sha256: "497580a779b155268c4aa8f491b75e3b0034d4d0ba05c762582e7d97222396b0", - size: 256660144, + sha256: "f7eb360ab67f74f8307302fc5948775155be3a68b65763fe3c62aceda728a968", + size: 263475936, executable: true } ] diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-credentials.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-credentials.test.ts index 3e3f11ede1f..f8c3bcb218c 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-credentials.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-credentials.test.ts @@ -29,17 +29,23 @@ it("keeps OAuth bound to its sidecar session and out of the actual native enviro expect(createSanitizedAcpxSpawnInput(undefined, "antigravity").env[ANTIGRAVITY_AUTH_ENV]).toBeUndefined(); }); +const cliTokenJson = (refreshToken: string) => JSON.stringify({ + token: { access_token: "fresh-at", token_type: "Bearer", refresh_token: refreshToken, expiry: "2099-01-01T00:00:00Z" }, + auth_method: "consumer", +}); + it("fences refresh owners, preserves native rotation, scrubs live files and removes stale handoffs on reuse", async () => { - const root = await home(), directory = join(root, "antigravity-acp"); + const root = await home(), directory = join(root, "antigravity-acp"), cliToken = join(root, "antigravity-cli", "antigravity-oauth-token"); const input = { agentHomeDirectory: root, environment: { [ANTIGRAVITY_AUTH_ENV]: credential } }; const first = await stageManagedAntigravityCredential(input); try { - expect((await stat(join(directory, "acp_token.json"))).mode & 0o777).toBe(0o600); + expect((await stat(cliToken)).mode & 0o777).toBe(0o600); await expect(stageManagedAntigravityCredential(input)).rejects.toThrow(/active lease|owned/); const rotated = credential.replace("fixture-refresh", "rotated-refresh"); - await writeFile(join(directory, "acp_token.json"), rotated, { mode: 0o600 }); + await writeFile(cliToken, cliTokenJson("rotated-refresh"), { mode: 0o600 }); await Promise.all([first.close(), first.close()]); expect(await readFile(join(directory, "auth-refresh.json"), "utf8")).toBe(rotated); + await expect(stat(cliToken)).rejects.toMatchObject({ code: "ENOENT" }); for (const name of ["auth.json", "acp_token.json"]) await expect(stat(join(directory, name))).rejects.toMatchObject({ code: "ENOENT" }); const second = await stageManagedAntigravityCredential(input); try { await expect(stat(join(directory, "auth-refresh.json"))).rejects.toMatchObject({ code: "ENOENT" }); } @@ -48,7 +54,7 @@ it("fences refresh owners, preserves native rotation, scrubs live files and remo }); it("retains ownership when a token is replaced by a symlink, and never reads its target", async () => { - const root = await home(), token = join(root, "antigravity-acp", "acp_token.json"); + const root = await home(), token = join(root, "antigravity-cli", "antigravity-oauth-token"); const input = { agentHomeDirectory: root, environment: { [ANTIGRAVITY_AUTH_ENV]: credential } }; const lease = await stageManagedAntigravityCredential(input), target = join(await home(), "unrelated"); await writeFile(target, "unrelated", { mode: 0o600 }); @@ -56,19 +62,19 @@ it("retains ownership when a token is replaced by a symlink, and never reads its await expect(lease.close()).rejects.toThrow(); await expect(stageManagedAntigravityCredential(input)).rejects.toThrow(/active lease|owned/); expect(await readFile(target, "utf8")).toBe("unrelated"); - await rm(token); await writeFile(token, credential, { mode: 0o600 }); await lease.close(); + await rm(token); await writeFile(token, cliTokenJson("fixture-refresh"), { mode: 0o600 }); await lease.close(); }); it("preserves a native OAuth rotation when startup admission never succeeds", async () => { - const root = await home(), directory = join(root, "antigravity-acp"); + const root = await home(), directory = join(root, "antigravity-acp"), cliToken = join(root, "antigravity-cli", "antigravity-oauth-token"); const lease = await stageManagedAntigravityCredential({ agentHomeDirectory: root, environment: { [ANTIGRAVITY_AUTH_ENV]: credential }, retainRefresh: () => false }); const rotated = credential.replace("fixture-refresh", "failed-startup-rotation"); - await writeFile(join(directory, "acp_token.json"), rotated, { mode: 0o600 }); + await writeFile(cliToken, cliTokenJson("failed-startup-rotation"), { mode: 0o600 }); await lease.close(); expect(await readFile(join(directory, "auth-refresh.json"), "utf8")).toBe(rotated); expect((await stat(join(directory, "auth-refresh.json"))).mode & 0o777).toBe(0o600); - await expect(stat(join(directory, "acp_token.json"))).rejects.toMatchObject({ code: "ENOENT" }); + await expect(stat(cliToken)).rejects.toMatchObject({ code: "ENOENT" }); }); it("retries the original lifetime lease after its first close fails without losing the rotated handoff", async () => { @@ -81,11 +87,11 @@ it("retries the original lifetime lease after its first close fails without losi await actual.close(); } }; }); - const root = await home(), directory = join(root, "antigravity-acp"); + const root = await home(), directory = join(root, "antigravity-acp"), cliToken = join(root, "antigravity-cli", "antigravity-oauth-token"); const input = { agentHomeDirectory: root, environment: { [ANTIGRAVITY_AUTH_ENV]: credential } }; const lease = await stageManagedAntigravityCredential(input); const rotated = credential.replace("fixture-refresh", "retry-close-rotation"); - await writeFile(join(directory, "acp_token.json"), rotated, { mode: 0o600 }); + await writeFile(cliToken, cliTokenJson("retry-close-rotation"), { mode: 0o600 }); try { await expect(lease.close()).rejects.toThrow("injected lifetime close failure"); await expect(lease.close()).resolves.toBeUndefined(); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-credentials.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-credentials.ts index 62bbe5bf671..ea6d150c537 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-credentials.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-credentials.ts @@ -1,11 +1,23 @@ import { constants } from "node:fs"; import { lstat, mkdir, open, realpath, rename, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { sanitizeAntigravityCredential } from "./antigravity-auth.js"; +import { + ANTIGRAVITY_CLI_TOKEN_DIR, ANTIGRAVITY_CLI_TOKEN_FILE, + antigravityCliStoredTokenFromCanonical, canonicalAntigravityCredentialFromCliToken, sanitizeAntigravityCredential, +} from "./antigravity-auth.js"; import { stageManagedCodexCredential, type AcpxProviderLifetimeLease } from "./codex-credentials.js"; export const ANTIGRAVITY_AUTH_ENV = "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"; +async function ensurePrivateSubdir(path: string): Promise { + await mkdir(path, { recursive: true, mode: 0o700 }); + const metadata = await lstat(path); + if (!metadata.isDirectory() || metadata.isSymbolicLink() || (metadata.mode & 0o077) !== 0 + || metadata.uid !== process.getuid?.() || await realpath(path) !== path) { + throw new Error("Antigravity credential home is unsafe"); + } +} + /** The controller's selected credential crosses stdio admission once, then lives * only in a private, fenced native home. It never enters provider environment. */ @@ -20,24 +32,28 @@ export async function stageManagedAntigravityCredential(input: { const key = source.GEMINI_API_KEY?.trim(); if (Boolean(inline) === Boolean(key)) throw new Error("Antigravity requires exactly one selected runtime credential"); const canonical = inline ? sanitizeAntigravityCredential(inline) : undefined; - const directory = join(input.agentHomeDirectory, "antigravity-acp"); - await mkdir(directory, { recursive: true, mode: 0o700 }); - const metadata = await lstat(directory); - if (!metadata.isDirectory() || metadata.isSymbolicLink() || (metadata.mode & 0o077) !== 0 - || metadata.uid !== process.getuid?.() || await realpath(directory) !== directory) { - throw new Error("Antigravity credential home is unsafe"); - } - // Reuse the established crash scrub, cleanup intent, and inherited quorum. - // The extra native token filename is scrubbed while that quorum is held. - const lease = await stageManagedCodexCredential({ agentHomeDirectory: directory, - environment: canonical ? { PAPERCLIP_ACPX_CODEX_AUTH_JSON_SECRET: canonical } : { OPENAI_API_KEY: key } }); - const token = join(directory, "acp_token.json"); - const refresh = join(directory, "auth-refresh.json"); + 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, 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], + }); try { - for (const filename of [token, refresh, `${refresh}.tmp`]) await rm(filename, { force: true }); - if (canonical) await writeFile(token, canonical, { flag: "wx", mode: 0o600 }); + 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 }); + } } catch (error) { - await rm(token, { force: true }); + await rm(cliToken, { force: true }); await lease.close(); throw error; } @@ -52,7 +68,7 @@ export async function stageManagedAntigravityCredential(input: { if (closed) return Promise.resolve(); return closing ??= (async () => { if (canonical && !tokenProcessed) { - const handle = await open(token, constants.O_RDONLY | constants.O_NOFOLLOW); + const handle = await open(cliToken, constants.O_RDONLY | constants.O_NOFOLLOW); try { const stat = await handle.stat(); if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.() @@ -66,7 +82,8 @@ export async function stageManagedAntigravityCredential(input: { size += read.bytesRead; } if (size > 65_536) throw new Error("Antigravity refreshed credential exceeds its bound"); - const refreshed = sanitizeAntigravityCredential(buffer.subarray(0, size).toString("utf8")); + const raw = buffer.subarray(0, size).toString("utf8"); + const refreshed = canonicalAntigravityCredentialFromCliToken(raw, canonical).credential; // Failed/cancelled startup can still consume a refresh token. // Admission controls retaining an unchanged copy, never rotation. if (refreshed !== canonical || (input.retainRefresh?.() ?? true)) { @@ -74,7 +91,7 @@ export async function stageManagedAntigravityCredential(input: { const handoff = await open(`${refresh}.tmp`, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600); try { await handoff.writeFile(refreshed); await handoff.sync(); } finally { await handoff.close(); } await rename(`${refresh}.tmp`, refresh); - const parent = await open(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); + const parent = await open(acpDirectory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW); try { await parent.sync(); } finally { await parent.close(); } } } finally { buffer.fill(0); await rm(`${refresh}.tmp`, { force: true }); } @@ -83,8 +100,10 @@ export async function stageManagedAntigravityCredential(input: { // reopening the token removed only after this durable handoff. tokenProcessed = true; } - await rm(token, { force: true }); - await rm(join(directory, "logs"), { recursive: true, force: true }); + 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; })().finally(() => { closing = undefined; }); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-installation.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-installation.ts index 777f514ce23..c699de7bc21 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-installation.ts @@ -43,22 +43,40 @@ function providerPackDistribution(pack: string, key: string): string | undefined return realDirectoryExists(directory, "Antigravity provider pack runtime must be a real directory") ? directory : undefined; } -export function antigravityNativeDistributionSpec(platform: NodeJS.Platform = process.platform, architecture: string = process.arch): NativeAcpxDistributionInput { +export function antigravityNativeDistributionSpec( + platform: NodeJS.Platform = process.platform, + architecture: string = process.arch, + extraArguments: readonly string[] = [], + options: { home?: string; environment?: NodeJS.ProcessEnv } = {}, +): NativeAcpxDistributionInput { const key = `${platform}-${architecture}`; if (!Object.hasOwn(ANTIGRAVITY_DISTRIBUTION_PINS, key)) throw new Error(`Antigravity has no admitted complete runtime closure for ${key}`); + if (!Array.isArray(extraArguments) || extraArguments.length > 64 || extraArguments.some(arg => typeof arg !== "string" || arg.length > 16_384 || arg.includes("\0"))) { + throw new Error("Antigravity launch arguments are invalid"); + } const pin = ANTIGRAVITY_DISTRIBUTION_PINS[key as keyof typeof ANTIGRAVITY_DISTRIBUTION_PINS]; const packaged = join(resolveRunnerProviderAssetsRoot(import.meta.url, "antigravity"), key); let distributionRoot = packaged; if (!realDirectoryExists(packaged, "Antigravity packaged runtime must be a real directory")) { - const pack = antigravityProviderPackRoot(); + const pack = antigravityProviderPackRoot(options.environment); distributionRoot = (pack === undefined ? undefined : providerPackDistribution(pack, key)) - ?? antigravityRuntimeCachePath(pin.closureSha256, platform, architecture); + ?? antigravityRuntimeCachePath(pin.closureSha256, platform, architecture, options.home); } - return { distributionRoot, manifestPath: join(distributionRoot, ".paperclip-antigravity-closure.json"), expectedClosureSha256: pin.closureSha256, - executable: pin.executable, fixedArguments: [...pin.args], storeFamily: "antigravity" }; + return { + distributionRoot, + manifestPath: join(distributionRoot, ".paperclip-antigravity-closure.json"), + expectedClosureSha256: pin.closureSha256, + executable: pin.executable, + fixedArguments: [...pin.args, ...extraArguments], + storeFamily: "antigravity", + }; } -export async function verifyAntigravityInstallation(profile: QualifiedAcpxProfile, candidateAdmission?: AcpxCandidateStartupAdmission): Promise { +export async function verifyAntigravityInstallation( + profile: QualifiedAcpxProfile, + candidateAdmission?: AcpxCandidateStartupAdmission, + extraArguments: readonly string[] = [], +): Promise { assertAcpxExecutionAdmission(profile, candidateAdmission); const trusted = QUALIFIED_ACPX_PROFILES.antigravity; const modelFields = new Set(["qualificationModel", "reportedModelId"]); @@ -67,5 +85,5 @@ export async function verifyAntigravityInstallation(profile: QualifiedAcpxProfil || !profile.qualificationModel?.trim() || profile.reportedModelId !== profile.qualificationModel) { throw new Error("Antigravity installation requires its exact pinned profile and an explicit model"); } - return { ...await verifyNativeAcpxInstallation(antigravityNativeDistributionSpec()), commandDigest: trusted.commandDigest }; + return { ...await verifyNativeAcpxInstallation(antigravityNativeDistributionSpec(process.platform, process.arch, extraArguments)), commandDigest: trusted.commandDigest }; } diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-model-catalog.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-model-catalog.test.ts index 97f6f77ae6e..a61f948c476 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-model-catalog.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-model-catalog.test.ts @@ -40,17 +40,17 @@ DEFAULT_MODEL_METADATA_MAP = { describe("Antigravity model catalog generator", () => { it("accepts the committed catalog against the checked-in runtime declaration", async () => { const catalog = await generator.checkAntigravityModelCatalog(); - expect(catalog.apiKey.models).toHaveLength(14); - expect(catalog.source.runtimeVersion).toBe("1.5.2"); + expect(catalog.apiKey.models).toHaveLength(25); + expect(catalog.source.runtimeVersion).toBe("1.5.19"); }); it("rejects the catalog once the pinned runtime changes", async () => { const directory = await scratch(); const declaration = JSON.parse(await readFile(declarationPath, "utf8")); - declaration.version = "1.5.3"; + declaration.version = "1.5.20"; await writeFile(join(directory, "declaration.json"), JSON.stringify(declaration)); await expect(generator.checkAntigravityModelCatalog({ declarationPath: join(directory, "declaration.json") })).rejects.toThrow(/stale/); - declaration.version = "1.5.2"; + declaration.version = "1.5.19"; declaration.platforms["darwin-arm64"].archiveSha256 = "0".repeat(64); await writeFile(join(directory, "declaration.json"), JSON.stringify(declaration)); await expect(generator.checkAntigravityModelCatalog({ declarationPath: join(directory, "declaration.json") })).rejects.toThrow(/stale/); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-models.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-models.test.ts index 72f7b8121da..6fe9862d70d 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-models.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-models.test.ts @@ -7,7 +7,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { CodexAcpxDriver } from "./codex-acpx-driver.js"; import { acpxCapabilities, acpxDriverDescriptor, validateAcpxDriverConfig } from "./driver-profile.js"; import { verifyQualifiedAcpxInstallation } from "./installation-integrity.js"; -import { verifyAcpxProfileInstallation } from "./profile-installation.js"; import { assertAcpxProfileReleased, resolveQualifiedAcpxProfile } from "./qualified-profiles.js"; const setup = vi.hoisted(() => ({ spawn: vi.fn(), close: vi.fn(async () => undefined), verify: vi.fn(), uncertainRetirement: false, spec: vi.fn((..._args: unknown[]) => ({ pinned: true })) })); @@ -47,23 +46,22 @@ const reply=(id,result)=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',id,r reader.on('line',line=>{ const request=JSON.parse(line);requests.push(request);fs.writeFileSync(path.join(home,'requests.json'),JSON.stringify(requests)); if(request.method==='initialize') { - reply(request.id,{protocolVersion:1,agentInfo:{name:'antigravity-acp',version:'1.5.2'},agentCapabilities:{_meta:{antigravity:{paperclipAdmission:1,paperclipModels:mode==='old-patch'?0:1}}},authMethods:[{id:'oauth-personal'}]}); - } else if(request.method==='_paperclip/models') { + reply(request.id,{protocolVersion:1,agentInfo:{name:mode==='wrong-agent'?'other-acp':'Antigravity ACP Server',version:mode==='wrong-version'?'1.5.2':'1.5.19'},agentCapabilities:{_meta:{antigravity:{systemPrompt:{append:true}}}},authMethods:[{id:'oauth-personal'}]}); + } else if(request.method==='session/new') { if(mode==='blocked'||mode==='stubborn') return; if(mode==='error') {process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:request.id,error:{code:-32000,message:'private-token-do-not-expose'}})+'\\n');return;} if(mode==='bad-utf8') {process.stdout.write(Buffer.from([255,10]));return;} - if(mode==='overflow') {process.stdout.write('x'.repeat(1048577));return;} - const result={schema:request.params.schema,nonce:request.params.nonce,authMethod:'oauth-personal',models:[{id:'gemini-pro-agent',label:'Gemini Pro (High)'},{id:'gemini-3.1-pro-low',label:'Gemini Pro (Low)'}],defaultModelId:'gemini-pro-agent',ignoredPrivateData:'private-token-do-not-expose'}; - if(mode==='wrong-nonce') result.nonce='stale-nonce'; - if(mode==='wrong-auth') result.authMethod='gemini-api-key'; - if(mode==='wrong-schema') result.schema='another-schema'; - if(mode==='duplicate') result.models.push(result.models[0]); - if(mode==='unknown-default') result.defaultModelId='unavailable-model'; - if(mode==='bad-label') result.models[0].label='bad\\u0000label'; - if(mode==='auto-model') result.models[0].id='auto'; - if(mode==='many-models') result.models=Array.from({length:201},(_,i)=>({id:'gemini-'+i,label:'Gemini '+i})); - reply(mode==='wrong-id'?91:request.id,result); - } else throw new Error('setup sent forbidden authentication/session/prompt method'); + if(mode==='overflow') {process.stdout.write('x'.repeat(2*1024*1024+10));return;} + const models=[{modelId:'gemini-4-neon-high',name:'Gemini 4 Neon (High)'},{modelId:'gemini-3.8-flash-low',name:'Gemini 3.8 Flash (Low)'}]; + let currentModelId='gemini-4-neon-high'; + if(mode==='duplicate') models.push(models[0]); + if(mode==='unknown-default') currentModelId='unavailable-model'; + if(mode==='bad-label') models[0].name='bad\\u0000label'; + if(mode==='auto-model') models[0].modelId='auto'; + if(mode==='many-models') models.splice(0,models.length,...Array.from({length:201},(_,i)=>({modelId:'gemini-'+i,name:'Gemini '+i}))); + if(mode==='empty-models') models.splice(0,models.length); + reply(mode==='wrong-id'?91:request.id,{sessionId:'s-catalog',models:{availableModels:models,currentModelId}}); + } else throw new Error('unexpected method '+request.method); }); reader.on('close',()=>mode==='stubborn'||mode==='blocked'?setInterval(()=>{},1000):process.exit(0)); `); @@ -74,24 +72,29 @@ reader.on('close',()=>mode==='stubborn'||mode==='blocked'?setInterval(()=>{},100 return home; } -describe("Antigravity session-free account model discovery", () => { - it("returns only nonce-bound account models after process retirement with no ambient auth or direct account requests", async () => { +describe("Antigravity prompt-free account model discovery", () => { + it("returns account models from agy acp session/new after process retirement with no ambient auth", async () => { const home = await fixture(), fetch = vi.fn(() => { throw new Error("direct account requests forbidden"); }); vi.stubGlobal("fetch", fetch); const result = await discoverAntigravityModels(home); - expect(result).toEqual({ models: [{ id: "gemini-pro-agent", label: "Gemini Pro (High)" }, { id: "gemini-3.1-pro-low", label: "Gemini Pro (Low)" }], defaultModelId: "gemini-pro-agent" }); + expect(result).toEqual({ + models: [{ id: "gemini-4-neon-high", label: "Gemini 4 Neon (High)" }, { id: "gemini-3.8-flash-low", label: "Gemini 3.8 Flash (Low)" }], + defaultModelId: "gemini-4-neon-high", + }); const requests = JSON.parse(await readFile(join(home, "requests.json"), "utf8")); - expect(requests.map((value: { method: string }) => value.method)).toEqual(["initialize", "_paperclip/models"]); - expect(requests[1].params).toEqual({ schema: "paperclip.antigravity.models.v1", nonce: expect.any(String), authMethod: "oauth-personal" }); - expect(setup.spawn.mock.calls[0]![1]).toMatchObject({ detached: true, env: { GEMINI_HOME: home, AGY_ACP_FORCE_FILE_STORAGE: "1", BROWSER: "/usr/bin/true" } }); + expect(requests.map((value: { method: string }) => value.method)).toEqual(["initialize", "session/new"]); + expect(setup.spawn.mock.calls[0]![1]).toMatchObject({ + detached: true, + env: { GEMINI_HOME: home, AGY_CLI_FORCE_FILE_TOKEN_STORAGE: "1", AGY_CLI_DISABLE_AUTO_UPDATE: "1", BROWSER: "/usr/bin/true" }, + }); expect(Object.keys(setup.spawn.mock.calls[0]![1].env).some(key => /^(?:GOOGLE_|GEMINI_API|ANTIGRAVITY_|PYTHON|NODE_OPTIONS|HTTP_PROXY)/.test(key))).toBe(false); expect(children[0]!.exitCode).toBe(0); expect(setup.close).toHaveBeenCalledOnce(); expect(fetch).not.toHaveBeenCalled(); }); - it.each(["old-patch", "wrong-nonce", "wrong-auth", "wrong-schema", "wrong-id", "duplicate", "unknown-default", "bad-label", "auto-model", "many-models", "bad-utf8", "overflow", "error"])("rejects %s and retires the process without exposing native text", async mode => { + it.each(["wrong-agent", "wrong-version", "wrong-id", "duplicate", "unknown-default", "bad-label", "auto-model", "many-models", "empty-models", "bad-utf8", "overflow", "error"])("rejects %s and retires the process without exposing native text", async mode => { const home = await fixture(mode); await expect(discoverAntigravityModels(home)).rejects.toThrow("Could not load models for this Google account"); expect(children[0]!.exitCode).toBe(0); expect(setup.close).toHaveBeenCalledOnce(); - if (mode === "old-patch") expect(JSON.parse(await readFile(join(home, "requests.json"), "utf8"))).toHaveLength(1); + if (mode === "wrong-agent" || mode === "wrong-version") expect(JSON.parse(await readFile(join(home, "requests.json"), "utf8"))).toHaveLength(1); }); it("reports a missing runtime by its own error without launching", async () => { @@ -144,7 +147,7 @@ describe("Antigravity session-free account model discovery", () => { expect(Date.now() - start).toBeGreaterThanOrEqual(29_500); expect(Date.now() - start).toBeLessThan(35_000); expect(children[0]!.signalCode).toBe("SIGTERM"); expect(setup.close).toHaveBeenCalledOnce(); - expect(JSON.parse(await readFile(join(home, "requests.json"), "utf8")).map((value: { method: string }) => value.method)).toEqual(["initialize", "_paperclip/models"]); + expect(JSON.parse(await readFile(join(home, "requests.json"), "utf8")).map((value: { method: string }) => value.method)).toEqual(["initialize", "session/new"]); }, 40_000); }); @@ -156,10 +159,10 @@ describe("Antigravity qualified release boundaries", () => { expect(acpxCapabilities("copilot")).toMatchObject({ typedEvents: true, dynamicTools: true }); }); - it("preserves the caller's exact model under the qualified revision 2 profile", () => { + it("preserves the caller's exact model under the qualified revision 3 profile", () => { const profile = resolveQualifiedAcpxProfile("antigravity", "caller-exact-model"); expect(profile).toMatchObject({ - agent: "antigravity", agentProfileVersion: 2, qualificationModel: "caller-exact-model", reportedModelId: "caller-exact-model", + agent: "antigravity", agentProfileVersion: 3, qualificationModel: "caller-exact-model", reportedModelId: "caller-exact-model", }); expect(profile.qualificationStatus).toBeUndefined(); expect(validateAcpxDriverConfig({ agent: "antigravity", model: "caller-exact-model" })) diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-models.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-models.ts index 69b0ef7e9f3..fad8daabda1 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-models.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-models.ts @@ -1,14 +1,21 @@ import type { ChildProcessWithoutNullStreams } from "node:child_process"; +import { constants } from "node:fs"; +import { lstat, mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises"; import { randomUUID } from "node:crypto"; +import { join } from "node:path"; +import { + ANTIGRAVITY_CLI_TOKEN_DIR, ANTIGRAVITY_CLI_TOKEN_FILE, + antigravityCliStoredTokenFromCanonical, canonicalAntigravityCredentialFromCliToken, sanitizeAntigravityCredential, +} from "./antigravity-auth.js"; import { antigravityNativeDistributionSpec } from "./antigravity-installation.js"; import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.js"; import { antigravityPrivateEnvironment, checkAntigravityPrivateHome, retireAntigravityProcess } from "./antigravity-process.js"; import { verifyNativeAcpxInstallation, type VerifiedAcpxCommandLease } from "./installation-integrity.js"; import { AntigravityRuntimeUnavailableError } from "./antigravity-runtime-unavailable.js"; -const SCHEMA = "paperclip.antigravity.models.v1"; +const AGENT_NAME = "Antigravity ACP Server"; const ERROR = "Could not load models for this Google account. Retry or sign in again."; -const MAX_WIRE_BYTES = 1024 * 1024; +const MAX_WIRE_BYTES = 2 * 1024 * 1024; const record = (value: unknown): Record => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; export type AntigravityModelCatalog = { models: Array<{ id: string; label: string }>; defaultModelId: string }; @@ -28,17 +35,22 @@ export class AntigravityModelDiscoveryCleanupError extends Error { } } -function retainCatalogCleanup(child: ChildProcessWithoutNullStreams | undefined, closed: Promise | undefined, lease: VerifiedAcpxCommandLease): Promise { +function retainCatalogCleanup( + child: ChildProcessWithoutNullStreams | undefined, + closed: Promise | undefined, + lease: VerifiedAcpxCommandLease | undefined, + home: string, + staged: { canonical: string; cliTokenPath: string } | null, +): Promise { let observedClose = child === undefined; + let retired = !child || !closed; + let leaseClosed = !lease; void closed?.then(() => { observedClose = true; }); return (async () => { - // This retry belongs only to an unresolved, active process/lease cleanup. - // Close wakes it immediately; successful cleanup leaves no timer or work. - while (true) { + while (!retired || !leaseClosed) { try { - if (child && closed) await retireAntigravityProcess(child, closed); - await lease.close(); - return; + if (!retired) { await retireAntigravityProcess(child!, closed!); retired = true; } + if (!leaseClosed) { await lease!.close(); leaseClosed = true; } } catch { let timer: ReturnType | undefined; const retry = new Promise(resolve => { timer = setTimeout(resolve, 1_000); }); @@ -46,29 +58,82 @@ function retainCatalogCleanup(child: ChildProcessWithoutNullStreams | undefined, finally { if (timer) clearTimeout(timer); } } } + try { await syncAndCleanCliToken(home, staged); } catch { /* best-effort after retirement */ } })(); } -function catalog(value: unknown, nonce: string): AntigravityModelCatalog { - const response = record(value); - if (response.schema !== SCHEMA || response.nonce !== nonce || response.authMethod !== "oauth-personal" - || !Array.isArray(response.models) || response.models.length < 1 || response.models.length > 200) throw new Error(ERROR); +function catalogFromSessionResult(value: unknown): AntigravityModelCatalog { + const session = record(value); + const modelsBlock = record(session.models); + const available = modelsBlock.availableModels; + if (!Array.isArray(available) || available.length < 1 || available.length > 200) throw new Error(ERROR); const ids = new Set(), models: AntigravityModelCatalog["models"] = []; - for (const value of response.models) { - const model = record(value); - if (typeof model.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,511}$/.test(model.id) - || ["auto", "default"].includes(model.id.toLowerCase()) || ids.has(model.id) - || typeof model.label !== "string" || !model.label.trim() || model.label.length > 200 || /[\x00-\x1f\x7f]/.test(model.label)) throw new Error(ERROR); - ids.add(model.id); models.push({ id: model.id, label: model.label }); + for (const item of available) { + const model = record(item); + const id = typeof model.modelId === "string" ? model.modelId : typeof model.id === "string" ? model.id : ""; + const label = typeof model.name === "string" ? model.name.trim() : typeof model.label === "string" ? model.label.trim() : ""; + if (!/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,511}$/.test(id) + || ["auto", "default"].includes(id.toLowerCase()) || ids.has(id) + || !label || label.length > 200 || /[\x00-\x1f\x7f]/.test(label)) throw new Error(ERROR); + ids.add(id); + models.push({ id, label }); } - if (typeof response.defaultModelId !== "string" || !ids.has(response.defaultModelId)) throw new Error(ERROR); - return { models, defaultModelId: response.defaultModelId }; + const current = typeof modelsBlock.currentModelId === "string" ? modelsBlock.currentModelId : models[0]!.id; + if (!ids.has(current)) throw new Error(ERROR); + return { models, defaultModelId: current }; } -/** Read-only account catalog discovery through the pinned native implementation. +/** Project `/antigravity-acp/acp_token.json` into `/antigravity-cli/antigravity-oauth-token`. */ +async function stageCliTokenFromAcpHome(home: string): Promise<{ canonical: string; cliTokenPath: string } | null> { + const acpTokenPath = join(home, "antigravity-acp", "acp_token.json"); + let raw: string; + try { raw = await readFile(acpTokenPath, "utf8"); } + catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; } + const canonical = sanitizeAntigravityCredential(raw); + const cliDir = join(home, ANTIGRAVITY_CLI_TOKEN_DIR); + await mkdir(cliDir, { recursive: true, mode: 0o700 }); + const stat = await lstat(cliDir); + if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077) !== 0) { + throw new Error(ERROR); + } + const cliTokenPath = join(cliDir, ANTIGRAVITY_CLI_TOKEN_FILE); + await rm(cliTokenPath, { force: true }); + await writeFile(cliTokenPath, antigravityCliStoredTokenFromCanonical(canonical), { flag: "wx", mode: 0o600 }); + return { canonical, cliTokenPath }; +} + +/** 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 { + if (!staged) return; + let raw: string | null = null; + try { + 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. * The caller owns the private projected credential home and any refreshed-secret - * writeback. Execution retires before ordinary results/errors. A cleanup error - * transfers the home-retention obligation through its retired completion. + * writeback. Execution retires before ordinary results/errors. */ export async function discoverAntigravityModels( home: string, @@ -79,22 +144,26 @@ export async function discoverAntigravityModels( let lease: VerifiedAcpxCommandLease | undefined, child: ChildProcessWithoutNullStreams | undefined, closed: Promise | undefined; let result: AntigravityModelCatalog | undefined, failure: Error | undefined; let cleanupError: AntigravityModelDiscoveryCleanupError | undefined; + let staged: { canonical: string; cliTokenPath: string } | null = null; try { signal.throwIfAborted(); await checkAntigravityPrivateHome(home); + staged = await stageCliTokenFromAcpHome(home); signal.throwIfAborted(); let installation; try { - installation = await verifyNativeAcpxInstallation(antigravityNativeDistributionSpec()); + 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: home, stdio: "pipe", detached: process.platform !== "win32", env: environment }) as ChildProcessWithoutNullStreams; + 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())); - const nonce = randomUUID(); result = await new Promise((resolve, reject) => { let phase = 1, stdout = "", outputBytes = 0, errorBytes = 0; const decoder = new TextDecoder("utf-8", { fatal: true }); @@ -103,7 +172,7 @@ export async function discoverAntigravityModels( signal.addEventListener("abort", abort, { 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: "_paperclip/models", params: { schema: SCHEMA, nonce, authMethod: "oauth-personal" } })}\n`); + : { jsonrpc: "2.0", id, method: "session/new", params: { cwd: workspace, mcpServers: [] } })}\n`); peer.stdout.on("data", (chunk: Buffer) => { outputBytes += chunk.length; if (outputBytes > MAX_WIRE_BYTES) { fail(); return; } @@ -113,22 +182,27 @@ export async function discoverAntigravityModels( if (!line.trim()) continue; let message: Record; try { message = record(JSON.parse(line)); } catch { fail(); return; } - if (phase > 2 || message.jsonrpc !== "2.0" || message.id !== phase || "method" in message || "error" in message || !Object.hasOwn(message, "result")) { fail(); return; } + // Ignore server-sent notifications (such as available_commands_update / usage_update). + 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), capabilities = record(record(record(initialized.agentCapabilities)._meta).antigravity); - if (initialized.protocolVersion !== 1 || info.name !== "antigravity-acp" || info.version !== ANTIGRAVITY_RUNTIME_VERSION - || capabilities.paperclipAdmission !== 1 || capabilities.paperclipModels !== 1 + const initialized = record(message.result), info = record(initialized.agentInfo); + if (initialized.protocolVersion !== 1 || info.name !== AGENT_NAME || info.version !== ANTIGRAVITY_RUNTIME_VERSION || !Array.isArray(initialized.authMethods) || !initialized.authMethods.some(value => record(value).id === "oauth-personal")) { fail(); return; } phase = 2; send(2); } else { - try { const models = catalog(message.result, nonce); phase = 3; resolve(models); } catch { fail(); } + try { const models = catalogFromSessionResult(message.result); phase = 3; resolve(models); } catch { fail(); } } } }); peer.stdout.once("end", () => { try { stdout += decoder.decode(); if (stdout.trim()) fail(); } catch { fail(); } }); - // Native error text may contain private account data. Count and discard. peer.stderr.on("data", (chunk: Buffer) => { errorBytes += chunk.length; if (errorBytes > MAX_WIRE_BYTES) fail(); }); peer.once("error", fail); peer.once("close", () => { signal.removeEventListener("abort", abort); if (phase !== 3) fail(); }); @@ -137,15 +211,28 @@ export async function discoverAntigravityModels( }); } catch (error) { failure ??= error instanceof AntigravityRuntimeUnavailableError ? error : new Error(ERROR); } finally { + let retired = !child || !closed; + let leaseClosed = !lease; try { - if (child && closed) await retireAntigravityProcess(child, closed); - await lease?.close(); + if (!retired) { await retireAntigravityProcess(child!, closed!); retired = true; } + if (!leaseClosed) { await lease!.close(); leaseClosed = true; } + await syncAndCleanCliToken(home, staged); } catch (error) { - if (lease) cleanupError = new AntigravityModelDiscoveryCleanupError( - retainCatalogCleanup(child, closed, lease), failure, - error instanceof Error ? error : new Error("Antigravity process retirement or command lease release could not be confirmed"), - ); - else failure ??= new Error(ERROR); + if (lease || staged) { + cleanupError = new AntigravityModelDiscoveryCleanupError( + retainCatalogCleanup( + retired ? undefined : child, + retired ? undefined : closed, + leaseClosed ? undefined : lease, + home, + staged, + ), + failure, + error instanceof Error ? error : new Error("Antigravity process retirement, command lease release, or credential sync could not be confirmed"), + ); + } else { + failure ??= new Error(ERROR); + } } clearTimeout(timer); } diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts index 668b0906baa..e35a263d4e2 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-process.ts @@ -23,8 +23,9 @@ export async function antigravityPrivateEnvironment(home: string): Promise = {}) { return { protocolVersion: 1, agentCapabilities: { _meta: { antigravity: { systemPrompt: { append: true } } } }, - agentInfo: { name: "Antigravity ACP Server", version: "1.5.15" }, + agentInfo: { name: "Antigravity ACP Server", version: "1.5.19" }, ...overrides, }; } @@ -63,16 +63,16 @@ function admitted() { describe("Antigravity CLI swarm guard (replaces the registry admission receipt)", () => { it("records a receipt when identity, workspace, tools, instructions, auto mode and model all read back", () => { expect(admitted().receipt()).toMatchObject({ - agentName: "Antigravity ACP Server", agentVersion: "1.5.15", sessionId: SESSION, workspace: WORKSPACE, + agentName: "Antigravity ACP Server", agentVersion: "1.5.19", sessionId: SESSION, workspace: WORKSPACE, mode: "auto", model: "gemini-3.8-flash-low", modelFamily: "gemini-3.8-flash", thoughtLevel: "low", mcpServers: ["paperclip"], }); }); it("refuses a CLI that is not the pinned identity or cannot take Paperclip's instructions", () => { const guard = () => createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE }); - expect(() => guard().initialize(initializeResult({ agentInfo: { name: "Antigravity ACP Server", version: "1.5.16" } }))) + expect(() => guard().initialize(initializeResult({ agentInfo: { name: "Antigravity ACP Server", version: "1.5.20" } }))) .toThrow(expect.objectContaining({ code: "ANTIGRAVITY_SWARM_RECEIPT_MISMATCH" })); - expect(() => guard().initialize(initializeResult({ agentInfo: { name: "antigravity-acp", version: "1.5.15" } }))).toThrow(/pinned version/); + expect(() => guard().initialize(initializeResult({ agentInfo: { name: "antigravity-acp", version: "1.5.19" } }))).toThrow(/pinned version/); expect(() => guard().initialize(initializeResult({ agentCapabilities: {} }))).toThrow(/instructions/); }); @@ -97,6 +97,23 @@ describe("Antigravity CLI swarm guard (replaces the registry admission receipt)" .toThrow(expect.objectContaining({ code: "ANTIGRAVITY_SWARM_UNAVAILABLE" })); }); + it("allows default mode in Cloud sandboxes launched with --dangerously-skip-permissions when auto mode is unavailable", () => { + const guard = createAntigravitySwarmGuard({ + model: "gemini-3.8-flash-low", + instructions: INSTRUCTIONS, + workspace: WORKSPACE, + allowSkipPermissionsDefaultMode: true, + }); + guard.initialize(initializeResult()); + guard.sessionRequest(sessionRequest()); + expect(guard.sessionResult(sessionResult(["default", "accept-edits", "plan"]))).toBe(SESSION); + expect(guard.targetMode()).toBe("default"); + guard.bindMode(); + guard.observe(config("gemini-3.8-flash", "low", "default")); + guard.bindModel(); + expect(guard.receipt()).toMatchObject({ mode: "default", model: "gemini-3.8-flash-low" }); + }); + it("fails closed when mode or model does not read back, or changes afterwards", () => { const base = () => { const guard = createAntigravitySwarmGuard({ model: "gemini-3.8-flash-low", instructions: INSTRUCTIONS, workspace: WORKSPACE }); @@ -180,7 +197,7 @@ describe("Antigravity CLI swarm guard (replaces the registry admission receipt)" guard.observe(config("gemini-4-neon", cliLevel!)); guard.bindModel(); expect(guard.receipt()).toMatchObject({ model: `gemini-4-neon-${level}`, modelFamily: "gemini-4-neon", thoughtLevel: cliLevel, - agentVersion: "1.5.15", modelName: expect.stringMatching(/^Gemini 4 Neon \((Low|Medium|High|XHigh)\)$/) }); + agentVersion: "1.5.19", modelName: expect.stringMatching(/^Gemini 4 Neon \((Low|Medium|High|XHigh)\)$/) }); } }); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts index fd034ffae2a..5d2443a8854 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-guard.ts @@ -117,7 +117,7 @@ export interface AntigravitySwarmReceipt { agentVersion: string; sessionId: string; workspace: string; - mode: typeof ANTIGRAVITY_CLI_SESSION_MODE; + mode: typeof ANTIGRAVITY_CLI_SESSION_MODE | "default"; model: string; /** The CLI's own name for the confirmed model, for people. */ modelName: string; @@ -133,6 +133,8 @@ export interface AntigravitySwarmGuardOptions { channel?: GeneratedAntigravitySwarmChannel; instructions: string; workspace: string; + /** Cloud/sandbox runs launched with `--dangerously-skip-permissions` may run in `default` mode when the OS lacks user namespaces for `auto`. */ + allowSkipPermissionsDefaultMode?: boolean; } type Json = Record; @@ -162,6 +164,7 @@ export function createAntigravitySwarmGuard(options: AntigravitySwarmGuardOption const instructionDigest = antigravitySwarmInstructionDigest(options.instructions); const state = { agentName: "", agentVersion: "", sessionId: "", modeBound: false, modelBound: false, + expectedMode: ANTIGRAVITY_CLI_SESSION_MODE as typeof ANTIGRAVITY_CLI_SESSION_MODE | "default", selections: new Map(), commands: null as string[] | null, mcpServers: [] as string[], modelName: "", }; const assertStable = (next: Map) => { @@ -204,7 +207,12 @@ export function createAntigravitySwarmGuard(options: AntigravitySwarmGuardOption const value = record(result); if (typeof value.sessionId !== "string" || !value.sessionId || value.sessionId.length > 256) mismatch("the provider did not open a session"); const modes = record(value.modes).availableModes; - if (!Array.isArray(modes) || !modes.some(mode => record(mode).id === ANTIGRAVITY_CLI_SESSION_MODE)) { + const modeIds = Array.isArray(modes) ? modes.map(mode => record(mode).id).filter((id): id is string => typeof id === "string") : []; + if (modeIds.includes(ANTIGRAVITY_CLI_SESSION_MODE)) { + state.expectedMode = ANTIGRAVITY_CLI_SESSION_MODE; + } else if (options.allowSkipPermissionsDefaultMode === true && modeIds.includes("default")) { + state.expectedMode = "default"; + } else { throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", "Swarm is not available with this Google connection: helpers can only change files in Antigravity's auto mode, which this sign-in does not offer."); } @@ -241,9 +249,12 @@ export function createAntigravitySwarmGuard(options: AntigravitySwarmGuardOption state.commands = update.availableCommands.map(command => String(record(command).name)); } }, - /** After `session/set_mode auto`: the read-back must say `auto`. */ + targetMode(): typeof ANTIGRAVITY_CLI_SESSION_MODE | "default" { + return state.expectedMode; + }, + /** After `session/set_mode`: the read-back must match the expected mode (`auto`, or `default` under `--dangerously-skip-permissions`). */ bindMode(): void { - if (state.selections.get("mode") !== ANTIGRAVITY_CLI_SESSION_MODE) mismatch("the provider did not confirm auto mode"); + if (state.selections.get("mode") !== state.expectedMode) mismatch(`the provider did not confirm ${state.expectedMode} mode`); state.modeBound = true; }, /** After `session/set_model `: family plus thinking level must read back as that model. */ @@ -264,7 +275,7 @@ export function createAntigravitySwarmGuard(options: AntigravitySwarmGuardOption const family = state.selections.get("model")!; return { agentName: state.agentName, agentVersion: state.agentVersion, sessionId: state.sessionId, - workspace: options.workspace, mode: ANTIGRAVITY_CLI_SESSION_MODE, model, modelName: state.modelName, modelFamily: family, + workspace: options.workspace, mode: state.expectedMode, model, modelName: state.modelName, modelFamily: family, thoughtLevel: family === model ? null : state.selections.get("thought_level") ?? null, instructionDigest, mcpServers: [...state.mcpServers], }; diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts index 07243f128d2..bca44c0cf5f 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.test.ts @@ -42,11 +42,14 @@ describe("Antigravity swarm route selection", () => { "--gemini-dir", "/home/run/antigravity-cli", "--log-file", "/home/run/antigravity-cli/cli.log", "--cloud_code_endpoint", "https://cloudcode-pa.googleapis.com", "--disable-telemetry", ]); + expect(antigravitySwarmArguments("/home/run/antigravity-cli", "provider_default", { dangerouslySkipPermissions: true })).toEqual([ + "--dangerously-skip-permissions", "--gemini-dir", "/home/run/antigravity-cli", "--log-file", "/home/run/antigravity-cli/cli.log", "--disable-telemetry", + ]); const environment = antigravitySwarmLaunchEnvironment( { HOME: "/private/home", GEMINI_HOME: "/private", AGY_ACP_FORCE_FILE_STORAGE: "1", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "s", GEMINI_API_KEY: "k", PATH: "/usr/bin" }, { agentHomeDirectory: "/private", platform: "linux" }); - expect(environment).toEqual({ HOME: "/private/home", PATH: "/usr/bin", AGY_CLI_DISABLE_AUTO_UPDATE: "1" }); - expect(antigravitySwarmLaunchEnvironment({ HOME: "/private/home" }, { agentHomeDirectory: "/private", platform: "darwin", realHome: "/Users/owner" }).HOME).toBe("/Users/owner"); + expect(environment).toEqual({ HOME: "/private/home", PATH: "/usr/bin", AGY_CLI_DISABLE_AUTO_UPDATE: "1", AGY_CLI_FORCE_FILE_TOKEN_STORAGE: "1" }); + expect(antigravitySwarmLaunchEnvironment({ HOME: "/private/home" }, { agentHomeDirectory: "/private", platform: "darwin", realHome: "/Users/owner" }).HOME).toBe("/private/home"); }); it("reads the channel and the connection account digest the controller bound to the credential, defaulting safely", () => { @@ -93,6 +96,24 @@ describe("Antigravity swarm route selection", () => { expect(await runtime.identity()).toMatchObject({ mode: "swarm" }); await runtime.close({ reason: "done" }); }); + + it("routes an ordinary Antigravity turn to the direct CLI runtime instead of ACPX", async () => { + const root = realpathSync(mkdtempSync(join(tmpdir(), "agy-ordinary-route-"))); + roots.push(root); + const cwd = join(root, "workspace"); + mkdirSync(cwd); + const runtime = await openQualifiedAcpxRuntime({ + command: { spawn: () => spawn(process.execPath, [FIXTURE], { cwd, detached: true, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, FAKE_AGY_SCENARIO: "success" } }), close: async () => {} }, + profile: { agent: "antigravity", reportedModelId: "gemini-3.8-flash-low", qualificationModel: "gemini-3.8-flash-low" }, + cwd, stateDirectory: root, providerSessionKey: "key", permissionMode: "approve-reads", + permissionPolicy: {}, launchEnvironment: {}, credentialFenceFds: null, activateCredentialFenceOwner: null, systemInstructions: "x", + mcpServers: [{ name: "paperclip", url: "http://127.0.0.1:9/mcp", bearerToken: "t", runnerOwned: true }], retainFailedAdmissionCleanup: () => {}, + } as unknown as AcpxRuntimePortOpenOptions, { + createRuntime: () => { throw new Error("ordinary Antigravity turns must not enter ACPX"); }, + }); + expect(await runtime.identity()).toMatchObject({ mode: "persistent" }); + await runtime.close({ reason: "done" }); + }); }); describe("swarm hand-in instructions", () => { diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts index bcb195380a9..7644e4c72d4 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-route.ts @@ -36,9 +36,11 @@ export function antigravitySwarmHandInInstructions(contract: { revision: string; ].join("\n"); } -/** Private CLI state (settings, skills, conversations) under the run's credential home. */ +/** Private CLI state (`--gemini-dir`) under the run's credential home. + * `agy` reads/writes `/antigravity-cli/antigravity-oauth-token`, so + * passing `agentHomeDirectory` aligns `--gemini-dir` directly with staged credentials. */ export function antigravitySwarmStateDirectory(agentHomeDirectory: string): string { - return join(agentHomeDirectory, "antigravity-cli"); + return agentHomeDirectory; } /** @@ -61,9 +63,18 @@ export function antigravitySwarmLogFile(stateDirectory: string): string { } /** Driver-owned CLI flags: private state and log, the channel, no telemetry. Self-update is off through the pinned environment. */ -export function antigravitySwarmArguments(stateDirectory: string, channel: AntigravitySwarmChannel = GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL): string[] { - return ["--gemini-dir", stateDirectory, "--log-file", antigravitySwarmLogFile(stateDirectory), - ...(channel === "stable" ? ["--cloud_code_endpoint", ANTIGRAVITY_CLI_STABLE_ENDPOINT] : []), "--disable-telemetry"]; +export function antigravitySwarmArguments( + stateDirectory: string, + channel: AntigravitySwarmChannel = GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL, + options: { dangerouslySkipPermissions?: boolean } = {}, +): string[] { + return [ + ...(options.dangerouslySkipPermissions ? ["--dangerously-skip-permissions"] : []), + "--gemini-dir", stateDirectory, + "--log-file", antigravitySwarmLogFile(stateDirectory), + ...(channel === "stable" ? ["--cloud_code_endpoint", ANTIGRAVITY_CLI_STABLE_ENDPOINT] : []), + "--disable-telemetry", + ]; } /** A one-way, non-identifying form of a Google account for comparing the CLI's sign-in with the connection. */ @@ -109,9 +120,9 @@ export function antigravitySwarmRouteRefusal(input: { environment: NodeJS.Proces */ export async function verifyAntigravitySwarmInstallation( stateDirectory: () => string, - options: Omit & { channel?: AntigravitySwarmChannel } = {}, + options: Omit & { channel?: AntigravitySwarmChannel; dangerouslySkipPermissions?: boolean } = {}, ): Promise { - const { channel, ...launchOptions } = options; + const { channel, dangerouslySkipPermissions, ...launchOptions } = options; const pinned = await resolveAntigravityCliLaunch(launchOptions).catch((error: unknown) => { // The runtime-missing and unsupported-platform messages are written for people; keep them visible. if (error instanceof AntigravityCliRuntimeError) throw new AntigravitySwarmError("ANTIGRAVITY_SWARM_UNAVAILABLE", `Swarm is not available on this computer: ${error.message}`); @@ -122,7 +133,10 @@ export async function verifyAntigravitySwarmInstallation( agentServerPackageJsonPath: null, agentRuntimePackageJsonPath: null, async openCommand(open?: { signal?: AbortSignal }) { - const launch = await resolveAntigravityCliLaunch({ ...launchOptions, arguments: antigravitySwarmArguments(stateDirectory(), channel) }); + const launch = await resolveAntigravityCliLaunch({ + ...launchOptions, + arguments: antigravitySwarmArguments(stateDirectory(), channel, { dangerouslySkipPermissions }), + }); if (launch.commandDigest !== pinned.commandDigest) throw new Error("Antigravity CLI installation changed during admission"); return launch.installation.openCommand(open); }, @@ -130,19 +144,22 @@ export async function verifyAntigravitySwarmInstallation( } /** - * Launch environment for the CLI: the sandbox's private environment without the - * registry server's credential plumbing. On macOS the CLI keeps its Google - * sign-in in the login keychain, which it finds through the real HOME, so HOME is - * the OS user's home there; all CLI state still lives in the private `--gemini-dir`. + * Launch environment for the CLI: isolated sandbox environment with file-backed + * token storage forced so the CLI always uses Paperclip's staged Google OAuth + * token at `/antigravity-cli/antigravity-oauth-token` on both + * macOS and Linux (Daytona, Unikraft, and local hosts). */ export function antigravitySwarmLaunchEnvironment( sandbox: Readonly, - input: { agentHomeDirectory: string; platform?: NodeJS.Platform; realHome?: string }, + _input: { agentHomeDirectory: string; platform?: NodeJS.Platform; realHome?: string }, ): NodeJS.ProcessEnv { const environment: NodeJS.ProcessEnv = { ...sandbox }; for (const name of ["GEMINI_HOME", "AGY_ACP_FORCE_FILE_STORAGE", "GEMINI_API_KEY", "GOOGLE_API_KEY", "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"]) delete environment[name]; - if ((input.platform ?? process.platform) === "darwin") environment.HOME = input.realHome ?? userInfo().homedir; - return { ...environment, ...ANTIGRAVITY_CLI_DISTRIBUTION.environment }; + return { + ...environment, + ...ANTIGRAVITY_CLI_DISTRIBUTION.environment, + AGY_CLI_FORCE_FILE_TOKEN_STORAGE: "1", + }; } /** diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts index 890be4af00b..a64c4075876 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.test.ts @@ -145,7 +145,7 @@ describe("Antigravity CLI swarm runtime", () => { "Started helper writer-a: Write a.txt containing exactly 'A' in the current workspace directory", "Checked on the helpers", "Files changed in the task folder: a.txt, b.txt", ])); - expect(run.titles).toContainEqual(expect.stringMatching(/^Swarm started in the task folder with Gemini 3\.8 Flash \(Low\) on Google's default channel \(Antigravity CLI 1\.5\.15\)\. /)); + expect(run.titles).toContainEqual(expect.stringMatching(/^Swarm started in the task folder with Gemini 3\.8 Flash \(Low\) on Google's default channel \(Antigravity CLI 1\.5\.19\)\. /)); expect(run.titles.some(title => /approved automatically/.test(title))).toBe(true); // The CLI streams its terminal hint in pieces (live run7); none of it, nor its period, reaches the thread. expect(run.text).not.toMatch(/swarm board|shortcut|live board/); @@ -413,10 +413,10 @@ describe("Antigravity CLI swarm runtime", () => { const notice = activity.usageNotice?.({}, run.status, "run-1:turn-1", "turn-1"); expect(notice).toMatchObject({ eventType: "provider.notice.recorded", itemId: "turn-1:antigravity-swarm-receipt", payload: { schema: "paperclip.provider.notice.v1", category: "antigravity_swarm_receipt", severity: "info", scope: "turn", - summary: "Swarm ran with Gemini 3.8 Flash (Low) on Google's default channel (Antigravity CLI 1.5.15).", + summary: "Swarm ran with Gemini 3.8 Flash (Low) on Google's default channel (Antigravity CLI 1.5.19).", details: [{ name: "Requested model", value: "gemini-3.8-flash-low" }, { name: "Confirmed model", value: "Gemini 3.8 Flash (Low)" }, { name: "Thinking level", value: "low" }, { name: "Mode", value: "auto" }, { name: "Channel", value: "provider_default" }, - { name: "Antigravity CLI version", value: "1.5.15" }, { name: "CLI account matches connection", value: "unknown" }, + { name: "Antigravity CLI version", value: "1.5.19" }, { name: "CLI account matches connection", value: "unknown" }, { name: "Account unknown reason", value: "no_connection_account" }] } }); expect(JSON.stringify(notice)).not.toContain(run.cwd); expect(JSON.stringify(notice)).not.toContain("e6536314"); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts index f0083a11aa9..1876900efc2 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-swarm-runtime.ts @@ -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"; @@ -10,7 +14,7 @@ import { antigravityOutsideChange } from "./antigravity-swarm-paths.js"; import { antigravityAccountDigest, antigravitySwarmChannelLabel, antigravitySwarmLogFile } from "./antigravity-swarm-route.js"; import { ANTIGRAVITY_CLI_SESSION_MODE, ANTIGRAVITY_SWARM_MCP_SERVER, ANTIGRAVITY_SWARM_MODE, AntigravitySwarmError, - antigravitySwarmWorkspaceEscape, classifyAntigravityRefusalText, createAntigravitySwarmGuard, + antigravitySelections, antigravitySwarmWorkspaceEscape, classifyAntigravityRefusalText, createAntigravitySwarmGuard, type AntigravitySwarmReceipt, } from "./antigravity-swarm-guard.js"; import { GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL, GENERATED_ANTIGRAVITY_SWARM_ENVELOPE_SCHEMA, GENERATED_ANTIGRAVITY_SWARM_REQUEST_FIELD, GENERATED_ANTIGRAVITY_SWARM_REQUEST_MAX_CHARS } from "./generated-sidecar-contract.js"; @@ -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; } -type Json = Record; -const record = (value: unknown): Json => - value !== null && typeof value === "object" && !Array.isArray(value) ? value as Json : {}; - /** * A lost CLI is an interruption, not a swarm failure: Paperclip's recovery * continues the task on its own (bounded by the server's per-request attempt @@ -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 void; reject: (error: Error) => void }>(); - #buffer = ""; - #queue: Promise = Promise.resolve(); - #lost: Error | null = null; - readonly exited: Promise; - onNotification: (method: string, params: Json) => void = () => {}; - onRequest: (method: string, params: Json) => Promise = 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(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 { - 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 { - if (this.#lost) return Promise.reject(this.#lost); - const id = this.#next++; - return new Promise((resolve, reject) => { - let timer: ReturnType | undefined; - const settle = (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 { - #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 { - for (;;) { - const item = this.#items.shift(); - if (item) { yield item; continue; } - if (this.#ended) return; - await new Promise(resolve => { this.#waiter = resolve; }); - this.#waiter = null; - } - } -} - type Snapshot = { files: Map; complete: boolean }; /** * Bounded, asynchronous listing of the task folder. The limit counts every @@ -253,16 +128,6 @@ function changedFiles(before: Map, after: Map): 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 }; @@ -374,13 +239,22 @@ export async function openAntigravitySwarmRuntime( const home = options.launchEnvironment.HOME ?? userInfo().homedir; const instructions = [options.systemInstructions, ANTIGRAVITY_SWARM_INSTRUCTIONS].filter(Boolean).join("\n\n"); const channel = options.antigravitySwarm?.channel ?? GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL; - const guard = createAntigravitySwarmGuard({ model, instructions, workspace: options.cwd, channel }); + const guard = createAntigravitySwarmGuard({ + model, + instructions, + workspace: options.cwd, + channel, + allowSkipPermissionsDefaultMode: options.permissionMode === "approve-all", + }); options.assertWorkspaceHeld?.(); 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). @@ -461,7 +335,10 @@ export async function openAntigravitySwarmRuntime( } await stage("session"); sessionId = guard.sessionResult(opened); - await connection.request("session/set_mode", { sessionId, modeId: ANTIGRAVITY_CLI_SESSION_MODE }, requestTimeoutMs); + const targetMode = guard.targetMode(); + if (targetMode !== "default" || antigravitySelections(opened).get("mode") !== "default") { + await connection.request("session/set_mode", { sessionId, modeId: targetMode }, requestTimeoutMs); + } await waitForReadback(() => guard.bindMode()); await stage("mode"); await connection.request("session/set_model", { sessionId, modelId: model }, requestTimeoutMs); diff --git a/packages/paperclip-runner/src/drivers/acpx/candidate-admission.test.ts b/packages/paperclip-runner/src/drivers/acpx/candidate-admission.test.ts index 262197742c6..b75b3da524c 100644 --- a/packages/paperclip-runner/src/drivers/acpx/candidate-admission.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/candidate-admission.test.ts @@ -24,7 +24,7 @@ const candidate = (): AcpxCandidateAdmission => ({ schema: "paperclip.acpx-candi describe("released Antigravity admission rejects candidate grants", () => { it("admits released Antigravity without candidate authority and rejects every candidate grant", () => { const profile = resolveQualifiedAcpxProfile("antigravity", expected.model); - expect(profile.agentProfileVersion).toBe(2); + expect(profile.agentProfileVersion).toBe(3); expect(profile.qualificationStatus).toBeUndefined(); expect(() => assertAcpxProfileReleased("antigravity")).not.toThrow(); expect(() => assertAcpxExecutionAdmission(profile)).not.toThrow(); @@ -42,13 +42,13 @@ describe("released Antigravity admission rejects candidate grants", () => { } }); - it("declares verified native targets and rejects darwin-x64", () => { - expect(Object.keys(ANTIGRAVITY_DISTRIBUTION_PINS).sort()).toEqual(["darwin-arm64", "linux-arm64", "linux-x64"]); + it("declares verified native targets for macOS and Linux and rejects win32", () => { + expect(Object.keys(ANTIGRAVITY_DISTRIBUTION_PINS).sort()).toEqual(["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"]); for (const target of Object.keys(ANTIGRAVITY_DISTRIBUTION_PINS)) { const [platform, architecture] = target.split("-"); expect(isAntigravityNativeTarget(platform, architecture)).toBe(true); } - expect(isAntigravityNativeTarget("darwin", "x64")).toBe(false); + expect(isAntigravityNativeTarget("win32", "x64")).toBe(false); }); it.each([ @@ -74,7 +74,7 @@ describe("released Antigravity installation remains cryptographically verified", expect(result.commandDigest).toBe(profile.commandDigest); expect(integrity.verifyNativeAcpxInstallation).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ expectedClosureSha256: ANTIGRAVITY_DISTRIBUTION_PINS["darwin-arm64"].closureSha256, - executable: "agy_acp_server.par", fixedArguments: [], + executable: "agy", fixedArguments: ["acp"], })); }); diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-credentials.ts b/packages/paperclip-runner/src/drivers/acpx/codex-credentials.ts index a0303794365..0f64ac43df5 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-credentials.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-credentials.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[]; validateDocument?: (bytes: Buffer) => void; }): Promise { const home = await resolvePrivateAgentHome(input.agentHomeDirectory); @@ -230,6 +233,7 @@ async function stageClaimedManagedCodexCredential( input: { environment?: NodeJS.ProcessEnv; sourcePath?: string; + additionalCleanupPaths?: readonly string[]; validateDocument?: (bytes: Buffer) => void; }, home: string, @@ -239,10 +243,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, ); @@ -250,7 +256,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, @@ -292,6 +298,7 @@ async function stageClaimedManagedCodexCredential( await createCredentialCleanupIntent(intentPath, home); return credentialLease( destination, + additionalCleanupPaths, home, intentPath, "api_key", @@ -317,6 +324,7 @@ async function stageClaimedManagedCodexCredential( // intent so later staging must recover both before admission. quarantineCredentialCleanup( destination, + additionalCleanupPaths, home, intentPath, ownerGeneration, @@ -329,6 +337,7 @@ async function stageClaimedManagedCodexCredential( } return credentialLease( destination, + additionalCleanupPaths, home, intentPath, hasInlineJson ? "inline_json" : "managed_file", @@ -541,6 +550,7 @@ async function closeCredentialLeaseServer(server: Server): Promise { } function quarantineCredentialCleanup( path: string, + additionalCleanupPaths: readonly string[], home: string, intentPath: string, ownerGeneration: CredentialLeaseGeneration, @@ -550,6 +560,7 @@ function quarantineCredentialCleanup( if (existing !== undefined) return; const cleanup: QuarantinedCredentialCleanup = { path, + additionalCleanupPaths, home, intentPath, ownerGeneration, @@ -575,12 +586,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); @@ -641,16 +656,18 @@ async function recoverQuarantinedCredentialCleanup( async function recoverPersistedCredentialCleanup( path: string, stagingPath: string, + additionalCleanupPaths: readonly string[], home: string, intentPath: string, ): Promise { 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, @@ -701,13 +718,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, @@ -925,8 +943,18 @@ async function removeReplaceableCredential(path: string): Promise { } } -async function removeCredential(path: string, home: string): Promise { - await removeCredentialArtifacts([path], home); +async function syncDirectoriesForArtifacts( + paths: readonly string[], + home: string, +): Promise { + const dirs = new Set([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( @@ -939,7 +967,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 { diff --git a/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts index 1d785e09b04..7c04ddbe140 100644 --- a/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts +++ b/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts @@ -9,12 +9,12 @@ export const QUALIFIED_ACPX_PROFILE_DATA = { "protocolVersion": 1, "acpxVersion": "0.22.0", "agent": "antigravity", - "agentProfileVersion": 2, - "agentServerPackage": "native:antigravity-acp", - "agentServerVersion": "1.5.2", - "agentRuntimePackage": "native:antigravity-localharness", - "agentRuntimeVersion": "1.5.2", - "commandDigest": "sha256:61ac14bf03ce4bbf8afe1f5a263b854517ec588d8407fe2d8f17c9fc0c037c4b", + "agentProfileVersion": 3, + "agentServerPackage": "native:antigravity-cli", + "agentServerVersion": "1.5.19", + "agentRuntimePackage": null, + "agentRuntimeVersion": null, + "commandDigest": "sha256:7dd51fb0646187701141c5e1a2ddd6296518e5799117e59b5ad2227e64e8394d", "permissionPolicy": "interactive" }, "grok": { @@ -128,26 +128,35 @@ export const CURSOR_DISTRIBUTION_PINS = { } } as const; -export const ANTIGRAVITY_RUNTIME_VERSION = "1.5.2" as const; +export const ANTIGRAVITY_RUNTIME_VERSION = "1.5.19" as const; export const ANTIGRAVITY_DISTRIBUTION_PINS = { "darwin-arm64": { - "closureSha256": "ab9df40a64806a8e1812234ce5331e04d1c6b5f8c7e5bdbb456cd645e58c5aad", - "executable": "agy_acp_server.par", - "args": [] + "closureSha256": "83d5143264b2f6e944eae9dda9dbdb489e2a7805b2c5246990bf4756e0f6502c", + "executable": "agy", + "args": [ + "acp" + ] + }, + "darwin-x64": { + "closureSha256": "4d9bca68a74eefbea4aa2545eb50b36afbd5c5b81d9f1278388611f89ec0a0ca", + "executable": "agy", + "args": [ + "acp" + ] }, "linux-x64": { - "closureSha256": "be35d65a32667550b5474588d705e6987a813e2fa619cf5db7d82d141c3c05fb", - "executable": "agy_acp_server.par", + "closureSha256": "8af424d013ce999900951e707888199ad63f4681ef8c5a5cd4ccae43ba60bfe6", + "executable": "agy", "args": [ - "--uid=" + "acp" ] }, "linux-arm64": { - "closureSha256": "46c36293779283c1f933eb438a143d116421a331f614601c754f1b94d9dc171a", - "executable": "agy_acp_server.par", + "closureSha256": "abbc84893dde911e12878bb611f9e068796686259efcaf9a2bd2e312a4626c8e", + "executable": "agy", "args": [ - "--uid=" + "acp" ] } } as const; diff --git a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts index e84fc5e2aa9..d50488f8af4 100644 --- a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test.ts @@ -64,11 +64,11 @@ describe("native ACPX execution closure", () => { } expect(() => parseNativeAcpxDistributionEntries({ entries: [entry] }, "b".repeat(64))).toThrow("manifest digest mismatch"); }); - it("admits the largest pinned Linux Antigravity server but not a file over the per-file bound", () => { + it("admits the largest pinned Linux Antigravity binary but not a file over the per-file bound", () => { const sizes = Object.values(antigravityDistributions.platforms as Record }>) .flatMap(platform => platform.entries ?? []).map(entry => entry.size); - const largest = { path: "agy_acp_server.par", sha256: "a".repeat(64), size: Math.max(...sizes), executable: true }; - expect(largest.size).toBeGreaterThan(384 * 1024 * 1024); + const largest = { path: "agy", sha256: "a".repeat(64), size: Math.max(...sizes), executable: true }; + expect(largest.size).toBeGreaterThan(256 * 1024 * 1024); expect(parseNativeAcpxDistributionEntries({ entries: [largest] }, hash(JSON.stringify([largest])))).toHaveLength(1); const oversized = [{ ...largest, size: 768 * 1024 * 1024 + 1 }]; expect(() => parseNativeAcpxDistributionEntries({ entries: oversized }, hash(JSON.stringify(oversized)))).toThrow("file metadata is invalid"); diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts index a205bb05bb2..8a033413d2d 100644 --- a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.test.ts @@ -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> = { - // 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, diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index 403f450bf41..3ba77222c6b 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts @@ -22,10 +22,11 @@ import { createAcpxRuntimeSkillLease } from "./runtime-skill-lease.js"; import { stageManagedGrokCredential } from "./grok-credentials.js"; import { supportsAcpxCredentialFile, validateCodexAuthDocument } from "./credential-file.js"; import { stageManagedAntigravityCredential } from "./antigravity-credentials.js"; +import { verifyAntigravityInstallation } from "./antigravity-installation.js"; import { claudeNativeSkillPrompt } from "./native-skill-prompt.js"; import { prepareStdioMcpBindings } from "../stdio-mcp.js"; import { antigravityLocalLinkEvents } from "./antigravity-local-links.js"; -import { antigravityRouteChangeRefusal, antigravitySwarmBinding, antigravitySwarmLaunchEnvironment, type AntigravitySwarmChannel, antigravitySwarmTools, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js"; +import { antigravityRouteChangeRefusal, antigravitySwarmArguments, antigravitySwarmBinding, antigravitySwarmLaunchEnvironment, type AntigravitySwarmChannel, antigravitySwarmTools, antigravitySwarmRouteRefusal, antigravitySwarmStateDirectory, isAntigravitySwarmRoute, verifyAntigravitySwarmInstallation } from "./antigravity-swarm-route.js"; import type { AcpRuntimeOptions, @@ -466,20 +467,34 @@ export class AcpxRuntimeHost { const refusal = antigravitySwarmRouteRefusal({ environment: options.environment ?? {} }); if (refusal) throw refusal; } - const swarmBinding = swarmRoute ? antigravitySwarmBinding(options.environment ?? {}) : null; - let swarmStateDirectory: string | null = null; + const swarmBinding = options.agent === "antigravity" ? antigravitySwarmBinding(options.environment ?? {}) : null; + const antigravitySkipPermissions = binding.permissionMode === "approve-all" && options.providerPolicy?.readOnly !== true; + let antigravityStateDirectory: string | null = null; const installation = await runAbortableAdmissionStage( options.signal, () => dependencies.verifyInstallation ? dependencies.verifyInstallation(profile) : swarmRoute - // The trusted /swarm turn runs the pinned Antigravity CLI, not the registry server. + // The trusted /swarm turn runs the pinned Antigravity CLI with driver-owned flags. ? verifyAntigravitySwarmInstallation(() => { - if (swarmStateDirectory === null) throw new Error("Antigravity CLI state directory is not prepared"); - return swarmStateDirectory; - }, { channel: swarmBinding!.channel }) - : verifyAcpxProfileInstallation(profile, options.candidateAdmission), + if (antigravityStateDirectory === null) throw new Error("Antigravity CLI state directory is not prepared"); + return antigravityStateDirectory; + }, { channel: swarmBinding!.channel, dangerouslySkipPermissions: antigravitySkipPermissions }) + : options.agent === "antigravity" + ? verifyAcpxProfileInstallation(profile, options.candidateAdmission).then(pinned => Object.freeze({ + ...pinned, + async openCommand(open?: { signal?: AbortSignal }) { + if (antigravityStateDirectory === null) throw new Error("Antigravity CLI state directory is not prepared"); + const args = antigravitySwarmArguments(antigravityStateDirectory, swarmBinding?.channel, { + dangerouslySkipPermissions: antigravitySkipPermissions, + }); + const fresh = await verifyAntigravityInstallation(profile, options.candidateAdmission, args); + if (fresh.commandDigest !== pinned.commandDigest) throw new Error("Antigravity CLI installation changed during admission"); + return fresh.openCommand(open); + }, + })) + : verifyAcpxProfileInstallation(profile, options.candidateAdmission), dependencies.retainAdmissionCleanup, ).catch(error => { throw recordAcpxAdmissionFailure(error, "installation"); }); if (!swarmRoute && installation.commandDigest !== profile.commandDigest) { @@ -575,7 +590,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, @@ -627,10 +642,12 @@ export class AcpxRuntimeHost { if (options.agent !== "antigravity") assertAcpxProfileEnvironment(options.agent, sandbox.launchEnvironment); admissionStage = "configuration"; let launchEnvironment = sandbox.launchEnvironment; - if (swarmRoute) { - swarmStateDirectory = antigravitySwarmStateDirectory(sandbox.agentHomeDirectory); - await mkdir(swarmStateDirectory, { recursive: true, mode: 0o700 }); - launchEnvironment = Object.freeze(antigravitySwarmLaunchEnvironment(launchEnvironment, { agentHomeDirectory: sandbox.agentHomeDirectory })); + if (options.agent === "antigravity") { + antigravityStateDirectory = antigravitySwarmStateDirectory(sandbox.agentHomeDirectory); + await mkdir(antigravityStateDirectory, { recursive: true, mode: 0o700 }); + if (swarmRoute) { + launchEnvironment = Object.freeze(antigravitySwarmLaunchEnvironment(launchEnvironment, { agentHomeDirectory: sandbox.agentHomeDirectory })); + } } // This copy is registered by the authenticated controller for its company, // agent and run. Environment/config values cannot widen the grant. Each @@ -716,7 +733,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(), @@ -745,8 +762,8 @@ export class AcpxRuntimeHost { profile, cwd: binding.workspacePath, stateDirectory: sandbox.stateDirectory, - ...(swarmStateDirectory === null ? {} : { antigravityStateDirectory: swarmStateDirectory }), - ...(swarmBinding === null ? {} : { antigravitySwarm: swarmBinding }), + ...(antigravityStateDirectory === null ? {} : { antigravityStateDirectory }), + ...(swarmRoute && swarmBinding !== null ? { antigravitySwarm: swarmBinding } : {}), providerSessionKey: binding.profileSessionKey, restoringSession: options.expectedIdentity !== undefined, permissionMode: binding.permissionMode, diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts index a3a421e93c7..f1f9b922f48 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-sandbox.ts @@ -548,7 +548,12 @@ export async function prepareAcpxRuntimeSandbox(input: { PAPERCLIP_ACPX_PROFILE: input.agent, PAPERCLIP_ACPX_ISOLATED_CONTEXT: "1", ...(input.agent === "kimi" ? { KIMI_CODE_HOME: agentHomeDirectory, PAPERCLIP_KIMI_INSTRUCTIONS: kimiInstructionBinding(policy.systemInstructions).payload } : {}), - ...(input.agent === "antigravity" ? { GEMINI_HOME: agentHomeDirectory, AGY_ACP_FORCE_FILE_STORAGE: "1" } : {}), + ...(input.agent === "antigravity" ? { + GEMINI_HOME: agentHomeDirectory, + AGY_ACP_FORCE_FILE_STORAGE: "1", + AGY_CLI_FORCE_FILE_TOKEN_STORAGE: "1", + AGY_CLI_DISABLE_AUTO_UPDATE: "1", + } : {}), ...(input.agent === "grok" ? { GROK_HOME: agentHomeDirectory, NO_BROWSER: "1", GROK_DISABLE_AUTOUPDATER: "1" } : {}), ...(input.agent === "pi" ? { @@ -737,7 +742,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, ) diff --git a/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs index 18eb3b9a5cf..10da7edbe76 100644 --- a/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs +++ b/packages/paperclip-runner/test-fixtures/antigravity-cli/fake-agy-acp.mjs @@ -247,7 +247,7 @@ async function handle(message) { if (method === "initialize") { return write({ jsonrpc: "2.0", id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true, promptCapabilities: { image: true, embeddedContext: true }, _meta: { antigravity: { tier: true, systemPrompt: { append: true } } } }, - agentInfo: { name: "Antigravity ACP Server", version: scenario === "wrong-version" ? "1.5.16" : "1.5.15" }, + agentInfo: { name: "Antigravity ACP Server", version: scenario === "wrong-version" ? "1.5.20" : "1.5.19" }, authMethods: [{ id: "oauth-personal" }, { id: "gemini-api-key" }] } }); } if (method === "session/new") { diff --git a/packages/shared/src/antigravity-models.generated.ts b/packages/shared/src/antigravity-models.generated.ts index cb1e231baef..20530735475 100644 --- a/packages/shared/src/antigravity-models.generated.ts +++ b/packages/shared/src/antigravity-models.generated.ts @@ -5,14 +5,70 @@ export const ANTIGRAVITY_GENERATED_MODEL_CATALOG = { "schema": "paperclip.antigravity.model_catalog.v1", "source": { - "runtimeVersion": "1.5.2", + "runtimeVersion": "1.5.19", "platform": "darwin-arm64", - "archiveSha256": "123a16d5c40a8ac99e20f01a62b68dd860fd96b1c528dfb8eaa37ca8733d4845", - "vendorClosureSha256": "d03a6f593b6400c4b41d33a1732f842b6ff887a50727fadecb38ee67eac7336b" + "archiveSha256": "4f1603c9de8c993a83a12ec06b7342b6fb7c27853e9d9fb6c786286461d1ff50", + "closureSha256": "83d5143264b2f6e944eae9dda9dbdb489e2a7805b2c5246990bf4756e0f6502c" }, "apiKey": { - "defaultModelId": "gemini-3.8-flash-high", + "defaultModelId": "gemini-3.1-pro-low", "models": [ + { + "id": "gemini-4-neon-high", + "label": "Gemini 4 Neon (High)" + }, + { + "id": "gemini-4-neon-xhigh", + "label": "Gemini 4 Neon (XHigh)" + }, + { + "id": "gemini-4-neon-medium", + "label": "Gemini 4 Neon (Medium)" + }, + { + "id": "gemini-4-neon-low", + "label": "Gemini 4 Neon (Low)" + }, + { + "id": "gemini-4-carbon-high", + "label": "Gemini 4 Carbon (High)" + }, + { + "id": "gemini-4-carbon-medium", + "label": "Gemini 4 Carbon (Medium)" + }, + { + "id": "gemini-4-carbon-low", + "label": "Gemini 4 Carbon (Low)" + }, + { + "id": "gemini-4-hydrogen-high", + "label": "Gemini 4 Hydrogen (High)" + }, + { + "id": "gemini-4-hydrogen-xhigh", + "label": "Gemini 4 Hydrogen (XHigh)" + }, + { + "id": "gemini-4-hydrogen-medium", + "label": "Gemini 4 Hydrogen (Medium)" + }, + { + "id": "gemini-4-hydrogen-low", + "label": "Gemini 4 Hydrogen (Low)" + }, + { + "id": "gemini-4-argon-high", + "label": "Gemini 4 Argon (High)" + }, + { + "id": "gemini-4-argon-medium", + "label": "Gemini 4 Argon (Medium)" + }, + { + "id": "gemini-4-argon-low", + "label": "Gemini 4 Argon (Low)" + }, { "id": "gemini-3.8-flash-high", "label": "Gemini 3.8 Flash (High)" @@ -49,18 +105,6 @@ export const ANTIGRAVITY_GENERATED_MODEL_CATALOG = { "id": "gemini-3.6-flash-low", "label": "Gemini 3.6 Flash (Low)" }, - { - "id": "gemini-3.5-flash-high", - "label": "Gemini 3.5 Flash (High)" - }, - { - "id": "gemini-3.5-flash-medium", - "label": "Gemini 3.5 Flash (Medium)" - }, - { - "id": "gemini-3.5-flash-low", - "label": "Gemini 3.5 Flash (Low)" - }, { "id": "gemini-3.1-pro-high", "label": "Gemini 3.1 Pro (High)" @@ -72,28 +116,28 @@ export const ANTIGRAVITY_GENERATED_MODEL_CATALOG = { ] }, "families": [ - { - "id": "gemini-4-carbon", - "label": "Gemini 4 Carbon", - "baseModelId": "gemini-4-carbon", - "levels": [ - "medium", - "high", - "low" - ], - "agentPlatformOnly": true - }, { "id": "gemini-4-neon", "label": "Gemini 4 Neon", "baseModelId": "gemini-4-neon", "levels": [ "high", - "extra_high", + "xhigh", "medium", "low" ], - "agentPlatformOnly": true + "agentPlatformOnly": false + }, + { + "id": "gemini-4-carbon", + "label": "Gemini 4 Carbon", + "baseModelId": "gemini-4-carbon", + "levels": [ + "high", + "medium", + "low" + ], + "agentPlatformOnly": false }, { "id": "gemini-4-hydrogen", @@ -101,11 +145,11 @@ export const ANTIGRAVITY_GENERATED_MODEL_CATALOG = { "baseModelId": "gemini-4-hydrogen", "levels": [ "high", - "extra_high", + "xhigh", "medium", "low" ], - "agentPlatformOnly": true + "agentPlatformOnly": false }, { "id": "gemini-4-argon", @@ -116,7 +160,7 @@ export const ANTIGRAVITY_GENERATED_MODEL_CATALOG = { "medium", "low" ], - "agentPlatformOnly": true + "agentPlatformOnly": false }, { "id": "gemini-3.8-flash", @@ -151,21 +195,10 @@ export const ANTIGRAVITY_GENERATED_MODEL_CATALOG = { ], "agentPlatformOnly": false }, - { - "id": "gemini-3.5-flash", - "label": "Gemini 3.5 Flash", - "baseModelId": "gemini-3.5-flash", - "levels": [ - "high", - "medium", - "low" - ], - "agentPlatformOnly": false - }, { "id": "gemini-3.1-pro", "label": "Gemini 3.1 Pro", - "baseModelId": "gemini-3.1-pro-preview", + "baseModelId": "gemini-3.1-pro", "levels": [ "high", "low" diff --git a/packages/shared/src/antigravity-models.test.ts b/packages/shared/src/antigravity-models.test.ts index eb5d07faee2..5830c34a7e6 100644 --- a/packages/shared/src/antigravity-models.test.ts +++ b/packages/shared/src/antigravity-models.test.ts @@ -17,7 +17,7 @@ const serverIds = CATALOG.families.flatMap(family => antigravityFamilyModelIds(f describe("Antigravity model ids", () => { it("round-trips every server catalog id exactly, including all Gemini 4 levels", () => { - expect(serverIds).toHaveLength(28); + expect(serverIds).toHaveLength(25); for (const id of serverIds) { const variant = parseAntigravityModelId(id, { catalog: "server" }); expect(variant, id).not.toBeNull(); @@ -59,26 +59,27 @@ describe("Antigravity model ids", () => { }); describe("Antigravity API-key suggestions", () => { - it("lists the live API-key catalog first, then every Gemini 4 level marked as needing a paid plan", () => { + it("lists the live 1.5.19 API-key catalog with Gemini 4 marked as needing a paid plan", () => { const models = antigravityApiKeyModels(); - expect(models.slice(0, 14).map(model => model.id)).toEqual([ + expect(models).toHaveLength(25); + expect(ANTIGRAVITY_API_KEY_DEFAULT_MODEL).toBe("gemini-3.1-pro-low"); + const gemini4 = models.filter(model => model.id.startsWith("gemini-4-")); + const gemini3 = models.filter(model => !model.id.startsWith("gemini-4-")); + expect(gemini4.map(model => model.id)).toEqual([ + "gemini-4-neon-high", "gemini-4-neon-xhigh", "gemini-4-neon-medium", "gemini-4-neon-low", + "gemini-4-carbon-high", "gemini-4-carbon-medium", "gemini-4-carbon-low", + "gemini-4-hydrogen-high", "gemini-4-hydrogen-xhigh", "gemini-4-hydrogen-medium", "gemini-4-hydrogen-low", + "gemini-4-argon-high", "gemini-4-argon-medium", "gemini-4-argon-low", + ]); + expect(gemini3.map(model => model.id)).toEqual([ "gemini-3.8-flash-high", "gemini-3.8-flash-medium", "gemini-3.8-flash-low", "gemini-3.7-flash-high", "gemini-3.7-flash-medium", "gemini-3.7-flash-low", "gemini-3.6-flash-high", "gemini-3.6-flash-medium", "gemini-3.6-flash-low", - "gemini-3.5-flash-high", "gemini-3.5-flash-medium", "gemini-3.5-flash-low", "gemini-3.1-pro-high", "gemini-3.1-pro-low", ]); - expect(ANTIGRAVITY_API_KEY_DEFAULT_MODEL).toBe("gemini-3.8-flash-high"); - const gemini4 = models.slice(14); - expect(gemini4.map(model => model.id)).toEqual([ - "gemini-4-carbon-medium", "gemini-4-carbon-high", "gemini-4-carbon-low", - "gemini-4-neon-high", "gemini-4-neon-extra_high", "gemini-4-neon-medium", "gemini-4-neon-low", - "gemini-4-hydrogen-high", "gemini-4-hydrogen-extra_high", "gemini-4-hydrogen-medium", "gemini-4-hydrogen-low", - "gemini-4-argon-high", "gemini-4-argon-medium", "gemini-4-argon-low", - ]); expect(gemini4.every(model => model.label.endsWith("needs a paid Gemini API plan"))).toBe(true); expect(gemini4.every(model => antigravityModelNeedsPaidGeminiApiPlan(model.id))).toBe(true); - expect(models.slice(0, 14).some(model => antigravityModelNeedsPaidGeminiApiPlan(model.id))).toBe(false); + expect(gemini3.some(model => antigravityModelNeedsPaidGeminiApiPlan(model.id))).toBe(false); }); it("names family and level for the picker", () => { diff --git a/packages/shared/src/antigravity-models.ts b/packages/shared/src/antigravity-models.ts index f829cc6bc37..e8248731f03 100644 --- a/packages/shared/src/antigravity-models.ts +++ b/packages/shared/src/antigravity-models.ts @@ -105,13 +105,18 @@ export function antigravityModelChoice(model: { id: string; label?: string }, op return { familyId: variant.familyId, familyLabel: known ?? (fromLabel && fromLabel !== model.id ? fromLabel : variant.familyId), level: variant.level, levelLabel }; } -/** Gemini 4 families the server lists only for Agent Platform. With an API key - * they run through the exact-model admission path, which needs a Gemini API - * plan with Gemini 4 quota (the free tier has none). */ +/** Gemini 4 families need a Gemini API plan with Gemini 4 quota when used with + * an API key (the free tier has none). */ export function antigravityModelNeedsPaidGeminiApiPlan(id: string): boolean { const variant = parseAntigravityModelId(id, { catalog: "server" }); - return Boolean(variant && FAMILIES.get(variant.familyId)?.agentPlatformOnly - && (FAMILIES.get(variant.familyId)!.levels as readonly string[]).includes(variant.level)); + if (!variant) return false; + const family = FAMILIES.get(variant.familyId); + if (!family) return false; + const matchesLevel = (family.levels as readonly string[]).some( + level => level === variant.level || antigravityServerThinkingLevel(level) === variant.level, + ); + if (!matchesLevel) return false; + return family.agentPlatformOnly || variant.familyId.startsWith("gemini-4-"); } export const ANTIGRAVITY_PAID_PLAN_NOTE = "needs a paid Gemini API plan"; @@ -120,11 +125,22 @@ export const ANTIGRAVITY_PAID_PLAN_NOTE = "needs a paid Gemini API plan"; * runtime. These are suggestions, not an allowlist: an explicit id stays * accepted and native admission decides. */ export function antigravityApiKeyModels(): Array<{ id: string; label: string }> { - const listed = CATALOG.apiKey.models.map(model => ({ id: model.id, label: model.label })); - const gemini4 = CATALOG.families.filter(family => family.agentPlatformOnly).flatMap(family => family.levels.map(level => ({ - id: `${family.id}-${level}`, - label: `${family.label} (${LEVEL_LABELS[level as AntigravityThinkingLevel]}) · ${ANTIGRAVITY_PAID_PLAN_NOTE}`, - }))); + const seen = new Set(); + const listed = CATALOG.apiKey.models.map(model => { + seen.add(model.id); + const label = antigravityModelNeedsPaidGeminiApiPlan(model.id) + ? `${model.label} · ${ANTIGRAVITY_PAID_PLAN_NOTE}` + : model.label; + return { id: model.id, label }; + }); + const gemini4 = CATALOG.families.filter(family => family.agentPlatformOnly).flatMap(family => + family.levels + .map(level => ({ + id: `${family.id}-${level}`, + label: `${family.label} (${LEVEL_LABELS[(antigravityServerThinkingLevel(level) ?? level) as AntigravityThinkingLevel]}) · ${ANTIGRAVITY_PAID_PLAN_NOTE}`, + })) + .filter(entry => !seen.has(entry.id)), + ); return [...listed, ...gemini4]; } diff --git a/server/src/__tests__/agent-adapter-validation-routes.test.ts b/server/src/__tests__/agent-adapter-validation-routes.test.ts index cf59279c8a6..60907059e23 100644 --- a/server/src/__tests__/agent-adapter-validation-routes.test.ts +++ b/server/src/__tests__/agent-adapter-validation-routes.test.ts @@ -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); diff --git a/server/src/__tests__/antigravity-connection-models.test.ts b/server/src/__tests__/antigravity-connection-models.test.ts index d04a4131417..1d628b15415 100644 --- a/server/src/__tests__/antigravity-connection-models.test.ts +++ b/server/src/__tests__/antigravity-connection-models.test.ts @@ -60,7 +60,7 @@ it("reports a missing server runtime plainly and logs its reason code", async () it("returns the pinned API-key catalog for a Gemini API key without preparing a credential or starting a process", async () => { const models = await antigravityConnectionModels({} as never, { ...input, binding: { provider: "google", method: "api_key", mode: "responsible_user" } }); expect(models.map(model => model.id)).toEqual(antigravityApiKeyModels().map(model => model.id)); - expect(models.slice(0, 14).map(model => model.id)).toContain("gemini-3.8-flash-high"); + expect(models.map(model => model.id)).toContain("gemini-3.8-flash-high"); expect(models.find(model => model.id === "gemini-4-neon-high")?.label).toBe("Gemini 4 Neon (High) · needs a paid Gemini API plan"); expect(mocks.managed).not.toHaveBeenCalled(); expect(mocks.discover).not.toHaveBeenCalled(); diff --git a/server/src/services/antigravity-swarm.db.test.ts b/server/src/services/antigravity-swarm.db.test.ts index 3d47ce71fca..24e9a8449f0 100644 --- a/server/src/services/antigravity-swarm.db.test.ts +++ b/server/src/services/antigravity-swarm.db.test.ts @@ -574,11 +574,17 @@ describe.skipIf(!support.supported)("trusted /swarm run selection (database)", ( expect((receipt!.payload as Record)._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([ diff --git a/server/src/services/antigravity-swarm.test.ts b/server/src/services/antigravity-swarm.test.ts index b7167831f1a..b20f065e19a 100644 --- a/server/src/services/antigravity-swarm.test.ts +++ b/server/src/services/antigravity-swarm.test.ts @@ -7,13 +7,13 @@ import { antigravitySwarmRefusal, isAntigravitySwarmExecution, requestedAntigrav const antigravity = { adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low" } }; describe("trusted /swarm for Google Antigravity", () => { - it("is available only when the experimental flag is on, for a local Antigravity assignee", () => { + it("is available only when the experimental flag is on, for local and remote Antigravity assignees", () => { expect(antigravitySwarmRefusal({ enabled: true, agent: antigravity })).toBeNull(); expect(antigravitySwarmRefusal({ enabled: false, agent: antigravity })).toMatch(/not turned on/); expect(antigravitySwarmRefusal({ enabled: true, agent: null })).toMatch(/Google Antigravity agent/); expect(antigravitySwarmRefusal({ enabled: true, agent: { adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "claude" } } })) .toMatch(/Google Antigravity agent/); - expect(antigravitySwarmRefusal({ enabled: true, agent: antigravity, remote: true })).toMatch(/this computer/); + expect(antigravitySwarmRefusal({ enabled: true, agent: antigravity, remote: true })).toBeNull(); expect(antigravitySwarmRefusal({ enabled: true, agent: antigravity, planning: true })).toMatch(/Plan mode/); // Helpers change files: only a standard task runs a swarm (allow-list), never ask or skill_test. expect(antigravitySwarmRefusal({ enabled: true, agent: antigravity, workMode: "standard" })).toBeNull(); diff --git a/server/src/services/antigravity-swarm.ts b/server/src/services/antigravity-swarm.ts index adfea2d4e97..797e1c144ef 100644 --- a/server/src/services/antigravity-swarm.ts +++ b/server/src/services/antigravity-swarm.ts @@ -50,7 +50,6 @@ export function antigravitySwarmRefusal(input: { if (input.workMode !== undefined && !antigravitySwarmWorkModeAllows(input.workMode)) { return "Swarm works only in a standard task: helpers change files, and this task's mode does not allow changes. Switch the task to Standard, then send /swarm."; } - if (input.remote) return "Swarm is not available for this agent: it runs only on this computer, not in a cloud or remote environment."; return null; } diff --git a/server/src/services/managed-ai-credential-writeback.ts b/server/src/services/managed-ai-credential-writeback.ts index 3d1afd3fe23..9b703a6a2d7 100644 --- a/server/src/services/managed-ai-credential-writeback.ts +++ b/server/src/services/managed-ai-credential-writeback.ts @@ -13,6 +13,8 @@ import { aiConnectionService } from "./ai-connections.js"; import { secretService } from "./secrets.js"; import { logActivity } from "./activity-log.js"; import { sanitizeAntigravityCredential } from "../vendor/paperclip-runner/index.js"; +import { readLocalAiCredentialFile } from "./local-ai-credential-file.js"; +import { reconcileRetainedGoogleCleanup, retainGoogleCredentialCleanup } from "./retained-google-credential-cleanup.js"; import { AntigravityAccountMismatchError, prepareAntigravityCredentialWriteback } from "./native-runtime/antigravity-runner-credentials.js"; export const managedAiCredentialWritebackBindingSchema = z.object({ @@ -109,6 +111,7 @@ export async function syncManagedAntigravityCredential( ) { const base = managedAiCredentialWritebackBindingSchema.parse(binding).google?.credentialSha256; if (!base) throw new Error("Managed credential binding is not a Google sign-in"); + await reconcileRetainedGoogleCleanup({ companyId, accountKey: binding.grantId }); const account = async (database: Db) => { const [grant] = await database.select().from(connectionGrants).where(and( eq(connectionGrants.companyId, companyId), eq(connectionGrants.id, binding.grantId), @@ -152,32 +155,76 @@ export async function syncManagedAntigravityCredential( }; if (!accountEmail) return refuse("This Google connection has no saved account to compare the refreshed sign-in with, so it was not saved. Reconnect the Google account."); const home = await realpath(await mkdtemp(join(tmpdir(), "paperclip-google-writeback-"))); - let verified: string; + const tokenPath = join(home, "antigravity-acp", "acp_token.json"); try { await mkdir(join(home, "antigravity-acp"), { mode: 0o700 }); - await writeFile(join(home, "antigravity-acp", "acp_token.json"), incoming, { flag: "wx", mode: 0o600 }); - verified = await prepareAntigravityCredentialWriteback({ originalCredential: current.stored, refreshedCredential: incoming, managedHome: home, accountEmail }); + await writeFile(tokenPath, incoming, { flag: "wx", mode: 0o600 }); } catch (error) { - if (!(error instanceof AntigravityAccountMismatchError)) throw error; - return refuse("The refreshed Google sign-in belongs to a different Google account than this connection, so it was not saved."); - } finally { await rm(home, { recursive: true, force: true }); + throw error; } - const writeBack = () => mutate(async database => { - const selected = await account(database); - if (!selected || selected.grant.providerTenant?.name?.toLowerCase() !== accountEmail.toLowerCase()) return "binding_changed" as const; - if (verified === selected.stored) return "unchanged" as const; - await secretService(database).rotate(binding.secretId, { value: verified, preserveAiSessionEpoch: true }, { userId: selected.grant.subjectUserId }); - await logActivity(database, { companyId, actorType: "system", actorId: "credential_refresh", - action: "ai_connection.credential_refreshed", entityType: "tool_connection", entityId: selected.connection.id, - details: { provider: "google", grantId: selected.grant.id } }); - return "rotated" as const; - }); - for (let attempt = 0; ; attempt++) { - try { - return await writeBack(); - } catch (error) { - if (attempt >= 2 || (error as NodeJS.ErrnoException)?.code !== WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE) throw error; + const persistVerified = async (verified: string) => { + const writeBack = () => mutate(async database => { + const selected = await account(database); + if (!selected || selected.grant.providerTenant?.name?.toLowerCase() !== accountEmail.toLowerCase()) return "binding_changed" as const; + if (verified === selected.stored) return "unchanged" as const; + await secretService(database).rotate(binding.secretId, { value: verified, preserveAiSessionEpoch: true }, { userId: selected.grant.subjectUserId }); + await logActivity(database, { companyId, actorType: "system", actorId: "credential_refresh", + action: "ai_connection.credential_refreshed", entityType: "tool_connection", entityId: selected.connection.id, + details: { provider: "google", grantId: selected.grant.id } }); + return "rotated" as const; + }); + for (let attempt = 0; ; attempt++) { + try { + return await writeBack(); + } catch (error) { + if (attempt >= 2 || (error as NodeJS.ErrnoException)?.code !== WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE) throw error; + } } + }; + let settledOutcome: "rotated" | "unchanged" | "binding_changed" | "account_refused" | undefined; + let accountMismatched = false; + const verifyAndPersist = async (): Promise<"rotated" | "unchanged" | "binding_changed" | "account_refused"> => { + if (settledOutcome === undefined) { + if (accountMismatched) { + settledOutcome = await refuse("The refreshed Google sign-in belongs to a different Google account than this connection, so it was not saved."); + } else { + // Re-read the private home's current credential on every retry: a failed + // verification may have rotated the refresh token inside `home` before + // throwing (e.g., transient userinfo failure). + const latest = await readLocalAiCredentialFile(tokenPath); + let verified: string | undefined; + try { + verified = await prepareAntigravityCredentialWriteback({ + originalCredential: current.stored, + refreshedCredential: latest, + managedHome: home, + accountEmail, + }); + } catch (error) { + if (error instanceof AntigravityAccountMismatchError) { + accountMismatched = true; + settledOutcome = await refuse("The refreshed Google sign-in belongs to a different Google account than this connection, so it was not saved."); + } else { + throw error; + } + } + if (settledOutcome === undefined) { + settledOutcome = await persistVerified(verified!); + } + } + } + await rm(home, { recursive: true, force: true }); + return settledOutcome; + }; + try { + return await verifyAndPersist(); + } catch (error) { + retainGoogleCredentialCleanup({ + scope: { companyId, accountKey: current.grant.id }, + home, + cleanup: async () => { await verifyAndPersist(); }, + }); + throw error; } } diff --git a/server/src/services/native-runtime/acpx-qualification.test.ts b/server/src/services/native-runtime/acpx-qualification.test.ts index 05fd7e4a2fe..1d2ebcce2a8 100644 --- a/server/src/services/native-runtime/acpx-qualification.test.ts +++ b/server/src/services/native-runtime/acpx-qualification.test.ts @@ -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 })) diff --git a/server/src/services/native-runtime/antigravity-candidate-admission.test.ts b/server/src/services/native-runtime/antigravity-candidate-admission.test.ts index 82cf57def10..dc4f3dce9bb 100644 --- a/server/src/services/native-runtime/antigravity-candidate-admission.test.ts +++ b/server/src/services/native-runtime/antigravity-candidate-admission.test.ts @@ -27,7 +27,7 @@ describe("released Antigravity admission ignores candidate grants", () => { it("admits released Antigravity without candidate authority and ignores candidate env values", () => { for (const value of [undefined, "malformed", JSON.stringify(admission()), JSON.stringify(targetAdmission("linux-x64"))]) { vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, value); - expect(QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion).toBe(2); + expect(QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion).toBe(3); expect(QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus).toBeUndefined(); expect(resolveAntigravityCandidateAdmission({ companyId, model })).toBeUndefined(); expect(resolveAntigravityCandidateAdmission({ companyId, model, target: ANTIGRAVITY_REMOTE_TARGET })).toBeUndefined(); @@ -49,7 +49,7 @@ describe("released Antigravity admission ignores candidate grants", () => { } }); - it("declares verified closures for macOS ARM and both Linux architectures", () => { - expect(verifiedTargets.sort()).toEqual(["darwin-arm64", "linux-arm64", "linux-x64"]); + it("declares verified closures for macOS and Linux architectures", () => { + expect(verifiedTargets.sort()).toEqual(["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"]); }); }); diff --git a/server/src/services/native-runtime/antigravity-release.test.ts b/server/src/services/native-runtime/antigravity-release.test.ts index c1178f4864d..dd3a3a965bf 100644 --- a/server/src/services/native-runtime/antigravity-release.test.ts +++ b/server/src/services/native-runtime/antigravity-release.test.ts @@ -51,7 +51,7 @@ describe("Antigravity executor admission", () => { it("takes the general qualified path without a candidate grant, including pluginTask and remote targets", () => { expect(antigravityReleasePending()).toBe(false); - expect(QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion).toBe(2); + expect(QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion).toBe(3); vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, undefined); const execution = antigravityExecution(); expect(admissible(execution)).not.toThrow(); diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 6cfff3d624a..bf2662d1463 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -4295,7 +4295,7 @@ describe("remote provider pack manifest", () => { // candidateProviders while pending, under providers after the flip, never both. const antigravityPath = "provider-assets/antigravity/linux-x64"; await mkdir(join(root, antigravityPath), { recursive: true }); - await writeFile(join(root, antigravityPath, "agy_acp_server.par"), "patched Antigravity runtime"); + await writeFile(join(root, antigravityPath, "agy"), "pinned Antigravity runtime"); const antigravity = { version: QUALIFIED_ACPX_PROFILES.antigravity.agentServerVersion, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, closureDigest: `sha256:${antigravityPack.linuxClosure}`, qualification: "pending", path: antigravityPath, @@ -4319,7 +4319,7 @@ describe("remote provider pack manifest", () => { Object.assign(payload, { providers: { cursor, kimi, antigravity }, candidateProviders: { antigravity } }); await writeKimiManifest(); expect(() => readRemoteProviderPackManifest(root)).toThrow("runner_remote_provider_artifact_incompatible"); - for (const closureDigest of [`sha256:${distributions.platforms["darwin-arm64"].vendorClosureSha256}`, + for (const closureDigest of [digest("stale-closure"), `sha256:${distributions.platforms["darwin-arm64"].closureSha256}`, digest("other-closure")]) { Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} }); Object.assign(inventories[admitted], { antigravity: { ...antigravity, closureDigest } }); @@ -4333,9 +4333,9 @@ describe("remote provider pack manifest", () => { Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} }); Object.assign(inventories[admitted], { antigravity }); await writeKimiManifest(); - await writeFile(join(root, antigravityPath, "agy_acp_server.par"), "vendor Antigravity runtime"); + await writeFile(join(root, antigravityPath, "agy"), "tampered Antigravity runtime"); expect(() => readRemoteProviderPackManifest(root)).toThrow("runner_remote_provider_artifact_incompatible: candidate asset tree digest mismatch"); - await writeFile(join(root, antigravityPath, "agy_acp_server.par"), "patched Antigravity runtime"); + await writeFile(join(root, antigravityPath, "agy"), "pinned Antigravity runtime"); } // Until the Linux runtime is pinned, no Antigravity image pack verifies. antigravityPack.linuxClosure = ""; diff --git a/tests/runner-e2e/antigravity-qualification-cases.ts b/tests/runner-e2e/antigravity-qualification-cases.ts index c7e68605560..28f11d0c103 100644 --- a/tests/runner-e2e/antigravity-qualification-cases.ts +++ b/tests/runner-e2e/antigravity-qualification-cases.ts @@ -24,16 +24,16 @@ export { ANTIGRAVITY_THINKING_LEVELS }; * selected through exact-model admission and need a billed Gemini API plan. */ const FAMILIES = ANTIGRAVITY_GENERATED_MODEL_CATALOG.families; -export const ANTIGRAVITY_API_KEY_FAMILIES = FAMILIES.filter(family => !family.agentPlatformOnly).map(family => family.id); -export const ANTIGRAVITY_GEMINI4_FAMILIES = FAMILIES.filter(family => family.agentPlatformOnly).map(family => family.id); +export const ANTIGRAVITY_GEMINI4_FAMILIES = FAMILIES.filter(family => family.agentPlatformOnly || family.id.startsWith("gemini-4-")).map(family => family.id); +export const ANTIGRAVITY_API_KEY_FAMILIES = FAMILIES.filter(family => !family.agentPlatformOnly && !family.id.startsWith("gemini-4-")).map(family => family.id); export function antigravityModelIds(families: readonly string[], levels?: readonly string[]): string[] { return families.flatMap(family => levels ? levels.map(level => `${family}-${level}`) : antigravityFamilyModelIds(family)); } -export const ANTIGRAVITY_API_KEY_LINEUP: readonly string[] = ANTIGRAVITY_GENERATED_MODEL_CATALOG.apiKey.models.map(model => model.id); +export const ANTIGRAVITY_API_KEY_LINEUP: readonly string[] = ANTIGRAVITY_GENERATED_MODEL_CATALOG.apiKey.models.map(model => model.id).filter(id => !id.startsWith("gemini-4-")); export const ANTIGRAVITY_GEMINI4_LINEUP: readonly string[] = antigravityModelIds(ANTIGRAVITY_GEMINI4_FAMILIES); -const MODEL_ID = /^gemini-[0-9][a-z0-9.-]*-(?:minimal|low|medium|high|extra_high)$/u; +const MODEL_ID = /^gemini-[0-9][a-z0-9.-]*-(?:minimal|low|medium|high|extra_high|xhigh)$/u; /** Cell IDs split on dots, so the profile suffix replaces them. */ export function antigravityLineupProfileId(model: string): string { if (!MODEL_ID.test(model)) throw new Error(`Invalid Antigravity model ID: ${model}`); diff --git a/tests/runner-e2e/antigravity-qualification.test.ts b/tests/runner-e2e/antigravity-qualification.test.ts index 139e0a8d048..2ccf450830a 100644 --- a/tests/runner-e2e/antigravity-qualification.test.ts +++ b/tests/runner-e2e/antigravity-qualification.test.ts @@ -161,20 +161,19 @@ describe("Antigravity model lineups", () => { expect(() => buildRunnerE2EProcessEnvironment({}, lineup)).not.toThrow(); expect(buildMatrixJobs(lineup).every(job => job.credentialName === "GEMINI_API_KEY" && !job.needsDaytona)).toBe(true); } - // Exactly what a 1.5.2 `gemini-api-key` session lists (live, prompt-free). + // Exactly what a 1.5.19 `gemini-api-key` session lists for Gemini 3 (live, prompt-free). expect(ANTIGRAVITY_API_KEY_LINEUP).toEqual([ "gemini-3.8-flash-high", "gemini-3.8-flash-medium", "gemini-3.8-flash-low", "gemini-3.7-flash-high", "gemini-3.7-flash-medium", "gemini-3.7-flash-low", "gemini-3.6-flash-high", "gemini-3.6-flash-medium", "gemini-3.6-flash-low", - "gemini-3.5-flash-high", "gemini-3.5-flash-medium", "gemini-3.5-flash-low", "gemini-3.1-pro-high", "gemini-3.1-pro-low", ]); expect(ANTIGRAVITY_API_KEY_LINEUP).not.toContain("gemini-3.1-pro-extra_high"); // Each Gemini 4 family keeps its own levels; none offers minimal. expect(ANTIGRAVITY_GEMINI4_LINEUP).toEqual([ - "gemini-4-carbon-medium", "gemini-4-carbon-high", "gemini-4-carbon-low", - "gemini-4-neon-high", "gemini-4-neon-extra_high", "gemini-4-neon-medium", "gemini-4-neon-low", - "gemini-4-hydrogen-high", "gemini-4-hydrogen-extra_high", "gemini-4-hydrogen-medium", "gemini-4-hydrogen-low", + "gemini-4-neon-high", "gemini-4-neon-xhigh", "gemini-4-neon-medium", "gemini-4-neon-low", + "gemini-4-carbon-high", "gemini-4-carbon-medium", "gemini-4-carbon-low", + "gemini-4-hydrogen-high", "gemini-4-hydrogen-xhigh", "gemini-4-hydrogen-medium", "gemini-4-hydrogen-low", "gemini-4-argon-high", "gemini-4-argon-medium", "gemini-4-argon-low", ]); expect(() => antigravityLineupProfileId("auto")).toThrow("Invalid Antigravity model ID"); diff --git a/tests/runner-e2e/catalog.test.ts b/tests/runner-e2e/catalog.test.ts index 56010d78d70..fb17acbec12 100644 --- a/tests/runner-e2e/catalog.test.ts +++ b/tests/runner-e2e/catalog.test.ts @@ -330,9 +330,9 @@ describe("runner E2E catalog", () => { expect(localIntegrityTasks).toHaveLength(2); expect(openRouterBreadthTasks).toHaveLength(3); expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([ - 1, 10, 2, 10, 2, 4, 1, 1, 3, 2, 2, 4, 4, 4, 4, 4, 4, 8, 10, 6, 63, 12, 6, 4, 2, 4, 2, 30, 3, 16, 16, 20, 24, 14, 14, 2, 2, 1, 6, 8, 46, 2, 23, 15, 68, 6, 8, 20, 26, 2, 56, 1, 491, 28, 18, 2, 6, 6, 13, 10, 4, 48, 16, 10, 2, 1, 1, 4, 116, 2, 1, 5, 2, + 1, 10, 2, 10, 2, 4, 1, 1, 3, 2, 2, 4, 4, 4, 4, 4, 4, 8, 10, 6, 63, 12, 6, 4, 2, 4, 2, 30, 3, 16, 16, 20, 24, 11, 14, 2, 2, 1, 6, 8, 46, 2, 23, 15, 68, 6, 8, 20, 26, 2, 56, 1, 491, 28, 18, 2, 6, 6, 13, 10, 4, 48, 16, 10, 2, 1, 1, 4, 116, 2, 1, 5, 2, ]); - expect(validateRunnerCatalog()).toHaveLength(1394); + expect(validateRunnerCatalog()).toHaveLength(1391); const frozenDirectory = new URL("./chat-scenarios/", import.meta.url); const frozenIds = readdirSync(frozenDirectory).filter(name => name.endsWith(".yaml") && name !== "defaults.yaml") .flatMap(name => parseDocument(readFileSync(new URL(name, frozenDirectory), "utf8")).toJS().scenarios.map((scenario: { id: string }) => scenario.id)); @@ -343,7 +343,7 @@ describe("runner E2E catalog", () => { expect(chat.map(cell => legacyScenarioIds[cell.task.id] ?? cell.task.id).sort()).toEqual(frozenIds.sort()); for (const cell of chat) expect(selectRunnerExecutions(parseRunnerSelectors(["--id", cell.id]))).toEqual([cell]); expect(selectRunnerExecutions(parseRunnerSelectors(["--all"])).some(cell => ["chat-features", "chat-setup-health"].includes(cell.suite.id))).toBe(false); - expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(1394); + expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(1391); expect( runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"), ).toHaveLength(48); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index f50f66c530a..14d707603b1 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -71,9 +71,9 @@ "packages/shared/src/analytics-consent.ts": "00c4bfbd24ac3a288a68caae52468dfcd26df3e7", "packages/shared/src/announcements.test.ts": "121ed97b560e0dd271fe6602c97e2415ee4e4bf7", "packages/shared/src/announcements.ts": "1405e849eeeeb67239bacc1bbb3903385a5faa6f", - "packages/shared/src/antigravity-models.generated.ts": "cb1e231baef960dff9efda50a9a9f3679a1cc9c1", - "packages/shared/src/antigravity-models.test.ts": "eb5d07faee2dbcd3b9e38690bff78faf01512845", - "packages/shared/src/antigravity-models.ts": "f829cc6bc3755743f39d6e14486bdf3ff7b52456", + "packages/shared/src/antigravity-models.generated.ts": "20530735475863be0cc42a7d19fddf6274a5053a", + "packages/shared/src/antigravity-models.test.ts": "5830c34a7e6efe1e36f372570eb78e51c6c6bd97", + "packages/shared/src/antigravity-models.ts": "e8248731f030904ae9d8249cb7e3de37d8a9e795", "packages/shared/src/antigravity-runtime.test.ts": "f9ebcc9430be51c342b42644b735f1434b405ec7", "packages/shared/src/api.ts": "1d61cdff51433c4136368d52ee7cf2f16aa820ed", "packages/shared/src/app-definitions-url.test.ts": "56792d6745a5bc7eafc36e7403f4c9bbd671ae99", diff --git a/ui/src/components/AdapterLoginChrome.test.tsx b/ui/src/components/AdapterLoginChrome.test.tsx index 175a9ed263d..a8c893bcdfd 100644 --- a/ui/src/components/AdapterLoginChrome.test.tsx +++ b/ui/src/components/AdapterLoginChrome.test.tsx @@ -398,9 +398,9 @@ describe("session replay", () => { expect(link!.getAttribute("target")).toBe("_blank"); expect(link!.getAttribute("rel")).toBe("noreferrer noopener"); expect(container.textContent).toContain("Sign in to Antigravity"); - expect(container.textContent).toContain("127.0.0.1"); + expect(container.textContent).toContain("authorization code or full callback URL"); - const input = container.querySelector('input[aria-label="Antigravity redirect URL"]') as HTMLInputElement | null; + const input = container.querySelector('input[aria-label="Antigravity authorization code or callback URL"]') as HTMLInputElement | null; expect(input).not.toBeNull(); expect(input!.getAttribute("autocomplete")).toBe("off"); expect(input!.getAttribute("spellcheck")).toBe("false"); @@ -416,7 +416,7 @@ describe("session replay", () => { await vi.waitFor(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("does not match")); expect(submitCode).toHaveBeenCalledWith("http://127.0.0.1:41234/?state=bad&code=abc"); // Input stays open after a retryable bad paste. - const retryInput = container.querySelector('input[aria-label="Antigravity redirect URL"]') as HTMLInputElement | null; + const retryInput = container.querySelector('input[aria-label="Antigravity authorization code or callback URL"]') as HTMLInputElement | null; expect(retryInput).not.toBeNull(); await act(async () => { @@ -429,6 +429,33 @@ describe("session replay", () => { expect(submitCode).toHaveBeenCalledWith("http://127.0.0.1:41234/?state=good&code=xyz"); }); + it("prompts for an authorization code with a Submit code button for antigravity.google/oauth-callback", async () => { + const submitCode = vi.fn().mockResolvedValueOnce(undefined); + const container = await render( + , + ); + expect(container.textContent).toContain("then paste the authorization code below"); + expect(container.textContent).toContain("copy the authorization code shown on the page"); + const input = container.querySelector('input[aria-label="Antigravity authorization code"]') as HTMLInputElement | null; + expect(input).not.toBeNull(); + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, "4/0code-value"); + input!.dispatchEvent(new Event("input", { bubbles: true })); + }); + const submitButton = Array.from(container.querySelectorAll("button")).find(b => b.textContent === "Submit code") as HTMLButtonElement | undefined; + expect(submitButton).toBeDefined(); + await act(async () => { submitButton!.click(); }); + expect(submitCode).toHaveBeenCalledWith("4/0code-value"); + }); + it("validates and normalizes pasted Claude codes in LocalProviderLoginInstructions", async () => { const submitCode = vi.fn(async () => {}); const container = await render( @@ -477,7 +504,7 @@ describe("session replay", () => { }} />, ); - expect(container.querySelector('input[aria-label="Antigravity redirect URL"]')).toBeNull(); + expect(container.querySelector('input[aria-label="Antigravity authorization code or callback URL"]')).toBeNull(); expect(container.textContent).toContain("Finish signing in in the Antigravity browser window"); }); diff --git a/ui/src/components/AdapterLoginChrome.tsx b/ui/src/components/AdapterLoginChrome.tsx index 03f1513c3d9..16429db98fa 100644 --- a/ui/src/components/AdapterLoginChrome.tsx +++ b/ui/src/components/AdapterLoginChrome.tsx @@ -598,7 +598,8 @@ export function ProviderSubscriptionCard({ > Sign in to {providerName} - {mode === "hosted_redirect" ? " then paste the redirect URL below" + {mode === "hosted_redirect" + ? (isHostedAntigravityCodeCallback(authorizationUrl) ? " then paste the authorization code below" : " then paste the redirect URL below") : mode === "browser_redirect" ? " then return here" : mode === "submitted_code" ? " then come back and enter authorization code" @@ -642,6 +643,15 @@ function isHttpAuthorizationUrl(url: string | null | undefined): url is string { } } +function isHostedAntigravityCodeCallback(url: string | null | undefined): boolean { + if (!url) return false; + try { + return new URL(url).searchParams.get("redirect_uri") === "https://antigravity.google/oauth-callback"; + } catch { + return false; + } +} + export type LocalLoginPrimaryAction = | { kind: "retry"; label: string; icon: "arrow"; disabled: false } | { kind: "open_sign_in"; label: string; icon: "none"; disabled: false; url: string } @@ -870,11 +880,13 @@ export function LocalProviderLoginInstructions({ adapterType, login, hostedRedir

{optionalHostedGoogleRedirect ? <>Finish signing in in the Antigravity browser window, then return here. If your browser is on another machine and the 127.0.0.1 redirect page won’t load, copy the full URL from your address bar and paste it below. - : <>After signing in to Antigravity, your browser will redirect to a 127.0.0.1 page that won’t load. Copy the full URL from your browser’s address bar and paste it below.} + : isHostedAntigravityCodeCallback(safeAuthorizationUrl) + ? <>After signing in to Antigravity, copy the authorization code shown on the page and paste it below. + : <>After signing in to Antigravity, copy the authorization code or full callback URL from your browser and paste it below.}

{ @@ -885,7 +897,9 @@ export function LocalProviderLoginInstructions({ adapterType, login, hostedRedir onSubmit={() => void submitBrowserCode()} disabled={submitting} /> - + {submitError &&

{submitError}

} : adapterType === "antigravity_runtime" ?

Finish signing in in the Antigravity browser window, then return here.

: } } diff --git a/ui/src/components/ai-connections/useLocalAiLogin.test.tsx b/ui/src/components/ai-connections/useLocalAiLogin.test.tsx index 794711f0d2f..e0fc012c3c6 100644 --- a/ui/src/components/ai-connections/useLocalAiLogin.test.tsx +++ b/ui/src/components/ai-connections/useLocalAiLogin.test.tsx @@ -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()); - 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 })); diff --git a/ui/src/components/new-agent/AgentProviderConnection.test.tsx b/ui/src/components/new-agent/AgentProviderConnection.test.tsx index abb933de5b3..cdb834e1f75 100644 --- a/ui/src/components/new-agent/AgentProviderConnection.test.tsx +++ b/ui/src/components/new-agent/AgentProviderConnection.test.tsx @@ -145,12 +145,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 { @@ -251,7 +251,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"); }); diff --git a/ui/src/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsx index 60746aea500..36cbc230b3a 100644 --- a/ui/src/pages/apps/AppsConnect.test.tsx +++ b/ui/src/pages/apps/AppsConnect.test.tsx @@ -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");