mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
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:
1 parent
c47452699a
commit
9092b0c667
34 files changed
+764
-207
No files matched your search
@@ -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({
|
||||
|
||||
Reference in new issue
Block a user