mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 01:57:31 +01:00
feat(server): adopt running remote agents through durable controller checkpoints (#17439)
## Thinking Path > - Paperclip must keep admitted remote work alive while its main server is replaced. > - Runner owns recovery mechanics and exposes opaque checkpoints through #17097. > - The server owns company scope, encryption, Stop, tool authority and execution ownership. > - A successor must prove current ownership before it adopts the original execution. > - Checkpoint bursts must also leave capacity for normal requests and lease renewal. > - This PR persists and adopts that authority through the existing runtime boundaries. ## Linked Issues or Issue Description **What existing behavior does this improve?** Remote agents retain the original execution during a bounded main-server outage. **Current behavior** A server restart can lose the controller's local state and connection. An unsafe replacement could repeat a turn or an uncertain mutation. Checkpoint writes in the request pool can also delay ordinary requests during an aligned burst. **Proposed behavior** Restore encrypted control records from Postgres and adopt the original runner under a fenced lease. Recover known tool receipts through current tool authority. Give control checkpoints a shared pool capped at two connections per database owner. Depends on #17097. Successors are #17455 and #17456. Qualification and presentation remain separate review slices. ## What Changed - Add company/run-bound encrypted checkpoint records and migration 0394. Keep the SQL idempotent after renumbering against current master. - Recover startup and expired ownership through native runtime and heartbeat. Preserve the sandbox lease, admitted runner artifact, harness configuration, native session and active turn. - Keep Stop, finalization, preparation ownership and stale-writer fencing transactional. Preserve graceful detach and natural crash takeover. - Recover committed tool receipts through the existing authority. Reauthorize reads and hold uncertain mutations. - Bound startup retention with the existing coordinator and preserve zero idle scans. - Share at most two checkpoint connections per database client. Keep application and liveness capacity separate. Close the checkpoint pool during shutdown; late writes cannot reopen it. - Count SQL across both application and checkpoint clients. Prove request/liveness progress, command recovery and failure after pool shutdown with real Postgres. ## Verification Project creation recovery now uses the existing project activity receipt owner. It retains authenticated input normalization, fingerprint checks and current run authority after the receipt lock. An absent receipt returns no result before mutation. The new lost-HTTP-response and no-effect regression uses real API routes and Postgres. The seven transport cases pass locally. This Mac skips all 20 database cases. On current source `5de803c2cd`, Linux [job 122593415890](https://github.com/paperclipai/paperclip/actions/runs/40620576702/job/122593415890) executes all 20 project-tool cases successfully (9.480 seconds), including the committed-project lost-response regression. Its shard passes 1,627 cases with three unrelated skips. Server typecheck passes. The transport regression initially has two failures; a subsequent incorrect expectation about schema defaults was corrected before the final pass. Ordinary execution adds no checkpoint writes or recurring work. Current candidate `5de803c2cd` includes the project-creation receipt recovery fix and master `2cd747d1b6`. Migration 0394 retains the prior idempotent checkpoint DDL. Every master SQL file and journal entry is preserved. Snapshots 0390–0394, migration checks and server typecheck pass. The ordinary warm-turn regression fails on its second turn before `a219ab51ad`. After correction, three completed warm turns select the correct prior checkpoint and preserve the original session. All 288 provider-wiring cases pass. The control plane, external persistence callback, identity rotation and filesystem are real; the backend and database-load seam are scripted. The 13 warm admission/configuration variants also pass after final master integration. This does not qualify an underlying harness. At current source `5de803c2cd`, Linux [job 122593415907](https://github.com/paperclipai/paperclip/actions/runs/40620576702/job/122593415907) passes all 940 native-session-executor cases (61.431 seconds), including the warm external-checkpoint behavior; the shard passes 2,358 cases with one skip. Current [Runner job 122593415475](https://github.com/paperclipai/paperclip/actions/runs/40620576702/job/122593415475) passes the native recovery lane: 115 passes and five container-only skips, including the encrypted restore guard, fresh preparation (63.189 seconds), blocked claim lock (1.226 seconds) and recovery beyond 101 blocked owners (3.897 seconds). The first lane passes 2,215 cases with one skip. The SQL cost test reports zero idle and streaming SQL for both output volumes; this is component evidence, not a production capacity claim. At prior candidate `1ff7bb44f4`, Linux job 122549307215 passes all 938 native-executor cases, including the three-turn external-checkpoint regression. Job 122549306469 passes the native recovery lane with 115 passes and five container-only skips, including the encrypted-restore session guard, fresh preparation (63.664 seconds), claim-lock contention (3.961 seconds), and 101-owner recovery (3.824 seconds). This Mac skips the real-Postgres suite. The earlier full local executor attempt has 921 passes and 16 failures during embedded-Postgres initialization before assertions. The original fixture collisions and their corrections remain recorded. At earlier candidate `8fbe62b41d`, server shard job 122535673841 has 3,876 passes, one failure and one skip in an unchanged expiry-worker retry/drain timing test. The same server/database tree on qualification source `b64cac6951` passes all 20 expiry cases and all 3,877 shard cases. The single diagnostic retry, job 122541891915, passes all 20 expiry cases and all 3,877 shard cases (one skip). No assertion was weakened. The original failure remains recorded and its exact timing race is not proven. All Actions checks and legacy status passed on `8fbe62b41d`, with completed Greptile 5/5 and no open feedback. The next candidate `1ff7bb44f4` also passed all Actions checks and Greptile 5/5. Its Paperclip Review remained queued before the new master conflict required integration. The new candidate needs fresh exact-head CI and reviews; old checks do not qualify it. Migration generation is checkpoint-only, all master SQL and journal entries remain unchanged, and migration checks, server typecheck and all 13 warm-owner variants pass after integration. The first migration check was blocked by TSX sandbox IPC; its permitted repeat passes. The first warm-test command used an incorrect path and ran no tests; the corrected command supplies the 13-case receipt. All 16 database pool-lifetime/options/teardown cases pass after granting loopback permission; the first batch had two EPERM failures and 14 passes. Earlier semantic-tool/HTTP recovery, adoption, encryption-batch, zero-streaming-write and idle-SQL receipts remain source-attributed in the [qualification record](https://github.com/paperclipai/paperclip/blob/2ff66f57da0da35bac1c19a2366ea4b84d87a986/doc/plans/2026-10-22-hot-upgrade-qualification.md). That record retains earlier assertion, setup and cleanup failures and their corrections. No failed gate is waived. The historical 300-session component campaign passes four after phases: steady read p99 is 107–108 ms at 500 reads/s and 100 writes/s; aligned-burst read p99 is 103–105 ms after the bounded pool, versus 584–689 ms before. This comparison isolates the persistence corrections. It does not measure the final stack's hosted active-agent capacity. The hosted zero-agent API pair leaves SQL and CPU essentially unchanged, but both arms fail absolute latency gates and candidate peak cgroup memory fails its gate. The active-agent/viewer matrix, different-artifact upgrade and rollback remain open. Run `PAPERCLIP_TEST_DATABASE_URL=<owned-disposable-postgres> pnpm --filter @paperclipai/server exec vitest run src/services/native-runtime/native-runner-restart-recovery.integration.test.ts`. Previous head `f2db8a6568` had one failed workspace setup gate: [job 122555672441](https://github.com/paperclipai/paperclip/actions/runs/40608984238/job/122555672441) passes all 4,169 UI tests and 285 CLI cases (one skip), but the company import/export suite reaches its 30-second health deadline during doctor startup. Its output does not reach the server-start step. The CLI, server, database, shared, adapter and plugin trees are identical on qualification source `a866619d7b`, whose [job 122555886663](https://github.com/paperclipai/paperclip/actions/runs/40609057937/job/122555886663) passes that fixture and all 286 CLI cases. The one diagnostic retry, [job 122561057225](https://github.com/paperclipai/paperclip/actions/runs/40608984238/job/122561057225), passes the formerly failing fixture and all 286 CLI cases. All Actions checks and legacy status on `f2db8a6568` pass. Its exact-head Greptile completed at 5/5 with no open feedback. The current integrated head requires fresh checks and a completed Paperclip Review before merge. The original failure remains recorded; its exact timing cause is unproven. A repeated failure requires investigation and repair rather than another retry. All current-head CI, legacy status, exact-head completed Greptile 5/5, resolved feedback and ordinary GitHub merge eligibility remain required before merge. The latest integration preserves master’s published Copilot v70 profiles and every published migration. Checkpoint migration `0394_conscious_whizzer.sql` was generated with `pnpm db:generate` and retains the prior idempotent DDL. The Runner vendor rebuild and replay parity checks pass. Server typecheck and all 13 warm-owner variants pass after that rebuild. The imported report-lock patch is byte-identical to master; its intentional patch-context whitespace is retained, and the feature delta passes whitespace checks. No hosted experiment was run. ## Risks The pool adds up to two active connections per instance, shared across agents. Checkpoint delivery can wait behind that bound; it still requires its commit. Steady component-test Postgres CPU rises by about 1.7 percentage points of a two-CPU allocation. These corrections do not remove the stack's control and renewal writes. The migration and key must survive replacement. Fresh-database tests and local load do not establish different-artifact hosted upgrade or rollback continuity. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools and code execution. The runtime does not expose a more specific model ID or context-window size. ## 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 - [ ] 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 --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
94a780286f
commit
09ad9adce2
62 files changed
+4671
-488
No files matched your search
@@ -1,6 +1,8 @@
|
||||
import { providerPackWorkspaceId, recordAdmittedRemoteProviderPack, resolveRemoteProviderPackAuthority } from "./remote-provider-pack-authority.js";
|
||||
import { type ProviderPackInstallation, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
import { writeEnvironmentCleanup } from "../environment-cleanup-notifications.js";
|
||||
import { NATIVE_SESSION_EXECUTION_LEASE_TTL_MS, startNativeSessionExecutionLeaseRenewal, type NativeExecutionLeaseRenewal } from "./native-execution-lease.js";
|
||||
export { renewNativeSessionExecutionLease } from "./native-execution-lease.js";
|
||||
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
|
||||
import { writeExecutionControl } from "../execution-control-notifications.js";
|
||||
import { notifyExecutionRunWork } from "../execution-control-notifications.js";
|
||||
@@ -9,7 +11,7 @@ import { registerPluginTaskCredentialHandoff, type PluginTaskCredentialWriteback
|
||||
import { resolvePluginTaskResume } from "../environment-task-runtime.js";
|
||||
import { environmentTaskResultSchema } from "@paperclipai/plugin-sdk";
|
||||
import { preparePluginRunnerCredentials } from "./plugin-runner-credentials.js";
|
||||
import { createPluginRunnerTaskOwner } from "./plugin-runner-task.js";
|
||||
import { createPluginRunnerTaskOwner, verifyPluginRunnerTaskReattachment } from "./plugin-runner-task.js";
|
||||
import { applyObservabilityEnvironment, type ProviderObservabilityLaunch } from "@paperclipai/adapter-utils/agent-observability";
|
||||
import { museRunnerBroker } from "../muse-runner-broker.js";
|
||||
import { nativeCaseHandoffResult } from "./native-case-handoff.js";
|
||||
@@ -86,6 +88,8 @@ import {
|
||||
} from "node:fs";
|
||||
import { tmpdir, userInfo } from "node:os";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { nativeRunnerCheckpointPersistence, nativeRunnerCheckpointRegistration, restoreNativeRunnerCheckpoint } from "./native-runner-checkpoint.js";
|
||||
import { REMOTE_CONTROLLER_LEASE_MS, REMOTE_RUNNER_RECONNECT_GRACE_MS } from "./native-runner-recovery-contract.js";
|
||||
import { basename, dirname, join, posix, resolve } from "node:path";
|
||||
import type {
|
||||
AdapterExecutionResult,
|
||||
@@ -259,9 +263,7 @@ export class NativeControllerDetachedForRestartError extends Error {
|
||||
|
||||
const activeNativeSessions = new Map<string, ActiveNativeSession>();
|
||||
// Shutdown can race provider startup before onSession publishes its handle.
|
||||
// Retain the request for the remainder of this controller's lifetime so that
|
||||
// the late publication detaches before it can dispatch another turn.
|
||||
const nativeRunsDetachingForRestart = new Set<string>();
|
||||
const nativeRunsDetachingForRestart = new Map<string, symbol>();
|
||||
|
||||
// A restart must not cut authority rotation between archiving the previous
|
||||
// runner state and authenticating its replacement. Keep the startup owner
|
||||
@@ -273,6 +275,9 @@ type NativeSessionStartup = {
|
||||
restartAdmissionPending?: boolean;
|
||||
cancellationSettled?: Promise<void>;
|
||||
governedWait?: boolean;
|
||||
priorRestartDetach?: symbol;
|
||||
leaseOwner?: string;
|
||||
executionLeaseRenewal?: NativeExecutionLeaseRenewal;
|
||||
settled: Promise<void>;
|
||||
settle: () => void;
|
||||
};
|
||||
@@ -305,6 +310,7 @@ async function waitForNativeSessionStartup(
|
||||
|
||||
export async function detachNativeSessionsForRestart(
|
||||
runIds: readonly string[],
|
||||
leaseOwner?: string,
|
||||
): Promise<{
|
||||
detachedRunIds: string[];
|
||||
inactiveRunIds: string[];
|
||||
@@ -330,7 +336,11 @@ export async function detachNativeSessionsForRestart(
|
||||
})]);
|
||||
} finally { clearTimeout(timer); }
|
||||
}
|
||||
nativeRunsDetachingForRestart.add(runId);
|
||||
if (leaseOwner !== undefined && nativeSessionStartups.get(runId)?.leaseOwner !== leaseOwner) {
|
||||
inactiveRunIds.push(runId);
|
||||
continue;
|
||||
}
|
||||
nativeRunsDetachingForRestart.set(runId, Symbol("native controller detach"));
|
||||
let active = activeNativeSessions.get(runId);
|
||||
if (!active) {
|
||||
// Only a startup registered before this fence may complete read-only
|
||||
@@ -447,8 +457,6 @@ const TERMINAL_HEARTBEAT_RUN_STATUSES = new Set([
|
||||
"cancelled",
|
||||
"timed_out",
|
||||
]);
|
||||
const NATIVE_SESSION_EXECUTION_LEASE_TTL_MS = 20 * 60_000;
|
||||
const NATIVE_SESSION_EXECUTION_LEASE_RENEW_INTERVAL_MS = 5 * 60_000;
|
||||
const NATIVE_SESSION_CANCELLATION_CLEANUP_GRACE_MS = 2_000;
|
||||
const NATIVE_RUNTIME_REQUEST_RESOLUTION_CACHE_MAX = 256;
|
||||
type NativeRuntimeRequestResolution = {
|
||||
@@ -535,6 +543,7 @@ type WarmNativeSession = {
|
||||
pluginTaskId?: string;
|
||||
observabilityCompatibilityKey?: string;
|
||||
runId: string;
|
||||
issueId: string;
|
||||
instructionWorkingCopy?: NativeInstructionWorkingCopy;
|
||||
// Keep the admitted physical root independent of the per-run collection
|
||||
// capability, which instruction preparation adopts before final admission.
|
||||
@@ -1743,6 +1752,13 @@ class SessionToolAuthorityEpoch {
|
||||
return this.#authority.definitions();
|
||||
}
|
||||
|
||||
async recover(call: Parameters<PaperclipRunnerToolAuthority["recover"]>[0]) {
|
||||
this.#assertCurrent();
|
||||
const result = await this.#authority.recover(call);
|
||||
this.#assertCurrent();
|
||||
return result;
|
||||
}
|
||||
|
||||
async execute(call: Parameters<PaperclipRunnerToolAuthority["execute"]>[0]) {
|
||||
this.#assertCurrent();
|
||||
return this.toolTrace
|
||||
@@ -4979,6 +4995,7 @@ async function migrateRunnerdStateRootForExecution(input: {
|
||||
runnerExecutionTarget?: AdapterExecutionTarget | null;
|
||||
}): Promise<VerifiedWarmTransitionBinding | undefined> {
|
||||
const scoped = scopedRunnerdStateRoot(input.execution);
|
||||
await restoreWarmRunnerdController(input);
|
||||
// A crash can leave a source archive intent before/after its rename. Until
|
||||
// that exact maintenance is settled, absence of a canonical root is not
|
||||
// permission to bootstrap a replacement provider session.
|
||||
@@ -5049,6 +5066,16 @@ async function migrateRunnerdStateRootForExecution(input: {
|
||||
throw new Error("runner_state_identity_mismatch: bootstrap_not_proven_incomplete");
|
||||
}
|
||||
if (input.restartRecovery?.kind === "reattach_remote_runner") {
|
||||
if (input.restartRecovery.remote.kind === "plugin_task") {
|
||||
const target = input.runnerExecutionTarget;
|
||||
if (target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask
|
||||
|| target.leaseId !== input.restartRecovery.remote.leaseId || identity.environmentLeaseId !== target.leaseId
|
||||
|| !durableIdentityMatchesExecution(identity, input.execution)) {
|
||||
throw new Error("native_plugin_recovery_lease_mismatch");
|
||||
}
|
||||
await verifyPluginRunnerTaskReattachment(target.runnerTask, identity);
|
||||
return;
|
||||
}
|
||||
await verifyRemoteRunnerReattachment({
|
||||
claim: input.restartRecovery, target: input.runnerExecutionTarget, identity,
|
||||
runId: input.execution.binding.runId, normalizedSessionId: nativeSessionKey(input.execution),
|
||||
@@ -5496,6 +5523,7 @@ type RunnerdDurableIdentity = Record<string, unknown> & {
|
||||
|
||||
function readRunnerdDurableIdentity(
|
||||
root: string,
|
||||
allowExternal = false,
|
||||
): Record<string, unknown> | null {
|
||||
if (!isSafeNativeStateDirectory(root)) return null;
|
||||
const controlPlaneRoot = resolve(root, "control-plane");
|
||||
@@ -5512,7 +5540,8 @@ function readRunnerdDurableIdentity(
|
||||
).toString("utf8"),
|
||||
),
|
||||
);
|
||||
if (state.schema !== RUNNERD_CONTROL_PLANE_STATE_SCHEMA) return null;
|
||||
if (state.schema !== RUNNERD_CONTROL_PLANE_STATE_SCHEMA &&
|
||||
!(allowExternal && state.schema === "paperclip.runner.external-control-plane-state.v1")) return null;
|
||||
return record(state.identity);
|
||||
} catch {
|
||||
return null;
|
||||
@@ -5661,6 +5690,45 @@ function idleWarmNativeSessionOwnerRunId(input: {
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/** Materialize opaque controller state before ordinary warm admission reads it.
|
||||
* A retained owner or server checkpoint identifies the last completed run;
|
||||
* the original external marker can precede several in-process warm turns. */
|
||||
async function restoreWarmRunnerdController(input: {
|
||||
db: Db; execution: NativeExecutionInput;
|
||||
runnerExecutionTarget?: AdapterExecutionTarget | null;
|
||||
restartRecovery?: NativeRestartRecoveryClaim;
|
||||
}): Promise<void> {
|
||||
if (input.restartRecovery || input.runnerExecutionTarget?.kind !== "remote" ||
|
||||
input.execution.session.lifecyclePolicy.mode !== "warm") return;
|
||||
const root = scopedRunnerdStateRoot(input.execution);
|
||||
const identity = readRunnerdDurableIdentity(root);
|
||||
const reference = identity ?? readRunnerdDurableIdentity(root, true);
|
||||
if (!durableIdentityMatchesSession(reference, input.execution)) return;
|
||||
const retainedRunId = idleWarmNativeSessionOwnerRunId(input);
|
||||
let runId = retainedRunId ?? reference.runId;
|
||||
let issueId = retainedRunId ? warmNativeSessions.get(nativeSessionScopeKey(input.execution))!.issueId
|
||||
: input.execution.binding.issueId;
|
||||
if (!retainedRunId) {
|
||||
const saved = nativeSessionCheckpointPath(input.execution);
|
||||
if (existsSync(saved)) {
|
||||
const envelope = record(JSON.parse(readBoundedNativeFile(saved,
|
||||
NATIVE_WARM_CHECKPOINT_MAX_BYTES, "native_session_supervisor_checkpoint_too_large").toString("utf8")));
|
||||
const prior = record(record(envelope.snapshot).identity);
|
||||
if (envelope.schema !== "paperclip.native-session-supervisor.v1" ||
|
||||
prior.companyId !== input.execution.binding.companyId || prior.agentId !== input.execution.binding.agentId ||
|
||||
prior.sessionId !== nativeSessionKey(input.execution) || typeof prior.runId !== "string" || !prior.runId ||
|
||||
typeof prior.issueId !== "string" || !prior.issueId) throw new Error("native_session_supervisor_checkpoint_mismatch");
|
||||
runId = prior.runId;
|
||||
issueId = prior.issueId;
|
||||
}
|
||||
}
|
||||
if (identity?.runId === runId) return;
|
||||
const restored = await restoreNativeRunnerCheckpoint(input.db,
|
||||
{ companyId: input.execution.binding.companyId, issueId, runId }, root, nativeSessionKey(input.execution));
|
||||
// A legacy file-backed root still follows its existing prior-owner checks.
|
||||
if (!restored && !identity) throw new Error("native_runner_checkpoint_missing");
|
||||
}
|
||||
|
||||
function nativeHarnessEnvironmentFingerprint(
|
||||
execution: NativeExecutionInput,
|
||||
): string {
|
||||
@@ -7651,93 +7719,6 @@ export function resolveNativeCancellationStatus(input: {
|
||||
};
|
||||
}
|
||||
|
||||
export async function renewNativeSessionExecutionLease(input: {
|
||||
db: Db;
|
||||
runId: string;
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
leaseOwner: string;
|
||||
attempt: number;
|
||||
controller?: NativeControllerIdentity;
|
||||
leaseTtlMs?: number;
|
||||
}): Promise<void> {
|
||||
const controller =
|
||||
input.controller ?? (await currentNativeControllerIdentity());
|
||||
const leaseTtlMs = input.leaseTtlMs ?? NATIVE_SESSION_EXECUTION_LEASE_TTL_MS;
|
||||
if (
|
||||
!Number.isInteger(leaseTtlMs) ||
|
||||
leaseTtlMs < 1_000 ||
|
||||
leaseTtlMs > NATIVE_SESSION_EXECUTION_LEASE_TTL_MS
|
||||
) {
|
||||
throw new Error("native_session_lease_ttl_invalid");
|
||||
}
|
||||
const [updated] = await input.db
|
||||
.update(nativeRunFinalizations)
|
||||
.set({
|
||||
leaseExpiresAt: sql`now() + (${leaseTtlMs} * interval '1 millisecond')`,
|
||||
updatedAt: sql`now()`,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(nativeRunFinalizations.runId, input.runId),
|
||||
eq(nativeRunFinalizations.companyId, input.companyId),
|
||||
eq(nativeRunFinalizations.issueId, input.issueId),
|
||||
eq(nativeRunFinalizations.leaseOwner, input.leaseOwner),
|
||||
eq(nativeRunFinalizations.attempt, input.attempt),
|
||||
eq(nativeRunFinalizations.controllerBootId, controller.bootId),
|
||||
eq(nativeRunFinalizations.controllerPid, controller.pid),
|
||||
eq(
|
||||
nativeRunFinalizations.controllerProcessStartedAt,
|
||||
controller.processStartedAt,
|
||||
),
|
||||
gt(nativeRunFinalizations.leaseExpiresAt, sql`now()`),
|
||||
),
|
||||
)
|
||||
.returning({ runId: nativeRunFinalizations.runId });
|
||||
if (!updated) throw new Error("native_session_lease_lost");
|
||||
}
|
||||
|
||||
function startNativeSessionExecutionLeaseRenewal(input: {
|
||||
db: Db;
|
||||
runId: string;
|
||||
companyId: string;
|
||||
issueId: string;
|
||||
leaseOwner: string;
|
||||
attempt: number;
|
||||
controller: NativeControllerIdentity;
|
||||
}): { stop: () => Promise<void> } {
|
||||
let leaseLost: Error | null = null;
|
||||
let renewal = Promise.resolve();
|
||||
const renew = () => {
|
||||
if (leaseLost) return;
|
||||
renewal = renewal
|
||||
.then(() => renewNativeSessionExecutionLease(input))
|
||||
.then(() => undefined)
|
||||
.catch(async (error: unknown) => {
|
||||
leaseLost =
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("native_session_lease_lost");
|
||||
await cancelNativeSession(
|
||||
input.runId,
|
||||
"native session execution lease lost",
|
||||
).catch(() => undefined);
|
||||
});
|
||||
};
|
||||
const timer = setInterval(
|
||||
renew,
|
||||
NATIVE_SESSION_EXECUTION_LEASE_RENEW_INTERVAL_MS,
|
||||
);
|
||||
timer.unref?.();
|
||||
return {
|
||||
stop: async () => {
|
||||
clearInterval(timer);
|
||||
await renewal;
|
||||
if (leaseLost) throw leaseLost;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function executePaperclipNativeSession(input: {
|
||||
casesEnabled?: boolean;
|
||||
getFreshSessionHandoff?: () => Promise<string | null>;
|
||||
@@ -7834,7 +7815,7 @@ export async function executePaperclipNativeSession(input: {
|
||||
}
|
||||
}
|
||||
const runId = input.execution.binding.runId;
|
||||
if (nativeRunsDetachingForRestart.has(runId)) {
|
||||
if (nativeRunsDetachingForRestart.has(runId) && input.restartRecovery?.runId !== runId) {
|
||||
throw new NativeControllerDetachedForRestartError();
|
||||
}
|
||||
if (nativeSessionStartups.has(runId)) {
|
||||
@@ -7845,6 +7826,7 @@ export async function executePaperclipNativeSession(input: {
|
||||
let resolveStartup!: (session: ActiveNativeSession | null) => void;
|
||||
let settle!: () => void;
|
||||
const startup: NativeSessionStartup = {
|
||||
priorRestartDetach: nativeRunsDetachingForRestart.get(runId),
|
||||
settled: new Promise<void>(resolve => { settle = resolve; }),
|
||||
settle: () => settle(),
|
||||
promise: new Promise<ActiveNativeSession | null>(resolve => { resolveStartup = resolve; }),
|
||||
@@ -7976,6 +7958,10 @@ export async function executePaperclipNativeSession(input: {
|
||||
) {
|
||||
executingRunnerdSessionScopes.delete(sessionScopeId);
|
||||
}
|
||||
// Preparation can fail before the execution loop owns its normal cleanup.
|
||||
// Remove the settled startup before yielding, so detachment cannot reacquire
|
||||
// its old resolved session while renewal cleanup drains.
|
||||
await startup.executionLeaseRenewal?.stop().catch(() => undefined);
|
||||
try {
|
||||
await cleanupStagedAttachments();
|
||||
} catch (cleanupError) {
|
||||
@@ -8002,6 +7988,10 @@ export async function executePaperclipNativeSession(input: {
|
||||
async function executePaperclipNativeSessionWithinScope(
|
||||
input: Parameters<typeof executePaperclipNativeSession>[0],
|
||||
): Promise<AdapterExecutionResult> {
|
||||
const restoredController = input.restartRecovery?.kind === "reattach_remote_runner"
|
||||
? await restoreNativeRunnerCheckpoint(input.db, input.execution.binding, scopedRunnerdStateRoot(input.execution))
|
||||
: null;
|
||||
if (input.useRunnerd) await restoreWarmRunnerdController(input);
|
||||
const identityRedactor = createAgentIdentityRedactor(input.runnerEnvironment?.PAPERCLIP_AGENT_PRIVATE_KEY);
|
||||
const redactIdentityText = (text: string) => redactSensitiveText(
|
||||
identityRedactor.chunk("diagnostic", text) + identityRedactor.finish("diagnostic"),
|
||||
@@ -8152,8 +8142,8 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
const leaseOwner =
|
||||
input.leaseOwner ?? `${effectiveRunnerInstanceId}:${randomUUID()}`;
|
||||
const controller = await currentNativeControllerIdentity();
|
||||
const leaseNow = new Date();
|
||||
const leaseExpiresAt = new Date(leaseNow.getTime() + 20 * 60_000);
|
||||
const executionLeaseTtlMs = input.runnerExecutionTarget?.kind === "remote"
|
||||
? REMOTE_CONTROLLER_LEASE_MS : NATIVE_SESSION_EXECUTION_LEASE_TTL_MS;
|
||||
let attempt: number;
|
||||
try {
|
||||
attempt = await trace.measure(
|
||||
@@ -8181,10 +8171,6 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!coordinator)
|
||||
throw new Error("native_finalization_coordinator_missing");
|
||||
const leaseNow = new Date();
|
||||
const leaseExpiresAt = new Date(
|
||||
leaseNow.getTime() + NATIVE_SESSION_EXECUTION_LEASE_TTL_MS,
|
||||
);
|
||||
// A durable result means provider execution already completed. The
|
||||
// recovery/finalization path must reconcile it; never reacquire a
|
||||
// provider session and execute the turn a second time.
|
||||
@@ -8303,13 +8289,15 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
: coordinator.controllerBootId === controller.bootId
|
||||
? Math.max(1, coordinator.controllerGeneration)
|
||||
: coordinator.controllerGeneration + 1;
|
||||
const leaseNow = new Date();
|
||||
const claimed = await tx
|
||||
.update(nativeRunFinalizations)
|
||||
.set({
|
||||
phase: "observed",
|
||||
attempt: nextAttempt,
|
||||
leaseOwner,
|
||||
leaseExpiresAt,
|
||||
// Start the full lease after claim locks and lineage reads finish.
|
||||
leaseExpiresAt: sql`clock_timestamp() + ${executionLeaseTtlMs} * interval '1 millisecond'`,
|
||||
controllerBootId: controller.bootId,
|
||||
controllerPid: controller.pid,
|
||||
controllerProcessStartedAt: controller.processStartedAt,
|
||||
@@ -8346,9 +8334,30 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
})
|
||||
.where(eq(heartbeatRuns.id, coordinator.runId));
|
||||
return nextAttempt;
|
||||
}).then(claimedAttempt => {
|
||||
const startup = nativeSessionStartups.get(input.execution.binding.runId);
|
||||
if (!startup) throw new Error("native_session_startup_owner_missing");
|
||||
startup.leaseOwner = leaseOwner;
|
||||
// Own renewal as soon as the claim commits, including slow tracing,
|
||||
// accounting history and retained-session cleanup before dispatch.
|
||||
startup.executionLeaseRenewal = startNativeSessionExecutionLeaseRenewal({
|
||||
db: input.db, runId: input.execution.binding.runId,
|
||||
companyId: input.execution.binding.companyId, issueId: input.execution.binding.issueId,
|
||||
leaseOwner, attempt: claimedAttempt, controller,
|
||||
remote: input.runnerExecutionTarget?.kind === "remote",
|
||||
onLost: () => input.runnerExecutionTarget?.kind === "remote"
|
||||
? detachNativeSessionsForRestart([input.execution.binding.runId], leaseOwner)
|
||||
: cancelNativeSession(input.execution.binding.runId, "native session execution lease lost"),
|
||||
});
|
||||
return claimedAttempt;
|
||||
}),
|
||||
{ parentName: "task.prepare" },
|
||||
);
|
||||
const startup = nativeSessionStartups.get(input.execution.binding.runId);
|
||||
if (input.restartRecovery && startup?.priorRestartDetach !== undefined
|
||||
&& nativeRunsDetachingForRestart.get(input.execution.binding.runId) === startup.priorRestartDetach) {
|
||||
nativeRunsDetachingForRestart.delete(input.execution.binding.runId);
|
||||
}
|
||||
await trace.end(taskPrepareScope);
|
||||
} catch (error) {
|
||||
await trace.end(taskPrepareScope, { outcome: "failed" });
|
||||
@@ -8843,7 +8852,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
let githubAccess: NativeGitHubAccess | undefined;
|
||||
let releaseGitHubRun: (() => void) | undefined;
|
||||
let persistedWarmSession: PersistedNativeSession | null | undefined;
|
||||
if (warmSessionId !== null && warmConfigDigest !== null) {
|
||||
if (warmSessionId !== null && warmConfigDigest !== null && !input.restartRecovery) {
|
||||
const entry = warmNativeSessions.get(warmSessionId);
|
||||
if (entry) {
|
||||
if (entry.preparingRunId && entry.preparingRunId !== input.execution.binding.runId) throw new Error("native_session_supervisor_busy");
|
||||
@@ -9030,15 +9039,8 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
},
|
||||
}
|
||||
: input.execution;
|
||||
const leaseRenewal = startNativeSessionExecutionLeaseRenewal({
|
||||
db: input.db,
|
||||
runId: input.execution.binding.runId,
|
||||
companyId: input.execution.binding.companyId,
|
||||
issueId: input.execution.binding.issueId,
|
||||
leaseOwner,
|
||||
attempt,
|
||||
controller,
|
||||
});
|
||||
const leaseRenewal = nativeSessionStartups.get(input.execution.binding.runId)?.executionLeaseRenewal;
|
||||
if (!leaseRenewal) throw new Error("native_session_renewal_owner_missing");
|
||||
try {
|
||||
const usesPluginTask = input.runnerExecutionTarget?.kind === "remote" && input.runnerExecutionTarget.transport === "sandbox" && !!input.runnerExecutionTarget.runnerTask;
|
||||
const prepareRunnerEnvironment = async () => {
|
||||
@@ -9071,6 +9073,10 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
input.useRunnerd && input.backend === undefined
|
||||
? await timeController("backend_setup", () => createRunnerdBackend({
|
||||
...input,
|
||||
controllerPersistence: input.runnerExecutionTarget?.kind === "remote" ? {
|
||||
bootId: controller.bootId,
|
||||
runnerArtifact: restoredController ? { version: restoredController.runnerVersion, digest: restoredController.runnerDigest } : undefined,
|
||||
} : undefined,
|
||||
...(overlapGitHubPreparation ? { prepareRunnerEnvironment } : {}),
|
||||
// Durable scope and prior-run verification use the controller's
|
||||
// canonical workspace identity. createRunnerdBackend separately
|
||||
@@ -9107,6 +9113,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
nativeSessionConfigDigest(remoteWarmRecovery.previousExecution, "remote"), await recovered.session.snapshot());
|
||||
persistedWarmSession = loadWarmNativeCheckpoint(input.execution, warmConfigDigest!, "remote");
|
||||
runnerdBackend = await createRunnerdBackend({ ...input, runnerInstanceId: effectiveRunnerInstanceId,
|
||||
controllerPersistence: input.runnerExecutionTarget?.kind === "remote" ? { bootId: controller.bootId } : undefined,
|
||||
durableEnvironmentLeaseId: durableRunnerBinding?.environmentLeaseId, trace, toolTrace });
|
||||
}
|
||||
}
|
||||
@@ -9311,11 +9318,13 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
}
|
||||
existing.session = session;
|
||||
existing.runId = input.execution.binding.runId;
|
||||
existing.issueId = input.execution.binding.issueId;
|
||||
} else
|
||||
warmNativeSessions.set(warmSessionId, {
|
||||
pluginTaskId: usesPluginTask && input.runnerExecutionTarget?.kind === "remote" && input.runnerExecutionTarget.transport === "sandbox"
|
||||
? input.runnerExecutionTarget.sandboxLeaseAcquisition?.providerLeaseId : undefined,
|
||||
runId: input.execution.binding.runId,
|
||||
issueId: input.execution.binding.issueId,
|
||||
instructionWorkingCopy: input.instructionWorkingCopy?.checkpointWarm ? undefined : input.instructionWorkingCopy,
|
||||
instructionRoot: input.instructionWorkingCopy?.root,
|
||||
agentId: input.execution.binding.agentId,
|
||||
@@ -11231,6 +11240,7 @@ export async function verifyRemoteRunnerReattachment(input: {
|
||||
}) {
|
||||
const { claim, target, identity } = input;
|
||||
if (
|
||||
claim.remote.kind === "plugin_task" ||
|
||||
target?.kind !== "remote" ||
|
||||
target.transport !== "sandbox" ||
|
||||
!target.runner ||
|
||||
@@ -11690,7 +11700,12 @@ export function createRemoteRunnerProcessLauncher(input: {
|
||||
};
|
||||
}
|
||||
})();
|
||||
return { child, completion, isExitConfirmed: () => exitConfirmed };
|
||||
return {
|
||||
child,
|
||||
completion,
|
||||
get startedAt() { return launchedIdentity?.startedAt; },
|
||||
isExitConfirmed: () => exitConfirmed,
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -11715,6 +11730,7 @@ export function remoteCheckpointIncompleteFailure(
|
||||
export async function createRunnerdBackend(input: {
|
||||
casesEnabled?: boolean;
|
||||
db: Db;
|
||||
controllerPersistence?: { bootId: string; runnerArtifact?: { version: string; digest: string } };
|
||||
execution: NativeExecutionInput;
|
||||
runnerInstanceId: string;
|
||||
chatAttachmentReadScope?: NativeChatAttachmentReadScope;
|
||||
@@ -11826,8 +11842,9 @@ async function prepareRemoteExternalRunner({ input, target, runner, root, identi
|
||||
const runnerStateDirectory = posix.join(remoteRoot, "sessions",
|
||||
createHash("sha256").update(identity.normalizedSessionId).digest("hex"), "runner");
|
||||
const requiredMode = resolveRemoteRunnerTransportMode({ target, runnerIngressAuthorized: input.runnerIngressAuthorized === true });
|
||||
const artifact = readRunnerdArtifactBinding(runnerBinary);
|
||||
const artifact = input.controllerPersistence?.runnerArtifact ?? readRunnerdArtifactBinding(runnerBinary);
|
||||
const prepare = async () => {
|
||||
if (input.restartRecovery?.kind === "reattach_remote_runner" && input.controllerPersistence?.runnerArtifact) return;
|
||||
if (input.restartRecovery?.kind !== "reattach_remote_runner") {
|
||||
if (!input.runnerRemoteBinaryPath?.trim()) {
|
||||
const platform = await runner.execute({ command: "sh", args: ["-c", "uname -s; uname -m"], bypassSession: true, timeoutMs: 10000 });
|
||||
@@ -11892,6 +11909,8 @@ async function prepareRemoteExternalRunner({ input, target, runner, root, identi
|
||||
};
|
||||
const executionDriver = createNativeRunnerExecutionDriver({
|
||||
target, binding: input.execution.binding,
|
||||
controllerPersistence: input.controllerPersistence ? nativeRunnerCheckpointPersistence(
|
||||
input.db, input.controllerPersistence.bootId, input.execution.binding.runId, detachNativeSessionsForRestart) : undefined,
|
||||
runnerIngressAuthorized: input.runnerIngressAuthorized,
|
||||
runnerPublicUrl: input.runnerPublicUrl,
|
||||
runnerCaBundlePath: input.runnerCaBundlePath,
|
||||
@@ -12063,9 +12082,15 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
}
|
||||
const description = input.pluginTaskDescription ?? environmentTaskResultSchema.parse(await pluginTask({ kind: "describe" }));
|
||||
if (description.kind !== "description" || description.launchPreparationVersion !== 1 || description.projectAuthCheckVersion !== 1) throw new Error("Plugin Runner launch preparation v1 unavailable");
|
||||
const prior = durableBinding ? durableIdentity as RunnerdDurableIdentity : undefined;
|
||||
const saved = durableBinding ? durableIdentity as RunnerdDurableIdentity : undefined;
|
||||
const prior = saved ? {
|
||||
runnerInstanceId: saved.runnerInstanceId, environmentLeaseId: saved.environmentLeaseId,
|
||||
runId: saved.runId, normalizedSessionId: saved.normalizedSessionId,
|
||||
turnId: typeof saved.turnId === "string" ? saved.turnId : "",
|
||||
itemId: typeof saved.itemId === "string" ? saved.itemId : "",
|
||||
} : undefined;
|
||||
const retainedOwner = input.retainedPluginTaskOwner;
|
||||
const adopting = input.remoteWarmRecovery !== undefined;
|
||||
const adopting = input.remoteWarmRecovery !== undefined || input.restartRecovery?.kind === "reattach_remote_runner";
|
||||
const adoptionIdentity = input.remoteWarmRecovery ? {
|
||||
runnerInstanceId: input.remoteWarmRecovery.identity.runnerInstanceId,
|
||||
environmentLeaseId: input.remoteWarmRecovery.identity.environmentLeaseId,
|
||||
@@ -12073,6 +12098,9 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
normalizedSessionId: input.remoteWarmRecovery.identity.normalizedSessionId,
|
||||
turnId: input.remoteWarmRecovery.identity.turnId, itemId: input.remoteWarmRecovery.identity.itemId,
|
||||
} : undefined;
|
||||
if (input.restartRecovery?.kind === "reattach_remote_runner" && (!prior || !prior.turnId || !prior.itemId || prior.environmentLeaseId !== remoteTarget.leaseId)) {
|
||||
throw new Error("native_plugin_recovery_lease_mismatch");
|
||||
}
|
||||
const resumeFrom = !retainedOwner && !adopting && prior && prior.environmentLeaseId !== remoteTarget.leaseId
|
||||
? await resolvePluginTaskResume(input.db, { companyId: input.execution.binding.companyId,
|
||||
leaseId: remoteTarget.leaseId!, priorIdentity: prior }) : undefined;
|
||||
@@ -12091,7 +12119,11 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
// Warm retirement can outlive the run's temporary credential home; complete uses the durable handoff.
|
||||
onCredentials: input.execution.session.lifecyclePolicy.mode === "warm" ? undefined : credentials.onCredentials,
|
||||
warmTaskVersion: description.warmTaskVersion,
|
||||
adoptIdentity: adoptionIdentity, projectAuthCheckVersion: description.projectAuthCheckVersion, task: pluginTask, projectIds: remoteTarget.runnerTaskProjectIds ?? [],
|
||||
adoptIdentity: adoptionIdentity ?? (adopting && prior ? {
|
||||
runnerInstanceId: prior.runnerInstanceId, environmentLeaseId: prior.environmentLeaseId,
|
||||
runId: prior.runId, normalizedSessionId: prior.normalizedSessionId,
|
||||
turnId: prior.turnId ?? "", itemId: prior.itemId ?? "",
|
||||
} : undefined), projectAuthCheckVersion: description.projectAuthCheckVersion, task: pluginTask, projectIds: remoteTarget.runnerTaskProjectIds ?? [],
|
||||
harness: provider.kind === "acpx" ? provider.agent : provider.kind, resumeFrom, priorIdentity: prior ? {
|
||||
runnerInstanceId: prior.runnerInstanceId, environmentLeaseId: prior.environmentLeaseId,
|
||||
runId: prior.runId, normalizedSessionId: prior.normalizedSessionId,
|
||||
@@ -12135,7 +12167,24 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
return nativeCompletionFeedback(input.db, current.runId, result);
|
||||
},
|
||||
codexTransportFactory: recovery => createRunnerdCodexTransport({ provider: provider.kind, stateDirectory: root,
|
||||
...owner.driver, runnerArtifact: description.runner,
|
||||
...owner.driver, runnerArtifact: input.controllerPersistence?.runnerArtifact ?? description.runner,
|
||||
controlPlaneRegistration: input.controllerPersistence ? async (authority, identity, signal) => {
|
||||
await nativeRunnerCheckpointRegistration({
|
||||
...nativeRunnerCheckpointPersistence(input.db, input.controllerPersistence!.bootId,
|
||||
() => {
|
||||
const current = sessionToolAuthorityEpochs.get(sessionScopeId);
|
||||
if (!current) throw new Error("native_session_tool_authority_unavailable");
|
||||
return current.runId;
|
||||
}, detachNativeSessionsForRestart),
|
||||
binding: input.execution.binding,
|
||||
})(authority, identity);
|
||||
return owner.driver.controlPlaneRegistration!(authority, identity, signal);
|
||||
} : owner.driver.controlPlaneRegistration,
|
||||
recoverSemanticToolInput: input.controllerPersistence ? call => {
|
||||
const current = sessionToolAuthorityEpochs.get(sessionScopeId);
|
||||
if (!current || current.runId !== call.correlation.runId) throw new Error("native_tool_authority_epoch_revoked");
|
||||
return current.recover({ tool: call.operationId, callId: call.callId, arguments: call.input });
|
||||
} : undefined,
|
||||
...(provider.kind === "codex" ? { disableCodexWebSearch: "webSearch" in provider && provider.webSearch === "disabled" } : {}),
|
||||
...(provider.kind === "acpx" ? { acpxAgent: provider.agent,
|
||||
acpxCandidateProfile: provider.agent === "pi" ? undefined : resolveAcpxQualification(provider, process.env),
|
||||
@@ -12145,7 +12194,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
grokDisableWebSearch: "grokDisableWebSearch" in provider ? provider.grokDisableWebSearch : undefined,
|
||||
acpxPermissionModePinned: true } : {}),
|
||||
...(provider.kind === "opencode" ? { opencodePermissionMode: provider.permissionMode } : {}),
|
||||
runnerReconnectGraceMs: 120_000, runnerProcessReconnectGraceMs: null,
|
||||
runnerReconnectGraceMs: REMOTE_RUNNER_RECONNECT_GRACE_MS, runnerProcessReconnectGraceMs: null,
|
||||
lifecyclePolicy: input.execution.session.lifecyclePolicy,
|
||||
runtimeContext: "runtimeContext" in input.execution ? input.execution.runtimeContext : null,
|
||||
externallySandboxed: true, baseInstructions: recovery?.baseInstructions,
|
||||
@@ -12155,7 +12204,8 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
prpIdentity: adoptionIdentity ?? { runnerInstanceId: prior?.runnerInstanceId ?? effectiveRunnerInstanceId,
|
||||
environmentLeaseId: prior?.environmentLeaseId ?? effectiveEnvironmentLeaseId,
|
||||
runId: input.execution.binding.runId, normalizedSessionId: nativeSessionKey(input.execution),
|
||||
turnId: `turn-${input.execution.binding.runId}`, itemId: `item-${input.execution.binding.runId}` },
|
||||
turnId: adopting ? prior!.turnId : `turn-${input.execution.binding.runId}`,
|
||||
itemId: adopting ? prior!.itemId : `item-${input.execution.binding.runId}` },
|
||||
}).transport,
|
||||
});
|
||||
sessionToolAuthorityEpochs.get(sessionScopeId)?.revoke();
|
||||
@@ -12176,6 +12226,10 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
const externalExecution = input.execution;
|
||||
const externalOptions = {
|
||||
stateDirectory: root, runnerBinary: remoteDot?.runnerBinary ?? resolvePaperclipRunnerBinary(),
|
||||
runnerArtifact: input.controllerPersistence?.runnerArtifact,
|
||||
runnerReconnectGraceMs: remoteDot ? REMOTE_RUNNER_RECONNECT_GRACE_MS : undefined,
|
||||
recoverSemanticToolInput: input.controllerPersistence ? (call: { operationId: string; callId: string; input: unknown }) =>
|
||||
authorityEpoch.recover({ tool: call.operationId, callId: call.callId, arguments: call.input }) : undefined,
|
||||
...(remoteDot ?? {}),
|
||||
identity: { runnerInstanceId: effectiveRunnerInstanceId, environmentLeaseId: effectiveEnvironmentLeaseId,
|
||||
runId: input.execution.binding.runId, normalizedSessionId: nativeSessionKey(input.execution),
|
||||
@@ -12216,12 +12270,15 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
remoteTarget !== null &&
|
||||
(input.execution.provider.kind === "opencode" ||
|
||||
input.execution.provider.kind === "acpx");
|
||||
const adoptingPersistedRemoteRunner = remoteTarget !== null
|
||||
&& input.restartRecovery?.kind === "reattach_remote_runner"
|
||||
&& input.controllerPersistence?.runnerArtifact !== undefined;
|
||||
const remoteClaude = remoteTarget !== null && input.execution.provider.kind === "acpx" && input.execution.provider.agent === "claude";
|
||||
const remoteClaudeRunnerBinary = remoteClaude
|
||||
const remoteClaudeRunnerBinary = remoteClaude && !adoptingPersistedRemoteRunner
|
||||
? await resolveRemotePaperclipRunnerBinary({ runner: remoteCommandRunner!, remoteCwd: remoteTarget!.remoteCwd, configuredPath: input.runnerRemoteBinaryPath })
|
||||
: null;
|
||||
const remoteClaudeTarget = remoteClaudeRunnerBinary ? runnerBinaryTarget(readFileSync(remoteClaudeRunnerBinary)) : null;
|
||||
const useBundledClaudePack = remoteClaude && !input.runnerRemoteProviderPackPath?.trim();
|
||||
const useBundledClaudePack = remoteClaude && !adoptingPersistedRemoteRunner && !input.runnerRemoteProviderPackPath?.trim();
|
||||
if (useBundledClaudePack && remoteClaudeTarget !== "linux-x64" && remoteClaudeTarget !== "linux-arm64") {
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: Claude remote provider packs require a qualified Linux target");
|
||||
}
|
||||
@@ -12232,7 +12289,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
// Pi's explicit operator import supplies the target-platform authority. Never
|
||||
// substitute a Mac controller daemon or trust an image's self-reported hashes.
|
||||
// Existing explicit overrides and every other provider keep their old path.
|
||||
const remotePiCompanion = await timeController("companion_selection", () => selectRemotePiCompanion({
|
||||
const remotePiCompanion = adoptingPersistedRemoteRunner ? null : await timeController("companion_selection", () => selectRemotePiCompanion({
|
||||
provider: input.execution.provider, remote: remoteTarget !== null,
|
||||
binaryOverride: input.runnerRemoteBinaryPath, packOverride: input.runnerRemoteProviderPackPath,
|
||||
workspaceRoot: input.execution.workspace.cwd!,
|
||||
@@ -12280,7 +12337,11 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
// When an explicit remote artifact is configured, prepareRemoteRunner stages
|
||||
// these exact bytes at remoteBinary before launch.
|
||||
const targetMatchedCodexArtifact = remoteTarget !== null && input.execution.provider.kind === "codex";
|
||||
const controllerRunnerBinary = targetMatchedCodexArtifact
|
||||
// The persisted admission owns a surviving runner's identity. Local release
|
||||
// files are launch inputs and may no longer exist on a replacement controller.
|
||||
const controllerRunnerBinary = adoptingPersistedRemoteRunner
|
||||
? input.runnerRemoteBinaryPath?.trim() || resolvePaperclipRunnerBinary()
|
||||
: targetMatchedCodexArtifact
|
||||
? await timeController("runner_binary", () => resolveRemotePaperclipRunnerBinary({ runner: remoteCommandRunner!, remoteCwd: remoteTarget.remoteCwd, configuredPath: input.runnerRemoteBinaryPath }))
|
||||
: remoteTarget
|
||||
? remoteClaudeRunnerBinary || input.runnerRemoteBinaryPath?.trim() || remotePiCompanion?.runnerBinary || (useBundledRemoteImageAssets ? bundledRemoteRunnerBinary() : resolvePaperclipRunnerBinary())
|
||||
@@ -12295,7 +12356,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
runnerArtifact: () => readRunnerdArtifactBinding(controllerRunnerBinary),
|
||||
current: resolveCurrentProviderPackManifest,
|
||||
}) : null;
|
||||
let providerPackAuthority = selectProviderPackAuthority(reattachProviderPack);
|
||||
let providerPackAuthority = adoptingPersistedRemoteRunner ? null : selectProviderPackAuthority(reattachProviderPack);
|
||||
let expectedProviderPackManifest = providerPackAuthority?.manifest ?? null;
|
||||
let providerPackVerified = false;
|
||||
const explicitRemoteCodex = input.runnerRemoteCodexPath?.trim() || null;
|
||||
@@ -12471,6 +12532,10 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
return;
|
||||
selectedRemoteMode = requiredMode;
|
||||
if (input.restartRecovery?.kind === "reattach_remote_runner" || input.remoteWarmRecovery) {
|
||||
if (input.controllerPersistence?.runnerArtifact) {
|
||||
remotePrepared = true;
|
||||
return;
|
||||
}
|
||||
await remoteNativeArtifacts?.verifyRemoteRunner(requiredMode, undefined, true);
|
||||
if (requiresRemoteProviderPack && await useInstalledProviderPack()) {
|
||||
remotePrepared = true;
|
||||
@@ -13689,12 +13754,17 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
: {}),
|
||||
stateDirectory: root,
|
||||
runnerBinary: controllerRunnerBinary,
|
||||
...(providerPackAuthority ? { runnerArtifact: providerPackAuthority.runnerArtifact } : {}),
|
||||
runnerArtifact: input.controllerPersistence?.runnerArtifact ?? providerPackAuthority?.runnerArtifact,
|
||||
recoverSemanticToolInput: input.controllerPersistence ? call => {
|
||||
const current = sessionToolAuthorityEpochs.get(sessionScopeId);
|
||||
if (!current || current.runId !== call.correlation.runId) throw new Error("native_tool_authority_epoch_revoked");
|
||||
return current.recover({ tool: call.operationId, callId: call.callId, arguments: call.input });
|
||||
} : undefined,
|
||||
codexCommand: remoteCodexBinary ?? undefined,
|
||||
sourceCodexHome: remoteTarget
|
||||
? resolveSourceCodexHome(resolveNativeProviderEnvironment(input.execution.provider, runnerEnvironment))
|
||||
: undefined,
|
||||
runnerReconnectGraceMs: remoteTarget ? 120_000 : undefined,
|
||||
runnerReconnectGraceMs: remoteTarget ? REMOTE_RUNNER_RECONNECT_GRACE_MS : undefined,
|
||||
// A controller's bounded reconnect attempt is not the remote owner's
|
||||
// lifetime. Retain it through restarts until its authenticated lease
|
||||
// expires or explicit Stop/suspension proves that execution ended.
|
||||
@@ -13806,6 +13876,12 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
adoptExistingRunner: adoptedProcess,
|
||||
},
|
||||
target,
|
||||
controllerPersistence: input.controllerPersistence ? nativeRunnerCheckpointPersistence(
|
||||
input.db, input.controllerPersistence.bootId, () => {
|
||||
const current = sessionToolAuthorityEpochs.get(sessionScopeId);
|
||||
if (!current) throw new Error("native_session_tool_authority_unavailable");
|
||||
return current.runId;
|
||||
}, detachNativeSessionsForRestart) : undefined,
|
||||
binding: input.remoteWarmRecovery
|
||||
? { ...input.execution.binding, runId: input.remoteWarmRecovery.identity.runId }
|
||||
: input.execution.binding,
|
||||
|
||||
Reference in new issue
Block a user