mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-01 23:43:16 +01:00
## Thinking Path > - Paperclip manages AI agents and their work. > - Native warm sessions retain a Runner owner between turns. > - Closing that owner must stop execution and preserve valid recovery state. > - A failed suspension can leave a rejected close promise after the task has stopped. > - A session reset then retries that same promise and blocks every fresh session. > - This PR separates task retirement proof from checkpoint reuse for a new session. > - A reset can proceed after exact stop proof, completed handoff, and file collection. ## Linked Issues or Issue Description Refs #18011. That change preserves checkpoint authority during warm preparation. This change handles a stopped owner whose checkpoint cannot be reused. Related: #14695 covers managed files retained with warm processes. A search found no duplicate stopped-owner reset fix. **What happened?** A warm Runner can stop and complete its task handoff while close reports `runner did not durably suspend before checkpoint`. The transport caches that rejected close promise. Core retains the warm owner. Each session reset retries the same promise before it can launch a provider. A controller restart clears the in-memory owner and permits recovery. **Expected behavior** A reset to a new normalized session should release the old owner when its exact task has proved that execution stopped and its handoff completed. Core must collect stopped instruction files before it admits the new session. An unconfirmed owner must continue to block replacement. **Steps to reproduce** 1. Complete a warm native run through a plugin task provider. 2. Change configuration so Core retires the warm owner. 3. Let the task stop and complete, but fail durable suspension proof. Close keeps its rejected promise. 4. Reset the session and start another run on the same task environment. 5. Observe the old close error before any new provider work starts. ## What Changed - Keep a lease-bound retirement receipt in the plugin task owner. It requires `executionStopped: true` and successful task completion after credential handoff. - Accept an unrecoverable suspension error only during retirement for a different normalized session, with that exact owner's receipt and settled Core tool results. - Collect stopped instruction files before releasing the warm owner. Preserve old checkpoint evidence. - Keep same-session, active-owner, incomplete-handoff, unrelated-owner, unresolved Core tool results, and other close-error fences. - Report Core tool settlement on the close error after ingress retirement and drain. Default missing proof to false. Expose the error through the server's Runner shim. Add regression tests and document the recovery boundary. ## Verification - The reset regression fails with the new handling disabled and passes with it enabled. - Both affected suites passed: 1,032 tests. The final 15 focused owner/reset cases pass after adding the tool-settlement guard. - The assembled regression uses the real task-owner and backend binding. Its controlled task provider proves stop and completion. Close returns the same rejected promise on every call. - Negative cases cover incomplete handoff, other close errors, same-session continuation, provider change with the same session ID, unrelated receipts, unresolved Core tool results, and failed file collection. Collection can later succeed without replaying stop or reading the old checkpoint. - Five real-process transport cases pass. They cover an insufficient suspension deadline, the cached rejected promise, late tool completion within and beyond the deadline, interruption, and result-persistence failure. Unsettled callbacks produce `semanticToolsSettled: false`. - `pnpm -r typecheck` passed with the repository's pinned Rust toolchain on PATH. After the final contract change, Runner TypeScript build and server `tsc --noEmit` passed. - The local full-suite run was stopped at the requester's direction. Full regression and build coverage are delegated to GitHub CI. - Full GitHub CI passed on `ef0040d80af679ce6d4a130468e15f75678c1f4c`. Standard Greptile reviewed the same commit: 5/5, zero comments. Apex then reviewed that same commit: 5/5, zero comments. Final checks confirm no unresolved review threads and no merge conflicts. - Initial full CI on `00c002fd5a` failed one scheduled-retry route test at 18/20 cancellations. Controlled cancellation latency reproduced the short poll-budget failure. Before the next cycle, master advanced with #18322, which coordinates that test at the first completed batch. The separate local timeout commit was dropped during rebase. The upstream test passes locally. The rebased run passed 46 targeted owner/reset and scheduled-retry route cases. This PR has no scheduled-retry source or test diff. - No deployed provider run or tenant rollout is claimed by these source tests. ## Risks The exception applies only to a new normalized session and an exact completed plugin task. The old checkpoint remains evidence and cannot authorize reuse through this path. The original suspension failure can remain visible on its run. This fix prevents repeated startup failures after a reset; it does not hide unconfirmed cleanup or make every suspension succeed. Missing task receipts and failed file collection continue to block replacement. No schema migration, plugin protocol change, Rust Runner binary change, or new polling is required. Tests use a controlled task boundary; they do not certify every external provider implementation. ## Model Used OpenAI Codex, GPT-6 family, with tool use and local code execution. The exact runtime model ID and context-window size are not exposed in this session. ## 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 references) - [x] My branch name describes the change and contains no internal issue or instance 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] Greptile Apex is 5/5 with no unresolved findings - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
348 lines
19 KiB
TypeScript
348 lines
19 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, 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 } from "../../vendor/paperclip-runner/index.js";
|
|
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.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: {
|
|
task: (operation: unknown) => Promise<unknown>;
|
|
projectIds: readonly string[];
|
|
harness: string;
|
|
projectAuthCheckVersion?: 1;
|
|
resumeFrom?: string;
|
|
priorIdentity?: DurableRecoveryIdentity;
|
|
credentialIdentity?: string;
|
|
accountIdentity?: string;
|
|
credential?: PluginEnvironmentTaskCredential;
|
|
onCredentials?: (credential: PluginEnvironmentTaskCredential) => Promise<void>;
|
|
onSessionRetained?: (state: Record<string, unknown>) => Promise<void>;
|
|
onDispatched?: () => Promise<void> | void;
|
|
pollMs?: number;
|
|
warmTaskVersion?: 1;
|
|
githubBroker?: { url: string; token: string };
|
|
adoptIdentity?: DurableRecoveryIdentity;
|
|
}) {
|
|
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 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) => void = () => {};
|
|
let stoppedState: Extract<PluginEnvironmentTaskResult, { kind: "status" }> | undefined;
|
|
let completed = 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"];
|
|
const result = environmentTaskResultSchema.parse(await (phase
|
|
? measureRunPhase(phase, () => input.task(operation)) : input.task(operation)));
|
|
if (result.kind !== (operation.kind === "read_file" ? "file" : operation.kind === "describe" ? "description" : operation.kind === "prepare" ? "prepared" : operation.kind === "check_project_auth" ? "project_auth" : ["read_state", "archive_state"].includes(operation.kind) ? "state" : ["status", "connection", "credentials"].includes(operation.kind) ? operation.kind : "accepted")) {
|
|
throw new Error("Plugin Runner returned an invalid operation result");
|
|
}
|
|
return result;
|
|
};
|
|
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;
|
|
}
|
|
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 ? { 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,
|
|
},
|
|
});
|
|
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 => {
|
|
if (child.exitCode !== null) return;
|
|
child.exitCode = code;
|
|
failReady(new Error("Plugin Runner stopped before connection"));
|
|
resolve({ code, signal: null, stdout: "", stderr: "" });
|
|
};
|
|
});
|
|
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;
|
|
try { await call(operation); } catch {
|
|
// Submission can have succeeded remotely. Inspect the same saved task.
|
|
await readStatus();
|
|
}
|
|
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) => {
|
|
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) {
|
|
await verifyPluginRunnerTaskReattachment(input.task, input.adoptIdentity);
|
|
} 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;
|
|
}
|
|
},
|
|
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 = {
|
|
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),
|
|
...(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;
|
|
};
|
|
return { launcher, registration, driver, readWorkspaceFile,
|
|
// 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,
|
|
rebind(next: typeof input) {
|
|
if (!launched || stopRequested || stoppedState || detached || 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;
|
|
},
|
|
};
|
|
|
|
}
|