mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 15:52:36 +01:00
feat(runner): Antigravity on ACP 1.5.2 with Linux, API-key auth and Gemini 4 Neon (still pending) (#22591)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The native Runner starts each agent harness and owns its lifecycle, credentials and recovery > - Google Antigravity is Google's only first-party coding harness, and it is the harness for Gemini 4 Neon > - The Runner had an Antigravity integration, but only as a pending candidate: ACP server 1.4.3, macOS ARM64 only, Google sign-in only, closed unless an operator opened it for one company and one model > - Cloud sandboxes run Linux and use API keys, so the candidate could not run there, and it had one attended test cell > - This pull request moves the integration to ACP server 1.5.2, makes it run on Linux and with a Gemini API key, adds the tests the other ACPX harnesses have, and removes the code paths that would block recovery after release > - The benefit is that the release of Antigravity becomes a small declaration change after the live suites pass. The profile stays `pending` in this pull request. ## Linked Issues or Issue Description Refs #98 Refs #6559 Refs #8523 Refs #21121 (a separate legacy-style `agy_local` adapter that uses the CLI print protocol; this pull request does not replace or include it) ## What Changed **Runtime** - Pin Antigravity ACP server 1.5.2 (was 1.4.3). Owned admission patch is `1.5.2-paperclip.2`. - Verified patched closures for `darwin-arm64`, `linux-x64` and `linux-arm64`. `darwin-x64` stays inventory-only. - The patcher reads Mach-O and ELF builds. It signs macOS output only. One admission source serves all platforms. - Platform gates in TypeScript, Rust, the sidecar schema and the server admit each host that has a verified closure. **Auth and models** - Gemini API-key auth reaches an exact-model session receipt. Admission accepts a model only when the base model and the thinking level both match the requested ID. - API-key connections get a model list on local and cloud environments. The list is generated at build time from the pinned runtime. The server starts no process to read it. - Gemini 4 Neon, Carbon, Argon and Hydrogen are selectable. The picker marks them "needs a paid Gemini API plan" for API-key connections. - One shared module maps model ID to family and thinking level. - `google/gemini-4-neon` is added to the OpenCode model list. A new model audit is in `doc/adapter-model-audit-2026-11-22.md`. **Lifecycle and failures** - A provider error no longer completes the turn. The driver classifies it: overloaded, rate limit, quota, auth rejected, model unavailable. - Overload retries are bounded (3 attempts, about 14 seconds). - A refused session reload maps to incompatible saved state, so the automatic replacement conversation applies. - Server gates that refused restart recovery, remote targets and shared state for Antigravity now apply only while the profile is pending. - A Google sign-in connection with a cloud environment is refused at save and at Test, with a plain message. - A released profile rejects candidate grants in TypeScript and in Rust. **Launch cost and integrity (all native ACPX providers)** - Each closure is verified one time into a sealed read-only store. Later launches check file identities and hash the exact executable they start. - Remote provider-pack verification is recorded per sandbox lease. Later runs check kernel identity and fall back to the full hash on any difference. - Superseded stores are removed in the background after a launch. **Provider pack and image** - The provider pack carries Antigravity for `linux-x64` as a candidate provider. It becomes an ordinary provider from the profile status alone. - The Daytona image build accepts the candidate. A credential-free smoke runs in the build. **Tests and CI** - New `antigravity-qualification` suite: 24 cells, local and Daytona. - New model lineup suites: 14 API-key cells and 14 Gemini 4 cells. Each cell requires the exact model in the Runner receipt. - Antigravity can run the `chat-features` cases with `--profile runner-acpx-antigravity`. - `runner-full-stack-e2e.yml` passes `GEMINI_API_KEY` for the new profile and derives candidate providers from the selected Daytona cells. **Docs** - `doc/plans/2026-11-22-antigravity-qualification.md` is the current release contract, acceptance ledger and operator recipe. ## Verification Commands that passed on the final revision: - `pnpm build` - Typecheck for all packages, including the runner-e2e test projects - `pnpm test:e2e:runner:unit`: 11,665 Vitest tests passed, 25 skipped; 386 node tests passed - `cargo test -p paperclip-runner-core -- --test-threads=4`: 1,199 passed, 2 failed. The 2 failures are Codex transport timing tests that pass alone and on `master`. - `cargo fmt --check`, `check:acpx-profiles`, `check:protocol-types`, `node scripts/check-maps.mjs` - Native patch tests: 9 of 9 on `darwin-arm64` and 9 of 9 on `linux-x64` - UI picker tests: 397 of 397 Known failures that also fail on `master`: - 11 runner package script tests (browser, Pi and package-boundary checks) - 6 `runtime-selection` tests that read an untracked local skill file Live evidence, without a prompt: - Clean provisioning on `darwin-arm64` and on `linux-x64` in a Daytona sandbox. The closure digests reproduce. A changed or missing file is rejected. - `initialize` reports 1.5.2. An API-key session returns a receipt for exactly `gemini-3.8-flash-low` and the exact instruction bytes, on both platforms. - All 28 model IDs (14 Gemini 3, 14 Gemini 4) return an exact receipt under an API key. - A session survives a process kill and resumes in a new process with exact receipts, on both platforms. - The server's remote path verifies the provider pack in a Daytona sandbox. - Run start to native `initialize`: 3.45 s to 1.46 s on macOS, 3.65 s to 1.74 s on Linux x64, before the per-launch executable hash was restored (about 60 ms on macOS; not measured on Linux). - Remote pack verification on a reused sandbox lease: about 4.3 s to about 0.25 s. Live evidence, with a prompt, on an already-released harness: - Pi native, `pi-native.runner-acpx-pi.local.agent-files-fresh-run`, on `darwin-arm64` at `427e9b088b`: 1 of 1 passed, 14 of 14 checks, both native runs succeeded (25.5 s and 25.7 s). The process started from the new launch store with no fallback warning. - The same cell and `native-pending-controller-restart` failed in the paid workflow on this branch and on `master` in the same way, before any native start. The workflow does not install the Pi runtime for local cells, so the agent setup check fails. That is a workflow gap, not part of this change. **Not run.** No Antigravity prompt completed on 1.5.2 on any platform. The only Gemini key available is on the free tier, and Google returned 503 or 429 for each attempt on two days. These gates are open: - All 24 `antigravity-qualification` cells - Both model lineup suites, including inference on Gemini 4 Neon - The attended Google sign-in journey on 1.5.2 - The chat cases under Antigravity - Image pull time and startup time on a published image - A native start on `linux-arm64` - A live provider-death cell for Kimi, Pi or Copilot on the new launch store (one ordinary Pi cell passed live; see above) ## Risks - **The launch store changes how every native ACPX provider starts** (Kimi, Copilot, Cursor, Pi), not only Antigravity. A review found two defects in the first version (an executable swap was possible, and Pi launches broke). Both are fixed with tests. One live Pi cell passed on this branch on macOS. No live provider-death cell and no Linux cell ran for those providers. - The profile digest changes. Saved Antigravity candidate sessions and existing candidate grants stop working. The new release refuses old state by name and starts a replacement conversation. - The Linux provider pack and the Daytona image grow by about 834 MB (about 274 MB compressed) when Antigravity is included. - The pack verification record is in server memory. The first run after a server restart pays the full hash again. - Antigravity 1.5.2 reads the workspace `GEMINI.md` and `AGENTS.md` as user rules. This is deliberate and matches Codex. Any other rule file is refused. - Orchestrator mode is not available. ACP server 1.5.2 does not expose it. - Antigravity stays `pending`. Normal users cannot run it until a later change removes the pending status. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) planned, briefed and integrated the work, with tool use. - Claude Opus 5.5 (`claude-opus-5-5`) subagents wrote the code and ran the tests, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
17ccf6bd2e
commit
78e4f4f130
170 files changed
+8498
-954
No files matched your search
@@ -1,26 +1,56 @@
|
||||
import { PAPERCLIP_RUNNER_ACPX_PROFILES } from "@paperclipai/adapter-utils";
|
||||
import { parseAcpxCandidateAdmission, QUALIFIED_ACPX_PROFILES, type AcpxCandidateAdmission, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
import { isAntigravityNativeTarget, parseAcpxCandidateAdmission, QUALIFIED_ACPX_PROFILES, type AcpxCandidateAdmission, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
|
||||
/** Trusted operator startup authority, separate from saved agent configuration. */
|
||||
export const ANTIGRAVITY_CANDIDATE_ADMISSION_ENV = "PAPERCLIP_ACPX_CANDIDATE_ADMISSION";
|
||||
|
||||
/** The only target a cloud environment runs Antigravity on: the remote pack's patched linux-x64 closure. */
|
||||
export const ANTIGRAVITY_REMOTE_TARGET = Object.freeze({ platform: "linux", architecture: "x64" });
|
||||
|
||||
/** True when the operator granted this company and exact model a cloud (linux-x64) candidate. */
|
||||
export function antigravityRemoteCandidateAdmitted(input: { companyId?: string; model?: string }, hostEnvironment: NodeJS.ProcessEnv = process.env): boolean {
|
||||
try { return Boolean(input.model && resolveAntigravityCandidateAdmission({ ...input, target: ANTIGRAVITY_REMOTE_TARGET }, hostEnvironment)); }
|
||||
catch { return false; }
|
||||
}
|
||||
|
||||
/**
|
||||
* The operator's candidate grant for one company and exact model. With a
|
||||
* `target`, the grant must name that execution target (this host, or
|
||||
* `ANTIGRAVITY_REMOTE_TARGET` for a cloud environment) and its patched
|
||||
* closure. Without one (availability surfaces) a grant for this host or for
|
||||
* the cloud target is accepted. Other companies get nothing.
|
||||
*/
|
||||
export function resolveAntigravityCandidateAdmission(
|
||||
input: { companyId?: string; model?: string },
|
||||
input: { companyId?: string; model?: string; target?: { platform: string; architecture: string } },
|
||||
hostEnvironment: NodeJS.ProcessEnv = process.env,
|
||||
): AcpxCandidateAdmission | undefined {
|
||||
const encoded = hostEnvironment[ANTIGRAVITY_CANDIDATE_ADMISSION_ENV];
|
||||
if (!encoded || !input.companyId || process.platform !== "darwin" || process.arch !== "arm64") return undefined;
|
||||
if (!encoded || !input.companyId) return undefined;
|
||||
const hostNative = isAntigravityNativeTarget(process.platform, process.arch);
|
||||
// Only a target with a verified, patched closure can run the native candidate.
|
||||
if (input.target && !isAntigravityNativeTarget(input.target.platform, input.target.architecture)) return undefined;
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(encoded); } catch { throw new Error("Invalid Antigravity candidate admission"); }
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid Antigravity candidate admission");
|
||||
const record = value as Record<string, unknown>;
|
||||
// Other companies receive no candidate surface or execution authority.
|
||||
if (record.companyId !== input.companyId) return undefined;
|
||||
return parseAcpxCandidateAdmission(value, {
|
||||
const admission = parseAcpxCandidateAdmission(value, {
|
||||
companyId: input.companyId,
|
||||
agent: "antigravity",
|
||||
model: input.model ?? (typeof record.model === "string" ? record.model : ""),
|
||||
});
|
||||
const names = (target: { platform: string; architecture: string }) => admission.platform === target.platform && admission.architecture === target.architecture;
|
||||
if (input.target) {
|
||||
if (!names(input.target)) throw new Error("Antigravity candidate admission does not match the execution target");
|
||||
} else if (!names(ANTIGRAVITY_REMOTE_TARGET) && !names({ platform: process.platform, architecture: process.arch })) {
|
||||
// A host without a verified closure has no local surface to refuse.
|
||||
if (!hostNative) return undefined;
|
||||
throw new Error("Antigravity candidate admission does not match this host");
|
||||
} else if (!names(ANTIGRAVITY_REMOTE_TARGET) && !hostNative) {
|
||||
return undefined;
|
||||
}
|
||||
return admission;
|
||||
}
|
||||
|
||||
export function resolveKimiCandidateAdmission(
|
||||
|
||||
@@ -1,19 +1,25 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { QUALIFIED_ACPX_PROFILES } from "../../vendor/paperclip-runner/index.js";
|
||||
import { ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, resolveAntigravityCandidateAdmission } from "./acpx-qualification.js";
|
||||
import { ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, ANTIGRAVITY_REMOTE_TARGET, antigravityRemoteCandidateAdmitted, resolveAntigravityCandidateAdmission } from "./acpx-qualification.js";
|
||||
import { resolvePaperclipRunnerNativeProviderInput, resolvePaperclipRunnerProviderProfile } from "./provider-profile.js";
|
||||
import { resolveNativeRuntimeMode } from "./runtime-mode.js";
|
||||
|
||||
const companyId = "candidate-company";
|
||||
const model = "gemini-3.8-flash-low";
|
||||
const config = { provider: "acpx", acpxAgent: "antigravity", model };
|
||||
const localHost = process.platform === "darwin" && process.arch === "arm64";
|
||||
const distributions = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8"));
|
||||
const admission = () => ({ schema: "paperclip.acpx-candidate-admission.v1", companyId,
|
||||
agent: "antigravity", model, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest,
|
||||
nativeClosureDigest: `sha256:${distributions.platforms["darwin-arm64"].closureSha256}`,
|
||||
platform: "darwin", architecture: "arm64", expiresAt: Date.now() + 60_000 });
|
||||
const verifiedTargets = Object.keys(distributions.platforms).filter(target => distributions.platforms[target].provisioning === "verified-closure");
|
||||
const hostTarget = `${process.platform}-${process.arch}`;
|
||||
const localHost = verifiedTargets.includes(hostTarget);
|
||||
const targetAdmission = (target: string) => {
|
||||
const [platform, architecture] = target.split("-");
|
||||
return { schema: "paperclip.acpx-candidate-admission.v1", companyId,
|
||||
agent: "antigravity", model, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest,
|
||||
nativeClosureDigest: `sha256:${distributions.platforms[target].closureSha256}`,
|
||||
platform, architecture, expiresAt: Date.now() + 60_000 };
|
||||
};
|
||||
const admission = () => targetAdmission(localHost ? hostTarget : "darwin-arm64");
|
||||
|
||||
describe("Antigravity operator candidate admission", () => {
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
@@ -54,10 +60,40 @@ describe("Antigravity operator candidate admission", () => {
|
||||
.toMatchObject({ kind: "native", profile: { backend: "acpx_runtime" } });
|
||||
});
|
||||
|
||||
it("binds a cloud grant to linux-x64 and the patched closure, for its company and model only", () => {
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify(targetAdmission("linux-x64")));
|
||||
expect(resolveAntigravityCandidateAdmission({ companyId, model, target: ANTIGRAVITY_REMOTE_TARGET }))
|
||||
.toMatchObject({ companyId, model, platform: "linux", architecture: "x64" });
|
||||
expect(antigravityRemoteCandidateAdmitted({ companyId, model })).toBe(true);
|
||||
expect(antigravityRemoteCandidateAdmitted({ companyId: "another-company", model })).toBe(false);
|
||||
expect(antigravityRemoteCandidateAdmitted({ companyId, model: "gemini-3.8-flash-high" })).toBe(false);
|
||||
if (hostTarget !== "linux-x64") {
|
||||
expect(() => resolveAntigravityCandidateAdmission({ companyId, model, target: { platform: process.platform, architecture: process.arch } }))
|
||||
.toThrow(/does not match the execution target/);
|
||||
}
|
||||
for (const grant of [targetAdmission("linux-arm64"), targetAdmission("darwin-arm64"),
|
||||
{ ...targetAdmission("linux-x64"), nativeClosureDigest: `sha256:${distributions.platforms["linux-x64"].vendorClosureSha256}` }]) {
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify(grant));
|
||||
expect(antigravityRemoteCandidateAdmitted({ companyId, model })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("declares verified closures for macOS ARM and both Linux architectures", () => {
|
||||
expect(verifiedTargets.sort()).toEqual(["darwin-arm64", "linux-arm64", "linux-x64"]);
|
||||
});
|
||||
|
||||
it.runIf(localHost)("rejects another verified platform's exact record on this host", () => {
|
||||
// linux-x64 is also the cloud target, so a grant for it is a valid surface grant on any host.
|
||||
for (const target of verifiedTargets.filter(target => target !== hostTarget && target !== "linux-x64")) {
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify(targetAdmission(target)));
|
||||
expect(() => resolveAntigravityCandidateAdmission({ companyId, model })).toThrow(/does not match this host/);
|
||||
}
|
||||
});
|
||||
|
||||
it.runIf(localHost).each([
|
||||
{ expiresAt: 0 }, { profileDigest: `sha256:${"0".repeat(64)}` },
|
||||
{ nativeClosureDigest: `sha256:${"0".repeat(64)}` }, { platform: "linux" },
|
||||
{ architecture: "x64" }, { allowAll: true },
|
||||
{ nativeClosureDigest: `sha256:${"0".repeat(64)}` }, { platform: process.platform === "linux" ? "darwin" : "linux" },
|
||||
{ architecture: process.arch === "x64" ? "arm64" : "x64" }, { allowAll: true },
|
||||
])("rejects expired, changed or broad operator authorization %j", changes => {
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, JSON.stringify({ ...admission(), ...changes }));
|
||||
expect(() => resolveAntigravityCandidateAdmission({ companyId, model })).toThrow();
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Which Google Antigravity connections can run where. Configuration save and
|
||||
* Test refuse an unsupported choice up front with these messages; the run-time
|
||||
* check stays only as a defense, as a named permanent startup rejection.
|
||||
*/
|
||||
export const ANTIGRAVITY_REMOTE_UNAVAILABLE = "antigravity_remote_unavailable";
|
||||
export const ANTIGRAVITY_REMOTE_SIGN_IN_UNSUPPORTED = "antigravity_remote_sign_in_unsupported";
|
||||
export const ANTIGRAVITY_WARM_UNSUPPORTED = "antigravity_warm_unsupported";
|
||||
|
||||
export type AntigravityConnectionRefusal = {
|
||||
code: typeof ANTIGRAVITY_REMOTE_UNAVAILABLE | typeof ANTIGRAVITY_REMOTE_SIGN_IN_UNSUPPORTED | typeof ANTIGRAVITY_WARM_UNSUPPORTED;
|
||||
message: string;
|
||||
};
|
||||
|
||||
export function antigravityConnectionRefusal(input: {
|
||||
/** A Google API key is the connection, rather than a Google sign-in. */
|
||||
apiKey: boolean;
|
||||
remote: boolean;
|
||||
lifecycleMode?: "per_turn" | "warm";
|
||||
releasePending: boolean;
|
||||
/**
|
||||
* While pending: the operator granted this company and model a candidate for
|
||||
* the cloud target (linux-x64). It admits an API key only, never sign-in.
|
||||
*/
|
||||
remoteCandidateAdmitted?: boolean;
|
||||
}): AntigravityConnectionRefusal | null {
|
||||
// Antigravity runs one turn at a time on every connection until a warm
|
||||
// owner is separately qualified; lifecycle resolution already enforces it.
|
||||
if (input.lifecycleMode === "warm") {
|
||||
return { code: ANTIGRAVITY_WARM_UNSUPPORTED,
|
||||
message: "Google Antigravity runs one turn at a time. Turn off warm sessions for this agent." };
|
||||
}
|
||||
if (input.remote && input.releasePending && !(input.remoteCandidateAdmitted && input.apiKey)) {
|
||||
if (input.remoteCandidateAdmitted) {
|
||||
return { code: ANTIGRAVITY_REMOTE_SIGN_IN_UNSUPPORTED,
|
||||
message: "Google sign-in for Google Antigravity works only on the Paperclip host. To run this agent in a cloud environment, connect a Google API key instead." };
|
||||
}
|
||||
return { code: ANTIGRAVITY_REMOTE_UNAVAILABLE,
|
||||
message: "Google Antigravity runs only on the Paperclip host for now. Choose the Paperclip host as this agent's environment." };
|
||||
}
|
||||
if (input.apiKey) return null;
|
||||
if (input.remote) {
|
||||
return { code: ANTIGRAVITY_REMOTE_SIGN_IN_UNSUPPORTED,
|
||||
message: "Google sign-in for Google Antigravity works only on the Paperclip host. To run this agent in a cloud environment, connect a Google API key instead." };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A run reached execution with a connection its target cannot use. Retrying
|
||||
* cannot change the saved choice, so it is a permanent, named refusal. */
|
||||
export class AntigravityConnectionConfigurationError extends Error {
|
||||
readonly code: AntigravityConnectionRefusal["code"];
|
||||
constructor(refusal: AntigravityConnectionRefusal) {
|
||||
super(refusal.message);
|
||||
this.name = "AntigravityConnectionConfigurationError";
|
||||
this.code = refusal.code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Both release states are exercised against the same build: the pending
|
||||
// candidate declaration that ships today, and the qualified declaration the
|
||||
// flip produces (no qualificationStatus, profile version bumped), as the Kimi
|
||||
// probe tests stub it.
|
||||
const release = vi.hoisted(() => ({ pending: true }));
|
||||
vi.mock("../../vendor/paperclip-runner/index.js", async importOriginal => {
|
||||
const original = await importOriginal<typeof import("../../vendor/paperclip-runner/index.js")>();
|
||||
const { qualificationStatus: _pending, ...qualified } = original.QUALIFIED_ACPX_PROFILES.antigravity;
|
||||
const released = { ...qualified, agentProfileVersion: qualified.agentProfileVersion + 1 };
|
||||
const profiles = { ...original.QUALIFIED_ACPX_PROFILES };
|
||||
Object.defineProperty(profiles, "antigravity", { enumerable: true,
|
||||
get: () => release.pending ? original.QUALIFIED_ACPX_PROFILES.antigravity : released });
|
||||
return { ...original, QUALIFIED_ACPX_PROFILES: profiles };
|
||||
});
|
||||
|
||||
import { NativeProviderStateIncompatibleError, QUALIFIED_ACPX_PROFILES, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
import { ANTIGRAVITY_CANDIDATE_ADMISSION_ENV } from "./acpx-qualification.js";
|
||||
import {
|
||||
antigravityForcesSameSessionRecovery,
|
||||
antigravityReleasePending,
|
||||
antigravityUsesRunScopedState,
|
||||
assertAntigravityExecutionAdmissible,
|
||||
} from "./antigravity-release.js";
|
||||
import { buildNativeExecutionInput } from "./native-execution-input.js";
|
||||
import { nativeSessionFailureDisposition, nativeSessionFailureSourceCode, scopedRunnerdStateRoot } from "./native-session-executor.js";
|
||||
import { NATIVE_PROVIDER_STATE_INCOMPATIBLE } from "./native-session-resume.js";
|
||||
import { nativeRuntimeContextFixture } from "./runtime-context.test-fixture.js";
|
||||
|
||||
const companyId = "10000000-0000-4000-8000-000000000001";
|
||||
const model = "gemini-3.8-flash-low";
|
||||
const localHost = process.platform === "darwin" && process.arch === "arm64";
|
||||
const distributions = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8"));
|
||||
|
||||
function antigravityExecution(input: { runId?: string; issueId?: string; workspaceId?: string; sessionId?: string } = {}) {
|
||||
const runId = input.runId ?? "40000000-0000-4000-8000-000000000004";
|
||||
const execution = buildNativeExecutionInput({
|
||||
companyId, runId, agentId: "30000000-0000-4000-8000-000000000003",
|
||||
issue: { id: input.issueId ?? "20000000-0000-4000-8000-000000000002", identifier: "AG-1", title: "Test", description: null, workMode: "standard" },
|
||||
taskPrompt: "Only the current turn",
|
||||
workspace: { id: input.workspaceId ?? "90000000-0000-4000-8000-000000000009", cwd: "/workspace", repoUrl: null, repoRef: null, branchName: null },
|
||||
normalizedSessionId: input.sessionId ?? "60000000-0000-4000-8000-000000000006",
|
||||
provider: "acpx", acpxAgent: "antigravity", model, acpxPermissionMode: "approve-all",
|
||||
completionContract: { id: "70000000-0000-4000-8000-000000000007", sha256: `sha256:${"a".repeat(64)}`, schemaVersion: "paperclip.run-result.v1",
|
||||
contract: { revision: "1", objective: "Test", criteria: [{ id: "objective", requirement: "Answer" }] } },
|
||||
runtimeContext: nativeRuntimeContextFixture(),
|
||||
}) as NativeExecutionInput;
|
||||
// The execution input binds the profile version the running release declares.
|
||||
(execution.provider as { profile: { agentProfileVersion: number } }).profile.agentProfileVersion =
|
||||
QUALIFIED_ACPX_PROFILES.antigravity.agentProfileVersion;
|
||||
return execution;
|
||||
}
|
||||
|
||||
const candidateGrant = (target = "darwin-arm64", changes: Record<string, unknown> = {}) => {
|
||||
const [platform, architecture] = target.split("-");
|
||||
return JSON.stringify({ schema: "paperclip.acpx-candidate-admission.v1", companyId,
|
||||
agent: "antigravity", model, profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest,
|
||||
nativeClosureDigest: `sha256:${distributions.platforms[target].closureSha256}`,
|
||||
platform, architecture, expiresAt: Date.now() + 60_000, ...changes });
|
||||
};
|
||||
|
||||
afterEach(() => { release.pending = true; vi.unstubAllEnvs(); });
|
||||
|
||||
describe("Antigravity executor admission", () => {
|
||||
const admissible = (execution: NativeExecutionInput, changes: Partial<Parameters<typeof assertAntigravityExecutionAdmissible>[0]> = {}) =>
|
||||
() => assertAntigravityExecutionAdmissible({ execution, useRunnerd: true, remoteTarget: false, ...changes });
|
||||
|
||||
it("requires the exact local per-turn candidate grant while the profile is pending", () => {
|
||||
expect(antigravityReleasePending()).toBe(true);
|
||||
const execution = antigravityExecution();
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, undefined);
|
||||
expect(admissible(execution)).toThrow(/paperclip_runner_antigravity_candidate_ineligible/);
|
||||
if (!localHost) return;
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, candidateGrant());
|
||||
expect(admissible(execution)).not.toThrow();
|
||||
// A local grant never admits a cloud run.
|
||||
for (const change of [{ remoteTarget: true }, { restartRecovery: { kind: "same_run" } }, { useRunnerd: false }, { backend: {} }]) {
|
||||
expect(admissible(execution, change)).toThrow(/candidate_ineligible/);
|
||||
}
|
||||
const warm = { ...execution, session: { ...execution.session, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 1 } } } as NativeExecutionInput;
|
||||
expect(admissible(warm)).toThrow(/candidate_ineligible/);
|
||||
});
|
||||
|
||||
it("admits a cloud run only with a linux-x64 grant naming the patched closure, for the granted company", () => {
|
||||
const execution = antigravityExecution();
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, candidateGrant("linux-x64"));
|
||||
expect(admissible(execution, { remoteTarget: true })).not.toThrow();
|
||||
const warm = { ...execution, session: { ...execution.session, lifecyclePolicy: { mode: "warm", idleTimeoutMs: 1 } } } as NativeExecutionInput;
|
||||
expect(admissible(warm, { remoteTarget: true })).toThrow(/candidate_ineligible/);
|
||||
expect(admissible(execution, { remoteTarget: true, restartRecovery: { kind: "reattach_remote_runner" } })).toThrow(/candidate_ineligible/);
|
||||
const otherCompany = { ...execution, binding: { ...execution.binding, companyId: "10000000-0000-4000-8000-0000000000ff" } } as NativeExecutionInput;
|
||||
expect(admissible(otherCompany, { remoteTarget: true })).toThrow(/candidate_ineligible/);
|
||||
for (const grant of [candidateGrant("linux-arm64"), candidateGrant("darwin-arm64"),
|
||||
candidateGrant("linux-x64", { nativeClosureDigest: `sha256:${distributions.platforms["linux-x64"].vendorClosureSha256}` }),
|
||||
candidateGrant("linux-x64", { model: "gemini-3.8-flash-high" })]) {
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, grant);
|
||||
expect(admissible(execution, { remoteTarget: true })).toThrow(/candidate_ineligible/);
|
||||
}
|
||||
});
|
||||
|
||||
it("takes the general qualified path after the flip: no grant, restart recovery, remote and warm targets", () => {
|
||||
release.pending = false;
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, undefined);
|
||||
const execution = antigravityExecution();
|
||||
expect(admissible(execution)).not.toThrow();
|
||||
expect(admissible(execution, { remoteTarget: true, restartRecovery: { kind: "reattach_remote_runner" } })).not.toThrow();
|
||||
const preconfigured = { ...execution, homeMode: "preconfigured" } as NativeExecutionInput;
|
||||
expect(admissible(preconfigured)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Antigravity recovery policy and state root", () => {
|
||||
it("forces the candidate's same-session recovery and per-run root only while pending", () => {
|
||||
const execution = antigravityExecution();
|
||||
const nextRun = antigravityExecution({ runId: "50000000-0000-4000-8000-000000000005" });
|
||||
expect(antigravityForcesSameSessionRecovery(execution.provider)).toBe(true);
|
||||
expect(antigravityUsesRunScopedState(execution)).toBe(true);
|
||||
expect(scopedRunnerdStateRoot(execution)).not.toBe(scopedRunnerdStateRoot(nextRun));
|
||||
|
||||
release.pending = false;
|
||||
expect(antigravityForcesSameSessionRecovery(execution.provider)).toBe(false);
|
||||
expect(antigravityUsesRunScopedState(execution)).toBe(false);
|
||||
// Qualified: one root per session scope, kept across the session's runs.
|
||||
expect(scopedRunnerdStateRoot(execution)).toBe(scopedRunnerdStateRoot(nextRun));
|
||||
});
|
||||
|
||||
it.each([false, true])("never shares a state root across subtasks or workspaces (pending=%s)", pending => {
|
||||
release.pending = pending;
|
||||
const parent = antigravityExecution();
|
||||
const subtask = antigravityExecution({ issueId: "21000000-0000-4000-8000-000000000002",
|
||||
workspaceId: "91000000-0000-4000-8000-000000000009", sessionId: "61000000-0000-4000-8000-000000000006" });
|
||||
const otherWorkspace = antigravityExecution({ workspaceId: "92000000-0000-4000-8000-000000000009" });
|
||||
const roots = new Set([parent, subtask, otherWorkspace].map(scopedRunnerdStateRoot));
|
||||
expect(roots.size).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Antigravity state saved by the pending candidate, resumed by the qualified release", () => {
|
||||
it("refuses the candidate's in-flight state permanently and by name, never as a retryable interruption", () => {
|
||||
// Saved before the deploy under the candidate's profile version.
|
||||
const saved = antigravityExecution();
|
||||
release.pending = false;
|
||||
vi.stubEnv(ANTIGRAVITY_CANDIDATE_ADMISSION_ENV, undefined);
|
||||
let refusal: unknown;
|
||||
try {
|
||||
assertAntigravityExecutionAdmissible({ execution: saved, useRunnerd: true, remoteTarget: false,
|
||||
restartRecovery: { kind: "same_run_resume" } });
|
||||
} catch (error) { refusal = error; }
|
||||
expect(refusal).toBeInstanceOf(NativeProviderStateIncompatibleError);
|
||||
const code = nativeSessionFailureSourceCode(refusal);
|
||||
expect(code).toBe(NATIVE_PROVIDER_STATE_INCOMPATIBLE);
|
||||
expect(nativeSessionFailureDisposition(1, new Date(), code)).toMatchObject({
|
||||
phase: "terminal_failure", failureCode: NATIVE_PROVIDER_STATE_INCOMPATIBLE, nextAttemptAt: null });
|
||||
});
|
||||
|
||||
it("refuses an older qualified profile version by the same name", () => {
|
||||
release.pending = false;
|
||||
const saved = antigravityExecution();
|
||||
(saved.provider as { profile: { agentProfileVersion: number } }).profile.agentProfileVersion -= 1;
|
||||
expect(() => assertAntigravityExecutionAdmissible({ execution: saved, useRunnerd: true, remoteTarget: false }))
|
||||
.toThrow(NativeProviderStateIncompatibleError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
import {
|
||||
NativeProviderStateIncompatibleError,
|
||||
QUALIFIED_ACPX_PROFILES,
|
||||
type NativeExecutionInput,
|
||||
} from "../../vendor/paperclip-runner/index.js";
|
||||
import { ANTIGRAVITY_REMOTE_TARGET, resolveAntigravityCandidateAdmission } from "./acpx-qualification.js";
|
||||
|
||||
/** The platform a pending candidate grant must name for this execution. */
|
||||
export function antigravityCandidateTarget(remote: boolean): { platform: string; architecture: string } {
|
||||
return remote ? ANTIGRAVITY_REMOTE_TARGET : { platform: process.platform, architecture: process.arch };
|
||||
}
|
||||
|
||||
/**
|
||||
* Google Antigravity's server gates while its Runner profile is pending, and
|
||||
* the general qualified ACPX path after the release flip. Every gate reads the
|
||||
* release declaration at call time, the way Kimi's do, never the agent name
|
||||
* alone, so the flip needs no change here.
|
||||
*/
|
||||
export function antigravityReleasePending(): boolean {
|
||||
return QUALIFIED_ACPX_PROFILES.antigravity.qualificationStatus === "pending";
|
||||
}
|
||||
|
||||
export function isAntigravityProvider(
|
||||
provider: NativeExecutionInput["provider"] | undefined,
|
||||
): provider is Extract<NativeExecutionInput["provider"], { kind: "acpx" }> {
|
||||
return provider?.kind === "acpx" && provider.agent === "antigravity";
|
||||
}
|
||||
|
||||
/** Only the pending candidate owns a fresh daemon and state root per run. A
|
||||
* qualified release keeps the ordinary per-session scope (company, agent,
|
||||
* workspace and task session), so subtasks still never share a root. */
|
||||
export function antigravityUsesRunScopedState(execution: NativeExecutionInput): boolean {
|
||||
return isAntigravityProvider(execution.provider) && antigravityReleasePending();
|
||||
}
|
||||
|
||||
/** The candidate keeps its saved conversation to the same session. A qualified
|
||||
* release uses the ordinary recovery policy, including the automatic
|
||||
* replacement conversation after a failed resume. */
|
||||
export function antigravityForcesSameSessionRecovery(provider: NativeExecutionInput["provider"] | undefined): boolean {
|
||||
return isAntigravityProvider(provider) && antigravityReleasePending();
|
||||
}
|
||||
|
||||
export const ANTIGRAVITY_EARLIER_RELEASE_STATE_REASON =
|
||||
"Google Antigravity session state was saved by an earlier release";
|
||||
|
||||
// The persisted profile snapshot carries no qualification status. The flip
|
||||
// bumps agentProfileVersion, so candidate-era state differs here by version.
|
||||
const RELEASE_IDENTITY_FIELDS = [
|
||||
"agentProfileVersion", "commandDigest", "acpxVersion", "agentServerPackage", "agentServerVersion",
|
||||
"agentRuntimePackage", "agentRuntimeVersion",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Saved Antigravity state binds the release profile it was created under. State
|
||||
* from another release (the pending candidate's per-run root and grant under
|
||||
* its profile version, or any older profile) is refused permanently and by
|
||||
* name. The run keeps its saved session and workspace, and the next run starts
|
||||
* a replacement conversation in the same workspace instead of repeating it.
|
||||
*/
|
||||
export function assertAntigravitySavedStateCurrent(execution: NativeExecutionInput): void {
|
||||
if (!isAntigravityProvider(execution.provider)) return;
|
||||
const saved = (execution.provider.profile ?? {}) as unknown as Record<string, unknown>;
|
||||
const current = QUALIFIED_ACPX_PROFILES.antigravity as unknown as Record<string, unknown>;
|
||||
if (RELEASE_IDENTITY_FIELDS.some(field => saved[field] !== current[field])) {
|
||||
throw new NativeProviderStateIncompatibleError(ANTIGRAVITY_EARLIER_RELEASE_STATE_REASON);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executor admission. While pending, only an exact per-turn candidate grant
|
||||
* bound to the execution target's platform may run: this host locally, or the
|
||||
* cloud pack's linux-x64 closure remotely. After the flip no grant is needed and Antigravity takes the
|
||||
* same path as Kimi and Copilot; only state saved by another release is refused.
|
||||
*/
|
||||
export function assertAntigravityExecutionAdmissible(input: {
|
||||
execution: NativeExecutionInput;
|
||||
useRunnerd?: boolean;
|
||||
backend?: unknown;
|
||||
restartRecovery?: unknown;
|
||||
remoteTarget: boolean;
|
||||
hostEnvironment?: NodeJS.ProcessEnv;
|
||||
}): void {
|
||||
const { execution } = input;
|
||||
if (!isAntigravityProvider(execution.provider)) return;
|
||||
if (!antigravityReleasePending()) {
|
||||
assertAntigravitySavedStateCurrent(execution);
|
||||
return;
|
||||
}
|
||||
let candidate: ReturnType<typeof resolveAntigravityCandidateAdmission>;
|
||||
try {
|
||||
candidate = resolveAntigravityCandidateAdmission({
|
||||
companyId: execution.binding.companyId, model: execution.provider.model, target: antigravityCandidateTarget(input.remoteTarget),
|
||||
}, input.hostEnvironment ?? process.env);
|
||||
} catch { candidate = undefined; }
|
||||
if (!candidate || !input.useRunnerd || input.backend || input.restartRecovery
|
||||
|| execution.session.lifecyclePolicy.mode !== "per_turn"
|
||||
|| ("homeMode" in execution && execution.homeMode === "preconfigured")) {
|
||||
throw new Error("paperclip_runner_antigravity_candidate_ineligible: exact target-bound per-turn candidate admission is required");
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import { antigravityCredentialTurn, bindAntigravityCredentialTurn, bindAntigravi
|
||||
import { completeManagedNativeCredentialTurn } from "./managed-native-credentials.js";
|
||||
import type { NativeSession, createRunnerdCodexTransport } from "../../vendor/paperclip-runner/index.js";
|
||||
import { bindRetainedGoogleCredentialHome } from "../retained-google-credential-cleanup.js";
|
||||
import { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } from "./antigravity-connection-policy.js";
|
||||
import { NATIVE_PROVIDER_STARTUP_REJECTED, nativeSessionFailureDisposition, nativeSessionFailureSourceCode } from "./native-session-executor.js";
|
||||
|
||||
const copyFault = vi.hoisted(() => ({ phase: "", destination: "", source: "", collisionPath: "", failedRemoval: "", removals: [] as string[], hits: 0 }));
|
||||
vi.mock("./runner-api-files.js", async importOriginal => {
|
||||
@@ -103,8 +105,40 @@ describe("Antigravity managed Runner credentials", () => {
|
||||
expect(await prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: { GEMINI_HOME: "/untrusted" } })).toEqual({
|
||||
home: managedHome, credential: credential("fixture-selected"), environment: { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: credential("fixture-selected") },
|
||||
});
|
||||
await expect(prepareAntigravityRunnerCredentials({ remote: true, managedHome, environment: {} })).rejects.toThrow("not qualified for remote");
|
||||
await expect(prepareAntigravityRunnerCredentials({ remote: false, managedHome, environment: {}, lifecycleMode: "warm" })).rejects.toThrow("warm sessions are not qualified");
|
||||
for (const [input, code] of [[{ remote: true, environment: {} }, "antigravity_remote_sign_in_unsupported"],
|
||||
[{ remote: false, lifecycleMode: "warm" as const, environment: {} }, "antigravity_warm_unsupported"],
|
||||
[{ remote: false, lifecycleMode: "warm" as const, environment: { GEMINI_API_KEY: "fixture-selected" } }, "antigravity_warm_unsupported"]] as const) {
|
||||
const refusal = await prepareAntigravityRunnerCredentials({ managedHome, ...input }).catch(error => error);
|
||||
// Configuration save and Test refuse this first; a run that still
|
||||
// reaches it stops permanently by name instead of offering a Retry.
|
||||
expect(refusal).toBeInstanceOf(AntigravityConnectionConfigurationError);
|
||||
expect(refusal).toMatchObject({ code });
|
||||
expect(refusal.message).toMatch(code === "antigravity_warm_unsupported" ? /^Google Antigravity runs one turn at a time\. Turn off warm sessions for this agent\.$/ : /Google API key/);
|
||||
const failure = nativeSessionFailureSourceCode(refusal);
|
||||
expect(failure).toBe(NATIVE_PROVIDER_STARTUP_REJECTED);
|
||||
expect(nativeSessionFailureDisposition(1, new Date(), failure)).toMatchObject({ phase: "terminal_failure", failureCode: NATIVE_PROVIDER_STARTUP_REJECTED });
|
||||
}
|
||||
});
|
||||
it("names the connection choices each target supports in both release states", () => {
|
||||
expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: false })).toBeNull();
|
||||
// Per-turn is one contract for both routes: an API key does not enable warm.
|
||||
for (const apiKey of [true, false]) {
|
||||
expect(antigravityConnectionRefusal({ apiKey, remote: false, lifecycleMode: "warm", releasePending: false })?.code).toBe("antigravity_warm_unsupported");
|
||||
expect(antigravityConnectionRefusal({ apiKey, remote: false, lifecycleMode: "per_turn", releasePending: false })).toBeNull();
|
||||
}
|
||||
expect(antigravityConnectionRefusal({ apiKey: false, remote: false, releasePending: false })).toBeNull();
|
||||
expect(antigravityConnectionRefusal({ apiKey: false, remote: true, releasePending: false })?.message)
|
||||
.toBe("Google sign-in for Google Antigravity works only on the Paperclip host. To run this agent in a cloud environment, connect a Google API key instead.");
|
||||
expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true })?.code).toBe("antigravity_remote_unavailable");
|
||||
expect(antigravityConnectionRefusal({ apiKey: false, remote: false, releasePending: true })).toBeNull();
|
||||
// While pending, an operator's cloud grant admits an API key in a cloud environment, never Google sign-in.
|
||||
expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true, remoteCandidateAdmitted: true })).toBeNull();
|
||||
expect(antigravityConnectionRefusal({ apiKey: false, remote: true, releasePending: true, remoteCandidateAdmitted: true })?.code)
|
||||
.toBe("antigravity_remote_sign_in_unsupported");
|
||||
expect(antigravityConnectionRefusal({ apiKey: true, remote: true, releasePending: true, remoteCandidateAdmitted: false })?.code)
|
||||
.toBe("antigravity_remote_unavailable");
|
||||
expect(antigravityConnectionRefusal({ apiKey: true, remote: true, lifecycleMode: "warm", releasePending: true, remoteCandidateAdmitted: true })?.code)
|
||||
.toBe("antigravity_warm_unsupported");
|
||||
});
|
||||
it.each(["symlink", "public", "invalid"])("rejects a %s selected token without using a fallback", async kind => {
|
||||
const managedHome = await home(), token = join(managedHome, "antigravity-acp", "acp_token.json");
|
||||
|
||||
@@ -11,6 +11,7 @@ import { withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-lo
|
||||
import { openRunnerWorkspaceFile } from "./runner-api-files.js";
|
||||
import type { NativeSession, createRunnerdCodexTransport } from "../../vendor/paperclip-runner/index.js";
|
||||
import { bindManagedNativeCredentialTurn } from "./managed-native-credentials.js";
|
||||
import { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } from "./antigravity-connection-policy.js";
|
||||
|
||||
const AUTH_SECRET = "PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET";
|
||||
const TOKEN_FILE = "acp_token.json";
|
||||
@@ -43,10 +44,12 @@ export async function prepareAntigravityRunnerCredentials(input: {
|
||||
}): Promise<{ environment: NodeJS.ProcessEnv; home: string | null; credential?: string }> {
|
||||
const environment = { ...input.environment };
|
||||
for (const key of [AUTH_SECRET, "GEMINI_HOME", "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_ACCESS_TOKEN"]) delete environment[key];
|
||||
if (environment.GEMINI_API_KEY?.trim()) return { environment, home: null };
|
||||
const apiKey = Boolean(environment.GEMINI_API_KEY?.trim());
|
||||
// Save and Test refuse these choices first; this is the run-time defense.
|
||||
const refusal = antigravityConnectionRefusal({ apiKey, remote: input.remote, lifecycleMode: input.lifecycleMode, releasePending: false });
|
||||
if (refusal) throw new AntigravityConnectionConfigurationError(refusal);
|
||||
if (apiKey) return { environment, home: null };
|
||||
delete environment.GEMINI_API_KEY;
|
||||
if (input.remote) throw new Error("Google Antigravity subscription authentication is not qualified for remote environments. Select a Google API key or use the Paperclip host.");
|
||||
if (input.lifecycleMode === "warm") throw new Error("Google Antigravity subscription authentication requires turn-by-turn sessions; warm sessions are not qualified.");
|
||||
const home = input.managedHome?.trim();
|
||||
if (!home) throw new Error("Google Antigravity requires a selected managed Google account or Google API key.");
|
||||
await reconcileRetainedGoogleCleanupForHome(home);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { PrpEvent, PrpTerminalState } from "../../vendor/paperclip-runner/index.js";
|
||||
import { createNativeProviderFailureObservation, NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC, NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_OVERLOADED_MESSAGE, readNativeTurnFailureDiagnostic } from "./native-provider-failure.js";
|
||||
import { antigravityModelRefusalMessage } from "@paperclipai/shared";
|
||||
import { createNativeProviderFailureObservation, nativeProviderUsageLimitFromEvent, NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC, NATIVE_MODEL_REJECTION_DIAGNOSTIC, NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_OVERLOADED_MESSAGE, readNativeTurnFailureDiagnostic } from "./native-provider-failure.js";
|
||||
|
||||
const model = "test-model";
|
||||
const response = {
|
||||
@@ -290,3 +291,66 @@ describe("native provider failure observation", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Google Antigravity provider failures", () => {
|
||||
const antigravity = (route?: "api_key" | "subscription", modelId = "gemini-4-neon-high") =>
|
||||
createNativeProviderFailureObservation({ kind: "acpx", agent: "antigravity", model: modelId }, route ? { antigravityRoute: route } : {});
|
||||
const failed = (providerFailure: Record<string, unknown>): PrpEvent => ({ ...event, payload: { status: "failed", error: { providerFailure: {
|
||||
schema: "paperclip.provider-failure.v1", provider: "antigravity", phase: "turn", ...providerFailure } } } });
|
||||
const refused = failed({ category: "model_unavailable", message: "The selected model is not available for this connection.",
|
||||
providerCode: "antigravity_model_unavailable", httpStatus: 429, retryability: "requires_action" });
|
||||
|
||||
it("names the refused model and the fix for an API key", () => {
|
||||
const observed = antigravity("api_key");
|
||||
observed.observe(refused);
|
||||
const result = observed.forTerminal("turn", terminal);
|
||||
expect(result).toMatchObject({ errorCode: "native_provider_model_rejected",
|
||||
errorMessage: antigravityModelRefusalMessage("gemini-4-neon-high", "api_key") });
|
||||
expect(result?.errorMessage).toContain("Gemini 4 Neon (High) is not available with this Gemini API key.");
|
||||
expect(result?.errorMessage).not.toMatch(/antigravity_model_unavailable|RESOURCE_EXHAUSTED|429/);
|
||||
expect(observed.unclassifiedTurnFailure("turn", terminal)).toBeNull();
|
||||
});
|
||||
|
||||
it("names the refused model and the fix for a Google sign-in", () => {
|
||||
const observed = antigravity("subscription", "gemini-3.8-flash-high");
|
||||
observed.observe(refused);
|
||||
expect(observed.forTerminal("turn", terminal)?.errorMessage)
|
||||
.toBe(antigravityModelRefusalMessage("gemini-3.8-flash-high", "subscription"));
|
||||
});
|
||||
|
||||
it("keeps the shared message when the connection route is unknown (recovered after restart)", () => {
|
||||
const observed = antigravity();
|
||||
observed.observe(refused);
|
||||
expect(observed.forTerminal("turn", terminal)).toMatchObject({ errorCode: "native_provider_model_rejected", errorMessage: NATIVE_MODEL_REJECTION_MESSAGE });
|
||||
});
|
||||
|
||||
it("takes the bounded capacity retry for a transient overload (503)", () => {
|
||||
const observed = antigravity("api_key");
|
||||
observed.observe(failed({ category: "overloaded", message: "This model is currently experiencing high demand.",
|
||||
providerCode: "UNAVAILABLE", httpStatus: 503, retryability: "transient" }));
|
||||
expect(observed.forTerminal("turn", terminal)).toEqual({ errorCode: "native_provider_overloaded",
|
||||
errorMessage: NATIVE_PROVIDER_OVERLOADED_MESSAGE, diagnostic: { provider: "antigravity", category: "server_overloaded" } });
|
||||
expect(observed.unclassifiedTurnFailure("turn", terminal)).toBeNull();
|
||||
});
|
||||
|
||||
it("leaves rate limits, quotas and rejected keys to their own plain-language paths", () => {
|
||||
for (const failure of [
|
||||
{ category: "rate_limit", message: "Slow down", httpStatus: 429, retryAt: "2026-01-01T00:01:00.000Z", retryability: "transient" },
|
||||
{ category: "quota_exhausted", message: "Quota exhausted", httpStatus: 429, retryability: "requires_action" },
|
||||
{ category: "authentication", message: "API key not valid. Please pass a valid API key.", httpStatus: 400, retryability: "requires_action" },
|
||||
]) {
|
||||
const observed = antigravity("api_key");
|
||||
const input = failed(failure);
|
||||
observed.observe(input);
|
||||
expect(observed.forTerminal("turn", terminal)).toBeNull();
|
||||
expect(observed.providerFailureForTerminal("turn", terminal)).toMatchObject({ category: failure.category, message: failure.message });
|
||||
expect(nativeProviderUsageLimitFromEvent(input)).toBe(failure.category !== "authentication");
|
||||
}
|
||||
});
|
||||
|
||||
it("does not turn another ACPX harness's overload into an Antigravity capacity retry", () => {
|
||||
const observed = createNativeProviderFailureObservation({ kind: "acpx", agent: "claude", model: "m" });
|
||||
observed.observe(failed({ provider: "claude", category: "overloaded", message: "Overloaded", httpStatus: 529, retryability: "transient" }));
|
||||
expect(observed.forTerminal("turn", terminal)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { PrpEvent, PrpTerminalState } from "../../vendor/paperclip-runner/index.js";
|
||||
import { readProviderFailure, type ProviderFailure } from "@paperclipai/shared";
|
||||
import { antigravityModelRefusalMessage, readProviderFailure, type AntigravityAuthRoute, type ProviderFailure } from "@paperclipai/shared";
|
||||
|
||||
/** The runner driver's provider code for a model Google refused for the connection. */
|
||||
const ANTIGRAVITY_MODEL_UNAVAILABLE_CODE = "antigravity_model_unavailable";
|
||||
|
||||
// Shared by every provider whose selected model is rejected, so it names no specific connection.
|
||||
export const NATIVE_MODEL_REJECTION_MESSAGE =
|
||||
@@ -234,7 +237,14 @@ export function readNativeTurnFailureDiagnostic(value: unknown): NativeTurnFailu
|
||||
}
|
||||
|
||||
/** Observe only events accepted by the bound control-plane persistence port. */
|
||||
export function createNativeProviderFailureObservation(provider: { kind: string; model?: string | null }) {
|
||||
export function createNativeProviderFailureObservation(
|
||||
provider: { kind: string; model?: string | null; agent?: string },
|
||||
options: {
|
||||
/** Google Antigravity's connection route, known only where the run's credentials were resolved. */
|
||||
antigravityRoute?: AntigravityAuthRoute;
|
||||
} = {},
|
||||
) {
|
||||
const antigravity = provider.kind === "acpx" && provider.agent === "antigravity";
|
||||
let rejectedTurnId: string | null = null;
|
||||
/** A Codex API-key turn whose configured model the Responses API does not serve (404). */
|
||||
let missingModelTurnId: string | null = null;
|
||||
@@ -252,6 +262,11 @@ export function createNativeProviderFailureObservation(provider: { kind: string;
|
||||
&& event.payload.status === "failed") {
|
||||
const failure = readProviderFailure(record(event.payload.error).providerFailure);
|
||||
if (failure && !providerFailures.has(event.turnId)) providerFailures.set(event.turnId, failure);
|
||||
// Antigravity's owned patch types Google's 503 as a transient overload:
|
||||
// it takes the same bounded capacity retry as Codex's serverOverloaded.
|
||||
if (antigravity && failure?.category === "overloaded" && failure.retryability === "transient") {
|
||||
overloadedTurnId = event.turnId;
|
||||
}
|
||||
}
|
||||
if ((provider.kind !== "codex" && provider.kind !== "opencode") ||
|
||||
event.sourceKind !== "runner" || event.eventType !== "turn.failed" || !event.turnId) return;
|
||||
@@ -305,11 +320,11 @@ export function createNativeProviderFailureObservation(provider: { kind: string;
|
||||
if (turnId === overloadedTurnId) return {
|
||||
errorCode: NATIVE_PROVIDER_OVERLOADED_CODE,
|
||||
errorMessage: NATIVE_PROVIDER_OVERLOADED_MESSAGE,
|
||||
diagnostic: { ...NATIVE_PROVIDER_OVERLOADED_DIAGNOSTIC },
|
||||
diagnostic: antigravity ? { provider: "antigravity", category: "server_overloaded" } : { ...NATIVE_PROVIDER_OVERLOADED_DIAGNOSTIC },
|
||||
};
|
||||
// Every model rejection shares one result; only its closed diagnostic differs.
|
||||
const modelRejection = <T>(diagnostic: T) => ({
|
||||
errorCode: "native_provider_model_rejected" as const, errorMessage: NATIVE_MODEL_REJECTION_MESSAGE, diagnostic,
|
||||
const modelRejection = <T>(diagnostic: T, errorMessage: string = NATIVE_MODEL_REJECTION_MESSAGE) => ({
|
||||
errorCode: "native_provider_model_rejected" as const, errorMessage, diagnostic,
|
||||
});
|
||||
if (turnId === missingModelTurnId) return modelRejection({ ...NATIVE_MODEL_NOT_FOUND_DIAGNOSTIC });
|
||||
if (turnId === rejectedTurnId) return modelRejection({ ...NATIVE_MODEL_REJECTION_DIAGNOSTIC });
|
||||
@@ -317,7 +332,12 @@ export function createNativeProviderFailureObservation(provider: { kind: string;
|
||||
// action-required rejection qualifies; a transient one may succeed on retry.
|
||||
if (!modelUnavailableTurn(turnId)) return null;
|
||||
const failure = providerFailures.get(turnId)!;
|
||||
return modelRejection(failedTurns.get(turnId) ?? { provider: failure.provider, category: failure.category });
|
||||
// Antigravity's typed refusal names the configured model and the fix for
|
||||
// its connection route. Without the route (a run recovered after a
|
||||
// restart), the shared message stays accurate.
|
||||
const message = antigravity && failure.providerCode === ANTIGRAVITY_MODEL_UNAVAILABLE_CODE && provider.model && options.antigravityRoute
|
||||
? antigravityModelRefusalMessage(provider.model, options.antigravityRoute) : undefined;
|
||||
return modelRejection(failedTurns.get(turnId) ?? { provider: failure.provider, category: failure.category }, message);
|
||||
},
|
||||
/** Diagnostics only: the failed turn that `forTerminal` did not classify. */
|
||||
unclassifiedTurnFailure(turnId: string | null | undefined, terminal: PrpTerminalState) {
|
||||
|
||||
@@ -149,6 +149,8 @@ vi.mock("node:fs", async (importOriginal) => {
|
||||
return { ...actual, readFileSync: vi.fn(actual.readFileSync) };
|
||||
});
|
||||
|
||||
const distributions = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8"));
|
||||
|
||||
const usageRecorder = vi.hoisted(() => ({
|
||||
create: vi.fn<typeof import("../usage-receipts.js")["createRunUsageRecorder"]>(),
|
||||
capture: vi.fn<(receipt: AdapterUsageCheckpoint) => Promise<AdapterUsageCheckpoint>>(),
|
||||
@@ -249,6 +251,14 @@ const durableRunnerState = (
|
||||
lifecycle,
|
||||
});
|
||||
|
||||
const antigravityPack = vi.hoisted(() => ({ released: false, linuxClosure: "b".repeat(64) }));
|
||||
vi.mock("./remote-provider-pack.js", async importOriginal => {
|
||||
const original = await importOriginal<typeof import("./remote-provider-pack.js")>();
|
||||
// The Linux patched closure is pinned by the image agent; this fixture stands in for it.
|
||||
return { ...original, ANTIGRAVITY_PATCHED_CLOSURE_SHA256: new Proxy({}, {
|
||||
get: (_target, key) => key === "linux-x64" ? antigravityPack.linuxClosure : original.ANTIGRAVITY_PATCHED_CLOSURE_SHA256[key as string],
|
||||
}) };
|
||||
});
|
||||
const state = vi.hoisted(() => ({
|
||||
localRuntimeApiUrl: vi.fn(() => "http://127.0.0.1:43219"),
|
||||
createAssignedMcpTools: vi.fn(),
|
||||
@@ -332,8 +342,14 @@ vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => {
|
||||
const original = await importOriginal<
|
||||
typeof import("../../vendor/paperclip-runner/index.js")
|
||||
>();
|
||||
// Antigravity's release state is stubbed per test (pending today, qualified after the flip).
|
||||
const { qualificationStatus: _antigravityPending, ...antigravityReleased } = original.QUALIFIED_ACPX_PROFILES.antigravity;
|
||||
const profiles = { ...original.QUALIFIED_ACPX_PROFILES };
|
||||
Object.defineProperty(profiles, "antigravity", { enumerable: true,
|
||||
get: () => antigravityPack.released ? antigravityReleased : original.QUALIFIED_ACPX_PROFILES.antigravity });
|
||||
return {
|
||||
...original,
|
||||
QUALIFIED_ACPX_PROFILES: profiles,
|
||||
bundledRemoteProviderPackManifestPath: vi.fn((moduleUrl?: string, target?: "linux-x64" | "linux-arm64") => state.bundledPackManifestPath ?? original.bundledRemoteProviderPackManifestPath(moduleUrl, target)),
|
||||
bundledRemoteRunnerBinary: () => state.bundledRunnerBinary ?? original.bundledRemoteRunnerBinary(),
|
||||
createNativeSessionBackend: state.createBackend,
|
||||
@@ -3711,6 +3727,62 @@ describe("remote provider pack manifest", () => {
|
||||
await writeFile(join(root, kimiPath, "runtime"), "substitute Kimi runtime");
|
||||
expect(() => readRemoteProviderPackManifest(root)).toThrow("candidate asset tree digest mismatch");
|
||||
await writeFile(join(root, kimiPath, "runtime"), "pinned Kimi runtime");
|
||||
// Google Antigravity image pack contract: the patched Linux closure under
|
||||
// candidateProviders while pending, under providers after the flip, never both.
|
||||
const antigravityPath = "provider-assets/antigravity/linux-x64";
|
||||
await mkdir(join(root, antigravityPath), { recursive: true });
|
||||
await writeFile(join(root, antigravityPath, "agy_acp_server.par"), "patched Antigravity runtime");
|
||||
const antigravity = { version: QUALIFIED_ACPX_PROFILES.antigravity.agentServerVersion,
|
||||
profileDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest,
|
||||
closureDigest: `sha256:${antigravityPack.linuxClosure}`, qualification: "pending", path: antigravityPath,
|
||||
sha256: sha256DirectoryTree(join(root, antigravityPath)) };
|
||||
try {
|
||||
const inventories = payload as unknown as Record<"providers" | "candidateProviders", Record<string, unknown>>;
|
||||
for (const released of [false, true]) {
|
||||
antigravityPack.released = released;
|
||||
antigravity.qualification = released ? "qualified" : "pending";
|
||||
const [admitted, refused] = released ? ["providers", "candidateProviders"] as const : ["candidateProviders", "providers"] as const;
|
||||
Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} });
|
||||
Object.assign(inventories[admitted], { antigravity });
|
||||
await writeKimiManifest();
|
||||
expect(readRemoteProviderPackManifest(root).payload[admitted]?.antigravity).toEqual(antigravity);
|
||||
expect(readBundledRemoteProviderPackManifest(manifestPath).payload[admitted]?.antigravity?.qualification)
|
||||
.toBe(released ? "qualified" : "pending");
|
||||
Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} });
|
||||
Object.assign(inventories[refused], { antigravity: { ...antigravity, qualification: "pending" } });
|
||||
await writeKimiManifest();
|
||||
expect(() => readRemoteProviderPackManifest(root)).toThrow("runner_remote_provider_artifact_incompatible: Antigravity is listed under the wrong pack inventory");
|
||||
Object.assign(payload, { providers: { cursor, kimi, antigravity }, candidateProviders: { antigravity } });
|
||||
await writeKimiManifest();
|
||||
expect(() => readRemoteProviderPackManifest(root)).toThrow("runner_remote_provider_artifact_incompatible");
|
||||
for (const closureDigest of [`sha256:${distributions.platforms["darwin-arm64"].vendorClosureSha256}`,
|
||||
`sha256:${distributions.platforms["darwin-arm64"].closureSha256}`, digest("other-closure")]) {
|
||||
Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} });
|
||||
Object.assign(inventories[admitted], { antigravity: { ...antigravity, closureDigest } });
|
||||
await writeKimiManifest();
|
||||
expect(() => readRemoteProviderPackManifest(root)).toThrow("runner_remote_provider_artifact_incompatible: Antigravity closure is not this release's patched closure");
|
||||
}
|
||||
Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} });
|
||||
Object.assign(inventories[admitted], { antigravity: { ...antigravity, version: "0.0.1" } });
|
||||
await writeKimiManifest();
|
||||
expect(() => readRemoteProviderPackManifest(root)).toThrow("runner_remote_provider_artifact_incompatible: Antigravity profile does not match this release");
|
||||
Object.assign(payload, { providers: { cursor, kimi }, candidateProviders: {} });
|
||||
Object.assign(inventories[admitted], { antigravity });
|
||||
await writeKimiManifest();
|
||||
await writeFile(join(root, antigravityPath, "agy_acp_server.par"), "vendor Antigravity runtime");
|
||||
expect(() => readRemoteProviderPackManifest(root)).toThrow("runner_remote_provider_artifact_incompatible: candidate asset tree digest mismatch");
|
||||
await writeFile(join(root, antigravityPath, "agy_acp_server.par"), "patched Antigravity runtime");
|
||||
}
|
||||
// Until the Linux runtime is pinned, no Antigravity image pack verifies.
|
||||
antigravityPack.linuxClosure = "";
|
||||
await writeKimiManifest();
|
||||
expect(() => readRemoteProviderPackManifest(root)).toThrow("Antigravity closure is not this release's patched closure");
|
||||
} finally {
|
||||
antigravityPack.released = false; antigravityPack.linuxClosure = "b".repeat(64);
|
||||
Object.assign(payload, { providers: { cursor, kimi } });
|
||||
Reflect.deleteProperty(payload, "candidateProviders");
|
||||
await writeKimiManifest();
|
||||
}
|
||||
const threeCandidates = { cursor,
|
||||
pi: { ...kimi, version: "1.0.0", qualification: "qualified", path: "provider-assets/pi/linux-x64" },
|
||||
copilot: { ...kimi, qualification: "pending", version: QUALIFIED_ACPX_PROFILES.copilot.agentServerVersion,
|
||||
@@ -3725,7 +3797,7 @@ describe("remote provider pack manifest", () => {
|
||||
Object.assign(payload, { candidateProviders: threeCandidates });
|
||||
await writeKimiManifest();
|
||||
expect(Object.keys(readRemoteProviderPackManifest(root).payload.candidateProviders!)).toHaveLength(3);
|
||||
Object.assign(payload, { candidateProviders: { ...threeCandidates, unknown: kimi } });
|
||||
Object.assign(payload, { candidateProviders: { ...threeCandidates, unknown: kimi, other: kimi } });
|
||||
await writeKimiManifest();
|
||||
expect(() => readBundledRemoteProviderPackManifest(manifestPath)).toThrow("invalid candidate inventory");
|
||||
Object.assign(payload, { candidateProviders: { unknown: kimi } });
|
||||
|
||||
@@ -112,6 +112,8 @@ import { activeIssueInteractionCondition } from "../issue-question-context.js";
|
||||
import { resolveAcpxQualification, resolveAntigravityCandidateAdmission, resolveKimiCandidateAdmission } from "./acpx-qualification.js";
|
||||
import { readLocalAiCredentialFile } from "../local-ai-credential-file.js";
|
||||
import { prepareGrokRunnerCredentials } from "./grok-runner-credentials.js";
|
||||
import { AntigravityConnectionConfigurationError } from "./antigravity-connection-policy.js";
|
||||
import { antigravityCandidateTarget, antigravityForcesSameSessionRecovery, antigravityReleasePending, antigravityUsesRunScopedState, assertAntigravityExecutionAdmissible } from "./antigravity-release.js";
|
||||
import { bindAntigravityCredentialTurn, bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js";
|
||||
import { copyBackGrokAuth } from "@paperclipai/adapter-grok-local/server";
|
||||
|
||||
@@ -141,7 +143,7 @@ import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server";
|
||||
import { nativeCompletionFeedback } from "./native-completion-feedback.js";
|
||||
import { hasAcknowledgedNativeLifecycleStopIntent, hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js";
|
||||
import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js";
|
||||
import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
|
||||
import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256, prepareVerifiedRemoteProviderPack, remoteProviderPackEntryRefusal, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
|
||||
import { uploadVerifiedProviderPack } from "./provider-pack-upload.js";
|
||||
import { selectRemotePiCompanion } from "./remote-pi-companion.js";
|
||||
import { scheduledResumeContinuationAllowed } from "./scheduled-resume-continuation.js";
|
||||
@@ -2735,9 +2737,10 @@ export async function noLocalRunnerProcessForRun(runId: string): Promise<boolean
|
||||
}
|
||||
|
||||
export function scopedRunnerdStateRoot(execution: NativeExecutionInput): string {
|
||||
// Antigravity's first release owns a fresh per-turn daemon. Its native
|
||||
// The pending Antigravity candidate owns a fresh per-turn daemon. Its native
|
||||
// conversation is stored separately and may load under each new run's grant.
|
||||
const scope = execution.provider.kind === "acpx" && execution.provider.agent === "antigravity"
|
||||
// A qualified release keeps the ordinary per-session scope.
|
||||
const scope = antigravityUsesRunScopedState(execution)
|
||||
? JSON.stringify([nativeSessionScopeKey(execution), execution.binding.runId])
|
||||
: nativeSessionScopeKey(execution);
|
||||
return resolve(
|
||||
@@ -7508,7 +7511,7 @@ function runnerdStateRoot(execution: NativeExecutionInput): string {
|
||||
}
|
||||
return scoped;
|
||||
}
|
||||
if (execution.provider.kind === "acpx" && execution.provider.agent === "antigravity") return scoped;
|
||||
if (antigravityUsesRunScopedState(execution)) return scoped;
|
||||
for (const legacy of [
|
||||
legacyCompanyRunnerdStateRoot(execution),
|
||||
legacyRunnerdStateRoot(execution),
|
||||
@@ -9316,6 +9319,9 @@ function classifyNativeSessionFailure(
|
||||
if (findNativePredecessorRetirementUnproven(error)) return NATIVE_PREDECESSOR_RETIREMENT_UNPROVEN_CODE;
|
||||
if (findNativeFailedBeforeProviderTurn(error)) return NATIVE_FAILED_BEFORE_PROVIDER_TURN_CODE;
|
||||
if (error instanceof NativePermissionDeclinedError) return "native_permission_declined";
|
||||
// A saved connection its target cannot use: no provider work began, and a
|
||||
// retry would meet the same configuration.
|
||||
if (error instanceof AntigravityConnectionConfigurationError) return NATIVE_PROVIDER_STARTUP_REJECTED;
|
||||
if (error instanceof NativeGovernedWaitSettlementPendingError) return "native_governed_wait_settlement_pending";
|
||||
if (error instanceof NativeProviderStateIncompatibleError) return NATIVE_PROVIDER_STATE_INCOMPATIBLE;
|
||||
if (error instanceof NativeProviderSideEffectPendingError) return NATIVE_PROVIDER_SIDE_EFFECT_PENDING;
|
||||
@@ -11028,17 +11034,10 @@ async function executePaperclipNativeSessionAttempt(
|
||||
const attemptDiagnosticLeases: NativeDiagnosticLease[] = [];
|
||||
const ownRunDiagnosticLease = ownDiagnosticLease;
|
||||
ownDiagnosticLease = lease => { attemptDiagnosticLeases.push(lease); ownRunDiagnosticLease?.(lease); };
|
||||
if (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "antigravity") {
|
||||
const candidate = resolveAntigravityCandidateAdmission({
|
||||
companyId: input.execution.binding.companyId, model: input.execution.provider.model,
|
||||
}, process.env);
|
||||
if (!candidate || !input.useRunnerd || input.backend || input.restartRecovery
|
||||
|| input.runnerExecutionTarget?.kind === "remote"
|
||||
|| input.execution.session.lifecyclePolicy.mode !== "per_turn"
|
||||
|| ("homeMode" in input.execution && input.execution.homeMode === "preconfigured")) {
|
||||
throw new Error("paperclip_runner_antigravity_candidate_ineligible: exact local per-turn candidate admission is required");
|
||||
}
|
||||
}
|
||||
assertAntigravityExecutionAdmissible({
|
||||
execution: input.execution, useRunnerd: input.useRunnerd, backend: input.backend,
|
||||
restartRecovery: input.restartRecovery, remoteTarget: input.runnerExecutionTarget?.kind === "remote",
|
||||
});
|
||||
if (input.execution.provider.kind === "acpx" && input.execution.provider.agent === "kimi"
|
||||
&& QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending") {
|
||||
const target = input.runnerExecutionTarget?.kind === "remote"
|
||||
@@ -11729,7 +11728,11 @@ async function executePaperclipNativeSessionAttempt(
|
||||
let firstTokenRecorded = false;
|
||||
const observeDeliverableText = createNativeDeliverableTextObservation();
|
||||
let providerUsageLimitObserved = false;
|
||||
const providerFailureObservation = createNativeProviderFailureObservation(input.execution.provider);
|
||||
// Antigravity runs on a Gemini API key exactly when one is bound; otherwise
|
||||
// on a Google sign-in (the same rule its credential preparation applies).
|
||||
const providerFailureObservation = createNativeProviderFailureObservation(input.execution.provider,
|
||||
input.execution.provider.kind === "acpx" && input.execution.provider.agent === "antigravity"
|
||||
? { antigravityRoute: input.runnerEnvironment?.GEMINI_API_KEY?.trim() ? "api_key" : "subscription" } : {});
|
||||
let turnCompletedAtMs: number | null = null;
|
||||
let runnerSessionStartupScope: NativeRunSpanScope | null = null;
|
||||
let agentTurnScope: NativeRunSpanScope | null = null;
|
||||
@@ -14403,8 +14406,10 @@ const REMOTE_PROVIDER_PACK_ARTIFACT_PATHS = {
|
||||
opencodeProxy: "dist/cli/opencode-app-server-proxy.cjs",
|
||||
acpxSidecar: "dist/cli/acpx-runtime-sidecar.cjs",
|
||||
} as const;
|
||||
const REMOTE_PROVIDER_PACK_PROVIDERS = ["pi", "cursor", "copilot", ...(QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus !== "pending" ? ["kimi"] as const : [])] as const;
|
||||
const REMOTE_PROVIDER_PACK_CANDIDATES = ["pi", "cursor", "copilot", ...(QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending" ? ["kimi"] as const : [])] as const;
|
||||
// Antigravity may appear in either inventory; its release state, read at
|
||||
// verification time, admits exactly one (antigravityProviderPackEntryRefusal).
|
||||
const REMOTE_PROVIDER_PACK_PROVIDERS = ["pi", "cursor", "copilot", ...(QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus !== "pending" ? ["kimi"] as const : []), "antigravity"] as const;
|
||||
const REMOTE_PROVIDER_PACK_CANDIDATES = ["pi", "cursor", "copilot", ...(QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending" ? ["kimi"] as const : []), "antigravity"] as const;
|
||||
|
||||
type RemoteProviderPackManifest = {
|
||||
schema: typeof REMOTE_PROVIDER_PACK_SCHEMA;
|
||||
@@ -14644,52 +14649,15 @@ function* providerPackIdentityChecks(
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: invalid candidate inventory");
|
||||
}
|
||||
for (const [provider, candidate] of Object.entries(candidates)) {
|
||||
const expectedPath = `provider-assets/${provider}/${payload.target.platform}-${payload.target.architecture}`;
|
||||
if (!allowedProviders.includes(provider) || !candidate
|
||||
|| Object.keys(candidate).some(key => !["version", "profileDigest", "closureDigest", "qualification", "path", "sha256"].includes(key))
|
||||
|| candidate.qualification !== (["pi", "cursor"].includes(provider) || inventory === "providers" && (provider === "copilot" || provider === "kimi" && QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus !== "pending") ? "qualified" : "pending") || candidate.path !== expectedPath
|
||||
|| typeof candidate.version !== "string" || !candidate.version || candidate.version.length > 120
|
||||
|| !/^sha256:[a-f0-9]{64}$/.test(candidate.profileDigest)
|
||||
|| !/^sha256:[a-f0-9]{64}$/.test(candidate.closureDigest)
|
||||
|| !/^sha256:[a-f0-9]{64}$/.test(candidate.sha256)) {
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: invalid candidate identity");
|
||||
}
|
||||
const refusal = remoteProviderPackEntryRefusal({ provider, inventory, allowedProviders, target: payload.target, entry: candidate,
|
||||
listed: { providers: Boolean((payload.providers as Record<string, unknown> | undefined)?.[provider]),
|
||||
candidateProviders: Boolean((payload.candidateProviders as Record<string, unknown> | undefined)?.[provider]) },
|
||||
release: {
|
||||
profiles: QUALIFIED_ACPX_PROFILES, cursorClosures: CURSOR_DISTRIBUTION_PINS, kimiLinuxX64Closure: KIMI_DISTRIBUTION_CLOSURE_SHA256["linux-x64"],
|
||||
antigravityReleasePending: antigravityReleasePending(), antigravityPatchedClosures: ANTIGRAVITY_PATCHED_CLOSURE_SHA256,
|
||||
} });
|
||||
if (refusal) throw new Error(`runner_remote_provider_artifact_incompatible: ${refusal}`);
|
||||
const candidatePath = providerPackRelativePath(candidate.path, "candidate assets");
|
||||
if (provider === "cursor") {
|
||||
const target = `${payload.target.platform}-${payload.target.architecture}`;
|
||||
const distribution = Object.hasOwn(CURSOR_DISTRIBUTION_PINS, target)
|
||||
? CURSOR_DISTRIBUTION_PINS[target as keyof typeof CURSOR_DISTRIBUTION_PINS] : undefined;
|
||||
if (!distribution || candidate.version !== QUALIFIED_ACPX_PROFILES.cursor.agentServerVersion
|
||||
|| candidate.profileDigest !== QUALIFIED_ACPX_PROFILES.cursor.commandDigest
|
||||
|| candidate.closureDigest !== `sha256:${distribution.closureSha256}`) {
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: Cursor profile or closure does not match this release");
|
||||
}
|
||||
}
|
||||
if (provider === "copilot") {
|
||||
const closurePins = {
|
||||
"darwin-arm64": "362f2663e967fb9e34a814bac4619cbf89e6b23069c4051ab1f2f686852d0a32",
|
||||
"darwin-x64": "c08b7c3dd4e7bcf9a3e16ec6eba29cfa10308e865d196c5f120a3a15f6b3116a",
|
||||
"linux-x64": "a3d8f4367cfa1694d79e3f8b7930b6fbfe42a229c272b375b11951d631db8d07"
|
||||
} as const;
|
||||
const target = `${payload.target.platform}-${payload.target.architecture}`;
|
||||
const closure = Object.hasOwn(closurePins, target) ? closurePins[target as keyof typeof closurePins] : undefined;
|
||||
if (!closure || (payload.providers?.copilot && payload.candidateProviders?.copilot)
|
||||
|| candidate.version !== QUALIFIED_ACPX_PROFILES.copilot.agentServerVersion
|
||||
|| candidate.profileDigest !== QUALIFIED_ACPX_PROFILES.copilot.commandDigest
|
||||
|| candidate.closureDigest !== `sha256:${closure}`) {
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: Copilot profile or closure does not match this release");
|
||||
}
|
||||
}
|
||||
if (provider === "kimi") {
|
||||
if (inventory !== (QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending" ? "candidateProviders" : "providers")
|
||||
|| payload[QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending" ? "providers" : "candidateProviders"]?.kimi
|
||||
|| payload.target.platform !== "linux" || payload.target.architecture !== "x64"
|
||||
|| candidate.version !== QUALIFIED_ACPX_PROFILES.kimi.agentServerVersion
|
||||
|| candidate.profileDigest !== QUALIFIED_ACPX_PROFILES.kimi.commandDigest
|
||||
|| candidate.closureDigest !== `sha256:${KIMI_DISTRIBUTION_CLOSURE_SHA256["linux-x64"]}`) {
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: Kimi profile or closure does not match this release");
|
||||
}
|
||||
}
|
||||
if (verifyControllerFiles && (yield { kind: "tree", path: resolve(packRoot, candidatePath) }) !== candidate.sha256) {
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: candidate asset tree digest mismatch");
|
||||
}
|
||||
@@ -14918,6 +14886,14 @@ export async function stageRemoteRunnerDirectory(input: {
|
||||
}
|
||||
}
|
||||
|
||||
/** The exact remote machine a pack sits on, when the target names one. */
|
||||
export function remoteProviderPackSeal(target: Extract<AdapterExecutionTarget, { kind: "remote" }>): { targetKey: string } | null {
|
||||
const sandboxLease = "sandboxLeaseAcquisition" in target ? target.sandboxLeaseAcquisition?.providerLeaseId : undefined;
|
||||
const lease = sandboxLease ?? target.leaseId;
|
||||
if (!lease || !target.environmentId) return null;
|
||||
return { targetKey: `${target.transport}:${target.environmentId}:${lease}` };
|
||||
}
|
||||
|
||||
/** The normal remote pack installer, without run/session/DB authority. Both
|
||||
* native execution and environment Test use the same admitted manifest and
|
||||
* complete archive/directory verification before a provider is invoked. */
|
||||
@@ -14938,9 +14914,11 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
let activeRemoteProviderPackRoot: string | null = null;
|
||||
let preinstalledProviderPackRoots: string[] = [];
|
||||
let selectedProviderPackManifest = expectedProviderPackManifest;
|
||||
const seal = remoteProviderPackSeal(remoteTarget);
|
||||
const verifyRemoteProviderPack = (packRoot: string, acceptProvenance = false) =>
|
||||
verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, cwd: remoteTarget.remoteCwd, packRoot,
|
||||
manifest: expectedProviderPackManifest, acceptProvenance: acceptProvenance && input.acceptProvenanceDifferences === true });
|
||||
manifest: expectedProviderPackManifest, acceptProvenance: acceptProvenance && input.acceptProvenanceDifferences === true,
|
||||
...(seal ? { seal } : {}) });
|
||||
const discoverPreinstalledProviderPack = async () => {
|
||||
if (!remoteTarget || !remoteCommandRunner) return [];
|
||||
const result = await remoteCommandRunner.execute({
|
||||
@@ -17415,8 +17393,9 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
if (providerPackVerified && packRoot === activeRemoteProviderPackRoot) return;
|
||||
if (!remoteTarget || !remoteCommandRunner || !expectedProviderPackManifest)
|
||||
return;
|
||||
const seal = remoteProviderPackSeal(remoteTarget);
|
||||
await verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner,
|
||||
cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest });
|
||||
cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest, ...(seal ? { seal } : {}) });
|
||||
providerPackVerified = true;
|
||||
};
|
||||
|
||||
@@ -18862,7 +18841,9 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
? undefined
|
||||
: resolveAcpxQualification(input.execution.provider, process.env),
|
||||
acpxCandidateAdmission: input.execution.provider.agent === "antigravity"
|
||||
? resolveAntigravityCandidateAdmission({ companyId: input.execution.binding.companyId, model: input.execution.provider.model }, process.env)
|
||||
// A released profile carries no candidate grant.
|
||||
? antigravityReleasePending() ? resolveAntigravityCandidateAdmission({ companyId: input.execution.binding.companyId, model: input.execution.provider.model,
|
||||
target: antigravityCandidateTarget(Boolean(remoteTarget)) }, process.env) : undefined
|
||||
: input.execution.provider.agent === "kimi" && QUALIFIED_ACPX_PROFILES.kimi.qualificationStatus === "pending"
|
||||
? resolveKimiCandidateAdmission({ companyId: input.execution.binding.companyId, model: input.execution.provider.model,
|
||||
target: remoteTarget ? { platform: "linux", architecture: "x64" } : { platform: process.platform, architecture: process.arch } }, process.env)
|
||||
@@ -19013,7 +18994,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
recoveryContext?.persistedSession?.activeTurnId ?? null,
|
||||
resumeProviderSession: recoveryContext?.persistedSession,
|
||||
providerRecoveryPolicy:
|
||||
input.execution.provider.kind === "acpx" && input.execution.provider.agent === "antigravity"
|
||||
antigravityForcesSameSessionRecovery(input.execution.provider)
|
||||
? "same_session_only"
|
||||
: recoveryContext?.providerRecoveryPolicy ??
|
||||
(input.execution.provider.kind === "acpx" &&
|
||||
|
||||
@@ -368,6 +368,44 @@ describe("a session saved by the previous Claude or Codex ACPX runtime", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("a Google Antigravity session saved by the pending candidate", () => {
|
||||
// The candidate's saved provider binds its pending profile. After the flip,
|
||||
// the next run carries the task into a fresh provider session in the same
|
||||
// workspace (the automatic replacement), never a Retry of the old session.
|
||||
const antigravityExecution = (runId: string) => buildNativeExecutionInput({
|
||||
companyId, runId,
|
||||
issue: { id: issueId, identifier: "DOT-2", title: "Test", description: null, workMode: "standard" },
|
||||
taskPrompt: "Only the current turn", agentId,
|
||||
workspace: { id: runId, cwd: "/workspace", repoUrl: null, repoRef: null, branchName: null },
|
||||
normalizedSessionId, provider: "acpx", acpxAgent: "antigravity", model: "gemini-3.8-flash-low",
|
||||
acpxPermissionMode: "approve-all", completionContract: execution(runId).completionContract,
|
||||
runtimeContext: nativeRuntimeContextFixture(),
|
||||
});
|
||||
|
||||
it("starts the next run on the qualified release in a fresh provider session in the same workspace", () => {
|
||||
const saved = antigravityExecution(previousRunId);
|
||||
const source = { ...previousRun(), runnerProfileJson: { ...previousRun().runnerProfileJson, nativeExecutionInput: saved } };
|
||||
// The flip bumps the profile version (the snapshot carries no qualification status).
|
||||
const released = (runId: string) => {
|
||||
const built = antigravityExecution(runId);
|
||||
(built.provider as { profile: { agentProfileVersion: number } }).profile.agentProfileVersion += 1;
|
||||
return built;
|
||||
};
|
||||
expect(rebindNativeSessionCheckpoint({ previousRun: source, currentExecution: antigravityExecution(currentRunId) })).not.toBeNull();
|
||||
expect(rebindNativeSessionCheckpoint({ previousRun: source, currentExecution: released(currentRunId) })).toBeNull();
|
||||
const result = buildNativeExecutionWithCheckpoint({ previousRun: source, normalizedSessionId,
|
||||
buildExecution: ({ normalizedSessionId: sessionId, resumedSession }) => {
|
||||
const built = released(currentRunId);
|
||||
built.session.normalizedSessionId = sessionId;
|
||||
built.task.prompt = resumedSession ? "wake delta" : "original goal and complete handoff";
|
||||
return built;
|
||||
} });
|
||||
expect(result.checkpoint).toBeNull();
|
||||
expect(result.execution.task.prompt).toContain("complete handoff");
|
||||
expect(result.execution.workspace).toEqual(released(currentRunId).workspace);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a source whose provider state was not saved after its result was accepted", () => {
|
||||
const unsaved = { [NATIVE_PROVIDER_STATE_UNSAVED_KEY]: { code: NATIVE_PROVIDER_STATE_INCOMPATIBLE,
|
||||
reason: "harness_backup_not_saved", recordedAt: "2026-11-11T00:00:00.000Z" } };
|
||||
|
||||
@@ -22,6 +22,13 @@ export function supportsNativeWarmFiles(profile: WarmProviderSelection): boolean
|
||||
(profile.backend === "acpx_runtime" && profile.acpxAgent === "copilot");
|
||||
}
|
||||
|
||||
/** Google Antigravity runs turn by turn with any credential, as Kimi does with a
|
||||
* managed key. A warm owner needs its own proof that a credential change retires
|
||||
* it and refreshes its native home on attach, so no choice selects warm yet. */
|
||||
export function requiresPerTurnNativeSession(profile: WarmProviderSelection): boolean {
|
||||
return profile.backend === "acpx_runtime" && profile.acpxAgent === "antigravity";
|
||||
}
|
||||
|
||||
/** Copilot carries a token in its fenced session environment, not a temporary auth file.
|
||||
* Credential generation changes still retire the exact warm owner before attachment. */
|
||||
export function supportsManagedNativeWarmSession(
|
||||
|
||||
@@ -455,7 +455,11 @@ export function claudeRunnerUnsupportedSettings(config: Record<string, unknown>)
|
||||
*/
|
||||
export function resolvePaperclipRunnerProviderProfile(
|
||||
adapterConfig: unknown,
|
||||
context: { companyId?: string } = {},
|
||||
context: {
|
||||
companyId?: string;
|
||||
/** The execution target's platform, when known: a pending Antigravity grant must name it. */
|
||||
candidateTarget?: { platform: string; architecture: string };
|
||||
} = {},
|
||||
): PaperclipRunnerProviderProfile {
|
||||
const config = asRecord(adapterConfig);
|
||||
const candidate = config.provider ?? "codex";
|
||||
@@ -608,7 +612,7 @@ export function resolvePaperclipRunnerProviderProfile(
|
||||
if (!model) throw new PaperclipRunnerProviderProfileError("paperclip_runner_acpx_model_required", `${pendingAcpxProfile.label} requires an explicit model ID; there is no default model.`);
|
||||
if (pendingAcpxProfile.value === "antigravity") {
|
||||
try {
|
||||
if (resolveAntigravityCandidateAdmission({ companyId: context.companyId, model }, process.env)) {
|
||||
if (resolveAntigravityCandidateAdmission({ companyId: context.companyId, model, target: context.candidateTarget }, process.env)) {
|
||||
return { provider: "acpx", backend: "acpx_runtime", model, acpxAgent: "antigravity" };
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { readFileSync } from "node:fs";
|
||||
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { canonicalProviderPackJson, verifyRemoteProviderPack, type ProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
import { canonicalProviderPackJson, clearSealedProviderPacksForTest, PROVIDER_PACK_IDENTITY_FUNCTION, verifyRemoteProviderPack, type ProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
|
||||
const sha = (text: string) => `sha256:${createHash("sha256").update(text).digest("hex")}`;
|
||||
const manifest = (revision: string): ProviderPackIdentity => {
|
||||
@@ -76,6 +76,11 @@ describe("installed provider pack compatibility", () => {
|
||||
await expect(verifyRemoteProviderPack(input)).rejects.toMatchObject({
|
||||
message: expect.stringContaining("manifest mismatch"), failureCheck: "manifest_mismatch:runnerSourceRevision" });
|
||||
expect(execute).toHaveBeenCalledOnce();
|
||||
// The sealing variant of the verifier runs the same checks in a real Node process.
|
||||
await expect(verifyRemoteProviderPack({ ...input, seal: { targetKey: "sandbox:env:real" } })).rejects.toMatchObject({
|
||||
failureCheck: "manifest_mismatch:runnerSourceRevision" });
|
||||
await expect(verifyRemoteProviderPack({ ...input, manifest: installed, seal: { targetKey: "sandbox:env:real" } })).rejects.toMatchObject({
|
||||
failureCheck: "artifact_digest:nodeCommand" });
|
||||
await expect(verifyRemoteProviderPack({ ...input, manifest: installed })).rejects.toMatchObject({
|
||||
message: expect.stringContaining("nodeCommand digest mismatch"), failureCheck: "artifact_digest:nodeCommand" });
|
||||
await rm(join(root, "provider-pack.json"));
|
||||
@@ -212,6 +217,71 @@ describe("installed provider pack compatibility", () => {
|
||||
await expect(verifyRemoteProviderPack({ ...input, provider: { kind: "acpx", agent: "codex" } })).rejects.toThrow("profile is incompatible");
|
||||
});
|
||||
|
||||
describe("sealed reuse on the same sandbox", () => {
|
||||
const identityOf = async (root: string) => {
|
||||
const { stdout } = await promisify(execFile)(process.execPath, ["-e",
|
||||
`${PROVIDER_PACK_IDENTITY_FUNCTION};process.stdout.write(packIdentity(process.argv[1]))`, root]);
|
||||
return stdout;
|
||||
};
|
||||
|
||||
it("changes the identity for any same-size rewrite, even with its mtime restored", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "pack-identity-"));
|
||||
try {
|
||||
await mkdir(join(root, "dist"));
|
||||
await writeFile(join(root, "dist", "file.js"), "original");
|
||||
await symlink(join(root, "dist", "file.js"), join(root, "link.js"));
|
||||
const sealed = await identityOf(root);
|
||||
expect(sealed).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(await identityOf(root)).toBe(sealed);
|
||||
const before = await stat(join(root, "dist", "file.js"));
|
||||
await new Promise(resolve => setTimeout(resolve, 20));
|
||||
await writeFile(join(root, "dist", "file.js"), "tampered");
|
||||
await utimes(join(root, "dist", "file.js"), before.atime, before.mtime);
|
||||
expect(await identityOf(root)).not.toBe(sealed);
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
it("re-checks only the identity on a sealed sandbox and fully re-verifies after any change", async () => {
|
||||
clearSealedProviderPacksForTest();
|
||||
const expected = manifest("b");
|
||||
let identity = "a".repeat(64);
|
||||
const execute = vi.fn(async (request: Parameters<CommandManagedRuntimeRunner["execute"]>[0]) => {
|
||||
const script = String(request.args?.[1] ?? "");
|
||||
const stdout = request.args?.[0] === "--version" ? `${expected.payload.pins.opencode}\n`
|
||||
: script.includes("paperclip-pack-check") ? `verified\npaperclip-pack-identity=${identity}\n`
|
||||
: `\npaperclip-pack-identity=${identity}\n`;
|
||||
return { exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "", stdout };
|
||||
});
|
||||
const kinds = () => execute.mock.calls.map(([request]) => request.args?.[0] === "--version" ? "version"
|
||||
: String(request.args?.[1]).includes("paperclip-pack-check") ? "full" : "identity");
|
||||
const input = { runner: { execute }, cwd: "/workspace", packRoot: "/workspace/provider-pack", manifest: expected,
|
||||
seal: { targetKey: "sandbox:env-1:sandbox-1" } };
|
||||
await expect(verifyRemoteProviderPack(input)).resolves.toEqual(expected);
|
||||
expect(kinds()).toEqual(["full", "version"]);
|
||||
execute.mockClear();
|
||||
await expect(verifyRemoteProviderPack(input)).resolves.toEqual(expected);
|
||||
expect(kinds()).toEqual(["identity"]);
|
||||
// Another sandbox, or no sandbox identity, never reuses the seal.
|
||||
execute.mockClear();
|
||||
await verifyRemoteProviderPack({ ...input, seal: { targetKey: "sandbox:env-1:sandbox-2" } });
|
||||
await verifyRemoteProviderPack({ ...input, seal: undefined });
|
||||
expect(kinds()).toEqual(["full", "version", "full", "version"]);
|
||||
// A changed identity falls back to the complete verification.
|
||||
execute.mockClear();
|
||||
identity = "b".repeat(64);
|
||||
await expect(verifyRemoteProviderPack(input)).resolves.toEqual(expected);
|
||||
expect(kinds()).toEqual(["identity", "full", "version"]);
|
||||
// A pack that changed while it was hashed reports no identity and is not sealed.
|
||||
execute.mockClear();
|
||||
clearSealedProviderPacksForTest();
|
||||
execute.mockImplementation(async (request) => ({ exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stderr: "",
|
||||
stdout: request.args?.[0] === "--version" ? `${expected.payload.pins.opencode}\n` : "verified\n" }));
|
||||
await verifyRemoteProviderPack(input);
|
||||
await verifyRemoteProviderPack(input);
|
||||
expect(kinds()).toEqual(["full", "version", "full", "version"]);
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects the published Grok pack from before native effort admission", async () => {
|
||||
const profiles = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/acpx-profiles.json", import.meta.url), "utf8"));
|
||||
const current = manifest("b"), installed = manifest("a");
|
||||
|
||||
@@ -105,7 +105,36 @@ function compatibleInstallation<T extends ProviderPackIdentity>(
|
||||
return structuredClone(actual);
|
||||
}
|
||||
|
||||
export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false, acceptProvenance = false }: {
|
||||
/**
|
||||
* A Node expression defining `packIdentity(root)`: a digest of the kernel
|
||||
* identity of every entry under the pack's real root (path, mode, device,
|
||||
* inode, size, mtime, ctime, link count, owner; a symlink's text and its
|
||||
* target's identity), bound to the machine's boot. Content cannot change
|
||||
* without moving a ctime, and no unprivileged process can set a ctime back,
|
||||
* so an unchanged identity proves bytes unchanged since they were hashed.
|
||||
*/
|
||||
export const PROVIDER_PACK_IDENTITY_FUNCTION = [
|
||||
"const packIdentity=(root)=>{const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');const h=crypto.createHash('sha256');let boot='none';try{boot=fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim()}catch{}",
|
||||
"const real=fs.realpathSync(root);h.update('boot\\0'+boot+'\\nroot\\0'+real+'\\n');const id=(s)=>[s.mode,s.dev,s.ino,s.size,s.mtimeNs,s.ctimeNs,s.nlink,s.uid].join('\\0');h.update('.\\0'+id(fs.lstatSync(real,{bigint:true}))+'\\n');",
|
||||
"const visit=(d,prefix)=>{for(const name of fs.readdirSync(d).sort()){const a=path.join(d,name),r=prefix?prefix+'/'+name:name,s=fs.lstatSync(a,{bigint:true});h.update(r+'\\0'+id(s)+'\\n');if(s.isSymbolicLink()){let t='missing';try{t=id(fs.statSync(a,{bigint:true}))}catch{}h.update('link\\0'+fs.readlinkSync(a)+'\\0'+t+'\\n')}else if(s.isDirectory())visit(a,r)}};visit(real,'');return h.digest('hex')}",
|
||||
].join("");
|
||||
|
||||
type SealedPackRecord = { identity: string; manifest: ProviderPackIdentity };
|
||||
/** Fully verified packs this server process has sealed, by target and expected identity. */
|
||||
const sealedPacks = new Map<string, SealedPackRecord>();
|
||||
const MAX_SEALED_PACKS = 512;
|
||||
|
||||
/** Test seam: forget every sealed pack record. */
|
||||
export function clearSealedProviderPacksForTest(): void { sealedPacks.clear(); }
|
||||
|
||||
function sealKeyFor(seal: { targetKey: string } | undefined, packRoot: string, manifest: ProviderPackIdentity, acceptProvenance: boolean): string | null {
|
||||
if (!seal?.targetKey) return null;
|
||||
return createHash("sha256").update(canonicalProviderPackJson([seal.targetKey, packRoot, manifest, acceptProvenance])).digest("hex");
|
||||
}
|
||||
|
||||
const reportedIdentity = (stdout: string) => /paperclip-pack-identity=([a-f0-9]{64})/.exec(stdout)?.[1] ?? null;
|
||||
|
||||
export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({ runner, cwd, packRoot, manifest, installation, provider, requireExactIdentity = false, requireCurrentOpenCodeProxy = false, acceptProvenance = false, seal }: {
|
||||
runner: CommandManagedRuntimeRunner;
|
||||
cwd: string;
|
||||
packRoot: string;
|
||||
@@ -115,20 +144,41 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
|
||||
requireExactIdentity?: boolean;
|
||||
requireCurrentOpenCodeProxy?: boolean;
|
||||
acceptProvenance?: boolean;
|
||||
/**
|
||||
* The exact sandbox this pack sits on. After one full verification the
|
||||
* server keeps the pack's kernel identity; later runs on the same sandbox
|
||||
* re-check only that identity instead of re-hashing every byte.
|
||||
*/
|
||||
seal?: { targetKey: string };
|
||||
}): Promise<T> {
|
||||
if (installation) {
|
||||
if (!provider) throw new Error("runner_remote_provider_artifact_incompatible: provider interface is required");
|
||||
return compatibleInstallation(installation, manifest, packRoot, provider, requireExactIdentity, requireCurrentOpenCodeProxy);
|
||||
}
|
||||
const expected = Buffer.from(
|
||||
canonicalProviderPackJson(manifest),
|
||||
"utf8",
|
||||
).toString("base64");
|
||||
const providerNodeCommand = posix.join(
|
||||
packRoot,
|
||||
manifest.payload.artifacts.nodeCommand.path,
|
||||
);
|
||||
const sealKey = sealKeyFor(seal, packRoot, manifest, acceptProvenance);
|
||||
const sealed = sealKey ? sealedPacks.get(sealKey) : undefined;
|
||||
if (sealKey && sealed) {
|
||||
// Any failure or difference falls through to the full verification.
|
||||
const current = await runner.execute({
|
||||
command: providerNodeCommand,
|
||||
args: ["-e", `${PROVIDER_PACK_IDENTITY_FUNCTION};process.stdout.write('\\npaperclip-pack-identity='+packIdentity(process.argv[1])+'\\n')`, packRoot],
|
||||
cwd, bypassSession: true, timeoutMs: 30_000,
|
||||
}).catch(() => null);
|
||||
if (current && current.exitCode === 0 && !current.timedOut && reportedIdentity(current.stdout) === sealed.identity) {
|
||||
return structuredClone(sealed.manifest) as T;
|
||||
}
|
||||
sealedPacks.delete(sealKey);
|
||||
}
|
||||
const expected = Buffer.from(
|
||||
canonicalProviderPackJson(manifest),
|
||||
"utf8",
|
||||
).toString("base64");
|
||||
const verifyScript = [
|
||||
...(sealKey ? [PROVIDER_PACK_IDENTITY_FUNCTION, "let identityBefore=null;try{identityBefore=packIdentity(process.argv[1])}catch{}"] : []),
|
||||
"const fs=require('node:fs')",
|
||||
"const crypto=require('node:crypto')",
|
||||
"const path=require('node:path')",
|
||||
@@ -157,6 +207,8 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
|
||||
"const expectedPackages={acpx:manifest.payload.pins.acpx,'@agentclientprotocol/claude-agent-acp':manifest.payload.pins.claudeAcp,'@agentclientprotocol/codex-acp':manifest.payload.pins.codexAcp,'opencode-ai':manifest.payload.pins.opencode}",
|
||||
"for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)fail('package_version:'+pkg,pkg+' version mismatch')",
|
||||
"if(provenance)process.stdout.write('\\npaperclip-pack-manifest='+Buffer.from(canonical(manifest)).toString('base64')+'\\n')",
|
||||
// Seal only when no entry changed while it was being hashed.
|
||||
...(sealKey ? ["let identityAfter=null;try{identityAfter=packIdentity(root)}catch{}if(identityBefore&&identityBefore===identityAfter)process.stdout.write('\\npaperclip-pack-identity='+identityAfter+'\\n')"] : []),
|
||||
].join(";");
|
||||
const verified = await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({
|
||||
command: providerNodeCommand,
|
||||
@@ -182,6 +234,11 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
|
||||
) {
|
||||
throw providerPackIncompatible("opencode_version", "OpenCode version mismatch");
|
||||
}
|
||||
const identity = sealKey ? reportedIdentity(verified.stdout) : null;
|
||||
if (sealKey && identity) {
|
||||
if (sealedPacks.size >= MAX_SEALED_PACKS) sealedPacks.delete(sealedPacks.keys().next().value!);
|
||||
sealedPacks.set(sealKey, { identity, manifest: structuredClone(selected) });
|
||||
}
|
||||
return structuredClone(selected);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@ import { describe, expect, it, vi } from "vitest";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { createNativeRunTrace } from "./native-run-trace.js";
|
||||
import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
|
||||
import { COPILOT_CLOSURE_SHA256 } from "../../vendor/paperclip-runner/index.js";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256, antigravityProviderPackEntryRefusal, COPILOT_PROVIDER_PACK_CLOSURES, prepareVerifiedRemoteProviderPack, remoteProviderPackEntryRefusal, type RemoteProviderPackRelease, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
|
||||
|
||||
describe("remote provider verification", () => {
|
||||
const ok = { exitCode: 0, timedOut: false, stdout: "verified", stderr: "", signal: null };
|
||||
@@ -172,7 +174,7 @@ describe("same-content pack reuse across builds", () => {
|
||||
|
||||
describe("ordinary ACPX image artifacts", () => {
|
||||
const provider = (agent: string) => ({ kind: "acpx", agent, model: "selected-model" } as Parameters<typeof shouldUseBundledAcpxImageAssets>[0]["provider"]);
|
||||
it.each(["cursor", "copilot"])("selects bundled artifacts for remote %s without an operator override", agent => {
|
||||
it.each(["cursor", "copilot", "kimi", "antigravity"])("selects bundled artifacts for remote %s without an operator override", agent => {
|
||||
expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: true, configuredProviderPackRoot: null, provider: provider(agent) })).toBe(true);
|
||||
expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: false, configuredProviderPackRoot: null, provider: provider(agent) })).toBe(false);
|
||||
expect(shouldUseBundledAcpxImageAssets({ requiresRemoteProviderPack: true, configuredProviderPackRoot: "/explicit/pack", provider: provider(agent) })).toBe(false);
|
||||
@@ -185,6 +187,98 @@ describe("ordinary ACPX image artifacts", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Google Antigravity image pack identity", () => {
|
||||
const distributions = JSON.parse(readFileSync(new URL("../../../../packages/paperclip-runner/antigravity-distributions.json", import.meta.url), "utf8"));
|
||||
const profile = { agentServerVersion: "1.4.3", commandDigest: `sha256:${"c".repeat(64)}` };
|
||||
const patchedClosures = { "linux-x64": "d".repeat(64) };
|
||||
const entry = { version: profile.agentServerVersion, profileDigest: profile.commandDigest, closureDigest: `sha256:${"d".repeat(64)}` };
|
||||
const base = { inventory: "providers" as const, target: { platform: "linux", architecture: "x64" }, inBoth: false,
|
||||
entry, releasePending: false, profile, patchedClosures };
|
||||
|
||||
it("admits exactly the patched closures pinned in antigravity-distributions.json, never a vendor closure", () => {
|
||||
const verified = Object.fromEntries(Object.entries(distributions.platforms as Record<string, { provisioning: string; closureSha256?: string }>)
|
||||
.filter(([, platform]) => platform.provisioning === "verified-closure").map(([key, platform]) => [key, platform.closureSha256]));
|
||||
expect(ANTIGRAVITY_PATCHED_CLOSURE_SHA256).toEqual(verified);
|
||||
for (const [key, closure] of Object.entries(ANTIGRAVITY_PATCHED_CLOSURE_SHA256)) {
|
||||
expect(closure).not.toBe(distributions.platforms[key].vendorClosureSha256);
|
||||
}
|
||||
});
|
||||
|
||||
it("admits the real linux-x64 image pack closure and refuses its vendor closure", () => {
|
||||
const linux = distributions.platforms["linux-x64"];
|
||||
const real = { ...base, patchedClosures: undefined, entry: { ...entry, closureDigest: `sha256:${linux.closureSha256}` } };
|
||||
expect(antigravityProviderPackEntryRefusal(real)).toBeNull();
|
||||
expect(antigravityProviderPackEntryRefusal({ ...real, entry: { ...real.entry, closureDigest: `sha256:${linux.vendorClosureSha256}` } }))
|
||||
.toMatch(/patched closure/);
|
||||
expect(antigravityProviderPackEntryRefusal({ ...real, entry: { ...real.entry, closureDigest: `sha256:${distributions.platforms["darwin-arm64"].closureSha256}` } }))
|
||||
.toMatch(/patched closure/);
|
||||
});
|
||||
|
||||
it("lists the qualified entry under providers and the pending one under candidateProviders, never both", () => {
|
||||
expect(antigravityProviderPackEntryRefusal(base)).toBeNull();
|
||||
expect(antigravityProviderPackEntryRefusal({ ...base, releasePending: true, inventory: "candidateProviders" })).toBeNull();
|
||||
expect(antigravityProviderPackEntryRefusal({ ...base, inventory: "candidateProviders" })).toMatch(/wrong pack inventory/);
|
||||
expect(antigravityProviderPackEntryRefusal({ ...base, releasePending: true })).toMatch(/wrong pack inventory/);
|
||||
expect(antigravityProviderPackEntryRefusal({ ...base, inBoth: true })).toMatch(/wrong pack inventory/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["the vendor closure", { entry: { ...entry, closureDigest: `sha256:${"e".repeat(64)}` } }],
|
||||
["an unpinned Linux closure", { patchedClosures: {} }],
|
||||
["another target", { target: { platform: "linux", architecture: "arm64" } }],
|
||||
["an older profile", { entry: { ...entry, profileDigest: `sha256:${"f".repeat(64)}` } }],
|
||||
["an older runtime version", { entry: { ...entry, version: "1.4.2" } }],
|
||||
])("refuses %s", (_name, change) => {
|
||||
expect(antigravityProviderPackEntryRefusal({ ...base, ...change })).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("remote provider pack entry expectation", () => {
|
||||
const digest = (char: string) => `sha256:${char.repeat(64)}`;
|
||||
const profile = (version: string, char: string) => ({ agentServerVersion: version, commandDigest: digest(char) });
|
||||
const release: RemoteProviderPackRelease = {
|
||||
profiles: { cursor: profile("c1", "1"), copilot: profile("p1", "2"), kimi: { ...profile("k1", "3"), qualificationStatus: "pending" }, antigravity: profile("a1", "4") },
|
||||
cursorClosures: { "linux-x64": { closureSha256: "5".repeat(64) } },
|
||||
kimiLinuxX64Closure: "6".repeat(64),
|
||||
antigravityReleasePending: true,
|
||||
antigravityPatchedClosures: { "linux-x64": "7".repeat(64) },
|
||||
};
|
||||
const target = { platform: "linux", architecture: "x64" };
|
||||
const all = ["pi", "cursor", "copilot", "kimi", "antigravity"];
|
||||
const entry = (provider: string, qualification: string, version: string, profileDigest: string, closure: string) => ({
|
||||
version, profileDigest, closureDigest: `sha256:${closure}`, qualification, path: `provider-assets/${provider}/linux-x64`, sha256: digest("9"),
|
||||
});
|
||||
const check = (provider: string, inventory: "providers" | "candidateProviders", value: unknown, listed = { providers: inventory === "providers", candidateProviders: inventory === "candidateProviders" }) =>
|
||||
remoteProviderPackEntryRefusal({ provider, inventory, allowedProviders: all, target, entry: value, listed, release });
|
||||
|
||||
it("checks Copilot against the Runner's canonical closure pins", () => {
|
||||
expect(COPILOT_PROVIDER_PACK_CLOSURES).toEqual(COPILOT_CLOSURE_SHA256);
|
||||
expect(Object.keys(COPILOT_PROVIDER_PACK_CLOSURES).sort()).toEqual(["darwin-arm64", "darwin-x64", "linux-x64"]);
|
||||
});
|
||||
|
||||
it("admits each provider's entry only with this release's inventory, qualification, profile and closure", () => {
|
||||
expect(check("pi", "providers", entry("pi", "qualified", "any", digest("8"), "8".repeat(64)))).toBeNull();
|
||||
expect(check("cursor", "providers", entry("cursor", "qualified", "c1", digest("1"), "5".repeat(64)))).toBeNull();
|
||||
expect(check("copilot", "providers", entry("copilot", "qualified", "p1", digest("2"), COPILOT_PROVIDER_PACK_CLOSURES["linux-x64"]!))).toBeNull();
|
||||
expect(check("copilot", "candidateProviders", entry("copilot", "pending", "p1", digest("2"), COPILOT_PROVIDER_PACK_CLOSURES["linux-x64"]!))).toBeNull();
|
||||
expect(check("kimi", "candidateProviders", entry("kimi", "pending", "k1", digest("3"), "6".repeat(64)))).toBeNull();
|
||||
expect(check("antigravity", "candidateProviders", entry("antigravity", "pending", "a1", digest("4"), "7".repeat(64)))).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses with the same reasons the pack verifier reports", () => {
|
||||
expect(check("grok", "providers", entry("grok", "qualified", "g", digest("1"), "1".repeat(64)))).toBe("invalid candidate identity");
|
||||
expect(check("antigravity", "providers", entry("antigravity", "qualified", "a1", digest("4"), "7".repeat(64)))).toBe("invalid candidate identity");
|
||||
expect(check("cursor", "providers", { ...entry("cursor", "qualified", "c1", digest("1"), "5".repeat(64)), extra: true })).toBe("invalid candidate identity");
|
||||
expect(check("cursor", "providers", entry("cursor", "qualified", "c0", digest("1"), "5".repeat(64)))).toBe("Cursor profile or closure does not match this release");
|
||||
expect(check("copilot", "providers", entry("copilot", "qualified", "p1", digest("2"), COPILOT_PROVIDER_PACK_CLOSURES["linux-x64"]!), { providers: true, candidateProviders: true }))
|
||||
.toBe("Copilot profile or closure does not match this release");
|
||||
expect(check("kimi", "candidateProviders", entry("kimi", "pending", "k1", digest("3"), "6".repeat(64)), { providers: true, candidateProviders: true }))
|
||||
.toBe("Kimi profile or closure does not match this release");
|
||||
expect(check("antigravity", "candidateProviders", entry("antigravity", "pending", "a1", digest("4"), "e".repeat(64))))
|
||||
.toBe("Antigravity closure is not this release's patched closure");
|
||||
});
|
||||
});
|
||||
|
||||
describe("standard remote provider pack discovery", () => {
|
||||
const roots = ["/opt/paperclip-runner/provider-pack", "/home/operator/.local/share/paperclip-runner/provider-pack"];
|
||||
it.each(["old manifest", "modified artifact", "failed link"])("tries the matching home pack after %s rejects /opt", async reason => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { redactSensitiveText } from "../../redaction.js";
|
||||
import { nativeRunFailureCheck, type NativeRunTrace } from "./native-run-trace.js";
|
||||
import type { NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
import { ANTIGRAVITY_DISTRIBUTION_PINS, COPILOT_CLOSURE_SHA256, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
|
||||
/** Qualified ACPX releases carry their Linux image manifest and daemon. */
|
||||
export function shouldUseBundledAcpxImageAssets(input: {
|
||||
@@ -10,7 +10,123 @@ export function shouldUseBundledAcpxImageAssets(input: {
|
||||
}): boolean {
|
||||
return input.requiresRemoteProviderPack && !input.configuredProviderPackRoot &&
|
||||
input.provider.kind === "acpx" &&
|
||||
["cursor", "copilot", "kimi"].includes(input.provider.agent);
|
||||
["cursor", "copilot", "kimi", "antigravity"].includes(input.provider.agent);
|
||||
}
|
||||
|
||||
/**
|
||||
* The patched Antigravity closure (never the vendor closure) this server
|
||||
* release admits per platform. It is read from the Runner's generated pins, so
|
||||
* re-pinning the closure in antigravity-distributions.json can never leave a
|
||||
* stale server copy; a test keeps it equal to the `verified-closure` platforms.
|
||||
*/
|
||||
export const ANTIGRAVITY_PATCHED_CLOSURE_SHA256: Readonly<Record<string, string>> = Object.freeze(
|
||||
Object.fromEntries(Object.entries(ANTIGRAVITY_DISTRIBUTION_PINS).map(([target, pin]) => [target, pin.closureSha256])),
|
||||
);
|
||||
|
||||
export type ProviderPackEntry = { version: string; profileDigest: string; closureDigest: string };
|
||||
|
||||
/**
|
||||
* The image pack contract for Antigravity. While the profile is pending the
|
||||
* entry lives only under `candidateProviders`; after the flip only under
|
||||
* `providers`. It targets Linux x64 and pins this release's profile and the
|
||||
* patched closure. Returns null when admitted, else a refusal reason.
|
||||
*/
|
||||
export function antigravityProviderPackEntryRefusal(input: {
|
||||
inventory: "providers" | "candidateProviders";
|
||||
target: { platform: string; architecture: string };
|
||||
inBoth: boolean;
|
||||
entry: ProviderPackEntry;
|
||||
releasePending: boolean;
|
||||
profile: { agentServerVersion: string; commandDigest: string };
|
||||
patchedClosures?: Readonly<Record<string, string>>;
|
||||
}): string | null {
|
||||
const expectedInventory = input.releasePending ? "candidateProviders" : "providers";
|
||||
if (input.inventory !== expectedInventory || input.inBoth) return "Antigravity is listed under the wrong pack inventory";
|
||||
if (input.target.platform !== "linux" || input.target.architecture !== "x64") return "Antigravity pack target must be linux-x64";
|
||||
const closure = (input.patchedClosures ?? ANTIGRAVITY_PATCHED_CLOSURE_SHA256)["linux-x64"];
|
||||
if (!closure || input.entry.closureDigest !== `sha256:${closure}`) return "Antigravity closure is not this release's patched closure";
|
||||
if (input.entry.version !== input.profile.agentServerVersion || input.entry.profileDigest !== input.profile.commandDigest) {
|
||||
return "Antigravity profile does not match this release";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type ProviderPackProfile = { agentServerVersion: string; commandDigest: string };
|
||||
|
||||
/** The provider identities one server release admits in a remote pack. */
|
||||
export type RemoteProviderPackRelease = {
|
||||
profiles: {
|
||||
cursor: ProviderPackProfile;
|
||||
copilot: ProviderPackProfile;
|
||||
kimi: ProviderPackProfile & { qualificationStatus?: string };
|
||||
antigravity: ProviderPackProfile;
|
||||
};
|
||||
cursorClosures: Readonly<Record<string, { closureSha256: string }>>;
|
||||
kimiLinuxX64Closure: string;
|
||||
antigravityReleasePending: boolean;
|
||||
antigravityPatchedClosures?: Readonly<Record<string, string>>;
|
||||
};
|
||||
|
||||
/** Copilot's pinned closure per platform: the Runner's canonical pins. */
|
||||
export const COPILOT_PROVIDER_PACK_CLOSURES: Readonly<Record<string, string>> = COPILOT_CLOSURE_SHA256;
|
||||
|
||||
/**
|
||||
* The complete expectation for one provider entry of a remote pack: which
|
||||
* inventory may list it, its qualification, asset path, digests, and the
|
||||
* release's profile and closure for the pack target. Returns null when the
|
||||
* entry is admitted, else the refusal reason.
|
||||
*/
|
||||
export function remoteProviderPackEntryRefusal(input: {
|
||||
provider: string;
|
||||
inventory: "providers" | "candidateProviders";
|
||||
allowedProviders: readonly string[];
|
||||
target: { platform: string; architecture: string };
|
||||
entry: unknown;
|
||||
/** Whether the provider is listed in each inventory of the same pack. */
|
||||
listed: { providers: boolean; candidateProviders: boolean };
|
||||
release: RemoteProviderPackRelease;
|
||||
}): string | null {
|
||||
const { provider, inventory, target, release } = input;
|
||||
const entry = input.entry as Record<string, unknown> | null | undefined;
|
||||
const kimiPending = release.profiles.kimi.qualificationStatus === "pending";
|
||||
const qualified = ["pi", "cursor"].includes(provider) || inventory === "providers" && (provider === "copilot" || provider === "kimi" && !kimiPending
|
||||
|| provider === "antigravity" && !release.antigravityReleasePending);
|
||||
if (!input.allowedProviders.includes(provider) || !entry || typeof entry !== "object"
|
||||
|| Object.keys(entry).some(key => !["version", "profileDigest", "closureDigest", "qualification", "path", "sha256"].includes(key))
|
||||
|| entry.qualification !== (qualified ? "qualified" : "pending") || entry.path !== `provider-assets/${provider}/${target.platform}-${target.architecture}`
|
||||
|| typeof entry.version !== "string" || !entry.version || entry.version.length > 120
|
||||
|| !/^sha256:[a-f0-9]{64}$/.test(String(entry.profileDigest))
|
||||
|| !/^sha256:[a-f0-9]{64}$/.test(String(entry.closureDigest))
|
||||
|| !/^sha256:[a-f0-9]{64}$/.test(String(entry.sha256))) {
|
||||
return "invalid candidate identity";
|
||||
}
|
||||
const identity = entry as ProviderPackEntry;
|
||||
const platform = `${target.platform}-${target.architecture}`;
|
||||
const matches = (profile: ProviderPackProfile, closure: string | undefined) => closure !== undefined
|
||||
&& identity.version === profile.agentServerVersion && identity.profileDigest === profile.commandDigest && identity.closureDigest === `sha256:${closure}`;
|
||||
if (provider === "cursor") {
|
||||
const closure = Object.hasOwn(release.cursorClosures, platform) ? release.cursorClosures[platform]!.closureSha256 : undefined;
|
||||
if (!matches(release.profiles.cursor, closure)) return "Cursor profile or closure does not match this release";
|
||||
}
|
||||
if (provider === "copilot") {
|
||||
const closure = Object.hasOwn(COPILOT_PROVIDER_PACK_CLOSURES, platform) ? COPILOT_PROVIDER_PACK_CLOSURES[platform] : undefined;
|
||||
if ((input.listed.providers && input.listed.candidateProviders) || !matches(release.profiles.copilot, closure)) {
|
||||
return "Copilot profile or closure does not match this release";
|
||||
}
|
||||
}
|
||||
if (provider === "kimi") {
|
||||
if (inventory !== (kimiPending ? "candidateProviders" : "providers") || input.listed[kimiPending ? "providers" : "candidateProviders"]
|
||||
|| platform !== "linux-x64" || !matches(release.profiles.kimi, release.kimiLinuxX64Closure)) {
|
||||
return "Kimi profile or closure does not match this release";
|
||||
}
|
||||
}
|
||||
if (provider === "antigravity") {
|
||||
return antigravityProviderPackEntryRefusal({ inventory, target, entry: identity,
|
||||
inBoth: input.listed.providers && input.listed.candidateProviders,
|
||||
releasePending: release.antigravityReleasePending, profile: release.profiles.antigravity,
|
||||
patchedClosures: release.antigravityPatchedClosures });
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A run may adopt a same-content pack from another build only when no saved or operator-selected identity binds it. */
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
resolvePaperclipRunnerProviderProfile,
|
||||
type PaperclipRunnerProviderProfile,
|
||||
} from "./provider-profile.js";
|
||||
import { antigravityCandidateTarget } from "./antigravity-release.js";
|
||||
|
||||
/**
|
||||
* Public compatibility resolver version. This value is persisted by the
|
||||
@@ -111,7 +112,8 @@ export function resolveNativeRuntimeMode(input: {
|
||||
}
|
||||
let runnerProfile: PaperclipRunnerProviderProfile;
|
||||
try {
|
||||
runnerProfile = resolvePaperclipRunnerProviderProfile(input.adapterConfig, { companyId: input.agent.companyId });
|
||||
runnerProfile = resolvePaperclipRunnerProviderProfile(input.adapterConfig, { companyId: input.agent.companyId,
|
||||
candidateTarget: antigravityCandidateTarget((input.target?.kind ?? "local") === "remote") });
|
||||
} catch (error) {
|
||||
if (error instanceof PaperclipRunnerProviderProfileError) {
|
||||
throw ineligible(error.code, error.message);
|
||||
|
||||
Reference in new issue
Block a user