Support live Antigravity credential writeback for both token stores (#23397)

## Thinking Path

> - Paperclip manages the connections agents use to work.
> - A run can outlive the Google refresh token that started it.
> - Antigravity writes a rotated token to a private file. Its two
runtimes use different paths and JSON layouts.
> - The task already records which connection supplied its sign-in.
> - Runner reports a rotation on PRP. Core saves it to that connection
if the saved generation still matches.
> - The next run can start with the rotated token.

## Linked Issues or Issue Description

Refs #23395. Refs #23168.

This PR targets `master` and includes the capability-based handler from
#23395. Merging this PR lands the handler and Antigravity writeback
together.

**Current behavior**

A managed Antigravity sign-in reaches the plugin as an environment
credential. Core waits for task retirement to collect a refresh.

**Proposed behavior**

Seed a private auth-file. Observe refresh-token changes for the ordinary
ACP server and the unified CLI. Use the existing credential update event
to save them during execution.

**Reason and benefit**

A long-running task can keep its source connection current across
successive rotations.

## What Changed

- Dispatch PRP credential updates to the live writeback capability
declared for the bound harness and execution target.
- Send Antigravity subscriptions as auth-file credentials to environment
task providers. Keep Gemini API keys and previously admitted environment
credentials on their existing paths.
- Watch the ACP token file and the unified CLI token file. Compare the
refresh token, copy it to the bound file, and emit the existing
secret-free event.
- Bind writeback to the original grant, secret, session epoch, and
credential generation. Save the next generation in the same transaction.

## Verification

- Reproduced the failed final Google save hanging on the next session
close. After commit `2b3e7897cd`, both focused cleanup suites passed (43
tests). The regression covers two overlapping close retries after the
credential home is released and checks that the saved credential is
removed only after persistence succeeds.
- All 21 Rust observer tests passed on both builds. They cover
interruption between the host file and event journal writes, a further
rotation before restart, and a reconnect that supersedes the task.
- On the legacy build, 422 Runner TypeScript tests passed. With the
merged unified CLI on this branch, all 126 tests in the auth, credential
staging, and runtime host suites passed.
- The two plugin writeback database suites passed (39 tests). A refresh
that starts before task stop cannot overwrite the final token after
stop.
- One run timed out in an unrelated process-retirement test. All three
suites passed together on repeat. All OAuth documents in these tests are
fixtures. No live Google sign-in was exercised.

## Risks

- The agent and any process it starts are trusted not to substitute
another account’s refresh token in the harness credential file. Core
accepts the file’s refresh token for the original connection only while
the grant, secret, session epoch, and expected credential generation
still match. Substitution within that boundary is an accepted risk.
[Review
finding](https://github.com/paperclipai/paperclip/pull/23397#discussion_r4759261984)
- Deploy with a plugin and Launcher that support the new auth-file
provider. This branch includes the unified CLI from #23168 and still
observes the legacy token format.

> 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

OpenAI GPT-6 in Codex, with local code execution and GitHub CLI.

## 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>
This commit is contained in:
Nicky LeachandPaperclip authored and GitHub committed 2026-12-02 01:49:46 +00:00
1 parent c47452699a
commit 9092b0c667
34 files changed
+764 -207

No files matched your search

@@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
import { mkdtemp, realpath, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { and, eq } from "drizzle-orm";
import { and, eq, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import {
activityLog, agents, companies, companyMemberships, connectionGrants, createDb, environmentLeases, environments, heartbeatRuns, plugins, toolConnections,
@@ -10,7 +10,7 @@ import {
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { aiConnectionService } from "../services/ai-connections.js";
import { prepareManagedAiRuntime } from "../services/ai-connection-runtime.js";
import { registerPluginTaskCredentialHandoff } from "../services/plugin-task-credential-writeback.js";
import { registerPluginTaskCredentialHandoff, syncPluginTaskCredentialHandoff } from "../services/plugin-task-credential-writeback.js";
import { settleDispatchedEnvironmentTask } from "../services/environment-task-runtime.js";
import { secretService } from "../services/secrets.js";
import { preparePluginRunnerCredentials } from "../services/native-runtime/plugin-runner-credentials.js";
@@ -57,7 +57,7 @@ suite("Google sign-in task credential writeback for plugin Runners", () => {
afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); });
afterEach(() => { vi.unstubAllGlobals(); secretRead.fail = false; Object.assign(google, { email: "alice@example.test", rotate: undefined, fail: false, calls: 0 }); });
async function fixture(saved = signIn("fixture-original", { project_id: "fixture-project" })) {
async function fixture(saved = signIn("fixture-original", { project_id: "fixture-project" }), authFile = false) {
stubGoogle();
const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), pluginId = randomUUID(), environmentId = randomUUID(), leaseId = randomUUID();
const owner = `fixture-${randomUUID()}`;
@@ -79,7 +79,7 @@ suite("Google sign-in task credential writeback for plugin Runners", () => {
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "manual", status: "running" });
await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, provider: `plugin:${pluginId}:tasks`, providerLeaseId: "fixture-task", status: "active",
metadata: { driver: "plugin", pluginId, driverKey: "tasks", runnerTaskLease: true, runnerTaskDispatched: true, runnerTaskExecutionStopped: false } });
await registerPluginTaskCredentialHandoff(db, { companyId, leaseId }, managed.sessionIdentity, managed.credentialWriteback!);
await registerPluginTaskCredentialHandoff(db, { companyId, leaseId }, managed.sessionIdentity, managed.credentialWriteback!, authFile ? "antigravity" : undefined);
await managed.cleanup();
const calls: string[] = [];
let exported: unknown = { type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: signIn("fixture-refreshed", { project_id: "fixture-project" }) } };
@@ -102,7 +102,7 @@ suite("Google sign-in task credential writeback for plugin Runners", () => {
const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, grant!.connectionId));
return service.credential({ connection: connection!, grant: grant! });
};
return { companyId, owner, managed, transfer, calls, lease, activity, credential,
return { companyId, leaseId, owner, managed, transfer, calls, lease, activity, credential,
exportCredential(value: unknown) { exported = value; },
failExport(value: boolean) { failExport = value; },
settle: () => settleDispatchedEnvironmentTask(db, workers, { companyId, id: leaseId }) };
@@ -113,11 +113,45 @@ suite("Google sign-in task credential writeback for plugin Runners", () => {
it("delivers the sanitized saved sign-in and binds writeback to its exact generation", async () => {
const saved = signIn("fixture-original", { project_id: "fixture-project" });
const f = await fixture(saved);
expect(f.transfer).toMatchObject({ needsWriteback: true, credential: { type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: saved } } });
expect(f.transfer).toMatchObject({ writeback: { mode: "live", requiresGoogleGeneration: true }, credential: { type: "auth-file", provider: "antigravity", content: saved } });
expect(f.managed.credentialWriteback).toMatchObject({ google: { credentialSha256: createHash("sha256").update(saved).digest("hex") } });
expect(leaked(JSON.stringify((await f.lease()).metadata))).toEqual([]);
});
it("saves successive live rotations to the seeded connection and discards updates after reconnect", async () => {
const f = await fixture(undefined, true);
const sync = (token: string) => syncPluginTaskCredentialHandoff(db, f, async () => ({
type: "auth-file", provider: "antigravity", content: signIn(token),
}));
expect(await sync("fixture-refreshed")).toBe("rotated");
expect(await sync("fixture-refreshed")).toBe("unchanged");
expect(await sync("fixture-rotated")).toBe("rotated");
expect(await f.credential()).toBe(signIn("fixture-rotated", { project_id: "fixture-project" }));
expect(google.calls).toBe(0);
await secretService(db).rotate(f.managed.credentialWriteback!.secretId, { value: signIn("fixture-reconnected") }, { userId: f.owner });
expect(await sync("fixture-other")).toBe("binding_changed");
expect(await f.credential()).toBe(signIn("fixture-reconnected"));
});
it("keeps a live export that overlaps task stop from consuming the final generation", async () => {
const f = await fixture(undefined, true);
const file = (token: string) => ({ type: "auth-file" as const, provider: "antigravity" as const, content: signIn(token) });
const live = syncPluginTaskCredentialHandoff(db, f, async () => {
await db.update(environmentLeases).set({
metadata: sql`${environmentLeases.metadata} || '{"runnerTaskExecutionStopped":true}'::jsonb`,
}).where(eq(environmentLeases.id, f.leaseId));
return file("fixture-refreshed");
});
await expect(live).rejects.toThrow("authority changed");
const exportAfterStop = vi.fn(async () => file("fixture-refreshed"));
await syncPluginTaskCredentialHandoff(db, f, exportAfterStop);
expect(exportAfterStop).not.toHaveBeenCalled();
f.exportCredential(file("fixture-rotated"));
expect(await f.settle()).toBe("completed");
expect(await f.credential()).toBe(signIn("fixture-rotated", { project_id: "fixture-project" }));
expect((await f.lease()).metadata?.runnerTaskCredentialHandoff).toMatchObject({ state: "complete", outcome: "rotated" });
});
it("saves a rotated refresh token for the same Google account and records it without the token", async () => {
const f = await fixture();
expect(await f.settle()).toBe("completed");
@@ -150,7 +150,7 @@ suite("durable plugin task credential handoff", () => {
payload: { schema: "paperclip.auth.credentials.updated.v1", provider: "codex", bindingId: "harness-auth", revision: 1, detection: "credential_store" },
};
const notification = { companyId: f.companyId, agentId: f.agentId, runnerInstanceId, normalizedSessionId,
event, synchronizeCredentials: f.synchronize };
event, liveWriteback: { provider: "codex", synchronize: f.synchronize } };
f.failExport(true);
await expect(appendNativeCredentialUpdate(db, notification)).rejects.toThrow();
expect(await f.credential()).toBe(auth("fixture-original"));
@@ -547,7 +547,7 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin
const target = context.executionTarget;
if (managed.credentialWriteback && target?.kind === "remote" && target.transport === "sandbox" && target.runnerTask && target.leaseId) {
await registerPluginTaskCredentialHandoff(db, { companyId: context.companyId, leaseId: target.leaseId }, managed.sessionIdentity, managed.credentialWriteback,
binding.provider === "xai" ? "grok" : undefined);
managed.credentialWriteback.google ? "antigravity" : binding.provider === "xai" ? "grok" : undefined);
}
const result = await probeManagedEnvironment(adapterType, context, binding, managed);
// A provider rejection invalidates the tested credential generation. A
@@ -6,8 +6,8 @@ import { createHash } from "node:crypto";
import { mkdir, mkdtemp, writeFile, rm, realpath } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { decideCodexAuthMerge, readSubscriptionAccountId, withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server";
import { decideGrokAuthMerge, parseGrokAuthPayload, hasUsableGrokAuthValue } from "@paperclipai/adapter-grok-local/server";
import { copyBackCodexAuth, decideCodexAuthMerge, readSubscriptionAccountId, withAccountHomeSecretMutationLock } from "@paperclipai/adapter-codex-local/server";
import { copyBackGrokAuth, decideGrokAuthMerge, parseGrokAuthPayload, hasUsableGrokAuthValue } from "@paperclipai/adapter-grok-local/server";
import { WORKSPACE_RESTORE_LOCK_TIMEOUT_CODE } from "@paperclipai/adapter-utils/workspace-restore-merge";
import { aiConnectionService } from "./ai-connections.js";
import { secretService } from "./secrets.js";
@@ -24,15 +24,44 @@ export const managedAiCredentialWritebackBindingSchema = z.object({
}).strict();
export type ManagedAiCredentialWritebackBinding = z.infer<typeof managedAiCredentialWritebackBindingSchema>;
type ReadAuth = () => Promise<Buffer>;
const authFileStrategies = {
codex: {
provider: "codex", connectionProvider: "openai", decideMerge: decideCodexAuthMerge,
usable: (content: string) => readSubscriptionAccountId(Buffer.from(content)) !== null,
copyBack: async (home: string, readSandboxAuth: ReadAuth) => {
await copyBackCodexAuth({ hostAuthPath: join(home, "auth.json"), readSandboxAuth, log: () => {} });
},
},
grok: {
provider: "grok", connectionProvider: "xai", decideMerge: decideGrokAuthMerge,
usable: (content: string) => {
try {
const parsed = parseGrokAuthPayload(JSON.parse(content));
return parsed !== null && hasUsableGrokAuthValue(parsed.value);
} catch { return false; }
},
copyBack: async (home: string, readSandboxAuth: ReadAuth) => {
await copyBackGrokAuth({ hostHomeDir: home, readSandboxAuth, log: () => {} });
},
},
} as const;
export function managedAuthFileStrategy(harness: string) {
return Object.hasOwn(authFileStrategies, harness) ? authFileStrategies[harness as keyof typeof authFileStrategies] : undefined;
}
/** Credential ownership survives the invocation home; reconnects and revocations win. */
export async function syncManagedAiCredentials(
db: Db,
companyId: string,
binding: ManagedAiCredentialWritebackBinding,
provider: "codex" | "grok",
provider: keyof typeof authFileStrategies,
fetchCredential: () => Promise<string | null>,
) {
managedAiCredentialWritebackBindingSchema.parse(binding);
const strategy = authFileStrategies[provider];
const home = await mkdtemp(join(await realpath(tmpdir()), "paperclip-ai-credential-"));
try {
// Revocation or an explicit account replacement intentionally discards an old refresh.
@@ -52,7 +81,7 @@ export async function syncManagedAiCredentials(
eq(toolConnections.companyId, companyId), eq(toolConnections.id, grant.connectionId),
));
const ai = aiConnectionMetadataSchema.safeParse(connection?.config.ai);
if (!connection || !ai.success || ai.data.provider !== (provider === "codex" ? "openai" : "xai") || ai.data.method !== "subscription") return null;
if (!connection || !ai.success || ai.data.provider !== strategy.connectionProvider || ai.data.method !== "subscription") return null;
return { connection, grant };
};
const mutate = <T>(operation: (database: Db) => Promise<T>) => withAccountHomeSecretMutationLock(
@@ -64,15 +93,7 @@ export async function syncManagedAiCredentials(
const credential = await fetchCredential();
if (credential === null) return "no_credentials" as const;
// A partial provider write must replay, not be acknowledged as unchanged.
let usable = false;
if (provider === "codex") usable = readSubscriptionAccountId(Buffer.from(credential)) !== null;
else {
try {
const parsed = parseGrokAuthPayload(JSON.parse(credential));
usable = parsed !== null && hasUsableGrokAuthValue(parsed.value);
} catch { /* Do not expose credential bytes through JSON parser errors. */ }
}
if (!usable) throw new Error("Managed credential snapshot invalid");
if (!strategy.usable(credential)) throw new Error("Managed credential snapshot invalid");
const incoming = join(home, "incoming.json"), destination = join(home, "current.json");
await writeFile(incoming, credential, { mode: 0o600 });
const writeBack = () => mutate(async database => {
@@ -80,7 +101,7 @@ export async function syncManagedAiCredentials(
if (!selected) return "binding_changed" as const;
const value = await aiConnectionService(database).credential(selected);
await writeFile(destination, value, { mode: 0o600 });
if (await (provider === "codex" ? decideCodexAuthMerge : decideGrokAuthMerge)(incoming, destination, { errorLabel: "AI account refresh" }) !== 10) return "unchanged" as const;
if (await strategy.decideMerge(incoming, destination, { errorLabel: "AI account refresh" }) !== 10) return "unchanged" as const;
await secretService(database).rotate(binding.secretId, {
value: credential, preserveAiSessionEpoch: true,
}, { userId: selected.grant.subjectUserId });
@@ -108,6 +129,10 @@ export async function syncManagedAntigravityCredential(
companyId: string,
binding: ManagedAiCredentialWritebackBinding,
fetchCredential: () => Promise<string | null>,
seeded?: {
expectedHash: string;
advance: (database: Db, nextHash: string) => Promise<void>;
},
) {
const base = managedAiCredentialWritebackBindingSchema.parse(binding).google?.credentialSha256;
if (!base) throw new Error("Managed credential binding is not a Google sign-in");
@@ -132,7 +157,7 @@ export async function syncManagedAntigravityCredential(
let stored: string;
try { stored = sanitizeAntigravityCredential(saved); }
catch { return null; }
if (createHash("sha256").update(stored, "utf8").digest("hex") !== base) return null;
if (createHash("sha256").update(stored, "utf8").digest("hex") !== (seeded?.expectedHash ?? base)) return null;
return { connection, grant, stored };
};
const mutate = <T>(operation: (database: Db) => Promise<T>) => withAccountHomeSecretMutationLock(
@@ -146,6 +171,23 @@ export async function syncManagedAntigravityCredential(
try { incoming = sanitizeAntigravityCredential(credential); }
catch { throw new Error("Managed credential snapshot invalid"); }
if (incoming === current.stored) return "unchanged" as const;
if (seeded) {
const previous = JSON.parse(current.stored);
const token = JSON.parse(incoming).refresh_token;
if (token === previous.refresh_token) return "unchanged" as const;
const rotated = sanitizeAntigravityCredential(JSON.stringify({ ...previous, refresh_token: token }));
return mutate(async database => {
const selected = await account(database);
if (!selected) return "binding_changed" as const;
await secretService(database).rotate(binding.secretId, { value: rotated, preserveAiSessionEpoch: true },
{ userId: selected.grant.subjectUserId });
await seeded.advance(database, antigravityCredentialSha256(rotated));
await logActivity(database, { companyId, actorType: "system", actorId: "credential_refresh",
action: "ai_connection.credential_refreshed", entityType: "tool_connection", entityId: selected.connection.id,
details: { provider: "google", grantId: selected.grant.id } });
return "rotated" as const;
});
}
const accountEmail = current.grant.providerTenant?.name;
const refuse = async (reason: string) => {
await mutate(database => logActivity(database, { companyId, actorType: "system", actorId: "credential_refresh",
@@ -152,8 +152,9 @@ describe("Antigravity run start once the profile is released", () => {
runnerExecutionTarget: pluginTarget() });
await backend.options!.codexTransportFactory!();
expect(ownerFactory).toHaveBeenCalledOnce();
expect(ownerFactory).toHaveBeenCalledWith(expect.objectContaining({ credential: { type: "provider-env", provider: "antigravity",
environment: method === "api_key" ? { GEMINI_API_KEY: "fixture-gemini" } : { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: signIn } } }));
expect(ownerFactory).toHaveBeenCalledWith(expect.objectContaining({ credential: method === "api_key"
? { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } }
: { type: "auth-file", provider: "antigravity", content: signIn } }));
expect(handoff).toHaveBeenCalledTimes(method === "sign_in" ? 1 : 0);
} finally {
handoff.mockRestore();
@@ -7,7 +7,7 @@ import { antigravityAccountDigest, antigravityCredentialTurn, antigravitySwarmCh
import { sanitizeAntigravityCredential } from "../../vendor/paperclip-runner/index.js";
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 { bindRetainedGoogleCredentialHome, reconcileRetainedGoogleCleanup } 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";
@@ -273,6 +273,28 @@ describe("Antigravity managed Runner credentials", () => {
expect(await readFile(destination, "utf8")).toBe(credential("fixture-refreshed"));
await expect(access(source)).rejects.toMatchObject({ code: "ENOENT" });
});
it("retries a failed final Google save through the retained account cleanup", async () => {
const managedHome = await home(), runtimeHome = await home();
const scope = { companyId: "company", accountKey: managedHome };
const release = bindRetainedGoogleCredentialHome(managedHome, scope);
const persist = vi.fn().mockRejectedValueOnce(new Error("save failed")).mockResolvedValue(undefined);
const runtimeStore = { read: vi.fn(), remove: vi.fn() };
const close = vi.fn(async () => {});
const session = bindAntigravityCredentialTurn({ close } as unknown as NativeSession, {
managedHome, runtimeHome, credential: credential("fixture-original"), runtimeStore,
saveRotation: async () => { await reconcileRetainedGoogleCleanup(scope); await persist(); },
});
try {
await expect(session.close({ reason: "final save" })).rejects.toThrow("save failed");
expect(runtimeStore.remove).not.toHaveBeenCalled();
} finally { release(); }
const retry = () => session.close({ reason: "retry final save" });
await Promise.all([retry(), retry()]);
await reconcileRetainedGoogleCleanup(scope);
expect(persist).toHaveBeenCalledTimes(2);
expect(runtimeStore.remove).toHaveBeenCalledOnce();
expect(close).toHaveBeenCalledOnce();
});
it("settles the retained runtime refresh before reusing its original home", async () => {
const managedHome = await home(), runtimeHome = await home();
const release = bindRetainedGoogleCredentialHome(managedHome, { companyId: "company", accountKey: managedHome });
@@ -178,6 +178,7 @@ export function antigravityCredentialTurn(input: {
managedHome: string;
runtimeHome: string;
credential: string;
saveRotation?: () => Promise<void>;
/** Remote Core sandbox runs export and scrub rotated tokens over the sandbox runner. */
runtimeStore?: { read: () => Promise<string>; remove: () => Promise<void> };
}) {
@@ -376,7 +377,8 @@ export function bindAntigravityCredentialTurn(session: NativeSession, input: Par
await proveRetirement();
retired = true;
};
const retain = () => retainGoogleCredentialCleanupForHome(input.managedHome, {
let retryHandoff: (() => Promise<void>) | undefined;
const retain = () => retryHandoff ??= retainGoogleCredentialCleanupForHome(input.managedHome, {
cleanup: handoff, ...(retired ? {} : { retired: retirement, ...(proveRetirement ? { retryRetirement } : {}) }),
});
const retire: NativeSession["close"] = options => retirement ??= Promise.resolve().then(() => close(options)).catch(error => {
@@ -395,7 +397,7 @@ export function bindAntigravityCredentialTurn(session: NativeSession, input: Par
await retire({ reason: "Google Antigravity subscription credential handoff" });
retired = true;
}
if (!copied) { await callbacks.copyBack(); copied = true; }
if (!copied) { await (input.saveRotation ?? callbacks.copyBack)(); copied = true; }
if (!removed) { await callbacks.remove(); removed = true; }
} catch (error) {
// Until copy-back succeeds, this private runtime can hold the only valid
@@ -416,7 +418,7 @@ export function bindAntigravityCredentialTurn(session: NativeSession, input: Par
await managedClose(options);
// The shared turn manager settles a failed turn once. Google retains its
// failed handoff, so a later close also retries the original private files.
if (!removed) await handoff();
if (!removed) await (retryHandoff ?? handoff)();
};
return session;
}
@@ -8,7 +8,7 @@ import { createNativeCredentialStore } from "./native-credential-store.js";
const execute = promisify(execFile), roots: string[] = [];
afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });
async function fixture(target: "local" | "ssh" | "sandbox", provider: "codex" | "grok" | "antigravity" = "codex") {
async function fixture(target: "local" | "ssh" | "sandbox", filename: "auth.json" | "acp_token.json" = "auth.json") {
const root = await realpath(await mkdtemp(join(tmpdir(), "native-credential-store-"))); roots.push(root);
const localHome = join(root, "local"), remoteHome = join(root, "remote");
await mkdir(localHome); await mkdir(remoteHome);
@@ -22,7 +22,7 @@ async function fixture(target: "local" | "ssh" | "sandbox", provider: "codex" |
return { exitCode: (error as { code: number }).code, stdout: "", stderr: "" };
}
}) };
return { home, runner, store: createNativeCredentialStore({ provider, localHome,
return { home, runner, store: createNativeCredentialStore({ filename, localHome,
...(target === "local" ? {} : { remoteHome, runner: runner as never }) }) };
}
@@ -35,8 +35,8 @@ it.each(["local", "ssh", "sandbox"] as const)("exports %s snapshots only on dema
await expect(store.read()).rejects.toMatchObject({ code: "ENOENT" });
});
it.each((["codex", "grok", "antigravity"] as const).flatMap(provider => (["local", "ssh", "sandbox"] as const).map(target => ({ provider, target }))))("uses the $provider close handoff for $target when primary token file is absent", async ({ target, provider }) => {
const { home, store } = await fixture(target, provider);
it.each((["auth.json", "acp_token.json"] as const).flatMap(filename => (["local", "ssh", "sandbox"] as const).map(target => ({ filename, target }))))("uses the $filename close handoff for $target when primary token file is absent", async ({ target, filename }) => {
const { home, store } = await fixture(target, filename);
await writeFile(join(home, "auth-refresh.json"), '{"synthetic":"refresh"}', { mode: 0o600 });
expect(await store.read()).toBe('{"synthetic":"refresh"}');
await store.remove();
@@ -44,7 +44,7 @@ it.each((["codex", "grok", "antigravity"] as const).flatMap(provider => (["local
});
it.each(["local", "ssh", "sandbox"] as const)("reads and removes antigravity acp_token.json on %s targets", async target => {
const { home, store } = await fixture(target, "antigravity");
const { home, store } = await fixture(target, "acp_token.json");
await writeFile(join(home, "acp_token.json"), '{"refresh_token":"synthetic"}', { mode: 0o600 });
expect(await store.read()).toBe('{"refresh_token":"synthetic"}');
await store.remove();
@@ -52,7 +52,7 @@ it.each(["local", "ssh", "sandbox"] as const)("reads and removes antigravity acp
});
it.each(["local", "ssh", "sandbox"] as const)("rejects unsafe %s files without falling back to another credential", async target => {
const { home, store } = await fixture(target, "grok");
const { home, store } = await fixture(target, "auth.json");
await writeFile(join(home, "auth-refresh.json"), "must-not-read", { mode: 0o600 });
await writeFile(join(home, "auth.json"), "unsafe", { mode: 0o644 });
await expect(store.read()).rejects.toThrow();
@@ -66,7 +66,7 @@ it.each(["local", "ssh", "sandbox"] as const)("rejects unsafe %s files without f
it("rejects truncated remote replies and timeouts", async () => {
const runner = { execute: vi.fn(async () => ({ exitCode: 0, stdout: "not-base64!", timedOut: false })) };
const store = createNativeCredentialStore({ provider: "codex", localHome: "/unused", remoteHome: "/owned", runner: runner as never });
const store = createNativeCredentialStore({ filename: "auth.json", localHome: "/unused", remoteHome: "/owned", runner: runner as never });
await expect(store.read()).rejects.toThrow("export invalid");
runner.execute.mockResolvedValue({ exitCode: 0, stdout: "", timedOut: true });
await expect(store.read()).rejects.toThrow("export unavailable");
@@ -37,13 +37,12 @@ try {
}`;
export function createNativeCredentialStore(input: {
provider: "codex" | "grok" | "antigravity";
filename: "auth.json" | "acp_token.json" | "antigravity-oauth-token";
localHome: string;
remoteHome?: string;
runner?: Pick<CommandManagedRuntimeRunner, "execute">;
}) {
if (Boolean(input.remoteHome) !== Boolean(input.runner)) throw new Error("native_credential_store_target_unavailable");
const names = input.provider === "antigravity" ? ["acp_token.json", "auth-refresh.json"] : ["auth.json", "auth-refresh.json"];
const read = async (name: string): Promise<string> => {
if (!input.runner || !input.remoteHome) return readLocalAiCredentialFile(join(input.localHome, name));
// Remote isolated-home preparation already requires Node. Read only on a refresh or retirement.
@@ -57,14 +56,14 @@ export function createNativeCredentialStore(input: {
};
return {
read: async () => {
try { return await read(names[0]!); }
try { return await read(input.filename); }
catch (error) {
if (names.length !== 2 || (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
return read(names[1]!);
if (input.filename === "antigravity-oauth-token" || (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
return read("auth-refresh.json");
}
},
remove: async () => {
for (const name of [...names, "auth-refresh.json.tmp"]) {
for (const name of [input.filename, "auth-refresh.json", "auth-refresh.json.tmp"]) {
await rm(join(input.localHome, name), { force: true });
if (input.runner && input.remoteHome) {
const result = await input.runner.execute({ command: "rm", args: ["-f", "--", posix.join(input.remoteHome, name)], bypassSession: true, timeoutMs: 10_000 });
@@ -66,14 +66,28 @@ it("retries credential writeback after the event is durably recorded", async ()
const synchronizeCredentials = vi.fn().mockRejectedValueOnce(new Error("synthetic writeback failure"))
.mockResolvedValue(undefined);
const update = { ...event, sourceSeq: 10, sourceEventId: "credential_update_retry", payload: { ...event.payload, revision: 2 } };
await expect(appendNativeCredentialUpdate(db, { ...binding, event: update, synchronizeCredentials }))
const liveWriteback = { provider: "codex", synchronize: synchronizeCredentials };
await expect(appendNativeCredentialUpdate(db, { ...binding, event: update, liveWriteback }))
.rejects.toThrow("synthetic writeback failure");
await appendNativeCredentialUpdate(db, { ...binding, event: update, synchronizeCredentials });
await appendNativeCredentialUpdate(db, { ...binding, event: update, liveWriteback });
expect(synchronizeCredentials).toHaveBeenCalledTimes(2);
const rows = await db.select().from(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, runId));
expect(rows.filter(row => row.sourceEventId === `credentials:${update.sourceEventId}`)).toHaveLength(1);
synchronizeCredentials.mockClear();
await expect(appendNativeCredentialUpdate(db, { ...binding, companyId: randomUUID(), event: update, synchronizeCredentials }))
await expect(appendNativeCredentialUpdate(db, { ...binding, companyId: randomUUID(), event: update, liveWriteback }))
.rejects.toThrow("binding_mismatch");
expect(synchronizeCredentials).not.toHaveBeenCalled();
});
it("dispatches only the selected harness-auth live writeback capability", async () => {
const synchronize = vi.fn(async () => {});
const update = { ...event, sourceSeq: 11, sourceEventId: "new-harness-update",
payload: { ...event.payload, provider: "fixture-harness" } };
const input = { ...binding, event: update, liveWriteback: { provider: "fixture-harness", synchronize } };
await appendNativeCredentialUpdate(db, input);
expect(synchronize).toHaveBeenCalledOnce();
for (const payload of [{ ...update.payload, provider: "other" }, { ...update.payload, bindingId: "other" }]) {
await expect(appendNativeCredentialUpdate(db, { ...input, event: { ...update, payload } })).rejects.toThrow("mismatch");
}
expect(synchronize).toHaveBeenCalledOnce();
});
@@ -3,13 +3,15 @@ import { heartbeatRuns, type Db } from "@paperclipai/db";
import { validatePrpEvent, type PrpEvent, type NativeSession } from "../../vendor/paperclip-runner/index.js";
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
export type LiveCredentialWriteback = { provider: string; synchronize: () => Promise<unknown> };
export async function appendNativeCredentialUpdate(db: Db, input: {
companyId: string;
agentId: string;
normalizedSessionId: string;
runnerInstanceId: string;
event: PrpEvent;
synchronizeCredentials?: () => Promise<unknown>;
liveWriteback?: LiveCredentialWriteback;
}): Promise<void> {
const parsed = validatePrpEvent(input.event);
if (!parsed.ok || parsed.event.eventType !== "auth.credentials.updated"
@@ -19,6 +21,9 @@ export async function appendNativeCredentialUpdate(db: Db, input: {
throw new Error("native_credential_update_binding_mismatch");
}
const event = parsed.event;
if (input.liveWriteback && (event.payload.provider !== input.liveWriteback.provider || event.payload.bindingId !== "harness-auth")) {
throw new Error("native_credential_update_binding_mismatch");
}
await db.transaction(async tx => {
const [run] = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, event.runId), eq(heartbeatRuns.companyId, input.companyId),
@@ -43,7 +48,7 @@ export async function appendNativeCredentialUpdate(db: Db, input: {
},
});
});
await input.synchronizeCredentials?.();
await input.liveWriteback?.synchronize();
}
type CredentialUpdateOwner = { handle: (event: PrpEvent) => Promise<void>; detached: boolean; closing: boolean };
@@ -0,0 +1,110 @@
import { join, posix, resolve } from "node:path";
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
import { heartbeatRuns, type Db } from "@paperclipai/db";
import { and, eq, sql } from "drizzle-orm";
import { resolvePaperclipInstanceRoot } from "../../home-paths.js";
import { acpxRuntimeSessionDirectoryName, type NativeExecutionInput, type NativeSession } from "../../vendor/paperclip-runner/index.js";
import { managedAuthFileStrategy, syncManagedAiCredentials, syncManagedAntigravityCredential, type ManagedAiCredentialWritebackBinding } from "../managed-ai-credential-writeback.js";
import { bindAntigravityCredentialTurn } from "./antigravity-runner-credentials.js";
import { bindManagedNativeCredentialTurn } from "./managed-native-credentials.js";
import { createNativeCredentialStore } from "./native-credential-store.js";
import type { LiveCredentialWriteback } from "./native-credential-updates.js";
type NativeCredentialWriteback = {
liveWriteback?: LiveCredentialWriteback;
bindTurn?: (session: NativeSession) => NativeSession;
};
export function prepareNativeCredentialWriteback(input: {
db: Db;
companyId: string;
runId: string;
binding?: ManagedAiCredentialWritebackBinding;
provider: NativeExecutionInput["provider"];
root: string;
sessionId: string;
preconfiguredHome: boolean;
destinationHome?: string | null;
antigravityCredential?: { home: string | null; credential?: string } | null;
remote?: { root: string; runner: Pick<CommandManagedRuntimeRunner, "execute"> };
}): NativeCredentialWriteback | undefined {
const { provider, binding, destinationHome, remote, antigravityCredential } = input;
const harness = provider.kind === "acpx" ? provider.agent : provider.kind;
const strategy = managedAuthFileStrategy(harness);
if (!strategy && !antigravityCredential?.credential) return;
if (strategy && input.preconfiguredHome) return {};
const relativeHome = provider.kind === "acpx"
? `acpx/acpx/${acpxRuntimeSessionDirectoryName(input.sessionId)}/${harness}-home` : "codex-home";
const runtimeHome = provider.kind === "acpx"
? resolve(resolvePaperclipInstanceRoot(), "runtime", "paperclip-runner", relativeHome) : join(input.root, relativeHome);
if (antigravityCredential?.home && antigravityCredential.credential) {
const { home: managedHome, credential } = antigravityCredential;
const runtimeStore = createNativeCredentialStore({
filename: "acp_token.json", localHome: join(runtimeHome, "antigravity-acp"),
...(remote && { remoteHome: posix.join(remote.root, relativeHome, "antigravity-acp"), runner: remote.runner }),
});
const google = binding?.google;
if (!google || !binding) return { bindTurn: session => bindAntigravityCredentialTurn(session, {
managedHome, credential, runtimeHome, runtimeStore: remote ? runtimeStore : undefined,
}) };
const cli = createNativeCredentialStore({
filename: "antigravity-oauth-token", localHome: join(runtimeHome, "antigravity-cli"),
...(remote && { remoteHome: posix.join(remote.root, relativeHome, "antigravity-cli"), runner: remote.runner }),
});
const read = async () => {
let token: string;
try { token = await cli.read(); }
catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
return runtimeStore.read();
}
const refresh: unknown = JSON.parse(token)?.token?.refresh_token;
if (typeof refresh !== "string" || !refresh) throw new Error("Invalid AGY refresh token");
return JSON.stringify({ ...JSON.parse(credential), refresh_token: refresh });
};
const synchronize = async (retiring = false) => {
const run = and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId));
const [owner] = await input.db.select({ hash: sql<string | null>`${heartbeatRuns.contextSnapshot}->>'runnerGoogleCredentialHash'` })
.from(heartbeatRuns).where(run);
if (!owner) throw new Error("Google credential run unavailable");
const outcome = await syncManagedAntigravityCredential(input.db, input.companyId, binding, async () => {
try { return await read(); }
catch (error) { if (retiring && (error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; }
}, {
expectedHash: owner.hash ?? google.credentialSha256,
advance: async (database, hash) => {
const updated = await database.update(heartbeatRuns).set({
contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ runnerGoogleCredentialHash: hash })}::jsonb`,
}).where(and(run, sql`${heartbeatRuns.contextSnapshot}->>'runnerGoogleCredentialHash' is not distinct from ${owner.hash}`))
.returning({ id: heartbeatRuns.id });
if (!updated.length) throw new Error("Google credential run changed");
},
});
if (!retiring && outcome === "no_credentials") throw new Error("Native credential snapshot unavailable");
};
return {
liveWriteback: { provider: harness, synchronize },
bindTurn: session => bindAntigravityCredentialTurn(session, {
managedHome, credential, runtimeHome, runtimeStore, saveRotation: () => synchronize(true),
}),
};
}
if (!strategy) return;
const store = createNativeCredentialStore({ filename: "auth.json", localHome: runtimeHome,
...(remote ? { remoteHome: posix.join(remote.root, relativeHome), runner: remote.runner } : {}) });
const synchronize = binding ? async () => {
const outcome = await syncManagedAiCredentials(input.db, input.companyId, binding, strategy.provider, store.read);
if (outcome === "no_credentials") throw new Error("Native credential snapshot unavailable");
} : undefined;
return {
liveWriteback: synchronize ? { provider: harness, synchronize } : undefined,
bindTurn: destinationHome ? session => bindManagedNativeCredentialTurn(session, {
copyBack: synchronize ? async () => {} : async () => {
await strategy.copyBack(destinationHome, async () => Buffer.from(await store.read()));
},
retire: synchronize, remove: store.remove,
}) : undefined,
};
}
@@ -139,6 +139,7 @@ import { canonicalProviderPackJson } from "./remote-provider-pack-verification.j
import * as providerPackAdmission from "./native-provider-pack-admission.js";
import * as providerArtifactStorage from "./native-provider-artifacts.js";
import * as providerArtifactCapture from "./native-provider-artifact-capture.js";
import * as nativeCredentialWriteback from "./native-credential-writeback.js";
import * as nativeCredentialEvents from "./native-credential-updates.js";
import * as nativeCredentialStores from "./native-credential-store.js";
import * as antigravityRelease from "./antigravity-release.js";
@@ -18773,7 +18774,7 @@ describe("runnerd provider runtime wiring", () => {
expect(transport.environment?.GOOGLE_API_KEY).toBeUndefined();
const session = await backend.openSession({} as never);
expect(storeSpy).toHaveBeenCalledWith(expect.objectContaining({
provider: "antigravity",
filename: "acp_token.json",
remoteHome: expect.stringMatching(/\/acpx\/acpx\/[^/]+\/antigravity-home\/antigravity-acp$/),
}));
await session.close({ reason: "completed" });
@@ -20496,6 +20497,37 @@ describe("runnerd provider runtime wiring", () => {
} finally { portable?.mockRestore(); }
});
it.each([true, false])("routes OpenCode credential events with live writeback capability %s", async enabled => {
const current = scopedNativeExecution("credential-capability");
const run: NativeExecutionInput = { ...current, provider: { kind: "opencode", model: "openai/test" } };
const synchronize = vi.fn(async () => {});
const liveWriteback = enabled ? { provider: "opencode", synchronize } : undefined;
const prepared = vi.spyOn(nativeCredentialWriteback, "prepareNativeCredentialWriteback").mockReturnValue(liveWriteback ? { liveWriteback } : undefined);
const append = vi.spyOn(nativeCredentialEvents, "appendNativeCredentialUpdate").mockResolvedValue(undefined);
try {
await createRunnerdBackend({ db: leaseDb(current), execution: run, runnerInstanceId: "capability-runner" });
state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!();
const event: PrpEvent = {
schema: "paperclip.prp.event.v3", schemaVersion: 3, sourceKind: "runner", sourceInstanceId: "capability-runner",
sourceEventId: "refresh", sourceSeq: 1, emittedAt: "2020-01-01T00:00:00Z", priority: 0,
runId: run.binding.runId, normalizedSessionId: run.session.normalizedSessionId!, eventType: "auth.credentials.updated",
payload: { schema: "paperclip.auth.credentials.updated.v1", provider: "opencode", bindingId: "harness-auth",
revision: 1, detection: "native_hook" },
};
const handler = state.createTransport.mock.calls.at(-1)![0].onCredentialsUpdated;
if (enabled) {
await handler!(event);
expect(append).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ event, liveWriteback }));
} else {
expect(handler).toBeUndefined();
expect(append).not.toHaveBeenCalled();
}
} finally {
append.mockRestore();
prepared.mockRestore();
}
});
it.each(["codex", "acpx-codex", "grok"] as const)("writes managed %s events through the current warm exporter without per-turn reads", async provider => {
const root = await realpath(await mkdtemp(join(tmpdir(), "native-managed-refresh-")));
const previousRoot = process.env.PAPERCLIP_RUNNER_STATE_DIR;
@@ -20515,7 +20547,7 @@ describe("runnerd provider runtime wiring", () => {
const persist = vi.spyOn(managedCredentialWriteback, "syncManagedAiCredentials").mockImplementation(async (_db, _company, _binding, _provider, read) => {
await read(); return "rotated";
});
const append = vi.spyOn(nativeCredentialEvents, "appendNativeCredentialUpdate").mockImplementation(async (_db, input) => { await input.synchronizeCredentials?.(); });
const append = vi.spyOn(nativeCredentialEvents, "appendNativeCredentialUpdate").mockImplementation(async (_db, input) => { await input.liveWriteback?.synchronize(); });
const binding = { grantId: "10000000-0000-4000-8000-000000000001", secretId: "10000000-0000-4000-8000-000000000002", sessionEpoch: 1, versionSelector: "latest" as const };
const session = { close: vi.fn(async () => {}) } as unknown as NativeSession;
try {
@@ -20553,9 +20585,6 @@ describe("runnerd provider runtime wiring", () => {
expect(nextStore.read).toHaveBeenCalledTimes(2);
expect(firstStore.remove).not.toHaveBeenCalled(); expect(nextStore.remove).toHaveBeenCalledOnce();
expect(stores.mock.calls[0]![0].localHome).toContain(provider === "grok" ? "grok-home" : "codex-home");
persist.mockClear();
await expect(retainedHook({ ...notification, payload: { provider: "unexpected" } })).rejects.toThrow("provider_mismatch");
expect(persist).not.toHaveBeenCalled();
} finally {
stores.mockRestore(); persist.mockRestore(); append.mockRestore();
if (previousRoot === undefined) delete process.env.PAPERCLIP_RUNNER_STATE_DIR;
@@ -125,8 +125,7 @@ import { prepareGrokRunnerCredentials } from "./grok-runner-credentials.js";
import { AntigravityConnectionConfigurationError, antigravityConnectionRefusal } from "./antigravity-connection-policy.js";
import { antigravityCandidateTarget, antigravityForcesSameSessionRecovery, antigravityReleasePending, antigravityUsesRunScopedState, assertAntigravityExecutionAdmissible } from "./antigravity-release.js";
import { ANTIGRAVITY_SWARM_UNAVAILABLE } from "../antigravity-swarm-refusal.js";
import { bindAntigravityCredentialTurn, bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js";
import { copyBackGrokAuth } from "@paperclipai/adapter-grok-local/server";
import { bindAntigravityTransportRetirement, prepareAntigravityRunnerCredentials } from "./antigravity-runner-credentials.js";
import { inferOpenAiCompatibleBiller, type AdapterUsageCheckpoint } from "@paperclipai/adapter-utils";
import { createAgentIdentityRedactor } from "../agent-identity-redaction.js";
@@ -143,14 +142,13 @@ import { createNativeDeliverableTextObservation } from "./native-deliverable-tex
import { reconcileControllerJournalWithRunner, refreshRetiredWarmOwnerProjection } from "./warm-controller-journal.js";
import { createNativeGitHubAccess, type NativeGitHubAccess } from "./native-github-access.js";
import { resolveGitHubOperationCredentials } from "../github-operation-credentials.js";
import { syncManagedAiCredentials, type ManagedAiCredentialWritebackBinding } from "../managed-ai-credential-writeback.js";
import { createNativeCredentialStore } from "./native-credential-store.js";
import { bindManagedNativeCredentialTurn, completeManagedNativeCredentialTurn } from "./managed-native-credentials.js";
import type { ManagedAiCredentialWritebackBinding } from "../managed-ai-credential-writeback.js";
import { prepareNativeCredentialWriteback } from "./native-credential-writeback.js";
import { completeManagedNativeCredentialTurn } from "./managed-native-credentials.js";
import { createLocalNativeQuestionBridge } from "./local-native-question-bridge.js";
import { createArtifactInstaller } from "./artifact-transfer.js";
import { imageGenerationBindingForRun } from "./generate-image-tool.js";
import { readVerifiedRemoteWorkspaceFile } from "./remote-deliverable-file.js";
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";
@@ -17130,13 +17128,14 @@ async function createRunnerdBackendWithinSessionClaim(
});
if (refusal) throw new AntigravityConnectionConfigurationError(refusal);
}
const harness = provider.kind === "acpx" ? provider.agent : provider.kind;
const credentials = await preparePluginRunnerCredentials({
provider: provider.kind === "acpx" ? provider.agent : provider.kind,
provider: harness,
identity: input.managedAiCredentialIdentity, accountIdentity: input.managedAiAccountIdentity,
home: input.managedAiCredentialHome, environment: input.runnerEnvironment ?? {},
});
if (credentials.needsWriteback && (!input.managedAiCredentialWriteback
|| (credentials.credential?.type === "provider-env") !== Boolean(input.managedAiCredentialWriteback.google))) {
if (credentials.writeback && (!input.managedAiCredentialWriteback
|| Boolean(credentials.writeback.requiresGoogleGeneration) !== Boolean(input.managedAiCredentialWriteback.google))) {
throw new Error("Plugin Runner credential writeback authority unavailable");
}
// Same-lease recovery already has a writeback binding. A portable move creates a new lease.
@@ -17160,13 +17159,16 @@ async function createRunnerdBackendWithinSessionClaim(
normalizedSessionId: nativeSessionKey(input.execution),
runnerInstanceId: adoptionIdentity?.runnerInstanceId ?? prior?.runnerInstanceId ?? effectiveRunnerInstanceId,
event,
synchronizeCredentials: credentials.credential?.type === "auth-file" && event.payload.provider === credentials.credential.provider ? () => syncPluginTaskCredentialHandoff(input.db, {
companyId: input.execution.binding.companyId, leaseId: remoteTarget.leaseId!, expectedTaskId: description.taskId,
}, async accountIdentity => {
const snapshot = environmentTaskResultSchema.parse(await pluginTask({ kind: "credentials", accountIdentity }, { expectedTaskId: description.taskId }));
if (snapshot.kind !== "credentials") throw new Error("Plugin Runner credential snapshot unavailable");
return snapshot.credential;
}) : undefined,
liveWriteback: credentials.writeback?.mode === "live" ? {
provider: harness,
synchronize: () => syncPluginTaskCredentialHandoff(input.db, {
companyId: input.execution.binding.companyId, leaseId: remoteTarget.leaseId!, expectedTaskId: description.taskId,
}, async accountIdentity => {
const snapshot = environmentTaskResultSchema.parse(await pluginTask({ kind: "credentials", accountIdentity }, { expectedTaskId: description.taskId }));
if (snapshot.kind !== "credentials") throw new Error("Plugin Runner credential snapshot unavailable");
return snapshot.credential;
}),
} : undefined,
}),
warmTaskVersion: description.warmTaskVersion,
githubCredentialBrokerVersion: description.githubCredentialBrokerVersion,
@@ -17187,7 +17189,7 @@ async function createRunnerdBackendWithinSessionClaim(
runId: prior.runId, normalizedSessionId: prior.normalizedSessionId,
turnId: prior.turnId ?? "", itemId: prior.itemId ?? "",
} : undefined), projectAuthCheckVersion: description.projectAuthCheckVersion, task: pluginTask, projectIds: remoteTarget.runnerTaskProjectIds ?? [],
harness: provider.kind === "acpx" ? provider.agent : provider.kind, resumeFrom, priorIdentity: prior ? {
harness, resumeFrom, priorIdentity: prior ? {
runnerInstanceId: prior.runnerInstanceId, environmentLeaseId: prior.environmentLeaseId,
runId: prior.runId, normalizedSessionId: prior.normalizedSessionId,
turnId: typeof prior.turnId === "string" ? prior.turnId : "",
@@ -19044,33 +19046,16 @@ async function createRunnerdBackendWithinSessionClaim(
owner => logger.warn({ companyId: owner.companyId, runId: owner.runId }, "Native session diagnostic recording failed"));
const diagnosticLease = diagnostics.activate(diagnosticOwner, input.onLog);
input.onDiagnosticLease?.(diagnosticLease);
const credentialProvider = input.execution.provider.kind === "codex" ? "codex"
: input.execution.provider.kind === "acpx" && (input.execution.provider.agent === "codex" || input.execution.provider.agent === "grok")
? input.execution.provider.agent : null;
const acpxCredential = input.execution.provider.kind === "acpx";
const credentialRelativeHome = credentialProvider && acpxCredential
? `acpx/acpx/${acpxRuntimeSessionDirectoryName(nativeSessionKey(input.execution))}/${credentialProvider}-home` : "codex-home";
const credentialStore = credentialProvider && !preconfiguredHome ? createNativeCredentialStore({
provider: credentialProvider,
localHome: acpxCredential ? resolve(resolvePaperclipInstanceRoot(), "runtime", "paperclip-runner", credentialRelativeHome) : join(root, "codex-home"),
...(remoteRunnerFilesystemRoot && remoteCommandRunner ? {
remoteHome: posix.join(remoteRunnerFilesystemRoot, credentialRelativeHome), runner: remoteCommandRunner,
} : {}),
}) : null;
const synchronizeCredentials = input.managedAiCredentialWriteback && credentialProvider && credentialStore
? async () => {
const outcome = await syncManagedAiCredentials(input.db, input.execution.binding.companyId,
input.managedAiCredentialWriteback!, credentialProvider, credentialStore.read);
if (outcome === "no_credentials") throw new Error("Native credential snapshot unavailable");
} : undefined;
const credentialUpdates = credentialProvider ? createNativeCredentialUpdateOwner(event => appendNativeCredentialUpdate(input.db, {
const credentials = prepareNativeCredentialWriteback({
runId: input.execution.binding.runId, db: input.db, companyId: input.execution.binding.companyId, binding: input.managedAiCredentialWriteback,
provider: input.execution.provider, sessionId: nativeSessionKey(input.execution), root, preconfiguredHome,
destinationHome: grokCredential ? grokCredential.home : input.managedAiCredentialHome, antigravityCredential,
remote: remoteRunnerFilesystemRoot && remoteCommandRunner ? { root: remoteRunnerFilesystemRoot, runner: remoteCommandRunner } : undefined,
});
const credentialUpdates = credentials && createNativeCredentialUpdateOwner(event => appendNativeCredentialUpdate(input.db, {
companyId: input.execution.binding.companyId, agentId: input.execution.binding.agentId,
normalizedSessionId: nativeSessionKey(input.execution), runnerInstanceId: effectiveRunnerInstanceId, event,
synchronizeCredentials: synchronizeCredentials ? async () => {
if (event.payload.provider !== credentialProvider) throw new Error("native_credential_update_provider_mismatch");
await synchronizeCredentials();
} : undefined,
})) : null;
normalizedSessionId: nativeSessionKey(input.execution), runnerInstanceId: effectiveRunnerInstanceId, event, liveWriteback: credentials.liveWriteback,
}));
const backend = createNativeSessionBackend(runnerExecution, {
retainedSystemInstructions,
runnerInstanceId:
@@ -19438,36 +19423,11 @@ async function createRunnerdBackendWithinSessionClaim(
const detach = session.detachControllerForRestart?.bind(session);
if (detach) session.detachControllerForRestart = async () => { cursorCloudRuntime.unregister(); return detach(); };
}
if (antigravityCredential?.home && antigravityCredential.credential && !boundManagedSessions.has(session)) {
if (credentials?.bindTurn && !boundManagedSessions.has(session)) {
boundManagedSessions.add(session);
const relativeHome = `acpx/acpx/${acpxRuntimeSessionDirectoryName(nativeSessionKey(input.execution))}/antigravity-home`;
const runtimeHome = resolve(resolvePaperclipInstanceRoot(), "runtime", "paperclip-runner", relativeHome);
const runtimeStore = remoteRunnerFilesystemRoot && remoteCommandRunner
? createNativeCredentialStore({
provider: "antigravity",
localHome: join(runtimeHome, "antigravity-acp"),
remoteHome: posix.join(remoteRunnerFilesystemRoot, relativeHome, "antigravity-acp"),
runner: remoteCommandRunner,
})
: undefined;
return bindAntigravityCredentialTurn(session, {
managedHome: antigravityCredential.home, credential: antigravityCredential.credential, runtimeHome,
...(runtimeStore ? { runtimeStore } : {}),
});
return credentials.bindTurn(session);
}
const destinationHome = credentialProvider === "grok" ? grokCredential?.home : input.managedAiCredentialHome;
if (!credentialProvider || !credentialStore || !destinationHome || boundManagedSessions.has(session)) return session;
boundManagedSessions.add(session);
return bindManagedNativeCredentialTurn(session, {
copyBack: synchronizeCredentials ? async () => {} : async () => {
if (credentialProvider === "grok") await copyBackGrokAuth({ hostHomeDir: destinationHome,
readSandboxAuth: async () => Buffer.from(await credentialStore.read()), log: () => {} });
else await copyBackCodexAuth({ hostAuthPath: join(destinationHome, "auth.json"),
readSandboxAuth: async () => Buffer.from(await credentialStore.read()), log: () => {} });
},
retire: synchronizeCredentials,
remove: credentialStore.remove,
});
return session;
};
input.executionContext?.signal.throwIfAborted();
const priorAuthorityEpoch = sessionToolAuthorityEpochs.get(sessionScopeId);
@@ -17,7 +17,7 @@ describe("plugin Runner selected credentials", () => {
const directory = await home(auth);
const transfer = await preparePluginRunnerCredentials({ provider: "codex", identity: "revision", accountIdentity: "account", home: directory, environment: {} });
expect(transfer.accountIdentity).toBe("account");
expect(transfer.needsWriteback).toBe(true);
expect(transfer.writeback?.mode).toBe("live");
expect(transfer.credential).toEqual({ type: "auth-file", provider: "codex", content: JSON.stringify(auth) });
const refreshed = { ...auth, tokens: { ...auth.tokens, refresh_token: "fixture-rotated" }, last_refresh: "2021-01-01T00:00:00Z" };
await transfer.onCredentials!({ type: "auth-file", provider: "codex", content: JSON.stringify(refreshed) });
@@ -26,7 +26,7 @@ describe("plugin Runner selected credentials", () => {
it("transfers a selected API key without requiring refresh authority", async () => {
const directory = await home({ OPENAI_API_KEY: "fixture-key" });
const transfer = await preparePluginRunnerCredentials({ provider: "codex", identity: "revision", accountIdentity: "account", home: directory, environment: {} });
expect(transfer.needsWriteback).toBe(false);
expect(transfer.writeback).toBeUndefined();
expect(transfer.credential).toEqual({ type: "auth-file", provider: "codex", content: JSON.stringify({ OPENAI_API_KEY: "fixture-key" }) });
});
it("transfers only the selected Claude authentication variable", async () => {
@@ -61,7 +61,7 @@ describe("plugin Runner Google Antigravity credentials", () => {
GOOGLE_GEMINI_BASE_URL: "https://router.example.test", GEMINI_HOME: "/controller/private/gemini", XAI_API_KEY: "fixture-xai",
HOME: "/controller/private", OTHER_SECRET: "fixture-unrelated" } });
expect(transfer).toEqual({ accountIdentity: "account", credential: { type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } } });
expect(transfer.needsWriteback).toBeUndefined();
expect(transfer.writeback).toBeUndefined();
expect(transfer.onCredentials).toBeUndefined();
});
it.each([
@@ -72,9 +72,9 @@ describe("plugin Runner Google Antigravity credentials", () => {
const directory = await googleHome(JSON.stringify({ ...JSON.parse(saved), access_token: "fixture-access", expiry: "2020-01-01T00:00:00Z", email: "alice@example.test" }));
const transfer = await preparePluginRunnerCredentials({ provider: "antigravity", identity: "revision", accountIdentity: "account",
home: directory, environment: blankManagedEnvironment });
expect(transfer).toEqual({ accountIdentity: "account", needsWriteback: true,
credential: { type: "provider-env", provider: "antigravity", environment: { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: saved } } });
const delivered = transfer.credential!.type === "provider-env" ? transfer.credential!.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET : "";
expect(transfer).toEqual({ accountIdentity: "account", writeback: { mode: "live", requiresGoogleGeneration: true },
credential: { type: "auth-file", provider: "antigravity", content: saved } });
const delivered = transfer.credential!.type === "auth-file" ? transfer.credential!.content : "";
expect(delivered).not.toContain("fixture-access");
expect(delivered).not.toContain("alice@example.test");
expect(transfer.onCredentials).toBeUndefined();
@@ -84,7 +84,7 @@ describe("plugin Runner Google Antigravity credentials", () => {
const transfer = await preparePluginRunnerCredentials({ provider: "antigravity", identity: "revision", home: directory,
environment: { ...blankManagedEnvironment, GEMINI_API_KEY: "fixture-gemini" } });
expect(transfer.credential).toEqual({ type: "provider-env", provider: "antigravity", environment: { GEMINI_API_KEY: "fixture-gemini" } });
expect(transfer.needsWriteback).toBeUndefined();
expect(transfer.writeback).toBeUndefined();
});
it.each([
["a sign-in supplied through the environment", { PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET: "{\"refresh_token\":\"fixture-refresh\"}" }, "selected credential unavailable"],
@@ -128,7 +128,7 @@ describe("plugin Runner provider environment credentials", () => {
const transfer = await preparePluginRunnerCredentials({ provider, identity: "revision", accountIdentity: "account",
environment: { ...blanks, ...environment, OPENCODE_CONFIG_CONTENT: "{\"provider\":{}}" } });
expect(transfer).toEqual({ accountIdentity: "account", credential: { type: "provider-env", provider, environment } });
expect(transfer.needsWriteback).toBeUndefined();
expect(transfer.writeback).toBeUndefined();
});
it("uses the credential revision as the account when no account identity is supplied", async () => {
const transfer = await preparePluginRunnerCredentials({ provider: "copilot", identity: "revision", environment: { COPILOT_GITHUB_TOKEN: "fixture-copilot" } });
@@ -145,7 +145,7 @@ describe("plugin Runner provider environment credentials", () => {
const directory = await home(grokAuth);
const transfer = await preparePluginRunnerCredentials({ provider: "grok", identity: "revision", accountIdentity: "account",
home: directory, environment: blanks });
expect(transfer).toEqual({ accountIdentity: "account", needsWriteback: true,
expect(transfer).toEqual({ accountIdentity: "account", writeback: { mode: "live" },
credential: { type: "auth-file", provider: "grok", content: JSON.stringify(grokAuth) } });
});
it("refuses a Grok subscription without a usable sign-in file", async () => {
@@ -15,7 +15,7 @@ interface PreparedPluginRunnerCredentials {
githubBroker?: { url: string; token: string };
accountIdentity?: string;
credential?: PluginEnvironmentTaskCredential;
needsWriteback?: boolean;
writeback?: { mode: "live" | "on_stop"; requiresGoogleGeneration?: true };
onCredentials?: (snapshot: PluginEnvironmentTaskCredential) => Promise<void>;
}
@@ -40,7 +40,7 @@ export async function preparePluginRunnerCredentials(input: {
const parsed = JSON.parse(authJson);
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Plugin Runner selected credential invalid");
const credential = environmentTaskCredentialSchema.parse({ type: "auth-file", provider: "codex", content: authJson });
return { ...github, accountIdentity, credential, needsWriteback: !!parsed.tokens,
return { ...github, accountIdentity, credential, writeback: parsed.tokens ? { mode: "live" } : undefined,
onCredentials: async (snapshot: PluginEnvironmentTaskCredential) => {
if (snapshot.type !== "auth-file" || snapshot.provider !== "codex") throw new Error("Plugin Runner credential provider mismatch");
await copyBackCodexAuth({ hostAuthPath, readSandboxAuth: async () => Buffer.from(snapshot.content), log: () => {} });
@@ -57,7 +57,7 @@ export async function preparePluginRunnerCredentials(input: {
usable = parsed !== null && hasUsableGrokAuthValue(parsed.value);
} catch { /* Do not expose credential bytes through JSON parser errors. */ }
if (!usable) throw new Error("Plugin Runner selected credential invalid");
return { ...github, accountIdentity, needsWriteback: true,
return { ...github, accountIdentity, writeback: { mode: "live" },
credential: environmentTaskCredentialSchema.parse({ type: "auth-file", provider: "grok", content }) };
}
if (input.provider === "claude") {
@@ -83,8 +83,8 @@ export async function preparePluginRunnerCredentials(input: {
} catch {
throw new Error("The selected Google Antigravity account is unavailable. Reconnect the Google account, then retry.");
}
const credential = environmentTaskCredentialSchema.parse({ type: "provider-env", provider, environment: { [ANTIGRAVITY_SIGN_IN_ENV]: authJson } });
return { ...github, accountIdentity, credential, needsWriteback: true };
const credential = environmentTaskCredentialSchema.parse({ type: "auth-file", provider, content: authJson });
return { ...github, accountIdentity, credential, writeback: { mode: "live", requiresGoogleGeneration: true } };
}
}
const names = new Set(provider === "antigravity" ? ["GEMINI_API_KEY"] : ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS[provider].flat());
@@ -161,11 +161,11 @@ describe("plugin Runner probe for Google Antigravity", () => {
harness: "antigravity",
credentialIdentity: "google-id",
accountIdentity: "google-session",
needsWriteback: true,
writeback: { mode: "live", requiresGoogleGeneration: true },
credential: {
type: "provider-env",
type: "auth-file",
provider: "antigravity",
environment: { [SIGN_IN_ENV]: signInJson },
content: signInJson,
},
}));
expect(mocks.probe).toHaveBeenCalledWith(expect.objectContaining({
@@ -65,17 +65,45 @@ export async function syncPluginTaskCredentialHandoff(
if (!lease.metadata?.[key]) return;
const handoff = handoffSchema.parse(lease.metadata[key]);
if (handoff.state === "complete") return;
const outcome = await writeBackCredentials(db, scope.companyId, handoff, fetchCredential);
if (handoff.provider === "antigravity" && lease.metadata.runnerTaskExecutionStopped === true) return;
const outcome = await writeBackCredentials(db, scope, lease.metadata, handoff, fetchCredential);
if (outcome === "no_credentials") throw new Error("Plugin task credential snapshot unavailable");
return outcome;
}
async function writeBackCredentials(
db: Db,
companyId: string,
scope: Scope,
metadata: Record<string, unknown>,
handoff: z.infer<typeof handoffSchema>,
fetchCredential: (accountIdentity: string) => Promise<PluginEnvironmentTaskCredential | null>,
) {
const { companyId } = scope;
const provider = handoff.provider ?? "codex";
if (provider === "antigravity") {
const base = handoff.binding.google?.credentialSha256;
if (!base) throw new Error("Plugin task Google credential authority unavailable");
const previous = metadata.runnerTaskGoogleCredentialHash;
return syncManagedAntigravityCredential(db, companyId, handoff.binding, async () => {
const credential = await fetchCredential(handoff.accountIdentity);
if (credential === null) return null;
if (credential.type !== "auth-file" || credential.provider !== provider) throw new Error("Plugin task credential provider mismatch");
return credential.content;
}, {
expectedHash: typeof previous === "string" ? previous : base,
advance: async (database, nextHash) => {
const updated = await database.update(environmentLeases).set({
metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ runnerTaskGoogleCredentialHash: nextHash })}::jsonb`,
}).where(and(
eq(environmentLeases.companyId, companyId), eq(environmentLeases.id, scope.leaseId),
sql`${environmentLeases.metadata}->${key} = ${JSON.stringify(handoff)}::jsonb`,
sql`coalesce(${environmentLeases.metadata}->>'runnerTaskExecutionStopped', 'false') = ${metadata.runnerTaskExecutionStopped === true ? "true" : "false"}`,
sql`${environmentLeases.metadata}->>'runnerTaskGoogleCredentialHash' is not distinct from ${previous ?? null}`,
)).returning({ id: environmentLeases.id });
if (!updated.length) throw new Error("Plugin task Google credential authority changed");
},
});
}
if (handoff.binding.google) return syncManagedAntigravityCredential(db, companyId, handoff.binding, async () => {
const credential = await fetchCredential(handoff.accountIdentity);
if (credential === null) return null;
@@ -84,7 +112,6 @@ async function writeBackCredentials(
if (!value) throw new Error("Plugin task credential provider mismatch");
return value;
});
const provider = handoff.provider ?? "codex";
return syncManagedAiCredentials(db, companyId, handoff.binding, provider, async () => {
const credential = await fetchCredential(handoff.accountIdentity);
if (credential === null) return null;
@@ -108,7 +135,7 @@ export async function settlePluginTaskCredentialHandoff(
throw new Error("Plugin task credential process termination is unconfirmed");
}
const outcome = dispatched
? await writeBackCredentials(db, scope.companyId, handoff, fetchCredential)
? await writeBackCredentials(db, scope, metadata, handoff, fetchCredential)
: "not_dispatched";
const settled = { ...handoff, state: "complete" as const, outcome };
const completed = await db.update(environmentLeases).set({
@@ -66,10 +66,11 @@ export function retainAiCredentialCleanup(input: {
// Accept legacy Google home metadata for compatibility. Only the explicit
// bindRetainedAiCredentialHome mapping grants home-to-account authority.
scope: RetainedAiCleanupScope; cleanup: () => Promise<void>; retired?: Promise<void>; retryRetirement?: () => Promise<void>; home?: string;
}): void {
}): () => Promise<void> {
const scopeKey = key(input.scope);
const entries = retained.get(scopeKey) ?? new Set<Cleanup>();
if ([...entries].some(entry => entry.cleanup === input.cleanup)) return;
const existing = [...entries].find(entry => entry.cleanup === input.cleanup);
if (existing) return () => attempt(existing);
const entry: Cleanup = { scope: { ...input.scope }, home: input.home, cleanup: input.cleanup, retryRetirement: input.retryRetirement,
retired: input.retired ? "pending" : "confirmed" };
entries.add(entry); retained.set(scopeKey, entries);
@@ -77,6 +78,7 @@ export function retainAiCredentialCleanup(input: {
entry.retired = "confirmed";
return attempt(entry).catch(() => undefined);
}, () => { entry.retired = "failed"; warn(entry); });
return () => attempt(entry);
}
export async function reconcileRetainedAiCleanup(scope: RetainedAiCleanupScope): Promise<void> {
@@ -100,7 +102,7 @@ export async function reconcileRetainedAiCleanupForHome(home: string): Promise<v
}
export function retainAiCredentialCleanupForHome(home: string, input: {
cleanup: () => Promise<void>; retired?: Promise<void>; retryRetirement?: () => Promise<void>;
}): void {
}): (() => Promise<void>) | undefined {
const scope = homes.get(home);
if (scope) retainAiCredentialCleanup({ ...input, scope, home });
if (scope) return retainAiCredentialCleanup({ ...input, scope, home });
}