Files
PaperClipAI/server/src/services/native-runtime/plugin-runner-task.ts
T
Nicky LeachandPaperclip e5351b240a Verify native Runner setup through plugin tasks (#17029)
## Thinking Path

> - Paperclip manages work for AI agents.
> - An environment plugin can own a Runner task.
> - The merged launch-preparation contract lets the execution owner
build the provider configuration.
> - Core still needs a task process owner and a setup test that uses
that configuration.
> - This PR connects the task API to the Runner process-owner contract.
> - Operators can test a plugin environment before Core sends it task
work.

## Linked Issues or Issue Description

**Subsystem affected**

Runner, plugin SDK, and agent environment tests.

**Problem or motivation**

A task-only environment cannot use the shell-based setup path. Core must
verify the Runner hello exchange and process cleanup through dedicated
task operations.

**Proposed solution**

Add a lease-bound task driver and use it for a bounded setup probe. Keep
heartbeat admission and task execution in #16978. This PR follows the
merged launch-preparation contract in #16997.

**Alternatives considered**

A provider declaration alone cannot prove that Runner and the provider
connect. A shell bridge would give the plugin an unnecessary command
interface.

## What Changed

- Pass structured Runner launch data to process owners. Support an
external connection and explicit detach.
- Add typed launch authentication checks and checkpoint operations.
Check lease, run, project, and retained-task authority.
- Connect launch preparation, PRP, termination proof, and credential
handoff to the task driver. Reject local environment overrides during
installed-account setup. Pass saved-account identity and credential home
directly from Core.
- Run a short-lived setup probe through the existing agent environment
test API. Require a verified provider hello and cleanup. Keep saved
Copilot account checks metadata-only through a dedicated task operation.
- Update the Copilot source identity because the shared transport source
changed. Keep provider behavior and the earlier identity fixture.

## Verification

- CI passes on `f987adec7`: 55 successful checks and 5 expected skips.
Standard Greptile and Apex are both 5/5 with no open findings. The
branch merges cleanly with current master.
- Repository typecheck and build pass after the rebase onto the
workspace-provider contract. Server typecheck and build also pass after
the final setup fix.
- The 110 focused lease, SDK, setup, Copilot, and route cases pass after
the rebase. All 14 setup cases pass after the final change. These
include a real local Runner with a test provider. The saved-agent
model-discovery case also passes.
- Apex found that Core's relative workspace marker failed the driver
path check, and non-Codex sessions omitted the observed model. Both
failures were reproduced and fixed. The probe leaves physical workspace
selection to plugin preparation. The transport reads each provider's
observed model and exposes it to the driver. All 14 setup cases, 6
transport peer cases, and both existing real Runner/OpenCode cases pass.
Runner build and server typecheck pass.
- The coverage audit removed two redundant cases, repeated fixture code,
and two extra real Runner launches. It kept authorization, credential
selection, cancellation, lost replies, termination proof, checkpoint
identity, and provider setup checks.
- The Copilot source-identity check passes. The added-line secret and
PII scan passes. The unmerged v52 attestation was regenerated after the
shared transport fix.
- CI on `13faeff02` caught one stale Copilot digest assertion after
attestation regeneration. The literal now matches the candidate
attestation, and all 49 installation cases pass. That CI lane otherwise
passed 1,818 cases.
- An earlier CI run hit an unchanged UI toast timing test. The separate
fix is tracked in #16952. Current CI passes that shard. CI also caught a
stale model-discovery assertion in this change; the assertion is fixed.
- The local full-suite run was stopped when master changed. The final CI
run supplies exact-head full-suite validation. No live Cloud or provider
test was run.

## Risks

- Native hello tests require a saved Core account or the installed
account. Local environment overrides are unsupported for
installed-account probes and fail before the provider runs.
- A native task provider must declare launch preparation and
authentication-check version 1. It must keep the checked configuration
fixed through submission. Core rejects providers that cannot make this
guarantee.
- A lost task reply does not prove process termination. Core retains
grants until the provider proves termination and Core saves required
state.
- This PR does not enable native heartbeat dispatch through plugin
environments. Cloud deployment and live provider validation remain
separate.

## Model Used

OpenAI Codex, GPT-6. The exact model ID and context window are not
exposed in this session. Tool use includes code editing, local tests,
and the GitHub CLI.

## 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 described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name describes the change and contains no internal issue
details
- [x] I have run focused 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-10-20 18:13:09 -07:00

252 lines
13 KiB
TypeScript

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";
/** 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;
}) {
const pollMs = input.pollMs ?? 500;
let registrationGeneration = 0;
let activeOutbound: ReturnType<typeof connectRunnerPrpIngress> | null = null;
let preparedLaunchId: string | undefined;
let preparedIdentity: DurableRecoveryIdentity | undefined;
let launched = false;
let stopRequested = false;
let released = false;
let submitted = false;
let detached = false;
let markReady!: () => void;
let failReady!: (error: unknown) => void;
let confirmStopped: (code: number) => void = () => {};
let stoppedState: Extract<PluginEnvironmentTaskResult, { kind: "status" }> | undefined;
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);
const call = async (operation: PluginEnvironmentTaskOperation) => {
const result = environmentTaskResultSchema.parse(await input.task(operation));
if (result.kind !== (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 prepareLaunch: RunnerLaunchPreparer = async (requirements, recovery) => {
if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled");
const result = await call(environmentTaskOperationSchema.parse({ kind: "prepare", requirements,
projectIds: [...input.projectIds], ...(recovery ? { recovery } : {}),
...(input.resumeFrom ? { resumeFrom: input.resumeFrom } : {}),
}));
if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled");
if (result.kind !== "prepared") throw new Error("Plugin Runner preparation unavailable");
{
const provider = input.harness === "codex" ? "openai" : input.harness === "claude" ? "anthropic" : input.harness;
if (input.projectAuthCheckVersion !== 1) throw new Error("Plugin Runner managed project authentication validation unavailable");
const validation = await call({ kind: "check_project_auth", configurationId: result.launch.configurationId,
provider, projectIds: [...input.projectIds] });
if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled");
if (validation.kind !== "project_auth" || !validation.allowed || validation.configurationId !== result.launch.configurationId
|| validation.provider !== provider) throw new Error("Plugin Runner project authentication conflicts with the selected managed account");
}
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"
|| !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; 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();
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 () => {
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" });
},
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, 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),
};
return { launcher, registration, driver };
}