refactor(runtime): dispatch credential updates by writeback capability

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Nicky LeachandPaperclip committed 2026-12-01 09:53:48 -08:00
1 parent 51541be36f
commit 388baefbe5
14 files changed
+225 -126

No files matched your search

+8 -4
View File
@@ -705,10 +705,14 @@ pnpm exec vitest run server/src/__tests__/native-session-resumption.test.ts -t '
## Native Runner credential refreshes
Core handles PRP `auth.credentials.updated` notifications for managed Codex and
Grok subscriptions across local, SSH, sandbox, and supported plugin Runner tasks.
After validating the company, agent, run, session, and Runner binding, it exports
the selected account and writes newer credentials directly to the tenant secret.
Native credential preparation opts a harness into PRP `auth.credentials.updated`
handling. Core validates the company, agent, run, session, and Runner binding
before recording the event. A credential that supports live writeback also
supplies its provider and synchronization callback.
Core uses it only for a matching provider and the `harness-auth` binding.
Managed Codex and Grok subscriptions supply live writeback on local, SSH,
sandbox, and supported plugin Runner tasks. Antigravity subscriptions export
at retirement because Google account verification can rotate the token again.
Grant, secret, version-selector, session-epoch, and provider freshness checks are
shared across execution targets. Explicit reconnects and revoked grants win over
old refreshes. Providers that do not emit this event keep their existing flow;
@@ -113,7 +113,7 @@ 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: "on_stop", requiresGoogleGeneration: true }, credential: { type: "provider-env", provider: "antigravity", environment: { [SIGN_IN]: saved } } });
expect(f.managed.credentialWriteback).toMatchObject({ google: { credentialSha256: createHash("sha256").update(saved).digest("hex") } });
expect(leaked(JSON.stringify((await f.lease()).metadata))).toEqual([]);
});
@@ -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"));
@@ -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";
@@ -22,15 +22,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.
@@ -50,7 +79,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(
@@ -62,15 +91,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 => {
@@ -78,7 +99,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 });
@@ -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";
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 ((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,66 @@
import { join, posix, resolve } from "node:path";
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
import type { Db } from "@paperclipai/db";
import { resolvePaperclipInstanceRoot } from "../../home-paths.js";
import { acpxRuntimeSessionDirectoryName, type NativeExecutionInput, type NativeSession } from "../../vendor/paperclip-runner/index.js";
import { managedAuthFileStrategy, syncManagedAiCredentials, 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;
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;
// Operator-owned auth files still report updates without granting tenant writeback.
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;
// Google account verification can rotate the token. Export only after the process stops.
const runtimeStore = remote ? createNativeCredentialStore({
filename: "acp_token.json", localHome: join(runtimeHome, "antigravity-acp"),
remoteHome: posix.join(remote.root, relativeHome, "antigravity-acp"), runner: remote.runner,
}) : undefined;
return { bindTurn: session => bindAntigravityCredentialTurn(session, { managedHome, credential, runtimeHome, runtimeStore }) };
}
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,38 @@ 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;
// Model a harness gaining an exporter without changing the transport or event handler.
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 +20548,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 +20586,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({
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,7 +72,7 @@ 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,
expect(transfer).toEqual({ accountIdentity: "account", writeback: { mode: "on_stop", requiresGoogleGeneration: 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(delivered).not.toContain("fixture-access");
@@ -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") {
@@ -84,7 +84,7 @@ export async function preparePluginRunnerCredentials(input: {
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 };
return { ...github, accountIdentity, credential, writeback: { mode: "on_stop", requiresGoogleGeneration: true } };
}
}
const names = new Set(provider === "antigravity" ? ["GEMINI_API_KEY"] : ENVIRONMENT_TASK_PROVIDER_CREDENTIAL_KEY_SETS[provider].flat());
@@ -161,7 +161,7 @@ describe("plugin Runner probe for Google Antigravity", () => {
harness: "antigravity",
credentialIdentity: "google-id",
accountIdentity: "google-session",
needsWriteback: true,
writeback: { mode: "on_stop", requiresGoogleGeneration: true },
credential: {
type: "provider-env",
provider: "antigravity",