mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 18:35:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The native Runner executes Google Antigravity on local hosts, Core managed sandboxes, and plugin Runner-task environments such as Paperclip Computer. > - Before this change, Paperclip refused Google sign-in on all remote targets even after release, returned an unavailable error when testing Antigravity on plugin Runner-task environments, and did not wire remote refresh-token write-back on Core sandboxes or released Antigravity profile resolution. > - Paperclip Cloud needs Google Antigravity to run with both Gemini API keys and Google sign-in on both plugin Runner-task environments and Core managed sandboxes once the profile flips from pending to qualified. > - This pull request lifts the released-state remote sign-in refusal, wires plugin Runner-task probing and released profile resolution for Antigravity, adds Core sandbox remote sign-in write-back and checkpoint exclusion, and keeps pending-release candidate grants restricted to API-key non-plugin targets. > - The benefit is that flipping the Antigravity profile from pending to qualified immediately enables picker selection, agent creation/save, Test probing, and execution with either Gemini API keys or Google sign-in on both plugin Runner-task environments and Core sandboxes. ## Linked Issues or Issue Description - Refs #22923 (Item 6 of `doc/plans/2026-11-25-antigravity-cloud-rollout.md`, gaps G6 and G7) - Pairs with #22933 (Item 2: Antigravity sign-in task credential and plugin write-back) and #22935 (Item 3: keep per-turn-only harnesses per-turn on warm environments) - Refs #22930 (Item 1: Gemini API key task credential for plugin Runners) ## What Changed - **Remote Google sign-in policy & credential preparation (`antigravity-connection-policy.ts`, `antigravity-runner-credentials.ts`)**: - Allow both Gemini API key and Google sign-in on remote targets in `antigravityConnectionRefusal` once `releasePending` is `false`, while keeping `lifecycleMode: "warm"` refused and keeping pending-release candidate grants API-key-only on non-plugin remote targets. - Strip all `GOOGLE_*` and non-selected `GEMINI_*` variables (plus `PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET`) in `prepareAntigravityRunnerCredentials`, enforce `antigravityConnectionRefusal` using `antigravityReleasePending()`, and pass pure sanitized sign-in JSON on remote runs (without local `/swarm` metadata). - **Core sandbox remote sign-in write-back & checkpoint safety (`native-credential-store.ts`, `native-session-executor.ts`, `antigravity-runner-credentials.ts`)**: - Extend `createNativeCredentialStore` to support `provider: "antigravity"` (`acp_token.json` and `auth-refresh.json`) over local and remote command runners. - Add optional `runtimeStore` support to `antigravityCredentialTurn` and wire it in `native-session-executor.ts` for Core remote sandboxes so rotated Google refresh tokens copy back after process retirement and remote credential files are scrubbed. - Exclude `antigravity-home/antigravity-acp/{acp_token.json,auth-refresh.json,auth-refresh.json.tmp,logs}` from remote ACPX session checkpoints. - Enforce `antigravityConnectionRefusal` in `preparePluginTaskOwner` and reject pending `pluginTask` execution in `assertAntigravityExecutionAdmissible` (defense in depth). - **Plugin Runner-task probing, released profile resolution & agent save/setup (`provider-profile.ts`, `plugin-runner-probe.ts`, `antigravity-connection-probe.ts`, `agent-environment-test.ts`, `agents.ts`, `NewAgentSetup.tsx`)**: - Add `antigravity` to `DEFAULT_ACPX_RUNNER_MODELS` and the qualified ACPX agent allowlist in `provider-profile.ts`, requiring an explicit non-placeholder model ID and checking `antigravityReleasePending()`. - Wire `testAntigravityConnection` to delegate plugin Runner-task targets to `probePluginRunnerEnvironment` instead of returning `"Google Antigravity is unavailable in this hosting environment."`, and update `probePluginRunnerEnvironment` to run `admissionOnly: true` for Antigravity with either Gemini API key or Google sign-in once released, returning `antigravity_metadata_verified`. - Allow Core sandbox/SSH `probeAntigravityExecutionTarget` for Google sign-in once released, preserve `antigravity_remote_runtime_ready` warn status in `agent-environment-test.ts` and `NewAgentSetup.tsx`. - Allow released Antigravity creation without `enableNativeRunner`, allow released remote sign-in account model discovery on the tenant host, and refuse pending plugin targets even when a `linux-x64` candidate grant exists. - Note on existing >1,000-line files: edits to `server/src/routes/agents.ts` and `server/src/services/native-runtime/native-session-executor.ts` are minimal wiring at existing Antigravity call sites (+12 and +26 net lines). - **Tests**: - Updated `antigravity-runner-credentials.test.ts`, `native-credential-store.test.ts`, `antigravity-save-refusal.test.ts`, `antigravity-connection-probe.test.ts`, `antigravity-release.test.ts`, `adapter-routes.test.ts`, `agent-runner-selection.test.ts`, `agent-environment-test-status.test.ts`, `native-session-executor.test.ts`, and `ui/src/lib/cloud-harness-policy.test.ts`. - Added `server/src/services/native-runtime/plugin-runner-probe-antigravity.test.ts`. ## Verification - Local Vitest (all passed against a released-profile fixture as well as the real pending profile): - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/antigravity-runner-credentials.test.ts src/services/native-runtime/native-credential-store.test.ts src/services/native-runtime/antigravity-release.test.ts src/services/native-runtime/plugin-runner-probe-antigravity.test.ts src/services/native-runtime/plugin-runner-probe-runner-mismatch.test.ts src/services/native-runtime/plugin-runner-credentials.test.ts src/__tests__/antigravity-connection-probe.test.ts src/__tests__/antigravity-save-refusal.test.ts src/__tests__/antigravity-managed-subscription.test.ts src/__tests__/antigravity-plugin-task-credential-writeback.test.ts src/services/agent-runner-selection.test.ts src/services/agent-environment-test-status.test.ts` (12 files, 425 tests passed) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/adapter-routes.test.ts --hookTimeout=60000` (36 passed) - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/agent-test-environment-routes.test.ts --hookTimeout=60000 -t "passes the selected Antigravity"` (1 passed) - `pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-session-executor.test.ts -t "projects the selected Antigravity subscription"` (2 passed) - `pnpm --filter @paperclipai/ui exec vitest run src/lib/cloud-harness-policy.test.ts` (36 passed) - Typechecks: - `pnpm --filter @paperclipai/server exec tsc --noEmit` (passed) - `pnpm --filter @paperclipai/ui typecheck` (passed) - Not run live: the real Antigravity profile remains `pending` until Item 8; live staging verification on Paperclip Computer and Core managed sandboxes is covered by Item 12. ## Risks - Low risk while the Antigravity profile remains `pending`: all new remote sign-in and plugin Runner-task paths stay gated behind `!antigravityReleasePending()`, and pending-release candidate behavior remains unchanged (and tighter on plugin environments). - Once Item 8 flips the profile to qualified, released Antigravity agents on Core sandboxes and plugin Runner-task environments will use the paths tested here; live acceptance on staging is gated by Items 9–12. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Google Gemini (Antigravity agent with tool use and code execution) ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
180 lines
13 KiB
TypeScript
180 lines
13 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import type { AdapterEnvironmentTestContext, AdapterEnvironmentTestResult } from "@paperclipai/adapter-utils";
|
|
import { runAdapterExecutionTargetShellCommand, type AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
|
|
import { NativeEnvironmentProbeCleanupError, QUALIFIED_ACPX_PROFILES, probeNativeRunnerEnvironment, resolveAcpxRuntimeRoot } from "../vendor/paperclip-runner/index.js";
|
|
import { logger } from "../middleware/logger.js";
|
|
import { antigravityRemoteCandidateAdmitted, resolveAntigravityCandidateAdmission } from "./native-runtime/acpx-qualification.js";
|
|
import { antigravityCredentialTurn, prepareAntigravityRunnerCredentials } from "./native-runtime/antigravity-runner-credentials.js";
|
|
import { antigravityConnectionRefusal } from "./native-runtime/antigravity-connection-policy.js";
|
|
import { antigravityReleasePending } from "./native-runtime/antigravity-release.js";
|
|
import { ANTIGRAVITY_PATCHED_CLOSURE_SHA256, antigravityProviderPackEntryRefusal } from "./native-runtime/remote-provider-pack.js";
|
|
import { resolvePaperclipRunnerBinary } from "./native-runtime/native-codex-runner.js";
|
|
import { probePluginRunnerEnvironment } from "./native-runtime/plugin-runner-probe.js";
|
|
|
|
const TRANSPORT_KEYS = ["PATH", "LANG", "LANGUAGE", "TZ", "TMPDIR", "TEMP", "TMP", "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", "ALL_PROXY"];
|
|
|
|
const asRecord = (value: unknown): Record<string, unknown> | null => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
|
|
|
|
/** Project only closed Rust admission categories from the private authenticated
|
|
* command result. Provider output and the outer serialized Error stay private.
|
|
*/
|
|
export function antigravityConnectionProbeFailure(companyId: string, error: unknown): AdapterEnvironmentTestResult {
|
|
if (error instanceof NativeEnvironmentProbeCleanupError) throw error;
|
|
const command = asRecord(asRecord(error)?.runnerCommandResult);
|
|
const result = command?.commandType === "session.open" && command.status === "failed" ? asRecord(command.result) : null;
|
|
const admission = result?.code === "command_execution_failed" && typeof result.message === "string" && result.message.length <= 2_048
|
|
? /^failed to start ACPX provider: ACPX sidecar command (?:initialize|session\.open) was rejected \(retryable=(true|false), classification=(admission_(?:binding|installation|sandbox|credential|configuration|skills|command|tool_bridge|runtime|identity|instructions))\)$/.exec(result.message)
|
|
: null;
|
|
const installation = admission?.[2] === "admission_installation";
|
|
const code = installation ? "antigravity_installation_check_failed" : "antigravity_admission_failed";
|
|
const errorClass = error instanceof Error && ["Error", "TypeError", "RangeError", "AggregateError"].includes(error.name) ? error.name : "Error";
|
|
logger.warn({ companyId, code, errorClass,
|
|
commandCode: admission ? "command_execution_failed" : "unclassified",
|
|
classification: admission?.[2] ?? "unclassified",
|
|
...(admission ? { retryable: admission[1] === "true" } : {}),
|
|
}, installation ? "Antigravity installation check failed before account verification" : "Antigravity runtime admission check failed");
|
|
return { adapterType: "paperclip_runner", status: "fail", testedAt: new Date().toISOString(), checks: [{ code, level: "error",
|
|
message: installation ? "Paperclip could not complete the local Google Antigravity installation check."
|
|
: "Google Antigravity could not complete its runtime check.",
|
|
hint: installation ? "The instance operator needs to repair this runtime before Test can verify your Google connection."
|
|
: "Retry Test. If it still fails, ask your Paperclip operator to inspect the runtime check.",
|
|
}] };
|
|
}
|
|
|
|
const failed = (code: string, message: string): AdapterEnvironmentTestResult => ({ adapterType: "paperclip_runner", status: "fail",
|
|
testedAt: new Date().toISOString(), checks: [{ code, level: "error", message }] });
|
|
|
|
const REMOTE_PACK_ROOTS = ["/opt/paperclip-runner/provider-pack", '"$HOME/.local/share/paperclip-runner/provider-pack"'];
|
|
|
|
/**
|
|
* A cloud environment runs Antigravity from its image's provider pack. Test
|
|
* proves that pack carries this release's patched Linux closure, exactly as run
|
|
* preparation admits it, without reading credentials there or sending a prompt.
|
|
* The run itself verifies the closure tree before launch.
|
|
*/
|
|
export async function probeAntigravityExecutionTarget(
|
|
target: Extract<AdapterExecutionTarget, { kind: "remote" }>,
|
|
options: { apiKey?: boolean } = {},
|
|
): Promise<AdapterEnvironmentTestResult> {
|
|
const unavailable = () => failed("antigravity_remote_runtime_missing",
|
|
"This cloud environment does not have the current Google Antigravity runtime. Use the current Paperclip runner image for this environment.");
|
|
if (target.transport === "sandbox" && target.runnerTask) {
|
|
return failed("antigravity_remote_runtime_missing", "Plugin Runner-task targets must be probed through the plugin Runner task API.");
|
|
}
|
|
const expectedPath = "provider-assets/antigravity/linux-x64";
|
|
const command = [
|
|
`for pack in ${REMOTE_PACK_ROOTS.join(" ")}; do`,
|
|
` if [ -f "$pack/provider-pack.json" ] && [ -d "$pack/${expectedPath}" ] && [ ! -L "$pack/${expectedPath}" ]; then`,
|
|
' uname -s; uname -m; head -c 262144 "$pack/provider-pack.json"; exit 0',
|
|
" fi",
|
|
"done",
|
|
"exit 127",
|
|
].join("\n");
|
|
let response: Awaited<ReturnType<typeof runAdapterExecutionTargetShellCommand>>;
|
|
try {
|
|
response = await runAdapterExecutionTargetShellCommand(`antigravity-pack-${randomUUID()}`, target, command,
|
|
{ cwd: target.remoteCwd, env: {}, timeoutSec: 20 });
|
|
} catch { return failed("antigravity_remote_check_failed", "Paperclip could not reach this cloud environment. Retry Test."); }
|
|
if (response.timedOut) return failed("antigravity_remote_check_failed", "Paperclip could not reach this cloud environment. Retry Test.");
|
|
if (response.exitCode !== 0) return unavailable();
|
|
const [os, arch, ...manifestLines] = response.stdout.split("\n");
|
|
if (os?.trim() !== "Linux" || arch?.trim() !== "x86_64") {
|
|
return failed("antigravity_remote_platform_unsupported", "Google Antigravity needs a Linux x64 cloud environment.");
|
|
}
|
|
let manifest: Record<string, unknown> | null;
|
|
try { manifest = asRecord(JSON.parse(manifestLines.join("\n"))); } catch { return unavailable(); }
|
|
const payload = asRecord(manifest?.payload);
|
|
// While pending, the image lists the candidate closure under candidateProviders.
|
|
const pending = antigravityReleasePending();
|
|
const inventory = pending ? "candidateProviders" : "providers";
|
|
const listed = asRecord(payload?.[inventory]), other = asRecord(payload?.[pending ? "providers" : "candidateProviders"]);
|
|
const entry = asRecord(listed?.antigravity);
|
|
const targetIdentity = asRecord(payload?.target);
|
|
if (!entry || entry.path !== expectedPath || entry.qualification !== (pending ? "pending" : "qualified")
|
|
|| typeof entry.version !== "string" || typeof entry.profileDigest !== "string" || typeof entry.closureDigest !== "string"
|
|
|| antigravityProviderPackEntryRefusal({ inventory, inBoth: Boolean(other?.antigravity),
|
|
target: { platform: String(targetIdentity?.platform), architecture: String(targetIdentity?.architecture) },
|
|
entry: { version: entry.version, profileDigest: entry.profileDigest, closureDigest: entry.closureDigest },
|
|
releasePending: pending, profile: QUALIFIED_ACPX_PROFILES.antigravity,
|
|
patchedClosures: ANTIGRAVITY_PATCHED_CLOSURE_SHA256 })) {
|
|
return unavailable();
|
|
}
|
|
return { adapterType: "paperclip_runner", status: "warn", testedAt: new Date().toISOString(),
|
|
checks: [{ code: "antigravity_remote_runtime_ready", level: "warn",
|
|
message: options.apiKey === false
|
|
? "This cloud environment has the verified Google Antigravity runtime. Google checks the selected Google sign-in and model when the agent first runs. No prompt was sent."
|
|
: "This cloud environment has the verified Google Antigravity runtime. Google checks the API key and the selected model when the agent first runs. No prompt was sent." }] };
|
|
}
|
|
|
|
/** The ordinary Test uses the selected connection and no model turn. */
|
|
export async function testAntigravityConnection(context: AdapterEnvironmentTestContext, model: string): Promise<AdapterEnvironmentTestResult> {
|
|
const configured = context.config.env;
|
|
const configuredKey = asRecord(configured)?.GEMINI_API_KEY;
|
|
const apiKey = typeof configuredKey === "string" && configuredKey.trim().length > 0;
|
|
const pending = antigravityReleasePending();
|
|
const target = context.executionTarget;
|
|
const remote = target?.kind === "remote";
|
|
const pluginRunnerTask = remote && target.transport === "sandbox" && Boolean(target.runnerTask);
|
|
const refusal = antigravityConnectionRefusal({ apiKey, remote, releasePending: pending,
|
|
remoteCandidateAdmitted: remote && !pluginRunnerTask && pending && antigravityRemoteCandidateAdmitted({ companyId: context.companyId, model }) });
|
|
if (refusal) return failed(refusal.code, refusal.message);
|
|
if (pluginRunnerTask) {
|
|
const managedConnection = asRecord(context.config.managedAiConnection);
|
|
const identity = typeof managedConnection?.identity === "string" ? managedConnection.identity : undefined;
|
|
const accountIdentity = typeof managedConnection?.sessionIdentity === "string" ? managedConnection.sessionIdentity : identity;
|
|
return probePluginRunnerEnvironment(context, identity
|
|
? { identity, accountIdentity: accountIdentity ?? identity, home: context.managedAiCredentialHome }
|
|
: undefined);
|
|
}
|
|
if (target?.kind === "remote") return probeAntigravityExecutionTarget(target, { apiKey });
|
|
// Only the pending candidate needs the operator's grant; a released profile carries none.
|
|
const admission = pending ? resolveAntigravityCandidateAdmission({ companyId: context.companyId, model,
|
|
target: { platform: process.platform, architecture: process.arch } }) : undefined;
|
|
if (pending && !admission) throw new Error("Google Antigravity is not available for this company.");
|
|
const environment = Object.fromEntries([
|
|
...TRANSPORT_KEYS.flatMap(key => typeof process.env[key] === "string" ? [[key, process.env[key]!]] : []),
|
|
...Object.entries(configured && typeof configured === "object" && !Array.isArray(configured) ? configured : {})
|
|
.filter((entry): entry is [string, string] => typeof entry[1] === "string"),
|
|
]);
|
|
const credentials = await prepareAntigravityRunnerCredentials({ environment, remote: false,
|
|
managedHome: context.managedAiCredentialHome, lifecycleMode: "per_turn" });
|
|
const runtimeDirectory = await realpath(await mkdtemp(join(tmpdir(), "paperclip-antigravity-setup-")));
|
|
const acpxRuntimeDirectory = join(runtimeDirectory, "acpx");
|
|
const nonce = randomUUID(), normalizedSessionId = `setup-${nonce}`;
|
|
let nativeHome: string, runnerBinary: string;
|
|
try {
|
|
await mkdir(acpxRuntimeDirectory, { mode: 0o700 });
|
|
nativeHome = join(await resolveAcpxRuntimeRoot(acpxRuntimeDirectory, normalizedSessionId), "antigravity-home");
|
|
runnerBinary = resolvePaperclipRunnerBinary();
|
|
} catch (error) {
|
|
await rm(runtimeDirectory, { recursive: true, force: true });
|
|
throw error;
|
|
}
|
|
const turn = credentials.home && credentials.credential
|
|
? antigravityCredentialTurn({ managedHome: credentials.home, runtimeHome: nativeHome, credential: credentials.credential }) : undefined;
|
|
const receipt = await probeNativeRunnerEnvironment({ runtimeDirectory, provider: "acpx", model,
|
|
environment: credentials.environment, admissionOnly: true, timeoutMs: 45_000,
|
|
transportOptions: { runnerBinary, externallySandboxed: false,
|
|
acpxAgent: "antigravity", ...(admission ? { acpxCandidateAdmission: admission } : {}), acpxRuntimeDirectory,
|
|
acpxPermissionMode: "approve-reads", acpxPermissionModePinned: true,
|
|
prpIdentity: { runnerInstanceId: `setup-runner-${nonce}`, runId: `setup-${nonce}`, normalizedSessionId,
|
|
environmentLeaseId: `setup-lease-${nonce}`, turnId: `setup-turn-${nonce}`, itemId: `setup-item-${nonce}` } },
|
|
onCleanupConfirmed: async () => {
|
|
// The native owner proves physical retirement before this callback.
|
|
await turn?.copyBack();
|
|
await turn?.remove();
|
|
await rm(runtimeDirectory, { recursive: true, force: true });
|
|
},
|
|
});
|
|
if (receipt.provider !== "acpx" || receipt.providerDriver !== "acpx_runtime" || receipt.effectiveModel !== model
|
|
|| receipt.sessionAdmissionPassed !== true || receipt.admissionOnly !== true || receipt.helloProbePassed !== false) {
|
|
throw new Error("The selected Google runtime returned no matching account and model admission receipt.");
|
|
}
|
|
return { adapterType: "paperclip_runner", status: "pass", testedAt: new Date().toISOString(),
|
|
checks: [{ code: "antigravity_metadata_verified", level: "info",
|
|
message: "Google Antigravity verified the selected connection and exact model. No model prompt was sent." }] };
|
|
}
|