From 78e4f4f130faaf9e2db4c205b733fd7948648b8c Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:21:11 -0600 Subject: [PATCH] feat(runner): Antigravity on ACP 1.5.2 with Linux, API-key auth and Gemini 4 Neon (still pending) (#22591) 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 native Runner starts each agent harness and owns its lifecycle, credentials and recovery > - Google Antigravity is Google's only first-party coding harness, and it is the harness for Gemini 4 Neon > - The Runner had an Antigravity integration, but only as a pending candidate: ACP server 1.4.3, macOS ARM64 only, Google sign-in only, closed unless an operator opened it for one company and one model > - Cloud sandboxes run Linux and use API keys, so the candidate could not run there, and it had one attended test cell > - This pull request moves the integration to ACP server 1.5.2, makes it run on Linux and with a Gemini API key, adds the tests the other ACPX harnesses have, and removes the code paths that would block recovery after release > - The benefit is that the release of Antigravity becomes a small declaration change after the live suites pass. The profile stays `pending` in this pull request. ## Linked Issues or Issue Description Refs #98 Refs #6559 Refs #8523 Refs #21121 (a separate legacy-style `agy_local` adapter that uses the CLI print protocol; this pull request does not replace or include it) ## What Changed **Runtime** - Pin Antigravity ACP server 1.5.2 (was 1.4.3). Owned admission patch is `1.5.2-paperclip.2`. - Verified patched closures for `darwin-arm64`, `linux-x64` and `linux-arm64`. `darwin-x64` stays inventory-only. - The patcher reads Mach-O and ELF builds. It signs macOS output only. One admission source serves all platforms. - Platform gates in TypeScript, Rust, the sidecar schema and the server admit each host that has a verified closure. **Auth and models** - Gemini API-key auth reaches an exact-model session receipt. Admission accepts a model only when the base model and the thinking level both match the requested ID. - API-key connections get a model list on local and cloud environments. The list is generated at build time from the pinned runtime. The server starts no process to read it. - Gemini 4 Neon, Carbon, Argon and Hydrogen are selectable. The picker marks them "needs a paid Gemini API plan" for API-key connections. - One shared module maps model ID to family and thinking level. - `google/gemini-4-neon` is added to the OpenCode model list. A new model audit is in `doc/adapter-model-audit-2026-11-22.md`. **Lifecycle and failures** - A provider error no longer completes the turn. The driver classifies it: overloaded, rate limit, quota, auth rejected, model unavailable. - Overload retries are bounded (3 attempts, about 14 seconds). - A refused session reload maps to incompatible saved state, so the automatic replacement conversation applies. - Server gates that refused restart recovery, remote targets and shared state for Antigravity now apply only while the profile is pending. - A Google sign-in connection with a cloud environment is refused at save and at Test, with a plain message. - A released profile rejects candidate grants in TypeScript and in Rust. **Launch cost and integrity (all native ACPX providers)** - Each closure is verified one time into a sealed read-only store. Later launches check file identities and hash the exact executable they start. - Remote provider-pack verification is recorded per sandbox lease. Later runs check kernel identity and fall back to the full hash on any difference. - Superseded stores are removed in the background after a launch. **Provider pack and image** - The provider pack carries Antigravity for `linux-x64` as a candidate provider. It becomes an ordinary provider from the profile status alone. - The Daytona image build accepts the candidate. A credential-free smoke runs in the build. **Tests and CI** - New `antigravity-qualification` suite: 24 cells, local and Daytona. - New model lineup suites: 14 API-key cells and 14 Gemini 4 cells. Each cell requires the exact model in the Runner receipt. - Antigravity can run the `chat-features` cases with `--profile runner-acpx-antigravity`. - `runner-full-stack-e2e.yml` passes `GEMINI_API_KEY` for the new profile and derives candidate providers from the selected Daytona cells. **Docs** - `doc/plans/2026-11-22-antigravity-qualification.md` is the current release contract, acceptance ledger and operator recipe. ## Verification Commands that passed on the final revision: - `pnpm build` - Typecheck for all packages, including the runner-e2e test projects - `pnpm test:e2e:runner:unit`: 11,665 Vitest tests passed, 25 skipped; 386 node tests passed - `cargo test -p paperclip-runner-core -- --test-threads=4`: 1,199 passed, 2 failed. The 2 failures are Codex transport timing tests that pass alone and on `master`. - `cargo fmt --check`, `check:acpx-profiles`, `check:protocol-types`, `node scripts/check-maps.mjs` - Native patch tests: 9 of 9 on `darwin-arm64` and 9 of 9 on `linux-x64` - UI picker tests: 397 of 397 Known failures that also fail on `master`: - 11 runner package script tests (browser, Pi and package-boundary checks) - 6 `runtime-selection` tests that read an untracked local skill file Live evidence, without a prompt: - Clean provisioning on `darwin-arm64` and on `linux-x64` in a Daytona sandbox. The closure digests reproduce. A changed or missing file is rejected. - `initialize` reports 1.5.2. An API-key session returns a receipt for exactly `gemini-3.8-flash-low` and the exact instruction bytes, on both platforms. - All 28 model IDs (14 Gemini 3, 14 Gemini 4) return an exact receipt under an API key. - A session survives a process kill and resumes in a new process with exact receipts, on both platforms. - The server's remote path verifies the provider pack in a Daytona sandbox. - Run start to native `initialize`: 3.45 s to 1.46 s on macOS, 3.65 s to 1.74 s on Linux x64, before the per-launch executable hash was restored (about 60 ms on macOS; not measured on Linux). - Remote pack verification on a reused sandbox lease: about 4.3 s to about 0.25 s. Live evidence, with a prompt, on an already-released harness: - Pi native, `pi-native.runner-acpx-pi.local.agent-files-fresh-run`, on `darwin-arm64` at `427e9b088b`: 1 of 1 passed, 14 of 14 checks, both native runs succeeded (25.5 s and 25.7 s). The process started from the new launch store with no fallback warning. - The same cell and `native-pending-controller-restart` failed in the paid workflow on this branch and on `master` in the same way, before any native start. The workflow does not install the Pi runtime for local cells, so the agent setup check fails. That is a workflow gap, not part of this change. **Not run.** No Antigravity prompt completed on 1.5.2 on any platform. The only Gemini key available is on the free tier, and Google returned 503 or 429 for each attempt on two days. These gates are open: - All 24 `antigravity-qualification` cells - Both model lineup suites, including inference on Gemini 4 Neon - The attended Google sign-in journey on 1.5.2 - The chat cases under Antigravity - Image pull time and startup time on a published image - A native start on `linux-arm64` - A live provider-death cell for Kimi, Pi or Copilot on the new launch store (one ordinary Pi cell passed live; see above) ## Risks - **The launch store changes how every native ACPX provider starts** (Kimi, Copilot, Cursor, Pi), not only Antigravity. A review found two defects in the first version (an executable swap was possible, and Pi launches broke). Both are fixed with tests. One live Pi cell passed on this branch on macOS. No live provider-death cell and no Linux cell ran for those providers. - The profile digest changes. Saved Antigravity candidate sessions and existing candidate grants stop working. The new release refuses old state by name and starts a replacement conversation. - The Linux provider pack and the Daytona image grow by about 834 MB (about 274 MB compressed) when Antigravity is included. - The pack verification record is in server memory. The first run after a server restart pays the full hash again. - Antigravity 1.5.2 reads the workspace `GEMINI.md` and `AGENTS.md` as user rules. This is deliberate and matches Codex. Any other rule file is refused. - Orchestrator mode is not available. ACP server 1.5.2 does not expose it. - Antigravity stays `pending`. Normal users cannot run it until a later change removes the pending status. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) planned, briefed and integrated the work, with tool use. - Claude Opus 5.5 (`claude-opus-5-5`) subagents wrote the code and ran the tests, with tool use and code execution. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 --- .dockerignore | 3 +- .env.runner-e2e.example | 3 + .github/docker-context-checks.Dockerfile | 8 +- .github/workflows/runner-full-stack-e2e.yml | 47 +- .github/workflows/runner-image.yml | 1 + Dockerfile | 5 +- doc/adapter-model-audit-2026-11-22.md | 108 +++ .../runner-rich-acp-capabilities.md | 23 +- doc/evals.md | 9 + .../2026-10-28-antigravity-integration.md | 7 + .../2026-11-22-antigravity-qualification.md | 178 ++++ doc/runner-internals.md | 30 +- docker/daytona-runner/Dockerfile | 6 + docker/daytona-runner/README.md | 11 + packages/adapters/opencode-local/src/index.ts | 1 + packages/paperclip-runner/README.md | 39 +- packages/paperclip-runner/acpx-profiles.json | 6 +- .../antigravity-distributions.json | 114 ++- packages/paperclip-runner/package.json | 4 +- .../provider-schemas/acpx-sidecar.schema.json | 6 +- .../src/acpx_candidate_admission.rs | 313 +++++-- .../runner-core/src/acpx_provider_backend.rs | 259 +++++- .../runner-core/src/acpx_provider_session.rs | 19 +- .../runner-core/src/acpx_sidecar_transport.rs | 18 +- .../runner-core/src/bin/fake-acpx-sidecar.rs | 23 + .../runner-core/src/bin/paperclip-runnerd.rs | 19 +- .../crates/runner-core/src/durable/mod.rs | 8 +- .../crates/runner-core/src/durable/runner.rs | 65 ++ .../src/generated_acpx_profiles.rs | 26 +- .../crates/runner-core/src/local_runner.rs | 21 +- .../src/native_provider_backend.rs | 97 +++ .../tests/acpx_saved_state_incompatible.rs | 297 +++++++ .../tests/native_provider_backend.rs | 35 +- .../antigravity-provider-pack-smoke.mjs | 168 ++++ .../antigravity-provider-pack-smoke.test.mjs | 71 ++ .../scripts/build-provider-pack.mjs | 11 +- .../scripts/candidate-provider-pack.mjs | 62 +- .../scripts/candidate-provider-pack.test.mjs | 74 +- .../scripts/generate-acpx-profiles.mjs | 18 +- .../scripts/generate-antigravity-models.mjs | 268 ++++++ .../materialize-antigravity-distribution.mjs | 6 +- ...erialize-antigravity-distribution.test.mjs | 72 +- .../patch-antigravity-runtime.admission.py | 266 +++++- .../scripts/patch-antigravity-runtime.mjs | 135 ++- .../patch-antigravity-runtime.test.mjs | 315 ++++++- ...antigravity-runtime.tool-lifecycle.test.py | 14 +- ...h-antigravity-runtime.turn-failure.test.py | 144 ++++ .../probe-antigravity-metadata.test.mjs | 33 +- .../scripts/release-provider-pack.mjs | 28 +- .../scripts/release-provider-pack.test.mjs | 59 +- .../src/cli/acpx-sidecar-input.ts | 2 + .../acpx-controller-recovery.test.ts | 39 +- .../src/drivers/acpx/acpx-runtime-adapter.ts | 19 +- .../acpx/antigravity-acpx-runtime.test.ts | 67 +- .../acpx/antigravity-admission.test.ts | 68 +- .../src/drivers/acpx/antigravity-admission.ts | 44 +- .../antigravity-auth-stream-order.test.ts | 4 +- .../src/drivers/acpx/antigravity-auth.test.ts | 2 +- .../src/drivers/acpx/antigravity-auth.ts | 12 +- .../drivers/acpx/antigravity-installation.ts | 2 +- .../acpx/antigravity-model-catalog.test.ts | 87 ++ .../drivers/acpx/antigravity-models.test.ts | 2 +- .../src/drivers/acpx/antigravity-models.ts | 3 +- .../src/drivers/acpx/antigravity-questions.ts | 28 +- .../acpx/antigravity-turn-failure.test.ts | 64 ++ ...date-admission.antigravity-release.test.ts | 61 ++ .../drivers/acpx/candidate-admission.test.ts | 17 +- .../src/drivers/acpx/candidate-admission.ts | 13 +- ...ility-profiles.antigravity-release.test.ts | 17 + .../src/drivers/acpx/capability-profiles.ts | 11 +- .../drivers/acpx/copilot-installation.test.ts | 2 +- .../src/drivers/acpx/copilot-installation.ts | 1 + .../src/drivers/acpx/cursor-installation.ts | 1 + .../src/drivers/acpx/generated-profiles.ts | 26 +- .../src/drivers/acpx/kimi-installation.ts | 1 + ...ative-distribution-integrity.store.test.ts | 360 ++++++++ ...ive-distribution-integrity.test-support.ts | 137 ++++ .../native-distribution-integrity.test.ts | 219 ++--- .../acpx/native-distribution-integrity.ts | 766 +++++++++++++++--- .../src/drivers/acpx/provider-failure.ts | 52 +- packages/paperclip-runner/src/index.ts | 5 +- .../antigravity-candidate-startup.test.ts | 24 +- ...odex-transport-antigravity-release.test.ts | 98 +++ .../src/live/runnerd-codex-transport.ts | 16 +- .../test/acpx-sidecar-contract.test.mjs | 4 +- .../src/antigravity-models.generated.ts | 177 ++++ .../shared/src/antigravity-models.test.ts | 98 +++ packages/shared/src/antigravity-models.ts | 154 ++++ packages/shared/src/index.ts | 21 + .../prepare-runner-release-image.test.mjs | 19 +- scripts/prepare-runner-release-image.mjs | 13 +- scripts/runner-image-identity.mjs | 5 +- .../agent-adapter-validation-routes.test.ts | 22 + .../antigravity-connection-models.test.ts | 37 +- .../antigravity-connection-probe.test.ts | 118 ++- .../antigravity-save-refusal.test.ts | 163 ++++ server/src/routes/agents.ts | 61 +- .../services/antigravity-connection-models.ts | 20 +- .../services/antigravity-connection-probe.ts | 90 +- .../heartbeat/native-lifecycle.test.ts | 21 + .../services/heartbeat/native-lifecycle.ts | 8 +- .../services/heartbeat/runtime-selection.ts | 4 +- .../native-runtime/acpx-qualification.ts | 38 +- .../antigravity-candidate-admission.test.ts | 52 +- .../antigravity-connection-policy.ts | 58 ++ .../antigravity-release.test.ts | 165 ++++ .../native-runtime/antigravity-release.ts | 100 +++ .../antigravity-runner-credentials.test.ts | 38 +- .../antigravity-runner-credentials.ts | 9 +- .../native-provider-failure.test.ts | 66 +- .../native-runtime/native-provider-failure.ts | 32 +- .../native-session-executor.test.ts | 74 +- .../native-runtime/native-session-executor.ts | 115 ++- .../native-session-resume.test.ts | 38 + .../native-runtime/native-warm-capability.ts | 7 + .../native-runtime/provider-profile.ts | 8 +- .../remote-provider-pack-verification.test.ts | 74 +- .../remote-provider-pack-verification.ts | 67 +- .../remote-provider-pack.test.ts | 98 ++- .../native-runtime/remote-provider-pack.ts | 120 ++- .../services/native-runtime/runtime-mode.ts | 4 +- server/src/vendor/paperclip-runner/index.ts | 3 + tests/runner-e2e/ANTIGRAVITY-AGENT-JOURNEY.md | 6 +- tests/runner-e2e/README.md | 1 + tests/runner-e2e/SUITES.md | 93 +++ tests/runner-e2e/antigravity-admission.ts | 46 ++ .../antigravity-journey-config.test.ts | 2 +- .../antigravity-journey-launch.test.ts | 2 +- .../antigravity-qualification-cases.ts | 165 ++++ .../antigravity-qualification.test.ts | 309 +++++++ tests/runner-e2e/catalog.test.ts | 6 +- tests/runner-e2e/catalog.ts | 48 +- .../runner-e2e/chat-catalog-contract.test.ts | 3 +- tests/runner-e2e/chat-feature-scoring.test.ts | 2 +- tests/runner-e2e/chat-flow.ts | 2 +- .../runner-e2e/copilot-provider-death.test.ts | 7 +- tests/runner-e2e/copilot-provider-death.ts | 6 +- tests/runner-e2e/daytona-image-content.ts | 2 +- tests/runner-e2e/harness-env.ts | 9 +- tests/runner-e2e/journey-features.ts | 15 +- tests/runner-e2e/kimi-lifecycle.test.ts | 19 +- tests/runner-e2e/kimi-local-provider-fault.ts | 27 +- .../kimi-provider-fault-contract.ts | 8 +- .../kimi-provider-fault-diagnostic.py | 2 +- tests/runner-e2e/kimi-provider-fault.py | 29 +- tests/runner-e2e/kimi-provider-fault.test.py | 89 +- tests/runner-e2e/kimi-provider-fault.test.ts | 13 +- tests/runner-e2e/launch.ts | 2 + tests/runner-e2e/live-fixtures.test.ts | 2 +- tests/runner-e2e/live-fixtures.ts | 2 +- .../runner-e2e/native-active-stop-evidence.ts | 106 ++- tests/runner-e2e/native-active-stop-flow.ts | 83 +- tests/runner-e2e/native-active-stop-tasks.ts | 25 + .../native-completion-defaults.test.ts | 6 +- tests/runner-e2e/native-provider-loss-flow.ts | 16 +- tests/runner-e2e/pi-provider-fault.py | 10 +- tests/runner-e2e/pi-provider-fault.test.py | 48 +- tests/runner-e2e/pi-provider-fault.test.ts | 2 +- .../runner-e2e/remote-native-fixtures.test.ts | 2 +- tests/runner-e2e/remote-native-fixtures.ts | 4 +- tests/runner-e2e/runner.spec.ts | 6 +- tests/runner-e2e/selectors.ts | 19 + tests/runner-e2e/server-restart-request.ts | 33 +- .../runner-e2e/source-sdk-public-inputs.json | 5 +- tests/runner-e2e/types.ts | 8 +- ui/src/components/AgentConfigForm.tsx | 57 +- ui/src/components/ModelDropdown.test.tsx | 45 +- ui/src/components/new-agent/NewAgentSetup.tsx | 12 +- ui/src/lib/native-model-catalog.ts | 16 +- ui/src/pages/NewAgent.test.tsx | 8 +- 170 files changed, 8498 insertions(+), 954 deletions(-) create mode 100644 doc/adapter-model-audit-2026-11-22.md create mode 100644 doc/plans/2026-11-22-antigravity-qualification.md create mode 100644 packages/paperclip-runner/runner/crates/runner-core/tests/acpx_saved_state_incompatible.rs create mode 100644 packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.mjs create mode 100644 packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.test.mjs create mode 100644 packages/paperclip-runner/scripts/generate-antigravity-models.mjs create mode 100644 packages/paperclip-runner/scripts/patch-antigravity-runtime.turn-failure.test.py create mode 100644 packages/paperclip-runner/src/drivers/acpx/antigravity-model-catalog.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/antigravity-turn-failure.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/candidate-admission.antigravity-release.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/capability-profiles.antigravity-release.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.store.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test-support.ts create mode 100644 packages/paperclip-runner/src/live/runnerd-codex-transport-antigravity-release.test.ts create mode 100644 packages/shared/src/antigravity-models.generated.ts create mode 100644 packages/shared/src/antigravity-models.test.ts create mode 100644 packages/shared/src/antigravity-models.ts create mode 100644 server/src/__tests__/antigravity-save-refusal.test.ts create mode 100644 server/src/services/native-runtime/antigravity-connection-policy.ts create mode 100644 server/src/services/native-runtime/antigravity-release.test.ts create mode 100644 server/src/services/native-runtime/antigravity-release.ts create mode 100644 tests/runner-e2e/antigravity-admission.ts create mode 100644 tests/runner-e2e/antigravity-qualification-cases.ts create mode 100644 tests/runner-e2e/antigravity-qualification.test.ts diff --git a/.dockerignore b/.dockerignore index f8c9dc4a4b4..a2e38f6f325 100644 --- a/.dockerignore +++ b/.dockerignore @@ -31,8 +31,9 @@ packages/paperclip-runner/**/*.test.ts packages/paperclip-runner/**/*.test.tsx packages/paperclip-runner/runner/crates/*/tests packages/paperclip-runner/scripts/*-smoke.mjs -# The provider-pack builder imports this helper during image builds. +# The provider-pack builder imports these helpers during image builds. !packages/paperclip-runner/scripts/kimi-provider-pack-smoke.mjs +!packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.mjs # Exceptions (last match wins): the image build re-runs the runner's # generated-file drift checks, so their committed outputs and inputs must # survive the slimming above. 2026-09-04: the *.md rule stripped the diff --git a/.env.runner-e2e.example b/.env.runner-e2e.example index dcfbfc6df40..3d77805c7ef 100644 --- a/.env.runner-e2e.example +++ b/.env.runner-e2e.example @@ -10,6 +10,9 @@ DAYTONA_API_KEY= CURSOR_AUTH_TOKEN= COPILOT_GITHUB_TOKEN= +# Explicit-only Google Antigravity suites (runner-acpx-antigravity). +GEMINI_API_KEY= + # Required only for Daytona cells. Use an immutable, anonymously pullable # digest from the Runner Full-Stack E2E image job or a locally published image. PAPERCLIP_E2E_DAYTONA_IMAGE=ghcr.io/paperclipai/paperclip-daytona-runner@sha256:REPLACE_ME diff --git a/.github/docker-context-checks.Dockerfile b/.github/docker-context-checks.Dockerfile index 6397a234929..144ec1b0e44 100644 --- a/.github/docker-context-checks.Dockerfile +++ b/.github/docker-context-checks.Dockerfile @@ -24,8 +24,14 @@ WORKDIR /context COPY . . # Verify ACPX release declarations against the exact Docker context. RUN node packages/paperclip-runner/scripts/generate-acpx-profiles.mjs --check -# The provider-pack builder imports this offline smoke helper during image builds. +# The provider-pack builder imports these offline smoke helpers during image builds. RUN node -e 'import("./packages/paperclip-runner/scripts/kimi-provider-pack-smoke.mjs")' +RUN node -e 'import("./packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.mjs")' +# The Antigravity pack patches its vendor closure with these source-owned inputs. +RUN test -f packages/paperclip-runner/scripts/materialize-antigravity-distribution.mjs \ + && test -f packages/paperclip-runner/scripts/patch-antigravity-runtime.mjs \ + && test -f packages/paperclip-runner/scripts/patch-antigravity-runtime.admission.py \ + && test -f packages/paperclip-runner/antigravity-distributions.json # Committed artifacts the image build reads whose drift checks cannot run # here (they need the locked dependency tree or compiled dist/). Existence # in the context is the property this probe guards; content correctness is diff --git a/.github/workflows/runner-full-stack-e2e.yml b/.github/workflows/runner-full-stack-e2e.yml index df00eb932fa..d8347bb4dd1 100644 --- a/.github/workflows/runner-full-stack-e2e.yml +++ b/.github/workflows/runner-full-stack-e2e.yml @@ -389,6 +389,7 @@ jobs: execution_ids: ${{ steps.catalog.outputs.execution_ids }} max_parallel: ${{ steps.catalog.outputs.max_parallel }} daytona_image_content_id: ${{ steps.daytona_image_content.outputs.content_id }} + candidate_providers: ${{ steps.catalog.outputs.candidate_providers }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -434,12 +435,6 @@ jobs: - run: pnpm install --frozen-lockfile - # The v2 contract fails closed unless every Docker FROM is digest-pinned, - # and hashes those exact base references into the immutable image tag. - - name: Compute Daytona image content ID with pinned bases - id: daytona_image_content - run: echo "content_id=$(pnpm --silent test:e2e:runner:image-id)" >> "$GITHUB_OUTPUT" - - name: Validate selectors and emit matrix id: catalog env: @@ -484,6 +479,7 @@ jobs: echo "needs_runner_typescript=true" echo "needs_native_binaries=true" echo "needs_remote_provider_pack=false" + echo "candidate_providers=" echo "max_parallel=1" } >> "$GITHUB_OUTPUT" exit 0 @@ -538,6 +534,11 @@ jobs: echo "needs_remote_provider_pack=$(jq -r '[.include[] | select((.environmentId == "daytona") and ((.profileId | startswith("runner-opencode")) or (.profileId | startswith("runner-acpx-"))))] | length > 0' <<< "$catalog_json")" echo "execution_ids=$(jq -c '.executionIds' <<< "$catalog_json")" } >> "$GITHUB_OUTPUT" + # Pending candidates the selected Daytona cells run, derived from + # their profiles; the image and the controller pack carry exactly these. + candidate_providers="$(jq -r '(.candidateProviders // []) | join(",")' <<< "$catalog_json")" + [[ "$candidate_providers" =~ ^([a-z]+(,[a-z]+)*)?$ ]] + echo "candidate_providers=$candidate_providers" >> "$GITHUB_OUTPUT" if ! [[ "$MAX_PARALLEL_LIMIT" =~ ^[1-9][0-9]*$ ]] || [ "$MAX_PARALLEL_LIMIT" -gt 100 ]; then echo "Runner selection emitted an invalid max-parallel limit." >&2 exit 1 @@ -555,6 +556,21 @@ jobs: fi echo "max_parallel=$MAX_PARALLEL" >> "$GITHUB_OUTPUT" + # The v2 contract fails closed unless every Docker FROM is digest-pinned, + # and hashes those exact base references into the immutable image tag. + # A candidate image has its own identity, never the default image's. + - name: Compute Daytona image content ID with pinned bases + id: daytona_image_content + env: + CANDIDATE_PROVIDERS: ${{ steps.catalog.outputs.candidate_providers }} + run: | + set -euo pipefail + if [ -n "$CANDIDATE_PROVIDERS" ]; then + echo "content_id=$(pnpm --silent test:e2e:runner:image-id "--candidate-providers=$CANDIDATE_PROVIDERS")" >> "$GITHUB_OUTPUT" + else + echo "content_id=$(pnpm --silent test:e2e:runner:image-id)" >> "$GITHUB_OUTPUT" + fi + daytona_image: name: Publish verified Daytona image needs: [authorize, target_lock, catalog] @@ -634,8 +650,10 @@ jobs: TARGET_LOCK_SHA256: ${{ needs.target_lock.outputs.lock_sha256 }} TARGET_REF: ${{ needs.authorize.outputs.target_ref }} DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + CANDIDATE_PROVIDERS: ${{ needs.catalog.outputs.candidate_providers }} run: | set -euo pipefail + [[ "$CANDIDATE_PROVIDERS" =~ ^([a-z]+(,[a-z]+)*)?$ ]] if [ "$NEEDS_DAYTONA" != true ]; then { echo "image=" @@ -683,6 +701,7 @@ jobs: --build-arg "PAPERCLIP_RUNNER_CONTENT_ID=${IMAGE_CONTENT_ID}" \ --build-arg "PAPERCLIP_RUNNER_SOURCE_REVISION=${TARGET_SHA}" \ --build-arg "PAPERCLIP_RUNNER_LOCK_SHA256=${TARGET_LOCK_SHA256}" \ + --build-arg "PAPERCLIP_RUNNER_CANDIDATE_PROVIDERS=${CANDIDATE_PROVIDERS}" \ --file docker/daytona-runner/Dockerfile \ --tag "$IMAGE_TAG" \ "${cache_args[@]}" \ @@ -965,7 +984,13 @@ jobs: # content ID. Matching that revision lets remote execution reuse the # verified pack already installed in the immutable image. PAPERCLIP_RUNNER_SOURCE_REVISION: ${{ needs.daytona_image.outputs.source_revision }} - run: node packages/paperclip-runner/scripts/build-provider-pack.mjs packages/paperclip-runner/provider-pack + # The same candidate selection as the image, so the image pack is reused. + CANDIDATE_PROVIDERS: ${{ needs.catalog.outputs.candidate_providers }} + run: | + set -euo pipefail + [[ "$CANDIDATE_PROVIDERS" =~ ^([a-z]+(,[a-z]+)*)?$ ]] + node packages/paperclip-runner/scripts/build-provider-pack.mjs packages/paperclip-runner/provider-pack \ + "--candidate-providers=$CANDIDATE_PROVIDERS" - name: Package verified remote provider pack if: needs.catalog.outputs.needs_remote_provider_pack == 'true' @@ -1218,6 +1243,13 @@ jobs: if: matrix.environmentId == 'local' && (matrix.profileId == 'runner-acpx-grok' || matrix.profileId == 'runner-acpx-grok-subscription') run: sudo node packages/paperclip-runner/scripts/provision-grok.mjs /opt/paperclip/providers/grok/1.0.13/grok + # Antigravity is not an npm package: provision its checksum-verified, + # admission-patched native closure into the runner-owned cache. Daytona + # cells use the closure carried by the remote provider pack instead. + - name: Provision verified Antigravity runtime + if: matrix.environmentId == 'local' && startsWith(matrix.profileId, 'runner-acpx-antigravity') + run: node --use-env-proxy packages/paperclip-runner/scripts/provision-antigravity.mjs + - name: Download immutable campaign outputs if: startsWith(matrix.profileId, 'runner-') || matrix.suiteId == 'openrouter-model-breadth' uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 @@ -1445,6 +1477,7 @@ jobs: XAI_API_KEY: ${{ matrix.credentialName == 'XAI_API_KEY' && secrets.XAI_API_KEY || '' }} GROK_AUTH_JSON: ${{ matrix.credentialName == 'GROK_AUTH_JSON' && secrets.GROK_AUTH_JSON || '' }} COPILOT_GITHUB_TOKEN: ${{ matrix.credentialName == 'COPILOT_GITHUB_TOKEN' && secrets.COPILOT_GITHUB_TOKEN || '' }} + GEMINI_API_KEY: ${{ matrix.credentialName == 'GEMINI_API_KEY' && secrets.GEMINI_API_KEY || '' }} DAYTONA_API_KEY: ${{ matrix.environmentId == 'daytona' && secrets.DAYTONA_API_KEY || '' }} PAPERCLIP_E2E_DAYTONA_IMAGE: ${{ needs.daytona_image.outputs.image }} PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH: ${{ github.workspace }}/packages/paperclip-runner/provider-pack diff --git a/.github/workflows/runner-image.yml b/.github/workflows/runner-image.yml index 633d63b5032..035e33d50d2 100644 --- a/.github/workflows/runner-image.yml +++ b/.github/workflows/runner-image.yml @@ -40,6 +40,7 @@ on: - patches/** - packages/paperclip-runner/** - packages/paperclip-eval-kernel/** + - packages/shared/src/antigravity-models.generated.ts - packages/shared/src/provider-failure.generated.ts - scripts/create-provider-pack-archive.mjs - scripts/link-plugin-dev-sdk.mjs diff --git a/Dockerfile b/Dockerfile index 88aa92814d6..3cd1ad0ecd6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -127,8 +127,9 @@ COPY scripts/create-provider-pack-archive.mjs scripts/link-plugin-dev-sdk.mjs sc COPY packages/paperclip-eval-kernel /packages/paperclip-eval-kernel COPY packages/paperclip-runner /packages/paperclip-runner # build:typescript checks the Runner's generated provider-failure contract -# against this copy, which @paperclipai/shared owns. -COPY packages/shared/src/provider-failure.generated.ts /packages/shared/src/ +# and the Antigravity model catalog against these copies, which +# @paperclipai/shared owns. +COPY packages/shared/src/provider-failure.generated.ts packages/shared/src/antigravity-models.generated.ts /packages/shared/src/ # Debian bookworm is the oldest glibc any consumer runs, so a daemon compiled # here also runs on trixie. The pack copies this Node binary as its own diff --git a/doc/adapter-model-audit-2026-11-22.md b/doc/adapter-model-audit-2026-11-22.md new file mode 100644 index 00000000000..a3959349fe5 --- /dev/null +++ b/doc/adapter-model-audit-2026-11-22.md @@ -0,0 +1,108 @@ +# Adapter model audit: November 22, 2026 + +This audit follows the [November 18, 2026 audit](adapter-model-audit-2026-11-18.md). +It adds Gemini 4 Neon where its neighbouring Gemini 4 models already appear, +records the Google Antigravity model catalog for the pinned ACP server 1.5.2, +and maps which Gemini models each Google sign-in route can reach. Catalog +entries identify models; accounts, plans and keys determine access. No agent +defaults or saved model selections are migrated. + +## Model changes + +| Adapter | Change | +| --- | --- | +| OpenCode | Add `google/gemini-4-neon` to the static fallback, ahead of Carbon, Argon and Hydrogen. | +| Google Antigravity (Paperclip Runner) | API-key connections now get a model list on every environment, generated from the pinned runtime: 14 Gemini 3 models, then the 14 Gemini 4 models marked as needing a paid Gemini API plan. Google sign-in still reads the account's own list on the Paperclip host. | +| Gemini CLI, Cursor | No change. Neither list carries a Gemini 4 model, so Neon is not added on its own. Gemini CLI support for Gemini 4 stays deferred as in the November 18 audit. | +| Claude Code, Codex, Grok Build, Kimi Code, Pi, Hermes | No change. | + +## Google Antigravity model catalog (ACP server 1.5.2) + +A model ID is `-`: the family is the base model and the level +is its thinking level. The server's levels are `minimal`, `low`, `medium`, +`high` and `extra_high`. A Google account's own list spells extra high as +`xhigh`, adds `max`, and keeps five legacy IDs that do not spell their level +(for example `gemini-3-flash-agent` is Gemini 3.5 Flash at high). One shared +module, `packages/shared/src/antigravity-models.ts`, parses and formats every +spelling; each ID formats back to itself. + +| Family | Levels, in the server's order | API key | Notes | +| --- | --- | --- | --- | +| Gemini 3.8 Flash | high, medium, low | Listed (default `gemini-3.8-flash-high`) | | +| Gemini 3.7 Flash | high, medium, low | Listed | | +| Gemini 3.6 Flash | high, medium, low | Listed | | +| Gemini 3.5 Flash | high, medium, low | Listed | | +| Gemini 3.1 Pro | high, low | Listed | Sent as `gemini-3.1-pro-preview` | +| Gemini 4 Carbon | medium, high, low | Selectable, needs a paid plan | Agent Platform default is `gemini-4-carbon-medium` | +| Gemini 4 Neon | high, extra_high, medium, low | Selectable, needs a paid plan | | +| Gemini 4 Hydrogen | high, extra_high, medium, low | Selectable, needs a paid plan | | +| Gemini 4 Argon | high, medium, low | Selectable, needs a paid plan | Vertex serves it only at location `global` | + +No family offers `minimal` in 1.5.2. The earlier 25-model API-key lineup (five +families times five levels) was wrong; the real list has 14 models. + +`node packages/paperclip-runner/scripts/generate-antigravity-models.mjs` +writes `packages/shared/src/antigravity-models.generated.ts` on darwin-arm64. +It starts the pinned, patched runtime with a placeholder API key (the server +does not check the key and builds this list locally), opens one session +without a prompt, and reads its model list. It also reads the families and +levels from the server's own catalog table in the verified vendor archive and +stops if the two disagree. The file records the runtime version and the +darwin-arm64 vendor archive and closure digests. Its `--check` mode +runs in the runner's TypeScript build and fails when the checked-in runtime +declaration changes or the file was edited by hand. + +## Routes to each model + +| Route | Gemini 3 (Flash, 3.1 Pro) | Gemini 4 (Carbon, Neon, Hydrogen, Argon) | State | +| --- | --- | --- | --- | +| Personal Google sign-in | Whatever the account's list offers | Whatever the account's list offers | Local Paperclip host only. Not exercised with a Gemini 4 account. | +| Gemini API key | Listed by the server | Not listed; selected through Paperclip's exact-model admission | Local and cloud environments. Gemini 4 needs a key on a paid plan with Gemini 4 quota. | +| Agent Platform (Vertex) | Listed | Listed | Advertised by the server; Paperclip has no Agent Platform connection. | + +How a Gemini 4 model runs with an API key: the server marks the Gemini 4 +families `agent_platform_only`, so a session started on its default model +refuses a later `set_model` to Neon. Paperclip does not start that way. +Its exact-model admission asks for the requested model when the session is +created. The server then keeps the model as a "custom model", sends the base +model with the thinking level to the Gemini Developer API, and the owned +admission patch checks that both match the requested ID before it acknowledges +the session. This needs no change to the admission patch and no +`AGY_ACP_DEFAULT_MODEL`. + +## Sources and verification + +Research date: November 22, 2026. + +- The pinned server's `model_selection.py` (ACP server 1.5.2, darwin-arm64 + archive `123a16d5…4845`) defines the families, their levels, + `agent_platform_only`, the account level spellings (`xhigh`, `max`) and the + legacy IDs. +- Live, prompt-free check on darwin-arm64: one `gemini-api-key` session listed + exactly the 14 IDs above, with `gemini-3.8-flash-high` current. The generated + file is that list. +- Live, prompt-free check of admission: for all 28 IDs (14 Gemini 3 and 14 + Gemini 4) a session created with Paperclip's admission request returned an + admission receipt for the exact ID, and `session/set_model` to the same ID + was accepted. As a control, `set_model` to `gemini-4-neon-high` on a default + API-key session was refused with "not available for the current + authentication method". +- The Gemini Developer API model list for the test key includes + `models/gemini-4-neon`, `gemini-4-carbon`, `gemini-4-hydrogen` and + `gemini-4-argon`, all with thinking. The key is free tier, so no prompt was + sent; Neon inference on a paid key is not yet observed. +- OpenRouter's public model list (`/api/v1/models`) includes + `google/gemini-4-neon` (and a `:batch` variant). The models.dev registry that + OpenCode reads lists `gemini-4-neon` under `google`, `google-vertex` and + `openrouter`. + +## Open items + +- Observe one accepted Neon prompt per level with a Gemini API key on a paid + plan; until then the Gemini 4 API-key lineup is admitted but not inferred. +- When Google refuses a model at run time (quota of zero, unknown model, or an + auth-method refusal), the run should show the plain-language message from + `antigravityModelRefusalMessage` instead of the provider's text. The runner + driver owns that classification. +- Agent Platform connections and remote Google sign-in remain open decisions + in the [qualification plan](plans/2026-11-22-antigravity-qualification.md). diff --git a/doc/architecture/runner-rich-acp-capabilities.md b/doc/architecture/runner-rich-acp-capabilities.md index 63bb5883d46..af7592feef3 100644 --- a/doc/architecture/runner-rich-acp-capabilities.md +++ b/doc/architecture/runner-rich-acp-capabilities.md @@ -902,9 +902,26 @@ configuration defaults to full auto; it never overrides read-only task policy. Cursor pins `2026.09.26-dd393fe`; Copilot pins `1.0.88`; Pi pins wrapper `0.0.33`, runtime `1.0.0` (Pi profile v13), portable Node and its full npm lock. Native distribution hashes cover macOS ARM64, macOS x64 and Linux x64. Source-owned closure pins remain -separate from profile declaration digests. Native admission reads held files, -verifies every admitted byte, creates a private immutable snapshot and retains -the existing process guardian. A manifest cannot supply its own trusted pin. +separate from profile declaration digests. Native admission reads held files and +verifies every admitted byte once per closure into a sealed, runner-owned +verified store (`$PAPERCLIP_ACPX_NATIVE_STORE_ROOT`, default +`$TMPDIR/paperclip-verified-native-`). A configured root that is not a +private directory of the runner user refuses the launch; an unsafe default root +falls back, with a warning, to a process-private store removed with its last +launch. A process leases a closure before reading its store, and pruning of +superseded closures excludes those leases through per-closure prune markers. +Later launches bind the store by the +kernel identity (device, inode, size, mtime, ctime) recorded when its bytes were +hashed, re-hash only a changed installed source, and get a small private launch +directory. The store also holds the closure's module guard beside its +entrypoints (Pi's pinned entry hands it to its child) and compares it byte for +byte on each launch. A failed store check retires the store and rebuilds it from +a fresh full verification. The recorded identities are not trusted for code +that runs, because a process with the runner's uid can rewrite a file and its +record together: the launcher streams the exact executable descriptor it spawns +through SHA-256 against the pinned digest, and the module guard hashes every +Node module at load. The existing process guardian is retained. A manifest cannot +supply its own trusted pin. Candidate credentials are only read from explicitly bound run environments: Cursor `CURSOR_API_KEY`/`CURSOR_AUTH_TOKEN`, Copilot `COPILOT_GITHUB_TOKEN`, Pi diff --git a/doc/evals.md b/doc/evals.md index 34eceed497d..463286469dd 100644 --- a/doc/evals.md +++ b/doc/evals.md @@ -39,6 +39,15 @@ browser, semantic interaction, file/artifact, Stop and continuation oracles with scoped candidate admission and an encrypted Code credential. Registration does not establish a live pass, native question/plan support or usable cost accounting. +The explicit-only [Google Antigravity qualification suite](../tests/runner-e2e/SUITES.md#google-antigravity-qualification) +registers 24 Gemini API-key cells across local and Daytona, including the shared +pending-permission Stop and provider-loss oracles. Separate +[model-lineup suites](../tests/runner-e2e/SUITES.md#google-antigravity-model-lineups) +check one exact-model receipt per model ID. Chat and instruction evals can run +under Antigravity with `--profile runner-acpx-antigravity`. Registration is not a +live pass; pending cells need a company-bound candidate grant that the harness +stages itself. + The public directory calls full-product testing **E2E tests**. Suites describe what is tested; deployment targets describe which app instance was tested. QA smoke is a named selection of existing journeys against QA, and appears in diff --git a/doc/plans/2026-10-28-antigravity-integration.md b/doc/plans/2026-10-28-antigravity-integration.md index 98d9dd440d2..5a504b3e6fc 100644 --- a/doc/plans/2026-10-28-antigravity-integration.md +++ b/doc/plans/2026-10-28-antigravity-integration.md @@ -472,3 +472,10 @@ restoration. The test drive continues to serve from its separate frozen mirror with the original isolated database and saved account, and reports ready/healthy. The final `.5` oracle and both browser journeys establish the requested local setup, task and follow-up outcome; broader release qualification remains pending. + +## 2026-11-22: superseded as the current ledger + +The current release contract and acceptance ledger for Google Antigravity is +[2026-11-22-antigravity-qualification.md](2026-11-22-antigravity-qualification.md) +(runtime 1.5.2, patch `1.5.2-paperclip.2`, macOS and Linux x64). This document +is kept unchanged above as the history of the 1.4.3 macOS candidate. diff --git a/doc/plans/2026-11-22-antigravity-qualification.md b/doc/plans/2026-11-22-antigravity-qualification.md new file mode 100644 index 00000000000..120b1b64469 --- /dev/null +++ b/doc/plans/2026-11-22-antigravity-qualification.md @@ -0,0 +1,178 @@ +# Google Antigravity: from pending candidate to qualified harness — 2026-11-22 + +Continues [the October integration plan](2026-10-28-antigravity-integration.md). +That document remains the historical ledger for the macOS candidate. This one +is the current release contract and acceptance ledger. + +## Release contract + +| Decision | Answer | +| --- | --- | +| User outcome | An operator picks Google Antigravity, binds a Google credential, picks a model (including Gemini 4 Neon at any offered thinking level) and assigns ordinary work, locally or in a cloud sandbox. | +| Native route | Google's official Antigravity ACP server through the existing ACPX driver. | +| Runtime pin | ACP server **1.5.2** (registry commit `e29b5bf3bf`, 2026-11-21), two-executable closure, owned admission patch re-ported. | +| Platforms | Target: linux-x64 (Daytona) and darwin-arm64 (local), both verified and started natively, neither yet live-qualified (see ledger). linux-arm64: static verification only, never started. darwin-x64: inventory-only (no native host). | +| Authentication | `gemini-api-key` (local and remote) and personal Google sign-in (local). Agent Platform (Vertex/ADC) and remote OAuth: see open decisions. | +| Models | Caller-selected, read from the account or server catalog. No product allowlist. Thinking level is part of the model ID (`-`, levels `minimal/low/medium/high/extra_high`). | +| Release target | One reviewable PR with green checks; merge and production flip are separate decisions. | +| Deployment policy | Unchanged: `PAPERCLIP_AVAILABLE_HARNESSES` stays the deployment's choice. | + +## Verified upstream facts (2026-11-22) + +- Registry is at 1.5.2; all four archive checksums match the registry. +- Linux `.par` is an ELF launcher with a Python 3.14 zip appended. macOS `.par` + is a signed Mach-O. The helper `localharness_external` is unchanged in role. +- In 1.5.2 a bare `GEMINI_API_KEY` no longer selects an auth method; `auth.type` + in settings or an `authenticate` call is required. +- **All four `gemini-4-*` families are marked `agent_platform_only` in the + server's built-in catalog.** In `gemini-api-key` mode the server lists only + the Flash families and 3.1 Pro. Google's "Neon with API keys" note (Nov 20) is + for the Antigravity App, not this ACP release. +- The Gemini Developer API lists `gemini-4-neon` for our test key, but the key is + free tier with a Neon quota of 0. +- Patch `1.5.2-paperclip.2` adds exact-model admission, so a requested API-key + model ID (Gemini 4 and Neon included) is admitted with an exact receipt despite + the built-in `agent_platform_only` marking. Inference is a separate question. +- The ACP layer exposes no Orchestrator mode. + +## Routes to Neon + +State as of the end of 2026-11-22. "Admitted" means the patched server returned +an exact-model receipt for the requested ID without sending a prompt; it is not +evidence that Google serves inference for that model on that credential. + +| Route | State | Needs | +| --- | --- | --- | +| API key (exact-model admission in patch `1.5.2-paperclip.2`) | All four Neon levels admitted prompt-free with exact receipts on macOS and Linux x64; no `AGY_ACP_DEFAULT_MODEL` needed. No Neon prompt has completed: the only key is free tier (Neon quota 0) | A paid Gemini key, then one accepted prompt per level | +| Personal Google sign-in (subscription catalog) | Local macOS sign-in journey proven on 1.4.3 (October); not re-run on 1.5.2; never offered in a cloud sandbox | An entitled account and the attended sign-in journey on 1.5.2 | +| Agent Platform (Vertex/ADC) | Advertised by the server, never exercised here | A Google Cloud project and service credentials | + +## Workstreams + +1. **Runtime 1.5.2 and cross-platform closure.** Bump the pin; port the patch to + 1.5.2 on Mach-O and ELF; per-platform helper identity; four-platform + distribution declaration; version checks; regenerate profiles; widen the + platform gates in the runner, Rust and the sidecar schema. Proof: clean + provisioning plus native initialize, API-key authenticate and one Flash prompt + on darwin-arm64 and linux-x64. +2. **Test catalog and CI.** Antigravity API-key profile, a qualification suite on + the Kimi pattern (local and Daytona), stop/lifecycle/provider-death cases, CI + matrix wiring for `GEMINI_API_KEY`, unit coverage of the catalog. +3. **API-key connection and models.** Model discovery for API-key connections, + Neon and thinking-level projection, model audit, Neon route chosen above. +4. **Remote execution.** Provider pack and Daytona image carry the Linux + closure; lift the executor's remote/warm gates for the API-key route; remote + credential home. +5. **Lifecycle gates.** Loaded-session admission, Stop, questions and + permissions, durable recovery (today it throws), provider-death expiry. +6. **Qualification flip and review.** Flip the four pending declarations on the + Kimi template, update UI/CLI/docs/maps, run the acceptance matrix and the + existing evals under the native Runner, record results here. + +Order: 1 and 2 in parallel; then 3, 4 and 5; then 6. + +## Acceptance ledger + +Profile state: **pending**. The qualification flip has not happened and must +not happen until every row marked NOT RUN below has passed live. + +**No prompt has completed on 1.5.2 on any platform.** The only Gemini key +available is free tier; Google answered every prompt attempt on two days with +503 (overloaded) or 429 (`RESOURCE_EXHAUSTED`). Everything below that needs a +model to answer is therefore NOT RUN, not failed and not passed. + +| Gate | Required observation | Verdict (2026-11-22) | +| --- | --- | --- | +| Runtime pin | ACP server 1.5.2 with owned patch `1.5.2-paperclip.2`, closures re-pinned | Done | +| Distribution | Clean setup verifies vendor and patched closures on each claimed platform; tamper rejected | darwin-arm64: verified and started natively. linux-x64: provisioned and started natively in Daytona. linux-arm64: static verification only, never started. darwin-x64: not supported | +| Remote provider pack | Pack carries the Linux closure; server's remote path verifies it | Passed for linux-x64 through the server's remote path in Daytona. Re-verification on a reused sandbox lease 4.3 s → ~0.25 s | +| API-key auth | Native `gemini-api-key` session reaches an exact-model receipt | Passed live on macOS and Linux x64 (receipt only; no prompt) | +| Model admission | Every model ID admitted by exact-model admission, prompt-free | Passed: all 28 IDs (14 Gemini 3, 14 Gemini 4 including Neon at four levels) get exact receipts under an API key on both platforms, without `AGY_ACP_DEFAULT_MODEL` | +| Kill and resume | Native process killed between turns; a new process resumes the session | Passed prompt-free on macOS and Linux x64 with exact receipts. Not yet shown with a completed prompt, and no live `session/load` was observed | +| Launch cost | Run start to native initialize | Sealed verified store: 1.46 s (macOS) / 1.74 s (Linux x64), from 3.45 / 3.65 s. Measured before the launcher regained its streamed executable hash (below); that hash measured ~60 ms for the 179 MB macOS server and is not yet re-measured for the ~722 MB Linux launcher | +| Model lineup inference | Per model/level: one accepted prompt | NOT RUN (no prompt completes on the free key) | +| Neon inference | Real task on `gemini-4-neon-*`, each level acknowledged | NOT RUN (free-tier Neon quota is 0) | +| Ordinary task | File bytes, artifact, accepted result, Done after reload, local and Daytona | NOT RUN on 1.5.2 (local macOS passed on 1.4.3 in October) | +| Scoped tools | Semantic and MCP round trip; wrong-company and stale authority denied | NOT RUN | +| Questions and permissions | Native identity, one continuation, denial holds | NOT RUN | +| Stop and lifecycle | Stop during a tool call, pending-input Stop, provider death mid-turn, no late revival | NOT RUN | +| Continuity and recovery | Loaded session keeps model and instructions; interrupted run resumes or Retry works | Partial: prompt-free resume only (see Kill and resume) | +| Qualification suite | All 24 `antigravity-qualification` cells, local and Daytona | NOT RUN | +| Evals under the native Runner | Applicable Product E2E and chat cases run with Antigravity; numbers recorded | NOT RUN | +| Image pull and startup time | Daytona image with the Linux closure, measured cold | NOT RUN | + +### Must pass live before the qualification flip + +1. All 24 `antigravity-qualification` cells, local (darwin-arm64) and Daytona + (linux-x64). +2. The 14-cell API-key lineup, each with an accepted prompt. +3. The Gemini 4 lineup, including Neon at every level, on a paid key. +4. A live `session/load` observed before the profile claims + `recovery: "session-load"`. +5. The attended Google sign-in journey on 1.5.2 (local only). +6. Daytona image pull and startup time, measured. + +### Excluded or unsupported for this release + +- Orchestrator mode: excluded. 1.5.2 does not expose it over ACP. +- Google sign-in in a cloud sandbox: refused at save and Test. +- Warm (session-reusing) runs: per-turn only. +- darwin-x64: no native host; inventory only. +- linux-arm64: verified statically; not started, so not claimed. + +### Operator recipe (local, API key) + +1. Install the runtime: `paperclipai runtime setup antigravity`. It downloads + the pinned 1.5.2 archive, checks it against the registry checksum and + installs the patched closure for this host (darwin-arm64 or linux-x64). +2. In Paperclip, add an AI connection for Google Antigravity and choose the + Google API key method, paste a Gemini API key and use Test. +3. On the agent, pick Google Antigravity and choose a model family and thinking + level. A free-tier key can be admitted but may be refused at prompt time; + Neon needs a paid key. +4. Not supported: Google sign-in in a cloud sandbox, warm sessions, + Orchestrator mode, darwin-x64. + +While the profile is pending, a cloud (Daytona) run needs an operator grant +for the company and exact model that names linux-x64 and the patched linux-x64 +closure, with an API-key connection, per-turn. The runner E2E harness stages +that grant for Daytona cells; a local cell's grant names the host instead. + +### Launch integrity follow-up (2026-11-22) + +The sealed verified store removed the per-launch closure copy, but its first +version trusted the store's recorded kernel identity for the executable. A +process running as the runner's user can rewrite both a stored file and that +record, so the launcher would have spawned a replaced executable. The launcher +again hashes the exact executable descriptor it spawns against the pinned digest +(streamed in 4 MiB chunks, so memory stays bounded), and the module guard still +hashes every Node module at load. The store also now holds the closure's module +guard beside its entrypoints, which Pi's pinned `pi-entry.cjs` hands to its +child; without it Pi launches from the store failed. The Kimi, Pi and Copilot +provider-death fixtures now target the store and per-launch directory layout. + +### Integration round (2026-11-22, no live cells yet) + +- Typed turn failures reach the user: a refused model is named with its fix + (`antigravityModelRefusalMessage`), a 503 overload takes the bounded capacity + retry, rate limits and quotas take the provider-limit wait, a rejected key is + shown as the provider's plain message. +- Save and Test refuse Google sign-in in a cloud environment (route test). +- A refused saved-conversation reload is `provider_state_incompatible` on every + reopen path; Antigravity never takes the Claude-only turn-end restart. +- Superseded sealed closure stores are retired once no live runner holds them. +- A verified provider pack is re-checked by kernel identity on the same sandbox + (958 MB / 18,002 files: 4.3 s full re-hash, ~0.25 s on a reused lease in + Daytona). +- CI builds the Daytona image and controller pack with the selected pending + candidates; the qualification suite gained `permission-deny-stop` (24 cells). +- Live: the Gemini key still returns 429 `RESOURCE_EXHAUSTED` for + `gemini-3.8-flash`, so no live cell ran. + +## Open decisions + +- A paid Gemini key for the prompt-dependent gates (the API-key route to Neon + is admitted; inference is unproven). +- Orchestrator mode: excluded for this release (not exposed over ACP in 1.5.2). +- Merge and production flip after the PR is green. +- Disposition of community PR #21121 (separate legacy-style adapter). diff --git a/doc/runner-internals.md b/doc/runner-internals.md index 2093cfdc7ae..4097fcde5e2 100644 --- a/doc/runner-internals.md +++ b/doc/runner-internals.md @@ -84,17 +84,25 @@ CLI paths that use stdin avoid that separate limit for the wake prompt. ## Adding a native Runner harness -Google Antigravity's pending integration uses the official ACP server 1.4.3 with -a pinned native admission patch. `paperclipai runtime setup antigravity` installs -its verified assets on macOS ARM64 as the OS user running Paperclip. Setup does -not enable global execution: qualification remains pending and admission is -closed by default. An isolated company can use a finite trusted server-startup -candidate authorization bound to the exact model, local platform, profile and -native closure. The candidate's recorded setup and two-turn task reused the same -owner's managed personal-default Google subscription on macOS ARM64 with -`gemini-3.8-flash-low`; fresh consent and API-key live acceptance remain separate -gates. Workspace OAuth is not runtime authentication. See the -[contract, evidence, and remaining gates](plans/2026-10-28-antigravity-integration.md). +Google Antigravity's pending integration uses the official ACP server 1.5.2 with +a pinned native admission patch. The patcher rewrites the Python archive in the +`.par_data` section of the macOS (Mach-O, re-signed ad hoc) and Linux (ELF) +servers, and writes the helper digest from the verified closure declaration into +a generated module, so one admission source serves every platform. +`paperclipai runtime setup antigravity` installs its verified assets +(`1.5.2-paperclip.2`) on macOS ARM64, Linux x64 and Linux ARM64 as the OS user +running Paperclip; macOS Intel is inventory-only. Launches execute a sealed, +runner-owned copy of the closure verified once per closure; a provider's +superseded closure stores are retired once no live runner holds them. The +patch also types a failed managed turn (overload, rate limit with retry time, +quota, rejected key, refused model) so the server can retry or explain it. +Authentication is a Gemini API key (`gemini-api-key`) or personal Google +sign-in (Paperclip host only). Setup does not enable global execution: +qualification remains pending and admission is closed by default. An isolated +company can use a finite trusted server-startup candidate authorization bound +to the exact model, local platform, profile and native closure. Live acceptance +on 1.5.2 remains open. Workspace OAuth is not runtime authentication. See the +[current plan and ledger](plans/2026-11-22-antigravity-qualification.md). To add a harness/provider to the new native Paperclip Runner, use [create-runner-adapter](../.agents/skills/create-runner-adapter/SKILL.md), the diff --git a/docker/daytona-runner/Dockerfile b/docker/daytona-runner/Dockerfile index 0b9a1885eac..90a156f72b6 100644 --- a/docker/daytona-runner/Dockerfile +++ b/docker/daytona-runner/Dockerfile @@ -45,6 +45,11 @@ COPY cli/package.json ./cli/package.json ARG PAPERCLIP_RUNNER_LOCK_SHA256 ARG PAPERCLIP_RUNNER_SOURCE_REVISION # Optional qualification assets; this never promotes candidate profiles. +# `antigravity` downloads its pinned ~274 MB archive into memory, patches it +# (about 2.4 GB peak, outside the JS heap bound below) and keeps only the +# ~850 MB patched closure in /provider-pack; the archive never touches disk. +# Its patcher refuses group- or world-writable inputs, so the RUN below drops +# shared write bits a umask-002 build context would otherwise carry in. ARG PAPERCLIP_RUNNER_CANDIDATE_PROVIDERS= # pnpm 9 subtracts PNPM_WORKERS from available CPUs; it is not a worker count. # Subtract all available CPUs to select its minimum (one tarball worker). @@ -58,6 +63,7 @@ RUN if ! printf '%s' "${PAPERCLIP_RUNNER_LOCK_SHA256}" | grep -Eqx '[0-9a-f]{64} && export PNPM_WORKERS="$(node -p 'require("node:os").availableParallelism()')" \ && printf '%s pnpm-lock.yaml\n' "${PAPERCLIP_RUNNER_LOCK_SHA256}" > /tmp/provider-lock.sha256 \ && sha256sum -c /tmp/provider-lock.sha256 \ + && chmod -R go-w /workspace \ && pnpm install --frozen-lockfile --filter '@paperclipai/paperclip-runner...' \ && pnpm --filter @paperclipai/paperclip-runner build:typescript \ && PAPERCLIP_RUNNER_SOURCE_REVISION="${PAPERCLIP_RUNNER_SOURCE_REVISION}" \ diff --git a/docker/daytona-runner/README.md b/docker/daytona-runner/README.md index 5ec6edfa95d..eb6a5162d07 100644 --- a/docker/daytona-runner/README.md +++ b/docker/daytona-runner/README.md @@ -179,6 +179,17 @@ Compute its content ID with the same selection: `pnpm --silent test:e2e:runner:image-id --candidate-providers=cursor`. Candidate assets and the default pack have distinct image identities. Never reuse the default image's content ID for a candidate build. + +Google Antigravity (`antigravity`) is built only for Linux x64. The builder +downloads the pinned ~274 MB archive into memory, patches it and keeps only the +~850 MB patched closure under `provider-assets/antigravity/linux-x64`; it then +starts the closure once, without credentials, to confirm the runtime version and +native admission patch. While the profile is pending the pack lists it under +`candidateProviders`; once the profile is released it moves to `providers` and +is included without the flag. The controller pack +(`PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH`) must be built with the same +candidate selection and source revision as the image, or the image pack is not +reused. Use each provider branch's recorded version and explicit model. Keep credentials out of images. Paid qualification requires bound provider and Daytona credentials, inspectable spend, and the shared $100 ceiling recorded in the capability report. diff --git a/packages/adapters/opencode-local/src/index.ts b/packages/adapters/opencode-local/src/index.ts index e203416e962..4c8c7415984 100644 --- a/packages/adapters/opencode-local/src/index.ts +++ b/packages/adapters/opencode-local/src/index.ts @@ -69,6 +69,7 @@ export const models: Array<{ id: string; label: string }> = [ { id: "anthropic/claude-sonnet-5-5", label: "anthropic/claude-sonnet-5-5" }, { id: "anthropic/claude-sonnet-5", label: "anthropic/claude-sonnet-5" }, { id: "anthropic/claude-haiku-5-5", label: "anthropic/claude-haiku-5-5" }, + { id: "google/gemini-4-neon", label: "google/gemini-4-neon" }, { id: "google/gemini-4-carbon", label: "google/gemini-4-carbon" }, { id: "google/gemini-4-argon", label: "google/gemini-4-argon" }, { id: "google/gemini-4-hydrogen", label: "google/gemini-4-hydrogen" }, diff --git a/packages/paperclip-runner/README.md b/packages/paperclip-runner/README.md index 98e1faedfa1..0343772db24 100644 --- a/packages/paperclip-runner/README.md +++ b/packages/paperclip-runner/README.md @@ -307,20 +307,31 @@ blocks new imports rather than resetting the budget. See the [local qualification record](../../doc/plans/2026-10-28-cursor-cloud-native-runner.md) for runnable acceptance cells and the remaining live qualification gates. -Google Antigravity is an **unqualified, pending** native ACPX integration. The -explicit `paperclipai runtime setup antigravity` command installs the verified -Antigravity ACP 1.4.3 distribution and its owned admission patch on macOS ARM64. -It verifies both the official vendor closure and the separately pinned patched -closure; npm installation downloads no Antigravity runtime. This setup installs -assets only. Global release qualification remains pending and normal execution -admission stays closed. An isolated operator can admit one company, exact model, -local platform and pinned native closure/profile until a fixed expiry through -trusted server startup authority. The candidate supports a managed saved Google -subscription; the recorded acceptance reused the same owner's personal default -grant and `gemini-3.8-flash-low` on macOS ARM64. This does not qualify fresh Google -consent or the separate API-key route. Google Workspace OAuth does not substitute -for a runtime credential. See the -[integration contract and evidence](../../doc/plans/2026-10-28-antigravity-integration.md). +Google Antigravity is an **unqualified, pending** native ACPX integration on +Google's official ACP server 1.5.2 with Paperclip's owned admission patch +(`1.5.2-paperclip.2`). The explicit `paperclipai runtime setup antigravity` +command installs it on macOS ARM64, Linux x64 and Linux ARM64; macOS Intel stays +inventory-only (no native host). Setup verifies both the official vendor closure +and the separately pinned patched closure; npm installation downloads no +Antigravity runtime. The Daytona image and remote provider pack carry the Linux +x64 closure only when built with `--candidate-providers=antigravity`; while the +profile is pending it is listed under `candidateProviders`. + +Two connection routes exist: a Gemini API key (`gemini-api-key`, locally and in +a cloud environment once released) and personal Google sign-in (Paperclip host +only, one turn at a time). Agent save and Test refuse any other combination in +plain language. Models are the server's own catalog. The 1.5.2 catalog lists +Gemini 4 families only for Agent Platform, but patch `1.5.2-paperclip.2` admits +an exact requested model ID under an API key, so Gemini 4 (Neon included) runs +on the API-key route with a paid key; a refused model is named with its fix. Global release qualification remains pending and normal execution +admission stays closed: an isolated operator can admit one company, exact +model, execution platform (this host, or linux-x64 for a cloud environment with +an API key) and pinned patched closure/profile, per-turn only, until a fixed +expiry through trusted server startup authority. Live acceptance on 1.5.2 (API key, Linux, +Daytona, the model lineups) has not passed yet. Google Workspace OAuth does not +substitute for a runtime credential. See the +[current qualification plan](../../doc/plans/2026-11-22-antigravity-qualification.md) +and the [October integration record](../../doc/plans/2026-10-28-antigravity-integration.md). A release includes all four platform daemons and the Linux provider-pack identity from its matching Daytona image. Run `stage:release-binaries` with a manifest that diff --git a/packages/paperclip-runner/acpx-profiles.json b/packages/paperclip-runner/acpx-profiles.json index 4b5cb4cea11..72a4f5874e6 100644 --- a/packages/paperclip-runner/acpx-profiles.json +++ b/packages/paperclip-runner/acpx-profiles.json @@ -7,10 +7,10 @@ "antigravity": { "agentProfileVersion": 1, "agentServerPackage": "native:antigravity-acp", - "agentServerVersion": "1.4.3", + "agentServerVersion": "1.5.2", "agentRuntimePackage": "native:antigravity-localharness", - "agentRuntimeVersion": "1.4.3", - "commandDigest": "sha256:acf5f574b6b9ec4388ff9d081890caa330e66bf1ae3fe3b08e7f0fb0e851b9ce", + "agentRuntimeVersion": "1.5.2", + "commandDigest": "sha256:61ac14bf03ce4bbf8afe1f5a263b854517ec588d8407fe2d8f17c9fc0c037c4b", "requiresProviderPolicy": true, "qualificationStatus": "pending" }, diff --git a/packages/paperclip-runner/antigravity-distributions.json b/packages/paperclip-runner/antigravity-distributions.json index c6836e59b98..822c5715775 100644 --- a/packages/paperclip-runner/antigravity-distributions.json +++ b/packages/paperclip-runner/antigravity-distributions.json @@ -1,70 +1,134 @@ { "schema": "paperclip.antigravity_distribution.v1", - "version": "1.4.3", + "version": "1.5.2", "platforms": { "darwin-arm64": { - "url": "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.4.3-darwin-arm64.zip", - "archiveSha256": "c57db0a9b8b712daa9c3c17cdb990a61842ea569f279e8bd79d7aa85a303b20b", - "closureSha256": "044792d793e203bc8b4524a418f1816c4d34db67bb41fa4bae5947a050c49b4a", + "url": "https://dl.google.com/agy-extensions/releases/macos/agy-acp-server-1.5.2-darwin-arm64.zip", + "archiveSha256": "123a16d5c40a8ac99e20f01a62b68dd860fd96b1c528dfb8eaa37ca8733d4845", + "closureSha256": "ab9df40a64806a8e1812234ce5331e04d1c6b5f8c7e5bdbb456cd645e58c5aad", "provisioning": "verified-closure", "executable": "agy_acp_server.par", "args": [], "entries": [ { "path": "agy_acp_server.par", - "sha256": "c5231c13eeb6a9fd554567e5ce6411d95fe8c2fe952302bbd52d7b81a4e63f15", - "size": 280804016, + "sha256": "c716c4a665f3cdc1f2be40f3545be9e95b7433cd07cc536485a14a85d6570a59", + "size": 178875248, "executable": true }, { "path": "localharness_external", - "sha256": "9e8fdc6e20a3262ca0a771850ca4a8414ca839a642cc964ec5c547cc2c33c200", - "size": 122957936, + "sha256": "31ec5f444b8c849ddb14da1c0893a87dddab60f1d5e282b79db36dc41b2521ab", + "size": 129208672, "executable": true } ], "vendorEntries": [ { "path": "agy_acp_server.par", - "sha256": "1251927db3e21f3d693fd042d6890d82f65eb00587e97f1f3d8f0d798e7f0954", - "size": 282446160, + "sha256": "4cea3c96875a4bb66a1c136d972b5cfdc5f7c91579ff7b9cbfc158a4358270bc", + "size": 179921328, "executable": true }, { "path": "localharness_external", - "sha256": "9e8fdc6e20a3262ca0a771850ca4a8414ca839a642cc964ec5c547cc2c33c200", - "size": 122957936, + "sha256": "31ec5f444b8c849ddb14da1c0893a87dddab60f1d5e282b79db36dc41b2521ab", + "size": 129208672, "executable": true } ], - "vendorClosureSha256": "023881d9f3b460adb22634c625725657358679e08c085156cc6de35e5f87b3c2", - "patchVersion": "1.4.3-paperclip.5", - "admissionSourceSha256": "d660759a424ddc27ac382ce4512e85ca4eb87e5ca446ea111e093d3ab257f7da" + "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.4.3-darwin-x86_64.zip", - "archiveSha256": "9392dbbdad7f0663dbfb5a0bf641297b0cf80d2ee9cd2d49a616bbbc7378731d", + "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": [] }, "linux-x64": { - "url": "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.4.3-linux-x86_64.zip", - "archiveSha256": "0634ce5306ba92c932945455e7a83fda78e2d99c33fa8aa6ee0566206a382714", - "provisioning": "inventory-only", + "url": "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.5.2-linux-x86_64.zip", + "archiveSha256": "99dd8612450805011619d7b8447ce374c289e00549d8557f36790e1dd6256852", + "closureSha256": "be35d65a32667550b5474588d705e6987a813e2fa619cf5db7d82d141c3c05fb", + "provisioning": "verified-closure", "executable": "agy_acp_server.par", "args": [ "--uid=" - ] + ], + "entries": [ + { + "path": "agy_acp_server.par", + "sha256": "69dc28c074628da7fdb3f26160850b7e7567458abdab0c81ca0e3c3ad5bac1dd", + "size": 714384320, + "executable": true + }, + { + "path": "localharness_external", + "sha256": "072fc497e7814b0e25a7d80109bceddacd815eb351d2e48ce579a05510e0cfdf", + "size": 139194456, + "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.4.3-linux-arm64.zip", - "archiveSha256": "05c153443b0b1175151c760eeddea538950bc9843e317d54786a1f03670182bc", - "provisioning": "inventory-only", + "url": "https://dl.google.com/agy-extensions/releases/linux/agy-acp-server-1.5.2-linux-arm64.zip", + "archiveSha256": "e729e05ef54ef0763e48900032466b47fa7c9939cde257f93ba49410ab577acb", + "closureSha256": "46c36293779283c1f933eb438a143d116421a331f614601c754f1b94d9dc171a", + "provisioning": "verified-closure", "executable": "agy_acp_server.par", "args": [ "--uid=" - ] + ], + "entries": [ + { + "path": "agy_acp_server.par", + "sha256": "93b1280744a8ce256574a1be1e02898530c7ea9aab48cbbbb429130be3030d8b", + "size": 721649155, + "executable": true + }, + { + "path": "localharness_external", + "sha256": "06b2fcf3c20d76cec15fc9db952731a2058356311e0760cb818feeabca6d6f91", + "size": 132598576, + "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/package.json b/packages/paperclip-runner/package.json index e37760e0a23..2ef2f23aa1e 100644 --- a/packages/paperclip-runner/package.json +++ b/packages/paperclip-runner/package.json @@ -68,7 +68,7 @@ "sideEffects": false, "scripts": { "build": "node scripts/record-build-inputs.mjs --begin && pnpm run check:protocol-manifest && pnpm run build:typescript && pnpm run check:capability-contract && pnpm run check:capability-inventory && pnpm run check:protocol-coverage && node scripts/generate-semantic-contracts.mjs --check && node scripts/check-runner-workflow-traceability.mjs && node scripts/build-runner-binary.mjs && node scripts/generate-replay-goldens.mjs --check && node scripts/generate-semantic-action-catalog.mjs --check && node scripts/record-build-inputs.mjs --finish", - "build:typescript": "pnpm run check:acpx-profiles && pnpm run ensure:eval-build-deps && pnpm run check:protocol-types && node ./node_modules/typescript/bin/tsc --version && node ./node_modules/typescript/bin/tsc -p tsconfig.json && node ./node_modules/typescript/bin/tsc -p tsconfig.surfaces.json && node scripts/build-verified-provider-entrypoints.mjs && node scripts/install-copilot-assets.mjs", + "build:typescript": "pnpm run check:acpx-profiles && node scripts/generate-antigravity-models.mjs --check && pnpm run ensure:eval-build-deps && pnpm run check:protocol-types && node ./node_modules/typescript/bin/tsc --version && node ./node_modules/typescript/bin/tsc -p tsconfig.json && node ./node_modules/typescript/bin/tsc -p tsconfig.surfaces.json && node scripts/build-verified-provider-entrypoints.mjs && node scripts/install-copilot-assets.mjs", "build:rust": "cargo build --manifest-path runner/Cargo.toml --locked --workspace --bins", "build:binary": "cargo build --release --manifest-path runner/Cargo.toml --locked -p paperclip-runner-core --bin paperclip-runnerd && node scripts/stage-runner-binary.mjs", "stage:release-binaries": "node scripts/stage-release-runner-binaries.mjs", @@ -85,7 +85,7 @@ "typecheck:browser": "tsc -p tsconfig.browser.json --noEmit", "test": "pnpm run test:typescript && pnpm run test:rust", "test:typescript": "pnpm run test:typescript:prep && vitest run", - "test:typescript:prep": "pnpm run ensure:eval-build-deps && pnpm run build:rust && node ../../scripts/ci-profile/node-test.mjs test/protocol-contract.test.mjs test/acpx-sidecar-contract.test.mjs test/acpx-codex-package-contract.test.mjs test/acpx-model-selection-package-contract.test.mjs test/acpx-session-carry-forward-package-contract.test.mjs test/acpx-message-boundaries-package-contract.test.mjs test/acpx-rich-extensions-package-contract.test.mjs scripts/candidate-provider-pack.test.mjs scripts/materialize-pi-distribution.test.mjs scripts/cursor-provisioner-layout.test.mjs scripts/release-provider-pack.test.mjs scripts/acpx-release-attestations.test.mjs scripts/provider-pack-runtime-tree.test.mjs scripts/aws-agentcore-provisioning.test.mjs scripts/build-verified-provider-entrypoints.test.mjs scripts/local-provider-smoke-environment.test.mjs scripts/materialize-opencode-binary.test.mjs scripts/materialize-kimi-distribution.test.mjs scripts/provision-kimi-package.test.mjs scripts/kimi-metadata-probe.test.mjs scripts/patch-kimi-runtime.test.mjs test/kimi-installed-runtime.test.mjs scripts/installed-package-pack.test.mjs scripts/runner-runtime-dependency-roots.test.mjs scripts/runner-package-executable.test.mjs scripts/stage-runner-provider-node.test.mjs scripts/stage-runner-binary.test.mjs scripts/build-inputs.test.mjs scripts/contracts/contract-fingerprints.test.mjs scripts/provider-pack-executable-shims.test.mjs scripts/controlled-evals/controller.test.mjs scripts/controlled-evals/portable.test.mjs scripts/runner-protocol-testops.test.mjs scripts/runner-protocol-eval-workflow-security.test.mjs && node --test scripts/build-copilot-distribution.test.mjs scripts/copilot-inner-distribution.test.mjs scripts/copilot-smoke-resources.test.mjs scripts/discover-copilot-acp.test.mjs scripts/materialize-copilot-binary.test.mjs scripts/install-copilot-assets.test.mjs scripts/probe-copilot-acp.test.mjs scripts/qualify-copilot-acp.test.mjs test/acpx-message-boundaries-package-contract.test.mjs", + "test:typescript:prep": "pnpm run ensure:eval-build-deps && pnpm run build:rust && node ../../scripts/ci-profile/node-test.mjs test/protocol-contract.test.mjs test/acpx-sidecar-contract.test.mjs test/acpx-codex-package-contract.test.mjs test/acpx-model-selection-package-contract.test.mjs test/acpx-session-carry-forward-package-contract.test.mjs test/acpx-message-boundaries-package-contract.test.mjs test/acpx-rich-extensions-package-contract.test.mjs scripts/candidate-provider-pack.test.mjs scripts/materialize-pi-distribution.test.mjs scripts/cursor-provisioner-layout.test.mjs scripts/release-provider-pack.test.mjs scripts/antigravity-provider-pack-smoke.test.mjs scripts/acpx-release-attestations.test.mjs scripts/provider-pack-runtime-tree.test.mjs scripts/aws-agentcore-provisioning.test.mjs scripts/build-verified-provider-entrypoints.test.mjs scripts/local-provider-smoke-environment.test.mjs scripts/materialize-opencode-binary.test.mjs scripts/materialize-kimi-distribution.test.mjs scripts/provision-kimi-package.test.mjs scripts/kimi-metadata-probe.test.mjs scripts/patch-kimi-runtime.test.mjs test/kimi-installed-runtime.test.mjs scripts/installed-package-pack.test.mjs scripts/runner-runtime-dependency-roots.test.mjs scripts/runner-package-executable.test.mjs scripts/stage-runner-provider-node.test.mjs scripts/stage-runner-binary.test.mjs scripts/build-inputs.test.mjs scripts/contracts/contract-fingerprints.test.mjs scripts/provider-pack-executable-shims.test.mjs scripts/controlled-evals/controller.test.mjs scripts/controlled-evals/portable.test.mjs scripts/runner-protocol-testops.test.mjs scripts/runner-protocol-eval-workflow-security.test.mjs && node --test scripts/build-copilot-distribution.test.mjs scripts/copilot-inner-distribution.test.mjs scripts/copilot-smoke-resources.test.mjs scripts/discover-copilot-acp.test.mjs scripts/materialize-copilot-binary.test.mjs scripts/install-copilot-assets.test.mjs scripts/probe-copilot-acp.test.mjs scripts/qualify-copilot-acp.test.mjs test/acpx-message-boundaries-package-contract.test.mjs", "test:typescript:vitest": "node ./scripts/run-pr-vitest-lane.mjs", "test:rust": "cargo test --release --manifest-path runner/Cargo.toml --locked --workspace", "test:codex": "cargo test --manifest-path runner/Cargo.toml --locked -p paperclip-runner-core --test codex_provider", diff --git a/packages/paperclip-runner/protocol/provider-schemas/acpx-sidecar.schema.json b/packages/paperclip-runner/protocol/provider-schemas/acpx-sidecar.schema.json index 2a95019100a..c129bbe11e2 100644 --- a/packages/paperclip-runner/protocol/provider-schemas/acpx-sidecar.schema.json +++ b/packages/paperclip-runner/protocol/provider-schemas/acpx-sidecar.schema.json @@ -95,7 +95,7 @@ ] }, "candidateAdmission": { - "description": "The same closed record is accepted only from trusted runner startup CLI and repeated on sidecar initialize/open. Company authority is validated by the server; the runtime additionally checks compiled pins, actual run/session identity, native host, and expiry.", + "description": "The same closed record is accepted only from trusted runner startup CLI and repeated on sidecar initialize/open. Company authority is validated by the server; the runtime additionally checks compiled pins (which admit only platforms with a verified closure), actual run/session identity, native host, and expiry.", "type": "object", "required": ["schema", "companyId", "agent", "model", "profileDigest", "nativeClosureDigest", "platform", "architecture", "expiresAt", "runId", "normalizedSessionId"], "properties": { @@ -105,8 +105,8 @@ "model": { "type": "string", "minLength": 1, "maxLength": 512, "pattern": "^[^\\u0000-\\u001f\\u007f]+$" }, "profileDigest": { "type": "string", "pattern": "^sha256:[a-f0-9]{64}$" }, "nativeClosureDigest": { "type": "string", "pattern": "^sha256:[a-f0-9]{64}$" }, - "platform": { "const": "darwin" }, - "architecture": { "const": "arm64" }, + "platform": { "enum": ["darwin", "linux"] }, + "architecture": { "enum": ["arm64", "x64"] }, "expiresAt": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 }, "runId": { "type": "string", "minLength": 1, "maxLength": 160, "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" }, "normalizedSessionId": { "type": "string", "minLength": 1, "maxLength": 160, "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$" } 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 fa036c4e4ae..56fbe151ae5 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 @@ -1,16 +1,74 @@ use std::time::{SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; -use serde_json::Value; -use crate::generated_acpx_profiles::{acpx_release_profile, kimi_native_closure}; +use crate::generated_acpx_profiles::{ + acpx_release_profile, antigravity_native_closure, kimi_native_closure, AcpxReleaseProfile, +}; use crate::local_runner::LocalRunnerError; use crate::stable_identity::{is_stable_id, DURABLE_STABLE_ID_CHARS, SHORT_STABLE_ID_CHARS}; const SCHEMA: &str = "paperclip.acpx-candidate-admission.v1"; const MAX_LIFETIME_MS: u64 = 24 * 60 * 60 * 1_000; const MAX_JSON_SAFE_INTEGER: u64 = 9_007_199_254_740_991; -const DISTRIBUTIONS: &str = include_str!("../../../../antigravity-distributions.json"); + +/// The record names Node's platform/architecture; the host check uses Rust's. +fn native_host_matches(platform: &str, architecture: &str, os: &str, host_arch: &str) -> bool { + matches!( + (platform, architecture, os, host_arch), + ("darwin", "arm64", "macos", "aarch64") + | ("linux", "x64", "linux", "x86_64") + | ("linux", "arm64", "linux", "aarch64") + ) +} + +/// The generated release profile that runtime qualification gates read. +/// +/// Every gate that depends on `qualification_pending` reads it here, so tests +/// can exercise the released state of a still-pending profile exactly as the +/// declaration change at qualification would produce it. +pub(crate) fn release_profile(agent: &str) -> Option { + #[allow(unused_mut)] + let mut profile = acpx_release_profile(agent)?; + #[cfg(test)] + if released_for_test::contains(agent) { + profile.qualification_pending = false; + } + Some(profile) +} + +/// Test-only simulation of a profile flipped to released on this thread. +#[cfg(test)] +pub(crate) mod released_for_test { + use std::cell::RefCell; + + thread_local! { + static RELEASED: RefCell> = const { RefCell::new(Vec::new()) }; + } + + pub(crate) fn contains(agent: &str) -> bool { + RELEASED.with(|released| released.borrow().iter().any(|name| name == agent)) + } + + /// Treats `agent` as released until the guard drops. + pub(crate) fn release(agent: &str) -> Guard { + RELEASED.with(|released| released.borrow_mut().push(agent.to_owned())); + Guard(agent.to_owned()) + } + + pub(crate) struct Guard(String); + + impl Drop for Guard { + fn drop(&mut self) { + RELEASED.with(|released| { + let mut released = released.borrow_mut(); + if let Some(index) = released.iter().position(|name| *name == self.0) { + released.remove(index); + } + }); + } + } +} /// Operator authority supplied only through trusted process startup. Company /// membership is authorized by the server; an agent descriptor cannot mint it. @@ -63,39 +121,32 @@ impl AcpxCandidateAdmission { } fn validate_at(&self, now: u64, os: &str, architecture: &str) -> Result<(), LocalRunnerError> { - let profile = acpx_release_profile(&self.agent).ok_or_else(invalid)?; - let (closure, host_matches) = match self.agent.as_str() { - "antigravity" => { - let manifest: Value = serde_json::from_str(DISTRIBUTIONS).map_err(|_| invalid())?; - let closure = manifest - .pointer("/platforms/darwin-arm64/closureSha256") - .and_then(Value::as_str) - .ok_or_else(invalid)? - .to_owned(); - ( - closure, - self.platform == "darwin" - && self.architecture == "arm64" - && os == "macos" - && architecture == "aarch64", - ) + let profile = release_profile(&self.agent).ok_or_else(invalid)?; + self.validate_against_profile(&profile, now, os, architecture) + } + + /// A candidate grant authorizes only a profile whose generated declaration + /// is still pending qualification. Releasing a profile is therefore a + /// declaration change: every candidate grant for that agent stops working. + fn validate_against_profile( + &self, + profile: &AcpxReleaseProfile, + now: u64, + os: &str, + architecture: &str, + ) -> Result<(), LocalRunnerError> { + let closure = match self.agent.as_str() { + "antigravity" if profile.qualification_pending => { + antigravity_native_closure(&self.platform, &self.architecture) } "kimi" if profile.qualification_pending => { - let closure = - kimi_native_closure(&self.platform, &self.architecture).ok_or_else(invalid)?; - let host_matches = matches!( - ( - self.platform.as_str(), - self.architecture.as_str(), - os, - architecture - ), - ("darwin", "arm64", "macos", "aarch64") | ("linux", "x64", "linux", "x86_64") - ); - (closure.to_owned(), host_matches) + kimi_native_closure(&self.platform, &self.architecture) } - _ => return Err(invalid()), - }; + _ => None, + } + .ok_or_else(invalid)?; + let host_matches = + native_host_matches(&self.platform, &self.architecture, os, architecture); if self.schema != SCHEMA || !is_stable_id(&self.company_id, DURABLE_STABLE_ID_CHARS) || self.model.trim().is_empty() @@ -157,9 +208,21 @@ impl AcpxCandidateAdmission { } } +/// The verified Antigravity target of the test host, or macOS ARM elsewhere. +#[cfg(test)] +pub(crate) fn test_target() -> (&'static str, &'static str) { + if cfg!(all(target_os = "linux", target_arch = "x86_64")) { + ("linux", "x64") + } else if cfg!(all(target_os = "linux", target_arch = "aarch64")) { + ("linux", "arm64") + } else { + ("darwin", "arm64") + } +} + #[cfg(test)] pub(crate) fn test_admission(run_id: &str, session_id: &str) -> AcpxCandidateAdmission { - let manifest: Value = serde_json::from_str(DISTRIBUTIONS).unwrap(); + let (platform, architecture) = test_target(); AcpxCandidateAdmission { schema: SCHEMA.to_owned(), company_id: "company-1".to_owned(), @@ -171,12 +234,10 @@ pub(crate) fn test_admission(run_id: &str, session_id: &str) -> AcpxCandidateAdm .to_owned(), native_closure_digest: format!( "sha256:{}", - manifest["platforms"]["darwin-arm64"]["closureSha256"] - .as_str() - .unwrap() + antigravity_native_closure(platform, architecture).unwrap() ), - platform: "darwin".to_owned(), - architecture: "arm64".to_owned(), + platform: platform.to_owned(), + architecture: architecture.to_owned(), expires_at: current_time_ms().unwrap() + 60_000, run_id: run_id.to_owned(), normalized_session_id: session_id.to_owned(), @@ -188,44 +249,80 @@ mod tests { use super::*; use serde_json::json; + fn antigravity_admission(platform: &str, architecture: &str) -> AcpxCandidateAdmission { + AcpxCandidateAdmission { + native_closure_digest: format!( + "sha256:{}", + antigravity_native_closure(platform, architecture).unwrap() + ), + platform: platform.to_owned(), + architecture: architecture.to_owned(), + ..test_admission("run-1", "session-1") + } + } + + const ANTIGRAVITY_HOSTS: [(&str, &str, &str, &str); 3] = [ + ("darwin", "arm64", "macos", "aarch64"), + ("linux", "x64", "linux", "x86_64"), + ("linux", "arm64", "linux", "aarch64"), + ]; + #[test] fn candidate_record_is_strict_and_pinned_to_native_host_and_time() { + assert!(antigravity_native_closure("darwin", "x64").is_none()); + for (platform, architecture, os, host_arch) in ANTIGRAVITY_HOSTS { + let candidate = antigravity_admission(platform, architecture); + let now = candidate.expires_at - 1; + candidate.validate_at(now, os, host_arch).unwrap(); + for (other_os, other_arch) in [ + ("macos", "aarch64"), + ("macos", "x86_64"), + ("linux", "x86_64"), + ("linux", "aarch64"), + ("windows", "x86_64"), + ] { + if (other_os, other_arch) != (os, host_arch) { + assert!(candidate.validate_at(now, other_os, other_arch).is_err()); + } + } + assert!(candidate + .validate_at(candidate.expires_at, os, host_arch) + .is_err()); + assert!(candidate + .validate_at(candidate.expires_at - MAX_LIFETIME_MS - 1, os, host_arch) + .is_err()); + let other_platform = if platform == "linux" { + "darwin" + } else { + "linux" + }; + let other_architecture = if architecture == "x64" { + "arm64" + } else { + "x64" + }; + for (field, value) in [ + ("schema", json!("unknown")), + ("companyId", json!("bad company")), + ("agent", json!("copilot")), + ("model", json!("auto")), + ("profileDigest", json!("sha256:wrong")), + ("nativeClosureDigest", json!("sha256:wrong")), + ("platform", json!(other_platform)), + ("architecture", json!(other_architecture)), + ("runId", json!("bad/run")), + ("normalizedSessionId", json!("bad/session")), + ] { + let mut changed = serde_json::to_value(&candidate).unwrap(); + changed[field] = value; + let changed: AcpxCandidateAdmission = serde_json::from_value(changed).unwrap(); + assert!( + changed.validate_at(now, os, host_arch).is_err(), + "{platform}-{architecture}: {field}" + ); + } + } let candidate = test_admission("run-1", "session-1"); - let now = candidate.expires_at - 1; - candidate.validate_at(now, "macos", "aarch64").unwrap(); - for (os, architecture) in [("linux", "aarch64"), ("macos", "x86_64")] { - assert!(candidate.validate_at(now, os, architecture).is_err()); - } - assert!(candidate - .validate_at(candidate.expires_at, "macos", "aarch64") - .is_err()); - assert!(candidate - .validate_at( - candidate.expires_at - MAX_LIFETIME_MS - 1, - "macos", - "aarch64" - ) - .is_err()); - for (field, value) in [ - ("schema", json!("unknown")), - ("companyId", json!("bad company")), - ("agent", json!("copilot")), - ("model", json!("auto")), - ("profileDigest", json!("sha256:wrong")), - ("nativeClosureDigest", json!("sha256:wrong")), - ("platform", json!("linux")), - ("architecture", json!("x64")), - ("runId", json!("bad/run")), - ("normalizedSessionId", json!("bad/session")), - ] { - let mut changed = serde_json::to_value(&candidate).unwrap(); - changed[field] = value; - let changed: AcpxCandidateAdmission = serde_json::from_value(changed).unwrap(); - assert!( - changed.validate_at(now, "macos", "aarch64").is_err(), - "{field}" - ); - } let mut value = serde_json::to_value(&candidate).unwrap(); value["extra"] = json!(true); assert!(serde_json::from_value::(value).is_err()); @@ -233,7 +330,13 @@ mod tests { } #[test] - #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + #[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) + ))] fn candidate_binds_actual_launch_and_does_not_echo_bad_input() { let candidate = test_admission("run-1", "session-1"); candidate @@ -253,6 +356,66 @@ mod tests { assert!(!error.to_string().contains("private")); } + /// The generated Antigravity profile with its qualification flipped to + /// released, exactly as the declaration change at qualification would. + pub(crate) fn released_antigravity_profile() -> AcpxReleaseProfile { + AcpxReleaseProfile { + qualification_pending: false, + ..acpx_release_profile("antigravity").unwrap() + } + } + + #[test] + fn released_antigravity_rejects_candidate_records_on_every_native_platform() { + let pending = acpx_release_profile("antigravity").unwrap(); + assert!(pending.qualification_pending); + let released = released_antigravity_profile(); + for (platform, architecture, os, host_arch) in ANTIGRAVITY_HOSTS { + let candidate = antigravity_admission(platform, architecture); + let now = candidate.expires_at - 1; + candidate + .validate_against_profile(&pending, now, os, host_arch) + .unwrap(); + assert!( + candidate + .validate_against_profile(&released, now, os, host_arch) + .is_err(), + "{platform}-{architecture}" + ); + let mut next = candidate.clone(); + next.run_id = "run-2".to_owned(); + assert!(next + .validate_against_profile(&released, now, os, host_arch) + .is_err()); + } + } + + #[test] + #[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) + ))] + fn released_antigravity_rejects_startup_and_binding_records() { + let current = test_admission("run-1", "session-1"); + current.validate().unwrap(); + let _released = released_for_test::release("antigravity"); + assert!( + !release_profile("antigravity") + .unwrap() + .qualification_pending + ); + assert!(current.validate().is_err()); + assert!(current + .validate_binding("antigravity", "explicit-model", "run-1", "session-1") + .is_err()); + assert!( + AcpxCandidateAdmission::parse_json(&serde_json::to_string(¤t).unwrap()).is_err() + ); + } + fn kimi_admission(platform: &str, architecture: &str) -> AcpxCandidateAdmission { AcpxCandidateAdmission { agent: "kimi".to_owned(), diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs index 2a1c87865c3..5f8fde0ab7e 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs @@ -328,7 +328,7 @@ impl AcpxProviderDescriptor { fn supports_host_parking(&self) -> bool { matches!(self.agent.as_str(), "codex" | "claude") && self.names_qualified_release() - && acpx_release_profile(&self.agent) + && crate::acpx_candidate_admission::release_profile(&self.agent) .is_some_and(|profile| !profile.qualification_pending) } @@ -1003,6 +1003,17 @@ fn validate_pending_runtime_requests( Ok(()) } +/// The sidecar refused to reload a saved conversation in a new provider +/// process (ACP `session/load` or `session/resume` behind a recovering +/// `session.open`). Only the typed rejection decides; the message never does. +fn saved_state_reload_refused(error: &crate::local_runner::LocalRunnerError) -> bool { + error.command_rejection().is_some_and(|rejection| { + rejection.command == GeneratedAcpxSidecarCommand::SessionOpen.as_str() + && rejection.classification + == crate::acpx_sidecar_transport::ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE + }) +} + fn attested_pending_runtime_requests( pending: &BTreeMap, provider: &crate::acpx_provider_state::AcpxProviderState, @@ -1537,8 +1548,17 @@ impl AcpxCommandExecutor { } Err(_) => return Ok(false), }; - let Ok(session) = self.start_session(true) else { - return Ok(false); + let session = match self.start_session(true) { + Ok(session) => session, + // The provider refused this saved conversation by name: closing + // the turn as a generic interruption would hide that the server + // must start a replacement conversation. + Err(error) + if error.classification() == Some(crate::durable::PROVIDER_STATE_INCOMPATIBLE) => + { + return Err(error) + } + Err(_) => return Ok(false), }; let identity = session.identity().clone(); let process_id = session.process_id(); @@ -1607,8 +1627,15 @@ impl AcpxCommandExecutor { self.launch_profile.as_ref(), )?; let mut session = AcpxProviderSession::start(&config).map_err(|error| { - DurableRunnerError::invalid(format!("failed to start ACPX provider: {error}")) - .with_provider_failure(error.provider_failure()) + let incompatible = recovering && saved_state_reload_refused(&error); + let failure = + DurableRunnerError::invalid(format!("failed to start ACPX provider: {error}")) + .with_provider_failure(error.provider_failure()); + if incompatible { + failure.with_classification(crate::durable::PROVIDER_STATE_INCOMPATIBLE) + } else { + failure + } })?; if session.identity().profile_digest != state.descriptor.command_digest { let _ = session.shutdown("qualified ACPX profile digest mismatch"); @@ -1619,7 +1646,7 @@ impl AcpxCommandExecutor { let expected_dormant = recovering && self.recovery_pending_effects == Some(0) && self.candidate_admission().is_none() - && acpx_release_profile(&state.descriptor.agent) + && crate::acpx_candidate_admission::release_profile(&state.descriptor.agent) .is_some_and(|profile| !profile.qualification_pending) && matches!(state.lifecycle.as_str(), "session_open" | "suspended") && state.active_turn_id.is_none() @@ -4447,7 +4474,13 @@ mod tests { } #[test] - #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + #[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) + ))] fn candidate_authority_cannot_come_from_descriptor_or_recover_a_prior_runner() { let directory = temporary_directory("candidate-authority"); let mut admission = crate::acpx_candidate_admission::test_admission("run-1", "session-1"); @@ -6112,6 +6145,209 @@ mod tests { drop(listeners.pop()); (candidates, listeners) } + /// An Antigravity session saved by `run-1` under an ordinary launch + /// profile (no candidate grant), and a runner for `context_run`. Its + /// sidecar records any launch and exits, so no test reaches a provider. + #[cfg(unix)] + fn ordinary_antigravity_fixture( + label: &str, + context_run: &str, + ) -> (PathBuf, DurableRunnerConfig, Value, PathBuf) { + let directory = temporary_directory(label); + let command = directory.join("owned-sidecar"); + let sentinel = directory.join("provider-opened"); + write_artifact( + &command, + format!("#!/bin/sh\ntouch '{}'\nexit 1\n", sentinel.display()).as_bytes(), + true, + ); + let profile = AcpxLaunchProfile { + candidate_admission: None, + authority_digest: format!("sha256:{}", "d".repeat(64)), + command: command.clone(), + args: vec![], + artifacts: vec![artifact(&command)], + }; + let runtime = directory.join("runtime"); + let workspace = directory.join("workspace"); + fs::create_dir_all(&runtime).unwrap(); + fs::create_dir_all(&workspace).unwrap(); + fs::set_permissions(&runtime, fs::Permissions::from_mode(0o700)).unwrap(); + fs::set_permissions(&workspace, fs::Permissions::from_mode(0o700)).unwrap(); + let mut value = descriptor("antigravity"); + value["runtimeDirectory"] = json!(runtime); + value["cwd"] = json!(workspace); + value["sidecarCommand"] = json!(command); + value["sidecarArgs"] = json!([]); + let desc: AcpxProviderDescriptor = serde_json::from_value(value.clone()).unwrap(); + let identity = AcpxProviderSessionIdentity { + kind: "acpx".to_owned(), + normalized_session_id: "session-1".to_owned(), + acpx_record_id: "record-1".to_owned(), + backend_session_id: "backend-1".to_owned(), + agent_session_id: "agent-1".to_owned(), + profile_digest: desc.command_digest.clone(), + workspace_digest: format!("sha256:{}", "a".repeat(64)), + requested_model: desc.model.clone(), + effective_model: desc.model.clone(), + permission_mode: Some(desc.permission_mode), + mode: None, + pi_thinking_level: None, + claude_effort: None, + grok_effort: None, + grok_disable_web_search: None, + provider_lifetime_fence_candidates: [60_001, 60_002, 60_003], + }; + let operations = Vec::new(); + let tools = AuthorizedToolSet { + schema: TOOL_SET_SCHEMA.to_owned(), + schema_version: 1, + catalog_digest: authorized_tool_catalog_digest(&operations).unwrap(), + operations, + }; + let mut state = AcpxDurableState::new(desc, tools, profile.canonical_digest().unwrap()); + state.lifecycle = "suspended".to_owned(); + state.identity = Some(identity); + let saving = test_config(&directory, Some(profile)); + let mut executor = AcpxCommandExecutor::with_runner_config(&directory, &saving); + executor.state = Some(state); + executor.save_state().unwrap(); + let mut config = saving; + if context_run != "run-1" { + config.run_id = context_run.to_owned(); + config.turn_id = "turn-2".to_owned(); + config.item_id = "item-2".to_owned(); + } + config.validate().unwrap(); + (directory, config, value, sentinel) + } + + /// The candidate grant the pending Antigravity profile admits for `run_id`. + fn antigravity_grant(run_id: &str) -> crate::acpx_candidate_admission::AcpxCandidateAdmission { + let mut grant = crate::acpx_candidate_admission::test_admission(run_id, "session-1"); + grant.model = "explicit-test-model".to_owned(); + grant + } + + // At qualification the Antigravity profile becomes released. Only the + // declaration changes: the candidate-only refusals key on a candidate + // grant, a released profile admits no grant, and the ordinary qualified + // path applies to the provider launch, recovery and attachment. + #[test] + #[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) + ))] + fn released_antigravity_launches_without_grant_and_rejects_any_candidate_grant() { + let (directory, config, _, _) = ordinary_antigravity_fixture("antigravity-flip", "run-1"); + let executor = AcpxCommandExecutor::with_runner_config(&directory, &config); + let saved: AcpxDurableState = + serde_json::from_slice(&fs::read(executor.state_path()).unwrap()).unwrap(); + let profile = config.acpx_launch_profile.as_ref().unwrap(); + // The launch configuration exactly as AcpxProviderSession::start + // validates it before spawning the sidecar. + let launch = |profile: &AcpxLaunchProfile| { + let config = saved + .descriptor + .session_config( + saved.tool_set.clone(), + saved.identity.clone(), + Some(profile), + ) + .map_err(|error| error.to_string())?; + config.validate().map_err(|error| error.to_string())?; + Ok::<_, String>(config) + }; + // Pending: an ordinary launch is refused until an operator grant. + let pending = launch(profile).unwrap_err(); + assert!(pending.contains("qualification is pending"), "{pending}"); + let mut granted = profile.clone(); + granted.candidate_admission = Some(antigravity_grant("run-1")); + let mut candidate_config = config.clone(); + candidate_config.acpx_launch_profile = Some(granted.clone()); + candidate_config.validate().unwrap(); + launch(&granted).unwrap(); + + let _released = crate::acpx_candidate_admission::released_for_test::release("antigravity"); + // Released: the ordinary launch needs no grant ... + let ordinary = launch(profile).unwrap(); + assert!(ordinary.candidate_admission.is_none()); + // ... and every candidate grant is refused at startup and at launch. + assert!(candidate_config.validate().is_err()); + assert!(launch(&granted).is_err()); + let mut injected = descriptor("antigravity"); + injected["candidateAdmission"] = json!(antigravity_grant("run-1")); + assert!(serde_json::from_value::(injected).is_err()); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + #[cfg(unix)] + fn released_antigravity_without_grant_restores_suspends_and_attaches_a_prior_activation() { + let _released = crate::acpx_candidate_admission::released_for_test::release("antigravity"); + let (directory, config, value, sentinel) = + ordinary_antigravity_fixture("antigravity-released-cold", "run-2"); + let mut recovered = AcpxCommandExecutor::with_runner_config(&directory, &config); + // load_state_without_session: an ordinary runner adopts the prior + // durable activation that a candidate would refuse. + recovered + .restore() + .expect("a released Antigravity runner adopts the prior activation"); + assert!(recovered.state.is_some()); + // runner.suspend keeps the recoverable session instead of retiring it. + let suspended = recovered.suspend().unwrap(); + assert_eq!(suspended.result["status"], "completed"); + assert_eq!(recovered.state.as_ref().unwrap().lifecycle, "suspended"); + // run.attach: the next run attaches to the saved conversation and + // reaches the ordinary provider launch (the fixture sidecar exits). + let mut provider = value; + provider["runId"] = json!("run-2"); + let error = recovered + .execute(&cold_attach_command(json!({"provider": provider}))) + .unwrap_err() + .to_string(); + assert!(error.contains("failed to start ACPX provider"), "{error}"); + assert!(sentinel.exists(), "the ordinary launch ran the sidecar"); + let saved: AcpxDurableState = + serde_json::from_slice(&fs::read(recovered.state_path()).unwrap()).unwrap(); + assert_eq!(saved.descriptor.run_id, "run-2"); + assert_ne!(saved.lifecycle, "closed"); + fs::remove_dir_all(directory).unwrap(); + } + + #[test] + #[cfg(unix)] + fn released_antigravity_without_grant_rotates_a_live_runner_authority() { + let _released = crate::acpx_candidate_admission::released_for_test::release("antigravity"); + let (directory, config, value, sentinel) = + ordinary_antigravity_fixture("antigravity-released-warm", "run-1"); + let mut executor = AcpxCommandExecutor::with_runner_config(&directory, &config); + executor.load_state_for_test(); + let mut provider = value; + provider["runId"] = json!("run-2"); + let attach = cold_attach_command(json!({"provider": provider, "paperclipNextAuthority": { + "identity": {"runId": "run-2", "normalizedSessionId": "session-1"} + }})); + // The rotation passes both candidate refusals and reaches the + // ordinary provider launch (the fixture sidecar exits). + let error = executor.execute(&attach).unwrap_err().to_string(); + assert!(error.contains("failed to start ACPX provider"), "{error}"); + assert!(sentinel.exists(), "the ordinary launch ran the sidecar"); + let updated = executor.state.as_ref().unwrap(); + assert_eq!(updated.descriptor.run_id, "run-2"); + assert_eq!(executor.context.run_id, "run-1"); + assert!(executor + .launch_profile + .as_ref() + .unwrap() + .candidate_admission + .is_none()); + fs::remove_dir_all(directory).unwrap(); + } + #[test] #[cfg(any( all(target_os = "macos", target_arch = "aarch64"), @@ -6379,6 +6615,15 @@ mod tests { ) } + impl AcpxCommandExecutor { + /// Loads the saved state as an already-restored runner holds it, so a + /// test reaches command dispatch without launching the provider. + fn load_state_for_test(&mut self) { + self.load_state_without_session().unwrap(); + self.restore_checked = true; + } + } + pub(super) fn cold_attach_command(payload: Value) -> Command { Command { schema: "paperclip.prp.command.v1".into(), diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs index f50b3011c02..970a27e9b81 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_session.rs @@ -1,4 +1,3 @@ -use crate::generated_acpx_profiles::acpx_release_profile; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; @@ -125,9 +124,10 @@ pub struct AcpxProviderSessionConfig { impl AcpxProviderSessionConfig { pub fn validate(&self) -> Result<(), LocalRunnerError> { self.transport.validate()?; - let profile = acpx_release_profile(&self.agent).ok_or_else(|| { - LocalRunnerError::invalid("ACPX agent must name a known immutable profile") - })?; + let profile = + crate::acpx_candidate_admission::release_profile(&self.agent).ok_or_else(|| { + LocalRunnerError::invalid("ACPX agent must name a known immutable profile") + })?; if let Some(admission) = &self.candidate_admission { admission.validate_binding( &self.agent, @@ -2041,7 +2041,8 @@ fn with_cleanup_error( Err(cleanup) => LocalRunnerError::invalid(format!( "{error}; ACPX sidecar cleanup also failed: {cleanup}" )) - .with_provider_failure(error.provider_failure()), + .with_provider_failure(error.provider_failure()) + .with_command_rejection(error.command_rejection()), } } @@ -2514,7 +2515,13 @@ mod mode_tests { } #[test] - #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + #[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) + ))] fn candidate_admission_is_bound_and_carried_through_both_bootstrap_requests() { let mut cfg = config(); assert!(initialize_params(&cfg).get("candidateAdmission").is_none()); diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs index ab572facb4a..4c78f656ee6 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_sidecar_transport.rs @@ -10,7 +10,7 @@ use crate::generated_acpx_sidecar_contract::{ GeneratedAcpxSidecarCommand, GeneratedAcpxSidecarEventType, GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, }; -use crate::local_runner::LocalRunnerError; +use crate::local_runner::{CommandRejection, LocalRunnerError}; use crate::process_supervisor::{ BoundedLogBuffer, ProcessOutput, SupervisedProcess, VerifiedProcessLaunch, }; @@ -828,14 +828,19 @@ impl AcpxSidecarTransport { && error.code == "SESSION_RESUME_REQUIRED"; let tool_call_retired = command == GeneratedAcpxSidecarCommand::ToolResolve && error.code == "ACPX_TOOL_CALL_STALE"; + let classification = response_error_classification(&error); return Ok(Some(CommandOutcome::Rejected { tool_call_retired, error: LocalRunnerError::invalid( format!( "ACPX sidecar command {} was rejected (retryable={}, classification={})", command.as_str(), error.retryable, - response_error_classification(&error), + classification, ), - ).with_provider_failure(provider_failure), resume_required })); + ).with_provider_failure(provider_failure) + .with_command_rejection(Some(CommandRejection { + command: command.as_str(), + classification, + })), resume_required })); } } } @@ -1278,6 +1283,12 @@ fn typed_provider_classification(error: &ResponseError) -> Option<&'static str> }) } +/// The sidecar refused to reload an Antigravity conversation in a new process: +/// its native admission receipt is missing or mismatched, or the managed +/// reload was refused. Retrying the same reload cannot succeed. +pub(crate) const ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE: &str = + "antigravity_saved_state_incompatible"; + fn response_error_classification(error: &ResponseError) -> &'static str { match error.code.as_str() { "GROK_EFFORT_ACKNOWLEDGEMENT_MISSING" => return "grok_effort_acknowledgement_missing", @@ -1347,6 +1358,7 @@ fn response_error_classification(error: &ResponseError) -> &'static str { "ACPX_MODEL_STATUS_UNAVAILABLE" => return "model_status_unavailable", "ACPX_MODEL_SELECTION_UNAVAILABLE" => return "model_selection_unavailable", "ACPX_EFFECTIVE_MODEL_MISMATCH" => return "effective_model_mismatch", + "ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE" => return ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE, _ => {} } match error.message.as_str() { diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs index 74d777b9c64..7ed0270231e 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/fake-acpx-sidecar.rs @@ -225,6 +225,29 @@ fn run() -> Result<(), Box> { continue; } } + // `--open-rejection `: while the file holds ` `, + // reject `session.open` with that sidecar error code. Scope `any` + // rejects every open; `recovering` only an open that reloads a saved + // conversation (one that names its expected identity). + if command == "session.open" { + let rejection = args + .windows(2) + .find(|pair| pair[0] == "--open-rejection") + .and_then(|pair| std::fs::read_to_string(&pair[1]).ok()) + .unwrap_or_default(); + if let Some((scope, code)) = rejection.trim().split_once(' ') { + if scope == "any" + || (scope == "recovering" && !request["params"]["expectedIdentity"].is_null()) + { + write_json( + &mut stdout, + &json!({"protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,"id":id,"ok":false, + "error":{"code":code,"message":"The saved conversation cannot be reloaded.","retryable":false}}), + )?; + continue; + } + } + } if command == "turn.cancel" && provider_turn_tokens() .iter() diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs index d68cce10104..ff41d9a0481 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs @@ -892,7 +892,13 @@ mod tests { } #[test] - #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + #[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) + ))] fn candidate_startup_requires_a_complete_trusted_launch_profile() { let profiles: serde_json::Value = serde_json::from_str(include_str!("../../../../../acpx-profiles.json")).unwrap(); @@ -900,11 +906,18 @@ mod tests { "../../../../../antigravity-distributions.json" )) .unwrap(); + let (platform, architecture) = if cfg!(target_os = "macos") { + ("darwin", "arm64") + } else if cfg!(target_arch = "x86_64") { + ("linux", "x64") + } else { + ("linux", "arm64") + }; let encoded = json!({ "schema":"paperclip.acpx-candidate-admission.v1", "companyId":"company-1", "agent":"antigravity", "model":"exact-model", "profileDigest":profiles["profiles"]["antigravity"]["commandDigest"], - "nativeClosureDigest":format!("sha256:{}",distributions["platforms"]["darwin-arm64"]["closureSha256"].as_str().unwrap()), - "platform":"darwin", "architecture":"arm64", "expiresAt":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64 + 60_000, + "nativeClosureDigest":format!("sha256:{}",distributions["platforms"][format!("{platform}-{architecture}")]["closureSha256"].as_str().unwrap()), + "platform":platform, "architecture":architecture, "expiresAt":std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64 + 60_000, "runId":"run-1", "normalizedSessionId":"session-1" }).to_string(); let mut args = vec!["--acpx-candidate-admission-json".to_owned(), encoded]; diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/durable/mod.rs b/packages/paperclip-runner/runner/crates/runner-core/src/durable/mod.rs index 156495ff974..25edf149d01 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/durable/mod.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/durable/mod.rs @@ -454,7 +454,13 @@ mod tests { } #[test] - #[cfg(all(target_os = "macos", target_arch = "aarch64"))] + #[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) + ))] fn candidate_launch_digest_binds_authority_and_config_binds_actual_identity() { let mut profile = AcpxLaunchProfile { authority_digest: format!("sha256:{}", "a".repeat(64)), diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs b/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs index 803e40f1312..22468650e7b 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/durable/runner.rs @@ -6561,4 +6561,69 @@ mod tests { assert!(stale_candidate.validate().is_err()); assert!(next_authority_config(&injected, &stale_candidate).is_err()); } + + #[test] + #[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) + ))] + fn released_antigravity_handoff_uses_ordinary_authority_and_rejects_candidate_injection() { + let directory = + std::env::temp_dir().join(format!("antigravity-grant-handoff-{}", std::process::id())); + let mut current = config(directory); + let grant = crate::acpx_candidate_admission::test_admission( + "run_1", + ¤t.normalized_session_id, + ); + let ordinary = crate::durable::AcpxLaunchProfile { + authority_digest: format!("sha256:{}", "a".repeat(64)), + command: PathBuf::from("/fixture/node"), + args: vec!["/fixture/sidecar.cjs".to_owned()], + artifacts: vec![crate::durable::QualifiedLaunchArtifact { + path: PathBuf::from("/fixture/node"), + sha256: format!("sha256:{}", "b".repeat(64)), + }], + candidate_admission: None, + }; + let mut candidate = current.clone(); + candidate.acpx_launch_profile = Some(crate::durable::AcpxLaunchProfile { + candidate_admission: Some(grant.clone()), + ..ordinary.clone() + }); + // Pending: the grant admits this run's startup. + candidate.validate().unwrap(); + + let _released = crate::acpx_candidate_admission::released_for_test::release("antigravity"); + current.acpx_launch_profile = Some(ordinary); + current.validate().unwrap(); + let mut next_grant = grant.clone(); + next_grant.run_id = "run_2".to_owned(); + let mut attach = command("run.attach"); + attach.payload = json!({"paperclipNextAuthority":{ + "identity":{"runnerInstanceId":current.runner_instance_id,"environmentLeaseId":current.environment_lease_id, + "runId":"run_2","normalizedSessionId":current.normalized_session_id,"turnId":"turn_2","itemId":"item_2"}, + "connection":{"mode":"external"} + }}); + let next = next_authority_config(&attach, ¤t).unwrap().unwrap(); + assert!(next + .acpx_launch_profile + .as_ref() + .unwrap() + .candidate_admission + .is_none()); + assert_eq!(next.acpx_launch_profile, current.acpx_launch_profile); + assert_eq!(next.run_id, "run_2"); + assert_eq!(next.turn_id, "turn_2"); + assert_eq!(next.item_id, "item_2"); + let mut injected = attach.clone(); + injected.payload["paperclipNextAuthority"]["candidateAdmission"] = json!(next_grant); + assert!(next_authority_config(&injected, ¤t).is_err()); + // Released: a stale grant no longer admits startup or a handoff. + assert!(candidate.validate().is_err()); + assert!(next_authority_config(&attach, &candidate).is_err()); + assert!(next_authority_config(&injected, &candidate).is_err()); + } } 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 2c39b15ad37..24549f50bc6 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 @@ -1,4 +1,4 @@ -// Generated from acpx-profiles.json and cursor-distributions.json. Do not edit. +// Generated from acpx-profiles.json, cursor-distributions.json and antigravity-distributions.json. Do not edit. pub(crate) const QUALIFIED_ACPX_VERSION: &str = "0.22.0"; pub(crate) const ACPX_DRIVER_KIND: &str = "acpx_runtime"; @@ -25,15 +25,33 @@ pub(crate) fn kimi_native_closure(platform: &str, architecture: &str) -> Option< } } +pub(crate) fn antigravity_native_closure( + platform: &str, + architecture: &str, +) -> Option<&'static str> { + match (platform, architecture) { + ("darwin", "arm64") => { + Some("ab9df40a64806a8e1812234ce5331e04d1c6b5f8c7e5bdbb456cd645e58c5aad") + } + ("linux", "x64") => { + Some("be35d65a32667550b5474588d705e6987a813e2fa619cf5db7d82d141c3c05fb") + } + ("linux", "arm64") => { + Some("46c36293779283c1f933eb438a143d116421a331f614601c754f1b94d9dc171a") + } + _ => None, + } +} + pub(crate) fn acpx_release_profile(agent: &str) -> Option { Some(match agent { "antigravity" => AcpxReleaseProfile { agent_server_package: "native:antigravity-acp", - agent_server_version: "1.4.3", + agent_server_version: "1.5.2", agent_runtime_package: Some("native:antigravity-localharness"), - agent_runtime_version: Some("1.4.3"), + agent_runtime_version: Some("1.5.2"), command_digest: - "sha256:acf5f574b6b9ec4388ff9d081890caa330e66bf1ae3fe3b08e7f0fb0e851b9ce", + "sha256:61ac14bf03ce4bbf8afe1f5a263b854517ec588d8407fe2d8f17c9fc0c037c4b", requires_provider_policy: true, qualification_pending: true, }, diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/local_runner.rs b/packages/paperclip-runner/runner/crates/runner-core/src/local_runner.rs index 839322c0097..c653c27cf19 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/local_runner.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/local_runner.rs @@ -22,11 +22,19 @@ const HARNESS_MESSAGE_SCHEMA: &str = "paperclip.fake_harness.message.v1"; const CONTROLLER_COMMAND_QUEUE_CAPACITY: usize = 256; #[derive(Clone, Debug, PartialEq, Eq)] -pub struct LocalRunnerError(String, Option); +pub struct LocalRunnerError(String, Option, Option); + +/// A provider process rejected a named command with a closed failure class. +/// Callers branch on this data, never on the error message. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CommandRejection { + pub command: &'static str, + pub classification: &'static str, +} impl LocalRunnerError { pub fn invalid(message: impl Into) -> Self { - Self(message.into(), None) + Self(message.into(), None, None) } pub fn with_provider_failure(mut self, value: Option) -> Self { @@ -37,6 +45,15 @@ impl LocalRunnerError { pub fn provider_failure(&self) -> Option { self.1.clone() } + + pub fn with_command_rejection(mut self, rejection: Option) -> Self { + self.2 = rejection; + self + } + + pub fn command_rejection(&self) -> Option { + self.2 + } } impl Display for LocalRunnerError { diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/native_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/native_provider_backend.rs index a643a2e73a3..c674d654b1a 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/native_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/native_provider_backend.rs @@ -612,3 +612,100 @@ impl CommandExecutor for NativeProviderCommandExecutor { cleanup.and(self.credentials.poll(true)) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::durable::{AcpxLaunchProfile, DurableRunnerConfig, QualifiedLaunchArtifact}; + use std::time::Duration; + + fn config(state_dir: &std::path::Path, profile: AcpxLaunchProfile) -> DurableRunnerConfig { + DurableRunnerConfig { + connect_url: "ws://127.0.0.1/runner".to_owned(), + ca_bundle_path: None, + state_dir: state_dir.to_owned(), + runner_instance_id: "runner-1".to_owned(), + environment_lease_id: "lease-1".to_owned(), + run_id: "run-1".to_owned(), + normalized_session_id: "session-1".to_owned(), + turn_id: "turn-1".to_owned(), + item_id: "item-1".to_owned(), + runner_version: "0.0.0".to_owned(), + runner_digest: "sha256:test".to_owned(), + acpx_launch_profile: Some(profile), + opencode_launch_profile: None, + cursor_cloud_launch_profile: None, + max_outbox_bytes: 1024 * 1024, + p0_reserve_bytes: 64 * 1024, + max_frame_bytes: 1024 * 1024, + reconnect_delay: Duration::from_millis(1), + reconnect_grace: None, + max_runtime: Duration::from_secs(60), + turn_scoped: false, + controller_silence: crate::durable::DEFAULT_CONTROLLER_SILENCE, + } + } + + // The candidate refusal to adopt a prior activation keys on an Antigravity + // grant. Once the profile is released no grant is admitted, and an + // ordinary runner recovers the prior activation. + #[test] + #[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) + ))] + fn released_antigravity_without_grant_recovers_a_prior_activation() { + let directory = std::env::temp_dir().join(format!( + "paperclip-native-released-antigravity-{}", + uuid::Uuid::new_v4() + )); + std::fs::create_dir_all(&directory).unwrap(); + std::fs::write(directory.join(CODEX_PROVIDER_STATE_FILE), b"{}").unwrap(); + let ordinary = AcpxLaunchProfile { + candidate_admission: None, + authority_digest: format!("sha256:{}", "a".repeat(64)), + command: PathBuf::from("/fixture/node"), + args: vec!["/fixture/sidecar.cjs".to_owned()], + artifacts: vec![QualifiedLaunchArtifact { + path: PathBuf::from("/fixture/node"), + sha256: format!("sha256:{}", "b".repeat(64)), + }], + }; + let candidate = config( + &directory, + AcpxLaunchProfile { + candidate_admission: Some(crate::acpx_candidate_admission::test_admission( + "run-1", + "session-1", + )), + ..ordinary.clone() + }, + ); + candidate.validate().unwrap(); + let refused = NativeProviderCommandExecutor::with_runner_config(&directory, &candidate) + .select_recovery() + .unwrap_err(); + assert!( + refused + .to_string() + .contains("cannot adopt a prior durable runner activation"), + "{refused}" + ); + + let _released = crate::acpx_candidate_admission::released_for_test::release("antigravity"); + assert!(candidate.validate().is_err()); + let ordinary = config(&directory, ordinary); + ordinary.validate().unwrap(); + let mut recovered = + NativeProviderCommandExecutor::with_runner_config(&directory, &ordinary); + recovered.select_recovery().unwrap(); + assert!(matches!( + recovered.selected, + Some(SelectedExecutor::LocalFacade(_)) + )); + std::fs::remove_dir_all(directory).unwrap(); + } +} diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_saved_state_incompatible.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_saved_state_incompatible.rs new file mode 100644 index 00000000000..14bb93c4806 --- /dev/null +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/acpx_saved_state_incompatible.rs @@ -0,0 +1,297 @@ +#![cfg(unix)] + +//! A sidecar that refuses to reload a saved conversation in a new provider +//! process (`ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE`) names the restore failure +//! `provider_state_incompatible`, so the server starts a replacement +//! conversation instead of retrying a generic interruption. + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; +use std::time::Duration; + +use paperclip_runner_core::acpx_provider_backend::AcpxCommandExecutor; +use paperclip_runner_core::durable::{ + AcpxLaunchProfile, Command, CommandExecutor, DurableRunnerConfig, QualifiedLaunchArtifact, + PROVIDER_STATE_INCOMPATIBLE, +}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +const PROFILE_DIGEST: &str = + "sha256:443491f4e814501a5dc47347e4510e84faeec9c9382e2d4e53bfe69386d5aabc"; +const INCOMPATIBLE: &str = "ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE"; + +struct Fixture { + directory: PathBuf, + config: DurableRunnerConfig, + descriptor: Value, +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.directory); + } +} + +impl Fixture { + fn new(label: &str) -> Self { + let directory = std::env::temp_dir().join(format!("acpx-{label}-{}", uuid::Uuid::new_v4())); + fs::create_dir_all(&directory).unwrap(); + fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap(); + let native = directory.join("native-sidecar"); + fs::copy(env!("CARGO_BIN_EXE_fake-acpx-sidecar"), &native).unwrap(); + fs::set_permissions(&native, fs::Permissions::from_mode(0o700)).unwrap(); + // The launch profile authenticates every absolute argument, so the + // rejection file is named inside the authenticated wrapper. + let sidecar = directory.join("sidecar"); + fs::write( + &sidecar, + format!( + "#!/bin/sh\nexec '{}' --open-rejection '{}' \"$@\"\n", + native.display(), + directory.join("open-rejection").display() + ), + ) + .unwrap(); + fs::set_permissions(&sidecar, fs::Permissions::from_mode(0o700)).unwrap(); + let ports = unused_fence_ports(); + let args = vec![ + "--mode".to_owned(), + "suspend".to_owned(), + "--profile-digest".to_owned(), + PROFILE_DIGEST.to_owned(), + "--lifetime-fence-ports".to_owned(), + format!("{},{},{}", ports[0], ports[1], ports[2]), + ]; + let config = DurableRunnerConfig { + connect_url: "ws://127.0.0.1/runner".to_owned(), + ca_bundle_path: None, + state_dir: directory.clone(), + runner_instance_id: "runner-1".to_owned(), + environment_lease_id: "lease-1".to_owned(), + run_id: "run-1".to_owned(), + normalized_session_id: "session-1".to_owned(), + turn_id: "turn-1".to_owned(), + item_id: "item-1".to_owned(), + runner_version: "0.0.0".to_owned(), + runner_digest: format!("sha256:{}", "a".repeat(64)), + acpx_launch_profile: Some(AcpxLaunchProfile { + candidate_admission: None, + authority_digest: format!("sha256:{}", "d".repeat(64)), + command: sidecar.clone(), + args: args.clone(), + artifacts: vec![QualifiedLaunchArtifact { + path: sidecar.clone(), + sha256: format!("sha256:{:x}", Sha256::digest(fs::read(&sidecar).unwrap())), + }], + }), + opencode_launch_profile: None, + cursor_cloud_launch_profile: None, + max_outbox_bytes: 1024 * 1024, + p0_reserve_bytes: 64 * 1024, + max_frame_bytes: 1024 * 1024, + reconnect_delay: Duration::from_millis(1), + reconnect_grace: None, + max_runtime: Duration::from_secs(30), + turn_scoped: false, + controller_silence: paperclip_runner_core::durable::DEFAULT_CONTROLLER_SILENCE, + }; + let descriptor = json!({ + "kind": "acpx", "provider": "acpx", "driver": "acpx_runtime", + "providerVersion": "0.22.0", "agent": "codex", "model": "gpt-5.6-sol", + "acpxVersion": "0.22.0", "agentServerPackage": "@agentclientprotocol/codex-acp", + "agentServerVersion": "1.6.2", "agentRuntimePackage": "@openai/codex", + "agentRuntimeVersion": "0.170.0", "commandDigest": PROFILE_DIGEST, + "sidecarCommand": sidecar, "sidecarArgs": args, "runtimeDirectory": directory, + "normalizedSessionId": "session-1", "runId": "run-1", "cwd": directory, + "instructions": "Complete the supplied work.", + "permissionMode": "approve-all", "permissionModePinned": true, + }); + Self { + directory, + config, + descriptor, + } + } + + fn reject_open(&self, scope: &str, code: &str) { + fs::write( + self.directory.join("open-rejection"), + format!("{scope} {code}"), + ) + .unwrap(); + } + + fn executor(&self) -> AcpxCommandExecutor { + AcpxCommandExecutor::with_runner_config(&self.directory, &self.config) + } + + /// Opens the conversation in a first runner and returns that runner. + fn opened(&self) -> AcpxCommandExecutor { + let mut original = self.executor(); + original + .execute(&command( + 1, + "run.prepare", + json!({"provider": self.descriptor}), + )) + .unwrap(); + original + .execute(&command(2, "session.open", json!({}))) + .unwrap(); + original + } + + /// Opens the conversation, then retires that runner with `runner.suspend`. + fn suspended(&self) { + let mut original = self.opened(); + original + .execute(&command(3, "runner.suspend", json!({}))) + .unwrap(); + drop(original); + } +} + +fn command(sequence: u64, kind: &str, payload: Value) -> Command { + Command { + schema: "paperclip.prp.command.v1".to_owned(), + command_id: format!("command-{sequence}"), + controller_seq: sequence, + command_type: kind.to_owned(), + issued_at: "2026-09-21T00:00:00.000Z".to_owned(), + deadline_at: None, + precondition: None, + payload, + } +} + +fn unused_fence_ports() -> [u16; 3] { + // Lifetime fence candidates must be dynamic ports (49152 and above). + let mut listeners = Vec::new(); + for port in (49_152..=u16::MAX).rev() { + if let Ok(listener) = std::net::TcpListener::bind(("127.0.0.1", port)) { + listeners.push(listener); + if listeners.len() == 3 { + break; + } + } + } + let ports = listeners + .iter() + .map(|listener| listener.local_addr().unwrap().port()) + .collect::>(); + [ports[0], ports[1], ports[2]] +} + +#[test] +fn a_refused_reload_of_a_suspended_session_names_the_saved_state_incompatible() { + let fixture = Fixture::new("incompatible-suspended"); + fixture.suspended(); + fixture.reject_open("recovering", INCOMPATIBLE); + let mut restored = fixture.executor(); + let error = restored + .execute(&command(4, "session.snapshot", json!({}))) + .expect_err("the provider refused to reload the saved conversation"); + assert_eq!( + error.classification(), + Some(PROVIDER_STATE_INCOMPATIBLE), + "{error}" + ); + // The refusal is deterministic: the same runner reports the same class. + let repeated = restored + .execute(&command(5, "session.open", json!({}))) + .unwrap_err(); + assert_eq!(repeated.classification(), Some(PROVIDER_STATE_INCOMPATIBLE)); +} + +#[test] +fn a_refused_reload_of_a_lost_turn_names_the_saved_state_incompatible() { + let fixture = Fixture::new("incompatible-lost-turn"); + let mut original = fixture.opened(); + let started = original + .execute(&command( + 3, + "turn.start", + json!({"turnId": "provider-turn-1", "text": "Do the work."}), + )) + .unwrap(); + assert_eq!(started.result["status"], "accepted"); + drop(original); + fixture.reject_open("recovering", INCOMPATIBLE); + let mut restored = fixture.executor(); + let error = restored + .execute(&command(4, "session.snapshot", json!({}))) + .expect_err("the provider refused to reload the lost turn's conversation"); + assert_eq!( + error.classification(), + Some(PROVIDER_STATE_INCOMPATIBLE), + "{error}" + ); +} + +/// Antigravity never restarts its provider at the end of a turn (the +/// turn-end generation restart is Claude-only), so a provider lost between +/// turns is reopened by the next `turn.start`. A refusal to reload the saved +/// conversation there is named the same way, never a generic closed session. +#[test] +fn a_refused_reload_at_the_next_turn_start_names_the_saved_state_incompatible() { + let fixture = Fixture::new("incompatible-next-turn"); + fixture.suspended(); + fixture.reject_open("recovering", INCOMPATIBLE); + let mut restored = fixture.executor(); + let error = restored + .execute(&command( + 4, + "turn.start", + json!({"turnId": "provider-turn-2", "text": "Continue the work."}), + )) + .expect_err("the provider refused to reload the saved conversation"); + assert_eq!( + error.classification(), + Some(PROVIDER_STATE_INCOMPATIBLE), + "{error}" + ); +} + +#[test] +fn another_reload_refusal_keeps_its_ordinary_failure() { + let fixture = Fixture::new("incompatible-other-code"); + fixture.suspended(); + fixture.reject_open("recovering", "ACPX_PERSISTED_SESSION_MISSING"); + let mut restored = fixture.executor(); + let error = restored + .execute(&command(4, "session.snapshot", json!({}))) + .unwrap_err(); + assert_ne!( + error.classification(), + Some(PROVIDER_STATE_INCOMPATIBLE), + "{error}" + ); +} + +#[test] +fn a_fresh_open_with_the_same_code_is_not_named_incompatible() { + let fixture = Fixture::new("incompatible-fresh-open"); + fixture.reject_open("any", INCOMPATIBLE); + let mut executor = fixture.executor(); + executor + .execute(&command( + 1, + "run.prepare", + json!({"provider": fixture.descriptor}), + )) + .unwrap(); + let error = executor + .execute(&command(2, "session.open", json!({}))) + .unwrap_err(); + assert!( + error.to_string().contains("failed to start ACPX provider"), + "{error}" + ); + assert_ne!( + error.classification(), + Some(PROVIDER_STATE_INCOMPATIBLE), + "{error}" + ); +} diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs index 6f37fd0faa1..b72b30952e4 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs @@ -178,7 +178,13 @@ fn acpx_config(state_dir: &Path, mode: &str) -> DurableRunnerConfig { config } -#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +#[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) +))] fn candidate_fixture(directory: &Path) -> (DurableRunnerConfig, Value) { use paperclip_runner_core::acpx_candidate_admission::AcpxCandidateAdmission; let profiles: Value = @@ -186,11 +192,18 @@ fn candidate_fixture(directory: &Path) -> (DurableRunnerConfig, Value) { let distributions: Value = serde_json::from_str(include_str!("../../../../antigravity-distributions.json")).unwrap(); let profile = &profiles["profiles"]["antigravity"]; + let (platform, architecture) = if cfg!(target_os = "macos") { + ("darwin", "arm64") + } else if cfg!(target_arch = "x86_64") { + ("linux", "x64") + } else { + ("linux", "arm64") + }; let admission = AcpxCandidateAdmission::parse_json(&json!({ "schema":"paperclip.acpx-candidate-admission.v1", "companyId":"company-1", "agent":"antigravity", "model":"explicit-test-model", "profileDigest":profile["commandDigest"], - "nativeClosureDigest":format!("sha256:{}",distributions["platforms"]["darwin-arm64"]["closureSha256"].as_str().unwrap()), - "platform":"darwin", "architecture":"arm64", "expiresAt":SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64 + 60_000, + "nativeClosureDigest":format!("sha256:{}",distributions["platforms"][format!("{platform}-{architecture}")]["closureSha256"].as_str().unwrap()), + "platform":platform, "architecture":architecture, "expiresAt":SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64 + 60_000, "runId":"run-1", "normalizedSessionId":"session-1" }).to_string()).unwrap(); let mut config = acpx_config(directory, "turns-reserved-result-terminal"); @@ -214,7 +227,13 @@ fn candidate_fixture(directory: &Path) -> (DurableRunnerConfig, Value) { } #[test] -#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +#[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) +))] fn candidate_cannot_change_provider_kind_or_adopt_prior_activation() { let directory = temporary_directory("candidate-provider-authority"); let (config, mut payload) = candidate_fixture(&directory); @@ -262,7 +281,13 @@ fn candidate_cannot_change_provider_kind_or_adopt_prior_activation() { } #[test] -#[cfg(all(target_os = "macos", target_arch = "aarch64"))] +#[cfg(any( + all(target_os = "macos", target_arch = "aarch64"), + all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "aarch64") + ) +))] fn candidate_verified_cold_session_retires_on_suspend_instead_of_warm_adoption() { let directory = temporary_directory("candidate-cold-session"); let (config, payload) = candidate_fixture(&directory); diff --git a/packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.mjs b/packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.mjs new file mode 100644 index 00000000000..5130c5bbaaf --- /dev/null +++ b/packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.mjs @@ -0,0 +1,168 @@ +import assert from "node:assert/strict"; +import { once } from "node:events"; +import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { performance } from "node:perf_hooks"; +import { pathToFileURL } from "node:url"; + +export const ANTIGRAVITY_SMOKE_MODEL = "gemini-3.8-flash-low"; +const SMOKE_INSTRUCTIONS = "Paperclip installed-package smoke: no prompt is sent.\n"; + +/** Exactly one inventory carries Antigravity: candidates while pending, providers after the flip. */ +export function assertAntigravityProviderPackInventory(manifest, profile, pins, platform = process.platform, architecture = process.arch) { + assert.equal(manifest.schema, "paperclip-runner/remote-provider-pack/v1"); + assert.deepEqual(manifest.payload.target, { platform, architecture }); + const target = `${platform}-${architecture}`; + assert.equal(target, "linux-x64", "Antigravity provider packs target only linux-x64"); + const pending = profile.qualificationStatus === "pending"; + const identity = pending ? manifest.payload.candidateProviders?.antigravity : manifest.payload.providers?.antigravity; + assert.equal(pending ? manifest.payload.providers?.antigravity : manifest.payload.candidateProviders?.antigravity, undefined, + "Antigravity must not appear in both pack inventories"); + assert.ok(identity, "Antigravity is missing from the pack inventory its release state requires"); + assert.deepEqual(Object.keys(identity).sort(), ["closureDigest", "path", "profileDigest", "qualification", "sha256", "version"]); + assert.equal(identity.qualification, pending ? "pending" : "qualified"); + assert.equal(identity.version, profile.agentServerVersion); + assert.equal(identity.path, `provider-assets/antigravity/${target}`); + assert.equal(identity.profileDigest, profile.commandDigest); + assert.match(pins[target]?.closureSha256 ?? "", /^[a-f0-9]{64}$/); + assert.equal(identity.closureDigest, `sha256:${pins[target].closureSha256}`); + assert.match(identity.sha256, /^sha256:[a-f0-9]{64}$/); + return identity; +} + +/** + * 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. + */ +export async function smokeAntigravityProviderPack(directory, { apiKey, model = ANTIGRAVITY_SMOKE_MODEL } = {}) { + const started = performance.now(); + const elapsed = from => Math.round(performance.now() - from); + const pack = await realpath(resolve(directory)); + const manifest = JSON.parse(await readFile(join(pack, "provider-pack.json"), "utf8")); + assert.equal(manifest.payload.target.platform, process.platform); + assert.equal(manifest.payload.target.architecture, process.arch); + 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([ + load("antigravity-installation.js"), load("qualified-profiles.js"), load("generated-profiles.js"), + load("candidate-admission.js"), load("antigravity-process.js"), load("antigravity-admission.js"), + ]); + const release = QUALIFIED_ACPX_PROFILES.antigravity; + const provider = assertAntigravityProviderPackInventory(manifest, release, ANTIGRAVITY_DISTRIBUTION_PINS); + const profile = resolveQualifiedAcpxProfile("antigravity", model); + const target = `${process.platform}-${process.arch}`; + const admission = release.qualificationStatus === "pending" ? bindAcpxCandidateAdmission({ + schema: "paperclip.acpx-candidate-admission.v1", companyId: "provider-pack-smoke", agent: "antigravity", model, + profileDigest: release.commandDigest, nativeClosureDigest: `sha256:${ANTIGRAVITY_DISTRIBUTION_PINS[target].closureSha256}`, + platform: process.platform, architecture: process.arch, expiresAt: Date.now() + 10 * 60_000, + }, { runId: "provider-pack-smoke", normalizedSessionId: "provider-pack-smoke" }) : undefined; + const keys = ["PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT", "PAPERCLIP_ACPX_PROVIDER_PACKAGE_MANIFEST"]; + const previous = keys.map(key => process.env[key]); + process.env[keys[0]] = pack; process.env[keys[1]] = join(pack, "package.json"); + const root = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-pack-smoke-"))); + const home = join(root, "home"), workspace = join(root, "workspace"); + await mkdir(home, { mode: 0o700 }); await mkdir(workspace, { mode: 0o700 }); + const timings = {}; + let lease, child, closed; + try { + let phase = performance.now(); + const installation = await verifyAntigravityInstallation(profile, admission); + 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(); + phase = performance.now(); + child = lease.spawn([], { cwd: workspace, stdio: "pipe", env }); + closed = once(child, "close").then(() => undefined); + const pending = new Map(); + let buffer = "", bytes = 0, sequence = 0; + const fail = error => { for (const request of pending.values()) request.reject(error); pending.clear(); }; + child.on("error", fail); child.on("close", () => fail(new Error("Antigravity exited with a pending ACP request"))); + child.stderr.resume(); + child.stdout.on("data", chunk => { + bytes += chunk.length; + if (bytes > 4 * 1024 * 1024) { fail(new Error("Antigravity ACP output exceeded its package smoke bound")); return; } + buffer += chunk.toString("utf8"); + let newline; + while ((newline = buffer.indexOf("\n")) >= 0) { + 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); + if (request && value.method === undefined) { + pending.delete(value.id); + if (value.error) request.reject(new Error(`Antigravity rejected ACP request (${value.error.code})`)); + else request.resolve(value.result); + } + } + }); + const request = (method, params, timeoutMs) => new Promise((accept, reject) => { + const id = sequence++; + const message = { jsonrpc: "2.0", id, method, params }; + 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?.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); + let session = null; + if (apiKey) { + phase = performance.now(); + const created = await request("session/new", { cwd: workspace, mcpServers: [] }, 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 }; + } + phase = performance.now(); + await retireAntigravityProcess(child, closed); + child = undefined; + await lease.close(); + lease = undefined; + timings.closeMs = elapsed(phase); + 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, + providerPrompts: 0, providerCredentials: Boolean(apiKey) }; + } finally { + try { + if (child) await retireAntigravityProcess(child, closed).catch(() => undefined); + if (lease) await lease.close().catch(() => undefined); + } finally { + keys.forEach((key, index) => { if (previous[index] === undefined) delete process.env[key]; else process.env[key] = previous[index]; }); + await rm(root, { recursive: true, force: true }); + } + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + const [directory, mode] = process.argv.slice(2); + if (!directory || process.argv.length > 4 || (mode !== undefined && mode !== "--session")) { + throw new Error("Usage: node scripts/antigravity-provider-pack-smoke.mjs /absolute/installed-provider-pack [--session] (--session reads GEMINI_API_KEY)"); + } + if (mode && !process.env.GEMINI_API_KEY) throw new Error("--session requires GEMINI_API_KEY"); + smokeAntigravityProviderPack(directory, { apiKey: mode ? process.env.GEMINI_API_KEY : undefined, model: process.env.PAPERCLIP_ANTIGRAVITY_SMOKE_MODEL || undefined }) + .then(result => console.log(JSON.stringify(result))).catch(error => { console.error(error.message); process.exitCode = 1; }); +} diff --git a/packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.test.mjs b/packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.test.mjs new file mode 100644 index 00000000000..0a188da8ccc --- /dev/null +++ b/packages/paperclip-runner/scripts/antigravity-provider-pack-smoke.test.mjs @@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { readFileSync } from "node:fs"; +import { assertAntigravityProviderPackInventory } from "./antigravity-provider-pack-smoke.mjs"; +import profiles from "../acpx-profiles.json" with { type: "json" }; +import distributions from "../antigravity-distributions.json" with { type: "json" }; + +const pins = Object.fromEntries(Object.entries(distributions.platforms).filter(([, platform]) => platform.provisioning === "verified-closure") + .map(([target, platform]) => [target, { closureSha256: platform.closureSha256 }])); +const released = () => { const { qualificationStatus: _pending, ...profile } = profiles.profiles.antigravity; return profile; }; + +function fixture(profile, target = "linux-x64") { + const [platform, architecture] = target.split("-"); + const pending = profile.qualificationStatus === "pending"; + return { schema: "paperclip-runner/remote-provider-pack/v1", payload: { target: { platform, architecture }, + [pending ? "candidateProviders" : "providers"]: { antigravity: { version: profile.agentServerVersion, + qualification: pending ? "pending" : "qualified", profileDigest: profile.commandDigest, + closureDigest: `sha256:${pins[target].closureSha256}`, path: `provider-assets/antigravity/${target}`, sha256: `sha256:${"a".repeat(64)}` } } } }; +} + +for (const [name, profile, inventory, other] of [ + ["pending", profiles.profiles.antigravity, "candidateProviders", "providers"], + ["released", released(), "providers", "candidateProviders"], +]) { + test(`${name} smoke accepts only the ${inventory} entry with the patched linux-x64 closure`, () => { + const manifest = fixture(profile); + assert.equal(assertAntigravityProviderPackInventory(manifest, profile, pins, "linux", "x64"), manifest.payload[inventory].antigravity); + for (const change of [{ closureDigest: `sha256:${distributions.platforms["linux-x64"].vendorClosureSha256}` }, + { closureDigest: `sha256:${pins["darwin-arm64"].closureSha256}` }, { profileDigest: `sha256:${"b".repeat(64)}` }, + { version: "1.4.3" }, { qualification: inventory === "providers" ? "pending" : "qualified" }, + { path: "provider-assets/antigravity/linux-arm64" }, { sha256: "stale" }, { executable: "agy_acp_server.par" }]) { + const invalid = structuredClone(manifest); Object.assign(invalid.payload[inventory].antigravity, change); + assert.throws(() => assertAntigravityProviderPackInventory(invalid, profile, pins, "linux", "x64")); + } + const both = structuredClone(manifest); both.payload[other] = { antigravity: both.payload[inventory].antigravity }; + assert.throws(() => assertAntigravityProviderPackInventory(both, profile, pins, "linux", "x64"), /both pack inventories/); + const moved = structuredClone(manifest); moved.payload[other] = moved.payload[inventory]; delete moved.payload[inventory]; + assert.throws(() => assertAntigravityProviderPackInventory(moved, profile, pins, "linux", "x64")); + }); +} + +test("smoke refuses every target other than linux-x64", () => { + for (const target of ["darwin-arm64", "linux-arm64"]) { + const [platform, architecture] = target.split("-"); + assert.throws(() => assertAntigravityProviderPackInventory(fixture(profiles.profiles.antigravity, target), profiles.profiles.antigravity, pins, platform, architecture), /only linux-x64/); + } +}); + +test("the actual builder smokes Antigravity in either inventory before replacing the retained pack", async () => { + const source = readFileSync(new URL("./build-provider-pack.mjs", import.meta.url), "utf8"); + const begin = source.indexOf(" if (payload.providers?.antigravity || payload.candidateProviders?.antigravity) {"); + const end = source.indexOf("\n} finally {", begin); + assert.ok(begin > 0 && end > begin); + const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; + const run = new AsyncFunction("payload", "smokeAntigravityProviderPack", "temporaryRoot", "outputRoot", "process", "rmSync", "renameSync", source.slice(begin, end)); + for (const payload of [{ candidateProviders: { antigravity: {} } }, { providers: { antigravity: {} } }]) { + for (const failed of [false, true]) { + const order = []; + const smoke = async (root, options) => { + assert.equal(root, "/owned/temporary"); assert.equal(options, undefined, "the build smoke is credential-free"); + order.push("smoke"); if (failed) throw Error("smoke failed"); return { providerPrompts: 0 }; + }; + const work = run(payload, smoke, "/owned/temporary", "/owned/output", { stdout: { write() {} } }, () => order.push("remove-old"), () => order.push("publish")); + if (failed) { await assert.rejects(work, /smoke failed/); assert.deepEqual(order, ["smoke"]); } + else { await work; assert.deepEqual(order, ["smoke", "remove-old", "publish"]); } + } + } + let calls = 0; + await run({ providers: {} }, () => { calls++; }, "/owned/temporary", "/owned/output", { stdout: { write() {} } }, () => {}, () => {}); + assert.equal(calls, 0); +}); diff --git a/packages/paperclip-runner/scripts/build-provider-pack.mjs b/packages/paperclip-runner/scripts/build-provider-pack.mjs index 50c9b204a5a..312e3dba465 100644 --- a/packages/paperclip-runner/scripts/build-provider-pack.mjs +++ b/packages/paperclip-runner/scripts/build-provider-pack.mjs @@ -19,8 +19,9 @@ import { tmpdir } from "node:os"; import { dirname, join, relative, resolve } from "node:path"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; -import { parseProviderPackArguments, materializeCandidateProviderPack, providerPackProviders, providerPackManifestFields } from "./candidate-provider-pack.mjs"; +import { parseProviderPackArguments, materializeCandidateProviderPack, providerPackProviders, providerPackManifestFields, providerPackQualification } from "./candidate-provider-pack.mjs"; import { smokeKimiProviderPack } from "./kimi-provider-pack-smoke.mjs"; +import { smokeAntigravityProviderPack } from "./antigravity-provider-pack-smoke.mjs"; import { buildNodeStartupTimeout } from "./build-node-startup-timeout.mjs"; import { writePortableExecutableShim, writePortableCopilotShims } from "./provider-pack-executable-shims.mjs"; import { providerPackLibc, removeControllerArtifactsFromProviderPack, removeForeignLibcPackagesFromProviderPack, sha256Tree } from "./provider-pack-runtime-tree.mjs"; @@ -154,7 +155,7 @@ try { || !/^sha256:[a-f0-9]{64}$/.test(metadata.profileDigest) || !/^sha256:[a-f0-9]{64}$/.test(metadata.closureDigest)) throw new Error("Candidate builder omitted its pinned identity"); candidateProviders[provider] = { version: metadata.version, profileDigest: metadata.profileDigest, - closureDigest: metadata.closureDigest, qualification: ["pi", "cursor", "copilot"].includes(provider) || provider === "kimi" && profiles.profiles.kimi.qualificationStatus !== "pending" ? "qualified" : "pending", path: assetPath, + closureDigest: metadata.closureDigest, qualification: providerPackQualification(provider), path: assetPath, sha256: sha256Tree(join(temporaryRoot, assetPath)) }; } @@ -372,6 +373,12 @@ try { const smoke = await smokeKimiProviderPack(temporaryRoot); process.stdout.write(`${JSON.stringify(smoke)}\n`); } + // Credential-free: the packaged closure starts and advertises its native + // admission patch. It sends no authentication, session or prompt request. + if (payload.providers?.antigravity || payload.candidateProviders?.antigravity) { + const smoke = await smokeAntigravityProviderPack(temporaryRoot); + process.stdout.write(`${JSON.stringify(smoke)}\n`); + } rmSync(outputRoot, { recursive: true, force: true }); renameSync(temporaryRoot, outputRoot); diff --git a/packages/paperclip-runner/scripts/candidate-provider-pack.mjs b/packages/paperclip-runner/scripts/candidate-provider-pack.mjs index 8376251cb35..46c7cde02c9 100644 --- a/packages/paperclip-runner/scripts/candidate-provider-pack.mjs +++ b/packages/paperclip-runner/scripts/candidate-provider-pack.mjs @@ -1,22 +1,40 @@ import { materializePiDistribution } from "./materialize-pi-distribution.mjs"; import profiles from "../acpx-profiles.json" with { type: "json" }; import { materializePinnedCursorDistribution } from "./materialize-cursor-distribution.mjs"; -const CANDIDATES = new Set(["cursor", "copilot", "pi", "kimi"]); +const CANDIDATES = new Set(["cursor", "copilot", "pi", "kimi", "antigravity"]); const releasedKimi = () => profiles.profiles.kimi.qualificationStatus !== "pending"; -const ordinaryProviders = () => ["pi", "cursor", "copilot", ...(releasedKimi() ? ["kimi"] : [])]; +// The flip to an ordinary provider is the profile's qualificationStatus alone. +const releasedAntigravity = () => profiles.profiles.antigravity.qualificationStatus !== "pending"; +// Remote packs carry Antigravity only for the Daytona image target. +export const ANTIGRAVITY_PACK_TARGETS = Object.freeze(["linux-x64"]); +const ordinaryProviders = () => ["pi", "cursor", "copilot", ...(releasedKimi() ? ["kimi"] : []), ...(releasedAntigravity() ? ["antigravity"] : [])]; +const ordinaryOnly = provider => provider === "copilot" || (provider === "kimi" && releasedKimi()) || (provider === "antigravity" && releasedAntigravity()); + +/** The manifest qualification the server admits for each materialized provider. */ +export function providerPackQualification(provider) { + return ["pi", "cursor", "copilot"].includes(provider) || ordinaryOnly(provider) ? "qualified" : "pending"; +} /** Only materialized providers enter the serialized manifest and its digest. */ export function providerPackManifestFields(providers, candidates) { + const ordinary = ordinaryProviders().filter(provider => providers[provider]); + const candidate = [...new Set(["pi", ...candidates])].filter(provider => !ordinaryOnly(provider) && providers[provider]); return { - ...(ordinaryProviders().some(provider => providers[provider]) ? { providers: Object.fromEntries(ordinaryProviders().filter(provider => providers[provider]).map(provider => [provider, providers[provider]])) } : {}), - ...(["pi", ...candidates].some(provider => provider !== "copilot" && !(provider === "kimi" && releasedKimi()) && providers[provider]) ? { candidateProviders: Object.fromEntries([...new Set(["pi", ...candidates])].filter(provider => provider !== "copilot" && !(provider === "kimi" && releasedKimi()) && providers[provider]).map(provider => [provider, providers[provider]])) } : {}), + ...(ordinary.length ? { providers: Object.fromEntries(ordinary.map(provider => [provider, providers[provider]])) } : {}), + ...(candidate.length ? { candidateProviders: Object.fromEntries(candidate.map(provider => [provider, providers[provider]])) } : {}), }; } export function providerPackProviders(platform, architecture, candidates) { - const nativeSupported = ["darwin-arm64", "darwin-x64", "linux-x64"].includes(`${platform}-${architecture}`); - const kimiSupported = ["darwin-arm64", "linux-x64"].includes(`${platform}-${architecture}`); - return [...new Set([...(nativeSupported ? ["pi", "cursor", "copilot"] : []), ...(releasedKimi() && kimiSupported ? ["kimi"] : []), ...candidates])]; + const target = `${platform}-${architecture}`; + const nativeSupported = ["darwin-arm64", "darwin-x64", "linux-x64"].includes(target); + const kimiSupported = ["darwin-arm64", "linux-x64"].includes(target); + const antigravitySupported = ANTIGRAVITY_PACK_TARGETS.includes(target); + if (candidates.includes("antigravity") && !antigravitySupported) { + throw new Error(`Antigravity provider-pack assets are built only for ${ANTIGRAVITY_PACK_TARGETS.join(", ")}`); + } + return [...new Set([...(nativeSupported ? ["pi", "cursor", "copilot"] : []), ...(releasedKimi() && kimiSupported ? ["kimi"] : []), + ...(releasedAntigravity() && antigravitySupported ? ["antigravity"] : []), ...candidates])]; } export function parseProviderPackArguments(args) { @@ -34,6 +52,35 @@ export function parseProviderPackArguments(args) { return { output, candidates }; } +// The ~274 MB public archive is the only network step of an Antigravity pack +// build. Repeat only a transport failure; an integrity failure is final. +const transientDownload = error => error?.name === "TimeoutError" || error?.name === "AbortError" + || /Antigravity archive download failed: (?:408|429|5\d\d)|fetch failed|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket|terminated/i.test(String(error?.message)); + +/** The PATCHED closure (never the vendor closure) for this build host's target. */ +export async function materializeAntigravityProviderPack({ outputRoot, platform = process.platform, architecture = process.arch, + materialize, attempts = 3, retryDelayMs = 5_000 }) { + if (!ANTIGRAVITY_PACK_TARGETS.includes(`${platform}-${architecture}`)) { + throw new Error(`Antigravity provider-pack assets are built only for ${ANTIGRAVITY_PACK_TARGETS.join(", ")}`); + } + materialize ??= (await import("./materialize-antigravity-distribution.mjs")).materializePinnedAntigravityDistribution; + let result; + for (let attempt = 1; ; attempt++) { + try { result = await materialize({ destination: outputRoot, platform, architecture }); break; } + catch (error) { + if (attempt >= attempts || !transientDownload(error)) throw error; + process.stderr.write(`Antigravity archive download attempt ${attempt} failed; retrying\n`); + await new Promise(resolve => setTimeout(resolve, retryDelayMs * attempt)); + } + } + 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"); + } + return { version: result.version, profileDigest: profile.commandDigest, closureDigest: `sha256:${result.closureSha256}` }; +} + /** Closed source-owned builder registry; provider branches add their exact pins. */ export async function materializeCandidateProviderPack({ provider, outputRoot }) { if (!CANDIDATES.has(provider)) throw new Error("Unknown candidate provider"); @@ -42,6 +89,7 @@ export async function materializeCandidateProviderPack({ provider, outputRoot }) const result = await materializeKimiDistribution({ outputRoot }); return { version: result.version, profileDigest: profiles.profiles.kimi.commandDigest, closureDigest: result.closureDigest }; } + if (provider === "antigravity") return materializeAntigravityProviderPack({ outputRoot }); if (provider === "pi") return materializePiDistribution({ outputRoot }); if (provider === "copilot") { const { buildPinnedCopilotDistribution } = await import("./build-copilot-distribution.mjs"); diff --git a/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs b/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs index 4d914e53cfe..c8148fa66ac 100644 --- a/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs +++ b/packages/paperclip-runner/scripts/candidate-provider-pack.test.mjs @@ -1,6 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { parseProviderPackArguments, materializeCandidateProviderPack, providerPackProviders, providerPackManifestFields } from "./candidate-provider-pack.mjs"; +import { parseProviderPackArguments, materializeCandidateProviderPack, materializeAntigravityProviderPack, providerPackProviders, providerPackManifestFields, providerPackQualification } from "./candidate-provider-pack.mjs"; +import profiles from "../acpx-profiles.json" with { type: "json" }; import { createHash } from "node:crypto"; async function withCopilotTestPlatform(run) { @@ -115,3 +116,74 @@ test("Pi pack selection reaches its pinned builder and rejects unsafe output bef await assert.rejects(materializeCandidateProviderPack({ provider: "pi", outputRoot: "relative-pi-output" }), /Pi distribution output must be absolute/); assert.equal(requests, 0); }); + +test("pending Antigravity is an explicit linux-x64 candidate and never an ordinary provider", () => { + const antigravity = { version: "1.5.2", qualification: "pending", profileDigest: "sha256:profile", closureDigest: "sha256:closure" }; + assert.equal(profiles.profiles.antigravity.qualificationStatus, "pending"); + assert.deepEqual(parseProviderPackArguments(["/pack", "--candidate-providers=antigravity"]), { output: "/pack", candidates: ["antigravity"] }); + assert.equal(providerPackProviders("linux", "x64", []).includes("antigravity"), false); + assert.equal(providerPackProviders("linux", "x64", ["antigravity"]).filter(provider => provider === "antigravity").length, 1); + for (const [platform, architecture] of [["darwin", "arm64"], ["darwin", "x64"], ["linux", "arm64"], ["win32", "x64"]]) { + assert.equal(providerPackProviders(platform, architecture, []).includes("antigravity"), false); + assert.throws(() => providerPackProviders(platform, architecture, ["antigravity"]), /only for linux-x64/); + } + assert.equal(providerPackQualification("antigravity"), "pending"); + const fields = providerPackManifestFields({ antigravity }, ["antigravity"]); + assert.deepEqual(fields.candidateProviders, { antigravity }); + assert.equal(fields.providers?.antigravity, undefined); + assert.equal(providerPackManifestFields({ antigravity }, []).candidateProviders?.antigravity, undefined); + assert.equal(digest(JSON.parse(JSON.stringify(fields))), digest(fields)); +}); + +test("released Antigravity flips to ordinary linux-x64 inventory with its profile status alone", () => { + const antigravity = { version: "1.5.2", qualification: "qualified", profileDigest: "sha256:profile", closureDigest: "sha256:closure" }; + const original = profiles.profiles.antigravity.qualificationStatus; + try { + delete profiles.profiles.antigravity.qualificationStatus; + assert.equal(providerPackProviders("linux", "x64", []).filter(provider => provider === "antigravity").length, 1); + assert.equal(providerPackProviders("linux", "x64", ["antigravity"]).filter(provider => provider === "antigravity").length, 1); + for (const [platform, architecture] of [["darwin", "arm64"], ["linux", "arm64"]]) { + assert.equal(providerPackProviders(platform, architecture, []).includes("antigravity"), false); + } + assert.equal(providerPackQualification("antigravity"), "qualified"); + for (const candidates of [[], ["antigravity"]]) { + const fields = providerPackManifestFields({ antigravity }, candidates); + assert.equal(fields.providers.antigravity, antigravity); + assert.equal(fields.candidateProviders?.antigravity, undefined); + } + } finally { profiles.profiles.antigravity.qualificationStatus = original; } +}); + +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" }; + 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(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" }]) { + await assert.rejects(materializeAntigravityProviderPack({ outputRoot: "/pack", platform: "linux", architecture: "x64", materialize: build({ ...distribution, ...wrong }) }), + /patched runtime closure/); + } + calls.length = 0; + await assert.rejects(materializeAntigravityProviderPack({ outputRoot: "/pack", platform: "darwin", architecture: "arm64", materialize: build(distribution) }), /only for linux-x64/); + assert.equal(calls.length, 0); +}); + +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" }; + 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 }); + assert.equal(result.closureDigest, `sha256:${"a".repeat(64)}`); + assert.equal(attempts, 3); + attempts = 0; + const tampered = async () => { attempts++; throw new Error("Antigravity archive digest mismatch"); }; + await assert.rejects(materializeAntigravityProviderPack({ outputRoot: "/pack", platform: "linux", architecture: "x64", materialize: tampered, retryDelayMs: 1 }), /digest mismatch/); + assert.equal(attempts, 1); + attempts = 0; + const down = async () => { attempts++; throw new TypeError("fetch failed"); }; + await assert.rejects(materializeAntigravityProviderPack({ outputRoot: "/pack", platform: "linux", architecture: "x64", materialize: down, retryDelayMs: 1 }), /fetch failed/); + assert.equal(attempts, 3); +}); diff --git a/packages/paperclip-runner/scripts/generate-acpx-profiles.mjs b/packages/paperclip-runner/scripts/generate-acpx-profiles.mjs index 8f65f62dff3..bf33a1188a9 100644 --- a/packages/paperclip-runner/scripts/generate-acpx-profiles.mjs +++ b/packages/paperclip-runner/scripts/generate-acpx-profiles.mjs @@ -55,6 +55,8 @@ assert.equal(manifest.profiles.antigravity.agentServerVersion, antigravityDistri for (const distribution of Object.values(distributions.platforms)) assert.match(distribution.closureSha256, /^[a-f0-9]{64}$/); const quote = JSON.stringify; +const antigravityVerified = Object.entries(antigravityDistributions.platforms).filter(([, pin]) => pin.provisioning === "verified-closure"); +for (const [target] of antigravityVerified) assert.match(target, /^(darwin|linux)-(arm64|x64)$/); const profiles = Object.fromEntries(entries.map(([agent, declaration]) => { const { requiresProviderPolicy, ...runtime } = declaration; return [agent, { @@ -63,7 +65,7 @@ const profiles = Object.fromEntries(entries.map(([agent, declaration]) => { permissionPolicy: "interactive", }]; })); -const header = "Generated from acpx-profiles.json and cursor-distributions.json. Do not edit."; +const header = "Generated from acpx-profiles.json, cursor-distributions.json and antigravity-distributions.json. Do not edit."; const typescript = `// ${header} export const QUALIFIED_ACPX_VERSION = ${quote(manifest.acpxVersion)} as const; export const ACPX_DRIVER_KIND = ${quote(manifest.driverKind)} as const; @@ -73,7 +75,9 @@ export const QUALIFIED_ACPX_PROFILE_DATA = ${JSON.stringify(profiles, null, 2)} export const CURSOR_DISTRIBUTION_PINS = ${JSON.stringify(Object.fromEntries(Object.entries(distributions.platforms).map(([platform, { closureSha256, executable, entrypoint }]) => [platform, { closureSha256, executable, entrypoint }])), null, 2)} as const; -export const ANTIGRAVITY_DISTRIBUTION_PINS = ${JSON.stringify(Object.fromEntries(Object.entries(antigravityDistributions.platforms).filter(([, pin]) => pin.provisioning === "verified-closure").map(([platform, { closureSha256, executable, args }]) => [platform, { closureSha256, executable, args }])), null, 2)} as const; +export const ANTIGRAVITY_RUNTIME_VERSION = ${quote(antigravityDistributions.version)} as const; + +export const ANTIGRAVITY_DISTRIBUTION_PINS = ${JSON.stringify(Object.fromEntries(antigravityVerified.map(([platform, { closureSha256, executable, args }]) => [platform, { closureSha256, executable, args }])), null, 2)} as const; `; const option = value => value === null ? "None" : `Some(${quote(value)})`; const rust = `// ${header} @@ -98,6 +102,16 @@ ${Object.entries(KIMI_DISTRIBUTION_CLOSURE_SHA256).map(([target, digest]) => { c } } +pub(crate) fn antigravity_native_closure( + platform: &str, + architecture: &str, +) -> Option<&'static str> { + match (platform, architecture) { +${antigravityVerified.map(([target, { closureSha256 }]) => { const [platform, architecture] = target.split("-"); return ` (${quote(platform)}, ${quote(architecture)}) => {\n Some(${quote(closureSha256)})\n }`; }).join("\n")} + _ => None, + } +} + pub(crate) fn acpx_release_profile(agent: &str) -> Option { Some(match agent { ${entries.map(([agent, p]) => ` ${quote(agent)} => AcpxReleaseProfile { diff --git a/packages/paperclip-runner/scripts/generate-antigravity-models.mjs b/packages/paperclip-runner/scripts/generate-antigravity-models.mjs new file mode 100644 index 00000000000..3bf621f7f82 --- /dev/null +++ b/packages/paperclip-runner/scripts/generate-antigravity-models.mjs @@ -0,0 +1,268 @@ +#!/usr/bin/env node +/** + * Derives the Google Antigravity model catalog from the pinned 1.5.2 runtime. + * + * Generation (on a host with the pinned closure installed) does two reads and + * requires them to agree: + * - live: the real patched runtime is started without a credential or prompt, + * authenticated with `gemini-api-key` (the server does not validate the key + * and builds that catalog locally), and one session lists its models; + * - static: the server's built-in catalog table, read from the verified + * vendor archive, supplies every family's levels, including the Gemini 4 + * families the server lists only for Agent Platform. + * The output is bound to the runtime version and the vendor archive identity. + * `--check` needs no runtime: it rejects a hand-edited file and a file whose + * binding no longer matches the checked-in distribution declaration. + */ +import { spawn } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { inflateRawSync } from "node:zlib"; + +const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); +const DISTRIBUTIONS_PATH = join(PACKAGE_ROOT, "antigravity-distributions.json"); +export const ANTIGRAVITY_MODELS_OUTPUT = resolve(PACKAGE_ROOT, "../shared/src/antigravity-models.generated.ts"); +const SOURCE_PLATFORM = "darwin-arm64"; +const SCHEMA = "paperclip.antigravity.model_catalog.v1"; +const MODEL_SELECTION_SOURCE = "google3/cloud/developer_experience/antigravity_extensions/acp_server/model_selection.py"; +const LEVELS = { MINIMAL: "minimal", LOW: "low", MEDIUM: "medium", HIGH: "high", EXTRA_HIGH: "extra_high" }; +/** Not a credential: the server stores it without a network call, and no prompt is sent. */ +const PLACEHOLDER_API_KEY = "paperclip-catalog-probe-sends-no-prompt"; +const BEGIN = "/* BEGIN GENERATED CATALOG */"; +const END = "/* END GENERATED CATALOG */"; +const fail = message => { throw new Error(`Antigravity model catalog: ${message}`); }; + +/** Reads the families from `DEFAULT_MODEL_METADATA_MAP` in the server's own source. + * Every entry must be a `_thinking_family(...)` call this parser fully understands. */ +export function parseAntigravityCatalogSource(source) { + const tuples = new Map(); + for (const match of source.matchAll(/^(_[A-Z_]+) = \(\s*([^)]*?)\s*\)$/gm)) { + tuples.set(match[1], parseLevels(match[2])); + } + const start = source.indexOf("\nDEFAULT_MODEL_METADATA_MAP = {\n"); + const end = source.indexOf("\n}\n", start); + if (start < 0 || end < 0) fail("the built-in catalog table was not found"); + const body = source.slice(start + "\nDEFAULT_MODEL_METADATA_MAP = {\n".length, end); + const code = body.split("\n").filter(line => !line.trim().startsWith("#")).join("\n").trim(); + const calls = code.split(/\*\*_thinking_family\(/).map(part => part.trim()).filter(Boolean); + if (!code.startsWith("**_thinking_family(")) fail("the built-in catalog has an entry this generator does not understand"); + const families = calls.map(call => { + const strings = [...call.matchAll(/^\s*"([^"]+)",\s*$/gm)].map(match => match[1]); + if (strings.length !== 2) fail("a catalog family has an unexpected shape"); + const [id, label] = strings; + let levels; + const named = call.match(/^\s*(_[A-Z_]+),\s*$/m); + const inline = call.match(/^\s*\(\s*([\s\S]*?)\s*\),\s*$/m); + if (named) levels = tuples.get(named[1]); + else if (inline) levels = parseLevels(inline[1]); + if (!levels?.length) fail(`levels for ${id} were not found`); + const base = call.match(/base_model_id="([^"]+)"/); + const agentPlatformOnly = /agent_platform_only=True/.test(call); + const known = call.replace(/^\s*"[^"]+",\s*$/gm, "").replace(/^\s*_[A-Z_]+,\s*$/m, "").replace(/^\s*\(\s*[\s\S]*?\s*\),\s*$/m, "") + .replace(/max_tokens=[\d_]+,?/, "").replace(/base_model_id="[^"]+",?/, "").replace(/agent_platform_only=True,?/, "").replace(/\),?$/, ""); + if (known.trim()) fail(`${id} has a catalog field this generator does not understand`); + if (!/^[a-z0-9][a-z0-9.-]*$/.test(id) || !label.trim()) fail("invalid family identity"); + return { id, label, baseModelId: base ? base[1] : id, levels, agentPlatformOnly }; + }); + if (new Set(families.map(family => family.id)).size !== families.length) fail("duplicate family"); + return families; +} + +function parseLevels(text) { + const names = text.split(",").map(part => part.trim()).filter(Boolean); + return names.map(name => { + const match = name.match(/^sdk_types_module\.ThinkingLevel\.([A-Z_]+)$/); + if (!match || !Object.hasOwn(LEVELS, match[1])) fail(`unknown thinking level ${name}`); + return LEVELS[match[1]]; + }); +} + +/** Reads one stored or deflated member of the verified ZIP embedded in the server. */ +export function readZipMember(zip, name) { + let end = zip.length - 22; + while (end >= 0 && zip.readUInt32LE(end) !== 0x06054b50) end--; + if (end < 0) fail("embedded archive has no directory"); + let cursor = zip.readUInt32LE(end + 16); + const count = zip.readUInt16LE(end + 10); + for (let index = 0; index < count; index++) { + if (zip.readUInt32LE(cursor) !== 0x02014b50) fail("embedded archive directory is invalid"); + const method = zip.readUInt16LE(cursor + 10), compressed = zip.readUInt32LE(cursor + 20); + const nameLength = zip.readUInt16LE(cursor + 28), extra = zip.readUInt16LE(cursor + 30), comment = zip.readUInt16LE(cursor + 32); + const local = zip.readUInt32LE(cursor + 42); + if (zip.subarray(cursor + 46, cursor + 46 + nameLength).toString("utf8") === name) { + const start = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28); + const data = zip.subarray(start, start + compressed); + return method === 0 ? data : method === 8 ? inflateRawSync(data) : fail("unsupported compression"); + } + cursor += 46 + nameLength + extra + comment; + } + return fail(`${name} is not in the embedded archive`); +} + +/** Minimal line-delimited JSON-RPC client. Provider text never enters errors. */ +function rpcClient(child) { + const waiting = new Map(); + let buffer = "", bytes = 0, failure; + const stop = error => { failure ??= error; for (const { reject } of waiting.values()) reject(failure); waiting.clear(); }; + child.stdout.on("data", chunk => { + bytes += chunk.length; + if (bytes > 4 * 1024 * 1024) { stop(new Error("antigravity_stdout_limit")); return; } + buffer += chunk.toString("utf8"); + while (buffer.includes("\n")) { + const line = buffer.slice(0, buffer.indexOf("\n")); buffer = buffer.slice(buffer.indexOf("\n") + 1); + if (!line.trim()) continue; + let message; + try { message = JSON.parse(line); } catch { stop(new Error("antigravity_malformed_json")); return; } + if (message.method !== undefined) { + // Requests from the agent are refused; notifications are ignored. + if (message.id !== undefined) child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "unsupported" } })}\n`); + continue; + } + const entry = waiting.get(message.id); + if (!entry) continue; + waiting.delete(message.id); + if (message.error) entry.reject(Object.assign(new Error(`antigravity_request_rejected:${entry.method}`), { rpcError: { code: message.error.code, message: String(message.error.message ?? "").slice(0, 300) } })); + else entry.resolve(message.result); + } + }); + child.once("error", () => stop(new Error("antigravity_spawn_failure"))); + child.once("close", () => stop(new Error("antigravity_exited"))); + let next = 1; + return (method, params, timeoutMs = 30_000) => new Promise((resolve, reject) => { + if (failure) { reject(failure); return; } + const id = next++; + const timer = setTimeout(() => { waiting.delete(id); reject(new Error(`antigravity_timeout:${method}`)); }, timeoutMs); + waiting.set(id, { method, resolve: value => { clearTimeout(timer); resolve(value); }, reject: error => { clearTimeout(timer); reject(error); } }); + child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`); + }); +} + +/** + * Starts the pinned patched runtime with only an API-key auth choice, runs + * `steps(request, workspace)` and always stops the process tree. Never sends a + * prompt. + */ +export async function withPromptFreeAntigravitySession(steps) { + const { antigravityDistribution, verifyAntigravityDistribution } = await import("./materialize-antigravity-distribution.mjs"); + const { antigravityRuntimeCachePath } = await import("./antigravity-provisioner-layout.mjs"); + const { antigravityMetadataEnvironment, stopAntigravityMetadataChild } = await import("./probe-antigravity-metadata.mjs"); + const distribution = await antigravityDistribution(); + if (`${distribution.platform}-${distribution.architecture}` !== SOURCE_PLATFORM) fail(`generate on ${SOURCE_PLATFORM}`); + const runtimeDirectory = antigravityRuntimeCachePath(distribution.closureSha256, distribution.platform, distribution.architecture); + await verifyAntigravityDistribution(runtimeDirectory, distribution); + const root = await mkdtemp(join(tmpdir(), "paperclip-antigravity-catalog-")); + let child; + try { + const env = { ...antigravityMetadataEnvironment(root, runtimeDirectory), GEMINI_API_KEY: PLACEHOLDER_API_KEY }; + 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.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"); + await request("authenticate", { methodId: "gemini-api-key" }); + return { distribution, result: await steps(request, workspace) }; + } finally { + await stopAntigravityMetadataChild(child, { eofTimeoutMs: 1_000, terminateTimeoutMs: 1_000, killTimeoutMs: 1_000 }); + await rm(root, { recursive: true, force: true }); + } +} + +/** 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"); + await request("session/close", { sessionId: session.sessionId }).catch(() => undefined); + return { + defaultModelId: models.currentModelId, + models: models.availableModels.map(model => ({ id: model.modelId, label: model.name })), + }; + }); +} + +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}`)); + const liveIds = live.models.map(model => model.id); + if (JSON.stringify(expanded) !== JSON.stringify(liveIds)) fail("the live API-key catalog differs from the built-in table"); + if (!liveIds.includes(live.defaultModelId)) fail("the live default model is not listed"); + const labels = new Map(live.models.map(model => [model.id, model.label])); + for (const family of families) { + for (const level of family.levels) { + const id = `${family.id}-${level}`; + if (labels.has(id) && !labels.get(id).startsWith(`${family.label} (`)) fail(`label for ${id} differs from its family`); + } + } + return { schema: SCHEMA, source: binding, apiKey: { defaultModelId: live.defaultModelId, models: live.models }, families }; +} + +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 }; +} + +export function renderAntigravityModelCatalog(catalog) { + return `// Generated by packages/paperclip-runner/scripts/generate-antigravity-models.mjs from the +// pinned Google Antigravity runtime. Do not edit; regenerate with +// \`node packages/paperclip-runner/scripts/generate-antigravity-models.mjs\` on darwin-arm64. +${BEGIN} +export const ANTIGRAVITY_GENERATED_MODEL_CATALOG = ${JSON.stringify(catalog, null, 2)} as const; +${END} +`; +} + +export function parseRenderedCatalog(text) { + const start = text.indexOf(BEGIN), end = text.indexOf(END); + if (start < 0 || end < 0) fail("generated markers are missing"); + const body = text.slice(start + BEGIN.length, end).trim(); + const match = body.match(/^export const ANTIGRAVITY_GENERATED_MODEL_CATALOG = ([\s\S]*) as const;$/); + if (!match) fail("generated body has an unexpected shape"); + return JSON.parse(match[1]); +} + +/** Static staleness check used by the package build. */ +export async function checkAntigravityModelCatalog({ output = ANTIGRAVITY_MODELS_OUTPUT, declarationPath = DISTRIBUTIONS_PATH } = {}) { + const text = await readFile(output, "utf8"); + const catalog = parseRenderedCatalog(text); + if (renderAntigravityModelCatalog(catalog) !== text) fail("generated file was edited by hand; regenerate it"); + if (catalog.schema !== SCHEMA) fail("unexpected schema"); + const expected = bindingFromDeclaration(JSON.parse(await readFile(declarationPath, "utf8"))); + if (JSON.stringify(catalog.source) !== JSON.stringify(expected)) fail("catalog is stale: the pinned Antigravity runtime changed; regenerate it on darwin-arm64"); + buildAntigravityModelCatalog({ families: catalog.families, live: catalog.apiKey, binding: catalog.source }); + return catalog; +} + +async function main() { + if (process.argv.includes("--check")) { + await checkAntigravityModelCatalog(); + process.stdout.write("Antigravity model catalog is current.\n"); + return; + } + 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 }); + await writeFile(ANTIGRAVITY_MODELS_OUTPUT, renderAntigravityModelCatalog(catalog)); + process.stdout.write(`Wrote ${catalog.apiKey.models.length} API-key models and ${catalog.families.length} families.\n`); +} + +if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { + main().catch(error => { process.stderr.write(`${error.message}\n`); process.exitCode = 1; }); +} diff --git a/packages/paperclip-runner/scripts/materialize-antigravity-distribution.mjs b/packages/paperclip-runner/scripts/materialize-antigravity-distribution.mjs index be9a8cc8e80..ad9ca47d572 100644 --- a/packages/paperclip-runner/scripts/materialize-antigravity-distribution.mjs +++ b/packages/paperclip-runner/scripts/materialize-antigravity-distribution.mjs @@ -9,7 +9,8 @@ import { ANTIGRAVITY_PATCH_VERSION, patchAntigravityRuntime } from "./patch-anti 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)); -const MAX_ARCHIVE_BYTES = 256 * 1024 * 1024; +// 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; export const ANTIGRAVITY_TREE_MANIFEST = ".paperclip-antigravity-closure.json"; const RUNTIME_FILES = ["agy_acp_server.par", "localharness_external"]; @@ -255,10 +256,11 @@ export async function materializePinnedAntigravityDistribution(options = {}) { if (content.length !== entry.size) throw new Error("Antigravity archive entry size mismatch"); await writeFile(join(unpacked, entry.path), content, { mode: 0o500, flag: "wx" }); } + 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 }); + 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); if (closure.sha256 !== distribution.closureSha256) throw new Error("Antigravity full execution closure digest mismatch"); diff --git a/packages/paperclip-runner/scripts/materialize-antigravity-distribution.test.mjs b/packages/paperclip-runner/scripts/materialize-antigravity-distribution.test.mjs index 9f922f72810..3670063b355 100644 --- a/packages/paperclip-runner/scripts/materialize-antigravity-distribution.test.mjs +++ b/packages/paperclip-runner/scripts/materialize-antigravity-distribution.test.mjs @@ -51,7 +51,8 @@ function zip(entries = files) { return Buffer.concat([...locals, central, end]); } -async function fixture(t, { expectedFiles = files, expectedVendorFiles = files, archive = zip(), patchSuffix = "", baseDirectory = tmpdir(), changeParentDuringPatch = false } = {}) { +async function fixture(t, { expectedFiles = files, expectedVendorFiles = files, archive = zip(), patchSuffix = "", baseDirectory = tmpdir(), changeParentDuringPatch = false, 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"); @@ -63,15 +64,15 @@ async function fixture(t, { expectedFiles = files, expectedVendorFiles = files, 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.4.3-paperclip.1'; -export async function patchAntigravityRuntime({source,destination}) { - await writeFile(${JSON.stringify(join(root, "patch.called"))},'called'); +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/darwin-arm64"))},0o777);` : ""} + ${changeParentDuringPatch ? `await chmod(${JSON.stringify(join(root, `home/.paperclip/runtimes/antigravity/${target}`))},0o777);` : ""} return {version:ANTIGRAVITY_PATCH_VERSION,admissionSourceSha256:${JSON.stringify(admissionSourceSha256)}}; } `); @@ -81,11 +82,11 @@ export async function patchAntigravityRuntime({source,destination}) { // 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. await writeFile(join(root, "antigravity-distributions.json"), JSON.stringify({ - schema: "paperclip.antigravity_distribution.v1", version: "1.4.3", - platforms: { "darwin-arm64": { - url: "https://dl.google.com/agy-extensions/releases/macos/fixture.zip", - archiveSha256: hash(archive), closureSha256, vendorEntries, vendorClosureSha256: hash(JSON.stringify(vendorEntries)), patchVersion: "1.4.3-paperclip.1", admissionSourceSha256, provisioning: "verified-closure", - executable: "agy_acp_server.par", args: [], entries, + 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, } }, })); const archivePath = join(root, "fixture.zip"); @@ -93,18 +94,28 @@ export async function patchAntigravityRuntime({source,destination}) { 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/darwin-arm64", closureSha256); - const options = { platform: "darwin", architecture: "arm64", archivePath, destination }; + 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" }); - return { root, destination, options, api, provision, distribution: await api.antigravityDistribution("darwin", "arm64") }; + return { root, destination, options, api, provision, distribution: await api.antigravityDistribution(platform, architecture) }; } -test("the inspected native mac ARM closure is pinned; other platforms remain inventory-only", async () => { - const pin = await antigravityDistribution("darwin", "arm64"); - assert.equal(pin.version, "1.4.3"); - assert.deepEqual(pin.entries.map(entry => entry.path), files.map(entry => entry.path)); - assert.equal(hash(JSON.stringify(pin.entries)), pin.closureSha256); - for (const [platform, architecture] of [["darwin", "x64"], ["linux", "x64"], ["linux", "arm64"]]) await assert.rejects(antigravityDistribution(platform, architecture), /inventory-only/); +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"]]) { + 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="] : []); + } + await assert.rejects(antigravityDistribution("darwin", "x64"), /inventory-only/); await assert.rejects(antigravityDistribution("win32", "x64"), /no pinned distribution/); }); @@ -168,7 +179,7 @@ test("verified vendor bytes are patched and only the separately pinned final clo 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.equal(await readFile(join(root, "patch.called"), "utf8"), "called"); + 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); @@ -322,3 +333,24 @@ test("a parent made replaceable while patching cannot receive a published runtim 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/); + } +}); diff --git a/packages/paperclip-runner/scripts/patch-antigravity-runtime.admission.py b/packages/paperclip-runner/scripts/patch-antigravity-runtime.admission.py index 9b67b239631..48287c18be0 100644 --- a/packages/paperclip-runner/scripts/patch-antigravity-runtime.admission.py +++ b/packages/paperclip-runner/scripts/patch-antigravity-runtime.admission.py @@ -1,8 +1,9 @@ -"""Paperclip-owned admission for the pinned Antigravity 1.4.3 native runtime. +"""Paperclip-owned admission for the pinned Antigravity 1.5.2 native runtime. -Loaded inside Google's hermetic distribution. No credentials or prompt content -are persisted in receipts. Native creation must acknowledge the exact config -before the ACP client receives authority to send a managed prompt. +Loaded inside Google's hermetic distribution on every patched platform. No +credentials or prompt content are persisted in receipts. Native creation must +acknowledge the exact config before the ACP client receives authority to send +a managed prompt. """ import asyncio import contextvars @@ -13,9 +14,16 @@ import hashlib import os import stat import re +import sys import uuid from acp import exceptions +from google.antigravity import types as sdk_types +from google3.cloud.developer_experience.antigravity_extensions.acp_server import api_errors +from google3.cloud.developer_experience.antigravity_extensions.acp_server import browser_subagent +from google3.cloud.developer_experience.antigravity_extensions.acp_server import model_selection +from google3.cloud.developer_experience.antigravity_extensions.acp_server.ccpa_connection import quota_errors +from google3.cloud.developer_experience.antigravity_extensions.acp_server import paperclip_native_identity from google3.cloud.developer_experience.antigravity_extensions.acp_server import request_meta from google3.cloud.developer_experience.antigravity_extensions.acp_server import system_prompt from google3.cloud.developer_experience.antigravity_extensions.acp_server import hooks as acp_hooks @@ -24,11 +32,119 @@ from google3.cloud.developer_experience.antigravity_extensions.acp_server.oauth. SCHEMA = "paperclip.antigravity.admission.v1" MODELS_SCHEMA = "paperclip.antigravity.models.v1" +TURN_FAILURE_SCHEMA = "paperclip.antigravity.turn_failure.v1" _CONTEXT = contextvars.ContextVar("paperclip_antigravity_admission", default=None) +# One managed prompt's provider failure evidence; never shared across turns. +_TURN = contextvars.ContextVar("paperclip_antigravity_turn", default=None) +# 1.5.2 retries model API errors for minutes without any ACP event. A managed +# turn retries briefly (about 14 seconds of backoff) and then fails with a +# classified provider failure that Paperclip's own capacity retry owns. +MANAGED_API_RETRY = {"max_retries": 3, "initial_sleep_duration_ms": 2000, "exponential_multiplier": 2.0} +# Rule files 1.5.2 discovers in the workspace and in the private GEMINI_HOME. +# Workspace rules are repository guidance, as Codex reads AGENTS.md; the +# Paperclip instructions stay the exact, receipted system prompt section. +MANAGED_RULE_FILENAMES = ("GEMINI.md", "AGENTS.md") def _fail(message): - raise exceptions.RequestError(code=-32602, message="Paperclip admission: " + message) + # Structured data names an admission refusal without matching its text. + raise exceptions.RequestError(code=-32602, message="Paperclip admission: " + message, data={"paperclipAdmission": "refused"}) + + +_GO_API_ERROR = re.compile(r"Error (?P\d{3}), Message: (?P.+?), Status: (?P[A-Z_]+)", re.DOTALL) +_ERROR_REASON = re.compile(r"\breason:(?P[A-Z_]+)") +_QUOTA_LIMIT = re.compile(r"\blimit: (?P\d+)") +_RETRY_DELAY = re.compile(r"(?:retry in |retryDelay:)(?P(?:\d+(?:\.\d+)?(?:ms|h|m|s))+)") +_GO_DURATION_PART = re.compile(r"(\d+(?:\.\d+)?)(ms|h|m|s)") +_AIR_CATEGORY = { + "model_unavailable": "request", "invalid_request": "request", "quota_exhausted": "limit", "rate_limit": "limit", + "authentication": "access", "permission": "access", "overloaded": "service", "timeout": "service", + "connection": "connection", "unknown": "unknown", +} + + +def _go_seconds(value): + units = {"ms": 0.001, "s": 1.0, "m": 60.0, "h": 3600.0} + return sum(float(amount) * units[unit] for amount, unit in _GO_DURATION_PART.findall(value)) + + +def classify_turn_failure(raw, http_code=0, connection_lost=False): + """Classify one terminal native failure from its structured fields. + + The model step carries the HTTP code; the terminal SDK error carries Go's + `Error , Message: ..., Status: ` rendering with ErrorInfo and + QuotaFailure details. The message text itself is never interpreted. + """ + if connection_lost: + return {"kind": "connection"} + raw = raw if isinstance(raw, str) else "" + match = _GO_API_ERROR.search(raw) + code = int(match.group("code")) if match else (http_code if isinstance(http_code, int) and 400 <= http_code <= 599 else 0) + status = match.group("status") if match else "" + reasons = {item.group("reason") for item in _ERROR_REASON.finditer(raw)} + delay = _RETRY_DELAY.search(raw) + retry_after = _go_seconds(delay.group("value")) if delay else None + if "QUOTA_EXHAUSTED" in reasons: + kind = "quota_exhausted" + elif code == 429 or status == "RESOURCE_EXHAUSTED": + limits = [int(item.group("limit")) for item in _QUOTA_LIMIT.finditer(raw)] + # A zero quota means this key's plan cannot use the model at all. + kind = "model_unavailable" if limits and all(limit == 0 for limit in limits) else "rate_limit" + elif code == 404 or status == "NOT_FOUND": + kind = "model_unavailable" + elif "API_KEY_INVALID" in reasons or code == 401 or status == "UNAUTHENTICATED": + kind = "authentication" + elif code == 403 or status == "PERMISSION_DENIED": + kind = "permission" + elif code in (500, 502, 503, 529) or status in ("UNAVAILABLE", "INTERNAL"): + kind = "overloaded" + elif code == 504 or status == "DEADLINE_EXCEEDED": + kind = "timeout" + elif code == 400 or status in ("INVALID_ARGUMENT", "FAILED_PRECONDITION"): + kind = "invalid_request" + else: + kind = "unknown" + result = {"kind": kind} + if code: + result["httpStatus"] = code + if status: + result["status"] = status + if kind == "rate_limit": + # A per-minute limit carries no delay; one minute is its natural window. + result["retryAfterSeconds"] = int(retry_after) if retry_after else 60 + elif retry_after and kind == "quota_exhausted": + result["retryAfterSeconds"] = int(retry_after) + return result + + +def _failure_title(kind, raw): + if kind == "model_unavailable": + # Never forward provider wording here; Paperclip names the model itself. + return "The selected model is not available for this connection." + if kind == "connection": + return "Google Antigravity lost its connection to the model service." + return quota_errors.quota_exhausted_message(raw) or api_errors.format_execution_error(raw) + + +def observe_step(step): + """Record a native SYSTEM step error's HTTP code for the active managed turn.""" + turn = _TURN.get() + if turn is None or step.status != sdk_types.StepStatus.ERROR or step.source != sdk_types.StepSource.SYSTEM: + return + http_code = getattr(step, "http_code", 0) + turn["httpCode"] = http_code if isinstance(http_code, int) else 0 + + +def turn_failure_meta(turn, admission, route): + """The prompt response `_meta` for a managed turn the native server ended with an error.""" + if not turn or ("raw" not in turn and not turn.get("connectionLost")): + return None + failure = classify_turn_failure(turn.get("raw"), turn.get("httpCode", 0), turn.get("connectionLost", False)) + air = {"severity": "error", "category": _AIR_CATEGORY[failure["kind"]], "title": _failure_title(failure["kind"], turn.get("raw") or "")} + return { + "jetbrains": {"air": {"version": 1, "sessionFailure": air}}, + "paperclipAntigravityFailure": {"schema": TURN_FAILURE_SCHEMA, **failure, "model": admission["model"], **({"route": route} if route else {})}, + } def _read_request(kwargs): @@ -58,25 +174,68 @@ def _read_request(kwargs): return {**value, "content": prompt["append"]} +def _owned_executable_path(): + """The kernel's record of this process image, never argv or the environment.""" + if sys.platform == "darwin": + executable_path = ctypes.create_string_buffer(4096) + path_size = ctypes.c_uint32(len(executable_path)) + get_executable_path = ctypes.CDLL("/usr/lib/libSystem.B.dylib")._NSGetExecutablePath + get_executable_path.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint32)] + get_executable_path.restype = ctypes.c_int + if get_executable_path(executable_path, ctypes.byref(path_size)) != 0: + _fail("cannot resolve the owned native executable path") + return os.path.realpath(os.fsdecode(executable_path.value)) + if sys.platform.startswith("linux"): + try: + path = os.readlink("/proc/self/exe") + except OSError: + _fail("cannot resolve the owned native executable path") + if not os.path.isabs(path) or path.endswith(" (deleted)"): + _fail("cannot resolve the owned native executable path") + return os.path.realpath(path) + _fail("unsupported native host") + + +def _native_model_matches(target, requested): + """Whether one native text target is exactly the requested `-` id. + + Personal sign-in sends the id literally. API-key, Agent Platform and gateway + sessions send the catalog's base model with the thinking level as an + endpoint option. Both forms must resolve to the same catalog entry: the + base model and the thinking level are checked together, never the family. + """ + levels = [ + endpoint.options.thinking_level + for field, endpoint in ( + ("gemini_api_endpoint", target.gemini_api_endpoint), + ("vertex_endpoint", target.vertex_endpoint), + ) + if target.HasField(field) + ] + if len(levels) > 1: + return False + level = levels[0] if levels else "" + if target.name == requested and not level: + return True + metadata = model_selection.DEFAULT_MODEL_METADATA_MAP.get(requested) + if metadata is None: + return False + expected_level = metadata.thinking_level.value if metadata.thinking_level is not None else "" + return target.name == metadata.base_model_id and level == expected_level + + def prepare_native_config(config, strategy): """Inspect the protobuf that will actually be sent to this owned harness.""" admission = _CONTEXT.get() if admission is None: return None - executable_path = ctypes.create_string_buffer(4096) - path_size = ctypes.c_uint32(len(executable_path)) - get_executable_path = ctypes.CDLL("/usr/lib/libSystem.B.dylib")._NSGetExecutablePath - get_executable_path.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_uint32)] - get_executable_path.restype = ctypes.c_int - if get_executable_path(executable_path, ctypes.byref(path_size)) != 0: - _fail("cannot resolve the owned native executable path") - helper = os.path.join(os.path.dirname(os.path.realpath(os.fsdecode(executable_path.value))), "localharness_external") + helper = os.path.join(os.path.dirname(_owned_executable_path()), "localharness_external") helper_stat = os.lstat(helper) if not stat.S_ISREG(helper_stat.st_mode) or helper_stat.st_nlink != 1: _fail("native helper must be the immutable sibling executable") with open(helper, "rb") as helper_file: helper_digest = hashlib.file_digest(helper_file, "sha256").hexdigest() - if helper_digest != "9e8fdc6e20a3262ca0a771850ca4a8414ca839a642cc964ec5c547cc2c33c200": + if helper_digest != paperclip_native_identity.HELPER_SHA256: _fail("native sibling helper digest differs") # The SDK resolves this attribute in its constructor. Updating the global # environment alone cannot replace that already-cached executable path. @@ -85,7 +244,7 @@ def prepare_native_config(config, strategy): strategy._env = {**strategy._env, "ANTIGRAVITY_HARNESS_PATH": helper} os.environ["ANTIGRAVITY_HARNESS_PATH"] = helper targets = [model for model in config.models if 1 in model.types] - if len(targets) != 1 or targets[0].name != admission["model"]: + if len(targets) != 1 or not _native_model_matches(targets[0], admission["model"]): _fail("native text model differs from the exact requested model") instructions = config.system_instructions expected = admission["content"] @@ -105,6 +264,11 @@ def prepare_native_config(config, strategy): _fail("managed subagents, workflows, and browser agents are unavailable") if config.harness_side_tools.schedule.enabled: _fail("managed timers and recurring schedules belong to Paperclip") + if tuple(config.rules_config.filenames) != MANAGED_RULE_FILENAMES: + _fail("native workspace rule discovery differs") + if not config.retry_config.HasField("api_retry"): + for key, value in MANAGED_API_RETRY.items(): + setattr(config.retry_config.api_retry, key, value) return { **admission, "sessionId": config.cascade_id, @@ -151,7 +315,36 @@ def _add_receipt(result, receipt): return result +def _auth_route(adapter): + """Which Google connection served the turn, for Paperclip's own model wording.""" + try: + state = adapter._ensure_auth_state() + except Exception: # pylint: disable=broad-except + return None + method = getattr(state, "method_id", None) + return {"gemini-api-key": "api_key", "oauth-personal": "subscription", "oauth-business": "subscription"}.get(method) + + +def configure_owned_helper_path(): + """Point the SDK at the helper beside this process image. + + The server's own discovery searches beside sys.argv[0] and sys.executable, + which does not find the helper in the Linux build; the SDK then refuses to + create any session. Managed sessions still verify the helper's digest in + prepare_native_config before it is launched. + """ + if os.environ.get("ANTIGRAVITY_HARNESS_PATH"): + return + try: + helper = os.path.join(os.path.dirname(_owned_executable_path()), "localharness_external") + except exceptions.RequestError: + return + if os.path.isfile(helper): + os.environ["ANTIGRAVITY_HARNESS_PATH"] = helper + + def install(adapter_type): + configure_owned_helper_path() if adapter_type.__dict__.get("_paperclip_admission_installed", False): return original_initialize = adapter_type.initialize @@ -161,6 +354,8 @@ def install(adapter_type): original_rebuild = adapter_type._rebuild_session_agent original_replace = adapter_type._maybe_replace_unavailable_model original_prompt = adapter_type.prompt + original_connection_lost = getattr(adapter_type, "_send_connection_lost_message", None) + original_execution_error_message = browser_subagent.execution_error_message original_cleanup = adapter_type.cleanup original_ext = getattr(adapter_type, "ext_method", None) original_oauth_mgr = getattr(adapter_type, "_ensure_oauth_mgr", None) @@ -230,6 +425,10 @@ def install(adapter_type): or kwargs.get("system_instructions") != admission["content"] ): _fail("native model or instruction input differs") + if admission is not None and kwargs.get("additional_directories"): + # 1.5.2 lets a client widen the native workspace and file-tool roots. + # A managed session keeps the single workspace Paperclip prepared. + _fail("managed sessions cannot add workspace directories") if admission is not None: requested_filter = kwargs.get("tool_filter", tool_filter.ToolFilterConfig()) if not isinstance(requested_filter, tool_filter.ToolFilterConfig): @@ -291,9 +490,37 @@ def install(adapter_type): async def prompt(self, *args, **kwargs): session_id = kwargs.get("session_id", args[1] if len(args) > 1 else None) admission = getattr(self, "_paperclip_managed_sessions", {}).get(session_id) - if admission is not None: - _receipt(self, session_id, admission) - return await original_prompt(self, *args, **kwargs) + if admission is None: + return await original_prompt(self, *args, **kwargs) + _receipt(self, session_id, admission) + turn = {} + token = _TURN.set(turn) + try: + result = await original_prompt(self, *args, **kwargs) + finally: + _TURN.reset(token) + # 1.5.2 reports a failed turn as agent text plus end_turn. Attach the + # typed failure so the client never accepts it as a completed result. + if result.stop_reason != "cancelled": + meta = turn_failure_meta(turn, admission, _auth_route(self)) + if meta is not None: + result.field_meta = {**(result.field_meta or {}), **meta} + return result + + async def connection_lost(self, session_id, error): + turn = _TURN.get() + if turn is not None: + turn["connectionLost"] = True + return await original_connection_lost(self, session_id, error) + + @functools.wraps(original_execution_error_message) + def execution_error_message(raw): + # Called with str(error) by every SDK execution/connection/validation + # failure branch of the native prompt handler, before it reports the text. + turn = _TURN.get() + if turn is not None and isinstance(raw, str): + turn["raw"] = raw + return original_execution_error_message(raw) def wrap_setting(original): @functools.wraps(original) @@ -435,6 +662,9 @@ def install(adapter_type): adapter_type._rebuild_session_agent = rebuild adapter_type._maybe_replace_unavailable_model = replace adapter_type.prompt = prompt + if original_connection_lost is not None: + adapter_type._send_connection_lost_message = connection_lost + browser_subagent.execution_error_message = execution_error_message adapter_type.cleanup = cleanup adapter_type.set_session_model = wrap_setting(adapter_type.set_session_model) adapter_type.set_config_option = wrap_setting(adapter_type.set_config_option) diff --git a/packages/paperclip-runner/scripts/patch-antigravity-runtime.mjs b/packages/paperclip-runner/scripts/patch-antigravity-runtime.mjs index ed56967b806..751590c5b6b 100644 --- a/packages/paperclip-runner/scripts/patch-antigravity-runtime.mjs +++ b/packages/paperclip-runner/scripts/patch-antigravity-runtime.mjs @@ -5,25 +5,48 @@ import { dirname, join, resolve } from "node:path"; import { inflateRawSync } from "node:zlib"; export const ANTIGRAVITY_PATCH_SCHEMA = "paperclip.antigravity.native_patch.v1"; -export const ANTIGRAVITY_PATCH_VERSION = "1.4.3-paperclip.5"; -const SERVER_HASH = "1251927db3e21f3d693fd042d6890d82f65eb00587e97f1f3d8f0d798e7f0954"; -const HARNESS_HASH = "9e8fdc6e20a3262ca0a771850ca4a8414ca839a642cc964ec5c547cc2c33c200"; +export const ANTIGRAVITY_PATCH_VERSION = "1.5.2-paperclip.2"; const ACP_ROOT = "google3/cloud/developer_experience/antigravity_extensions/acp_server/"; const SDK_ROOT = "google3/third_party/py/google/antigravity/connections/local/"; const SERVER_SOURCE = ACP_ROOT + "server.py"; const SDK_SOURCE = SDK_ROOT + "local_connection.py"; const EVENT_PROCESSOR_SOURCE = SDK_ROOT + "event_processor.py"; const ADMISSION_SOURCE = ACP_ROOT + "paperclip_admission.py"; +const IDENTITY_SOURCE = ACP_ROOT + "paperclip_native_identity.py"; const REMOVED_BYTECODE = new Set([ ACP_ROOT + "__pycache__/server.cpython-314.pyc", SDK_ROOT + "__pycache__/local_connection.cpython-314.pyc", SDK_ROOT + "__pycache__/event_processor.cpython-314.pyc", ]); +const RUNTIME_FILES = ["agy_acp_server.par", "localharness_external"]; +/** Each patchable vendor build and how its Python archive is embedded. The + * Linux builds are ELF launchers with the archive appended; macOS embeds it in + * a Mach-O section and must be re-signed after patching. */ +export const ANTIGRAVITY_PATCH_TARGETS = Object.freeze({ + "darwin-arm64": Object.freeze({ format: "macho", cpuType: 0x0100000c, signed: true }), + "linux-x64": Object.freeze({ format: "elf", machine: 62, signed: false }), + "linux-arm64": Object.freeze({ format: "elf", machine: 183, signed: false }), +}); +const SHA256 = /^[a-f0-9]{64}$/; const digest = value => createHash("sha256").update(value).digest("hex"); const fail = message => { throw new Error(`Antigravity native patch: ${message}`); }; -export function antigravityParSection(bytes) { - if (!Buffer.isBuffer(bytes) || bytes.length < 32 || bytes.readUInt32LE(0) !== 0xfeedfacf || bytes.readUInt32LE(4) !== 0x0100000c) fail("expected the pinned ARM64 Mach-O executable"); +/** Exact vendor identity for one target, taken from the verified closure declaration. */ +export function antigravityPatchTarget(target, vendorEntries) { + if (typeof target !== "string" || !Object.hasOwn(ANTIGRAVITY_PATCH_TARGETS, target)) fail("unsupported native target"); + if (!Array.isArray(vendorEntries) || vendorEntries.length !== RUNTIME_FILES.length || vendorEntries.some((entry, index) => entry?.path !== RUNTIME_FILES[index] || !SHA256.test(entry.sha256))) fail("explicit verified vendor entries are required"); + return { target, ...ANTIGRAVITY_PATCH_TARGETS[target], serverSha256: vendorEntries[0].sha256, harnessSha256: vendorEntries[1].sha256 }; +} + +/** Generated identity module: the helper digest comes from the verified closure + * manifest, so one owned admission source serves every platform. */ +export function antigravityNativeIdentitySource(harnessSha256) { + if (!SHA256.test(harnessSha256)) fail("invalid native helper digest"); + return Buffer.from(`"""Generated by Paperclip's native patch from the verified closure manifest."""\nHELPER_SHA256 = "${harnessSha256}"\n`); +} + +export function antigravityParSection(bytes, cpuType = ANTIGRAVITY_PATCH_TARGETS["darwin-arm64"].cpuType) { + if (!Buffer.isBuffer(bytes) || bytes.length < 32 || bytes.readUInt32LE(0) !== 0xfeedfacf || bytes.readUInt32LE(4) !== cpuType) fail("expected the pinned ARM64 Mach-O executable"); const commandCount = bytes.readUInt32LE(16); let cursor = 32; const sections = []; @@ -51,6 +74,53 @@ export function antigravityParSection(bytes) { return sections[0]; } +/** The Linux launcher is a 64-bit little-endian ELF executable whose last + * file bytes are a `.par_data` section holding the Python ZIP. Its offsets are + * relative to the section start; every other byte stays unchanged. */ +export function antigravityElfArchive(bytes, machine) { + if (!Buffer.isBuffer(bytes) || bytes.length < 64 || bytes.readUInt32BE(0) !== 0x7f454c46 || bytes[4] !== 2 || bytes[5] !== 1 || bytes[6] !== 1 + || ![2, 3].includes(bytes.readUInt16LE(16)) || bytes.readUInt16LE(18) !== machine) fail("expected the pinned 64-bit ELF executable"); + const programOffset = Number(bytes.readBigUInt64LE(32)); + const sectionOffset = Number(bytes.readBigUInt64LE(40)); + const programSize = bytes.readUInt16LE(54), programCount = bytes.readUInt16LE(56); + const sectionSize = bytes.readUInt16LE(58), sectionCount = bytes.readUInt16LE(60), namesIndex = bytes.readUInt16LE(62); + if (programSize !== 56 || sectionSize !== 64 || !programCount || namesIndex >= sectionCount || !Number.isSafeInteger(programOffset) || !Number.isSafeInteger(sectionOffset) + || programOffset + programCount * programSize > bytes.length || sectionOffset + sectionCount * sectionSize > bytes.length) fail("invalid ELF header bounds"); + const range = header => { + const start = Number(bytes.readBigUInt64LE(header + 24)), length = Number(bytes.readBigUInt64LE(header + 32)); + if (!Number.isSafeInteger(start) || !Number.isSafeInteger(length) || start + length > bytes.length) fail("invalid ELF section bounds"); + return { start, length }; + }; + const names = range(sectionOffset + namesIndex * sectionSize); + const sections = []; + let otherEnd = Math.max(64, programOffset + programCount * programSize, sectionOffset + sectionCount * sectionSize); + for (let index = 0; index < sectionCount; index++) { + const header = sectionOffset + index * sectionSize; + const nameOffset = bytes.readUInt32LE(header); + const nameEnd = bytes.indexOf(0, names.start + nameOffset); + if (nameOffset >= names.length || nameEnd < 0 || nameEnd > names.start + names.length) fail("invalid ELF section name"); + const bounds = range(header); + if (bytes.subarray(names.start + nameOffset, nameEnd).toString("latin1") === ".par_data") { + if (bytes.readUInt32LE(header + 4) !== 1) fail("invalid embedded Python archive section"); + sections.push(bounds); + } else if (bytes.readUInt32LE(header + 4) !== 8) otherEnd = Math.max(otherEnd, bounds.start + bounds.length); // SHT_NOBITS has no file bytes. + } + for (let index = 0; index < programCount; index++) { + const header = programOffset + index * programSize; + const end = Number(bytes.readBigUInt64LE(header + 8)) + Number(bytes.readBigUInt64LE(header + 32)); + if (!Number.isSafeInteger(end) || end > bytes.length) fail("invalid ELF segment bounds"); + otherEnd = Math.max(otherEnd, end); + } + if (sections.length !== 1) fail("expected exactly one embedded Python archive"); + const [section] = sections; + if (section.length < 22 || section.start < otherEnd || section.start + section.length !== bytes.length) fail("invalid embedded Python archive bounds"); + return section; +} + +export function antigravityEmbeddedArchive(bytes, target) { + return target.format === "macho" ? antigravityParSection(bytes, target.cpuType) : antigravityElfArchive(bytes, target.machine); +} + const crcTable = Array.from({ length: 256 }, (_, index) => { let value = index; for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ ((value & 1) ? 0xedb88320 : 0); @@ -165,6 +235,8 @@ export function antigravityPatchedSources(server, sdk, eventProcessor) { logging.warning( "Step error encountered for %s. Error: %s", step.id, step.error ) + from google3.cloud.developer_experience.antigravity_extensions.acp_server import paperclip_admission as paperclip_turn + paperclip_turn.observe_step(step) `, ); @@ -235,52 +307,59 @@ function rebuildZip(entries, length) { return result; } -export function patchAntigravityServerBytes(server, admissionSource) { - if (digest(server) !== SERVER_HASH) fail("official server SHA-256 mismatch"); - const section = antigravityParSection(server); +/** Verifies the complete vendor executable before decoding it. The buffer is + * patched in place, so large Linux builds need only one copy in memory. */ +export function patchAntigravityServerBytes(server, admissionSource, target) { + if (!target || !Object.hasOwn(ANTIGRAVITY_PATCH_TARGETS, target.target ?? "") || !SHA256.test(target.serverSha256 ?? "") || !SHA256.test(target.harnessSha256 ?? "")) fail("explicit verified native target is required"); + if (!Buffer.isBuffer(server) || digest(server) !== target.serverSha256) fail("official server SHA-256 mismatch"); + const section = antigravityEmbeddedArchive(server, target); const entries = antigravityEmbeddedZip(server.subarray(section.start, section.start + section.length)); const byName = new Map(entries.map(entry => [entry.name, entry])); - if (!byName.has(SERVER_SOURCE) || !byName.has(SDK_SOURCE) || !byName.has(EVENT_PROCESSOR_SOURCE) || byName.has(ADMISSION_SOURCE) || [...REMOVED_BYTECODE].some(name => !byName.has(name))) fail("pinned Python runtime layout changed"); + if (!byName.has(SERVER_SOURCE) || !byName.has(SDK_SOURCE) || !byName.has(EVENT_PROCESSOR_SOURCE) || byName.has(ADMISSION_SOURCE) || byName.has(IDENTITY_SOURCE) || [...REMOVED_BYTECODE].some(name => !byName.has(name))) fail("pinned Python runtime layout changed"); const patched = antigravityPatchedSources(content(byName.get(SERVER_SOURCE)).toString("utf8"), content(byName.get(SDK_SOURCE)).toString("utf8"), content(byName.get(EVENT_PROCESSOR_SOURCE)).toString("utf8")); const replacements = new Map([[SERVER_SOURCE, Buffer.from(patched.server)], [SDK_SOURCE, Buffer.from(patched.sdk)], [EVENT_PROCESSOR_SOURCE, Buffer.from(patched.eventProcessor)]]); const updated = entries.filter(entry => !REMOVED_BYTECODE.has(entry.name)).map(entry => replacements.has(entry.name) ? storedEntry(entry.name, replacements.get(entry.name)) : entry); - updated.push(storedEntry(ADMISSION_SOURCE, admissionSource)); + updated.push(storedEntry(ADMISSION_SOURCE, admissionSource), storedEntry(IDENTITY_SOURCE, antigravityNativeIdentitySource(target.harnessSha256))); + // rebuildZip copies every retained entry before the original bytes change. const archive = rebuildZip(updated, section.length); - const result = Buffer.from(server); - archive.copy(result, section.start); - return result; + archive.copy(server, section.start); + return server; } -/** Explicit install step; uses Node built-ins and the macOS signing tool only. */ -export async function patchAntigravityRuntime({ source, destination } = {}) { - if (process.platform !== "darwin" || process.arch !== "arm64") fail("only native macOS ARM64 is supported by this patch"); +/** Explicit install step; uses Node built-ins, plus the macOS signing tool for a macOS target. */ +export async function patchAntigravityRuntime({ source, destination, target: targetName, vendorEntries } = {}) { + const target = antigravityPatchTarget(targetName, vendorEntries); + if (target.signed && process.platform !== "darwin") fail("a macOS target must be patched and signed on macOS"); if (!source || !destination) fail("explicit source and destination directories are required"); const original = resolve(source); - const target = resolve(destination); + const destinationPath = resolve(destination); const serverPath = join(original, "agy_acp_server.par"); const harnessPath = join(original, "localharness_external"); for (const file of [serverPath, harnessPath]) { const stat = await lstat(file); if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1) fail("vendor closure contains links or special files"); } - const [server, harness, admission] = await Promise.all([readFile(serverPath), readFile(harnessPath), readFile(new URL("./patch-antigravity-runtime.admission.py", import.meta.url))]); - if (digest(harness) !== HARNESS_HASH) fail("official helper SHA-256 mismatch"); - const patched = patchAntigravityServerBytes(server, admission); - await mkdir(dirname(target), { recursive: true, mode: 0o700 }); - try { await lstat(target); fail("destination exists; refusing to replace a runtime"); } + const [harness, admission] = await Promise.all([readFile(harnessPath), readFile(new URL("./patch-antigravity-runtime.admission.py", import.meta.url))]); + if (digest(harness) !== target.harnessSha256) fail("official helper SHA-256 mismatch"); + const patched = patchAntigravityServerBytes(await readFile(serverPath), admission, target); + const unsignedServerSha256 = digest(patched); + await mkdir(dirname(destinationPath), { recursive: true, mode: 0o700 }); + try { await lstat(destinationPath); fail("destination exists; refusing to replace a runtime"); } catch (error) { if (error.code !== "ENOENT") throw error; } - const temporary = await mkdtemp(join(dirname(target), ".antigravity-native-patch-")); + const temporary = await mkdtemp(join(dirname(destinationPath), ".antigravity-native-patch-")); try { const executable = join(temporary, "agy_acp_server.par"); await writeFile(executable, patched, { mode: 0o700 }); - execFileSync("/usr/bin/codesign", ["--force", "--sign", "-", "--timestamp=none", executable], { stdio: "pipe", timeout: 30_000 }); - execFileSync("/usr/bin/codesign", ["--verify", "--strict", executable], { stdio: "pipe", timeout: 30_000 }); + if (target.signed) { + execFileSync("/usr/bin/codesign", ["--force", "--sign", "-", "--timestamp=none", executable], { stdio: "pipe", timeout: 30_000 }); + execFileSync("/usr/bin/codesign", ["--verify", "--strict", executable], { stdio: "pipe", timeout: 30_000 }); + } await writeFile(join(temporary, "localharness_external"), harness, { mode: 0o555 }); await chmod(executable, 0o555); await chmod(join(temporary, "localharness_external"), 0o555); - const signed = await readFile(executable); - const result = { schema: ANTIGRAVITY_PATCH_SCHEMA, version: ANTIGRAVITY_PATCH_VERSION, sourceServerSha256: SERVER_HASH, sourceHarnessSha256: HARNESS_HASH, admissionSourceSha256: digest(admission), unsignedServerSha256: digest(patched), serverSha256: digest(signed), harnessSha256: HARNESS_HASH }; - await rename(temporary, target); + const serverSha256 = target.signed ? digest(await readFile(executable)) : unsignedServerSha256; + const result = { schema: ANTIGRAVITY_PATCH_SCHEMA, version: ANTIGRAVITY_PATCH_VERSION, target: target.target, sourceServerSha256: target.serverSha256, sourceHarnessSha256: target.harnessSha256, admissionSourceSha256: digest(admission), unsignedServerSha256, serverSha256, harnessSha256: target.harnessSha256 }; + await rename(temporary, destinationPath); return result; } catch (error) { await rm(temporary, { recursive: true, force: true }); diff --git a/packages/paperclip-runner/scripts/patch-antigravity-runtime.test.mjs b/packages/paperclip-runner/scripts/patch-antigravity-runtime.test.mjs index 2e9cfc257f6..c59677f79de 100644 --- a/packages/paperclip-runner/scripts/patch-antigravity-runtime.test.mjs +++ b/packages/paperclip-runner/scripts/patch-antigravity-runtime.test.mjs @@ -1,24 +1,44 @@ import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { execFile } from "node:child_process"; -import { copyFile, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { test } from "node:test"; +import { inflateRawSync } from "node:zlib"; import { pathToFileURL } from "node:url"; -import { antigravityParSection, patchAntigravityServerBytes, replaceAntigravitySource } from "./patch-antigravity-runtime.mjs"; +import { antigravityElfArchive, antigravityEmbeddedZip, antigravityParSection, antigravityPatchTarget, patchAntigravityRuntime, patchAntigravityServerBytes, replaceAntigravitySource } from "./patch-antigravity-runtime.mjs"; const hash = value => createHash("sha256").update(value).digest("hex"); +// Native regressions run the real vendor build for this host. Point the source +// at an extracted, registry-verified vendor archive for the declared target. const source = process.env.PAPERCLIP_ANTIGRAVITY_NATIVE_TEST_SOURCE; +const nativeTarget = `${process.platform}-${process.arch}`; +const distributions = JSON.parse(await readFile(new URL("../antigravity-distributions.json", import.meta.url), "utf8")); +const nativeVendorEntries = distributions.platforms[nativeTarget]?.vendorEntries; +const skipNative = !source || !nativeVendorEntries; +const patchNative = (patcher, destination) => patcher.patchAntigravityRuntime({ source, destination, target: nativeTarget, vendorEntries: nativeVendorEntries }); +// 1.5.2 shuts down on stdin EOF without answering queued requests, so send +// each request after the previous response and close stdin only at the end. function runNative(executable, home, requests) { return new Promise((resolve, reject) => { - const child = execFile(executable, [], { + let stdout = "", next = 0; + const send = () => next < requests.length ? child.stdin.write(`${JSON.stringify(requests[next++])}\n`) : child.stdin.end(); + const child = execFile(executable, distributions.platforms[nativeTarget].args, { cwd: dirname(executable), env: { PATH: process.env.PATH, HOME: home, GEMINI_HOME: join(home, ".gemini"), BROWSER: "/usr/bin/true", AGY_ACP_FORCE_FILE_STORAGE: "1", ANTIGRAVITY_HARNESS_PATH: join(executable, "..", "localharness_external") }, timeout: 30_000, maxBuffer: 2 * 1024 * 1024, - }, (error, stdout, stderr) => error ? reject(Object.assign(error, { stdout, stderr })) : resolve({ events: stdout.trim().split("\n").filter(Boolean).map(line => JSON.parse(line)), stderr })); - child.stdin.end(requests.map(request => JSON.stringify(request)).join("\n") + "\n"); + }, (error, output, stderr) => error ? reject(Object.assign(error, { stdout: output, stderr })) : resolve({ events: output.trim().split("\n").filter(Boolean).map(line => JSON.parse(line)), stderr })); + child.stdout.on("data", chunk => { + stdout += chunk; + for (let end = stdout.indexOf("\n"); end >= 0; end = stdout.indexOf("\n")) { + const message = JSON.parse(stdout.slice(0, end)); + stdout = stdout.slice(end + 1); + if (message.id !== undefined && message.method === undefined) send(); + } + }); + send(); }); } @@ -53,6 +73,7 @@ def _paperclip_native_boundary_regressions(): bad = {"antigravity": {"paperclipAdmission": {**request, "byteLength": len(raw) + 1}, "systemPrompt": {"append": content}}} rejected(lambda: _read_request(bad)) config = pb.HarnessConfig(cascade_id="native-session", models=[pb.ModelConfig(name="literal-model", types=[1])]) + config.rules_config.filenames.extend(MANAGED_RULE_FILENAMES) if content: config.system_instructions.appended.appended_sections.add(content=content) token = _CONTEXT.set(expected) @@ -73,6 +94,9 @@ def _paperclip_native_boundary_regressions(): rejected(lambda: prepare_native_config(config, strategy)) rejected(lambda: acknowledge_native_config(prepared, native_ack, config)) config.models[0].name = "literal-model" + config.models[0].gemini_api_endpoint.options.thinking_level = "low" + rejected(lambda: prepare_native_config(config, strategy)) + config.models[0].ClearField("gemini_api_endpoint") config.system_instructions.appended.appended_sections.add(content="unexpected instruction") rejected(lambda: prepare_native_config(config, strategy)) del config.system_instructions.appended.appended_sections[:] @@ -87,15 +111,77 @@ def _paperclip_native_boundary_regressions(): config.harness_side_tools.schedule.enabled = True rejected(lambda: prepare_native_config(config, strategy)) config.harness_side_tools.schedule.enabled = False + # Workspace rules are deliberate: exactly GEMINI.md and AGENTS.md. + del config.rules_config.filenames[:] + rejected(lambda: prepare_native_config(config, strategy)) + config.rules_config.filenames.extend((*MANAGED_RULE_FILENAMES, "CUSTOM.md")) + rejected(lambda: prepare_native_config(config, strategy)) + del config.rules_config.filenames[:] + config.rules_config.filenames.extend(MANAGED_RULE_FILENAMES) + # A managed native config retries model API errors only briefly. + assert config.retry_config.api_retry.max_retries == MANAGED_API_RETRY["max_retries"] + assert config.retry_config.api_retry.initial_sleep_duration_ms == MANAGED_API_RETRY["initial_sleep_duration_ms"] config.custom_subagents.add(name="unpromised-browser-agent") rejected(lambda: prepare_native_config(config, strategy)) finally: _CONTEXT.reset(token) + # Mapped API-key targets: base model and thinking level must both match. + from google3.cloud.developer_experience.antigravity_extensions.acp_server import model_selection + requested = "gemini-3.8-flash-low" + base = model_selection.DEFAULT_MODEL_METADATA_MAP[requested].base_model_id + raw = b"" + mapped = {"schema": SCHEMA, "nonce": "mapped-regression", "model": requested, "digest": "sha256:" + hashlib.sha256(raw).hexdigest(), "byteLength": 0, "content": ""} + def mapped_config(name, level=None, vertex=False): + model = pb.ModelConfig(name=name, types=[1]) + endpoint = model.vertex_endpoint if vertex else model.gemini_api_endpoint + endpoint.SetInParent() + if level is not None: + endpoint.options.thinking_level = level + config = pb.HarnessConfig(cascade_id="mapped-session", models=[model]) + config.rules_config.filenames.extend(MANAGED_RULE_FILENAMES) + return config + strategy = SimpleNamespace(_binary_path="/untrusted", _env=None) + token = _CONTEXT.set(mapped) + try: + assert prepare_native_config(mapped_config(base, "low"), strategy)["model"] == requested + assert prepare_native_config(mapped_config(base, "low", vertex=True), strategy)["model"] == requested + assert prepare_native_config(mapped_config(requested), strategy)["model"] == requested + for name, level in ((base, "high"), (base, None), (base, ""), ("gemini-3.7-flash", "low"), (requested, "low")): + rejected(lambda: prepare_native_config(mapped_config(name, level), strategy)) + finally: + _CONTEXT.reset(token) sys.stderr.write("paperclip-native-boundary-regressions: passed\\n") _paperclip_native_boundary_regressions() `; +// The Linux server's own helper discovery misses the sibling helper, and the +// SDK then refuses every session. The owned patch supplies the kernel path. +const nativeOwnedHelperPathTests = ` + +def _paperclip_owned_helper_path_regression(): + import sys + from google.antigravity import types as sdk_types + from google.antigravity.connections.local.local_connection_config import LocalAgentConfig + saved = os.environ.pop("ANTIGRAVITY_HARNESS_PATH", None) + try: + configure_owned_helper_path() + expected = os.path.join(os.path.dirname(_owned_executable_path()), "localharness_external") + assert os.environ.get("ANTIGRAVITY_HARNESS_PATH") == expected, os.environ.get("ANTIGRAVITY_HARNESS_PATH") + config = LocalAgentConfig(conversation_id="owned-helper-path-1234567890123456", system_instructions="owned helper path", capabilities=sdk_types.CapabilitiesConfig(enable_subagents=False), models=[sdk_types.ModelTarget(name="literal-model", types=[sdk_types.ModelType.TEXT], endpoint=sdk_types.GeminiAPIEndpoint())]) + assert config.create_strategy(tool_runner=None, hook_runner=None)._binary_path == expected + os.environ["ANTIGRAVITY_HARNESS_PATH"] = "/explicit/operator/helper" + configure_owned_helper_path() + assert os.environ["ANTIGRAVITY_HARNESS_PATH"] == "/explicit/operator/helper", "an explicit path is never replaced" + finally: + os.environ.pop("ANTIGRAVITY_HARNESS_PATH", None) + if saved is not None: + os.environ["ANTIGRAVITY_HARNESS_PATH"] = saved + sys.stderr.write("paperclip-owned-helper-path-regression: passed\\n") + +_paperclip_owned_helper_path_regression() +`; + // Calls the real SDK subprocess/stdio/WebSocket startup. The native helper has // not received InitializeConversationEvent, so no auth or inference is used. const nativeHelperIsolationTests = ` @@ -106,7 +192,7 @@ def _paperclip_native_helper_isolation_regression(): import sys from google.antigravity import types as sdk_types from google.antigravity.tools.tool_runner import ToolRunner - from google.antigravity.connections.local.local_connection_config import LocalAgentConfig + from google3.cloud.developer_experience.antigravity_extensions.acp_server.proxy_agent_config import ProxyAgentConfig as LocalAgentConfig # the managed server strategy async def run(): home = os.environ["HOME"] os.makedirs(home, exist_ok=True) @@ -202,7 +288,9 @@ def _paperclip_managed_surface_regressions(): assert acp_hooks.load_hooks_config(workspace), "unmanaged source loader must remain functional" content = " Exact managed source config 🧷\\n" raw = content.encode() - admission = {"schema": SCHEMA, "nonce": "managed-source-policy", "model": "gemini-3.1-flash-lite", "digest": "sha256:" + hashlib.sha256(raw).hexdigest(), "byteLength": len(raw), "content": content} + # API-key sessions map a catalog id to its base model plus a thinking + # level; the exact requested id must still be admitted and acknowledged. + admission = {"schema": SCHEMA, "nonce": "managed-source-policy", "model": "gemini-3.8-flash-low", "digest": "sha256:" + hashlib.sha256(raw).hexdigest(), "byteLength": len(raw), "content": content} adapter = AgyAdapter() adapter._auth_state = AuthState(method_id="gemini-api-key", api_key="controlled-fixture-key-not-used") original_preflight = browser_subagent.preflight_launcher @@ -215,6 +303,12 @@ def _paperclip_managed_surface_regressions(): browser_subagent.preflight_launcher = forbidden_preflight config, teardown = await adapter._create_agent_config(cwd=workspace, session_id="managed-source-policy-1234567890123456", gemini_home=os.environ["GEMINI_HOME"], model_id=admission["model"], system_instructions=content) assert teardown is None + try: + await adapter._create_agent_config(cwd=workspace, session_id="managed-source-policy-1234567890123456", gemini_home=os.environ["GEMINI_HOME"], model_id=admission["model"], system_instructions=content, additional_directories=[os.environ["HOME"]]) + except exceptions.RequestError as error: + assert "cannot add workspace directories" in str(error) + else: + raise AssertionError("a managed session widened its workspace roots") assert not config.capabilities.enable_subagents and not config.subagents assert all(isinstance(hook, acp_hooks.ExternalOnInteractionHook) for hook in config.hooks) strategy = config.create_strategy(tool_runner=ToolRunner(tools=config._get_all_custom_tools()), hook_runner=None) @@ -222,6 +316,8 @@ def _paperclip_managed_surface_regressions(): assert not native.harness_side_tools.subagents.enabled assert not native.harness_side_tools.run_workflow.enabled and not native.custom_subagents assert not native.harness_side_tools.schedule.enabled + text_targets = [model for model in native.models if 1 in model.types] + assert [(model.name, model.gemini_api_endpoint.options.thinking_level) for model in text_targets] == [("gemini-3.8-flash", "low")], text_targets prepare_native_config(native, strategy) managed_manager = FixtureCredentials() adapter._oauth_mgr = managed_manager @@ -415,7 +511,7 @@ def _paperclip_managed_state_regressions(): from types import SimpleNamespace from acp import schema from google.antigravity import types as sdk_types - from google.antigravity.connections.local.local_connection_config import LocalAgentConfig + from google3.cloud.developer_experience.antigravity_extensions.acp_server.proxy_agent_config import ProxyAgentConfig as LocalAgentConfig # the managed server strategy from google3.learning.genai.api.localharness import localharness_pb2 as pb from google3.cloud.developer_experience.antigravity_extensions.acp_server.server import SessionInfo sid = "native-managed-session-12345678901234567890" @@ -518,8 +614,170 @@ def _paperclip_managed_state_regressions(): _paperclip_managed_state_regressions() `; -test("native patch rejects an unpinned executable before decoding", () => { - assert.throws(() => patchAntigravityServerBytes(Buffer.from("ambient executable"), Buffer.from("module")), /SHA-256 mismatch/); +// A minimal stored ZIP holding the exact pinned anchors, so the ELF path is +// exercised end to end without vendor binaries. +const ACP = "google3/cloud/developer_experience/antigravity_extensions/acp_server/"; +const SDK = "google3/third_party/py/google/antigravity/connections/local/"; +const fixtureSources = { + [ACP + "server.py"]: `class AgyAdapter(Agent): + pass + + # Immediately flush open tool calls on error step (validation/execution + # failure). + if step.status == sdk_types_module.StepStatus.ERROR: + if open_tool_calls: + logging.warning( + "Step error encountered; flushing open tool calls: %s. Error: %s", + open_tool_calls, + step.error, + ) + for tc_id in list(open_tool_calls): + open_tool_calls.pop(tc_id, None) + await self._client.session_update( + session_id=session_id, + update=schema.ToolCallProgress( + session_update="tool_call_update", + tool_call_id=tc_id, + raw_output=step.error or "Tool execution failed", + status="failed", + ), + ) + +`, + [SDK + "local_connection.py"]: " harness_config = self._build_harness_config()\n process, ws, ws_url = await self._spawn_harness_and_connect_ws()\n init_resp = init_resp_event.initialize_conversation_response\n parsed = event_processor.parse_initialize_response(init_resp)\n", + [SDK + "event_processor.py"]: " result = await self._execute_client_tool(tc)\n if result is not None:\n await self._send_tool_results([result])\n", + [ACP + "__pycache__/server.cpython-314.pyc"]: "x".repeat(65536), + [SDK + "__pycache__/local_connection.cpython-314.pyc"]: "y".repeat(65536), + [SDK + "__pycache__/event_processor.cpython-314.pyc"]: "z".repeat(65536), + [ACP + "unrelated.py"]: "VALUE = 1\n", +}; + +function storedZip(files) { + const locals = [], centrals = []; + let offset = 0; + for (const [name, text] of Object.entries(files)) { + const filename = Buffer.from(name), value = Buffer.from(text); + const checksum = crc32(value); + const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50); local.writeUInt16LE(20, 4); local.writeUInt32LE(checksum, 14); local.writeUInt32LE(value.length, 18); local.writeUInt32LE(value.length, 22); local.writeUInt16LE(filename.length, 26); + const central = Buffer.alloc(46); central.writeUInt32LE(0x02014b50); central.writeUInt16LE(20, 6); central.writeUInt32LE(checksum, 16); central.writeUInt32LE(value.length, 20); central.writeUInt32LE(value.length, 24); central.writeUInt16LE(filename.length, 28); central.writeUInt32LE(offset, 42); + locals.push(local, filename, value); centrals.push(central, filename); + offset += 30 + filename.length + value.length; + } + const directory = Buffer.concat(centrals); + const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50); end.writeUInt16LE(Object.keys(files).length, 8); end.writeUInt16LE(Object.keys(files).length, 10); end.writeUInt32LE(directory.length, 12); end.writeUInt32LE(offset, 16); + return Buffer.concat([...locals, directory, end]); +} + +function crc32(bytes) { + let value = 0xffffffff; + for (const byte of bytes) { value ^= byte; for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ ((value & 1) ? 0xedb88320 : 0); } + return (value ^ 0xffffffff) >>> 0; +} + +/** ELF64 launcher: header, one PT_LOAD over the code, section names, then the + * archive section as the final file bytes, as in the vendor Linux builds. */ +function elfLauncher(archive, { machine = 62, archiveAtEnd = true, sectionName = ".par_data" } = {}) { + const code = Buffer.alloc(256, 0xcc); + const names = Buffer.from(`\0.shstrtab\0${sectionName}\0`); + const sectionHeaders = 64 + code.length + names.length; + const archiveStart = Math.ceil((sectionHeaders + 3 * 64) / 4096) * 4096; + const tail = archiveAtEnd ? Buffer.alloc(0) : Buffer.alloc(16, 1); + const bytes = Buffer.alloc(archiveStart + archive.length + tail.length); + bytes.writeUInt32BE(0x7f454c46); bytes[4] = 2; bytes[5] = 1; bytes[6] = 1; + bytes.writeUInt16LE(3, 16); bytes.writeUInt16LE(machine, 18); + bytes.writeBigUInt64LE(BigInt(archiveStart - 56), 32); // program header in padding + bytes.writeBigUInt64LE(BigInt(sectionHeaders), 40); + bytes.writeUInt16LE(56, 54); bytes.writeUInt16LE(1, 56); bytes.writeUInt16LE(64, 58); bytes.writeUInt16LE(3, 60); bytes.writeUInt16LE(1, 62); + code.copy(bytes, 64); names.copy(bytes, 64 + code.length); + const program = archiveStart - 56; + bytes.writeUInt32LE(1, program); bytes.writeBigUInt64LE(64n, program + 8); bytes.writeBigUInt64LE(BigInt(code.length), program + 32); + const section = (index, name, type, offset, size) => { + const header = sectionHeaders + index * 64; + bytes.writeUInt32LE(name, header); bytes.writeUInt32LE(type, header + 4); + bytes.writeBigUInt64LE(BigInt(offset), header + 24); bytes.writeBigUInt64LE(BigInt(size), header + 32); + }; + section(1, 1, 3, 64 + code.length, names.length); + section(2, 11, 1, archiveStart, archive.length); + archive.copy(bytes, archiveStart); + tail.copy(bytes, archiveStart + archive.length); + return { bytes, archiveStart }; +} + +const fixtureTarget = server => ({ ...antigravityPatchTarget("linux-x64", [ + { path: "agy_acp_server.par", sha256: hash(server) }, { path: "localharness_external", sha256: "c".repeat(64) }, +]) }); + +function archiveFiles(bytes, start) { + return new Map(antigravityEmbeddedZip(bytes.subarray(start)).map(entry => [entry.name, entry.method === 8 ? inflateRawSync(entry.payload) : entry.payload])); +} + +test("native patch rejects an unpinned or tampered executable before decoding", () => { + const { bytes } = elfLauncher(storedZip(fixtureSources)); + assert.throws(() => patchAntigravityServerBytes(Buffer.from("ambient executable"), Buffer.from("module"), fixtureTarget(bytes)), /SHA-256 mismatch/); + const target = fixtureTarget(bytes); + const tampered = Buffer.from(bytes); + tampered[tampered.length - 100] ^= 1; + assert.throws(() => patchAntigravityServerBytes(tampered, Buffer.from("module"), target), /SHA-256 mismatch/); + assert.throws(() => patchAntigravityServerBytes(Buffer.from(bytes), Buffer.from("module")), /explicit verified native target/); + assert.throws(() => antigravityPatchTarget("darwin-x64", []), /unsupported native target/); + assert.throws(() => antigravityPatchTarget("linux-x64", [{ path: "localharness_external", sha256: "a".repeat(64) }]), /vendor entries/); +}); + +test("ELF patch replaces only the appended Python archive, deterministically", () => { + const { bytes, archiveStart } = elfLauncher(storedZip(fixtureSources)); + const target = fixtureTarget(bytes); + const admission = Buffer.from("# owned admission\n"); + const first = patchAntigravityServerBytes(Buffer.from(bytes), admission, target); + const second = patchAntigravityServerBytes(Buffer.from(bytes), admission, target); + assert.deepEqual(first, second); + assert.equal(first.length, bytes.length); + assert.deepEqual(first.subarray(0, archiveStart), bytes.subarray(0, archiveStart), "the ELF launcher is unchanged"); + assert.deepEqual(antigravityElfArchive(first, 62), { start: archiveStart, length: bytes.length - archiveStart }); + const files = archiveFiles(first, archiveStart); + assert.equal(files.get(ACP + "paperclip_admission.py").toString(), admission.toString()); + assert.match(files.get(ACP + "paperclip_native_identity.py").toString(), new RegExp(`HELPER_SHA256 = "${"c".repeat(64)}"`)); + assert.match(files.get(ACP + "server.py").toString(), /paperclip_admission\.install\(AgyAdapter\)/); + assert.match(files.get(SDK + "local_connection.py").toString(), /prepare_native_config/); + assert.match(files.get(SDK + "event_processor.py").toString(), /Client file result identity differs/); + assert.equal(files.get(ACP + "unrelated.py").toString(), "VALUE = 1\n"); + assert(![...files.keys()].some(name => name.endsWith(".pyc")), "stale bytecode for patched sources is removed"); +}); + +test("ELF archive decoding rejects the wrong architecture and misplaced archives", () => { + const archive = storedZip(fixtureSources); + assert.throws(() => antigravityElfArchive(Buffer.alloc(64), 62), /64-bit ELF/); + assert.throws(() => antigravityElfArchive(elfLauncher(archive).bytes, 183), /64-bit ELF/); + assert.equal(antigravityElfArchive(elfLauncher(archive, { machine: 183 }).bytes, 183).length, archive.length); + assert.throws(() => antigravityElfArchive(elfLauncher(archive, { archiveAtEnd: false }).bytes, 62), /archive bounds/); + assert.throws(() => antigravityElfArchive(elfLauncher(archive, { sectionName: ".rodata" }).bytes, 62), /exactly one embedded Python archive/); + const sourceMissing = storedZip(Object.fromEntries(Object.entries(fixtureSources).filter(([name]) => !name.endsWith("event_processor.py")))); + const missing = elfLauncher(sourceMissing).bytes; + assert.throws(() => patchAntigravityServerBytes(missing, Buffer.from("module"), fixtureTarget(missing)), /runtime layout changed/); +}); + +test("Linux closure patching runs on any host, verifies each vendor file, and never signs", async t => { + const root = await mkdtemp(join(tmpdir(), "paperclip-antigravity-elf-patch-test-")); + t.after(() => rm(root, { recursive: true, force: true })); + const vendor = join(root, "vendor"); + await mkdir(vendor, { mode: 0o700 }); + const { bytes } = elfLauncher(storedZip(fixtureSources)); + const helper = Buffer.from("fixture helper"); + await writeFile(join(vendor, "agy_acp_server.par"), bytes, { mode: 0o500 }); + const vendorEntries = [{ path: "agy_acp_server.par", sha256: hash(bytes) }, { path: "localharness_external", sha256: hash(helper) }]; + await assert.rejects(patchAntigravityRuntime({ source: vendor, destination: join(root, "missing"), target: "linux-x64", vendorEntries }), { code: "ENOENT" }); + await writeFile(join(vendor, "localharness_external"), Buffer.from("tampered helper"), { mode: 0o500 }); + await assert.rejects(patchAntigravityRuntime({ source: vendor, destination: join(root, "tampered"), target: "linux-x64", vendorEntries }), /helper SHA-256 mismatch/); + await rm(join(vendor, "localharness_external")); + await writeFile(join(vendor, "localharness_external"), helper, { mode: 0o500 }); + const first = await patchAntigravityRuntime({ source: vendor, destination: join(root, "first"), target: "linux-x64", vendorEntries }); + const second = await patchAntigravityRuntime({ source: vendor, destination: join(root, "second"), target: "linux-x64", vendorEntries }); + assert.deepEqual(second, first); + assert.equal(first.serverSha256, first.unsignedServerSha256, "Linux output is never re-signed"); + assert.equal(first.harnessSha256, hash(helper)); + assert.equal(hash(await readFile(join(root, "first/agy_acp_server.par"))), first.serverSha256); + assert.match(archiveFiles(await readFile(join(root, "first/agy_acp_server.par")), antigravityElfArchive(await readFile(join(root, "first/agy_acp_server.par")), 62).start).get(ACP + "paperclip_native_identity.py").toString(), new RegExp(hash(helper))); + await assert.rejects(patchAntigravityRuntime({ source: vendor, destination: join(root, "first"), target: "linux-x64", vendorEntries }), /destination exists/); + await assert.rejects(patchAntigravityRuntime({ source: vendor, destination: join(root, "arm"), target: "linux-arm64", vendorEntries }), /64-bit ELF/); }); test("source changes require a single exact pinned anchor", () => { @@ -543,15 +801,15 @@ test("Mach-O section decoding rejects invalid architecture and out-of-bounds nat }); test("pinned native closure reproducibly loads exact admission and rejects requests before authentication", { - skip: !source || process.platform !== "darwin" || process.arch !== "arm64", + skip: skipNative, timeout: 180_000, }, async t => { const root = await mkdtemp(join(tmpdir(), "paperclip-antigravity-native-patch-test-")); t.after(() => rm(root, { recursive: true, force: true })); const originalHash = hash(await readFile(join(source, "agy_acp_server.par"))); - const { patchAntigravityRuntime } = await import("./patch-antigravity-runtime.mjs"); - const first = await patchAntigravityRuntime({ source, destination: join(root, "first") }); - const second = await patchAntigravityRuntime({ source, destination: join(root, "second") }); + const patcher = await import("./patch-antigravity-runtime.mjs"); + const first = await patchNative(patcher, join(root, "first")); + const second = await patchNative(patcher, join(root, "second")); assert.deepEqual(second, first, "the complete signed patch must be reproducible"); assert.equal(hash(await readFile(join(source, "agy_acp_server.par"))), originalHash, "vendor source remains immutable"); const content = " exact café 🧷\n"; @@ -572,15 +830,15 @@ test("pinned native closure reproducibly loads exact admission and rejects reque assert(!result.events.some(event => event.result?._meta?.paperclipAntigravityAdmission), "no native init means no fabricated receipt"); const fixtureScripts = join(root, "fixture-scripts"); - const { mkdir } = await import("node:fs/promises"); await mkdir(fixtureScripts); await copyFile(new URL("./patch-antigravity-runtime.mjs", import.meta.url), join(fixtureScripts, "patch-antigravity-runtime.mjs")); const module = await readFile(new URL("./patch-antigravity-runtime.admission.py", import.meta.url), "utf8"); - await writeFile(join(fixtureScripts, "patch-antigravity-runtime.admission.py"), module + nativeBoundaryTests + nativeHelperIsolationTests + nativeManagedSurfaceTests + nativeModelCatalogTests + nativeStateTests); + await writeFile(join(fixtureScripts, "patch-antigravity-runtime.admission.py"), module + nativeBoundaryTests + nativeOwnedHelperPathTests + nativeHelperIsolationTests + nativeManagedSurfaceTests + nativeModelCatalogTests + nativeStateTests); const fixture = await import(pathToFileURL(join(fixtureScripts, "patch-antigravity-runtime.mjs"))); - await fixture.patchAntigravityRuntime({ source, destination: join(root, "boundary-fixture") }); + await patchNative(fixture, join(root, "boundary-fixture")); const tested = await runNative(join(root, "boundary-fixture/agy_acp_server.par"), join(root, "fixture-home"), [initialize()]); assert.match(tested.stderr, /paperclip-native-boundary-regressions: passed/); + assert.match(tested.stderr, /paperclip-owned-helper-path-regression: passed/); assert.match(tested.stderr, /paperclip-native-helper-isolation-regression: passed/); assert.match(tested.stderr, /paperclip-managed-surface-regressions: passed/); assert.match(tested.stderr, /paperclip-model-catalog-regressions: passed/); @@ -591,21 +849,38 @@ test("pinned native closure reproducibly loads exact admission and rejects reque test("native client file callbacks settle exact tool identity without broadcasting errors", { - skip: !source || process.platform !== "darwin" || process.arch !== "arm64", + skip: skipNative, timeout: 90_000, }, async t => { const root = await mkdtemp(join(tmpdir(), "paperclip-antigravity-tool-lifecycle-test-")); t.after(() => rm(root, { recursive: true, force: true })); const fixtureScripts = join(root, "scripts"); - const { mkdir } = await import("node:fs/promises"); await mkdir(fixtureScripts); await copyFile(new URL("./patch-antigravity-runtime.mjs", import.meta.url), join(fixtureScripts, "patch-antigravity-runtime.mjs")); const module = await readFile(new URL("./patch-antigravity-runtime.admission.py", import.meta.url), "utf8"); const regression = await readFile(new URL("./patch-antigravity-runtime.tool-lifecycle.test.py", import.meta.url), "utf8"); await writeFile(join(fixtureScripts, "patch-antigravity-runtime.admission.py"), module + "\n" + regression); const fixture = await import(pathToFileURL(join(fixtureScripts, "patch-antigravity-runtime.mjs"))); - await fixture.patchAntigravityRuntime({ source, destination: join(root, "runtime") }); + await patchNative(fixture, join(root, "runtime")); const tested = await runNative(join(root, "runtime/agy_acp_server.par"), join(root, "home"), [initialize()]); assert.match(tested.stderr, /paperclip-tool-lifecycle-regressions: passed/); assert.equal(tested.events[0].result.agentCapabilities._meta.antigravity.paperclipAdmission, 1); }); + +test("native managed turns report classified provider failures instead of a completed turn", { + skip: skipNative, + timeout: 90_000, +}, async t => { + const root = await mkdtemp(join(tmpdir(), "paperclip-antigravity-turn-failure-test-")); + t.after(() => rm(root, { recursive: true, force: true })); + const fixtureScripts = join(root, "scripts"); + await mkdir(fixtureScripts); + await copyFile(new URL("./patch-antigravity-runtime.mjs", import.meta.url), join(fixtureScripts, "patch-antigravity-runtime.mjs")); + const module = await readFile(new URL("./patch-antigravity-runtime.admission.py", import.meta.url), "utf8"); + const regression = await readFile(new URL("./patch-antigravity-runtime.turn-failure.test.py", import.meta.url), "utf8"); + await writeFile(join(fixtureScripts, "patch-antigravity-runtime.admission.py"), module + "\n" + regression); + const fixture = await import(pathToFileURL(join(fixtureScripts, "patch-antigravity-runtime.mjs"))); + await patchNative(fixture, join(root, "runtime")); + const tested = await runNative(join(root, "runtime/agy_acp_server.par"), join(root, "home"), [initialize()]); + assert.match(tested.stderr, /paperclip-turn-failure-regressions: passed/); +}); diff --git a/packages/paperclip-runner/scripts/patch-antigravity-runtime.tool-lifecycle.test.py b/packages/paperclip-runner/scripts/patch-antigravity-runtime.tool-lifecycle.test.py index b16c7ebc4b6..e4690c85bd7 100644 --- a/packages/paperclip-runner/scripts/patch-antigravity-runtime.tool-lifecycle.test.py +++ b/packages/paperclip-runner/scripts/patch-antigravity-runtime.tool-lifecycle.test.py @@ -46,7 +46,8 @@ def _paperclip_tool_lifecycle_regressions(): return schema.ReadTextFileResponse(content=Path(path).read_bytes().decode("utf-8")) class Adapter(AgyAdapter): - async def _maybe_send_usage_update(self, session_id): + # 1.5.2 observes usage through the live agent, which this fixture omits. + async def _observe_usage(self, session_id): pass def forbidden(*args, **kwargs): @@ -58,7 +59,7 @@ def _paperclip_tool_lifecycle_regressions(): adapter._client = client info = SessionInfo(agent=SimpleNamespace(), stack=contextlib.AsyncExitStack(), cwd=str(workspace), current_model_id="offline") adapter._sessions[sid] = info - runner = ToolRunner(tools=[tools.make_client_view_file(client, str(workspace)), tools.make_client_create_file(client, str(workspace)), tools.make_client_edit_file(client, str(workspace))]) + runner = ToolRunner(tools=[tools.make_client_view_file(client, [str(workspace)]), tools.make_client_create_file(client, [str(workspace)]), tools.make_client_edit_file(client, [str(workspace)])]) runner.set_context(ToolContext(SimpleNamespace(conversation_id=sid))) wire = [] @@ -100,8 +101,11 @@ def _paperclip_tool_lifecycle_regressions(): assert proof.read_bytes() == exact.encode("utf-8") assert json.loads(response.response_json) == {"result": None} terminal, update, response = await call("client_view_file", "read-call", {"absolute_path": str(proof)}) - assert terminal.content == exact and update.raw_output == exact - assert json.loads(response.response_json) == {"result": exact} + # 1.5.2 returns numbered lines under a header; the same native result must + # reach the step, the ACP update and the harness response unchanged. + assert exact.strip() in terminal.content + assert update.raw_output == terminal.content + assert json.loads(response.response_json) == {"result": terminal.content} edited = "replacement\n" await call("client_edit_file", "edit-call", {"target_file": str(proof), "code_content": edited}) assert proof.read_bytes() == edited.encode("utf-8") @@ -128,7 +132,7 @@ def _paperclip_tool_lifecycle_regressions(): await pending await drain() assert "pending-call" not in opened - assert [u for u in client.updates if u.tool_call_id == "pending-call" and u.status == "completed"][0].raw_output == "still independent\n" + assert "still independent" in [u for u in client.updates if u.tool_call_id == "pending-call" and u.status == "completed"][0].raw_output # Native errors close only the failing call, including permission identity. def native_step(call_id, status, error="", calls=True): diff --git a/packages/paperclip-runner/scripts/patch-antigravity-runtime.turn-failure.test.py b/packages/paperclip-runner/scripts/patch-antigravity-runtime.turn-failure.test.py new file mode 100644 index 00000000000..4e2f14c6998 --- /dev/null +++ b/packages/paperclip-runner/scripts/patch-antigravity-runtime.turn-failure.test.py @@ -0,0 +1,144 @@ +"""Credential-free turn-failure regressions executed in the real pinned hermetic SDK.""" + + +def _paperclip_turn_failure_regressions(): + import asyncio + import contextlib + import socket + import subprocess + import sys + from types import SimpleNamespace + from unittest import mock + from google.antigravity import types as sdk_types + from google3.cloud.developer_experience.antigravity_extensions.acp_server.server import AgyAdapter, SessionInfo + from google3.learning.genai.api.localharness import localharness_pb2 as pb + # This regression runs while server.py imports this module, before server.py + # calls install; install is idempotent, so the later call is a no-op. + install(AgyAdapter) + + # Provider strings as the live 1.5.2 helper rendered them (API keys removed). + zero_quota = ("agent executor error: Error 429, Message: You exceeded your current quota, please check your plan and billing details.\n" + "* Quota exceeded for metric: generativelanguage.googleapis.com/generate_content_free_tier_input_token_count, limit: 0, model: gemini-3.8-flash\n" + "Please retry in 4h33m54.066207256s., Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.QuotaFailure violations:[map[quotaValue:0]]]]") + per_minute = ("Error 429, Message: You exceeded your current quota.\n* Quota exceeded for metric: generate_content_requests, limit: 15, model: gemini-3.8-flash\n" + "Please retry in 23.5s., Status: RESOURCE_EXHAUSTED, Details: []") + overloaded = ("Encountered retryable error from model provider: Agent execution terminated due to error. (\"Error 503, Message: This model is currently" + " experiencing high demand. Spikes in demand are usually temporary. Please try again later., Status: UNAVAILABLE, Details: []\")") + subscription = "Error 429, Message: Resource has been exhausted, Status: RESOURCE_EXHAUSTED, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo reason:QUOTA_EXHAUSTED metadata:map[quotaResetDelay:2h0m0s]]]" + bad_key = "Error 400, Message: API key not valid. Please pass a valid API key., Status: INVALID_ARGUMENT, Details: [map[@type:type.googleapis.com/google.rpc.ErrorInfo reason:API_KEY_INVALID]]" + missing = "Error 404, Message: models/gemini-4-neon is not found for API version v1beta, Status: NOT_FOUND, Details: []" + assert classify_turn_failure(zero_quota) == {"kind": "model_unavailable", "httpStatus": 429, "status": "RESOURCE_EXHAUSTED"} + assert classify_turn_failure(per_minute) == {"kind": "rate_limit", "httpStatus": 429, "status": "RESOURCE_EXHAUSTED", "retryAfterSeconds": 23} + assert classify_turn_failure(overloaded) == {"kind": "overloaded", "httpStatus": 503, "status": "UNAVAILABLE"} + assert classify_turn_failure(subscription)["kind"] == "quota_exhausted" + assert classify_turn_failure(bad_key)["kind"] == "authentication" + assert classify_turn_failure(missing)["kind"] == "model_unavailable" + # A typed connection error for 401 carries only the step's HTTP code. + assert classify_turn_failure("System error occurred.", 401) == {"kind": "authentication", "httpStatus": 401} + assert classify_turn_failure("anything", 0, True) == {"kind": "connection"} + assert classify_turn_failure("opaque failure") == {"kind": "unknown"} + + # Managed native configs retry briefly and keep exactly the workspace rule files. + config = pb.HarnessConfig() + config.rules_config.filenames.extend(MANAGED_RULE_FILENAMES) + assert not config.retry_config.HasField("api_retry") + for key, value in MANAGED_API_RETRY.items(): + setattr(config.retry_config.api_retry, key, value) + assert config.retry_config.api_retry.max_retries == 3 + total = sum(MANAGED_API_RETRY["initial_sleep_duration_ms"] * MANAGED_API_RETRY["exponential_multiplier"] ** attempt for attempt in range(MANAGED_API_RETRY["max_retries"])) + assert total <= 30_000, "bounded native retries must end well inside the five-minute silence watchdog" + + sid = "offline-turn-failure" + model = "gemini-3.8-flash-low" + admission = {"schema": SCHEMA, "nonce": "turn-failure", "model": model, "digest": "sha256:" + "0" * 64, "byteLength": 0, "content": ""} + + class Client: + def __init__(self): + self.updates = [] + + async def session_update(self, session_id, update): + self.updates.append(update) + + class Agent: + def __init__(self, scenario): + self.scenario = scenario + self.model_id = model + self._strategy = SimpleNamespace(_paperclip_native_admission={k: admission[k] for k in ("schema", "nonce", "model", "digest", "byteLength")} | {"sessionId": sid, "connectionId": "c"}) + self.conversation = SimpleNamespace(receive_steps=self.receive_steps) + + async def chat(self, prompt): + if self.scenario == "connection": + raise sdk_types.AntigravityConnectionError("System error occurred.") + return SimpleNamespace(stop_reason=None) + + async def receive_steps(self): + if self.scenario in ("overloaded", "zero_quota"): + yield sdk_types.Step(id="retry", trajectory_id=sid, type=sdk_types.StepType.UNKNOWN, source=sdk_types.StepSource.SYSTEM, + status=sdk_types.StepStatus.ERROR, error="retrying") + raise sdk_types.AntigravityExecutionError(overloaded if self.scenario == "overloaded" else zero_quota) + if self.scenario == "success-after-retry": + step = sdk_types.Step(id="retry", trajectory_id=sid, type=sdk_types.StepType.UNKNOWN, source=sdk_types.StepSource.SYSTEM, + status=sdk_types.StepStatus.ERROR, error="retrying") + yield step + + class Adapter(AgyAdapter): + async def _observe_usage(self, session_id): + pass + + async def _maybe_refresh_admin_controls_for_turn(self, session_id): + pass + + async def _maybe_apply_model_switch(self, session_id): + pass + + async def _send_citation_notice(self, session_id): + pass + + def _ensure_auth_state(self): + return SimpleNamespace(method_id="gemini-api-key") + + def forbidden(*args, **kwargs): + raise AssertionError("offline turn-failure regression reached network or process launch") + + async def turn(scenario): + adapter = Adapter() + adapter._client = Client() + info = SessionInfo(agent=Agent(scenario), stack=contextlib.AsyncExitStack(), cwd="/", current_model_id=model) + info.agent_model_id = model + info.mode_id = "default" + info.system_prompt = "" + adapter._sessions[sid] = info + adapter._paperclip_managed_sessions = {sid: admission} + result = await adapter.prompt([{"type": "text", "text": "work"}], sid) + return result, adapter._client.updates + + async def run(): + result, updates = await turn("overloaded") + assert result.stop_reason == "end_turn", "1.5.2 itself still reports end_turn" + failure = result.field_meta["paperclipAntigravityFailure"] + assert failure == {"schema": TURN_FAILURE_SCHEMA, "kind": "overloaded", "httpStatus": 503, "status": "UNAVAILABLE", "model": model, "route": "api_key"} + air = result.field_meta["jetbrains"]["air"]["sessionFailure"] + assert air["severity"] == "error" and air["category"] == "service" and "high demand" in air["title"] + assert any(getattr(update, "session_update", "") == "agent_message_chunk" for update in updates) + + result, _ = await turn("zero_quota") + failure = result.field_meta["paperclipAntigravityFailure"] + assert failure["kind"] == "model_unavailable" and failure["route"] == "api_key" and failure["model"] == model + title = result.field_meta["jetbrains"]["air"]["sessionFailure"]["title"] + assert "quota" not in title.lower(), "a model refusal never forwards provider wording" + + result, _ = await turn("connection") + assert result.field_meta["paperclipAntigravityFailure"]["kind"] == "unknown", "no model HTTP code was observed" + + result, _ = await turn("success-after-retry") + assert not (result.field_meta or {}).get("paperclipAntigravityFailure"), "a retried turn that recovered is not a failure" + assert _TURN.get() is None + + with contextlib.ExitStack() as stack: + for owner, name in ((socket, "create_connection"), (subprocess, "Popen"), (asyncio, "create_subprocess_exec")): + stack.enter_context(mock.patch.object(owner, name, side_effect=forbidden)) + asyncio.run(run()) + sys.stderr.write("paperclip-turn-failure-regressions: passed\n") + + +_paperclip_turn_failure_regressions() diff --git a/packages/paperclip-runner/scripts/probe-antigravity-metadata.test.mjs b/packages/paperclip-runner/scripts/probe-antigravity-metadata.test.mjs index bdad055564a..9913bbab8bb 100644 --- a/packages/paperclip-runner/scripts/probe-antigravity-metadata.test.mjs +++ b/packages/paperclip-runner/scripts/probe-antigravity-metadata.test.mjs @@ -11,12 +11,14 @@ import { antigravityMetadataEnvironment, createAntigravityMetadataRpc } from "./ const hash = bytes => createHash("sha256").update(bytes).digest("hex"); const response = { - protocolVersion: 1, agentInfo: { name: "antigravity-acp", title: "private-provider-text 🛰", version: "1.4.3" }, + 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" }], }; -async function fixture(t, behavior = "success") { +async function fixture(t, behavior = "success", { platform = "darwin", architecture = "arm64" } = {}) { + const target = `${platform}-${architecture}`; + const args = platform === "linux" ? ["--uid="] : []; const root = await mkdtemp(join(tmpdir(), "paperclip-antigravity-probe-test-")); t.after(() => rm(root, { recursive: true, force: true })); const scripts = join(root, "scripts"); @@ -25,7 +27,7 @@ async function fixture(t, behavior = "success") { 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.4.3-paperclip.1'; export function patchAntigravityRuntime(){throw new Error('Metadata must never patch or install');}"); + 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');}"); const auditPath = join(root, "audit.json"); const script = `#!${process.execPath} const { writeFileSync } = require('node:fs'); @@ -38,7 +40,7 @@ process.stdin.on('data',chunk=>{ buffer+=chunk; if(!buffer.includes('\\n'))return; const requests=buffer.trim().split('\\n').map(line=>JSON.parse(line)); - writeFileSync(${JSON.stringify(auditPath)},JSON.stringify({pid:process.pid,home:process.env.HOME,geminiHome:process.env.GEMINI_HOME,cwd:process.cwd(),env:process.env,requests})); + writeFileSync(${JSON.stringify(auditPath)},JSON.stringify({pid:process.pid,argv:process.argv.slice(2),home:process.env.HOME,geminiHome:process.env.GEMINI_HOME,cwd:process.cwd(),env:process.env,requests})); if(requests.length!==1||requests[0].method!=='initialize')process.exit(41); if(behavior==='timeout')return; if(behavior==='malformed')return process.stdout.write('not-json\\n'); @@ -67,17 +69,17 @@ process.stdin.on('end',()=>{if(behavior!=='ignore-stop')process.exit(0)}); ]; 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.4.3-paperclip.1", 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.4.3", platforms: { "darwin-arm64": item } })); + 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 home = join(root, "operator-home"); - const runtime = join(home, ".paperclip/runtimes/antigravity/darwin-arm64", closureSha256); + 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.4.3", patchVersion: item.patchVersion, admissionSourceSha256, archiveSha256: item.archiveSha256, vendorClosureSha256: closureSha256, closureSha256, entries }), { mode: 0o400 }); + 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 }); const api = await import(pathToFileURL(join(scripts, "probe-antigravity-metadata.mjs"))); return { root, runtime, auditPath, - probe: options => api.probeAntigravityMetadata({ home, platform: "darwin", architecture: "arm64", startupTimeoutMs: 2_000, eofTimeoutMs: 60, terminateTimeoutMs: 60, killTimeoutMs: 250, ...options }), + probe: options => api.probeAntigravityMetadata({ home, platform, architecture, startupTimeoutMs: 2_000, eofTimeoutMs: 60, terminateTimeoutMs: 60, killTimeoutMs: 250, ...options }), }; } @@ -129,7 +131,7 @@ test("real stdio probe sends initialize only, sanitizes metadata and removes its 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.4.3"); + assert.equal(output.agentInfo.version, "1.5.2"); assert.equal(output.promptRequestsSent, 0); assert.equal(output.shutdown.exitCode, 0); assert.equal(output.shutdown.method, "eof"); @@ -194,3 +196,14 @@ test("invalid startup or shutdown limits fail before any native process starts", 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" }); }); + +test("a Linux closure probe starts the pinned executable with its declared arguments", async t => { + 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.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"); +}); diff --git a/packages/paperclip-runner/scripts/release-provider-pack.mjs b/packages/paperclip-runner/scripts/release-provider-pack.mjs index 698ac9fc9f4..ec8a2e65daa 100644 --- a/packages/paperclip-runner/scripts/release-provider-pack.mjs +++ b/packages/paperclip-runner/scripts/release-provider-pack.mjs @@ -1,6 +1,7 @@ import { createHash } from "node:crypto"; import profiles from "../acpx-profiles.json" with { type: "json" }; import distributions from "../cursor-distributions.json" with { type: "json" }; +import antigravityDistributions from "../antigravity-distributions.json" with { type: "json" }; import { KIMI_DISTRIBUTION_CLOSURE_SHA256 as kimiClosures } from "../src/drivers/acpx/kimi-closure-pins.ts"; const canonical = value => Array.isArray(value) ? `[${value.map(canonical).join(",")}]` @@ -8,7 +9,7 @@ const canonical = value => Array.isArray(value) ? `[${value.map(canonical).join( : JSON.stringify(value); /** Release assembly must reject a self-consistent pack built for another release. */ -export function verifyReleaseProviderPack(identity, sourceRevision, target = "linux-x64", expected = { profiles, distributions, kimiClosures }) { +export function verifyReleaseProviderPack(identity, sourceRevision, target = "linux-x64", expected = { profiles, distributions, kimiClosures, antigravityDistributions }) { const { profiles: releaseProfiles, distributions: releaseDistributions } = expected; const payload = identity?.payload; if (identity?.schema !== "paperclip-runner/remote-provider-pack/v1" || !payload @@ -62,5 +63,30 @@ export function verifyReleaseProviderPack(identity, sourceRevision, target = "li throw new Error("Remote provider-pack Kimi identity does not match this release"); } } + const antigravityProfile = releaseProfiles.profiles.antigravity; + verifyReleaseAntigravity(payload, antigravityProfile, expected.antigravityDistributions + ?? (antigravityProfile?.commandDigest === profiles.profiles.antigravity.commandDigest ? antigravityDistributions : undefined)); return identity; } + +/** 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. */ +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"); }; + if (!profile) return ordinary || candidate ? mismatch() : undefined; + const pending = profile.qualificationStatus === "pending"; + const entry = pending ? candidate : ordinary; + if ((pending ? ordinary : candidate) || (!pending && !entry)) mismatch(); + if (!entry) return; + 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 + || 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" + || Object.keys(entry).sort().join(",") !== "closureDigest,path,profileDigest,qualification,sha256,version" + || !/^sha256:[a-f0-9]{64}$/.test(entry.sha256 ?? "")) mismatch(); +} diff --git a/packages/paperclip-runner/scripts/release-provider-pack.test.mjs b/packages/paperclip-runner/scripts/release-provider-pack.test.mjs index 06605daa9d7..fd8e09b87f7 100644 --- a/packages/paperclip-runner/scripts/release-provider-pack.test.mjs +++ b/packages/paperclip-runner/scripts/release-provider-pack.test.mjs @@ -10,6 +10,7 @@ import profiles from "../acpx-profiles.json" with { type: "json" }; import historicalKimi from "../test/fixtures/kimi-profile-v14-identity.json" with { type: "json" }; import { KIMI_DISTRIBUTION_CLOSURE_SHA256 as kimiClosures } from "../src/drivers/acpx/kimi-closure-pins.ts"; import distributions from "../cursor-distributions.json" with { type: "json" }; +import antigravityDistributions from "../antigravity-distributions.json" with { type: "json" }; import { verifyReleaseProviderPack } from "./release-provider-pack.mjs"; import { existingReleaseProviderPack, releaseProviderPackManifest } from "./stage-release-runner-binaries.mjs"; @@ -60,7 +61,7 @@ test("release assembly rejects rehashed stale or missing packs before staging an const source = dirname(dirname(fileURLToPath(import.meta.url))); try { // Run the actual assembler in an isolated layout so it cannot overwrite built artifacts. - for (const file of ["scripts/stage-release-runner-binaries.mjs", "scripts/release-provider-pack.mjs", "src/live/runner-binary.ts", "src/drivers/acpx/kimi-closure-pins.ts", "acpx-profiles.json", "cursor-distributions.json", "release-runner-targets.json"]) { + for (const file of ["scripts/stage-release-runner-binaries.mjs", "scripts/release-provider-pack.mjs", "src/live/runner-binary.ts", "src/drivers/acpx/kimi-closure-pins.ts", "acpx-profiles.json", "cursor-distributions.json", "antigravity-distributions.json", "release-runner-targets.json"]) { mkdirSync(dirname(join(root, file)), { recursive: true }); cpSync(join(source, file), join(root, file)); } const platforms = {}; @@ -203,3 +204,59 @@ test("historical pending releases keep their separate candidate inventory", () = const pack = seal(payload); assert.equal(verifyReleaseProviderPack(pack, revision, "linux-x64", { profiles: historical, distributions }), pack); }); + +const antigravityProfile = profiles.profiles.antigravity; +const antigravityEntry = qualification => ({ version: antigravityProfile.agentServerVersion, profileDigest: antigravityProfile.commandDigest, + closureDigest: `sha256:${antigravityDistributions.platforms["linux-x64"].closureSha256}`, qualification, + path: "provider-assets/antigravity/linux-x64", sha256: digest }); +function releasedAntigravityProfiles() { + const released = structuredClone(profiles); delete released.profiles.antigravity.qualificationStatus; return released; +} + +test("pending Antigravity may ship only as one patched linux-x64 candidate", () => { + assert.equal(antigravityProfile.qualificationStatus, "pending"); + const absent = seal(fixture()); + assert.equal(verifyReleaseProviderPack(absent, revision), absent); + const candidate = fixture(); candidate.candidateProviders = { antigravity: antigravityEntry("pending") }; + assert.equal(verifyReleaseProviderPack(seal(candidate), revision).payload, candidate); + const promoted = fixture(); promoted.providers.antigravity = antigravityEntry("qualified"); + assert.throws(() => verifyReleaseProviderPack(seal(promoted), revision), /Antigravity identity/); + const both = fixture(); both.providers.antigravity = antigravityEntry("pending"); both.candidateProviders = { antigravity: antigravityEntry("pending") }; + assert.throws(() => verifyReleaseProviderPack(seal(both), revision), /Antigravity identity/); +}); + +test("released Antigravity requires one ordinary identity and never a candidate", () => { + const released = releasedAntigravityProfiles(); + const expected = { profiles: released, distributions, kimiClosures, antigravityDistributions }; + const payload = fixture(); payload.providers.antigravity = antigravityEntry("qualified"); + assert.equal(verifyReleaseProviderPack(seal(payload), revision, "linux-x64", expected).payload, payload); + const missing = fixture(); + assert.throws(() => verifyReleaseProviderPack(seal(missing), revision, "linux-x64", expected), /Antigravity identity/); + const candidate = fixture(); candidate.candidateProviders = { antigravity: antigravityEntry("pending") }; + assert.throws(() => verifyReleaseProviderPack(seal(candidate), revision, "linux-x64", expected), /Antigravity identity/); + const both = structuredClone(payload); both.candidateProviders = { antigravity: antigravityEntry("pending") }; + assert.throws(() => verifyReleaseProviderPack(seal(both), revision, "linux-x64", expected), /Antigravity identity/); +}); + +for (const [name, change] of [ + ["vendor closure", { closureDigest: `sha256:${antigravityDistributions.platforms["linux-x64"].vendorClosureSha256}` }], + ["darwin closure", { closureDigest: `sha256:${antigravityDistributions.platforms["darwin-arm64"].closureSha256}` }], + ["older runtime version", { version: "1.4.3" }], ["older profile", { profileDigest: digest }], + ["foreign path", { path: "provider-assets/antigravity/linux-arm64" }], ["unbound tree", { sha256: "stale" }], + ["qualification", { qualification: "qualified" }], ["extra field", { executable: "agy_acp_server.par" }], +]) test(`rejects an Antigravity candidate with a stale ${name}`, () => { + const payload = fixture(); payload.candidateProviders = { antigravity: { ...antigravityEntry("pending"), ...change } }; + assert.throws(() => verifyReleaseProviderPack(seal(payload), revision), /Antigravity identity/); +}); + +test("frozen Antigravity validation reads the release's own patched closure", () => { + const frozen = structuredClone(antigravityDistributions); frozen.platforms["linux-x64"].closureSha256 = "c".repeat(64); + const frozenProfiles = structuredClone(profiles); frozenProfiles.profiles.antigravity.commandDigest = "sha256:" + "e".repeat(64); + const payload = fixture(); payload.candidateProviders = { antigravity: { ...antigravityEntry("pending"), + profileDigest: frozenProfiles.profiles.antigravity.commandDigest, closureDigest: `sha256:${"c".repeat(64)}` } }; + // Without the release's frozen declaration a different profile fails closed. + assert.throws(() => verifyReleaseProviderPack(seal(payload), revision, "linux-x64", { profiles: frozenProfiles, distributions, kimiClosures }), /Antigravity identity/); + assert.equal(verifyReleaseProviderPack(seal(payload), revision, "linux-x64", { profiles: frozenProfiles, distributions, kimiClosures, antigravityDistributions: frozen }).payload, payload); + const vendorAsPatched = structuredClone(frozen); vendorAsPatched.platforms["linux-x64"].vendorClosureSha256 = "c".repeat(64); + assert.throws(() => verifyReleaseProviderPack(seal(payload), revision, "linux-x64", { profiles: frozenProfiles, distributions, kimiClosures, antigravityDistributions: vendorAsPatched }), /Antigravity identity/); +}); diff --git a/packages/paperclip-runner/src/cli/acpx-sidecar-input.ts b/packages/paperclip-runner/src/cli/acpx-sidecar-input.ts index 5d544314fdd..c731ce15752 100644 --- a/packages/paperclip-runner/src/cli/acpx-sidecar-input.ts +++ b/packages/paperclip-runner/src/cli/acpx-sidecar-input.ts @@ -137,6 +137,8 @@ const GENERIC_ACPX_OUTPUT_CODES = new Set([ const STABLE_ACPX_SIDECAR_CODES = new Set([ ...GROK_ADMISSION_ERROR_CODES, "ACPX_RUNTIME_PACKAGE_MISSING", + // A recovering open the Runner names provider_state_incompatible. + "ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE", "COPILOT_POLICY_VIOLATION", "COPILOT_DETACHED_WORK_UNSUPPORTED", "ACP_MODEL_UNSUPPORTED", diff --git a/packages/paperclip-runner/src/control-plane/acpx-controller-recovery.test.ts b/packages/paperclip-runner/src/control-plane/acpx-controller-recovery.test.ts index 1e605b0bc84..4abe2e0ad8c 100644 --- a/packages/paperclip-runner/src/control-plane/acpx-controller-recovery.test.ts +++ b/packages/paperclip-runner/src/control-plane/acpx-controller-recovery.test.ts @@ -54,6 +54,7 @@ function sidecarSource(root: string, selectedProfile = profile, agent = "claude" " const lines=rl.createInterface({input:process.stdin}); lines.on('close',()=>process.exit(0)); lines.on('line', line => {", " const r=JSON.parse(line), p=r.params || {};", " fs.appendFileSync(root+'/commands.jsonl',r.command+'\\n');", + " if(r.command==='session.open'&&p.expectedIdentity&&fs.existsSync(root+'/reload-refusal')){send({protocolVersion,id:r.id,ok:false,error:{code:fs.readFileSync(root+'/reload-refusal','utf8'),message:'The saved conversation cannot be reloaded in this process.',retryable:false}});return;}", " if(r.command==='session.open'&&fs.existsSync(root+'/startup-failure.json')){send({protocolVersion,id:r.id,ok:false,error:{code:'ACPX_SESSION_ENSURE_FAILED',message:'Internal error',retryable:false,providerFailure:JSON.parse(fs.readFileSync(root+'/startup-failure.json','utf8'))}});return;}", " switch(r.command) {", " case 'initialize': reply(r,{protocolVersion,sidecarPid:process.pid,profile:{agent:" + JSON.stringify(agent) + "},capabilities:{persistentSessions:true,exactModelVerification:true,permissions:'runner_policy',semanticTools:'runner_bridge',structuredInput:'paperclip.question_set.v1'}});break;", @@ -144,9 +145,9 @@ async function fixture(maxLifetimeMs?: number, candidateAdmission?: AcpxCandidat sidecarScript: script, sidecarScriptSha256: digest(script) }, environment: { PATH: process.env.PATH }, }); - const child = bounded?.child as ChildProcess | undefined - ?? spawn(binary,args,{env:{PATH:process.env.PATH,PAPERCLIP_RUNNER_BOOTSTRAP_TICKET:ticket},stdio:["ignore","ignore","pipe"],detached:true}); - const exit = once(child,"exit"); + const launchRunner = (runnerTicket: string) => spawn(binary,args,{env:{PATH:process.env.PATH,PAPERCLIP_RUNNER_BOOTSTRAP_TICKET:runnerTicket},stdio:["ignore","ignore","pipe"],detached:true}); + let child = bounded?.child as ChildProcess | undefined ?? launchRunner(ticket); + let exit = once(child,"exit"); child.stderr!.on("data",bytes=>{diagnostics=(diagnostics+String(bytes)).slice(-4096);}); let commandNumber=0; async function command(type:string,payload:Record={}) { @@ -196,6 +197,19 @@ async function fixture(maxLifetimeMs?: number, candidateAdmission?: AcpxCandidat controller=create();await controller.start(port); }, launches:()=>readFileSync(resolve(root,"launches.jsonl"),"utf8").trim().split("\n").map(line=>JSON.parse(line)), + /** Kills the Runner and every provider it launched, then starts a replacement Runner on the same state. */ + restartRunner:async()=>{ + try{process.kill(-child.pid!,"SIGKILL");}catch{} + await exit; + for(const line of readFileSync(resolve(root,"launches.jsonl"),"utf8").trim().split("\n")){ + try{process.kill((JSON.parse(line) as {pid:number}).pid,"SIGKILL");}catch{} + } + const replacementTicket=controller.issueBootstrapTicket(5_000); + await controller.flushCheckpoint(); + child=launchRunner(replacementTicket); + exit=once(child,"exit"); + child.stderr!.on("data",bytes=>{diagnostics=(diagnostics+String(bytes)).slice(-4096);}); + }, cleanup:async()=>{ await controller.stop(); if(child.exitCode===null && child.signalCode===null){try{process.kill(-child.pid!,"SIGKILL");}catch{}} @@ -523,3 +537,22 @@ it("requires a surviving provider when requesting a live snapshot after explicit expect(run.launches()).toHaveLength(1); }finally{await run.cleanup();} },60000); + +it("names a refused reload of the saved conversation after provider death so the server replaces it",async()=>{ + const run=await fixture(); + try{ + await run.ready(); + // The Runner and its provider die together. The replacement Runner + // reloads the saved conversation in a new provider process, and the + // sidecar refuses that reload by name. + writeFileSync(resolve(run.root,"reload-refusal"),"ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE"); + await run.restartRunner(); + const restored=await run.command("session.snapshot"); + expect(restored,JSON.stringify(restored)).toMatchObject({status:"failed",result:{result:{ + code:"command_execution_failed",classification:"provider_state_incompatible", + }}}); + expect(JSON.stringify(restored)).not.toContain("native_session_interrupted"); + expect(run.launches()).toHaveLength(2); + expect(readFileSync(resolve(run.root,"commands.jsonl"),"utf8").trim().split("\n").slice(-2)).toEqual(["initialize","session.open"]); + }finally{await run.cleanup();} +},60000); 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 a561ac6a7f4..39923380a86 100644 --- a/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts +++ b/packages/paperclip-runner/src/drivers/acpx/acpx-runtime-adapter.ts @@ -8,7 +8,7 @@ import { createGrokSessionOpenGuard } from "./grok-session-rules.js"; import { resolveClaudeEffort, createClaudeEffortAdmission } from "./claude-effort.js"; import { CLAUDE_ASYNC_TASKS_CAPABILITY } from "./claude-background-tasks.js"; import { ClaudeProviderCycles } from "./claude-provider-turns.js"; -import { acpxProviderFailure, acpxTypedSessionFailureClientCapabilities, acpxTypedTerminalSessionFailure, type AcpxTerminalSessionFailure } from "./provider-failure.js"; +import { ANTIGRAVITY_MODEL_UNAVAILABLE, acpxProviderFailure, acpxTypedSessionFailureClientCapabilities, acpxTypedTerminalSessionFailure, type AcpxTerminalSessionFailure } from "./provider-failure.js"; import type { ProviderFailure } from "../../contracts/provider-failure.generated.js"; import { createPiThinkingAdmission, resolvePiThinkingLevel } from "./pi-thinking.js"; import { usesPreconfiguredHome } from "../preconfigured-home.js"; @@ -51,7 +51,7 @@ 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 { createAntigravityAdmission } from "./antigravity-admission.js"; +import { antigravitySavedStateIncompatible, createAntigravityAdmission } from "./antigravity-admission.js"; import { createAcpxModeBinding } from "./provider-mode.js"; import { isAcpPromptRequest, type AcpxTurnDispatchJournal } from "./turn-dispatch-journal.js"; import { assertCopilotPromptPolicy, createCopilotPolicyEnforcement, type CopilotPolicyEnforcement } from "./copilot-policy.js"; @@ -757,6 +757,10 @@ 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. @@ -2579,7 +2583,7 @@ function definedEnvironment( } /** A typed AIR session failure fails the turn even though ACP reported a normal stop. */ -function typedTerminalTurnResult( +export function typedTerminalTurnResult( result: AcpRuntimeTurnResult, onFailure?: (failure: AcpxTerminalSessionFailure) => void, ): AcpRuntimeTurnResult { @@ -2591,6 +2595,15 @@ function typedTerminalTurnResult( } catch { // Diagnostics cannot change the failed terminal outcome. } + const provider = failure.provider; + if (provider?.kind === "model_unavailable") { + // Permanent: never an accepted result and never retried as capacity. The + // server words it from these fields, without provider text. + const error = { message: "The selected model is not available for this connection.", + code: ANTIGRAVITY_MODEL_UNAVAILABLE, retryable: false, + ...(provider.model ? { model: provider.model } : {}), ...(provider.route ? { route: provider.route } : {}) }; + return { status: "failed", error }; + } return { status: "failed", error: { message: `ACP agent reported a terminal ${failure.category} failure.`, code: "RUNTIME" } }; } 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 c8aef50aaa0..d3f271923aa 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 @@ -4,13 +4,15 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, expect, it } from "vitest"; import { createAcpRuntime } from "acpx/runtime"; -import { createAntigravityAdmission } from "./antigravity-admission.js"; +import { ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE, antigravitySavedStateIncompatible, createAntigravityAdmission } from "./antigravity-admission.js"; +import { typedTerminalTurnResult } from "./acpx-runtime-adapter.js"; +import { acpxSidecarErrorCode } from "../../cli/acpx-sidecar-input.js"; const cleanups: Array<() => Promise> = []; afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); }); /** The real installed manager/stdio transport, with only the remote provider replaced. */ -async function fixture(behavior: "accept" | "missing" | "mismatch" | "question" | "family" | "family-change" = "accept") { +async function fixture(behavior: "accept" | "missing" | "mismatch" | "question" | "family" | "family-change" | "reload-refused" | "reload-mismatch" | "quota" | "exit-mid-turn" = "accept") { const cwd = await mkdtemp(join(tmpdir(), "antigravity-acpx-contract-")); const requests: Array> = []; const nativeResponses: Array> = []; @@ -60,10 +62,12 @@ 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.4.3'}, + if(m.method==='initialize') send({id:m.id,result:{protocolVersion:1,agentInfo:{name:'antigravity-acp',version:'1.5.2'}, 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'}}}); else if(['session/new','session/load','session/resume','session/set_config_option','session/set_model'].includes(m.method)) { - const a=m.params._meta.antigravity.paperclipAdmission; + const a={...m.params._meta.antigravity.paperclipAdmission,...(${JSON.stringify(behavior)}==='reload-mismatch'&&m.method==='session/load'?{digest:'sha256:'+'0'.repeat(64)}:{})}; const model=${JSON.stringify(behavior)}==='mismatch'?'fallback':a.model; send({id:m.id,result:{...(!family||m.method==='session/new'?{sessionId:'native-session'}:{}),...(!family||['session/new','session/load','session/resume'].includes(m.method)?{modes:{currentModeId:'default'}}:{}), ...(!family||['session/new','session/load','session/resume'].includes(m.method)?{models:{currentModelId:model,availableModels:family?[{modelId:'gemini-3.8-flash-high',name:'Gemini 3.8 Flash (High)'},{modelId:'gemini-3.8-flash-medium',name:'Gemini 3.8 Flash (Medium)'},{modelId:'gemini-3.8-flash-low',name:'Gemini 3.8 Flash (Low)'}]:[{modelId:'advertised-only',name:'Advertised'}]}}:{}), @@ -76,8 +80,15 @@ async function fixture(behavior: "accept" | "missing" | "mismatch" | "question" const changed=nativeOptions();changed.find(o=>o.id==='thinking_level').currentValue='high'; send({method:'session/update',params:{sessionId:'native-session',update:{sessionUpdate:'config_option_update',configOptions:changed}}}); } + if(${JSON.stringify(behavior)}==='exit-mid-turn') process.exit(0); + if(${JSON.stringify(behavior)}==='quota') { + send({method:'session/update',params:{sessionId:'native-session',update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:'You exceeded your current quota.'}}}}); + send({id:m.id,result:{stopReason:'end_turn',_meta:{jetbrains:{air:{version:1,sessionFailure:{severity:'error',category:'request',title:'The selected model is not available for this connection.'}}}, + paperclipAntigravityFailure:{schema:'paperclip.antigravity.turn_failure.v1',kind:'model_unavailable',httpStatus:429,status:'RESOURCE_EXHAUSTED',model:${JSON.stringify("caller-model-absent-from-catalog")},route:'api_key'}}}}); + return; + } if(${JSON.stringify(behavior)}==='question') send({id:0,method:'session/request_permission',params:{sessionId:'native-session', - toolCall:{toolCallId:'interaction_choices',title:'Pick one',status:'pending',rawInput:{}}, + toolCall:{toolCallId:'interaction_0a1b2c3d',title:'Pick one',status:'pending',rawInput:{}}, options:[{optionId:'yes',name:'Yes',kind:'allow_once'},{optionId:'deny',name:'No',kind:'reject_once'}]}}); else send({id:m.id,result:{stopReason:'end_turn'}}); } else if(m.id===0 && m.result?.outcome) { @@ -171,3 +182,49 @@ it("rejects an unacknowledged thinking-level change after a native family model if (result.status !== "failed") throw new Error("turn did not fail"); expect(result.error?.message).toMatch(/admission/i); }); + +it.each(["reload-refused", "reload-mismatch"] as const)("names a %s reload as incompatible saved state, never a generic admission failure", async behavior => { + const f = await fixture(behavior); const first = await f.open(); + expect((await f.turn(first)).status).toBe("completed"); + await first.runtime.close({ handle: first.handle, reason: "provider restart" }); + const prompts = f.requests.filter(message => message.method === "session/prompt").length; + // As the adapter's cold admission does: a reused saved record is reopened + // through the exact-model control, which forces session/load. + const second = await f.open(); + const error = await second.runtime.setConfigOption!({ handle: second.handle, key: "model", value: f.model }) + .then(() => null, (reason: unknown) => reason as Error); + expect(error).toBeInstanceOf(Error); + // ACPX reports it as a retryable "resume required"; the adapter surfaces the + // typed refusal it wraps, which the sidecar sends as a stable, final code. + const refused = antigravitySavedStateIncompatible(error); + expect(refused).not.toBeNull(); + expect(refused!.retryable).toBe(false); + expect(acpxSidecarErrorCode(refused!)).toBe(ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE); + expect(f.requests.some(message => message.method === "session/load")).toBe(true); + // Never a silent fresh conversation or a prompt on unadmitted state. + expect(f.requests.filter(message => message.method === "session/new")).toHaveLength(1); + expect(f.requests.filter(message => message.method === "session/prompt")).toHaveLength(prompts); +}); + +it("keeps a refused fresh session an admission failure, not saved-state incompatibility", async () => { + const f = await fixture("mismatch"); + const error = await f.open().then(() => null, (reason: unknown) => reason as Error); + expect(error?.name).toBe("AntigravityAdmissionError"); + expect(acpxSidecarErrorCode(error!)).not.toBe(ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE); +}); + +it("fails a native end_turn that carries a classified provider failure", async () => { + const f = await fixture("quota"); const owner = await f.open(); + const settled = await f.turn(owner); + // Installed ACPX passes the prompt response _meta through; the adapter fails the turn. + expect(settled).toMatchObject({ status: "completed" }); + expect(typedTerminalTurnResult(settled)).toMatchObject({ status: "failed", error: { code: "antigravity_model_unavailable", retryable: false, route: "api_key" } }); +}); + +it("settles an in-flight prompt deterministically when 1.5.2 exits without answering it", async () => { + const f = await fixture("exit-mid-turn"); const owner = await f.open(); + const settled = await Promise.race([f.turn(owner).catch((error: unknown) => ({ status: "rejected", error })), + new Promise(resolve => setTimeout(() => resolve({ status: "hung" }), 10_000))]); + expect((settled as { status: string }).status).not.toBe("hung"); + expect((settled as { status: string }).status).not.toBe("completed"); +}, 20_000); 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 343317d0f29..5d8a04bc2dc 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,9 @@ import { describe, expect, it } from "vitest"; -import { ANTIGRAVITY_ADMISSION_SCHEMA, createAntigravityAdmission } from "./antigravity-admission.js"; +import { ANTIGRAVITY_ADMISSION_SCHEMA, ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE, AntigravityAdmissionError, AntigravitySavedStateIncompatibleError, createAntigravityAdmission } from "./antigravity-admission.js"; const content = " Exact governance 🧷\n\n"; const model = "caller/model-not-in-catalog"; -const initialize = { agentInfo: { name: "antigravity-acp", version: "1.4.3" }, agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 1 } } } }; +const initialize = { agentInfo: { name: "antigravity-acp", version: "1.5.2" }, agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 1 } } } }; function fixture() { const admission = createAntigravityAdmission(content, model); const guard = admission.createGuard(); @@ -117,6 +117,32 @@ describe("Antigravity exact native admission", () => { expect(() => f.guard("outbound", { ...prompt(), params: { ...prompt().params, prompt: [{ type: "text", text: "Do the task" }, { type: "text", text: "/logout" }] } })).toThrow("slash commands"); }); + it.each([ + ["a mismatched model receipt", (sent: ReturnType) => response(sent, { model: "another-model" })], + ["mismatched instruction bytes", (sent: ReturnType) => response(sent, { digest: `sha256:${"0".repeat(64)}` })], + ["no receipt", (sent: ReturnType) => ({ id: sent.id, result: { sessionId: "native-session" } })], + ["a managed-reload refusal", (sent: ReturnType) => ({ id: sent.id, error: { code: -32602, + message: "Paperclip admission: managed reload requires a fresh exact content acknowledgment", data: { paperclipAdmission: "refused" } } })], + ])("names %s on session/load as incompatible saved state", (_label, reply) => { + for (const method of ["session/load", "session/resume"]) { + const f = fixture(); const sent = request(f, method); + expect(() => f.guard("inbound", reply(sent))).toThrow(AntigravitySavedStateIncompatibleError); + expect(() => f.admission.assertReady()).toThrow(expect.objectContaining({ code: ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE, retryable: false })); + expect(() => f.guard("outbound", prompt())).toThrow(); + } + }); + + it("keeps fresh-session refusals and ordinary reload errors out of the saved-state class", () => { + const fresh = fixture(); const sent = request(fresh); + let thrown: unknown; + try { fresh.guard("inbound", response(sent, { model: "another-model" })); } catch (error) { thrown = error; } + expect(thrown).toBeInstanceOf(AntigravityAdmissionError); + expect(thrown).not.toBeInstanceOf(AntigravitySavedStateIncompatibleError); + // A transient provider error on reload keeps its own typed form. + const reload = fixture(); const load = request(reload, "session/load"); + expect(() => reload.guard("inbound", { id: load.id, error: { code: -32603, message: "Internal error" } })).not.toThrow(); + }); + it("rejects unpatched native runtimes before creating a session", () => { const f = createAntigravityAdmission("", model); const guard = f.createGuard(); guard("outbound", { id: 0, method: "initialize", params: {} }); @@ -129,7 +155,7 @@ describe("Antigravity native questions", () => { const f = fixture(); const sent = request(f); f.guard("inbound", response(sent)); return f; } const question = () => ({ id: 0, method: "session/request_permission", params: { - sessionId: "native-session", toolCall: { toolCallId: "interaction_123", title: "Choose a deployment" }, + sessionId: "native-session", toolCall: { toolCallId: "interaction_1a2b3c4d", title: "Choose a deployment" }, options: [{ optionId: "allow/weird:α", name: "Deploy", kind: "allow_once" }, { optionId: "deny", name: "Keep it local", kind: "reject_once" }], } }); @@ -166,12 +192,40 @@ describe("Antigravity native questions", () => { const f = admitted(); f.guard("inbound", question()); const sent = request(f, "session/new", "new-session-request"), ack = response(sent, { sessionId: "new-native-session" }); ack.result.sessionId = "new-native-session"; f.guard("inbound", ack); - const late = { id: 0, result: { action: "accept", content: { answer: "deny" } } }; - expect(() => f.guard("outbound", late)).not.toThrow(); - expect(late.result).toEqual({ action: "accept", content: { answer: "deny" } }); - const next = question(); next.params.sessionId = "new-native-session"; + const next = question(); next.params.sessionId = "new-native-session"; next.id = 1; expect(() => f.guard("inbound", next)).not.toThrow(); expect(next.method).toBe("elicitation/create"); expect(() => f.admission.assertReady()).not.toThrow(); + // An answer to the replaced question is stale and never reaches 1.5.2. + const late = { id: 0, result: { action: "accept", content: { answer: "deny" } } }; + expect(() => f.guard("outbound", late)).toThrow("stale or duplicate"); + }); + + it.each(["decline", "cancel"])("delivers %s as a native cancelled outcome, never a selected choice", action => { + const f = admitted(); f.guard("inbound", question()); + const answer = { id: 0, result: { action } as Record }; + f.guard("outbound", answer); + expect(answer.result).toEqual({ outcome: { outcome: "cancelled" } }); + }); + + it("settles a question that Stop answered with an error and rejects any later answer to it", () => { + const f = admitted(); f.guard("inbound", question()); + const stopped = { id: 0, error: { code: -32800, message: "Request cancelled" } }; + f.guard("outbound", stopped); + expect(stopped).toEqual({ id: 0, error: { code: -32800, message: "Request cancelled" } }); + expect(() => f.guard("outbound", { id: 0, result: { action: "accept", content: { answer: "deny" } } })).toThrow("stale or duplicate"); + }); + + it("rejects a duplicate answer after the first one settled the question", () => { + const f = admitted(); f.guard("inbound", question()); + f.guard("outbound", { id: 0, result: { action: "accept", content: { answer: "deny" } } }); + expect(() => f.guard("outbound", { id: 0, result: { action: "accept", content: { answer: "allow/weird:α" } } })).toThrow("stale or duplicate"); + }); + + it("treats only 1.5.2's exact synthetic interaction identity as a question", () => { + for (const toolCallId of ["interaction_", "interaction_123", "interaction_1A2B3C4D", "interaction_1a2b3c4d5", "xinteraction_1a2b3c4d"]) { + const f = admitted(); const q = question(); q.params.toolCall.toolCallId = toolCallId; + const before = structuredClone(q); f.guard("inbound", q); expect(q).toEqual(before); + } }); }); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-admission.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-admission.ts index c4d98393f2b..46fbfb87c7d 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-admission.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-admission.ts @@ -1,15 +1,27 @@ import { createHash, randomBytes } from "node:crypto"; import { createAntigravityQuestionBridge } from "./antigravity-questions.js"; +import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.js"; export const ANTIGRAVITY_ADMISSION_SCHEMA = "paperclip.antigravity.admission.v1"; const SESSION_METHODS = new Set(["session/new", "session/load", "session/resume"]); export class AntigravityAdmissionError extends Error { - readonly code = "ANTIGRAVITY_ADMISSION_FAILED"; + readonly code: string = "ANTIGRAVITY_ADMISSION_FAILED"; readonly retryable = false; constructor(detail: string) { super(`Antigravity admission failed: ${detail}`); this.name = "AntigravityAdmissionError"; } } +/** The sidecar code the Runner names `provider_state_incompatible` on a recovering open. */ +export const ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE = "ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE"; + +/** A saved native conversation cannot be reopened with this exact model and + * instructions. Reloading again fails the same way, so the server opens a + * replacement conversation instead of showing Retry. */ +export class AntigravitySavedStateIncompatibleError extends AntigravityAdmissionError { + override readonly code = ANTIGRAVITY_SAVED_STATE_INCOMPATIBLE; + constructor(detail: string) { super(`the saved conversation cannot be reopened: ${detail}`); this.name = "AntigravitySavedStateIncompatibleError"; } +} + export function antigravityInstructionBinding(content: string) { if (typeof content !== "string" || content.includes("\0") || Buffer.byteLength(content) > 256 * 1024) { throw new AntigravityAdmissionError("instructions exceed their size limit or contain NUL"); @@ -98,22 +110,34 @@ export function createAntigravityAdmission(content: string, model: string) { const request = pending.get(id); if (request) { pending.delete(id); - if (message.error !== undefined) return; // Keep the provider's typed error. + const reload = request.method === "session/load" || request.method === "session/resume"; + if (message.error !== undefined) { + // The native patch marks its own admission refusals as data. On a + // reload that names saved state this build cannot reopen; every + // other provider error keeps its typed form. + if (reload && record(record(message.error).data).paperclipAdmission === "refused") { + throw new AntigravitySavedStateIncompatibleError("the runtime refused its native admission"); + } + return; + } const result = record(message.result); if (request.method === "initialize") { const info = record(result.agentInfo); const native = record(record(record(result.agentCapabilities)._meta).antigravity); - if (info.name !== "antigravity-acp" || info.version !== "1.4.3" || native.paperclipAdmission !== 1) fail("runtime identity or native admission patch is unavailable"); + if (info.name !== "antigravity-acp" || info.version !== ANTIGRAVITY_RUNTIME_VERSION || native.paperclipAdmission !== 1) fail("runtime identity or native admission patch is unavailable"); initialized = true; } else if (request.nonce) { const ack = record(record(result._meta).paperclipAntigravityAdmission); const sessionId = request.sessionId ?? result.sessionId; + const refuse = (detail: string): never => { + throw reload ? new AntigravitySavedStateIncompatibleError(detail) : new AntigravityAdmissionError(detail); + }; if (typeof sessionId !== "string" || !sessionId || ack.schema !== ANTIGRAVITY_ADMISSION_SCHEMA || ack.nonce !== request.nonce || ack.sessionId !== sessionId || ack.model !== model || ack.digest !== binding.digest || ack.byteLength !== binding.byteLength - || typeof ack.connectionId !== "string" || !ack.connectionId || ack.connectionId.length > 256) fail("native configuration receipt is missing, stale, or mismatched"); + || typeof ack.connectionId !== "string" || !ack.connectionId || ack.connectionId.length > 256) refuse("native configuration receipt is missing, stale, or mismatched"); const selected = selectedModel(result); - if (selected !== undefined && selected !== model) fail("provider acknowledged a different model"); + if (selected !== undefined && selected !== model) refuse("provider acknowledged a different model"); const mode = record(result.modes).currentModeId; if (mode !== undefined && mode !== "default") fail("native permissions are outside the admitted default mode"); nativeSelection = selectionValues(result); @@ -185,6 +209,16 @@ function selectedModel(value: Record): unknown { return record(value.models).currentModelId; } +/** ACPX wraps a refused reload as a retryable "resume required" error. Resuming + * the same saved state cannot succeed, so the typed refusal is the outcome. */ +export function antigravitySavedStateIncompatible(error: unknown): AntigravitySavedStateIncompatibleError | null { + for (let current = error, depth = 0; current && typeof current === "object" && depth < 8; depth++) { + if (current instanceof AntigravitySavedStateIncompatibleError) return current; + current = (current as { cause?: unknown }).cause; + } + return null; +} + function record(value: unknown): Record { return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; } 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 e44bb0ade13..6425d60f8fd 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 @@ -43,7 +43,7 @@ async function fixture(mode: Mode) { queueMicrotask(() => { if (request.method === "initialize") { stdout.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result: { protocolVersion: 1, - agentInfo: { name: "antigravity-acp", version: "1.4.3" }, agentCapabilities: { _meta: { antigravity: { paperclipAdmission: 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; @@ -116,7 +116,7 @@ reader.on('line', line => { 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.4.3'},agentCapabilities:{_meta:{antigravity:{paperclipAdmission: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}); 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 9cac23eca93..d7dda7f9d96 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.test.ts @@ -45,7 +45,7 @@ reader.on('line', line => { 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.4.3'},agentCapabilities:{_meta:{antigravity:{paperclipAdmission:1}}},authMethods:[{id:'oauth-personal'}]}})+'\\n'); + 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'; diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts index 7f4b3bf54bd..c9f5a0a54cc 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-auth.ts @@ -1,11 +1,12 @@ import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { constants } from "node:fs"; -import { lstat, open, rename, rm } from "node:fs/promises"; +import { lstat, open, readlink, rename, rm } from "node:fs/promises"; import { randomUUID } 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 { verifyNativeAcpxInstallation, type VerifiedAcpxCommandLease } from "./installation-integrity.js"; const CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"; @@ -67,10 +68,13 @@ async function credentialFile(home: string): Promise { 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. This candidate is macOS ARM64 only. + // concurrently replaced parent. Linux has no such open flag, so the opened + // descriptor's kernel path must equal the checked canonical path instead. const noFollow = process.platform === "darwin" ? 0x20000000 : constants.O_NOFOLLOW; - const file = await open(join(parent, "acp_token.json"), constants.O_RDONLY | noFollow | constants.O_NONBLOCK); + const path = join(parent, "acp_token.json"); + 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"); 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"); const bytes = Buffer.alloc(MAX_BYTES + 1); @@ -187,7 +191,7 @@ export function startAntigravityBrowserLogin(home: string): AntigravityBrowserLo 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 !== "1.4.3" + 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; send(2); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-installation.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-installation.ts index d94f3fbf166..71883a83144 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-installation.ts @@ -37,7 +37,7 @@ export function antigravityNativeDistributionSpec(platform: NodeJS.Platform = pr distributionRoot = antigravityRuntimeCachePath(pin.closureSha256, platform, architecture); } return { distributionRoot, manifestPath: join(distributionRoot, ".paperclip-antigravity-closure.json"), expectedClosureSha256: pin.closureSha256, - executable: pin.executable, fixedArguments: [...pin.args] }; + executable: pin.executable, fixedArguments: [...pin.args], storeFamily: "antigravity" }; } export async function verifyAntigravityInstallation(profile: QualifiedAcpxProfile, candidateAdmission?: AcpxCandidateStartupAdmission): Promise { 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 new file mode 100644 index 00000000000..97f6f77ae6e --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-model-catalog.test.ts @@ -0,0 +1,87 @@ +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import * as generator from "../../../scripts/generate-antigravity-models.mjs"; + +const declarationPath = resolve(import.meta.dirname, "../../../antigravity-distributions.json"); +const temporary: string[] = []; +afterEach(async () => { await Promise.all(temporary.splice(0).map(directory => rm(directory, { recursive: true, force: true }))); }); +async function scratch() { const directory = await mkdtemp(join(tmpdir(), "antigravity-catalog-")); temporary.push(directory); return directory; } + +const SOURCE = ` +_HIGH_MEDIUM_LOW = ( + sdk_types_module.ThinkingLevel.HIGH, + sdk_types_module.ThinkingLevel.MEDIUM, + sdk_types_module.ThinkingLevel.LOW, +) + +DEFAULT_MODEL_METADATA_MAP = { + # Agent Platform only. + **_thinking_family( + "gemini-4-neon", + "Gemini 4 Neon", + ( + sdk_types_module.ThinkingLevel.HIGH, + sdk_types_module.ThinkingLevel.EXTRA_HIGH, + ), + max_tokens=1_048_576, + agent_platform_only=True, + ), + **_thinking_family( + "gemini-3.8-flash", + "Gemini 3.8 Flash", + _HIGH_MEDIUM_LOW, + max_tokens=1_048_576, + ), +} +`; + +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"); + }); + + 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"; + 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.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/); + }); + + it("rejects a hand-edited catalog", async () => { + const directory = await scratch(); + const edited = (await readFile(generator.ANTIGRAVITY_MODELS_OUTPUT, "utf8")).replace('"gemini-3.1-pro-low"', '"gemini-3.1-pro-medium"'); + await writeFile(join(directory, "catalog.ts"), edited); + await expect(generator.checkAntigravityModelCatalog({ output: join(directory, "catalog.ts") })).rejects.toThrow(); + }); + + it("reads families and levels from the server's catalog table", () => { + expect(generator.parseAntigravityCatalogSource(SOURCE)).toEqual([ + { id: "gemini-4-neon", label: "Gemini 4 Neon", baseModelId: "gemini-4-neon", levels: ["high", "extra_high"], agentPlatformOnly: true }, + { id: "gemini-3.8-flash", label: "Gemini 3.8 Flash", baseModelId: "gemini-3.8-flash", levels: ["high", "medium", "low"], agentPlatformOnly: false }, + ]); + }); + + it("stops on a catalog shape it does not understand", () => { + expect(() => generator.parseAntigravityCatalogSource(SOURCE.replace("max_tokens=1_048_576,\n agent_platform_only", "max_tokens=1_048_576,\n gateway_only=True,\n agent_platform_only"))).toThrow(/does not understand/); + expect(() => generator.parseAntigravityCatalogSource(SOURCE.replace("ThinkingLevel.EXTRA_HIGH", "ThinkingLevel.ULTRA"))).toThrow(/unknown thinking level/); + expect(() => generator.parseAntigravityCatalogSource(SOURCE.replace("**_thinking_family(\n \"gemini-4-neon\"", "\"custom\": meta,\n **_thinking_family(\n \"gemini-4-neon\""))).toThrow(); + }); + + it("refuses to generate when the live session disagrees with the table", () => { + const families = generator.parseAntigravityCatalogSource(SOURCE); + const binding = { runtimeVersion: "1.5.2", platform: "darwin-arm64", archiveSha256: "a", vendorClosureSha256: "b" }; + const live = { defaultModelId: "gemini-3.8-flash-high", models: ["high", "medium", "low"].map(level => ({ id: `gemini-3.8-flash-${level}`, label: `Gemini 3.8 Flash (${level})` })) }; + expect(generator.buildAntigravityModelCatalog({ families, live, binding }).apiKey.models).toHaveLength(3); + expect(() => generator.buildAntigravityModelCatalog({ families, live: { ...live, models: live.models.slice(1) }, binding })).toThrow(/differs/); + expect(() => generator.buildAntigravityModelCatalog({ families, live: { ...live, defaultModelId: "gemini-4-neon-high" }, binding })).toThrow(/default/); + }); +}); 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 aad213e1f37..bae59ea0f9f 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-models.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-models.test.ts @@ -46,7 +46,7 @@ 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.4.3'},agentCapabilities:{_meta:{antigravity:{paperclipAdmission:1,paperclipModels:mode==='old-patch'?0:1}}},authMethods:[{id:'oauth-personal'}]}); + 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') { 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;} diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-models.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-models.ts index ea5227a20f0..9ded767ee76 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-models.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-models.ts @@ -1,6 +1,7 @@ import type { ChildProcessWithoutNullStreams } from "node:child_process"; import { randomUUID } from "node:crypto"; 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"; @@ -108,7 +109,7 @@ export async function discoverAntigravityModels(home: string, options: { signal? 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), capabilities = record(record(record(initialized.agentCapabilities)._meta).antigravity); - if (initialized.protocolVersion !== 1 || info.name !== "antigravity-acp" || info.version !== "1.4.3" + if (initialized.protocolVersion !== 1 || info.name !== "antigravity-acp" || info.version !== ANTIGRAVITY_RUNTIME_VERSION || capabilities.paperclipAdmission !== 1 || capabilities.paperclipModels !== 1 || !Array.isArray(initialized.authMethods) || !initialized.authMethods.some(value => record(value).id === "oauth-personal")) { fail(); return; } phase = 2; send(2); diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-questions.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-questions.ts index b93653951a0..afdd2d8c3aa 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-questions.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-questions.ts @@ -1,15 +1,28 @@ -/** Antigravity 1.4.3 encodes fixed-choice questions as permission callbacks. */ +/** Antigravity 1.5.2 encodes fixed-choice questions as permission callbacks. + * Its `_ask_question_handler` sends `session/request_permission` with a + * synthetic tool call `interaction_<8 hex>` (checked in the 1.5.2 server + * source); every other permission callback is a real tool approval. */ +const QUESTION_TOOL_CALL = /^interaction_[0-9a-f]{8}$/; +const MAX_RETIRED = 256; + export function createAntigravityQuestionBridge(ownsSession: (sessionId: unknown) => boolean) { const pending = new Map }>(); + // Answered, cancelled or replaced questions. A later answer for one of them + // is stale or duplicate and must never reach the native server. + const retired = new Set(); + const retire = (id: string | number) => { + retired.add(id); + if (retired.size > MAX_RETIRED) retired.delete(retired.values().next().value!); + }; return { - clear() { pending.clear(); }, + clear() { for (const id of pending.keys()) retire(id); pending.clear(); }, guard(direction: "inbound" | "outbound", value: unknown): void { const message = record(value); const id = message.id; if (direction === "inbound" && message.method === "session/request_permission") { const params = record(message.params); const tool = record(params.toolCall); - if (typeof tool.toolCallId !== "string" || !tool.toolCallId.startsWith("interaction_")) return; + if (typeof tool.toolCallId !== "string" || !QUESTION_TOOL_CALL.test(tool.toolCallId)) return; if ((typeof id !== "string" && typeof id !== "number") || pending.has(id) || pending.size >= 16 || !ownsSession(params.sessionId) || typeof params.sessionId !== "string" || typeof tool.title !== "string" || !tool.title.trim() @@ -35,16 +48,22 @@ export function createAntigravityQuestionBridge(ownsSession: (sessionId: unknown }, }; if (Buffer.byteLength(JSON.stringify(form)) > 196 * 1024) throw new Error("Antigravity question exceeds its complete-content limit"); + retired.delete(id); pending.set(id, { sessionId: params.sessionId, optionIds }); // The installed ACPX form path owns durable input and delivery. Convert // before its permission policy can interpret a choice as an approval. message.method = "elicitation/create"; message.params = form; + } else if (direction === "outbound" && message.method === undefined + && (typeof id === "string" || typeof id === "number") && retired.has(id)) { + throw new Error("Antigravity answer is stale or duplicate"); } else if (direction === "outbound" && message.method === undefined && (typeof id === "string" || typeof id === "number") && pending.has(id)) { const question = pending.get(id)!; if (!ownsSession(question.sessionId)) throw new Error("Antigravity answer belongs to a stale session"); - if (message.error !== undefined) { pending.delete(id); return; } + // Stop or a failed card: ACPX answers with an error, which the native + // server treats as no selection. The question is settled either way. + if (message.error !== undefined) { pending.delete(id); retire(id); return; } const result = record(message.result); if (result.action === "accept") { const content = record(result.content); @@ -56,6 +75,7 @@ export function createAntigravityQuestionBridge(ownsSession: (sessionId: unknown message.result = { outcome: { outcome: "cancelled" } }; } else throw new Error("Antigravity question response is invalid"); pending.delete(id); + retire(id); } }, }; diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-turn-failure.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-turn-failure.test.ts new file mode 100644 index 00000000000..a2c8bc854ca --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-turn-failure.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from "vitest"; +import { readProviderFailure } from "../../contracts/provider-failure.generated.js"; +import { typedTerminalTurnResult } from "./acpx-runtime-adapter.js"; +import { ACPX_CAPABILITY_PROFILES } from "./capability-profiles.js"; +import { QUALIFIED_ACPX_PROFILES } from "./qualified-profiles.js"; +import { ANTIGRAVITY_MODEL_UNAVAILABLE, ANTIGRAVITY_TURN_FAILURE_SCHEMA, acpxTerminalResult, acpxTypedTerminalSessionFailure, type AcpxTerminalSessionFailure } from "./provider-failure.js"; + +/** The prompt response `_meta` the 1.5.2-paperclip.2 patch attaches to a failed managed turn. */ +function nativeFailure(kind: string, title: string, extra: Record = {}) { + return { + jetbrains: { air: { version: 1, sessionFailure: { severity: "error", category: kind === "overloaded" ? "service" : kind === "model_unavailable" ? "request" : "limit", title } } }, + paperclipAntigravityFailure: { schema: ANTIGRAVITY_TURN_FAILURE_SCHEMA, kind, model: "gemini-4-neon-high", route: "api_key", ...extra }, + }; +} + +function settle(meta: Record) { + let observed: AcpxTerminalSessionFailure | undefined; + // 1.5.2 ends a failed turn with stopReason end_turn after streaming the error as text. + const result = typedTerminalTurnResult({ status: "completed", stopReason: "end_turn", _meta: meta }, failure => { observed = failure; }); + return { result, terminal: acpxTerminalResult(result, "antigravity", { GEMINI_API_KEY: "fixture-secret" }, observed) }; +} + +describe("Antigravity managed-turn failures", () => { + it("never accepts an end_turn that the native server reported as a provider failure", () => { + const { result, terminal } = settle(nativeFailure("overloaded", "This model is currently experiencing high demand.", { httpStatus: 503, status: "UNAVAILABLE" })); + expect(result.status).toBe("failed"); + const failure = readProviderFailure((terminal.error as Record).providerFailure); + expect(failure).toMatchObject({ provider: "antigravity", phase: "turn", category: "overloaded", httpStatus: 503, + providerCode: "UNAVAILABLE", retryability: "transient", message: "This model is currently experiencing high demand." }); + }); + + it("classifies a per-minute rate limit as transient with its retry time, distinct from overload", () => { + const before = Date.now(); + const { terminal } = settle(nativeFailure("rate_limit", "You exceeded your current quota.", { httpStatus: 429, status: "RESOURCE_EXHAUSTED", retryAfterSeconds: 23 })); + const failure = readProviderFailure((terminal.error as Record).providerFailure)!; + expect(failure).toMatchObject({ category: "rate_limit", httpStatus: 429, retryability: "transient" }); + expect(Date.parse(failure.retryAt!)).toBeGreaterThanOrEqual(before + 23_000); + }); + + it("reports a model the connection cannot use as a permanent typed refusal without provider text", () => { + const { result, terminal } = settle(nativeFailure("model_unavailable", "The selected model is not available for this connection.", { httpStatus: 429, status: "RESOURCE_EXHAUSTED" })); + expect(result).toEqual({ status: "failed", error: { code: ANTIGRAVITY_MODEL_UNAVAILABLE, retryable: false, + message: "The selected model is not available for this connection.", model: "gemini-4-neon-high", route: "api_key" } }); + const error = terminal.error as Record; + expect(error).toMatchObject({ code: "antigravity_model_unavailable", retryable: false, model: "gemini-4-neon-high", route: "api_key" }); + expect(readProviderFailure(error.providerFailure)).toMatchObject({ category: "model_unavailable", providerCode: "antigravity_model_unavailable", + retryability: "requires_action", message: "The selected model is not available for this connection." }); + expect(JSON.stringify(terminal)).not.toMatch(/quota|fixture-secret/i); + }); + + it("keeps an unmarked or malformed native failure on the generic typed path", () => { + const meta = nativeFailure("rate_limit", "Slow down", { httpStatus: 9999, route: "other", model: "bad\u0000model" }); + expect(acpxTypedTerminalSessionFailure(meta)?.provider).toEqual({ kind: "rate_limit" }); + expect(acpxTypedTerminalSessionFailure({ jetbrains: meta.jetbrains })?.provider).toBeUndefined(); + expect(acpxTypedTerminalSessionFailure({ ...meta, paperclipAntigravityFailure: { schema: "other", kind: "rate_limit" } })?.provider).toBeUndefined(); + // A completed turn without any failure stays completed. + expect(typedTerminalTurnResult({ status: "completed", stopReason: "end_turn", _meta: {} })).toMatchObject({ status: "completed" }); + }); + + it("keeps question and permission claims withheld while the declaration is pending", () => { + if (QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus !== "pending") return; + expect(ACPX_CAPABILITY_PROFILES.antigravity).toMatchObject({ qualification: "pending", questions: "not-exposed", permissions: "unverified" }); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/candidate-admission.antigravity-release.test.ts b/packages/paperclip-runner/src/drivers/acpx/candidate-admission.antigravity-release.test.ts new file mode 100644 index 00000000000..fad91ede069 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/candidate-admission.antigravity-release.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it, vi } from "vitest"; + +const status = vi.hoisted(() => ({ released: false })); +// Simulate the qualification flip: the same build with Antigravity's +// `qualificationStatus` removed from its declaration. +vi.mock("./qualified-profiles.js", async importOriginal => { + const actual = await importOriginal(); + const profile = (agent: string) => { + const value = actual.QUALIFIED_ACPX_PROFILES[agent as keyof typeof actual.QUALIFIED_ACPX_PROFILES]; + if (agent !== "antigravity" || !status.released) return value; + const { qualificationStatus: _pending, ...released } = value; + return released; + }; + const QUALIFIED_ACPX_PROFILES = Object.fromEntries(Object.keys(actual.QUALIFIED_ACPX_PROFILES).map(agent => [agent, undefined])); + for (const agent of Object.keys(QUALIFIED_ACPX_PROFILES)) Object.defineProperty(QUALIFIED_ACPX_PROFILES, agent, { get: () => profile(agent), enumerable: true }); + return { + ...actual, QUALIFIED_ACPX_PROFILES, + assertAcpxProfileReleased: (agent: string) => { + if ((profile(agent) as { qualificationStatus?: string }).qualificationStatus === "pending") { + throw Object.assign(new Error(`ACPX ${agent} qualification is pending; this build cannot launch the provider.`), { code: "ACPX_PROFILE_QUALIFICATION_PENDING" }); + } + }, + resolveQualifiedAcpxProfile: (agent: string, model: string) => ({ ...structuredClone(profile(agent)), qualificationModel: model, reportedModelId: model }), + }; +}); + +const { parseAcpxCandidateAdmission, bindAcpxCandidateAdmission, assertAcpxExecutionAdmission } = await import("./candidate-admission.js"); +const { QUALIFIED_ACPX_PROFILES, resolveQualifiedAcpxProfile } = await import("./qualified-profiles.js"); +const { ANTIGRAVITY_DISTRIBUTION_PINS } = await import("./generated-profiles.js"); + +const now = 1_800_000_000_000; +const model = "gemini-3.8-flash-low"; +const expected = { companyId: "company-antigravity", agent: "antigravity", model }; +const candidate = () => ({ + schema: "paperclip.acpx-candidate-admission.v1" as const, ...expected, agent: "antigravity" as const, + profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, + nativeClosureDigest: `sha256:${ANTIGRAVITY_DISTRIBUTION_PINS["darwin-arm64"].closureSha256}`, + platform: "darwin" as const, architecture: "arm64" as const, expiresAt: now + 60_000, +}); + +describe("Antigravity candidate admission across the qualification flip", () => { + it("binds operator candidate authority only while the profile is pending", () => { + status.released = false; + expect(QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus).toBe("pending"); + expect(parseAcpxCandidateAdmission(candidate(), expected, now)).toEqual(candidate()); + expect(() => assertAcpxExecutionAdmission(resolveQualifiedAcpxProfile("antigravity", model))).toThrow("qualification is pending"); + }); + + it("rejects every candidate grant once the declaration is released, and launches without one", () => { + status.released = true; + try { + expect(QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus).toBeUndefined(); + expect(() => parseAcpxCandidateAdmission(candidate(), expected, now)).toThrow(expect.objectContaining({ code: "ACPX_CANDIDATE_ADMISSION_INVALID" })); + expect(() => bindAcpxCandidateAdmission(candidate(), { runId: "run-1", normalizedSessionId: "session-1" })).toThrow(expect.objectContaining({ code: "ACPX_CANDIDATE_ADMISSION_INVALID" })); + const profile = resolveQualifiedAcpxProfile("antigravity", model); + expect(() => assertAcpxExecutionAdmission(profile)).not.toThrow(); + // A saved or injected startup grant cannot ride along a released launch. + expect(() => assertAcpxExecutionAdmission(profile, { ...candidate(), runId: "run-1", normalizedSessionId: "session-1" })).toThrow(); + } finally { status.released = false; } + }); +}); 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 f1a63094cb9..5ad97d944b9 100644 --- a/packages/paperclip-runner/src/drivers/acpx/candidate-admission.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/candidate-admission.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { KIMI_DISTRIBUTION_CLOSURE_SHA256 } from "./kimi-closure-pins.js"; import { ANTIGRAVITY_DISTRIBUTION_PINS } from "./generated-profiles.js"; import { assertAcpxProfileReleased, resolveQualifiedAcpxProfile } from "./qualified-profiles.js"; -import { assertAcpxExecutionAdmission, bindAcpxCandidateAdmission, parseAcpxCandidateAdmission, parseAcpxCandidateStartupAdmission, type AcpxCandidateAdmission } from "./candidate-admission.js"; +import { assertAcpxExecutionAdmission, bindAcpxCandidateAdmission, isAntigravityNativeTarget, parseAcpxCandidateAdmission, parseAcpxCandidateStartupAdmission, type AcpxCandidateAdmission } from "./candidate-admission.js"; import historicalKimi from "../../../test/fixtures/kimi-profile-v16-identity.json" with { type: "json" }; import { verifyAcpxProfileInstallation } from "./profile-installation.js"; import { AcpxRuntimeHost } from "./runtime-host.js"; @@ -40,6 +40,21 @@ describe("operator candidate execution admission", () => { expect(() => parseAcpxCandidateAdmission({ ...candidate(), ...change }, expected, now)).toThrow(expect.objectContaining({ code: "ACPX_CANDIDATE_ADMISSION_INVALID" })); }); + it("admits each verified native closure only for its own platform", () => { + expect(Object.keys(ANTIGRAVITY_DISTRIBUTION_PINS).sort()).toEqual(["darwin-arm64", "linux-arm64", "linux-x64"]); + for (const target of Object.keys(ANTIGRAVITY_DISTRIBUTION_PINS) as Array) { + const [platform, architecture] = target.split("-"); + const record = { ...candidate(), platform, architecture, nativeClosureDigest: `sha256:${ANTIGRAVITY_DISTRIBUTION_PINS[target].closureSha256}` }; + expect(parseAcpxCandidateAdmission(record, expected, now)).toEqual(record); + expect(isAntigravityNativeTarget(platform, architecture)).toBe(true); + for (const other of Object.keys(ANTIGRAVITY_DISTRIBUTION_PINS).filter(other => other !== target) as Array) { + expect(() => parseAcpxCandidateAdmission({ ...record, nativeClosureDigest: `sha256:${ANTIGRAVITY_DISTRIBUTION_PINS[other].closureSha256}` }, expected, now)).toThrow(); + } + } + expect(isAntigravityNativeTarget("darwin", "x64")).toBe(false); + expect(() => parseAcpxCandidateAdmission({ ...candidate(), architecture: "x64" }, expected, now)).toThrow(); + }); + it("binds actual startup run/session and refuses replay against another identity", () => { const current = { ...candidate(), expiresAt: Date.now() + 60_000 }; const startup = bindAcpxCandidateAdmission(current, { runId: "actual-run", normalizedSessionId: "actual-session" }); diff --git a/packages/paperclip-runner/src/drivers/acpx/candidate-admission.ts b/packages/paperclip-runner/src/drivers/acpx/candidate-admission.ts index 1ba3d0f817d..74933ee5311 100644 --- a/packages/paperclip-runner/src/drivers/acpx/candidate-admission.ts +++ b/packages/paperclip-runner/src/drivers/acpx/candidate-admission.ts @@ -21,6 +21,11 @@ export interface AcpxCandidateStartupAdmission extends AcpxCandidateAdmission { normalizedSessionId: string; } +/** A host with a verified, patched Antigravity closure. */ +export function isAntigravityNativeTarget(platform: unknown, architecture: unknown): boolean { + return typeof platform === "string" && typeof architecture === "string" && Object.hasOwn(ANTIGRAVITY_DISTRIBUTION_PINS, `${platform}-${architecture}`); +} + const BASE_FIELDS = ["schema", "companyId", "agent", "model", "profileDigest", "nativeClosureDigest", "platform", "architecture", "expiresAt"]; const stableId = (value: unknown): value is string => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,239}$/.test(value); const invalid = (): never => { throw Object.assign(new Error("ACPX candidate admission is missing, expired, or does not match the exact authorized execution"), { code: "ACPX_CANDIDATE_ADMISSION_INVALID", retryable: false }); }; @@ -35,15 +40,17 @@ export function parseAcpxCandidateAdmission( const profile = entry.agent === "antigravity" ? QUALIFIED_ACPX_PROFILES.antigravity : entry.agent === "kimi" ? QUALIFIED_ACPX_PROFILES.kimi : undefined; const target = `${entry.platform}-${entry.architecture}`; - const closure = entry.agent === "antigravity" && target === "darwin-arm64" - ? ANTIGRAVITY_DISTRIBUTION_PINS["darwin-arm64"].closureSha256 + const closure = entry.agent === "antigravity" && isAntigravityNativeTarget(entry.platform, entry.architecture) + ? ANTIGRAVITY_DISTRIBUTION_PINS[target as keyof typeof ANTIGRAVITY_DISTRIBUTION_PINS].closureSha256 : entry.agent === "kimi" && (target === "darwin-arm64" || target === "linux-x64") ? KIMI_DISTRIBUTION_CLOSURE_SHA256[target] : undefined; if (!Number.isSafeInteger(now) || now < 0 || Object.keys(entry).length !== BASE_FIELDS.length || Object.keys(entry).some(key => !BASE_FIELDS.includes(key)) || entry.schema !== "paperclip.acpx-candidate-admission.v1" || !stableId(entry.companyId) || entry.companyId !== expected.companyId || !profile || entry.agent !== expected.agent - || entry.agent === "kimi" && profile.qualificationStatus !== "pending" + // A released profile never takes operator candidate authority, so the + // qualification flip is only a declaration change. + || profile.qualificationStatus !== "pending" || typeof entry.model !== "string" || entry.model !== expected.model || !entry.model.trim() || entry.model !== entry.model.trim() || Buffer.byteLength(entry.model) > 512 || /[\u0000-\u001f\u007f]/.test(entry.model) || ["auto", "default"].includes(entry.model.toLowerCase()) diff --git a/packages/paperclip-runner/src/drivers/acpx/capability-profiles.antigravity-release.test.ts b/packages/paperclip-runner/src/drivers/acpx/capability-profiles.antigravity-release.test.ts new file mode 100644 index 00000000000..a882cf9a361 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/capability-profiles.antigravity-release.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it, vi } from "vitest"; + +// The same build with Antigravity's `qualificationStatus` removed. +vi.mock("./qualified-profiles.js", async importOriginal => { + const actual = await importOriginal(); + const { qualificationStatus: _pending, ...antigravity } = actual.QUALIFIED_ACPX_PROFILES.antigravity; + return { ...actual, QUALIFIED_ACPX_PROFILES: { ...actual.QUALIFIED_ACPX_PROFILES, antigravity } }; +}); + +describe("Antigravity capability claims at the qualification flip", () => { + it("exposes form questions and interactive permissions once released", async () => { + const { ACPX_CAPABILITY_PROFILES } = await import("./capability-profiles.js"); + expect(ACPX_CAPABILITY_PROFILES.antigravity).toMatchObject({ questions: "form", permissions: "interactive" }); + // Recovery stays unverified until a live cell proves a cross-process load. + expect(ACPX_CAPABILITY_PROFILES.antigravity.recovery).toBe("unverified"); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/capability-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/capability-profiles.ts index cb90254d413..5518dce8e0f 100644 --- a/packages/paperclip-runner/src/drivers/acpx/capability-profiles.ts +++ b/packages/paperclip-runner/src/drivers/acpx/capability-profiles.ts @@ -1,4 +1,10 @@ -import type { QualifiedAcpxAgent } from "./qualified-profiles.js"; +import { QUALIFIED_ACPX_PROFILES, type QualifiedAcpxAgent } from "./qualified-profiles.js"; + +/** Antigravity's interactive claims follow its declaration: 1.5.2 questions + * arrive as `interaction_*` permission callbacks that the admission guard turns + * into forms, and every other permission goes through the interactive runner + * policy. They take effect with the qualification flip and not before. */ +const ANTIGRAVITY_RELEASED = QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus !== "pending"; export interface AcpxCapabilityProfile { readonly displayName: string; @@ -22,7 +28,8 @@ export interface AcpxCapabilityProfile { export const ACPX_CAPABILITY_PROFILES: Readonly> = { antigravity: { displayName: "Google Antigravity", qualification: "pending", models: "unverified", - permissions: "unverified", questions: "not-exposed", plans: "semantic-only", tools: "unverified", + permissions: ANTIGRAVITY_RELEASED ? "interactive" : "unverified", questions: ANTIGRAVITY_RELEASED ? "form" : "not-exposed", + plans: "semantic-only", tools: "unverified", recovery: "unverified", usage: "unverified", steering: "unsupported", followUp: "controller-queue", artifacts: "policy_disabled", extensionRequests: [], extensionNotifications: [], }, diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts index f68a0425120..ff270d8fefa 100644 --- a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts @@ -708,7 +708,7 @@ describe("Copilot build-owned installation", () => { distributionRoot: root, manifestPath: `${root}/.paperclip-copilot-closure.json`, expectedClosureSha256: COPILOT_CLOSURE_SHA256[`${process.platform}-${process.arch}` as keyof typeof COPILOT_CLOSURE_SHA256], executable: "copilot", fixedArguments: COPILOT_LAUNCH_ARGUMENTS, isolatedCacheEnvironmentName: "COPILOT_PKG_CACHE_HOME", - copilotDistributionDirectory: "distribution", + copilotDistributionDirectory: "distribution", storeFamily: "copilot", }); expect(result.commandDigest).toBe(QUALIFIED_ACPX_PROFILES.copilot.commandDigest); expect(result.openCommand).toBe(openCommand); diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.ts index 320005f173b..ca81f89629f 100644 --- a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.ts @@ -29,6 +29,7 @@ export async function verifyCopilotInstallation(profile: AcpxReleaseProfile): Pr executable: "copilot", fixedArguments: COPILOT_LAUNCH_ARGUMENTS, isolatedCacheEnvironmentName: "COPILOT_PKG_CACHE_HOME", copilotDistributionDirectory: "distribution", + storeFamily: "copilot", }); } catch { throw Object.assign(new Error("Install the verified Copilot runtime beside the admitted sidecar."), { code: "COPILOT_INSTALLATION_INVALID", retryable: false }); } diff --git a/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts b/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts index d2eb43eae7b..a88fb0a482c 100644 --- a/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts @@ -26,6 +26,7 @@ export function cursorNativeDistributionSpec( executable: distribution.executable, entrypoint: distribution.entrypoint, fixedArguments: [...CURSOR_FIXED_ARGUMENTS], + storeFamily: "cursor", }; } diff --git a/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts index f0cb090f298..c50d3cad2cc 100644 --- a/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts +++ b/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts @@ -1,4 +1,4 @@ -// Generated from acpx-profiles.json and cursor-distributions.json. Do not edit. +// Generated from acpx-profiles.json, cursor-distributions.json and antigravity-distributions.json. Do not edit. export const QUALIFIED_ACPX_VERSION = "0.22.0" as const; export const ACPX_DRIVER_KIND = "acpx_runtime" as const; export const ACPX_DRIVER_PROTOCOL_VERSION = 1 as const; @@ -11,10 +11,10 @@ export const QUALIFIED_ACPX_PROFILE_DATA = { "agent": "antigravity", "agentProfileVersion": 1, "agentServerPackage": "native:antigravity-acp", - "agentServerVersion": "1.4.3", + "agentServerVersion": "1.5.2", "agentRuntimePackage": "native:antigravity-localharness", - "agentRuntimeVersion": "1.4.3", - "commandDigest": "sha256:acf5f574b6b9ec4388ff9d081890caa330e66bf1ae3fe3b08e7f0fb0e851b9ce", + "agentRuntimeVersion": "1.5.2", + "commandDigest": "sha256:61ac14bf03ce4bbf8afe1f5a263b854517ec588d8407fe2d8f17c9fc0c037c4b", "qualificationStatus": "pending", "permissionPolicy": "interactive" }, @@ -129,10 +129,26 @@ export const CURSOR_DISTRIBUTION_PINS = { } } as const; +export const ANTIGRAVITY_RUNTIME_VERSION = "1.5.2" as const; + export const ANTIGRAVITY_DISTRIBUTION_PINS = { "darwin-arm64": { - "closureSha256": "044792d793e203bc8b4524a418f1816c4d34db67bb41fa4bae5947a050c49b4a", + "closureSha256": "ab9df40a64806a8e1812234ce5331e04d1c6b5f8c7e5bdbb456cd645e58c5aad", "executable": "agy_acp_server.par", "args": [] + }, + "linux-x64": { + "closureSha256": "be35d65a32667550b5474588d705e6987a813e2fa619cf5db7d82d141c3c05fb", + "executable": "agy_acp_server.par", + "args": [ + "--uid=" + ] + }, + "linux-arm64": { + "closureSha256": "46c36293779283c1f933eb438a143d116421a331f614601c754f1b94d9dc171a", + "executable": "agy_acp_server.par", + "args": [ + "--uid=" + ] } } as const; diff --git a/packages/paperclip-runner/src/drivers/acpx/kimi-installation.ts b/packages/paperclip-runner/src/drivers/acpx/kimi-installation.ts index a66954aaa46..a8ab94631f4 100644 --- a/packages/paperclip-runner/src/drivers/acpx/kimi-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/kimi-installation.ts @@ -57,6 +57,7 @@ export async function verifyKimiInstallation(profile: AcpxReleaseProfile): Promi executable: "node/bin/node", entrypoint, fixedArguments: ["acp"], + storeFamily: "kimi", }); return Object.freeze({ commandDigest: profile.commandDigest, diff --git a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.store.test.ts b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.store.test.ts new file mode 100644 index 00000000000..4dcb04ea6d7 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.store.test.ts @@ -0,0 +1,360 @@ +import { once } from "node:events"; +import { constants } from "node:fs"; +import { fork, spawn, spawnSync } from "node:child_process"; +import { chmod, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, stat, writeFile, type FileHandle } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { verifyNativeAcpxInstallation } from "./installation-integrity.js"; +import { createNativeAcpxDistributionSnapshot, NATIVE_ACPX_STORE_ROOT_ENV, NativeAcpxStoreRootError, readNativeAcpxDistributionEntries, pruneNativeAcpxStores, scheduledNativeAcpxStorePrune, type NativeAcpxDistributionInput } from "./native-distribution-integrity.js"; +import { filePrototype, fixture, hash, output, roots, storeRoot, unsealAndRemove, useNativeStoreFixtures } from "./native-distribution-integrity.test-support.js"; + +vi.mock("node:fs/promises", async (importOriginal) => { + const original = await importOriginal(); + return { ...original, open: vi.fn(original.open), rm: vi.fn(original.rm), mkdir: vi.fn(original.mkdir), chmod: vi.fn(original.chmod), rename: vi.fn(original.rename) }; +}); + +useNativeStoreFixtures(); + +describe("native ACPX verified store reuse", () => { + const storeFiles = (declaration: NativeAcpxDistributionInput) => join(storeRoot, declaration.expectedClosureSha256, "distribution"); + const createdFiles = () => vi.mocked(open).mock.calls.filter(([, flags]) => typeof flags === "number" && (flags & constants.O_CREAT) !== 0).map(([path]) => String(path)); + async function tamper(path: string, bytes: string): Promise { + await chmod(path, 0o700); await writeFile(path, bytes); await chmod(path, 0o500); + } + + it("verifies a closure once; a later launch reads and copies no closure bytes", async () => { + const declaration = await fixture(); + const prototype = await filePrototype(join(declaration.distributionRoot, "runtime")); + const read = vi.spyOn(prototype, "read"); + expect((await output((await (await verifyNativeAcpxInstallation(declaration)).openCommand()).spawn())).text).toBe("native:fixed:none"); + expect(read).toHaveBeenCalled(); + read.mockClear(); vi.mocked(open).mockClear(); + // A new installation object models the next run in a fresh runner. + const lease = await (await verifyNativeAcpxInstallation(declaration)).openCommand(); + expect(read).not.toHaveBeenCalled(); + expect(createdFiles().filter(path => path.startsWith(storeRoot))).toEqual([]); + expect(vi.mocked(open).mock.calls.map(([path]) => String(path))).not.toContain(join(declaration.distributionRoot, "runtime")); + expect(await output(lease.spawn())).toEqual({ text: "native:fixed:none", error: "", code: 0 }); + await lease.close(); + }); + + it("detects a tampered verified store, retires it and relaunches from a fresh verification", async () => { + const declaration = await fixture(); + const installation = await verifyNativeAcpxInstallation(declaration); + await (await installation.openCommand()).close(); + const stored = join(storeFiles(declaration), "runtime"); + const before = await stat(stored); + const original = await readFile(stored); + await tamper(stored, '#!/bin/sh\nprintf "tampered:%s:%s" "$1" "${COPILOT_PKG_CACHE_HOME:-n}"\n'.slice(0, original.length).padEnd(original.length, "#")); + vi.mocked(open).mockClear(); + const lease = await installation.openCommand(); + expect(await output(lease.spawn())).toEqual({ text: "native:fixed:none", error: "", code: 0 }); + await lease.close(); + expect(await readFile(stored)).toEqual(original); + // The file system may reuse the freed inode, so the rebuild is proven by + // the new store's files being written, not by a different inode. + expect(createdFiles().filter(path => path.startsWith(storeRoot) && path.endsWith("/runtime"))).toHaveLength(1); + expect((await stat(stored)).ctimeMs).toBeGreaterThanOrEqual(before.ctimeMs); + expect((await readdir(storeRoot)).filter(name => name.startsWith(".retired-") || name.startsWith(".staging-"))).toEqual([]); + }); + + it("refuses to spawn an executable whose bytes changed after the launch was admitted", async () => { + const declaration = await fixture(); + const lease = await (await verifyNativeAcpxInstallation(declaration)).openCommand(); + const stored = join(storeFiles(declaration), "runtime"); + const size = (await stat(stored)).size; + await tamper(stored, '#!/bin/sh\nprintf tampered-code-executed\n'.padEnd(size, "#")); + const result = await output(lease.spawn()); + expect(result.code).not.toBe(0); + expect(result.error).toContain("Native ACPX executable changed before spawn"); + expect(result.text).not.toContain("tampered-code-executed"); + await lease.close(); + }); + + it("refuses an executable swapped into the store together with a rewritten verification record", async () => { + const declaration = await fixture(); + const installation = await verifyNativeAcpxInstallation(declaration); + await (await installation.openCommand()).close(); + const store = join(storeRoot, declaration.expectedClosureSha256); + const distribution = join(store, "distribution"); + const stored = join(distribution, "runtime"); + const original = await readFile(stored); + // A process running as the runner's user can unseal the store, replace the + // executable and rewrite the record with the replacement's identity. The + // record is not a trust anchor: the executable must still match its pin. + await chmod(store, 0o700); await chmod(distribution, 0o700); + await rm(stored); + await writeFile(stored, "#!/bin/sh\nprintf forged-code-executed\n".padEnd(original.length, "#"), { mode: 0o500 }); + await chmod(stored, 0o500); + const recordPath = join(store, "verified.json"); + const record = JSON.parse(await readFile(recordPath, "utf8")) as { entries: Array<{ path: string; identity: string[] }> }; + const replaced = await stat(stored, { bigint: true }); + for (const entry of record.entries) { + if (entry.path === "runtime") entry.identity = [replaced.dev, replaced.ino, replaced.size, replaced.mtimeNs, replaced.ctimeNs].map(String); + } + await chmod(recordPath, 0o600); await writeFile(recordPath, JSON.stringify(record)); await chmod(recordPath, 0o400); + await chmod(distribution, 0o500); await chmod(store, 0o500); + const lease = await installation.openCommand(); + const result = await output(lease.spawn()); + expect(result.text).not.toContain("forged-code-executed"); + expect(result.code).not.toBe(0); + expect(result.error).toContain("Native ACPX executable changed before spawn"); + await lease.close(); + }); + + it("re-hashes a changed installed source in place without copying it again", async () => { + const declaration = await fixture(); + await (await (await verifyNativeAcpxInstallation(declaration)).openCommand()).close(); + const storeBefore = await stat(join(storeFiles(declaration), "runtime")); + const source = join(await realpath(declaration.distributionRoot), "runtime"); + await writeFile(source, await readFile(source)); + const prototype = await filePrototype(source); + const read = vi.spyOn(prototype, "read"); vi.mocked(open).mockClear(); + const lease = await (await verifyNativeAcpxInstallation(declaration)).openCommand(); + expect(vi.mocked(open).mock.calls.map(([path]) => String(path))).toContain(source); + expect(read).toHaveBeenCalled(); + expect(createdFiles().filter(path => path.startsWith(storeRoot))).toEqual([]); + expect((await stat(join(storeFiles(declaration), "runtime"))).ino).toBe(storeBefore.ino); + await lease.close(); + // A source changed to different bytes is still refused, as before. + await writeFile(source, "altered"); + await expect((await verifyNativeAcpxInstallation(declaration)).openCommand()).rejects.toThrow(); + }); + + it("never renames a sealed store directory, which some macOS releases refuse", async () => { + const actual = await vi.importActual("node:fs/promises"); + // Model macOS 15: moving a directory its owner cannot write fails. + vi.mocked(rename).mockImplementation(async (from, to) => { + const info = await actual.lstat(from); + if (info.isDirectory() && (info.mode & 0o200) === 0) throw Object.assign(new Error("EACCES: permission denied, rename"), { code: "EACCES" }); + return await actual.rename(from, to); + }); + const old = { ...await fixture(), storeFamily: "sealed-provider" }; + const installation = await verifyNativeAcpxInstallation(old); + const first = await installation.openCommand(); + expect((await output(first.spawn())).text).toBe("native:fixed:none"); + await first.close(); + expect((await stat(join(storeRoot, old.expectedClosureSha256))).mode & 0o777).toBe(0o500); + // A damaged store is retired and rebuilt. + const stored = join(storeFiles(old), "runtime"); + await tamper(stored, (await readFile(stored, "utf8")).replace("native", "nativf")); + const second = await installation.openCommand(); + expect((await output(second.spawn())).text).toBe("native:fixed:none"); + await second.close(); + // A superseded store no live runner holds is retired. + await rename(join(storeRoot, `${old.expectedClosureSha256}.lease-${process.pid}`), join(storeRoot, `${old.expectedClosureSha256}.lease-${spawnSync("true").pid!}`)); + expect(await pruneNativeAcpxStores(storeRoot, "sealed-provider", hash("next"))).toEqual([old.expectedClosureSha256]); + expect((await readdir(storeRoot)).filter(name => name.startsWith("."))).toEqual([]); + }); + + it("publishes exactly one verified store for concurrent first launches", async () => { + const declaration = await fixture(); + const installation = await verifyNativeAcpxInstallation(declaration); + const leases = await Promise.all([installation.openCommand(), installation.openCommand(), installation.openCommand()]); + for (const lease of leases) expect((await output(lease.spawn())).text).toBe("native:fixed:none"); + await Promise.all(leases.map(lease => lease.close())); + expect((await readdir(storeRoot)).filter(name => !name.endsWith(".source.json"))).toEqual([declaration.expectedClosureSha256]); + }); + + it("refuses to launch from a configured store root another user could write", async () => { + const declaration = await fixture(); + const shared = await mkdtemp(join(tmpdir(), "native-acpx-shared-store-")); roots.push(shared); + await chmod(shared, 0o777); + process.env[NATIVE_ACPX_STORE_ROOT_ENV] = shared; + const failure = (await verifyNativeAcpxInstallation(declaration)).openCommand(); + await expect(failure).rejects.toBeInstanceOf(NativeAcpxStoreRootError); + await expect(failure).rejects.toThrow(`${NATIVE_ACPX_STORE_ROOT_ENV} must name an absolute directory owned by the runner user`); + expect(await readdir(shared)).toEqual([]); + }); + + describe("an unsafe default store root", () => { + const previousTmpdir = process.env.TMPDIR; + let temporary = ""; + beforeEach(async () => { + temporary = await realpath(await mkdtemp(join(tmpdir(), "native-acpx-tmpdir-"))); roots.push(temporary); + delete process.env[NATIVE_ACPX_STORE_ROOT_ENV]; + process.env.TMPDIR = temporary; + // Another user squatted the per-uid default root. + await mkdir(join(temporary, `paperclip-verified-native-${process.getuid!()}`), { mode: 0o777 }); + await chmod(join(temporary, `paperclip-verified-native-${process.getuid!()}`), 0o777); + }); + afterEach(() => { if (previousTmpdir === undefined) delete process.env.TMPDIR; else process.env.TMPDIR = previousTmpdir; }); + const privateStores = async () => (await readdir(temporary)).filter(name => /^paperclip-verified-native-(?!\d+$)/.test(name)); + + it("reports the fallback and removes the process-private store with its last launch", async () => { + const declaration = await fixture(); + const warn = vi.spyOn(process, "emitWarning").mockImplementation(() => undefined); + const installation = await verifyNativeAcpxInstallation(declaration); + const first = await installation.openCommand(); + const second = await installation.openCommand(); + expect(await privateStores()).toHaveLength(1); + expect(warn).toHaveBeenCalledWith(expect.stringContaining("default_store_root_not_private"), expect.objectContaining({ code: "PAPERCLIP_ACPX_NATIVE_STORE_FALLBACK" })); + expect(JSON.stringify(warn.mock.calls)).not.toContain(temporary); + expect((await output(first.spawn())).text).toBe("native:fixed:none"); + await first.close(); + expect(await privateStores()).toHaveLength(1); + expect((await output(second.spawn())).text).toBe("native:fixed:none"); + await second.close(); + expect(await privateStores()).toEqual([]); + expect(await readdir(join(temporary, `paperclip-verified-native-${process.getuid!()}`))).toEqual([]); + }); + + it("retries a failed launch cleanup and keeps the private store until it succeeds", async () => { + vi.spyOn(process, "emitWarning").mockImplementation(() => undefined); + const declaration = await fixture(); + const snapshot = await createNativeAcpxDistributionSnapshot(declaration, await readNativeAcpxDistributionEntries(declaration)); + await snapshot.commandDirectory.close(); + const actual = await vi.importActual("node:fs/promises"); + let failures = 1; + vi.mocked(rm).mockImplementation(async (path, options) => { + if (failures > 0 && String(path).includes("paperclip-acpx-native-")) { failures--; throw Object.assign(new Error("EBUSY: resource busy"), { code: "EBUSY" }); } + return await actual.rm(path, options); + }); + await expect(snapshot.snapshot.close()).rejects.toThrow("EBUSY"); + expect(await privateStores()).toHaveLength(1); + await snapshot.snapshot.close(); + expect(await privateStores()).toEqual([]); + await snapshot.snapshot.close(); + }); + }); + + describe("superseded closure stores", () => { + const script = (marker: string) => `#!/bin/sh\nprintf "${marker}:%s" "$1"\n`; + const launch = async (declaration: NativeAcpxDistributionInput) => { + const lease = await (await verifyNativeAcpxInstallation(declaration)).openCommand(); + const result = await output(lease.spawn()); + await lease.close(); + return result.text; + }; + /** Hand this process's lease on `closure` to a runner process that has exited. */ + const releaseToExitedRunner = async (closure: string) => { + const exited = spawnSync("true").pid!; + await rename(join(storeRoot, `${closure}.lease-${process.pid}`), join(storeRoot, `${closure}.lease-${exited}`)); + }; + + it("retires a provider's superseded closure once no live runner holds it, and nothing else", async () => { + const old = { ...await fixture({ script: script("old") }), storeFamily: "fixture-provider" }; + const other = { ...await fixture({ script: script("other") }), storeFamily: "other-provider" }; + const unmarked = await fixture({ script: script("unmarked") }); + for (const declaration of [old, other, unmarked]) await launch(declaration); + await releaseToExitedRunner(old.expectedClosureSha256); + await releaseToExitedRunner(other.expectedClosureSha256); + const current = { ...await fixture({ script: script("current") }), storeFamily: "fixture-provider" }; + expect(await launch(current)).toBe("current:fixed"); + expect(await scheduledNativeAcpxStorePrune("fixture-provider", current.expectedClosureSha256)).toEqual([old.expectedClosureSha256]); + const names = await readdir(storeRoot); + expect(names.filter(name => name.startsWith(old.expectedClosureSha256))).toEqual([]); + expect(names).toEqual(expect.arrayContaining([current.expectedClosureSha256, other.expectedClosureSha256, unmarked.expectedClosureSha256])); + expect(names.filter(name => name.startsWith(".retiring-") || name.startsWith(".retired-"))).toEqual([]); + // A later launch of the retired closure verifies it again from source. + expect(await launch(old)).toBe("old:fixed"); + }); + + const moduleUrl = new URL("./installation-integrity.ts", import.meta.url).href; + const storeModuleUrl = new URL("./native-distribution-integrity.ts", import.meta.url).href; + /** Runs a script in a separate runner process sharing this test's store root. */ + const runChild = async (name: string, body: string) => { + const scripts = await realpath(await mkdtemp(join(tmpdir(), "native-acpx-race-scripts-"))); roots.push(scripts); + const file = join(scripts, name); + await writeFile(file, body); + const child = fork(file, [], { execArgv: ["--import", "tsx"], stdio: ["ignore", "pipe", "pipe", "ipc"], env: { ...process.env, [NATIVE_ACPX_STORE_ROOT_ENV]: storeRoot } }); + const result = await output(child); + expect(result.code, result.error).toBe(0); + return result.text.trim(); + }; + /** Another runner verifies the store, runs it and exits, so no live lease holds it. */ + const verifyInExitedRunner = async (declaration: NativeAcpxDistributionInput) => { + expect(await runChild("verify.mjs", [ + `const { verifyNativeAcpxInstallation } = await import(${JSON.stringify(moduleUrl)});`, + `const lease = await (await verifyNativeAcpxInstallation(${JSON.stringify(declaration)})).openCommand();`, + "await lease.close();", 'console.log("verified");', + ].join("\n"))).toBe("verified"); + }; + + it("keeps a store that another runner process starts using while it is being pruned", async () => { + const family = "race-provider"; + const old = { ...await fixture({ script: script("raced") }), storeFamily: family }; + const keep = hash("current closure"); + await verifyInExitedRunner(old); + // This runner starts using the store. Right after it has checked the + // store, a third runner prunes the closure as superseded. + const actual = await vi.importActual("node:fs/promises"); + let pruned: string | undefined; + vi.mocked(open).mockImplementation((async (path: Parameters[0], ...rest: unknown[]) => { + if (pruned === undefined && String(path) === join(storeRoot, `${old.expectedClosureSha256}.source.json`)) { + pruned = await runChild("prune.mjs", [ + `const { pruneNativeAcpxStores } = await import(${JSON.stringify(storeModuleUrl)});`, + `console.log(JSON.stringify(await pruneNativeAcpxStores(${JSON.stringify(storeRoot)}, ${JSON.stringify(family)}, ${JSON.stringify(keep)})));`, + ].join("\n")); + } + return await (actual.open as (...args: unknown[]) => Promise)(path, ...rest); + }) as typeof open); + const lease = await (await verifyNativeAcpxInstallation(old)).openCommand(); + vi.mocked(open).mockImplementation(actual.open); + expect(pruned).toBe("[]"); + expect(await output(lease.spawn())).toEqual({ text: "raced:fixed", error: "", code: 0 }); + await lease.close(); + const names = await readdir(storeRoot); + expect(names).toEqual(expect.arrayContaining([old.expectedClosureSha256, `${old.expectedClosureSha256}.family`, `${old.expectedClosureSha256}.source.json`])); + expect(names.filter(name => name.startsWith(".retiring-") || name.includes(".pruning-"))).toEqual([]); + }, 60_000); + + it("waits for a live prune of the closure before reading its store, and cleans trees an exited pruner left", async () => { + const old = { ...await fixture({ script: script("waited") }), storeFamily: "wait-provider" }; + await verifyInExitedRunner(old); + // A live process (this test's helper) is mid-prune of the closure. + const exitedPruner = spawnSync("true").pid!; + const helper = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" }); + const marker = join(storeRoot, `${old.expectedClosureSha256}.pruning-${helper.pid}`); + await writeFile(marker, ""); + const abandoned = join(storeRoot, `.retiring-${exitedPruner}-left-behind`); + await mkdir(join(abandoned, "distribution"), { recursive: true }); await chmod(join(abandoned, "distribution"), 0o500); await chmod(abandoned, 0o500); + let settled = false; + const reading = (async () => { + const lease = await (await verifyNativeAcpxInstallation({ ...old })).openCommand(); + settled = true; + return lease; + })(); + await new Promise(resolve => setTimeout(resolve, 100)); + expect(settled).toBe(false); + // The prune finishes: it retired the store and removed its records. + await unsealAndRemove(join(storeRoot, old.expectedClosureSha256)); + await rm(join(storeRoot, `${old.expectedClosureSha256}.source.json`)); await rm(join(storeRoot, `${old.expectedClosureSha256}.family`)); + await rm(marker); + const lease = await reading; + helper.kill("SIGKILL"); + expect((await output(lease.spawn())).text).toBe("waited:fixed"); + await lease.close(); + expect(await readFile(join(storeRoot, `${old.expectedClosureSha256}.family`), "utf8")).toBe("wait-provider"); + expect(await pruneNativeAcpxStores(storeRoot, "wait-provider", hash("next"))).toEqual([]); + expect((await readdir(storeRoot)).filter(name => name.startsWith(".retiring-"))).toEqual([]); + }); + + it("retires a closure whose previous pruner was killed mid-prune", async () => { + const old = { ...await fixture({ script: script("killed") }), storeFamily: "killed-provider" }; + await verifyInExitedRunner(old); + // A runner killed between writing its prune marker and removing it. + const killed = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" }); + await once(killed, "spawn"); + await writeFile(join(storeRoot, `${old.expectedClosureSha256}.pruning-${killed.pid}`), ""); + killed.kill("SIGKILL"); + await once(killed, "exit"); + expect(await pruneNativeAcpxStores(storeRoot, "killed-provider", hash("next"))).toEqual([old.expectedClosureSha256]); + expect((await readdir(storeRoot)).filter(name => name.startsWith(old.expectedClosureSha256))).toEqual([]); + }); + + it("never retires a superseded store that a live runner still holds", async () => { + const old = { ...await fixture({ script: script("held") }), storeFamily: "held-provider" }; + await launch(old); + const current = { ...await fixture({ script: script("next") }), storeFamily: "held-provider" }; + await launch(current); + expect(await scheduledNativeAcpxStorePrune("held-provider", current.expectedClosureSha256)).toEqual([]); + expect(await readdir(join(storeRoot, old.expectedClosureSha256))).toContain("distribution"); + expect(await pruneNativeAcpxStores(storeRoot, "held-provider", current.expectedClosureSha256)).toEqual([]); + await releaseToExitedRunner(old.expectedClosureSha256); + expect(await pruneNativeAcpxStores(storeRoot, "held-provider", current.expectedClosureSha256)).toEqual([old.expectedClosureSha256]); + expect(await pruneNativeAcpxStores(storeRoot, "held-provider", old.expectedClosureSha256)).toEqual([]); + }); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test-support.ts b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test-support.ts new file mode 100644 index 00000000000..6bfea573e2a --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.test-support.ts @@ -0,0 +1,137 @@ +// Shared fixtures for the native ACPX closure and verified-store tests. +import { createHash } from "node:crypto"; +import { once } from "node:events"; +import { chmod, mkdir, mkdtemp, open, readFile, readdir, realpath, rm, writeFile, type FileHandle } from "node:fs/promises"; +import { createServer, type Server } from "node:net"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import type { ChildProcess } from "node:child_process"; +import { afterEach, beforeEach, vi } from "vitest"; +import { copyOwnedNodeRuntime } from "../../test-support/owned-node-runtime.js"; +import { NATIVE_ACPX_STORE_ROOT_ENV, readNativeAcpxDistributionEntries, type NativeAcpxDistributionInput, type NativeAcpxDistributionEntry } from "./native-distribution-integrity.js"; + +/** Every test verifies into its own empty store; fixtures repeat closure pins. */ +export function useNativeStoreFixtures(): void { + const previousStoreRoot = process.env[NATIVE_ACPX_STORE_ROOT_ENV]; + beforeEach(async () => { storeRoot = await realpath(await mkdtemp(join(tmpdir(), "native-acpx-store-"))); process.env[NATIVE_ACPX_STORE_ROOT_ENV] = storeRoot; }); + afterEach(async () => { + vi.restoreAllMocks(); + if (previousStoreRoot === undefined) delete process.env[NATIVE_ACPX_STORE_ROOT_ENV]; else process.env[NATIVE_ACPX_STORE_ROOT_ENV] = previousStoreRoot; + await Promise.all([...roots.splice(0), storeRoot].map(root => unsealAndRemove(root))); + }); +} + +export const roots: string[] = []; +export const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex"); +export async function unsealAndRemove(root: string): Promise { + const pending = [root]; + while (pending.length > 0) { + const directory = pending.pop()!; + await chmod(directory, 0o700).catch(() => undefined); + for (const child of await readdir(directory, { withFileTypes: true }).catch(() => [])) if (child.isDirectory()) pending.push(join(directory, child.name)); + } + await rm(root, { recursive: true, force: true }); +} +export let storeRoot = ""; +/** Private per-launch directory, from its first creation after `start`. */ +export function launchRootSince(start: number): string { + const created = vi.mocked(mkdir).mock.calls.slice(start).map(([path]) => String(path)).find(path => path.includes("paperclip-acpx-native-")); + return dirname(created!); +} +/** Staging distribution root of the store built after `start`. */ +export function stagingRootSince(start: number): string { + return vi.mocked(mkdir).mock.calls.slice(start).map(([path]) => String(path)).find(path => /\/\.staging-[^/]+\/distribution$/.test(path))!; +} + +export async function fixture(options: { node?: boolean; script?: string } = {}): Promise { + const root = await mkdtemp(join(tmpdir(), "native-acpx-test-")); roots.push(root); + const entries: NativeAcpxDistributionEntry[] = []; + if (options.node) { + const { executable, libraries } = await copyOwnedNodeRuntime(root); + const bytes = await readFile(executable); entries.push({ path: "runtime", sha256: hash(bytes), size: bytes.length, executable: true }); + for (const libraryPath of libraries) { + const library = await readFile(libraryPath); entries.push({ path: libraryPath.slice(root.length + 1), sha256: hash(library), size: library.length, executable: false }); + } + const script = options.script ?? 'console.log("qualified-entry");'; + await writeFile(join(root, "entry.cjs"), script, { mode: 0o600 }); + entries.push({ path: "entry.cjs", sha256: hash(script), size: Buffer.byteLength(script), executable: false }); + } else { + const script = options.script ?? '#!/bin/sh\nprintf "native:%s:%s" "$1" "${COPILOT_PKG_CACHE_HOME:-none}"\n'; + await writeFile(join(root, "runtime"), script, { mode: 0o700 }); + entries.push({ path: "runtime", sha256: hash(script), size: Buffer.byteLength(script), executable: true }); + } + entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0); + const manifestPath = join(root, "closure.json"); + await writeFile(manifestPath, JSON.stringify({ entries })); + return { distributionRoot: root, manifestPath, expectedClosureSha256: hash(JSON.stringify(entries)), executable: "runtime", ...(options.node ? { entrypoint: "entry.cjs" } : {}), fixedArguments: options.node ? [] : ["fixed"] }; +} +export async function manyFileFixture(sizes: number[]) { + const declaration = await fixture(); + const entries = await readNativeAcpxDistributionEntries(declaration); + for (let index = 0; index < sizes.length; index++) { + const path = `file-${String(index).padStart(2, "0")}`; + const bytes = Buffer.alloc(sizes[index]!, index + 1); + await writeFile(join(declaration.distributionRoot, path), bytes, { mode: 0o600 }); + entries.push({ path, sha256: hash(bytes), size: bytes.length, executable: false }); + } + entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0); + await writeFile(declaration.manifestPath, JSON.stringify({ entries })); + return { declaration: { ...declaration, expectedClosureSha256: hash(JSON.stringify(entries)) }, entries }; +} +export async function directoryFixture() { + const declaration = await fixture(); + const entries = await readNativeAcpxDistributionEntries(declaration); + for (let index = 0; index < 40; index++) { + const parent = `dir-${String(index).padStart(2, "0")}/nested`; + await mkdir(join(declaration.distributionRoot, parent), { recursive: true }); + for (const name of ["a", "b"]) { + const path = `${parent}/${name}`; const bytes = Buffer.from(path); + await writeFile(join(declaration.distributionRoot, path), bytes, { mode: 0o600 }); + entries.push({ path, sha256: hash(bytes), size: bytes.length, executable: false }); + } + } + entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0); + await writeFile(declaration.manifestPath, JSON.stringify({ entries })); + return { declaration: { ...declaration, expectedClosureSha256: hash(JSON.stringify(entries)) }, entries }; +} +export async function filePrototype(path: string): Promise { + const probe = await open(path, "r"); const prototype = Object.getPrototypeOf(probe) as FileHandle; + await probe.close(); return prototype; +} +export function gate() { + let release!: () => void; + const promise = new Promise((resolve) => { release = resolve; }); + return { promise, release }; +} + +export async function output(child: ChildProcess): Promise<{ text: string; error: string; code: number | null }> { + let text = ""; let error = ""; + child.stdout!.on("data", value => { text += String(value); }); + child.stderr!.on("data", value => { error += String(value); }); + const [code] = await once(child, "close") as [number | null]; + return { text, error, code }; +} + +export const blockingCopilotPeer = String.raw` +const send=m=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...m})+'\n'); +require('node:fs').writeFileSync(process.env.NATIVE_TEST_PID_FILE,String(process.pid)); +const mode='https://agentclientprotocol.com/protocol/session-modes#agent'; +const config=[{id:'mode',name:'Mode',type:'select',currentValue:mode,options:[{value:mode,name:'Agent'}]}, + {id:'allow_all',name:'Allow all',type:'select',currentValue:'off',options:[{value:'off',name:'Off'}]}, + {id:'model',name:'Model',type:'select',currentValue:'gpt-5.6-luna',options:[{value:'gpt-5.6-luna',name:'Luna'}]}]; +const snapshot={sessionId:'copilot-death-session',modes:{currentModeId:mode,availableModes:[{id:mode,name:'Agent'}]},configOptions:config, + models:{currentModelId:'gpt-5.6-luna',availableModels:[{modelId:'gpt-5.6-luna',name:'Luna'}]}}; +require('node:readline').createInterface({input:process.stdin}).on('line',line=>{ + const m=JSON.parse(line); + if(m.method==='initialize')send({id:m.id,result:{protocolVersion:1,agentCapabilities:{loadSession:true},authMethods:[]}}); + else if(['session/new','session/load'].includes(m.method))send({id:m.id,result:snapshot}); + else if(m.method==='session/set_model'||m.method==='session/close')send({id:m.id,result:{}}); + else if(m.method==='session/set_config_option')send({id:m.id,result:{configOptions:config}}); + else if(m.method==='session/prompt')send({id:'pending-edit',method:'session/request_permission',params:{sessionId:'copilot-death-session', + toolCall:{toolCallId:'native-edit',title:'Write file',kind:'edit',status:'pending',rawInput:{path:'target.txt',content:'FORBIDDEN'}}, + options:[{optionId:'allow',name:'Allow',kind:'allow_once'},{optionId:'deny',name:'Deny',kind:'reject_once'}]}}); +});`; + +export async function listen(): Promise { + const server = createServer(); server.listen(0, "127.0.0.1"); await once(server, "listening"); return server; +} 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 6f9b02e4233..e84fc5e2aa9 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 @@ -1,97 +1,24 @@ -import { createHash } from "node:crypto"; import { once } from "node:events"; import { constants } from "node:fs"; -import { execFileSync } from "node:child_process"; -import { chmod, copyFile, link, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, stat, symlink, writeFile, type FileHandle } from "node:fs/promises"; -import { createServer, type Server } from "node:net"; -import { tmpdir } from "node:os"; +import { execFileSync, spawn, spawnSync } from "node:child_process"; +import { chmod, copyFile, link, mkdir, open, readFile, realpath, rename, rm, stat, symlink, writeFile, type FileHandle } from "node:fs/promises"; +import { type Server } from "node:net"; import { dirname, join } from "node:path"; -import type { ChildProcess } from "node:child_process"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { copyOwnedNodeRuntime } from "../../test-support/owned-node-runtime.js"; +import { describe, expect, it, vi } from "vitest"; import { awaitVerifiedAcpxProviderExit, awaitVerifiedAcpxProviderOwnership, verifyNativeAcpxInstallation } from "./installation-integrity.js"; -import { createNativeAcpxDistributionSnapshot, readNativeAcpxDistributionEntries, parseNativeAcpxDistributionEntries, type NativeAcpxDistributionInput, type NativeAcpxDistributionEntry } from "./native-distribution-integrity.js"; +import { createNativeAcpxDistributionSnapshot, readNativeAcpxDistributionEntries, parseNativeAcpxDistributionEntries } from "./native-distribution-integrity.js"; import { openQualifiedAcpxRuntime } from "./acpx-runtime-adapter.js"; import { createAcpxCommandLeaseOwner } from "./command-lease-owner.js"; import { resolveQualifiedAcpxProfile } from "./qualified-profiles.js"; +import antigravityDistributions from "../../../antigravity-distributions.json" with { type: "json" }; +import { blockingCopilotPeer, directoryFixture, filePrototype, fixture, gate, hash, launchRootSince, listen, manyFileFixture, output, stagingRootSince, storeRoot, useNativeStoreFixtures } from "./native-distribution-integrity.test-support.js"; vi.mock("node:fs/promises", async (importOriginal) => { const original = await importOriginal(); - return { ...original, open: vi.fn(original.open), rm: vi.fn(original.rm), mkdir: vi.fn(original.mkdir), chmod: vi.fn(original.chmod) }; + return { ...original, open: vi.fn(original.open), rm: vi.fn(original.rm), mkdir: vi.fn(original.mkdir), chmod: vi.fn(original.chmod), rename: vi.fn(original.rename) }; }); -const roots: string[] = []; -const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex"); -afterEach(async () => { vi.restoreAllMocks(); await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); - -async function fixture(options: { node?: boolean; script?: string } = {}): Promise { - const root = await mkdtemp(join(tmpdir(), "native-acpx-test-")); roots.push(root); - const entries: NativeAcpxDistributionEntry[] = []; - if (options.node) { - const { executable, libraries } = await copyOwnedNodeRuntime(root); - const bytes = await readFile(executable); entries.push({ path: "runtime", sha256: hash(bytes), size: bytes.length, executable: true }); - for (const libraryPath of libraries) { - const library = await readFile(libraryPath); entries.push({ path: libraryPath.slice(root.length + 1), sha256: hash(library), size: library.length, executable: false }); - } - const script = options.script ?? 'console.log("qualified-entry");'; - await writeFile(join(root, "entry.cjs"), script, { mode: 0o600 }); - entries.push({ path: "entry.cjs", sha256: hash(script), size: Buffer.byteLength(script), executable: false }); - } else { - const script = options.script ?? '#!/bin/sh\nprintf "native:%s:%s" "$1" "${COPILOT_PKG_CACHE_HOME:-none}"\n'; - await writeFile(join(root, "runtime"), script, { mode: 0o700 }); - entries.push({ path: "runtime", sha256: hash(script), size: Buffer.byteLength(script), executable: true }); - } - entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0); - const manifestPath = join(root, "closure.json"); - await writeFile(manifestPath, JSON.stringify({ entries })); - return { distributionRoot: root, manifestPath, expectedClosureSha256: hash(JSON.stringify(entries)), executable: "runtime", ...(options.node ? { entrypoint: "entry.cjs" } : {}), fixedArguments: options.node ? [] : ["fixed"] }; -} -async function manyFileFixture(sizes: number[]) { - const declaration = await fixture(); - const entries = await readNativeAcpxDistributionEntries(declaration); - for (let index = 0; index < sizes.length; index++) { - const path = `file-${String(index).padStart(2, "0")}`; - const bytes = Buffer.alloc(sizes[index]!, index + 1); - await writeFile(join(declaration.distributionRoot, path), bytes, { mode: 0o600 }); - entries.push({ path, sha256: hash(bytes), size: bytes.length, executable: false }); - } - entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0); - await writeFile(declaration.manifestPath, JSON.stringify({ entries })); - return { declaration: { ...declaration, expectedClosureSha256: hash(JSON.stringify(entries)) }, entries }; -} -async function directoryFixture() { - const declaration = await fixture(); - const entries = await readNativeAcpxDistributionEntries(declaration); - for (let index = 0; index < 40; index++) { - const parent = `dir-${String(index).padStart(2, "0")}/nested`; - await mkdir(join(declaration.distributionRoot, parent), { recursive: true }); - for (const name of ["a", "b"]) { - const path = `${parent}/${name}`; const bytes = Buffer.from(path); - await writeFile(join(declaration.distributionRoot, path), bytes, { mode: 0o600 }); - entries.push({ path, sha256: hash(bytes), size: bytes.length, executable: false }); - } - } - entries.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0); - await writeFile(declaration.manifestPath, JSON.stringify({ entries })); - return { declaration: { ...declaration, expectedClosureSha256: hash(JSON.stringify(entries)) }, entries }; -} -async function filePrototype(path: string): Promise { - const probe = await open(path, "r"); const prototype = Object.getPrototypeOf(probe) as FileHandle; - await probe.close(); return prototype; -} -function gate() { - let release!: () => void; - const promise = new Promise((resolve) => { release = resolve; }); - return { promise, release }; -} - -async function output(child: ChildProcess): Promise<{ text: string; error: string; code: number | null }> { - let text = ""; let error = ""; - child.stdout!.on("data", value => { text += String(value); }); - child.stderr!.on("data", value => { error += String(value); }); - const [code] = await once(child, "close") as [number | null]; - return { text, error, code }; -} +useNativeStoreFixtures(); describe("native ACPX execution closure", () => { it("reuses shared parent prefixes with exactly the original levels, insertion order and sorted batches", async () => { @@ -109,9 +36,9 @@ describe("native ACPX execution closure", () => { const sealingStart = vi.mocked(chmod).mock.calls.length; const created = await createNativeAcpxDistributionSnapshot({ ...declaration, expectedClosureSha256: hash(JSON.stringify(entries)) }, entries); try { - const root = created.snapshot.roots[0]!; + const root = stagingRootSince(creatingStart); const levels = new Map>(); - const directories = new Set([dirname(root), root]); + const directories = new Set([root]); // Frozen reference: the original repeated-prefix planner. for (const entry of entries) { const parts = entry.path.split("/"); @@ -122,9 +49,12 @@ describe("native ACPX execution closure", () => { } } const expectedCreation = [root, ...[...levels.keys()].sort((a, b) => a - b).flatMap(depth => [...levels.get(depth)!].sort())]; - expect(vi.mocked(mkdir).mock.calls.slice(creatingStart)).toEqual(expectedCreation.map(path => [path, { mode: 0o700 }])); - expect(vi.mocked(chmod).mock.calls.slice(sealingStart)).toEqual([...directories].map(path => [path, 0o500])); - for (const path of directories) expect((await stat(path)).mode & 0o777).toBe(0o500); + expect(vi.mocked(mkdir).mock.calls.slice(creatingStart).filter(([path]) => String(path).startsWith(root))).toEqual(expectedCreation.map(path => [path, { mode: 0o700 }])); + // Every distribution directory is sealed before the staging tree is + // published; the store directory itself is sealed right after the move. + expect(vi.mocked(chmod).mock.calls.slice(sealingStart).filter(([path]) => String(path).startsWith(dirname(root)))).toEqual([...directories].map(path => [path, 0o500])); + expect(vi.mocked(chmod).mock.calls.slice(sealingStart).filter(([path]) => String(path) === dirname(created.distributionRoot))).toEqual([[dirname(created.distributionRoot), 0o500]]); + for (const path of [dirname(created.distributionRoot), ...[...directories].map(path => created.distributionRoot + path.slice(root.length))]) expect((await stat(path)).mode & 0o777).toBe(0o500); } finally { await created.commandDirectory.close(); await created.snapshot.close(); } }); it("rejects paths, ordering, oversized files and altered manifest pins", () => { @@ -134,6 +64,15 @@ 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", () => { + 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); + 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"); + }); it("checks every file digest and refuses links at admission", async () => { const declaration = await fixture(); const installation = await verifyNativeAcpxInstallation(declaration); await writeFile(join(declaration.distributionRoot, "runtime"), "altered"); @@ -243,7 +182,7 @@ describe("native ACPX execution closure", () => { const declaration = await fixture({ script: '#!/bin/sh\nprintf ready\nexec sleep 1000\n' }); const creatingStart = vi.mocked(mkdir).mock.calls.length; const lease = await (await verifyNativeAcpxInstallation(declaration)).openCommand(); - const snapshotRoot = dirname(String(vi.mocked(mkdir).mock.calls[creatingStart]![0])); + const snapshotRoot = launchRootSince(creatingStart); const child = lease.spawn(); const exited = once(child, "close"); child.stderr!.resume(); @@ -288,7 +227,7 @@ describe("native ACPX execution closure", () => { const declaration = await fixture({ script: '#!/bin/sh\nprintf ready\nexec sleep 1000\n' }); const creatingStart = vi.mocked(mkdir).mock.calls.length; const lease = await (await verifyNativeAcpxInstallation(declaration)).openCommand(); - const snapshotRoot = dirname(String(vi.mocked(mkdir).mock.calls[creatingStart]![0])); + const snapshotRoot = launchRootSince(creatingStart); const child = lease.spawn(); const exited = once(child, "close"); child.stderr!.resume(); @@ -370,8 +309,9 @@ describe("native ACPX execution closure", () => { const result = await output(lease.spawn([], { env: { COPILOT_CLI_DIST_DIR: "/ambient/evil", COPILOT_CLI_VERSION: "99.0.0", NODE_OPTIONS: "--untrusted-option" } })); expect(result.code, result.error).toBe(0); const observed = JSON.parse(result.text); - expect(observed.owned).toMatch(/paperclip-acpx-native-.*\/distribution\/distribution$/); - expect(observed.dist).toBe(join(dirname(observed.owned), ".paperclip-copilot-entry")); + // Owned code runs from the sealed verified store; only the shim is per launch. + expect(observed.owned).toBe(join(storeRoot, owned.expectedClosureSha256, "distribution", "distribution")); + expect(observed.dist).toMatch(/paperclip-acpx-native-[^/]+\/launch\/\.paperclip-copilot-entry$/); expect(observed.version).toBeNull(); expect(observed.options).toBeNull(); await lease.close(); await expect(readNativeAcpxDistributionEntries({ ...owned, copilotDistributionDirectory: "../ambient" })).rejects.toThrow("launch declaration"); @@ -387,6 +327,39 @@ describe("native ACPX execution closure", () => { const denied = await output((await (await verifyNativeAcpxInstallation(evil)).openCommand()).spawn()); expect(denied.code).not.toBe(0); expect(denied.error).toContain("escaped its closed distribution"); }, 30_000); + it("keeps the module guard beside a pinned entrypoint that launches its own guarded Node child", async () => { + // Pi's pinned pi-entry.cjs hands its child `__dirname/.paperclip-native-module-guard.cjs`. + const script = 'const cp=require("node:child_process"),path=require("node:path");' + + 'const child=cp.spawnSync(process.execPath,["--require",path.join(__dirname,".paperclip-native-module-guard.cjs"),"-e","process.stdout.write(\\"sibling-guard-loaded\\")"],{encoding:"utf8"});' + + 'process.stdout.write(child.stdout+":"+child.status);'; + const declaration = await fixture({ node: true, script }); + for (let launch = 0; launch < 2; launch++) { + const lease = await (await verifyNativeAcpxInstallation(declaration)).openCommand(); + const result = await output(lease.spawn()); + await lease.close(); + expect(result.code, result.error).toBe(0); + expect(result.text).toBe("sibling-guard-loaded:0"); + } + }, 30_000); + it("rebuilds a store whose sibling module guard was removed or rewritten", async () => { + const script = 'const cp=require("node:child_process"),path=require("node:path");' + + 'const child=cp.spawnSync(process.execPath,["--require",path.join(__dirname,".paperclip-native-module-guard.cjs"),"-e","process.stdout.write(\\"guarded\\")"],{encoding:"utf8"});' + + 'process.stdout.write(child.stdout+":"+child.status);'; + const declaration = await fixture({ node: true, script }); + const installation = await verifyNativeAcpxInstallation(declaration); + await (await installation.openCommand()).close(); + const distribution = join(storeRoot, declaration.expectedClosureSha256, "distribution"); + const guard = join(distribution, ".paperclip-native-module-guard.cjs"); + const original = await readFile(guard); + await chmod(distribution, 0o700); await chmod(guard, 0o600); + await writeFile(guard, "process.stdout.write('forged-guard-loaded');"); + await chmod(guard, 0o400); await chmod(distribution, 0o500); + const lease = await installation.openCommand(); + const result = await output(lease.spawn()); + await lease.close(); + expect(result.text).toBe("guarded:0"); + expect(await readFile(guard)).toEqual(original); + }, 30_000); it.each([false, true])("runs real Node module hooks with interleaved formats and tamper=%s", async tamper => { const script = tamper ? ` const fs = require("node:fs"); @@ -442,10 +415,11 @@ describe("native ACPX execution closure", () => { const creatingStart = vi.mocked(mkdir).mock.calls.length; const created = await createNativeAcpxDistributionSnapshot(declaration, entries); try { - const root = created.snapshot.roots[0]!; - const calls = vi.mocked(mkdir).mock.calls.slice(creatingStart).map(([path]) => String(path)).filter(path => path.startsWith(root)); + const root = created.distributionRoot; + const staging = stagingRootSince(creatingStart); + const calls = vi.mocked(mkdir).mock.calls.slice(creatingStart).map(([path]) => String(path)).filter(path => path.startsWith(staging)); expect(calls).toHaveLength(81); expect(new Set(calls).size).toBe(81); - for (const path of calls) expect((await stat(path)).mode & 0o777).toBe(0o500); + for (const path of calls) expect((await stat(root + path.slice(staging.length))).mode & 0o777).toBe(0o500); for (const entry of entries) { const path = join(root, entry.path); expect(hash(await readFile(path))).toBe(entry.sha256); @@ -460,7 +434,7 @@ describe("native ACPX execution closure", () => { const removalStart = vi.mocked(rm).mock.calls.length; const operation = async (path: any, mode: any) => { const selected = stage === "create" - ? /paperclip-acpx-native-.*\/distribution\/dir-\d+$/.test(String(path)) + ? /\/\.staging-[^/]+\/distribution\/dir-\d+$/.test(String(path)) : mode === 0o500; if (!selected) return stage === "create" ? original.mkdir(path, mode) : original.chmod(path, mode); const index = started++; active++; peak = Math.max(peak, active); @@ -477,12 +451,12 @@ describe("native ACPX execution closure", () => { try { await vi.waitFor(() => expect(started).toBe(32)); expect(peak).toBeGreaterThan(1); expect(peak).toBeLessThanOrEqual(32); expect(settled).toBe(false); - expect(vi.mocked(rm).mock.calls.slice(removalStart).filter(([path]) => String(path).includes("paperclip-acpx-native-"))).toHaveLength(0); + expect(vi.mocked(rm).mock.calls.slice(removalStart).filter(([path]) => String(path).includes("/.staging-"))).toHaveLength(0); } finally { hold.release(); } try { await expect(creating).rejects.toThrow(`fixture ${stage} failure`); expect(active).toBe(0); expect(started).toBe(32); - const removed = vi.mocked(rm).mock.calls.slice(removalStart).map(([path]) => String(path)).filter(path => path.includes("paperclip-acpx-native-")); + const removed = vi.mocked(rm).mock.calls.slice(removalStart).map(([path]) => String(path)).filter(path => path.includes("/.staging-")); expect(removed).toHaveLength(1); await expect(stat(removed[0]!)).rejects.toMatchObject({ code: "ENOENT" }); } finally { vi.mocked(mkdir).mockImplementation(original.mkdir); vi.mocked(chmod).mockImplementation(original.chmod); } @@ -505,8 +479,8 @@ describe("native ACPX execution closure", () => { const created = await creating; try { expect(peak).toBe(32); - expect(Object.keys(created.snapshot.digests).slice(0, entries.length)).toEqual(entries.map(entry => join(created.snapshot.roots[0]!, entry.path))); - for (const entry of entries) expect(hash(await readFile(join(created.snapshot.roots[0]!, entry.path)))).toBe(entry.sha256); + expect(Object.keys(created.snapshot.digests).slice(0, entries.length)).toEqual(entries.map(entry => join(created!.distributionRoot, entry.path))); + for (const entry of entries) expect(hash(await readFile(join(created!.distributionRoot, entry.path)))).toBe(entry.sha256); } finally { await created.commandDirectory.close(); await created.snapshot.close(); } }); it("uses released capacity while an earlier copy is still pending", async () => { @@ -527,29 +501,30 @@ describe("native ACPX execution closure", () => { try { try { await vi.waitFor(() => expect(laterReached).toBe(true)); expect(active).toBeGreaterThan(0); expect(peak).toBeLessThanOrEqual(32); } finally { hold.release(); created = await creating; } - expect(Object.keys(created.snapshot.digests).slice(0, entries.length)).toEqual(entries.map(entry => join(created!.snapshot.roots[0]!, entry.path))); + expect(Object.keys(created.snapshot.digests).slice(0, entries.length)).toEqual(entries.map(entry => join(created!.distributionRoot, entry.path))); } finally { if (created) { await created.commandDirectory.close(); await created.snapshot.close(); } } }); - it("bounds simultaneous buffers and gives an oversized admitted file exclusive capacity", async () => { + it("streams every file through bounded chunks, so even an oversized file never needs a whole-file buffer", async () => { const mib = 1024 * 1024; const { declaration, entries } = await manyFileFixture([17 * mib, 17 * mib, 33 * mib]); const prototype = await filePrototype(join(declaration.distributionRoot, "runtime")); const originalRead = prototype.read; - const retained = new Map(); const observed: number[] = []; + const retained = new Map(); const observed: number[] = []; const buffers: number[] = []; vi.spyOn(prototype, "read").mockImplementation(async function (this: FileHandle, ...args: any[]): Promise { if (!retained.has(this)) { const file = this; const originalClose = file.close.bind(file); file.close = async () => { try { await originalClose(); } finally { retained.delete(file); } }; } - retained.set(this, args[0].length); - const total = [...retained.values()].reduce((sum, size) => sum + size, 0); observed.push(total); - expect(total).toBeLessThanOrEqual(Math.max(32 * mib, args[0].length)); - if (args[0].length > 32 * mib) expect(retained.size).toBe(1); + retained.set(this, args[0].length); buffers.push(args[0].length); + observed.push([...retained.values()].reduce((sum, size) => sum + size, 0)); return originalRead.apply(this, args as never); }); const created = await createNativeAcpxDistributionSnapshot(declaration, entries); - try { expect(Math.max(...observed)).toBe(33 * mib); } - finally { await created.commandDirectory.close(); await created.snapshot.close(); } + try { + expect(Math.max(...buffers)).toBe(4 * mib); + expect(Math.max(...observed)).toBeLessThanOrEqual(32 * mib); + for (const entry of entries) expect(hash(await readFile(join(created.distributionRoot, entry.path)))).toBe(entry.sha256); + } finally { await created.commandDirectory.close(); await created.snapshot.close(); } }); it("drains every admitted copy before failed-snapshot cleanup and schedules no later batch", async () => { const { declaration, entries } = await manyFileFixture(Array.from({ length: 40 }, (_, index) => 91 + index)); @@ -577,7 +552,7 @@ describe("native ACPX execution closure", () => { } finally { hold.release(); } await expect(creating).rejects.toThrow("digest mismatch: file-00"); expect(readSizes).not.toContain(123); - const removals = vi.mocked(rm).mock.calls.slice(removalStart).map(([path]) => String(path)).filter(path => /paperclip-acpx-native-/.test(path)); + const removals = vi.mocked(rm).mock.calls.slice(removalStart).map(([path]) => String(path)).filter(path => /\/\.staging-/.test(path)); expect(removals).toHaveLength(1); await new Promise(resolve => setImmediate(resolve)); await expect(stat(removals[0]!)).rejects.toMatchObject({ code: "ENOENT" }); @@ -604,7 +579,7 @@ describe("native ACPX execution closure", () => { hold.release(); await expect(creating).rejects.toThrow("owned command refresh cancelled"); expect(readSizes).not.toContain(123); - const removals = vi.mocked(rm).mock.calls.slice(removalStart).map(([path]) => String(path)).filter(path => /paperclip-acpx-native-/.test(path)); + const removals = vi.mocked(rm).mock.calls.slice(removalStart).map(([path]) => String(path)).filter(path => /\/\.staging-/.test(path)); expect(removals).toHaveLength(1); await expect(stat(removals[0]!)).rejects.toMatchObject({ code: "ENOENT" }); } finally { @@ -734,27 +709,3 @@ describe("native ACPX execution closure", () => { } }, 15_000); }); - -const blockingCopilotPeer = String.raw` -const send=m=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...m})+'\n'); -require('node:fs').writeFileSync(process.env.NATIVE_TEST_PID_FILE,String(process.pid)); -const mode='https://agentclientprotocol.com/protocol/session-modes#agent'; -const config=[{id:'mode',name:'Mode',type:'select',currentValue:mode,options:[{value:mode,name:'Agent'}]}, - {id:'allow_all',name:'Allow all',type:'select',currentValue:'off',options:[{value:'off',name:'Off'}]}, - {id:'model',name:'Model',type:'select',currentValue:'gpt-5.6-luna',options:[{value:'gpt-5.6-luna',name:'Luna'}]}]; -const snapshot={sessionId:'copilot-death-session',modes:{currentModeId:mode,availableModes:[{id:mode,name:'Agent'}]},configOptions:config, - models:{currentModelId:'gpt-5.6-luna',availableModels:[{modelId:'gpt-5.6-luna',name:'Luna'}]}}; -require('node:readline').createInterface({input:process.stdin}).on('line',line=>{ - const m=JSON.parse(line); - if(m.method==='initialize')send({id:m.id,result:{protocolVersion:1,agentCapabilities:{loadSession:true},authMethods:[]}}); - else if(['session/new','session/load'].includes(m.method))send({id:m.id,result:snapshot}); - else if(m.method==='session/set_model'||m.method==='session/close')send({id:m.id,result:{}}); - else if(m.method==='session/set_config_option')send({id:m.id,result:{configOptions:config}}); - else if(m.method==='session/prompt')send({id:'pending-edit',method:'session/request_permission',params:{sessionId:'copilot-death-session', - toolCall:{toolCallId:'native-edit',title:'Write file',kind:'edit',status:'pending',rawInput:{path:'target.txt',content:'FORBIDDEN'}}, - options:[{optionId:'allow',name:'Allow',kind:'allow_once'},{optionId:'deny',name:'Deny',kind:'reject_once'}]}}); -});`; - -async function listen(): Promise { - const server = createServer(); server.listen(0, "127.0.0.1"); await once(server, "listening"); return server; -} diff --git a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.ts b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.ts index 88f44996f74..584f5b0d3c6 100644 --- a/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.ts +++ b/packages/paperclip-runner/src/drivers/acpx/native-distribution-integrity.ts @@ -1,8 +1,8 @@ -import { createHash } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { constants } from "node:fs"; -import { chmod, lstat, mkdir, mkdtemp, open, realpath, rm, writeFile, type FileHandle } from "node:fs/promises"; +import { chmod, lstat, mkdir, mkdtemp, open, readdir, readFile, realpath, rename, rm, writeFile, type FileHandle } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { isAbsolute, join, relative, resolve } from "node:path"; +import { isAbsolute, join } from "node:path"; import type { AcpxPrivateSnapshot } from "./private-snapshot.js"; export interface NativeAcpxDistributionEntry { path: string; sha256: string; size: number; executable: boolean } @@ -18,25 +18,42 @@ export interface NativeAcpxDistributionInput { isolatedCacheEnvironmentName?: "COPILOT_PKG_CACHE_HOME"; /** Trusted Copilot profile only; resolved inside each immutable spawn lease. */ copilotDistributionDirectory?: string; + /** + * The provider whose pinned closure this is (for example `antigravity`). When + * set, a launch retires this provider's sealed stores for closures it no + * longer pins, once no live runner process holds them. + */ + storeFamily?: string; } export interface NativeAcpxDistributionSnapshot { snapshot: AcpxPrivateSnapshot; commandDirectory: FileHandle; bootstrap: Buffer; + /** Sealed, runner-owned verified copy of the admitted closure. */ + distributionRoot: string; } const MAX_NATIVE_TREE_BYTES = 1024 * 1024 * 1024; -const MAX_NATIVE_FILE_BYTES = 384 * 1024 * 1024; +// Antigravity's Linux ACP server is a ~722 MB launcher with its Python archive. +const MAX_NATIVE_FILE_BYTES = 768 * 1024 * 1024; const MAX_NATIVE_MANIFEST_BYTES = 4 * 1024 * 1024; -// Bound both file descriptors and buffers. A single larger admitted file runs -// alone and remains subject to MAX_NATIVE_FILE_BYTES. +const MAX_NATIVE_RECORD_BYTES = 16 * 1024 * 1024; +// Bound file descriptors and buffers. Files stream through fixed-size chunks, +// so even the largest admitted file holds at most one chunk in memory. const NATIVE_COPY_CONCURRENCY = 32; const NATIVE_DIRECTORY_CONCURRENCY = 32; const NATIVE_COPY_BUFFER_BYTES = 32 * 1024 * 1024; +const NATIVE_COPY_CHUNK_BYTES = 4 * 1024 * 1024; +const NATIVE_STAT_CONCURRENCY = 64; const BOOTSTRAP = ".paperclip-native-entry.cjs"; const GUARD = ".paperclip-native-module-guard.cjs"; const COPILOT_ENTRY = ".paperclip-copilot-entry"; +const STORE_RECORD = "verified.json"; +const STORE_SCHEMA = "paperclip.native-acpx-verified-store.v1"; +const SOURCE_SCHEMA = "paperclip.native-acpx-verified-source.v1"; export const NATIVE_ACPX_BOOTSTRAP_NAME = BOOTSTRAP; +/** Optional absolute directory for the runner-owned verified closure store. */ +export const NATIVE_ACPX_STORE_ROOT_ENV = "PAPERCLIP_ACPX_NATIVE_STORE_ROOT"; const sha256 = (value: string | Buffer) => createHash("sha256").update(value).digest("hex"); const validPath = (value: unknown): value is string => typeof value === "string" && value.length > 0 && value.length <= 4_096 && !isAbsolute(value) && !/[\u0000-\u001f\u007f\\]/.test(value) && value.split("/").every(part => part.length > 0 && part !== "." && part !== ".."); @@ -77,9 +94,46 @@ export async function readNativeAcpxDistributionEntries(input: NativeAcpxDistrib } finally { await file.close(); } } +type FileIdentity = { dev: bigint; ino: bigint; size: bigint; mtimeNs: bigint; ctimeNs: bigint }; +type IdentityRecord = [string, string, string, string, string]; +const identityRecord = (value: FileIdentity): IdentityRecord => [String(value.dev), String(value.ino), String(value.size), String(value.mtimeNs), String(value.ctimeNs)]; +const identityMatches = (value: FileIdentity, recorded: unknown): boolean => Array.isArray(recorded) && recorded.length === 5 + && identityRecord(value).every((part, index) => part === recorded[index]); +const runnerUid = () => BigInt(process.getuid!()); +const entryPath = (root: string, entry: { path: string }) => join(root, ...entry.path.split("/")); /** - * Freeze only manifest-admitted bytes. Native trees deliberately have a separate - * bound; the tighter JavaScript/npm snapshot limits remain unchanged. + * Fallback store used only when the per-uid store root is unsafe. It lives + * while a launch uses it and is removed with the last one. + */ +type PrivateStore = { root: Promise; users: number }; +let processPrivateStore: PrivateStore | undefined; +let reportedPrivateStoreFallback = false; + +/** + * Admit a native closure for one launch. + * + * The admitted bytes are verified once per closure into a runner-owned, sealed + * store (`//distribution`, 0500 directories, 0400/0500 files, + * single-link, owned by the runner uid). Every launch then binds the store by + * the kernel identity (dev, inode, size, mtime, ctime) recorded right after its + * bytes were hashed. Content cannot change without a write, which requires a + * chmod of the sealed file and moves its ctime, so an unchanged identity proves + * unchanged bytes without re-reading them. A store that fails this check is + * retired and rebuilt from a fresh full verification. + * + * The installed source keeps its own recorded identity. A changed source is + * re-hashed in place before launch, so a later corrupt install is still refused + * even though launches execute the verified store. + * + * Each launch gets only a small private directory for its trusted bootstrap, + * Node module guard, Copilot shim and cache. + * + * The recorded identities are not a trust anchor against a process running as + * the runner's user: such a process can unseal the store and rewrite both a + * file and its record. Code that runs is therefore still checked against the + * pinned manifest at use: the bootstrap streams the executable descriptor it + * spawns through SHA-256, and the module guard hashes every Node module it + * loads. The store removes the per-launch copy, not those checks. */ export async function createNativeAcpxDistributionSnapshot(input: NativeAcpxDistributionInput, entries: NativeAcpxDistributionEntry[], signal?: AbortSignal): Promise { signal?.throwIfAborted(); @@ -87,154 +141,602 @@ export async function createNativeAcpxDistributionSnapshot(input: NativeAcpxDist entries = parseNativeAcpxDistributionEntries({ entries }, input.expectedClosureSha256); if (process.platform !== "linux" && process.platform !== "darwin") throw new Error("Native ACPX snapshots require Linux or macOS"); const source = await realpath(input.distributionRoot); + const resolved = await resolveNativeStoreRoot(); + try { + const launch = await admitFromVerifiedStore(input, entries, source, resolved.root, signal); + if (resolved.privateStore === undefined) return launch; + const privateStore = resolved.privateStore; + const closeLaunch = launch.snapshot.close; + // A failed cleanup stays retryable, and the store is released only once + // the launch directory is actually gone. + let closing: Promise | undefined; + let released = false; + launch.snapshot.close = () => closing ??= closeLaunch().then(async () => { + if (released) return; + released = true; + await releasePrivateStore(privateStore); + }, error => { + closing = undefined; + throw error; + }); + return launch; + } catch (error) { + if (resolved.privateStore !== undefined) await releasePrivateStore(resolved.privateStore); + throw error; + } +} + +async function admitFromVerifiedStore(input: NativeAcpxDistributionInput, entries: NativeAcpxDistributionEntry[], source: string, storeRoot: string, signal?: AbortSignal): Promise { + const storeDirectory = join(storeRoot, input.expectedClosureSha256); + // The lease is taken before the store is read, so a concurrent prune either + // sees it and keeps the store, or finishes retiring it before this reads. + if (input.storeFamily !== undefined) await holdVerifiedStore(storeRoot, input.expectedClosureSha256, input.storeFamily); + let identities = await readVerifiedStore(storeDirectory, entries); + if (identities === "invalid") { + await retireVerifiedStore(storeRoot, storeDirectory); + identities = "missing"; + } + let sourceVerified = false; + for (let attempt = 0; identities === "missing"; attempt++) { + if (attempt === 3) throw new Error("Native ACPX verified store could not be established"); + const observed = await materializeVerifiedStore(source, storeRoot, storeDirectory, entries, signal); + if (observed !== null) { + await writeSourceRecord(storeRoot, input.expectedClosureSha256, source, observed); + sourceVerified = true; + } + identities = await readVerifiedStore(storeDirectory, entries); + if (identities === "invalid") throw new Error("Native ACPX verified store failed its identity check"); + } + if (!sourceVerified && !await sourceUnchanged(storeRoot, input.expectedClosureSha256, source, entries)) { + await writeSourceRecord(storeRoot, input.expectedClosureSha256, source, await verifyNativeSource(source, entries, signal)); + } + signal?.throwIfAborted(); + const launch = await createNativeLaunch(input, entries, join(storeDirectory, "distribution")); + // Retiring superseded closures never delays this launch. + if (input.storeFamily !== undefined) scheduleNativeAcpxStorePrune(storeRoot, input.storeFamily, input.expectedClosureSha256); + return launch; +} + +const validStoreFamily = (value: string) => /^[a-z0-9][a-z0-9-]{0,63}$/.test(value); +const heldStores = new Set(); +const scheduledPrunes = new Map>(); + +// A prune holds its marker only while it parks one store and removes two small +// records. A launch waits for that, never for the parked tree's deletion. +const PRUNE_MARKER_WAIT_MS = 10_000; +const PRUNE_MARKER_POLL_MS = 5; + +/** + * Mark a store as used by this runner process and record its provider. The + * lease names the process, so a store stays while any live runner holds it, + * including an older release still finishing its runs during a deploy. + * + * Leases and prunes exclude each other across processes without a lock: a + * launch writes its lease and then looks for a prune marker; a prune writes its + * marker and then looks for leases. Whichever writes second sees the other. A + * launch that sees a live prune waits for it to finish, so it reads either the + * kept store or none, and writes its records after the prune removed the + * retired ones. + */ +async function holdVerifiedStore(storeRoot: string, closure: string, family: string): Promise { + if (!validStoreFamily(family)) throw new Error("Native ACPX store family is invalid"); + const key = `${storeRoot}\0${closure}`; + if (heldStores.has(key)) return; + await writeFile(join(storeRoot, `${closure}.lease-${process.pid}`), "", { mode: 0o600 }); + await awaitNoLivePrune(storeRoot, closure); + await writeFile(join(storeRoot, `${closure}.family`), family, { mode: 0o600 }); + heldStores.add(key); +} + +/** + * True while a live process holds a prune marker for `closure`. Markers of + * exited processes (a runner killed mid-prune) are removed, so they never + * block a later launch or prune. Like leases, a marker names its process id. + */ +async function livePruneMarker(storeRoot: string, closure: string): Promise { + const pattern = new RegExp(`^${closure}\\.pruning-(\\d{1,10})$`); + let pruning = false; + for (const name of await readdir(storeRoot)) { + const pid = pattern.exec(name)?.[1]; + if (pid === undefined) continue; + if (processAlive(Number(pid))) pruning = true; + else await rm(join(storeRoot, name), { force: true }); + } + return pruning; +} + +async function awaitNoLivePrune(storeRoot: string, closure: string): Promise { + const deadline = Date.now() + PRUNE_MARKER_WAIT_MS; + // A stuck prune never blocks a launch: past the deadline this proceeds and + // the store is read, or verified again, as usual. + while (await livePruneMarker(storeRoot, closure) && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, PRUNE_MARKER_POLL_MS)); + } +} + +function scheduleNativeAcpxStorePrune(storeRoot: string, family: string, keepClosure: string): void { + const key = `${storeRoot}\0${family}\0${keepClosure}`; + if (scheduledPrunes.has(key)) return; + scheduledPrunes.set(key, pruneNativeAcpxStores(storeRoot, family, keepClosure).catch(() => [])); +} + +/** Test seam: the background prune a launch scheduled, if any. */ +export function scheduledNativeAcpxStorePrune(family: string, keepClosure: string): Promise | undefined { + for (const [key, prune] of scheduledPrunes) if (key.endsWith(`\0${family}\0${keepClosure}`)) return prune; + return undefined; +} + +const processAlive = (pid: number): boolean => { + try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; } +}; + +/** Live runner processes holding `closure`; stale leases of exited processes are removed. */ +async function liveStoreHolders(storeRoot: string, closure: string, names: readonly string[]): Promise { + let live = 0; + for (const name of names) { + const match = new RegExp(`^${closure}\\.lease-(\\d{1,10})$`).exec(name); + if (!match) continue; + if (processAlive(Number(match[1]))) live++; + else await rm(join(storeRoot, name), { force: true }); + } + return live; +} + +/** + * Remove `family`'s sealed stores whose closure is not `keepClosure` and that + * no live runner process holds. Stores of other providers, unmarked stores and + * the kept closure are never touched. Returns the retired closures. + * + * Each retirement runs under a per-closure prune marker (see + * `holdVerifiedStore`): the store is parked and its records removed only when + * no live lease exists after the marker is written. The parked tree is removed + * on every path, and trees an exited runner left behind are removed here. + */ +export async function pruneNativeAcpxStores(storeRoot: string, family: string, keepClosure: string): Promise { + if (!validStoreFamily(family) || !/^[a-f0-9]{64}$/.test(keepClosure)) return []; + await removeAbandonedStoreTrees(storeRoot); + const retired: string[] = []; + for (const name of await readdir(storeRoot)) { + const closure = /^([a-f0-9]{64})\.family$/.exec(name)?.[1]; + if (!closure || closure === keepClosure) continue; + if (await readFile(join(storeRoot, name), "utf8").catch(() => null) !== family) continue; + if (await liveStoreHolders(storeRoot, closure, await readdir(storeRoot)) > 0) continue; + if (await retireUnheldStore(storeRoot, closure)) retired.push(closure); + } + return retired; +} + +async function retireUnheldStore(storeRoot: string, closure: string): Promise { + const marker = join(storeRoot, `${closure}.pruning-${process.pid}`); + // Another live prune of this closure owns it; an exited one's marker is removed here. + if (await livePruneMarker(storeRoot, closure)) return false; + try { await writeFile(marker, "", { mode: 0o600, flag: "wx" }); } catch { return false; } + let parked: string | undefined; + try { + // A launch that wrote its lease before this marker is seen here; one that + // writes it later sees the marker and waits until this returns. + if (await liveStoreHolders(storeRoot, closure, await readdir(storeRoot)) > 0) return false; + parked = join(storeRoot, `.retiring-${process.pid}-${randomUUID()}`); + try { await renameSealedDirectory(join(storeRoot, closure), parked); } catch (error) { + parked = undefined; + if ((error as NodeJS.ErrnoException).code !== "ENOENT") return false; + } + await rm(join(storeRoot, `${closure}.source.json`), { force: true }); + await rm(join(storeRoot, `${closure}.family`), { force: true }); + return true; + } finally { + await rm(marker, { force: true }); + if (parked !== undefined) await removeSealedTree(parked).catch(() => undefined); + } +} + +/** Staging, retired and parked trees of runner processes that have exited. */ +async function removeAbandonedStoreTrees(storeRoot: string): Promise { + for (const name of await readdir(storeRoot)) { + const pid = /^\.(?:staging|retired|retiring)-(\d{1,10})-/.exec(name)?.[1]; + if (pid !== undefined && !processAlive(Number(pid))) await removeSealedTree(join(storeRoot, name)).catch(() => undefined); + } +} + +/** + * Rename a store directory. Some macOS releases refuse to rename a directory + * its owner cannot write, so the directory is unsealed for the move. + */ +async function renameSealedDirectory(from: string, to: string): Promise { + await chmod(from, 0o700); + try { await rename(from, to); } catch (error) { + await chmod(from, 0o500).catch(() => undefined); + throw error; + } +} + +/** Raised when the operator-configured store root cannot be used safely. */ +export class NativeAcpxStoreRootError extends Error { + readonly code = "ACPX_NATIVE_STORE_ROOT_UNSAFE"; + constructor() { + super(`${NATIVE_ACPX_STORE_ROOT_ENV} must name an absolute directory owned by the runner user and closed to other users (mode 0700). Fix the directory or unset the variable.`); + this.name = "NativeAcpxStoreRootError"; + } +} + +async function usableStoreRoot(root: string): Promise { + if (!isAbsolute(root) || root.includes("\0")) return undefined; + try { + await mkdir(root, { recursive: true, mode: 0o700 }); + if (await isPrivateDirectory(root)) return await realpath(root); + } catch { /* unusable */ } + return undefined; +} + +/** + * Runner-owned private store root. An operator-configured root that is unsafe + * fails closed. When the default per-uid root is unsafe (for example squatted + * by another user), launches use a process-private store, report it once, and + * remove it when the last launch using it closes. + */ +async function resolveNativeStoreRoot(): Promise<{ root: string; privateStore?: PrivateStore }> { + const configured = process.env[NATIVE_ACPX_STORE_ROOT_ENV]; + if (configured) { + const root = await usableStoreRoot(configured); + if (root === undefined) throw new NativeAcpxStoreRootError(); + return { root }; + } + const root = await usableStoreRoot(join(tmpdir(), `paperclip-verified-native-${process.getuid!()}`)); + if (root !== undefined) return { root }; + // A squatted shared path must not block launches or reuse foreign bytes. + if (!reportedPrivateStoreFallback) { + reportedPrivateStoreFallback = true; + process.emitWarning(JSON.stringify({ schema: "paperclip.runner.native_store_fallback.v1", reason: "default_store_root_not_private" }), + { code: "PAPERCLIP_ACPX_NATIVE_STORE_FALLBACK", type: "PaperclipRunnerStoreWarning" }); + } + const privateStore = processPrivateStore ??= { root: mkdtemp(join(tmpdir(), "paperclip-verified-native-")).then(path => realpath(path)), users: 0 }; + privateStore.users++; + try { return { root: await privateStore.root, privateStore }; } catch (error) { + await releasePrivateStore(privateStore); + throw error; + } +} + +async function releasePrivateStore(store: PrivateStore): Promise { + if (--store.users > 0) return; + if (processPrivateStore === store) processPrivateStore = undefined; + const root = await store.root.catch(() => undefined); + if (root !== undefined) await removeSealedTree(root).catch(() => undefined); +} + +async function isPrivateDirectory(path: string): Promise { + const info = await lstat(path, { bigint: true }); + return info.isDirectory() && !info.isSymbolicLink() && info.uid === runnerUid() && (info.mode & 0o077n) === 0n; +} + +async function boundedEach(items: readonly T[], concurrency: number, operation: (item: T, index: number) => Promise): Promise { + for (let start = 0; start < items.length; start += concurrency) { + const settled = await Promise.allSettled(items.slice(start, start + concurrency).map((item, offset) => operation(item, start + offset))); + const failed = settled.find(result => result.status === "rejected"); + if (failed?.status === "rejected") throw failed.reason; + } +} + +/** Identities recorded at verification time, "missing" when absent, "invalid" when anything differs. */ +async function readVerifiedStore(storeDirectory: string, entries: NativeAcpxDistributionEntry[]): Promise { + try { await lstat(storeDirectory); } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing"; + throw error; + } + try { + if (!await isPrivateDirectory(storeDirectory)) return "invalid"; + const recordFile = await open(join(storeDirectory, STORE_RECORD), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + let record: { schema?: unknown; entries?: unknown }; + try { + const info = await recordFile.stat({ bigint: true }); + if (!info.isFile() || info.uid !== runnerUid() || (info.mode & 0o222n) !== 0n || info.size > BigInt(MAX_NATIVE_RECORD_BYTES)) return "invalid"; + record = JSON.parse((await recordFile.readFile()).toString("utf8")); + } finally { await recordFile.close(); } + const recorded = record.entries; + if (record.schema !== STORE_SCHEMA || !Array.isArray(recorded) || recorded.length !== entries.length) return "invalid"; + const identities: IdentityRecord[] = []; + for (let index = 0; index < entries.length; index++) { + const entry = entries[index]!; const value = recorded[index] as Record | null; + if (value === null || typeof value !== "object" || value.path !== entry.path || value.sha256 !== entry.sha256 || value.size !== entry.size + || value.executable !== entry.executable || !Array.isArray(value.identity) || value.identity.length !== 5 || value.identity.some(part => typeof part !== "string")) return "invalid"; + identities.push(value.identity as IdentityRecord); + } + const distribution = join(storeDirectory, "distribution"); + let intact = true; + await boundedEach(entries, NATIVE_STAT_CONCURRENCY, async (entry, index) => { + const info = await lstat(entryPath(distribution, entry), { bigint: true }); + if (!info.isFile() || info.nlink !== 1n || info.uid !== runnerUid() || (info.mode & 0o7777n) !== (entry.executable ? 0o500n : 0o400n) + || !identityMatches(info, identities[index])) intact = false; + }); + // The store's guard is small and fully derivable, so it is compared byte + // for byte on every launch rather than trusted from the record. + return intact && await storeGuardIntact(join(distribution, GUARD), storeModuleGuard(distribution, entries)) ? identities : "invalid"; + } catch { + return "invalid"; + } +} + +function storeModuleGuard(distribution: string, entries: NativeAcpxDistributionEntry[]): Buffer { + const digests: Record = {}; + for (const entry of entries) digests[entryPath(distribution, entry)] = entry.sha256; + return Buffer.from(nativeModuleGuard(digests)); +} + +async function storeGuardIntact(path: string, expected: Buffer): Promise { + const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const info = await file.stat({ bigint: true }); + if (!info.isFile() || info.nlink !== 1n || info.uid !== runnerUid() || (info.mode & 0o7777n) !== 0o400n || info.size !== BigInt(expected.length)) return false; + return (await file.readFile()).equals(expected); + } finally { await file.close(); } +} + +async function retireVerifiedStore(storeRoot: string, storeDirectory: string): Promise { + const retired = join(storeRoot, `.retired-${process.pid}-${randomUUID()}`); + try { await renameSealedDirectory(storeDirectory, retired); } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return; + throw error; + } + await removeSealedTree(retired).catch(() => undefined); +} + +async function removeSealedTree(root: string): Promise { + const pending = [root]; + while (pending.length > 0) { + const directory = pending.pop()!; + await chmod(directory, 0o700).catch(() => undefined); + for (const child of await readdir(directory, { withFileTypes: true }).catch(() => [])) { + if (child.isDirectory()) pending.push(join(directory, child.name)); + } + } + await rm(root, { recursive: true, force: true }); +} + +/** + * Hash one admitted file through a held descriptor and optionally stream the + * same chunks into the verified store. NONBLOCK prevents a raced-in FIFO from + * blocking open; only a bounded regular single-link file reaches the read. + */ +async function streamNativeEntry(path: string, entry: NativeAcpxDistributionEntry, target: string | null, signal?: AbortSignal): Promise<{ source: FileIdentity; target: FileIdentity | null }> { + signal?.throwIfAborted(); + if (await realpath(path) !== path) throw new Error("Native ACPX closure contains a symbolic link"); + const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + let output: FileHandle | undefined; + try { + const before = await file.stat({ bigint: true }); + if (!before.isFile() || before.nlink !== 1n || before.size !== BigInt(entry.size) || Boolean(before.mode & 0o111n) !== entry.executable) throw new Error("Native ACPX closure file identity is invalid"); + const digest = createHash("sha256"); + const buffer = Buffer.alloc(Math.min(entry.size, NATIVE_COPY_CHUNK_BYTES)); + if (target !== null) output = await open(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, entry.executable ? 0o500 : 0o400); + let offset = 0; + while (offset < entry.size) { + signal?.throwIfAborted(); + const read = await file.read(buffer, 0, Math.min(buffer.length, entry.size - offset), offset); + if (read.bytesRead === 0) throw new Error("Native ACPX closure file ended during snapshot"); + const chunk = buffer.subarray(0, read.bytesRead); + digest.update(chunk); + for (let written = 0; output !== undefined && written < chunk.length;) { + written += (await output.write(chunk, written, chunk.length - written, offset + written)).bytesWritten; + } + offset += read.bytesRead; + } + if (!same(before, await file.stat({ bigint: true })) || !same(before, await lstat(path, { bigint: true })) || await realpath(path) !== path) throw new Error("Native ACPX closure file changed while read"); + if (digest.digest("hex") !== entry.sha256) throw new Error(`Native ACPX closure file digest mismatch: ${entry.path}`); + if (output === undefined || target === null) return { source: before, target: null }; + // The process umask must not change the sealed mode later checks require. + await output.chmod(entry.executable ? 0o500 : 0o400); + await output.close(); output = undefined; + return { source: before, target: await lstat(target, { bigint: true }) }; + } finally { + await output?.close(); + await file.close(); + } +} + +/** + * Keep bounded capacity occupied when one file is slower than its peers. Every + * task catches its rejection before releasing capacity; once failed (or + * aborted), no new task is admitted and all owned descriptors drain first. + */ +async function streamNativeEntries(entries: NativeAcpxDistributionEntry[], operation: (entry: NativeAcpxDistributionEntry, index: number) => Promise, signal?: AbortSignal): Promise { + const results: T[] = new Array(entries.length); + const active = new Set>(); + let activeBytes = 0; + let failed = false; + let failure: unknown; + // Only the admission loop waits for capacity; notify it once per completion. + let capacityAvailable: (() => void) | undefined; + for (let index = 0; index < entries.length; index++) { + const entry = entries[index]!; + const bytes = Math.min(entry.size, NATIVE_COPY_CHUNK_BYTES); + if (signal?.aborted && !failed) { failed = true; failure = signal.reason; } + while (!failed && (active.size >= NATIVE_COPY_CONCURRENCY || (active.size > 0 && activeBytes + bytes > NATIVE_COPY_BUFFER_BYTES))) { + await new Promise(resolve => { capacityAvailable = resolve; }); + if (signal?.aborted && !failed) { failed = true; failure = signal.reason; } + } + if (failed) break; + activeBytes += bytes; + const running = operation(entry, index).then(result => { results[index] = result; }, error => { + if (!failed) { failed = true; failure = error; } + }).finally(() => { + activeBytes -= bytes; + active.delete(running); + const notify = capacityAvailable; + capacityAvailable = undefined; + notify?.(); + }); + active.add(running); + } + await Promise.all(active); + if (failed) throw failure; + signal?.throwIfAborted(); + return results; +} + +async function withHeldSourceRoot(source: string, operation: () => Promise): Promise { const rootBefore = await lstat(source, { bigint: true }); if (!rootBefore.isDirectory() || rootBefore.isSymbolicLink()) throw new Error("Native ACPX distribution must be a directory"); const heldRoot = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY); + try { + if (!same(rootBefore, await heldRoot.stat({ bigint: true }))) throw new Error("Native ACPX distribution root changed before snapshot"); + const result = await operation(); + if (!same(rootBefore, await heldRoot.stat({ bigint: true })) || !same(rootBefore, await lstat(source, { bigint: true }))) throw new Error("Native ACPX distribution root changed during snapshot"); + return result; + } finally { await heldRoot.close(); } +} + +/** Re-hash a changed installed source in place; nothing is copied. */ +async function verifyNativeSource(source: string, entries: NativeAcpxDistributionEntry[], signal?: AbortSignal): Promise { + return await withHeldSourceRoot(source, async () => (await streamNativeEntries(entries, + async entry => (await streamNativeEntry(entryPath(source, entry), entry, null, signal)).source, signal))); +} + +/** + * Build the sealed store in a private staging directory and publish it with one + * rename. Returns the observed source identities, or null when a concurrent + * launch published the same closure first. + */ +async function materializeVerifiedStore(source: string, storeRoot: string, storeDirectory: string, entries: NativeAcpxDistributionEntry[], signal?: AbortSignal): Promise { + const staging = await realpath(await mkdtemp(join(storeRoot, `.staging-${process.pid}-`))); + const packageRoot = join(staging, "distribution"); + const directories = [packageRoot]; + let published = false; + try { + const observed = await withHeldSourceRoot(source, async () => { + signal?.throwIfAborted(); + await mkdir(packageRoot, { mode: 0o700 }); + // Build each private parent once. Level ordering prevents child creation + // from racing its parent; batches bound work and drain before cleanup. + const parentLevels = new Map>(); + let previousParts: string[] = []; + const parentPaths = [packageRoot]; + for (const entry of entries) { + const parts = entry.path.split("/"); + let shared = 0; + // Canonical sorted paths keep each parent prefix contiguous. + while (shared < parts.length - 1 && shared < previousParts.length - 1 && parts[shared] === previousParts[shared]) shared++; + parentPaths.length = shared + 1; + for (let depth = shared + 1; depth < parts.length; depth++) { + const path = join(parentPaths[depth - 1]!, parts[depth - 1]!); + parentPaths.push(path); + const level = parentLevels.get(depth) ?? new Set(); + level.add(path); parentLevels.set(depth, level); directories.push(path); + } + previousParts = parts; + } + for (const depth of [...parentLevels.keys()].sort((a, b) => a - b)) { + signal?.throwIfAborted(); + await boundedEach([...parentLevels.get(depth)!].sort(), NATIVE_DIRECTORY_CONCURRENCY, path => mkdir(path, { mode: 0o700 }).then(() => undefined)); + } + return await streamNativeEntries(entries, entry => streamNativeEntry(entryPath(source, entry), entry, entryPath(packageRoot, entry), signal), signal); + }); + signal?.throwIfAborted(); + // Pinned entrypoints that start their own Node child (Pi's pi-entry.cjs) + // pass it `__dirname/`. The guard is a pure function of the closure + // and its final store path, so it is sealed into the store beside them. + await writeFile(join(packageRoot, GUARD), storeModuleGuard(join(storeDirectory, "distribution"), entries), { mode: 0o400, flag: "wx" }); + await boundedEach(directories, NATIVE_DIRECTORY_CONCURRENCY, path => chmod(path, 0o500)); + const record = Buffer.from(JSON.stringify({ schema: STORE_SCHEMA, entries: entries.map((entry, index) => ({ ...entry, identity: identityRecord(observed[index]!.target!) })) })); + await writeFile(join(staging, STORE_RECORD), record, { mode: 0o400, flag: "wx" }); + // Published while still writable: some macOS releases refuse to rename a + // directory its owner cannot write. It is sealed right after the move. + try { + await rename(staging, storeDirectory); + published = true; + } catch (error) { + if (await lstat(storeDirectory).then(() => true, () => false)) return null; + throw error; + } + await chmod(storeDirectory, 0o500); + return observed.map(result => result.source); + } finally { + if (!published) await removeSealedTree(staging); + } +} + +async function writeSourceRecord(storeRoot: string, closure: string, source: string, identities: FileIdentity[]): Promise { + const temporary = join(storeRoot, `.source-${randomUUID()}`); + await writeFile(temporary, JSON.stringify({ schema: SOURCE_SCHEMA, closure, root: source, identities: identities.map(identityRecord) }), { mode: 0o600, flag: "wx" }); + try { await rename(temporary, join(storeRoot, `${closure}.source.json`)); } catch (error) { + await rm(temporary, { force: true }); + throw error; + } +} + +/** True only when every installed file still has the identity it had when last hashed. */ +async function sourceUnchanged(storeRoot: string, closure: string, source: string, entries: NativeAcpxDistributionEntry[]): Promise { + try { + const file = await open(join(storeRoot, `${closure}.source.json`), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + let record: { schema?: unknown; closure?: unknown; root?: unknown; identities?: unknown }; + try { + const info = await file.stat({ bigint: true }); + if (!info.isFile() || info.uid !== runnerUid() || info.size > BigInt(MAX_NATIVE_RECORD_BYTES)) return false; + record = JSON.parse((await file.readFile()).toString("utf8")); + } finally { await file.close(); } + if (record.schema !== SOURCE_SCHEMA || record.closure !== closure || record.root !== source || !Array.isArray(record.identities) || record.identities.length !== entries.length) return false; + const identities = record.identities; + let unchanged = true; + await boundedEach(entries, NATIVE_STAT_CONCURRENCY, async (entry, index) => { + const info = await lstat(entryPath(source, entry), { bigint: true }); + if (!info.isFile() || info.nlink !== 1n || Boolean(info.mode & 0o111n) !== entry.executable || !identityMatches(info, identities[index])) unchanged = false; + }); + return unchanged; + } catch { + return false; + } +} + +/** Small private per-launch directory: bootstrap, module guard, Copilot shim, cache and handoff manifest. */ +async function createNativeLaunch(input: NativeAcpxDistributionInput, entries: NativeAcpxDistributionEntry[], distributionRoot: string): Promise { const privateRoot = await realpath(await mkdtemp(join(tmpdir(), "paperclip-acpx-native-"))); - const packageRoot = join(privateRoot, "distribution"); + const launchRoot = join(privateRoot, "launch"); const cacheRoot = join(privateRoot, "state"); - const directories = new Set([privateRoot, packageRoot]); - const digests: Record = {}; + const directories = [privateRoot, launchRoot]; const close = async () => { for (const path of directories) await chmod(path, 0o700).catch(() => undefined); await rm(privateRoot, { recursive: true, force: true }); }; let commandDirectory: FileHandle | undefined; try { - signal?.throwIfAborted(); - if (!same(rootBefore, await heldRoot.stat({ bigint: true }))) throw new Error("Native ACPX distribution root changed before snapshot"); - await mkdir(packageRoot, { mode: 0o700 }); + await mkdir(launchRoot, { mode: 0o700 }); if (input.isolatedCacheEnvironmentName) await mkdir(cacheRoot, { mode: 0o700 }); - // Build each private parent once. Level ordering prevents child creation - // from racing its parent; batches bound work and drain before any cleanup. - const parentLevels = new Map>(); - let previousParts: string[] = []; - const parentPaths = [packageRoot]; - for (const entry of entries) { - const parts = entry.path.split("/"); - let shared = 0; - // Canonical sorted paths keep each parent prefix contiguous. Reuse the - // previous entry's joined parents instead of rebuilding every prefix. - while (shared < parts.length - 1 && shared < previousParts.length - 1 && parts[shared] === previousParts[shared]) shared++; - parentPaths.length = shared + 1; - for (let depth = shared + 1; depth < parts.length; depth++) { - const path = join(parentPaths[depth - 1]!, parts[depth - 1]!); - parentPaths.push(path); - const level = parentLevels.get(depth) ?? new Set(); - level.add(path); parentLevels.set(depth, level); directories.add(path); - } - previousParts = parts; - } - const directoryBatch = async (paths: string[], operation: (path: string) => Promise): Promise => { - for (let start = 0; start < paths.length; start += NATIVE_DIRECTORY_CONCURRENCY) { - signal?.throwIfAborted(); - const settled = await Promise.allSettled(paths.slice(start, start + NATIVE_DIRECTORY_CONCURRENCY).map(operation)); - const failed = settled.find(result => result.status === "rejected"); - if (failed?.status === "rejected") throw failed.reason; - signal?.throwIfAborted(); - } - }; - for (const depth of [...parentLevels.keys()].sort((a, b) => a - b)) { - await directoryBatch([...parentLevels.get(depth)!].sort(), path => mkdir(path, { mode: 0o700 })); - } - const copyEntry = async (entry: NativeAcpxDistributionEntry): Promise => { - signal?.throwIfAborted(); - const path = join(source, ...entry.path.split("/")); - if (await realpath(path) !== path) throw new Error("Native ACPX closure contains a symbolic link"); - // Bind metadata to the descriptor we will read, without a redundant - // pathname stat. NONBLOCK prevents a raced-in FIFO from blocking open; - // only a bounded regular single-link file may reach the read below. - const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); - try { - const before = await file.stat({ bigint: true }); - if (!before.isFile() || before.nlink !== 1n || before.size !== BigInt(entry.size) || Boolean(before.mode & 0o111n) !== entry.executable) throw new Error("Native ACPX closure file identity is invalid"); - const bytes = Buffer.alloc(entry.size); - let offset = 0; - while (offset < bytes.length) { - signal?.throwIfAborted(); - const read = await file.read(bytes, offset, bytes.length - offset, offset); - if (read.bytesRead === 0) throw new Error("Native ACPX closure file ended during snapshot"); - offset += read.bytesRead; - } - if (!same(before, await file.stat({ bigint: true })) || !same(before, await lstat(path, { bigint: true })) || await realpath(path) !== path) throw new Error("Native ACPX closure file changed while read"); - if (sha256(bytes) !== entry.sha256) throw new Error(`Native ACPX closure file digest mismatch: ${entry.path}`); - const target = join(packageRoot, ...entry.path.split("/")); - signal?.throwIfAborted(); - await writeFile(target, bytes, { mode: entry.executable ? 0o500 : 0o400, flag: "wx" }); - } finally { await file.close(); } - }; - // Keep bounded capacity occupied when one file is slower than its peers. - // Every task catches its rejection before releasing capacity; once failed, - // no new copy is admitted and all owned descriptors drain before cleanup. - const active = new Set>(); - let activeBytes = 0; - let failed = false; - let failure: unknown; - // Only the admission loop waits for capacity. Notify that waiter once per - // completion instead of attaching Promise.race handlers to every active - // copy on each admission (including long-lived large-file reads). - let capacityAvailable: (() => void) | undefined; - for (const entry of entries) { - // An aborted acquisition must still drain its admitted reads before - // deleting the partial tree. Stop scheduling copies at the same bound - // used for any observed copy failure. - if (signal?.aborted && !failed) { failed = true; failure = signal.reason; } - while (!failed && (active.size >= NATIVE_COPY_CONCURRENCY - || (active.size > 0 && activeBytes + entry.size > NATIVE_COPY_BUFFER_BYTES))) { - await new Promise(resolve => { capacityAvailable = resolve; }); - if (signal?.aborted && !failed) { failed = true; failure = signal.reason; } - } - if (failed) break; - activeBytes += entry.size; - const copying = copyEntry(entry).catch(error => { - if (!failed) { failed = true; failure = error; } - }).finally(() => { - activeBytes -= entry.size; - active.delete(copying); - const notify = capacityAvailable; - capacityAvailable = undefined; - notify?.(); - }); - active.add(copying); - } - await Promise.all(active); - if (failed) throw failure; - signal?.throwIfAborted(); - // Completion order must not change the module guard or manifest. - for (const entry of entries) digests[join(packageRoot, ...entry.path.split("/"))] = entry.sha256; - if (!same(rootBefore, await heldRoot.stat({ bigint: true })) || !same(rootBefore, await lstat(source, { bigint: true }))) throw new Error("Native ACPX distribution root changed during snapshot"); - const executable = join(packageRoot, ...input.executable.split("/")); - const args = [...(input.entrypoint === undefined ? [] : ["--require", join(packageRoot, GUARD), join(packageRoot, ...input.entrypoint.split("/"))]), ...input.fixedArguments]; + // Canonical manifest order keeps the module guard and handoff stable. + const digests: Record = {}; + for (const entry of entries) digests[entryPath(distributionRoot, entry)] = entry.sha256; + const executableIndex = entries.findIndex(entry => entry.path === input.executable && entry.executable); + if (executableIndex < 0) throw new Error("Native ACPX executable is absent from its closure"); + const executable = entryPath(distributionRoot, entries[executableIndex]!); + const args = [...(input.entrypoint === undefined ? [] : ["--require", join(launchRoot, GUARD), join(distributionRoot, ...input.entrypoint.split("/"))]), ...input.fixedArguments]; let copilotEntryDirectory: string | undefined; if (input.copilotDistributionDirectory !== undefined) { - copilotEntryDirectory = join(packageRoot, COPILOT_ENTRY); - await mkdir(copilotEntryDirectory, { mode: 0o700 }); directories.add(copilotEntryDirectory); + copilotEntryDirectory = join(launchRoot, COPILOT_ENTRY); + await mkdir(copilotEntryDirectory, { mode: 0o700 }); directories.push(copilotEntryDirectory); const shim = Buffer.from([ - `require(${JSON.stringify(join(packageRoot, GUARD))});`, - `import(require("node:url").pathToFileURL(${JSON.stringify(join(packageRoot, input.copilotDistributionDirectory, "index.js"))}).href).catch(error=>{console.error(error);process.exitCode=1;});`, + `require(${JSON.stringify(join(launchRoot, GUARD))});`, + `import(require("node:url").pathToFileURL(${JSON.stringify(join(distributionRoot, input.copilotDistributionDirectory, "index.js"))}).href).catch(error=>{console.error(error);process.exitCode=1;});`, ].join("\n")); const shimPath = join(copilotEntryDirectory, "index.js"); await writeFile(shimPath, shim, { mode: 0o400, flag: "wx" }); digests[shimPath] = sha256(shim); } if (input.entrypoint !== undefined || copilotEntryDirectory !== undefined) { const guard = Buffer.from(nativeModuleGuard(digests)); - await writeFile(join(packageRoot, GUARD), guard, { mode: 0o400, flag: "wx" }); - digests[join(packageRoot, GUARD)] = sha256(guard); + await writeFile(join(launchRoot, GUARD), guard, { mode: 0o400, flag: "wx" }); + digests[join(launchRoot, GUARD)] = sha256(guard); } - const bootstrap = Buffer.from(nativeBootstrap(executable, digests[executable]!, args, input.isolatedCacheEnvironmentName ? { name: input.isolatedCacheEnvironmentName, value: cacheRoot } : undefined, copilotEntryDirectory)); - await writeFile(join(packageRoot, BOOTSTRAP), bootstrap, { mode: 0o400, flag: "wx" }); - digests[join(packageRoot, BOOTSTRAP)] = sha256(bootstrap); + const bootstrap = Buffer.from(nativeBootstrap(executable, entries[executableIndex]!.sha256, args, input.isolatedCacheEnvironmentName ? { name: input.isolatedCacheEnvironmentName, value: cacheRoot } : undefined, copilotEntryDirectory)); + await writeFile(join(launchRoot, BOOTSTRAP), bootstrap, { mode: 0o400, flag: "wx" }); + digests[join(launchRoot, BOOTSTRAP)] = sha256(bootstrap); // executable is null: commandLease's separately-qualified provider runtime // slot is unused; this distribution is spawned by the trusted bootstrap. - const manifest = Buffer.from(JSON.stringify({ roots: [packageRoot], executable: null, digests })); + const manifest = Buffer.from(JSON.stringify({ roots: [launchRoot], executable: null, digests })); const manifestPath = join(privateRoot, "manifest.json"); await writeFile(manifestPath, manifest, { mode: 0o400, flag: "wx" }); - await directoryBatch([...directories], path => chmod(path, 0o500)); - commandDirectory = await open(packageRoot, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY); - return { commandDirectory, bootstrap, snapshot: { roots: [packageRoot], executable: null, digests, handoff: { path: manifestPath, digest: sha256(manifest) }, close } }; + await boundedEach(directories, NATIVE_DIRECTORY_CONCURRENCY, path => chmod(path, 0o500)); + commandDirectory = await open(launchRoot, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_DIRECTORY); + return { commandDirectory, bootstrap, distributionRoot, snapshot: { roots: [launchRoot], executable: null, digests, handoff: { path: manifestPath, digest: sha256(manifest) }, close } }; } catch (error) { await commandDirectory?.close(); await close(); throw error; - } finally { await heldRoot.close(); } + } } function nativeBootstrap(executable: string, executableDigest: string, args: string[], cache?: { name: string; value: string }, copilotEntryDirectory?: string): string { @@ -255,7 +757,13 @@ function nativeBootstrap(executable: string, executableDigest: string, args: str ] : []), 'if(guarded)for(const fd of [5,6,7,8])fs.fstatSync(fd);', `const executable=${JSON.stringify(executable)};const fd=fs.openSync(executable,fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW);`, - `if(require("node:crypto").createHash("sha256").update(fs.readFileSync(fd)).digest("hex")!==${JSON.stringify(executableDigest)})throw new Error("Native ACPX executable changed before spawn");`, + // Hash the exact descriptor that is spawned against the pinned digest. The + // store's recorded identity is not trusted for this: a same-user process + // can rewrite it. Fixed 4 MiB chunks keep a large executable out of memory. + 'const opened=fs.fstatSync(fd,{bigint:true});if(!opened.isFile()||opened.nlink!==1n)throw new Error("Native ACPX executable changed before spawn");', + 'const executableHash=require("node:crypto").createHash("sha256");const chunk=Buffer.allocUnsafe(4194304);let offset=0;for(let read;(read=fs.readSync(fd,chunk,0,chunk.length,offset))>0;offset+=read)executableHash.update(chunk.subarray(0,read));', + 'const hashed=fs.fstatSync(fd,{bigint:true});', + `if(BigInt(offset)!==opened.size||["dev","ino","size","mtimeNs","ctimeNs","nlink"].some(key=>hashed[key]!==opened[key])||executableHash.digest("hex")!==${JSON.stringify(executableDigest)})throw new Error("Native ACPX executable changed before spawn");`, 'const stdio=guarded?[0,1,2,5,6,7,8]:[0,1,2]; const childExecutable=process.platform==="linux"?"/proc/self/fd/"+stdio.length:executable;stdio.push(fd);', `const child=spawn(childExecutable,${JSON.stringify(args)},{env,cwd:process.cwd(),shell:false,detached:false,stdio});fs.closeSync(fd);`, // A guarded Node launcher has a pending filesystem read on its guardian diff --git a/packages/paperclip-runner/src/drivers/acpx/provider-failure.ts b/packages/paperclip-runner/src/drivers/acpx/provider-failure.ts index ec6c3328815..b02ff0c377f 100644 --- a/packages/paperclip-runner/src/drivers/acpx/provider-failure.ts +++ b/packages/paperclip-runner/src/drivers/acpx/provider-failure.ts @@ -31,7 +31,42 @@ const CATEGORIES = new Map([ const ACP_AUTH_REQUIRED = -32000; /** The typed AIR session failure ACPX reports beside its generic terminal error. */ -export type AcpxTerminalSessionFailure = { category: string; title?: string; details?: string }; +export type AcpxTerminalSessionFailure = { + category: string; title?: string; details?: string; + /** Structured provider fields an owned runtime patch reported beside the AIR failure. */ + provider?: AcpxStructuredTurnFailure; +}; + +/** Google Antigravity's managed-turn failure, classified by Paperclip's native patch. */ +export type AcpxStructuredTurnFailure = { + kind: ProviderFailure["category"] | "connection"; + httpStatus?: number; status?: string; retryAfterSeconds?: number; + model?: string; route?: "api_key" | "subscription"; +}; + +export const ANTIGRAVITY_TURN_FAILURE_SCHEMA = "paperclip.antigravity.turn_failure.v1"; +/** A permanent model refusal: the server names the model; no provider text travels. */ +export const ANTIGRAVITY_MODEL_UNAVAILABLE = "antigravity_model_unavailable"; +const STRUCTURED_KINDS = new Set(["rate_limit", "quota_exhausted", "authentication", "permission", "model_unavailable", + "invalid_request", "overloaded", "timeout", "unknown", "connection"]); + +function structuredTurnFailure(meta: Record | null): AcpxStructuredTurnFailure | undefined { + const value = meta?.paperclipAntigravityFailure; + if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined; + const entry = value as Record; + if (entry.schema !== ANTIGRAVITY_TURN_FAILURE_SCHEMA || typeof entry.kind !== "string" || !STRUCTURED_KINDS.has(entry.kind)) return undefined; + const integer = (field: unknown, min: number, max: number) => Number.isInteger(field) && Number(field) >= min && Number(field) <= max ? Number(field) : undefined; + const httpStatus = integer(entry.httpStatus, 400, 599); + const retryAfterSeconds = integer(entry.retryAfterSeconds, 0, 7 * 24 * 60 * 60); + return { + kind: entry.kind as AcpxStructuredTurnFailure["kind"], + ...(httpStatus !== undefined ? { httpStatus } : {}), + ...(typeof entry.status === "string" && /^[A-Z_]{1,64}$/.test(entry.status) ? { status: entry.status } : {}), + ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}), + ...(typeof entry.model === "string" && entry.model.length > 0 && entry.model.length <= 512 && !/[\u0000-\u001f\u007f]/.test(entry.model) ? { model: entry.model } : {}), + ...(entry.route === "api_key" || entry.route === "subscription" ? { route: entry.route } : {}), + }; +} const TYPED_SESSION_FAILURE_CATEGORIES = new Set(["connection", "access", "limit", "service", "request", "unknown"]); @@ -61,11 +96,13 @@ export function acpxTypedTerminalSessionFailure(meta: unknown): AcpxTerminalSess if (!air || !Number.isInteger(air.version) || Number(air.version) < 1) return null; const failure = object(air.sessionFailure); if (!failure || failure.severity !== "error") return null; + const provider = structuredTurnFailure(object(meta)); // Keep complete provider text; consumers redact before bounding it. return { category: typeof failure.category === "string" && TYPED_SESSION_FAILURE_CATEGORIES.has(failure.category) ? failure.category : "unknown", ...(typeof failure.title === "string" ? { title: failure.title } : {}), ...(typeof failure.details === "string" ? { details: failure.details } : {}), + ...(provider ? { provider } : {}), }; } @@ -117,6 +154,19 @@ export function acpxProviderFailure(error: unknown, agent: string, phase: Provid if (typeof message !== "string" || !message) return null; const status = data.status ?? data.statusCode ?? detail.status ?? (agent === "claude" ? Number(/^API error: (\d{3})\b/.exec(message)?.[1]) : undefined); + const structured = sessionFailure?.provider; + if (structured) { + // The owned patch classified the native failure from its HTTP status and + // Google status; a model refusal carries no provider wording at all. + const modelRefused = structured.kind === "model_unavailable"; + return createProviderFailure({ provider: agent, phase, + message: modelRefused ? "The selected model is not available for this connection." : title || message, + httpStatus: structured.httpStatus, + providerCode: modelRefused ? ANTIGRAVITY_MODEL_UNAVAILABLE : structured.status, + category: structured.kind === "connection" ? "unknown" : structured.kind, + retryAt: structured.retryAfterSeconds === undefined ? undefined : new Date(Date.now() + structured.retryAfterSeconds * 1000).toISOString(), + environment }); + } const code = detail.type ?? detail.code ?? data.errorType ?? data.errorKind; const category = (typeof code === "string" ? CATEGORIES.get(code) : undefined) ?? (acp?.code === ACP_AUTH_REQUIRED ? "authentication" : undefined) diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.ts index 247ccd5ead8..db819b7a6c4 100644 --- a/packages/paperclip-runner/src/index.ts +++ b/packages/paperclip-runner/src/index.ts @@ -1,8 +1,9 @@ export * from "./configured-environment.js"; export * from "./catalog/index.js"; export { taskDocumentKeySchema } from "./protocol-actions/task-document-key-schema.js"; -export { CURSOR_DISTRIBUTION_PINS } from "./drivers/acpx/generated-profiles.js"; +export { ANTIGRAVITY_DISTRIBUTION_PINS, ANTIGRAVITY_RUNTIME_VERSION, CURSOR_DISTRIBUTION_PINS } from "./drivers/acpx/generated-profiles.js"; export { KIMI_DISTRIBUTION_CLOSURE_SHA256 } from "./drivers/acpx/kimi-closure-pins.js"; +export { COPILOT_CLOSURE_SHA256 } from "./drivers/acpx/copilot-closure-pins.js"; export * from "./contracts/control-plane-port.js"; export * from "./contracts/completion-result.js"; export * from "./contracts/codex.js"; @@ -83,7 +84,7 @@ export { runnerBinaryTarget } from "./live/runner-binary.js"; export * from "./drivers/opencode/opencode-server-driver.js"; export * from "./drivers/opencode/mcp-bridge.js"; export * from "./drivers/acpx/qualified-profiles.js"; -export { parseAcpxCandidateAdmission, type AcpxCandidateAdmission } from "./drivers/acpx/candidate-admission.js"; +export { isAntigravityNativeTarget, parseAcpxCandidateAdmission, type AcpxCandidateAdmission } from "./drivers/acpx/candidate-admission.js"; export { startAntigravityBrowserLogin, verifyAntigravityCredential, sanitizeAntigravityCredential } from "./drivers/acpx/antigravity-auth.js"; export { AntigravityModelDiscoveryCleanupError, discoverAntigravityModels, type AntigravityModelCatalog } from "./drivers/acpx/antigravity-models.js"; export { acpxRuntimeSessionDirectoryName, resolveAcpxRuntimeRoot } from "./drivers/acpx/recovery-identity.js"; diff --git a/packages/paperclip-runner/src/live/antigravity-candidate-startup.test.ts b/packages/paperclip-runner/src/live/antigravity-candidate-startup.test.ts index 3776ad229ef..4b840ddc2a0 100644 --- a/packages/paperclip-runner/src/live/antigravity-candidate-startup.test.ts +++ b/packages/paperclip-runner/src/live/antigravity-candidate-startup.test.ts @@ -78,12 +78,34 @@ describe("Antigravity candidate trusted startup", () => { await expect(owner.transport.prepareConversationResume!({ threadId: retained.driverSessionId, model: "wrong-model", cwd: root })).rejects.toThrow("exact current conversation"); await expect(owner.transport.prepareConversationResume!({ threadId: retained.driverSessionId, model: admission.model, cwd: "/wrong-workspace" })).rejects.toThrow("exact current conversation"); await owner.transport.close(); - expect(() => createRunnerdCodexTransport({ ...options, resumeActiveTurnId: "stale-active-turn" })).toThrow("fresh local isolated"); + expect(() => createRunnerdCodexTransport({ ...options, resumeActiveTurnId: "stale-active-turn" })).toThrow("fresh isolated per-turn"); expect(() => createRunnerdCodexTransport({ ...options, resumeProviderSession: { ...retained, providerIdentity: { ...retained.providerIdentity, effectiveModel: "wrong-model" } } })).toThrow("exact retained native conversation"); } finally { await rm(root, { recursive: true, force: true }); } }); + it("admits a remote owner only with a linux-x64 grant, per-turn, on any controller host", async () => { + const root = await mkdtemp(join(tmpdir(), "antigravity-candidate-remote-")); + const linux = (): AcpxCandidateAdmission => ({ ...candidate(), platform: "linux", architecture: "x64", + nativeClosureDigest: `sha256:${ANTIGRAVITY_DISTRIBUTION_PINS["linux-x64"].closureSha256}` }); + try { + const options = { provider: "acpx" as const, acpxAgent: "antigravity" as const, stateDirectory: root, + runnerFilesystemRoot: "/owned-runner", acpxCandidateAdmission: linux() }; + const owner = createRunnerdCodexTransport(options); + await owner.transport.close(); + for (const change of [{ acpxCandidateAdmission: candidate() }, + { acpxCandidateAdmission: { ...linux(), nativeClosureDigest: `sha256:${ANTIGRAVITY_DISTRIBUTION_PINS["darwin-arm64"].closureSha256}` } }, + { acpxCandidateAdmission: { ...linux(), architecture: "arm64" as const, nativeClosureDigest: `sha256:${ANTIGRAVITY_DISTRIBUTION_PINS["linux-arm64"].closureSha256}` } }, + { lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 1000 } }, { homeMode: "preconfigured" as const }]) { + expect(() => createRunnerdCodexTransport({ ...options, ...change })).toThrow(); + } + // The same linux-x64 grant never admits a local owner on another host. + if (process.platform !== "linux" || process.arch !== "x64") { + expect(() => createRunnerdCodexTransport({ ...options, runnerFilesystemRoot: undefined })).toThrow("on its admitted platform"); + } + } finally { await rm(root, { recursive: true, force: true }); } + }); + it("binds the startup authority to the actual Runner identity and keeps it out of provider configuration", () => { const admission = bindAcpxCandidateAdmission(candidate(), identity); const launches: RunnerProcessLaunchSpec[] = []; diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport-antigravity-release.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport-antigravity-release.test.ts new file mode 100644 index 00000000000..bc3dff16992 --- /dev/null +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport-antigravity-release.test.ts @@ -0,0 +1,98 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + createCapabilityRunnerdProviderEnvironment, + createRunnerdCodexTransport, + runnerdLaunchProfileInternals, +} from "./runnerd-codex-transport.js"; + +// At qualification Antigravity's profile flips from pending to qualified; no +// other code changes. These cases simulate that declaration and prove the +// transport's Antigravity refusals key on a candidate grant only, so a +// released profile without a grant takes the general qualified path. +const qualification = vi.hoisted(() => ({ antigravity: "pending" as "pending" | "qualified" })); +vi.mock("../drivers/acpx/capability-profiles.js", async importOriginal => { + const actual = await importOriginal(); + const profiles = Object.create(actual.ACPX_CAPABILITY_PROFILES) as Record; + Object.defineProperty(profiles, "antigravity", { + enumerable: true, + get: () => ({ ...actual.ACPX_CAPABILITY_PROFILES.antigravity, qualification: qualification.antigravity }), + }); + return { ...actual, ACPX_CAPABILITY_PROFILES: profiles }; +}); + +const identity = { + runnerInstanceId: "runner-released", environmentLeaseId: "lease-released", runId: "run-released", + normalizedSessionId: "session-released", turnId: "turn-released", itemId: "item-released", +}; +const digest = (fill: string) => `sha256:${fill.repeat(64)}`; + +async function withRoot(label: string, work: (root: string) => Promise): Promise { + const root = await mkdtemp(join(tmpdir(), `antigravity-released-${label}-`)); + try { return await work(root); } finally { await rm(root, { recursive: true, force: true }); } +} + +afterEach(() => { qualification.antigravity = "pending"; }); + +describe("released Antigravity without a candidate grant", () => { + it("is refused while pending and admitted as an ordinary transport once released", async () => { + await withRoot("admission", async root => { + const options = { provider: "acpx" as const, acpxAgent: "antigravity" as const, stateDirectory: root }; + expect(() => createRunnerdCodexTransport(options)).toThrow("explicit evaluation opt-in"); + qualification.antigravity = "qualified"; + // The candidate-only shape limits (warm lifecycle, active-turn and + // conversation resume) do not apply. + for (const change of [{}, { lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 1000 } }, + { resumeActiveTurnId: "turn-active" }, + { resumeProviderSession: { driverSessionId: "driver-retained" } }]) { + const owner = createRunnerdCodexTransport({ ...options, ...change }); + // The candidate-only conversation-resume preparation is not installed. + expect(owner.transport.prepareConversationResume).toBeUndefined(); + await owner.transport.close(); + } + // A preconfigured home stays limited to Claude and Codex for every ACPX + // agent; that general rule, not the candidate one, refuses it. + expect(() => createRunnerdCodexTransport({ ...options, homeMode: "preconfigured" })) + .toThrow("preconfigured_home_unsupported_provider"); + }); + }); + + it("reaches the general durable runner recovery instead of the candidate refusal", async () => { + qualification.antigravity = "qualified"; + await withRoot("recovery", async root => { + const owner = createRunnerdCodexTransport({ provider: "acpx", acpxAgent: "antigravity", stateDirectory: root }); + try { + // A recovery read with no saved PRP identity fails at the first step + // of the general recovery, after the candidate refusal would have run. + const failure = owner.transport.request("thread/read", { threadId: "thread-released", includeTurns: false }); + await expect(failure).rejects.toThrow("PRP provider resume state is unavailable"); + await expect(failure).rejects.not.toThrow("candidate"); + } finally { await owner.transport.close(); } + }); + }); + + it("builds a remote launch profile without startup authority", () => { + qualification.antigravity = "qualified"; + const profile = runnerdLaunchProfileInternals.acpxRunnerLaunchProfile({ + provider: "acpx", acpxAgent: "antigravity", runnerFilesystemRoot: "/guest", + providerNodeCommandSha256: digest("b"), acpxSidecarSha256: digest("c"), providerPackAuthorityDigest: digest("d"), + }, "/guest/node", "/guest/acpx-runtime-sidecar.cjs"); + expect(profile).toEqual({ + authorityDigest: digest("d"), command: "/guest/node", commandSha256: digest("b"), + sidecarScript: "/guest/acpx-runtime-sidecar.cjs", sidecarScriptSha256: digest("c"), + }); + expect(profile).not.toHaveProperty("candidateAdmission"); + }); + + it("forwards the governed replacement recovery policy to the sidecar", () => { + qualification.antigravity = "qualified"; + const environment = createCapabilityRunnerdProviderEnvironment({ + provider: "acpx", + options: { provider: "acpx", acpxAgent: "antigravity", providerRecoveryPolicy: "allow_replacement_after_governed_wait" }, + identity, codexHome: "/isolated/home", runtimeContextPath: "/isolated/context.json", hasRuntimeContext: false, + }); + expect(environment.PAPERCLIP_ACPX_PROVIDER_RECOVERY_POLICY).toBe("allow_replacement_after_governed_wait"); + }); +}); diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 378837d2d70..87c38f45527 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -12,7 +12,7 @@ export { createRunnerdCodexAppServerArgs, resolveRunnerdAcpxPermissionMode, trus import { applyProviderObservabilityEnvironment, redactObservabilityDiagnostic } from "../drivers/agent-observability.js"; import type { RunnerExecutionDriver } from "../control-plane/runner-execution-driver.js"; import { resolvePinnedOpenCodeCommand } from "../drivers/opencode/opencode-server-driver.js"; -import { bindAcpxCandidateAdmission, parseAcpxCandidateAdmission, type AcpxCandidateAdmission, type AcpxCandidateStartupAdmission } from "../drivers/acpx/candidate-admission.js"; +import { bindAcpxCandidateAdmission, isAntigravityNativeTarget, parseAcpxCandidateAdmission, type AcpxCandidateAdmission, type AcpxCandidateStartupAdmission } from "../drivers/acpx/candidate-admission.js"; import { ACPX_CAPABILITY_PROFILES } from "../drivers/acpx/capability-profiles.js"; import { resolveClaudeEffort, admittedClaudeEffort } from "../drivers/acpx/claude-effort.js"; import { resolveGrokEffort, admittedGrokEffort } from "../drivers/acpx/grok-effort.js"; @@ -3726,7 +3726,7 @@ function acpxRunnerLaunchProfile( `sha256:${createHash("sha256").update(readFileSync(path)).digest("hex")}`; let candidateAdmission: AcpxCandidateStartupAdmission | undefined; if (options.acpxCandidateAdmission) { - if (!identity || options.acpxCandidateAdmission.agent === "antigravity" && options.runnerFilesystemRoot) throw new Error("ACPX candidate requires an actual authorized startup identity"); + if (!identity) throw new Error("ACPX candidate requires an actual authorized startup identity"); candidateAdmission = bindAcpxCandidateAdmission(options.acpxCandidateAdmission, identity); } if (!options.runnerFilesystemRoot) { @@ -4398,12 +4398,18 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { const admitted = parseAcpxCandidateAdmission(candidate, { companyId: candidate.companyId, agent: options.acpxAgent ?? "", model: candidate.model }); this.options = { ...this.options, acpxCandidateAdmission: Object.freeze(admitted), ...(candidate.agent === "antigravity" ? { providerRecoveryPolicy: "same_session_only" as const } : {}) }; if (candidate.agent === "antigravity") this.prepareConversationResume = params => this.#prepareCandidateConversationResume(params); - if (candidate.agent === "antigravity" && (options.provider !== "acpx" || process.platform !== "darwin" || process.arch !== "arm64" - || options.runnerFilesystemRoot || options.prepareLaunch || options.runnerProcessLauncher + // A local grant names this host. A remote grant names the cloud pack's + // only Antigravity target, linux-x64; the remote Runner checks that grant + // again against its own host before it starts the provider. + const remote = options.runnerFilesystemRoot !== undefined; + if (candidate.agent === "antigravity" && (options.provider !== "acpx" + || (remote ? admitted.platform !== "linux" || admitted.architecture !== "x64" + : !isAntigravityNativeTarget(process.platform, process.arch) || admitted.platform !== process.platform || admitted.architecture !== process.arch + || options.prepareLaunch || options.runnerProcessLauncher) || options.homeMode === "preconfigured" || options.lifecyclePolicy?.mode === "warm" || options.adoptExistingRunner || options.resumeActiveTurnId )) { - throw new Error("ACPX candidate admission supports only a fresh local isolated per-turn execution"); + throw new Error("ACPX candidate admission supports only a fresh isolated per-turn execution on its admitted platform"); } } if (options.acpxCandidateAdmission?.agent === "antigravity" && options.resumeProviderSession) { diff --git a/packages/paperclip-runner/test/acpx-sidecar-contract.test.mjs b/packages/paperclip-runner/test/acpx-sidecar-contract.test.mjs index 52de5098f1c..ce2e2e741d0 100644 --- a/packages/paperclip-runner/test/acpx-sidecar-contract.test.mjs +++ b/packages/paperclip-runner/test/acpx-sidecar-contract.test.mjs @@ -87,7 +87,7 @@ test("candidate startup and sidecar admission share one strict identity-bound JS for (const command of ["initialize", "session.open"]) { const request = { protocolVersion, id: 1, command, params: { agent: "antigravity", model: candidateAdmission.model, candidateAdmission } }; assert.equal(validate(request), true, JSON.stringify(validate.errors)); - for (const change of [{ unknown: true }, { runId: undefined }, { normalizedSessionId: "wrong session" }, { platform: "linux" }, { expiresAt: "1800000060000" }]) { + for (const change of [{ unknown: true }, { runId: undefined }, { normalizedSessionId: "wrong session" }, { platform: "win32" }, { architecture: "ia32" }, { expiresAt: "1800000060000" }]) { const altered = JSON.parse(JSON.stringify({ ...request, params: { ...request.params, candidateAdmission: { ...candidateAdmission, ...change } } })); assert.equal(validate(altered), false); assert.equal(startup(altered.params.candidateAdmission), false); @@ -95,6 +95,8 @@ test("candidate startup and sidecar admission share one strict identity-bound JS assert.equal(validate({ ...request, params: { ...request.params, agent: "codex" } }), false); } assert.equal(validate({ protocolVersion, id: 1, command: "turn.start", params: { candidateAdmission } }), false); + // The schema admits each verified-closure platform; compiled pins decide the exact pairs. + for (const [platform, architecture] of [["linux", "x64"], ["linux", "arm64"]]) assert.equal(startup({ ...candidateAdmission, platform, architecture }), true); }); test("Pi session admission requires an explicit supported thinking level including recovery", () => { diff --git a/packages/shared/src/antigravity-models.generated.ts b/packages/shared/src/antigravity-models.generated.ts new file mode 100644 index 00000000000..cb1e231baef --- /dev/null +++ b/packages/shared/src/antigravity-models.generated.ts @@ -0,0 +1,177 @@ +// Generated by packages/paperclip-runner/scripts/generate-antigravity-models.mjs from the +// pinned Google Antigravity runtime. Do not edit; regenerate with +// `node packages/paperclip-runner/scripts/generate-antigravity-models.mjs` on darwin-arm64. +/* BEGIN GENERATED CATALOG */ +export const ANTIGRAVITY_GENERATED_MODEL_CATALOG = { + "schema": "paperclip.antigravity.model_catalog.v1", + "source": { + "runtimeVersion": "1.5.2", + "platform": "darwin-arm64", + "archiveSha256": "123a16d5c40a8ac99e20f01a62b68dd860fd96b1c528dfb8eaa37ca8733d4845", + "vendorClosureSha256": "d03a6f593b6400c4b41d33a1732f842b6ff887a50727fadecb38ee67eac7336b" + }, + "apiKey": { + "defaultModelId": "gemini-3.8-flash-high", + "models": [ + { + "id": "gemini-3.8-flash-high", + "label": "Gemini 3.8 Flash (High)" + }, + { + "id": "gemini-3.8-flash-medium", + "label": "Gemini 3.8 Flash (Medium)" + }, + { + "id": "gemini-3.8-flash-low", + "label": "Gemini 3.8 Flash (Low)" + }, + { + "id": "gemini-3.7-flash-high", + "label": "Gemini 3.7 Flash (High)" + }, + { + "id": "gemini-3.7-flash-medium", + "label": "Gemini 3.7 Flash (Medium)" + }, + { + "id": "gemini-3.7-flash-low", + "label": "Gemini 3.7 Flash (Low)" + }, + { + "id": "gemini-3.6-flash-high", + "label": "Gemini 3.6 Flash (High)" + }, + { + "id": "gemini-3.6-flash-medium", + "label": "Gemini 3.6 Flash (Medium)" + }, + { + "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)" + }, + { + "id": "gemini-3.1-pro-low", + "label": "Gemini 3.1 Pro (Low)" + } + ] + }, + "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", + "medium", + "low" + ], + "agentPlatformOnly": true + }, + { + "id": "gemini-4-hydrogen", + "label": "Gemini 4 Hydrogen", + "baseModelId": "gemini-4-hydrogen", + "levels": [ + "high", + "extra_high", + "medium", + "low" + ], + "agentPlatformOnly": true + }, + { + "id": "gemini-4-argon", + "label": "Gemini 4 Argon", + "baseModelId": "gemini-4-argon", + "levels": [ + "high", + "medium", + "low" + ], + "agentPlatformOnly": true + }, + { + "id": "gemini-3.8-flash", + "label": "Gemini 3.8 Flash", + "baseModelId": "gemini-3.8-flash", + "levels": [ + "high", + "medium", + "low" + ], + "agentPlatformOnly": false + }, + { + "id": "gemini-3.7-flash", + "label": "Gemini 3.7 Flash", + "baseModelId": "gemini-3.7-flash", + "levels": [ + "high", + "medium", + "low" + ], + "agentPlatformOnly": false + }, + { + "id": "gemini-3.6-flash", + "label": "Gemini 3.6 Flash", + "baseModelId": "gemini-3.6-flash", + "levels": [ + "high", + "medium", + "low" + ], + "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", + "levels": [ + "high", + "low" + ], + "agentPlatformOnly": false + } + ] +} as const; +/* END GENERATED CATALOG */ diff --git a/packages/shared/src/antigravity-models.test.ts b/packages/shared/src/antigravity-models.test.ts new file mode 100644 index 00000000000..eb5d07faee2 --- /dev/null +++ b/packages/shared/src/antigravity-models.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from "vitest"; +import { ANTIGRAVITY_GENERATED_MODEL_CATALOG as CATALOG } from "./antigravity-models.generated.js"; +import { + ANTIGRAVITY_API_KEY_DEFAULT_MODEL, + ANTIGRAVITY_THINKING_LEVELS, + antigravityApiKeyModels, + antigravityFamilyModelIds, + antigravityModelChoice, + antigravityModelNeedsPaidGeminiApiPlan, + antigravityModelRefusalMessage, + antigravityServerThinkingLevel, + formatAntigravityModelId, + parseAntigravityModelId, +} from "./antigravity-models.js"; + +const serverIds = CATALOG.families.flatMap(family => antigravityFamilyModelIds(family.id)); + +describe("Antigravity model ids", () => { + it("round-trips every server catalog id exactly, including all Gemini 4 levels", () => { + expect(serverIds).toHaveLength(28); + for (const id of serverIds) { + const variant = parseAntigravityModelId(id, { catalog: "server" }); + expect(variant, id).not.toBeNull(); + expect(formatAntigravityModelId(variant!)).toBe(id); + } + }); + + it("parses and formats all five server thinking levels", () => { + for (const level of ANTIGRAVITY_THINKING_LEVELS) { + const id = `gemini-4-neon-${level}`; + expect(parseAntigravityModelId(id)).toEqual({ familyId: "gemini-4-neon", level, spelling: "server" }); + expect(formatAntigravityModelId({ familyId: "gemini-4-neon", level, spelling: "server" })).toBe(id); + } + }); + + it("keeps the account catalog's xhigh spelling distinct from the server's extra_high", () => { + expect(parseAntigravityModelId("gemini-4-neon-xhigh", { catalog: "account" })).toEqual({ familyId: "gemini-4-neon", level: "extra_high", spelling: "account" }); + expect(parseAntigravityModelId("gemini-4-neon-extra_high", { catalog: "account" })).toEqual({ familyId: "gemini-4-neon", level: "extra_high", spelling: "server" }); + for (const id of ["gemini-4-neon-xhigh", "gemini-4-neon-extra_high", "gemini-4-neon-high", "gemini-4-neon-max", "gemini-4-neon-high-effort", "gemini-4-neon-xhigh-effort"]) { + expect(formatAntigravityModelId(parseAntigravityModelId(id, { catalog: "account" })!), id).toBe(id); + } + expect(antigravityServerThinkingLevel("xhigh")).toBe("extra_high"); + expect(antigravityServerThinkingLevel("extra_high")).toBe("extra_high"); + expect(antigravityServerThinkingLevel("max")).toBeNull(); + expect(() => formatAntigravityModelId({ familyId: "gemini-4-neon", level: "max", spelling: "server" })).toThrow(); + }); + + it("reads legacy account ids the way the server does, and round-trips them", () => { + expect(parseAntigravityModelId("gemini-3.5-flash-low", { catalog: "account" })).toMatchObject({ familyId: "gemini-3.5-flash", level: "medium" }); + expect(parseAntigravityModelId("gemini-3.5-flash-low", { catalog: "server" })).toMatchObject({ familyId: "gemini-3.5-flash", level: "low" }); + for (const id of ["gemini-3.5-flash-extra-low", "gemini-3.5-flash-low", "gemini-3-flash-agent", "gemini-3.1-pro-low", "gemini-pro-agent"]) { + expect(formatAntigravityModelId(parseAntigravityModelId(id, { catalog: "account" })!)).toBe(id); + } + }); + + it("does not invent a level for ids that carry none", () => { + for (const id of ["gemini-4-neon", "auto", "", "-high", "claude-sonnet-4"]) expect(parseAntigravityModelId(id)).toBeNull(); + }); +}); + +describe("Antigravity API-key suggestions", () => { + it("lists the live API-key catalog first, then every Gemini 4 level marked as needing a paid plan", () => { + const models = antigravityApiKeyModels(); + expect(models.slice(0, 14).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); + }); + + it("names family and level for the picker", () => { + expect(antigravityModelChoice({ id: "gemini-4-neon-extra_high" })).toEqual({ familyId: "gemini-4-neon", familyLabel: "Gemini 4 Neon", level: "extra_high", levelLabel: "Extra high" }); + expect(antigravityModelChoice({ id: "gemini-9-nova-xhigh", label: "Gemini 9 Nova (Extra)" }, { catalog: "account" })) + .toEqual({ familyId: "gemini-9-nova", familyLabel: "Gemini 9 Nova", level: "extra_high", levelLabel: "Extra high" }); + }); + + it("explains a refused model in plain language, naming only the model", () => { + const neon = antigravityModelRefusalMessage("gemini-4-neon-high", "api_key"); + expect(neon).toBe("Gemini 4 Neon (High) is not available with this Gemini API key. Use a key on a paid Gemini API plan that includes Gemini 4, or choose a Gemini 3 model."); + expect(antigravityModelRefusalMessage("gemini-4-neon-xhigh", "subscription")).toContain("Gemini 4 Neon (Extra high) is not available to this Google account."); + for (const message of [neon, antigravityModelRefusalMessage("gemini-3.8-flash-high", "api_key")]) { + expect(message).not.toMatch(/-32602|429|RESOURCE_EXHAUSTED|agent_platform|gemini-/); + } + }); +}); diff --git a/packages/shared/src/antigravity-models.ts b/packages/shared/src/antigravity-models.ts new file mode 100644 index 00000000000..f829cc6bc37 --- /dev/null +++ b/packages/shared/src/antigravity-models.ts @@ -0,0 +1,154 @@ +import { ANTIGRAVITY_GENERATED_MODEL_CATALOG as CATALOG } from "./antigravity-models.generated.js"; + +/** + * Google Antigravity model identity. A model id is `-`: the + * family is the base model and the level is its thinking level. The ACP + * server spells levels `minimal, low, medium, high, extra_high`. A Google + * account's catalog uses the Antigravity CLI's spellings instead: `xhigh` for + * extra high, plus `max`, and a few legacy ids that do not encode their level. + * Ids round-trip exactly: formatting a parsed id restores its own spelling. + */ +export const ANTIGRAVITY_THINKING_LEVELS = ["minimal", "low", "medium", "high", "extra_high"] as const; +export type AntigravityThinkingLevel = (typeof ANTIGRAVITY_THINKING_LEVELS)[number]; +/** `max` exists only in Google account catalogs; the server has no equivalent. */ +export type AntigravityModelLevel = AntigravityThinkingLevel | "max"; +export type AntigravityLevelSpelling = "server" | "account" | "legacy"; + +export interface AntigravityModelVariant { + familyId: string; + level: AntigravityModelLevel; + spelling: AntigravityLevelSpelling; + /** Present when the account id ends in `-effort`, which formatting keeps. */ + effortSuffix?: true; +} + +const LEVEL_LABELS: Record = { + minimal: "Minimal", low: "Low", medium: "Medium", high: "High", extra_high: "Extra high", max: "Max", +}; +/** Account-only spellings, per the server's own `_CCPA_LEVEL_NAMES`. */ +const ACCOUNT_LEVELS: Record = { xhigh: "extra_high", max: "max" }; +/** Account ids that do not spell their level (the server's `_CCPA_LEGACY_VARIANTS`). */ +const LEGACY_VARIANTS: Record = { + "gemini-3.5-flash-extra-low": ["gemini-3.5-flash", "low"], + "gemini-3.5-flash-low": ["gemini-3.5-flash", "medium"], + "gemini-3-flash-agent": ["gemini-3.5-flash", "high"], + "gemini-3.1-pro-low": ["gemini-3.1-pro", "low"], + "gemini-pro-agent": ["gemini-3.1-pro", "high"], +}; +const SERVER_LEVELS = new Set(ANTIGRAVITY_THINKING_LEVELS); + +/** Parses a model id from any Antigravity catalog, or null when it has no level. */ +export function parseAntigravityModelId(id: string, options: { catalog?: "server" | "account" } = {}): AntigravityModelVariant | null { + if (typeof id !== "string" || !id) return null; + // `gemini-3.1-pro-low` is both a server id and a legacy account id with the + // same meaning; `gemini-3.5-flash-low` is not, so account ids check legacy first. + if (options.catalog === "account" && Object.hasOwn(LEGACY_VARIANTS, id)) { + const [familyId, level] = LEGACY_VARIANTS[id]!; + return { familyId, level, spelling: "legacy" }; + } + const effortSuffix = options.catalog === "account" && id.endsWith("-effort"); + const stem = effortSuffix ? id.slice(0, -"-effort".length) : id; + const cut = stem.lastIndexOf("-"); + if (cut < 1) return null; + const familyId = stem.slice(0, cut), suffix = stem.slice(cut + 1); + const effort = effortSuffix ? { effortSuffix: true as const } : {}; + if (SERVER_LEVELS.has(suffix)) { + // `extra_high` is only ever the server's spelling, so it formats back as itself. + const spelling = options.catalog === "account" && suffix !== "extra_high" ? "account" : "server"; + return { familyId, level: suffix as AntigravityThinkingLevel, spelling, ...effort }; + } + if (Object.hasOwn(ACCOUNT_LEVELS, suffix)) return { familyId, level: ACCOUNT_LEVELS[suffix]!, spelling: "account", ...effort }; + return null; +} + +/** The exact inverse of `parseAntigravityModelId` for the same spelling. */ +export function formatAntigravityModelId(variant: AntigravityModelVariant): string { + if (variant.spelling === "legacy") { + const id = Object.entries(LEGACY_VARIANTS).find(([, [family, level]]) => family === variant.familyId && level === variant.level)?.[0]; + if (!id) throw new Error("No legacy Antigravity id has this family and level"); + return id; + } + if (variant.spelling === "server" && variant.level === "max") throw new Error("The Antigravity server has no max thinking level"); + const level = variant.spelling === "account" && variant.level === "extra_high" ? "xhigh" : variant.level; + return `${variant.familyId}-${level}${variant.effortSuffix ? "-effort" : ""}`; +} + +/** Converts an account-catalog level to the server's enum; `max` has none. */ +export function antigravityServerThinkingLevel(level: string): AntigravityThinkingLevel | null { + if (SERVER_LEVELS.has(level)) return level as AntigravityThinkingLevel; + const mapped = ACCOUNT_LEVELS[level]; + return mapped && mapped !== "max" ? mapped : null; +} + +export function antigravityThinkingLevelLabel(level: AntigravityModelLevel): string { + return LEVEL_LABELS[level]; +} + +type CatalogFamily = (typeof CATALOG.families)[number]; +const FAMILIES: ReadonlyMap = new Map(CATALOG.families.map(family => [family.id, family])); + +export interface AntigravityModelChoice { + familyId: string; + familyLabel: string; + level: AntigravityModelLevel; + levelLabel: string; +} + +/** Family and level for a picker. The family label comes from the catalog, or + * from the provider's own label with its level parenthetical removed. */ +export function antigravityModelChoice(model: { id: string; label?: string }, options: { catalog?: "server" | "account" } = {}): AntigravityModelChoice | null { + const variant = parseAntigravityModelId(model.id, options); + if (!variant) return null; + const levelLabel = LEVEL_LABELS[variant.level]; + const known = FAMILIES.get(variant.familyId)?.label; + const fromLabel = model.label?.replace(/\s*\((?:[^()]*)\)\s*$/u, "").trim(); + 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). */ +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)); +} + +export const ANTIGRAVITY_PAID_PLAN_NOTE = "needs a paid Gemini API plan"; + +/** Model suggestions for a Google API-key connection, generated from the pinned + * 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}`, + }))); + return [...listed, ...gemini4]; +} + +export const ANTIGRAVITY_API_KEY_DEFAULT_MODEL = CATALOG.apiKey.defaultModelId; +export const ANTIGRAVITY_RUNTIME_CATALOG_VERSION = CATALOG.source.runtimeVersion; + +/** Every server-catalog id of one family, in the server's priority order. */ +export function antigravityFamilyModelIds(familyId: string): string[] { + const family = FAMILIES.get(familyId); + return family ? family.levels.map(level => `${family.id}-${level}`) : []; +} + +export type AntigravityAuthRoute = "api_key" | "subscription"; + +/** Plain-language reason and fix when Google refuses a model for a connection. + * Names only the model; never a provider code. */ +export function antigravityModelRefusalMessage(modelId: string, route: AntigravityAuthRoute): string { + const choice = antigravityModelChoice({ id: modelId }, { catalog: route === "api_key" ? "server" : "account" }); + const name = choice ? `${choice.familyLabel} (${choice.levelLabel})` : modelId; + if (route === "subscription") { + return `${name} is not available to this Google account. Choose a model from the account's list, or sign in with an account that includes it.`; + } + if (antigravityModelNeedsPaidGeminiApiPlan(modelId)) { + return `${name} is not available with this Gemini API key. Use a key on a paid Gemini API plan that includes Gemini 4, or choose a Gemini 3 model.`; + } + return `${name} is not available with this Gemini API key. Choose a model from the list, or check that the model name is correct.`; +} diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 9c9d4c7e805..92261d37eff 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -3074,6 +3074,27 @@ export { updatePrimaryAgentSchema, type UpdatePrimaryAgent, type PrimaryAgentPre export * from "./agent-avatar-upload.js"; export type { DotBinding, DotInvitation, DotConnection, DotPairing } from "./dot-invitations.js"; +export { + ANTIGRAVITY_API_KEY_DEFAULT_MODEL, + ANTIGRAVITY_PAID_PLAN_NOTE, + ANTIGRAVITY_RUNTIME_CATALOG_VERSION, + ANTIGRAVITY_THINKING_LEVELS, + antigravityApiKeyModels, + antigravityFamilyModelIds, + antigravityModelChoice, + antigravityModelNeedsPaidGeminiApiPlan, + antigravityModelRefusalMessage, + antigravityServerThinkingLevel, + antigravityThinkingLevelLabel, + formatAntigravityModelId, + parseAntigravityModelId, + type AntigravityAuthRoute, + type AntigravityModelChoice, + type AntigravityModelLevel, + type AntigravityModelVariant, + type AntigravityThinkingLevel, +} from "./antigravity-models.js"; +export { ANTIGRAVITY_GENERATED_MODEL_CATALOG } from "./antigravity-models.generated.js"; export { agentHarnessType, agentRuntimeSettingsHarness, agentRunner, paperclipRunnerCreationLifecycle, paperclipRunnerProfileForHarness, paperclipRunnerSupportsPlatform, PAPERCLIP_RUNNER_MINIMUM_GLIBC_VERSION, type AgentRunnerChoice, type AgentRunner, type AgentRunnerAvailability } from "./agent-runner.js"; export { normalizeClaudeRunnerOptions, type AgentConfigurationWarning } from "./runner-configuration-warnings.js"; export { EXTERNAL_AGENT_TOOL_GUIDANCE, DOT_AGENT_TOOL_GUIDANCE, GROK_BOT_AGENT_TOOL_GUIDANCE } from "./external-agent-guidance.js"; diff --git a/scripts/__tests__/prepare-runner-release-image.test.mjs b/scripts/__tests__/prepare-runner-release-image.test.mjs index 769b5c2bf60..c5e99d9d7e7 100644 --- a/scripts/__tests__/prepare-runner-release-image.test.mjs +++ b/scripts/__tests__/prepare-runner-release-image.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { createHash } from 'node:crypto'; -import { validateReleaseRun, selectReleaseArtifacts, validateReleaseImageBase, validateImageBindings, decodeReleaseJson, decodeReleaseKimiClosures } from '../prepare-runner-release-image.mjs'; +import { validateReleaseRun, selectReleaseArtifacts, validateReleaseImageBase, validateImageBindings, decodeReleaseJson, decodeReleaseKimiClosures, loadReleaseAntigravityDistributions } from '../prepare-runner-release-image.mjs'; const source = 'a'.repeat(40); const run = { head_sha: source, conclusion: 'success', path: '.github/workflows/release-smoke.yml', repository: { full_name: 'paperclipai/paperclip' } }; @@ -94,3 +94,20 @@ test('frozen Kimi closure data is decoded without executing release source', () const duplicate = Buffer.from(source + source); assert.throws(() => decodeReleaseKimiClosures({ ...file, content: duplicate.toString('base64'), size: duplicate.length }, path)); }); + +test('frozen Antigravity declaration is read from the release only when it has the profile', async () => { + const path = 'packages/paperclip-runner/antigravity-distributions.json'; + const declaration = { schema: 'paperclip.antigravity_distribution.v1', version: '1.5.2', platforms: { 'linux-x64': { closureSha256: 'a'.repeat(64) } } }; + const bytes = Buffer.from(JSON.stringify(declaration)); + const file = { type: 'file', path, encoding: 'base64', size: bytes.length, content: bytes.toString('base64') }; + const requested = []; + const fetchFile = async requestedPath => { requested.push(requestedPath); return file; }; + assert.equal(await loadReleaseAntigravityDistributions({ profiles: { kimi: {} } }, fetchFile), undefined); + assert.deepEqual(requested, []); + assert.deepEqual(await loadReleaseAntigravityDistributions({ profiles: { antigravity: {} } }, fetchFile), declaration); + assert.deepEqual(requested, [path]); + const other = Buffer.from(JSON.stringify({ ...declaration, schema: 'other' })); + await assert.rejects(loadReleaseAntigravityDistributions({ profiles: { antigravity: {} } }, + async () => ({ ...file, size: other.length, content: other.toString('base64') })), /Antigravity distribution/); + await assert.rejects(loadReleaseAntigravityDistributions({ profiles: { antigravity: {} } }, async () => ({ ...file, path: 'other.json' }))); +}); diff --git a/scripts/prepare-runner-release-image.mjs b/scripts/prepare-runner-release-image.mjs index 5db92937efd..3b92455bac4 100644 --- a/scripts/prepare-runner-release-image.mjs +++ b/scripts/prepare-runner-release-image.mjs @@ -72,6 +72,16 @@ export function decodeReleaseKimiClosures(file, path) { return { 'darwin-arm64': matches[0][1], 'linux-x64': matches[0][2] }; } +/** The release's frozen Antigravity declaration, read as data from the release + * commit. Its PATCHED Linux closure is what the image pack must carry. */ +export async function loadReleaseAntigravityDistributions(profiles, fetchFile) { + if (!profiles?.profiles?.antigravity) return undefined; + const path = 'packages/paperclip-runner/antigravity-distributions.json'; + const frozen = decodeReleaseJson(await fetchFile(path), path); + if (frozen?.schema !== 'paperclip.antigravity_distribution.v1') throw Error('Invalid frozen Antigravity distribution declaration'); + return frozen; +} + const digestFile = async file => { const hash = createHash('sha256'); for await (const chunk of createReadStream(file)) hash.update(chunk); @@ -150,7 +160,8 @@ z.extractall(dest) const path = 'packages/paperclip-runner/src/drivers/acpx/kimi-closure-pins.ts'; kimiClosures = decodeReleaseKimiClosures(await api(`contents/${path}?ref=${source}`), path); } - verifyReleaseProviderPack(pack, source, 'linux-x64', { profiles, distributions, kimiClosures }); + const antigravityDistributions = await loadReleaseAntigravityDistributions(profiles, path => api(`contents/${path}?ref=${source}`)); + verifyReleaseProviderPack(pack, source, 'linux-x64', { profiles, distributions, kimiClosures, antigravityDistributions }); const packages = JSON.parse(await readFile(join(dirs[2], 'manifest.json'), 'utf8')); if (packages.schema !== 'paperclip.runner.public-packages/v1' || packages.sourceRevision !== source) throw Error('Wrong public-package source'); const server = packages.archives?.filter(a => a.name === '@paperclipai/server'); diff --git a/scripts/runner-image-identity.mjs b/scripts/runner-image-identity.mjs index 83879adc88a..5c3a3b442fa 100644 --- a/scripts/runner-image-identity.mjs +++ b/scripts/runner-image-identity.mjs @@ -44,14 +44,15 @@ export const RUNNER_IMAGE_PLATFORMS = Object.freeze(["linux/amd64", "linux/arm64 * context. A test checks that the stage copies nothing else and that no other * Runner stage reads the build context. * - * @paperclipai/shared owns the generated file. build:typescript only checks - * the Runner's own copy against it, but it fails without it. + * @paperclipai/shared owns the generated files. build:typescript only checks + * the Runner's own copy and inputs against them, but it fails without them. */ export const RUNNER_IMAGE_CONTEXT_INPUTS = Object.freeze([ ".npmrc", "package.json", "packages/paperclip-eval-kernel", "packages/paperclip-runner", + "packages/shared/src/antigravity-models.generated.ts", "packages/shared/src/provider-failure.generated.ts", "patches", "pnpm-lock.yaml", diff --git a/server/src/__tests__/agent-adapter-validation-routes.test.ts b/server/src/__tests__/agent-adapter-validation-routes.test.ts index bd0c194715f..3f704b129c9 100644 --- a/server/src/__tests__/agent-adapter-validation-routes.test.ts +++ b/server/src/__tests__/agent-adapter-validation-routes.test.ts @@ -491,6 +491,28 @@ describe("agent routes adapter validation", () => { expect(mockAntigravityModels).not.toHaveBeenCalled(); }); + it("lists Antigravity models for a Gemini API key on a cloud environment, but keeps account discovery on the host", async () => { + const environments = await import("../services/environments.js"); + const cloud = { id: "env-cloud", companyId: "company-1", driver: "daytona" }; + vi.spyOn(environments, "environmentService").mockReturnValue({ getById: vi.fn(async () => cloud), + findManagedSandboxEnvironment: vi.fn(async () => null), listBoundCompanyIds: vi.fn(async () => []) } as never); + const catalog = [{ id: "gemini-3.8-flash-high", label: "Gemini 3.8 Flash (High)" }]; + mockAntigravityModels.mockResolvedValue(catalog); + const app = await createApp(); + const url = (method: string) => `/api/companies/company-1/adapters/paperclip_runner/models?provider=acpx&acpxAgent=antigravity&environmentId=env-cloud&aiConnection=${ + encodeURIComponent(JSON.stringify({ provider: "google", method, mode: "responsible_user" }))}`; + const apiKey = await requestApp(app, base => request(base).get(url("api_key"))); + expect(apiKey.status, JSON.stringify(apiKey.body)).toBe(200); + expect(apiKey.body).toEqual(catalog); + expect(mockAntigravityModels).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ + binding: { provider: "google", method: "api_key", mode: "responsible_user" } })); + mockAntigravityModels.mockClear(); + const signIn = await requestApp(app, base => request(base).get(url("subscription"))); + expect(signIn.status).toBe(422); + expect(signIn.body.error).toContain("requires the Paperclip host"); + expect(mockAntigravityModels).not.toHaveBeenCalled(); + }); + it.each(["create", "hire", "edit"])("refuses pending Antigravity %s before persistence", async action => { mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableNativeRunner: true }); const app = await createApp(); diff --git a/server/src/__tests__/antigravity-connection-models.test.ts b/server/src/__tests__/antigravity-connection-models.test.ts index 2fe0cb219ea..24f0e160371 100644 --- a/server/src/__tests__/antigravity-connection-models.test.ts +++ b/server/src/__tests__/antigravity-connection-models.test.ts @@ -1,3 +1,4 @@ +import { antigravityApiKeyModels } from "@paperclipai/shared"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ managed: vi.fn(), discover: vi.fn(), cleanup: vi.fn(), warn: vi.fn(), @@ -5,6 +6,12 @@ const mocks = vi.hoisted(() => ({ managed: vi.fn(), discover: vi.fn(), cleanup: constructor(readonly retired: Promise) { super("cleanup pending"); } }, })); +const spawned = vi.hoisted(() => vi.fn()); +vi.mock("node:child_process", async original => { + const actual = await original(); + const record = (name: string) => (...args: unknown[]) => { spawned(name); return (actual as never as Record unknown>)[name]!(...args); }; + return { ...actual, spawn: record("spawn"), execFile: record("execFile"), fork: record("fork"), exec: record("exec") }; +}); vi.mock("../services/ai-connection-runtime.js", () => ({ prepareManagedAiRuntime: mocks.managed })); vi.mock("../middleware/logger.js", () => ({ logger: { warn: mocks.warn } })); vi.mock("../vendor/paperclip-runner/index.js", () => ({ @@ -38,14 +45,30 @@ it("uses the selected account lifecycle and returns only its model catalog", asy expect(mocks.cleanup).toHaveBeenCalledExactlyOnceWith(); }); -it("does not disguise an API key or absent private home as Google subscription discovery", async () => { - for (const runtime of [{ attribution: { method: "api_key" }, config: { env: { GEMINI_HOME: "/private/home" } } }, - { attribution: { method: "subscription" }, config: { env: {} } }]) { - mocks.managed.mockResolvedValue({ ...runtime, cleanup: mocks.cleanup }); - await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow(/Google|model identifier/); - } +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.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(); - expect(mocks.cleanup).toHaveBeenCalledTimes(2); + expect(spawned).not.toHaveBeenCalled(); +}); + +it("answers a sign-in binding that resolves to a Gemini API key with the API-key catalog, never a dead end", async () => { + mocks.managed.mockResolvedValue({ attribution: { method: "api_key" }, config: { env: { GEMINI_HOME: "/private/home" } }, cleanup: mocks.cleanup }); + const models = await antigravityConnectionModels({} as never, input); + expect(models).toEqual(antigravityApiKeyModels()); + expect(JSON.stringify(models)).not.toContain("exact model identifier"); + expect(mocks.discover).not.toHaveBeenCalled(); + expect(mocks.cleanup).toHaveBeenCalledTimes(1); +}); + +it("does not disguise an absent private home as Google subscription discovery", async () => { + mocks.managed.mockResolvedValue({ attribution: { method: "subscription" }, config: { env: {} }, cleanup: mocks.cleanup }); + await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow(/Google/); + expect(mocks.discover).not.toHaveBeenCalled(); + expect(mocks.cleanup).toHaveBeenCalledTimes(1); }); it("preserves account-resolution denial and sanitizes native discovery errors", async () => { diff --git a/server/src/__tests__/antigravity-connection-probe.test.ts b/server/src/__tests__/antigravity-connection-probe.test.ts index b47eab42838..69a27311e84 100644 --- a/server/src/__tests__/antigravity-connection-probe.test.ts +++ b/server/src/__tests__/antigravity-connection-probe.test.ts @@ -3,12 +3,26 @@ import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { AdapterEnvironmentTestContext } from "@paperclipai/adapter-utils"; -const mocks = vi.hoisted(() => ({ probe: vi.fn(), admission: vi.fn(), credentials: vi.fn(), copyBack: vi.fn(), remove: vi.fn(), turn: vi.fn(), warn: vi.fn() })); +const mocks = vi.hoisted(() => ({ probe: vi.fn(), admission: vi.fn(), remoteAdmitted: vi.fn(() => false), credentials: vi.fn(), copyBack: vi.fn(), remove: vi.fn(), turn: vi.fn(), warn: vi.fn(), + shell: vi.fn(), released: false })); vi.mock("../middleware/logger.js", () => ({ logger: { warn: mocks.warn } })); -vi.mock("../vendor/paperclip-runner/index.js", async original => ({ - ...await original(), probeNativeRunnerEnvironment: mocks.probe, +vi.mock("../vendor/paperclip-runner/index.js", async importOriginal => { + const original = await importOriginal(); + // Pending today; the flip removes qualificationStatus and bumps the profile. + const { qualificationStatus: _pending, ...released } = original.QUALIFIED_ACPX_PROFILES.antigravity; + const profiles = { ...original.QUALIFIED_ACPX_PROFILES }; + Object.defineProperty(profiles, "antigravity", { enumerable: true, + get: () => mocks.released ? released : original.QUALIFIED_ACPX_PROFILES.antigravity }); + return { ...original, QUALIFIED_ACPX_PROFILES: profiles, probeNativeRunnerEnvironment: mocks.probe }; +}); +vi.mock("@paperclipai/adapter-utils/execution-target", async importOriginal => ({ + ...await importOriginal(), runAdapterExecutionTargetShellCommand: mocks.shell, })); -vi.mock("../services/native-runtime/acpx-qualification.js", () => ({ resolveAntigravityCandidateAdmission: mocks.admission })); +vi.mock("../services/native-runtime/remote-provider-pack.js", async importOriginal => ({ + ...await importOriginal(), ANTIGRAVITY_PATCHED_CLOSURE_SHA256: { "linux-x64": "b".repeat(64) }, +})); +vi.mock("../services/native-runtime/acpx-qualification.js", () => ({ resolveAntigravityCandidateAdmission: mocks.admission, + antigravityRemoteCandidateAdmitted: mocks.remoteAdmitted })); vi.mock("../services/native-runtime/antigravity-runner-credentials.js", () => ({ prepareAntigravityRunnerCredentials: mocks.credentials, antigravityCredentialTurn: mocks.turn, })); @@ -17,7 +31,7 @@ vi.mock("../services/native-runtime/native-codex-runner.js", () => ({ resolvePaperclipRunnerBinaryAsync: async () => "/owned/runnerd", })); import { antigravityConnectionProbeFailure, testAntigravityConnection } from "../services/antigravity-connection-probe.js"; -import { NativeEnvironmentProbeCleanupError, resolveAcpxRuntimeRoot } from "../vendor/paperclip-runner/index.js"; +import { NativeEnvironmentProbeCleanupError, QUALIFIED_ACPX_PROFILES, resolveAcpxRuntimeRoot } from "../vendor/paperclip-runner/index.js"; const model = "exact-google-model"; const admission = { agent: "antigravity", model, companyId: "company-1" }; @@ -40,6 +54,7 @@ beforeEach(() => { }); }); afterEach(async () => { + mocks.released = false; vi.unstubAllEnvs(); await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); @@ -123,7 +138,7 @@ describe("Google Antigravity setup admission", () => { const result = await testAntigravityConnection(context, model); expect(result.status).toBe("pass"); expect(result.checks).toContainEqual(expect.objectContaining({ code: "antigravity_metadata_verified" })); - expect(mocks.admission).toHaveBeenCalledExactlyOnceWith({ companyId: "company-1", model }); + expect(mocks.admission).toHaveBeenCalledExactlyOnceWith({ companyId: "company-1", model, target: { platform: process.platform, architecture: process.arch } }); expect(mocks.credentials).toHaveBeenCalledWith(expect.objectContaining({ managedHome: "/selected/provider", remote: false, lifecycleMode: "per_turn" })); expect(order).toEqual(["retired", "copy-back", "scrub"]); }); @@ -142,9 +157,96 @@ describe("Google Antigravity setup admission", () => { it("rejects an unavailable company or remote target before reading credentials or launching native code", async () => { mocks.admission.mockReturnValue(undefined); await expect(testAntigravityConnection(context, model)).rejects.toThrow("not available for this company"); - await expect(testAntigravityConnection({ ...context, executionTarget: { kind: "remote" } as AdapterEnvironmentTestContext["executionTarget"] }, model)) - .rejects.toThrow("requires the Paperclip host"); + const remote = await testAntigravityConnection({ ...context, executionTarget: { kind: "remote" } as AdapterEnvironmentTestContext["executionTarget"] }, model); + expect(remote).toMatchObject({ status: "fail", checks: [{ code: "antigravity_remote_unavailable", message: expect.stringMatching(/only on the Paperclip host/) }] }); expect(mocks.credentials).not.toHaveBeenCalled(); expect(mocks.probe).not.toHaveBeenCalled(); + expect(mocks.shell).not.toHaveBeenCalled(); + }); +}); + +describe("Google Antigravity cloud candidate while pending", () => { + const remoteTarget = { kind: "remote", transport: "ssh", remoteCwd: "/workspace" } as unknown as AdapterEnvironmentTestContext["executionTarget"]; + const apiKeyContext = { ...context, managedAiCredentialHome: undefined, + config: { ...context.config, env: { GEMINI_API_KEY: "fixture-google-key" } }, executionTarget: remoteTarget }; + const pendingEntry = () => ({ version: QUALIFIED_ACPX_PROFILES.antigravity.agentServerVersion, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, + closureDigest: `sha256:${"b".repeat(64)}`, qualification: "pending", path: "provider-assets/antigravity/linux-x64", sha256: `sha256:${"c".repeat(64)}` }); + const pendingManifest = (providers: Record) => ["Linux", "x86_64", JSON.stringify({ + schema: "paperclip-runner/remote-provider-pack/v1", payload: { target: { platform: "linux", architecture: "x64" }, ...providers } })].join("\n"); + afterEach(() => { mocks.remoteAdmitted.mockReset(); mocks.remoteAdmitted.mockReturnValue(false); }); + + it("checks the cloud candidate pack for an API key the operator granted this company and model", async () => { + mocks.remoteAdmitted.mockReturnValue(true); + mocks.shell.mockResolvedValue({ exitCode: 0, timedOut: false, stdout: pendingManifest({ candidateProviders: { antigravity: pendingEntry() } }), stderr: "" }); + expect(await testAntigravityConnection(apiKeyContext, model)).toMatchObject({ status: "warn", checks: [{ code: "antigravity_remote_runtime_ready" }] }); + expect(mocks.remoteAdmitted).toHaveBeenCalledWith({ companyId: "company-1", model }); + mocks.shell.mockResolvedValue({ exitCode: 0, timedOut: false, stdout: pendingManifest({ providers: { antigravity: { ...pendingEntry(), qualification: "qualified" } } }), stderr: "" }); + expect((await testAntigravityConnection(apiKeyContext, model)).status).toBe("fail"); + expect(mocks.credentials).not.toHaveBeenCalled(); + }); + + it("refuses Google sign-in in the cloud even with a grant, and any cloud run without one", async () => { + mocks.remoteAdmitted.mockReturnValue(true); + expect(await testAntigravityConnection({ ...context, executionTarget: remoteTarget }, model)) + .toMatchObject({ status: "fail", checks: [{ code: "antigravity_remote_sign_in_unsupported" }] }); + mocks.remoteAdmitted.mockReturnValue(false); + expect(await testAntigravityConnection(apiKeyContext, model)) + .toMatchObject({ status: "fail", checks: [{ code: "antigravity_remote_unavailable" }] }); + expect(mocks.shell).not.toHaveBeenCalled(); + }); +}); + +describe("Google Antigravity setup admission after the release flip", () => { + const remoteTarget = { kind: "remote", transport: "ssh", remoteCwd: "/workspace" } as unknown as AdapterEnvironmentTestContext["executionTarget"]; + const apiKeyContext = { ...context, managedAiCredentialHome: undefined, + config: { ...context.config, env: { GEMINI_API_KEY: "fixture-google-key" } }, executionTarget: remoteTarget }; + const manifest = (antigravity: Record, extra: Record = {}) => ["Linux", "x86_64", JSON.stringify({ + schema: "paperclip-runner/remote-provider-pack/v1", payload: { target: { platform: "linux", architecture: "x64" }, providers: { antigravity }, ...extra } })].join("\n"); + const entry = () => ({ version: QUALIFIED_ACPX_PROFILES.antigravity.agentServerVersion, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, + closureDigest: `sha256:${"b".repeat(64)}`, qualification: "qualified", path: "provider-assets/antigravity/linux-x64", sha256: `sha256:${"c".repeat(64)}` }); + beforeEach(() => { mocks.released = true; }); + + it("verifies the local connection without a candidate grant", async () => { + mocks.admission.mockReturnValue(undefined); + const result = await testAntigravityConnection(context, model); + expect(result.status).toBe("pass"); + expect(mocks.admission).not.toHaveBeenCalled(); + expect(mocks.probe.mock.calls[0][0].transportOptions.acpxCandidateAdmission).toBeUndefined(); + }); + + it("refuses Google sign-in for a cloud environment with a plain next step", async () => { + const result = await testAntigravityConnection({ ...context, executionTarget: remoteTarget }, model); + expect(result).toMatchObject({ status: "fail", checks: [{ code: "antigravity_remote_sign_in_unsupported", + message: "Google sign-in for Google Antigravity works only on the Paperclip host. To run this agent in a cloud environment, connect a Google API key instead." }] }); + expect(mocks.shell).not.toHaveBeenCalled(); + expect(mocks.credentials).not.toHaveBeenCalled(); + }); + + it("checks the cloud image's patched Antigravity runtime for an API key without sending the key or a prompt", async () => { + mocks.shell.mockResolvedValue({ exitCode: 0, timedOut: false, stdout: manifest(entry()), stderr: "" }); + const result = await testAntigravityConnection(apiKeyContext, model); + expect(result).toMatchObject({ status: "warn", checks: [{ code: "antigravity_remote_runtime_ready" }] }); + const [, , command, options] = mocks.shell.mock.calls[0]; + expect(options.env).toEqual({}); + expect(command).not.toContain("fixture-google-key"); + expect(mocks.probe).not.toHaveBeenCalled(); + expect(mocks.credentials).not.toHaveBeenCalled(); + }); + + it.each([ + ["the vendor closure", manifest({ ...entry(), closureDigest: `sha256:${"e".repeat(64)}` })], + ["a pending entry", manifest({ ...entry(), qualification: "pending" })], + ["an entry in both inventories", manifest(entry(), { candidateProviders: { antigravity: entry() } })], + ["an older profile", manifest({ ...entry(), profileDigest: `sha256:${"f".repeat(64)}` })], + ["an ARM host", manifest(entry()).replace("x86_64", "aarch64")], + ])("refuses %s", async (_name, stdout) => { + mocks.shell.mockResolvedValue({ exitCode: 0, timedOut: false, stdout, stderr: "" }); + expect((await testAntigravityConnection(apiKeyContext, model)).status).toBe("fail"); + }); + + it("reports a missing pack in plain language", async () => { + mocks.shell.mockResolvedValue({ exitCode: 127, timedOut: false, stdout: "", stderr: "" }); + expect(await testAntigravityConnection(apiKeyContext, model)).toMatchObject({ status: "fail", + checks: [{ code: "antigravity_remote_runtime_missing" }] }); }); }); diff --git a/server/src/__tests__/antigravity-save-refusal.test.ts b/server/src/__tests__/antigravity-save-refusal.test.ts new file mode 100644 index 00000000000..a563dcfc3a1 --- /dev/null +++ b/server/src/__tests__/antigravity-save-refusal.test.ts @@ -0,0 +1,163 @@ +import { randomUUID } from "node:crypto"; +import { mkdtemp, realpath, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import express from "express"; +import request from "supertest"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { eq } from "drizzle-orm"; +import { agents, agentConfigRevisions, builtInManagedResources, companies, companyMemberships, createDb, environments } from "@paperclipai/db"; +import { agentRoutes } from "../routes/agents.js"; +import { aiConnectionService } from "../services/ai-connections.js"; +import * as environmentTests from "../services/agent-environment-test.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { readFileSync } from "node:fs"; +import { QUALIFIED_ACPX_PROFILES } from "../vendor/paperclip-runner/index.js"; +import { ANTIGRAVITY_CANDIDATE_ADMISSION_ENV } from "../services/native-runtime/acpx-qualification.js"; + +const distributions = JSON.parse(readFileSync(new URL("../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8")); +/** The operator's pending grant for one company, model and platform. */ +const grant = (companyId: string, target: string) => { + const [platform, architecture] = target.split("-"); + return JSON.stringify({ schema: "paperclip.acpx-candidate-admission.v1", companyId, agent: "antigravity", model: "gemini-3.8-flash-high", + profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, nativeClosureDigest: `sha256:${distributions.platforms[target].closureSha256}`, + platform, architecture, expiresAt: Date.now() + 60_000 }); +}; + +const release = vi.hoisted(() => ({ pending: true })); +vi.mock("../services/native-runtime/antigravity-release.js", async importOriginal => ({ + ...await importOriginal(), + antigravityReleasePending: () => release.pending, +})); + +const support = await getEmbeddedPostgresTestSupport(); +const describePostgres = support.supported ? describe : describe.skip; +const realEnvironmentTests = environmentTests.agentEnvironmentTestService; + +/** + * An Antigravity connection its environment cannot run is refused when the + * agent is saved, in plain language, never later as a failed run. + */ +describePostgres("Google Antigravity connection refusal at agent save", () => { + let database: Awaited>; + let db: ReturnType; + let home: string; + let app: express.Express; + let agent: typeof agents.$inferSelect; + let cloud: typeof environments.$inferSelect; + let fixtureNumber = 0; + const userId = randomUUID(); + const allocate = vi.fn(); + const probe = vi.fn(); + const readAgent = async () => (await db.select().from(agents).where(eq(agents.id, agent.id)))[0]; + + beforeAll(async () => { + home = await realpath(await mkdtemp(path.join(os.tmpdir(), "paperclip-antigravity-save-"))); + vi.stubEnv("PAPERCLIP_HOME", home); + vi.stubEnv("PAPERCLIP_INSTANCE_ID", "antigravity-save-fixture"); + database = await startEmbeddedPostgresTestDatabase("paperclip-antigravity-save-db-"); + db = createDb(database.connectionString); + }, 90_000); + + beforeEach(async () => { + release.pending = true; + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Antigravity save", issuePrefix: `AS${++fixtureNumber}` }); + await db.insert(companyMemberships).values({ companyId, principalId: userId, principalType: "user", status: "active", membershipRole: "member" }); + [agent] = await db.insert(agents).values({ companyId, name: "Antigravity agent", adapterType: "paperclip_runner", + adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-high" } }).returning(); + [cloud] = await db.insert(environments).values({ name: `Cloud ${companyId}`, driver: "sandbox", config: { provider: "daytona" } }).returning(); + await db.insert(builtInManagedResources).values({ companyId, bundleKey: "managed-environment", resourceKind: "environment", + resourceKey: "managed-sandbox", resourceId: cloud.id, stockVersion: "1", stockHash: "fixture" }); + allocate.mockReset().mockRejectedValue(new Error("A save must not allocate a remote computer")); + probe.mockReset().mockRejectedValue(new Error("A save must not probe the runtime")); + vi.spyOn(environmentTests, "agentEnvironmentTestService").mockImplementation((database, manager) => ({ + ...realEnvironmentTests(database, manager), resolveAdapterTestExecutionContext: allocate, testManagedEnvironment: probe, + })); + vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("A save must not contact the provider")); + app = express(); app.use(express.json()); + app.use((req, _res, next) => { req.actor = { type: "board", source: "local_implicit", userId, companyIds: [companyId] }; next(); }); + app.use("/api", agentRoutes(db)); + app.use((error: { status?: number; message: string; details?: unknown }, _req: express.Request, res: express.Response, _next: express.NextFunction) => { + res.status(error.status ?? 500).json({ error: error.message, details: error.details }); + }); + }); + afterEach(() => { vi.restoreAllMocks(); vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, undefined); }); + afterAll(async () => { + await database?.cleanup(); vi.unstubAllEnvs(); + if (home) await rm(home, { recursive: true, force: true }); + }); + + async function saveGoogleConnection(method: "api_key" | "subscription") { + const connection = method === "api_key" + ? await aiConnectionService(db).save(agent.companyId, userId, { provider: "google", method: "api_key", ownership: "personal", + name: "Gemini key", apiKey: "fixture-gemini-key", agentIds: [agent.id], allAgents: false }, "fixture-gemini-key") + : await aiConnectionService(db).save(agent.companyId, userId, { provider: "google", method: "subscription", ownership: "personal", + name: "Google account", agentIds: [agent.id], allAgents: false }, "fixture-google-sign-in"); + await aiConnectionService(db).setDefault(agent.companyId, userId, connection.grantId); + return { provider: "google", method, mode: "responsible_user" } as const; + } + + it("refuses Google sign-in on a cloud environment with the plain-language fix", async () => { + release.pending = false; + const binding = await saveGoogleConnection("subscription"); + const response = await request(app).patch(`/api/agents/${agent.id}`).send({ defaultEnvironmentId: cloud.id, runtimeConfig: { aiConnection: binding } }); + expect(response.status, JSON.stringify(response.body)).toBe(422); + expect(response.body.error).toBe("Google sign-in for Google Antigravity works only on the Paperclip host. To run this agent in a cloud environment, connect a Google API key instead."); + expect(response.body.details).toMatchObject({ code: "antigravity_remote_sign_in_unsupported" }); + const saved = await readAgent(); + expect(saved.defaultEnvironmentId).toBeNull(); + expect(saved.runtimeConfig.aiConnection).toBeUndefined(); + expect(await db.select().from(agentConfigRevisions).where(eq(agentConfigRevisions.agentId, agent.id))).toHaveLength(0); + expect(allocate).not.toHaveBeenCalled(); expect(probe).not.toHaveBeenCalled(); + }); + + it("refuses any cloud environment while the release is pending", async () => { + const binding = await saveGoogleConnection("api_key"); + const response = await request(app).patch(`/api/agents/${agent.id}`).send({ defaultEnvironmentId: cloud.id, runtimeConfig: { aiConnection: binding } }); + expect(response.status, JSON.stringify(response.body)).toBe(422); + expect(response.body.error).toBe("Google Antigravity runs only on the Paperclip host for now. Choose the Paperclip host as this agent's environment."); + expect(JSON.stringify(response.body)).not.toContain("fixture-gemini-key"); + expect((await readAgent()).defaultEnvironmentId).toBeNull(); + }); + + it("saves a Gemini API key on a cloud environment while pending when the operator granted linux-x64", async () => { + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, grant(agent.companyId, "linux-x64")); + const binding = await saveGoogleConnection("api_key"); + const response = await request(app).patch(`/api/agents/${agent.id}`).send({ defaultEnvironmentId: cloud.id, runtimeConfig: { aiConnection: binding } }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + expect((await readAgent()).defaultEnvironmentId).toBe(cloud.id); + expect(allocate).not.toHaveBeenCalled(); expect(probe).not.toHaveBeenCalled(); + }); + + it("refuses a cloud environment when the grant is for another company or another platform", async () => { + const binding = await saveGoogleConnection("api_key"); + for (const value of [grant(randomUUID(), "linux-x64"), grant(agent.companyId, "linux-arm64")]) { + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, value); + const response = await request(app).patch(`/api/agents/${agent.id}`).send({ defaultEnvironmentId: cloud.id, runtimeConfig: { aiConnection: binding } }); + expect(response.status, JSON.stringify(response.body)).toBe(422); + expect(response.body.details).toMatchObject({ code: "antigravity_remote_unavailable" }); + } + expect((await readAgent()).defaultEnvironmentId).toBeNull(); + }); + + it.skipIf(process.platform === "linux" && process.arch === "x64")("refuses a host agent when the company holds only a cloud grant", async () => { + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, grant(agent.companyId, "linux-x64")); + const response = await request(app).patch(`/api/agents/${agent.id}`) + .send({ adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-high" } }); + expect(response.status, JSON.stringify(response.body)).toBe(422); + expect(response.body.error).toBe("Google Antigravity is enabled only for cloud environments in this company for now. Choose a cloud environment for this agent."); + expect(await db.select().from(agentConfigRevisions).where(eq(agentConfigRevisions.agentId, agent.id))).toHaveLength(0); + }); + + it("saves a Gemini API key on a cloud environment once released", async () => { + release.pending = false; + const binding = await saveGoogleConnection("api_key"); + const response = await request(app).patch(`/api/agents/${agent.id}`).send({ defaultEnvironmentId: cloud.id, runtimeConfig: { aiConnection: binding } }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const saved = await readAgent(); + expect(saved.defaultEnvironmentId).toBe(cloud.id); + expect(saved.runtimeConfig.aiConnection).toEqual(binding); + expect(allocate).not.toHaveBeenCalled(); expect(probe).not.toHaveBeenCalled(); + }); +}); diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 306c48fe770..1d7872b6aed 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -49,7 +49,9 @@ import { toolConnections } from "@paperclipai/db"; import { aiConnectionService } from "../services/ai-connections.js"; import { probeCopilotConnection, probeCopilotExecutionTarget } from "../services/copilot-connection-probe.js"; import { antigravityConnectionModels } from "../services/antigravity-connection-models.js"; -import { resolveAntigravityCandidateAdmission, resolveKimiCandidateAdmission } from "../services/native-runtime/acpx-qualification.js"; +import { antigravityConnectionRefusal } from "../services/native-runtime/antigravity-connection-policy.js"; +import { antigravityCandidateTarget, antigravityReleasePending } from "../services/native-runtime/antigravity-release.js"; +import { antigravityRemoteCandidateAdmitted, resolveAntigravityCandidateAdmission, resolveKimiCandidateAdmission } from "../services/native-runtime/acpx-qualification.js"; import { defaultAiConnectionForHire } from "../services/agent-ai-connection-default.js"; import { assertAiConnectionCreateAccess, canInstallSharedAiConnectionForNewAgent, responsibleUserForAiRequest } from "./ai-connections.js"; import { isAiConnectionCompatible } from "@paperclipai/shared"; @@ -1222,6 +1224,39 @@ export function agentRoutes( // The cancellation controllers for the in-flight login runs this process owns. const adapterLoginAbortControllers = new Map(); + /** + * While Antigravity is pending, the operator's grant names one platform: this + * host, or linux-x64 for a cloud environment. Refuse saving an agent whose + * environment the grant does not cover, so a saved agent can always run. + */ + async function assertAntigravityCandidateCoversEnvironment( + companyId: string, + adapterType: string, + adapterConfig: unknown, + environmentId: string | null | undefined, + ) { + const config = asRecord(adapterConfig); + if (adapterType !== "paperclip_runner" || config?.provider !== "acpx" || config.acpxAgent !== "antigravity" + || !antigravityReleasePending() || typeof config.model !== "string" || !config.model.trim()) return; + const effectiveEnvironmentId = await resolveAdapterTestEnvironmentId(companyId, environmentId); + const driver = effectiveEnvironmentId ? (await environmentsSvc.getById(effectiveEnvironmentId))?.driver : "local"; + const remote = driver !== undefined && driver !== "local"; + const model = config.model; + const granted = (cloud: boolean) => { + try { return Boolean(resolveAntigravityCandidateAdmission({ companyId, model, target: antigravityCandidateTarget(cloud) })); } + catch { return false; } + }; + if (remote && !granted(true)) { + const refusal = antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true, remoteCandidateAdmitted: false })!; + throw unprocessable(refusal.message, { code: refusal.code }); + } + // A company enabled only for cloud environments cannot run it on this host. + if (!remote && !granted(false) && granted(true)) { + throw unprocessable("Google Antigravity is enabled only for cloud environments in this company for now. Choose a cloud environment for this agent.", + { code: "antigravity_local_unavailable" }); + } + } + async function assertAgentEnvironmentSelection( companyId: string, adapterType: string, @@ -3127,7 +3162,6 @@ export function agentRoutes( return; } if (type === "paperclip_runner" && provider === "acpx" && req.query.acpxAgent === "antigravity") { - if (environment && environment.driver !== "local") throw unprocessable("Google Antigravity account model discovery requires the Paperclip host."); let binding: AiConnectionBinding = { provider: "google", method: "subscription", mode: "responsible_user" }; if (typeof req.query.aiConnection === "string") { if (req.query.aiConnection.length > 4096) throw unprocessable("Invalid AI connection binding"); @@ -3135,12 +3169,16 @@ export function agentRoutes( catch { throw unprocessable("Invalid AI connection binding"); } } if (binding.provider !== "google") throw unprocessable("Select a Google runtime connection"); + // A Gemini API key's catalog is the same on every environment; only + // Google sign-in reads an account catalog on the Paperclip host. + const accountCatalog = binding.method !== "api_key"; + if (accountCatalog && environment && environment.driver !== "local") throw unprocessable("Google Antigravity account model discovery requires the Paperclip host."); const modelAgentId = asNonEmptyString(req.query.agentId); if (modelAgentId) { const modelAgent = await svc.getById(modelAgentId); if (!modelAgent || modelAgent.companyId !== companyId) throw notFound("Agent not found"); await assertCanUpdateAgent(req, modelAgent); - if (modelAgent.defaultEnvironmentId && !environmentId) { + if (accountCatalog && modelAgent.defaultEnvironmentId && !environmentId) { const target = await environmentsSvc.getById(modelAgent.defaultEnvironmentId); if (!target || target.driver !== "local") throw unprocessable("Google Antigravity account model discovery requires the Paperclip host."); } @@ -3252,6 +3290,17 @@ export function agentRoutes( throw error; }); if (!selection) return undefined; + if (adapterType === "paperclip_runner" && config.provider === "acpx" && config.acpxAgent === "antigravity") { + // Refuse a connection its environment cannot run here, not as a failed run. + const effectiveEnvironmentId = await resolveAdapterTestEnvironmentId(companyId, environmentId); + const driver = effectiveEnvironmentId ? (await environmentsSvc.getById(effectiveEnvironmentId))?.driver : "local"; + const remote = driver !== undefined && driver !== "local"; + const releasePending = antigravityReleasePending(); + const refusal = antigravityConnectionRefusal({ apiKey: selection.attribution.method === "api_key", remote, releasePending, + remoteCandidateAdmitted: remote && releasePending && antigravityRemoteCandidateAdmitted({ companyId, + model: typeof config.model === "string" ? config.model : undefined }) }); + if (refusal) throw unprocessable(refusal.message, { code: refusal.code }); + } const routing = validateModelCatalog ? aiConnectionMetadataSchema.parse(selection.connection.config.ai).routing : undefined; if (validateModelCatalog && routing?.models.length && !routing.models.some(model => aiRoutingModel(routing, agentHarnessType(adapterType, config), model.id) === config.model)) { @@ -4661,6 +4710,7 @@ export function agentRoutes( runtimeConfig: normalizedRuntimeConfig, }; await assertAgentEnvironmentSelection(companyId, hireInput.adapterType, hireInput.defaultEnvironmentId); + await assertAntigravityCandidateCoversEnvironment(companyId, hireInput.adapterType, hireInput.adapterConfig, hireInput.defaultEnvironmentId); await assertAgentDefaultEnvironmentSelection(companyId, hireInput.defaultEnvironmentId, { allowedDrivers: allowedEnvironmentDriversForAgent(hireInput.adapterType), allowedSandboxProviders: allowedSandboxProvidersForAgent(hireInput.adapterType), @@ -4982,6 +5032,7 @@ export function agentRoutes( }); const normalizedRuntimeConfig = await normalizeCreatedAgentRuntimeConfig(req, companyId, createInput.adapterType, normalizedAdapterConfig, createInput.runtimeConfig); await assertAgentEnvironmentSelection(companyId, createInput.adapterType, createInput.defaultEnvironmentId); + await assertAntigravityCandidateCoversEnvironment(companyId, createInput.adapterType, createInput.adapterConfig, createInput.defaultEnvironmentId); await assertAgentDefaultEnvironmentSelection(companyId, createInput.defaultEnvironmentId, { allowedDrivers: allowedEnvironmentDriversForAgent(createInput.adapterType), allowedSandboxProviders: allowedSandboxProvidersForAgent(createInput.adapterType), @@ -5804,6 +5855,10 @@ export function agentRoutes( }); } const nextAiConfig = (patchData.adapterConfig ?? existing.adapterConfig) as Record; + if (touchesAdapterConfiguration || hasOwn(patchData, "defaultEnvironmentId")) { + await assertAntigravityCandidateCoversEnvironment(existing.companyId, requestedAdapterType, nextAiConfig, + hasOwn(patchData, "defaultEnvironmentId") ? patchData.defaultEnvironmentId as string | null : existing.defaultEnvironmentId); + } if (existing.runtimeConfig.aiConnection && requestedRuntimeConfig && !requestedRuntimeConfig.aiConnection && !isAgentSetupDraft(existing)) { const existingBinding = aiRuntimeConnectionBindingSchema.safeParse(existing.runtimeConfig.aiConnection).data; diff --git a/server/src/services/antigravity-connection-models.ts b/server/src/services/antigravity-connection-models.ts index be787da0f3a..d8ee2729098 100644 --- a/server/src/services/antigravity-connection-models.ts +++ b/server/src/services/antigravity-connection-models.ts @@ -1,5 +1,5 @@ import type { Db } from "@paperclipai/db"; -import type { AiConnectionBinding } from "@paperclipai/shared"; +import { antigravityApiKeyModels, type AiConnectionBinding } from "@paperclipai/shared"; import { AntigravityModelDiscoveryCleanupError, discoverAntigravityModels } from "../vendor/paperclip-runner/index.js"; import { unprocessable } from "../errors.js"; import { logger } from "../middleware/logger.js"; @@ -7,8 +7,16 @@ import { prepareManagedAiRuntime } from "./ai-connection-runtime.js"; import { RetiredCredentialRecoveryError } from "./quota-credential-recovery.js"; import { retainGoogleCredentialCleanup } from "./retained-google-credential-cleanup.js"; -/** Metadata uses the selected connection's ordinary authority and encrypted - * refresh writeback. The native client cannot create a session or send a prompt. +/** A Google API key's catalog does not depend on the key or the environment: + * the pinned runtime builds it locally. Suggestions only; an explicit model id + * stays accepted and native admission decides. */ +export function antigravityApiKeyModelCatalog() { + return antigravityApiKeyModels(); +} + +/** Account metadata uses the selected connection's ordinary authority and + * encrypted refresh writeback. The native client cannot create a session or + * send a prompt. An API-key connection never starts a process here. */ export async function antigravityConnectionModels(db: Db, input: { companyId: string; @@ -18,6 +26,7 @@ export async function antigravityConnectionModels(db: Db, input: { allowUninstalledShared: boolean; }) { if (input.binding.provider !== "google") throw unprocessable("Select a Google runtime connection"); + if (input.binding.method === "api_key") return antigravityApiKeyModelCatalog(); const runtime = await prepareManagedAiRuntime(db, { companyId: input.companyId, responsibleUserId: input.userId, agentId: input.agentId ?? "00000000-0000-0000-0000-000000000000", @@ -28,9 +37,8 @@ export async function antigravityConnectionModels(db: Db, input: { }); let retained = false; try { - if (runtime.attribution.method !== "subscription") throw unprocessable( - "Sign in to Google Antigravity to discover account models. With an API key, enter the exact model identifier.", - ); + // The binding named sign-in but the selected connection holds a Gemini API key. + if (runtime.attribution.method !== "subscription") return antigravityApiKeyModelCatalog(); const home = runtime.config.env.GEMINI_HOME; if (typeof home !== "string" || !home) throw unprocessable("The selected Google runtime account is unavailable."); try { return (await discoverAntigravityModels(home)).models; } diff --git a/server/src/services/antigravity-connection-probe.ts b/server/src/services/antigravity-connection-probe.ts index a2939809e4b..498c158da42 100644 --- a/server/src/services/antigravity-connection-probe.ts +++ b/server/src/services/antigravity-connection-probe.ts @@ -3,10 +3,14 @@ import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import type { AdapterEnvironmentTestContext, AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils"; -import { NativeEnvironmentProbeCleanupError, probeNativeRunnerEnvironment, resolveAcpxRuntimeRoot } from "../vendor/paperclip-runner/index.js"; +import { runAdapterExecutionTargetShellCommand, type AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target"; +import { NativeEnvironmentProbeCleanupError, QUALIFIED_ACPX_PROFILES, probeNativeRunnerEnvironment, resolveAcpxRuntimeRoot } from "../vendor/paperclip-runner/index.js"; import { logger } from "../middleware/logger.js"; -import { resolveAntigravityCandidateAdmission } from "./native-runtime/acpx-qualification.js"; +import { antigravityRemoteCandidateAdmitted, resolveAntigravityCandidateAdmission } from "./native-runtime/acpx-qualification.js"; import { antigravityCredentialTurn, prepareAntigravityRunnerCredentials } from "./native-runtime/antigravity-runner-credentials.js"; +import { antigravityConnectionRefusal } from "./native-runtime/antigravity-connection-policy.js"; +import { antigravityReleasePending } from "./native-runtime/antigravity-release.js"; +import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256, antigravityProviderPackEntryRefusal } from "./native-runtime/remote-provider-pack.js"; import { resolvePaperclipRunnerBinary } from "./native-runtime/native-codex-runner.js"; const TRANSPORT_KEYS = ["PATH", "LANG", "LANGUAGE", "TZ", "TMPDIR", "TEMP", "TMP", "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "ALL_PROXY"]; @@ -39,12 +43,82 @@ export function antigravityConnectionProbeFailure(companyId: string, error: unkn }] }; } -/** The ordinary Test uses the selected managed account and no model turn. */ +const failed = (code: string, message: string): AdapterEnvironmentTestResult => ({ adapterType: "paperclip_runner", status: "fail", + testedAt: new Date().toISOString(), checks: [{ code, level: "error", message }] }); + +const REMOTE_PACK_ROOTS = ["/opt/paperclip-runner/provider-pack", '"$HOME/.local/share/paperclip-runner/provider-pack"']; + +/** + * A cloud environment runs Antigravity from its image's provider pack. Test + * proves that pack carries this release's patched Linux closure, exactly as run + * preparation admits it, without reading credentials there or sending a prompt. + * The run itself verifies the closure tree before launch. + */ +export async function probeAntigravityExecutionTarget(target: Extract): Promise { + const unavailable = () => failed("antigravity_remote_runtime_missing", + "This cloud environment does not have the current Google Antigravity runtime. Use the current Paperclip runner image for this environment."); + if (target.transport === "sandbox" && target.runnerTask) { + return failed("antigravity_remote_runtime_missing", "Google Antigravity is unavailable in this hosting environment."); + } + const expectedPath = "provider-assets/antigravity/linux-x64"; + const command = [ + `for pack in ${REMOTE_PACK_ROOTS.join(" ")}; do`, + ` if [ -f "$pack/provider-pack.json" ] && [ -d "$pack/${expectedPath}" ] && [ ! -L "$pack/${expectedPath}" ]; then`, + ' uname -s; uname -m; head -c 262144 "$pack/provider-pack.json"; exit 0', + " fi", + "done", + "exit 127", + ].join("\n"); + let response: Awaited>; + try { + response = await runAdapterExecutionTargetShellCommand(`antigravity-pack-${randomUUID()}`, target, command, + { cwd: target.remoteCwd, env: {}, timeoutSec: 20 }); + } catch { return failed("antigravity_remote_check_failed", "Paperclip could not reach this cloud environment. Retry Test."); } + if (response.timedOut) return failed("antigravity_remote_check_failed", "Paperclip could not reach this cloud environment. Retry Test."); + if (response.exitCode !== 0) return unavailable(); + const [os, arch, ...manifestLines] = response.stdout.split("\n"); + if (os?.trim() !== "Linux" || arch?.trim() !== "x86_64") { + return failed("antigravity_remote_platform_unsupported", "Google Antigravity needs a Linux x64 cloud environment."); + } + let manifest: Record | null; + try { manifest = asRecord(JSON.parse(manifestLines.join("\n"))); } catch { return unavailable(); } + const payload = asRecord(manifest?.payload); + // While pending, the image lists the candidate closure under candidateProviders. + const pending = antigravityReleasePending(); + const inventory = pending ? "candidateProviders" : "providers"; + const listed = asRecord(payload?.[inventory]), other = asRecord(payload?.[pending ? "providers" : "candidateProviders"]); + const entry = asRecord(listed?.antigravity); + const targetIdentity = asRecord(payload?.target); + if (!entry || entry.path !== expectedPath || entry.qualification !== (pending ? "pending" : "qualified") + || typeof entry.version !== "string" || typeof entry.profileDigest !== "string" || typeof entry.closureDigest !== "string" + || antigravityProviderPackEntryRefusal({ inventory, inBoth: Boolean(other?.antigravity), + target: { platform: String(targetIdentity?.platform), architecture: String(targetIdentity?.architecture) }, + entry: { version: entry.version, profileDigest: entry.profileDigest, closureDigest: entry.closureDigest }, + releasePending: pending, profile: QUALIFIED_ACPX_PROFILES.antigravity, + patchedClosures: ANTIGRAVITY_PATCHED_CLOSURE_SHA256 })) { + return unavailable(); + } + return { adapterType: "paperclip_runner", status: "warn", testedAt: new Date().toISOString(), + checks: [{ code: "antigravity_remote_runtime_ready", level: "warn", + message: "This cloud environment has the verified Google Antigravity runtime. Google checks the API key and the selected model when the agent first runs. No prompt was sent." }] }; +} + +/** The ordinary Test uses the selected connection and no model turn. */ export async function testAntigravityConnection(context: AdapterEnvironmentTestContext, model: string): Promise { - if (context.executionTarget?.kind === "remote") throw new Error("Google Antigravity candidate testing requires the Paperclip host."); - const admission = resolveAntigravityCandidateAdmission({ companyId: context.companyId, model }); - if (!admission) throw new Error("Google Antigravity is not available for this company."); const configured = context.config.env; + const configuredKey = asRecord(configured)?.GEMINI_API_KEY; + const pending = antigravityReleasePending(); + const target = context.executionTarget; + const remote = target?.kind === "remote"; + const refusal = antigravityConnectionRefusal({ apiKey: typeof configuredKey === "string" && configuredKey.trim().length > 0, + remote, releasePending: pending, + remoteCandidateAdmitted: remote && pending && antigravityRemoteCandidateAdmitted({ companyId: context.companyId, model }) }); + if (refusal) return failed(refusal.code, refusal.message); + if (target?.kind === "remote") return probeAntigravityExecutionTarget(target); + // Only the pending candidate needs the operator's grant; a released profile carries none. + const admission = pending ? resolveAntigravityCandidateAdmission({ companyId: context.companyId, model, + target: { platform: process.platform, architecture: process.arch } }) : undefined; + if (pending && !admission) throw new Error("Google Antigravity is not available for this company."); const environment = Object.fromEntries([ ...TRANSPORT_KEYS.flatMap(key => typeof process.env[key] === "string" ? [[key, process.env[key]!]] : []), ...Object.entries(configured && typeof configured === "object" && !Array.isArray(configured) ? configured : {}) @@ -69,7 +143,7 @@ export async function testAntigravityConnection(context: AdapterEnvironmentTestC const receipt = await probeNativeRunnerEnvironment({ runtimeDirectory, provider: "acpx", model, environment: credentials.environment, admissionOnly: true, timeoutMs: 45_000, transportOptions: { runnerBinary, externallySandboxed: false, - acpxAgent: "antigravity", acpxCandidateAdmission: admission, acpxRuntimeDirectory, + acpxAgent: "antigravity", ...(admission ? { acpxCandidateAdmission: admission } : {}), acpxRuntimeDirectory, acpxPermissionMode: "approve-reads", acpxPermissionModePinned: true, prpIdentity: { runnerInstanceId: `setup-runner-${nonce}`, runId: `setup-${nonce}`, normalizedSessionId, environmentLeaseId: `setup-lease-${nonce}`, turnId: `setup-turn-${nonce}`, itemId: `setup-item-${nonce}` } }, @@ -86,5 +160,5 @@ export async function testAntigravityConnection(context: AdapterEnvironmentTestC } return { adapterType: "paperclip_runner", status: "pass", testedAt: new Date().toISOString(), checks: [{ code: "antigravity_metadata_verified", level: "info", - message: "The Google Antigravity candidate verified the selected account and exact model. No model prompt was sent." }] }; + message: "Google Antigravity verified the selected connection and exact model. No model prompt was sent." }] }; } diff --git a/server/src/services/heartbeat/native-lifecycle.test.ts b/server/src/services/heartbeat/native-lifecycle.test.ts index 86bc6ca244d..cc21dea658b 100644 --- a/server/src/services/heartbeat/native-lifecycle.test.ts +++ b/server/src/services/heartbeat/native-lifecycle.test.ts @@ -75,3 +75,24 @@ describe("default lifecycle for an agent that never chose one", () => { expect(resolveHeartbeatNativeLifecyclePolicy({ ...unset, ...change })).toEqual(expected); }); }); + +describe("Google Antigravity lifecycle", () => { + // Like Kimi, Antigravity runs turn by turn: a warm Antigravity owner needs its + // own credential-rotation proof first. The policy resolves it instead of the + // executor refusing a warm run, in both release states. + const antigravity: Input = { ...base, backend: "acpx_runtime", acpxAgent: "antigravity" }; + it.each<{ name: string; change: Partial }>([ + { name: "an explicit warm choice with a plain environment key", change: {} }, + { name: "an explicit warm choice with a managed API key", change: { managedAiSelected: true, managedAiAttribution: { provider: "google", method: "api_key" } } }, + { name: "a managed Google sign-in", change: { managedAiSelected: true, managedAiAttribution: { provider: "google", method: "subscription" } } }, + { name: "an environment that chose warm", change: { agentMode: "per_turn", environmentPolicy: warm } }, + { name: "a remote sandbox on a reusable lease", change: { agentMode: undefined, localTarget: false, remoteSandboxTarget: { reusableLease: true } } }, + { name: "a task-owned sandbox", change: { taskOwned: true, environmentPolicy: warm } }, + // No release ever admitted a warm Antigravity turn, so a saved warm policy + // has no live warm owner to retire; the next turn simply runs per-turn. + { name: "a saved warm policy with an API key", change: { persistedPolicy: warm, managedAiSelected: true, managedAiAttribution: { provider: "google", method: "api_key" } } }, + { name: "a saved warm policy with a Google sign-in", change: { persistedPolicy: warm, managedAiSelected: true, managedAiAttribution: { provider: "google", method: "subscription" } } }, + ])("runs per-turn for $name", ({ change }) => { + expect(resolveHeartbeatNativeLifecyclePolicy({ ...antigravity, ...change })).toEqual(perTurn); + }); +}); diff --git a/server/src/services/heartbeat/native-lifecycle.ts b/server/src/services/heartbeat/native-lifecycle.ts index 21789901d25..07fa42c103a 100644 --- a/server/src/services/heartbeat/native-lifecycle.ts +++ b/server/src/services/heartbeat/native-lifecycle.ts @@ -1,7 +1,7 @@ import { PAPERCLIP_RUNNER_IDLE_TIMEOUT_DEFAULT_MS, resolvePaperclipRunnerIdleTimeoutMs } from "@paperclipai/adapter-utils"; import type { NativeExecutionInput } from "../../vendor/paperclip-runner/index.js"; import { - defaultsRemoteSandboxRunToWarm, defaultsToWarmFollowUp, supportsManagedNativeWarmSession, + defaultsRemoteSandboxRunToWarm, defaultsToWarmFollowUp, requiresPerTurnNativeSession, supportsManagedNativeWarmSession, } from "../native-runtime/native-warm-capability.js"; export type NativeLifecyclePolicy = NonNullable; @@ -51,8 +51,12 @@ export function resolveHeartbeatNativeLifecyclePolicy(input: { : { mode: "per_turn", idleTimeoutMs: null }; const supportsManagedWarm = input.adapterType === "paperclip_runner" && (input.taskOwned || supportsManagedNativeWarmSession(profile, input.managedAiAttribution)); + // A harness qualified only per-turn runs per-turn even when a saved policy + // says warm: no release admitted a warm turn for it, so none can be live. + if (requiresPerTurnNativeSession(profile)) return { mode: "per_turn", idleTimeoutMs: null }; return input.persistedPolicy ?? - (["openai_dot_mcp", "grok_bot_mcp", "muse_external", "cursor_cloud_api"].includes(input.backend) || input.managedAiSelected && !supportsManagedWarm + (["openai_dot_mcp", "grok_bot_mcp", "muse_external", "cursor_cloud_api"].includes(input.backend) + || input.managedAiSelected && !supportsManagedWarm ? { mode: "per_turn", idleTimeoutMs: null } : input.environmentPolicy ?? agentPolicy); } diff --git a/server/src/services/heartbeat/runtime-selection.ts b/server/src/services/heartbeat/runtime-selection.ts index fd10d8ad1c1..f55c5b40e59 100644 --- a/server/src/services/heartbeat/runtime-selection.ts +++ b/server/src/services/heartbeat/runtime-selection.ts @@ -1,4 +1,5 @@ import { assertPaperclipRunnerBinaryConfiguration } from "../native-runtime/native-codex-runner.js"; +import { antigravityForcesSameSessionRecovery } from "../native-runtime/antigravity-release.js"; import { readNativeWorkspaceMigration, migratedNativeExecutionCwd } from "../native-runtime/native-workspace-migration.js"; import { resolveProviderApiPlacement } from "../native-runtime/provider-api-placement.js"; import { readClaimedNativeStopRecovery } from "../native-runtime/native-cancellation-request.js"; @@ -951,8 +952,7 @@ export async function selectHeartbeatRuntime(db: Db, input: HeartbeatRuntimeSele } nativeSessionId = nativeExecutionWithCheckpoint.normalizedSessionId; } - if (nativeResumeCheckpoint && nativeExecution.provider.kind === "acpx" - && nativeExecution.provider.agent === "antigravity") { + if (nativeResumeCheckpoint && antigravityForcesSameSessionRecovery(nativeExecution.provider)) { nativeResumeCheckpoint = { ...nativeResumeCheckpoint, providerRecoveryPolicy: "same_session_only" }; } const nativeSandboxLifecycle = resolveNativeSandboxLifecycle({ diff --git a/server/src/services/native-runtime/acpx-qualification.ts b/server/src/services/native-runtime/acpx-qualification.ts index da67efd8220..ebc8013adf7 100644 --- a/server/src/services/native-runtime/acpx-qualification.ts +++ b/server/src/services/native-runtime/acpx-qualification.ts @@ -1,26 +1,56 @@ import { PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils"; -import { parseAcpxCandidateAdmission, QUALIFIED_ACPX_PROFILES, type AcpxCandidateAdmission, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js"; +import { isAntigravityNativeTarget, parseAcpxCandidateAdmission, QUALIFIED_ACPX_PROFILES, type AcpxCandidateAdmission, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js"; /** Trusted operator startup authority, separate from saved agent configuration. */ export const ANTIGRAVITY_CANDIDATE_ADMISSION_ENV = "PAPERCLIP_ACPX_CANDIDATE_ADMISSION"; +/** The only target a cloud environment runs Antigravity on: the remote pack's patched linux-x64 closure. */ +export const ANTIGRAVITY_REMOTE_TARGET = Object.freeze({ platform: "linux", architecture: "x64" }); + +/** True when the operator granted this company and exact model a cloud (linux-x64) candidate. */ +export function antigravityRemoteCandidateAdmitted(input: { companyId?: string; model?: string }, hostEnvironment: NodeJS.ProcessEnv = process.env): boolean { + try { return Boolean(input.model && resolveAntigravityCandidateAdmission({ ...input, target: ANTIGRAVITY_REMOTE_TARGET }, hostEnvironment)); } + catch { return false; } +} + +/** + * The operator's candidate grant for one company and exact model. With a + * `target`, the grant must name that execution target (this host, or + * `ANTIGRAVITY_REMOTE_TARGET` for a cloud environment) and its patched + * closure. Without one (availability surfaces) a grant for this host or for + * the cloud target is accepted. Other companies get nothing. + */ export function resolveAntigravityCandidateAdmission( - input: { companyId?: string; model?: string }, + input: { companyId?: string; model?: string; target?: { platform: string; architecture: string } }, hostEnvironment: NodeJS.ProcessEnv = process.env, ): AcpxCandidateAdmission | undefined { const encoded = hostEnvironment[ANTIGRAVITY_CANDIDATE_ADMISSION_ENV]; - if (!encoded || !input.companyId || process.platform !== "darwin" || process.arch !== "arm64") return undefined; + if (!encoded || !input.companyId) return undefined; + const hostNative = isAntigravityNativeTarget(process.platform, process.arch); + // Only a target with a verified, patched closure can run the native candidate. + if (input.target && !isAntigravityNativeTarget(input.target.platform, input.target.architecture)) return undefined; let value: unknown; try { value = JSON.parse(encoded); } catch { throw new Error("Invalid Antigravity candidate admission"); } if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid Antigravity candidate admission"); const record = value as Record; // Other companies receive no candidate surface or execution authority. if (record.companyId !== input.companyId) return undefined; - return parseAcpxCandidateAdmission(value, { + const admission = parseAcpxCandidateAdmission(value, { companyId: input.companyId, agent: "antigravity", model: input.model ?? (typeof record.model === "string" ? record.model : ""), }); + const names = (target: { platform: string; architecture: string }) => admission.platform === target.platform && admission.architecture === target.architecture; + if (input.target) { + if (!names(input.target)) throw new Error("Antigravity candidate admission does not match the execution target"); + } else if (!names(ANTIGRAVITY_REMOTE_TARGET) && !names({ platform: process.platform, architecture: process.arch })) { + // A host without a verified closure has no local surface to refuse. + if (!hostNative) return undefined; + throw new Error("Antigravity candidate admission does not match this host"); + } else if (!names(ANTIGRAVITY_REMOTE_TARGET) && !hostNative) { + return undefined; + } + return admission; } export function resolveKimiCandidateAdmission( 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 3eddbc27d6f..77812bb2ffa 100644 --- a/server/src/services/native-runtime/antigravity-candidate-admission.test.ts +++ b/server/src/services/native-runtime/antigravity-candidate-admission.test.ts @@ -1,19 +1,25 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { readFileSync } from "node:fs"; import { QUALIFIED_ACPX_PROFILES } from "../../vendor/paperclip-runner/index.js"; -import { ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, resolveAntigravityCandidateAdmission } from "./acpx-qualification.js"; +import { ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, ANTIGRAVITY_REMOTE_TARGET, antigravityRemoteCandidateAdmitted, resolveAntigravityCandidateAdmission } from "./acpx-qualification.js"; import { resolvePaperclipRunnerNativeProviderInput, resolvePaperclipRunnerProviderProfile } from "./provider-profile.js"; import { resolveNativeRuntimeMode } from "./runtime-mode.js"; const companyId = "candidate-company"; const model = "gemini-3.8-flash-low"; const config = { provider: "acpx", acpxAgent: "antigravity", model }; -const localHost = process.platform === "darwin" && process.arch === "arm64"; const distributions = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8")); -const admission = () => ({ schema: "paperclip.acpx-candidate-admission.v1", companyId, - agent: "antigravity", model, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, - nativeClosureDigest: `sha256:${distributions.platforms["darwin-arm64"].closureSha256}`, - platform: "darwin", architecture: "arm64", expiresAt: Date.now() + 60_000 }); +const verifiedTargets = Object.keys(distributions.platforms).filter(target => distributions.platforms[target].provisioning === "verified-closure"); +const hostTarget = `${process.platform}-${process.arch}`; +const localHost = verifiedTargets.includes(hostTarget); +const targetAdmission = (target: string) => { + const [platform, architecture] = target.split("-"); + return { schema: "paperclip.acpx-candidate-admission.v1", companyId, + agent: "antigravity", model, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, + nativeClosureDigest: `sha256:${distributions.platforms[target].closureSha256}`, + platform, architecture, expiresAt: Date.now() + 60_000 }; +}; +const admission = () => targetAdmission(localHost ? hostTarget : "darwin-arm64"); describe("Antigravity operator candidate admission", () => { afterEach(() => vi.unstubAllEnvs()); @@ -54,10 +60,40 @@ describe("Antigravity operator candidate admission", () => { .toMatchObject({ kind: "native", profile: { backend: "acpx_runtime" } }); }); + it("binds a cloud grant to linux-x64 and the patched closure, for its company and model only", () => { + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify(targetAdmission("linux-x64"))); + expect(resolveAntigravityCandidateAdmission({ companyId, model, target: ANTIGRAVITY_REMOTE_TARGET })) + .toMatchObject({ companyId, model, platform: "linux", architecture: "x64" }); + expect(antigravityRemoteCandidateAdmitted({ companyId, model })).toBe(true); + expect(antigravityRemoteCandidateAdmitted({ companyId: "another-company", model })).toBe(false); + expect(antigravityRemoteCandidateAdmitted({ companyId, model: "gemini-3.8-flash-high" })).toBe(false); + if (hostTarget !== "linux-x64") { + expect(() => resolveAntigravityCandidateAdmission({ companyId, model, target: { platform: process.platform, architecture: process.arch } })) + .toThrow(/does not match the execution target/); + } + for (const grant of [targetAdmission("linux-arm64"), targetAdmission("darwin-arm64"), + { ...targetAdmission("linux-x64"), nativeClosureDigest: `sha256:${distributions.platforms["linux-x64"].vendorClosureSha256}` }]) { + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify(grant)); + expect(antigravityRemoteCandidateAdmitted({ companyId, model })).toBe(false); + } + }); + + it("declares verified closures for macOS ARM and both Linux architectures", () => { + expect(verifiedTargets.sort()).toEqual(["darwin-arm64", "linux-arm64", "linux-x64"]); + }); + + it.runIf(localHost)("rejects another verified platform's exact record on this host", () => { + // linux-x64 is also the cloud target, so a grant for it is a valid surface grant on any host. + for (const target of verifiedTargets.filter(target => target !== hostTarget && target !== "linux-x64")) { + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify(targetAdmission(target))); + expect(() => resolveAntigravityCandidateAdmission({ companyId, model })).toThrow(/does not match this host/); + } + }); + it.runIf(localHost).each([ { expiresAt: 0 }, { profileDigest: `sha256:${"0".repeat(64)}` }, - { nativeClosureDigest: `sha256:${"0".repeat(64)}` }, { platform: "linux" }, - { architecture: "x64" }, { allowAll: true }, + { nativeClosureDigest: `sha256:${"0".repeat(64)}` }, { platform: process.platform === "linux" ? "darwin" : "linux" }, + { architecture: process.arch === "x64" ? "arm64" : "x64" }, { allowAll: true }, ])("rejects expired, changed or broad operator authorization %j", changes => { vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify({ ...admission(), ...changes })); expect(() => resolveAntigravityCandidateAdmission({ companyId, model })).toThrow(); diff --git a/server/src/services/native-runtime/antigravity-connection-policy.ts b/server/src/services/native-runtime/antigravity-connection-policy.ts new file mode 100644 index 00000000000..47164767eb9 --- /dev/null +++ b/server/src/services/native-runtime/antigravity-connection-policy.ts @@ -0,0 +1,58 @@ +/** + * Which Google Antigravity connections can run where. Configuration save and + * Test refuse an unsupported choice up front with these messages; the run-time + * check stays only as a defense, as a named permanent startup rejection. + */ +export const ANTIGRAVITY_REMOTE_UNAVAILABLE = "antigravity_remote_unavailable"; +export const ANTIGRAVITY_REMOTE_SIGN_IN_UNSUPPORTED = "antigravity_remote_sign_in_unsupported"; +export const ANTIGRAVITY_WARM_UNSUPPORTED = "antigravity_warm_unsupported"; + +export type AntigravityConnectionRefusal = { + code: typeof ANTIGRAVITY_REMOTE_UNAVAILABLE | typeof ANTIGRAVITY_REMOTE_SIGN_IN_UNSUPPORTED | typeof ANTIGRAVITY_WARM_UNSUPPORTED; + message: string; +}; + +export function antigravityConnectionRefusal(input: { + /** A Google API key is the connection, rather than a Google sign-in. */ + apiKey: boolean; + remote: boolean; + lifecycleMode?: "per_turn" | "warm"; + releasePending: boolean; + /** + * While pending: the operator granted this company and model a candidate for + * the cloud target (linux-x64). It admits an API key only, never sign-in. + */ + remoteCandidateAdmitted?: boolean; +}): AntigravityConnectionRefusal | null { + // Antigravity runs one turn at a time on every connection until a warm + // owner is separately qualified; lifecycle resolution already enforces it. + if (input.lifecycleMode === "warm") { + return { code: ANTIGRAVITY_WARM_UNSUPPORTED, + message: "Google Antigravity runs one turn at a time. Turn off warm sessions for this agent." }; + } + if (input.remote && input.releasePending && !(input.remoteCandidateAdmitted && input.apiKey)) { + if (input.remoteCandidateAdmitted) { + return { code: ANTIGRAVITY_REMOTE_SIGN_IN_UNSUPPORTED, + message: "Google sign-in for Google Antigravity works only on the Paperclip host. To run this agent in a cloud environment, connect a Google API key instead." }; + } + return { code: ANTIGRAVITY_REMOTE_UNAVAILABLE, + message: "Google Antigravity runs only on the Paperclip host for now. Choose the Paperclip host as this agent's environment." }; + } + if (input.apiKey) return null; + if (input.remote) { + return { code: ANTIGRAVITY_REMOTE_SIGN_IN_UNSUPPORTED, + message: "Google sign-in for Google Antigravity works only on the Paperclip host. To run this agent in a cloud environment, connect a Google API key instead." }; + } + return null; +} + +/** A run reached execution with a connection its target cannot use. Retrying + * cannot change the saved choice, so it is a permanent, named refusal. */ +export class AntigravityConnectionConfigurationError extends Error { + readonly code: AntigravityConnectionRefusal["code"]; + constructor(refusal: AntigravityConnectionRefusal) { + super(refusal.message); + this.name = "AntigravityConnectionConfigurationError"; + this.code = refusal.code; + } +} diff --git a/server/src/services/native-runtime/antigravity-release.test.ts b/server/src/services/native-runtime/antigravity-release.test.ts new file mode 100644 index 00000000000..8a83e712121 --- /dev/null +++ b/server/src/services/native-runtime/antigravity-release.test.ts @@ -0,0 +1,165 @@ +import { readFileSync } from "node:fs"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +// Both release states are exercised against the same build: the pending +// candidate declaration that ships today, and the qualified declaration the +// flip produces (no qualificationStatus, profile version bumped), as the Kimi +// probe tests stub it. +const release = vi.hoisted(() => ({ pending: true })); +vi.mock("../../vendor/paperclip-runner/index.js", async importOriginal => { + const original = await importOriginal(); + const { qualificationStatus: _pending, ...qualified } = original.QUALIFIED_ACPX_PROFILES.antigravity; + const released = { ...qualified, agentProfileVersion: qualified.agentProfileVersion + 1 }; + const profiles = { ...original.QUALIFIED_ACPX_PROFILES }; + Object.defineProperty(profiles, "antigravity", { enumerable: true, + get: () => release.pending ? original.QUALIFIED_ACPX_PROFILES.antigravity : released }); + return { ...original, QUALIFIED_ACPX_PROFILES: profiles }; +}); + +import { NativeProviderStateIncompatibleError, QUALIFIED_ACPX_PROFILES, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js"; +import { ANTIGRAVITY_CANDIDATE_ADMISSION_ENV } from "./acpx-qualification.js"; +import { + antigravityForcesSameSessionRecovery, + antigravityReleasePending, + antigravityUsesRunScopedState, + assertAntigravityExecutionAdmissible, +} from "./antigravity-release.js"; +import { buildNativeExecutionInput } from "./native-execution-input.js"; +import { nativeSessionFailureDisposition, nativeSessionFailureSourceCode, scopedRunnerdStateRoot } from "./native-session-executor.js"; +import { NATIVE_PROVIDER_STATE_INCOMPATIBLE } from "./native-session-resume.js"; +import { nativeRuntimeContextFixture } from "./runtime-context.test-fixture.js"; + +const companyId = "10000000-0000-4000-8000-000000000001"; +const model = "gemini-3.8-flash-low"; +const localHost = process.platform === "darwin" && process.arch === "arm64"; +const distributions = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8")); + +function antigravityExecution(input: { runId?: string; issueId?: string; workspaceId?: string; sessionId?: string } = {}) { + const runId = input.runId ?? "40000000-0000-4000-8000-000000000004"; + const execution = buildNativeExecutionInput({ + companyId, runId, agentId: "30000000-0000-4000-8000-000000000003", + issue: { id: input.issueId ?? "20000000-0000-4000-8000-000000000002", identifier: "AG-1", title: "Test", description: null, workMode: "standard" }, + taskPrompt: "Only the current turn", + workspace: { id: input.workspaceId ?? "90000000-0000-4000-8000-000000000009", cwd: "/workspace", repoUrl: null, repoRef: null, branchName: null }, + normalizedSessionId: input.sessionId ?? "60000000-0000-4000-8000-000000000006", + provider: "acpx", acpxAgent: "antigravity", model, acpxPermissionMode: "approve-all", + completionContract: { id: "70000000-0000-4000-8000-000000000007", sha256: `sha256:${"a".repeat(64)}`, schemaVersion: "paperclip.run-result.v1", + contract: { revision: "1", objective: "Test", criteria: [{ id: "objective", requirement: "Answer" }] } }, + runtimeContext: nativeRuntimeContextFixture(), + }) as NativeExecutionInput; + // The execution input binds the profile version the running release declares. + (execution.provider as { profile: { agentProfileVersion: number } }).profile.agentProfileVersion = + QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion; + return execution; +} + +const candidateGrant = (target = "darwin-arm64", changes: Record = {}) => { + const [platform, architecture] = target.split("-"); + return JSON.stringify({ schema: "paperclip.acpx-candidate-admission.v1", companyId, + agent: "antigravity", model, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, + nativeClosureDigest: `sha256:${distributions.platforms[target].closureSha256}`, + platform, architecture, expiresAt: Date.now() + 60_000, ...changes }); +}; + +afterEach(() => { release.pending = true; vi.unstubAllEnvs(); }); + +describe("Antigravity executor admission", () => { + const admissible = (execution: NativeExecutionInput, changes: Partial[0]> = {}) => + () => assertAntigravityExecutionAdmissible({ execution, useRunnerd: true, remoteTarget: false, ...changes }); + + it("requires the exact local per-turn candidate grant while the profile is pending", () => { + expect(antigravityReleasePending()).toBe(true); + const execution = antigravityExecution(); + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, undefined); + expect(admissible(execution)).toThrow(/paperclip_runner_antigravity_candidate_ineligible/); + if (!localHost) return; + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, candidateGrant()); + expect(admissible(execution)).not.toThrow(); + // A local grant never admits a cloud run. + for (const change of [{ remoteTarget: true }, { restartRecovery: { kind: "same_run" } }, { useRunnerd: false }, { backend: {} }]) { + expect(admissible(execution, change)).toThrow(/candidate_ineligible/); + } + const warm = { ...execution, session: { ...execution.session, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 1 } } } as NativeExecutionInput; + expect(admissible(warm)).toThrow(/candidate_ineligible/); + }); + + it("admits a cloud run only with a linux-x64 grant naming the patched closure, for the granted company", () => { + const execution = antigravityExecution(); + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, candidateGrant("linux-x64")); + expect(admissible(execution, { remoteTarget: true })).not.toThrow(); + const warm = { ...execution, session: { ...execution.session, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 1 } } } as NativeExecutionInput; + expect(admissible(warm, { remoteTarget: true })).toThrow(/candidate_ineligible/); + expect(admissible(execution, { remoteTarget: true, restartRecovery: { kind: "reattach_remote_runner" } })).toThrow(/candidate_ineligible/); + const otherCompany = { ...execution, binding: { ...execution.binding, companyId: "10000000-0000-4000-8000-0000000000ff" } } as NativeExecutionInput; + expect(admissible(otherCompany, { remoteTarget: true })).toThrow(/candidate_ineligible/); + for (const grant of [candidateGrant("linux-arm64"), candidateGrant("darwin-arm64"), + candidateGrant("linux-x64", { nativeClosureDigest: `sha256:${distributions.platforms["linux-x64"].vendorClosureSha256}` }), + candidateGrant("linux-x64", { model: "gemini-3.8-flash-high" })]) { + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, grant); + expect(admissible(execution, { remoteTarget: true })).toThrow(/candidate_ineligible/); + } + }); + + it("takes the general qualified path after the flip: no grant, restart recovery, remote and warm targets", () => { + release.pending = false; + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, undefined); + const execution = antigravityExecution(); + expect(admissible(execution)).not.toThrow(); + expect(admissible(execution, { remoteTarget: true, restartRecovery: { kind: "reattach_remote_runner" } })).not.toThrow(); + const preconfigured = { ...execution, homeMode: "preconfigured" } as NativeExecutionInput; + expect(admissible(preconfigured)).not.toThrow(); + }); +}); + +describe("Antigravity recovery policy and state root", () => { + it("forces the candidate's same-session recovery and per-run root only while pending", () => { + const execution = antigravityExecution(); + const nextRun = antigravityExecution({ runId: "50000000-0000-4000-8000-000000000005" }); + expect(antigravityForcesSameSessionRecovery(execution.provider)).toBe(true); + expect(antigravityUsesRunScopedState(execution)).toBe(true); + expect(scopedRunnerdStateRoot(execution)).not.toBe(scopedRunnerdStateRoot(nextRun)); + + release.pending = false; + expect(antigravityForcesSameSessionRecovery(execution.provider)).toBe(false); + expect(antigravityUsesRunScopedState(execution)).toBe(false); + // Qualified: one root per session scope, kept across the session's runs. + expect(scopedRunnerdStateRoot(execution)).toBe(scopedRunnerdStateRoot(nextRun)); + }); + + it.each([false, true])("never shares a state root across subtasks or workspaces (pending=%s)", pending => { + release.pending = pending; + const parent = antigravityExecution(); + const subtask = antigravityExecution({ issueId: "21000000-0000-4000-8000-000000000002", + workspaceId: "91000000-0000-4000-8000-000000000009", sessionId: "61000000-0000-4000-8000-000000000006" }); + const otherWorkspace = antigravityExecution({ workspaceId: "92000000-0000-4000-8000-000000000009" }); + const roots = new Set([parent, subtask, otherWorkspace].map(scopedRunnerdStateRoot)); + expect(roots.size).toBe(3); + }); +}); + +describe("Antigravity state saved by the pending candidate, resumed by the qualified release", () => { + it("refuses the candidate's in-flight state permanently and by name, never as a retryable interruption", () => { + // Saved before the deploy under the candidate's profile version. + const saved = antigravityExecution(); + release.pending = false; + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, undefined); + let refusal: unknown; + try { + assertAntigravityExecutionAdmissible({ execution: saved, useRunnerd: true, remoteTarget: false, + restartRecovery: { kind: "same_run_resume" } }); + } catch (error) { refusal = error; } + expect(refusal).toBeInstanceOf(NativeProviderStateIncompatibleError); + const code = nativeSessionFailureSourceCode(refusal); + expect(code).toBe(NATIVE_PROVIDER_STATE_INCOMPATIBLE); + expect(nativeSessionFailureDisposition(1, new Date(), code)).toMatchObject({ + phase: "terminal_failure", failureCode: NATIVE_PROVIDER_STATE_INCOMPATIBLE, nextAttemptAt: null }); + }); + + it("refuses an older qualified profile version by the same name", () => { + release.pending = false; + const saved = antigravityExecution(); + (saved.provider as { profile: { agentProfileVersion: number } }).profile.agentProfileVersion -= 1; + expect(() => assertAntigravityExecutionAdmissible({ execution: saved, useRunnerd: true, remoteTarget: false })) + .toThrow(NativeProviderStateIncompatibleError); + }); +}); diff --git a/server/src/services/native-runtime/antigravity-release.ts b/server/src/services/native-runtime/antigravity-release.ts new file mode 100644 index 00000000000..a831e4b9fc1 --- /dev/null +++ b/server/src/services/native-runtime/antigravity-release.ts @@ -0,0 +1,100 @@ +import { + NativeProviderStateIncompatibleError, + QUALIFIED_ACPX_PROFILES, + type NativeExecutionInput, +} from "../../vendor/paperclip-runner/index.js"; +import { ANTIGRAVITY_REMOTE_TARGET, resolveAntigravityCandidateAdmission } from "./acpx-qualification.js"; + +/** The platform a pending candidate grant must name for this execution. */ +export function antigravityCandidateTarget(remote: boolean): { platform: string; architecture: string } { + return remote ? ANTIGRAVITY_REMOTE_TARGET : { platform: process.platform, architecture: process.arch }; +} + +/** + * Google Antigravity's server gates while its Runner profile is pending, and + * the general qualified ACPX path after the release flip. Every gate reads the + * release declaration at call time, the way Kimi's do, never the agent name + * alone, so the flip needs no change here. + */ +export function antigravityReleasePending(): boolean { + return QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus === "pending"; +} + +export function isAntigravityProvider( + provider: NativeExecutionInput["provider"] | undefined, +): provider is Extract { + return provider?.kind === "acpx" && provider.agent === "antigravity"; +} + +/** Only the pending candidate owns a fresh daemon and state root per run. A + * qualified release keeps the ordinary per-session scope (company, agent, + * workspace and task session), so subtasks still never share a root. */ +export function antigravityUsesRunScopedState(execution: NativeExecutionInput): boolean { + return isAntigravityProvider(execution.provider) && antigravityReleasePending(); +} + +/** The candidate keeps its saved conversation to the same session. A qualified + * release uses the ordinary recovery policy, including the automatic + * replacement conversation after a failed resume. */ +export function antigravityForcesSameSessionRecovery(provider: NativeExecutionInput["provider"] | undefined): boolean { + return isAntigravityProvider(provider) && antigravityReleasePending(); +} + +export const ANTIGRAVITY_EARLIER_RELEASE_STATE_REASON = + "Google Antigravity session state was saved by an earlier release"; + +// The persisted profile snapshot carries no qualification status. The flip +// bumps agentProfileVersion, so candidate-era state differs here by version. +const RELEASE_IDENTITY_FIELDS = [ + "agentProfileVersion", "commandDigest", "acpxVersion", "agentServerPackage", "agentServerVersion", + "agentRuntimePackage", "agentRuntimeVersion", +] as const; + +/** + * Saved Antigravity state binds the release profile it was created under. State + * from another release (the pending candidate's per-run root and grant under + * its profile version, or any older profile) is refused permanently and by + * name. The run keeps its saved session and workspace, and the next run starts + * a replacement conversation in the same workspace instead of repeating it. + */ +export function assertAntigravitySavedStateCurrent(execution: NativeExecutionInput): void { + if (!isAntigravityProvider(execution.provider)) return; + const saved = (execution.provider.profile ?? {}) as unknown as Record; + const current = QUALIFIED_ACPX_PROFILES.antigravity as unknown as Record; + if (RELEASE_IDENTITY_FIELDS.some(field => saved[field] !== current[field])) { + throw new NativeProviderStateIncompatibleError(ANTIGRAVITY_EARLIER_RELEASE_STATE_REASON); + } +} + +/** + * Executor admission. While pending, only an exact per-turn candidate grant + * bound to the execution target's platform may run: this host locally, or the + * cloud pack's linux-x64 closure remotely. After the flip no grant is needed and Antigravity takes the + * same path as Kimi and Copilot; only state saved by another release is refused. + */ +export function assertAntigravityExecutionAdmissible(input: { + execution: NativeExecutionInput; + useRunnerd?: boolean; + backend?: unknown; + restartRecovery?: unknown; + remoteTarget: boolean; + hostEnvironment?: NodeJS.ProcessEnv; +}): void { + const { execution } = input; + if (!isAntigravityProvider(execution.provider)) return; + if (!antigravityReleasePending()) { + assertAntigravitySavedStateCurrent(execution); + return; + } + let candidate: ReturnType; + try { + candidate = resolveAntigravityCandidateAdmission({ + companyId: execution.binding.companyId, model: execution.provider.model, target: antigravityCandidateTarget(input.remoteTarget), + }, input.hostEnvironment ?? process.env); + } catch { candidate = undefined; } + if (!candidate || !input.useRunnerd || input.backend || input.restartRecovery + || execution.session.lifecyclePolicy.mode !== "per_turn" + || ("homeMode" in execution && execution.homeMode === "preconfigured")) { + throw new Error("paperclip_runner_antigravity_candidate_ineligible: exact target-bound per-turn candidate admission is required"); + } +} diff --git a/server/src/services/native-runtime/antigravity-runner-credentials.test.ts b/server/src/services/native-runtime/antigravity-runner-credentials.test.ts index e5e11d9c580..366ff2ba184 100644 --- a/server/src/services/native-runtime/antigravity-runner-credentials.test.ts +++ b/server/src/services/native-runtime/antigravity-runner-credentials.test.ts @@ -7,6 +7,8 @@ import { antigravityCredentialTurn, bindAntigravityCredentialTurn, bindAntigravi import { completeManagedNativeCredentialTurn } from "./managed-native-credentials.js"; import type { NativeSession, createRunnerdCodexTransport } from "../../vendor/paperclip-runner/index.js"; import { bindRetainedGoogleCredentialHome } from "../retained-google-credential-cleanup.js"; +import { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } from "./antigravity-connection-policy.js"; +import { NATIVE_PROVIDER_STARTUP_REJECTED, nativeSessionFailureDisposition, nativeSessionFailureSourceCode } from "./native-session-executor.js"; const copyFault = vi.hoisted(() => ({ phase: "", destination: "", source: "", collisionPath: "", failedRemoval: "", removals: [] as string[], hits: 0 })); vi.mock("./runner-api-files.js", async importOriginal => { @@ -103,8 +105,40 @@ describe("Antigravity managed Runner credentials", () => { expect(await prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: { GEMINI_HOME: "/untrusted" } })).toEqual({ home: managedHome, credential: credential("fixture-selected"), environment: { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: credential("fixture-selected") }, }); - await expect(prepareAntigravityRunnerCredentials({ remote: true, managedHome, environment: {} })).rejects.toThrow("not qualified for remote"); - await expect(prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: {}, lifecycleMode: "warm" })).rejects.toThrow("warm sessions are not qualified"); + for (const [input, code] of [[{ remote: true, environment: {} }, "antigravity_remote_sign_in_unsupported"], + [{ remote: false, lifecycleMode: "warm" as const, environment: {} }, "antigravity_warm_unsupported"], + [{ remote: false, lifecycleMode: "warm" as const, environment: { GEMINI_API_KEY: "fixture-selected" } }, "antigravity_warm_unsupported"]] as const) { + const refusal = await prepareAntigravityRunnerCredentials({ managedHome, ...input }).catch(error => error); + // Configuration save and Test refuse this first; a run that still + // reaches it stops permanently by name instead of offering a Retry. + expect(refusal).toBeInstanceOf(AntigravityConnectionConfigurationError); + expect(refusal).toMatchObject({ code }); + expect(refusal.message).toMatch(code === "antigravity_warm_unsupported" ? /^Google Antigravity runs one turn at a time\. Turn off warm sessions for this agent\.$/ : /Google API key/); + const failure = nativeSessionFailureSourceCode(refusal); + expect(failure).toBe(NATIVE_PROVIDER_STARTUP_REJECTED); + expect(nativeSessionFailureDisposition(1, new Date(), failure)).toMatchObject({ phase: "terminal_failure", failureCode: NATIVE_PROVIDER_STARTUP_REJECTED }); + } + }); + it("names the connection choices each target supports in both release states", () => { + expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: false })).toBeNull(); + // Per-turn is one contract for both routes: an API key does not enable warm. + for (const apiKey of [true, false]) { + expect(antigravityConnectionRefusal({ apiKey, remote: false, lifecycleMode: "warm", releasePending: false })?.code).toBe("antigravity_warm_unsupported"); + expect(antigravityConnectionRefusal({ apiKey, remote: false, lifecycleMode: "per_turn", releasePending: false })).toBeNull(); + } + expect(antigravityConnectionRefusal({ apiKey: false, remote: false, releasePending: false })).toBeNull(); + expect(antigravityConnectionRefusal({ apiKey: false, remote: true, releasePending: false })?.message) + .toBe("Google sign-in for Google Antigravity works only on the Paperclip host. To run this agent in a cloud environment, connect a Google API key instead."); + expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true })?.code).toBe("antigravity_remote_unavailable"); + expect(antigravityConnectionRefusal({ apiKey: false, remote: false, releasePending: true })).toBeNull(); + // While pending, an operator's cloud grant admits an API key in a cloud environment, never Google sign-in. + expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true, remoteCandidateAdmitted: true })).toBeNull(); + expect(antigravityConnectionRefusal({ apiKey: false, remote: true, releasePending: true, remoteCandidateAdmitted: true })?.code) + .toBe("antigravity_remote_sign_in_unsupported"); + expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true, remoteCandidateAdmitted: false })?.code) + .toBe("antigravity_remote_unavailable"); + expect(antigravityConnectionRefusal({ apiKey: true, remote: true, lifecycleMode: "warm", releasePending: true, remoteCandidateAdmitted: true })?.code) + .toBe("antigravity_warm_unsupported"); }); it.each(["symlink", "public", "invalid"])("rejects a %s selected token without using a fallback", async kind => { const managedHome = await home(), token = join(managedHome, "antigravity-acp", "acp_token.json"); diff --git a/server/src/services/native-runtime/antigravity-runner-credentials.ts b/server/src/services/native-runtime/antigravity-runner-credentials.ts index 6e117cbc71a..6580b0ad991 100644 --- a/server/src/services/native-runtime/antigravity-runner-credentials.ts +++ b/server/src/services/native-runtime/antigravity-runner-credentials.ts @@ -11,6 +11,7 @@ import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-lo import { openRunnerWorkspaceFile } from "./runner-api-files.js"; import type { NativeSession, createRunnerdCodexTransport } from "../../vendor/paperclip-runner/index.js"; import { bindManagedNativeCredentialTurn } from "./managed-native-credentials.js"; +import { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } from "./antigravity-connection-policy.js"; const AUTH_SECRET = "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"; const TOKEN_FILE = "acp_token.json"; @@ -43,10 +44,12 @@ export async function prepareAntigravityRunnerCredentials(input: { }): Promise<{ environment: NodeJS.ProcessEnv; home: string | null; credential?: string }> { const environment = { ...input.environment }; for (const key of [AUTH_SECRET, "GEMINI_HOME", "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_ACCESS_TOKEN"]) delete environment[key]; - if (environment.GEMINI_API_KEY?.trim()) return { environment, home: null }; + const apiKey = Boolean(environment.GEMINI_API_KEY?.trim()); + // Save and Test refuse these choices first; this is the run-time defense. + const refusal = antigravityConnectionRefusal({ apiKey, remote: input.remote, lifecycleMode: input.lifecycleMode, releasePending: false }); + if (refusal) throw new AntigravityConnectionConfigurationError(refusal); + if (apiKey) return { environment, home: null }; delete environment.GEMINI_API_KEY; - if (input.remote) throw new Error("Google Antigravity subscription authentication is not qualified for remote environments. Select a Google API key or use the Paperclip host."); - if (input.lifecycleMode === "warm") throw new Error("Google Antigravity subscription authentication requires turn-by-turn sessions; warm sessions are not qualified."); const home = input.managedHome?.trim(); if (!home) throw new Error("Google Antigravity requires a selected managed Google account or Google API key."); await reconcileRetainedGoogleCleanupForHome(home); diff --git a/server/src/services/native-runtime/native-provider-failure.test.ts b/server/src/services/native-runtime/native-provider-failure.test.ts index a777eef55d7..002ec6363be 100644 --- a/server/src/services/native-runtime/native-provider-failure.test.ts +++ b/server/src/services/native-runtime/native-provider-failure.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import type { PrpEvent, PrpTerminalState } from "../../vendor/paperclip-runner/index.js"; -import { createNativeProviderFailureObservation, NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC, NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_OVERLOADED_MESSAGE, readNativeTurnFailureDiagnostic } from "./native-provider-failure.js"; +import { antigravityModelRefusalMessage } from "@paperclipai/shared"; +import { createNativeProviderFailureObservation, nativeProviderUsageLimitFromEvent, NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC, NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_OVERLOADED_MESSAGE, readNativeTurnFailureDiagnostic } from "./native-provider-failure.js"; const model = "test-model"; const response = { @@ -290,3 +291,66 @@ describe("native provider failure observation", () => { }, ); }); + +describe("Google Antigravity provider failures", () => { + const antigravity = (route?: "api_key" | "subscription", modelId = "gemini-4-neon-high") => + createNativeProviderFailureObservation({ kind: "acpx", agent: "antigravity", model: modelId }, route ? { antigravityRoute: route } : {}); + const failed = (providerFailure: Record): PrpEvent => ({ ...event, payload: { status: "failed", error: { providerFailure: { + schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "turn", ...providerFailure } } } }); + const refused = failed({ category: "model_unavailable", message: "The selected model is not available for this connection.", + providerCode: "antigravity_model_unavailable", httpStatus: 429, retryability: "requires_action" }); + + it("names the refused model and the fix for an API key", () => { + const observed = antigravity("api_key"); + observed.observe(refused); + const result = observed.forTerminal("turn", terminal); + expect(result).toMatchObject({ errorCode: "native_provider_model_rejected", + errorMessage: antigravityModelRefusalMessage("gemini-4-neon-high", "api_key") }); + expect(result?.errorMessage).toContain("Gemini 4 Neon (High) is not available with this Gemini API key."); + expect(result?.errorMessage).not.toMatch(/antigravity_model_unavailable|RESOURCE_EXHAUSTED|429/); + expect(observed.unclassifiedTurnFailure("turn", terminal)).toBeNull(); + }); + + it("names the refused model and the fix for a Google sign-in", () => { + const observed = antigravity("subscription", "gemini-3.8-flash-high"); + observed.observe(refused); + expect(observed.forTerminal("turn", terminal)?.errorMessage) + .toBe(antigravityModelRefusalMessage("gemini-3.8-flash-high", "subscription")); + }); + + it("keeps the shared message when the connection route is unknown (recovered after restart)", () => { + const observed = antigravity(); + observed.observe(refused); + expect(observed.forTerminal("turn", terminal)).toMatchObject({ errorCode: "native_provider_model_rejected", errorMessage: NATIVE_MODEL_REJECTION_MESSAGE }); + }); + + it("takes the bounded capacity retry for a transient overload (503)", () => { + const observed = antigravity("api_key"); + observed.observe(failed({ category: "overloaded", message: "This model is currently experiencing high demand.", + providerCode: "UNAVAILABLE", httpStatus: 503, retryability: "transient" })); + expect(observed.forTerminal("turn", terminal)).toEqual({ errorCode: "native_provider_overloaded", + errorMessage: NATIVE_PROVIDER_OVERLOADED_MESSAGE, diagnostic: { provider: "antigravity", category: "server_overloaded" } }); + expect(observed.unclassifiedTurnFailure("turn", terminal)).toBeNull(); + }); + + it("leaves rate limits, quotas and rejected keys to their own plain-language paths", () => { + for (const failure of [ + { category: "rate_limit", message: "Slow down", httpStatus: 429, retryAt: "2026-01-01T00:01:00.000Z", retryability: "transient" }, + { category: "quota_exhausted", message: "Quota exhausted", httpStatus: 429, retryability: "requires_action" }, + { category: "authentication", message: "API key not valid. Please pass a valid API key.", httpStatus: 400, retryability: "requires_action" }, + ]) { + const observed = antigravity("api_key"); + const input = failed(failure); + observed.observe(input); + expect(observed.forTerminal("turn", terminal)).toBeNull(); + expect(observed.providerFailureForTerminal("turn", terminal)).toMatchObject({ category: failure.category, message: failure.message }); + expect(nativeProviderUsageLimitFromEvent(input)).toBe(failure.category !== "authentication"); + } + }); + + it("does not turn another ACPX harness's overload into an Antigravity capacity retry", () => { + const observed = createNativeProviderFailureObservation({ kind: "acpx", agent: "claude", model: "m" }); + observed.observe(failed({ provider: "claude", category: "overloaded", message: "Overloaded", httpStatus: 529, retryability: "transient" })); + expect(observed.forTerminal("turn", terminal)).toBeNull(); + }); +}); diff --git a/server/src/services/native-runtime/native-provider-failure.ts b/server/src/services/native-runtime/native-provider-failure.ts index 03680535dd1..b38f2acf472 100644 --- a/server/src/services/native-runtime/native-provider-failure.ts +++ b/server/src/services/native-runtime/native-provider-failure.ts @@ -1,5 +1,8 @@ import type { PrpEvent, PrpTerminalState } from "../../vendor/paperclip-runner/index.js"; -import { readProviderFailure, type ProviderFailure } from "@paperclipai/shared"; +import { antigravityModelRefusalMessage, readProviderFailure, type AntigravityAuthRoute, type ProviderFailure } from "@paperclipai/shared"; + +/** The runner driver's provider code for a model Google refused for the connection. */ +const ANTIGRAVITY_MODEL_UNAVAILABLE_CODE = "antigravity_model_unavailable"; // Shared by every provider whose selected model is rejected, so it names no specific connection. export const NATIVE_MODEL_REJECTION_MESSAGE = @@ -234,7 +237,14 @@ export function readNativeTurnFailureDiagnostic(value: unknown): NativeTurnFailu } /** Observe only events accepted by the bound control-plane persistence port. */ -export function createNativeProviderFailureObservation(provider: { kind: string; model?: string | null }) { +export function createNativeProviderFailureObservation( + provider: { kind: string; model?: string | null; agent?: string }, + options: { + /** Google Antigravity's connection route, known only where the run's credentials were resolved. */ + antigravityRoute?: AntigravityAuthRoute; + } = {}, +) { + const antigravity = provider.kind === "acpx" && provider.agent === "antigravity"; let rejectedTurnId: string | null = null; /** A Codex API-key turn whose configured model the Responses API does not serve (404). */ let missingModelTurnId: string | null = null; @@ -252,6 +262,11 @@ export function createNativeProviderFailureObservation(provider: { kind: string; && event.payload.status === "failed") { const failure = readProviderFailure(record(event.payload.error).providerFailure); if (failure && !providerFailures.has(event.turnId)) providerFailures.set(event.turnId, failure); + // Antigravity's owned patch types Google's 503 as a transient overload: + // it takes the same bounded capacity retry as Codex's serverOverloaded. + if (antigravity && failure?.category === "overloaded" && failure.retryability === "transient") { + overloadedTurnId = event.turnId; + } } if ((provider.kind !== "codex" && provider.kind !== "opencode") || event.sourceKind !== "runner" || event.eventType !== "turn.failed" || !event.turnId) return; @@ -305,11 +320,11 @@ export function createNativeProviderFailureObservation(provider: { kind: string; if (turnId === overloadedTurnId) return { errorCode: NATIVE_PROVIDER_OVERLOADED_CODE, errorMessage: NATIVE_PROVIDER_OVERLOADED_MESSAGE, - diagnostic: { ...NATIVE_PROVIDER_OVERLOADED_DIAGNOSTIC }, + diagnostic: antigravity ? { provider: "antigravity", category: "server_overloaded" } : { ...NATIVE_PROVIDER_OVERLOADED_DIAGNOSTIC }, }; // Every model rejection shares one result; only its closed diagnostic differs. - const modelRejection = (diagnostic: T) => ({ - errorCode: "native_provider_model_rejected" as const, errorMessage: NATIVE_MODEL_REJECTION_MESSAGE, diagnostic, + const modelRejection = (diagnostic: T, errorMessage: string = NATIVE_MODEL_REJECTION_MESSAGE) => ({ + errorCode: "native_provider_model_rejected" as const, errorMessage, diagnostic, }); if (turnId === missingModelTurnId) return modelRejection({ ...NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC }); if (turnId === rejectedTurnId) return modelRejection({ ...NATIVE_MODEL_REJECTION_DIAGNOSTIC }); @@ -317,7 +332,12 @@ export function createNativeProviderFailureObservation(provider: { kind: string; // action-required rejection qualifies; a transient one may succeed on retry. if (!modelUnavailableTurn(turnId)) return null; const failure = providerFailures.get(turnId)!; - return modelRejection(failedTurns.get(turnId) ?? { provider: failure.provider, category: failure.category }); + // Antigravity's typed refusal names the configured model and the fix for + // its connection route. Without the route (a run recovered after a + // restart), the shared message stays accurate. + const message = antigravity && failure.providerCode === ANTIGRAVITY_MODEL_UNAVAILABLE_CODE && provider.model && options.antigravityRoute + ? antigravityModelRefusalMessage(provider.model, options.antigravityRoute) : undefined; + return modelRejection(failedTurns.get(turnId) ?? { provider: failure.provider, category: failure.category }, message); }, /** Diagnostics only: the failed turn that `forTerminal` did not classify. */ unclassifiedTurnFailure(turnId: string | null | undefined, terminal: PrpTerminalState) { 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 cc18a0d071c..2bac73feed7 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -149,6 +149,8 @@ vi.mock("node:fs", async (importOriginal) => { return { ...actual, readFileSync: vi.fn(actual.readFileSync) }; }); +const distributions = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8")); + const usageRecorder = vi.hoisted(() => ({ create: vi.fn(), capture: vi.fn<(receipt: AdapterUsageCheckpoint) => Promise>(), @@ -249,6 +251,14 @@ const durableRunnerState = ( lifecycle, }); +const antigravityPack = vi.hoisted(() => ({ released: false, linuxClosure: "b".repeat(64) })); +vi.mock("./remote-provider-pack.js", async importOriginal => { + const original = await importOriginal(); + // The Linux patched closure is pinned by the image agent; this fixture stands in for it. + return { ...original, ANTIGRAVITY_PATCHED_CLOSURE_SHA256: new Proxy({}, { + get: (_target, key) => key === "linux-x64" ? antigravityPack.linuxClosure : original.ANTIGRAVITY_PATCHED_CLOSURE_SHA256[key as string], + }) }; +}); const state = vi.hoisted(() => ({ localRuntimeApiUrl: vi.fn(() => "http://127.0.0.1:43219"), createAssignedMcpTools: vi.fn(), @@ -332,8 +342,14 @@ vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => { const original = await importOriginal< typeof import("../../vendor/paperclip-runner/index.js") >(); + // Antigravity's release state is stubbed per test (pending today, qualified after the flip). + const { qualificationStatus: _antigravityPending, ...antigravityReleased } = original.QUALIFIED_ACPX_PROFILES.antigravity; + const profiles = { ...original.QUALIFIED_ACPX_PROFILES }; + Object.defineProperty(profiles, "antigravity", { enumerable: true, + get: () => antigravityPack.released ? antigravityReleased : original.QUALIFIED_ACPX_PROFILES.antigravity }); return { ...original, + QUALIFIED_ACPX_PROFILES: profiles, bundledRemoteProviderPackManifestPath: vi.fn((moduleUrl?: string, target?: "linux-x64" | "linux-arm64") => state.bundledPackManifestPath ?? original.bundledRemoteProviderPackManifestPath(moduleUrl, target)), bundledRemoteRunnerBinary: () => state.bundledRunnerBinary ?? original.bundledRemoteRunnerBinary(), createNativeSessionBackend: state.createBackend, @@ -3711,6 +3727,62 @@ describe("remote provider pack manifest", () => { await writeFile(join(root, kimiPath, "runtime"), "substitute Kimi runtime"); expect(() => readRemoteProviderPackManifest(root)).toThrow("candidate asset tree digest mismatch"); await writeFile(join(root, kimiPath, "runtime"), "pinned Kimi runtime"); + // Google Antigravity image pack contract: the patched Linux closure under + // 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"); + const antigravity = { version: QUALIFIED_ACPX_PROFILES.antigravity.agentServerVersion, + profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, + closureDigest: `sha256:${antigravityPack.linuxClosure}`, qualification: "pending", path: antigravityPath, + sha256: sha256DirectoryTree(join(root, antigravityPath)) }; + try { + const inventories = payload as unknown as Record<"providers" | "candidateProviders", Record>; + for (const released of [false, true]) { + antigravityPack.released = released; + antigravity.qualification = released ? "qualified" : "pending"; + const [admitted, refused] = released ? ["providers", "candidateProviders"] as const : ["candidateProviders", "providers"] as const; + Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} }); + Object.assign(inventories[admitted], { antigravity }); + await writeKimiManifest(); + expect(readRemoteProviderPackManifest(root).payload[admitted]?.antigravity).toEqual(antigravity); + expect(readBundledRemoteProviderPackManifest(manifestPath).payload[admitted]?.antigravity?.qualification) + .toBe(released ? "qualified" : "pending"); + Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} }); + Object.assign(inventories[refused], { antigravity: { ...antigravity, qualification: "pending" } }); + await writeKimiManifest(); + expect(() => readRemoteProviderPackManifest(root)).toThrow("runner_remote_provider_artifact_incompatible: Antigravity is listed under the wrong pack inventory"); + 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}`, + `sha256:${distributions.platforms["darwin-arm64"].closureSha256}`, digest("other-closure")]) { + Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} }); + Object.assign(inventories[admitted], { antigravity: { ...antigravity, closureDigest } }); + await writeKimiManifest(); + expect(() => readRemoteProviderPackManifest(root)).toThrow("runner_remote_provider_artifact_incompatible: Antigravity closure is not this release's patched closure"); + } + Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} }); + Object.assign(inventories[admitted], { antigravity: { ...antigravity, version: "0.0.1" } }); + await writeKimiManifest(); + expect(() => readRemoteProviderPackManifest(root)).toThrow("runner_remote_provider_artifact_incompatible: Antigravity profile does not match this release"); + 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"); + 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"); + } + // Until the Linux runtime is pinned, no Antigravity image pack verifies. + antigravityPack.linuxClosure = ""; + await writeKimiManifest(); + expect(() => readRemoteProviderPackManifest(root)).toThrow("Antigravity closure is not this release's patched closure"); + } finally { + antigravityPack.released = false; antigravityPack.linuxClosure = "b".repeat(64); + Object.assign(payload, { providers: { cursor, kimi } }); + Reflect.deleteProperty(payload, "candidateProviders"); + await writeKimiManifest(); + } const threeCandidates = { cursor, pi: { ...kimi, version: "1.0.0", qualification: "qualified", path: "provider-assets/pi/linux-x64" }, copilot: { ...kimi, qualification: "pending", version: QUALIFIED_ACPX_PROFILES.copilot.agentServerVersion, @@ -3725,7 +3797,7 @@ describe("remote provider pack manifest", () => { Object.assign(payload, { candidateProviders: threeCandidates }); await writeKimiManifest(); expect(Object.keys(readRemoteProviderPackManifest(root).payload.candidateProviders!)).toHaveLength(3); - Object.assign(payload, { candidateProviders: { ...threeCandidates, unknown: kimi } }); + Object.assign(payload, { candidateProviders: { ...threeCandidates, unknown: kimi, other: kimi } }); await writeKimiManifest(); expect(() => readBundledRemoteProviderPackManifest(manifestPath)).toThrow("invalid candidate inventory"); Object.assign(payload, { candidateProviders: { unknown: kimi } }); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 6189cee896a..93a313418b8 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -112,6 +112,8 @@ import { activeIssueInteractionCondition } from "../issue-question-context.js"; import { resolveAcpxQualification, resolveAntigravityCandidateAdmission, resolveKimiCandidateAdmission } from "./acpx-qualification.js"; import { readLocalAiCredentialFile } from "../local-ai-credential-file.js"; import { prepareGrokRunnerCredentials } from "./grok-runner-credentials.js"; +import { AntigravityConnectionConfigurationError } from "./antigravity-connection-policy.js"; +import { antigravityCandidateTarget, antigravityForcesSameSessionRecovery, antigravityReleasePending, antigravityUsesRunScopedState, assertAntigravityExecutionAdmissible } from "./antigravity-release.js"; import { bindAntigravityCredentialTurn, bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js"; import { copyBackGrokAuth } from "@paperclipai/adapter-grok-local/server"; @@ -141,7 +143,7 @@ import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server"; import { nativeCompletionFeedback } from "./native-completion-feedback.js"; import { hasAcknowledgedNativeLifecycleStopIntent, hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js"; import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js"; -import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; +import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256, prepareVerifiedRemoteProviderPack, remoteProviderPackEntryRefusal, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; import { uploadVerifiedProviderPack } from "./provider-pack-upload.js"; import { selectRemotePiCompanion } from "./remote-pi-companion.js"; import { scheduledResumeContinuationAllowed } from "./scheduled-resume-continuation.js"; @@ -2735,9 +2737,10 @@ export async function noLocalRunnerProcessForRun(runId: string): Promise { attemptDiagnosticLeases.push(lease); ownRunDiagnosticLease?.(lease); }; - if (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "antigravity") { - const candidate = resolveAntigravityCandidateAdmission({ - companyId: input.execution.binding.companyId, model: input.execution.provider.model, - }, process.env); - if (!candidate || !input.useRunnerd || input.backend || input.restartRecovery - || input.runnerExecutionTarget?.kind === "remote" - || input.execution.session.lifecyclePolicy.mode !== "per_turn" - || ("homeMode" in input.execution && input.execution.homeMode === "preconfigured")) { - throw new Error("paperclip_runner_antigravity_candidate_ineligible: exact local per-turn candidate admission is required"); - } - } + assertAntigravityExecutionAdmissible({ + execution: input.execution, useRunnerd: input.useRunnerd, backend: input.backend, + restartRecovery: input.restartRecovery, remoteTarget: input.runnerExecutionTarget?.kind === "remote", + }); if (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "kimi" && QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending") { const target = input.runnerExecutionTarget?.kind === "remote" @@ -11729,7 +11728,11 @@ async function executePaperclipNativeSessionAttempt( let firstTokenRecorded = false; const observeDeliverableText = createNativeDeliverableTextObservation(); let providerUsageLimitObserved = false; - const providerFailureObservation = createNativeProviderFailureObservation(input.execution.provider); + // Antigravity runs on a Gemini API key exactly when one is bound; otherwise + // on a Google sign-in (the same rule its credential preparation applies). + const providerFailureObservation = createNativeProviderFailureObservation(input.execution.provider, + input.execution.provider.kind === "acpx" && input.execution.provider.agent === "antigravity" + ? { antigravityRoute: input.runnerEnvironment?.GEMINI_API_KEY?.trim() ? "api_key" : "subscription" } : {}); let turnCompletedAtMs: number | null = null; let runnerSessionStartupScope: NativeRunSpanScope | null = null; let agentTurnScope: NativeRunSpanScope | null = null; @@ -14403,8 +14406,10 @@ const REMOTE_PROVIDER_PACK_ARTIFACT_PATHS = { opencodeProxy: "dist/cli/opencode-app-server-proxy.cjs", acpxSidecar: "dist/cli/acpx-runtime-sidecar.cjs", } as const; -const REMOTE_PROVIDER_PACK_PROVIDERS = ["pi", "cursor", "copilot", ...(QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus !== "pending" ? ["kimi"] as const : [])] as const; -const REMOTE_PROVIDER_PACK_CANDIDATES = ["pi", "cursor", "copilot", ...(QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending" ? ["kimi"] as const : [])] as const; +// Antigravity may appear in either inventory; its release state, read at +// verification time, admits exactly one (antigravityProviderPackEntryRefusal). +const REMOTE_PROVIDER_PACK_PROVIDERS = ["pi", "cursor", "copilot", ...(QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus !== "pending" ? ["kimi"] as const : []), "antigravity"] as const; +const REMOTE_PROVIDER_PACK_CANDIDATES = ["pi", "cursor", "copilot", ...(QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending" ? ["kimi"] as const : []), "antigravity"] as const; type RemoteProviderPackManifest = { schema: typeof REMOTE_PROVIDER_PACK_SCHEMA; @@ -14644,52 +14649,15 @@ function* providerPackIdentityChecks( throw new Error("runner_remote_provider_artifact_incompatible: invalid candidate inventory"); } for (const [provider, candidate] of Object.entries(candidates)) { - const expectedPath = `provider-assets/${provider}/${payload.target.platform}-${payload.target.architecture}`; - if (!allowedProviders.includes(provider) || !candidate - || Object.keys(candidate).some(key => !["version", "profileDigest", "closureDigest", "qualification", "path", "sha256"].includes(key)) - || candidate.qualification !== (["pi", "cursor"].includes(provider) || inventory === "providers" && (provider === "copilot" || provider === "kimi" && QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus !== "pending") ? "qualified" : "pending") || candidate.path !== expectedPath - || typeof candidate.version !== "string" || !candidate.version || candidate.version.length > 120 - || !/^sha256:[a-f0-9]{64}$/.test(candidate.profileDigest) - || !/^sha256:[a-f0-9]{64}$/.test(candidate.closureDigest) - || !/^sha256:[a-f0-9]{64}$/.test(candidate.sha256)) { - throw new Error("runner_remote_provider_artifact_incompatible: invalid candidate identity"); - } + const refusal = remoteProviderPackEntryRefusal({ provider, inventory, allowedProviders, target: payload.target, entry: candidate, + listed: { providers: Boolean((payload.providers as Record | undefined)?.[provider]), + candidateProviders: Boolean((payload.candidateProviders as Record | undefined)?.[provider]) }, + release: { + profiles: QUALIFIED_ACPX_PROFILES, cursorClosures: CURSOR_DISTRIBUTION_PINS, kimiLinuxX64Closure: KIMI_DISTRIBUTION_CLOSURE_SHA256["linux-x64"], + antigravityReleasePending: antigravityReleasePending(), antigravityPatchedClosures: ANTIGRAVITY_PATCHED_CLOSURE_SHA256, + } }); + if (refusal) throw new Error(`runner_remote_provider_artifact_incompatible: ${refusal}`); const candidatePath = providerPackRelativePath(candidate.path, "candidate assets"); - if (provider === "cursor") { - const target = `${payload.target.platform}-${payload.target.architecture}`; - const distribution = Object.hasOwn(CURSOR_DISTRIBUTION_PINS, target) - ? CURSOR_DISTRIBUTION_PINS[target as keyof typeof CURSOR_DISTRIBUTION_PINS] : undefined; - if (!distribution || candidate.version !== QUALIFIED_ACPX_PROFILES.cursor.agentServerVersion - || candidate.profileDigest !== QUALIFIED_ACPX_PROFILES.cursor.commandDigest - || candidate.closureDigest !== `sha256:${distribution.closureSha256}`) { - throw new Error("runner_remote_provider_artifact_incompatible: Cursor profile or closure does not match this release"); - } - } - if (provider === "copilot") { - const closurePins = { - "darwin-arm64": "362f2663e967fb9e34a814bac4619cbf89e6b23069c4051ab1f2f686852d0a32", - "darwin-x64": "c08b7c3dd4e7bcf9a3e16ec6eba29cfa10308e865d196c5f120a3a15f6b3116a", - "linux-x64": "a3d8f4367cfa1694d79e3f8b7930b6fbfe42a229c272b375b11951d631db8d07" -} as const; - const target = `${payload.target.platform}-${payload.target.architecture}`; - const closure = Object.hasOwn(closurePins, target) ? closurePins[target as keyof typeof closurePins] : undefined; - if (!closure || (payload.providers?.copilot && payload.candidateProviders?.copilot) - || candidate.version !== QUALIFIED_ACPX_PROFILES.copilot.agentServerVersion - || candidate.profileDigest !== QUALIFIED_ACPX_PROFILES.copilot.commandDigest - || candidate.closureDigest !== `sha256:${closure}`) { - throw new Error("runner_remote_provider_artifact_incompatible: Copilot profile or closure does not match this release"); - } - } - if (provider === "kimi") { - if (inventory !== (QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending" ? "candidateProviders" : "providers") - || payload[QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending" ? "providers" : "candidateProviders"]?.kimi - || payload.target.platform !== "linux" || payload.target.architecture !== "x64" - || candidate.version !== QUALIFIED_ACPX_PROFILES.kimi.agentServerVersion - || candidate.profileDigest !== QUALIFIED_ACPX_PROFILES.kimi.commandDigest - || candidate.closureDigest !== `sha256:${KIMI_DISTRIBUTION_CLOSURE_SHA256["linux-x64"]}`) { - throw new Error("runner_remote_provider_artifact_incompatible: Kimi profile or closure does not match this release"); - } - } if (verifyControllerFiles && (yield { kind: "tree", path: resolve(packRoot, candidatePath) }) !== candidate.sha256) { throw new Error("runner_remote_provider_artifact_incompatible: candidate asset tree digest mismatch"); } @@ -14918,6 +14886,14 @@ export async function stageRemoteRunnerDirectory(input: { } } +/** The exact remote machine a pack sits on, when the target names one. */ +export function remoteProviderPackSeal(target: Extract): { targetKey: string } | null { + const sandboxLease = "sandboxLeaseAcquisition" in target ? target.sandboxLeaseAcquisition?.providerLeaseId : undefined; + const lease = sandboxLease ?? target.leaseId; + if (!lease || !target.environmentId) return null; + return { targetKey: `${target.transport}:${target.environmentId}:${lease}` }; +} + /** The normal remote pack installer, without run/session/DB authority. Both * native execution and environment Test use the same admitted manifest and * complete archive/directory verification before a provider is invoked. */ @@ -14938,9 +14914,11 @@ export async function prepareRemoteProviderPackOnTarget(input: { let activeRemoteProviderPackRoot: string | null = null; let preinstalledProviderPackRoots: string[] = []; let selectedProviderPackManifest = expectedProviderPackManifest; + const seal = remoteProviderPackSeal(remoteTarget); const verifyRemoteProviderPack = (packRoot: string, acceptProvenance = false) => verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, cwd: remoteTarget.remoteCwd, packRoot, - manifest: expectedProviderPackManifest, acceptProvenance: acceptProvenance && input.acceptProvenanceDifferences === true }); + manifest: expectedProviderPackManifest, acceptProvenance: acceptProvenance && input.acceptProvenanceDifferences === true, + ...(seal ? { seal } : {}) }); const discoverPreinstalledProviderPack = async () => { if (!remoteTarget || !remoteCommandRunner) return []; const result = await remoteCommandRunner.execute({ @@ -17415,8 +17393,9 @@ async function createRunnerdBackendWithinSessionClaim( if (providerPackVerified && packRoot === activeRemoteProviderPackRoot) return; if (!remoteTarget || !remoteCommandRunner || !expectedProviderPackManifest) return; + const seal = remoteProviderPackSeal(remoteTarget); await verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, - cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest }); + cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest, ...(seal ? { seal } : {}) }); providerPackVerified = true; }; @@ -18862,7 +18841,9 @@ async function createRunnerdBackendWithinSessionClaim( ? undefined : resolveAcpxQualification(input.execution.provider, process.env), acpxCandidateAdmission: input.execution.provider.agent === "antigravity" - ? resolveAntigravityCandidateAdmission({ companyId: input.execution.binding.companyId, model: input.execution.provider.model }, process.env) + // A released profile carries no candidate grant. + ? antigravityReleasePending() ? resolveAntigravityCandidateAdmission({ companyId: input.execution.binding.companyId, model: input.execution.provider.model, + target: antigravityCandidateTarget(Boolean(remoteTarget)) }, process.env) : undefined : input.execution.provider.agent === "kimi" && QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending" ? resolveKimiCandidateAdmission({ companyId: input.execution.binding.companyId, model: input.execution.provider.model, target: remoteTarget ? { platform: "linux", architecture: "x64" } : { platform: process.platform, architecture: process.arch } }, process.env) @@ -19013,7 +18994,7 @@ async function createRunnerdBackendWithinSessionClaim( recoveryContext?.persistedSession?.activeTurnId ?? null, resumeProviderSession: recoveryContext?.persistedSession, providerRecoveryPolicy: - input.execution.provider.kind === "acpx" && input.execution.provider.agent === "antigravity" + antigravityForcesSameSessionRecovery(input.execution.provider) ? "same_session_only" : recoveryContext?.providerRecoveryPolicy ?? (input.execution.provider.kind === "acpx" && diff --git a/server/src/services/native-runtime/native-session-resume.test.ts b/server/src/services/native-runtime/native-session-resume.test.ts index 1d26ebad290..aeeddaaa185 100644 --- a/server/src/services/native-runtime/native-session-resume.test.ts +++ b/server/src/services/native-runtime/native-session-resume.test.ts @@ -368,6 +368,44 @@ describe("a session saved by the previous Claude or Codex ACPX runtime", () => { }); }); +describe("a Google Antigravity session saved by the pending candidate", () => { + // The candidate's saved provider binds its pending profile. After the flip, + // the next run carries the task into a fresh provider session in the same + // workspace (the automatic replacement), never a Retry of the old session. + const antigravityExecution = (runId: string) => buildNativeExecutionInput({ + companyId, runId, + issue: { id: issueId, identifier: "DOT-2", title: "Test", description: null, workMode: "standard" }, + taskPrompt: "Only the current turn", agentId, + workspace: { id: runId, cwd: "/workspace", repoUrl: null, repoRef: null, branchName: null }, + normalizedSessionId, provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low", + acpxPermissionMode: "approve-all", completionContract: execution(runId).completionContract, + runtimeContext: nativeRuntimeContextFixture(), + }); + + it("starts the next run on the qualified release in a fresh provider session in the same workspace", () => { + const saved = antigravityExecution(previousRunId); + const source = { ...previousRun(), runnerProfileJson: { ...previousRun().runnerProfileJson, nativeExecutionInput: saved } }; + // The flip bumps the profile version (the snapshot carries no qualification status). + const released = (runId: string) => { + const built = antigravityExecution(runId); + (built.provider as { profile: { agentProfileVersion: number } }).profile.agentProfileVersion += 1; + return built; + }; + expect(rebindNativeSessionCheckpoint({ previousRun: source, currentExecution: antigravityExecution(currentRunId) })).not.toBeNull(); + expect(rebindNativeSessionCheckpoint({ previousRun: source, currentExecution: released(currentRunId) })).toBeNull(); + const result = buildNativeExecutionWithCheckpoint({ previousRun: source, normalizedSessionId, + buildExecution: ({ normalizedSessionId: sessionId, resumedSession }) => { + const built = released(currentRunId); + built.session.normalizedSessionId = sessionId; + built.task.prompt = resumedSession ? "wake delta" : "original goal and complete handoff"; + return built; + } }); + expect(result.checkpoint).toBeNull(); + expect(result.execution.task.prompt).toContain("complete handoff"); + expect(result.execution.workspace).toEqual(released(currentRunId).workspace); + }); +}); + describe("a source whose provider state was not saved after its result was accepted", () => { const unsaved = { [NATIVE_PROVIDER_STATE_UNSAVED_KEY]: { code: NATIVE_PROVIDER_STATE_INCOMPATIBLE, reason: "harness_backup_not_saved", recordedAt: "2026-11-11T00:00:00.000Z" } }; diff --git a/server/src/services/native-runtime/native-warm-capability.ts b/server/src/services/native-runtime/native-warm-capability.ts index 9c1408976af..5a884eeb52b 100644 --- a/server/src/services/native-runtime/native-warm-capability.ts +++ b/server/src/services/native-runtime/native-warm-capability.ts @@ -22,6 +22,13 @@ export function supportsNativeWarmFiles(profile: WarmProviderSelection): boolean (profile.backend === "acpx_runtime" && profile.acpxAgent === "copilot"); } +/** Google Antigravity runs turn by turn with any credential, as Kimi does with a + * managed key. A warm owner needs its own proof that a credential change retires + * it and refreshes its native home on attach, so no choice selects warm yet. */ +export function requiresPerTurnNativeSession(profile: WarmProviderSelection): boolean { + return profile.backend === "acpx_runtime" && profile.acpxAgent === "antigravity"; +} + /** Copilot carries a token in its fenced session environment, not a temporary auth file. * Credential generation changes still retire the exact warm owner before attachment. */ export function supportsManagedNativeWarmSession( diff --git a/server/src/services/native-runtime/provider-profile.ts b/server/src/services/native-runtime/provider-profile.ts index c908d8cb725..d797d704e6b 100644 --- a/server/src/services/native-runtime/provider-profile.ts +++ b/server/src/services/native-runtime/provider-profile.ts @@ -455,7 +455,11 @@ export function claudeRunnerUnsupportedSettings(config: Record) */ export function resolvePaperclipRunnerProviderProfile( adapterConfig: unknown, - context: { companyId?: string } = {}, + context: { + companyId?: string; + /** The execution target's platform, when known: a pending Antigravity grant must name it. */ + candidateTarget?: { platform: string; architecture: string }; + } = {}, ): PaperclipRunnerProviderProfile { const config = asRecord(adapterConfig); const candidate = config.provider ?? "codex"; @@ -608,7 +612,7 @@ export function resolvePaperclipRunnerProviderProfile( if (!model) throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_model_required", `${pendingAcpxProfile.label} requires an explicit model ID; there is no default model.`); if (pendingAcpxProfile.value === "antigravity") { try { - if (resolveAntigravityCandidateAdmission({ companyId: context.companyId, model }, process.env)) { + if (resolveAntigravityCandidateAdmission({ companyId: context.companyId, model, target: context.candidateTarget }, process.env)) { return { provider: "acpx", backend: "acpx_runtime", model, acpxAgent: "antigravity" }; } } catch { diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts index 4e7baca7493..4097b212c07 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts @@ -1,13 +1,13 @@ import { createHash } from "node:crypto"; import { execFile } from "node:child_process"; -import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, rm, stat, symlink, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { promisify } from "node:util"; import { readFileSync } from "node:fs"; import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; import { describe, expect, it, vi } from "vitest"; -import { canonicalProviderPackJson, verifyRemoteProviderPack, type ProviderPackIdentity } from "./remote-provider-pack-verification.js"; +import { canonicalProviderPackJson, clearSealedProviderPacksForTest, PROVIDER_PACK_IDENTITY_FUNCTION, verifyRemoteProviderPack, type ProviderPackIdentity } from "./remote-provider-pack-verification.js"; const sha = (text: string) => `sha256:${createHash("sha256").update(text).digest("hex")}`; const manifest = (revision: string): ProviderPackIdentity => { @@ -76,6 +76,11 @@ describe("installed provider pack compatibility", () => { await expect(verifyRemoteProviderPack(input)).rejects.toMatchObject({ message: expect.stringContaining("manifest mismatch"), failureCheck: "manifest_mismatch:runnerSourceRevision" }); expect(execute).toHaveBeenCalledOnce(); + // The sealing variant of the verifier runs the same checks in a real Node process. + await expect(verifyRemoteProviderPack({ ...input, seal: { targetKey: "sandbox:env:real" } })).rejects.toMatchObject({ + failureCheck: "manifest_mismatch:runnerSourceRevision" }); + await expect(verifyRemoteProviderPack({ ...input, manifest: installed, seal: { targetKey: "sandbox:env:real" } })).rejects.toMatchObject({ + failureCheck: "artifact_digest:nodeCommand" }); await expect(verifyRemoteProviderPack({ ...input, manifest: installed })).rejects.toMatchObject({ message: expect.stringContaining("nodeCommand digest mismatch"), failureCheck: "artifact_digest:nodeCommand" }); await rm(join(root, "provider-pack.json")); @@ -212,6 +217,71 @@ describe("installed provider pack compatibility", () => { await expect(verifyRemoteProviderPack({ ...input, provider: { kind: "acpx", agent: "codex" } })).rejects.toThrow("profile is incompatible"); }); + describe("sealed reuse on the same sandbox", () => { + const identityOf = async (root: string) => { + const { stdout } = await promisify(execFile)(process.execPath, ["-e", + `${PROVIDER_PACK_IDENTITY_FUNCTION};process.stdout.write(packIdentity(process.argv[1]))`, root]); + return stdout; + }; + + it("changes the identity for any same-size rewrite, even with its mtime restored", async () => { + const root = await mkdtemp(join(tmpdir(), "pack-identity-")); + try { + await mkdir(join(root, "dist")); + await writeFile(join(root, "dist", "file.js"), "original"); + await symlink(join(root, "dist", "file.js"), join(root, "link.js")); + const sealed = await identityOf(root); + expect(sealed).toMatch(/^[a-f0-9]{64}$/); + expect(await identityOf(root)).toBe(sealed); + const before = await stat(join(root, "dist", "file.js")); + await new Promise(resolve => setTimeout(resolve, 20)); + await writeFile(join(root, "dist", "file.js"), "tampered"); + await utimes(join(root, "dist", "file.js"), before.atime, before.mtime); + expect(await identityOf(root)).not.toBe(sealed); + } finally { await rm(root, { recursive: true, force: true }); } + }); + + it("re-checks only the identity on a sealed sandbox and fully re-verifies after any change", async () => { + clearSealedProviderPacksForTest(); + const expected = manifest("b"); + let identity = "a".repeat(64); + const execute = vi.fn(async (request: Parameters[0]) => { + const script = String(request.args?.[1] ?? ""); + const stdout = request.args?.[0] === "--version" ? `${expected.payload.pins.opencode}\n` + : script.includes("paperclip-pack-check") ? `verified\npaperclip-pack-identity=${identity}\n` + : `\npaperclip-pack-identity=${identity}\n`; + return { exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "", stdout }; + }); + const kinds = () => execute.mock.calls.map(([request]) => request.args?.[0] === "--version" ? "version" + : String(request.args?.[1]).includes("paperclip-pack-check") ? "full" : "identity"); + const input = { runner: { execute }, cwd: "/workspace", packRoot: "/workspace/provider-pack", manifest: expected, + seal: { targetKey: "sandbox:env-1:sandbox-1" } }; + await expect(verifyRemoteProviderPack(input)).resolves.toEqual(expected); + expect(kinds()).toEqual(["full", "version"]); + execute.mockClear(); + await expect(verifyRemoteProviderPack(input)).resolves.toEqual(expected); + expect(kinds()).toEqual(["identity"]); + // Another sandbox, or no sandbox identity, never reuses the seal. + execute.mockClear(); + await verifyRemoteProviderPack({ ...input, seal: { targetKey: "sandbox:env-1:sandbox-2" } }); + await verifyRemoteProviderPack({ ...input, seal: undefined }); + expect(kinds()).toEqual(["full", "version", "full", "version"]); + // A changed identity falls back to the complete verification. + execute.mockClear(); + identity = "b".repeat(64); + await expect(verifyRemoteProviderPack(input)).resolves.toEqual(expected); + expect(kinds()).toEqual(["identity", "full", "version"]); + // A pack that changed while it was hashed reports no identity and is not sealed. + execute.mockClear(); + clearSealedProviderPacksForTest(); + execute.mockImplementation(async (request) => ({ exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "", + stdout: request.args?.[0] === "--version" ? `${expected.payload.pins.opencode}\n` : "verified\n" })); + await verifyRemoteProviderPack(input); + await verifyRemoteProviderPack(input); + expect(kinds()).toEqual(["full", "version", "full", "version"]); + }); + }); + it("rejects the published Grok pack from before native effort admission", async () => { const profiles = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/acpx-profiles.json", import.meta.url), "utf8")); const current = manifest("b"), installed = manifest("a"); diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.ts b/server/src/services/native-runtime/remote-provider-pack-verification.ts index dff334bc7dd..0fc4d332ea6 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.ts @@ -105,7 +105,36 @@ function compatibleInstallation( return structuredClone(actual); } -export async function verifyRemoteProviderPack({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false, acceptProvenance = false }: { +/** + * A Node expression defining `packIdentity(root)`: a digest of the kernel + * identity of every entry under the pack's real root (path, mode, device, + * inode, size, mtime, ctime, link count, owner; a symlink's text and its + * target's identity), bound to the machine's boot. Content cannot change + * without moving a ctime, and no unprivileged process can set a ctime back, + * so an unchanged identity proves bytes unchanged since they were hashed. + */ +export const PROVIDER_PACK_IDENTITY_FUNCTION = [ + "const packIdentity=(root)=>{const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');const h=crypto.createHash('sha256');let boot='none';try{boot=fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim()}catch{}", + "const real=fs.realpathSync(root);h.update('boot\\0'+boot+'\\nroot\\0'+real+'\\n');const id=(s)=>[s.mode,s.dev,s.ino,s.size,s.mtimeNs,s.ctimeNs,s.nlink,s.uid].join('\\0');h.update('.\\0'+id(fs.lstatSync(real,{bigint:true}))+'\\n');", + "const visit=(d,prefix)=>{for(const name of fs.readdirSync(d).sort()){const a=path.join(d,name),r=prefix?prefix+'/'+name:name,s=fs.lstatSync(a,{bigint:true});h.update(r+'\\0'+id(s)+'\\n');if(s.isSymbolicLink()){let t='missing';try{t=id(fs.statSync(a,{bigint:true}))}catch{}h.update('link\\0'+fs.readlinkSync(a)+'\\0'+t+'\\n')}else if(s.isDirectory())visit(a,r)}};visit(real,'');return h.digest('hex')}", +].join(""); + +type SealedPackRecord = { identity: string; manifest: ProviderPackIdentity }; +/** Fully verified packs this server process has sealed, by target and expected identity. */ +const sealedPacks = new Map(); +const MAX_SEALED_PACKS = 512; + +/** Test seam: forget every sealed pack record. */ +export function clearSealedProviderPacksForTest(): void { sealedPacks.clear(); } + +function sealKeyFor(seal: { targetKey: string } | undefined, packRoot: string, manifest: ProviderPackIdentity, acceptProvenance: boolean): string | null { + if (!seal?.targetKey) return null; + return createHash("sha256").update(canonicalProviderPackJson([seal.targetKey, packRoot, manifest, acceptProvenance])).digest("hex"); +} + +const reportedIdentity = (stdout: string) => /paperclip-pack-identity=([a-f0-9]{64})/.exec(stdout)?.[1] ?? null; + +export async function verifyRemoteProviderPack({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false, acceptProvenance = false, seal }: { runner: CommandManagedRuntimeRunner; cwd: string; packRoot: string; @@ -115,20 +144,41 @@ export async function verifyRemoteProviderPack({ requireExactIdentity?: boolean; requireCurrentOpenCodeProxy?: boolean; acceptProvenance?: boolean; + /** + * The exact sandbox this pack sits on. After one full verification the + * server keeps the pack's kernel identity; later runs on the same sandbox + * re-check only that identity instead of re-hashing every byte. + */ + seal?: { targetKey: string }; }): Promise { if (installation) { if (!provider) throw new Error("runner_remote_provider_artifact_incompatible: provider interface is required"); return compatibleInstallation(installation, manifest, packRoot, provider, requireExactIdentity, requireCurrentOpenCodeProxy); } - const expected = Buffer.from( - canonicalProviderPackJson(manifest), - "utf8", - ).toString("base64"); const providerNodeCommand = posix.join( packRoot, manifest.payload.artifacts.nodeCommand.path, ); + const sealKey = sealKeyFor(seal, packRoot, manifest, acceptProvenance); + const sealed = sealKey ? sealedPacks.get(sealKey) : undefined; + if (sealKey && sealed) { + // Any failure or difference falls through to the full verification. + const current = await runner.execute({ + command: providerNodeCommand, + args: ["-e", `${PROVIDER_PACK_IDENTITY_FUNCTION};process.stdout.write('\\npaperclip-pack-identity='+packIdentity(process.argv[1])+'\\n')`, packRoot], + cwd, bypassSession: true, timeoutMs: 30_000, + }).catch(() => null); + if (current && current.exitCode === 0 && !current.timedOut && reportedIdentity(current.stdout) === sealed.identity) { + return structuredClone(sealed.manifest) as T; + } + sealedPacks.delete(sealKey); + } + const expected = Buffer.from( + canonicalProviderPackJson(manifest), + "utf8", + ).toString("base64"); const verifyScript = [ + ...(sealKey ? [PROVIDER_PACK_IDENTITY_FUNCTION, "let identityBefore=null;try{identityBefore=packIdentity(process.argv[1])}catch{}"] : []), "const fs=require('node:fs')", "const crypto=require('node:crypto')", "const path=require('node:path')", @@ -157,6 +207,8 @@ export async function verifyRemoteProviderPack({ "const expectedPackages={acpx:manifest.payload.pins.acpx,'@agentclientprotocol/claude-agent-acp':manifest.payload.pins.claudeAcp,'@agentclientprotocol/codex-acp':manifest.payload.pins.codexAcp,'opencode-ai':manifest.payload.pins.opencode}", "for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)fail('package_version:'+pkg,pkg+' version mismatch')", "if(provenance)process.stdout.write('\\npaperclip-pack-manifest='+Buffer.from(canonical(manifest)).toString('base64')+'\\n')", + // Seal only when no entry changed while it was being hashed. + ...(sealKey ? ["let identityAfter=null;try{identityAfter=packIdentity(root)}catch{}if(identityBefore&&identityBefore===identityAfter)process.stdout.write('\\npaperclip-pack-identity='+identityAfter+'\\n')"] : []), ].join(";"); const verified = await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({ command: providerNodeCommand, @@ -182,6 +234,11 @@ export async function verifyRemoteProviderPack({ ) { throw providerPackIncompatible("opencode_version", "OpenCode version mismatch"); } + const identity = sealKey ? reportedIdentity(verified.stdout) : null; + if (sealKey && identity) { + if (sealedPacks.size >= MAX_SEALED_PACKS) sealedPacks.delete(sealedPacks.keys().next().value!); + sealedPacks.set(sealKey, { identity, manifest: structuredClone(selected) }); + } return structuredClone(selected); } diff --git a/server/src/services/native-runtime/remote-provider-pack.test.ts b/server/src/services/native-runtime/remote-provider-pack.test.ts index e67f3a9c4c6..2e06ba4a490 100644 --- a/server/src/services/native-runtime/remote-provider-pack.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack.test.ts @@ -2,7 +2,9 @@ import { describe, expect, it, vi } from "vitest"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { createNativeRunTrace } from "./native-run-trace.js"; -import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; +import { COPILOT_CLOSURE_SHA256 } from "../../vendor/paperclip-runner/index.js"; +import { readFileSync } from "node:fs"; +import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256, antigravityProviderPackEntryRefusal, COPILOT_PROVIDER_PACK_CLOSURES, prepareVerifiedRemoteProviderPack, remoteProviderPackEntryRefusal, type RemoteProviderPackRelease, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; describe("remote provider verification", () => { const ok = { exitCode: 0, timedOut: false, stdout: "verified", stderr: "", signal: null }; @@ -172,7 +174,7 @@ describe("same-content pack reuse across builds", () => { describe("ordinary ACPX image artifacts", () => { const provider = (agent: string) => ({ kind: "acpx", agent, model: "selected-model" } as Parameters[0]["provider"]); - it.each(["cursor", "copilot"])("selects bundled artifacts for remote %s without an operator override", agent => { + it.each(["cursor", "copilot", "kimi", "antigravity"])("selects bundled artifacts for remote %s without an operator override", agent => { expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: true, configuredProviderPackRoot: null, provider: provider(agent) })).toBe(true); expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: false, configuredProviderPackRoot: null, provider: provider(agent) })).toBe(false); expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: true, configuredProviderPackRoot: "/explicit/pack", provider: provider(agent) })).toBe(false); @@ -185,6 +187,98 @@ describe("ordinary ACPX image artifacts", () => { }); }); +describe("Google Antigravity image pack identity", () => { + const distributions = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8")); + const profile = { agentServerVersion: "1.4.3", commandDigest: `sha256:${"c".repeat(64)}` }; + const patchedClosures = { "linux-x64": "d".repeat(64) }; + const entry = { version: profile.agentServerVersion, profileDigest: profile.commandDigest, closureDigest: `sha256:${"d".repeat(64)}` }; + const base = { inventory: "providers" as const, target: { platform: "linux", architecture: "x64" }, inBoth: false, + entry, releasePending: false, profile, patchedClosures }; + + it("admits exactly the patched closures pinned in antigravity-distributions.json, never a vendor closure", () => { + const verified = Object.fromEntries(Object.entries(distributions.platforms as Record) + .filter(([, platform]) => platform.provisioning === "verified-closure").map(([key, platform]) => [key, platform.closureSha256])); + expect(ANTIGRAVITY_PATCHED_CLOSURE_SHA256).toEqual(verified); + for (const [key, closure] of Object.entries(ANTIGRAVITY_PATCHED_CLOSURE_SHA256)) { + expect(closure).not.toBe(distributions.platforms[key].vendorClosureSha256); + } + }); + + it("admits the real linux-x64 image pack closure and refuses its vendor closure", () => { + const linux = distributions.platforms["linux-x64"]; + const real = { ...base, patchedClosures: undefined, entry: { ...entry, closureDigest: `sha256:${linux.closureSha256}` } }; + expect(antigravityProviderPackEntryRefusal(real)).toBeNull(); + expect(antigravityProviderPackEntryRefusal({ ...real, entry: { ...real.entry, closureDigest: `sha256:${linux.vendorClosureSha256}` } })) + .toMatch(/patched closure/); + expect(antigravityProviderPackEntryRefusal({ ...real, entry: { ...real.entry, closureDigest: `sha256:${distributions.platforms["darwin-arm64"].closureSha256}` } })) + .toMatch(/patched closure/); + }); + + it("lists the qualified entry under providers and the pending one under candidateProviders, never both", () => { + expect(antigravityProviderPackEntryRefusal(base)).toBeNull(); + expect(antigravityProviderPackEntryRefusal({ ...base, releasePending: true, inventory: "candidateProviders" })).toBeNull(); + expect(antigravityProviderPackEntryRefusal({ ...base, inventory: "candidateProviders" })).toMatch(/wrong pack inventory/); + expect(antigravityProviderPackEntryRefusal({ ...base, releasePending: true })).toMatch(/wrong pack inventory/); + expect(antigravityProviderPackEntryRefusal({ ...base, inBoth: true })).toMatch(/wrong pack inventory/); + }); + + it.each([ + ["the vendor closure", { entry: { ...entry, closureDigest: `sha256:${"e".repeat(64)}` } }], + ["an unpinned Linux closure", { patchedClosures: {} }], + ["another target", { target: { platform: "linux", architecture: "arm64" } }], + ["an older profile", { entry: { ...entry, profileDigest: `sha256:${"f".repeat(64)}` } }], + ["an older runtime version", { entry: { ...entry, version: "1.4.2" } }], + ])("refuses %s", (_name, change) => { + expect(antigravityProviderPackEntryRefusal({ ...base, ...change })).not.toBeNull(); + }); +}); + +describe("remote provider pack entry expectation", () => { + const digest = (char: string) => `sha256:${char.repeat(64)}`; + const profile = (version: string, char: string) => ({ agentServerVersion: version, commandDigest: digest(char) }); + const release: RemoteProviderPackRelease = { + profiles: { cursor: profile("c1", "1"), copilot: profile("p1", "2"), kimi: { ...profile("k1", "3"), qualificationStatus: "pending" }, antigravity: profile("a1", "4") }, + cursorClosures: { "linux-x64": { closureSha256: "5".repeat(64) } }, + kimiLinuxX64Closure: "6".repeat(64), + antigravityReleasePending: true, + antigravityPatchedClosures: { "linux-x64": "7".repeat(64) }, + }; + const target = { platform: "linux", architecture: "x64" }; + const all = ["pi", "cursor", "copilot", "kimi", "antigravity"]; + const entry = (provider: string, qualification: string, version: string, profileDigest: string, closure: string) => ({ + version, profileDigest, closureDigest: `sha256:${closure}`, qualification, path: `provider-assets/${provider}/linux-x64`, sha256: digest("9"), + }); + const check = (provider: string, inventory: "providers" | "candidateProviders", value: unknown, listed = { providers: inventory === "providers", candidateProviders: inventory === "candidateProviders" }) => + remoteProviderPackEntryRefusal({ provider, inventory, allowedProviders: all, target, entry: value, listed, release }); + + it("checks Copilot against the Runner's canonical closure pins", () => { + expect(COPILOT_PROVIDER_PACK_CLOSURES).toEqual(COPILOT_CLOSURE_SHA256); + expect(Object.keys(COPILOT_PROVIDER_PACK_CLOSURES).sort()).toEqual(["darwin-arm64", "darwin-x64", "linux-x64"]); + }); + + it("admits each provider's entry only with this release's inventory, qualification, profile and closure", () => { + expect(check("pi", "providers", entry("pi", "qualified", "any", digest("8"), "8".repeat(64)))).toBeNull(); + expect(check("cursor", "providers", entry("cursor", "qualified", "c1", digest("1"), "5".repeat(64)))).toBeNull(); + expect(check("copilot", "providers", entry("copilot", "qualified", "p1", digest("2"), COPILOT_PROVIDER_PACK_CLOSURES["linux-x64"]!))).toBeNull(); + expect(check("copilot", "candidateProviders", entry("copilot", "pending", "p1", digest("2"), COPILOT_PROVIDER_PACK_CLOSURES["linux-x64"]!))).toBeNull(); + expect(check("kimi", "candidateProviders", entry("kimi", "pending", "k1", digest("3"), "6".repeat(64)))).toBeNull(); + expect(check("antigravity", "candidateProviders", entry("antigravity", "pending", "a1", digest("4"), "7".repeat(64)))).toBeNull(); + }); + + it("refuses with the same reasons the pack verifier reports", () => { + expect(check("grok", "providers", entry("grok", "qualified", "g", digest("1"), "1".repeat(64)))).toBe("invalid candidate identity"); + expect(check("antigravity", "providers", entry("antigravity", "qualified", "a1", digest("4"), "7".repeat(64)))).toBe("invalid candidate identity"); + expect(check("cursor", "providers", { ...entry("cursor", "qualified", "c1", digest("1"), "5".repeat(64)), extra: true })).toBe("invalid candidate identity"); + expect(check("cursor", "providers", entry("cursor", "qualified", "c0", digest("1"), "5".repeat(64)))).toBe("Cursor profile or closure does not match this release"); + expect(check("copilot", "providers", entry("copilot", "qualified", "p1", digest("2"), COPILOT_PROVIDER_PACK_CLOSURES["linux-x64"]!), { providers: true, candidateProviders: true })) + .toBe("Copilot profile or closure does not match this release"); + expect(check("kimi", "candidateProviders", entry("kimi", "pending", "k1", digest("3"), "6".repeat(64)), { providers: true, candidateProviders: true })) + .toBe("Kimi profile or closure does not match this release"); + expect(check("antigravity", "candidateProviders", entry("antigravity", "pending", "a1", digest("4"), "e".repeat(64)))) + .toBe("Antigravity closure is not this release's patched closure"); + }); +}); + describe("standard remote provider pack discovery", () => { const roots = ["/opt/paperclip-runner/provider-pack", "/home/operator/.local/share/paperclip-runner/provider-pack"]; it.each(["old manifest", "modified artifact", "failed link"])("tries the matching home pack after %s rejects /opt", async reason => { diff --git a/server/src/services/native-runtime/remote-provider-pack.ts b/server/src/services/native-runtime/remote-provider-pack.ts index be4a1656891..ae04605c462 100644 --- a/server/src/services/native-runtime/remote-provider-pack.ts +++ b/server/src/services/native-runtime/remote-provider-pack.ts @@ -1,6 +1,6 @@ import { redactSensitiveText } from "../../redaction.js"; import { nativeRunFailureCheck, type NativeRunTrace } from "./native-run-trace.js"; -import type { NativeExecutionInput } from "../../vendor/paperclip-runner/index.js"; +import { ANTIGRAVITY_DISTRIBUTION_PINS, COPILOT_CLOSURE_SHA256, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js"; /** Qualified ACPX releases carry their Linux image manifest and daemon. */ export function shouldUseBundledAcpxImageAssets(input: { @@ -10,7 +10,123 @@ export function shouldUseBundledAcpxImageAssets(input: { }): boolean { return input.requiresRemoteProviderPack && !input.configuredProviderPackRoot && input.provider.kind === "acpx" && - ["cursor", "copilot", "kimi"].includes(input.provider.agent); + ["cursor", "copilot", "kimi", "antigravity"].includes(input.provider.agent); +} + +/** + * The patched Antigravity closure (never the vendor closure) this server + * release admits per platform. It is read from the Runner's generated pins, so + * re-pinning the closure in antigravity-distributions.json can never leave a + * stale server copy; a test keeps it equal to the `verified-closure` platforms. + */ +export const ANTIGRAVITY_PATCHED_CLOSURE_SHA256: Readonly> = Object.freeze( + Object.fromEntries(Object.entries(ANTIGRAVITY_DISTRIBUTION_PINS).map(([target, pin]) => [target, pin.closureSha256])), +); + +export type ProviderPackEntry = { version: string; profileDigest: string; closureDigest: string }; + +/** + * The image pack contract for Antigravity. While the profile is pending the + * entry lives only under `candidateProviders`; after the flip only under + * `providers`. It targets Linux x64 and pins this release's profile and the + * patched closure. Returns null when admitted, else a refusal reason. + */ +export function antigravityProviderPackEntryRefusal(input: { + inventory: "providers" | "candidateProviders"; + target: { platform: string; architecture: string }; + inBoth: boolean; + entry: ProviderPackEntry; + releasePending: boolean; + profile: { agentServerVersion: string; commandDigest: string }; + patchedClosures?: Readonly>; +}): string | null { + const expectedInventory = input.releasePending ? "candidateProviders" : "providers"; + if (input.inventory !== expectedInventory || input.inBoth) return "Antigravity is listed under the wrong pack inventory"; + if (input.target.platform !== "linux" || input.target.architecture !== "x64") return "Antigravity pack target must be linux-x64"; + const closure = (input.patchedClosures ?? ANTIGRAVITY_PATCHED_CLOSURE_SHA256)["linux-x64"]; + if (!closure || input.entry.closureDigest !== `sha256:${closure}`) return "Antigravity closure is not this release's patched closure"; + if (input.entry.version !== input.profile.agentServerVersion || input.entry.profileDigest !== input.profile.commandDigest) { + return "Antigravity profile does not match this release"; + } + return null; +} + +type ProviderPackProfile = { agentServerVersion: string; commandDigest: string }; + +/** The provider identities one server release admits in a remote pack. */ +export type RemoteProviderPackRelease = { + profiles: { + cursor: ProviderPackProfile; + copilot: ProviderPackProfile; + kimi: ProviderPackProfile & { qualificationStatus?: string }; + antigravity: ProviderPackProfile; + }; + cursorClosures: Readonly>; + kimiLinuxX64Closure: string; + antigravityReleasePending: boolean; + antigravityPatchedClosures?: Readonly>; +}; + +/** Copilot's pinned closure per platform: the Runner's canonical pins. */ +export const COPILOT_PROVIDER_PACK_CLOSURES: Readonly> = COPILOT_CLOSURE_SHA256; + +/** + * The complete expectation for one provider entry of a remote pack: which + * inventory may list it, its qualification, asset path, digests, and the + * release's profile and closure for the pack target. Returns null when the + * entry is admitted, else the refusal reason. + */ +export function remoteProviderPackEntryRefusal(input: { + provider: string; + inventory: "providers" | "candidateProviders"; + allowedProviders: readonly string[]; + target: { platform: string; architecture: string }; + entry: unknown; + /** Whether the provider is listed in each inventory of the same pack. */ + listed: { providers: boolean; candidateProviders: boolean }; + release: RemoteProviderPackRelease; +}): string | null { + const { provider, inventory, target, release } = input; + const entry = input.entry as Record | null | undefined; + const kimiPending = release.profiles.kimi.qualificationStatus === "pending"; + const qualified = ["pi", "cursor"].includes(provider) || inventory === "providers" && (provider === "copilot" || provider === "kimi" && !kimiPending + || provider === "antigravity" && !release.antigravityReleasePending); + if (!input.allowedProviders.includes(provider) || !entry || typeof entry !== "object" + || Object.keys(entry).some(key => !["version", "profileDigest", "closureDigest", "qualification", "path", "sha256"].includes(key)) + || entry.qualification !== (qualified ? "qualified" : "pending") || entry.path !== `provider-assets/${provider}/${target.platform}-${target.architecture}` + || typeof entry.version !== "string" || !entry.version || entry.version.length > 120 + || !/^sha256:[a-f0-9]{64}$/.test(String(entry.profileDigest)) + || !/^sha256:[a-f0-9]{64}$/.test(String(entry.closureDigest)) + || !/^sha256:[a-f0-9]{64}$/.test(String(entry.sha256))) { + return "invalid candidate identity"; + } + const identity = entry as ProviderPackEntry; + const platform = `${target.platform}-${target.architecture}`; + const matches = (profile: ProviderPackProfile, closure: string | undefined) => closure !== undefined + && identity.version === profile.agentServerVersion && identity.profileDigest === profile.commandDigest && identity.closureDigest === `sha256:${closure}`; + if (provider === "cursor") { + const closure = Object.hasOwn(release.cursorClosures, platform) ? release.cursorClosures[platform]!.closureSha256 : undefined; + if (!matches(release.profiles.cursor, closure)) return "Cursor profile or closure does not match this release"; + } + if (provider === "copilot") { + const closure = Object.hasOwn(COPILOT_PROVIDER_PACK_CLOSURES, platform) ? COPILOT_PROVIDER_PACK_CLOSURES[platform] : undefined; + if ((input.listed.providers && input.listed.candidateProviders) || !matches(release.profiles.copilot, closure)) { + return "Copilot profile or closure does not match this release"; + } + } + if (provider === "kimi") { + if (inventory !== (kimiPending ? "candidateProviders" : "providers") || input.listed[kimiPending ? "providers" : "candidateProviders"] + || platform !== "linux-x64" || !matches(release.profiles.kimi, release.kimiLinuxX64Closure)) { + return "Kimi profile or closure does not match this release"; + } + } + if (provider === "antigravity") { + return antigravityProviderPackEntryRefusal({ inventory, target, entry: identity, + inBoth: input.listed.providers && input.listed.candidateProviders, + releasePending: release.antigravityReleasePending, profile: release.profiles.antigravity, + patchedClosures: release.antigravityPatchedClosures }); + } + return null; } /** A run may adopt a same-content pack from another build only when no saved or operator-selected identity binds it. */ diff --git a/server/src/services/native-runtime/runtime-mode.ts b/server/src/services/native-runtime/runtime-mode.ts index 19e1167d276..156faffea16 100644 --- a/server/src/services/native-runtime/runtime-mode.ts +++ b/server/src/services/native-runtime/runtime-mode.ts @@ -8,6 +8,7 @@ import { resolvePaperclipRunnerProviderProfile, type PaperclipRunnerProviderProfile, } from "./provider-profile.js"; +import { antigravityCandidateTarget } from "./antigravity-release.js"; /** * Public compatibility resolver version. This value is persisted by the @@ -111,7 +112,8 @@ export function resolveNativeRuntimeMode(input: { } let runnerProfile: PaperclipRunnerProviderProfile; try { - runnerProfile = resolvePaperclipRunnerProviderProfile(input.adapterConfig, { companyId: input.agent.companyId }); + runnerProfile = resolvePaperclipRunnerProviderProfile(input.adapterConfig, { companyId: input.agent.companyId, + candidateTarget: antigravityCandidateTarget((input.target?.kind ?? "local") === "remote") }); } catch (error) { if (error instanceof PaperclipRunnerProviderProfileError) { throw ineligible(error.code, error.message); diff --git a/server/src/vendor/paperclip-runner/index.ts b/server/src/vendor/paperclip-runner/index.ts index c3c27e9fe83..2f1b872597c 100644 --- a/server/src/vendor/paperclip-runner/index.ts +++ b/server/src/vendor/paperclip-runner/index.ts @@ -194,12 +194,15 @@ export const resolveQualifiedAcpxProfile = runner.resolveQualifiedAcpxProfile; export const runnerProviderLaunchRequirements = runner.runnerProviderLaunchRequirements; export const createRunnerProviderLaunch = runner.createRunnerProviderLaunch; export const parseAcpxCandidateAdmission = runner.parseAcpxCandidateAdmission; +export const isAntigravityNativeTarget = runner.isAntigravityNativeTarget; export const resolveClaudeEffort = runner.resolveClaudeEffort; export const resolveGrokEffort = runner.resolveGrokEffort; export const QUALIFIED_ACPX_PROFILES = runner.QUALIFIED_ACPX_PROFILES; export const QUALIFIED_ACPX_VERSION = runner.QUALIFIED_ACPX_VERSION; export const CURSOR_DISTRIBUTION_PINS = runner.CURSOR_DISTRIBUTION_PINS; +export const ANTIGRAVITY_DISTRIBUTION_PINS = runner.ANTIGRAVITY_DISTRIBUTION_PINS; export const KIMI_DISTRIBUTION_CLOSURE_SHA256 = runner.KIMI_DISTRIBUTION_CLOSURE_SHA256; +export const COPILOT_CLOSURE_SHA256 = runner.COPILOT_CLOSURE_SHA256; export const SANDBOX_DISK_FULL_FAILURE_CODE = runner.SANDBOX_DISK_FULL_FAILURE_CODE; export const isSandboxDiskFullFailure = runner.isSandboxDiskFullFailure; export const resolveSourceCodexHome = runner.resolveSourceCodexHome; diff --git a/tests/runner-e2e/ANTIGRAVITY-AGENT-JOURNEY.md b/tests/runner-e2e/ANTIGRAVITY-AGENT-JOURNEY.md index f613e6bf2c2..98c51ffa680 100644 --- a/tests/runner-e2e/ANTIGRAVITY-AGENT-JOURNEY.md +++ b/tests/runner-e2e/ANTIGRAVITY-AGENT-JOURNEY.md @@ -112,9 +112,9 @@ setup and retains a blocked report. "candidate": { "platform": "darwin", "architecture": "arm64", - "nativeVersion": "1.4.3-paperclip.5", - "profileDigest": "sha256:acf5f574b6b9ec4388ff9d081890caa330e66bf1ae3fe3b08e7f0fb0e851b9ce", - "nativeClosureDigest": "sha256:044792d793e203bc8b4524a418f1816c4d34db67bb41fa4bae5947a050c49b4a" + "nativeVersion": "1.5.2-paperclip.2", + "profileDigest": "sha256:61ac14bf03ce4bbf8afe1f5a263b854517ec588d8407fe2d8f17c9fc0c037c4b", + "nativeClosureDigest": "sha256:ab9df40a64806a8e1812234ce5331e04d1c6b5f8c7e5bdbb456cd645e58c5aad" }, "limits": { "durationMs": 1200000, diff --git a/tests/runner-e2e/README.md b/tests/runner-e2e/README.md index afa4be32129..fac3c0c38cd 100644 --- a/tests/runner-e2e/README.md +++ b/tests/runner-e2e/README.md @@ -29,6 +29,7 @@ Shell variables take precedence over the local file. The recognized names are: - `DAYTONA_API_KEY` - `CURSOR_AUTH_TOKEN` (extended Cursor candidate) - `COPILOT_GITHUB_TOKEN` (extended Copilot candidate) +- `GEMINI_API_KEY` (Google Antigravity API-key profile `runner-acpx-antigravity`) - `PAPERCLIP_E2E_DAYTONA_IMAGE` (Daytona only) - `PAPERCLIP_E2E_DAYTONA_NODE_SHA256` and `PAPERCLIP_E2E_DAYTONA_RUNNERD_SHA256` (native Cursor/Pi/Copilot Daytona fixtures; exact `sha256:...` executable digests from that image) diff --git a/tests/runner-e2e/SUITES.md b/tests/runner-e2e/SUITES.md index e1ec469dd01..c2d37f05b48 100644 --- a/tests/runner-e2e/SUITES.md +++ b/tests/runner-e2e/SUITES.md @@ -1661,6 +1661,99 @@ pnpm test:e2e:runner -- --list --suite kimi-qualification pnpm test:e2e:runner -- --id kimi-qualification.runner-acpx-kimi.local.message-marker --max-automatic-retries 0 ``` +### Google Antigravity qualification + +`antigravity-qualification` is the explicit-only, unattended suite for the +native Runner Antigravity harness with a Gemini API key. It follows the Kimi +template: twelve journeys on local and on Daytona (24 cells), one attempt each, +profile `runner-acpx-antigravity`, credential `GEMINI_API_KEY`, acceptance model +`gemini-3.8-flash-low`. It is not part of `--all`, `extended-harnesses` or the +attended [Antigravity journey](ANTIGRAVITY-AGENT-JOURNEY.md), which stays a +separate saved-subscription cell refused by CI matrix jobs. + +While the Antigravity release declaration is `pending`, the supervisor stages a +company-bound candidate grant (company, exact model, profile digest, closure +digest, platform, architecture, one-hour expiry) when each cell's disposable +company is created, exactly as Kimi did. Ambient grants are discarded. When the +declaration is flipped to qualified, `antigravityCandidateAdmissionForExecution` +returns nothing and the same cells prove ordinary admission without a grant; +the suite definition does not change. Daytona lifecycle cases use per-turn +leases; the other Daytona cases use the warm environment. + +Each case maps to one row of the +[playbook section 13 acceptance matrix](../../doc/RUNNER-INTEGRATION-PLAYBOOK.md#13-run-the-product-acceptance-matrix): + +| Case | Fixture reused | Acceptance row | +| --- | --- | --- | +| `message-marker` | core runner task | Task completion | +| `plan-revise-accept` | core runner task | Plans | +| `ask-question`, `structured-question-resume` | core runner tasks | Questions (semantic forms) | +| `structured-question-restart-resume` | local-integrity task | Pending input + controller restart | +| `file-edit-validate` | extended-harness file task | File/edit/validate/deliver | +| `warm-three-turn` | warm workspace continuity (workspace-file variant) | Warm follow-ups | +| `stop-new-resume` | chat hardening | Stop (active real work) | +| `continuity-restart` | chat hardening | Continuity after controller restart | +| `pending-permission-stop` | shared `native_active_stop` (Cursor/Copilot) | Stop (pending native permission) | +| `permission-deny-stop` | shared `native_active_stop` with a browser Deny first | Permission denial | +| `pending-permission-provider-loss` | shared `native_provider_loss` (Cursor) | Provider death | + +Antigravity emits no provider tool-evidence notice, so the shared Stop and loss +oracles read the canonical stream for it: one `runtime_request.created` +permission card with the native ACPX origin, its tool execution (an edit or +write on the exact target, never completed), only completed read/search +operations before it, then a cancelled (Stop) or expired (loss) closure and one +turn terminal. A stale Allow must return 409 in both cases. + +`permission-deny-stop` follows the same pending boundary, then the operator +clicks Deny in the browser and stops the task. It passes only when the browser's +POST declines that exact run, turn and request; the canonical stream records a +`runtime_request.resolved` `decline` for it before the one turn terminal; the +mutation never completes and nothing runs after the terminal; the target stays +absent through cleanup; and there is one run. When Stop wins (the expected +branch) the run is cancelled with the caller's acknowledged Stop; when the +provider ended its turn after the denial first, the task must not be done. + +Instructions and assigned skills use the shared `native-completion` cells; the +Antigravity profile there is opt-in (`--profile runner-acpx-antigravity`). +Normal setup through the picker is covered by the attended journey. Native +questions, plans, steering, agent files and accounting are not claimed. + +```sh +pnpm test:e2e:runner -- --list --suite antigravity-qualification +pnpm test:e2e:runner -- --id antigravity-qualification.runner-acpx-antigravity.local.message-marker --max-automatic-retries 0 +pnpm test:e2e:runner -- --suite antigravity-qualification --environment daytona --max-automatic-retries 0 +``` + +### Google Antigravity model lineups + +`antigravity-model-lineup` (14 cells) and `antigravity-model-lineup-gemini4` +(14 cells) are local, explicit-only suites with one cell per exact model ID, +case `model-receipt`, generated from the pinned server's catalog. Model IDs +are `-`. The API-key lineup is Flash 3.5 to 3.8 at `low`, +`medium` and `high`, plus 3.1 Pro at `low` and `high`. The Gemini 4 lineup is +each family at the levels it offers: Neon and Hydrogen at `low` to +`extra_high`, Carbon and Argon at `low` to `high`. Both lineups bind +`GEMINI_API_KEY`. The 1.5.2 server's own catalog lists Gemini 4 only for Agent +Platform, but patch `1.5.2-paperclip.2` admits an exact requested model ID +under an API key, so the Gemini 4 lineup runs on the same API-key route. It +needs a paid Gemini key: a free-tier key has no Gemini 4 quota, so its cells +reach the exact-model receipt but no reply. Each +cell admits its own model, sends the ordinary one-reply prompt, and grades the +run's native input model plus the Runner's requested and effective model +receipt against the requested ID; a reply alone does not pass. Profile IDs +replace dots, for example +`antigravity-model-lineup.runner-acpx-antigravity-gemini-3-8-flash-low.local.model-receipt`. +`buildAntigravityModelLineupSuite` takes any other list. + +### Antigravity in shared eval suites + +`chat-features` and `native-completion` include an Antigravity profile that is +selected only when named, so existing suite selections are unchanged: + +```sh +pnpm test:e2e:runner -- --list --suite chat-features --profile runner-acpx-antigravity +``` + ### Grok branch qualification on EC2 The trusted default-branch workflow can run the explicit `grok-qualification` diff --git a/tests/runner-e2e/antigravity-admission.ts b/tests/runner-e2e/antigravity-admission.ts new file mode 100644 index 00000000000..f6597828d90 --- /dev/null +++ b/tests/runner-e2e/antigravity-admission.ts @@ -0,0 +1,46 @@ +import { parseAcpxCandidateAdmission, type AcpxCandidateAdmission } from "../../packages/paperclip-runner/src/drivers/acpx/candidate-admission.js"; +import { ANTIGRAVITY_DISTRIBUTION_PINS } from "../../packages/paperclip-runner/src/drivers/acpx/generated-profiles.js"; +import { QUALIFIED_ACPX_PROFILES } from "../../packages/paperclip-runner/src/drivers/acpx/qualified-profiles.js"; +import { ANTIGRAVITY_GEMINI4_LINEUP_SUITE, ANTIGRAVITY_MODEL_LINEUP_SUITE, ANTIGRAVITY_PROFILE_ID, ANTIGRAVITY_QUALIFICATION_SUITE } from "./antigravity-qualification-cases.js"; +import type { MatrixExecution } from "./types.js"; + +const LINEUP_SUITES = new Set([ANTIGRAVITY_MODEL_LINEUP_SUITE, ANTIGRAVITY_GEMINI4_LINEUP_SUITE]); +/** Shared suites that admit the Antigravity profile only when it is named explicitly. */ +const OPT_IN_SUITES = new Set(["chat-features", "native-completion"]); +const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + +/** The explicit manual suites that may carry an Antigravity candidate cell. */ +export function isAntigravityAdmittedExecution(execution: MatrixExecution): boolean { + if (execution.profile.qualificationCandidate !== "antigravity" || !execution.suite.manualOnly) return false; + if (execution.suite.id === ANTIGRAVITY_QUALIFICATION_SUITE) return execution.profile.id === ANTIGRAVITY_PROFILE_ID; + if (LINEUP_SUITES.has(execution.suite.id)) return execution.profile.id.startsWith(`${ANTIGRAVITY_PROFILE_ID}-`); + return OPT_IN_SUITES.has(execution.suite.id) && execution.profile.id === ANTIGRAVITY_PROFILE_ID && execution.profile.explicitOnly === true; +} + +/** Remote cells execute on the pinned Linux sandbox; local cells on this host. */ +export function antigravityExecutionTarget(execution: MatrixExecution, host: Pick = process) { + return execution.environment.expectedExecutionTarget.kind === "remote" + ? { platform: "linux", architecture: "x64" } : { platform: host.platform, architecture: host.arch }; +} + +/** + * A pending profile needs trusted operator authority bound to this disposable + * company, exact model, profile digest, closure and target, expiring within an + * hour. Once the declaration is qualified this returns undefined: the same + * cells then prove ordinary admission without any grant. + */ +export function antigravityCandidateAdmissionForExecution(execution: MatrixExecution, companyId: string, now = Date.now(), + host: Pick = process): AcpxCandidateAdmission | undefined { + if (execution.profile.qualificationCandidate !== "antigravity" || QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus !== "pending") return undefined; + if (!isAntigravityAdmittedExecution(execution) || !UUID.test(companyId)) { + throw new Error("Antigravity qualification requires an exact disposable company and an explicit Antigravity suite"); + } + const target = antigravityExecutionTarget(execution, host), key = `${target.platform}-${target.architecture}`; + const pins = ANTIGRAVITY_DISTRIBUTION_PINS as Readonly>; + const closure = pins[key]?.closureSha256; + if (!closure) throw new Error(`Antigravity has no admitted runtime closure for ${key}; no provider credentials were sent.`); + return parseAcpxCandidateAdmission({ schema: "paperclip.acpx-candidate-admission.v1", companyId, agent: "antigravity", + model: execution.profile.model, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, + nativeClosureDigest: `sha256:${closure}`, platform: target.platform, architecture: target.architecture, + expiresAt: now + 60 * 60 * 1000 }, { companyId, agent: "antigravity", model: execution.profile.model }, now); +} diff --git a/tests/runner-e2e/antigravity-journey-config.test.ts b/tests/runner-e2e/antigravity-journey-config.test.ts index 834b9b9ddd9..7154ec81e6d 100644 --- a/tests/runner-e2e/antigravity-journey-config.test.ts +++ b/tests/runner-e2e/antigravity-journey-config.test.ts @@ -18,7 +18,7 @@ const connectionId = "33333333-3333-4333-8333-333333333333", agentId = "44444444 function fixture() { return { version: 1, setupId: "synthetic", hosting: "self-hosted", executionEnvironment: "local", target: { mode: "attach", baseURL: "http://127.0.0.1:3104", expectedCommit: "a".repeat(40), deploymentMode: "local_trusted", companyId, environmentId }, browser: { headed: false, channel: "chromium", freshness: "signed-in" }, savedConnection: { id: connectionId, name: "Synthetic Google subscription", ownerUserId: "synthetic-user" }, - candidate: { platform: "darwin", architecture: "arm64", nativeVersion: "1.4.3-paperclip.5", profileDigest: `sha256:${"b".repeat(64)}`, nativeClosureDigest: `sha256:${"c".repeat(64)}` }, + candidate: { platform: "darwin", architecture: "arm64", nativeVersion: "1.5.2-paperclip.2", profileDigest: `sha256:${"b".repeat(64)}`, nativeClosureDigest: `sha256:${"c".repeat(64)}` }, limits: { durationMs: 900_000, turnTimeoutMs: 300_000, maxRuns: 2, budgetCents: 100 } }; } function resources(): AntigravityJourneyResources { return { version: 1, executionId: ANTIGRAVITY_JOURNEY_EXECUTION, origin: "http://127.0.0.1:3104", companyId, environmentId, connectionId, agentName: "Antigravity QA 0123456789ab", agentId, runIds: [], processes: {}, retained: false, setupProbe: "not_started" }; } diff --git a/tests/runner-e2e/antigravity-journey-launch.test.ts b/tests/runner-e2e/antigravity-journey-launch.test.ts index 714209175bb..e036dc43f69 100644 --- a/tests/runner-e2e/antigravity-journey-launch.test.ts +++ b/tests/runner-e2e/antigravity-journey-launch.test.ts @@ -130,7 +130,7 @@ beforeEach(() => { companyId: "11111111-1111-4111-8111-111111111111", environmentId: "22222222-2222-4222-8222-222222222222" }, browser: { headed: true, channel: "chromium", freshness: "signed-in" }, savedConnection: { id: "33333333-3333-4333-8333-333333333333", name: "Synthetic subscription", ownerUserId: "synthetic-operator" }, - candidate: { platform: "darwin", architecture: "arm64", nativeVersion: "1.4.3-paperclip.5", profileDigest: `sha256:${"b".repeat(64)}`, nativeClosureDigest: `sha256:${"c".repeat(64)}` }, + candidate: { platform: "darwin", architecture: "arm64", nativeVersion: "1.5.2-paperclip.2", profileDigest: `sha256:${"b".repeat(64)}`, nativeClosureDigest: `sha256:${"c".repeat(64)}` }, limits: { durationMs: 900_000, turnTimeoutMs: 300_000, maxRuns: 2, budgetCents: 100 } }); scenario.prepare.mockResolvedValue({ identity: { commit: "a".repeat(40) }, company: { issuePrefix: "QA" }, connection: { id: scenario.config.savedConnection.id, grantId: "synthetic-grant", ownerUserId: "synthetic-operator", isDefault: true, method: "subscription" }, accounting: {} }); diff --git a/tests/runner-e2e/antigravity-qualification-cases.ts b/tests/runner-e2e/antigravity-qualification-cases.ts new file mode 100644 index 00000000000..c7e68605560 --- /dev/null +++ b/tests/runner-e2e/antigravity-qualification-cases.ts @@ -0,0 +1,165 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { QUALIFIED_ACPX_PROFILES } from "../../packages/paperclip-runner/src/drivers/acpx/qualified-profiles.js"; +import { ANTIGRAVITY_THINKING_LEVELS, antigravityFamilyModelIds } from "../../packages/shared/src/antigravity-models.js"; +import { ANTIGRAVITY_GENERATED_MODEL_CATALOG } from "../../packages/shared/src/antigravity-models.generated.js"; +import { nativePermissionDenialTasks } from "./native-active-stop-tasks.js"; +import type { EnvironmentFixture, RunnerProfileFixture, RunnerSuiteFixture, RunnerTaskFixture } from "./types.js"; + +/** Unattended Google API-key route. The acceptance model is repeatable on a free-tier key. */ +export const ANTIGRAVITY_PROFILE_ID = "runner-acpx-antigravity"; +export const ANTIGRAVITY_ACCEPTANCE_MODEL = "gemini-3.8-flash-low"; +export const ANTIGRAVITY_QUALIFICATION_SUITE = "antigravity-qualification"; +export const ANTIGRAVITY_MODEL_LINEUP_SUITE = "antigravity-model-lineup"; +export const ANTIGRAVITY_GEMINI4_LINEUP_SUITE = "antigravity-model-lineup-gemini4"; +export const ANTIGRAVITY_MODEL_RECEIPT_CASE = "model-receipt"; + +/** Thinking level is part of the model ID: `-`. */ +export { ANTIGRAVITY_THINKING_LEVELS }; +/** + * Lineups come from the catalog generated from the pinned runtime, never a + * hand-kept list: the API-key lineup is exactly what a `gemini-api-key` + * session lists, and each Gemini 4 family keeps its own levels. The server + * marks the Gemini 4 families `agent_platform_only`; with an API key they are + * 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 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_GEMINI4_LINEUP: readonly string[] = antigravityModelIds(ANTIGRAVITY_GEMINI4_FAMILIES); + +const MODEL_ID = /^gemini-[0-9][a-z0-9.-]*-(?:minimal|low|medium|high|extra_high)$/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}`); + return `${ANTIGRAVITY_PROFILE_ID}-${model.replaceAll(".", "-").replaceAll("_", "-")}`; +} + +/** + * While the profile is pending, an unattended cell needs its own company-bound + * candidate grant (server-restart-request.ts). When the profile flips to + * qualified, that grant builder returns undefined and the same cells run as an + * ordinary released profile: flipping needs no change here. + */ +export function antigravityQualificationStatus(): "pending" | "qualified" { + return QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus === "pending" ? "pending" : "qualified"; +} + +/** + * Exact-model receipt. The run's native input names the requested model; the + * Runner's provider identity records the model the native connection + * acknowledged. All three must equal the requested ID, not merely produce a reply. + */ +export function antigravityModelReceiptMatchers(model: string) { + return [ + { kind: "json_path" as const, path: "run.runnerProfileJson.nativeExecutionInput.provider.agent", expected: "antigravity" }, + { kind: "json_path" as const, path: "run.runnerProfileJson.nativeExecutionInput.provider.model", expected: model }, + { kind: "json_path" as const, path: "run.runnerProfileJson.sessionCheckpoint.providerIdentity.requestedModel", expected: model }, + { kind: "json_path" as const, path: "run.runnerProfileJson.sessionCheckpoint.providerIdentity.effectiveModel", expected: model }, + ]; +} + +export interface AntigravitySuiteDependencies { + nativeProfile(input: { + id: string; label: string; provider: "acpx"; acpxAgent: "antigravity"; qualificationCandidate: "antigravity"; + model: string; credential: "GEMINI_API_KEY"; supportedEnvironments?: readonly ("local" | "daytona")[]; + modelQualification: RunnerProfileFixture["modelQualification"]; + }): RunnerProfileFixture; + localEnvironment: EnvironmentFixture; + daytonaEnvironment: EnvironmentFixture; + daytonaWarmEnvironment: EnvironmentFixture; + runnerTasks: readonly RunnerTaskFixture[]; + localIntegrityTasks: readonly RunnerTaskFixture[]; + extendedHarnessFileTask: RunnerTaskFixture; + warmFollowupTask: RunnerTaskFixture; + chatHardeningTasks: readonly RunnerTaskFixture[]; + nativeActiveStopTasks: readonly RunnerTaskFixture[]; + nativeProviderLossTasks: readonly RunnerTaskFixture[]; +} + +export function buildAntigravityProfile(deps: Pick, model = ANTIGRAVITY_ACCEPTANCE_MODEL, id = ANTIGRAVITY_PROFILE_ID): RunnerProfileFixture { + return deps.nativeProfile({ + id, label: model === ANTIGRAVITY_ACCEPTANCE_MODEL && id === ANTIGRAVITY_PROFILE_ID ? "Runner Google Antigravity (API key)" : `Runner Google Antigravity ${model}`, + provider: "acpx", acpxAgent: "antigravity", qualificationCandidate: "antigravity", + credential: "GEMINI_API_KEY", model, + modelQualification: { source: "candidate_runner_profile", qualificationId: `antigravity:${QUALIFIED_ACPX_PROFILES.antigravity.agentServerVersion}:gemini-api-key:${model}` }, + }); +} + +/** Lifecycle cases that need one owned process tree per run use per-turn Daytona leases. */ +const LIFECYCLE_CASES = ["pending-permission-stop", "permission-deny-stop", "pending-permission-provider-loss"] as const; + +function definitionDigest(extra: unknown): string { + const hash = createHash("sha256").update(JSON.stringify(extra)); + for (const file of ["antigravity-qualification-cases.ts", "native-active-stop-evidence.ts", "native-active-stop-flow.ts", "native-provider-loss-flow.ts", "native-active-stop-tasks.ts"]) + hash.update(file).update(readFileSync(new URL(`./${file}`, import.meta.url))); + return hash.digest("hex"); +} + +/** + * Mirrors kimi-qualification: ordinary daily work, files, questions, plans, + * warm follow-ups and chat Stop/restart, plus the shared Cursor/Copilot + * pending-permission Stop and provider-loss fixtures. SUITES.md maps each case + * to its playbook section 13 row. + */ +export function buildAntigravityQualificationSuite(deps: AntigravitySuiteDependencies): RunnerSuiteFixture { + const tasks = [ + ...deps.runnerTasks, ...deps.localIntegrityTasks, deps.extendedHarnessFileTask, deps.warmFollowupTask, + ...deps.chatHardeningTasks.filter(task => ["stop-new-resume", "continuity-restart"].includes(task.id)), + ...deps.nativeActiveStopTasks.filter(task => task.id === "pending-permission-stop"), + ...nativePermissionDenialTasks, + ...deps.nativeProviderLossTasks, + ].map(task => ({ ...task, automaticRetryPolicy: "single_attempt" as const })); + if (tasks.filter(task => (LIFECYCLE_CASES as readonly string[]).includes(task.id)).length !== LIFECYCLE_CASES.length) { + throw new Error("Antigravity lifecycle fixtures are missing"); + } + return { + id: ANTIGRAVITY_QUALIFICATION_SUITE, label: "Google Antigravity Qualification", manualOnly: true, + description: "Google Antigravity with a Gemini API key: replies, plans, questions, verified file delivery, warm follow-ups, Stop, controller restart, pending-permission Stop and provider loss through local and Daytona user journeys.", + groups: ["native"], + profiles: [buildAntigravityProfile(deps)], + environments: [deps.localEnvironment, deps.daytonaWarmEnvironment], + environmentOverrides: Object.fromEntries(LIFECYCLE_CASES.map(id => [id, { daytona: deps.daytonaEnvironment }])), + tasks, expectedMatrixSize: tasks.length * 2, + definitionMetadata: { version: 2, digest: definitionDigest(tasks.map(task => task.id)), runtime: QUALIFIED_ACPX_PROFILES.antigravity.agentServerVersion, + model: ANTIGRAVITY_ACCEPTANCE_MODEL, authentication: "gemini-api-key", qualification: antigravityQualificationStatus(), + candidateAdmission: "company-bound-grant-staged-at-company-creation-while-pending-none-once-qualified-v1", + profileVersion: QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion, + scheduling: "explicit-only", maximumAttemptsPerCell: 1, repetitionsRequired: 1, + permissionDenial: "browser-deny-then-stop-canonical-v1", nativeQuestions: "not-claimed", accounting: "usage-and-cost-unavailable", + lifecycleEvidence: "canonical-runtime-request-and-tool-execution-without-provider-notices-v1", + artifactOracle: "independent-workspace-and-public-download-bytes", stopBoundary: "provider-turn-started" }, + }; +} + +/** + * One admission plus one prompt per exact model ID. The list is a parameter: + * the registered suites use the API-key catalog and the Gemini 4 families, and + * a caller can build another lineup for a different credential route. + */ +export function buildAntigravityModelLineupSuite(deps: Pick, input: { + id: string; label: string; models: readonly string[]; route: string; +}): RunnerSuiteFixture { + if (!input.models.length || new Set(input.models).size !== input.models.length) throw new Error("Antigravity model lineup requires distinct models"); + const base = deps.runnerTasks.find(task => task.id === "message-marker"); + if (!base) throw new Error("Antigravity model lineup requires the ordinary reply fixture"); + const task: RunnerTaskFixture = { ...base, id: ANTIGRAVITY_MODEL_RECEIPT_CASE, label: "Admit the exact model and answer one prompt", + automaticRetryPolicy: "single_attempt", + buildMatchers: (nonce, execution) => [...base.buildMatchers(nonce, execution), ...antigravityModelReceiptMatchers(execution.profile.model)] }; + return { + id: input.id, label: input.label, manualOnly: true, + description: `One admission and one ordinary prompt per ${input.route} model; each cell requires the Runner's exact-model receipt to equal the requested ID.`, + groups: ["native"], + profiles: input.models.map(model => buildAntigravityProfile(deps, model, antigravityLineupProfileId(model))), + environments: [deps.localEnvironment], tasks: [task], expectedMatrixSize: input.models.length, + definitionMetadata: { version: 1, digest: definitionDigest(input.models), route: input.route, models: [...input.models], + runtime: QUALIFIED_ACPX_PROFILES.antigravity.agentServerVersion, qualification: antigravityQualificationStatus(), + receipt: "native-input-requested-and-effective-model-equal-requested-id", scheduling: "explicit-only", maximumAttemptsPerCell: 1 }, + }; +} + diff --git a/tests/runner-e2e/antigravity-qualification.test.ts b/tests/runner-e2e/antigravity-qualification.test.ts new file mode 100644 index 00000000000..139e0a8d048 --- /dev/null +++ b/tests/runner-e2e/antigravity-qualification.test.ts @@ -0,0 +1,309 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { QUALIFIED_ACPX_PROFILES } from "../../packages/paperclip-runner/src/drivers/acpx/qualified-profiles.js"; +import { ANTIGRAVITY_DISTRIBUTION_PINS } from "../../packages/paperclip-runner/src/drivers/acpx/generated-profiles.js"; +import { antigravityCandidateAdmissionForExecution, isAntigravityAdmittedExecution } from "./antigravity-admission.js"; +import { ANTIGRAVITY_API_KEY_LINEUP, ANTIGRAVITY_GEMINI4_LINEUP, antigravityLineupProfileId } from "./antigravity-qualification-cases.js"; +import { runnerMatrix, runnerSuites } from "./catalog.js"; +import { buildRunnerE2EProcessEnvironment, buildPaperclipServerEnvironment } from "./harness-env.js"; +import { evaluateMatchers } from "./matchers.js"; +import { observeActiveStopPending, readActiveStopCaller, readActiveStopSettlement, readDeniedPermissionSettlement } from "./native-active-stop-evidence.js"; +import { assertProviderLossSettlement } from "./native-provider-loss-flow.js"; +import { buildMatrixJobs, daytonaCandidateProviders, parseRunnerSelectors, selectRunnerExecutions } from "./selectors.js"; +import { readRestartRequest } from "./server-restart-request.js"; + +type Row = Record; +const suiteId = "antigravity-qualification"; +const cells = runnerMatrix.filter(cell => cell.suite.id === suiteId); +const companyId = "11111111-1111-4111-8111-111111111111"; +const select = (...args: string[]) => selectRunnerExecutions(parseRunnerSelectors(args)); + +describe("Google Antigravity explicit Product qualification", () => { + it("lists twelve journeys in local and Daytona without entering --all", () => { + expect(cells).toHaveLength(24); + expect(new Set(cells.map(cell => cell.environment.id))).toEqual(new Set(["local", "daytona"])); + expect(new Set(cells.map(cell => cell.task.id))).toEqual(new Set([ + "message-marker", "plan-revise-accept", "ask-question", "structured-question-resume", "structured-question-restart-resume", + "file-edit-validate", "warm-three-turn", "stop-new-resume", "continuity-restart", "pending-permission-stop", "permission-deny-stop", "pending-permission-provider-loss", + ])); + expect(select("--suite", suiteId)).toHaveLength(24); + expect(select("--all").some(cell => cell.profile.qualificationCandidate === "antigravity")).toBe(false); + expect(() => select("--profile", "runner-acpx-antigravity")).toThrow("zero executions"); + expect(runnerSuites.find(suite => suite.id === suiteId)?.definitionMetadata).toMatchObject({ + model: "gemini-3.8-flash-low", authentication: "gemini-api-key", scheduling: "explicit-only", + qualification: QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus === "pending" ? "pending" : "qualified", + }); + }); + + it("reuses the shared lifecycle fixtures on per-turn Daytona leases", () => { + const lifecycle = cells.filter(cell => cell.task.flow === "native_active_stop" || cell.task.flow === "native_provider_loss"); + expect(lifecycle.map(cell => cell.task.id).sort()).toEqual(["pending-permission-provider-loss", "pending-permission-provider-loss", "pending-permission-stop", "pending-permission-stop", "permission-deny-stop", "permission-deny-stop"]); + const cursorLoss = runnerMatrix.find(cell => cell.suite.id === "native-provider-loss" && cell.environment.id === "local")!; + expect(cells.find(cell => cell.task.id === "pending-permission-provider-loss")!.task.buildPrompt("n")).toBe(cursorLoss.task.buildPrompt("n")); + for (const cell of lifecycle.filter(cell => cell.environment.id === "daytona")) expect(cell.environment.configurationKey).toBeUndefined(); + const warmDaytona = cells.find(cell => cell.environment.id === "daytona" && cell.task.id === "message-marker")!; + expect(warmDaytona.environment).not.toBe(lifecycle.find(cell => cell.environment.id === "daytona")!.environment); + }); + + it("binds only the selected encrypted Gemini key on a per-turn native agent", () => { + const ref = { type: "secret_ref" as const, secretId: "22222222-2222-4222-8222-222222222222", version: "latest" as const }; + for (const cell of cells) { + expect(cell.suite.manualOnly).toBe(true); + expect(cell.task.automaticRetryPolicy).toBe("single_attempt"); + expect(cell.requiredCredentials).toEqual(cell.environment.id === "local" ? ["GEMINI_API_KEY"] : ["GEMINI_API_KEY", "DAYTONA_API_KEY"]); + expect(cell.profile).toMatchObject({ id: "runner-acpx-antigravity", qualificationCandidate: "antigravity", model: "gemini-3.8-flash-low", credential: "GEMINI_API_KEY" }); + expect(cell.profile.buildAgent({ executionId: cell.id, environmentId: "env", environmentFixtureId: cell.environment.id, + workspacePath: "/workspace", secretRefs: { GEMINI_API_KEY: ref } })).toMatchObject({ + adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low", + lifecycleMode: "per_turn", timeoutSec: 120, env: { GEMINI_API_KEY: ref } }, + }); + } + }); + + it("admits CI matrix jobs for unattended cells but still refuses the attended journey", () => { + const jobs = buildMatrixJobs(select("--suite", suiteId)); + expect(jobs).toHaveLength(24); + expect(new Set(jobs.map(job => job.credentialName))).toEqual(new Set(["GEMINI_API_KEY"])); + expect(jobs.filter(job => job.needsDaytona)).toHaveLength(12); + expect(() => buildMatrixJobs(select("--suite", "antigravity-agent-journey"))).toThrow("Attended connection journeys"); + }); + + it("asks CI for an Antigravity image and controller pack only for pending Daytona cells", () => { + const pending = QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus === "pending"; + expect(daytonaCandidateProviders(select("--suite", suiteId))).toEqual(pending ? ["antigravity"] : []); + expect(daytonaCandidateProviders(select("--suite", suiteId, "--environment", "local"))).toEqual([]); + // Released providers live in the default pack and are never requested. + expect(daytonaCandidateProviders(select("--id", "rolling-web-deployment.runner-acpx-kimi.daytona.recover-controller"))).toEqual([]); + }); + + it("keeps candidate authority out of the shared operator list and rejects unrelated suites", () => { + const cell = cells[0]!; + const ambient = { PAPERCLIP_RUNNER_ACPX_QUALIFICATION: "ambient", PAPERCLIP_ACPX_CANDIDATE_ADMISSION: "ambient" }; + const env = buildRunnerE2EProcessEnvironment(ambient, cells); + expect(env.PAPERCLIP_RUNNER_ACPX_QUALIFICATION).toBeUndefined(); + expect(env.PAPERCLIP_ACPX_CANDIDATE_ADMISSION).toBeUndefined(); + for (const suite of [{ ...cell.suite, manualOnly: false }, { ...cell.suite, id: "extended-harnesses" }, { ...cell.suite, id: "kimi-qualification" }]) { + expect(() => buildRunnerE2EProcessEnvironment({}, [{ ...cell, suite }])).toThrow("explicit provider qualification suite"); + } + expect(() => buildRunnerE2EProcessEnvironment({}, [{ ...cell, profile: { ...cell.profile, id: "unrelated-profile" } }])).toThrow("explicit provider qualification suite"); + const chat = runnerMatrix.find(row => row.suite.id === "chat-features" && row.profile.qualificationCandidate === "antigravity")!; + expect(isAntigravityAdmittedExecution(chat)).toBe(true); + expect(isAntigravityAdmittedExecution({ ...chat, profile: { ...chat.profile, explicitOnly: undefined } })).toBe(false); + }); + + it("removes ambient Google credentials before starting the product server", () => { + const source = { GEMINI_API_KEY: "selected", GOOGLE_API_KEY: "ambient", GOOGLE_APPLICATION_CREDENTIALS: "/adc.json", GEMINI_HOME: "/login" }; + const server = buildPaperclipServerEnvironment(source); + for (const name of Object.keys(source)) expect(server[name]).toBeUndefined(); + }); +}); + +describe("Antigravity company-bound candidate grant", () => { + const local = cells.find(cell => cell.environment.id === "local")!; + const remote = cells.find(cell => cell.environment.id === "daytona")!; + const pending = QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus === "pending"; + + it.runIf(pending)("binds the disposable company, exact model, digests and darwin-arm64 target", () => { + const now = Date.now(); + expect(antigravityCandidateAdmissionForExecution(local, companyId, now, { platform: "darwin", arch: "arm64" })).toMatchObject({ + schema: "paperclip.acpx-candidate-admission.v1", companyId, agent: "antigravity", model: "gemini-3.8-flash-low", + profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, platform: "darwin", architecture: "arm64", expiresAt: now + 3_600_000, + }); + expect(() => antigravityCandidateAdmissionForExecution(local, "not-a-company")).toThrow("exact disposable company"); + expect(() => antigravityCandidateAdmissionForExecution({ ...local, suite: { ...local.suite, id: "extended-harnesses" } }, companyId)).toThrow("explicit Antigravity suite"); + expect(antigravityCandidateAdmissionForExecution({ ...local, profile: { ...local.profile, qualificationCandidate: "kimi" } }, companyId)).toBeUndefined(); + }); + + it.runIf(pending)("stages a linux-x64 grant with the patched closure for a Daytona cell on any controller host", () => { + const now = Date.now(); + for (const host of [{ platform: "darwin", arch: "arm64" }, { platform: "linux", arch: "x64" }] as const) { + expect(antigravityCandidateAdmissionForExecution(remote, companyId, now, host)).toMatchObject({ + companyId, agent: "antigravity", model: "gemini-3.8-flash-low", platform: "linux", architecture: "x64", + nativeClosureDigest: `sha256:${ANTIGRAVITY_DISTRIBUTION_PINS["linux-x64"].closureSha256}`, expiresAt: now + 3_600_000, + }); + } + }); + + it.runIf(pending)("fails before provider spend on a target without an admitted closure", () => { + expect(() => antigravityCandidateAdmissionForExecution(local, companyId, Date.now(), { platform: "win32", arch: "x64" })).toThrow(/no admitted runtime closure|does not match/i); + }); + + it.runIf(pending)("stages the grant only for a selected Antigravity cell and its model", async () => { + const root = await mkdtemp(join(tmpdir(), "antigravity-restart-")); + try { + const path = join(root, "request.json"), grant = antigravityCandidateAdmissionForExecution(local, companyId, Date.now(), process)!; + if (`${process.platform}-${process.arch}` !== "darwin-arm64") return; + await writeFile(path, JSON.stringify({ requestId: "antigravity-startup", kimiCandidateAdmission: grant })); + await expect(readRestartRequest(path, [local.id])).resolves.toMatchObject({ kimiCandidateAdmission: { agent: "antigravity", companyId } }); + await expect(readRestartRequest(path, [runnerMatrix.find(cell => cell.suite.id === "kimi-qualification")!.id])).rejects.toThrow("explicit Kimi or Antigravity"); + await writeFile(path, JSON.stringify({ requestId: "antigravity-startup", kimiCandidateAdmission: { ...grant, model: "gemini-3.1-pro-low" } })); + await expect(readRestartRequest(path, [local.id])).rejects.toThrow("does not match the selected execution"); + } finally { await rm(root, { recursive: true, force: true }); } + expect(remote.environment.expectedExecutionTarget.kind).toBe("remote"); + }); + + it.runIf(!pending)("needs no grant once the profile is released", () => { + expect(antigravityCandidateAdmissionForExecution(local, companyId)).toBeUndefined(); + }); +}); + +describe("Antigravity model lineups", () => { + it("parameterises one exact-model cell per API-key and Gemini 4 model", () => { + for (const [suite, models] of [["antigravity-model-lineup", ANTIGRAVITY_API_KEY_LINEUP], ["antigravity-model-lineup-gemini4", ANTIGRAVITY_GEMINI4_LINEUP]] as const) { + const lineup = runnerMatrix.filter(cell => cell.suite.id === suite); + expect(lineup.map(cell => cell.profile.model)).toEqual(models); + expect(lineup.every(cell => cell.environment.id === "local" && cell.task.id === "model-receipt" && cell.id === `${suite}.${antigravityLineupProfileId(cell.profile.model)}.local.model-receipt`)).toBe(true); + expect(lineup.every(cell => cell.id.split(".").length === 4)).toBe(true); + expect(select("--suite", suite)).toHaveLength(models.length); + expect(lineup.every(isAntigravityAdmittedExecution)).toBe(true); + 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). + 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-argon-high", "gemini-4-argon-medium", "gemini-4-argon-low", + ]); + expect(() => antigravityLineupProfileId("auto")).toThrow("Invalid Antigravity model ID"); + }); + + it("requires the Runner's exact-model receipt, not merely a reply", async () => { + const cell = runnerMatrix.find(row => row.suite.id === "antigravity-model-lineup-gemini4" && row.profile.model === "gemini-4-neon-high")!; + const receiptMatchers = cell.task.buildMatchers("nonce", cell).filter(matcher => matcher.kind === "json_path"); + expect(receiptMatchers).toHaveLength(4); + const run = (effectiveModel: string) => ({ runnerProfileJson: { nativeExecutionInput: { provider: { kind: "acpx", agent: "antigravity", model: "gemini-4-neon-high" } }, + sessionCheckpoint: { providerIdentity: { requestedModel: "gemini-4-neon-high", effectiveModel } } } }); + const grade = (value: Row) => evaluateMatchers(receiptMatchers, { message: "", json: { run: value } } as never); + expect((await grade(run("gemini-4-neon-high"))).every(result => result.passed)).toBe(true); + expect((await grade(run("gemini-4-neon-low"))).every(result => result.passed)).toBe(false); + expect((await grade({})).some(result => result.passed)).toBe(false); + }); +}); + +describe("Antigravity opt-in profiles in shared eval suites", () => { + it.each(["chat-features", "native-completion"])("%s keeps Antigravity behind an explicit profile selector", suite => { + const all = select("--suite", suite); + expect(all.some(cell => cell.profile.qualificationCandidate === "antigravity")).toBe(false); + const opted = select("--suite", suite, "--profile", "runner-acpx-antigravity"); + expect(opted.length).toBeGreaterThan(0); + expect(opted.every(cell => cell.profile.qualificationCandidate === "antigravity" && cell.profile.explicitOnly === true)).toBe(true); + expect(() => buildRunnerE2EProcessEnvironment({}, opted.slice(0, 1))).not.toThrow(); + }); +}); + +describe("Antigravity pending-permission lifecycle evidence", () => { + const caller = readActiveStopCaller({ deploymentMode: "local_trusted" }, { session: { userId: "local-board", id: "paperclip:local_implicit:local-board" } }); + const cancellationRequestId = "11111111-2222-4333-8444-555555555555"; + function fixture() { + const scope = { provider: "antigravity" as const, companyId: "company", issueId: "issue", runId: "run", target: "pc-denied/active-stop.txt" }; + const row = (eventType: string, payload: Row): Row => { + const seq = events.length + 1; + return { companyId: "company", runId: "run", seq, eventType, protocolSchemaVersion: 1, + payload: { prpEvent: { schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", eventType, runId: "run", turnId: "turn", + normalizedSessionId: "session", sourceInstanceId: "runner", sourceSeq: seq, sourceEventId: `runner:run:${seq}`, emittedAt: "2026-11-22T00:00:00Z", payload } } }; + }; + const tool = (executionId: string, operation: string, target: string | null, status = "running") => ({ schema: "paperclip.tool.execution.v1", executionId, transport: "builtin", name: null, operation, target, status }); + const events: Row[] = []; + const push = (eventType: string, payload: Row) => { events.push(row(eventType, payload)); }; + push("tool.execution.started", tool("read-1", "read", "README.md")); + push("tool.execution.completed", tool("read-1", "read", "README.md", "completed")); + push("tool.execution.started", tool("write-1", "edit", scope.target)); + push("runtime_request.created", { request: { schema: "paperclip.runtime_request.v2", type: "permission", requestKind: "permission_approval", status: "pending", + requestId: "request", turnId: "turn", itemId: "item", prompt: `Edit ${scope.target}`, details: { toolCallId: "write-1" }, + choices: [{ key: "accept" }, { key: "decline" }], origin: { adapter: "acpx-runtime-sidecar", provider: "antigravity", method: "session/request_permission" } } }); + const run: Row = { id: "run", companyId: "company", nativeIssueId: "issue", runtimeMode: "native", status: "running", resultJson: {}, error: null }; + const issue: Row = { id: "issue", companyId: "company", status: "in_progress" }; + const observe = () => observeActiveStopPending({ events, run, issue, scope, caller, cancellationRequestId }); + return { scope, events, run, issue, push, tool, observe }; + } + + it("observes the exact pending native edit from canonical events alone", () => { + const f = fixture(); + expect(f.observe()).toMatchObject({ requestId: "request", toolCallId: "write-1", turnId: "turn", normalizedSessionId: "session" }); + }); + + it("rejects an extra mutation, a completed write, a foreign provider or a missing target", () => { + const extra = fixture(); extra.events.splice(2, 0, ...[]); extra.push("tool.execution.started", extra.tool("write-2", "edit", "other.txt")); + expect(() => extra.observe()).toThrow(/extra native operation/); + const done = fixture(); done.push("tool.execution.completed", done.tool("write-1", "edit", done.scope.target, "completed")); + expect(() => done.observe()).toThrow(/mutation lifecycle/); + const foreign = fixture(); foreign.events[3]!.payload.prpEvent.payload.request.origin.provider = "cursor"; + expect(() => foreign.observe()).toThrow(/permission identity/); + const elsewhere = fixture(); elsewhere.events[2]!.payload.prpEvent.payload.target = null; elsewhere.events[3]!.payload.prpEvent.payload.request.prompt = "Edit file"; + expect(() => elsewhere.observe()).toThrow(/mutation lifecycle/); + }); + + it("requires cancellation of the retained request for Stop and expiry for provider loss", () => { + const stop = fixture(), pending = stop.observe(), dispatchMonotonicNs = (BigInt(pending.observedMonotonicNs) + 1n).toString(); + stop.push("runtime_request.cancelled", { requestId: "request", requestKind: "permission_approval", turnId: "turn", itemId: "item", reason: "turn_terminal" }); + stop.push("turn.cancelled", { status: "cancelled", error: null }); + expect(() => readActiveStopSettlement({ events: stop.events, run: stop.run, issue: stop.issue, pending, dispatchMonotonicNs })).toThrow(/acknowledgement/); + stop.run.status = "cancelled"; + stop.run.resultJson = { startupCancellation: { cancellationRequestId, requestedBy: { type: "board", userId: "local-board" } }, nativeCancellation: { + schema: "paperclip.native-cancellation.v1", intentId: `native-cancellation:${cancellationRequestId}`, companyId: "company", runId: "run", issueId: "issue", scope: "run", + dispatched: true, dispatchState: "acknowledged", reasonCode: "cancellation_run_only", effects: ["release_run_resources"], intentAuditId: "intent", acknowledgementAuditId: "ack" } }; + expect(readActiveStopSettlement({ events: stop.events, run: stop.run, issue: stop.issue, pending, dispatchMonotonicNs })).toMatchObject({ branch: "pending_permission_cancelled", replayAllowed: false }); + + const loss = fixture(), lost = loss.observe(); + loss.push("runtime_request.expired", { requestId: "request", requestKind: "permission_approval", turnId: "turn", reason: "provider_process_lost", replayAllowed: false }); + loss.push("turn.failed", { error: { code: "provider_transport_lost" } }); + Object.assign(loss.run, { status: "failed", error: "Provider transport lost" }); loss.issue.status = "blocked"; + expect(assertProviderLossSettlement(loss.run, loss.issue, loss.events, lost)).toMatchObject({ requestClosure: "runtime_request.expired", replayAllowed: false }); + loss.push("tool.execution.completed", loss.tool("write-1", "edit", loss.scope.target, "completed")); + expect(() => assertProviderLossSettlement(loss.run, loss.issue, loss.events, lost)).toThrow(/completed mutation/); + }); + + it("requires a delivered decline of the exact request, no completed mutation and the operator's Stop", () => { + const acknowledged = (run: Row) => Object.assign(run, { status: "cancelled", resultJson: { + startupCancellation: { cancellationRequestId, requestedBy: { type: "board", userId: "local-board" } }, nativeCancellation: { + schema: "paperclip.native-cancellation.v1", intentId: `native-cancellation:${cancellationRequestId}`, companyId: "company", runId: "run", issueId: "issue", scope: "run", + dispatched: true, dispatchState: "acknowledged", reasonCode: "cancellation_run_only", effects: ["release_run_resources"], intentAuditId: "intent", acknowledgementAuditId: "ack" } } }); + const denied = () => { + const f = fixture(), pending = f.observe(); + f.push("runtime_request.resolved", { requestId: "request", requestKind: "permission_approval", turnId: "turn", itemId: "item", action: "decline" }); + f.push("tool.execution.completed", f.tool("write-1", "edit", f.scope.target, "failed")); + return { ...f, pending }; + }; + const stopped = denied(); + stopped.push("turn.cancelled", { status: "cancelled", error: null }); acknowledged(stopped.run); + expect(readDeniedPermissionSettlement({ events: stopped.events, run: stopped.run, issue: stopped.issue, pending: stopped.pending, stopDispatched: true })) + .toMatchObject({ branch: "denied_then_stopped", requestId: "request", replayAllowed: false }); + // A cancellation nobody asked for is not this journey. + expect(() => readDeniedPermissionSettlement({ events: stopped.events, run: stopped.run, issue: stopped.issue, pending: stopped.pending, stopDispatched: false })).toThrow(/without the operator's Stop/); + + const finished = denied(); + finished.push("turn.completed", { status: "completed" }); finished.run.status = "succeeded"; + expect(readDeniedPermissionSettlement({ events: finished.events, run: finished.run, issue: finished.issue, pending: finished.pending, stopDispatched: false })) + .toMatchObject({ branch: "denied_then_finished" }); + finished.issue.status = "done"; + expect(() => readDeniedPermissionSettlement({ events: finished.events, run: finished.run, issue: finished.issue, pending: finished.pending, stopDispatched: false })).toThrow(/claims completion/); + + const accepted = fixture(), acceptedPending = accepted.observe(); + accepted.push("runtime_request.resolved", { requestId: "request", requestKind: "permission_approval", turnId: "turn", itemId: "item", action: "accept" }); + accepted.push("turn.cancelled", { status: "cancelled", error: null }); acknowledged(accepted.run); + expect(() => readDeniedPermissionSettlement({ events: accepted.events, run: accepted.run, issue: accepted.issue, pending: acceptedPending, stopDispatched: true })).toThrow(/denial was not delivered/); + + const cancelledOnly = fixture(), cancelledPending = cancelledOnly.observe(); + cancelledOnly.push("runtime_request.cancelled", { requestId: "request", requestKind: "permission_approval", turnId: "turn", itemId: "item", reason: "turn_terminal" }); + cancelledOnly.push("turn.cancelled", { status: "cancelled", error: null }); acknowledged(cancelledOnly.run); + expect(() => readDeniedPermissionSettlement({ events: cancelledOnly.events, run: cancelledOnly.run, issue: cancelledOnly.issue, pending: cancelledPending, stopDispatched: true })).toThrow(/denial was not delivered/); + + const written = denied(); + written.events.pop(); written.push("tool.execution.completed", written.tool("write-1", "edit", written.scope.target, "completed")); + written.push("turn.cancelled", { status: "cancelled", error: null }); acknowledged(written.run); + expect(() => readDeniedPermissionSettlement({ events: written.events, run: written.run, issue: written.issue, pending: written.pending, stopDispatched: true })).toThrow(); + }); +}); diff --git a/tests/runner-e2e/catalog.test.ts b/tests/runner-e2e/catalog.test.ts index b6ab0a85b76..63ab5d62146 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, 9, 2, 9, 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, 2, 2, 1, 6, 8, 46, 2, 23, 15, 68, 6, 6, 20, 26, 2, 56, 1, 247, 28, 18, 2, 6, 6, 13, 10, 4, 48, 16, 10, 2, 1, 1, 4, 116, 2, 1, 2, + 1, 9, 2, 9, 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, 2, ]); - expect(validateRunnerCatalog()).toHaveLength(1089); + expect(validateRunnerCatalog()).toHaveLength(1387); 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(1089); + expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(1387); expect( runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"), ).toHaveLength(48); diff --git a/tests/runner-e2e/catalog.ts b/tests/runner-e2e/catalog.ts index 28d4b024e65..dca73379ffc 100644 --- a/tests/runner-e2e/catalog.ts +++ b/tests/runner-e2e/catalog.ts @@ -12,7 +12,8 @@ import { caseReceiptTask, caseReceiptDefinitionDigest, CASE_RECEIPT_BUDGET_CENTS import { TASK_WORKSPACES_SUITE, taskWorkspaceTask, taskWorkspaceProfile, taskWorkspaceDefinitionDigest } from "./task-workspaces-cases.js"; import { repositoryProofTasks, repositoryProofProfile, repositoryProofDigest } from "./repository-verification.js"; import { automaticRepositoryTask, automaticRepositoryDigest } from "./automatic-repository.js"; -import { nativeActiveStopTasks } from "./native-active-stop-tasks.js"; +import { nativeActiveStopTasks, nativeProviderLossTasks } from "./native-active-stop-tasks.js"; +import { ANTIGRAVITY_API_KEY_LINEUP, ANTIGRAVITY_GEMINI4_LINEUP, ANTIGRAVITY_GEMINI4_LINEUP_SUITE, ANTIGRAVITY_MODEL_LINEUP_SUITE, buildAntigravityModelLineupSuite, buildAntigravityProfile, buildAntigravityQualificationSuite, type AntigravitySuiteDependencies } from "./antigravity-qualification-cases.js"; import { CURSOR_CLOUD_SUITE, cursorCloudArtifactTask, cursorCloudStopTask, CURSOR_CLOUD_QUIET_WINDOW_MS, cursorCloudDefinitionDigest } from "./cursor-cloud-cases.js"; import { kimiLifecycleTasks } from "./kimi-lifecycle-tasks.js"; import { piControlTasks } from "./pi-controls-cases.js"; @@ -211,7 +212,7 @@ function nativeProfile(input: { provider: "codex" | "opencode" | "acpx"; model: string; credential: RunnerProfileFixture["credential"]; - acpxAgent?: "claude" | "codex" | "grok" | "cursor" | "copilot" | "pi" | "kimi"; + acpxAgent?: "claude" | "codex" | "grok" | "cursor" | "copilot" | "pi" | "kimi" | "antigravity"; qualificationCandidate?: RunnerProfileFixture["qualificationCandidate"]; supportedEnvironments?: readonly (typeof ENVIRONMENT_IDS)[number][]; modelQualification?: RunnerProfileFixture["modelQualification"]; @@ -1262,6 +1263,24 @@ export const kimiRunnerProfile = nativeProfile({ modelQualification: { source: "qualified_runner_profile", qualificationId: "kimi:2.3.3:native-qualified-profile17" }, }); +const antigravitySuiteDependencies: AntigravitySuiteDependencies = { + nativeProfile, localEnvironment, daytonaWarmEnvironment, + daytonaEnvironment: runnerEnvironments.find(environment => environment.id === "daytona")!, + runnerTasks, localIntegrityTasks, extendedHarnessFileTask, chatHardeningTasks, nativeActiveStopTasks, nativeProviderLossTasks, + // Workspace-file continuity: ACP collects changed agent files only after + // provider retirement, so the managed-home variant is not used here. + warmFollowupTask: { ...daytonaWarmContinuityTask, + buildPrompt: nonce => warmTurnInstructions(1, nonce), + buildFollowupMessages: nonce => [warmTurnInstructions(2, nonce), warmTurnInstructions(3, nonce)], + turnTimeoutMs: 120_000, attemptTimeoutMs: { local: 420_000, daytona: 420_000 } }, +}; +/** Google Antigravity through a Gemini API key; pending until the qualification flip. */ +export const antigravityRunnerProfile = buildAntigravityProfile(antigravitySuiteDependencies); +/** Chat evals under Antigravity are opt-in: name the profile explicitly. */ +const antigravityChatProfile: RunnerProfileFixture = { ...chatFeatureProfile(antigravityRunnerProfile), explicitOnly: true }; +/** Instructions and assigned skills under the production default; opt-in by profile. */ +const antigravityNativeCompletionProfile: RunnerProfileFixture = { ...nativeCompletionProfile(antigravityRunnerProfile), explicitOnly: true }; + /** * ACPX facades admitted only for the reliability long-silent-command case. Like the * rolling-deployment matrix, they run as ordinary released profiles: a pending @@ -1299,7 +1318,7 @@ function everydayReliabilityExcludedIds(suiteId: string): string[] { } -const rollingDeploymentProfiles = [...runnerProfiles, ...extendedHarnessProfiles, kimiRunnerProfile] +const rollingDeploymentProfiles = [...runnerProfiles, ...extendedHarnessProfiles, kimiRunnerProfile, antigravityRunnerProfile] .filter(profile => profile.generation === "native" && profile.supportedEnvironments.includes("daytona") && (!profile.qualificationCandidate || QUALIFIED_ACPX_PROFILES[profile.qualificationCandidate].qualificationStatus !== "pending")) .map(original => { @@ -1585,15 +1604,7 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [ description: "Lose the owned Cursor runtime while a native mutation remains unanswered; require a visible failed run, closed unanswerable input, stale-answer refusal and independent retirement with no effects or replay.", groups: ["native"], profiles: extendedHarnessProfiles.filter(profile => profile.qualificationCandidate === "cursor"), environments: runnerEnvironments, - tasks: [{ - id: "pending-permission-provider-loss", label: "Owned runtime loss with pending permission", groups: [], workMode: "standard", flow: "native_provider_loss", - expectedRunCount: 1, attemptTimeoutMs: { local: 300_000, daytona: 300_000 }, turnTimeoutMs: 120_000, - expectedTerminalState: { issue: "blocked", run: "failed" }, - buildTitle: nonce => `Native provider loss ${nonce}`, - buildVisibleMarker: nonce => `NATIVE-PROVIDER-LOSS-${nonce}`, - buildPrompt: () => "Attempt the supplied exact native shell operation once and leave its permission callback unanswered. Do not retry, use another tool or path, answer your own permission, call paperclip_finish, or claim completion. The qualification fixture will deliberately lose the isolated runtime before any approval.", - buildMatchers: () => [], - }], expectedMatrixSize: 2, + tasks: nativeProviderLossTasks, expectedMatrixSize: 2, definitionMetadata: { version: 1, qualification: "pending", scheduling: "explicit-only", fault: "observed-per-turn-run-root-loss", remoteFaultAuthority: "pidfd-start-ticks-boot-id", replayAllowed: false }, }, @@ -1672,6 +1683,11 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [ remoteLifecycleBootstrap: "observer-bound-scoped-get-task-context-dual-turn-workspace-binding-full-semantic-command-ack-and-bounded-native-receipt", nativeWriteLifecycle: "pending-permission-stop-and-exact-native-worker-loss", nativeWriteCleanup: "continuous-no-effects-through-owned-tree-retirement" }, }, + buildAntigravityQualificationSuite(antigravitySuiteDependencies), + buildAntigravityModelLineupSuite(antigravitySuiteDependencies, { id: ANTIGRAVITY_MODEL_LINEUP_SUITE, label: "Google Antigravity API-key model lineup", + models: ANTIGRAVITY_API_KEY_LINEUP, route: "gemini-api-key" }), + buildAntigravityModelLineupSuite(antigravitySuiteDependencies, { id: ANTIGRAVITY_GEMINI4_LINEUP_SUITE, label: "Google Antigravity Gemini 4 model lineup", + models: ANTIGRAVITY_GEMINI4_LINEUP, route: "gemini-4 (billed key, subscription or Agent Platform)" }), { id: "api-response-reading", label: "Bounded API response reading", manualOnly: true, description: "Retrieve evidence beyond a saved API preview through authorized bounded text windows.", @@ -1808,8 +1824,8 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [ id: "native-completion", label: "Native completion guidance", manualOnly: true, description: "Production-default assigned-skill document completion and concrete whole-task blocking, with independent native result/final ordering.", groups: ["native", "local"], - profiles: runnerProfiles.filter(profile => ["runner-codex", "runner-acpx-claude", "runner-opencode"].includes(profile.id)).map(nativeCompletionProfile), - environments: [localEnvironment], tasks: nativeCompletionTasks, expectedMatrixSize: 6, + profiles: [...runnerProfiles.filter(profile => ["runner-codex", "runner-acpx-claude", "runner-opencode"].includes(profile.id)).map(nativeCompletionProfile), antigravityNativeCompletionProfile], + environments: [localEnvironment], tasks: nativeCompletionTasks, expectedMatrixSize: 8, definitionMetadata: { version: 1, fixtureDigest: nativeCompletionDefinitionDigest(), instructions: "unchanged-master-production-default", providerTurns: 6, maximumAttemptsPerCell: 1, automaticRetryPolicy: "single_attempt", budgetMonthlyCents: NATIVE_COMPLETION_BUDGET_CENTS, grading: "original-assigned-skill-durable-document-plus-native-disposition-and-observable-final-order", scheduling: "explicit-only" }, @@ -1892,8 +1908,8 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [ profiles: [chatFeatureExecutionProfile, chatFeatureProfile(nativeProfile({ id: "runner-codex-subscription", label: "Native Codex subscription", provider: "codex", model: DEFAULT_CODEX_LOCAL_MODEL, credential: "CODEX_AUTH_JSON", supportedEnvironments: ["local"] })), - chatFeatureProfile(runnerOpenCodeDeepSeek1017Profile)], - environments: [localEnvironment], tasks: [...chatFeatureTasks, ...chatCatalogTasks], expectedMatrixSize: 5 + chatCatalogTasks.length, + chatFeatureProfile(runnerOpenCodeDeepSeek1017Profile), antigravityChatProfile], + environments: [localEnvironment], tasks: [...chatFeatureTasks, ...chatCatalogTasks], expectedMatrixSize: 5 + chatCatalogTasks.length + chatFeatureTasks.length + chatCatalogTasks.length, excludedExecutionIds: [ ...chatCatalogTasks.map(task => `chat-features.runner-codex-subscription.local.${task.id}`), ...[...chatFeatureTasks, ...chatCatalogTasks].filter(task => task.id !== "create-backlog").map(task => `chat-features.runner-opencode-deepseek-1017.local.${task.id}`), diff --git a/tests/runner-e2e/chat-catalog-contract.test.ts b/tests/runner-e2e/chat-catalog-contract.test.ts index e3216b8d7b1..4a24ac46064 100644 --- a/tests/runner-e2e/chat-catalog-contract.test.ts +++ b/tests/runner-e2e/chat-catalog-contract.test.ts @@ -15,7 +15,8 @@ describe("catalog oracle contract", () => { }); it("discovers each concrete implementation explicitly with its exact query and bounds", () => { for (const implementation of chatCatalogCases) { - const cells = runnerMatrix.filter(cell => cell.suite.id === "chat-features" && cell.task.id === implementation.scenarioId); + // Opt-in harness profiles (for example Antigravity) add separately selected cells. + const cells = runnerMatrix.filter(cell => cell.suite.id === "chat-features" && !cell.profile.explicitOnly && cell.task.id === implementation.scenarioId); expect(cells).toHaveLength(1); const cell = cells[0]!; expect(cell.task.buildPrompt("nonce")).toBe(chatCatalogScenarios.find(row => row.id === implementation.scenarioId)!.query); diff --git a/tests/runner-e2e/chat-feature-scoring.test.ts b/tests/runner-e2e/chat-feature-scoring.test.ts index 34ff363b530..d88618a036c 100644 --- a/tests/runner-e2e/chat-feature-scoring.test.ts +++ b/tests/runner-e2e/chat-feature-scoring.test.ts @@ -109,7 +109,7 @@ describe("chat feature saved-state oracle", () => { describe("chat feature selection", () => { it("preserves the historical OpenCode aliases beside the two shipped subscription cells", () => { - const cells = runnerMatrix.filter(cell => cell.suite.id === "chat-features" && cell.profile.id !== "runner-opencode-deepseek-1017" && ["create-backlog", "delegate-announcement"].includes(cell.task.id)); + const cells = runnerMatrix.filter(cell => cell.suite.id === "chat-features" && cell.profile.id !== "runner-opencode-deepseek-1017" && !cell.profile.explicitOnly && ["create-backlog", "delegate-announcement"].includes(cell.task.id)); expect(cells).toHaveLength(4); const historical = cells.filter(cell => cell.profile.id === "runner-opencode"); expect(historical.map(cell => cell.profile.model)).toEqual([CHAT_OPENCODE_MODEL, CHAT_OPENCODE_MODEL]); diff --git a/tests/runner-e2e/chat-flow.ts b/tests/runner-e2e/chat-flow.ts index a28515d5ab7..48f7cfbdf3b 100644 --- a/tests/runner-e2e/chat-flow.ts +++ b/tests/runner-e2e/chat-flow.ts @@ -427,7 +427,7 @@ export async function runChatFlow(input: ChatFlowInput) { let issue: ChatIssue; let runs: ChatRun[] = []; let catalogFinalRunVerifier: ChatCatalogFinalRunVerifier | void = undefined; - const admissionAccounting = execution.suite.id === "kimi-qualification" && caseId === "stop-new-resume" && execution.profile.generation === "native"; + const admissionAccounting = ["kimi-qualification", "antigravity-qualification"].includes(execution.suite.id) && caseId === "stop-new-resume" && execution.profile.generation === "native"; let admissionWaits: ChatAdmissionWait[] = []; let stoppedForSessionReset: string | undefined; // A catalog task's queued run retired by reassignment before it started, with diff --git a/tests/runner-e2e/copilot-provider-death.test.ts b/tests/runner-e2e/copilot-provider-death.test.ts index 119c4ce8bef..c8e81bf377c 100644 --- a/tests/runner-e2e/copilot-provider-death.test.ts +++ b/tests/runner-e2e/copilot-provider-death.test.ts @@ -5,7 +5,7 @@ import { canonicalRemoteCopilotCommand, copilotDeathArguments, selectOwnedCopilo describe("owned Copilot provider death selector", () => { const root = { pid: 10, parent: 1 }, sidecar = { pid: 11, parent: 10 }, native = { pid: 12, parent: 11 }; - const argv = ["/private/paperclip-acpx-native-owned/distribution/copilot", ...copilotDeathArguments]; + const argv = ["/private/paperclip-verified-native-501/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee/distribution/copilot", ...copilotDeathArguments]; it("selects only the native child of the live owned run", () => { expect(selectOwnedCopilotProcess(10, [root, sidecar, native], [10, 11, 12], new Map([[12, argv]]))).toEqual(native); }); @@ -27,6 +27,11 @@ describe("owned Copilot provider death selector", () => { expect(() => selectOwnedCopilotProcess(10, [root, sidecar, native], [10, 11, 12], new Map([[12, canonical]]))).toThrow(); } }); + it("targets only Copilot from the sealed verified store, not a per-launch or foreign copy", () => { + for (const executable of ["/private/paperclip-acpx-native-owned/distribution/copilot", "/private/paperclip-verified-native-501/short/distribution/copilot", "/private/elsewhere/distribution/copilot"]) { + expect(() => selectOwnedCopilotProcess(10, [root, sidecar, native], [10, 11, 12], new Map([[12, [executable, ...copilotDeathArguments]]]))).toThrow(); + } + }); it("refuses foreign, retired, ambiguous and caller-selected processes", () => { const commands = new Map([[12, argv]]); expect(() => selectOwnedCopilotProcess(10, [root, sidecar, { ...native, parent: 99 }], [10, 11, 12], commands)).toThrow(); diff --git a/tests/runner-e2e/copilot-provider-death.ts b/tests/runner-e2e/copilot-provider-death.ts index 0900c613f36..addfa7eb778 100644 --- a/tests/runner-e2e/copilot-provider-death.ts +++ b/tests/runner-e2e/copilot-provider-death.ts @@ -8,6 +8,8 @@ import type { BootstrapReadProof } from "./native-bootstrap-read-proof.js"; import type { ActiveStopPending } from "./copilot-active-stop-evidence.js"; /** Closed selector shared by local and remote observers. It accepts no caller PID. + * Copilot runs from the runner's sealed verified store (`//distribution/copilot`); + * the regex is inline because this function is serialized into the remote observer. * Only a live native executable under an already owned run root is eligible. */ export function selectOwnedCopilotProcess( rootPid: number, journal: readonly T[], live: readonly number[], argv: ReadonlyMap, fixedArguments: readonly string[] = COPILOT_LAUNCH_ARGUMENTS, @@ -17,7 +19,7 @@ export function selectOwnedCopilotProcess { if (row.pid === rootPid || !live.includes(row.pid)) return false; const command = argv.get(row.pid); - if (!command || command.length !== fixedArguments.length + 1 || !/^\/[^\u0000-\u0020]*\/paperclip-acpx-native-[A-Za-z0-9_-]+\/distribution\/copilot$/u.test(command[0] ?? "") || !fixedArguments.every((arg, i) => command[i + 1] === arg)) return false; + if (!command || command.length !== fixedArguments.length + 1 || !/^\/[^\u0000-\u0020]*\/paperclip-verified-native-[A-Za-z0-9_-]+\/[a-f0-9]{64}\/distribution\/copilot$/u.test(command[0] ?? "") || !fixedArguments.every((arg, i) => command[i + 1] === arg)) return false; const seen = new Set(); let parent = row.parent; while (parent !== rootPid) { if (seen.has(parent) || !live.includes(parent)) return false; @@ -38,7 +40,7 @@ export function canonicalRemoteCopilotCommand( executableIdentity: { dev: string; ino: string }, descriptor?: { path: string; dev: string; ino: string }, ): readonly string[] { - if (!/^\/[^\u0000-\u0020]*\/paperclip-acpx-native-[A-Za-z0-9_-]+\/distribution\/copilot$/u.test(executable)) return command; + if (!/^\/[^\u0000-\u0020]*\/paperclip-verified-native-[A-Za-z0-9_-]+\/[a-f0-9]{64}\/distribution\/copilot$/u.test(executable)) return command; if (command[0] === executable) return command; if (!/^\/proc\/self\/fd\/(?:3|7)$/u.test(command[0] ?? "") || !descriptor || descriptor.path !== executable || descriptor.dev !== executableIdentity.dev || descriptor.ino !== executableIdentity.ino) return command; diff --git a/tests/runner-e2e/daytona-image-content.ts b/tests/runner-e2e/daytona-image-content.ts index 9b69aa4f3be..a32fa57245a 100644 --- a/tests/runner-e2e/daytona-image-content.ts +++ b/tests/runner-e2e/daytona-image-content.ts @@ -106,7 +106,7 @@ export interface DaytonaImageContentOptions { export function normalizedDaytonaCandidateProviders(values: readonly string[]): string[] { const selected = [...values].sort(); - if (selected.some(value => !["cursor", "copilot", "pi", "kimi"].includes(value)) + if (selected.some(value => !["cursor", "copilot", "pi", "kimi", "antigravity"].includes(value)) || new Set(selected).size !== selected.length) { throw new Error("Daytona candidate providers must be distinct known ACP profiles"); } diff --git a/tests/runner-e2e/harness-env.ts b/tests/runner-e2e/harness-env.ts index 47759191876..31e587b31b0 100644 --- a/tests/runner-e2e/harness-env.ts +++ b/tests/runner-e2e/harness-env.ts @@ -9,6 +9,7 @@ import path from "node:path"; import { isEvalRemoteOrigin } from "./eval-remote-gateway.js"; import { chatNeedsApiTools, isManagedHiringCase } from "./chat-cases.js"; import { CREDENTIAL_NAMES } from "./types.js"; +import { isAntigravityAdmittedExecution } from "./antigravity-admission.js"; import type { MatrixExecution } from "./types.js"; const DATABASE_KEYS = ["DATABASE_URL", "DATABASE_MIGRATION_URL", "PAPERCLIP_RUNNER_E2E_POSTGRES_ADMIN_URL"] as const; @@ -38,7 +39,7 @@ const AMBIENT_EXTERNAL_STATE_KEYS = [ "PAPERCLIP_STORAGE_S3_PREFIX", "PAPERCLIP_STORAGE_S3_FORCE_PATH_STYLE", ] as const; -const PROVIDER_SECRET_KEY = /^(?:OPENAI|ANTHROPIC|OPENROUTER|BRAINTRUST|DAYTONA|XAI|GROK|KIMI|CURSOR|COPILOT|GITHUB|GH)(?:_|$)/; +const PROVIDER_SECRET_KEY = /^(?:OPENAI|ANTHROPIC|OPENROUTER|BRAINTRUST|DAYTONA|XAI|GROK|KIMI|CURSOR|COPILOT|GITHUB|GH|GEMINI|GOOGLE)(?:_|$)/; /** Vault SDK authority is never ambient chat input. An explicitly selected * server-only vault handoff supplies its own finite overrides after scrubbing. */ @@ -176,6 +177,8 @@ export function buildRunnerE2EProcessEnvironment( if (!agent) continue; const admittedSuite = agent === "kimi" ? execution.suite.id === "kimi-qualification" && execution.profile.id === "runner-acpx-kimi" + : agent === "antigravity" + ? isAntigravityAdmittedExecution(execution) : execution.suite.id === "extended-harnesses" || execution.suite.id === "rich-acp-warm-continuity" || (execution.suite.id === "pi-native" && agent === "pi") @@ -189,7 +192,9 @@ export function buildRunnerE2EProcessEnvironment( if (QUALIFIED_ACPX_PROFILES[agent].qualificationStatus !== "pending") { continue; } - if (agent === "kimi") continue; + // Kimi and Antigravity receive a company-bound grant per cell, never the + // shared operator list (server-restart-request.ts). + if (agent === "kimi" || agent === "antigravity") continue; const prior = candidates.get(agent); if (prior !== undefined && prior !== execution.profile.model) throw new Error("Conflicting candidate models"); candidates.set(agent, execution.profile.model); diff --git a/tests/runner-e2e/journey-features.ts b/tests/runner-e2e/journey-features.ts index 5c0386a76c9..28ba799d690 100644 --- a/tests/runner-e2e/journey-features.ts +++ b/tests/runner-e2e/journey-features.ts @@ -38,7 +38,7 @@ associate(["antigravity-agent-journey"], { "saved-subscription-two-turn": ["agents/hire", "agents/instructions", "runs-adapters/validation", "runs-adapters/session", "tasks/create", "tasks/completion", "documents-artifacts/attachments", "documents-artifacts/work-products"], }); -associate(["core-compatibility", "openrouter-model-breadth", "extended-harnesses", "grok-qualification", "grok-subscription-qualification", "kimi-qualification"], { +associate(["core-compatibility", "openrouter-model-breadth", "extended-harnesses", "grok-qualification", "grok-subscription-qualification", "kimi-qualification", "antigravity-qualification"], { "message-marker": ["runs-adapters/runs"], "hello-complete": ["runs-adapters/runs"], "plan-revise-accept": ["questions-and-approvals/plan-review"], @@ -46,7 +46,7 @@ associate(["core-compatibility", "openrouter-model-breadth", "extended-harnesses "ask-question": ["questions-and-approvals/questions"], "question-resume-complete": ["questions-and-approvals/questions", "questions-and-approvals/continuation"], }); -associate(["local-session-integrity", "extended-harnesses", "grok-qualification", "grok-subscription-qualification", "kimi-qualification"], { +associate(["local-session-integrity", "extended-harnesses", "grok-qualification", "grok-subscription-qualification", "kimi-qualification", "antigravity-qualification"], { "structured-question-resume": ["questions-and-approvals/continuation", "runs-adapters/session"], "structured-question-restart-resume": ["questions-and-approvals/continuation", "runs-adapters/session"], }); @@ -76,7 +76,7 @@ associate(["confirmation-replies"], { "confirmation-ambiguous": ["questions-and-approvals/confirmations", "questions-and-approvals/audience"], "unanswered-question-return": ["questions-and-approvals/dismiss-and-reopen", "questions-and-approvals/continuation"], }); -associate(["agent-chat", "agent-chat-hardening", "grok-qualification", "grok-subscription-qualification", "kimi-qualification", "stock-harness"], { +associate(["agent-chat", "agent-chat-hardening", "grok-qualification", "grok-subscription-qualification", "kimi-qualification", "antigravity-qualification", "stock-harness"], { "create-backlog": ["tasks/create"], "reassign-task": ["tasks/properties"], "continuity-restart": ["agent-chat/history", "runs-adapters/session"], @@ -123,6 +123,15 @@ associate(["kimi-qualification"], { "native-write-permission-stop": ["steering/stop-and-pause", "questions-and-approvals/tool-review"], "native-write-provider-loss": ["recovery/diagnosis", "questions-and-approvals/tool-review"], }); +associate(["antigravity-qualification"], { + "file-edit-validate": ["documents-artifacts/work-products"], + "warm-three-turn": ["runs-adapters/session"], + "pending-permission-stop": ["steering/stop-and-pause", "questions-and-approvals/tool-review"], + "pending-permission-provider-loss": ["recovery/diagnosis", "questions-and-approvals/tool-review"], +}); +associate(["antigravity-model-lineup", "antigravity-model-lineup-gemini4"], { + "model-receipt": ["runs-adapters/runs"], +}); associate(["task-workspaces"], { "task-directory-repository-resume": ["workspaces/binding", "workspaces/provisioning", "projects/repositories"], }); diff --git a/tests/runner-e2e/kimi-lifecycle.test.ts b/tests/runner-e2e/kimi-lifecycle.test.ts index e2f39e8cd38..905fab17628 100644 --- a/tests/runner-e2e/kimi-lifecycle.test.ts +++ b/tests/runner-e2e/kimi-lifecycle.test.ts @@ -182,16 +182,17 @@ describe("Kimi native Write lifecycle evidence", () => { }); function localFixture() { - const timestamp = Date.parse("2026-10-28T00:00:00Z"), distribution = "/private/tmp/paperclip-acpx-native-fixture/distribution"; + const closureSha256 = "c".repeat(64), timestamp = Date.parse("2026-10-28T00:00:00Z"); + const launch = "/private/tmp/paperclip-acpx-native-fixture/launch", distribution = `/private/tmp/paperclip-verified-native-501/${closureSha256}/distribution`; const bootId = "12345678-1234-1234-1234-123456789abc", loader = "exact compiled guarded loader"; const proc = (pid: number, ppid: number, executable: string, command: string): KimiLocalProcess => ({ pid, ppid, pgid: pid === 21 ? 21 : 22, startUs: String(timestamp * 1000 + pid), executable, executableDev: "1", executableIno: String(pid), command, argv: [executable], cwd: "/workspace", bootId }); const processes = [proc(21, 1, "/runner", "/runner --run-id run --lifecycle-mode per_turn"), - proc(22, 21, "/host-node", `/host-node --eval ${loader} ${distribution} .paperclip-native-entry.cjs 0 0 commonjs [] 0`), + proc(22, 21, "/host-node", `/host-node --eval ${loader} ${launch} .paperclip-native-entry.cjs 0 0 commonjs [] 0`), proc(23, 22, `${distribution}/node/bin/node`, "kimi-code")]; - processes[1]!.argv = ["/host-node", "--eval", loader, distribution, ".paperclip-native-entry.cjs", "0", "0", "commonjs", "[]", "0"]; + processes[1]!.argv = ["/host-node", "--eval", loader, launch, ".paperclip-native-entry.cjs", "0", "0", "commonjs", "[]", "0"]; const input = { authority: { pid: 21, groupId: 21, startedAt: new Date(timestamp).toISOString(), runId: "run" }, - journal: processes.map(row => ({ pid: row.pid, parent: row.ppid, start: new Date(timestamp).toISOString() })), processes, workspacePath: "/workspace", guardLoaderSha256: sha(loader) }; + journal: processes.map(row => ({ pid: row.pid, parent: row.ppid, start: new Date(timestamp).toISOString() })), processes, workspacePath: "/workspace", guardLoaderSha256: sha(loader), closureSha256 }; return { input, select: () => selectKimiLocalTarget(input) }; } describe("Kimi local native child selector", () => { @@ -228,8 +229,16 @@ describe("Kimi local native child selector", () => { expect(JSON.stringify(rows)).not.toContain("must-never-be-returned"); } finally { child.kill("SIGTERM"); await closed; } }); - it.each(["root", "foreign-loader", "wrong-entry", "unowned", "wrong-cwd", "boot", "cycle", "ambiguous"])("fails closed for %s", kind => { + it("returns the store distribution and the separate launch directory", () => { + const selected = localFixture().select(); + expect(selected.distribution).toBe(`/private/tmp/paperclip-verified-native-501/${"c".repeat(64)}/distribution`); + expect(selected.launch).toBe("/private/tmp/paperclip-acpx-native-fixture/launch"); + }); + it.each(["root", "foreign-loader", "wrong-entry", "unowned", "wrong-cwd", "boot", "cycle", "ambiguous", "foreign-closure", "old-snapshot-layout", "foreign-launch"])("fails closed for %s", kind => { const f = localFixture(); + if (kind === "foreign-closure") f.input.closureSha256 = "d".repeat(64); + if (kind === "old-snapshot-layout") f.input.processes[2]!.executable = "/private/tmp/paperclip-acpx-native-fixture/distribution/node/bin/node"; + if (kind === "foreign-launch") f.input.processes[1]!.argv[3] = "/private/tmp/elsewhere/launch"; if (kind === "root") f.input.authority.runId = "other"; if (kind === "foreign-loader") f.input.processes[1]!.argv[2] = "wrong loader"; if (kind === "wrong-entry") f.input.processes[1]!.argv[4] = "foreign.cjs"; diff --git a/tests/runner-e2e/kimi-local-provider-fault.ts b/tests/runner-e2e/kimi-local-provider-fault.ts index 28bc5095f3b..b3adfad6417 100644 --- a/tests/runner-e2e/kimi-local-provider-fault.ts +++ b/tests/runner-e2e/kimi-local-provider-fault.ts @@ -106,7 +106,7 @@ export function readKimiLocalProcesses(pids: readonly number[]): KimiLocalProces export function selectKimiLocalTarget(input: { authority: RunProcessAuthority; journal: readonly JournalIdentity[]; processes: readonly KimiLocalProcess[]; - workspacePath: string; guardLoaderSha256: string; + workspacePath: string; guardLoaderSha256: string; closureSha256: string; }) { const byPid = new Map(input.processes.map(row => [row.pid, row])), root = byPid.get(input.authority.pid); const retainedRoot = input.journal.find(row => row.pid === input.authority.pid); @@ -116,11 +116,15 @@ export function selectKimiLocalTarget(input: { const matches = []; for (const candidate of input.processes) { if (candidate.pid === root.pid || candidate.cwd !== input.workspacePath || candidate.bootId !== root.bootId) continue; - const match = /^(\/[^\u0000-\u0020]*\/paperclip-acpx-native-[A-Za-z0-9_-]+\/distribution)\/node\/bin\/node$/u.exec(candidate.executable); - if (!match) continue; + // The child runs Node from the runner's sealed store for the pinned closure; + // its bootstrap parent runs from a separate per-launch directory. + const match = /^(\/[^\u0000-\u0020]*\/paperclip-verified-native-[A-Za-z0-9_-]+\/([a-f0-9]{64})\/distribution)\/node\/bin\/node$/u.exec(candidate.executable); + if (!match || match[2] !== input.closureSha256) continue; const distribution = match[1]!, parent = byPid.get(candidate.ppid); if (!parent || parent.cwd !== input.workspacePath || parent.bootId !== root.bootId) continue; - if (!Array.isArray(parent.argv) || parent.argv.length !== 10 || parent.argv[1] !== "--eval" || parent.argv[3] !== distribution + const launch = Array.isArray(parent.argv) ? parent.argv[3] ?? "" : ""; + if (!Array.isArray(parent.argv) || parent.argv.length !== 10 || parent.argv[1] !== "--eval" + || !/^\/[^\u0000-\u0020]*\/paperclip-acpx-native-[A-Za-z0-9_-]+\/launch$/u.test(launch) || JSON.stringify(parent.argv.slice(4)) !== JSON.stringify([".paperclip-native-entry.cjs", "0", "0", "commonjs", "[]", "0"]) || sha(parent.argv[2]!) !== input.guardLoaderSha256) continue; const ancestry = [candidate]; let cursor = candidate; @@ -133,7 +137,7 @@ export function selectKimiLocalTarget(input: { } demand(input.journal.some(row => row.pid === candidate.pid && row.parent === candidate.ppid && Math.floor(Date.parse(row.start) / 1000) === Math.floor(Number(candidate.startUs) / 1_000_000)), "unobserved_native_child"); - matches.push({ target: candidate, ancestry, distribution }); + matches.push({ target: candidate, ancestry, distribution, launch }); } demand(matches.length === 1, "unique_native_child"); return matches[0]!; @@ -156,9 +160,10 @@ export function terminateKimiLocalProvider(input: { authority: RunProcessAuthori demand(supportsKimiLocalProviderFault(), "supported_platform"); const contract = kimiFaultRuntimeContract("darwin-arm64"); const pids = input.journal.map(row => row.pid); - const before = selectKimiLocalTarget({ ...input, processes: readKimiLocalProcesses(pids), guardLoaderSha256: contract.guardLoaderSha256 }); + const selector = { guardLoaderSha256: contract.guardLoaderSha256, closureSha256: contract.closureSha256 }; + const before = selectKimiLocalTarget({ ...input, processes: readKimiLocalProcesses(pids), ...selector }); demand(before.target.pid !== process.pid && before.target.pid !== input.authority.pid, "not_runner"); - for (const path of [before.distribution, dirname(before.distribution)]) { + for (const path of [before.launch, dirname(before.launch), before.distribution, dirname(before.distribution)]) { const stat = lstatSync(path); demand(stat.isDirectory() && !stat.isSymbolicLink() && (stat.mode & 0o222) === 0 && realpathSync(path) === path, "snapshot_seal"); } @@ -166,14 +171,14 @@ export function terminateKimiLocalProvider(input: { authority: RunProcessAuthori const entries = parseNativeAcpxDistributionEntries(metadata, contract.closureSha256); const node = sealedFile(join(before.distribution, "node/bin/node"), 256 * 1024 * 1024); const entry = sealedFile(join(before.distribution, KIMI_FAULT_ENTRY), 256 * 1024 * 1024); - const guard = sealedFile(join(before.distribution, ".paperclip-native-module-guard.cjs"), 4 * 1024 * 1024); - const bootstrap = sealedFile(join(before.distribution, ".paperclip-native-entry.cjs"), 65536); + const guard = sealedFile(join(before.launch, ".paperclip-native-module-guard.cjs"), 4 * 1024 * 1024); + const bootstrap = sealedFile(join(before.launch, ".paperclip-native-entry.cjs"), 65536); demand(node.dev === before.target.executableDev && node.ino === before.target.executableIno && node.digest === contract.nodeSha256 && node.digest === `sha256:${entries.find(row => row.path === "node/bin/node")?.sha256}` && entry.digest === `sha256:${entries.find(row => row.path === KIMI_FAULT_ENTRY)?.sha256}` && guard.bytes.toString("utf8") === expectedNativeModuleGuard(before.distribution, entries) - && bootstrap.bytes.toString("utf8") === expectedNativeBootstrap(before.distribution, contract.nodeSha256), "pinned_native_bytes"); - const fresh = selectKimiLocalTarget({ ...input, processes: readKimiLocalProcesses(pids), guardLoaderSha256: contract.guardLoaderSha256 }); + && bootstrap.bytes.toString("utf8") === expectedNativeBootstrap(before.launch, before.distribution, contract.nodeSha256), "pinned_native_bytes"); + const fresh = selectKimiLocalTarget({ ...input, processes: readKimiLocalProcesses(pids), ...selector }); demand(JSON.stringify(fresh) === JSON.stringify(before), "native_identity_changed"); process.kill(fresh.target.pid, "SIGKILL"); const identity = ({ pid, ppid, pgid, startUs, bootId }: KimiLocalProcess) => ({ pid, ppid, pgid, startUs, bootId }); diff --git a/tests/runner-e2e/kimi-provider-fault-contract.ts b/tests/runner-e2e/kimi-provider-fault-contract.ts index 76d9855c50a..c07ec786244 100644 --- a/tests/runner-e2e/kimi-provider-fault-contract.ts +++ b/tests/runner-e2e/kimi-provider-fault-contract.ts @@ -5,7 +5,10 @@ import { KIMI_DISTRIBUTION_CLOSURE_SHA256, KIMI_NODE_DISTRIBUTIONS } from "../.. import type { RemoteNativeBinding, RemoteProcessIdentity } from "./remote-native-fixtures.js"; export const KIMI_FAULT_ENTRY = "node_modules/@moonshot-ai/kimi-code/dist/main.mjs"; +/** Placeholder for the sealed verified store's distribution (`//distribution`). */ export const KIMI_FAULT_SNAPSHOT = "/__paperclip_kimi_fault_snapshot__/distribution"; +/** Placeholder for the per-launch directory that holds the bootstrap and module guard. */ +export const KIMI_FAULT_LAUNCH = "/__paperclip_kimi_fault_launch__/launch"; const sha = (bytes: string | Buffer) => `sha256:${createHash("sha256").update(bytes).digest("hex")}`; const requireValue = (value: unknown, code: string): void => { if (!value) throw new Error(`kimi_provider_fault:${code}`); }; @@ -45,11 +48,12 @@ export function kimiFaultRuntimeContract(target: keyof typeof KIMI_DISTRIBUTION_ nodeSha256: `sha256:${KIMI_NODE_DISTRIBUTIONS[target].executableSha256}` }; } -export function expectedNativeBootstrap(distribution: string, nodeSha256: string): string { +/** The bootstrap spawns the store's pinned Node (checked by digest) and loads the guard from its launch directory. */ +export function expectedNativeBootstrap(launch: string, distribution: string, nodeSha256: string): string { const digest = nodeSha256.replace(/^sha256:/u, ""); requireValue(/^[a-f0-9]{64}$/u.test(digest), "node_digest"); return compiledBuilders().nativeBootstrap(`${distribution}/node/bin/node`, digest, - ["--require", `${distribution}/.paperclip-native-module-guard.cjs`, `${distribution}/${KIMI_FAULT_ENTRY}`, "acp"]); + ["--require", `${launch}/.paperclip-native-module-guard.cjs`, `${distribution}/${KIMI_FAULT_ENTRY}`, "acp"]); } export function expectedNativeModuleGuard(distribution: string, entries: readonly { path: string; sha256: string }[]): string { diff --git a/tests/runner-e2e/kimi-provider-fault-diagnostic.py b/tests/runner-e2e/kimi-provider-fault-diagnostic.py index 48825651c5a..94f43896b71 100644 --- a/tests/runner-e2e/kimi-provider-fault-diagnostic.py +++ b/tests/runner-e2e/kimi-provider-fault-diagnostic.py @@ -1,7 +1,7 @@ import base64,hashlib,importlib.util,json,os,re,sys from pathlib import Path sys.dont_write_bytecode=True -EXPECTED_SOURCE_SHA256='585494ff2f10125c98c4102df5b6b6dba643de6c92266186711695b1e993efe6' +EXPECTED_SOURCE_SHA256='c6af3f9b66b02ec52e08f6be1113d3590358fca03154f800e394d62c9386e9ee' def run(fault,config,allow_signal): state={'schema':'paperclip.kimi11.remote-fault-diagnostic.v1','qualification':False,'stage':'inspect','status':'FAIL','failingGuard':None,'errno':None,'signalAttempted':False,'signalDispatched':False,'receipt':None,'externalModelCalls':0} diff --git a/tests/runner-e2e/kimi-provider-fault.py b/tests/runner-e2e/kimi-provider-fault.py index 90a813cbc6a..6995e9a0cfd 100644 --- a/tests/runner-e2e/kimi-provider-fault.py +++ b/tests/runner-e2e/kimi-provider-fault.py @@ -15,6 +15,7 @@ NODE = 'node/bin/node' GUARD = '.paperclip-native-module-guard.cjs' BOOTSTRAP = '.paperclip-native-entry.cjs' PLACEHOLDER = '/__paperclip_kimi_fault_snapshot__/distribution' +LAUNCH_PLACEHOLDER = '/__paperclip_kimi_fault_launch__/launch' def require(value, code): @@ -134,12 +135,14 @@ def parse_closure(content, expected): return normalized -def expected_sources(config, distribution, entries): +def expected_sources(config, launch, distribution, entries): + # The bootstrap and guard live in the per-launch directory; the closure they + # name (and the guard's digests) live in the runner's sealed verified store. bootstrap, guard = config['bootstrapTemplate'], config['guardTemplate'] - require(isinstance(bootstrap, str) and 0 < len(bootstrap) <= 32768 and PLACEHOLDER in bootstrap, 'bootstrap_template') + require(isinstance(bootstrap, str) and 0 < len(bootstrap) <= 32768 and PLACEHOLDER in bootstrap and LAUNCH_PLACEHOLDER in bootstrap, 'bootstrap_template') require(isinstance(guard, str) and 0 < len(guard) <= 32768 and guard.count('const digests={};') == 1, 'guard_template') digests = {distribution + '/' + entry['path']: entry['sha256'] for entry in entries} - return bootstrap.replace(PLACEHOLDER, distribution).encode(), guard.replace('const digests={};', 'const digests=' + json.dumps(digests, separators=(',', ':'), ensure_ascii=False) + ';').encode() + return bootstrap.replace(PLACEHOLDER, distribution).replace(LAUNCH_PLACEHOLDER, launch).encode(), guard.replace('const digests={};', 'const digests=' + json.dumps(digests, separators=(',', ':'), ensure_ascii=False) + ';').encode() def inspect(config): @@ -203,11 +206,17 @@ def inspect(config): continue if len(args) != 10 or args[1] != '--eval' or args[4] != BOOTSTRAP: continue - distribution = args[3] - require(re.fullmatch(r'/tmp/paperclip-acpx-native-[A-Za-z0-9_-]+/distribution', distribution), 'snapshot_path') + launch = args[3] + require(re.fullmatch(r'/tmp/paperclip-acpx-native-[A-Za-z0-9_-]+/launch', launch), 'snapshot_path') require(args[4:] == [BOOTSTRAP, '0', '0', 'commonjs', '[]', '0'] and 'sha256:' + digest(args[2].encode()) == config['guardLoaderSha256'], 'parent_bootstrap') require(argv(pid) == ['kimi-code'], 'native_title') - for directory in (distribution, os.path.dirname(distribution)): + # The child runs Node from the runner's sealed store for this exact + # closure; the launch's bootstrap below must name that same store. + native_path = os.path.realpath(f'/proc/{pid}/exe') + require(native_path.endswith('/' + NODE), 'snapshot_path') + distribution = native_path[:-len('/' + NODE)] + require(re.fullmatch(r'/tmp/paperclip-verified-native-[A-Za-z0-9_-]+/' + re.escape(config['closureSha256']) + '/distribution', distribution), 'snapshot_path') + for directory in (launch, os.path.dirname(launch), distribution, os.path.dirname(distribution)): status = os.lstat(directory) require(stat.S_ISDIR(status.st_mode) and not status.st_mode & 0o222 and os.path.realpath(directory) == directory, 'snapshot_seal') require(os.readlink(f'/proc/{pid}/cwd') == binding['remoteCwd'] and os.readlink(f'/proc/{parent}/cwd') == binding['remoteCwd'], 'cwd') @@ -216,9 +225,9 @@ def inspect(config): content, inode = checked_file(distribution + '/' + name, 256 * 1024 * 1024, True) require(len(content) == entries[name]['size'] and digest(content) == entries[name]['sha256'], 'snapshot_digest') identities[name] = inode - bootstrap, guard = expected_sources(config, distribution, ordered_entries) - require(checked_file(distribution + '/' + BOOTSTRAP, 32768, True)[0] == bootstrap, 'native_bootstrap_bytes') - require(checked_file(distribution + '/' + GUARD, 4 * 1024 * 1024, True)[0] == guard, 'native_guard_bytes') + bootstrap, guard = expected_sources(config, launch, distribution, ordered_entries) + require(checked_file(launch + '/' + BOOTSTRAP, 32768, True)[0] == bootstrap, 'native_bootstrap_bytes') + require(checked_file(launch + '/' + GUARD, 4 * 1024 * 1024, True)[0] == guard, 'native_guard_bytes') native_exe, held_node = os.stat(f'/proc/{pid}/exe'), os.stat(f'/proc/{pid}/fd/7') require((native_exe.st_dev, native_exe.st_ino) == identities[NODE] == (held_node.st_dev, held_node.st_ino), 'native_executable') if args[0] == '/proc/self/fd/10': @@ -230,7 +239,7 @@ def inspect(config): if args[0] != '/proc/self/fd/10': require(args[0] == PACK + '/node_modules/node/bin/node' and checked_file(args[0], 256 * 1024 * 1024)[1] == parent_inode, 'parent_node_path') directory_fd = os.stat(f'/proc/{parent}/fd/4') - directory = os.lstat(distribution) + directory = os.lstat(launch) require(stat.S_ISDIR(directory_fd.st_mode) and (directory_fd.st_dev, directory_fd.st_ino) == (directory.st_dev, directory.st_ino), 'parent_directory_descriptor') source_mode = os.stat(f'/proc/{parent}/fd/3').st_mode require(stat.S_ISFIFO(source_mode) or stat.S_ISSOCK(source_mode), 'parent_source_pipe') diff --git a/tests/runner-e2e/kimi-provider-fault.test.py b/tests/runner-e2e/kimi-provider-fault.test.py index a2c0ec31508..83decbbe6e4 100644 --- a/tests/runner-e2e/kimi-provider-fault.test.py +++ b/tests/runner-e2e/kimi-provider-fault.test.py @@ -22,7 +22,8 @@ BOOT = '12345678-1234-1234-1234-123456789abc' ROOT = {'pid': 21, 'ppid': 1, 'startTicks': '100', 'bootId': BOOT} PARENT = {'pid': 22, 'ppid': 21, 'startTicks': '101', 'bootId': BOOT} TARGET = {'pid': 23, 'ppid': 22, 'startTicks': '102', 'bootId': BOOT} -DIST = '/tmp/paperclip-acpx-native-fixture/distribution' +LAUNCH = '/tmp/paperclip-acpx-native-fixture/launch' +STORE = '/tmp/paperclip-verified-native-501' RUNTIME = '/workspace/.paperclip-runtime/paperclip-runner' HOST_NODE = fault.PACK + '/node_modules/node/bin/node' LOADER = 'admitted guarded loader' @@ -40,15 +41,18 @@ class IdentityTests(unittest.TestCase): self.config = {'root': ROOT, 'binding': {'remoteCwd': '/workspace', 'runId': 'run'}, 'runtimeEnvironmentLeaseId': 'workspace-id', 'runnerdSha256': 'sha256:' + fault.digest(b'runner'), 'nodeSha256': 'sha256:' + fault.digest(fault.NODE.encode()), 'guardLoaderSha256': 'sha256:' + fault.digest(LOADER.encode()), 'closureSha256': fault.digest(json.dumps(self.entries, separators=(',', ':')).encode()), - 'bootstrapTemplate': 'bootstrap ' + fault.PLACEHOLDER, 'guardTemplate': 'const digests={};'} - bootstrap, guard = fault.expected_sources(self.config, DIST, self.entries) - self.files = {DIST + '/' + fault.NODE: (fault.NODE.encode(), (1, 100)), DIST + '/' + fault.ENTRY: (fault.ENTRY.encode(), (1, 101)), - DIST + '/' + fault.BOOTSTRAP: (bootstrap, (1, 102)), DIST + '/' + fault.GUARD: (guard, (1, 103)), + 'bootstrapTemplate': 'bootstrap ' + fault.PLACEHOLDER + ' ' + fault.LAUNCH_PLACEHOLDER, 'guardTemplate': 'const digests={};'} + self.dist = STORE + '/' + self.config['closureSha256'] + '/distribution' + bootstrap, guard = fault.expected_sources(self.config, LAUNCH, self.dist, self.entries) + self.paths = {fault.NODE: self.dist + '/' + fault.NODE, fault.ENTRY: self.dist + '/' + fault.ENTRY, fault.BOOTSTRAP: LAUNCH + '/' + fault.BOOTSTRAP, fault.GUARD: LAUNCH + '/' + fault.GUARD} + self.files = {self.paths[fault.NODE]: (fault.NODE.encode(), (1, 100)), self.paths[fault.ENTRY]: (fault.ENTRY.encode(), (1, 101)), + self.paths[fault.BOOTSTRAP]: (bootstrap, (1, 102)), self.paths[fault.GUARD]: (guard, (1, 103)), RUNTIME + '/bin/paperclip-runnerd': (b'runner', (1, 90)), HOST_NODE: (fault.NODE.encode(), (1, 110)), fault.PACK + '/provider-assets/kimi/linux-x64/native-closure.json': (json.dumps({'entries': self.entries}, indent=2).encode(), (1, 80))} self.table = {21: ROOT, 22: PARENT, 23: TARGET} self.args = {21: [RUNTIME + '/bin/paperclip-runnerd', '--run-id', 'run', '--environment-lease-id', 'workspace-id', '--lifecycle-mode', 'per_turn', '--state-dir', RUNTIME + '/sessions/' + 'a' * 64 + '/runner'], - 22: [HOST_NODE, '--eval', LOADER, DIST, fault.BOOTSTRAP, '0', '0', 'commonjs', '[]', '0'], 23: ['kimi-code']} + 22: [HOST_NODE, '--eval', LOADER, LAUNCH, fault.BOOTSTRAP, '0', '0', 'commonjs', '[]', '0'], 23: ['kimi-code']} + self.links = {'/proc/22/exe': HOST_NODE, '/proc/23/exe': self.paths[fault.NODE], '/proc/24/exe': self.paths[fault.NODE]} self.stats = {'/proc/21/exe': (90, stat.S_IFREG), '/proc/23/exe': (100, stat.S_IFREG), '/proc/23/fd/7': (100, stat.S_IFREG), '/proc/24/exe': (100, stat.S_IFREG), '/proc/24/fd/7': (100, stat.S_IFREG), '/proc/22/exe': (110, stat.S_IFREG), '/proc/22/fd/10': (110, stat.S_IFREG), '/proc/22/fd/4': (2, stat.S_IFDIR), '/proc/22/fd/3': (3, stat.S_IFIFO)} @@ -60,7 +64,7 @@ class IdentityTests(unittest.TestCase): patch.object(fault, 'checked_runner', side_effect=lambda name: self.files[name]), patch.object(fault, 'checked_file', side_effect=checked_fixture_file), patch.object(Path, 'read_text', return_value=BOOT), patch.object(os, 'listdir', side_effect=lambda name: [str(pid) for pid in self.table]), patch.object(os, 'getpgid', return_value=21), patch.object(os, 'lstat', return_value=SimpleNamespace(st_mode=stat.S_IFDIR | 0o500, st_dev=1, st_ino=2)), - patch.object(os.path, 'realpath', side_effect=lambda name: HOST_NODE if name == '/proc/22/exe' else name), + patch.object(os.path, 'realpath', side_effect=lambda name: self.links.get(name, name)), patch.object(os, 'readlink', return_value='/workspace'), patch.object(os, 'stat', side_effect=lambda name: SimpleNamespace(st_dev=1, st_ino=self.stats[name][0], st_mode=self.stats[name][1]))] for mocked in patches: mocked.start() @@ -82,7 +86,8 @@ class IdentityTests(unittest.TestCase): def test_memfd_parent_uses_the_live_descriptor_without_reopening_deleted_alias(self): self.args[22][0] = '/proc/self/fd/10' - with patch.object(os.path, 'realpath', side_effect=lambda name: '/memfd:paperclip-verified-launch (deleted)' if name == '/proc/22/exe' else name), self.parent_descriptor(True): + self.links['/proc/22/exe'] = '/memfd:paperclip-verified-launch (deleted)' + with self.parent_descriptor(True): receipt = fault.inspect(self.config) self.assertEqual(receipt['target'], TARGET) self.assertFalse(any('/memfd:' in str(call) for call in fault.checked_file.call_args_list)) @@ -129,11 +134,11 @@ class IdentityTests(unittest.TestCase): def test_native_main_node_guard_bootstrap_and_parent_code_are_exact(self): for name in [fault.NODE, fault.ENTRY, fault.GUARD, fault.BOOTSTRAP]: - original = self.files[DIST + '/' + name] - self.files[DIST + '/' + name] = (b'changed', original[1]) + original = self.files[self.paths[name]] + self.files[self.paths[name]] = (b'changed', original[1]) with self.subTest(name=name), self.assertRaises(RuntimeError): fault.inspect(self.config) - self.files[DIST + '/' + name] = original + self.files[self.paths[name]] = original for index, value in [(2, 'foreign loader'), (5, '1'), (8, '["module"]'), (0, '/foreign/node')]: original = self.args[22][index] self.args[22][index] = value @@ -141,6 +146,28 @@ class IdentityTests(unittest.TestCase): fault.inspect(self.config) self.args[22][index] = original + def test_native_child_must_run_from_the_sealed_store_of_the_pinned_closure(self): + for executable in ['/tmp/paperclip-verified-native-501/' + '0' * 64 + '/distribution/' + fault.NODE, + '/tmp/paperclip-acpx-native-fixture/distribution/' + fault.NODE, + '/home/user/paperclip-verified-native-501/' + self.config['closureSha256'] + '/distribution/' + fault.NODE, + self.dist + '/node/bin/other']: + with self.subTest(executable=executable), self.assertRaisesRegex(RuntimeError, 'snapshot_path'): + self.links['/proc/23/exe'] = executable + fault.inspect(self.config) + self.links['/proc/23/exe'] = self.paths[fault.NODE] + self.args[22][3] = '/tmp/paperclip-acpx-native-fixture/distribution' + with self.assertRaisesRegex(RuntimeError, 'snapshot_path'): + fault.inspect(self.config) + + def test_bootstrap_naming_another_store_or_launch_is_refused(self): + for launch, distribution in [(LAUNCH, STORE + '/' + 'f' * 64 + '/distribution'), ('/tmp/paperclip-acpx-native-other/launch', self.dist)]: + bootstrap, _ = fault.expected_sources(self.config, launch, distribution, self.entries) + original = self.files[self.paths[fault.BOOTSTRAP]] + self.files[self.paths[fault.BOOTSTRAP]] = (bootstrap, original[1]) + with self.subTest(launch=launch), self.assertRaisesRegex(RuntimeError, 'native_bootstrap_bytes'): + fault.inspect(self.config) + self.files[self.paths[fault.BOOTSTRAP]] = original + def test_live_executable_and_retained_descriptors_must_match(self): for name in ['/proc/23/exe', '/proc/23/fd/7', '/proc/22/fd/4']: original = self.stats[name] @@ -316,7 +343,10 @@ class PidfdTests(unittest.TestCase): self.assertIsNotNone(node) base = Path(tempfile.mkdtemp(prefix='kimi-fault-calibration-', dir='/tmp')) snapshot = Path(tempfile.mkdtemp(prefix='paperclip-acpx-native-', dir='/tmp')) - distribution = snapshot / 'distribution' + launch = snapshot / 'launch' + store = Path(tempfile.mkdtemp(prefix='paperclip-verified-native-', dir='/tmp')) + staged = store / 'staged' / 'distribution' + distribution = staged workspace = base / 'workspace' runtime = workspace / '.paperclip-runtime/paperclip-runner' pack = base / 'pack' @@ -335,21 +365,27 @@ class PidfdTests(unittest.TestCase): closure = pack / 'provider-assets/kimi/linux-x64/native-closure.json' closure.parent.mkdir(parents=True) closure.write_text(json.dumps({'entries': entries})) + closure_sha256 = fault.digest(json.dumps(entries, separators=(',', ':'), ensure_ascii=False).encode()) + # Publish the store under its closure digest, as the runner does. + (store / 'staged').rename(store / closure_sha256) + distribution = store / closure_sha256 / 'distribution' + launch.mkdir() loader = 'const source=require("node:fs").readFileSync(3,"utf8");require("node:vm").runInThisContext(source);' - template = 'const fs=require("node:fs"),cp=require("node:child_process");const fd=fs.openSync(' + json.dumps(fault.PLACEHOLDER + '/' + fault.NODE) + ',"r");const child=cp.spawn("/proc/self/fd/7",["--require",' + json.dumps(fault.PLACEHOLDER + '/' + fault.GUARD) + ',' + json.dumps(fault.PLACEHOLDER + '/' + fault.ENTRY) + ',"acp"],{stdio:["ignore","ignore","ignore","ignore","ignore","ignore","ignore",fd]});fs.closeSync(fd);child.on("exit",()=>process.exit(0));process.on("SIGTERM",()=>child.kill("SIGTERM"));' + template = 'const fs=require("node:fs"),cp=require("node:child_process");const fd=fs.openSync(' + json.dumps(fault.PLACEHOLDER + '/' + fault.NODE) + ',"r");const child=cp.spawn("/proc/self/fd/7",["--require",' + json.dumps(fault.LAUNCH_PLACEHOLDER + '/' + fault.GUARD) + ',' + json.dumps(fault.PLACEHOLDER + '/' + fault.ENTRY) + ',"acp"],{stdio:["ignore","ignore","ignore","ignore","ignore","ignore","ignore",fd]});fs.closeSync(fd);child.on("exit",()=>process.exit(0));process.on("SIGTERM",()=>child.kill("SIGTERM"));' config = {'binding': {'remoteCwd': str(workspace), 'runId': 'fixture'}, 'runtimeEnvironmentLeaseId': 'workspace-id', 'runnerdSha256': 'sha256:' + fault.digest((runtime / 'bin/paperclip-runnerd').read_bytes()), - 'closureSha256': fault.digest(json.dumps(entries, separators=(',', ':'), ensure_ascii=False).encode()), 'nodeSha256': 'sha256:' + fault.digest((distribution / fault.NODE).read_bytes()), + 'closureSha256': closure_sha256, 'nodeSha256': 'sha256:' + fault.digest((distribution / fault.NODE).read_bytes()), 'guardLoaderSha256': 'sha256:' + fault.digest(loader.encode()), 'bootstrapTemplate': template, 'guardTemplate': 'const digests={};'} - bootstrap, guard = fault.expected_sources(config, str(distribution), entries) - (distribution / fault.BOOTSTRAP).write_bytes(bootstrap) - (distribution / fault.GUARD).write_bytes(guard) + bootstrap, guard = fault.expected_sources(config, str(launch), str(distribution), entries) + (launch / fault.BOOTSTRAP).write_bytes(bootstrap) + (launch / fault.GUARD).write_bytes(guard) script = base / 'root.cjs' - script.write_text('const fs=require("node:fs"),cp=require("node:child_process");const directory=fs.openSync(' + json.dumps(str(distribution)) + ',"r");const child=cp.spawn(' + json.dumps(str(host_node)) + ',["--eval",' + json.dumps(loader) + ',' + json.dumps(str(distribution)) + ',' + json.dumps(fault.BOOTSTRAP) + ',"0","0","commonjs","[]","0"],{detached:true,stdio:["ignore","ignore","ignore","pipe",directory]});fs.closeSync(directory);child.stdio[3].end(fs.readFileSync(' + json.dumps(str(distribution / fault.BOOTSTRAP)) + '));process.on("SIGTERM",()=>{if(child.exitCode!==null||child.signalCode!==null)process.exit(0);child.once("exit",()=>process.exit(0));child.kill("SIGTERM")});setInterval(()=>{},1000);') - for directory, _, files in os.walk(snapshot): - for name in files: - path = Path(directory) / name - path.chmod(0o500 if path == distribution / fault.NODE else 0o400) - Path(directory).chmod(0o500) + script.write_text('const fs=require("node:fs"),cp=require("node:child_process");const directory=fs.openSync(' + json.dumps(str(launch)) + ',"r");const child=cp.spawn(' + json.dumps(str(host_node)) + ',["--eval",' + json.dumps(loader) + ',' + json.dumps(str(launch)) + ',' + json.dumps(fault.BOOTSTRAP) + ',"0","0","commonjs","[]","0"],{detached:true,stdio:["ignore","ignore","ignore","pipe",directory]});fs.closeSync(directory);child.stdio[3].end(fs.readFileSync(' + json.dumps(str(launch / fault.BOOTSTRAP)) + '));process.on("SIGTERM",()=>{if(child.exitCode!==null||child.signalCode!==null)process.exit(0);child.once("exit",()=>process.exit(0));child.kill("SIGTERM")});setInterval(()=>{},1000);') + for sealed in (snapshot, store / closure_sha256): + for directory, _, files in os.walk(sealed): + for name in files: + path = Path(directory) / name + path.chmod(0o500 if path == distribution / fault.NODE else 0o400) + Path(directory).chmod(0o500) check_cancelled() root_child = subprocess.Popen([str(runtime / 'bin/paperclip-runnerd'), str(script), '--run-id', 'fixture', '--environment-lease-id', 'workspace-id', '--lifecycle-mode', 'per_turn', '--state-dir', str(runtime / 'sessions' / ('a' * 64) / 'runner')], cwd=workspace, env={'PATH': '/usr/bin:/bin'}, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) owned.append(os.pidfd_open(root_child.pid)) @@ -397,9 +433,10 @@ class PidfdTests(unittest.TestCase): pass for fd in owned: os.close(fd) - for directory, _, _ in os.walk(snapshot): - os.chmod(directory, 0o700) - shutil.rmtree(snapshot) + for sealed in (snapshot, store): + for directory, _, _ in os.walk(sealed): + os.chmod(directory, 0o700) + shutil.rmtree(sealed) shutil.rmtree(base) diff --git a/tests/runner-e2e/kimi-provider-fault.test.ts b/tests/runner-e2e/kimi-provider-fault.test.ts index 65ec400c35b..ea696e9d442 100644 --- a/tests/runner-e2e/kimi-provider-fault.test.ts +++ b/tests/runner-e2e/kimi-provider-fault.test.ts @@ -20,16 +20,19 @@ function receipt() { describe("Kimi native child fault contract", () => { it("uses compiled production loader, module guard and native bootstrap bytes", () => { - const contract = kimiFaultRuntimeContract("linux-x64"), distribution = "/tmp/paperclip-acpx-native-test/distribution"; + const contract = kimiFaultRuntimeContract("linux-x64"), launch = "/tmp/paperclip-acpx-native-test/launch"; + const distribution = `/tmp/paperclip-verified-native-501/${contract.closureSha256}/distribution`; expect(contract.guardLoaderSha256).toMatch(/^sha256:[a-f0-9]{64}$/u); expect(contract.closureSha256).toMatch(/^[a-f0-9]{64}$/u); - const bootstrap = expectedNativeBootstrap(distribution, contract.nodeSha256); + const bootstrap = expectedNativeBootstrap(launch, distribution, contract.nodeSha256); expect(bootstrap).toContain(`const executable="${distribution}/node/bin/node"`); - expect(bootstrap).toContain(`"${distribution}/${KIMI_FAULT_ENTRY}","acp"`); + expect(bootstrap).toContain(`["--require","${launch}/.paperclip-native-module-guard.cjs","${distribution}/${KIMI_FAULT_ENTRY}","acp"]`); + // The spawned Node descriptor is hashed against its pin, never trusted from a recorded store identity. + expect(bootstrap).toContain(`executableHash.digest("hex")!==${JSON.stringify(contract.nodeSha256.slice("sha256:".length))}`); expect(bootstrap).toContain('const childExecutable=process.platform==="linux"?"/proc/self/fd/"+stdio.length:executable'); expect(expectedNativeModuleGuard(distribution, [{ path: KIMI_FAULT_ENTRY, sha256: "a".repeat(64) }])) .toContain(`const digests={"${distribution}/${KIMI_FAULT_ENTRY}":"${"a".repeat(64)}"};`); - expect(() => expectedNativeBootstrap(distribution, "invalid")).toThrow("node_digest"); + expect(() => expectedNativeBootstrap(launch, distribution, "invalid")).toThrow("node_digest"); }); it("accepts the exact child and rejects misleading or incomplete receipts", () => { @@ -63,7 +66,7 @@ describe("Kimi native child fault contract", () => { expect(result.error).toBeUndefined(); expect(result.signal).toBeNull(); expect(result.status, result.stderr).toBe(0); - expect(result.stderr).toContain("Ran 25 tests"); + expect(result.stderr).toContain("Ran 27 tests"); if (process.platform === "linux") expect(result.stderr).not.toContain("skipped"); else expect(result.stderr).toContain("skipped=1"); }, 35_000); diff --git a/tests/runner-e2e/launch.ts b/tests/runner-e2e/launch.ts index fcf2927176c..0265a93d7e3 100644 --- a/tests/runner-e2e/launch.ts +++ b/tests/runner-e2e/launch.ts @@ -83,6 +83,7 @@ import { } from "./redaction.js"; import { buildMatrixJobs, + daytonaCandidateProviders, parseRunnerSelectors, RunnerSelectorError, selectorArgumentsWithEnvironment, @@ -1237,6 +1238,7 @@ async function main() { JSON.stringify({ include: jobs, needsDaytona: jobs.some((job) => job.needsDaytona), + candidateProviders: daytonaCandidateProviders(executions), executionIds: executions.map((execution) => execution.id), }), ); diff --git a/tests/runner-e2e/live-fixtures.test.ts b/tests/runner-e2e/live-fixtures.test.ts index dd618c3da2f..53dc1c769b4 100644 --- a/tests/runner-e2e/live-fixtures.test.ts +++ b/tests/runner-e2e/live-fixtures.test.ts @@ -528,7 +528,7 @@ describe("Daytona fixture readiness after candidate startup", () => { const end = source.indexOf(" const api = new RunnerApi(request);", start); expect(start).toBeGreaterThan(0); expect(end).toBeGreaterThan(start); const js = transformSync(source.slice(start, end), { loader: "ts", format: "cjs" }).code; - return new Function("kimiCandidateAdmissionForExecution", "execution", "api", "nonce", "startedAtMs", "deadlineMs", "trace", "saveTrace", "restartIsolatedPaperclipServer", "waitForFixtureDaytonaProvider", js + ";return onCompanyCreated;")( + return new Function("candidateAdmissionForExecution", "execution", "api", "nonce", "startedAtMs", "deadlineMs", "trace", "saveTrace", "restartIsolatedPaperclipServer", "waitForFixtureDaytonaProvider", js + ";return onCompanyCreated;")( () => ({}), execution, api, "fixture", 0, deadlineAt, undefined, async () => {}, restart, waitReady(), ) as (id: string) => Promise; } diff --git a/tests/runner-e2e/live-fixtures.ts b/tests/runner-e2e/live-fixtures.ts index 7795f356094..a54dec5403a 100644 --- a/tests/runner-e2e/live-fixtures.ts +++ b/tests/runner-e2e/live-fixtures.ts @@ -467,7 +467,7 @@ export async function setupLiveFixtures(input: { || execution.task.flow === "finalization_recovery" || execution.task.flow === "followup_stop_resume" || execution.task.flow === "warm_three_turn" - || (["extended-harnesses", "kimi-qualification"].includes(execution.suite.id) && execution.task.id === "file-edit-validate")) { + || (["extended-harnesses", "kimi-qualification", "antigravity-qualification"].includes(execution.suite.id) && execution.task.id === "file-edit-validate")) { registry.register({ id: "project", dependencies: ["company", "environment"], diff --git a/tests/runner-e2e/native-active-stop-evidence.ts b/tests/runner-e2e/native-active-stop-evidence.ts index 1b7b0d22ffb..56013563c39 100644 --- a/tests/runner-e2e/native-active-stop-evidence.ts +++ b/tests/runner-e2e/native-active-stop-evidence.ts @@ -9,7 +9,9 @@ import { bootstrapReadExecutionId, withoutProvenBootstrapReads, type BootstrapRe type Row = Record; export interface ActiveStopCaller { type: "board"; userId: "local-board"; source: "local_implicit" } -export type ActiveStopProvider = "cursor" | "copilot"; +export type ActiveStopProvider = "cursor" | "copilot" | "antigravity"; +/** Providers without a native tool-evidence notice; their proof is the canonical PRP stream alone. */ +const CANONICAL_PROVIDERS: ReadonlySet = new Set(["antigravity"]); export interface ActiveStopScope { provider: ActiveStopProvider; companyId: string; issueId: string; runId: string; target: string; commandSha256?: string } export interface ActiveStopPending { schema: "paperclip.e2e.native-active-stop-pending.v2"; @@ -59,9 +61,57 @@ function canonicalRows(events: readonly unknown[], scope: ActiveStopScope) { } const terminals = new Set(["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"]); const closures = new Set(["runtime_request.resolved", "runtime_request.cancelled", "runtime_request.expired"]); +type CanonicalRow = ReturnType[number]; +const MUTATIONS = new Set(["edit", "write", "execute"]); +const READS = new Set(["read", "search"]); +/** + * No provider notice exists, so bind the one durable permission card to its + * exact native tool call through the canonical execution ID. Only completed + * read-only operations may precede it; the mutation may not complete. + */ +function canonicalOrigin(rows: CanonicalRow[], scope: ActiveStopScope) { + const created = rows.filter(x => x.event.eventType === "runtime_request.created"); + fail(created.length === 1, "one durable native card required"); + const card = created[0]!, request = rec(rec(card.event.payload).request), details = rec(request.details); + const choices = Array.isArray(request.choices) ? request.choices.map(rec) : []; + fail(request.schema === "paperclip.runtime_request.v2" && request.type === "permission" && request.requestKind === "permission_approval" + && request.status === "pending" && id(request.requestId) && id(request.itemId) && id(details.toolCallId) && request.turnId === card.event.turnId + && id(card.event.turnId) && id(card.event.normalizedSessionId) && hasAcpxNativeOrigin(request.origin, scope.provider, "session/request_permission") + && choices.some(choice => choice.key === "decline") && choices.some(choice => choice.key === "accept"), "exact native permission identity missing"); + const stream = (event: Row) => event.turnId === card.event.turnId && event.normalizedSessionId === card.event.normalizedSessionId && event.sourceInstanceId === card.event.sourceInstanceId; + fail(rows.filter(x => x.event.turnId != null).every(x => stream(x.event)), "foreign turn/session/source"); + const executionId = bootstrapReadExecutionId(details.toolCallId); + const executions = rows.filter(x => x.event.eventType.startsWith("tool.execution.")); + const own = executions.filter(x => rec(x.event.payload).executionId === executionId); + const started = own.filter(x => x.event.eventType === "tool.execution.started"); + fail(started.length === 1 && own[0] === started[0] && own.filter(x => x.event.eventType === "tool.execution.completed").length <= 1 + && own.every(x => rec(x.event.payload).schema === "paperclip.tool.execution.v1" + && ["tool.execution.started", "tool.execution.progressed", "tool.execution.completed"].includes(x.event.eventType) + && rec(x.event.payload).status === (x.event.eventType === "tool.execution.completed" ? "failed" : "running") + && (MUTATIONS.has(rec(x.event.payload).operation) || rec(x.event.payload).operation === "unknown") + && (rec(x.event.payload).target === scope.target || rec(x.event.payload).target == null)) + && own.some(x => MUTATIONS.has(rec(x.event.payload).operation)) + && (own.some(x => rec(x.event.payload).target === scope.target) || String(request.prompt ?? "").includes(scope.target)), + "exact native mutation lifecycle missing or completed"); + const boundary = Math.min(card.row.seq, started[0]!.row.seq), others = new Map(); + for (const x of executions.filter(x => rec(x.event.payload).executionId !== executionId)) { + const key = String(rec(x.event.payload).executionId); others.set(key, [...others.get(key) ?? [], x]); + } + for (const group of others.values()) { + fail(group[0]!.event.eventType === "tool.execution.started" && group.at(-1)!.event.eventType === "tool.execution.completed" + && group.at(-1)!.row.seq < boundary && group.every(x => READS.has(rec(x.event.payload).operation) || rec(x.event.payload).operation === "unknown") + && group.some(x => READS.has(rec(x.event.payload).operation)) && group.every(x => rec(x.event.payload).target !== scope.target), + "extra native operation before or beside the pending mutation"); + } + const notice = { runId: scope.runId, sessionId: card.event.normalizedSessionId as string, turnId: card.event.turnId as string, + toolCallId: details.toolCallId as string, requestId: request.requestId as string, seq: card.row.seq, stage: "permission_requested" as const, + declineOffered: true, operation: "edit" }; + return { rows, notice, permission: card, created: card, toolOrigin: started[0]!, toolStarted: started[0]!, request, stream }; +} function origin(events: readonly unknown[], scope: ActiveStopScope, bootstrap?: BootstrapReadProof) { - fail([scope.companyId, scope.issueId, scope.runId, scope.target].every(id) && ["cursor", "copilot"].includes(scope.provider), "exact scope required"); + fail([scope.companyId, scope.issueId, scope.runId, scope.target].every(id) && ["cursor", "copilot", "antigravity"].includes(scope.provider), "exact scope required"); const rows = canonicalRows(events, scope); + if (CANONICAL_PROVIDERS.has(scope.provider)) return canonicalOrigin(rows, scope); const notices = scope.provider === "cursor" ? readCursorToolEvidence(events, scope.runId) : readCopilotToolEvidence(events, scope.runId); const requests = notices.filter(n => n.stage === "permission_requested"); fail(requests.length === 1, "one native permission required"); @@ -120,7 +170,7 @@ export function observeActiveStopPending(input: { events: readonly unknown[]; ru fail(isActiveStopCaller(input.caller) && uuid(input.cancellationRequestId) && run.id === scope.runId && run.companyId === scope.companyId && run.nativeIssueId === scope.issueId && run.status === "running" && run.runtimeMode === "native" && issue.id === scope.issueId && issue.companyId === scope.companyId && issue.status === "in_progress" && run.resultJson?.startupCancellation == null && run.resultJson?.nativeCancellation == null, "run is not fresh active work"); - fail(!(scope.provider === "cursor" ? readCursorToolEvidence(input.events, scope.runId) : readCopilotToolEvidence(input.events, scope.runId)).some(n => n.stage === "permission_delivered"), "permission already answered"); + fail(CANONICAL_PROVIDERS.has(scope.provider) || !(scope.provider === "cursor" ? readCursorToolEvidence(input.events, scope.runId) : readCopilotToolEvidence(input.events, scope.runId)).some(n => n.stage === "permission_delivered"), "permission already answered"); fail(!proof.rows.some(x => terminals.has(x.event.eventType) || closures.has(x.event.eventType)), "request or provider already settled"); fail(!proof.rows.some(x => x.event.eventType === "tool.execution.completed" && rec(x.event.payload).executionId === bootstrapReadExecutionId(proof.notice.toolCallId)), "operation already ended"); return { schema: "paperclip.e2e.native-active-stop-pending.v2", scope, caller: input.caller, requestId: proof.notice.requestId!, toolCallId: proof.notice.toolCallId, @@ -161,6 +211,50 @@ export function readActiveStopSettlement(input: { events: readonly unknown[]; ru fail(proof.rows.filter(x => x.event.eventType.startsWith("tool.execution.") || (x.event.eventType === "provider.notice.recorded" && ["cursor_tool_evidence_v1", "copilot_tool_evidence_v1"].includes(rec(x.event.payload).category))) .every(x => x.event.sourceSeq < t.event.sourceSeq), "native operation after provider cancellation"); + const stop = assertStopAcknowledged(run, issue, before); + return { schema: "paperclip.e2e.native-active-stop-settlement.v2", pending: before, dispatchMonotonicNs: input.dispatchMonotonicNs, + branch: "pending_permission_cancelled" as const, closedRequestSourceSeq: c.event.sourceSeq, terminalSourceSeq: t.event.sourceSeq, + closedRequestRowSha256: hash(c.row), terminalRowSha256: hash(t.row), intentId: stop.intentId as string, + intentAuditId: stop.intentAuditId as string, acknowledgementAuditId: stop.acknowledgementAuditId as string, + taskStillInProgress: true, normalCompletionAccepted: false, replayAllowed: false }; +} +/** + * Playbook section 13, "Permission denial": the operator denies the one real + * native permission in the browser, then stops the task. The denial must reach + * the provider as a `decline` resolution of that exact request before the + * turn ends; the mutation never completes; nothing runs after the terminal; + * and Stop is acknowledged for this run. If the provider already ended its + * turn after the denial, the run must not claim the task done. + */ +export function readDeniedPermissionSettlement(input: { events: readonly unknown[]; run: Row; issue: Row; pending: ActiveStopPending; stopDispatched: boolean }) { + const before = input.pending, { run, issue } = input; + fail(before?.schema === "paperclip.e2e.native-active-stop-pending.v2" && isActiveStopCaller(before.caller), "pre-denial pending observation missing"); + const proof = origin(input.events, before.scope); + fail(hash(proof.created.row) === before.requestRowSha256 && proof.notice.requestId === before.requestId && proof.notice.turnId === before.turnId + && proof.notice.toolCallId === before.toolCallId, "observed pending request changed"); + const closed = proof.rows.filter(x => closures.has(x.event.eventType)), terminal = proof.rows.filter(x => terminals.has(x.event.eventType)); + fail(closed.length === 1 && terminal.length === 1, "one closed request and one terminal required"); + const c = closed[0]!, t = terminal[0]!, cp = rec(c.event.payload); + fail(proof.stream(c.event) && proof.stream(t.event) && c.event.eventType === "runtime_request.resolved" && cp.requestId === before.requestId + && cp.turnId === before.turnId && cp.action === "decline" && c.event.sourceSeq > before.requestSourceSeq && t.event.sourceSeq > c.event.sourceSeq, + "denial was not delivered to the exact native request before the turn ended"); + fail(proof.rows.filter(x => x.event.eventType.startsWith("tool.execution.")).every(x => x.event.sourceSeq < t.event.sourceSeq + && !(x.event.eventType === "tool.execution.completed" && rec(x.event.payload).status === "completed" && MUTATIONS.has(rec(x.event.payload).operation))), + "native mutation completed or ran after the terminal"); + fail(run.id === before.scope.runId && run.companyId === before.scope.companyId && run.nativeIssueId === before.scope.issueId && run.runtimeMode === "native", + "foreign run"); + if (t.event.eventType === "turn.cancelled") { + fail(input.stopDispatched, "turn cancelled without the operator's Stop"); + const stop = assertStopAcknowledged(run, issue, before); + return { schema: "paperclip.e2e.native-permission-denial.v1", branch: "denied_then_stopped" as const, requestId: before.requestId, + resolvedSourceSeq: c.event.sourceSeq, terminalSourceSeq: t.event.sourceSeq, intentId: stop.intentId as string, replayAllowed: false }; + } + fail(["succeeded", "failed"].includes(run.status) && issue.id === before.scope.issueId && issue.status !== "done", + "provider finished after the denial but the task claims completion"); + return { schema: "paperclip.e2e.native-permission-denial.v1", branch: "denied_then_finished" as const, requestId: before.requestId, + resolvedSourceSeq: c.event.sourceSeq, terminalSourceSeq: t.event.sourceSeq, replayAllowed: false }; +} +function assertStopAcknowledged(run: Row, issue: Row, before: ActiveStopPending): Row { const stop = rec(rec(run.resultJson).nativeCancellation), startup = rec(rec(run.resultJson).startupCancellation); fail(run.id === before.scope.runId && run.companyId === before.scope.companyId && run.nativeIssueId === before.scope.issueId && run.runtimeMode === "native" && run.status === "cancelled" && issue.id === before.scope.issueId && issue.companyId === before.scope.companyId && issue.status === "in_progress" @@ -171,11 +265,7 @@ export function readActiveStopSettlement(input: { events: readonly unknown[]; ru && Array.isArray(stop.effects) && stop.effects.length === 1 && stop.effects[0] === "release_run_resources" && id(stop.intentAuditId) && id(stop.acknowledgementAuditId) && stop.intentAuditId !== stop.acknowledgementAuditId, "same-scope caller Stop acknowledgement missing"); - return { schema: "paperclip.e2e.native-active-stop-settlement.v2", pending: before, dispatchMonotonicNs: input.dispatchMonotonicNs, - branch: "pending_permission_cancelled" as const, closedRequestSourceSeq: c.event.sourceSeq, terminalSourceSeq: t.event.sourceSeq, - closedRequestRowSha256: hash(c.row), terminalRowSha256: hash(t.row), intentId: stop.intentId as string, - intentAuditId: stop.intentAuditId as string, acknowledgementAuditId: stop.acknowledgementAuditId as string, - taskStillInProgress: true, normalCompletionAccepted: false, replayAllowed: false }; + return stop; } export interface ActiveStopRemoteObservation { diff --git a/tests/runner-e2e/native-active-stop-flow.ts b/tests/runner-e2e/native-active-stop-flow.ts index b3290af7ab2..e5c83c56128 100644 --- a/tests/runner-e2e/native-active-stop-flow.ts +++ b/tests/runner-e2e/native-active-stop-flow.ts @@ -7,7 +7,7 @@ import { createTaskThroughUi } from "./user-actions.js"; import { createDeniedTargetFixture, exists, observeRunProcesses } from "./copilot-local-fixtures.js"; import { assertCopilotRemoteRetirement, copilotRemoteDeniedSample, prepareCopilotRemoteAction, type CopilotRemoteBootstrap, type CopilotRemoteFixture, type CopilotRemoteSnapshot } from "./copilot-protection-evidence.js"; import { cursorDeniedCommand } from "./cursor-native-evidence.js"; -import { assertActiveStopRetirement, readActiveStopCaller, observeActiveStopPending, readActiveStopSettlement, type ActiveStopRemoteObservation, type ActiveStopCaller, type ActiveStopPending, type ActiveStopScope } from "./native-active-stop-evidence.js"; +import { assertActiveStopRetirement, readActiveStopCaller, observeActiveStopPending, readActiveStopSettlement, readDeniedPermissionSettlement, type ActiveStopRemoteObservation, type ActiveStopCaller, type ActiveStopPending, type ActiveStopScope } from "./native-active-stop-evidence.js"; import type { BootstrapReadProof } from "./native-bootstrap-read-proof.js"; import type { LiveFixtureValues } from "./live-fixtures.js"; import type { MatrixExecution } from "./types.js"; @@ -51,7 +51,9 @@ export async function runNativeActiveStopFlow(input: { evidence(name: string, value: unknown): Promise; }) { const { api, page, fixtures, execution, nonce } = input, provider = execution.profile.qualificationCandidate; - if ((provider !== "cursor" && provider !== "copilot") || execution.task.id !== "pending-permission-stop") throw new Error("Unknown native active Stop case"); + // Browser denial before Stop has a canonical-stream oracle only for Antigravity. + const denyFirst = execution.task.id === "permission-deny-stop" && provider === "antigravity"; + if ((provider !== "cursor" && provider !== "copilot" && provider !== "antigravity") || (execution.task.id !== "pending-permission-stop" && !denyFirst)) throw new Error("Unknown native active Stop case"); const remote = execution.environment.id === "daytona"; if ((!remote && execution.environment.id !== "local") || (remote && !input.remoteBootstrap)) throw new Error("Active Stop requires an isolated admitted environment"); const checks: Check[] = []; let issue: Row = {}, runs: Row[] = [], events: Row[] = []; @@ -67,6 +69,10 @@ export async function runNativeActiveStopFlow(input: { const samples: Array<{ phase: string; absent: boolean }> = []; let fixture: CopilotRemoteFixture | undefined, baseline: CopilotRemoteSnapshot | undefined, sealed: CopilotRemoteSnapshot | undefined; let completed: Awaited> | undefined; + let denied: { pending: ActiveStopPending; stopDispatched: boolean; settlement: ReturnType } | undefined; + const settle = async () => denied + ? readDeniedPermissionSettlement({ ...await load(), pending: denied.pending, stopDispatched: denied.stopDispatched }) + : readActiveStopSettlement({ ...await load(), ...completed!, bootstrap: bootstrap() }); const observeProcesses = () => { const run = runs[0], authority = run?.processPid ? { pid: run.processPid, groupId: run.processGroupId, startedAt: run.processStartedAt, runId: run.id } : undefined; if (authority) { const key = JSON.stringify(authority); if (processIdentity && processIdentity !== key) processError = true; processIdentity ??= key; } @@ -106,10 +112,10 @@ export async function runNativeActiveStopFlow(input: { } if (!remote) await sample("after-cleanup"); const watch = remote ? sealed!.watcher : local!.watcher.finish(); - retirement = assertActiveStopRetirement({ completed: Boolean(completed), identityChanged: processError, processes, watcher: watch, + retirement = assertActiveStopRetirement({ completed: Boolean(completed ?? denied), identityChanged: processError, processes, watcher: watch, ...(remote ? { environment: "daytona" as const, remote: { scope: scope(), observations: remoteObservations } } : { environment: "local" as const, samples }) }); - if (!completed) throw new Error("Missing active Stop settlement"); - readActiveStopSettlement({ ...await load(), ...completed, bootstrap: bootstrap() }); + if (!completed && !denied) throw new Error("Missing active Stop settlement"); + await settle(); receipt.push({ id: "active-stop-retired-no-effects", passed: true, detail: remote ? "Exact run root/descendants retired with continuous no-effects proof through retirement; later UI/API checks do not claim fresh filesystem observation" : "Exact run root/descendants retired; unanswered target remained absent through cleanup" }); return receipt; } finally { @@ -153,15 +159,44 @@ export async function runNativeActiveStopFlow(input: { await page.goto(`/${fixtures.company.issuePrefix}/issues/${issue.identifier ?? issue.id}`); const card = page.getByTestId("task-chat-runtime-request").filter({ visible: true }); await expect(card).toHaveCount(1); await expect(card.getByRole("button", { name: "Deny", exact: true })).toBeEnabled(); - await input.capture("pending-permission", "Native permission left unanswered before Stop", "pending-permission.png"); await sample("pending"); - completed = await stopAtPendingPermission({ scope: scope(), caller, bootstrap: bootstrap(), deadlineAt: input.deadlineAt, load, - retain: proof => input.evidence("native-active-stop-pending.json", proof), stop: (runId, cancellationRequestId) => api.post(`/api/heartbeat-runs/${runId}/cancel`, { cancellationRequestId }) }); - check("pending-callback-cancelled", true, "Unanswered native permission closed through a cancelled provider turn and the exact caller-owned Stop acknowledgement"); - await input.evidence("native-active-stop-settlement.json", completed); - // Only after confirmed cancellation: test the real public stale-response fence. - const response = await api.request.post(`/api/heartbeat-runs/${runs[0]!.id}/runtime-requests/${encodeURIComponent(completed.pending.requestId)}/resolve`, { data: { turnId: completed.pending.turnId, requestKind: "permission_approval", resolution: { action: "accept" } } }); + await input.capture("pending-permission", denyFirst ? "Native permission awaiting the operator's denial" : "Native permission left unanswered before Stop", "pending-permission.png"); await sample("pending"); + if (denyFirst) { + const cancellationRequestId = randomUUID(); + const pending = observeActiveStopPending({ ...await load(), scope: scope(), caller, cancellationRequestId, bootstrap: bootstrap() }); + await input.evidence("native-permission-denial-pending.json", pending); + const route = `/api/heartbeat-runs/${pending.scope.runId}/runtime-requests/${encodeURIComponent(pending.requestId)}/resolve`; + const posted = page.waitForRequest(request => new URL(request.url()).pathname === route && request.method() === "POST"); + await card.getByRole("button", { name: "Deny", exact: true }).click(); + const answer = (await posted).postDataJSON(); + check("browser-exact-denial", answer.turnId === pending.turnId && answer.requestKind === "permission_approval" && answer.resolution?.action === "decline", + "The browser's Deny declines this exact run, turn and native request"); + // The operator then stops the unfinished task. A turn the provider already + // ended after the denial leaves nothing to stop; the settlement says which. + let stopDispatched = false; + try { + const stopped = await api.post(`/api/heartbeat-runs/${pending.scope.runId}/cancel`, { cancellationRequestId }); + stopDispatched = stopped.id === pending.scope.runId; + } catch { stopDispatched = false; } + const label = "denied native permission settlement"; + const attempt = async () => readDeniedPermissionSettlement({ ...await load(), pending, stopDispatched }); + const settlement = await pollUntil({ label, deadlineAt: input.deadlineAt, intervalMs: 200, + load: async () => { try { return await attempt(); } catch { return null; } }, accept: Boolean }) + // Surface the exact unmet condition rather than a bare timeout. + .catch(() => attempt()); + denied = { pending, stopDispatched, settlement: settlement! }; + check("native-denial-delivered", true, `Decline reached the exact native request before the turn ended (${denied.settlement.branch})`); + await input.evidence("native-permission-denial-settlement.json", denied); + } else { + completed = await stopAtPendingPermission({ scope: scope(), caller, bootstrap: bootstrap(), deadlineAt: input.deadlineAt, load, + retain: proof => input.evidence("native-active-stop-pending.json", proof), stop: (runId, cancellationRequestId) => api.post(`/api/heartbeat-runs/${runId}/cancel`, { cancellationRequestId }) }); + check("pending-callback-cancelled", true, "Unanswered native permission closed through a cancelled provider turn and the exact caller-owned Stop acknowledgement"); + await input.evidence("native-active-stop-settlement.json", completed); + } + const answered = denied?.pending ?? completed!.pending; + // Only after confirmed settlement: test the real public stale-response fence. + const response = await api.request.post(`/api/heartbeat-runs/${runs[0]!.id}/runtime-requests/${encodeURIComponent(answered.requestId)}/resolve`, { data: { turnId: answered.turnId, requestKind: "permission_approval", resolution: { action: "accept" } } }); check("stale-answer-refused", response.status() === 409, "Stopped permission rejects a later answer rather than replaying work"); - await load(); readActiveStopSettlement({ ...await load(), ...completed, bootstrap: bootstrap() }); + await settle(); if (remote) { // finish drains the observer's automatic retirement seal. It does not // extend the remote watch through subsequent host UI/cleanup assertions. @@ -177,20 +212,24 @@ export async function runNativeActiveStopFlow(input: { }; // Absence of a permission button during React loading is not proof that a // stopped request is unanswerable. First observe the actual task/run UI. - await expect(page.getByTestId("issue-detail-header").getByRole("button", { - name: "Change status (current: In Progress)", exact: true, - })).toBeVisible({ timeout: finalUiTimeout() }); - await expect(page.getByTestId("task-chat-thread").getByTestId("task-chat-collapsible-marker") - .filter({ has: page.getByText("Run cancelled", { exact: true }) })) - .toBeVisible({ timeout: finalUiTimeout() }); + const stoppedRun = !denied || denied.settlement.branch === "denied_then_stopped"; + if (stoppedRun) { + await expect(page.getByTestId("issue-detail-header").getByRole("button", { + name: "Change status (current: In Progress)", exact: true, + })).toBeVisible({ timeout: finalUiTimeout() }); + await expect(page.getByTestId("task-chat-thread").getByTestId("task-chat-collapsible-marker") + .filter({ has: page.getByText("Run cancelled", { exact: true }) })) + .toBeVisible({ timeout: finalUiTimeout() }); + } await expect(page.getByTestId("task-chat-history-loading")) .toHaveCount(0, { timeout: finalUiTimeout() }); await expect(card.getByRole("button", { name: "Deny", exact: true })) .toHaveCount(0, { timeout: finalUiTimeout() }); - await load(); readActiveStopSettlement({ ...await load(), ...completed, bootstrap: bootstrap() }); - check("one-unfinished-cancelled-run", runs.length === 1 && issue.status === "in_progress" && runs[0]!.status === "cancelled", "No automatic follow-up run or false task completion"); + await settle(); + check("one-unfinished-cancelled-run", runs.length === 1 && (stoppedRun ? issue.status === "in_progress" && runs[0]!.status === "cancelled" : issue.status !== "done"), + "No automatic follow-up run or false task completion"); await input.capture("final-state", "Stopped native permission is no longer answerable", "final-state.png"); - await input.evidence("api-state.json", { issue, run: runs[0], runs, checks, samples, remoteObservations, runEvents: events, runEventsByRun: [{ runId: runs[0]!.id, events }], activeStop: completed }); + await input.evidence("api-state.json", { issue, run: runs[0], runs, checks, samples, remoteObservations, runEvents: events, runEventsByRun: [{ runId: runs[0]!.id, events }], activeStop: completed, permissionDenial: denied }); return { issue, runs, checks }; } finally { // Local observation continues through cleanup. Remote cleanup revalidates diff --git a/tests/runner-e2e/native-active-stop-tasks.ts b/tests/runner-e2e/native-active-stop-tasks.ts index 3446ef501de..96cd7b620a9 100644 --- a/tests/runner-e2e/native-active-stop-tasks.ts +++ b/tests/runner-e2e/native-active-stop-tasks.ts @@ -8,3 +8,28 @@ export const nativeActiveStopTasks: readonly RunnerTaskFixture[] = [{ buildPrompt: () => "Attempt the supplied exact native operation once. Leave its native permission callback pending for the board operator. Do not answer, reject or cancel your own permission; do not retry, use another tool/path, call paperclip_finish, or claim completion. The operator will stop this unfinished task while permission is still unanswered.", buildMatchers: () => [], // Dedicated flow requires pending API observation, caller-owned Stop and retirement. }]; +/** + * Playbook section 13 "Permission denial" for providers whose proof is the + * canonical stream alone (Antigravity): the operator denies the real native + * permission in the browser, then stops the task. Same flow as the pending + * Stop, with a browser denial first. + */ +export const nativePermissionDenialTasks: readonly RunnerTaskFixture[] = [{ + id: "permission-deny-stop", label: "Deny a native permission, then Stop", groups: [], workMode: "standard", flow: "native_active_stop", + expectedRunCount: 1, attemptTimeoutMs: { local: 300_000, daytona: 300_000 }, turnTimeoutMs: 120_000, + expectedTerminalState: { issue: "in_progress", run: "cancelled" }, + buildTitle: nonce => `Native permission denial ${nonce}`, + buildVisibleMarker: nonce => `NATIVE-PERMISSION-DENIAL-${nonce}`, + buildPrompt: () => "Attempt the supplied exact native operation once and wait for the board operator's permission decision. If it is denied, do not retry, do not use another tool or path, do not call paperclip_finish and do not claim completion; say only that the operation was denied. The operator will then stop this unfinished task.", + buildMatchers: () => [], // Dedicated flow: browser denial, delivered decline, Stop and no-effect proof. +}]; +/** Shared native transport-loss fixture: the run root is lost while a native mutation waits for permission. */ +export const nativeProviderLossTasks: readonly RunnerTaskFixture[] = [{ + id: "pending-permission-provider-loss", label: "Owned runtime loss with pending permission", groups: [], workMode: "standard", flow: "native_provider_loss", + expectedRunCount: 1, attemptTimeoutMs: { local: 300_000, daytona: 300_000 }, turnTimeoutMs: 120_000, + expectedTerminalState: { issue: "blocked", run: "failed" }, + buildTitle: nonce => `Native provider loss ${nonce}`, + buildVisibleMarker: nonce => `NATIVE-PROVIDER-LOSS-${nonce}`, + buildPrompt: () => "Attempt the supplied exact native shell operation once and leave its permission callback unanswered. Do not retry, use another tool or path, answer your own permission, call paperclip_finish, or claim completion. The qualification fixture will deliberately lose the isolated runtime before any approval.", + buildMatchers: () => [], +}]; diff --git a/tests/runner-e2e/native-completion-defaults.test.ts b/tests/runner-e2e/native-completion-defaults.test.ts index 8777a2cb39b..df3d39dc261 100644 --- a/tests/runner-e2e/native-completion-defaults.test.ts +++ b/tests/runner-e2e/native-completion-defaults.test.ts @@ -32,11 +32,13 @@ describe("native production defaults", () => { const completion = suite.tasks.find(value => value.id === original.id)!; expect({ ...completion, automaticRetryPolicy: undefined }).toEqual({ ...original, automaticRetryPolicy: undefined }); expect(suite.manualOnly).toBe(true); - expect(suite.expectedMatrixSize).toBe(6); + // Six default cells plus two cells for the opt-in Antigravity profile. + expect(suite.expectedMatrixSize).toBe(8); + expect(suite.profiles.filter(profile => !profile.explicitOnly)).toHaveLength(3); expect(suite.tasks).toHaveLength(2); expect(suite.tasks.every(task => task.expectedRunCount === 1 && task.automaticRetryPolicy === "single_attempt")).toBe(true); expect(suite.environments.map(value => value.id)).toEqual(["local"]); - expect(suite.profiles.map(value => value.id).sort()).toEqual(["runner-acpx-claude", "runner-codex", "runner-opencode"]); + expect(suite.profiles.filter(value => !value.explicitOnly).map(value => value.id).sort()).toEqual(["runner-acpx-claude", "runner-codex", "runner-opencode"]); }); it("accepts only the unchanged master default and bounded budgets", () => expect(gradeNativeDefault(receipt()).passed).toBe(true)); it.each(["qa", "reduced", "extra-file", "wrong-entry", "company-unbounded", "agent-unbounded"])("rejects %s override", name => { diff --git a/tests/runner-e2e/native-provider-loss-flow.ts b/tests/runner-e2e/native-provider-loss-flow.ts index e7525d901c8..b2765a8384a 100644 --- a/tests/runner-e2e/native-provider-loss-flow.ts +++ b/tests/runner-e2e/native-provider-loss-flow.ts @@ -46,12 +46,13 @@ export async function runNativeProviderLossFlow(input: { evidence(name: string, value: unknown): Promise; }) { const { api, page, fixtures, execution, nonce } = input; - if (execution.profile.qualificationCandidate !== "cursor" || execution.task.id !== "pending-permission-provider-loss") throw new Error("Unknown provider-loss case"); + const provider = execution.profile.qualificationCandidate; + if ((provider !== "cursor" && provider !== "antigravity") || execution.task.id !== "pending-permission-provider-loss") throw new Error("Unknown provider-loss case"); const remote = execution.environment.id === "daytona"; if (remote && !input.remoteBootstrap) throw new Error("Provider loss requires its admitted remote observer"); const local = remote ? undefined : await createDeniedTargetFixture(input.workspacePath, `provider-loss-${nonce}.txt`); const target = local?.targetRelativePath ?? `provider-loss-${nonce}.txt`; - let command = local ? cursorDeniedCommand(local.targetPath) : undefined; + let command = provider === "cursor" && local ? cursorDeniedCommand(local.targetPath) : undefined; const observer = remote ? undefined : observeRunProcesses(); let issue: Row = {}, runs: Row[] = [], events: Row[] = []; let fixture: NativeRemoteFixture | undefined, baseline: NativeRemoteSnapshot | undefined, sealed: NativeRemoteSnapshot | undefined; @@ -59,7 +60,7 @@ export async function runNativeProviderLossFlow(input: { let pending: ActiveStopPending | undefined, settled = false; const checks: Check[] = [], samples: Array<{ phase: string; absent: boolean }> = []; const check = (id: string, ok: boolean, detail: string) => { checks.push({ id, passed: ok, detail }); expect(ok, detail).toBe(true); }; - const scope = (): ActiveStopScope => ({ provider: "cursor", companyId: fixtures.company.id, issueId: issue.id, runId: runs[0]!.id, target, commandSha256: command!.commandSha256 }); + const scope = (): ActiveStopScope => ({ provider, companyId: fixtures.company.id, issueId: issue.id, runId: runs[0]!.id, target, ...(command ? { commandSha256: command.commandSha256 } : {}) }); const bootstrap = (): BootstrapReadProof | undefined => fixture ? { actionFile: fixture.actionFile, events } : undefined; const authority = () => { const run = runs[0]!; return { pid: run.processPid, groupId: run.processGroupId, startedAt: run.processStartedAt, runId: run.id }; }; const load = async () => { @@ -97,11 +98,14 @@ export async function runNativeProviderLossFlow(input: { } }; (remote ? input.registerBeforeEnvironmentTeardownAssertion : input.registerCleanupAssertion)(cleanup); - const prompt = () => `${execution.task.buildPrompt(nonce)}\nUse this exact native shell command once:\n${command!.command}`; + // Antigravity has no command-digest notice; its oracle is the exact native edit target. + const prompt = () => provider === "cursor" + ? `${execution.task.buildPrompt(nonce)}\nUse this exact native shell command once:\n${command!.command}` + : `${execution.task.buildPrompt(nonce)}\nInstead of a shell command, use the native file edit tool once to create exactly ${target} with content MUST_NOT_EXIST.`; try { const caller = readActiveStopCaller(await api.get("/api/health"), await api.get("/api/auth/get-session")); const agent = await api.get(`/api/agents/${fixtures.agent.id}`); - await api.patch(`/api/agents/${fixtures.agent.id}`, { adapterConfig: { ...agent.adapterConfig, acpxPermissionMode: "approve-reads", acpxSessionMode: "agent", timeoutSec: 120, lifecycleMode: "per_turn" } }); + await api.patch(`/api/agents/${fixtures.agent.id}`, { adapterConfig: { ...agent.adapterConfig, acpxPermissionMode: "approve-reads", ...(provider === "cursor" ? { acpxSessionMode: "agent" } : {}), timeoutSec: 120, lifecycleMode: "per_turn" } }); const project = await api.post(`/api/companies/${fixtures.company.id}/projects`, { name: `Native provider loss ${nonce}`, executionWorkspacePolicy: { enabled: true, defaultMode: "shared_workspace", sharedWorkspaceConcurrency: "serialize", allowIssueOverride: false, environmentId: fixtures.environment.id, workspaceStrategy: { type: "project_primary" } }, workspace: { name: "Primary", sourceType: "local_path", cwd: input.workspacePath, isPrimary: true } }); if (!remote) await sample("before-request"); const createdTask = await createTaskThroughUi({ page, issuePrefix: fixtures.company.issuePrefix!, agentName: fixtures.agent.name, title: execution.task.buildTitle(nonce), prompt: remote ? input.remoteBootstrap!.prompt(nonce) : prompt(), workMode: "standard", projectName: project.name, requireExplicitTitle: true }); @@ -110,7 +114,7 @@ export async function runNativeProviderLossFlow(input: { if (remote) { await pollUntil({ label: "provider-loss bootstrap", deadlineAt: input.deadlineAt, load, accept: value => value.run.status === "running" }); fixture = await input.remoteBootstrap!.bindAndRelease({ issueId: issue.id, runId: runs[0]!.id, targets: [target], actionPrompt: async value => { - fixture = value; command = cursorDeniedCommand(join(value.remoteCwd, target)); + fixture = value; if (provider === "cursor") command = cursorDeniedCommand(join(value.remoteCwd, target)); const prepared = await prepareNativeRemoteAction({ fixture: value, companyId: fixtures.company.id, environmentId: fixtures.environment.id, runId: runs[0]!.id, target, prompt: prompt() }); baseline = prepared.baseline; await input.evidence("provider-loss-baseline.json", baseline); return prepared.prompt; } }); diff --git a/tests/runner-e2e/pi-provider-fault.py b/tests/runner-e2e/pi-provider-fault.py index 56537a8b53f..83dc8e70425 100644 --- a/tests/runner-e2e/pi-provider-fault.py +++ b/tests/runner-e2e/pi-provider-fault.py @@ -163,9 +163,13 @@ def inspect(config): parent_args = argv(parent) if len(parent_args) != 4 or not parent_args[3].endswith('/distribution/pi-entry.cjs'): continue + # The wrapper runs the pinned closure from the runner's sealed store for + # this exact closure, with the module guard from its per-launch directory. distribution = parent_args[3][:-len('/pi-entry.cjs')] - require(re.fullmatch(r'/tmp/paperclip-acpx-native-[A-Za-z0-9_-]+/distribution', distribution), 'snapshot_path') - require(parent_args[1:] == ['--require', distribution + '/' + GUARD, distribution + '/pi-entry.cjs'], 'wrapper_parent') + require(re.fullmatch(r'/tmp/paperclip-verified-native-[A-Za-z0-9_-]+/' + re.escape(config['closureSha256']) + '/distribution', distribution), 'snapshot_path') + launch = os.path.dirname(parent_args[2]) + require(re.fullmatch(r'/tmp/paperclip-acpx-native-[A-Za-z0-9_-]+/launch', launch), 'snapshot_path') + require(parent_args[1:] == ['--require', launch + '/' + GUARD, distribution + '/pi-entry.cjs'], 'wrapper_parent') descriptor = None if parent_args[0] != distribution + '/' + NODE: # Production nativeBootstrap executes the held Node through child @@ -177,7 +181,7 @@ def inspect(config): # Pi sets process.title and overwrites Linux argv. The exact pinned # parent's launch code attests the entrypoint; title alone never selects. require(argv(pid) == ['pi'], 'pi_process_title') - for directory in (distribution, os.path.dirname(distribution)): + for directory in (launch, os.path.dirname(launch), distribution, os.path.dirname(distribution)): st = os.lstat(directory) require(stat.S_ISDIR(st.st_mode) and not st.st_mode & 0o222 and os.path.realpath(directory) == directory, 'snapshot_seal') require(os.readlink(f'/proc/{pid}/cwd') == binding['remoteCwd'], 'cwd') diff --git a/tests/runner-e2e/pi-provider-fault.test.py b/tests/runner-e2e/pi-provider-fault.test.py index 2b93b01a5c1..14e5f72332f 100644 --- a/tests/runner-e2e/pi-provider-fault.test.py +++ b/tests/runner-e2e/pi-provider-fault.test.py @@ -22,7 +22,7 @@ BOOT = '12345678-1234-1234-1234-123456789abc' ROOT = {'pid': 21, 'ppid': 1, 'startTicks': '100', 'bootId': BOOT} PARENT = {'pid': 22, 'ppid': 21, 'startTicks': '101', 'bootId': BOOT} TARGET = {'pid': 23, 'ppid': 22, 'startTicks': '102', 'bootId': BOOT} -DIST = '/tmp/paperclip-acpx-native-fixture/distribution' +LAUNCH = '/tmp/paperclip-acpx-native-fixture/launch' RUNTIME = '/workspace/.paperclip-runtime/paperclip-runner' CANCELLED = False @@ -31,6 +31,9 @@ def check_cancelled(): NAMES = [fault.NODE, fault.ENTRY, fault.EXTENSION, 'pi-entry.cjs', 'node_modules/pi-acp/dist/index.js', 'node_modules/pi-acp/dist/paperclip-runtime.js'] +FIXTURE_PIN = fault.digest(json.dumps([{'path': n, 'sha256': fault.digest(n.encode()), 'size': len(n), 'executable': n == fault.NODE} for n in sorted(NAMES)], separators=(',', ':'), ensure_ascii=False).encode()) +# The runner's sealed verified store for this exact closure. +DIST = '/tmp/paperclip-verified-native-501/' + FIXTURE_PIN + '/distribution' class ClosureMetadataTests(unittest.TestCase): @@ -97,7 +100,8 @@ class IdentityTests(unittest.TestCase): 'runnerdSha256': 'sha256:' + fault.digest(b'runner'), 'closureSha256': fault.digest(json.dumps(entries, separators=(',', ':'), ensure_ascii=False).encode())} self.table = {21: ROOT, 22: PARENT, 23: TARGET} self.args = {21: [RUNTIME + '/bin/paperclip-runnerd', '--run-id', 'run', '--environment-lease-id', 'workspace-id', '--lifecycle-mode', 'per_turn', '--state-dir', RUNTIME + '/sessions/' + 'a' * 64 + '/runner'], - 22: [DIST + '/' + fault.NODE, '--require', DIST + '/' + fault.GUARD, DIST + '/pi-entry.cjs'], 23: ['pi']} + 22: [DIST + '/' + fault.NODE, '--require', LAUNCH + '/' + fault.GUARD, DIST + '/pi-entry.cjs'], 23: ['pi']} + self.assertEqual(self.config['closureSha256'], FIXTURE_PIN) self.patches = [patch.object(fault, 'proc', side_effect=lambda pid, boot: self.table[pid]), patch.object(fault, 'argv', side_effect=lambda pid: self.args[pid]), patch.object(fault, 'checked_runner_executable', side_effect=lambda p: self.files[p]), patch.object(fault, 'checked_file', side_effect=lambda p, *a: self.files[p]), patch.object(Path, 'read_text', return_value=BOOT), @@ -139,6 +143,17 @@ class IdentityTests(unittest.TestCase): for field, value in [('closureSha256', '0' * 64), ('runtimeEnvironmentLeaseId', 'foreign'), ('runnerdSha256', 'sha256:' + '0' * 64)]: with self.subTest(field=field), self.assertRaises(RuntimeError): fault.inspect({**self.config, field: value}) + def test_wrapper_must_run_the_sealed_store_with_its_launch_guard(self): + for distribution in ['/tmp/paperclip-acpx-native-fixture/distribution', '/tmp/paperclip-verified-native-501/' + '0' * 64 + '/distribution']: + self.args[22][0], self.args[22][3] = distribution + '/' + fault.NODE, distribution + '/pi-entry.cjs' + with self.subTest(distribution=distribution), self.assertRaisesRegex(RuntimeError, 'snapshot_path'): + fault.inspect(self.config) + self.args[22][0], self.args[22][3] = DIST + '/' + fault.NODE, DIST + '/pi-entry.cjs' + for guard in [DIST + '/' + fault.GUARD, '/tmp/elsewhere/launch/' + fault.GUARD]: + self.args[22][2] = guard + with self.subTest(guard=guard), self.assertRaisesRegex(RuntimeError, 'snapshot_path'): + fault.inspect(self.config) + def test_wrong_title_is_not_a_generic_node_selector(self): self.args[23] = ['node'] with self.assertRaisesRegex(RuntimeError, 'pi_process_title'): fault.inspect(self.config) @@ -232,8 +247,12 @@ class PidfdTests(unittest.TestCase): def calibrate_real_child(self, descriptor=None, runner_link=False): node = shutil.which('node'); self.assertIsNotNone(node) base = Path(tempfile.mkdtemp(prefix='pi-fault-calibration-', dir='/tmp')) + # Production layout: a per-launch directory holds the module guard; the + # pinned closure runs from the runner's sealed store keyed by its pin. snapshot = Path(tempfile.mkdtemp(prefix='paperclip-acpx-native-', dir='/tmp')) - distribution = snapshot / 'distribution'; workspace = base / 'workspace'; workspace.mkdir() + launch_dir = snapshot / 'launch'; launch_dir.mkdir() + store = Path(tempfile.mkdtemp(prefix='paperclip-verified-native-', dir='/tmp')) + distribution = store / 'staged' / 'distribution'; workspace = base / 'workspace'; workspace.mkdir() runtime = workspace / '.paperclip-runtime/paperclip-runner'; (runtime / 'bin').mkdir(parents=True) pack = base / 'pack'; (pack / 'provider-assets/pi/linux-x64').mkdir(parents=True) root_child = None @@ -258,17 +277,22 @@ class PidfdTests(unittest.TestCase): # still-empty file. publish = 'const publish=(f,v)=>{const fs=require("node:fs"),t=f+".tmp";fs.writeFileSync(t,JSON.stringify(v));fs.renameSync(t,f)};' (distribution / fault.ENTRY).write_text(publish + 'process.title="pi"; publish(' + json.dumps(str(ready)) + ',{pid:process.pid});setInterval(()=>{},1000);') - (distribution / 'pi-entry.cjs').write_text(publish + 'const p=require("node:child_process").spawn(process.execPath,["--require",' + json.dumps(str(distribution / fault.GUARD)) + ',' + json.dumps(str(distribution / fault.ENTRY)) + '],{stdio:"ignore"});p.on("exit",(code,signal)=>publish(' + json.dumps(str(exited)) + ',{code,signal}));process.on("SIGTERM",()=>{if(p.exitCode!==null||p.signalCode!==null)process.exit(0);p.once("exit",()=>process.exit(0));p.kill("SIGTERM")});setInterval(()=>{},1000);') + (launch_dir / fault.GUARD).write_text('// fixture\n') + # Like production pi-entry.cjs, name the sibling guard and entry by __dirname. + (distribution / 'pi-entry.cjs').write_text(publish + 'const path=require("node:path");const p=require("node:child_process").spawn(process.execPath,["--require",path.join(__dirname,' + json.dumps(fault.GUARD) + '),path.join(__dirname,' + json.dumps(fault.ENTRY) + ')],{stdio:"ignore"});p.on("exit",(code,signal)=>publish(' + json.dumps(str(exited)) + ',{code,signal}));process.on("SIGTERM",()=>{if(p.exitCode!==null||p.signalCode!==null)process.exit(0);p.once("exit",()=>process.exit(0));p.kill("SIGTERM")});setInterval(()=>{},1000);') entries = [] for name in sorted(NAMES): p = distribution / name; content = p.read_bytes(); entries.append({'path': name, 'sha256': fault.digest(content), 'size': len(content), 'executable': name == fault.NODE}) closure = json.dumps({'entries': entries}).encode(); (pack / 'provider-assets/pi/linux-x64/native-closure.json').write_bytes(closure) - for directory, dirs, files in os.walk(snapshot): - for f in files: - p = Path(directory) / f; p.chmod(0o500 if p == distribution / fault.NODE else 0o400) - Path(directory).chmod(0o500) + pin = fault.digest(json.dumps(entries, separators=(',', ':'), ensure_ascii=False).encode()) + (store / 'staged').rename(store / pin); distribution = store / pin / 'distribution' + for sealed in (snapshot, store / pin): + for directory, dirs, files in os.walk(sealed): + for f in files: + p = Path(directory) / f; p.chmod(0o500 if p == distribution / fault.NODE else 0o400) + Path(directory).chmod(0o500) node_path = shlex.quote(str(distribution / fault.NODE)) - wrapper = '--require ' + shlex.quote(str(distribution / fault.GUARD)) + ' ' + shlex.quote(str(distribution / 'pi-entry.cjs')) + wrapper = '--require ' + shlex.quote(str(launch_dir / fault.GUARD)) + ' ' + shlex.quote(str(distribution / 'pi-entry.cjs')) launch = node_path + ' ' + wrapper + ' /dev/null 2>&1' if descriptor is not None: # Production nativeBootstrap keeps its executable descriptor @@ -336,8 +360,10 @@ class PidfdTests(unittest.TestCase): self.assertTrue(select.select([fd], [], [], 3)[0], 'owned descendant must retire') finally: for fd in owned_fds: os.close(fd) - for directory, dirs, files in os.walk(snapshot): os.chmod(directory, 0o700) - shutil.rmtree(snapshot); shutil.rmtree(base) + for sealed in (snapshot, store): + for directory, dirs, files in os.walk(sealed): os.chmod(directory, 0o700) + shutil.rmtree(sealed) + shutil.rmtree(base) if __name__ == '__main__': diff --git a/tests/runner-e2e/pi-provider-fault.test.ts b/tests/runner-e2e/pi-provider-fault.test.ts index 9ddf2131e27..b64602d6121 100644 --- a/tests/runner-e2e/pi-provider-fault.test.ts +++ b/tests/runner-e2e/pi-provider-fault.test.ts @@ -22,7 +22,7 @@ it("calibrates the exact Pi fault helper with metadata negatives and native Linu expect(result.error).toBeUndefined(); expect(result.signal).toBeNull(); expect(result.status, result.stderr).toBe(0); - expect(result.stderr).toContain("Ran 21 tests"); + expect(result.stderr).toContain("Ran 22 tests"); if (process.platform === "linux") expect(result.stderr).not.toContain("skipped"); else expect(result.stderr).toContain("skipped=3"); console.info(result.stderr.trim()); diff --git a/tests/runner-e2e/remote-native-fixtures.test.ts b/tests/runner-e2e/remote-native-fixtures.test.ts index ca5b8cebccf..6807520e3b5 100644 --- a/tests/runner-e2e/remote-native-fixtures.test.ts +++ b/tests/runner-e2e/remote-native-fixtures.test.ts @@ -889,7 +889,7 @@ describe("actual generated observer state machine", () => { it.each(["valid", "wrong-inode", "foreign-executable", "ambiguous", "wrong-arguments"])("dispatches generated provider death only for verified descriptor ownership: %s", async variant => { const o = await observerHarness(); o.request("snapshot"); o.request("publish", { path: "action.txt", text: "do task" }); - const executable = "/tmp/paperclip-acpx-native-owned/distribution/copilot"; + const executable = "/tmp/paperclip-verified-native-501/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee/distribution/copilot"; o.proc.set(22, { ppid: 21, group: 21, ticks: "200", argv: ["/node"] }); o.proc.set(23, { ppid: 22, group: 21, ticks: "300", argv: ["/proc/self/fd/7", ...copilotDeathArguments] }); o.processExecutables.set("/proc/23/exe", { path: executable, dev: 1n, ino: 40n }); diff --git a/tests/runner-e2e/remote-native-fixtures.ts b/tests/runner-e2e/remote-native-fixtures.ts index 44602354b26..97c2e2bb2b3 100644 --- a/tests/runner-e2e/remote-native-fixtures.ts +++ b/tests/runner-e2e/remote-native-fixtures.ts @@ -1,5 +1,5 @@ import { canonicalRemoteCopilotCommand, copilotDeathArguments, selectOwnedCopilotProcess } from "./copilot-provider-death.js"; -import { expectedNativeBootstrap, expectedNativeModuleGuard, KIMI_FAULT_SNAPSHOT, kimiFaultRuntimeContract, validateKimiProviderDeathReceipt, type KimiProviderDeathReceipt } from "./kimi-provider-fault-contract.js"; +import { expectedNativeBootstrap, expectedNativeModuleGuard, KIMI_FAULT_LAUNCH, KIMI_FAULT_SNAPSHOT, kimiFaultRuntimeContract, validateKimiProviderDeathReceipt, type KimiProviderDeathReceipt } from "./kimi-provider-fault-contract.js"; import { createHash, randomBytes } from "node:crypto"; import { watch, lstatSync, readFileSync } from "node:fs"; import { posix } from "node:path"; @@ -587,7 +587,7 @@ export async function bindRemoteNativeFixture(options: RemoteNativeFixtureOption kimiFaultAttempted = true; const contract = kimiFaultRuntimeContract("linux-x64"); const receipt = await rpc({ op: "kimi-provider-death", runtimeEnvironmentLeaseId, contract, - bootstrapTemplate: expectedNativeBootstrap(KIMI_FAULT_SNAPSHOT, contract.nodeSha256), guardTemplate: expectedNativeModuleGuard(KIMI_FAULT_SNAPSHOT, []) }); + bootstrapTemplate: expectedNativeBootstrap(KIMI_FAULT_LAUNCH, KIMI_FAULT_SNAPSHOT, contract.nodeSha256), guardTemplate: expectedNativeModuleGuard(KIMI_FAULT_SNAPSHOT, []) }); return validateKimiProviderDeathReceipt(receipt, binding!, baseline.processes.root!, runtimeEnvironmentLeaseId); }, async readFile(path) { diff --git a/tests/runner-e2e/runner.spec.ts b/tests/runner-e2e/runner.spec.ts index 9d368ea2561..5982d45b8c6 100644 --- a/tests/runner-e2e/runner.spec.ts +++ b/tests/runner-e2e/runner.spec.ts @@ -13,7 +13,7 @@ import { isProductDeliveredSecret, trackedPrivateSecrets } from "./private-diagn import { findChatCatalogCase } from "./chat-catalog-registry.js"; import { runChatBoundaryFlow } from "./chat-boundary-flow.js"; import { chatCatalogScenarios } from "./chat-catalog-inventory.js"; -import { kimiCandidateAdmissionForExecution } from "./server-restart-request.js"; +import { candidateAdmissionForExecution } from "./server-restart-request.js"; import { runPlanRevisionAcceptance, isPendingPlanConfirmation, normalizePlanMarkdown, expectPlanStageVisible } from "./plan-revision-flow.js"; import { createWorkerTiming } from "./worker-timing.js"; import { captureTaskChat, type TaskChatEvidence } from "./task-chat.js"; @@ -643,9 +643,9 @@ for (const execution of executions) { }) : undefined; const saveTrace = async () => { if (trace) await writeSanitizedJson(snapshotsDir, "braintrust-trace.json", trace.snapshot(), secrets); }; const onCompanyCreated = async (id: string) => { - const admission = kimiCandidateAdmissionForExecution(execution, id); + const admission = candidateAdmissionForExecution(execution, id); if (admission) { - await restartIsolatedPaperclipServer({ api, requestId: `kimi-startup-${nonce}`, + await restartIsolatedPaperclipServer({ api, requestId: `${admission.agent}-startup-${nonce}`, kimiCandidateAdmission: admission, deadlineAt: startedAtMs + deadlineMs }); if (execution.environment.id === "daytona") { await waitForFixtureDaytonaProvider(api, { companyId: id, deadlineAt: startedAtMs + deadlineMs }); diff --git a/tests/runner-e2e/selectors.ts b/tests/runner-e2e/selectors.ts index 149fdbce1ce..42bc5c18cb2 100644 --- a/tests/runner-e2e/selectors.ts +++ b/tests/runner-e2e/selectors.ts @@ -1,4 +1,5 @@ import { runnerMatrix } from "./catalog.js"; +import { QUALIFIED_ACPX_PROFILES } from "../../packages/paperclip-runner/src/drivers/acpx/qualified-profiles.js"; import type { MatrixExecution, MatrixJob } from "./types.js"; export interface RunnerSelectorOptions { @@ -210,6 +211,8 @@ export function selectRunnerExecutions( if (execution.suite.manualOnly && !options.suites.includes(execution.suite.id) && !options.list) return false; const unfilteredList = options.list && options.groups.length + options.suites.length + options.profiles.length + options.environments.length + options.cases.length === 0; + // An opt-in profile requires its own name; a suite selector alone never adds it. + if (execution.profile.explicitOnly && !unfilteredList && !options.profiles.includes(execution.profile.id)) return false; const explicitGroup = execution.task.explicitGroup; // Naming any of the task's own groups (for example `slow`) also opts in. if (explicitGroup && !unfilteredList && !options.groups.some(group => group === explicitGroup || execution.task.groups.includes(group)) @@ -268,3 +271,19 @@ export function buildMatrixJobs( })) .sort((left, right) => left.executionId.localeCompare(right.executionId)); } + +/** + * The pending ACPX candidates the selected Daytona cells run. The Daytona + * image and the controller's provider pack must both carry exactly these + * (`--candidate-providers`), derived from the profiles rather than typed in. + * A released provider is in the default pack and is never listed. + */ +export function daytonaCandidateProviders(executions: readonly MatrixExecution[]): string[] { + const candidates = new Set(); + for (const execution of executions) { + const candidate = execution.profile.qualificationCandidate; + if (execution.environment.id === "daytona" && candidate && + QUALIFIED_ACPX_PROFILES[candidate].qualificationStatus === "pending") candidates.add(candidate); + } + return [...candidates].sort(); +} diff --git a/tests/runner-e2e/server-restart-request.ts b/tests/runner-e2e/server-restart-request.ts index dc335c83c3b..e21aa7739ac 100644 --- a/tests/runner-e2e/server-restart-request.ts +++ b/tests/runner-e2e/server-restart-request.ts @@ -5,6 +5,7 @@ import { parseAcpxCandidateAdmission, type AcpxCandidateAdmission } from "../../ import { QUALIFIED_ACPX_PROFILES } from "../../packages/paperclip-runner/src/drivers/acpx/qualified-profiles.js"; import { KIMI_DISTRIBUTION_CLOSURE_SHA256 } from "../../packages/paperclip-runner/src/drivers/acpx/kimi-closure-pins.js"; import type { MatrixExecution } from "./types.js"; +import { antigravityCandidateAdmissionForExecution, isAntigravityAdmittedExecution } from "./antigravity-admission.js"; import { controllerOutageForExecution, parseControllerOutage, type ControllerOutage } from "./controller-outage.js"; import { parseRecoveryBinding, type RecoveryBinding } from "./controller-recovery-observer.js"; import { parseFinalizationCrashBinding, type FinalizationCrashBinding } from "./finalization-crash-boundary.js"; @@ -22,6 +23,13 @@ export interface RestartRequest { recoveryBinding?: RecoveryBinding; } +/** Company-bound startup authority for a pending candidate cell, if it needs one. */ +export function candidateAdmissionForExecution(execution: MatrixExecution, companyId: string, now = Date.now()): AcpxCandidateAdmission | undefined { + return execution.profile.qualificationCandidate === "antigravity" + ? antigravityCandidateAdmissionForExecution(execution, companyId, now) + : kimiCandidateAdmissionForExecution(execution, companyId, now); +} + export function kimiCandidateAdmissionForExecution(execution: MatrixExecution, companyId: string, now = Date.now()): AcpxCandidateAdmission | undefined { if (execution.suite.id !== "kimi-qualification" || execution.profile.qualificationCandidate !== "kimi" || QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus !== "pending") return undefined; @@ -37,18 +45,23 @@ export function kimiCandidateAdmissionForExecution(execution: MatrixExecution, c expiresAt: now + 60 * 60 * 1000 }, { companyId, agent: "kimi", model: execution.profile.model }, now); } +/** The staged grant must belong to a selected explicit candidate cell and its target. */ function selectedKimiCandidateAdmission(value: unknown, executionIds: readonly string[]): AcpxCandidateAdmission { const executions = executionIds.map(id => runnerMatrix.find(row => row.id === id)); - if (!executions.length || executions.some(row => !row || row.suite.id !== "kimi-qualification" - || !row.suite.manualOnly || row.profile.id !== "runner-acpx-kimi" || row.profile.qualificationCandidate !== "kimi")) { - throw new Error("Kimi authority staging requires an explicit Kimi qualification selection"); - } const record = value as Partial | null; - if (!record || typeof record.companyId !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(record.companyId)) throw new Error("Invalid Kimi fixture company"); - const admission = parseAcpxCandidateAdmission(value, { companyId: record.companyId, agent: "kimi", model: executions[0]!.profile.model }); - if (!executions.some(row => row!.environment.expectedExecutionTarget.kind === "remote" + const agent = record?.agent; + if (!executions.length || (agent !== "kimi" && agent !== "antigravity") || executions.some(row => !row || (agent === "kimi" + ? row.suite.id !== "kimi-qualification" || !row.suite.manualOnly || row.profile.id !== "runner-acpx-kimi" || row.profile.qualificationCandidate !== "kimi" + : !isAntigravityAdmittedExecution(row)))) { + throw new Error("Candidate authority staging requires an explicit Kimi or Antigravity qualification selection"); + } + if (!record || typeof record.companyId !== "string" || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(record.companyId)) throw new Error("Invalid candidate fixture company"); + const matching = executions.filter(row => row!.profile.model === record.model); + if (!matching.length) throw new Error("Candidate fixture model does not match the selected execution"); + const admission = parseAcpxCandidateAdmission(value, { companyId: record.companyId, agent, model: matching[0]!.profile.model }); + if (!matching.some(row => row!.environment.expectedExecutionTarget.kind === "remote" ? admission.platform === "linux" && admission.architecture === "x64" - : admission.platform === process.platform && admission.architecture === process.arch)) throw new Error("Kimi fixture target does not match the selected execution"); + : admission.platform === process.platform && admission.architecture === process.arch)) throw new Error("Candidate fixture target does not match the selected execution"); return admission; } @@ -78,10 +91,10 @@ export async function readRestartRequest(restartRequestPath: string, executionId const kimiAuthority = (value as { kimiCandidateAdmission?: unknown }).kimiCandidateAdmission; const kimiCandidateAdmission = kimiAuthority === undefined ? undefined : selectedKimiCandidateAdmission(kimiAuthority, executionIds); if (kimiCandidateAdmission && Object.keys(value).some(key => !["requestId", "kimiCandidateAdmission", "discardControllerCache"].includes(key))) { - throw new Error("Kimi startup authority staging cannot combine another restart operation"); + throw new Error("Candidate startup authority staging cannot combine another restart operation"); } if (kimiCandidateAdmission && (value as { discardControllerCache?: unknown }).discardControllerCache === true) { - throw new Error("Kimi startup authority staging cannot replace controller state"); + throw new Error("Candidate startup authority staging cannot replace controller state"); } const preserveRunner = (value as { preserveRunner?: unknown }).preserveRunner; const controllerDowntimeMs = (value as { controllerDowntimeMs?: unknown }).controllerDowntimeMs; diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index aee268d9087..958e426e798 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -69,6 +69,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-runtime.test.ts": "f9ebcc9430be51c342b42644b735f1434b405ec7", "packages/shared/src/api.ts": "1d61cdff51433c4136368d52ee7cf2f16aa820ed", "packages/shared/src/app-definitions-url.test.ts": "56792d6745a5bc7eafc36e7403f4c9bbd671ae99", @@ -272,7 +275,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "9c9d4c7e805c2d701a3367ce3c2fe9863210f7ea", + "packages/shared/src/index.ts": "92261d37eff283b4eaac2566bab089d426e9f987", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", diff --git a/tests/runner-e2e/types.ts b/tests/runner-e2e/types.ts index 3903c9b80d4..ff4f4a9715e 100644 --- a/tests/runner-e2e/types.ts +++ b/tests/runner-e2e/types.ts @@ -97,7 +97,13 @@ export interface RunnerProfileFixture { | "openrouter_rankings_snapshot"; qualificationId: string; }; - qualificationCandidate?: "cursor" | "copilot" | "pi" | "kimi"; + qualificationCandidate?: "cursor" | "copilot" | "pi" | "kimi" | "antigravity"; + /** + * Opt-in profile. Its cells are selected only when `--profile` names it or an + * exact execution ID is given; suite, group, case and environment selectors + * alone never select it. + */ + explicitOnly?: true; ranking?: { rank: number; canonicalModelId: string; diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx index 19c4207044c..ea5a348b762 100644 --- a/ui/src/components/AgentConfigForm.tsx +++ b/ui/src/components/AgentConfigForm.tsx @@ -1,6 +1,6 @@ import { environmentSupportsLoginPty } from "@paperclipai/shared"; import { matchesAdapterLoginTarget, useAdapterLoginCancellation } from "./useAdapterLoginCancellation"; -import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, isAccountBoundAcpxAgent } from "@/lib/native-model-catalog"; +import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, antigravityModelGroup, isAccountBoundAcpxAgent } from "@/lib/native-model-catalog"; import { useConnectionModels } from "./ai-connections/useConnectionModels"; import { agentHarnessType, agentRunner, paperclipRunnerProfileForHarness, normalizeClaudeRunnerOptions, type AgentRunnerChoice } from "@paperclipai/shared"; import { adaptersApi } from "../api/adapters"; @@ -1055,6 +1055,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) { const cloudHarnessAllowed = !cloud || harnessPolicy.isCloudHarnessAllowed(adapterType, { provider: runnerProvider, acpxAgent: runnerAcpxAgent }); const modelAiBinding = aiConnectionBindingSchema.safeParse((overlay.runtime.runtimeConfig as Record | undefined)?.aiConnection ?? runtimeConfig.aiConnection).data; const accountBoundCatalog = isAccountBoundAcpxAgent(runnerAcpxAgent); + const antigravityPickerGroup = useMemo(() => antigravityModelGroup(modelAiBinding?.method), [modelAiBinding?.method]); const modelCacheIdentity = accountBoundCatalog ? `${modelProvider}:${runnerAcpxAgent}:${isCreate ? "new" : props.agent.id}:${JSON.stringify(modelAiBinding ?? null)}` : runnerAcpxAgent ? `${modelProvider}:${runnerAcpxAgent}` : modelProvider; const connectionModels = useConnectionModels(isExternalRunner || !cloudHarnessAllowed ? null : selectedCompanyId, isCreate ? undefined : modelAiBinding, aiRoutingHarness(adapterType, runnerProvider, runnerAcpxAgent)); // Fetch adapter models for the effective provider, including unsaved changes. @@ -2005,7 +2006,8 @@ export function AgentConfigForm(props: AgentConfigFormProps) { allowDefault={adapterType !== "opencode_local" && adapterType !== "pi_local" && adapterType !== "paperclip_runner" && !isCursorCloudRunner} required={adapterType === "opencode_local" || adapterType === "pi_local" || isCursorCloudRunner || runnerAcpxAgent === "antigravity"} groupByProvider={!connectionModels && (adapterType === "opencode_local" || adapterType === "pi_local")} - preserveOrder={Boolean(connectionModels) || adapterCuratesModelOrder(adapterType)} + preserveOrder={Boolean(connectionModels) || adapterCuratesModelOrder(adapterType) || runnerAcpxAgent === "antigravity"} + groupModel={runnerAcpxAgent === "antigravity" && !connectionModels ? antigravityPickerGroup : undefined} creatable detectedModel={connectionModels ? undefined : detectedModel} detectedModelCandidates={[]} @@ -4078,6 +4080,8 @@ function ExperimentalBadge() { ); } +export type ModelGroupEntry = { group: string; label: string; note?: string }; + export function ModelDropdown({ models, value, @@ -4099,6 +4103,7 @@ export function ModelDropdown({ emptyDetectHint, defaultLabel, presentation = "searchable", + groupModel, }: { models: AdapterModel[]; value: string; @@ -4121,6 +4126,9 @@ export function ModelDropdown({ emptyDetectHint?: string; defaultLabel?: string; presentation?: "searchable" | "native"; + /** Groups a curated list by model family, keeping its order; each entry shows + * the variant (for example a thinking level) and an optional note. */ + groupModel?: (model: AdapterModel) => ModelGroupEntry | null; }) { const [modelSearch, setModelSearch] = useState(""); const [enteringCustomModel, setEnteringCustomModel] = useState(false); @@ -4155,7 +4163,18 @@ export function ModelDropdown({ ); }); }, [models, modelSearch, promotedModelIds]); - const groupedModels = useMemo(() => { + const groupedModels = useMemo((): Array<{ provider: string; heading?: string; entries: AdapterModel[] }> => { + if (groupModel && !groupByProvider) { + const groups = new Map(); + const other: AdapterModel[] = []; + for (const model of filteredModels) { + const group = groupModel(model)?.group; + if (!group) { other.push(model); continue; } + groups.set(group, [...(groups.get(group) ?? []), model]); + } + return [...[...groups].map(([group, entries]) => ({ provider: group, heading: group, entries })), + ...(other.length ? [{ provider: "other", heading: groups.size ? "Other models" : undefined, entries: other }] : [])]; + } if (!groupByProvider) { // A hand-ordered list (newest release of each family first, older releases at the end) is // shown as the adapter ordered it; a discovered list has no stable order, so sort it. @@ -4175,7 +4194,11 @@ export function ModelDropdown({ provider, entries: [...entries].sort((a, b) => a.id.localeCompare(b.id)), })); - }, [filteredModels, groupByProvider, preserveOrder]); + }, [filteredModels, groupByProvider, preserveOrder, groupModel]); + const entryLabel = (model: AdapterModel) => { + const entry = groupModel?.(model); + return entry ? (entry.note ? `${entry.label} · ${entry.note}` : entry.label) : model.label; + }; async function handleDetectModel() { if (!onDetectModel) return; @@ -4212,11 +4235,11 @@ export function ModelDropdown({ {allowDefault ? (defaultLabel ?? "Default") : loadingModels ? "Loading models…" : required ? "Select model (required)" : "Select model"} {extraModels.map(id => )} - {groupedModels.map(({ provider, entries }) => groupByProvider ? ( - - {entries.map(model => )} + {groupedModels.map(({ provider, heading, entries }) => groupByProvider || heading ? ( + + {entries.map(model => )} - ) : entries.map(model => ))} + ) : entries.map(model => ))} {creatable && } {enteringCustomModel && ( @@ -4405,6 +4428,11 @@ export function ModelDropdown({ {group.provider} ({group.entries.length}) )} + {!groupByProvider && group.heading && ( +
+ {group.heading} +
+ )} {group.entries.map((m) => ( ))} diff --git a/ui/src/components/ModelDropdown.test.tsx b/ui/src/components/ModelDropdown.test.tsx index 6a17a623cc4..b11d4976904 100644 --- a/ui/src/components/ModelDropdown.test.tsx +++ b/ui/src/components/ModelDropdown.test.tsx @@ -5,7 +5,9 @@ import { createRoot, type Root } from "react-dom/client"; import { afterEach, describe, expect, it } from "vitest"; import type { AdapterModel } from "@paperclipai/adapter-utils"; import { TooltipProvider } from "@/components/ui/tooltip"; -import { ModelDropdown } from "./AgentConfigForm"; +import { antigravityApiKeyModels } from "@paperclipai/shared"; +import { antigravityModelGroup } from "@/lib/native-model-catalog"; +import { ModelDropdown, type ModelGroupEntry } from "./AgentConfigForm"; const roots: Root[] = []; @@ -18,7 +20,10 @@ afterEach(() => { function renderOpenDropdown( models: AdapterModel[], - { groupByProvider = false, preserveOrder = false }: { groupByProvider?: boolean; preserveOrder?: boolean } = {}, + { groupByProvider = false, preserveOrder = false, groupModel, presentation }: { + groupByProvider?: boolean; preserveOrder?: boolean; + groupModel?: (model: AdapterModel) => ModelGroupEntry | null; presentation?: "searchable" | "native"; + } = {}, ) { const container = document.createElement("div"); document.body.appendChild(container); @@ -37,6 +42,8 @@ function renderOpenDropdown( required groupByProvider={groupByProvider} preserveOrder={preserveOrder} + groupModel={groupModel} + presentation={presentation} /> , ); @@ -78,4 +85,38 @@ describe("ModelDropdown", () => { expect(shownModelIds()).toEqual(["openai/gpt-6-astra", "openai/gpt-6-sol"]); }); + + it("groups the Antigravity API-key catalog by family, with the thinking level and paid-plan note on each choice", () => { + renderOpenDropdown(antigravityApiKeyModels(), { preserveOrder: true, groupModel: antigravityModelGroup("api_key") }); + const headings = Array.from(document.body.querySelectorAll('[role="presentation"]')).map(node => node.textContent); + expect(headings).toEqual(["Gemini 3.8 Flash", "Gemini 3.7 Flash", "Gemini 3.6 Flash", "Gemini 3.5 Flash", "Gemini 3.1 Pro", + "Gemini 4 Carbon", "Gemini 4 Neon", "Gemini 4 Hydrogen", "Gemini 4 Argon"]); + expect(shownModelIds()).toEqual(antigravityApiKeyModels().map(model => model.id)); + const neonExtraHigh = document.body.querySelector('span[title="gemini-4-neon-extra_high"]'); + expect(neonExtraHigh?.textContent).toBe("Extra highneeds a paid Gemini API plan"); + expect(document.body.querySelector('span[title="gemini-3.8-flash-high"]')?.textContent).toBe("High"); + }); + + it("groups a Google account catalog that spells extra high as xhigh", () => { + renderOpenDropdown([ + { id: "gemini-4-neon-high", label: "Gemini 4 Neon (High)" }, + { id: "gemini-4-neon-xhigh", label: "Gemini 4 Neon (Extra)" }, + { id: "account-only-model", label: "Account model" }, + ], { preserveOrder: true, groupModel: antigravityModelGroup("subscription") }); + expect(Array.from(document.body.querySelectorAll('[role="presentation"]')).map(node => node.textContent)).toEqual(["Gemini 4 Neon", "Other models"]); + expect(document.body.querySelector('span[title="gemini-4-neon-xhigh"]')?.textContent).toBe("Extra high"); + }); + + it("uses family option groups in the native picker", () => { + renderOpenDropdown(antigravityApiKeyModels(), { preserveOrder: true, groupModel: antigravityModelGroup("api_key"), presentation: "native" }); + const groups = Array.from(document.body.querySelectorAll("optgroup")); + expect(groups.map(group => group.label)).toContain("Gemini 4 Neon"); + const neon = groups.find(group => group.label === "Gemini 4 Neon")!; + expect(Array.from(neon.querySelectorAll("option")).map(option => [option.value, option.textContent])).toEqual([ + ["gemini-4-neon-high", "High · needs a paid Gemini API plan"], + ["gemini-4-neon-extra_high", "Extra high · needs a paid Gemini API plan"], + ["gemini-4-neon-medium", "Medium · needs a paid Gemini API plan"], + ["gemini-4-neon-low", "Low · needs a paid Gemini API plan"], + ]); + }); }); diff --git a/ui/src/components/new-agent/NewAgentSetup.tsx b/ui/src/components/new-agent/NewAgentSetup.tsx index 3b6824fbb5c..3dfe90ab057 100644 --- a/ui/src/components/new-agent/NewAgentSetup.tsx +++ b/ui/src/components/new-agent/NewAgentSetup.tsx @@ -1,4 +1,4 @@ -import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS } from "@/lib/native-model-catalog"; +import { ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS, antigravityModelGroup } from "@/lib/native-model-catalog"; import { PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils"; import { ExternalAgentInviteDialog } from "./ExternalAgentInviteDialog"; import { useConnectionModels } from "../ai-connections/useConnectionModels"; @@ -21,7 +21,7 @@ import { useCloudInstance } from "@/hooks/useCloudInstance"; import { isNewAgentAdapterAllowed } from "@/lib/new-agent-adapters"; import { useCloudHarnessPolicy } from "@/hooks/useCloudHarnessPolicy"; import { pendingAgentSetupChoice } from "@/lib/agent-setup-choice"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { hashKey, useQuery, useQueryClient } from "@tanstack/react-query"; import { AnimatePresence, motion, MotionConfig } from "motion/react"; import { ArrowLeft, ArrowRight, Check, Settings2 } from "lucide-react"; @@ -337,10 +337,13 @@ function Setup({ describeError(cause).body; } const accountBoundCatalog = brandType === "copilot_runtime" || brandType === "antigravity_runtime"; - const accountCatalogAvailable = brandType === "copilot_runtime" || (brandType === "antigravity_runtime" && aiBinding?.method === "subscription"); + // Google sign-in reads the account's catalog; a Gemini API key gets the + // catalog generated from the pinned runtime, on any environment. + const accountCatalogAvailable = brandType === "copilot_runtime" || (brandType === "antigravity_runtime" && (aiBinding?.method === "subscription" || aiBinding?.method === "api_key")); const requestAccountModels = accountCatalogAvailable && showModel && !connectionModels && Boolean(aiBinding) && envs.isSuccess && settings.isSuccess && experimental.isSuccess && general.isSuccess && !environmentError; const accountModelScope = JSON.stringify([companyId, environmentId, aiBinding]); + const antigravityPickerGroup = useMemo(() => antigravityModelGroup(aiBinding?.method), [aiBinding?.method]); const models = useQuery({ queryKey: queryKeys.agents.adapterModels(companyId, brandType, environmentId, accountBoundCatalog ? JSON.stringify(aiBinding ?? null) : aiBinding?.provider), queryFn: () => agentsApi.adapterModels(companyId, isKimi || accountBoundCatalog ? "paperclip_runner" : brandType, isKimi @@ -1244,7 +1247,8 @@ function Setup({ required={isKimi || multiProvider || accountBoundCatalog || nativeCursorCloud} creatable={brandType !== "copilot_runtime"} groupByProvider={multiProvider && !connectionModels} - preserveOrder={Boolean(connectionModels) || adapterCuratesModelOrder(brandType)} + preserveOrder={Boolean(connectionModels) || adapterCuratesModelOrder(brandType) || brandType === "antigravity_runtime"} + groupModel={brandType === "antigravity_runtime" && !connectionModels ? antigravityPickerGroup : undefined} /> )} {efforts.length > 0 && ( diff --git a/ui/src/lib/native-model-catalog.ts b/ui/src/lib/native-model-catalog.ts index 06a4bac7085..d5780ec0b1e 100644 --- a/ui/src/lib/native-model-catalog.ts +++ b/ui/src/lib/native-model-catalog.ts @@ -1,4 +1,4 @@ -import { aiConnectionBindingSchema, type Agent } from "@paperclipai/shared"; +import { aiConnectionBindingSchema, antigravityModelChoice, type Agent } from "@paperclipai/shared"; import { COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS, copilotTaskModelCatalogOptions } from "./copilot-task-model-catalog"; /** These ACP catalogs resolve the selected account rather than a generic list. */ @@ -16,3 +16,17 @@ export function nativeTaskModelCatalogOptions(agent: Agent | null | undefined) { /** Account reconciliation must not repeatedly provision catalog discovery. */ export const ACCOUNT_BOUND_MODEL_DISCOVERY_QUERY_OPTIONS = COPILOT_MODEL_DISCOVERY_QUERY_OPTIONS; + +/** Google Antigravity ids are `-`. The picker groups + * them by family and shows the level, with the paid-plan note the API-key + * catalog carries for Gemini 4. A Google account's own catalog uses the + * account level spellings. */ +export function antigravityModelGroup(method: string | undefined) { + const catalog = method === "api_key" ? "server" as const : "account" as const; + return (model: { id: string; label: string }) => { + const choice = antigravityModelChoice(model, { catalog }); + if (!choice) return null; + const note = model.label.includes(" · ") ? model.label.slice(model.label.indexOf(" · ") + 3) : undefined; + return { group: choice.familyLabel, label: choice.levelLabel, ...(note ? { note } : {}) }; + }; +} diff --git a/ui/src/pages/NewAgent.test.tsx b/ui/src/pages/NewAgent.test.tsx index 90bfa730d27..5fbc6d9859a 100644 --- a/ui/src/pages/NewAgent.test.tsx +++ b/ui/src/pages/NewAgent.test.tsx @@ -677,8 +677,9 @@ describe("New agent setup", () => { expect(api.testEnvironment).not.toHaveBeenCalled(); expect(api.hire).not.toHaveBeenCalled(); expect(api.adapterModels.mock.calls.every(call => call[1] === "paperclip_runner" && call[2]?.acpxAgent === "antigravity" && !call[2]?.agentId)).toBe(true); - if (method === "api_key") expect(api.adapterModels).not.toHaveBeenCalled(); - else expect(api.adapterModels).toHaveBeenCalled(); + // A Gemini API key gets the pinned runtime's catalog too, never a type-the-id dead end. + expect(api.adapterModels).toHaveBeenCalledWith("company-1", "paperclip_runner", expect.objectContaining({ + acpxAgent: "antigravity", aiConnection: expect.objectContaining({ provider: "google", method }) })); await click("Back to agents"); expect(state.navigate).toHaveBeenLastCalledWith("/agents/all"); }); @@ -701,8 +702,7 @@ describe("New agent setup", () => { await click(method === "subscription" ? "Use saved subscription" : "Use saved API key"); expect(api.testEnvironment).not.toHaveBeenCalled(); expect(container.textContent).toContain("Configure your agent"); - if (method === "api_key") expect(api.adapterModels).not.toHaveBeenCalled(); - else await vi.waitFor(() => expect(api.adapterModels).toHaveBeenLastCalledWith("company-1", "paperclip_runner", expect.objectContaining({ + await vi.waitFor(() => expect(api.adapterModels).toHaveBeenLastCalledWith("company-1", "paperclip_runner", expect.objectContaining({ provider: "acpx", acpxAgent: "antigravity", aiConnection: expect.objectContaining({ provider: "google", method }), environmentId: "local-1", }))); await click("Finish setup");