mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 06:03:51 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - Native runs keep a warm Runner between turns of the same task, so
the next run can start fast
> - When the next run needs a new provider session (for example after an
agent setting or skill changes), it first retires the previous run's
warm Runner
> - That retirement uses the previous owner's close. When the close
cannot prove checkpoint suspension, the new run failed before any
provider work, with the previous owner's error
`provider_transport_failed: runner did not durably suspend before
checkpoint`
> - A governed-wait park (a saved question or review request) always
leaves such an owner: its question callback stays unsettled by design. A
failed Launcher stop RPC leaves one too
> - Nothing retried the run, and the task rested as "recovery needed"
with no provider work done
> - This pull request lets the new run retire the old owner when that
owner is contained, and forces the containment when the close left it
unproven
> - The benefit is that a fresh run never fails on its predecessor's
close, and the chaos harness now covers this class
## Linked Issues or Issue Description
**What happened?**
A new run on a task whose previous run left a warm Runner retained
failed within two minutes, before any provider turn. The error was
`provider_transport_failed: runner did not durably suspend before
checkpoint`. The run row recorded `executionRecovery: { kind:
"bootstrap", providerWorkStarted: false }`. Two runs of the same agent
on two tasks failed this way 47 seconds apart, after a configuration
change made both start new provider sessions. One predecessor had parked
on a `request_human_input` question; its callback never settled.
**Expected behavior**
A run that has done no provider work does not fail because its
predecessor's Runner could not prove suspension. The new session never
resumes the old checkpoint. Core must only prove that the old owner is
contained, and then start.
**Steps to reproduce**
1. Run a warm native task that parks on a saved question (chaos workload
Q1).
2. After the asking run settles, change the agent's adapter
configuration, so the next run cannot resume the saved session.
3. Answer the question. The follow-up run retires the parked owner and
fails with the error above.
Related: #18373 added the stopped-owner reset path that this change
extends.
## What Changed
- `closeWarmNativeSession` (server native executor): during retirement
for a different normalized session, accept an unrecoverable close when
the old owner is contained. A plugin task owner must show its
`executionStopped: true` receipt and a completed handoff. Without a task
owner, the Runner's own durable suspension
(`settlement.runnerSuspended`) is the proof. Unsettled Core tool
callbacks of the discarded conversation no longer block the reset.
- With a plugin task owner, any close error qualifies once the Launcher
receipt exists. This includes a failed `stop` that
`releaseRunnerProcessOwnership` rethrows, and "Controller journal drain
timed out": the discarded session's journal lives in its own state root.
Owners without a task keep the narrower rule. `--matrix` now rejects
session faults.
- `createPluginRunnerTaskOwner`: add `retireSupersededTask()`. When
close left the receipt unproven, the new run sends one confirmed `stop`
(not resent after a confirmed stop), takes the credential snapshot, and
calls `complete`. It never reads the old state.
- Same-session continuation, a handoff that still fails, other close
errors and failed instruction collection still block replacement.
- Chaos harness: add session fault SR1
(`tests/restart-chaos/session-faults.ts`). With Q1 and `--lifecycle
warm` (or `--daytona-warm`), the board changes
`adapterConfig.idleTimeoutMs` after the asking run settles and before it
answers. `--tasks 2 --concurrency 2` is the two-concurrent-runs variant.
Q1's oracle applies, plus `session_rotated_before_answer` and
`follow_up_new_session`.
- Docs: `doc/plugins/PLUGIN_RUNNER_EXECUTION.md` and the chaos README
describe the new boundary and cell.
## Verification
- RED on master: `native-session-executor.test.ts -t "permanently
rejected plugin close during reset"` fails the `pending-semantic` and
`stop-unconfirmed-at-close` cases with
`NativeSessionCloseUnrecoverableError: provider_transport_failed: runner
did not durably suspend before checkpoint`. GREEN with this change: all
identity-transition cases pass (49).
- Chaos SR1 local, master server code (`--env local --lifecycle warm
--workloads Q1 --faults SR1`, seeds 301 with 2 tasks and 303 with 1
task): all tasks pass, and the follow-up started a new provider session.
The local parked owner closes cleanly, so the local cell does not
reproduce the failure. It needs a Daytona task owner.
- Chaos SR1 local with this change (seed 302, 2 concurrent tasks on one
agent): 2/2 pass, `follow_up_new_session` true for both.
- Not run: the Daytona SR1 variant. No runner image matches this
checkout's runner content ID, and this change does not touch runner
inputs.
- `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts
question-handoff scheduler config` passes. Server and harness `tsc
--noEmit` pass.
## Risks
- The reset no longer waits for unsettled Core tool callbacks of the
discarded session. Their run is already terminal and their provider is
stopped, so no result can reach a provider, and the new session never
replays them. Core-side tool executions keep their own receipts under
the old run.
- A local owner without a task needs the Runner's durable suspension. A
local owner that did not suspend still blocks replacement, as before.
- Previous-release story: this changes no persisted state. Warm owners
live only in controller memory, so a deploy drops them as before.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, agentic coding with
tool use (shell, file edits, test runs) in Claude Code.
## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
470 lines
26 KiB
TypeScript
470 lines
26 KiB
TypeScript
import { measureRunPhase } from "../execution-preparation-timing.js";
|
|
import { createHash } from "node:crypto";
|
|
import { setTimeout as delay } from "node:timers/promises";
|
|
import { environmentTaskOperationSchema, environmentTaskResultSchema, parseEnvironmentTaskResult, type PluginEnvironmentTaskOperation, type PluginEnvironmentTaskResult, type PluginEnvironmentTaskCredential } from "@paperclipai/plugin-sdk";
|
|
import type { RunnerIngressEndpoint } from "@paperclipai/adapter-utils/runner-connectivity";
|
|
import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
|
|
type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent } from "../../vendor/paperclip-runner/index.js";
|
|
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js";
|
|
import type { NativeExecutionContext } from "./native-execution-context.js";
|
|
|
|
export async function verifyPluginRunnerTaskReattachment(
|
|
task: (operation: unknown) => Promise<unknown>, identity: unknown,
|
|
): Promise<void> {
|
|
const operation = environmentTaskOperationSchema.parse({ kind: "read_state", identity });
|
|
if (operation.kind !== "read_state") throw new Error("Plugin Runner recovery identity unavailable");
|
|
const status = environmentTaskResultSchema.parse(await task({ kind: "status" }));
|
|
if (status.kind !== "status" || status.executionStopped || status.phase !== "running") {
|
|
throw new Error("Plugin Runner is not running");
|
|
}
|
|
const result = environmentTaskResultSchema.parse(await task(operation));
|
|
if (result.kind !== "state" || result.state.schema !== "paperclip.runner.durable.state.v1"
|
|
|| Object.entries(operation.identity).some(([key, value]) => result.state[key] !== value)) {
|
|
throw new Error("Plugin Runner adoption identity mismatch");
|
|
}
|
|
}
|
|
|
|
/** Adapts a lease-bound task provider to the existing native process owner.
|
|
* No provider pid is treated as a local pid. Only executionStopped settles it.
|
|
*/
|
|
export function createPluginRunnerTaskOwner(input: {
|
|
executionContext?: NativeExecutionContext;
|
|
taskId: string;
|
|
task: (operation: unknown, options?: { expectedTaskId?: string }) => Promise<unknown>;
|
|
projectIds: readonly string[];
|
|
harness: string;
|
|
projectAuthCheckVersion?: 1;
|
|
resumeFrom?: string;
|
|
priorIdentity?: DurableRecoveryIdentity;
|
|
/** Current authenticated lease owner; the restored PRP identity may belong to its predecessor. */
|
|
authorityRunId?: string;
|
|
codexSourceRecoveryVersion?: 1;
|
|
credentialIdentity?: string;
|
|
accountIdentity?: string;
|
|
credential?: PluginEnvironmentTaskCredential;
|
|
onCredentials?: (credential: PluginEnvironmentTaskCredential) => Promise<void>;
|
|
onCredentialsUpdated?: (event: PrpEvent) => Promise<void>;
|
|
onSessionRetained?: (state: Record<string, unknown>) => Promise<void>;
|
|
onDispatched?: () => Promise<void> | void;
|
|
pollMs?: number;
|
|
warmTaskVersion?: 1;
|
|
releaseResumeVersion?: 1;
|
|
releasedSource?: DurableRecoveryIdentity;
|
|
onResumed?: (identity: DurableRecoveryIdentity) => Promise<void>;
|
|
onRetired?: (identity: DurableRecoveryIdentity) => Promise<void>;
|
|
githubBroker?: { url: string; token: string };
|
|
adoptIdentity?: DurableRecoveryIdentity;
|
|
}) {
|
|
const taskId = input.taskId;
|
|
if (!taskId) throw new Error("Plugin Runner physical task unavailable");
|
|
const pollMs = input.pollMs ?? 500;
|
|
let registrationGeneration = 0;
|
|
let activeOutbound: ReturnType<typeof connectRunnerPrpIngress> | null = null;
|
|
let preparedLaunchId: string | undefined;
|
|
let preparedIdentity: DurableRecoveryIdentity | undefined = input.adoptIdentity;
|
|
let launched = !!input.adoptIdentity;
|
|
let launchIdentity = input.adoptIdentity;
|
|
let stopRequested = false;
|
|
let released = false;
|
|
let submitted = !!input.adoptIdentity;
|
|
let detached = false;
|
|
let adoptionVerified = false;
|
|
let markReady!: () => void;
|
|
let failReady!: (error: unknown) => void;
|
|
let confirmStopped: (code: number, error?: Error) => void = () => {};
|
|
let stoppedState: Extract<PluginEnvironmentTaskResult, { kind: "status" }> | undefined;
|
|
let completed = false;
|
|
let retiredBeforeClaim = false;
|
|
let rejectFailure!: (error: unknown) => void;
|
|
const failure = new Promise<never>((_resolve, reject) => { rejectFailure = reject; });
|
|
void failure.catch(() => undefined);
|
|
const running = new Promise<void>((resolve, reject) => { markReady = resolve; failReady = reject; });
|
|
void running.catch(() => undefined);
|
|
if (input.adoptIdentity) markReady();
|
|
const call = async (operation: PluginEnvironmentTaskOperation) => {
|
|
const phase = ({ prepare: "execution.plugin_prepare", check_project_auth: "execution.plugin_project_auth",
|
|
submit: "execution.plugin_submit", connection: "execution.plugin_connection" } as const)[operation.kind as "prepare" | "check_project_auth" | "submit" | "connection"];
|
|
return parseEnvironmentTaskResult(operation, taskId, await (phase
|
|
? measureRunPhase(phase, () => input.task(operation, { expectedTaskId: taskId })) : input.task(operation, { expectedTaskId: taskId })));
|
|
};
|
|
let removeStartupAbort = () => {};
|
|
const bindStartupAbort = () => {
|
|
removeStartupAbort();
|
|
const context = input.executionContext;
|
|
if (!context) return;
|
|
const abort = () => {
|
|
if (input.executionContext !== context || !context.active) return;
|
|
stopRequested = true;
|
|
void call({ kind: "stop" }).catch(rejectFailure);
|
|
};
|
|
context.signal.addEventListener("abort", abort, { once: true });
|
|
removeStartupAbort = () => context.signal.removeEventListener("abort", abort);
|
|
if (context.signal.aborted) abort();
|
|
};
|
|
bindStartupAbort();
|
|
const checkProjectAuth = async (configurationId:string) => {
|
|
if (input.projectAuthCheckVersion !== 1) throw new Error("Plugin Runner managed project authentication validation unavailable");
|
|
const provider = input.harness === "codex" ? "openai" : input.harness === "claude" ? "anthropic" : input.harness;
|
|
const validation = await call({kind:"check_project_auth",configurationId,provider,projectIds:[...input.projectIds]});
|
|
if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled");
|
|
if (validation.kind !== "project_auth" || !validation.allowed || validation.configurationId !== configurationId
|
|
|| validation.provider !== provider) throw new Error("Plugin Runner project authentication conflicts with the selected managed account");
|
|
};
|
|
const authorizeRunnerAdoption = async (configurationId: string, identity: DurableRecoveryIdentity) => {
|
|
if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled");
|
|
if (!input.adoptIdentity || Object.entries(input.adoptIdentity).some(([key, value]) => identity[key as keyof DurableRecoveryIdentity] !== value)) {
|
|
throw new Error("Plugin Runner adoption identity mismatch");
|
|
}
|
|
await checkProjectAuth(configurationId);
|
|
preparedLaunchId = configurationId;
|
|
};
|
|
const prepareLaunch: RunnerLaunchPreparer = async (requirements, recovery) => {
|
|
if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled");
|
|
// Reconnecting the previous authority must not prepare it through the new run's lease.
|
|
if (recovery && input.adoptIdentity && Object.entries(input.adoptIdentity).every(([key,value]) => requirements.identity[key as keyof DurableRecoveryIdentity] === value)) {
|
|
await authorizeRunnerAdoption(recovery.configurationId, requirements.identity);
|
|
return recovery;
|
|
}
|
|
const authorityRunId = input.authorityRunId ?? input.executionContext?.execution.binding.runId;
|
|
const sourceRecovery = !!authorityRunId && requirements.identity.runId !== authorityRunId;
|
|
if (sourceRecovery && (input.codexSourceRecoveryVersion !== 1 || !input.resumeFrom || !input.priorIdentity || !input.accountIdentity ||
|
|
input.harness !== "codex" || input.adoptIdentity || Object.entries(input.priorIdentity).some(([key, value]) =>
|
|
requirements.identity[key as keyof DurableRecoveryIdentity] !== value))) {
|
|
throw new Error("Plugin Runner source reconciliation unavailable");
|
|
}
|
|
if (input.githubBroker) {
|
|
const description = await call({ kind: "describe" });
|
|
if (description.kind !== "description" || description.githubCredentialBrokerVersion !== 1) {
|
|
throw new Error("Update the environment plugin to support the GitHub credential broker v1");
|
|
}
|
|
}
|
|
const result = await call(environmentTaskOperationSchema.parse({ kind: "prepare", requirements,
|
|
...(input.githubBroker ? { githubBroker: input.githubBroker } : {}),
|
|
projectIds: [...input.projectIds], ...(recovery ? { recovery } : {}),
|
|
...(input.resumeFrom && (!authorityRunId || !launchIdentity || launchIdentity.runId === authorityRunId || sourceRecovery)
|
|
? { resumeFrom: input.resumeFrom } : {}),
|
|
...(input.accountIdentity ? { accountIdentity: input.accountIdentity } : {}),
|
|
...(launched && preparedIdentity && requirements.identity.runId !== preparedIdentity.runId
|
|
? { priorIdentity: preparedIdentity } : {}),
|
|
}));
|
|
if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled");
|
|
if (result.kind !== "prepared") throw new Error("Plugin Runner preparation unavailable");
|
|
if (input.projectAuthCheckVersion !== 1) throw new Error("Plugin Runner managed project authentication validation unavailable");
|
|
if (launched || !result.projectAuthCheckAtSubmit) await checkProjectAuth(result.launch.configurationId);
|
|
preparedLaunchId = result.launch.configurationId;
|
|
preparedIdentity = requirements.identity;
|
|
return result.launch;
|
|
};
|
|
const readRunnerState = async () => {
|
|
const identity = submitted ? preparedIdentity : input.priorIdentity ?? preparedIdentity;
|
|
if (!identity) throw new Error("Plugin Runner state identity unavailable");
|
|
const result = await call({ kind: "read_state", identity,
|
|
...(!submitted && input.resumeFrom ? { resumeFrom: input.resumeFrom } : {}),
|
|
});
|
|
if (result.kind !== "state") throw new Error("Plugin Runner state unavailable");
|
|
return result.state;
|
|
};
|
|
const readStatus = async (deadline = Date.now() + 15_000) => {
|
|
for (;;) {
|
|
if (stoppedState) return stoppedState;
|
|
try {
|
|
const state = await call({ kind: "status" });
|
|
if (state.kind === "status") {
|
|
if (state.executionStopped === true) {
|
|
stoppedState = state;
|
|
confirmStopped(state.exitCode ?? (state.phase === "completed" ? 0 : 1));
|
|
}
|
|
return state;
|
|
}
|
|
} catch { /* A failed read is not proof that execution stopped. */ }
|
|
if (Date.now() >= deadline) throw new Error("Plugin Runner status unavailable; reconcile the saved task");
|
|
await delay(pollMs);
|
|
}
|
|
};
|
|
const stopAndConfirm = async () => {
|
|
await call({ kind: "stop" });
|
|
const deadline = Date.now() + 15_000;
|
|
do {
|
|
const state = await readStatus(deadline);
|
|
if (state.executionStopped === true) return;
|
|
await delay(pollMs);
|
|
} while (Date.now() < deadline);
|
|
throw new Error("Plugin Runner termination is unconfirmed; retain the lease for cleanup");
|
|
};
|
|
const launcher = (spec: RunnerProcessLaunchSpec): RunnerProcessHandle => {
|
|
if (launched || released) throw new Error("Plugin Runner replacement requires a new task lease");
|
|
const native = spec.nativeRunner;
|
|
if (!preparedLaunchId) throw new Error("Plugin Runner launch requires preparation");
|
|
if (!native || (native.lifecyclePolicy?.mode !== "per_turn" && !(native.lifecyclePolicy?.mode === "warm" && input.accountIdentity && input.warmTaskVersion === 1))
|
|
|| !preparedIdentity || Object.entries(preparedIdentity).some(([key, value]) => native.identity[key as keyof DurableRecoveryIdentity] !== value)) {
|
|
throw new Error("Plugin Runner requires a structured per-turn native launch");
|
|
}
|
|
const operation = environmentTaskOperationSchema.parse({
|
|
kind: "submit", preparedLaunchId, projectIds: [...input.projectIds], bootstrapTicket: native.ticket,
|
|
...(input.resumeFrom ? { resumeFrom: input.resumeFrom } : {}),
|
|
...(input.credentialIdentity ? { credentialIdentity: input.credentialIdentity } : {}),
|
|
...(input.accountIdentity ? { accountIdentity: input.accountIdentity } : {}),
|
|
...(input.credential ? { credential: input.credential } : {}),
|
|
runner: { protocolMin: RUNNER_PRP_PROTOCOL_MIN, protocolMax: RUNNER_PRP_PROTOCOL_MAX,
|
|
harness: input.harness,
|
|
runnerId: native.identity.runnerInstanceId, leaseId: native.identity.environmentLeaseId,
|
|
runId: native.identity.runId, sessionId: native.identity.normalizedSessionId,
|
|
turnId: native.identity.turnId, itemId: native.identity.itemId },
|
|
launch: { runnerVersion: native.runnerVersion, runnerDigest: native.runnerDigest,
|
|
maxOutboxBytes: native.maxOutboxBytes, p0ReserveBytes: native.p0ReserveBytes,
|
|
maxRuntimeMs: native.maxRuntimeMs, maxLifetimeMs: native.maxLifetimeMs,
|
|
reconnectGraceMs: native.reconnectGraceMs, lifecyclePolicy: native.lifecyclePolicy,
|
|
},
|
|
});
|
|
launchIdentity = native.identity;
|
|
launched = true;
|
|
const child: RunnerProcessHandle["child"] = { exitCode: null, signalCode: null,
|
|
kill: () => {
|
|
stopRequested = true;
|
|
if (native.lifecyclePolicy?.mode === "warm" && submitted) void stopAndConfirm().catch(rejectFailure);
|
|
return true;
|
|
} };
|
|
const completion = new Promise<Awaited<RunnerProcessHandle["completion"]>>(resolve => {
|
|
confirmStopped = (code, error) => {
|
|
if (child.exitCode !== null) return;
|
|
child.exitCode = code;
|
|
failReady(error ?? new Error("Plugin Runner stopped before connection"));
|
|
resolve({ code, signal: null, stdout: "", stderr: error?.message ?? "" });
|
|
};
|
|
});
|
|
void (async () => {
|
|
if (released || stopRequested) {
|
|
failReady(new Error("Plugin Runner startup cancelled"));
|
|
confirmStopped(1);
|
|
return;
|
|
}
|
|
environmentTaskOperationSchema.parse(operation);
|
|
// Persist/mark dispatch before crossing the provider boundary. A lost reply
|
|
// must reconcile this attempt and must never launch another task.
|
|
await input.onDispatched?.();
|
|
if (released || stopRequested) {
|
|
failReady(new Error("Plugin Runner startup cancelled"));
|
|
confirmStopped(1);
|
|
return;
|
|
}
|
|
submitted = true;
|
|
const result = await call(operation).catch(async () => {
|
|
// Submission can have succeeded remotely. Inspect the same saved task.
|
|
await readStatus();
|
|
});
|
|
if (result?.kind === "admission_rejected") {
|
|
submitted = false;
|
|
removeStartupAbort();
|
|
const error = new Error(`runner_task_admission_rejected: ${result.reason}`);
|
|
rejectFailure(error);
|
|
confirmStopped(1, error);
|
|
return;
|
|
}
|
|
let stopSent = false;
|
|
while (child.exitCode === null) {
|
|
if (detached) return;
|
|
if (stopRequested && !stopSent) { await call({ kind: "stop" }); stopSent = true; }
|
|
const state = await readStatus();
|
|
if (state.phase === "running" && !stopRequested) {
|
|
markReady();
|
|
// PRP owns live failure detection; warm idle tasks must not keep polling Launcher.
|
|
if (native.lifecyclePolicy?.mode === "warm") return;
|
|
}
|
|
if (state.executionStopped === true) return;
|
|
await delay(pollMs);
|
|
}
|
|
})().catch(error => {
|
|
if (stoppedState) return;
|
|
failReady(error);
|
|
rejectFailure(new Error("Plugin Runner operation failed; reconcile the saved task"));
|
|
if (!submitted) confirmStopped(1);
|
|
});
|
|
return { child, completion, restart: null };
|
|
};
|
|
const registration = async (authority: DurablePrpControlPlane, runId: string, signal?: AbortSignal, expectedIdentity?: DurableRecoveryIdentity) => {
|
|
const desired = expectedIdentity ? structuredClone(expectedIdentity) : undefined;
|
|
const generation = ++registrationGeneration;
|
|
let registrationReleased = false;
|
|
let outbound: ReturnType<typeof connectRunnerPrpIngress> | null = null;
|
|
let activation: Promise<void> | null = null;
|
|
const endpoint = async (): Promise<RunnerIngressEndpoint> => {
|
|
const result = await call({ kind: "connection" });
|
|
if (result.kind !== "connection") throw new Error("Plugin Runner connection unavailable");
|
|
return { ...result.endpoint, refresh: endpoint, close: async () => {} };
|
|
};
|
|
return {
|
|
connection: { mode: "external" as const },
|
|
startupFailureCode: "runner_ingress_unavailable" as const,
|
|
activate: () => {
|
|
activation = (async () => {
|
|
if (input.adoptIdentity) {
|
|
if (!desired || runId === input.adoptIdentity.runId) {
|
|
if (desired && Object.entries(input.adoptIdentity).some(([key, value]) => desired[key as keyof DurableRecoveryIdentity] !== value)) {
|
|
throw new Error("Plugin Runner adoption identity mismatch");
|
|
}
|
|
await verifyPluginRunnerTaskReattachment(input.task, input.adoptIdentity);
|
|
} else if (!preparedIdentity || Object.entries(preparedIdentity).some(([key, value]) => desired[key as keyof DurableRecoveryIdentity] !== value)
|
|
|| ["runnerInstanceId", "environmentLeaseId", "normalizedSessionId"].some(key => desired[key as keyof DurableRecoveryIdentity] !== input.adoptIdentity![key as keyof DurableRecoveryIdentity])) {
|
|
throw new Error("Plugin Runner adoption identity mismatch");
|
|
}
|
|
} else await running;
|
|
if (registrationReleased || signal?.aborted) throw new Error("Plugin Runner startup cancelled");
|
|
const ingress = await endpoint();
|
|
if (registrationReleased || signal?.aborted) throw new Error("Plugin Runner startup cancelled");
|
|
await activeOutbound?.close();
|
|
if (registrationReleased || signal?.aborted) throw new Error("Plugin Runner startup cancelled");
|
|
outbound = connectRunnerPrpIngress({ authority, endpoint: ingress });
|
|
activeOutbound = outbound;
|
|
void outbound.failure?.catch(rejectFailure);
|
|
await outbound.ready;
|
|
})();
|
|
void activation.catch(() => undefined);
|
|
},
|
|
ready: async () => { await activation; },
|
|
failure,
|
|
checkpoint: async (settlement: "settled" | "unsettled") => {
|
|
if (submitted) { stopRequested = true; await stopAndConfirm(); }
|
|
if (submitted && input.accountIdentity && input.onCredentials) {
|
|
const snapshot = await call({ kind: "credentials", accountIdentity: input.accountIdentity });
|
|
if (snapshot.kind !== "credentials") throw new Error("Plugin Runner credential snapshot unavailable");
|
|
if (snapshot.credential !== null) await input.onCredentials(snapshot.credential);
|
|
}
|
|
if (settlement === "settled" && stoppedState?.sessionStateAvailable === true && input.onSessionRetained) {
|
|
const state = await readRunnerState();
|
|
if (state.schema !== "paperclip.runner.durable.state.v1" || state.lifecycle !== "suspended"
|
|
|| !preparedIdentity || Object.entries(preparedIdentity).some(([key, value]) => state[key] !== value)) {
|
|
throw new Error("Plugin Runner suspended state identity mismatch");
|
|
}
|
|
await input.onSessionRetained(state);
|
|
}
|
|
if (submitted) {
|
|
await call({ kind: "complete" });
|
|
completed = true;
|
|
const identity = preparedIdentity ?? launchIdentity ?? input.priorIdentity;
|
|
if (identity) await input.onRetired?.(identity);
|
|
}
|
|
},
|
|
release: async (reason?: "detach") => {
|
|
registrationReleased = true;
|
|
if (generation === registrationGeneration) released = true;
|
|
if (reason === "detach") { released = true; detached = true; }
|
|
// Closing WSS does not retire the provider process or release its lease.
|
|
await outbound?.close();
|
|
},
|
|
};
|
|
};
|
|
const driver: RunnerExecutionDriver = {
|
|
get releaseResume() {
|
|
if (input.releaseResumeVersion !== 1 || input.warmTaskVersion !== 1 || !input.accountIdentity) return undefined;
|
|
return {
|
|
releasedSource: input.releasedSource,
|
|
release: async (identity: DurableRecoveryIdentity) => {
|
|
requireReleaseResume();
|
|
const outbound = activeOutbound;
|
|
outbound?.quiesce();
|
|
await release(identity);
|
|
await outbound?.close();
|
|
if (activeOutbound === outbound) activeOutbound = null;
|
|
},
|
|
resume: async (identity: DurableRecoveryIdentity, ticket: string) => {
|
|
const outcome = await resume(identity, ticket);
|
|
if (outcome === "resumed") await input.onResumed?.(identity);
|
|
return outcome;
|
|
},
|
|
};
|
|
},
|
|
get authorityRunId() { return input.authorityRunId ?? input.executionContext?.execution.binding.runId; },
|
|
get codexSourceRecoveryVersion() { return input.codexSourceRecoveryVersion; },
|
|
prepareLaunch, authorizeRunnerAdoption, readRunnerState, runnerProcessLauncher: launcher,
|
|
// The provider resolves the authorized retained task before each state operation.
|
|
prepareExternalRunnerState: async () => {},
|
|
archiveExternalRunnerState: async archive => {
|
|
if (!input.resumeFrom) throw new Error("Plugin Runner archive requires a retained task");
|
|
const result = await call({ kind: "archive_state", ...archive, resumeFrom: input.resumeFrom });
|
|
if (result.kind !== "state") throw new Error("Plugin Runner archived state unavailable");
|
|
return result.state;
|
|
},
|
|
controlPlaneRegistration: (authority, identity, signal) => registration(authority, identity?.runId ?? "", signal, identity),
|
|
...(input.adoptIdentity ? { adoptExistingRunner: {
|
|
// Provider ownership is attested by Launcher, never by a controller-local PID.
|
|
pid: null, processGroupId: null, startedAt: null,
|
|
isAlive: async () => {
|
|
if (!adoptionVerified) { if ((await readStatus()).executionStopped === true) return false; adoptionVerified = true; }
|
|
// Authenticated PRP detects disconnects; this cache never asserts termination.
|
|
return stoppedState === undefined;
|
|
},
|
|
signal: async () => { stopRequested = true; await stopAndConfirm(); return true; },
|
|
} } : {}),
|
|
};
|
|
const readWorkspaceFile = async (path: string, maxBytes: number): Promise<Buffer> => {
|
|
if (!submitted || !preparedIdentity || released || stopRequested) throw new Error("Plugin Runner file access unavailable");
|
|
const result = await call(environmentTaskOperationSchema.parse({ kind: "read_file", identity: preparedIdentity,
|
|
projectIds: [...input.projectIds], path, maxBytes }));
|
|
if (released || stopRequested || result.kind !== "file" || result.byteSize > maxBytes) throw new Error("Plugin Runner file access unavailable");
|
|
const bytes = Buffer.from(result.base64, "base64");
|
|
if (bytes.length !== result.byteSize || bytes.toString("base64") !== result.base64 ||
|
|
createHash("sha256").update(bytes).digest("hex") !== result.sha256) throw new Error("Plugin Runner file integrity check failed");
|
|
return bytes;
|
|
};
|
|
const requireReleaseResume = () => {
|
|
if (released || stopRequested || detached) throw new Error("Plugin Runner lifecycle operation cancelled");
|
|
if (input.releaseResumeVersion !== 1 || input.warmTaskVersion !== 1 || !input.accountIdentity) {
|
|
throw new Error("Plugin Runner release/resume unavailable");
|
|
}
|
|
};
|
|
// The caller owns settlement, connection quieting and exact-ticket retries.
|
|
const release = async (identity: DurableRecoveryIdentity): Promise<void> => {
|
|
requireReleaseResume();
|
|
await call(environmentTaskOperationSchema.parse({ kind: "release", identity }));
|
|
requireReleaseResume();
|
|
};
|
|
const resume = async (identity: DurableRecoveryIdentity, bootstrapTicket: string): Promise<"resumed" | "unavailable"> => {
|
|
requireReleaseResume();
|
|
const result = await call(environmentTaskOperationSchema.parse({ kind: "resume", identity, bootstrapTicket }));
|
|
requireReleaseResume();
|
|
if (result.kind !== "resume") throw new Error("Plugin Runner resume result unavailable");
|
|
if (result.outcome === "unavailable") {
|
|
const state = await call({ kind: "status" }).catch(() => undefined);
|
|
retiredBeforeClaim = state?.kind === "status" && state.executionStopped === true && state.sessionStateAvailable === true;
|
|
}
|
|
return result.outcome;
|
|
};
|
|
// A successor that discards this owner's session must not inherit its
|
|
// failed close. Repeat the unsettled checkpoint's task obligations: confirmed
|
|
// stop (sent once), credential handoff, then completion. Never reads state.
|
|
const retireSupersededTask = async () => {
|
|
if (!submitted || detached) return false;
|
|
if (!completed) {
|
|
stopRequested = true;
|
|
if (stoppedState?.executionStopped !== true) await stopAndConfirm();
|
|
if (input.accountIdentity && input.onCredentials) {
|
|
const snapshot = await call({ kind: "credentials", accountIdentity: input.accountIdentity });
|
|
if (snapshot.kind !== "credentials") throw new Error("Plugin Runner credential snapshot unavailable");
|
|
if (snapshot.credential !== null) await input.onCredentials(snapshot.credential);
|
|
}
|
|
await call({ kind: "complete" });
|
|
completed = true;
|
|
const identity = preparedIdentity ?? launchIdentity ?? input.priorIdentity;
|
|
if (identity) await input.onRetired?.(identity);
|
|
}
|
|
return stoppedState?.executionStopped === true && completed && !detached;
|
|
};
|
|
return { launcher, registration, driver, readWorkspaceFile, release, resume, retireSupersededTask,
|
|
// A warm transport outlives its first lease and invocation's private home.
|
|
credentialsUpdated: async (event: PrpEvent) => { await input.onCredentialsUpdated?.(event); },
|
|
// This is a lease-bound Launcher receipt, not a terminal phase or a sent
|
|
// stop request. Completion also proves credential/writeback obligations ran.
|
|
isRetired: () => stoppedState?.executionStopped === true && completed && !detached,
|
|
retiredBeforeClaim: () => retiredBeforeClaim,
|
|
rebind(next: typeof input) {
|
|
if (!launched || stopRequested || stoppedState || detached || next.taskId !== taskId || next.harness !== input.harness ||
|
|
input.accountIdentity !== next.accountIdentity || input.credentialIdentity !== next.credentialIdentity ||
|
|
JSON.stringify(input.projectIds) !== JSON.stringify(next.projectIds)) throw new Error("Plugin warm task cannot be rebound");
|
|
input = next;
|
|
released = false;
|
|
bindStartupAbort();
|
|
},
|
|
};
|
|
|
|
}
|