Files
PaperClipAI/packages/plugins/sdk/src/workspace-provider.ts
T
Nicky LeachandPaperclip 5dfbb04b85 Poll asynchronous workspace provider preparation (#20865)
## Thinking Path

> - Paperclip starts agent runs through a workspace provider when a
project uses remote storage.
> - The provider must prepare the workspace before the agent starts.
> - One long worker call ties the checkout to its transport.
> - Some checkouts take longer than the transport allows.
> - This change lets an opted-in provider accept work and report its
deadline.
> - Core waits for completion through short status calls and stops at
the provider deadline.

## Linked Issues or Issue Description

**What happened?**

A workspace provider can lose its reply when preparation takes longer
than a single transport request. This stops run bootstrap before agent
execution.

**Expected behavior**

Core should wait for a provider-confirmed workspace through short
requests. The provider's deadline must bound the wait.

**Steps to reproduce**

Use a workspace provider that takes longer to prepare a checkout than
its transport can remain open. Start a run that requires a new checkout.

## What Changed

- Add an optional workspace preparation method to the plugin SDK.
- Validate pending receipts and keep the original binding checks on
completed replies.
- Poll only during active preparation. Retry a lost status reply within
the advertised deadline.
- Preserve the original operation for providers that do not offer
asynchronous preparation.
- Reject deadline offers that exceed the existing lifecycle lock budget.
Honor accepted offers without shortening them.
- Checkout verification uses the existing synchronous RPC with a
10-second deadline and a 12-second transport timeout. [Core verification
PR #20876](https://github.com/paperclipai/paperclip/pull/20876)

## Verification

- All 63 workspace SDK and Core integration tests passed with temporary
local PostgreSQL. The tests cover lost status replies, deadline expiry,
oversized offers, and synchronous verification with an async-capable
worker.
- All 58 runner SDK input, evidence, and public type tests passed with
the regenerated source pins. The local server typecheck passed.

## Risks

- This change activates only when the provider advertises the method.
Existing providers keep their current behavior.
- Polling uses one-second intervals during active preparation. It stops
at completion, failure, or the provider deadline.
- No database migration is required.

## Model Used

- OpenAI GPT-6 Codex with local code execution and tests.

## 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-11-11 10:33:02 -08:00

195 lines
7.5 KiB
TypeScript

import { z } from "zod";
import { workspaceProviderBindingSchema } from "@paperclipai/shared";
const recoveryFile = z.object({
path: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
byteSize: z.number().int().positive(),
}).strict();
export const freshWorkspaceSchema = z.object({
attemptId: z.string().uuid(),
sourceRunId: z.string().uuid(),
previousWorkspaceId: z.string().uuid().nullable(),
recoverySnapshots: z.array(z.object({
operationId: z.string().uuid(), sourceRunId: z.string().uuid(),
archive: recoveryFile, manifest: recoveryFile,
}).strict()),
}).strict();
export type PluginFreshWorkspace = z.infer<typeof freshWorkspaceSchema>;
const sha = z.string().regex(/^[a-f0-9]{40,64}$/);
export const workspaceRecoveryPullRequestSchema = z.object({
number: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
headSha: z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),
}).strict();
export type PluginWorkspaceRecoveryPullRequest = z.infer<typeof workspaceRecoveryPullRequestSchema>;
const destinationRef = z.string().max(266).regex(/^refs\/heads\/[^\x00-\x20\x7f~^:?*\[\]\\]+$/)
.refine(ref => !ref.includes("..") && !ref.includes("@{") && !ref.endsWith(".") && !ref.endsWith("/")
&& ref.split("/").every(part => part && !part.startsWith(".") && !part.endsWith(".lock")));
export const workspaceProviderOperationSchema = z.discriminatedUnion("kind", [
z
.object({
kind: z.literal("prepare"),
source: z
.object({
id: z.string().uuid(),
revision: z.string().min(1).max(256),
repoUrl: z.string().url().nullable(),
repoRef: z.string().nullable(),
defaultRef: z.string().nullable(),
})
.strict(),
mode: z.enum([
"shared_workspace",
"isolated_workspace",
"operator_branch",
]),
strategy: z.enum(["project_primary", "git_worktree"]),
branchName: z.string().min(1).max(256).nullable(),
branchMode: z.enum(["create", "existing"]).optional(),
baseRef: z.string().nullable(),
existing: workspaceProviderBindingSchema.nullable(),
fresh: freshWorkspaceSchema.optional(),
verifyExisting: z.literal(true).optional(),
})
.strict(),
// Verify the retained workspace and flush run writes. This does not certify
// remote recoverability or authorize removal; dirty work is valid output.
z.object({ kind: z.literal("finalize"), binding: workspaceProviderBindingSchema }).strict(),
z
.object({
kind: z.literal("inspect"),
binding: workspaceProviderBindingSchema,
recoveryPullRequest: workspaceRecoveryPullRequestSchema.optional(),
})
.strict(),
z
.object({
kind: z.literal("remove"),
binding: workspaceProviderBindingSchema.nullable(),
expectedHeadSha: sha.nullable(),
recoveryPullRequest: workspaceRecoveryPullRequestSchema.optional(),
})
.strict(),
]);
export const workspaceProviderResultSchema = z.discriminatedUnion("kind", [
z
.object({
kind: z.literal("prepared"),
binding: workspaceProviderBindingSchema,
branchName: z.string().min(1).max(256).nullable(),
baseSha: sha.nullable(),
destinationRef: destinationRef.nullable().optional(),
created: z.boolean(),
branchCreatedByRuntime: z.boolean(),
})
.strict(),
z
.object({
kind: z.literal("inspection"),
headSha: sha.nullable(),
branchName: z.string().nullable(),
hasDirtyTrackedFiles: z.boolean(),
hasUntrackedFiles: z.boolean(),
hasLocalOnlyData: z.boolean(),
isMergedIntoBase: z.boolean().nullable(),
remotelyRecoverable: z.boolean().nullable(),
})
.strict(),
// Return only after retained files are durable and their identity is verified.
z.object({ kind: z.literal("finalized"), headSha: sha.nullable(), branchName: z.string().nullable() }).strict(),
// Return only after removal is confirmed. Busy, failed and uncertain operations must throw.
z.object({ kind: z.literal("removed") }).strict(),
]);
export type PluginWorkspaceOperation = z.infer<
typeof workspaceProviderOperationSchema
>;
export type PluginWorkspaceResult = z.infer<
typeof workspaceProviderResultSchema
>;
export const pluginWorkspaceParamsSchema = z
.object({
pluginId: z.string().uuid(),
companyId: z.string().uuid(),
projectId: z.string().uuid(),
executionWorkspaceId: z.string().uuid(),
/** Stable across ambiguous retries; reconcile before repeating effects. */
operationId: z.string().min(1).max(256),
generation: z.number().int().nonnegative(),
deadline: z.string().datetime(),
runId: z.string().uuid().nullable(),
agentId: z.string().uuid().nullable(),
operation: workspaceProviderOperationSchema,
})
.strict();
/** Finalization receives the originating run/agent context; maintenance remains agent-independent. */
export type PluginWorkspaceParams = z.infer<typeof pluginWorkspaceParamsSchema>;
export const pluginWorkspacePrepareParamsSchema = pluginWorkspaceParamsSchema.extend({
phase: z.enum(["submit", "poll"]),
}).refine((input) => input.operation.kind === "prepare");
export type PluginWorkspacePrepareParams = z.infer<typeof pluginWorkspacePrepareParamsSchema>;
export type PluginWorkspacePrepareResult =
| { kind: "unsupported" }
| { kind: "pending"; deadline: string }
| Extract<PluginWorkspaceResult, { kind: "prepared" }>;
export function parseWorkspacePrepareResult(
params: PluginWorkspacePrepareParams,
value: unknown,
): PluginWorkspacePrepareResult {
const result = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("unsupported") }).strict(),
z.object({ kind: z.literal("pending"), deadline: z.string().datetime() }).strict(),
]).safeParse(value);
if (result.success) {
if (result.data.kind === "unsupported" && params.phase !== "submit")
throw new Error("Workspace provider withdrew asynchronous preparation");
return result.data;
}
const prepared = parseWorkspaceProviderResult(params, value);
if (prepared.kind !== "prepared") throw new Error("Workspace provider returned the wrong preparation result");
return prepared;
}
export function parseWorkspaceProviderResult(
params: PluginWorkspaceParams,
value: unknown,
): PluginWorkspaceResult {
const result = workspaceProviderResultSchema.parse(value);
const expected =
params.operation.kind === "prepare"
? "prepared"
: params.operation.kind === "inspect"
? "inspection"
: params.operation.kind === "finalize" ? "finalized" : "removed";
if (result.kind !== expected)
throw new Error("Workspace provider returned the wrong operation result");
if (
result.kind === "prepared" &&
(result.binding.pluginId !== params.pluginId ||
result.binding.executionWorkspaceId !== params.executionWorkspaceId ||
result.binding.projectId !== params.projectId ||
result.binding.projectWorkspaceId !==
(params.operation.kind === "prepare"
? params.operation.source.id
: undefined) ||
result.binding.sourceRevision !==
(params.operation.kind === "prepare"
? params.operation.source.revision
: undefined))
) {
throw new Error("Workspace provider returned a different source binding");
}
if (
result.kind === "prepared" &&
params.operation.kind === "prepare" &&
params.operation.branchName &&
result.branchName !== params.operation.branchName
) {
throw new Error("Workspace provider returned a different branch");
}
return result;
}