Files
PaperClipAI/server/src/services/native-runtime/plugin-runner-task.ts
T
DottaandPaperclip 596bb8a512 fix(native-runtime): classify exited plugin Runner on restart reattachment (#23769)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native remote runs use restart recovery (`reattach_remote_runner`)
to reattach to an existing Runner after a Core restart or deploy
> - For `plugin_task` Runners, `verifyPluginRunnerTaskReattachment`
threw a raw `Error("Plugin Runner is not running")` when the Runner
exited before reattachment, and `migrateRunnerdStateRoot` did not wrap
that error with `withRemoteRunnerTurnProof`
> - Without a structured `RemoteRunnerRecoveryError`, the executor never
emitted `native.remote_runner_recovery_failed` and
`requestRestartInterruptedTurnRetry` could not recognize the exited
Runner, leaving the run permanently failed
> - This pull request updates `verifyPluginRunnerTaskReattachment` to
throw structured `RemoteRunnerRecoveryError` diagnostics (distinguishing
proven `executionStopped === true` exits from `probe_failed`) and wraps
the call in `migrateRunnerdStateRoot` with `withRemoteRunnerTurnProof`
> - The benefit is that stopped `plugin_task` Runners record consistent
exit diagnostics and turn-proof evidence during restart reattachment so
recovery policy can classify and retry them accurately

## Linked Issues or Issue Description

**What happened?**
When Core restarts while a `per_turn` `plugin_task` Runner is active and
the Runner exits before `reattach_remote_runner` runs,
`verifyPluginRunnerTaskReattachment` throws a raw `Error("Plugin Runner
is not running")`. The executor does not emit
`native.remote_runner_recovery_failed`, does not attach
`providerTurnIssued: false` from the controller journal, and
`requestRestartInterruptedTurnRetry` fails to recognize the exited
Runner.

**Expected behavior**
When `status.executionStopped === true`,
`verifyPluginRunnerTaskReattachment` throws a
`RemoteRunnerRecoveryError` with `stage: "process_verification"` and
`reason: "process_not_running"`, attaches best-effort redacted
exited-runner diagnostics from `read_state` when
`status.sessionStateAvailable === true`, and `migrateRunnerdStateRoot`
wraps the error with `withRemoteRunnerTurnProof(error, scoped)`. When
the status probe returns a non-status result or a non-running phase
without `executionStopped === true`, it throws
`RemoteRunnerRecoveryError` with `reason: "probe_failed"` instead of
falsely proving exit.

**Steps to reproduce**
1. Start a native run backed by a `plugin_task` Runner with a controller
journal that proves no turn was issued.
2. Restart Core and trigger `reattach_remote_runner` after the plugin
task reports `executionStopped: true`.
3. Observe that `verifyPluginRunnerTaskReattachment` throws a raw
`Error("Plugin Runner is not running")` and
`executePaperclipNativeSession` does not emit
`native.remote_runner_recovery_failed`.

**Paperclip version or commit**
`f4baaa4f48` (`master`)

**Deployment mode**
Self-hosted server

**Installation method**
Built from source (pnpm dev / pnpm build)

## What Changed

- Updated `verifyPluginRunnerTaskReattachment` in
`server/src/services/native-runtime/plugin-runner-task.ts` to:
- Throw `RemoteRunnerRecoveryError({ stage: "process_verification",
reason: "probe_failed" })` when the status probe does not return `kind:
"status"` or reports `phase !== "running"` without `executionStopped ===
true`.
- Throw `RemoteRunnerRecoveryError({ stage: "process_verification",
reason: "process_not_running", ... })` when `status.executionStopped ===
true`, attaching best-effort redacted `describeExitedRemoteRunner` and
`describeExitedRemoteRunnerReason` diagnostics from `read_state` when
`status.sessionStateAvailable === true` and the identity matches.
- Wrapped `verifyPluginRunnerTaskReattachment(...)` in
`migrateRunnerdStateRoot`
(`server/src/services/native-runtime/native-session-executor.ts`) with
`withRemoteRunnerTurnProof(error, scoped)`, matching non-plugin sandbox
reattachment.
- Added unit tests in
`server/src/services/native-runtime/plugin-runner-task.test.ts` covering
stopped tasks with and without `sessionStateAvailable`, best-effort
`read_state` failure/mismatch, and `probe_failed` responses.
- Added an integration-style executor test in
`server/src/services/native-runtime/native-session-executor.test.ts`
verifying `providerTurnIssued: false` and
`native.remote_runner_recovery_failed` emission on
`reattach_remote_runner` for a stopped `plugin_task`.

## Verification

- Verified red-before-fix failures on both new test suites (`expected
Error: Plugin Runner is not running to be an instance of
RemoteRunnerRecoveryError`).
- `pnpm --dir server exec vitest run
src/services/native-runtime/plugin-runner-task.test.ts` — 120/120
passed.
- `pnpm --dir server exec vitest run
src/services/native-runtime/native-session-executor.test.ts -t
"classifies a stopped plugin_task on reattach_remote_runner|reattaches a
surviving plugin task through its owner"` — 6/6 passed.
- `pnpm --dir server typecheck` — passed.

## Risks

- Low risk. The change is scoped to `verifyPluginRunnerTaskReattachment`
and its `plugin_task` reattachment caller in `migrateRunnerdStateRoot`.
- Any caller or log parser that previously matched the unstructured
`"Plugin Runner is not running"` string now receives the standard
`RemoteRunnerRecoveryError`
(`runner_remote_process_identity_unavailable`) used by other remote
Runner reattachment paths. No existing tests or code in the repository
matched that string.
- Terminal phases without `executionStopped === true` report `reason:
"probe_failed"` rather than `process_not_running`, preserving the
invariant that only explicit `executionStopped === true` proves the task
and descendants stopped.

## Model Used

- Google DeepMind Gemini 4 Neon (Medium reasoning budget)

## 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-04 14:09:30 -06:00

681 lines
36 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, runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerReleaseResumeOutcome, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent,
} from "../../vendor/paperclip-runner/index.js";
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js";
import { redactSensitiveText } from "../../redaction.js";
import type { NativeExecutionContext } from "./native-execution-context.js";
import {
RemoteRunnerRecoveryError,
attachRemoteRunnerRecoveryDiagnostic,
describeExitedRemoteRunner,
describeExitedRemoteRunnerReason,
readRemoteRunnerRecoveryError,
type RemoteRunnerRecoveryDiagnostic,
} from "./remote-runner-recovery-diagnostics.js";
const RELAUNCH_TICKET_TTL_MS = 60_000;
function pluginRunnerStateMatchesIdentity(
state: Record<string, unknown>,
identity: Record<string, unknown>,
): boolean {
return state.schema === "paperclip.runner.durable.state.v1"
&& Object.entries(identity).every(([key, value]) => state[key] === value);
}
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");
let rawStatus: unknown;
try {
rawStatus = await task({ kind: "status" });
} catch (error) {
if (readRemoteRunnerRecoveryError(error)) throw error;
throw attachRemoteRunnerRecoveryDiagnostic(error, {
stage: "process_verification",
reason: "probe_transport_failed",
});
}
const parsedStatus = environmentTaskResultSchema.safeParse(rawStatus);
if (!parsedStatus.success || parsedStatus.data.kind !== "status") {
throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "probe_failed" });
}
const status = parsedStatus.data;
if (status.executionStopped === true) {
let exitedDiagnostics: Partial<RemoteRunnerRecoveryDiagnostic> = {};
if (status.sessionStateAvailable === true) {
try {
const result = environmentTaskResultSchema.parse(await task(operation));
if (result.kind === "state" && pluginRunnerStateMatchesIdentity(result.state, operation.identity)) {
exitedDiagnostics = {
...describeExitedRemoteRunner(result.state),
...describeExitedRemoteRunnerReason(result.state, redactSensitiveText),
};
}
} catch {
// Best-effort diagnostics: keep process_not_running even if state read fails.
}
}
throw new RemoteRunnerRecoveryError({
stage: "process_verification",
reason: "process_not_running",
...exitedDiagnostics,
});
}
if (status.phase !== "running") {
throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "probe_failed" });
}
const result = environmentTaskResultSchema.parse(await task(operation));
if (result.kind !== "state" || !pluginRunnerStateMatchesIdentity(result.state, operation.identity)) {
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;
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;
resumeLaunchInputsVersion?: 1;
resumeRelaunchedRunnerVersion?: 1;
resumeIdentityVersion?: 1;
relaunch?: { source: DurableRecoveryIdentity; runner: { version: string; digest: string } };
releasedSourceRunner?: { version: string; digest: string };
launchDigestVersion?: 1;
releasedSource?: DurableRecoveryIdentity;
sessionHandoff?: boolean;
githubBroker?: { url: string; token: string };
githubCredentialBrokerVersion?: 1;
configuredEnvironmentVersion?: 1;
configuredEnvironment?: Readonly<Record<string, string>>;
adoptIdentity?: DurableRecoveryIdentity;
mapReattachmentError?: (error: unknown) => unknown;
}) {
const taskId = input.taskId;
if (!taskId) throw new Error("Plugin Runner physical task unavailable");
const pollMs = input.pollMs ?? 500;
let registrationGeneration = 0;
let registeredAuthority: DurablePrpControlPlane | null = null;
let relaunchProgress: "none" | "sent" | "refused" = "none";
let activeOutbound: ReturnType<typeof connectRunnerPrpIngress> | null = null;
let preparedLaunchId: string | undefined;
const relaunchedTask = !input.adoptIdentity && input.resumeIdentityVersion === 1 ? input.relaunch?.source : undefined;
let preparedIdentity: DurableRecoveryIdentity | undefined = input.adoptIdentity ?? relaunchedTask;
let launched = !!(input.adoptIdentity ?? relaunchedTask);
let launchIdentity = input.adoptIdentity ?? relaunchedTask;
let stopRequested = false;
let stopSent = false;
let stopRequestInFlight: Promise<void> | null = null;
let stopInFlight: Promise<void> | null = null;
let released = false;
let submitted = launched;
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 pendingLaunch = () => {
const launch = new Promise<void>((resolve, reject) => { markReady = resolve; failReady = reject; });
void launch.catch(() => undefined);
return launch;
};
let running = pendingLaunch();
if (input.adoptIdentity) markReady();
const configuredEnvironmentFields = (launchesRunner: boolean) =>
input.configuredEnvironmentVersion === 1 && launchesRunner ? { configuredEnvironment: { ...input.configuredEnvironment } } : {};
let configuredEnvironmentDelivered: boolean | undefined = launched ? undefined : false;
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 })));
};
const sendStopOnce = (): Promise<void> => {
if (stopSent) return Promise.resolve();
stopRequestInFlight ??= call({ kind: "stop" })
.then(() => {
stopSent = true;
})
.finally(() => {
stopRequestInFlight = null;
});
return stopRequestInFlight;
};
let removeStartupAbort = () => {};
const bindStartupAbort = () => {
removeStartupAbort();
const context = input.executionContext;
if (!context) return;
const abort = () => {
if (input.executionContext !== context || !context.active) return;
stopRequested = true;
void sendStopOnce().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;
if (authorityRunId && requirements.identity.runId !== authorityRunId) {
throw new Error("Plugin Runner source reconciliation unavailable");
}
if (input.githubBroker && input.githubCredentialBrokerVersion !== 1) {
throw new Error("Update the environment plugin to support the GitHub credential broker v1");
}
const preparationDigest = input.launchDigestVersion === 1 ? runnerLaunchPreparationDigest(requirements) : undefined;
const result = await call(environmentTaskOperationSchema.parse({ kind: "prepare", requirements,
...(preparationDigest ? { preparationDigest, runDigest: runnerLaunchRunDigest(preparationDigest, requirements) } : {}),
...(input.githubBroker ? { githubBroker: input.githubBroker } : {}),
projectIds: [...input.projectIds], ...(recovery ? { recovery } : {}),
...(input.resumeFrom && (!authorityRunId || !launchIdentity || launchIdentity.runId === authorityRunId)
? { 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 (!result.projectAuthChecked && (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 recordStatusState = (state: Extract<PluginEnvironmentTaskResult, { kind: "status" }>) => {
if (state.executionStopped === true && !stoppedState) {
stoppedState = state;
confirmStopped(state.exitCode ?? (state.phase === "completed" ? 0 : 1));
}
return state;
};
const probeStatusOnce = async (shouldRecord = () => true) => {
if (stoppedState) return stoppedState;
try {
const state = await call({ kind: "status" });
if (state.kind === "status" && shouldRecord()) return recordStatusState(state);
} catch { /* A failed read is not proof that execution stopped. */ }
return stoppedState;
};
const readStatus = async (deadline = Date.now() + 15_000) => {
for (;;) {
const state = await probeStatusOnce();
if (state) return state;
if (Date.now() >= deadline) throw new Error("Plugin Runner status unavailable; reconcile the saved task");
await delay(pollMs);
}
};
const pollUntilStopped = async (deadline: number, shouldContinue = () => true) => {
let observedStatus = Boolean(stoppedState);
while (!stoppedState && shouldContinue()) {
const state = await probeStatusOnce(shouldContinue);
if (state) observedStatus = true;
if (state?.executionStopped === true) return { stopped: true, observedStatus };
if (!shouldContinue() || Date.now() >= deadline) break;
await delay(pollMs);
}
return { stopped: Boolean(stoppedState), observedStatus };
};
const stopAndConfirm = () => {
if (stopSent && stoppedState?.executionStopped === true) return Promise.resolve();
stopInFlight ??= (async () => {
await sendStopOnce();
const { stopped, observedStatus } = await pollUntilStopped(Date.now() + 15_000);
if (stopped) return;
throw new Error(observedStatus
? "Plugin Runner termination is unconfirmed; retain the lease for cleanup"
: "Plugin Runner status unavailable; reconcile the saved task");
})().finally(() => {
stopInFlight = null;
});
return stopInFlight;
};
const relaunchStopped = (spec: RunnerProcessLaunchSpec, relaunch: NonNullable<typeof input.relaunch>): RunnerProcessHandle => {
const native = spec.nativeRunner;
const source = relaunch.source;
const authority = registeredAuthority;
if (!native || native.lifecyclePolicy?.mode !== "warm" || !authority || !preparedIdentity
|| Object.entries(preparedIdentity).some(([key, value]) => native.identity[key as keyof DurableRecoveryIdentity] !== value)
|| (["runnerInstanceId", "environmentLeaseId", "normalizedSessionId"] as const).some(key => native.identity[key] !== source[key])
|| native.identity.runId === source.runId) {
throw new Error("Plugin Runner relaunch identity mismatch");
}
requireReleaseResume();
relaunchProgress = "none";
running = pendingLaunch();
const operation = environmentTaskOperationSchema.parse({ kind: "resume", identity: source, bootstrapTicket: native.ticket,
...resumeLaunchFields(),
runner: { runId: native.identity.runId, turnId: native.identity.turnId, itemId: native.identity.itemId } });
launchIdentity = native.identity;
configuredEnvironmentDelivered = "configuredEnvironment" in operation;
const child: RunnerProcessHandle["child"] = { exitCode: null, signalCode: null,
kill: () => { stopRequested = true; if (!stoppedState && !detached) 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 ?? "" });
};
});
const deadline = Date.now() + RELAUNCH_TICKET_TTL_MS;
void (async () => {
await input.onDispatched?.();
for (;;) {
if (released || stopRequested || detached) throw new Error("Plugin Runner startup cancelled");
let result: PluginEnvironmentTaskResult;
try {
relaunchProgress = "sent";
result = await call(operation);
} catch (error) {
if (Date.now() >= deadline) throw error;
await delay(250);
continue;
}
if (result.kind !== "resume") throw new Error("Plugin Runner resume result unavailable");
if (result.outcome === "unavailable") {
relaunchProgress = "refused";
const state = await call({ kind: "status" }).catch(() => undefined);
retiredBeforeClaim = state?.kind === "status" && state.executionStopped === true && state.sessionStateAvailable === true;
throw new Error("native_runner_reuse_unavailable");
}
if (!result.runner) throw new Error("native_runner_released_state_unsettled");
authority.acceptRelaunchedRunner(native.ticket, result.runner, relaunch.runner);
markReady();
return;
}
})().catch(error => {
failReady(error);
rejectFailure(error);
});
return { child, completion, restart: null };
};
const launcher = (spec: RunnerProcessLaunchSpec): RunnerProcessHandle => {
if (launched && input.relaunch && input.resumeIdentityVersion === 1) return relaunchStopped(spec, input.relaunch);
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 } : {}),
...configuredEnvironmentFields(true),
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;
configuredEnvironmentDelivered = "configuredEnvironment" in operation;
const child: RunnerProcessHandle["child"] = { exitCode: null, signalCode: null,
kill: () => {
stopRequested = true;
if (submitted && !stoppedState && !detached) 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;
}
while (child.exitCode === null) {
if (detached) return;
if (stopRequested) { await stopAndConfirm(); return; }
const state = await readStatus();
if (state.phase === "running" && !stopRequested) {
markReady();
// PRP owns live failure detection; active and warm idle tasks must not keep polling Launcher.
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;
registeredAuthority = authority;
let registrationReleased = false;
let outbound: ReturnType<typeof connectRunnerPrpIngress> | null = null;
let activation: Promise<void> | null = null;
let quiesceExitProbe: 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");
}
try {
await verifyPluginRunnerTaskReattachment(input.task, input.adoptIdentity);
} catch (error) {
throw input.mapReattachmentError ? input.mapReattachmentError(error) : error;
}
} 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");
let authenticatedOnce = false;
let reconnectStatusCheckInFlight = false;
const canRecord = () => !released && !registrationReleased && !detached && generation === registrationGeneration;
outbound = connectRunnerPrpIngress({
authority,
endpoint: ingress,
onStateChange: state => {
if (state === "authenticated") {
authenticatedOnce = true;
return;
}
const isReconnectAttempt = state === "reconnecting" || (state === "connecting" && authenticatedOnce);
if (!isReconnectAttempt || reconnectStatusCheckInFlight || stoppedState || stopRequested || !canRecord()) return;
reconnectStatusCheckInFlight = true;
void probeStatusOnce(canRecord).finally(() => { reconnectStatusCheckInFlight = false; });
},
});
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;
}
},
// The Runner is about to exit (its close suspend completed), as on release.
quiesce: () => {
outbound?.quiesce?.();
const canProbe = () => submitted && !stopRequested && !released && !registrationReleased && !detached && generation === registrationGeneration;
if (stoppedState || !canProbe()) return;
quiesceExitProbe ??= pollUntilStopped(Date.now() + 15_000, canProbe).then(() => undefined).finally(() => {
quiesceExitProbe = null;
});
},
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 adoptedRunner: NonNullable<RunnerExecutionDriver["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 driver: RunnerExecutionDriver = {
get releaseResume() {
if (input.releaseResumeVersion !== 1 || input.warmTaskVersion !== 1 || !input.accountIdentity) return undefined;
return {
releasedSource: input.releasedSource,
releasedSourceRunner: input.releasedSourceRunner,
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) => {
return await resume(identity, ticket);
},
};
},
get authorityRunId() { return input.authorityRunId ?? input.executionContext?.execution.binding.runId; },
get relaunchReleasedRunner() { return launched && input.resumeIdentityVersion === 1 ? input.relaunch?.source : undefined; },
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),
get adoptExistingRunner() { return input.adoptIdentity ? adoptedRunner : undefined; },
};
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");
}
};
const resumeLaunchFields = () => {
const handoffCredential = input.sessionHandoff && input.credential?.type === "claude-env"
? { accountIdentity: input.accountIdentity, environment: input.credential.environment }
: undefined;
const launchInputs = input.resumeLaunchInputsVersion === 1;
return {
...(handoffCredential ? { handoffCredential } : {}),
...(launchInputs && input.credential ? { credential: input.credential } : {}),
...configuredEnvironmentFields(!!input.sessionHandoff || launchInputs),
...(input.resumeRelaunchedRunnerVersion === 1 ? { relaunchedRunnerVersion: 1 as const } : {}),
};
};
// 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<RunnerReleaseResumeOutcome> => {
requireReleaseResume();
const result = await call(environmentTaskOperationSchema.parse({ kind: "resume", identity, bootstrapTicket, ...resumeLaunchFields() }));
requireReleaseResume();
if (result.kind !== "resume") throw new Error("Plugin Runner resume result unavailable");
if (result.outcome === "resumed" && input.sessionHandoff) configuredEnvironmentDelivered = input.configuredEnvironmentVersion === 1;
if (result.outcome === "unavailable") {
const state = await call({ kind: "status" }).catch(() => undefined);
retiredBeforeClaim = state?.kind === "status" && state.executionStopped === true && state.sessionStateAvailable === true;
}
if (result.outcome === "resumed" && result.runner && input.resumeRelaunchedRunnerVersion === 1) {
return { outcome: "resumed", runner: result.runner };
}
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;
}
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,
relaunchMayHaveStarted: () => relaunchProgress === "sent",
configuredEnvironmentDelivered: () => configuredEnvironmentDelivered,
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;
relaunchProgress = "none";
bindStartupAbort();
},
};
}