Files
PaperClipAI/server/src/services/plugin-task-credential-writeback.ts
T
Nicky LeachandPaperclip 9092b0c667 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>
2026-12-02 01:49:46 +00:00

159 lines
8.6 KiB
TypeScript

import { and, eq, sql } from "drizzle-orm";
import { environmentLeases, type Db } from "@paperclipai/db";
import { ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS, z, type PluginEnvironmentTaskAuthFileProvider, type PluginEnvironmentTaskCredential } from "@paperclipai/plugin-sdk";
import { isDeepStrictEqual } from "node:util";
import { managedAiCredentialWritebackBindingSchema, syncManagedAiCredentials, syncManagedAntigravityCredential, type ManagedAiCredentialWritebackBinding } from "./managed-ai-credential-writeback.js";
const handoffSchema = z.object({
accountIdentity: z.string().min(1),
provider: z.enum(ENVIRONMENT_TASK_AUTH_FILE_PROVIDERS).optional(),
binding: managedAiCredentialWritebackBindingSchema,
state: z.enum(["pending", "complete"]),
outcome: z.enum(["rotated", "unchanged", "binding_changed", "not_dispatched", "no_credentials", "account_refused"]).optional(),
}).strict();
const key = "runnerTaskCredentialHandoff";
type Scope = { companyId: string; leaseId: string; expectedTaskId?: string };
export function canReadStoppedPluginTaskCredential(metadata: Record<string, unknown>, accountIdentity: string): boolean {
const handoff = handoffSchema.safeParse(metadata[key]);
return metadata.runnerTaskExecutionStopped === true && handoff.success &&
handoff.data.state === "pending" && handoff.data.accountIdentity === accountIdentity;
}
/** Save authority, never credential bytes or a controller-local temporary path. */
export async function registerPluginTaskCredentialHandoff(
db: Db,
scope: Scope,
accountIdentity: string,
binding: ManagedAiCredentialWritebackBinding,
provider: PluginEnvironmentTaskAuthFileProvider = "codex",
) {
const handoff = handoffSchema.parse({ accountIdentity, binding, state: "pending", ...(provider === "codex" ? {} : { provider }) });
await db.transaction(async tx => {
const [lease] = await tx.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, scope.companyId), eq(environmentLeases.id, scope.leaseId),
)).for("update");
if (!lease || lease.status !== "active" || lease.metadata?.runnerTaskLease !== true ||
lease.metadata.runnerTaskRetiring === true) {
throw new Error("Plugin task credential lease unavailable");
}
const saved = lease.metadata[key];
if (saved) {
const prior = handoffSchema.parse(saved);
if (prior.accountIdentity !== accountIdentity || !isDeepStrictEqual(prior.binding, handoff.binding) ||
(prior.provider ?? "codex") !== provider) {
throw new Error("Plugin task credential authority changed");
}
return;
}
await tx.update(environmentLeases).set({ metadata: { ...lease.metadata, [key]: handoff } })
.where(eq(environmentLeases.id, lease.id));
});
}
/** Live PRP updates use durable authority, including while a warm task is idle. */
export async function syncPluginTaskCredentialHandoff(
db: Db,
scope: Scope,
fetchCredential: (accountIdentity: string) => Promise<PluginEnvironmentTaskCredential | null>,
) {
const [lease] = await db.select().from(environmentLeases).where(and(
eq(environmentLeases.companyId, scope.companyId), eq(environmentLeases.id, scope.leaseId),
scope.expectedTaskId === undefined ? undefined : eq(environmentLeases.providerLeaseId, scope.expectedTaskId),
));
if (!lease) throw new Error("Plugin task credential lease unavailable");
if (!lease.metadata?.[key]) return;
const handoff = handoffSchema.parse(lease.metadata[key]);
if (handoff.state === "complete") return;
if (handoff.provider === "antigravity" && lease.metadata.runnerTaskExecutionStopped === true) return;
const outcome = await writeBackCredentials(db, scope, lease.metadata, handoff, fetchCredential);
if (outcome === "no_credentials") throw new Error("Plugin task credential snapshot unavailable");
return outcome;
}
async function writeBackCredentials(
db: Db,
scope: Scope,
metadata: Record<string, unknown>,
handoff: z.infer<typeof handoffSchema>,
fetchCredential: (accountIdentity: string) => Promise<PluginEnvironmentTaskCredential | null>,
) {
const { companyId } = scope;
const provider = handoff.provider ?? "codex";
if (provider === "antigravity") {
const base = handoff.binding.google?.credentialSha256;
if (!base) throw new Error("Plugin task Google credential authority unavailable");
const previous = metadata.runnerTaskGoogleCredentialHash;
return syncManagedAntigravityCredential(db, companyId, handoff.binding, async () => {
const credential = await fetchCredential(handoff.accountIdentity);
if (credential === null) return null;
if (credential.type !== "auth-file" || credential.provider !== provider) throw new Error("Plugin task credential provider mismatch");
return credential.content;
}, {
expectedHash: typeof previous === "string" ? previous : base,
advance: async (database, nextHash) => {
const updated = await database.update(environmentLeases).set({
metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ runnerTaskGoogleCredentialHash: nextHash })}::jsonb`,
}).where(and(
eq(environmentLeases.companyId, companyId), eq(environmentLeases.id, scope.leaseId),
sql`${environmentLeases.metadata}->${key} = ${JSON.stringify(handoff)}::jsonb`,
sql`coalesce(${environmentLeases.metadata}->>'runnerTaskExecutionStopped', 'false') = ${metadata.runnerTaskExecutionStopped === true ? "true" : "false"}`,
sql`${environmentLeases.metadata}->>'runnerTaskGoogleCredentialHash' is not distinct from ${previous ?? null}`,
)).returning({ id: environmentLeases.id });
if (!updated.length) throw new Error("Plugin task Google credential authority changed");
},
});
}
if (handoff.binding.google) return syncManagedAntigravityCredential(db, companyId, handoff.binding, async () => {
const credential = await fetchCredential(handoff.accountIdentity);
if (credential === null) return null;
const value = credential.type === "provider-env" && credential.provider === "antigravity"
? credential.environment.PAPERCLIP_ACPX_ANTIGRAVITY_AUTH_JSON_SECRET : undefined;
if (!value) throw new Error("Plugin task credential provider mismatch");
return value;
});
return syncManagedAiCredentials(db, companyId, handoff.binding, provider, async () => {
const credential = await fetchCredential(handoff.accountIdentity);
if (credential === null) return null;
if (credential.type !== "auth-file" || credential.provider !== provider) throw new Error("Plugin task credential provider mismatch");
return credential.content;
});
}
/** Runs for live completion and the cleanup sweep, including after Core restarts. */
export async function settlePluginTaskCredentialHandoff(
db: Db,
scope: Scope,
metadata: Record<string, unknown>,
fetchCredential: (accountIdentity: string) => Promise<PluginEnvironmentTaskCredential | null>,
) {
if (!metadata[key]) return;
const handoff = handoffSchema.parse(metadata[key]);
if (handoff.state === "complete") return;
const dispatched = metadata.runnerTaskDispatched === true || !!metadata.runnerTaskIdentity;
if (dispatched && metadata.runnerTaskExecutionStopped !== true) {
throw new Error("Plugin task credential process termination is unconfirmed");
}
const outcome = dispatched
? await writeBackCredentials(db, scope, metadata, handoff, fetchCredential)
: "not_dispatched";
const settled = { ...handoff, state: "complete" as const, outcome };
const completed = await db.update(environmentLeases).set({
metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({ [key]: settled })}::jsonb`,
}).where(and(
eq(environmentLeases.companyId, scope.companyId), eq(environmentLeases.id, scope.leaseId),
scope.expectedTaskId === undefined ? undefined : eq(environmentLeases.providerLeaseId, scope.expectedTaskId),
sql`${environmentLeases.metadata}->${key} = ${JSON.stringify(handoff)}::jsonb`,
)).returning({ id: environmentLeases.id });
if (completed.length !== 1) {
const [current] = await db.select({ metadata: environmentLeases.metadata, taskId: environmentLeases.providerLeaseId }).from(environmentLeases).where(and(
eq(environmentLeases.companyId, scope.companyId), eq(environmentLeases.id, scope.leaseId),
));
const saved = handoffSchema.safeParse(current?.metadata?.[key]);
if (scope.expectedTaskId !== undefined && current?.taskId !== scope.expectedTaskId ||
!saved.success || !isDeepStrictEqual({ ...saved.data, outcome: settled.outcome }, settled)) {
throw new Error("Plugin task credential handoff changed");
}
}
}