mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 19:08:33 +01:00
## Thinking Path > - Daytona preserves a stopped sandbox filesystem, but deleting or replacing a sandbox removes its only remote copy. > - Warm reuse therefore improves latency but cannot be Paperclip's durability boundary. > - The host execution workspace must remain authoritative after every successful turn, while same-run recovery must avoid overwriting unexported remote work. > - Result proposal, workspace export/merge, and terminal completion need a durable, replayable ordering so a crash never starts a duplicate provider turn. > - A paid browser acceptance suite must exercise both legacy Codex and Runner Codex for three real turns on one continuously warm Daytona sandbox. ## Linked Issues or Issue Description Refs #12901. Runner Codex did not previously export successful Daytona workspace changes back to the authoritative host workspace. That made warm reuse depend on Daytona's remote filesystem and left deleted/replacement sandboxes without a reliable reconstruction path. The existing paid fixture also lacked a focused three-turn continuity case for both Codex adapters. ## What Changed - Persist versioned, atomic native workspace-sync descriptors and durable seeds in `PAPERCLIP_HOME`, without credentials or a database migration. - Classify fresh, warm, replacement, and same-run-recovery workspace preparation explicitly; ambiguous lease/root/digest evidence fails closed. - Finalize native workspace export/merge after semantic result proposal and before run completion, with idempotent replay that never submits a second provider turn. - Surface legacy Codex workspace restoration failures instead of masking them, while preserving an earlier provider error when both fail. - Keep healthy reusable Daytona leases warm for legacy and native adapters, stamp finalized workspace generations, and retain existing cleanup behavior for per-turn or unhealthy leases. - Preserve Runner Codex's provider process/session across warm turns, including bounded post-terminal tail draining and exact authority rotation. - Add the exact paid `daytona-warm-continuity` matrix: - `legacy-codex × daytona × warm-three-turn` - `runner-codex × daytona × warm-three-turn` - Drive all three turns through the browser, verify ordered file continuity and stable lease/workspace/runtime identities, capture per-turn timings, and delete the sandbox immediately after assertions. - Document `pnpm test:e2e:runner -- --suite daytona-warm-continuity`; no package script was added. ## Verification - `pnpm typecheck` — passed, including migration safety (no migration added) - Focused server/runner Vitest coverage — 144 passed - `pnpm test:e2e:runner:unit` — 114 passed - `pnpm test:e2e:runner:typecheck` — passed - `pnpm --filter @paperclipai/paperclip-runner test:codex` — 66 passed, 1 helper ignored - `native-session-executor.test.ts` — 139 passed, including safe fail-closed cleanup after remote runner identity capture failure - Paid local browser acceptance, exact post-rebase Linux/amd64 runner binary: - Runner Codex — passed in 1.7m; 3 runs; lease outcomes `created, resumed, resumed`; 10/10 matchers; cleanup passed - Legacy Codex — passed in 2.7m; 3 runs; lease outcomes `created, resumed, resumed`; 10/10 matchers; cleanup passed - [Protected paid GitHub Actions campaign](https://github.com/paperclipai/paperclip/actions/runs/34026735033) against `7da42a91b95fa7fb2df126668ef7e37afb3b2b9d` — passed 2/2: - Runner Codex — 3 runs; lease outcomes `created, resumed, resumed`; evidence and cleanup passed - Legacy Codex — 3 runs; lease outcomes `created, resumed, resumed`; evidence and cleanup passed - Merge/enforcement, S3 history, and Pages publication jobs passed - Paid result artifacts were scanned for both provider credentials; neither secret was present. - Current PR checks — 31 passed, 1 expected Storybook skip; Greptile 5/5; Superagent security scan passed - `git diff --check origin/master...HEAD` — passed - Confirmed no `package.json`, lockfile, migration, or SQL changes. ## Risks - Workspace synchronization now sits on the terminal-success path, so a remote export failure deliberately prevents false success. Retryable state retains its lease/seed; loss of the only unexported remote copy fails closed. - Warm provider reuse has strict identity and quiescence checks. Mismatched or ambiguous evidence blocks reuse rather than risking concurrent provider work. - The paid suite incurs Daytona and Codex cost only in the existing protected scheduled/manual workflow and explicitly destroys its sandbox after each cell. ## Model Used OpenAI Codex with GPT-5 agentic reasoning, repository inspection, real browser E2E execution, Rust/TypeScript test execution, and GitHub Actions diagnostics. ## 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 linked an existing issue or described the issue in-PR - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name contains no internal ticket id - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have documented the dedicated suite invocation without adding a package script - [x] I have considered and documented risks above - [x] All Paperclip CI gates are green on the current revision - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups on the current revision - [x] I will address all reviewer comments before requesting merge
402 lines
13 KiB
TypeScript
402 lines
13 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import type {
|
|
EnvironmentLeaseStatus,
|
|
EnvironmentProbeResult,
|
|
FakeSandboxEnvironmentConfig,
|
|
SandboxEnvironmentConfig,
|
|
SandboxEnvironmentProvider,
|
|
} from "@paperclipai/shared";
|
|
|
|
export interface SandboxProviderValidationResult {
|
|
ok: boolean;
|
|
summary: string;
|
|
details?: Record<string, unknown>;
|
|
}
|
|
|
|
export interface AcquireSandboxLeaseInput {
|
|
config: SandboxEnvironmentConfig;
|
|
environmentId: string;
|
|
heartbeatRunId: string;
|
|
issueId: string | null;
|
|
agentId?: string | null;
|
|
executionWorkspaceId?: string | null;
|
|
/**
|
|
* The absolute latest time the acquired lease may stay active, as an ISO 8601
|
|
* timestamp. A caller with an independent deadline sets it. The provider must
|
|
* configure a provider-side expiry at or before this time, and return the real
|
|
* provider expiry in `SandboxLeaseHandle.expiresAt`. When omitted, the provider
|
|
* keeps its default lifetime.
|
|
*/
|
|
requestedExpiresAt?: string | null;
|
|
}
|
|
|
|
export interface ResumeSandboxLeaseInput {
|
|
config: SandboxEnvironmentConfig;
|
|
providerLeaseId: string;
|
|
}
|
|
|
|
export interface ReleaseSandboxLeaseInput {
|
|
config: SandboxEnvironmentConfig;
|
|
providerLeaseId: string | null;
|
|
status: Extract<EnvironmentLeaseStatus, "released" | "expired" | "failed">;
|
|
}
|
|
|
|
export interface DestroySandboxLeaseInput {
|
|
config: SandboxEnvironmentConfig;
|
|
providerLeaseId: string | null;
|
|
}
|
|
|
|
export interface PrepareSandboxWorkspaceInput {
|
|
config: SandboxEnvironmentConfig;
|
|
providerLeaseId: string | null;
|
|
workspace: {
|
|
localPath?: string;
|
|
remotePath?: string;
|
|
mode?: string;
|
|
metadata?: Record<string, unknown>;
|
|
};
|
|
}
|
|
|
|
export interface SandboxExecuteInput {
|
|
config: SandboxEnvironmentConfig;
|
|
providerLeaseId: string | null;
|
|
command: string;
|
|
args?: string[];
|
|
cwd?: string;
|
|
env?: Record<string, string>;
|
|
stdin?: string;
|
|
timeoutMs?: number;
|
|
}
|
|
|
|
export interface SandboxLeaseHandle {
|
|
providerLeaseId: string;
|
|
metadata: Record<string, unknown>;
|
|
/**
|
|
* The real provider-side expiry the provider granted, as an ISO 8601 timestamp.
|
|
* A provider that honors a requested deadline returns the actual expiry it
|
|
* configured. Absent when the provider granted no bounded lifetime.
|
|
*/
|
|
expiresAt?: string | null;
|
|
}
|
|
|
|
export interface PreparedSandboxWorkspace {
|
|
remotePath?: string | null;
|
|
metadata?: Record<string, unknown>;
|
|
}
|
|
|
|
export interface SandboxExecuteResult {
|
|
exitCode: number | null;
|
|
stdout: string;
|
|
stderr: string;
|
|
}
|
|
|
|
export interface SandboxProvider {
|
|
readonly provider: SandboxEnvironmentProvider;
|
|
readonly supportsReusableLeases?: boolean;
|
|
validateConfig(config: SandboxEnvironmentConfig): Promise<SandboxProviderValidationResult>;
|
|
probe(config: SandboxEnvironmentConfig): Promise<EnvironmentProbeResult>;
|
|
acquireLease(input: AcquireSandboxLeaseInput): Promise<SandboxLeaseHandle>;
|
|
resumeLease(input: ResumeSandboxLeaseInput): Promise<SandboxLeaseHandle | null>;
|
|
releaseLease(input: ReleaseSandboxLeaseInput): Promise<void>;
|
|
destroyLease(input: DestroySandboxLeaseInput): Promise<void>;
|
|
matchesReusableLease(input: {
|
|
config: SandboxEnvironmentConfig;
|
|
lease: { providerLeaseId: string | null; metadata: Record<string, unknown> | null };
|
|
}): boolean;
|
|
configFromLeaseMetadata(metadata: Record<string, unknown>): SandboxEnvironmentConfig | null;
|
|
prepareWorkspace?(input: PrepareSandboxWorkspaceInput): Promise<PreparedSandboxWorkspace>;
|
|
execute?(input: SandboxExecuteInput): Promise<SandboxExecuteResult>;
|
|
}
|
|
|
|
function assertProviderConfig<T extends SandboxEnvironmentConfig>(
|
|
provider: SandboxEnvironmentProvider,
|
|
config: SandboxEnvironmentConfig,
|
|
): asserts config is T {
|
|
if (config.provider !== provider) {
|
|
throw new Error(`Sandbox provider "${provider}" received config for provider "${config.provider}".`);
|
|
}
|
|
}
|
|
|
|
function buildFakeSandboxProbe(config: FakeSandboxEnvironmentConfig): EnvironmentProbeResult {
|
|
return {
|
|
ok: true,
|
|
driver: "sandbox",
|
|
summary: `Fake sandbox provider is ready for image ${config.image}.`,
|
|
details: {
|
|
provider: config.provider,
|
|
image: config.image,
|
|
reuseLease: config.reuseLease,
|
|
},
|
|
};
|
|
}
|
|
|
|
class FakeSandboxProvider implements SandboxProvider {
|
|
readonly provider = "fake" as const;
|
|
readonly supportsReusableLeases = false;
|
|
|
|
async validateConfig(config: SandboxEnvironmentConfig): Promise<SandboxProviderValidationResult> {
|
|
assertProviderConfig<FakeSandboxEnvironmentConfig>(this.provider, config);
|
|
return {
|
|
ok: true,
|
|
summary: `Fake sandbox provider config is valid for image ${config.image}.`,
|
|
details: {
|
|
provider: config.provider,
|
|
image: config.image,
|
|
reuseLease: config.reuseLease,
|
|
},
|
|
};
|
|
}
|
|
|
|
async probe(config: SandboxEnvironmentConfig): Promise<EnvironmentProbeResult> {
|
|
assertProviderConfig<FakeSandboxEnvironmentConfig>(this.provider, config);
|
|
return buildFakeSandboxProbe(config);
|
|
}
|
|
|
|
async acquireLease(input: AcquireSandboxLeaseInput): Promise<SandboxLeaseHandle> {
|
|
assertProviderConfig<FakeSandboxEnvironmentConfig>(this.provider, input.config);
|
|
const providerLeaseId = input.config.reuseLease && this.supportsReusableLeases
|
|
? `sandbox://fake/${input.environmentId}/${input.executionWorkspaceId ?? "workspace"}/${input.agentId ?? "agent"}`
|
|
: `sandbox://fake/${input.heartbeatRunId}/${randomUUID()}`;
|
|
|
|
return {
|
|
providerLeaseId,
|
|
metadata: {
|
|
provider: input.config.provider,
|
|
image: input.config.image,
|
|
reuseLease: input.config.reuseLease,
|
|
},
|
|
};
|
|
}
|
|
|
|
async resumeLease(input: ResumeSandboxLeaseInput): Promise<SandboxLeaseHandle | null> {
|
|
assertProviderConfig<FakeSandboxEnvironmentConfig>(this.provider, input.config);
|
|
return {
|
|
providerLeaseId: input.providerLeaseId,
|
|
metadata: {
|
|
provider: input.config.provider,
|
|
image: input.config.image,
|
|
reuseLease: input.config.reuseLease,
|
|
resumedLease: true,
|
|
},
|
|
};
|
|
}
|
|
|
|
async releaseLease(): Promise<void> {
|
|
return;
|
|
}
|
|
|
|
async destroyLease(): Promise<void> {
|
|
return;
|
|
}
|
|
|
|
matchesReusableLease(input: {
|
|
config: SandboxEnvironmentConfig;
|
|
lease: { providerLeaseId: string | null; metadata: Record<string, unknown> | null };
|
|
}): boolean {
|
|
assertProviderConfig<FakeSandboxEnvironmentConfig>(this.provider, input.config);
|
|
return (
|
|
typeof input.lease.providerLeaseId === "string" &&
|
|
input.lease.providerLeaseId.length > 0 &&
|
|
input.lease.metadata?.provider === input.config.provider &&
|
|
input.lease.metadata?.reuseLease === true &&
|
|
input.lease.metadata?.image === input.config.image
|
|
);
|
|
}
|
|
|
|
configFromLeaseMetadata(metadata: Record<string, unknown>): SandboxEnvironmentConfig | null {
|
|
if (metadata.provider !== this.provider || typeof metadata.image !== "string") {
|
|
return null;
|
|
}
|
|
return {
|
|
provider: this.provider,
|
|
image: metadata.image,
|
|
reuseLease: metadata.reuseLease === true,
|
|
};
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Provider registry — built-in providers only.
|
|
// Plugin-backed providers are resolved through the plugin environment driver
|
|
// system at the environment-runtime layer.
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const registeredSandboxProviders = new Map<SandboxEnvironmentProvider, SandboxProvider>([
|
|
["fake", new FakeSandboxProvider()],
|
|
]);
|
|
|
|
/**
|
|
* Returns a built-in sandbox provider, or null if the provider key is not
|
|
* registered. Plugin-backed providers are not returned here — they are
|
|
* resolved through the plugin worker manager at the environment-runtime level.
|
|
*/
|
|
export function getSandboxProvider(provider: string): SandboxProvider | null {
|
|
return registeredSandboxProviders.get(provider as SandboxEnvironmentProvider) ?? null;
|
|
}
|
|
|
|
export function requireSandboxProvider(provider: string): SandboxProvider {
|
|
const sandboxProvider = getSandboxProvider(provider);
|
|
if (!sandboxProvider) {
|
|
throw new Error(`Sandbox provider "${provider}" is not registered as a built-in provider.`);
|
|
}
|
|
return sandboxProvider;
|
|
}
|
|
|
|
/**
|
|
* Returns true if the given provider key is handled by a built-in sandbox
|
|
* provider (as opposed to a plugin-backed provider).
|
|
*/
|
|
export function isBuiltinSandboxProvider(provider: string): boolean {
|
|
return registeredSandboxProviders.has(provider as SandboxEnvironmentProvider);
|
|
}
|
|
|
|
export function listSandboxProviders(): SandboxProvider[] {
|
|
return [...registeredSandboxProviders.values()];
|
|
}
|
|
|
|
export async function validateSandboxProviderConfig(
|
|
config: SandboxEnvironmentConfig,
|
|
): Promise<SandboxProviderValidationResult> {
|
|
return await requireSandboxProvider(config.provider).validateConfig(config);
|
|
}
|
|
|
|
export function sandboxConfigFromLeaseMetadata(
|
|
lease: Pick<{ metadata: Record<string, unknown> | null }, "metadata">,
|
|
): SandboxEnvironmentConfig | null {
|
|
const metadata = lease.metadata ?? {};
|
|
const provider = typeof metadata.provider === "string" ? getSandboxProvider(metadata.provider) : null;
|
|
return provider?.configFromLeaseMetadata(metadata) ?? null;
|
|
}
|
|
|
|
/**
|
|
* Reconstruct a sandbox environment config from lease metadata, including
|
|
* plugin-backed providers. For plugin-backed providers, the
|
|
* config is synthesized from lease metadata fields without requiring the
|
|
* built-in provider to be registered.
|
|
*/
|
|
export function sandboxConfigFromLeaseMetadataLoose(
|
|
lease: Pick<{ metadata: Record<string, unknown> | null }, "metadata">,
|
|
): SandboxEnvironmentConfig | null {
|
|
const metadata = lease.metadata ?? {};
|
|
const providerKey = typeof metadata.provider === "string" ? metadata.provider : null;
|
|
if (!providerKey) return null;
|
|
|
|
// Try built-in provider first.
|
|
const builtinProvider = getSandboxProvider(providerKey);
|
|
if (builtinProvider) {
|
|
return builtinProvider.configFromLeaseMetadata(metadata);
|
|
}
|
|
|
|
return {
|
|
...metadata,
|
|
provider: providerKey,
|
|
reuseLease: metadata.reuseLease === true,
|
|
} satisfies SandboxEnvironmentConfig;
|
|
}
|
|
|
|
export function findReusableSandboxProviderLeaseId(input: {
|
|
config: SandboxEnvironmentConfig;
|
|
leases: Array<{ providerLeaseId: string | null; metadata: Record<string, unknown> | null }>;
|
|
}): string | null {
|
|
const provider = getSandboxProvider(input.config.provider);
|
|
if (!provider) {
|
|
for (const lease of input.leases) {
|
|
const metadata = lease.metadata ?? {};
|
|
if (
|
|
typeof lease.providerLeaseId === "string" &&
|
|
lease.providerLeaseId.length > 0 &&
|
|
metadata.provider === input.config.provider &&
|
|
metadataMatchesPluginSandboxConfig(input.config, metadata)
|
|
) {
|
|
return lease.providerLeaseId;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
for (const lease of input.leases) {
|
|
if (provider.matchesReusableLease({ config: input.config, lease })) {
|
|
return lease.providerLeaseId;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function metadataMatchesPluginSandboxConfig(
|
|
config: SandboxEnvironmentConfig,
|
|
metadata: Record<string, unknown>,
|
|
): boolean {
|
|
if (metadata.reuseLease !== true) return false;
|
|
for (const [key, value] of Object.entries(config)) {
|
|
if (key === "provider" || key === "reuseLease") continue;
|
|
// Null is the normalized form of an unspecified optional provider setting.
|
|
// The provider may report the concrete default it realized (for example,
|
|
// Daytona resolves a null target to "us"), which remains compatible with
|
|
// the caller's lack of a preference.
|
|
if (value === undefined || value === null) continue;
|
|
if (JSON.stringify(metadata[key]) !== JSON.stringify(value)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
export async function probeSandboxProvider(
|
|
config: SandboxEnvironmentConfig,
|
|
): Promise<EnvironmentProbeResult> {
|
|
return await requireSandboxProvider(config.provider).probe(config);
|
|
}
|
|
|
|
export async function acquireSandboxProviderLease(input: {
|
|
config: SandboxEnvironmentConfig;
|
|
environmentId: string;
|
|
heartbeatRunId: string;
|
|
issueId: string | null;
|
|
agentId?: string | null;
|
|
executionWorkspaceId?: string | null;
|
|
reusableProviderLeaseId?: string | null;
|
|
requestedExpiresAt?: string | null;
|
|
}): Promise<SandboxLeaseHandle> {
|
|
const provider = requireSandboxProvider(input.config.provider);
|
|
if (provider.supportsReusableLeases && input.config.reuseLease && input.reusableProviderLeaseId) {
|
|
const resumedLease = await provider.resumeLease({
|
|
config: input.config,
|
|
providerLeaseId: input.reusableProviderLeaseId,
|
|
});
|
|
if (resumedLease) {
|
|
return resumedLease;
|
|
}
|
|
}
|
|
|
|
return await provider.acquireLease({
|
|
config: input.config,
|
|
environmentId: input.environmentId,
|
|
heartbeatRunId: input.heartbeatRunId,
|
|
issueId: input.issueId,
|
|
agentId: input.agentId,
|
|
executionWorkspaceId: input.executionWorkspaceId,
|
|
requestedExpiresAt: input.requestedExpiresAt,
|
|
});
|
|
}
|
|
|
|
export async function resumeSandboxProviderLease(input: {
|
|
config: SandboxEnvironmentConfig;
|
|
providerLeaseId: string;
|
|
}): Promise<SandboxLeaseHandle | null> {
|
|
return await requireSandboxProvider(input.config.provider).resumeLease(input);
|
|
}
|
|
|
|
export async function releaseSandboxProviderLease(input: {
|
|
config: SandboxEnvironmentConfig;
|
|
providerLeaseId: string | null;
|
|
status: Extract<EnvironmentLeaseStatus, "released" | "expired" | "failed">;
|
|
}): Promise<void> {
|
|
await requireSandboxProvider(input.config.provider).releaseLease(input);
|
|
}
|
|
|
|
export async function destroySandboxProviderLease(input: {
|
|
config: SandboxEnvironmentConfig;
|
|
providerLeaseId: string | null;
|
|
}): Promise<void> {
|
|
await requireSandboxProvider(input.config.provider).destroyLease(input);
|
|
}
|