fix(runner): persist warm Daytona workspaces across turns (#12904)

## Thinking Path

> - Daytona preserves a stopped sandbox filesystem, but deleting or
replacing a sandbox removes its only remote copy.
> - Warm reuse therefore improves latency but cannot be Paperclip's
durability boundary.
> - The host execution workspace must remain authoritative after every
successful turn, while same-run recovery must avoid overwriting
unexported remote work.
> - Result proposal, workspace export/merge, and terminal completion
need a durable, replayable ordering so a crash never starts a duplicate
provider turn.
> - A paid browser acceptance suite must exercise both legacy Codex and
Runner Codex for three real turns on one continuously warm Daytona
sandbox.

## Linked Issues or Issue Description

Refs #12901.

Runner Codex did not previously export successful Daytona workspace
changes back to the authoritative host workspace. That made warm reuse
depend on Daytona's remote filesystem and left deleted/replacement
sandboxes without a reliable reconstruction path. The existing paid
fixture also lacked a focused three-turn continuity case for both Codex
adapters.

## What Changed

- Persist versioned, atomic native workspace-sync descriptors and
durable seeds in `PAPERCLIP_HOME`, without credentials or a database
migration.
- Classify fresh, warm, replacement, and same-run-recovery workspace
preparation explicitly; ambiguous lease/root/digest evidence fails
closed.
- Finalize native workspace export/merge after semantic result proposal
and before run completion, with idempotent replay that never submits a
second provider turn.
- Surface legacy Codex workspace restoration failures instead of masking
them, while preserving an earlier provider error when both fail.
- Keep healthy reusable Daytona leases warm for legacy and native
adapters, stamp finalized workspace generations, and retain existing
cleanup behavior for per-turn or unhealthy leases.
- Preserve Runner Codex's provider process/session across warm turns,
including bounded post-terminal tail draining and exact authority
rotation.
- Add the exact paid `daytona-warm-continuity` matrix:
  - `legacy-codex × daytona × warm-three-turn`
  - `runner-codex × daytona × warm-three-turn`
- Drive all three turns through the browser, verify ordered file
continuity and stable lease/workspace/runtime identities, capture
per-turn timings, and delete the sandbox immediately after assertions.
- Document `pnpm test:e2e:runner -- --suite daytona-warm-continuity`; no
package script was added.

## Verification

- `pnpm typecheck` — passed, including migration safety (no migration
added)
- Focused server/runner Vitest coverage — 144 passed
- `pnpm test:e2e:runner:unit` — 114 passed
- `pnpm test:e2e:runner:typecheck` — passed
- `pnpm --filter @paperclipai/paperclip-runner test:codex` — 66 passed,
1 helper ignored
- `native-session-executor.test.ts` — 139 passed, including safe
fail-closed cleanup after remote runner identity capture failure
- Paid local browser acceptance, exact post-rebase Linux/amd64 runner
binary:
- Runner Codex — passed in 1.7m; 3 runs; lease outcomes `created,
resumed, resumed`; 10/10 matchers; cleanup passed
- Legacy Codex — passed in 2.7m; 3 runs; lease outcomes `created,
resumed, resumed`; 10/10 matchers; cleanup passed
- [Protected paid GitHub Actions
campaign](https://github.com/paperclipai/paperclip/actions/runs/34026735033)
against `7da42a91b95fa7fb2df126668ef7e37afb3b2b9d` — passed 2/2:
- Runner Codex — 3 runs; lease outcomes `created, resumed, resumed`;
evidence and cleanup passed
- Legacy Codex — 3 runs; lease outcomes `created, resumed, resumed`;
evidence and cleanup passed
  - Merge/enforcement, S3 history, and Pages publication jobs passed
- Paid result artifacts were scanned for both provider credentials;
neither secret was present.
- Current PR checks — 31 passed, 1 expected Storybook skip; Greptile
5/5; Superagent security scan passed
- `git diff --check origin/master...HEAD` — passed
- Confirmed no `package.json`, lockfile, migration, or SQL changes.

## Risks

- Workspace synchronization now sits on the terminal-success path, so a
remote export failure deliberately prevents false success. Retryable
state retains its lease/seed; loss of the only unexported remote copy
fails closed.
- Warm provider reuse has strict identity and quiescence checks.
Mismatched or ambiguous evidence blocks reuse rather than risking
concurrent provider work.
- The paid suite incurs Daytona and Codex cost only in the existing
protected scheduled/manual workflow and explicitly destroys its sandbox
after each cell.

## Model Used

OpenAI Codex with GPT-5 agentic reasoning, repository inspection, real
browser E2E execution, Rust/TypeScript test execution, and GitHub
Actions diagnostics.

## 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 linked an existing issue or described the issue
in-PR
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [x] My branch name contains no internal ticket id
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have documented the dedicated suite invocation without adding a
package script
- [x] I have considered and documented risks above
- [x] All Paperclip CI gates are green on the current revision
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
on the current revision
- [x] I will address all reviewer comments before requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-09-06 08:16:12 -05:00
1 parent af8439a70b
commit 0c1e7504c0
47 files changed
+4160 -581

No files matched your search

+67 -29
View File
@@ -29,6 +29,9 @@ const mockProjectService = vi.hoisted(() => ({
const mockEnvironmentRuntimeService = vi.hoisted(() => ({
destroyReusableSandboxLeasesForEnvironment: vi.fn(async () => ({ destroyed: 0, failed: 0, skippedLiveRun: 0 })),
}));
const mockCloseWarmNativeSessionsForEnvironment = vi.hoisted(() =>
vi.fn(async () => ({ closed: 0, busy: 0, failed: 0 })),
);
const mockInstanceSettingsService = vi.hoisted(() => ({
listCompanyIds: vi.fn(),
getGeneral: vi.fn(),
@@ -111,6 +114,10 @@ vi.mock("../services/environments.js", () => ({
vi.mock("../services/environment-runtime.js", () => ({
environmentRuntimeService: () => mockEnvironmentRuntimeService,
}));
vi.mock("../services/native-runtime/native-session-executor.js", () => ({
closeWarmNativeSessionsForEnvironment:
mockCloseWarmNativeSessionsForEnvironment,
}));
vi.mock("../services/execution-workspaces.js", () => ({
executionWorkspaceService: () => mockExecutionWorkspaceService,
@@ -229,7 +236,8 @@ const originalSecretsProviderEnv = process.env.PAPERCLIP_SECRETS_PROVIDER;
// it only needs to be identity-checkable in assertions.
const routeDbTx = { __routeDbTx: true };
const routeDb = {
transaction: async <T>(fn: (tx: unknown) => Promise<T>): Promise<T> => fn(routeDbTx),
transaction: async <T>(fn: (tx: unknown) => Promise<T>): Promise<T> =>
fn(routeDbTx),
};
function createApp(actor: Record<string, unknown>, options: Record<string, unknown> = {}) {
@@ -279,7 +287,15 @@ describe("environment routes", () => {
mockProjectService.getById.mockReset();
mockProjectService.clearExecutionWorkspaceEnvironmentSelection.mockReset();
mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment.mockReset();
mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment.mockResolvedValue({ destroyed: 0, failed: 0, skippedLiveRun: 0 });
mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment.mockResolvedValue(
{ destroyed: 0, failed: 0, skippedLiveRun: 0 },
);
mockCloseWarmNativeSessionsForEnvironment.mockReset();
mockCloseWarmNativeSessionsForEnvironment.mockResolvedValue({
closed: 0,
busy: 0,
failed: 0,
});
mockInstanceSettingsService.listCompanyIds.mockReset();
mockInstanceSettingsService.getGeneral.mockReset();
mockInstanceSettingsService.getGeneral.mockResolvedValue({ executionMode: "any" });
@@ -1655,12 +1671,21 @@ describe("environment routes", () => {
const res = await request(app).delete("/api/environments/env-1?destroyReusableSandboxLeases=true");
expect(res.status).toBe(200);
expect(mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment)
.toHaveBeenCalledExactlyOnceWith({
environmentId: "env-1",
failureReason: "environment_deleted",
});
expect(mockEnvironmentService.removeIfDeletable).toHaveBeenCalledWith("env-1");
expect(
mockEnvironmentRuntimeService.destroyReusableSandboxLeasesForEnvironment,
).toHaveBeenCalledExactlyOnceWith({
environmentId: "env-1",
failureReason: "environment_deleted",
});
expect(
mockCloseWarmNativeSessionsForEnvironment,
).toHaveBeenCalledExactlyOnceWith({
environmentId: "env-1",
reason: "environment deleted",
});
expect(mockEnvironmentService.removeIfDeletable).toHaveBeenCalledWith(
"env-1",
);
expect(res.body.destroyedReusableSandboxLeaseCount).toBe(2);
});
@@ -2154,11 +2179,11 @@ describe("environment routes", () => {
expect(mockSecretService.create).not.toHaveBeenCalled();
});
it("keeps the host-owned stream flag and drops a removed flag a saved config still carries", async () => {
// The host owns `streamRunLogs`. It reads it to select the run-log stream. A
// provider plugin normalizes only its own driver fields, so it drops the host
// flag from its normalized config. The host must re-apply it, or the saved
// environment loses the operator opt-out and the stream never starts.
it("keeps host-owned sandbox flags and drops a removed flag a saved config still carries", async () => {
// The host owns run-log streaming and runner lifecycle. A provider plugin
// may normalize only its own driver fields, so it drops these host flags.
// The host must re-apply them or a saved warm environment silently becomes
// per-turn at execution time.
//
// `streamAgentSessionOutput` is a removed operator flag. A saved config can
// still carry it, but session-output streaming now follows the capability
@@ -2172,22 +2197,31 @@ describe("environment routes", () => {
config: { provider: "fake-plugin", image: "fake:test" },
};
mockEnvironmentService.create.mockResolvedValue(environment);
mockValidatePluginSandboxProviderConfig.mockImplementation(async ({ provider, config }) => {
// Drop the host flag to reproduce a plugin that allowlists driver fields.
const { streamRunLogs, ...driverConfig } = config as Record<string, unknown>;
void streamRunLogs;
return {
normalizedConfig: driverConfig,
pluginId: `plugin-${provider}`,
pluginKey: `plugin.${provider}`,
driver: {
driverKey: provider,
kind: "sandbox_provider",
displayName: provider,
configSchema: { type: "object" },
},
};
});
mockValidatePluginSandboxProviderConfig.mockImplementation(
async ({ provider, config }) => {
// Drop the host flag to reproduce a plugin that allowlists driver fields.
const {
streamRunLogs,
runnerLifecycleMode,
runnerIdleTimeoutMs,
...driverConfig
} = config as Record<string, unknown>;
void streamRunLogs;
void runnerLifecycleMode;
void runnerIdleTimeoutMs;
return {
normalizedConfig: driverConfig,
pluginId: `plugin-${provider}`,
pluginKey: `plugin.${provider}`,
driver: {
driverKey: provider,
kind: "sandbox_provider",
displayName: provider,
configSchema: { type: "object" },
},
};
},
);
const pluginWorkerManager = {};
const app = createApp({
type: "board",
@@ -2204,6 +2238,8 @@ describe("environment routes", () => {
provider: "fake-plugin",
image: "fake:test",
streamRunLogs: false,
runnerLifecycleMode: "warm",
runnerIdleTimeoutMs: 180_000,
streamAgentSessionOutput: true,
},
});
@@ -2213,6 +2249,8 @@ describe("environment routes", () => {
// The removed key never reaches the persisted config.
expect(persisted.streamAgentSessionOutput).toBeUndefined();
expect(persisted.streamRunLogs).toBe(false);
expect(persisted.runnerLifecycleMode).toBe("warm");
expect(persisted.runnerIdleTimeoutMs).toBe(180_000);
});
it("creates a schema-driven sandbox environment with secret-ref fields persisted as secrets", async () => {
@@ -115,6 +115,35 @@ describe("findReusableSandboxLeaseId", () => {
expect(selected).toBe("sandbox-template-b");
});
it("ignores host-only log streaming when matching a reusable plugin lease", () => {
const selected = findReusableSandboxLeaseId({
config: {
provider: "fake-plugin",
image: "template-b",
timeoutMs: 300000,
reuseLease: true,
streamRunLogs: true,
runnerLifecycleMode: "warm",
target: null,
},
leases: [
{
providerLeaseId: "sandbox-template-b",
metadata: {
provider: "fake-plugin",
image: "template-b",
timeoutMs: 300000,
reuseLease: true,
runnerLifecycleMode: "warm",
target: "us",
},
},
],
});
expect(selected).toBe("sandbox-template-b");
});
it("requires image identity for reusable fake sandbox leases", () => {
const selected = findReusableSandboxLeaseId({
config: {
@@ -610,6 +639,12 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
expect(acquired.lease.metadata?.nativeWorkspaceSync).toEqual(
workspaceSyncStamp,
);
await expect(
environmentService(db).getLeaseById(first.lease.id),
).resolves.toMatchObject({
status: "expired",
cleanupStatus: "success",
});
expect(
workerManager.call.mock.calls.filter(
(call) => call[1] === "environmentAcquireLease",
@@ -617,6 +652,76 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
).toHaveLength(1);
});
it("reacquires one provider lease row idempotently during same-run recovery", async () => {
const seeded = await seedReusablePluginSandboxLease();
const workerManager = {
isRunning: vi.fn((id: string) => id === seeded.pluginId),
call: vi.fn(async (_pluginId: string, method: string) => {
if (method === "environmentResumeLease") {
return {
providerLeaseId: seeded.reusableLease.providerLeaseId,
metadata: {
provider: "fake-plugin",
image: "fake:test",
timeoutMs: 1234,
reuseLease: true,
remoteCwd: "/workspace",
},
};
}
throw new Error(
`Unexpected plugin method during same-run reacquisition: ${method}`,
);
}),
getWorker: vi.fn(() => ({
supportedMethods: [
"environmentResumeLease",
"environmentReleaseLease",
"environmentDestroyLease",
],
})),
} as unknown as PluginWorkerManager;
const runtimeWithPlugin = environmentRuntimeService(db, {
pluginWorkerManager: workerManager,
});
const reacquired = await runtimeWithPlugin.acquireRunLease({
companyId: seeded.companyId,
environment: seeded.environment,
issueId: null,
agentId: seeded.agentId,
heartbeatRunId: seeded.runId,
persistedExecutionWorkspace: {
id: seeded.executionWorkspaceId,
mode: "shared_workspace",
},
});
expect(reacquired.lease).toMatchObject({
id: seeded.reusableLease.id,
heartbeatRunId: seeded.runId,
providerLeaseId: seeded.reusableLease.providerLeaseId,
status: "active",
cleanupStatus: null,
});
const rows = await environmentService(db).listLeases(seeded.environment.id);
expect(
rows.filter(
(lease) =>
lease.heartbeatRunId === seeded.runId &&
lease.providerLeaseId === seeded.reusableLease.providerLeaseId,
),
).toHaveLength(1);
expect(workerManager.call).toHaveBeenCalledWith(
seeded.pluginId,
"environmentResumeLease",
expect.objectContaining({
providerLeaseId: seeded.reusableLease.providerLeaseId,
}),
expect.any(Number),
);
});
it("destroys a disposable paperclip_runner sandbox after the turn", async () => {
const { pluginId, runId, reusableLease } = await seedReusablePluginSandboxLease();
const workerManager = {
@@ -658,6 +763,13 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
const { pluginId, runId, reusableLease } = await seedReusablePluginSandboxLease();
await environmentService(db).updateLeaseMetadata(reusableLease.id, {
...(reusableLease.metadata ?? {}),
reusableSandboxLease: {
...((reusableLease.metadata?.reusableSandboxLease as Record<
string,
unknown
>) ?? {}),
adapterType: "paperclip_runner",
},
sandboxLeaseAcquisition: { outcome: "created" },
});
const workerManager = {
@@ -6022,8 +6134,12 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
});
it("destroys scoped reusable plugin-backed sandbox leases", async () => {
const { pluginId, companyId, executionWorkspaceId, reusableLease } =
const { pluginId, companyId, runId, executionWorkspaceId, reusableLease } =
await seedReusablePluginSandboxLease();
await db
.update(heartbeatRuns)
.set({ status: "succeeded" })
.where(eq(heartbeatRuns.id, runId));
const workerManager = {
isRunning: vi.fn((id: string) => id === pluginId),
@@ -6062,6 +6178,37 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
});
});
it("does not destroy a scoped reusable lease while its run is active", async () => {
const { pluginId, companyId, executionWorkspaceId, reusableLease } =
await seedReusablePluginSandboxLease();
const workerManager = {
isRunning: vi.fn((id: string) => id === pluginId),
call: vi.fn(async () => undefined),
getWorker: vi.fn(() => ({
supportedMethods: [
"environmentResumeLease",
"environmentReleaseLease",
"environmentDestroyLease",
],
})),
} as unknown as PluginWorkerManager;
const runtimeWithPlugin = environmentRuntimeService(db, {
pluginWorkerManager: workerManager,
});
const destroyed = await runtimeWithPlugin.destroyReusableSandboxLeases({
companyId,
executionWorkspaceId,
failureReason: "issue_terminal_done",
});
expect(destroyed).toEqual([]);
expect(workerManager.call).not.toHaveBeenCalled();
await expect(
environmentService(db).getLeaseById(reusableLease.id),
).resolves.toMatchObject({ status: "active" });
});
it("destroys reusable plugin-backed sandbox leases scoped to an environment", async () => {
const { pluginId, runId, reusableLease } = await seedReusablePluginSandboxLease();
// The holding run is finished, so the reservation is stale and destroyable.
@@ -6192,8 +6339,12 @@ describeEmbeddedPostgres("environmentRuntimeService", () => {
});
it("retries reusable plugin-backed sandbox destroy when the worker is unavailable", async () => {
const { pluginId, companyId, executionWorkspaceId, reusableLease } =
const { pluginId, companyId, executionWorkspaceId, runId, reusableLease } =
await seedReusablePluginSandboxLease();
await db
.update(heartbeatRuns)
.set({ status: "succeeded", finishedAt: new Date() })
.where(eq(heartbeatRuns.id, runId));
const offlineWorkerManager = {
isRunning: vi.fn(() => false),
@@ -148,9 +148,11 @@ describeEmbeddedPostgres("heartbeat teardown terminalizes the run before releasi
runId: string;
companyId: string;
agentId: string;
providerResourceDisposition?: "keep_running" | "stop_and_retain" | "destroy";
}) {
const { runId, companyId, agentId } = input;
const releaseLeafCalls: Array<{ runId: string; status: string }> = [];
const ordering: string[] = [];
const fakeEnvironmentRuntime = {
// The orchestrator's `releaseForRun` calls this leaf with the mapped lease
// status. There are no seeded leases, so return an empty release set.
@@ -158,11 +160,18 @@ describeEmbeddedPostgres("heartbeat teardown terminalizes the run before releasi
heartbeatRunId: string,
status: "released" | "expired" | "failed",
) => {
ordering.push(`release:${heartbeatRunId}`);
releaseLeafCalls.push({ runId: heartbeatRunId, status });
return [];
},
} as unknown as HeartbeatEnvironmentRuntime;
const heartbeat = heartbeatService(db, { environmentRuntime: fakeEnvironmentRuntime });
const heartbeat = heartbeatService(db, {
environmentRuntime: fakeEnvironmentRuntime,
closeWarmNativeSessionsForRun: async ({ runId }) => {
ordering.push(`close:${runId}`);
return { closed: 1, busy: 0, failed: 0 };
},
});
let latestRun = await db
.select()
@@ -182,6 +191,7 @@ describeEmbeddedPostgres("heartbeat teardown terminalizes the run before releasi
companyId,
agentId,
status: statusThreadedToRelease,
providerResourceDisposition: input.providerResourceDisposition,
});
const orchestratorObservedRunId = releaseLeafCalls.at(-1)?.runId ?? null;
const orchestratorObservedLeaseStatus = releaseLeafCalls.at(-1)?.status ?? null;
@@ -193,10 +203,43 @@ describeEmbeddedPostgres("heartbeat teardown terminalizes the run before releasi
releaseCallCount: releaseLeafCalls.length,
orchestratorObservedRunId,
orchestratorObservedLeaseStatus,
ordering,
terminalRun: latestRun,
};
}
it("closes a warm native session before destroying its terminal lease", async () => {
const { companyId, agentId, runId } = await seed({ issueStatus: "done", runStatus: "running" });
const observed = await runTeardownSequenceObservingRelease({
runId,
companyId,
agentId,
providerResourceDisposition: "destroy",
});
expect(observed.ordering).toEqual([`close:${runId}`, `release:${runId}`]);
expect(observed.releaseCallCount).toBe(1);
});
it("does not destroy a terminal lease while its warm native session is busy", async () => {
const { companyId, agentId, runId } = await seed({ issueStatus: "done", runStatus: "running" });
const releaseRunLeases = vi.fn(async () => []);
const heartbeat = heartbeatService(db, {
environmentRuntime: { releaseRunLeases } as unknown as HeartbeatEnvironmentRuntime,
closeWarmNativeSessionsForRun: async () => ({ closed: 0, busy: 1, failed: 0 }),
});
await heartbeat.releaseEnvironmentLeasesForRun({
runId,
companyId,
agentId,
status: "succeeded",
providerResourceDisposition: "destroy",
});
expect(releaseRunLeases).not.toHaveBeenCalled();
});
it("terminalizes a running run to succeeded before release when the issue reached done", async () => {
const { companyId, agentId, issueId, runId } = await seed({ issueStatus: "done", runStatus: "running" });
@@ -2286,6 +2286,45 @@ describe("effective run session config freshness", () => {
});
});
it("does not reset when a reusable execution workspace becomes realized", async () => {
const base = await buildSessionConfigMetadata({
workspaceConfig: {
requestedMode: "shared_workspace",
effectiveMode: "shared_workspace",
reusableExecutionWorkspaceConfig: null,
existingExecutionWorkspace: null,
},
});
const realized = await buildSessionConfigMetadata({
workspaceConfig: {
requestedMode: "shared_workspace",
effectiveMode: "shared_workspace",
reusableExecutionWorkspaceConfig: {
strategyType: "project_primary",
workspaceGeneration: 1,
},
existingExecutionWorkspace: {
id: "workspace-realized-after-first-turn",
mode: "shared_workspace",
strategyType: "project_primary",
},
},
});
expect(
resolveTaskSessionConfigFreshness({
hasTaskSession: true,
configuredModel: "gpt-5.4-mini",
taskSessionParams: sessionParamsWithConfigMetadata(base),
configMetadata: realized,
}),
).toMatchObject({
reset: false,
changedCategories: [],
reasons: [],
});
});
it("keeps model-only compatibility as an additional reset reason", async () => {
const base = await buildSessionConfigMetadata();
@@ -1999,6 +1999,62 @@ describe.sequential("issue thread interaction routes", () => {
);
});
it("delivers generic confirmation rejection feedback as the next turn message", async () => {
mockInteractionService.rejectInteraction.mockResolvedValueOnce({
id: "interaction-warm-turn",
companyId: "company-1",
issueId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
kind: "request_confirmation",
status: "rejected",
continuationPolicy: "wake_assignee",
idempotencyKey: "warm-turn-1",
sourceCommentId: null,
sourceRunId: RUN_3,
payload: {
version: 1,
prompt: "Continue to turn two?",
target: {
type: "custom",
key: "warm_turn_1",
revisionId: "turn-1",
},
},
result: {
version: 1,
outcome: "rejected",
reason: "Read T1, append T2, and verify both lines.",
},
createdAt: "2026-04-20T12:00:00.000Z",
updatedAt: "2026-04-20T12:05:00.000Z",
resolvedAt: "2026-04-20T12:05:00.000Z",
});
const res = await request(await createApp())
.post(
"/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/interactions/interaction-warm-turn/reject",
)
.send({ reason: "Read T1, append T2, and verify both lines." });
expect(res.status).toBe(200);
expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith(
ASSIGNEE_AGENT_ID,
expect.objectContaining({
payload: expect.objectContaining({
paperclipAgentMessage: {
text: "Read T1, append T2, and verify both lines.",
source: "interaction_rejection",
sessionId: "interaction-warm-turn",
},
}),
contextSnapshot: expect.objectContaining({
paperclipAgentMessage: expect.objectContaining({
text: "Read T1, append T2, and verify both lines.",
}),
}),
}),
);
});
it("returns a rejected native completion review with a narrow reviewer-reason continuation", async () => {
const issue = createIssue({ status: "in_review" });
mockIssueService.getById.mockResolvedValue(issue);
@@ -1906,6 +1906,56 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => {
})).rejects.toThrow("A decline reason is required for this confirmation");
});
it("reopens an in-review issue before waking the assignee after rejection", async () => {
const { companyId, issueId } = await seedConfirmationIssue(
"Continue after review rejection",
);
const created = await interactionsSvc.create(
{ id: issueId, companyId },
{
kind: "request_confirmation",
continuationPolicy: "wake_assignee",
payload: {
version: 1,
prompt: "Continue the next turn?",
rejectLabel: "Continue work",
rejectRequiresReason: true,
target: {
type: "custom",
key: "warm_turn_1",
revisionId: "warm-turn-1",
},
},
},
{
userId: "local-board",
},
);
await db
.update(issues)
.set({ status: "in_review" })
.where(eq(issues.id, issueId));
await interactionsSvc.rejectInteraction(
{
id: issueId,
companyId,
status: "in_review",
},
created.id,
{
reason: "Proceed with turn two.",
},
{
userId: "local-board",
},
);
await expect(issuesSvc.getById(issueId)).resolves.toMatchObject({
status: "todo",
});
});
it("records an authorized agent as the review-confirmation resolver", async () => {
const { companyId, goalId, issueId } = await seedConfirmationIssue("Agent review verdict");
const resolverAgentId = randomUUID();
@@ -7130,4 +7130,26 @@ describeEmbeddedPostgres("issueService.addComment createdByRunId", () => {
expect(await createdByRunIdFor(comment.id)).toBe(runId);
});
it("deduplicates concurrent identical comments from the same run", async () => {
const runId = randomUUID();
await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
status: "running",
});
const [first, second] = await Promise.all([
svc.addComment(issueId, "one durable result", { agentId, runId }),
svc.addComment(issueId, "one durable result", { agentId, runId }),
]);
expect(second.id).toBe(first.id);
const duplicates = await db
.select({ id: issueComments.id })
.from(issueComments)
.where(eq(issueComments.createdByRunId, runId));
expect(duplicates).toHaveLength(1);
});
});
@@ -14,11 +14,13 @@ const reusableSandbox = {
describe("paperclip_runner sandbox lifecycle", () => {
it("keeps a warm reusable sandbox running", () => {
expect(resolveNativeSandboxLifecycle({
adapterType: "paperclip_runner",
lifecyclePolicy: { mode: "warm", idleTimeoutMs: 300_000 },
target: reusableSandbox,
})).toEqual({
expect(
resolveNativeSandboxLifecycle({
adapterType: "paperclip_runner",
lifecyclePolicy: { mode: "warm", idleTimeoutMs: 300_000 },
target: reusableSandbox,
}),
).toEqual({
runnerProcess: "warm",
sandboxResource: "keep_running",
failoverBackup: "verified",
@@ -39,11 +41,13 @@ describe("paperclip_runner sandbox lifecycle", () => {
});
it("stops and reuses a per-turn reusable sandbox", () => {
expect(resolveNativeSandboxLifecycle({
adapterType: "paperclip_runner",
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
target: reusableSandbox,
})).toEqual({
expect(
resolveNativeSandboxLifecycle({
adapterType: "paperclip_runner",
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
target: reusableSandbox,
}),
).toEqual({
runnerProcess: "per_turn",
sandboxResource: "stop_and_reuse",
failoverBackup: "verified",
@@ -51,14 +55,16 @@ describe("paperclip_runner sandbox lifecycle", () => {
});
it("destroys a per-turn disposable sandbox", () => {
expect(resolveNativeSandboxLifecycle({
adapterType: "paperclip_runner",
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
target: {
...reusableSandbox,
reusableLeaseConfigured: false,
},
})).toEqual({
expect(
resolveNativeSandboxLifecycle({
adapterType: "paperclip_runner",
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
target: {
...reusableSandbox,
reusableLeaseConfigured: false,
},
}),
).toEqual({
runnerProcess: "per_turn",
sandboxResource: "destroy_after_turn",
failoverBackup: "verified",
@@ -66,27 +72,33 @@ describe("paperclip_runner sandbox lifecycle", () => {
});
it("rejects warm mode without an effective reusable-lease capability", () => {
expect(() => resolveNativeSandboxLifecycle({
adapterType: "paperclip_runner",
lifecyclePolicy: { mode: "warm", idleTimeoutMs: 300_000 },
target: {
...reusableSandbox,
effectiveCapabilities: { reusableLeases: false },
},
})).toThrow("runner_warm_lifecycle_requires_reusable_provider_lease");
expect(() =>
resolveNativeSandboxLifecycle({
adapterType: "paperclip_runner",
lifecyclePolicy: { mode: "warm", idleTimeoutMs: 300_000 },
target: {
...reusableSandbox,
effectiveCapabilities: { reusableLeases: false },
},
}),
).toThrow("runner_warm_lifecycle_requires_reusable_provider_lease");
});
it("leaves legacy and non-sandbox targets untouched", () => {
expect(resolveNativeSandboxLifecycle({
adapterType: "codex_local",
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
target: reusableSandbox,
})).toBeNull();
expect(resolveNativeSandboxLifecycle({
adapterType: "paperclip_runner",
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
target: { kind: "local" },
})).toBeNull();
expect(
resolveNativeSandboxLifecycle({
adapterType: "codex_local",
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
target: reusableSandbox,
}),
).toBeNull();
expect(
resolveNativeSandboxLifecycle({
adapterType: "paperclip_runner",
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
target: { kind: "local" },
}),
).toBeNull();
});
it("keeps a warm sandbox only after a successful turn", () => {
@@ -77,6 +77,14 @@ describe("native workspace sync durable metadata", () => {
sameProviderLease: false,
}),
).toBe("durable_seed");
expect(
classifyNativeWorkspaceInbound({
kind: "existing_run",
restartRecovery: false,
sameRunRecovery: true,
sameProviderLease: true,
}),
).toBe("adopt_remote");
expect(() =>
classifyNativeWorkspaceInbound({
kind: "existing_run",
+16 -2
View File
@@ -59,6 +59,7 @@ import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import { environmentService } from "../services/environments.js";
import { environmentRuntimeService } from "../services/environment-runtime.js";
import { executionWorkspaceService } from "../services/execution-workspaces.js";
import { closeWarmNativeSessionsForEnvironment } from "../services/native-runtime/native-session-executor.js";
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1294,10 +1295,23 @@ export function environmentRoutes(
&& impact.reusableSandboxLeaseCount > 0
&& impact.deleteBlockedReasons.every((reason) => reason === "reusable_sandbox_lease")
) {
const destroyResult = await environmentRuntime.destroyReusableSandboxLeasesForEnvironment({
const warmSessions = await closeWarmNativeSessionsForEnvironment({
environmentId: existing.id,
failureReason: "environment_deleted",
reason: "environment deleted",
});
if (warmSessions.busy > 0 || warmSessions.failed > 0) {
throw conflict(
warmSessions.busy > 0
? "Cannot delete this environment while a native runner session is active. Wait for its run to finish, then retry."
: "Cannot delete this environment because its warm native runner did not shut down cleanly. Retry after the runner exits.",
{ nativeRunnerSessions: warmSessions },
);
}
const destroyResult =
await environmentRuntime.destroyReusableSandboxLeasesForEnvironment({
environmentId: existing.id,
failureReason: "environment_deleted",
});
destroyedReusableSandboxLeaseCount = destroyResult.destroyed;
impact = await svc.getDeleteBlastRadius(existing.id);
if (!impact) {
+79 -49
View File
@@ -2231,55 +2231,85 @@ async function queueResolvedInteractionContinuationWakeup(input: {
result: interactionResult,
}
: null;
void input.heartbeat.wakeup(input.issue.assigneeAgentId, {
source: "automation",
triggerDetail: "system",
reason: "issue_commented",
payload: {
issueId: input.issue.id,
interactionId: input.interaction.id,
interactionKind: input.interaction.kind,
interactionStatus: input.interaction.status,
sourceCommentId: input.interaction.sourceCommentId ?? null,
sourceRunId: input.interaction.sourceRunId ?? null,
...(planReviewInteraction ? { planReviewInteraction } : {}),
...(nativeCompletionReview ? { nativeCompletionReview } : {}),
...(checkboxSelection ? { checkboxSelection } : {}),
...(toolAction ? { toolAction } : {}),
...(secretProposal ? { secretProposal } : {}),
...(itemVerdicts ? { itemVerdicts, newlyResolvedItemIds } : {}),
...(reviewPathContext ?? {}),
mutation: "interaction",
},
idempotencyKey: input.idempotencyKey ?? `interaction:${input.interaction.id}:${input.interaction.status}`,
requestedByActorType: input.actor.actorType,
requestedByActorId: input.actor.actorId,
contextSnapshot: {
issueId: input.issue.id,
taskId: input.issue.id,
interactionId: input.interaction.id,
interactionKind: input.interaction.kind,
interactionStatus: input.interaction.status,
sourceCommentId: input.interaction.sourceCommentId ?? null,
sourceRunId: input.interaction.sourceRunId ?? null,
...(planReviewInteraction ? { planReviewInteraction } : {}),
...(nativeCompletionReview ? { nativeCompletionReview } : {}),
...(checkboxSelection ? { checkboxSelection } : {}),
...(toolAction ? { toolAction } : {}),
...(secretProposal ? { secretProposal } : {}),
...(itemVerdicts ? { itemVerdicts, newlyResolvedItemIds } : {}),
...(reviewPathContext ?? {}),
wakeReason: "issue_commented",
source: input.source,
...(forceFreshSession ? { forceFreshSession: true } : {}),
...(workspaceRefreshReason ? { workspaceRefreshReason } : {}),
},
}).catch((err) => logger.warn({
err,
issueId: input.issue.id,
interactionId: input.interaction.id,
agentId: input.issue.assigneeAgentId,
}, "failed to wake assignee on issue interaction resolution"));
const genericRejectionReason =
!planReviewInteraction &&
!nativeCompletionReview &&
input.interaction.status === "rejected" &&
(input.interaction.kind === "request_confirmation" ||
input.interaction.kind === "request_checkbox_confirmation")
? readNonEmptyString(readObject(input.interaction.result).reason)
: null;
const rejectionAgentMessage = genericRejectionReason
? {
text: genericRejectionReason,
source: "interaction_rejection",
sessionId: input.interaction.id,
}
: null;
void input.heartbeat
.wakeup(input.issue.assigneeAgentId, {
source: "automation",
triggerDetail: "system",
reason: "issue_commented",
payload: {
issueId: input.issue.id,
interactionId: input.interaction.id,
interactionKind: input.interaction.kind,
interactionStatus: input.interaction.status,
sourceCommentId: input.interaction.sourceCommentId ?? null,
sourceRunId: input.interaction.sourceRunId ?? null,
...(planReviewInteraction ? { planReviewInteraction } : {}),
...(nativeCompletionReview ? { nativeCompletionReview } : {}),
...(checkboxSelection ? { checkboxSelection } : {}),
...(toolAction ? { toolAction } : {}),
...(secretProposal ? { secretProposal } : {}),
...(itemVerdicts ? { itemVerdicts, newlyResolvedItemIds } : {}),
...(rejectionAgentMessage
? { paperclipAgentMessage: rejectionAgentMessage }
: {}),
...(reviewPathContext ?? {}),
mutation: "interaction",
},
idempotencyKey:
input.idempotencyKey ??
`interaction:${input.interaction.id}:${input.interaction.status}`,
requestedByActorType: input.actor.actorType,
requestedByActorId: input.actor.actorId,
contextSnapshot: {
issueId: input.issue.id,
taskId: input.issue.id,
interactionId: input.interaction.id,
interactionKind: input.interaction.kind,
interactionStatus: input.interaction.status,
sourceCommentId: input.interaction.sourceCommentId ?? null,
sourceRunId: input.interaction.sourceRunId ?? null,
...(planReviewInteraction ? { planReviewInteraction } : {}),
...(nativeCompletionReview ? { nativeCompletionReview } : {}),
...(checkboxSelection ? { checkboxSelection } : {}),
...(toolAction ? { toolAction } : {}),
...(secretProposal ? { secretProposal } : {}),
...(itemVerdicts ? { itemVerdicts, newlyResolvedItemIds } : {}),
...(rejectionAgentMessage
? { paperclipAgentMessage: rejectionAgentMessage }
: {}),
...(reviewPathContext ?? {}),
wakeReason: "issue_commented",
source: input.source,
...(forceFreshSession ? { forceFreshSession: true } : {}),
...(workspaceRefreshReason ? { workspaceRefreshReason } : {}),
},
})
.catch((err) =>
logger.warn(
{
err,
issueId: input.issue.id,
interactionId: input.interaction.id,
agentId: input.issue.assigneeAgentId,
},
"failed to wake assignee on issue interaction resolution",
),
);
}
function readCheckboxSelectionForWake(input: {
+16 -11
View File
@@ -408,22 +408,24 @@ export function stripSandboxProviderEnvelope(config: SandboxEnvironmentConfig):
return driverConfig;
}
// The host owns this sandbox run-behavior flag, not the provider plugin. The
// host reads it to select the run-log stream. The host passes the whole config
// to the plugin, so a plugin that allowlists its own driver fields drops the
// flag from its normalized config. Re-apply it from the parsed envelope after
// the plugin normalizes, or a saved environment loses the operator opt-in and
// the stream never starts.
const HOST_OWNED_SANDBOX_STREAM_FLAGS = [
// The host owns these sandbox run-behavior flags, not the provider plugin. The
// host passes the whole config to the plugin, so a plugin that allowlists only
// its provider fields may drop them from its normalized config. Re-apply them
// from the parsed envelope after plugin normalization. Otherwise a saved
// environment can silently fall back to per-turn runner behavior even though
// the caller explicitly selected a warm lifecycle.
const HOST_OWNED_SANDBOX_FLAGS = [
"streamRunLogs",
"runnerLifecycleMode",
"runnerIdleTimeoutMs",
] as const;
function applyHostOwnedSandboxStreamFlags(
function applyHostOwnedSandboxFlags(
normalizedConfig: Record<string, unknown>,
envelope: Record<string, unknown>,
): Record<string, unknown> {
const merged: Record<string, unknown> = { ...normalizedConfig };
for (const key of HOST_OWNED_SANDBOX_STREAM_FLAGS) {
for (const key of HOST_OWNED_SANDBOX_FLAGS) {
if (envelope[key] !== undefined) {
merged[key] = envelope[key];
}
@@ -518,7 +520,10 @@ export function normalizeEnvironmentConfigForProbe(input: {
...(await resolveConfigSecretRefsForProbe({
db: input.db,
companyId: input.companyId,
config: applyHostOwnedSandboxStreamFlags(validated.normalizedConfig, parsed.data),
config: applyHostOwnedSandboxFlags(
validated.normalizedConfig,
parsed.data,
),
accessContext: input.accessContext,
schema:
validated.driver.configSchema &&
@@ -610,7 +615,7 @@ export async function normalizeEnvironmentConfigForPersistence(input: {
secretProvider: input.secretProvider,
config: {
provider: parsed.data.provider,
...applyHostOwnedSandboxStreamFlags(validated.normalizedConfig, parsed.data),
...applyHostOwnedSandboxFlags(validated.normalizedConfig, parsed.data),
},
schema:
validated.driver.configSchema && typeof validated.driver.configSchema === "object" && !Array.isArray(validated.driver.configSchema)
+66 -1
View File
@@ -1077,7 +1077,16 @@ export function findReusableSandboxLeaseId(input: {
config: SandboxEnvironmentConfig;
leases: Array<Pick<EnvironmentLease, "providerLeaseId" | "metadata">>;
}): string | null {
return findReusableSandboxProviderLeaseId(input);
// Host-only run behavior (for example streamRunLogs) is intentionally not
// echoed by a sandbox provider in lease metadata and must not invalidate an
// otherwise identical reusable provider lease.
return findReusableSandboxProviderLeaseId({
config: {
provider: input.config.provider,
...stripSandboxProviderEnvelope(input.config),
} as SandboxEnvironmentConfig,
leases: input.leases,
});
}
function createLocalEnvironmentDriver(db: Db): EnvironmentRuntimeDriver {
@@ -2083,6 +2092,16 @@ function createSandboxEnvironmentDriver(
acquiredLease.expiresAt ? new Date(acquiredLease.expiresAt) : undefined,
),
metadata: pluginLeaseMetadata,
reusesReusableLeaseId:
providerLease &&
reusableLease?.heartbeatRunId === input.heartbeatRunId
? reusableLease.id
: null,
replacesReusableLeaseId:
providerLease &&
reusableLease?.heartbeatRunId !== input.heartbeatRunId
? reusableLease?.id
: null,
});
} catch (error) {
// The conditional lease insert rejected, so no lease row exists. A
@@ -2312,6 +2331,18 @@ function createSandboxEnvironmentDriver(
providerLease.expiresAt ? new Date(providerLease.expiresAt) : undefined,
),
metadata: builtinLeaseMetadata,
reusesReusableLeaseId:
reusableLease &&
providerLease.providerLeaseId === reusableLease.providerLeaseId &&
reusableLease.heartbeatRunId === input.heartbeatRunId
? reusableLease.id
: null,
replacesReusableLeaseId:
reusableLease &&
providerLease.providerLeaseId === reusableLease.providerLeaseId &&
reusableLease.heartbeatRunId !== input.heartbeatRunId
? reusableLease.id
: null,
});
} catch (error) {
// The conditional lease insert rejected, so no lease row exists. A managed
@@ -3717,6 +3748,9 @@ export function environmentRuntimeService(
}
if (
providerResourceDisposition === "destroy" &&
isRecord(leaseSnapshot.metadata?.reusableSandboxLease) &&
leaseSnapshot.metadata.reusableSandboxLease.adapterType ===
"paperclip_runner" &&
leaseSnapshot.metadata?.sandboxLeaseAcquisition &&
(!leaseSnapshot.providerLeaseId ||
!verifyNativeHarnessBackupStamp(
@@ -3845,8 +3879,39 @@ export function environmentRuntimeService(
),
);
const holdingRunIds = leaseRows
.map((row) => row.heartbeatRunId)
.filter((runId): runId is string => Boolean(runId));
const liveRunIds = new Set<string>();
if (holdingRunIds.length > 0) {
const liveRuns = await db
.select({ id: heartbeatRuns.id })
.from(heartbeatRuns)
.where(
and(
inArray(heartbeatRuns.id, holdingRunIds),
inArray(heartbeatRuns.status, [
"queued",
"scheduled_retry",
"running",
]),
),
);
for (const liveRun of liveRuns) liveRunIds.add(liveRun.id);
}
const destroyed: EnvironmentRuntimeLeaseRecord[] = [];
for (const leaseRow of leaseRows) {
// An issue may become terminal inside its provider turn. Do not tear
// down the sandbox while that run is still exporting its workspace or
// polling the callback bridge. The heartbeat finalizer observes the
// terminal issue and destroys the resource after those boundaries.
if (
leaseRow.heartbeatRunId &&
liveRunIds.has(leaseRow.heartbeatRunId)
) {
continue;
}
const environment = leaseRow.environmentId
? await environmentsSvc.getById(leaseRow.environmentId)
: null;
+173 -37
View File
@@ -1335,6 +1335,21 @@ export function environmentService(db: Db) {
providerLeaseId?: string | null;
expiresAt?: Date | null;
metadata?: Record<string, unknown> | null;
/**
* Atomically retire the previous database ownership record when this
* acquisition reuses the same provider resource for a new run. The
* provider resume happens before this write, so a failed transaction
* leaves the prior retained row recoverable instead of publishing two
* reusable owners for one sandbox.
*/
replacesReusableLeaseId?: string | null;
/**
* Reactivate the exact lease row already owned by this heartbeat run.
* Native same-run recovery re-enters environment startup after the
* provider process is interrupted; it must not manufacture a second
* database owner for the same run and provider resource.
*/
reusesReusableLeaseId?: string | null;
/**
* Re-check the environment company binding inside the lease insert
* transaction. The login routes set this to close the check-to-lease
@@ -1368,47 +1383,168 @@ export function environmentService(db: Db) {
createdAt: now,
updatedAt: now,
};
const row = input.assertCompanyBinding
? await db.transaction(async (tx) => {
// Lock the environment row first. Managed reconciliation locks the
// same sandbox environment rows with `for update` before it writes a
// company binding, so this lock serializes the two transactions on
// this row and closes the time-of-check to time-of-use window.
await tx
.select({ id: environments.id })
.from(environments)
.where(eq(environments.id, input.environmentId))
.for("update");
// Re-read the company binding inside the locked transaction. A
// binding a reconciliation committed after the route guard now
// appears here. Reject a foreign-company environment before the
// insert, so the login holds no lease.
const boundRows = await tx
.select({ companyId: builtInManagedResources.companyId })
.from(builtInManagedResources)
.where(
and(
eq(builtInManagedResources.resourceKind, MANAGED_ENVIRONMENT_RESOURCE_KIND),
eq(builtInManagedResources.resourceId, input.environmentId),
),
);
const boundCompanyIds = Array.from(new Set(boundRows.map((boundRow) => boundRow.companyId)));
if (boundCompanyIds.length > 0 && !boundCompanyIds.includes(input.companyId)) {
throw forbidden("The selected environment belongs to another company.", {
code: "environment_company_mismatch",
});
}
return tx
if (
(input.replacesReusableLeaseId || input.reusesReusableLeaseId) &&
(!input.executionWorkspaceId || !input.providerLeaseId)
) {
throw new Error(
"A reusable lease handoff requires an execution workspace and provider lease id.",
);
}
if (input.reusesReusableLeaseId && !input.heartbeatRunId) {
throw new Error(
"A same-run reusable lease reacquisition requires a heartbeat run id.",
);
}
if (input.replacesReusableLeaseId && input.reusesReusableLeaseId) {
throw new Error(
"A reusable lease cannot be replaced and reacquired in the same operation.",
);
}
const row =
input.assertCompanyBinding ||
input.replacesReusableLeaseId ||
input.reusesReusableLeaseId
? await db.transaction(async (tx) => {
if (input.assertCompanyBinding) {
// Lock the environment row first. Managed reconciliation locks the
// same sandbox environment rows with `for update` before it writes a
// company binding, so this lock serializes the two transactions on
// this row and closes the time-of-check to time-of-use window.
await tx
.select({ id: environments.id })
.from(environments)
.where(eq(environments.id, input.environmentId))
.for("update");
// Re-read the company binding inside the locked transaction. A
// binding a reconciliation committed after the route guard now
// appears here. Reject a foreign-company environment before the
// insert, so the login holds no lease.
const boundRows = await tx
.select({ companyId: builtInManagedResources.companyId })
.from(builtInManagedResources)
.where(
and(
eq(
builtInManagedResources.resourceKind,
MANAGED_ENVIRONMENT_RESOURCE_KIND,
),
eq(
builtInManagedResources.resourceId,
input.environmentId,
),
),
);
const boundCompanyIds = Array.from(
new Set(boundRows.map((boundRow) => boundRow.companyId)),
);
if (
boundCompanyIds.length > 0 &&
!boundCompanyIds.includes(input.companyId)
) {
throw forbidden(
"The selected environment belongs to another company.",
{
code: "environment_company_mismatch",
},
);
}
}
if (input.replacesReusableLeaseId) {
const retired = await tx
.update(environmentLeases)
.set({
status: "expired",
releasedAt: now,
lastUsedAt: now,
updatedAt: now,
cleanupStatus: "success",
})
.where(
and(
eq(environmentLeases.id, input.replacesReusableLeaseId),
eq(environmentLeases.companyId, input.companyId),
eq(environmentLeases.environmentId, input.environmentId),
eq(
environmentLeases.executionWorkspaceId,
input.executionWorkspaceId!,
),
eq(environmentLeases.leasePolicy, "reuse_by_environment"),
eq(
environmentLeases.providerLeaseId,
input.providerLeaseId!,
),
inArray(environmentLeases.status, [
"released",
"retained",
]),
),
)
.returning({ id: environmentLeases.id });
if (retired.length !== 1) {
throw conflict(
"Reusable sandbox lease ownership changed during acquisition.",
);
}
}
if (input.reusesReusableLeaseId) {
const reacquired = await tx
.update(environmentLeases)
.set({
status: "active",
releasedAt: null,
lastUsedAt: now,
expiresAt: input.expiresAt ?? null,
failureReason: null,
cleanupStatus: null,
metadata: input.metadata ?? null,
updatedAt: now,
})
.where(
and(
eq(environmentLeases.id, input.reusesReusableLeaseId),
eq(environmentLeases.companyId, input.companyId),
eq(environmentLeases.environmentId, input.environmentId),
eq(
environmentLeases.executionWorkspaceId,
input.executionWorkspaceId!,
),
eq(
environmentLeases.heartbeatRunId,
input.heartbeatRunId!,
),
eq(environmentLeases.leasePolicy, "reuse_by_environment"),
eq(
environmentLeases.providerLeaseId,
input.providerLeaseId!,
),
inArray(environmentLeases.status, [
"active",
"released",
"retained",
]),
),
)
.returning()
.then((rows) => rows[0] ?? null);
if (!reacquired) {
throw conflict(
"Reusable sandbox lease ownership changed during reacquisition.",
);
}
return reacquired;
}
return tx
.insert(environmentLeases)
.values(values)
.returning()
.then((rows) => rows[0] ?? null);
})
: await db
.insert(environmentLeases)
.values(values)
.returning()
.then((rows) => rows[0] ?? null);
})
: await db
.insert(environmentLeases)
.values(values)
.returning()
.then((rows) => rows[0] ?? null);
if (!row) {
throw new Error("Failed to acquire environment lease");
}
+222 -92
View File
@@ -130,6 +130,7 @@ import {
buildNativeRuntimeContext,
cancelNativeSession,
claimNativeRestartRecoveries,
closeWarmNativeSessionsForEnvironment,
currentNativeControllerIdentity,
dispatchNativeSessionResumptions,
detachNativeSessionsForRestart,
@@ -1295,7 +1296,8 @@ export async function resolveExecutionRunAdapterConfig(input: {
input.trustPreset?.kind === "low_trust_review"
? (input.trustPreset.boundary.allowedSecretBindingIds ?? [])
: undefined;
const allowTrustedEnvProjection = input.trustPreset?.kind !== "low_trust_review";
const allowTrustedEnvProjection =
input.trustPreset?.kind !== "low_trust_review";
if (input.trustPreset?.kind === "low_trust_review") {
assertLowTrustEnvConfigAllowed(environmentEnv, "environment.env");
assertLowTrustEnvConfigAllowed(executionRunConfig.env, "agent.env");
@@ -1306,7 +1308,8 @@ export async function resolveExecutionRunAdapterConfig(input: {
const requiredScopedBindingsConfigured = requiredScopedEnvBinding
? requiredScopedEnvBinding.keys.some(
(key) =>
(allowTrustedEnvProjection && typeof input.trustedEnvProjection?.[key] === "string") ||
(allowTrustedEnvProjection &&
typeof input.trustedEnvProjection?.[key] === "string") ||
(requiredScopedEnvBinding.consumerScopes.includes("agent") &&
isConfiguredEnvBindingValue(agentEnv[key])) ||
(requiredScopedEnvBinding.consumerScopes.includes("project") &&
@@ -1567,9 +1570,9 @@ export async function resolveExecutionRunAdapterConfig(input: {
}
}
if (
allowTrustedEnvProjection
&& input.trustedEnvProjection
&& Object.keys(input.trustedEnvProjection).length > 0
allowTrustedEnvProjection &&
input.trustedEnvProjection &&
Object.keys(input.trustedEnvProjection).length > 0
) {
resolvedConfig.env = {
...parseObject(resolvedConfig.env),
@@ -1753,9 +1756,8 @@ export function providerResourceDispositionForTerminalRun(
desired: ProviderResourceDisposition | undefined,
status: string | null | undefined,
): ProviderResourceDisposition | undefined {
return desired === "keep_running" && status !== "succeeded"
? "stop_and_retain"
: desired;
if (desired !== "keep_running") return desired;
return status === "succeeded" ? desired : "stop_and_retain";
}
export interface NativeSandboxLifecycle {
@@ -4089,19 +4091,22 @@ export async function buildPaperclipRuntimeMcpServers(input: {
const [runIdentity] = await input.db
.select({ responsibleUserId: heartbeatRuns.responsibleUserId })
.from(heartbeatRuns)
.where(and(
eq(heartbeatRuns.id, input.runId),
eq(heartbeatRuns.companyId, input.agent.companyId),
eq(heartbeatRuns.agentId, input.agent.id),
))
.where(
and(
eq(heartbeatRuns.id, input.runId),
eq(heartbeatRuns.companyId, input.agent.companyId),
eq(heartbeatRuns.agentId, input.agent.id),
),
)
.limit(1);
const resolvedInstalledConnections = await filterResolvedGitHubConnectionsForRun({
db: input.db,
companyId: input.agent.companyId,
agentId: input.agent.id,
responsibleUserId: runIdentity?.responsibleUserId ?? null,
connections: effective.installedConnections,
});
const resolvedInstalledConnections =
await filterResolvedGitHubConnectionsForRun({
db: input.db,
companyId: input.agent.companyId,
agentId: input.agent.id,
responsibleUserId: runIdentity?.responsibleUserId ?? null,
connections: effective.installedConnections,
});
const permittedConnectionIds = new Set([
...effective.entries
.filter((entry) => entry.effect === "include" && entry.connectionId)
@@ -4572,30 +4577,36 @@ export async function createManagedMcpRunConfig(input: {
const [runIdentity] = await input.db
.select({ responsibleUserId: heartbeatRuns.responsibleUserId })
.from(heartbeatRuns)
.where(and(
eq(heartbeatRuns.id, input.runId),
eq(heartbeatRuns.companyId, input.agent.companyId),
eq(heartbeatRuns.agentId, input.agent.id),
))
.where(
and(
eq(heartbeatRuns.id, input.runId),
eq(heartbeatRuns.companyId, input.agent.companyId),
eq(heartbeatRuns.agentId, input.agent.id),
),
)
.limit(1);
const resolvedAvailableInstalls = await filterResolvedGitHubConnectionsForRun({
db: input.db,
companyId: input.agent.companyId,
agentId: input.agent.id,
responsibleUserId: runIdentity?.responsibleUserId ?? null,
connections: installRows.filter(
(install) =>
install.enabled &&
install.status === "active" &&
!["degraded", "failed", "error", "missing_secret"].includes(
install.healthStatus,
),
).map((install) => ({
id: install.connectionId,
config: install.config,
transportConfig: install.transportConfig,
})),
});
const resolvedAvailableInstalls = await filterResolvedGitHubConnectionsForRun(
{
db: input.db,
companyId: input.agent.companyId,
agentId: input.agent.id,
responsibleUserId: runIdentity?.responsibleUserId ?? null,
connections: installRows
.filter(
(install) =>
install.enabled &&
install.status === "active" &&
!["degraded", "failed", "error", "missing_secret"].includes(
install.healthStatus,
),
)
.map((install) => ({
id: install.connectionId,
config: install.config,
transportConfig: install.transportConfig,
})),
},
);
const availableInstalledConnectionIds = new Set(
resolvedAvailableInstalls.map((install) => install.id),
);
@@ -6055,6 +6066,14 @@ function buildSessionConfigCategoryValues(input: {
// the timestamp here makes every comment invalidate an otherwise reusable
// task session.
delete workspaceConfig.issueConfigRevisionAt;
// This row is runtime state, not requested configuration. It is absent
// before the first reusable run is realized and present on the next turn;
// fingerprinting that transition would rotate the native session exactly
// when the warm runner first becomes reusable. The requested/effective mode,
// project policy, and issue settings remain the configuration compatibility
// boundary; the reusable row and its evolving generation are state.
delete workspaceConfig.existingExecutionWorkspace;
delete workspaceConfig.reusableExecutionWorkspaceConfig;
return {
adapter: {
adapterType: input.adapterType,
@@ -8151,6 +8170,11 @@ export interface HeartbeatServiceOptions {
nativeSessionBackendFactory?: (
execution: NativeExecutionInput,
) => NativeSessionBackend;
/** Test seam for observing the native-session shutdown boundary before lease destruction. */
closeWarmNativeSessionsForRun?: (input: {
runId: string;
reason: string;
}) => Promise<{ closed: number; busy: number; failed: number }>;
/** Test seam for changing a continuation issue at the final pre-dispatch boundary. */
beforeResolvedInteractionContinuationDispatchCheck?: (input: {
runId: string;
@@ -8731,6 +8755,57 @@ export function heartbeatService(
sandboxResource: "keep_running" | "stop_and_reuse" | "destroy_after_turn";
};
}) {
if (input.providerResourceDisposition === "destroy") {
const closeResult = await (
options.closeWarmNativeSessionsForRun ??
(async ({ runId, reason }) => {
const environmentIds = await db
.selectDistinct({ environmentId: environmentLeases.environmentId })
.from(environmentLeases)
.where(
and(
eq(environmentLeases.heartbeatRunId, runId),
eq(environmentLeases.status, "active"),
),
)
.then((rows) =>
rows.flatMap((row) =>
typeof row.environmentId === "string" &&
row.environmentId.length > 0
? [row.environmentId]
: [],
),
);
const aggregate = { closed: 0, busy: 0, failed: 0 };
for (const environmentId of environmentIds) {
const result = await closeWarmNativeSessionsForEnvironment({
environmentId,
reason,
});
aggregate.closed += result.closed;
aggregate.busy += result.busy;
aggregate.failed += result.failed;
}
return aggregate;
})
)({
runId: input.runId,
reason: "terminal heartbeat run destroyed its environment lease",
}).catch((err) => {
logger.warn(
{ err, runId: input.runId },
"failed to close warm native sessions before environment lease destruction",
);
return { closed: 0, busy: 0, failed: 1 };
});
if (closeResult.busy > 0 || closeResult.failed > 0) {
logger.warn(
{ runId: input.runId, warmNativeSessions: closeResult },
"deferred environment lease destruction until warm native sessions close",
);
return;
}
}
const releaseResult = await envOrchestrator
.releaseForRun({
heartbeatRunId: input.runId,
@@ -10408,8 +10483,9 @@ export function heartbeatService(
readNonEmptyString(context.issueId) ?? readNonEmptyString(context.taskId);
const resolveGitAuth = createGitRemoteAuthProvider(db, agent.companyId, {
issueId,
responsibleUserId: readNonEmptyString(context.responsibleUserId)
?? readNonEmptyString(context.responsible_user_id),
responsibleUserId:
readNonEmptyString(context.responsibleUserId) ??
readNonEmptyString(context.responsible_user_id),
agentId: agent.id,
});
const contextProjectId = readNonEmptyString(context.projectId);
@@ -10668,8 +10744,9 @@ export function heartbeatService(
readNonEmptyString(context.issueId) ?? readNonEmptyString(context.taskId);
const resolveGitAuth = createGitRemoteAuthProvider(db, agent.companyId, {
issueId,
responsibleUserId: readNonEmptyString(context.responsibleUserId)
?? readNonEmptyString(context.responsible_user_id),
responsibleUserId:
readNonEmptyString(context.responsibleUserId) ??
readNonEmptyString(context.responsible_user_id),
agentId: agent.id,
});
const { additionalWorkspaces, warnings, failures } =
@@ -18760,12 +18837,16 @@ export function heartbeatService(
issueId,
explicitRunScopedSkillKeys: runScopedMentionedSkillKeys,
});
const githubRunAuth = await createGitRemoteAuthProvider(db, agent.companyId, {
issueId,
heartbeatRunId: run.id,
responsibleUserId,
agentId: agent.id,
})("https://github.com/paperclipai/credential-probe.git");
const githubRunAuth = await createGitRemoteAuthProvider(
db,
agent.companyId,
{
issueId,
heartbeatRunId: run.id,
responsibleUserId,
agentId: agent.id,
},
)("https://github.com/paperclipai/credential-probe.git");
const { resolvedConfig, secretKeys, secretManifest } =
await resolveExecutionRunAdapterConfig({
companyId: agent.companyId,
@@ -18784,10 +18865,16 @@ export function heartbeatService(
routineEnv: routineEnvContext.env,
secretsSvc,
trustPreset,
...(githubRunAuth ? {
trustedEnvProjection: githubRunAuth.env,
trustedEnvSecretKeys: ["GH_TOKEN", "GITHUB_TOKEN", GIT_CREDENTIAL_TOKEN_ENV_KEY],
} : {}),
...(githubRunAuth
? {
trustedEnvProjection: githubRunAuth.env,
trustedEnvSecretKeys: [
"GH_TOKEN",
"GITHUB_TOKEN",
GIT_CREDENTIAL_TOKEN_ENV_KEY,
],
}
: {}),
requiredScopedEnvBinding: pushCapabilityPreflightRequired
? {
keys: [...PUSH_CAPABILITY_ENV_KEYS],
@@ -19223,6 +19310,63 @@ export function heartbeatService(
const resolvedProjectWorkspaceId =
issueRef?.projectWorkspaceId ?? resolvedWorkspace.workspaceId ?? null;
let persistedExecutionWorkspace: ExecutionWorkspace | null = null;
let issueExecutionWorkspaceIdForRun =
issueRef?.executionWorkspaceId ?? null;
let issueProjectWorkspaceIdForRun = issueRef?.projectWorkspaceId ?? null;
let issueExecutionWorkspacePreferenceForRun =
issueRef?.executionWorkspacePreference ?? null;
let issueExecutionWorkspaceModeForRun =
issueExecutionWorkspaceSettings?.mode ?? null;
const warmReusableExecutionWorkspace =
selectedEnvironmentForConfig?.driver === "sandbox" &&
selectedEnvironmentConfigForFingerprint.reuseLease === true &&
selectedEnvironmentConfigForFingerprint.runnerLifecycleMode === "warm";
const bindIssueToPersistedExecutionWorkspace = async (
workspace: ExecutionWorkspace | null,
) => {
if (!issueId || !workspace || nativeRecoveryExecutionWorkspaceId) {
return;
}
const nextIssueWorkspaceMode =
issueExecutionWorkspaceModeForPersistedWorkspace(workspace.mode) ??
"agent_default";
const shouldSwitchIssueToExistingWorkspace =
issueRef?.executionWorkspacePreference === "reuse_existing" ||
requestedExecutionWorkspaceMode === "isolated_workspace" ||
requestedExecutionWorkspaceMode === "operator_branch" ||
warmReusableExecutionWorkspace;
const nextIssuePatch: Record<string, unknown> = {};
if (issueExecutionWorkspaceIdForRun !== workspace.id) {
nextIssuePatch.executionWorkspaceId = workspace.id;
}
if (
resolvedProjectWorkspaceId &&
issueProjectWorkspaceIdForRun !== resolvedProjectWorkspaceId
) {
nextIssuePatch.projectWorkspaceId = resolvedProjectWorkspaceId;
}
if (
shouldSwitchIssueToExistingWorkspace &&
(issueExecutionWorkspacePreferenceForRun !== "reuse_existing" ||
issueExecutionWorkspaceModeForRun !== nextIssueWorkspaceMode)
) {
nextIssuePatch.executionWorkspacePreference = "reuse_existing";
nextIssuePatch.executionWorkspaceSettings = {
...(issueExecutionWorkspaceSettings ?? {}),
mode: nextIssueWorkspaceMode,
};
}
if (Object.keys(nextIssuePatch).length > 0) {
await issuesSvc.update(issueId, nextIssuePatch);
issueExecutionWorkspaceIdForRun = workspace.id;
issueProjectWorkspaceIdForRun =
resolvedProjectWorkspaceId ?? issueProjectWorkspaceIdForRun;
if (shouldSwitchIssueToExistingWorkspace) {
issueExecutionWorkspacePreferenceForRun = "reuse_existing";
issueExecutionWorkspaceModeForRun = nextIssueWorkspaceMode;
}
}
};
const baseExecutionWorkspaceMetadata =
mergeExecutionWorkspaceMetadataForPersistence({
existingMetadata:
@@ -19440,40 +19584,7 @@ export function heartbeatService(
},
);
}
if (
issueId &&
persistedExecutionWorkspace &&
!nativeRecoveryExecutionWorkspaceId
) {
const nextIssueWorkspaceMode =
issueExecutionWorkspaceModeForPersistedWorkspace(
persistedExecutionWorkspace.mode,
);
const shouldSwitchIssueToExistingWorkspace =
issueRef?.executionWorkspacePreference === "reuse_existing" ||
requestedExecutionWorkspaceMode === "isolated_workspace" ||
requestedExecutionWorkspaceMode === "operator_branch";
const nextIssuePatch: Record<string, unknown> = {};
if (issueRef?.executionWorkspaceId !== persistedExecutionWorkspace.id) {
nextIssuePatch.executionWorkspaceId = persistedExecutionWorkspace.id;
}
if (
resolvedProjectWorkspaceId &&
issueRef?.projectWorkspaceId !== resolvedProjectWorkspaceId
) {
nextIssuePatch.projectWorkspaceId = resolvedProjectWorkspaceId;
}
if (shouldSwitchIssueToExistingWorkspace) {
nextIssuePatch.executionWorkspacePreference = "reuse_existing";
nextIssuePatch.executionWorkspaceSettings = {
...(issueExecutionWorkspaceSettings ?? {}),
mode: nextIssueWorkspaceMode,
};
}
if (Object.keys(nextIssuePatch).length > 0) {
await issuesSvc.update(issueId, nextIssuePatch);
}
}
await bindIssueToPersistedExecutionWorkspace(persistedExecutionWorkspace);
if (persistedExecutionWorkspace) {
context.executionWorkspaceId = persistedExecutionWorkspace.id;
await db
@@ -19612,6 +19723,11 @@ export function heartbeatService(
};
persistedExecutionWorkspace =
realizationResult.persistedExecutionWorkspace;
// A sandbox realization may materialize or replace the durable workspace
// after the host-side provisioning boundary above. Bind that final ID to
// the issue before dispatch so warm turns reuse the exact same workspace
// and lease scope instead of silently creating a per-run replacement.
await bindIssueToPersistedExecutionWorkspace(persistedExecutionWorkspace);
const workspaceRealization = realizationResult.workspaceRealization;
const executionTarget = realizationResult.executionTarget;
const remoteExecution = realizationResult.remoteExecution;
@@ -20861,6 +20977,7 @@ export function heartbeatService(
target: executionTarget,
lease: activeEnvironmentLease.lease,
restartRecovery: runOptions.nativeRestartRecovery,
sameRunRecovery: Boolean(runOptions.nativeLeaseOwner),
resourceDisposition: providerResourceDispositionForRun,
});
} else {
@@ -22207,6 +22324,7 @@ export function heartbeatService(
.select({
nextAttemptAt: nativeRunFinalizations.nextAttemptAt,
attempt: nativeRunFinalizations.attempt,
failureDetail: nativeRunFinalizations.failureDetail,
})
.from(nativeRunFinalizations)
.where(eq(nativeRunFinalizations.runId, run.id))
@@ -22225,6 +22343,12 @@ export function heartbeatService(
nextAttemptAt: coordinator?.nextAttemptAt?.toISOString() ?? null,
fallbackSuppressed: true,
retryReasonCode,
// The executor has already redacted and bounded this diagnostic
// before persisting it. Retain it on the immutable transition
// event as well: a same-run retry reopens the log stream, so the
// first attempt's stderr must not be the only explanation for
// why a live warm runner was replaced.
failureDetail: coordinator?.failureDetail ?? null,
},
}).catch(() => undefined);
if (coordinator?.nextAttemptAt) {
@@ -22415,7 +22539,13 @@ export function heartbeatService(
livenessRun,
agent,
);
await releaseIssueExecutionAndPromote(livenessRun);
await releaseIssueExecutionAndPromote(livenessRun, {
// Native recovery owns the original heartbeat run through
// exhaustion. Once its durable coordinator has classified a
// terminal failure, generic issue recovery must not create a
// replacement retryOfRunId chain for the same provider work.
suppressImmediateRecovery: nativeTerminalFailureCode !== null,
});
await handleIssueReviewPathDisposition(livenessRun);
await updateRuntimeState(
@@ -1989,14 +1989,31 @@ export function issueThreadInteractionService(db: Db, opts: IssueThreadInteracti
"Interaction has already been resolved",
);
}
if (isNativeCompletionReview(lockedCurrent)) {
await issueService(db).update(args.issue.id, {
status: "todo",
assigneeAgentId: issueContext.assigneeAgentId,
assigneeUserId: null,
actorAgentId: args.actor.agentId ?? null,
actorUserId: args.actor.userId ?? null,
}, tx);
const rejectedPlanNeedsRevision =
lockedCurrent.kind === "request_confirmation" &&
readAcceptedPlanConfirmationTarget(
lockedCurrent.payload,
issueContext.id,
)?.key === "plan";
const shouldResumeReviewedIssue =
issueContext.status === "in_review" &&
(lockedCurrent.continuationPolicy === "wake_assignee" ||
rejectedPlanNeedsRevision);
if (
isNativeCompletionReview(lockedCurrent) ||
shouldResumeReviewedIssue
) {
await issueService(db).update(
args.issue.id,
{
status: "todo",
assigneeAgentId: issueContext.assigneeAgentId,
assigneeUserId: null,
actorAgentId: args.actor.agentId ?? null,
actorUserId: args.actor.userId ?? null,
},
tx,
);
} else {
await touchIssue(tx, args.issue.id);
}
+55 -7
View File
@@ -8963,7 +8963,7 @@ export function issueService(db: Db) {
});
},
addComment: async (
addComment: async function addComment(
issueId: string,
body: string,
actor: {
@@ -8981,7 +8981,21 @@ export function issueService(db: Db) {
createdAt?: Date | string | null;
},
dbOrTx: any = db,
) => {
): Promise<IssueComment> {
if (dbOrTx === db && actor.runId) {
return db.transaction(async (tx) => {
// Serialize run-authored comments on the issue so a provider retry
// cannot publish the same visible result twice. This needs no schema
// change: the issue row is the transaction fence, and the recursive
// call below performs the lookup and insert while holding it.
await tx
.select({ id: issues.id })
.from(issues)
.where(eq(issues.id, issueId))
.for("update");
return addComment(issueId, body, actor, options, tx);
});
}
const issue = await dbOrTx
.select({ companyId: issues.companyId })
.from(issues)
@@ -9016,11 +9030,45 @@ export function issueService(db: Db) {
actor.onBehalfOfUserId,
)
: null;
const metadata = issueCommentMetadataSchema.nullable().parse(
actor.agentId
? withAgentCommentAuthorizationMetadata(options?.metadata ?? null, options?.authorizationReason)
: options?.metadata ?? null,
);
const metadata = issueCommentMetadataSchema
.nullable()
.parse(
actor.agentId
? withAgentCommentAuthorizationMetadata(
options?.metadata ?? null,
options?.authorizationReason,
)
: (options?.metadata ?? null),
);
if (createdByRunId) {
const existing = await dbOrTx
.select()
.from(issueComments)
.where(
and(
eq(issueComments.companyId, issue.companyId),
eq(issueComments.issueId, issueId),
eq(issueComments.createdByRunId, createdByRunId),
eq(issueComments.authorType, authorType),
actor.agentId
? eq(issueComments.authorAgentId, actor.agentId)
: isNull(issueComments.authorAgentId),
eq(issueComments.body, redactedBody),
isNull(issueComments.deletedAt),
),
)
.orderBy(issueComments.createdAt, issueComments.id)
.limit(1)
.then(
(rows: Array<typeof issueComments.$inferSelect>) => rows[0] ?? null,
);
if (existing) {
return redactIssueComment(
existing,
currentUserRedactionOptions.enabled,
);
}
}
const [comment] = await dbOrTx
.insert(issueComments)
.values({
@@ -167,7 +167,9 @@ import {
buildNativeProviderEnvironment,
buildNativeHarnessBackupManifest,
cancelNativeSession,
closeWarmNativeSessionsForEnvironment,
createGovernedWaitEventObservation,
createRemoteRunnerProcessLauncher,
createRunnerdBackend,
executePaperclipNativeSession,
getNativeSessionSteeringState,
@@ -181,6 +183,7 @@ import {
mayUsePreinstalledRunnerArtifact,
nativeUsageCostUsd,
normalizeNativeUsage,
parseRemoteRunnerProcessIdentity,
readRemoteProviderPackManifest,
providerSessionIdentityFromDurableProviderState,
providerSessionIdentityTransitionIsAllowed,
@@ -202,6 +205,285 @@ import {
shouldRestoreNativeHarnessBackupIntoSandbox,
} from "./native-session-executor.js";
describe("remote runner process supervision", () => {
it("detaches runnerd from the provider RPC and monitors its durable identity", async () => {
let launchNonce = "";
const execute = vi.fn(
async (input: {
command?: string;
args?: string[];
timeoutMs?: number;
useSession?: boolean;
bypassSession?: boolean;
}) => {
const label = input.args?.[2];
if (label === "paperclip-runner-launch") {
launchNonce = input.args?.[4] ?? "";
return {
exitCode: 0,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
};
}
if (label === "paperclip-runner-process-identity") {
return {
exitCode: 0,
signal: null,
timedOut: false,
stdout: `${launchNonce}\n4321\n2026-09-06T00:00:00.000Z\nrunner-remote\n`,
stderr: "",
};
}
if (label === "paperclip-runner-monitor") {
return {
exitCode: 3,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
};
}
if (label === "paperclip-runner-diagnostics") {
return {
exitCode: 0,
signal: null,
timedOut: false,
stdout: "paperclip-runnerd: provider transport closed",
stderr: "",
};
}
if (input.command === "sh" && input.args?.[1]?.includes("base64")) {
return {
exitCode: 0,
signal: null,
timedOut: false,
stdout: Buffer.from(
JSON.stringify({
lifecycle: "ready",
diagnostics: ["last durable diagnostic"],
}),
).toString("base64"),
stderr: "",
};
}
if (label === "paperclip-runner-signal") {
return {
exitCode: 0,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
};
}
throw new Error(`unexpected remote command: ${label ?? "missing"}`);
},
);
const onSpawn = vi.fn(async () => undefined);
const launcher = createRemoteRunnerProcessLauncher({
target: {
kind: "remote",
transport: "sandbox",
environmentId: "environment-remote",
leaseId: "lease-remote",
remoteCwd: "/workspace",
},
runner: { execute } as never,
remoteBinary: "/runtime/paperclip-runnerd",
processIdentityPath: "/runtime/runner-process.identity",
stateDirectory: "/runtime",
diagnosticsDirectory: "/runtime/diagnostics",
runnerInstanceId: "runner-remote",
onSpawn,
});
const handle = launcher({
command: "/controller/paperclip-runnerd",
args: ["--runner-id", "runner-remote"],
cwd: "/controller",
environment: {},
});
await expect(handle.completion).resolves.toMatchObject({
code: null,
stderr: "paperclip-runnerd: provider transport closed",
});
const launch = execute.mock.calls.find(
([input]) => input.args?.[2] === "paperclip-runner-launch",
)?.[0];
expect(launch).toMatchObject({
timeoutMs: 20_000,
bypassSession: true,
});
expect(launch?.useSession).toBeUndefined();
expect(launch?.args?.[1]).toContain("nohup setsid");
expect(launch?.args?.[6]).toContain('"$$"');
expect(launch?.args?.[6]).toContain('exec "$@"');
expect(launch?.args?.[7]).toBe("/runtime/diagnostics");
expect(launch?.args).toContain("/runtime/diagnostics");
expect(onSpawn).toHaveBeenCalledExactlyOnceWith({
pid: 4321,
processGroupId: null,
startedAt: "2026-09-06T00:00:00.000Z",
});
expect(handle.child.pid).toBe(4321);
expect(handle.child.kill("SIGKILL")).toBe(true);
await vi.waitFor(() =>
expect(
execute.mock.calls.some(
([input]) =>
input.args?.[2] === "paperclip-runner-signal" &&
input.args?.[1]?.includes('kill -KILL "$expected_pid"'),
),
).toBe(true),
);
});
it("terminates a detached runner when its process identity cannot be adopted", async () => {
vi.useFakeTimers();
try {
let launchNonce = "";
const execute = vi.fn(
async (input: { command?: string; args?: string[] }) => {
const label = input.args?.[2];
if (label === "paperclip-runner-launch") {
launchNonce = input.args?.[4] ?? "";
return {
exitCode: 0,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
};
}
if (label === "paperclip-runner-process-identity") {
return {
exitCode: 3,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
};
}
if (label === "paperclip-runner-identity-failure-cleanup") {
expect(input.args?.[4]).toBe(launchNonce);
return {
exitCode: 0,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
};
}
throw new Error(`unexpected remote command: ${label ?? "missing"}`);
},
);
const launcher = createRemoteRunnerProcessLauncher({
target: {
kind: "remote",
transport: "sandbox",
environmentId: "environment-remote",
leaseId: "lease-remote",
remoteCwd: "/workspace",
},
runner: { execute } as never,
remoteBinary: "/runtime/paperclip-runnerd",
processIdentityPath: "/runtime/runner-process.identity",
stateDirectory: "/runtime",
diagnosticsDirectory: "/runtime/diagnostics",
runnerInstanceId: "runner-remote",
});
const handle = launcher({
command: "/controller/paperclip-runnerd",
args: ["--runner-id", "runner-remote"],
cwd: "/controller",
environment: {},
});
const completion = expect(handle.completion).rejects.toThrow(
"runner_remote_process_identity_unavailable",
);
await vi.advanceTimersByTimeAsync(20_100);
await completion;
const cleanup = execute.mock.calls.find(
([call]) =>
call.args?.[2] === "paperclip-runner-identity-failure-cleanup",
)?.[0];
expect(cleanup).toMatchObject({
bypassSession: true,
timeoutMs: 20_000,
});
expect(cleanup?.args?.[1]).toContain('test "$nonce" = "$expected_nonce"');
expect(cleanup?.args?.[1]).toContain('grep -Fqx -- "--runner-id"');
expect(cleanup?.args?.[1]).toContain('kill -TERM -- "$signal_target"');
expect(cleanup?.args?.[1]).toContain('kill -KILL -- "$signal_target"');
expect(cleanup?.args?.[1]?.indexOf("rm -f --")).toBeGreaterThan(
cleanup?.args?.[1]?.indexOf('kill -0 "$pid" 2>/dev/null && exit 5') ??
Number.MAX_SAFE_INTEGER,
);
} finally {
vi.useRealTimers();
}
});
it("reports cleanup failure when a detached runner cannot be safely identified", async () => {
vi.useFakeTimers();
try {
const execute = vi.fn(
async (input: { command?: string; args?: string[] }) => {
const label = input.args?.[2];
return {
exitCode:
label === "paperclip-runner-launch"
? 0
: label === "paperclip-runner-process-identity"
? 3
: label === "paperclip-runner-identity-failure-cleanup"
? 4
: 1,
signal: null,
timedOut: false,
stdout: "",
stderr: "",
};
},
);
const launcher = createRemoteRunnerProcessLauncher({
target: {
kind: "remote",
transport: "sandbox",
environmentId: "environment-remote",
leaseId: "lease-remote",
remoteCwd: "/workspace",
},
runner: { execute } as never,
remoteBinary: "/runtime/paperclip-runnerd",
processIdentityPath: "/runtime/runner-process.identity",
stateDirectory: "/runtime",
diagnosticsDirectory: "/runtime/diagnostics",
runnerInstanceId: "runner-remote",
});
const handle = launcher({
command: "/controller/paperclip-runnerd",
args: ["--runner-id", "runner-remote"],
cwd: "/controller",
environment: {},
});
const completion = expect(handle.completion).rejects.toThrow(
"runner_remote_process_identity_unavailable_cleanup_failed",
);
await vi.advanceTimersByTimeAsync(20_100);
await completion;
} finally {
vi.useRealTimers();
}
});
});
describe("native incomplete-bootstrap evidence", () => {
it("requires zero connections, zero events, and only untouched bootstrap commands", async () => {
const root = await mkdtemp(join(tmpdir(), "native-bootstrap-evidence-"));
@@ -1346,6 +1628,40 @@ describe("remote preinstalled executable discovery", () => {
});
describe("remote runner build metadata", () => {
it("accepts only an exact remote runner process identity marker", () => {
const expected = {
nonce: "launch-nonce",
runnerInstanceId: "runner-remote-process",
};
expect(
parseRemoteRunnerProcessIdentity(
"launch-nonce\n4102\n2026-09-06T04:20:30.123Z\nrunner-remote-process\n",
expected,
),
).toEqual({
pid: 4102,
startedAt: "2026-09-06T04:20:30.123Z",
});
expect(
parseRemoteRunnerProcessIdentity(
"stale-nonce\n4102\n2026-09-06T04:20:30.123Z\nrunner-remote-process\n",
expected,
),
).toBeNull();
expect(
parseRemoteRunnerProcessIdentity(
"launch-nonce\n4102\n2026-09-06T04:20:30.123Z\nwrong-runner\n",
expected,
),
).toBeNull();
expect(
parseRemoteRunnerProcessIdentity(
"launch-nonce\nnot-a-pid\n2026-09-06T04:20:30.123Z\nrunner-remote-process\n",
expected,
),
).toBeNull();
});
const current = {
schema: "paperclip-runner/runnerd-build-metadata/v1",
binaryName: "paperclip-runnerd",
@@ -2716,6 +3032,66 @@ describe("native session same-turn steering", () => {
});
describe("native warm session supervision", () => {
it("closes an idle warm session before its remote environment is destroyed", async () => {
const close = vi.fn(async () => undefined);
const warmExecution = {
...execution,
binding: {
...execution.binding,
runId: "run-warm-environment-delete",
executionWorkspaceId: "workspace-warm-environment-delete",
},
session: {
...execution.session,
normalizedSessionId: "session-warm-environment-delete",
lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 },
},
} as NativeExecutionInputV1;
state.execute.mockReset().mockImplementationOnce(async (options) => {
options.onSession?.({ close });
return {
result: { summary: "completed" },
terminal: { runTerminalState: "succeeded" },
turnId: "turn-warm-environment-delete",
normalizedSessionId: warmExecution.session.normalizedSessionId,
providerSessionId: "provider-warm-environment-delete",
driverKind: "test",
driverVersion: "1",
nativeEventCount: 1,
highestContiguousSourceSeq: 1,
usage: null,
};
});
await executePaperclipNativeSession({
db: leaseDb(warmExecution),
execution: warmExecution,
runnerInstanceId: "runner-warm-environment-delete",
runnerExecutionTarget: {
kind: "remote",
transport: "sandbox",
environmentId: "environment-warm-delete",
remoteCwd: "/tmp/warm-environment-delete",
},
});
await expect(
closeWarmNativeSessionsForEnvironment({
environmentId: "other-environment",
reason: "environment deleted",
}),
).resolves.toEqual({ closed: 0, busy: 0, failed: 0 });
await expect(
closeWarmNativeSessionsForEnvironment({
environmentId: "environment-warm-delete",
reason: "environment deleted",
}),
).resolves.toEqual({ closed: 1, busy: 0, failed: 0 });
expect(close).toHaveBeenCalledExactlyOnceWith({
reason: "environment deleted",
});
});
it("preserves the active turn when a warm checkpoint resumes the same run", async () => {
const stateBase = await mkdtemp(
join(tmpdir(), "paperclip-warm-same-run-recovery-"),
@@ -2852,11 +3228,13 @@ describe("native warm session supervision", () => {
.mockReset()
.mockImplementationOnce(async (options) => {
expect(options.existingSession).toBeUndefined();
expect(options.semanticResultTerminalGraceMs).toBe(30_000);
options.onSession?.(sharedSession);
return result;
})
.mockImplementationOnce(async (options) => {
expect(options.existingSession).toBe(sharedSession);
expect(options.semanticResultTerminalGraceMs).toBe(30_000);
return result;
});
@@ -2880,6 +3258,67 @@ describe("native warm session supervision", () => {
);
});
it("does not offer a quarantined warm session to the next run", async () => {
const close = vi.fn(async () => undefined);
const quarantinedSession = { close };
const first = {
...execution,
binding: {
...execution.binding,
runId: "run-native-warm-quarantined-first",
executionWorkspaceId: "workspace-native-warm-quarantined",
},
session: {
...execution.session,
normalizedSessionId: "session-native-warm-quarantined",
lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 },
},
} as NativeExecutionInputV1;
const second = {
...first,
binding: {
...first.binding,
runId: "run-native-warm-quarantined-second",
},
} as NativeExecutionInputV1;
const result = {
result: { summary: "completed" },
terminal: { runTerminalState: "succeeded" },
turnId: "turn",
normalizedSessionId: first.session.normalizedSessionId,
providerSessionId: "provider-native-warm-quarantined",
driverKind: "test",
driverVersion: "1",
nativeEventCount: 1,
highestContiguousSourceSeq: 1,
usage: null,
};
state.execute
.mockReset()
.mockImplementationOnce(async (options) => {
expect(options.existingSession).toBeUndefined();
options.onSession?.(quarantinedSession);
options.onSession?.(null);
return result;
})
.mockImplementationOnce(async (options) => {
expect(options.existingSession).toBeUndefined();
return result;
});
await executePaperclipNativeSession({
db: leaseDb(first),
execution: first,
runnerInstanceId: "runner-native-warm-quarantined",
});
await executePaperclipNativeSession({
db: leaseDb(second),
execution: second,
runnerInstanceId: "runner-native-warm-quarantined",
});
expect(close).not.toHaveBeenCalled();
});
it("reattaches a live runnerd warm session under a fresh run authority", async () => {
const stateBase = await mkdtemp(
join(tmpdir(), "paperclip-runnerd-warm-authority-"),
@@ -2907,13 +3346,20 @@ describe("native warm session supervision", () => {
normalizedSessionId: "session-runnerd-warm-authority",
driverKind: "codex_app_server" as const,
protocolVersion: 1 as const,
lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 20 },
lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 500 },
},
} as NativeExecutionInputV1;
const second = {
...first,
binding: { ...first.binding, runId: "run-runnerd-warm-second" },
} as NativeExecutionInputV1;
const remoteTarget = {
kind: "remote" as const,
transport: "sandbox" as const,
environmentId: "environment-runnerd-warm-authority",
remoteCwd: "/home/daytona/paperclip-workspace",
runner: { execute: vi.fn() },
} as never;
const result = {
result: { summary: "completed" },
terminal: { runTerminalState: "succeeded" },
@@ -2956,6 +3402,7 @@ describe("native warm session supervision", () => {
execution: first,
runnerInstanceId: "runner-runnerd-warm",
useRunnerd: true,
runnerExecutionTarget: remoteTarget,
});
const scopedRoots = (await readdir(stateBase, { withFileTypes: true }))
.filter(
@@ -2971,15 +3418,10 @@ describe("native warm session supervision", () => {
environmentLeaseId: first.binding.executionWorkspaceId,
};
await mkdir(join(durableRoot, "control-plane"), { recursive: true });
await mkdir(join(durableRoot, "runner"), { recursive: true });
await writeFile(
join(durableRoot, "control-plane", "control-plane-state.json"),
JSON.stringify(durableControlPlaneState(durableIdentity)),
);
await writeFile(
join(durableRoot, "runner", "runner-state.json"),
JSON.stringify(durableRunnerState(durableIdentity, "suspended")),
);
const continuationDb = {
...leaseDb(second),
select: () => ({
@@ -3001,13 +3443,18 @@ describe("native warm session supervision", () => {
execution: second,
runnerInstanceId: "runner-runnerd-warm",
useRunnerd: true,
runnerExecutionTarget: remoteTarget,
});
expect(firstClose).not.toHaveBeenCalled();
await vi.waitFor(() => expect(firstClose).toHaveBeenCalledWith({
reason: "warm native session idle timeout",
}), {
timeout: 500,
});
await vi.waitFor(
() =>
expect(firstClose).toHaveBeenCalledWith({
reason: "warm native session idle timeout",
}),
{
timeout: 1_500,
},
);
} finally {
if (previousStateDirectory === undefined) {
delete process.env.PAPERCLIP_RUNNER_STATE_DIR;
@@ -3760,6 +4207,7 @@ describe("runnerd provider runtime wiring", () => {
state.createBackend.mock.calls[0]![1].codexTransportFactory!();
expect(state.createTransport).toHaveBeenCalledWith(
expect.objectContaining({
externallySandboxed: true,
environment: expect.objectContaining({
PAPERCLIP_RUNNER_EXTERNAL_SANDBOX: "1",
}),
@@ -186,6 +186,12 @@ const TERMINAL_HEARTBEAT_RUN_STATUSES = new Set([
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;
// A reusable provider must publish its terminal suffix before the next run can
// rotate PRP authority. Remote Codex can take more than the ordinary five-second
// result grace to flush its final answer over Daytona, so retain the bounded
// turn long enough to reach a naturally quiescent, reusable state. This adds no
// delay when the provider terminates normally.
const NATIVE_WARM_SEMANTIC_RESULT_TERMINAL_GRACE_MS = 30_000;
const NATIVE_RUNTIME_REQUEST_RESOLUTION_CACHE_MAX = 256;
type NativeRuntimeRequestResolution = {
runId: string;
@@ -258,7 +264,10 @@ function clearNativeRuntimeRequestResolutions(runId: string): void {
type WarmNativeSession = {
session: NativeSession;
ownerToken: symbol;
configDigest: string;
companyId: string;
environmentId: string | null;
busy: boolean;
idleTimer: ReturnType<typeof setTimeout> | null;
lastActivityAt: string;
@@ -266,6 +275,42 @@ type WarmNativeSession = {
const warmNativeSessions = new Map<string, WarmNativeSession>();
/**
* Close idle native sessions before an operator destroys their remote
* environment. A warm runner owns a long-lived sandbox command stream, so the
* provider cannot safely delete that sandbox until the session has closed the
* stream. Busy sessions are reported instead of interrupted; the environment
* delete guard can then fail closed while their heartbeat run is still live.
*/
export async function closeWarmNativeSessionsForEnvironment(input: {
environmentId: string;
reason: string;
}): Promise<{ closed: number; busy: number; failed: number }> {
let closed = 0;
let busy = 0;
let failed = 0;
for (const [sessionId, entry] of [...warmNativeSessions]) {
if (entry.environmentId !== input.environmentId) {
continue;
}
if (entry.busy) {
busy += 1;
continue;
}
if (entry.idleTimer !== null) clearTimeout(entry.idleTimer);
// Remove ownership before awaiting close so a racing continuation cannot
// adopt a session whose transport is already shutting down.
warmNativeSessions.delete(sessionId);
try {
await entry.session.close({ reason: input.reason });
closed += 1;
} catch {
failed += 1;
}
}
return { closed, busy, failed };
}
function readBoundedNativeFile(
path: string,
maxBytes: number,
@@ -1453,6 +1498,7 @@ function runnerdAuthorityLifecycleWithVerifiedBackup(input: {
type PriorRunnerdStateVerification =
| "verified"
| "retained_warm_runner"
| "active"
| "authority_indeterminate"
| "scope_mismatch"
@@ -1465,6 +1511,7 @@ async function verifyPriorRunnerdStateForSessionScope(input: {
identity: RunnerdDurableIdentity;
execution: NativeExecutionInput;
allowVerifiedBackup: boolean;
allowRetainedWarmRunner: boolean;
}): Promise<PriorRunnerdStateVerification> {
let priorRun: {
status: string;
@@ -1505,9 +1552,24 @@ async function verifyPriorRunnerdStateForSessionScope(input: {
nativeSessionScopeKey(input.execution);
if (!sameScope) return "scope_mismatch";
const lifecycle = runnerdAuthorityLifecycleWithVerifiedBackup(input);
return lifecycle === "suspended"
? "verified"
: "terminal_state_indeterminate";
if (lifecycle === "suspended") return "verified";
const directLifecycle = runnerdAuthorityLifecycle(
input.root,
input.identity,
);
if (
input.allowRetainedWarmRunner &&
(lifecycle === "not_suspended" ||
// A remote runner keeps runner-state.json in the sandbox rather than
// beside the controller's PRP journal. During a genuinely warm handoff
// there is intentionally no suspended failover backup yet. The exact
// idle in-memory session owner is the authority for this one case;
// after a restart that owner is absent and this remains fail-closed.
(input.allowVerifiedBackup && directLifecycle === "absent"))
) {
return "retained_warm_runner";
}
return "terminal_state_indeterminate";
} catch {
return "authority_indeterminate";
}
@@ -1517,6 +1579,7 @@ async function migrateRunnerdStateRootForExecution(input: {
db: Db;
execution: NativeExecutionInput;
allowVerifiedBackup: boolean;
allowRetainedWarmRunner: boolean;
restartRecovery?: NativeRestartRecoveryClaim;
}): Promise<void> {
const scoped = scopedRunnerdStateRoot(input.execution);
@@ -1568,8 +1631,12 @@ async function migrateRunnerdStateRootForExecution(input: {
identity,
execution: input.execution,
allowVerifiedBackup: input.allowVerifiedBackup,
allowRetainedWarmRunner: input.allowRetainedWarmRunner,
});
if (verification !== "verified") {
if (
verification !== "verified" &&
verification !== "retained_warm_runner"
) {
if (verification !== "active" && verification !== "unavailable") {
quarantineRunnerdStateRoot(
scoped,
@@ -1606,8 +1673,12 @@ async function migrateRunnerdStateRootForExecution(input: {
identity,
execution: input.execution,
allowVerifiedBackup: input.allowVerifiedBackup,
allowRetainedWarmRunner: input.allowRetainedWarmRunner,
});
if (verification !== "verified") {
if (
verification !== "verified" &&
verification !== "retained_warm_runner"
) {
if (verification === "terminal_state_indeterminate") {
// The database proves this ambiguous legacy path belongs to the same
// full session scope and its owner is terminal, so it is now safe to
@@ -1802,6 +1873,24 @@ function nativeSessionConfigDigest(execution: NativeExecutionInput): string {
.digest("hex")}`;
}
function hasIdleWarmNativeSessionOwner(input: {
execution: NativeExecutionInput;
runnerExecutionTarget?: AdapterExecutionTarget | null;
}): boolean {
if (input.execution.session.lifecyclePolicy.mode !== "warm") return false;
const entry = warmNativeSessions.get(nativeSessionScopeKey(input.execution));
if (!entry || entry.busy) return false;
const environmentId =
input.runnerExecutionTarget?.kind === "remote"
? (input.runnerExecutionTarget.environmentId ?? null)
: null;
return (
entry.companyId === input.execution.binding.companyId &&
entry.environmentId === environmentId &&
entry.configDigest === nativeSessionConfigDigest(input.execution)
);
}
function nativeHarnessEnvironmentFingerprint(
execution: NativeExecutionInput,
): string {
@@ -2447,11 +2536,14 @@ function loadWarmNativeCheckpoint(
async function releaseWarmNativeSession(
sessionId: string,
ownerToken: symbol,
idleTimeoutMs: number,
failed: boolean,
): Promise<void> {
const entry = warmNativeSessions.get(sessionId);
if (!entry) return;
// A late completion or cleanup callback from an older execution must never
// release a replacement that has since claimed the same logical session.
if (!entry || entry.ownerToken !== ownerToken) return;
entry.busy = false;
entry.lastActivityAt = new Date().toISOString();
if (entry.idleTimer !== null) clearTimeout(entry.idleTimer);
@@ -2464,9 +2556,13 @@ async function releaseWarmNativeSession(
}
entry.idleTimer = setTimeout(() => {
const current = warmNativeSessions.get(sessionId);
if (!current || current.busy) return;
// clearTimeout cannot revoke an already-queued callback. The entry object
// is the idle timer's ownership fence across a later warm acquisition.
if (current !== entry || current.busy) return;
warmNativeSessions.delete(sessionId);
void current.session.close({ reason: "warm native session idle timeout" });
void current.session
.close({ reason: "warm native session idle timeout" })
.catch(() => undefined);
}, idleTimeoutMs);
entry.idleTimer.unref();
}
@@ -2626,7 +2722,9 @@ export async function nativeProviderRecoveryEvidence(input: {
.where(
and(
eq(heartbeatRunEvents.runId, input.runId),
inArray(heartbeatRunEvents.eventType, [...PROVIDER_DURABLE_EVENT_TYPES]),
inArray(heartbeatRunEvents.eventType, [
...PROVIDER_DURABLE_EVENT_TYPES,
]),
),
)
.limit(1);
@@ -3661,6 +3759,11 @@ async function executePaperclipNativeSessionWithinScope(
allowVerifiedBackup:
input.runnerExecutionTarget?.kind === "remote" &&
input.runnerExecutionTarget.transport === "sandbox",
// A retained warm runner is deliberately still ready rather than
// suspended. Only the exact idle in-process owner may rotate that
// prior-run authority; after a hard restart the map is empty and the
// durable-state verifier continues to require a suspended runner.
allowRetainedWarmRunner: hasIdleWarmNativeSessionOwner(input),
restartRecovery: input.restartRecovery,
});
}
@@ -4156,6 +4259,9 @@ async function executePaperclipNativeSessionWithinScope(
lifecyclePolicy.mode === "warm"
? nativeSessionConfigDigest(input.execution)
: null;
const warmSessionOwnerToken = Symbol(
`native-warm-session:${input.execution.binding.runId}`,
);
let existingWarmSession: NativeSession | undefined;
let persistedWarmSession: PersistedNativeSession | null | undefined;
if (warmSessionId !== null && warmConfigDigest !== null) {
@@ -4175,6 +4281,9 @@ async function executePaperclipNativeSessionWithinScope(
} else {
if (entry.busy) throw new Error("native_session_supervisor_busy");
entry.busy = true;
entry.ownerToken = warmSessionOwnerToken;
entry.environmentId =
input.runnerExecutionTarget?.environmentId ?? null;
if (entry.idleTimer !== null) clearTimeout(entry.idleTimer);
entry.idleTimer = null;
existingWarmSession = entry.session;
@@ -4311,6 +4420,10 @@ async function executePaperclipNativeSessionWithinScope(
existingSession: existingWarmSession,
persistedSession: persistedWarmSession,
keepSessionOpen: warmSessionId !== null,
semanticResultTerminalGraceMs:
warmSessionId === null
? undefined
: NATIVE_WARM_SEMANTIC_RESULT_TERMINAL_GRACE_MS,
requireSessionCloseBeforeReturn:
runnerdBackend !== null &&
input.runnerExecutionTarget?.kind === "remote",
@@ -4323,6 +4436,21 @@ async function executePaperclipNativeSessionWithinScope(
snapshot,
)
: undefined,
onPostCompletionEnrichmentFailure: async ({ stage, error }) => {
const detail = redactSensitiveText(
error instanceof Error ? error.message : String(error),
).slice(-4_096);
await input.onLog?.(
"stderr",
`[paperclip-runner] post-completion ${stage} enrichment failed: ${detail}\n`,
);
},
onSessionQuarantined: async (reason) => {
await input.onLog?.(
"stderr",
`[paperclip-runner] warm native session quarantined: ${redactSensitiveText(reason).slice(-1_000)}\n`,
);
},
onContinuityBreak: async (continuity) => {
const atMs = Date.now();
await trace.record({
@@ -4354,15 +4482,34 @@ async function executePaperclipNativeSessionWithinScope(
warmConfigDigest !== null
) {
const existing = warmNativeSessions.get(warmSessionId);
if (existing) existing.session = session;
else
if (existing) {
if (existing.ownerToken !== warmSessionOwnerToken) {
throw new Error("native_session_supervisor_busy");
}
existing.session = session;
} else
warmNativeSessions.set(warmSessionId, {
session,
ownerToken: warmSessionOwnerToken,
configDigest: warmConfigDigest,
companyId: input.execution.binding.companyId,
environmentId:
input.runnerExecutionTarget?.environmentId ?? null,
busy: true,
idleTimer: null,
lastActivityAt: new Date().toISOString(),
});
} else if (!session && warmSessionId !== null) {
const existing = warmNativeSessions.get(warmSessionId);
// onSession(null) quarantines a transport that can no longer
// be reused. Remove only this execution's generation so a
// late failure cannot evict a successor session.
if (existing?.ownerToken === warmSessionOwnerToken) {
if (existing.idleTimer !== null) {
clearTimeout(existing.idleTimer);
}
warmNativeSessions.delete(warmSessionId);
}
}
if (session)
activeNativeSessions.set(input.execution.binding.runId, {
@@ -4398,6 +4545,13 @@ async function executePaperclipNativeSessionWithinScope(
} catch (error) {
await leaseRenewal.stop().catch(() => undefined);
const failedAtMs = Date.now();
const executionFailureMessage = redactSensitiveText(
error instanceof Error ? error.message : String(error),
).slice(-4_096);
await input.onLog?.(
"stderr",
`[paperclip-runner] native session execution failed: ${executionFailureMessage}\n`,
);
if (runnerSessionStartupScope) {
await trace.end(runnerSessionStartupScope, {
endedAtMs: failedAtMs,
@@ -4422,6 +4576,7 @@ async function executePaperclipNativeSessionWithinScope(
if (warmSessionId !== null && lifecyclePolicy.mode === "warm") {
await releaseWarmNativeSession(
warmSessionId,
warmSessionOwnerToken,
lifecyclePolicy.idleTimeoutMs,
true,
);
@@ -4711,6 +4866,7 @@ async function executePaperclipNativeSessionWithinScope(
if (warmSessionId !== null && lifecyclePolicy.mode === "warm") {
await releaseWarmNativeSession(
warmSessionId,
warmSessionOwnerToken,
lifecyclePolicy.idleTimeoutMs,
false,
);
@@ -5546,10 +5702,102 @@ async function readRemoteRunnerProviderState(input: {
);
}
function createRemoteRunnerProcessLauncher(input: {
const REMOTE_RUNNER_PROCESS_IDENTITY_WAIT_MS = 20_000;
const REMOTE_RUNNER_PROCESS_POLL_MS = 1_000;
const REMOTE_RUNNER_IDENTITY_CHECK_SCRIPT =
'set -eu; identity_path=$1; expected_nonce=$2; expected_runner_id=$3; expected_pid=$4; test -f "$identity_path" && test ! -L "$identity_path" || exit 3; { IFS= read -r nonce; IFS= read -r pid; IFS= read -r started_at; IFS= read -r runner_id; } < "$identity_path"; test "$nonce" = "$expected_nonce" && test "$runner_id" = "$expected_runner_id" && test "$pid" = "$expected_pid" && test -n "$started_at" || exit 4; kill -0 "$pid" 2>/dev/null || exit 3; if test -r "/proc/$pid/cmdline"; then command_line=$(tr "\\000" "\\n" < "/proc/$pid/cmdline"); printf "%s\\n" "$command_line" | grep -Fqx -- "--runner-id" || exit 4; printf "%s\\n" "$command_line" | grep -Fqx -- "$expected_runner_id" || exit 4; fi';
const REMOTE_RUNNER_CHILD_LAUNCH_SCRIPT =
'set -eu; identity_path=$1; identity_nonce=$2; runner_instance_id=$3; diagnostics_directory=$4; shift 4; umask 077; test ! -L "$diagnostics_directory"; if test -e "$diagnostics_directory"; then test -d "$diagnostics_directory"; else mkdir -p -- "$diagnostics_directory"; fi; chmod 0700 "$diagnostics_directory"; started_at=$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ"); identity_tmp="${identity_path}.tmp.$$"; printf "%s\\n%s\\n%s\\n%s\\n" "$identity_nonce" "$$" "$started_at" "$runner_instance_id" > "$identity_tmp"; chmod 0600 "$identity_tmp"; mv -f -- "$identity_tmp" "$identity_path"; exec "$@"';
const REMOTE_RUNNER_FAILED_IDENTITY_CLEANUP_SCRIPT =
'set -eu; identity_path=$1; expected_nonce=$2; expected_runner_id=$3; marker_wait=0; while { test ! -f "$identity_path" || test -L "$identity_path"; } && test "$marker_wait" -lt 50; do marker_wait=$((marker_wait + 1)); sleep 0.1; done; test -f "$identity_path" && test ! -L "$identity_path" || exit 3; { IFS= read -r nonce; IFS= read -r pid; IFS= read -r started_at; IFS= read -r runner_id; } < "$identity_path"; test "$nonce" = "$expected_nonce" && test "$runner_id" = "$expected_runner_id" && test -n "$started_at" || exit 4; case "$pid" in ""|*[!0-9]*) exit 4 ;; esac; test "$pid" -gt 0 || exit 4; if kill -0 "$pid" 2>/dev/null; then if test -r "/proc/$pid/cmdline"; then command_line=$(tr "\\000" "\\n" < "/proc/$pid/cmdline"); printf "%s\\n" "$command_line" | grep -Fqx -- "--runner-id" || exit 4; printf "%s\\n" "$command_line" | grep -Fqx -- "$expected_runner_id" || exit 4; fi; signal_target=$pid; if command -v ps >/dev/null 2>&1; then session_id=$(ps -o sid= -p "$pid" 2>/dev/null | tr -d " ") || true; if test "$session_id" = "$pid"; then signal_target="-$pid"; fi; fi; kill -TERM -- "$signal_target" 2>/dev/null || kill -TERM "$pid" 2>/dev/null || true; term_wait=0; while kill -0 "$pid" 2>/dev/null && test "$term_wait" -lt 50; do term_wait=$((term_wait + 1)); sleep 0.1; done; if kill -0 "$pid" 2>/dev/null; then kill -KILL -- "$signal_target" 2>/dev/null || kill -KILL "$pid" 2>/dev/null || true; kill_wait=0; while kill -0 "$pid" 2>/dev/null && test "$kill_wait" -lt 50; do kill_wait=$((kill_wait + 1)); sleep 0.1; done; fi; kill -0 "$pid" 2>/dev/null && exit 5; fi; test -f "$identity_path" && test ! -L "$identity_path" || exit 4; { IFS= read -r final_nonce; IFS= read -r final_pid; IFS= read -r final_started_at; IFS= read -r final_runner_id; } < "$identity_path"; test "$final_nonce" = "$nonce" && test "$final_pid" = "$pid" && test "$final_started_at" = "$started_at" && test "$final_runner_id" = "$runner_id" || exit 4; rm -f -- "$identity_path"';
export function parseRemoteRunnerProcessIdentity(
value: string,
expected: { nonce: string; runnerInstanceId: string },
): { pid: number; startedAt: string } | null {
const [nonce, rawPid, startedAt, runnerInstanceId, ...remainder] = value
.trim()
.split("\n");
const pid = Number(rawPid);
if (
remainder.length > 0 ||
nonce !== expected.nonce ||
runnerInstanceId !== expected.runnerInstanceId ||
!Number.isSafeInteger(pid) ||
pid <= 0 ||
!startedAt ||
Number.isNaN(new Date(startedAt).getTime())
) {
return null;
}
return { pid, startedAt };
}
async function waitForRemoteRunnerProcessIdentity(input: {
runner: CommandManagedRuntimeRunner;
identityPath: string;
nonce: string;
runnerInstanceId: string;
}): Promise<{ pid: number; startedAt: string }> {
const deadline = Date.now() + REMOTE_RUNNER_PROCESS_IDENTITY_WAIT_MS;
while (Date.now() < deadline) {
const result = await input.runner
.execute({
command: "sh",
args: [
"-c",
'test -f "$1" && test ! -L "$1" && cat -- "$1"',
"paperclip-runner-process-identity",
input.identityPath,
],
bypassSession: true,
timeoutMs: 2_000,
})
.catch(() => null);
const identity =
result && result.exitCode === 0 && !result.timedOut
? parseRemoteRunnerProcessIdentity(result.stdout, input)
: null;
if (identity) return identity;
await new Promise<void>((resolve) => setTimeout(resolve, 100));
}
throw new Error("runner_remote_process_identity_unavailable");
}
async function cleanupRemoteRunnerAfterIdentityFailure(input: {
runner: CommandManagedRuntimeRunner;
identityPath: string;
nonce: string;
runnerInstanceId: string;
}): Promise<boolean> {
const result = await input.runner
.execute({
command: "sh",
args: [
"-c",
REMOTE_RUNNER_FAILED_IDENTITY_CLEANUP_SCRIPT,
"paperclip-runner-identity-failure-cleanup",
input.identityPath,
input.nonce,
input.runnerInstanceId,
],
bypassSession: true,
timeoutMs: 20_000,
})
.catch(() => null);
return result?.exitCode === 0 && result.timedOut === false;
}
export function createRemoteRunnerProcessLauncher(input: {
target: Extract<AdapterExecutionTarget, { kind: "remote" }>;
runner: CommandManagedRuntimeRunner;
remoteBinary: string;
processIdentityPath: string;
stateDirectory: string;
diagnosticsDirectory: string;
runnerInstanceId: string;
ensureArtifact?: () => Promise<void>;
onSpawn?: (meta: {
@@ -5563,15 +5811,39 @@ function createRemoteRunnerProcessLauncher(input: {
}): (spec: RunnerProcessLaunchSpec) => RunnerProcessHandle {
const runner = input.runner;
return (spec) => {
let launchedIdentity: {
nonce: string;
pid: number;
startedAt: string;
} | null = null;
const child: RunnerProcessHandle["child"] = {
pid: undefined,
exitCode: null,
signalCode: null,
kill: () => {
const pattern = `--runner-id ${input.runnerInstanceId}`;
kill: (requestedSignal) => {
const identity = launchedIdentity;
if (!identity) return false;
const signal =
requestedSignal === "SIGKILL" || requestedSignal === 9
? "KILL"
: requestedSignal === "SIGINT" || requestedSignal === 2
? "INT"
: "TERM";
// The durable marker, nonce, exact pid, and runner-id command line are
// revalidated in the sandbox immediately before signalling. A recycled
// pid or replaced marker therefore fails closed instead of killing an
// unrelated process.
void runner.execute({
command: "pkill",
args: ["-f", pattern],
command: "sh",
args: [
"-c",
`${REMOTE_RUNNER_IDENTITY_CHECK_SCRIPT}; kill -${signal} "$expected_pid"`,
"paperclip-runner-signal",
input.processIdentityPath,
identity.nonce,
input.runnerInstanceId,
String(identity.pid),
],
bypassSession: true,
timeoutMs: 10_000,
});
@@ -5604,36 +5876,164 @@ function createRemoteRunnerProcessLauncher(input: {
endedAtMs: Date.now(),
attributes: { target: "remote" },
});
const result = await runner.execute({
command: input.remoteBinary,
args: [...spec.args],
const identityNonce = randomUUID();
const remoteArgs = [...spec.args];
const diagnosticsArgumentIndex = remoteArgs.indexOf(
"--diagnostics-directory",
);
if (diagnosticsArgumentIndex >= 0) {
remoteArgs[diagnosticsArgumentIndex + 1] = input.diagnosticsDirectory;
} else {
remoteArgs.push("--diagnostics-directory", input.diagnosticsDirectory);
}
// Do not keep runnerd as the foreground command of a provider RPC. Some
// sandbox command/session transports impose a provider-side lifetime on
// that RPC even when Paperclip requests a longer timeout. Detach runnerd
// into its own session instead; its own bounded diagnostics directory and
// durable PRP state remain the authorities, and the controller monitors
// the exact persisted process identity below.
const launchResult = await runner.execute({
command: "sh",
args: [
"-c",
'set -eu; identity_path=$1; identity_nonce=$2; runner_instance_id=$3; child_script=$4; shift 4; umask 077; identity_dir=$(dirname -- "$identity_path"); mkdir -p -- "$identity_dir"; if command -v setsid >/dev/null 2>&1; then nohup setsid sh -c "$child_script" paperclip-runner-child "$identity_path" "$identity_nonce" "$runner_instance_id" "$@" </dev/null >/dev/null 2>&1 & else nohup sh -c "$child_script" paperclip-runner-child "$identity_path" "$identity_nonce" "$runner_instance_id" "$@" </dev/null >/dev/null 2>&1 & fi',
"paperclip-runner-launch",
input.processIdentityPath,
identityNonce,
input.runnerInstanceId,
REMOTE_RUNNER_CHILD_LAUNCH_SCRIPT,
input.diagnosticsDirectory,
input.remoteBinary,
...remoteArgs,
],
cwd: input.target.remoteCwd,
env: processEnvironment(spec.environment),
timeoutMs: 62 * 60_000,
useSession: true,
timeoutMs: 20_000,
bypassSession: true,
onLog: input.onLog,
onSpawn: async (meta) => {
child.pid = meta.pid;
await input.onSpawn?.({
pid: meta.pid,
processGroupId: null,
startedAt: new Date().toISOString(),
});
await input.trace?.record({
name: "runner.process.launch",
parentName: "runner.session.startup",
startedAtMs: launchStartedAtMs,
endedAtMs: Date.now(),
});
},
});
child.exitCode = result.exitCode;
return {
code: result.exitCode,
signal: null,
stdout: result.stdout,
stderr: result.stderr,
};
if (launchResult.exitCode !== 0 || launchResult.timedOut) {
throw new Error(
launchResult.timedOut
? "runner_remote_process_launch_timed_out"
: "runner_remote_process_launch_failed",
);
}
let identity: { pid: number; startedAt: string };
try {
identity = await waitForRemoteRunnerProcessIdentity({
runner,
identityPath: input.processIdentityPath,
nonce: identityNonce,
runnerInstanceId: input.runnerInstanceId,
});
} catch {
const cleanupStartedAtMs = Date.now();
const cleaned = await cleanupRemoteRunnerAfterIdentityFailure({
runner,
identityPath: input.processIdentityPath,
nonce: identityNonce,
runnerInstanceId: input.runnerInstanceId,
});
await input.trace?.record({
name: "runner.process.identity_failure_cleanup",
parentName: "runner.session.startup",
startedAtMs: cleanupStartedAtMs,
endedAtMs: Date.now(),
attributes: { cleaned },
});
if (!cleaned) {
throw new Error(
"runner_remote_process_identity_unavailable_cleanup_failed",
);
}
throw new Error("runner_remote_process_identity_unavailable");
}
launchedIdentity = { nonce: identityNonce, ...identity };
child.pid = identity.pid;
await input.onSpawn?.({
pid: identity.pid,
processGroupId: null,
startedAt: identity.startedAt,
});
await input.trace?.record({
name: "runner.process.launch",
parentName: "runner.session.startup",
startedAtMs: launchStartedAtMs,
endedAtMs: Date.now(),
attributes: { identitySource: "remote_marker", detached: true },
});
while (true) {
const observed = await runner.execute({
command: "sh",
args: [
"-c",
REMOTE_RUNNER_IDENTITY_CHECK_SCRIPT,
"paperclip-runner-monitor",
input.processIdentityPath,
identityNonce,
input.runnerInstanceId,
String(identity.pid),
],
bypassSession: true,
timeoutMs: 10_000,
});
if (observed.exitCode === 0 && !observed.timedOut) {
await new Promise<void>((resolve) =>
setTimeout(resolve, REMOTE_RUNNER_PROCESS_POLL_MS),
);
continue;
}
child.exitCode = null;
const identityMismatch = observed.exitCode === 4;
const diagnostic = await runner
.execute({
command: "sh",
args: [
"-c",
'set -eu; directory=$1; file="$directory/runnerd.stderr.log"; test -d "$directory" && test ! -L "$directory" && test -f "$file" && test ! -L "$file"; tail -c 65536 -- "$file"',
"paperclip-runner-diagnostics",
input.diagnosticsDirectory,
],
bypassSession: true,
timeoutMs: 10_000,
})
.catch(() => null);
const diagnosticTail =
diagnostic && diagnostic.exitCode === 0 && !diagnostic.timedOut
? redactSensitiveText(diagnostic.stdout).slice(-16_384).trim()
: "";
const durableState = await readRemoteRunnerState({
runner,
stateDirectory: input.stateDirectory,
}).catch(() => null);
const lifecycle =
typeof durableState?.lifecycle === "string"
? durableState.lifecycle
: "unavailable";
const recoverableFailure =
typeof durableState?.recoverableFailure === "string"
? durableState.recoverableFailure
: typeof durableState?.recoverable_failure === "string"
? durableState.recoverable_failure
: null;
const stateDiagnostics = Array.isArray(durableState?.diagnostics)
? durableState.diagnostics
.filter((value): value is string => typeof value === "string")
.slice(-4)
.map((value) => redactSensitiveText(value).slice(-1_000))
: [];
const stateSummary = `runner_remote_process_exited lifecycle=${lifecycle}${recoverableFailure ? ` recoverableFailure=${redactSensitiveText(recoverableFailure).slice(-1_000)}` : ""}${stateDiagnostics.length > 0 ? ` diagnostics=${JSON.stringify(stateDiagnostics)}` : ""}`;
return {
code: null,
signal: null,
stdout: "",
stderr: identityMismatch
? "runner_remote_process_identity_mismatch"
: diagnosticTail || stateSummary,
};
}
})();
return { child, completion };
};
@@ -5721,14 +6121,25 @@ export async function createRunnerdBackend(input: {
}
initializingSessionToolAuthorities.add(sessionScopeId);
try {
await migrateRunnerdStateRootForExecution({
db: input.db,
execution: input.execution,
allowVerifiedBackup:
input.runnerExecutionTarget?.kind === "remote" &&
input.runnerExecutionTarget.transport === "sandbox",
restartRecovery: input.restartRecovery,
});
// executePaperclipNativeSession holds the full session-scope claim and
// verifies/migrates the durable root before it acquires the coordinator
// lease. Avoid reclassifying the same root after that path has marked its
// retained warm owner busy for this run. Direct backend construction still
// performs the complete fail-closed verification here.
if (
executingRunnerdSessionScopes.get(sessionScopeId) !==
input.execution.binding.runId
) {
await migrateRunnerdStateRootForExecution({
db: input.db,
execution: input.execution,
allowVerifiedBackup:
input.runnerExecutionTarget?.kind === "remote" &&
input.runnerExecutionTarget.transport === "sandbox",
allowRetainedWarmRunner: false,
restartRecovery: input.restartRecovery,
});
}
return await createRunnerdBackendWithinSessionClaim(input, sessionScopeId);
} finally {
initializingSessionToolAuthorities.delete(sessionScopeId);
@@ -7154,11 +7565,17 @@ async function createRunnerdBackendWithinSessionClaim(
: undefined;
const remoteProcessLauncher =
remoteTarget && remoteCommandRunner && remoteBinary
remoteTarget && remoteCommandRunner && remoteBinary && remoteStateDirectory
? createRemoteRunnerProcessLauncher({
target: remoteTarget,
runner: remoteCommandRunner,
remoteBinary,
processIdentityPath: posix.join(
remoteStateDirectory,
"runner-process.identity",
),
stateDirectory: remoteStateDirectory,
diagnosticsDirectory: posix.join(remoteSessionRoot!, "diagnostics"),
runnerInstanceId: input.runnerInstanceId,
ensureArtifact: ensureRemoteRunner,
onSpawn: input.onSpawn,
@@ -7186,8 +7603,12 @@ async function createRunnerdBackendWithinSessionClaim(
const effectiveRunnerEnvironment: NodeJS.ProcessEnv = remoteRuntimeRoot
? {
...effectiveRunnerEnvironmentBase,
HOME: remoteTarget!.remoteCwd,
CODEX_HOME: posix.join(remoteTarget!.remoteCwd, ".codex"),
// The provider home is runner-owned state, not the execution workspace.
// Codex's permission profile explicitly denies HOME and CODEX_HOME. If
// either points at remoteCwd, that deny rule shadows the workspace write
// grant and the provider cannot initialize its shell sandbox or edit.
HOME: posix.join(remoteRunnerFilesystemRoot!, "codex-home"),
CODEX_HOME: posix.join(remoteRunnerFilesystemRoot!, "codex-home"),
PAPERCLIP_WORKSPACE_CWD: remoteTarget!.remoteCwd,
...(remoteTarget!.transport === "sandbox"
? { PAPERCLIP_RUNNER_EXTERNAL_SANDBOX: "1" }
@@ -7389,6 +7810,12 @@ async function createRunnerdBackendWithinSessionClaim(
}
: undefined,
environment: effectiveRunnerEnvironment,
onDiagnostic: (message) => {
void input.onLog?.(
"stderr",
`[paperclip-runner] runnerd diagnostic: ${redactSensitiveText(message).slice(-4_096)}\n`,
);
},
lifecyclePolicy: input.execution.session.lifecyclePolicy,
runtimeContext:
"runtimeContext" in input.execution
@@ -7396,6 +7823,7 @@ async function createRunnerdBackendWithinSessionClaim(
: null,
runnerRuntimeContext: remoteRuntimeContext,
runnerFilesystemRoot: remoteRunnerFilesystemRoot ?? undefined,
externallySandboxed: remoteTarget?.transport === "sandbox",
opencodeRuntimeDirectory: remoteRunnerFilesystemRoot
? posix.join(remoteRunnerFilesystemRoot, "opencode")
: undefined,
@@ -7621,6 +8049,13 @@ async function createRunnerdBackendWithinSessionClaim(
},
{ parentName: "runner.session.startup" },
);
// Cancellation can release the sandbox while activation is
// still waiting for the remote runner process. Attach a
// rejection observer immediately; `ready()` still awaits the
// original promise and reports the same startup failure, but
// an early teardown can no longer crash the controller with
// an unhandled plugin RPC rejection.
void activation.catch(() => undefined);
},
ready: async () => {
await measureNativeRunnerSpan(
@@ -90,6 +90,7 @@ export type NativeWorkspaceInboundEvidence =
| {
kind: "existing_run";
restartRecovery: boolean;
sameRunRecovery?: boolean;
sameProviderLease: boolean;
}
| {
@@ -102,7 +103,7 @@ export function classifyNativeWorkspaceInbound(
evidence: NativeWorkspaceInboundEvidence,
): WorkspaceInboundMode {
if (evidence.kind === "existing_run") {
if (!evidence.restartRecovery) {
if (!evidence.restartRecovery && !evidence.sameRunRecovery) {
throw new Error("native_workspace_sync_unexpected_existing_descriptor");
}
return evidence.sameProviderLease ? "adopt_remote" : "durable_seed";
@@ -734,6 +735,7 @@ export async function prepareNativeWorkspaceSync(input: {
target: AdapterExecutionTarget | null;
lease: EnvironmentLease;
restartRecovery?: NativeRestartRecoveryClaim;
sameRunRecovery?: boolean;
resourceDisposition?: NativeWorkspaceResourceDisposition;
}): Promise<PreparedNativeWorkspaceSync | null> {
if (input.target?.kind !== "remote" || input.target.transport !== "sandbox") {
@@ -777,6 +779,7 @@ export async function prepareNativeWorkspaceSync(input: {
mode = classifyNativeWorkspaceInbound({
kind: "existing_run",
restartRecovery: Boolean(input.restartRecovery),
sameRunRecovery: input.sameRunRecovery,
sameProviderLease,
});
const durableSeed =
@@ -328,7 +328,11 @@ function metadataMatchesPluginSandboxConfig(
if (metadata.reuseLease !== true) return false;
for (const [key, value] of Object.entries(config)) {
if (key === "provider" || key === "reuseLease") continue;
if (value === undefined) continue;
// Null is the normalized form of an unspecified optional provider setting.
// The provider may report the concrete default it realized (for example,
// Daytona resolves a null target to "us"), which remains compatible with
// the caller's lack of a preference.
if (value === undefined || value === null) continue;
if (JSON.stringify(metadata[key]) !== JSON.stringify(value)) {
return false;
}