fix(antigravity): resolve the hosted runtime in one place and report sign-in failures plainly (#22990)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Google Antigravity agents can sign in with a Google subscription. On
hosted public deployments the server starts the pinned Antigravity
runtime and relays the pasted loopback redirect (#22932).
> - The server looked for that runtime only in the server package's
vendored assets and the OS-account cache. The Docker image keeps the
verified closure in the build-owned provider pack
(`PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH`).
> - So every hosted attempt failed before the runtime started, and the
page showed "Google sign-in did not complete. Start sign-in again." with
no sign-in link. Every failure reason became that one message, and
nothing was logged.
> - #22983 added the pack lookup as an option that each caller had to
pass. That leaves several search paths that can drift: installation
verification still used none.
> - This pull request moves the pack lookup into the one canonical
resolver, gives sign-in failures a typed reason with one plain-language
message each, and logs a secret-free reason code.
> - The benefit is that sign-in, model discovery and installation
verification always find the same verified runtime, and a server without
the runtime says why.

## Linked Issues or Issue Description

Refs #22932, Refs #22983

**Describe the bug**
On a hosted authenticated public deployment, the user chooses Google
Antigravity and then "Google Subscription". The page immediately shows
"Google sign-in did not complete. Start sign-in again." `POST
.../ai-connections/local/attempts` returns 201, and every `POST
.../ai-connections/local/check` returns `sign_in_required` with the same
message and no `authorizationUrl`.

**Steps to reproduce**
1. Run the standard image as an authenticated public deployment. Do not
create an Antigravity runtime cache in the server account.
2. Create an agent with Google Antigravity and choose Google
Subscription.
3. See the error before any sign-in step runs.

**Expected behavior**
The server starts the pinned runtime from the image's provider pack and
shows the Google sign-in link. If the server has no runtime, the message
says so in plain language and does not tell the user to start again.

**Root cause**
`antigravityNativeDistributionSpec()` resolved
`<server>/dist/vendor/paperclip-runner/provider-assets/antigravity/<target>`
and then `$HOME/.paperclip/runtimes/antigravity/<target>/<closure>`. The
image ships the closure at
`$PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH/provider-assets/antigravity/linux-x64`.
`startAntigravityBrowserLogin` caught every failure with a bare `catch`
and showed the generic message. The #22932 tests mocked both the runtime
resolution and the installation check.

## What Changed

- Runner: `antigravityNativeDistributionSpec` is the one resolver for
every caller. The search order is: the runner package's own assets
(runnerd binds Runner children to the selected pack with
`PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT`), then the deployment provider
pack from `PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH`, then the
OS-account cache. The pack root must be a normalized absolute path. The
pack goes through the manifest and link checks of
`resolveRunnerProviderAssetsRoot` from #22983. The pinned closure digest
check is unchanged.
- Runner: the `providerPackageRoot` option on
`startAntigravityBrowserLogin`, `discoverAntigravityModels` and
`antigravityNativeDistributionSpec` is removed. The server no longer
reads the pack path.
- Runner: sign-in failures have a typed reason (`runtime_unavailable`,
`start_failed`, `login_incomplete`, `aborted`). One table maps each
reason to its message. A missing runtime reports "This server does not
have the current Google Antigravity runtime, so Google sign-in cannot
start. Use a Google API key instead, or update Paperclip on this
server."
- Runner: model discovery throws `AntigravityRuntimeUnavailableError`
when the runtime is missing. The server shows a plain-language message
for it instead of "Could not load models for this Google account".
- Server: sign-in failures, except cancelled attempts, are logged with a
secret-free code such as `ANTIGRAVITY_SIGN_IN_RUNTIME_UNAVAILABLE`. A
missing runtime during model discovery is logged as
`ANTIGRAVITY_RUNTIME_UNAVAILABLE`.

## Verification

- Red on master, green on this branch:
- `antigravity-installation.test.ts`: pack resolution, precedence, cache
fallback, link and path refusal, and one test that binds sign-in, model
discovery and `verifyAntigravityInstallation` to the same pack with no
vendored assets.
- `antigravity-auth.test.ts`: one test for each failure reason and its
message.
- `antigravity-models.test.ts`: a missing runtime gives
`AntigravityRuntimeUnavailableError` without a launch.
- `pnpm --filter @paperclipai/paperclip-runner exec vitest run` on the
antigravity auth, stream-order, installation, models and
provider-assets-root suites: 76 of 76 pass.
- `server/src/__tests__/local-ai-browser-login-google.test.ts`,
`antigravity-connection-models.test.ts` and
`antigravity-local-ai-login.test.ts`: 33 of 33 pass.
- The runner `tsc --noEmit` and the server `tsc --noEmit` pass.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
reports no registry change.
- `pnpm verify` returned exit 2 (runner test files are outside the
resolved test graphs). Required CI supplies the broad coverage.
- Not run: a live Google sign-in against the real closure in a hosted
image. That needs a deploy and a real Google account.

## Risks

- Low risk. The pack is used only when the packaged assets are absent
and the pack contains the target. A modified pack still fails the pinned
closure check.
- A pack root that is relative or contains `..` now fails as "runtime
unavailable" instead of being ignored silently.
- Error text changes only for failures before the runtime initializes.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits, test runs).

## 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
- [ ] All Paperclip CI gates are green
- [ ] 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 Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-25 14:30:43 -06:00
1 parent cb39f99a39
commit 304854ee99
15 files changed
+297 -126

No files matched your search

@@ -4,8 +4,8 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
const setup = vi.hoisted(() => ({ spawn: vi.fn(), close: vi.fn(async () => undefined), verify: vi.fn() }));
vi.mock("./antigravity-installation.js", () => ({ antigravityNativeDistributionSpec: () => ({ pinned: true }) }));
const setup = vi.hoisted(() => ({ spawn: vi.fn(), close: vi.fn(async () => undefined), verify: vi.fn(), spec: vi.fn((..._args: unknown[]) => ({ pinned: true })) }));
vi.mock("./antigravity-installation.js", () => ({ antigravityNativeDistributionSpec: setup.spec }));
vi.mock("./installation-integrity.js", () => ({ verifyNativeAcpxInstallation: setup.verify }));
import { sanitizeAntigravityCredential, startAntigravityBrowserLogin, validateAntigravityAuthorizationUrl, verifyAntigravityCredential } from "./antigravity-auth.js";
@@ -191,6 +191,63 @@ describe("Antigravity setup-only Google authentication", () => {
expect(setup.close).toHaveBeenCalledOnce();
});
it("reports a missing server runtime plainly instead of an unfinished sign-in", async () => {
const home = await fixture(); const fetch = vi.fn(); vi.stubGlobal("fetch", fetch);
setup.verify.mockRejectedValueOnce(Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }));
const onFailure = vi.fn();
const login = startAntigravityBrowserLogin(home, { onFailure });
await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 });
expect(onFailure).toHaveBeenCalledExactlyOnceWith("runtime_unavailable");
expect(login.error).toBe("This server does not have the current Google Antigravity runtime, so Google sign-in cannot start. Use a Google API key instead, or update Paperclip on this server.");
expect(login.authorizationUrl).toBeUndefined();
expect(setup.spawn).not.toHaveBeenCalled();
expect(fetch).not.toHaveBeenCalled();
});
it("reports a runtime that exits before showing a sign-in link as a failed start", async () => {
const home = await fixture(); vi.stubGlobal("fetch", vi.fn());
setup.spawn.mockImplementationOnce((_args, options) => {
const child = spawn(process.execPath, ["-e", "process.exit(1)"], { ...options, detached: true }); children.push(child); return child;
});
const onFailure = vi.fn();
const login = startAntigravityBrowserLogin(home, { onFailure });
await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 });
await vi.waitFor(() => expect(setup.close).toHaveBeenCalledOnce(), { timeout: 5_000 });
expect(login.error).toBe("Google sign-in could not start on this server. Start sign-in again.");
expect(onFailure).toHaveBeenCalledExactlyOnceWith("start_failed");
expect(login.authorizationUrl).toBeUndefined();
});
it("reports a resolver failure as an unavailable runtime", async () => {
const home = await fixture(); vi.stubGlobal("fetch", vi.fn());
setup.spec.mockImplementationOnce(() => { throw new Error("Antigravity has no admitted complete runtime closure for fixture"); });
const onFailure = vi.fn();
const login = startAntigravityBrowserLogin(home, { onFailure });
await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 });
expect(onFailure).toHaveBeenCalledExactlyOnceWith("runtime_unavailable");
expect(login.error).toContain("does not have the current Google Antigravity runtime");
expect(login.error).not.toContain("Start sign-in again");
});
it("reports a failure after the runtime starts as an incomplete sign-in", async () => {
const home = await fixture("error"); vi.stubGlobal("fetch", vi.fn());
const onFailure = vi.fn();
const login = startAntigravityBrowserLogin(home, { onFailure });
await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 });
expect(onFailure).toHaveBeenCalledExactlyOnceWith("login_incomplete");
expect(login.error).toBe("Google sign-in did not complete. Start sign-in again.");
});
it("reports a cancelled attempt as aborted", async () => {
const home = await fixture("blocked"); vi.stubGlobal("fetch", vi.fn());
const onFailure = vi.fn();
const login = startAntigravityBrowserLogin(home, { onFailure });
await vi.waitFor(() => expect(login.authorizationUrl).toBeDefined());
await login.abort();
expect(onFailure).toHaveBeenCalledExactlyOnceWith("aborted");
expect(login.outcome).toBe("failure");
});
it("requires the pinned OAuth client and token destination and strips unrelated native fields", () => {
expect(JSON.parse(sanitizeAntigravityCredential(JSON.stringify({ ...credential, endpoint: "https://example.invalid", access_token: "discard" })))).toEqual(credential);
expect(sanitizeAntigravityCredential(JSON.stringify({ ...credential, scopes: [...credential.scopes].reverse() }))).toBe(sanitizeAntigravityCredential(JSON.stringify(credential)));
@@ -7,6 +7,7 @@ import { StringDecoder } from "node:string_decoder";
import { antigravityPrivateEnvironment, checkAntigravityPrivateHome, retireAntigravityProcess } from "./antigravity-process.js";
import { antigravityNativeDistributionSpec } from "./antigravity-installation.js";
import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.js";
import { AntigravityRuntimeUnavailableError } from "./antigravity-runtime-unavailable.js";
import { verifyNativeAcpxInstallation, type VerifiedAcpxCommandLease } from "./installation-integrity.js";
const CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
@@ -35,6 +36,15 @@ function recordUsedRedirectCodeDigest(digest: string): void {
}
}
export type AntigravityBrowserLoginFailureReason = "runtime_unavailable" | "start_failed" | "login_incomplete" | "aborted";
const FAILURE_MESSAGES: Readonly<Record<AntigravityBrowserLoginFailureReason, string>> = {
runtime_unavailable: "This server does not have the current Google Antigravity runtime, so Google sign-in cannot start. Use a Google API key instead, or update Paperclip on this server.",
start_failed: "Google sign-in could not start on this server. Start sign-in again.",
login_incomplete: LOGIN_ERROR,
aborted: LOGIN_ERROR,
};
export type AntigravityBrowserLoginState = {
authorizationUrl?: string;
outcome?: "success" | "failure";
@@ -170,10 +180,7 @@ export async function verifyAntigravityCredential(home: string, options: { signa
* initialize/authenticate; pending provider qualification remains enforced for
* every session and prompt by the ordinary runtime installation path.
*/
export function startAntigravityBrowserLogin(
home: string,
options?: { providerPackageRoot?: string },
): AntigravityBrowserLoginState {
export function startAntigravityBrowserLogin(home: string, options: { onFailure?: (reason: AntigravityBrowserLoginFailureReason) => void } = {}): AntigravityBrowserLoginState {
const controller = new AbortController();
activeBrowserHomes.add(home);
let resolveStopped: () => void;
@@ -183,12 +190,11 @@ export function startAntigravityBrowserLogin(
let lease: VerifiedAcpxCommandLease | undefined;
let child: ChildProcessWithoutNullStreams | undefined, closed: Promise<void> | undefined;
let timeout: ReturnType<typeof setTimeout> | undefined, failPending: ((error: Error) => void) | undefined;
let pendingReason: AntigravityBrowserLoginFailureReason = "start_failed";
try {
await checkAntigravityPrivateHome(home);
const spec = options?.providerPackageRoot !== undefined
? antigravityNativeDistributionSpec(process.platform, process.arch, { providerPackageRoot: options.providerPackageRoot })
: antigravityNativeDistributionSpec();
const installation = await verifyNativeAcpxInstallation(spec);
const installation = await Promise.resolve().then(() => verifyNativeAcpxInstallation(antigravityNativeDistributionSpec()))
.catch(() => { throw new AntigravityRuntimeUnavailableError(); });
lease = await installation.openCommand({ signal: controller.signal });
const environment = await antigravityPrivateEnvironment(home);
if (controller.signal.aborted) throw new Error(LOGIN_ERROR);
@@ -218,7 +224,7 @@ export function startAntigravityBrowserLogin(
if (initialized.protocolVersion !== 1 || info.name !== "antigravity-acp" || info.version !== ANTIGRAVITY_RUNTIME_VERSION
|| record(record(record(initialized.agentCapabilities)._meta).antigravity).paperclipAdmission !== 1
|| !Array.isArray(initialized.authMethods) || !initialized.authMethods.some(method => record(method).id === "oauth-personal")) { fail(); return; }
phase = 2; send(2);
phase = 2; pendingReason = "login_incomplete"; send(2);
} else { phase = 3; state.submitRedirect = undefined; resolve(); }
}
});
@@ -352,8 +358,12 @@ export function startAntigravityBrowserLogin(
await verifyAntigravityCredential(home, { signal: controller.signal });
if (controller.signal.aborted) throw new Error(LOGIN_ERROR);
state.outcome = "success";
} catch {
state.outcome = "failure"; state.error = LOGIN_ERROR;
} catch (error) {
state.outcome = "failure";
const reason: AntigravityBrowserLoginFailureReason = controller.signal.aborted ? "aborted"
: error instanceof AntigravityRuntimeUnavailableError ? "runtime_unavailable" : pendingReason;
state.error = FAILURE_MESSAGES[reason];
try { options.onFailure?.(reason); } catch {}
} finally {
state.submitRedirect = undefined;
if (timeout) clearTimeout(timeout);
@@ -0,0 +1,99 @@
import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir, userInfo } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
const setup = vi.hoisted(() => ({ assets: "", verify: vi.fn() }));
vi.mock("./provider-assets-root.js", async original => {
const actual = await original<typeof import("./provider-assets-root.js")>();
return { ...actual, resolveRunnerProviderAssetsRoot: (...args: Parameters<typeof actual.resolveRunnerProviderAssetsRoot>) =>
args[2]?.providerPackageRoot === undefined ? setup.assets : actual.resolveRunnerProviderAssetsRoot(...args) };
});
vi.mock("./installation-integrity.js", async original => ({
...await original<typeof import("./installation-integrity.js")>(), verifyNativeAcpxInstallation: setup.verify,
}));
import { startAntigravityBrowserLogin } from "./antigravity-auth.js";
import { antigravityNativeDistributionSpec, antigravityProviderPackRoot, antigravityRuntimeCachePath, verifyAntigravityInstallation } from "./antigravity-installation.js";
import { discoverAntigravityModels } from "./antigravity-models.js";
import { AntigravityRuntimeUnavailableError } from "./antigravity-runtime-unavailable.js";
import { ANTIGRAVITY_DISTRIBUTION_PINS } from "./generated-profiles.js";
import { QUALIFIED_ACPX_PROFILES } from "./qualified-profiles.js";
const PACK_ENV = "PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH";
const target = `${process.platform}-${process.arch}`;
const pinned = Object.hasOwn(ANTIGRAVITY_DISTRIBUTION_PINS, target);
const roots: string[] = [];
afterEach(async () => {
vi.unstubAllEnvs(); vi.clearAllMocks();
await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })));
});
async function layout() {
const root = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-installation-"))); roots.push(root);
setup.assets = join(root, "server-vendor", "provider-assets", "antigravity");
const pack = join(root, "provider-pack");
await mkdir(pack);
await writeFile(join(pack, "package.json"), JSON.stringify({ name: "@paperclipai/paperclip-runner" }));
return { root, pack, packed: (key: string) => join(pack, "provider-assets", "antigravity", key) };
}
describe("Antigravity runtime resolution", () => {
it("uses the deployment's build-owned provider pack when the server package carries no packaged runtime", async () => {
const { pack, packed } = await layout();
await mkdir(packed("linux-x64"), { recursive: true });
vi.stubEnv(PACK_ENV, ` ${pack}/ `);
const spec = antigravityNativeDistributionSpec("linux", "x64");
expect(spec.distributionRoot).toBe(packed("linux-x64"));
expect(spec.manifestPath).toBe(join(packed("linux-x64"), ".paperclip-antigravity-closure.json"));
expect(spec.expectedClosureSha256).toBe(ANTIGRAVITY_DISTRIBUTION_PINS["linux-x64"].closureSha256);
});
it("prefers the packaged runtime over the provider pack", async () => {
const { pack, packed } = await layout();
await mkdir(packed("linux-x64"), { recursive: true });
await mkdir(join(setup.assets, "linux-x64"), { recursive: true });
vi.stubEnv(PACK_ENV, pack);
expect(antigravityNativeDistributionSpec("linux", "x64").distributionRoot).toBe(join(setup.assets, "linux-x64"));
});
it("falls back to the account runtime cache when no provider pack carries this target", async () => {
const { pack } = await layout();
const cache = antigravityRuntimeCachePath(ANTIGRAVITY_DISTRIBUTION_PINS["linux-x64"].closureSha256, "linux", "x64", userInfo().homedir);
vi.stubEnv(PACK_ENV, pack);
expect(antigravityNativeDistributionSpec("linux", "x64").distributionRoot).toBe(cache);
vi.stubEnv(PACK_ENV, "");
expect(antigravityNativeDistributionSpec("linux", "x64").distributionRoot).toBe(cache);
});
it("refuses a provider pack runtime reached through a link or a relative root", async () => {
const { root, pack } = await layout();
await mkdir(join(root, "elsewhere", "linux-x64"), { recursive: true });
await mkdir(join(pack, "provider-assets"), { recursive: true });
await symlink(join(root, "elsewhere"), join(pack, "provider-assets", "antigravity"));
vi.stubEnv(PACK_ENV, pack);
expect(() => antigravityNativeDistributionSpec("linux", "x64")).toThrow(/not contained by its package/);
expect(() => antigravityProviderPackRoot({ [PACK_ENV]: "provider-pack" })).toThrow(/normalized absolute path/);
expect(() => antigravityProviderPackRoot({ [PACK_ENV]: "/opt/paperclip-runner/../etc" })).toThrow(/normalized absolute path/);
expect(antigravityProviderPackRoot({ [PACK_ENV]: " /opt/paperclip-runner/provider-pack/ " })).toBe("/opt/paperclip-runner/provider-pack");
expect(antigravityProviderPackRoot({})).toBeUndefined();
});
it.runIf(pinned)("binds sign-in, model discovery and installation verification to the same provider pack", async () => {
const { root, pack, packed } = await layout();
await mkdir(packed(target), { recursive: true });
vi.stubEnv(PACK_ENV, pack);
const resolved: string[] = [];
setup.verify.mockImplementation(async (spec: { distributionRoot: string }) => { resolved.push(spec.distributionRoot); throw new Error("fixture closure absent"); });
const home = join(root, "home");
await mkdir(home, { mode: 0o700 });
const onFailure = vi.fn();
const login = startAntigravityBrowserLogin(home, { onFailure });
await vi.waitFor(() => expect(login.outcome).toBe("failure"), { timeout: 5_000 });
expect(onFailure).toHaveBeenCalledExactlyOnceWith("runtime_unavailable");
await expect(discoverAntigravityModels(home)).rejects.toBeInstanceOf(AntigravityRuntimeUnavailableError);
await expect(verifyAntigravityInstallation({ ...QUALIFIED_ACPX_PROFILES.antigravity, qualificationModel: "fixture-model", reportedModelId: "fixture-model" }))
.rejects.toThrow("fixture closure absent");
expect(resolved).toEqual([packed(target), packed(target), packed(target)]);
});
});
@@ -1,7 +1,7 @@
import { assertAcpxExecutionAdmission, type AcpxCandidateStartupAdmission } from "./candidate-admission.js";
import { lstatSync } from "node:fs";
import { userInfo } from "node:os";
import { isAbsolute, join } from "node:path";
import { isAbsolute, join, resolve } from "node:path";
import { ANTIGRAVITY_DISTRIBUTION_PINS } from "./generated-profiles.js";
import { verifyNativeAcpxInstallation, type VerifiedAcpxInstallation } from "./installation-integrity.js";
import type { NativeAcpxDistributionInput } from "./native-distribution-integrity.js";
@@ -16,29 +16,43 @@ export function antigravityRuntimeCachePath(closure: string, platform: string, a
return realRuntimeCachePath(home, "antigravity", `${platform}-${architecture}`, closure, "Antigravity runtime cache must contain real directories");
}
export function antigravityNativeDistributionSpec(
platform: NodeJS.Platform = process.platform,
architecture: string = process.arch,
options?: { providerPackageRoot?: string },
): NativeAcpxDistributionInput {
function realDirectoryExists(path: string, message: string): boolean {
try {
const stat = lstatSync(path);
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(message);
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
return false;
}
}
const ANTIGRAVITY_PROVIDER_PACK_ENV = "PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH";
export function antigravityProviderPackRoot(environment: NodeJS.ProcessEnv = process.env): string | undefined {
const configured = environment[ANTIGRAVITY_PROVIDER_PACK_ENV]?.trim();
if (!configured) return undefined;
const root = configured.replace(/\/+$/, "") || "/";
if (!isAbsolute(root) || root.includes("\0") || resolve(root) !== root) throw new Error("Antigravity provider pack root must be a normalized absolute path");
return root;
}
function providerPackDistribution(pack: string, key: string): string | undefined {
if (!realDirectoryExists(pack, "Antigravity provider pack must be a real directory")) return undefined;
const directory = join(resolveRunnerProviderAssetsRoot(import.meta.url, "antigravity", { providerPackageRoot: pack }), key);
return realDirectoryExists(directory, "Antigravity provider pack runtime must be a real directory") ? directory : undefined;
}
export function antigravityNativeDistributionSpec(platform: NodeJS.Platform = process.platform, architecture: string = process.arch): NativeAcpxDistributionInput {
const key = `${platform}-${architecture}`;
if (!Object.hasOwn(ANTIGRAVITY_DISTRIBUTION_PINS, key)) throw new Error(`Antigravity has no admitted complete runtime closure for ${key}`);
const pin = ANTIGRAVITY_DISTRIBUTION_PINS[key as keyof typeof ANTIGRAVITY_DISTRIBUTION_PINS];
const packaged = join(
resolveRunnerProviderAssetsRoot(
import.meta.url,
"antigravity",
options?.providerPackageRoot !== undefined ? { providerPackageRoot: options.providerPackageRoot } : undefined,
),
key,
);
const packaged = join(resolveRunnerProviderAssetsRoot(import.meta.url, "antigravity"), key);
let distributionRoot = packaged;
try {
const stat = lstatSync(packaged);
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Antigravity packaged runtime must be a real directory");
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
distributionRoot = antigravityRuntimeCachePath(pin.closureSha256, platform, architecture);
if (!realDirectoryExists(packaged, "Antigravity packaged runtime must be a real directory")) {
const pack = antigravityProviderPackRoot();
distributionRoot = (pack === undefined ? undefined : providerPackDistribution(pack, key))
?? antigravityRuntimeCachePath(pin.closureSha256, platform, architecture);
}
return { distributionRoot, manifestPath: join(distributionRoot, ".paperclip-antigravity-closure.json"), expectedClosureSha256: pin.closureSha256,
executable: pin.executable, fixedArguments: [...pin.args], storeFamily: "antigravity" };
@@ -10,8 +10,8 @@ import { verifyQualifiedAcpxInstallation } from "./installation-integrity.js";
import { verifyAcpxProfileInstallation } from "./profile-installation.js";
import { assertAcpxProfileReleased, resolveQualifiedAcpxProfile } from "./qualified-profiles.js";
const setup = vi.hoisted(() => ({ spawn: vi.fn(), close: vi.fn(async () => undefined), verify: vi.fn(), uncertainRetirement: false }));
vi.mock("./antigravity-installation.js", () => ({ antigravityNativeDistributionSpec: () => ({ pinned: true }) }));
const setup = vi.hoisted(() => ({ spawn: vi.fn(), close: vi.fn(async () => undefined), verify: vi.fn(), uncertainRetirement: false, spec: vi.fn((..._args: unknown[]) => ({ pinned: true })) }));
vi.mock("./antigravity-installation.js", () => ({ antigravityNativeDistributionSpec: setup.spec }));
vi.mock("./installation-integrity.js", async original => ({
...await original<typeof import("./installation-integrity.js")>(), verifyNativeAcpxInstallation: setup.verify,
}));
@@ -21,6 +21,7 @@ vi.mock("./antigravity-process.js", async original => {
? Promise.reject(new Error("controlled retirement uncertainty")) : actual.retireAntigravityProcess(...args) };
});
import { AntigravityModelDiscoveryCleanupError, discoverAntigravityModels } from "./antigravity-models.js";
import { AntigravityRuntimeUnavailableError } from "./antigravity-runtime-unavailable.js";
const roots: string[] = [], children: ChildProcess[] = [];
afterEach(async () => {
@@ -93,6 +94,15 @@ describe("Antigravity session-free account model discovery", () => {
if (mode === "old-patch") expect(JSON.parse(await readFile(join(home, "requests.json"), "utf8"))).toHaveLength(1);
});
it("reports a missing runtime by its own error without launching", async () => {
const home = await fixture();
setup.verify.mockRejectedValueOnce(Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" }));
const failure = await discoverAntigravityModels(home).catch(error => error);
expect(failure).toBeInstanceOf(AntigravityRuntimeUnavailableError);
expect(failure.code).toBe("ANTIGRAVITY_RUNTIME_UNAVAILABLE");
expect(setup.spawn).not.toHaveBeenCalled();
});
it("cancellation retires a blocked catalog process and inherited descendant before rejecting", async () => {
const home = await fixture("stubborn"), controller = new AbortController();
const result = discoverAntigravityModels(home, { signal: controller.signal });
@@ -4,6 +4,7 @@ import { antigravityNativeDistributionSpec } from "./antigravity-installation.js
import { ANTIGRAVITY_RUNTIME_VERSION } from "./generated-profiles.js";
import { antigravityPrivateEnvironment, checkAntigravityPrivateHome, retireAntigravityProcess } from "./antigravity-process.js";
import { verifyNativeAcpxInstallation, type VerifiedAcpxCommandLease } from "./installation-integrity.js";
import { AntigravityRuntimeUnavailableError } from "./antigravity-runtime-unavailable.js";
const SCHEMA = "paperclip.antigravity.models.v1";
const ERROR = "Could not load models for this Google account. Retry or sign in again.";
@@ -71,7 +72,7 @@ function catalog(value: unknown, nonce: string): AntigravityModelCatalog {
*/
export async function discoverAntigravityModels(
home: string,
options: { signal?: AbortSignal; providerPackageRoot?: string } = {},
options: { signal?: AbortSignal } = {},
): Promise<AntigravityModelCatalog> {
const deadline = new AbortController(), timer = setTimeout(() => deadline.abort(), 30_000);
const signal = options.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal;
@@ -82,10 +83,10 @@ export async function discoverAntigravityModels(
signal.throwIfAborted();
await checkAntigravityPrivateHome(home);
signal.throwIfAborted();
const spec = options.providerPackageRoot !== undefined
? antigravityNativeDistributionSpec(process.platform, process.arch, { providerPackageRoot: options.providerPackageRoot })
: antigravityNativeDistributionSpec();
const installation = await verifyNativeAcpxInstallation(spec);
let installation;
try {
installation = await verifyNativeAcpxInstallation(antigravityNativeDistributionSpec());
} catch { throw new AntigravityRuntimeUnavailableError(); }
signal.throwIfAborted();
lease = await installation.openCommand({ signal });
const environment = await antigravityPrivateEnvironment(home);
@@ -134,7 +135,7 @@ export async function discoverAntigravityModels(
peer.stdin.on("error", () => { if (phase !== 3) fail(); });
if (signal.aborted) fail(); else send(1);
});
} catch { failure ??= new Error(ERROR); }
} catch (error) { failure ??= error instanceof AntigravityRuntimeUnavailableError ? error : new Error(ERROR); }
finally {
try {
if (child && closed) await retireAntigravityProcess(child, closed);
@@ -0,0 +1,7 @@
export class AntigravityRuntimeUnavailableError extends Error {
readonly code = "ANTIGRAVITY_RUNTIME_UNAVAILABLE";
constructor() {
super("This server does not have the current Google Antigravity runtime.");
this.name = "AntigravityRuntimeUnavailableError";
}
}
@@ -141,7 +141,8 @@ it("resolves explicit providerPackageRoot for bundled server runtimes and Antigr
await mkdir(join(pack, "provider-assets/antigravity/linux-x64"), { recursive: true });
expect(resolveRunnerProviderAssetsRoot("file:///app/server/dist-runtime/index.mjs", "antigravity", { providerPackageRoot: pack }))
.toBe(join(pack, "provider-assets/antigravity"));
expect(antigravityNativeDistributionSpec("linux", "x64", { providerPackageRoot: pack }).distributionRoot)
vi.stubEnv("PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH", pack);
expect(antigravityNativeDistributionSpec("linux", "x64").distributionRoot)
.toBe(join(pack, "provider-assets/antigravity/linux-x64"));
// Explicit invalid roots fail closed instead of falling back to process.env.
vi.stubEnv("PAPERCLIP_ACPX_PROVIDER_PACKAGE_ROOT", pack);
+2 -1
View File
@@ -86,7 +86,8 @@ export * from "./drivers/opencode/opencode-server-driver.js";
export * from "./drivers/opencode/mcp-bridge.js";
export * from "./drivers/acpx/qualified-profiles.js";
export { isAntigravityNativeTarget, parseAcpxCandidateAdmission, type AcpxCandidateAdmission } from "./drivers/acpx/candidate-admission.js";
export { startAntigravityBrowserLogin, verifyAntigravityCredential, sanitizeAntigravityCredential, type AntigravityBrowserLoginState } from "./drivers/acpx/antigravity-auth.js";
export { startAntigravityBrowserLogin, verifyAntigravityCredential, sanitizeAntigravityCredential, type AntigravityBrowserLoginFailureReason, type AntigravityBrowserLoginState } from "./drivers/acpx/antigravity-auth.js";
export { AntigravityRuntimeUnavailableError } from "./drivers/acpx/antigravity-runtime-unavailable.js";
export {
GENERATED_ANTIGRAVITY_SWARM_CHANNELS, GENERATED_ANTIGRAVITY_SWARM_CREDENTIAL_FACTS_FIELD, GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL,
readGeneratedAntigravitySwarmCredentialFacts, type GeneratedAntigravitySwarmChannel, type GeneratedAntigravitySwarmCredentialFacts,
@@ -5,6 +5,9 @@ const mocks = vi.hoisted(() => ({ managed: vi.fn(), discover: vi.fn(), cleanup:
CleanupError: class extends Error {
constructor(readonly retired: Promise<void>) { super("cleanup pending"); }
},
UnavailableError: class extends Error {
readonly code = "ANTIGRAVITY_RUNTIME_UNAVAILABLE";
},
}));
const spawned = vi.hoisted(() => vi.fn());
vi.mock("node:child_process", async original => {
@@ -16,6 +19,7 @@ vi.mock("../services/ai-connection-runtime.js", () => ({ prepareManagedAiRuntime
vi.mock("../middleware/logger.js", () => ({ logger: { warn: mocks.warn } }));
vi.mock("../vendor/paperclip-runner/index.js", () => ({
discoverAntigravityModels: mocks.discover, AntigravityModelDiscoveryCleanupError: mocks.CleanupError,
AntigravityRuntimeUnavailableError: mocks.UnavailableError,
}));
import { antigravityConnectionModels } from "../services/antigravity-connection-models.js";
import { RetiredCredentialRecoveryError } from "../services/quota-credential-recovery.js";
@@ -45,6 +49,14 @@ it("uses the selected account lifecycle and returns only its model catalog", asy
expect(mocks.cleanup).toHaveBeenCalledExactlyOnceWith();
});
it("reports a missing server runtime plainly and logs its reason code", async () => {
mocks.discover.mockRejectedValueOnce(new mocks.UnavailableError("runtime missing"));
await expect(antigravityConnectionModels({} as never, input)).rejects.toThrow(
"This server does not have the current Google Antigravity runtime, so Google account models cannot load. Use a Google API key instead, or update Paperclip on this server.");
expect(mocks.warn).toHaveBeenCalledWith({ companyId: "company", code: "ANTIGRAVITY_RUNTIME_UNAVAILABLE" }, "Antigravity model discovery runtime is unavailable");
expect(mocks.cleanup).toHaveBeenCalledExactlyOnceWith();
});
it("returns the pinned API-key catalog for a Gemini API key without preparing a credential or starting a process", async () => {
const models = await antigravityConnectionModels({} as never, { ...input, binding: { provider: "google", method: "api_key", mode: "responsible_user" } });
expect(models.map(model => model.id)).toEqual(antigravityApiKeyModels().map(model => model.id));
@@ -147,19 +159,3 @@ it("allows another provider launch while the original cleanup still cannot journ
expect(mocks.discover).toHaveBeenCalledTimes(2);
expect(mocks.cleanup).toHaveBeenCalledTimes(3);
});
it("forwards PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH to model discovery and rejects non-normalized paths", async () => {
try {
vi.stubEnv("PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH", "/opt/paperclip-runner/provider-pack/");
mocks.discover.mockResolvedValueOnce({ models: [{ id: "gemini-3.8-flash-high", label: "Gemini 3.8 Flash (High)" }], defaultModelId: "gemini-3.8-flash-high" });
await antigravityConnectionModels({} as never, input);
expect(mocks.discover).toHaveBeenLastCalledWith("/private/selected-google-home", { providerPackageRoot: "/opt/paperclip-runner/provider-pack" });
vi.stubEnv("PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH", "/opt/paperclip-runner/../etc");
mocks.discover.mockResolvedValueOnce({ models: [{ id: "gemini-3.8-flash-high", label: "Gemini 3.8 Flash (High)" }], defaultModelId: "gemini-3.8-flash-high" });
await antigravityConnectionModels({} as never, input);
expect(mocks.discover).toHaveBeenLastCalledWith("/private/selected-google-home");
} finally {
vi.unstubAllEnvs();
}
});
@@ -0,0 +1,28 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const runner = vi.hoisted(() => ({ warn: vi.fn(), start: vi.fn((_home: string, _options?: { onFailure?: (reason: string) => void }) => ({ abort: async () => undefined })) }));
vi.mock("../middleware/logger.js", () => ({ logger: { warn: runner.warn } }));
vi.mock("../vendor/paperclip-runner/index.js", () => ({ resolveCodexCommand: vi.fn(), startAntigravityBrowserLogin: runner.start }));
vi.mock("@paperclipai/adapter-claude-local/server", () => ({ runSetupTokenLogin: vi.fn() }));
vi.mock("@paperclipai/adapter-codex-local/server", () => ({ runDeviceLogin: vi.fn() }));
import { startLocalBrowserLogin } from "../services/local-ai-browser-login.js";
afterEach(() => { vi.clearAllMocks(); });
describe("server-host Google sign-in failure logging", () => {
it.each([
["runtime_unavailable", "ANTIGRAVITY_SIGN_IN_RUNTIME_UNAVAILABLE"],
["start_failed", "ANTIGRAVITY_SIGN_IN_START_FAILED"],
["login_incomplete", "ANTIGRAVITY_SIGN_IN_LOGIN_INCOMPLETE"],
])("logs %s by its secret-free reason code", (reason, code) => {
startLocalBrowserLogin("google", "/tmp/attempt");
runner.start.mock.calls[0]![1]!.onFailure!(reason);
expect(runner.warn).toHaveBeenCalledExactlyOnceWith({ code }, "Google Antigravity sign-in failed");
});
it("does not log a cancelled attempt", () => {
startLocalBrowserLogin("google", "/tmp/attempt");
runner.start.mock.calls[0]![1]!.onFailure!("aborted");
expect(runner.warn).not.toHaveBeenCalled();
});
});
@@ -1,20 +1,12 @@
import path from "node:path";
import type { Db } from "@paperclipai/db";
import { antigravityApiKeyModels, type AiConnectionBinding } from "@paperclipai/shared";
import { AntigravityModelDiscoveryCleanupError, discoverAntigravityModels } from "../vendor/paperclip-runner/index.js";
import { AntigravityModelDiscoveryCleanupError, AntigravityRuntimeUnavailableError, discoverAntigravityModels } from "../vendor/paperclip-runner/index.js";
import { unprocessable } from "../errors.js";
import { logger } from "../middleware/logger.js";
import { prepareManagedAiRuntime } from "./ai-connection-runtime.js";
import { RetiredCredentialRecoveryError } from "./quota-credential-recovery.js";
import { retainGoogleCredentialCleanup } from "./retained-google-credential-cleanup.js";
function configuredRemoteProviderPackRoot(): string | undefined {
const raw = process.env.PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH?.trim();
if (!raw || raw.includes("\0") || !path.isAbsolute(raw)) return undefined;
const trimmed = raw.replace(/\/+$/, "") || "/";
return path.resolve(trimmed) === trimmed ? trimmed : undefined;
}
/** A Google API key's catalog does not depend on the key or the environment:
* the pinned runtime builds it locally. Suggestions only; an explicit model id
* stays accepted and native admission decides. */
@@ -49,13 +41,12 @@ export async function antigravityConnectionModels(db: Db, input: {
if (runtime.attribution.method !== "subscription") return antigravityApiKeyModelCatalog();
const home = runtime.config.env.GEMINI_HOME;
if (typeof home !== "string" || !home) throw unprocessable("The selected Google runtime account is unavailable.");
const providerPackageRoot = configuredRemoteProviderPackRoot();
try {
return (await (providerPackageRoot
? discoverAntigravityModels(home, { providerPackageRoot })
: discoverAntigravityModels(home))).models;
}
try { return (await discoverAntigravityModels(home)).models; }
catch (error) {
if (error instanceof AntigravityRuntimeUnavailableError) {
logger.warn({ companyId: input.companyId, code: error.code }, "Antigravity model discovery runtime is unavailable");
throw unprocessable("This server does not have the current Google Antigravity runtime, so Google account models cannot load. Use a Google API key instead, or update Paperclip on this server.", { code: error.code });
}
if (error instanceof AntigravityModelDiscoveryCleanupError) {
// The native owner retains the live child and immutable command lease.
// Keep this selected credential home until that owner proves retirement.
@@ -1,41 +0,0 @@
import { afterEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
startAntigravityBrowserLogin: vi.fn(() => ({ abort: async () => undefined })),
}));
vi.mock("../vendor/paperclip-runner/index.js", () => ({
resolveCodexCommand: vi.fn(),
startAntigravityBrowserLogin: mocks.startAntigravityBrowserLogin,
}));
import { startLocalBrowserLogin } from "./local-ai-browser-login.js";
afterEach(() => {
vi.unstubAllEnvs();
vi.clearAllMocks();
});
describe("startLocalBrowserLogin (google)", () => {
it("forwards normalized PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH to startAntigravityBrowserLogin", () => {
vi.stubEnv("PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH", "/opt/paperclip-runner/provider-pack/");
startLocalBrowserLogin("google", "/tmp/google-login-home");
expect(mocks.startAntigravityBrowserLogin).toHaveBeenCalledExactlyOnceWith("/tmp/google-login-home", {
providerPackageRoot: "/opt/paperclip-runner/provider-pack",
});
});
it("omits providerPackageRoot when PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH is unset or non-normalized", () => {
vi.stubEnv("PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH", "");
startLocalBrowserLogin("google", "/tmp/google-login-home");
expect(mocks.startAntigravityBrowserLogin).toHaveBeenLastCalledWith("/tmp/google-login-home");
vi.stubEnv("PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH", "/opt/paperclip-runner/../etc");
startLocalBrowserLogin("google", "/tmp/google-login-home");
expect(mocks.startAntigravityBrowserLogin).toHaveBeenLastCalledWith("/tmp/google-login-home");
vi.stubEnv("PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH", "relative/pack");
startLocalBrowserLogin("google", "/tmp/google-login-home");
expect(mocks.startAntigravityBrowserLogin).toHaveBeenLastCalledWith("/tmp/google-login-home");
});
});
+6 -11
View File
@@ -6,6 +6,7 @@ import { runSetupTokenLogin } from "@paperclipai/adapter-claude-local/server";
import { runDeviceLogin } from "@paperclipai/adapter-codex-local/server";
import { ensureCommandResolvable, resolveCommandForLogs } from "@paperclipai/adapter-utils/server-utils";
import { resolveCodexCommand, startAntigravityBrowserLogin } from "../vendor/paperclip-runner/index.js";
import { logger } from "../middleware/logger.js";
export type LocalBrowserLoginState = {
authorizationUrl?: string;
@@ -47,20 +48,14 @@ _, status = os.waitpid(pid, 0)
sys.exit(os.waitstatus_to_exitcode(status))
`;
function configuredRemoteProviderPackRoot(): string | undefined {
const raw = process.env.PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH?.trim();
if (!raw || raw.includes("\0") || !path.isAbsolute(raw)) return undefined;
const trimmed = raw.replace(/\/+$/, "") || "/";
return path.resolve(trimmed) === trimmed ? trimmed : undefined;
}
/** Run the same browser-code login used by sandbox connections on the local host. */
export function startLocalBrowserLogin(provider: "anthropic" | "openai" | "google", home: string): LocalBrowserLoginState {
if (provider === "google") {
const providerPackageRoot = configuredRemoteProviderPackRoot();
return providerPackageRoot
? startAntigravityBrowserLogin(home, { providerPackageRoot })
: startAntigravityBrowserLogin(home);
return startAntigravityBrowserLogin(home, {
onFailure: (reason) => {
if (reason !== "aborted") logger.warn({ code: `ANTIGRAVITY_SIGN_IN_${reason.toUpperCase()}` }, "Google Antigravity sign-in failed");
},
});
}
const controller = new AbortController();
const state: LocalBrowserLoginState = { abort: () => controller.abort() };
+2
View File
@@ -10,6 +10,7 @@
type RunnerModule = typeof import("@paperclipai/paperclip-runner");
export type {
AntigravityBrowserLoginFailureReason,
AntigravityBrowserLoginState,
GeneratedAntigravitySwarmChannel,
GeneratedAntigravitySwarmCredentialFacts,
@@ -244,6 +245,7 @@ export const GENERATED_ANTIGRAVITY_SWARM_DEFAULT_CHANNEL = runner.GENERATED_ANTI
export const readGeneratedAntigravitySwarmCredentialFacts = runner.readGeneratedAntigravitySwarmCredentialFacts;
export const discoverAntigravityModels = runner.discoverAntigravityModels;
export const AntigravityModelDiscoveryCleanupError = runner.AntigravityModelDiscoveryCleanupError;
export const AntigravityRuntimeUnavailableError = runner.AntigravityRuntimeUnavailableError;
export const PROVIDER_PACK_COMPATIBILITY = runner.PROVIDER_PACK_COMPATIBILITY;
export const bundledRemoteProviderPackManifestPath = runner.bundledRemoteProviderPackManifestPath;
export const bundledRemoteRunnerBinary = runner.bundledRemoteRunnerBinary;