From e04efb9734e0db9ed87a807e3743a2f1d63e9956 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:36:37 -0600 Subject: [PATCH] feat(antigravity): allow plugin Runner-task and remote Google sign-in targets once released (#22940) 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 executes Google Antigravity on local hosts, Core managed sandboxes, and plugin Runner-task environments such as Paperclip Computer. > - Before this change, Paperclip refused Google sign-in on all remote targets even after release, returned an unavailable error when testing Antigravity on plugin Runner-task environments, and did not wire remote refresh-token write-back on Core sandboxes or released Antigravity profile resolution. > - Paperclip Cloud needs Google Antigravity to run with both Gemini API keys and Google sign-in on both plugin Runner-task environments and Core managed sandboxes once the profile flips from pending to qualified. > - This pull request lifts the released-state remote sign-in refusal, wires plugin Runner-task probing and released profile resolution for Antigravity, adds Core sandbox remote sign-in write-back and checkpoint exclusion, and keeps pending-release candidate grants restricted to API-key non-plugin targets. > - The benefit is that flipping the Antigravity profile from pending to qualified immediately enables picker selection, agent creation/save, Test probing, and execution with either Gemini API keys or Google sign-in on both plugin Runner-task environments and Core sandboxes. ## Linked Issues or Issue Description - Refs #22923 (Item 6 of `doc/plans/2026-11-25-antigravity-cloud-rollout.md`, gaps G6 and G7) - Pairs with #22933 (Item 2: Antigravity sign-in task credential and plugin write-back) and #22935 (Item 3: keep per-turn-only harnesses per-turn on warm environments) - Refs #22930 (Item 1: Gemini API key task credential for plugin Runners) ## What Changed - **Remote Google sign-in policy & credential preparation (`antigravity-connection-policy.ts`, `antigravity-runner-credentials.ts`)**: - Allow both Gemini API key and Google sign-in on remote targets in `antigravityConnectionRefusal` once `releasePending` is `false`, while keeping `lifecycleMode: "warm"` refused and keeping pending-release candidate grants API-key-only on non-plugin remote targets. - Strip all `GOOGLE_*` and non-selected `GEMINI_*` variables (plus `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`) in `prepareAntigravityRunnerCredentials`, enforce `antigravityConnectionRefusal` using `antigravityReleasePending()`, and pass pure sanitized sign-in JSON on remote runs (without local `/swarm` metadata). - **Core sandbox remote sign-in write-back & checkpoint safety (`native-credential-store.ts`, `native-session-executor.ts`, `antigravity-runner-credentials.ts`)**: - Extend `createNativeCredentialStore` to support `provider: "antigravity"` (`acp_token.json` and `auth-refresh.json`) over local and remote command runners. - Add optional `runtimeStore` support to `antigravityCredentialTurn` and wire it in `native-session-executor.ts` for Core remote sandboxes so rotated Google refresh tokens copy back after process retirement and remote credential files are scrubbed. - Exclude `antigravity-home/antigravity-acp/{acp_token.json,auth-refresh.json,auth-refresh.json.tmp,logs}` from remote ACPX session checkpoints. - Enforce `antigravityConnectionRefusal` in `preparePluginTaskOwner` and reject pending `pluginTask` execution in `assertAntigravityExecutionAdmissible` (defense in depth). - **Plugin Runner-task probing, released profile resolution & agent save/setup (`provider-profile.ts`, `plugin-runner-probe.ts`, `antigravity-connection-probe.ts`, `agent-environment-test.ts`, `agents.ts`, `NewAgentSetup.tsx`)**: - Add `antigravity` to `DEFAULT_ACPX_RUNNER_MODELS` and the qualified ACPX agent allowlist in `provider-profile.ts`, requiring an explicit non-placeholder model ID and checking `antigravityReleasePending()`. - Wire `testAntigravityConnection` to delegate plugin Runner-task targets to `probePluginRunnerEnvironment` instead of returning `"Google Antigravity is unavailable in this hosting environment."`, and update `probePluginRunnerEnvironment` to run `admissionOnly: true` for Antigravity with either Gemini API key or Google sign-in once released, returning `antigravity_metadata_verified`. - Allow Core sandbox/SSH `probeAntigravityExecutionTarget` for Google sign-in once released, preserve `antigravity_remote_runtime_ready` warn status in `agent-environment-test.ts` and `NewAgentSetup.tsx`. - Allow released Antigravity creation without `enableNativeRunner`, allow released remote sign-in account model discovery on the tenant host, and refuse pending plugin targets even when a `linux-x64` candidate grant exists. - Note on existing >1,000-line files: edits to `server/src/routes/agents.ts` and `server/src/services/native-runtime/native-session-executor.ts` are minimal wiring at existing Antigravity call sites (+12 and +26 net lines). - **Tests**: - Updated `antigravity-runner-credentials.test.ts`, `native-credential-store.test.ts`, `antigravity-save-refusal.test.ts`, `antigravity-connection-probe.test.ts`, `antigravity-release.test.ts`, `adapter-routes.test.ts`, `agent-runner-selection.test.ts`, `agent-environment-test-status.test.ts`, `native-session-executor.test.ts`, and `ui/src/lib/cloud-harness-policy.test.ts`. - Added `server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts`. ## Verification - Local Vitest (all passed against a released-profile fixture as well as the real pending profile): - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/antigravity-runner-credentials.test.ts src/services/native-runtime/native-credential-store.test.ts src/services/native-runtime/antigravity-release.test.ts src/services/native-runtime/plugin-runner-probe-antigravity.test.ts src/services/native-runtime/plugin-runner-probe-runner-mismatch.test.ts src/services/native-runtime/plugin-runner-credentials.test.ts src/__tests__/antigravity-connection-probe.test.ts src/__tests__/antigravity-save-refusal.test.ts src/__tests__/antigravity-managed-subscription.test.ts src/__tests__/antigravity-plugin-task-credential-writeback.test.ts src/services/agent-runner-selection.test.ts src/services/agent-environment-test-status.test.ts` (12 files, 425 tests passed) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/adapter-routes.test.ts --hookTimeout=60000` (36 passed) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/agent-test-environment-routes.test.ts --hookTimeout=60000 -t "passes the selected Antigravity"` (1 passed) - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "projects the selected Antigravity subscription"` (2 passed) - `pnpm --filter @paperclipai/ui exec vitest run src/lib/cloud-harness-policy.test.ts` (36 passed) - Typechecks: - `pnpm --filter @paperclipai/server exec tsc --noEmit` (passed) - `pnpm --filter @paperclipai/ui typecheck` (passed) - Not run live: the real Antigravity profile remains `pending` until Item 8; live staging verification on Paperclip Computer and Core managed sandboxes is covered by Item 12. ## Risks - Low risk while the Antigravity profile remains `pending`: all new remote sign-in and plugin Runner-task paths stay gated behind `!antigravityReleasePending()`, and pending-release candidate behavior remains unchanged (and tighter on plugin environments). - Once Item 8 flips the profile to qualified, released Antigravity agents on Core sandboxes and plugin Runner-task environments will use the paths tested here; live acceptance on staging is gated by Items 9–12. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Google Gemini (Antigravity agent 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 --------- Co-authored-by: Paperclip --- server/src/__tests__/adapter-routes.test.ts | 12 +- .../antigravity-connection-probe.test.ts | 49 +++- .../antigravity-save-refusal.test.ts | 85 ++++++- server/src/routes/agents.ts | 30 ++- .../agent-environment-test-status.test.ts | 8 + server/src/services/agent-environment-test.ts | 2 + .../services/agent-runner-selection.test.ts | 22 ++ .../services/antigravity-connection-probe.ts | 29 ++- .../antigravity-connection-policy.ts | 5 - .../antigravity-release.test.ts | 2 + .../native-runtime/antigravity-release.ts | 12 +- .../antigravity-runner-credentials.test.ts | 61 ++++- .../antigravity-runner-credentials.ts | 41 +++- .../native-credential-store.test.ts | 12 +- .../native-runtime/native-credential-store.ts | 4 +- .../native-session-executor.test.ts | 117 +++++++++- .../native-runtime/native-session-executor.ts | 29 ++- .../plugin-runner-probe-antigravity.test.ts | 217 ++++++++++++++++++ .../native-runtime/plugin-runner-probe.ts | 30 ++- .../native-runtime/provider-profile.ts | 11 +- ui/src/components/new-agent/NewAgentSetup.tsx | 2 +- ui/src/lib/cloud-harness-policy.test.ts | 33 ++- 22 files changed, 737 insertions(+), 76 deletions(-) create mode 100644 server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts diff --git a/server/src/__tests__/adapter-routes.test.ts b/server/src/__tests__/adapter-routes.test.ts index 46f86c6bce0..b2e986ee9fd 100644 --- a/server/src/__tests__/adapter-routes.test.ts +++ b/server/src/__tests__/adapter-routes.test.ts @@ -206,8 +206,16 @@ describe("adapter routes", () => { expect(await candidates({ driver: "sandbox", platform: "linux", architecture: "arm64" })).toBeUndefined(); expect(await candidates({ driver: "sandbox" })).toBeUndefined(); expect(await candidates({ driver: "unavailable" })).toBeUndefined(); - // A plugin Runner-task environment cannot launch Antigravity yet. - expect(await candidates({ driver: "plugin", runnerTasks: true })).toBeUndefined(); + // A plugin Runner-task environment offers no pending candidate grant (the plugin + // launch contract carries none), while still exposing paperclip_runner so released + // ACPX profiles like Copilot and released Antigravity are offered without a grant. + const pluginResponse = await request(createApp({}, { resolveRunnerTarget: async () => ({ driver: "plugin", runnerTasks: true }) })) + .get("/api/adapters?companyId=company-1&environmentId=plugin-tasks"); + expect(pluginResponse.status).toBe(200); + const pluginRunner = pluginResponse.body.find((adapter: any) => adapter.type === "paperclip_runner"); + expect(pluginRunner).toMatchObject({ type: "paperclip_runner", loaded: true, disabled: false }); + expect(pluginRunner.supportedRunners.length).toBeGreaterThan(0); + expect(pluginRunner.candidateHarnesses).toBeUndefined(); // A grant for this host does not open a cloud environment. mockCandidateAdmission.mockImplementation(grant("darwin", "arm64")); diff --git a/server/src/__tests__/antigravity-connection-probe.test.ts b/server/src/__tests__/antigravity-connection-probe.test.ts index 69a27311e84..6c57c1fed74 100644 --- a/server/src/__tests__/antigravity-connection-probe.test.ts +++ b/server/src/__tests__/antigravity-connection-probe.test.ts @@ -3,7 +3,7 @@ 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(), remoteAdmitted: vi.fn(() => false), credentials: vi.fn(), copyBack: vi.fn(), remove: vi.fn(), turn: vi.fn(), warn: vi.fn(), +const mocks = vi.hoisted(() => ({ probe: vi.fn(), pluginProbe: 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 importOriginal => { @@ -30,6 +30,9 @@ vi.mock("../services/native-runtime/native-codex-runner.js", () => ({ resolvePaperclipRunnerBinary: () => "/owned/runnerd", resolvePaperclipRunnerBinaryAsync: async () => "/owned/runnerd", })); +vi.mock("../services/native-runtime/plugin-runner-probe.js", () => ({ + probePluginRunnerEnvironment: mocks.pluginProbe, +})); import { antigravityConnectionProbeFailure, testAntigravityConnection } from "../services/antigravity-connection-probe.js"; import { NativeEnvironmentProbeCleanupError, QUALIFIED_ACPX_PROFILES, resolveAcpxRuntimeRoot } from "../vendor/paperclip-runner/index.js"; @@ -185,10 +188,15 @@ describe("Google Antigravity cloud candidate while pending", () => { expect(mocks.credentials).not.toHaveBeenCalled(); }); - it("refuses Google sign-in in the cloud even with a grant, and any cloud run without one", async () => { + it("refuses Google sign-in in the cloud even with a grant, refuses plugin Runner-task targets while pending, and refuses any cloud run without a grant", async () => { mocks.remoteAdmitted.mockReturnValue(true); expect(await testAntigravityConnection({ ...context, executionTarget: remoteTarget }, model)) .toMatchObject({ status: "fail", checks: [{ code: "antigravity_remote_sign_in_unsupported" }] }); + const pluginTarget = { kind: "remote", transport: "sandbox", remoteCwd: ".", leaseId: "lease-1", + runnerTaskProbe: { runId: "run-1", sessionId: "session-1" }, runnerTask: vi.fn() } as unknown as AdapterEnvironmentTestContext["executionTarget"]; + expect(await testAntigravityConnection({ ...apiKeyContext, executionTarget: pluginTarget }, model)) + .toMatchObject({ status: "fail", checks: [{ code: "antigravity_remote_unavailable" }] }); + expect(mocks.pluginProbe).not.toHaveBeenCalled(); mocks.remoteAdmitted.mockReturnValue(false); expect(await testAntigravityConnection(apiKeyContext, model)) .toMatchObject({ status: "fail", checks: [{ code: "antigravity_remote_unavailable" }] }); @@ -214,14 +222,43 @@ describe("Google Antigravity setup admission after the release flip", () => { 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 () => { + it("checks the cloud image's patched Antigravity runtime for Google sign-in once released without sending credentials or a prompt", async () => { + mocks.shell.mockResolvedValue({ exitCode: 0, timedOut: false, stdout: manifest(entry()), stderr: "" }); 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(result).toMatchObject({ status: "warn", checks: [{ code: "antigravity_remote_runtime_ready", + message: expect.stringContaining("Google sign-in") }] }); + const [, , command, options] = mocks.shell.mock.calls[0]; + expect(options.env).toEqual({}); + expect(command).not.toContain("/selected/provider"); + expect(mocks.probe).not.toHaveBeenCalled(); expect(mocks.credentials).not.toHaveBeenCalled(); }); + it("delegates plugin Runner-task targets to probePluginRunnerEnvironment for both Gemini API key and Google sign-in once released", async () => { + const pluginTarget = { kind: "remote", transport: "sandbox", remoteCwd: ".", leaseId: "lease-1", + runnerTaskProbe: { runId: "run-1", sessionId: "session-1" }, runnerTask: vi.fn() } as unknown as AdapterEnvironmentTestContext["executionTarget"]; + const verified = { adapterType: "paperclip_runner", status: "pass" as const, testedAt: new Date(0).toISOString(), + checks: [{ code: "antigravity_metadata_verified", level: "info" as const, message: "Verified." }] }; + mocks.pluginProbe.mockResolvedValue(verified); + + const apiKeyPluginContext: AdapterEnvironmentTestContext = { + ...apiKeyContext, + config: { ...apiKeyContext.config, managedAiConnection: { identity: "key-id", sessionIdentity: "key-session" } }, + executionTarget: pluginTarget, + }; + expect(await testAntigravityConnection(apiKeyPluginContext, model)).toEqual(verified); + expect(mocks.pluginProbe).toHaveBeenCalledWith(apiKeyPluginContext, { identity: "key-id", accountIdentity: "key-session", home: undefined }); + + const signInPluginContext: AdapterEnvironmentTestContext = { + ...context, + config: { ...context.config, managedAiConnection: { identity: "google-id", sessionIdentity: "google-session" } }, + executionTarget: pluginTarget, + }; + expect(await testAntigravityConnection(signInPluginContext, model)).toEqual(verified); + expect(mocks.pluginProbe).toHaveBeenLastCalledWith(signInPluginContext, { identity: "google-id", accountIdentity: "google-session", home: "/selected/provider" }); + expect(mocks.shell).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); diff --git a/server/src/__tests__/antigravity-save-refusal.test.ts b/server/src/__tests__/antigravity-save-refusal.test.ts index a563dcfc3a1..1310b006335 100644 --- a/server/src/__tests__/antigravity-save-refusal.test.ts +++ b/server/src/__tests__/antigravity-save-refusal.test.ts @@ -6,7 +6,7 @@ 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 { agents, agentConfigRevisions, builtInManagedResources, companies, companyMemberships, createDb, environments, plugins } 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"; @@ -98,8 +98,30 @@ describePostgres("Google Antigravity connection refusal at agent save", () => { 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; + async function insertPluginTaskEnvironment() { + const pluginId = randomUUID(); + const pluginKey = `fixture-tasks-${pluginId}`; + await db.insert(plugins).values({ + id: pluginId, + pluginKey, + packageName: pluginKey, + version: "1.0.0", + status: "ready", + manifestJson: { + capabilities: ["environment.drivers.register"], + environmentDrivers: [{ driverKey: "tasks", supportsTasks: true }], + } as never, + }); + const [pluginEnv] = await db.insert(environments).values({ + name: `Plugin tasks ${agent.companyId}`, + driver: "plugin", + config: { pluginKey, driverKey: "tasks", driverConfig: {} }, + }).returning(); + return pluginEnv!; + } + + it("refuses Google sign-in on a cloud environment while pending even with a linux-x64 grant", async () => { + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, grant(agent.companyId, "linux-x64")); 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); @@ -112,6 +134,16 @@ describePostgres("Google Antigravity connection refusal at agent save", () => { expect(allocate).not.toHaveBeenCalled(); expect(probe).not.toHaveBeenCalled(); }); + it("refuses a plugin Runner-task environment while pending even with a linux-x64 grant", async () => { + vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, grant(agent.companyId, "linux-x64")); + const pluginEnv = await insertPluginTaskEnvironment(); + const binding = await saveGoogleConnection("api_key"); + const response = await request(app).patch(`/api/agents/${agent.id}`).send({ defaultEnvironmentId: pluginEnv.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("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 } }); @@ -150,14 +182,47 @@ describePostgres("Google Antigravity connection refusal at agent save", () => { 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 () => { + it("saves a Gemini API key and Google sign-in on a Core sandbox 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); + for (const method of ["api_key", "subscription"] as const) { + const binding = await saveGoogleConnection(method); + 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(); + }); + + it("saves a Gemini API key and Google sign-in on a plugin Runner-task environment once released", async () => { + release.pending = false; + const pluginEnv = await insertPluginTaskEnvironment(); + for (const method of ["api_key", "subscription"] as const) { + const binding = await saveGoogleConnection(method); + const response = await request(app).patch(`/api/agents/${agent.id}`).send({ defaultEnvironmentId: pluginEnv.id, runtimeConfig: { aiConnection: binding } }); + expect(response.status, JSON.stringify(response.body)).toBe(200); + const saved = await readAgent(); + expect(saved.defaultEnvironmentId).toBe(pluginEnv.id); + expect(saved.runtimeConfig.aiConnection).toEqual(binding); + } + expect(allocate).not.toHaveBeenCalled(); expect(probe).not.toHaveBeenCalled(); + }); + + it("creates a released Antigravity agent on a plugin Runner-task environment without enableNativeRunner", async () => { + release.pending = false; + const pluginEnv = await insertPluginTaskEnvironment(); + const binding = await saveGoogleConnection("subscription"); + const response = await request(app).post(`/api/companies/${agent.companyId}/agents`).send({ + name: "Released Antigravity agent", + adapterType: "paperclip_runner", + adapterConfig: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-high" }, + defaultEnvironmentId: pluginEnv.id, + runtimeConfig: { aiConnection: binding }, + }); + expect(response.status, JSON.stringify(response.body)).toBe(201); + expect(response.body.defaultEnvironmentId).toBe(pluginEnv.id); + expect(response.body.adapterConfig).toMatchObject({ provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-high" }); expect(allocate).not.toHaveBeenCalled(); expect(probe).not.toHaveBeenCalled(); }); }); diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 2063d295b16..15522905dcd 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -1239,14 +1239,16 @@ export function agentRoutes( 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 environment = effectiveEnvironmentId ? await environmentsSvc.getById(effectiveEnvironmentId) : null; + const driver = environment?.driver ?? "local"; + const remote = driver !== "local"; + const candidateEligibleRemote = driver === "sandbox" || driver === "ssh"; const model = config.model; const granted = (cloud: boolean) => { try { return Boolean(resolveAntigravityCandidateAdmission({ companyId, model, target: antigravityCandidateTarget(cloud) })); } catch { return false; } }; - if (remote && !granted(true)) { + if (remote && (!candidateEligibleRemote || !granted(true))) { const refusal = antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true, remoteCandidateAdmitted: false })!; throw unprocessable(refusal.message, { code: refusal.code }); } @@ -1935,9 +1937,10 @@ export function agentRoutes( if (adapterType === "paperclip_runner") { const experimental = await instanceSettings.getExperimental(); const selected = asRecord(config); + const antigravityPending = antigravityReleasePending(); let antigravityCandidate: ReturnType; if (companyId && selected?.provider === "acpx" && selected.acpxAgent === "antigravity" - && typeof selected.model === "string" && selected.model.trim()) { + && antigravityPending && typeof selected.model === "string" && selected.model.trim()) { try { antigravityCandidate = resolveAntigravityCandidateAdmission({ companyId, model: selected.model }); } catch { throw unprocessable("This Google Antigravity candidate requires the exact enabled model and a current operator authorization.", { code: "paperclip_runner_antigravity_candidate_invalid" }); } } @@ -1956,7 +1959,7 @@ export function agentRoutes( } else if (asRecord(config)?.provider === "grok_bot" && (experimental.enableGrokBot !== true || experimental.enableNativeRunner !== true)) { throw unprocessable("Enable Grok Bot and Paperclip Runner before connecting this agent.", { code: "paperclip_runner_grok_disabled" }); } else if (!([undefined, "codex", "opencode"].includes(asRecord(config)?.provider as string | undefined)) && - !(asRecord(config)?.provider === "acpx" && asRecord(config)?.acpxAgent === "copilot") && + !(asRecord(config)?.provider === "acpx" && (asRecord(config)?.acpxAgent === "copilot" || (asRecord(config)?.acpxAgent === "antigravity" && !antigravityPending))) && !["claude_local", "pi_local", "grok_local"].includes(agentHarnessType("paperclip_runner", asRecord(config) ?? {})) && experimental.enableNativeRunner !== true && !antigravityCandidate && !kimiCandidate) { throw unprocessable( @@ -3169,16 +3172,17 @@ 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. + // While pending, Google sign-in is local-only; once released, account + // model discovery runs on the tenant host for remote environments too. const accountCatalog = binding.method !== "api_key"; - if (accountCatalog && environment && environment.driver !== "local") throw unprocessable("Google Antigravity account model discovery requires the Paperclip host."); + const localOnlySignIn = accountCatalog && antigravityReleasePending(); + if (localOnlySignIn && 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 (accountCatalog && modelAgent.defaultEnvironmentId && !environmentId) { + if (localOnlySignIn && 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."); } @@ -3293,11 +3297,13 @@ export function agentRoutes( 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 environment = effectiveEnvironmentId ? await environmentsSvc.getById(effectiveEnvironmentId) : null; + const driver = environment?.driver ?? "local"; + const remote = driver !== "local"; + const candidateEligibleRemote = driver === "sandbox" || driver === "ssh"; const releasePending = antigravityReleasePending(); const refusal = antigravityConnectionRefusal({ apiKey: selection.attribution.method === "api_key", remote, releasePending, - remoteCandidateAdmitted: remote && releasePending && antigravityRemoteCandidateAdmitted({ companyId, + remoteCandidateAdmitted: candidateEligibleRemote && releasePending && antigravityRemoteCandidateAdmitted({ companyId, model: typeof config.model === "string" ? config.model : undefined }) }); if (refusal) throw unprocessable(refusal.message, { code: refusal.code }); } diff --git a/server/src/services/agent-environment-test-status.test.ts b/server/src/services/agent-environment-test-status.test.ts index 2991000c5a2..5313e13ff14 100644 --- a/server/src/services/agent-environment-test-status.test.ts +++ b/server/src/services/agent-environment-test-status.test.ts @@ -71,6 +71,14 @@ describe("managed Runner connection test status", () => { expect(missing.status).toBe("fail"); expect(missing.checks).toContainEqual(expect.objectContaining({ code: "ai_connection_validation_incomplete" })); expect(claudeProbe).not.toHaveBeenCalled(); + + // A Core remote sandbox verifies the image's patched runtime pack without a prompt and returns warn. + runtimeProbe.mockResolvedValue({ adapterType: "paperclip_runner", status: "warn", testedAt: checkedAt, + checks: [{ code: "antigravity_remote_runtime_ready", level: "warn", message: "Verified remote runtime." }] }); + const remoteResult = await service.testManagedEnvironment("paperclip_runner", { ...input, executionTarget: context.executionTarget }, binding, managed); + expect(remoteResult.status).toBe("warn"); + expect(remoteResult.checks).toContainEqual(expect.objectContaining({ code: "antigravity_remote_runtime_ready" })); + expect(claudeProbe).not.toHaveBeenCalled(); }); it("passes a healthy Cloud Claude connection without asking the user to verify launch-time runtime preparation", async () => { vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "managed-fixture"); diff --git a/server/src/services/agent-environment-test.ts b/server/src/services/agent-environment-test.ts index 78d9a983c66..253d097401f 100644 --- a/server/src/services/agent-environment-test.ts +++ b/server/src/services/agent-environment-test.ts @@ -598,6 +598,8 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin // exact model without a billable turn. Do not invoke another Google CLI. if (adapterType === "paperclip_runner" && context.config.provider === "acpx" && context.config.acpxAgent === "antigravity") { if (result.status === "pass" && result.checks.some(check => check.code === "antigravity_metadata_verified" && check.level === "info")) return result; + if (target?.kind === "remote" && !(target.transport === "sandbox" && target.runnerTask) && result.status === "warn" + && result.checks.some(check => check.code === "antigravity_remote_runtime_ready")) return result; return { ...result, status: "fail", checks: [...result.checks, { code: "ai_connection_validation_incomplete", level: "error", message: "The selected Google account has not completed native account and model verification. Retry before adopting it." }] }; } diff --git a/server/src/services/agent-runner-selection.test.ts b/server/src/services/agent-runner-selection.test.ts index 98dab18024c..03b6a26ab03 100644 --- a/server/src/services/agent-runner-selection.test.ts +++ b/server/src/services/agent-runner-selection.test.ts @@ -895,4 +895,26 @@ describe("Claude runner defaults", () => { state.overridden.clear(); state.disabled = ["claude_local"]; expect(() => resolveNewAgentRunner({ adapterType: "claude_local", target: mac })).toThrow("Claude is disabled"); }); + + it("retains native paperclip_runner Antigravity and Copilot selections on plugin Runner-task targets", async () => { + state.getEnvironment.mockResolvedValue({ id: "plugin-env", driver: "plugin", status: "active", config: { pluginKey: "agent-computer", driverKey: "tasks", driverConfig: {} } }); + state.pluginByKey.mockResolvedValue({ + pluginKey: "agent-computer", + manifestJson: { capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", supportsTasks: true }] }, + }); + const pluginTarget = await resolveAgentRunnerTargetForCompany({} as never, "company-1", "plugin-env"); + expect(pluginTarget).toEqual({ driver: "plugin", runnerTasks: true }); + expect(agentRunnerAvailability("paperclip_runner", pluginTarget).supportedRunners.length).toBeGreaterThan(0); + for (const acpxAgent of ["copilot", "antigravity"] as const) { + const selected = await resolveNewAgentRunnerForCompany({} as never, "company-1", { + adapterType: "paperclip_runner", + adapterConfig: { provider: "acpx", acpxAgent, model: "explicit-model" }, + defaultEnvironmentId: "plugin-env", + }); + expect(selected).toEqual({ + adapterType: "paperclip_runner", + adapterConfig: { provider: "acpx", acpxAgent, model: "explicit-model" }, + }); + } + }); }); diff --git a/server/src/services/antigravity-connection-probe.ts b/server/src/services/antigravity-connection-probe.ts index 498c158da42..22d0c6eadcd 100644 --- a/server/src/services/antigravity-connection-probe.ts +++ b/server/src/services/antigravity-connection-probe.ts @@ -12,6 +12,7 @@ import { antigravityConnectionRefusal } from "./native-runtime/antigravity-conne 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"; +import { probePluginRunnerEnvironment } from "./native-runtime/plugin-runner-probe.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"]; @@ -54,11 +55,14 @@ const REMOTE_PACK_ROOTS = ["/opt/paperclip-runner/provider-pack", '"$HOME/.local * 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 { +export async function probeAntigravityExecutionTarget( + target: Extract, + options: { apiKey?: boolean } = {}, +): 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."); + return failed("antigravity_remote_runtime_missing", "Plugin Runner-task targets must be probed through the plugin Runner task API."); } const expectedPath = "provider-assets/antigravity/linux-x64"; const command = [ @@ -100,21 +104,32 @@ export async function probeAntigravityExecutionTarget(target: Extract { const configured = context.config.env; const configuredKey = asRecord(configured)?.GEMINI_API_KEY; + const apiKey = typeof configuredKey === "string" && configuredKey.trim().length > 0; 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 }) }); + const pluginRunnerTask = remote && target.transport === "sandbox" && Boolean(target.runnerTask); + const refusal = antigravityConnectionRefusal({ apiKey, remote, releasePending: pending, + remoteCandidateAdmitted: remote && !pluginRunnerTask && pending && antigravityRemoteCandidateAdmitted({ companyId: context.companyId, model }) }); if (refusal) return failed(refusal.code, refusal.message); - if (target?.kind === "remote") return probeAntigravityExecutionTarget(target); + if (pluginRunnerTask) { + const managedConnection = asRecord(context.config.managedAiConnection); + const identity = typeof managedConnection?.identity === "string" ? managedConnection.identity : undefined; + const accountIdentity = typeof managedConnection?.sessionIdentity === "string" ? managedConnection.sessionIdentity : identity; + return probePluginRunnerEnvironment(context, identity + ? { identity, accountIdentity: accountIdentity ?? identity, home: context.managedAiCredentialHome } + : undefined); + } + if (target?.kind === "remote") return probeAntigravityExecutionTarget(target, { apiKey }); // 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; diff --git a/server/src/services/native-runtime/antigravity-connection-policy.ts b/server/src/services/native-runtime/antigravity-connection-policy.ts index 47164767eb9..66c3a2741be 100644 --- a/server/src/services/native-runtime/antigravity-connection-policy.ts +++ b/server/src/services/native-runtime/antigravity-connection-policy.ts @@ -38,11 +38,6 @@ export function antigravityConnectionRefusal(input: { 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; } diff --git a/server/src/services/native-runtime/antigravity-release.test.ts b/server/src/services/native-runtime/antigravity-release.test.ts index 3ff7e7a30b0..47524ba2b04 100644 --- a/server/src/services/native-runtime/antigravity-release.test.ts +++ b/server/src/services/native-runtime/antigravity-release.test.ts @@ -90,6 +90,7 @@ describe("Antigravity executor admission", () => { const execution = antigravityExecution(); vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, candidateGrant("linux-x64")); expect(admissible(execution, { remoteTarget: true })).not.toThrow(); + expect(admissible(execution, { remoteTarget: true, pluginTask: true })).toThrow(/candidate_ineligible/); 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/); @@ -108,6 +109,7 @@ describe("Antigravity executor admission", () => { vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, undefined); const execution = antigravityExecution(); expect(admissible(execution)).not.toThrow(); + expect(admissible(execution, { remoteTarget: true, pluginTask: true })).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(); diff --git a/server/src/services/native-runtime/antigravity-release.ts b/server/src/services/native-runtime/antigravity-release.ts index 7175a5579bb..8aba25c2825 100644 --- a/server/src/services/native-runtime/antigravity-release.ts +++ b/server/src/services/native-runtime/antigravity-release.ts @@ -17,9 +17,11 @@ export function antigravityCandidateTarget(remote: boolean): { platform: string; * the target the run would use. This host needs a grant that names this host. * A Core sandbox or SSH environment needs a grant for the cloud pack's * linux-x64 closure and a linux-x64 glibc Computer the Runner supports (or the - * managed cloud image). A plugin Runner-task environment offers none: it cannot - * launch Antigravity yet. A released profile offers no candidate. May throw for - * a grant that is invalid or names another target. + * managed cloud image). A plugin Runner-task environment offers no candidate + * grant while pending because the plugin launch contract carries no candidate + * grant; once released, no candidate grant is needed and plugin Runner-task + * environments offer Antigravity through the ordinary qualified Runner path. + * May throw for a grant that is invalid or names another target. */ export function antigravityCandidateForRunnerTarget(companyId: string, target: RunnerTarget) { if (!antigravityReleasePending()) return undefined; @@ -100,6 +102,7 @@ export function assertAntigravityExecutionAdmissible(input: { backend?: unknown; restartRecovery?: unknown; remoteTarget: boolean; + pluginTask?: boolean; hostEnvironment?: NodeJS.ProcessEnv; }): void { const { execution } = input; @@ -108,6 +111,9 @@ export function assertAntigravityExecutionAdmissible(input: { assertAntigravitySavedStateCurrent(execution); return; } + if (input.pluginTask) { + throw new Error("paperclip_runner_antigravity_candidate_ineligible: exact target-bound per-turn candidate admission is required"); + } let candidate: ReturnType; try { candidate = resolveAntigravityCandidateAdmission({ 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 d64150ea818..67f979662bd 100644 --- a/server/src/services/native-runtime/antigravity-runner-credentials.test.ts +++ b/server/src/services/native-runtime/antigravity-runner-credentials.test.ts @@ -12,6 +12,11 @@ import { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } 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 })); +const release = vi.hoisted(() => ({ pending: true })); +vi.mock("./antigravity-release.js", async importOriginal => ({ + ...await importOriginal(), + antigravityReleasePending: () => release.pending, +})); vi.mock("./runner-api-files.js", async importOriginal => { const actual = await importOriginal(); return { ...actual, openRunnerWorkspaceFile: async (...args: Parameters) => { @@ -83,7 +88,7 @@ const credential = (token: string) => JSON.stringify({ refresh_token: token, token_uri: "https://oauth2.googleapis.com/token", scopes: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"], }); async function home() { const root = await realpath(await mkdtemp(join(tmpdir(), "antigravity-controller-test-"))); roots.push(root); await mkdir(join(root, "antigravity-acp"), { mode: 0o700 }); return root; } -beforeEach(async () => { vi.stubEnv("PAPERCLIP_HOME", await home()); }); +beforeEach(async () => { release.pending = true; vi.stubEnv("PAPERCLIP_HOME", await home()); }); afterEach(async () => { copyFault.phase = ""; copyFault.destination = ""; copyFault.source = ""; copyFault.collisionPath = ""; copyFault.failedRemoval = ""; copyFault.removals = []; copyFault.hits = 0; vi.unstubAllEnvs(); await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true }))); }); describe("Antigravity managed Runner credentials", () => { @@ -96,7 +101,8 @@ describe("Antigravity managed Runner credentials", () => { }); it("uses the explicit API key while removing all subscription home and payload inputs", async () => { expect(await prepareAntigravityRunnerCredentials({ remote: true, environment: { - GEMINI_API_KEY: "fixture-selected", GOOGLE_API_KEY: "other", GEMINI_HOME: "/ambient", GOOGLE_APPLICATION_CREDENTIALS: "/ambient.json", + GEMINI_API_KEY: "fixture-selected", GEMINI_MODEL: "ambient-model", GOOGLE_API_KEY: "other", GOOGLE_GEMINI_BASE_URL: "https://ambient.invalid", + GEMINI_HOME: "/ambient", GOOGLE_APPLICATION_CREDENTIALS: "/ambient.json", GOOGLE_CLOUD_ACCESS_TOKEN: "ambient", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "spoofed", } })).toEqual({ home: null, environment: { GEMINI_API_KEY: "fixture-selected" } }); }); @@ -118,7 +124,7 @@ describe("Antigravity managed Runner credentials", () => { expect(antigravitySwarmChannel({})).toBe("provider_default"); expect(antigravitySwarmChannel({ PAPERCLIP_ANTIGRAVITY_SWARM_CHANNEL: "daily" })).toBe("provider_default"); }); - it("projects only the selected private token and rejects remote subscription delivery", async () => { + it("projects only the selected private token, refuses remote sign-in while pending, and accepts remote sign-in once released", async () => { const managedHome = await home(); await writeFile(join(managedHome, "antigravity-acp", "acp_token.json"), credential("fixture-selected"), { mode: 0o600 }); const projected = await prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: { GEMINI_HOME: "/untrusted" } }); @@ -128,6 +134,7 @@ describe("Antigravity managed Runner credentials", () => { expect(JSON.parse(projected.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET!)).toEqual({ ...JSON.parse(credential("fixture-selected")), paperclip: { swarmChannel: "provider_default" } }); expect(sanitizeAntigravityCredential(projected.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET!)).toBe(credential("fixture-selected")); + // While pending, remote sign-in and warm sessions are refused permanently by name. 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) { @@ -141,17 +148,37 @@ describe("Antigravity managed Runner credentials", () => { expect(failure).toBe(NATIVE_PROVIDER_STARTUP_REJECTED); expect(nativeSessionFailureDisposition(1, new Date(), failure)).toMatchObject({ phase: "terminal_failure", failureCode: NATIVE_PROVIDER_STARTUP_REJECTED }); } + // Once released, remote sign-in delivers the pure sanitized credential and strips GOOGLE_*/GEMINI_* overrides; warm stays refused. + release.pending = false; + const remoteProjected = await prepareAntigravityRunnerCredentials({ + remote: true, + managedHome, + accountEmail: "Owner@Example.test", + environment: { GEMINI_HOME: "/untrusted", GOOGLE_CLOUD_PROJECT: "untrusted", GEMINI_MODEL: "untrusted", KEEP: "ok" }, + }); + expect(remoteProjected).toEqual({ + home: managedHome, + credential: credential("fixture-selected"), + environment: { KEEP: "ok", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: credential("fixture-selected") }, + }); + const remoteWarm = await prepareAntigravityRunnerCredentials({ + remote: true, managedHome, lifecycleMode: "warm", environment: {}, + }).catch(error => error); + expect(remoteWarm).toBeInstanceOf(AntigravityConnectionConfigurationError); + expect(remoteWarm).toMatchObject({ code: "antigravity_warm_unsupported" }); }); 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(); + for (const remote of [false, true]) { + expect(antigravityConnectionRefusal({ apiKey, remote, lifecycleMode: "warm", releasePending: false })?.code).toBe("antigravity_warm_unsupported"); + expect(antigravityConnectionRefusal({ apiKey, remote, 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."); + // Once released, Google sign-in is accepted on remote targets too. + expect(antigravityConnectionRefusal({ apiKey: false, remote: true, releasePending: false })).toBeNull(); 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. @@ -163,6 +190,26 @@ describe("Antigravity managed Runner credentials", () => { expect(antigravityConnectionRefusal({ apiKey: true, remote: true, lifecycleMode: "warm", releasePending: true, remoteCandidateAdmitted: true })?.code) .toBe("antigravity_warm_unsupported"); }); + it("exports rotated refreshes and scrubs remote credentials via a remote runtimeStore after session retirement", async () => { + const managedHome = await home(), runtimeHome = await home(); + const destination = join(managedHome, "antigravity-acp", "acp_token.json"); + await writeFile(destination, credential("fixture-original"), { mode: 0o600 }); + const order: string[] = []; + const close = vi.fn(async () => { order.push("close"); }); + const runtimeStore = { + read: vi.fn(async () => { order.push("read"); return credential("fixture-remote-refreshed"); }), + remove: vi.fn(async () => { order.push("remove"); }), + }; + const session = bindAntigravityCredentialTurn({ close } as unknown as NativeSession, + { managedHome, runtimeHome, credential: credential("fixture-original"), runtimeStore }); + await completeManagedNativeCredentialTurn(session); + expect(order).toEqual(["close", "read", "remove"]); + expect(await readFile(destination, "utf8")).toBe(credential("fixture-remote-refreshed")); + await session.close({ reason: "completed" }); + expect(close).toHaveBeenCalledOnce(); + expect(runtimeStore.read).toHaveBeenCalledOnce(); + expect(runtimeStore.remove).toHaveBeenCalledOnce(); + }); 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"); const other = join(managedHome, "other.json"); diff --git a/server/src/services/native-runtime/antigravity-runner-credentials.ts b/server/src/services/native-runtime/antigravity-runner-credentials.ts index 81b23ce5ef6..c840bfb3ac0 100644 --- a/server/src/services/native-runtime/antigravity-runner-credentials.ts +++ b/server/src/services/native-runtime/antigravity-runner-credentials.ts @@ -16,6 +16,7 @@ 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"; +import { antigravityReleasePending } from "./antigravity-release.js"; const AUTH_SECRET = "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"; const TOKEN_FILE = "acp_token.json"; @@ -67,13 +68,25 @@ export async function prepareAntigravityRunnerCredentials(input: { accountEmail?: string; }): 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]; const apiKey = Boolean(environment.GEMINI_API_KEY?.trim()); + for (const key of Object.keys(environment)) { + if (key === AUTH_SECRET || key.startsWith("GOOGLE_") || (key.startsWith("GEMINI_") && !(apiKey && key === "GEMINI_API_KEY"))) { + delete environment[key]; + } + } + const releasePending = antigravityReleasePending(); // 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 }); + // While pending, assertAntigravityExecutionAdmissible enforces the operator's + // cloud grant separately; remote sign-in remains refused until released. + const refusal = antigravityConnectionRefusal({ + apiKey, + remote: input.remote, + lifecycleMode: input.lifecycleMode, + releasePending, + remoteCandidateAdmitted: releasePending && input.remote, + }); if (refusal) throw new AntigravityConnectionConfigurationError(refusal); if (apiKey) return { environment, home: null }; - delete environment.GEMINI_API_KEY; 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); @@ -83,6 +96,10 @@ export async function prepareAntigravityRunnerCredentials(input: { } catch { throw new Error("The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry."); } + if (input.remote) { + environment[AUTH_SECRET] = credential; + return { environment, home, credential }; + } // Run facts bound to this credential for the swarm route (channel, account // digest). The Runner's credential sanitizer drops them before any write, so // the staged token and its writeback comparison are unchanged. @@ -161,6 +178,8 @@ export function antigravityCredentialTurn(input: { managedHome: string; runtimeHome: string; credential: string; + /** Remote Core sandbox runs export and scrub rotated tokens over the sandbox runner. */ + runtimeStore?: { read: () => Promise; remove: () => Promise }; }) { const runtimeDirectory = join(input.runtimeHome, "antigravity-acp"); const destination = join(input.managedHome, "antigravity-acp", TOKEN_FILE); @@ -169,10 +188,14 @@ export function antigravityCredentialTurn(input: { copyBack: async () => { let serialized: string; try { - try { serialized = await readLocalAiCredentialFile(join(runtimeDirectory, TOKEN_FILE)); } - catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; - serialized = await readLocalAiCredentialFile(join(runtimeDirectory, REFRESH_FILE)); + if (input.runtimeStore) { + serialized = await input.runtimeStore.read(); + } else { + try { serialized = await readLocalAiCredentialFile(join(runtimeDirectory, TOKEN_FILE)); } + catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + serialized = await readLocalAiCredentialFile(join(runtimeDirectory, REFRESH_FILE)); + } } } catch (error) { // A provider that never started has no refresh to preserve. @@ -317,6 +340,10 @@ export function antigravityCredentialTurn(input: { }); }, remove: async () => { + if (input.runtimeStore) { + await input.runtimeStore.remove(); + return; + } const directory = await openRunnerWorkspaceFile(runtimeDirectory, constants.O_RDONLY | constants.O_DIRECTORY) .catch((error: NodeJS.ErrnoException) => { if (error.code === "ENOENT") return null; throw error; }); if (!directory) return; diff --git a/server/src/services/native-runtime/native-credential-store.test.ts b/server/src/services/native-runtime/native-credential-store.test.ts index 8edc454f459..0be089e8d34 100644 --- a/server/src/services/native-runtime/native-credential-store.test.ts +++ b/server/src/services/native-runtime/native-credential-store.test.ts @@ -8,7 +8,7 @@ import { createNativeCredentialStore } from "./native-credential-store.js"; const execute = promisify(execFile), roots: string[] = []; afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); -async function fixture(target: "local" | "ssh" | "sandbox", provider: "codex" | "grok" = "codex") { +async function fixture(target: "local" | "ssh" | "sandbox", provider: "codex" | "grok" | "antigravity" = "codex") { const root = await realpath(await mkdtemp(join(tmpdir(), "native-credential-store-"))); roots.push(root); const localHome = join(root, "local"), remoteHome = join(root, "remote"); await mkdir(localHome); await mkdir(remoteHome); @@ -35,7 +35,7 @@ it.each(["local", "ssh", "sandbox"] as const)("exports %s snapshots only on dema await expect(store.read()).rejects.toMatchObject({ code: "ENOENT" }); }); -it.each((["codex", "grok"] as const).flatMap(provider => (["local", "ssh", "sandbox"] as const).map(target => ({ provider, target }))))("uses the $provider close handoff for $target when auth.json is absent", async ({ target, provider }) => { +it.each((["codex", "grok", "antigravity"] as const).flatMap(provider => (["local", "ssh", "sandbox"] as const).map(target => ({ provider, target }))))("uses the $provider close handoff for $target when primary token file is absent", async ({ target, provider }) => { const { home, store } = await fixture(target, provider); await writeFile(join(home, "auth-refresh.json"), '{"synthetic":"refresh"}', { mode: 0o600 }); expect(await store.read()).toBe('{"synthetic":"refresh"}'); @@ -43,6 +43,14 @@ it.each((["codex", "grok"] as const).flatMap(provider => (["local", "ssh", "sand await expect(store.read()).rejects.toMatchObject({ code: "ENOENT" }); }); +it.each(["local", "ssh", "sandbox"] as const)("reads and removes antigravity acp_token.json on %s targets", async target => { + const { home, store } = await fixture(target, "antigravity"); + await writeFile(join(home, "acp_token.json"), '{"refresh_token":"synthetic"}', { mode: 0o600 }); + expect(await store.read()).toBe('{"refresh_token":"synthetic"}'); + await store.remove(); + await expect(store.read()).rejects.toMatchObject({ code: "ENOENT" }); +}); + it.each(["local", "ssh", "sandbox"] as const)("rejects unsafe %s files without falling back to another credential", async target => { const { home, store } = await fixture(target, "grok"); await writeFile(join(home, "auth-refresh.json"), "must-not-read", { mode: 0o600 }); diff --git a/server/src/services/native-runtime/native-credential-store.ts b/server/src/services/native-runtime/native-credential-store.ts index 183b4c15d3f..c6775c0b5ad 100644 --- a/server/src/services/native-runtime/native-credential-store.ts +++ b/server/src/services/native-runtime/native-credential-store.ts @@ -37,13 +37,13 @@ try { }`; export function createNativeCredentialStore(input: { - provider: "codex" | "grok"; + provider: "codex" | "grok" | "antigravity"; localHome: string; remoteHome?: string; runner?: Pick; }) { if (Boolean(input.remoteHome) !== Boolean(input.runner)) throw new Error("native_credential_store_target_unavailable"); - const names = ["auth.json", "auth-refresh.json"]; + const names = input.provider === "antigravity" ? ["acp_token.json", "auth-refresh.json"] : ["auth.json", "auth-refresh.json"]; const read = async (name: string): Promise => { if (!input.runner || !input.remoteHome) return readLocalAiCredentialFile(join(input.localHome, name)); // Remote isolated-home preparation already requires Node. Read only on a refresh or retirement. 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 1cdedc406b1..2bfd423b190 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -140,6 +140,8 @@ import * as providerArtifactStorage from "./native-provider-artifacts.js"; import * as providerArtifactCapture from "./native-provider-artifact-capture.js"; import * as nativeCredentialEvents from "./native-credential-updates.js"; import * as nativeCredentialStores from "./native-credential-store.js"; +import * as antigravityRelease from "./antigravity-release.js"; +import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256 } from "./remote-provider-pack.js"; import * as managedCredentialWriteback from "../managed-ai-credential-writeback.js"; import { completeManagedNativeCredentialTurn } from "./managed-native-credentials.js"; import * as nativeExecutionDriver from "./native-runner-execution-driver.js"; @@ -5308,18 +5310,21 @@ describe("split durable provider checkpoint identity", () => { }); describe("remote provider checkpoint snapshots", () => { - it.each(["codex", "grok"] as const)("excludes %s credentials and handoffs from real checkpoint copies while retaining sessions", async provider => { + it.each(["codex", "grok", "antigravity"] as const)("excludes %s credentials and handoffs from real checkpoint copies while retaining sessions", async provider => { const root = await mkdtemp(join(tmpdir(), `${provider}-checkpoint-`)); try { const source = join(root, "source"); const target = join(root, "backup"); const sessionDirectory = acpxRuntimeSessionDirectoryName("session"); - const relativeHome = join("acpx", sessionDirectory, `${provider}-home`); + const relativeHome = provider === "antigravity" + ? join("acpx", sessionDirectory, "antigravity-home", "antigravity-acp") + : join("acpx", sessionDirectory, `${provider}-home`); + const primaryToken = provider === "antigravity" ? "acp_token.json" : "auth.json"; const home = join(source, relativeHome); await mkdir(join(home, "logs"), { recursive: true }); await mkdir(join(home, "sessions")); await writeFile(join(home, "logs", "unified.jsonl"), "AUTH_SENTINEL"); - await writeFile(join(home, "auth.json"), "AUTH_SENTINEL"); + await writeFile(join(home, primaryToken), "AUTH_SENTINEL"); await writeFile(join(home, "auth-refresh.json"), "AUTH_SENTINEL"); await writeFile(join(home, "auth-refresh.json.tmp"), "AUTH_SENTINEL"); await writeFile(join(home, "sessions", "session.json"), "resume-state"); @@ -5337,7 +5342,7 @@ describe("remote provider checkpoint snapshots", () => { await syncRemoteRunnerDirectoryOut({ runner: { execute, syncOut } as never, sourcePath: source, targetPath: target, mode: 0o700, excludeEntries: profile.directories.find(directory => directory.name === "acpx")!.excludeEntries }); - for (const entry of ["auth.json", "auth-refresh.json", "auth-refresh.json.tmp", ...(provider === "grok" ? ["logs"] : [])]) + for (const entry of [primaryToken, "auth-refresh.json", "auth-refresh.json.tmp", ...(provider === "grok" || provider === "antigravity" ? ["logs"] : [])]) await expect(access(join(target, relativeHome, entry))).rejects.toMatchObject({ code: "ENOENT" }); expect(await readFile(join(target, relativeHome, "sessions", "session.json"), "utf8")).toBe("resume-state"); expect(await readFile(join(home, "logs", "unified.jsonl"), "utf8")).toBe("AUTH_SENTINEL"); @@ -18605,6 +18610,110 @@ describe("runnerd provider runtime wiring", () => { } }); + it("projects the selected Antigravity subscription onto a Core remote sandbox and writes back rotated refreshes over the remote store", async () => { + const priorHome = process.env.PAPERCLIP_HOME; + const privateRoot = await realpath(isolatedStateDirectory); + process.env.PAPERCLIP_HOME = privateRoot; + const managedHome = join(privateRoot, "antigravity-remote-managed-home"); + await mkdir(join(managedHome, "antigravity-acp"), { recursive: true, mode: 0o700 }); + const credential = (project?: string) => JSON.stringify({ + client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com", client_secret: "fixture-client-secret", + refresh_token: "fixture-google-refresh", token_uri: "https://oauth2.googleapis.com/token", scopes: ["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/aicode"], + ...(project ? { project_id: project } : {}), + }); + const managedToken = join(managedHome, "antigravity-acp", "acp_token.json"); + await writeFile(managedToken, credential(), { mode: 0o600 }); + const current = { ...execution, + provider: { kind: "acpx", agent: "antigravity", model: "caller-selected-model", permissionMode: "deny-all" }, + session: { ...execution.session, driverKind: "acpx_runtime" }, + } as unknown as NativeExecutionInputV1; + const order: string[] = []; + const transportClose = vi.fn(async () => { order.push("transport-close"); }); + const nativeTransport = { close: transportClose }; + state.createTransport.mockReturnValueOnce({ transport: nativeTransport } as never); + const close = vi.fn(async () => { order.push("session-close"); await nativeTransport.close(); }); + state.createBackend.mockReturnValueOnce({ kind: "test", openSession: async () => ({ close }) } as never); + const remoteStore = { + read: vi.fn(async () => { order.push("remote-read"); return credential("rotated-remote-project"); }), + remove: vi.fn(async () => { order.push("remote-remove"); }), + }; + const releaseSpy = vi.spyOn(antigravityRelease, "antigravityReleasePending").mockReturnValue(false); + const storeSpy = vi.spyOn(nativeCredentialStores, "createNativeCredentialStore").mockReturnValueOnce(remoteStore); + const prepareRemoteSpy = vi.spyOn(nativeExecutionDriver, "prepareNativeRemoteRunner").mockResolvedValueOnce(undefined); + const execute = vi.fn(async () => ({ exitCode: 0, timedOut: false, stdout: "", stderr: "", signal: null, pid: null, startedAt: null })); + const packRoot = join(privateRoot, "antigravity-remote-pack"); + await mkdir(packRoot, { recursive: true, mode: 0o700 }); + const digest = "sha256:" + "a".repeat(64); + const canonical = (value: unknown): string => Array.isArray(value) + ? `[${value.map(canonical).join(",")}]` + : value && typeof value === "object" + ? `{${Object.entries(value as Record).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}` + : JSON.stringify(value); + const artifacts = Object.fromEntries(Object.entries({ + grokLauncher: "dist/providers/grok/launcher.cjs", nodeCommand: "node_modules/node/bin/node", + productionLock: "pnpm-lock.yaml", opencodeCommand: "node_modules/.bin/opencode", + opencodeExecutable: "node_modules/opencode-ai/bin/opencode.exe", + opencodeProxy: "dist/cli/opencode-app-server-proxy.cjs", acpxSidecar: "dist/cli/acpx-runtime-sidecar.cjs", + }).map(([key, path]) => [key, { path, sha256: digest }])); + const payload = { + compatibility: { opencode: 1, acpx: 1 }, contractDigest: digest, + target: { platform: "linux", architecture: "x64" }, runnerSourceRevision: "a".repeat(40), + pins: { nodeMinimum: "24.11.0", codex: QUALIFIED_ACPX_PROFILES.codex.agentRuntimeVersion, + opencode: "1.18.34", acpx: "0.22.0", grok: QUALIFIED_ACPX_PROFILES.grok.agentRuntimeVersion, + claudeAcp: QUALIFIED_ACPX_PROFILES.claude.agentServerVersion, codexAcp: QUALIFIED_ACPX_PROFILES.codex.agentServerVersion }, + acpxProfileDigests: Object.fromEntries(["grok", "claude", "codex"].map(agent => + [agent, QUALIFIED_ACPX_PROFILES[agent as "grok" | "claude" | "codex"].commandDigest])), + distDigest: digest, artifacts, + bridgeDigest: "sha256:" + createHash("sha256").update(digest + "\n" + digest + "\n" + digest).digest("hex"), + providers: { + antigravity: { + version: QUALIFIED_ACPX_PROFILES.antigravity.agentServerVersion, + profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, + closureDigest: `sha256:${ANTIGRAVITY_PATCHED_CLOSURE_SHA256["linux-x64"]}`, + qualification: "qualified", + path: "provider-assets/antigravity/linux-x64", + sha256: digest, + }, + }, + }; + const manifest = { schema: "paperclip-runner/remote-provider-pack/v1", payload, + digest: "sha256:" + createHash("sha256").update(canonical(payload)).digest("hex") }; + const previousPackPath = state.bundledPackManifestPath; + const previousRunnerBinary = state.bundledRunnerBinary; + state.bundledPackManifestPath = join(packRoot, "provider-pack.json"); + state.bundledRunnerBinary = join(packRoot, "linux-paperclip-runnerd"); + await writeFile(state.bundledPackManifestPath, JSON.stringify(manifest)); + const daemon = Buffer.alloc(64); daemon.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]); daemon.writeUInt16LE(62, 18); + await writeFile(state.bundledRunnerBinary, daemon); + try { + const backend = await createRunnerdBackend({ db: leaseDb(current), execution: current, + runnerInstanceId: "antigravity-remote-credential-close", managedAiCredentialHome: managedHome, + runnerExecutionTarget: { kind: "remote", transport: "sandbox", remoteCwd: "/workspace", runner: { execute } }, + runnerEnvironment: { GEMINI_HOME: "/ambient", GOOGLE_API_KEY: "ambient-key", PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "spoofed" } }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + const transport = state.createTransport.mock.calls.at(-1)![0]; + expect(transport.environment!.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET).toBe(credential()); + expect(transport.environment?.GEMINI_HOME).toBeUndefined(); + expect(transport.environment?.GOOGLE_API_KEY).toBeUndefined(); + const session = await backend.openSession({} as never); + expect(storeSpy).toHaveBeenCalledWith(expect.objectContaining({ + provider: "antigravity", + remoteHome: expect.stringMatching(/\/acpx\/acpx\/[^/]+\/antigravity-home\/antigravity-acp$/), + })); + await session.close({ reason: "completed" }); + expect(order).toEqual(["session-close", "transport-close", "remote-read", "remote-remove"]); + expect(await readFile(managedToken, "utf8")).toBe(credential("rotated-remote-project")); + } finally { + state.bundledPackManifestPath = previousPackPath; + state.bundledRunnerBinary = previousRunnerBinary; + releaseSpy.mockRestore(); + storeSpy.mockRestore(); + prepareRemoteSpy.mockRestore(); + if (priorHome === undefined) delete process.env.PAPERCLIP_HOME; + else process.env.PAPERCLIP_HOME = priorHome; + } + }); + it("still cleans up managed Codex credentials after an owned session closes", async () => { const close = vi.fn(async () => undefined); state.copyBackCodexAuth.mockClear(); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 3d940a64500..e0eafa55494 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -116,7 +116,7 @@ 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 { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } from "./antigravity-connection-policy.js"; import { antigravityCandidateTarget, antigravityForcesSameSessionRecovery, antigravityReleasePending, antigravityUsesRunScopedState, assertAntigravityExecutionAdmissible } from "./antigravity-release.js"; import { ANTIGRAVITY_SWARM_UNAVAILABLE } from "../antigravity-swarm-refusal.js"; import { bindAntigravityCredentialTurn, bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js"; @@ -8048,6 +8048,9 @@ export function resolveNativeHarnessPersistenceProfile( ...(execution.provider.agent === "grok" ? ["auth.json", "auth-refresh.json", "auth-refresh.json.tmp", "config.toml", "logs"].map((entry) => `acpx/${acpxRuntimeSessionDirectoryName(nativeSessionKey(execution))}/grok-home/${entry}`) + : execution.provider.agent === "antigravity" + ? ["acp_token.json", "auth-refresh.json", "auth-refresh.json.tmp", "logs"].map((entry) => + `acpx/${acpxRuntimeSessionDirectoryName(nativeSessionKey(execution))}/antigravity-home/antigravity-acp/${entry}`) : execution.provider.agent === "codex" ? CODEX_HOME_CHECKPOINT_EXCLUDED_ENTRIES.map( (entry) => @@ -11053,6 +11056,7 @@ async function executePaperclipNativeSessionAttempt( assertAntigravityExecutionAdmissible({ execution: input.execution, useRunnerd: input.useRunnerd, backend: input.backend, restartRecovery: input.restartRecovery, remoteTarget: input.runnerExecutionTarget?.kind === "remote", + pluginTask: input.runnerExecutionTarget?.kind === "remote" && input.runnerExecutionTarget.transport === "sandbox" && Boolean(input.runnerExecutionTarget.runnerTask), }); if (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "kimi" && QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending") { @@ -16989,6 +16993,16 @@ async function createRunnerdBackendWithinSessionClaim( const resumeFrom = !retainedOwner && !adopting && !input.relaunchReleased && prior && prior.environmentLeaseId !== remoteTarget.leaseId ? await resolvePluginTaskResume(input.db, { companyId: input.execution.binding.companyId, leaseId: remoteTarget.leaseId!, priorIdentity: prior }) : undefined; + if (provider.kind === "acpx" && provider.agent === "antigravity") { + const refusal = antigravityConnectionRefusal({ + apiKey: Boolean(input.runnerEnvironment?.GEMINI_API_KEY?.trim()), + remote: true, + lifecycleMode: input.execution.session.lifecyclePolicy.mode, + releasePending: antigravityReleasePending(), + remoteCandidateAdmitted: false, + }); + if (refusal) throw new AntigravityConnectionConfigurationError(refusal); + } const credentials = await preparePluginRunnerCredentials({ provider: provider.kind === "acpx" ? provider.agent : provider.kind, identity: input.managedAiCredentialIdentity, accountIdentity: input.managedAiAccountIdentity, @@ -19294,10 +19308,19 @@ async function createRunnerdBackendWithinSessionClaim( } if (antigravityCredential?.home && antigravityCredential.credential && !boundManagedSessions.has(session)) { boundManagedSessions.add(session); - const runtimeHome = resolve(resolvePaperclipInstanceRoot(), "runtime", "paperclip-runner", "acpx", "acpx", - acpxRuntimeSessionDirectoryName(nativeSessionKey(input.execution)), "antigravity-home"); + const relativeHome = `acpx/acpx/${acpxRuntimeSessionDirectoryName(nativeSessionKey(input.execution))}/antigravity-home`; + const runtimeHome = resolve(resolvePaperclipInstanceRoot(), "runtime", "paperclip-runner", relativeHome); + const runtimeStore = remoteRunnerFilesystemRoot && remoteCommandRunner + ? createNativeCredentialStore({ + provider: "antigravity", + localHome: join(runtimeHome, "antigravity-acp"), + remoteHome: posix.join(remoteRunnerFilesystemRoot, relativeHome, "antigravity-acp"), + runner: remoteCommandRunner, + }) + : undefined; return bindAntigravityCredentialTurn(session, { managedHome: antigravityCredential.home, credential: antigravityCredential.credential, runtimeHome, + ...(runtimeStore ? { runtimeStore } : {}), }); } const destinationHome = credentialProvider === "grok" ? grokCredential?.home : input.managedAiCredentialHome; diff --git a/server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts b/server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts new file mode 100644 index 00000000000..25e9bbb715e --- /dev/null +++ b/server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts @@ -0,0 +1,217 @@ +import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +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(() => ({ + released: false, + probe: vi.fn(), + createOwner: vi.fn(), +})); + +vi.mock("../../vendor/paperclip-runner/index.js", async importOriginal => { + const original = await importOriginal(); + 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("./plugin-runner-task.js", async importOriginal => { + const original = await importOriginal(); + return { + ...original, + createPluginRunnerTaskOwner: (input: Parameters[0]) => { + mocks.createOwner(input); + return { driver: { prepareLaunch: vi.fn() } }; + }, + }; +}); + +import { probePluginRunnerEnvironment } from "./plugin-runner-probe.js"; +import { resolvePaperclipRunnerProviderProfile } from "./provider-profile.js"; + +const SIGN_IN_ENV = "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET"; +const signInJson = JSON.stringify({ + client_id: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com", + client_secret: "fixture-client-secret", + refresh_token: "fixture-refresh-token", + token_uri: "https://oauth2.googleapis.com/token", + scopes: [ + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/userinfo.email", + "https://www.googleapis.com/auth/aicode", + ], +}); + +describe("plugin Runner probe for Google Antigravity", () => { + const roots: string[] = []; + const runnerTask = vi.fn(); + + function buildContext(env: Record = {}): AdapterEnvironmentTestContext { + return { + companyId: "company-1", + adapterType: "paperclip_runner", + config: { provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-high", env }, + executionTarget: { + kind: "remote", + transport: "sandbox", + remoteCwd: ".", + leaseId: "probe-lease", + runnerTaskProbe: { runId: "probe-run", sessionId: "probe-session" }, + runnerTask, + }, + } as unknown as AdapterEnvironmentTestContext; + } + + beforeEach(() => { + vi.clearAllMocks(); + mocks.released = false; + runnerTask.mockResolvedValue({ + kind: "description", + launchPreparationVersion: 1, + projectAuthCheckVersion: 1, + taskId: "probe-task", + runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` }, + }); + mocks.probe.mockImplementation(async input => { + await input.onCleanupConfirmed?.(); + return { + provider: "acpx", + providerDriver: "acpx_runtime", + effectiveModel: "gemini-3.8-flash-high", + admissionOnly: true, + sessionAdmissionPassed: true, + helloProbePassed: false, + }; + }); + }); + + afterEach(async () => { + mocks.released = false; + await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); + }); + + it("refuses plugin Runner-task probing while Antigravity is pending", async () => { + const result = await probePluginRunnerEnvironment(buildContext({ GEMINI_API_KEY: "fixture-gemini-key" }), { + identity: "key-id", + accountIdentity: "key-session", + }); + expect(result).toMatchObject({ + status: "fail", + checks: [{ code: "antigravity_remote_unavailable", level: "error" }], + }); + expect(runnerTask).not.toHaveBeenCalled(); + expect(mocks.probe).not.toHaveBeenCalled(); + }); + + it("probes a released Antigravity agent with a Gemini API key through the plugin Runner", async () => { + mocks.released = true; + const result = await probePluginRunnerEnvironment(buildContext({ GEMINI_API_KEY: "fixture-gemini-key" }), { + identity: "key-id", + accountIdentity: "key-session", + }); + expect(result).toMatchObject({ + status: "pass", + checks: [{ code: "antigravity_metadata_verified", level: "info" }], + }); + expect(mocks.createOwner).toHaveBeenCalledWith(expect.objectContaining({ + harness: "antigravity", + credentialIdentity: "key-id", + accountIdentity: "key-session", + credential: { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini-key" } }, + })); + expect(mocks.probe).toHaveBeenCalledWith(expect.objectContaining({ + provider: "acpx", + model: "gemini-3.8-flash-high", + admissionOnly: true, + transportOptions: expect.objectContaining({ + acpxAgent: "antigravity", + acpxPermissionMode: "deny-all", + acpxPermissionModePinned: true, + }), + })); + }); + + it("probes a released Antigravity agent with a Google sign-in through the plugin Runner", async () => { + mocks.released = true; + const managedHome = await realpath(await mkdtemp(join(tmpdir(), "antigravity-plugin-probe-"))); + roots.push(managedHome); + await mkdir(join(managedHome, "antigravity-acp"), { mode: 0o700 }); + await writeFile(join(managedHome, "antigravity-acp", "acp_token.json"), signInJson, { mode: 0o600 }); + + const result = await probePluginRunnerEnvironment(buildContext({}), { + identity: "google-id", + accountIdentity: "google-session", + home: managedHome, + }); + expect(result).toMatchObject({ + status: "pass", + checks: [{ code: "antigravity_metadata_verified", level: "info" }], + }); + expect(mocks.createOwner).toHaveBeenCalledWith(expect.objectContaining({ + harness: "antigravity", + credentialIdentity: "google-id", + accountIdentity: "google-session", + needsWriteback: true, + credential: { + type: "provider-env", + provider: "antigravity", + environment: { [SIGN_IN_ENV]: signInJson }, + }, + })); + expect(mocks.probe).toHaveBeenCalledWith(expect.objectContaining({ + provider: "acpx", + model: "gemini-3.8-flash-high", + admissionOnly: true, + })); + }); + + it("fails when the plugin Runner returns a mismatched Antigravity admission receipt", async () => { + mocks.released = true; + mocks.probe.mockImplementationOnce(async input => { + await input.onCleanupConfirmed?.(); + return { + provider: "acpx", + providerDriver: "acpx_runtime", + effectiveModel: "wrong-model", + admissionOnly: true, + sessionAdmissionPassed: true, + helloProbePassed: false, + }; + }); + const result = await probePluginRunnerEnvironment(buildContext({ GEMINI_API_KEY: "fixture-gemini-key" }), { + identity: "key-id", + accountIdentity: "key-session", + }); + expect(result).toMatchObject({ status: "fail", checks: [{ code: "runner_hello_probe_failed", level: "error" }] }); + }); + + it("requires a managed AI connection for Antigravity on a plugin Runner-task environment", async () => { + mocks.released = true; + const result = await probePluginRunnerEnvironment(buildContext({})); + expect(result).toMatchObject({ + status: "fail", + checks: [{ code: "runner_account_selection_required", level: "error" }], + }); + expect(runnerTask).not.toHaveBeenCalled(); + }); + + it("resolves released Antigravity profiles only with an explicit non-placeholder model", () => { + mocks.released = true; + expect(resolvePaperclipRunnerProviderProfile({ provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-high" })) + .toEqual({ provider: "acpx", backend: "acpx_runtime", model: "gemini-3.8-flash-high", acpxAgent: "antigravity" }); + for (const model of ["", "auto", "default"]) { + expect(() => resolvePaperclipRunnerProviderProfile({ provider: "acpx", acpxAgent: "antigravity", model })) + .toThrow("explicit model ID"); + } + }); +}); diff --git a/server/src/services/native-runtime/plugin-runner-probe.ts b/server/src/services/native-runtime/plugin-runner-probe.ts index 4a9a87a773a..3a37f7fa9a8 100644 --- a/server/src/services/native-runtime/plugin-runner-probe.ts +++ b/server/src/services/native-runtime/plugin-runner-probe.ts @@ -11,6 +11,8 @@ import { preparePluginRunnerCredentials } from "./plugin-runner-credentials.js"; import { createPluginRunnerTaskOwner } from "./plugin-runner-task.js"; import { resolvePaperclipRunnerProviderProfile } from "./provider-profile.js"; import { resolveAcpxQualification } from "./acpx-qualification.js"; +import { antigravityConnectionRefusal } from "./antigravity-connection-policy.js"; +import { antigravityReleasePending } from "./antigravity-release.js"; import { isRunnerRevisionMismatch, runnerRevisionMismatchTestResult } from "../runner-revision-mismatch.js"; /** Core verifies a real Runner; providers only implement their task API. */ @@ -29,10 +31,23 @@ export async function probePluginRunnerEnvironment(context: AdapterEnvironmentTe let cleanupConfirmed = false; let probeStarted = false; try { + const environment = (context.config.env ?? {}) as NodeJS.ProcessEnv; + const isAntigravityConfig = context.config.provider === "acpx" && context.config.acpxAgent === "antigravity"; + if (isAntigravityConfig) { + const refusal = antigravityConnectionRefusal({ + apiKey: Boolean(environment.GEMINI_API_KEY?.trim()), + remote: true, + releasePending: antigravityReleasePending(), + remoteCandidateAdmitted: false, + }); + if (refusal) { + return { adapterType: "paperclip_runner", status: "fail", testedAt, + checks: [{ code: refusal.code, level: "error", message: refusal.message }] }; + } + } const profile = resolvePaperclipRunnerProviderProfile(context.config); if (profile.provider !== "codex" && profile.provider !== "opencode" && profile.provider !== "acpx") throw new Error("Plugin Runner setup requires a workspace harness"); - const environment = (context.config.env ?? {}) as NodeJS.ProcessEnv; - if (!managed && (context.config.managedAiConnection || Object.values(environment).some(value => Boolean(value)))) { + if (!managed && (isAntigravityConfig || context.config.managedAiConnection || Object.values(environment).some(value => Boolean(value)))) { return { adapterType: "paperclip_runner", status: "fail", testedAt, checks: [{ code: "runner_account_selection_required", level: "error", message: "Select a saved AI account, or remove local environment overrides to test the installed account." }] }; @@ -50,9 +65,11 @@ export async function probePluginRunnerEnvironment(context: AdapterEnvironmentTe credentialIdentity: managed?.identity }); probeStarted = true; const effort = context.config.modelReasoningEffort ?? context.config.reasoningEffort ?? context.config.effort; + const isAntigravity = profile.provider === "acpx" && profile.acpxAgent === "antigravity"; const result = await probeNativeRunnerEnvironment({ runtimeDirectory: root, provider: profile.provider, // Plugin preparation selects the physical workspace; the probe uses its own logical scope. model: profile.model, timeoutMs: 45_000, + ...(isAntigravity ? { admissionOnly: true } : {}), ...(profile.provider === "codex" && typeof effort === "string" && effort ? { reasoningEffort: effort } : {}), environment: {}, transportOptions: { @@ -68,6 +85,15 @@ export async function probePluginRunnerEnvironment(context: AdapterEnvironmentTe }, onCleanupConfirmed: async () => { rmSync(root, { recursive: true, force: true }); cleanupConfirmed = true; }, }); + if (isAntigravity) { + if (result.provider !== "acpx" || result.providerDriver !== "acpx_runtime" || result.effectiveModel !== profile.model + || result.sessionAdmissionPassed !== true || result.admissionOnly !== true || result.helloProbePassed !== false) { + throw new Error("The selected Google runtime returned no matching account and model admission receipt."); + } + return { adapterType: "paperclip_runner", status: "pass", testedAt, + checks: [{ code: "antigravity_metadata_verified", level: "info", + message: "Google Antigravity verified the selected connection and exact model. No model prompt was sent." }] }; + } return { adapterType: "paperclip_runner", status: "pass", testedAt, checks: [{ code: "runner_hello_probe_passed", level: "info", message: `Runner verified ${result.providerDriver} with model ${result.effectiveModel}.` }] }; } catch (error) { diff --git a/server/src/services/native-runtime/provider-profile.ts b/server/src/services/native-runtime/provider-profile.ts index d797d704e6b..163a91967db 100644 --- a/server/src/services/native-runtime/provider-profile.ts +++ b/server/src/services/native-runtime/provider-profile.ts @@ -21,6 +21,7 @@ import { CLAUDE_MANAGED_QUALIFIED_MODEL, } from "../provider-profile-qualification.js"; import { resolveAcpxQualification, resolveAntigravityCandidateAdmission, resolveKimiCandidateAdmission, type AcpxQualificationCandidate } from "./acpx-qualification.js"; +import { antigravityReleasePending } from "./antigravity-release.js"; import { compatibleCodexModel } from "./codex-model-fallback.js"; import { claudeCliVersionAtLeast, @@ -43,6 +44,7 @@ export const DEFAULT_ACPX_RUNNER_MODELS = { copilot: null, pi: null, kimi: null, + antigravity: null, } as const; export type QualifiedPaperclipRunnerAcpxAgent = @@ -607,7 +609,12 @@ export function resolvePaperclipRunnerProviderProfile( if (acpxAgent === "copilot" && (!model || ["auto", "default"].includes(model.toLowerCase()))) { throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_model_required", "GitHub Copilot requires an explicit model ID; there is no default model."); } - const pendingAcpxProfile = PAPERCLIP_RUNNER_ACPX_PROFILES.find(profile => profile.value === acpxAgent && !profile.qualified); + if (acpxAgent === "antigravity" && (!model || ["auto", "default"].includes(model.toLowerCase()))) { + throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_model_required", "Google Antigravity requires an explicit model ID; there is no default model."); + } + const pendingAcpxProfile = acpxAgent === "antigravity" + ? (antigravityReleasePending() ? PAPERCLIP_RUNNER_ACPX_PROFILES.find(profile => profile.value === "antigravity") : undefined) + : PAPERCLIP_RUNNER_ACPX_PROFILES.find(profile => profile.value === acpxAgent && !profile.qualified); if (pendingAcpxProfile) { 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") { @@ -644,7 +651,7 @@ export function resolvePaperclipRunnerProviderProfile( if ((acpxAgent === "cursor" || acpxAgent === "pi" || acpxAgent === "kimi") && !model) { throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_model_required", "This ACPX agent requires an explicit model ID; there is no default model."); } - if (acpxAgent !== "claude" && acpxAgent !== "codex" && acpxAgent !== "grok" && acpxAgent !== "cursor" && acpxAgent !== "copilot" && acpxAgent !== "pi" && acpxAgent !== "kimi") { + if (acpxAgent !== "claude" && acpxAgent !== "codex" && acpxAgent !== "grok" && acpxAgent !== "cursor" && acpxAgent !== "copilot" && acpxAgent !== "pi" && acpxAgent !== "kimi" && acpxAgent !== "antigravity") { throw new PaperclipRunnerProviderProfileError( "paperclip_runner_acpx_agent_unavailable", "Paperclip Runner ACPX requires a qualified agent profile.", diff --git a/ui/src/components/new-agent/NewAgentSetup.tsx b/ui/src/components/new-agent/NewAgentSetup.tsx index 961c0b520af..a7018099b21 100644 --- a/ui/src/components/new-agent/NewAgentSetup.tsx +++ b/ui/src/components/new-agent/NewAgentSetup.tsx @@ -764,7 +764,7 @@ function Setup({ (tested.checks.some(check => check.code === "environment_agent_approval_required") || !connectionAdapter || tested.checks.some((check) => check.code.endsWith("hello_probe_passed") || check.code === "ai_connection_api_key_reverified" - || (brandType === "antigravity_runtime" && check.code === "antigravity_metadata_verified"), + || (brandType === "antigravity_runtime" && (check.code === "antigravity_metadata_verified" || check.code === "antigravity_remote_runtime_ready")), )) ) ? config : null; } catch (cause) { diff --git a/ui/src/lib/cloud-harness-policy.test.ts b/ui/src/lib/cloud-harness-policy.test.ts index f18f0f5e708..4340b6a8946 100644 --- a/ui/src/lib/cloud-harness-policy.test.ts +++ b/ui/src/lib/cloud-harness-policy.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { createCloudHarnessPolicy } from "./cloud-harness-policy"; import { isNewAgentAdapterAllowed } from "./new-agent-adapters"; @@ -67,4 +67,35 @@ describe("configured Cloud harness choices", () => { expect(isNewAgentAdapterAllowed("paperclip_runner", { cloud: true, harnessPolicy, nativeRunnerEnabled: false, runnerProvider: "codex" })).toBe(false); expect(isNewAgentAdapterAllowed("paperclip_runner", { cloud: true, harnessPolicy, nativeRunnerEnabled: false, runnerProvider: "copilot" })).toBe(true); }); + + it("offers a released Antigravity profile on Cloud without nativeRunnerEnabled or candidateHarnesses", async () => { + vi.resetModules(); + vi.doMock("@paperclipai/adapter-utils", async importOriginal => { + const actual = await importOriginal(); + return { + ...actual, + PAPERCLIP_RUNNER_ACPX_PROFILES: actual.PAPERCLIP_RUNNER_ACPX_PROFILES.map(profile => + profile.value === "antigravity" ? { ...profile, qualified: true } : profile), + }; + }); + try { + const { isNewAgentAdapterAllowed: allowed } = await import("./new-agent-adapters"); + const policy = createCloudHarnessPolicy(["antigravity_runtime"]); + expect(allowed("paperclip_runner", { + cloud: true, + harnessPolicy: policy, + nativeRunnerEnabled: false, + runnerProvider: "antigravity", + })).toBe(true); + expect(allowed("paperclip_runner", { + cloud: true, + harnessPolicy, + nativeRunnerEnabled: true, + runnerProvider: "antigravity", + })).toBe(false); + } finally { + vi.doUnmock("@paperclipai/adapter-utils"); + vi.resetModules(); + } + }); });