feat(runner): add remote execution substrate (#12638)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Paperclip Runner gives native runs a durable and governed execution
path.
> - The current native path runs on the control-plane host.
> - Remote environments need an authenticated execution-target contract.
> - The contract must not change direct adapters or enable new runtimes
by default.
> - This pull request adds the remote execution substrate and Daytona
ingress.
> - The benefit is a bounded base for later remote runner transport
work.

## Linked Issues or Issue Description

Refs #12616.
Refs #12352.

**Subsystem affected**

Cross-cutting. This change touches runner transport, server
orchestration, plugin contracts, and shared settings.

**Problem or motivation**

Native execution cannot resolve an authenticated runner ingress through
a remote environment. The server also lacks one provider-neutral
contract for remote execution targets.

**Proposed solution**

Add a default-off runner preview ingress capability. Add
transport-neutral runner connectivity. Add remote execution target and
lifecycle handling. Add a Daytona ingress implementation with redacted
credentials.

**Alternatives considered**

A provider-specific server path would duplicate orchestration and
authorization. A public endpoint without an environment contract would
weaken the trust boundary.

**Roadmap alignment**

This work supports the Cloud and Sandbox agents milestone. It also
supports self-healing runs and governed tool access.

## What Changed

- Added execution-target traits for local, SSH, and sandbox
environments.
- Added plugin RPC contracts for runner ingress endpoints.
- Added authenticated Daytona preview ingress.
- Added transport-neutral PRP outbound connections.
- Added remote runner artifact verification and fail-closed provider
selection.
- Added bounded native session resume, cancellation, and lifecycle
recovery.
- Preserved Codex-only selection for fresh experimental runner starts.
- Preserved all direct adapter execution and finalization paths.
- Removed stale Pi provider-pack requirements that security review
rejected.
- Kept the rollout controls off by default.
- Did not change pnpm-lock.yaml, Cargo, database migrations, or GitHub
workflows.

## Verification

- GitHub Actions will run the repository test, typecheck, build,
security, and policy gates.
- Focused tests cover ingress validation, redaction, execution targets,
remote lifecycle, cancellation, resume, and legacy adapter selection.
- Local tests were not run. The requested verification policy uses
GitHub Actions for this series.
- `git diff --check origin/master...HEAD` passes.
- The diff contains 52 files.

## Risks

- Remote execution crosses a trust boundary.
- The implementation validates target capabilities, artifact digests,
provider-pack pins, and connection metadata.
- The feature remains default-off.
- Fresh native selection remains Codex-only.
- Existing direct adapters remain on the legacy path.
- This PR does not yet make remote Codex runnable. The next PR adds the
Rust WSS and TLS transport.

## Model Used

OpenAI Codex with GPT-5.6. The work used high-reasoning agent mode,
repository tools, GitHub tools, and parallel code-audit agents.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with Fixes: / Closes /
Refs OR (b) described the issue in-PR following the relevant issue
template
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My branch name describes the change and contains no internal
Paperclip ticket id
- [ ] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-09-01 01:29:06 -05:00
1 parent 209680409d
commit 0a422fda52
52 files changed
+6920 -223

No files matched your search

@@ -11,7 +11,9 @@ const PLUGIN_ID = "paperclip.daytona-sandbox-provider";
// neutral `supportsLoginPty`.
// 0.1.4 adds the `concurrentSyncOperations` sandbox capability to the driver.
// 0.1.5 adds the `duplexCommandStream` sandbox capability to the driver.
const PLUGIN_VERSION = "0.1.5";
// 0.1.6 adds private authenticated WebSocket ingress for paperclip_runner.
// 0.1.7 exposes host-owned warm/cold runner lifecycle controls.
const PLUGIN_VERSION = "0.1.7";
const manifest: PaperclipPluginManifestV1 = {
id: PLUGIN_ID,
@@ -58,6 +60,7 @@ const manifest: PaperclipPluginManifestV1 = {
incrementalSessionOutput: true,
concurrentSyncOperations: true,
duplexCommandStream: true,
runnerWebSocketIngress: true,
},
supportsInteractiveSetup: true,
interactiveSetupConnectionTypes: ["ssh"],
@@ -169,6 +172,21 @@ const manifest: PaperclipPluginManifestV1 = {
"Whether to stop and later resume the sandbox across runs instead of deleting it on release.",
default: false,
},
runnerLifecycleMode: {
type: "string",
enum: ["inherit", "per_turn", "warm"],
description:
"paperclip_runner lifecycle for this environment. Inherit uses the agent setting; warm keeps runnerd and the sandbox available between turns.",
default: "inherit",
},
runnerIdleTimeoutMs: {
type: "integer",
description:
"How long an idle warm paperclip_runner stays alive before it checkpoints and suspends.",
minimum: 1000,
maximum: 86400000,
default: 300000,
},
},
},
},
@@ -46,6 +46,7 @@ function createMockSandbox(overrides: {
recoverable?: boolean;
workDir?: string;
autoDestroyAt?: string | null;
updatedAt?: string;
} = {}) {
return {
id: overrides.id ?? "sandbox-123",
@@ -57,6 +58,7 @@ function createMockSandbox(overrides: {
// A configured provider TTL populates `autoDestroyAt` after `setTtl` +
// `refreshData`. The default mock leaves it unset (no TTL configured).
autoDestroyAt: overrides.autoDestroyAt ?? undefined,
updatedAt: overrides.updatedAt,
getWorkDir: vi.fn().mockResolvedValue(overrides.workDir ?? "/home/daytona"),
getUserHomeDir: vi.fn().mockResolvedValue("/home/daytona"),
start: vi.fn().mockResolvedValue(undefined),
@@ -75,6 +77,10 @@ function createMockSandbox(overrides: {
token: "ssh-token-secret",
command: "ssh ssh-token-secret@ssh.app.daytona.io",
}),
getPreviewLink: vi.fn().mockResolvedValue({
url: "https://43127-sandbox-123.proxy.daytona.test",
token: "preview-token-secret",
}),
_experimental_createSnapshot: vi.fn().mockResolvedValue(undefined),
fs: {
createFolder: vi.fn().mockResolvedValue(undefined),
@@ -161,11 +167,90 @@ describe("Daytona sandbox provider plugin", () => {
expect(plugin.definition.onDuplexChannelClose).toBeTypeOf("function");
});
it("declares and returns private authenticated runner WebSocket ingress", async () => {
process.env.DAYTONA_API_KEY = "host-key";
const sandbox = createMockSandbox();
mockCreate.mockResolvedValue(sandbox);
const base = {
driverKey: "daytona",
companyId: "company-1",
environmentId: "env-1",
config: { image: "node:20", timeoutMs: 300_000, reuseLease: false },
};
const lease = await plugin.definition.onEnvironmentAcquireLease?.({
...base,
runId: "00000000-0000-4000-8000-000000000001",
});
const endpoint = await plugin.definition.onEnvironmentRunnerIngressEndpoint?.({
...base,
lease: lease!,
port: 43_127,
path: "/api/runner/v1/connect/00000000-0000-4000-8000-000000000001",
});
expect(manifest.environmentDrivers?.[0]?.sandboxCapabilities).toMatchObject({
runnerWebSocketIngress: true,
});
expect(endpoint).toMatchObject({
kind: "authenticated_websocket",
websocketUrl:
"wss://43127-sandbox-123.proxy.daytona.test/api/runner/v1/connect/00000000-0000-4000-8000-000000000001",
secretHeaders: [
{ name: "X-Daytona-Preview-Token", value: "preview-token-secret" },
],
});
expect(endpoint?.websocketUrl).not.toContain("preview-token-secret");
expect(endpoint?.websocketUrl).not.toContain("host-key");
});
it("keeps ingress generation independent of token rotation and changes it after a sandbox lifecycle revision", async () => {
process.env.DAYTONA_API_KEY = "host-key";
const sandbox = createMockSandbox({ updatedAt: "2026-08-25T10:00:00.000Z" });
sandbox.getPreviewLink
.mockResolvedValueOnce({
url: "https://43127-sandbox-123.proxy.daytona.test",
token: "preview-token-1",
})
.mockResolvedValueOnce({
url: "https://43127-sandbox-123.proxy.daytona.test",
token: "preview-token-2",
})
.mockResolvedValueOnce({
url: "https://43127-sandbox-123.proxy.daytona.test",
token: "preview-token-3",
});
mockCreate.mockResolvedValue(sandbox);
const base = {
driverKey: "daytona",
companyId: "company-1",
environmentId: "env-1",
config: { image: "node:20", timeoutMs: 300_000, reuseLease: false },
};
const lease = await plugin.definition.onEnvironmentAcquireLease?.({
...base,
runId: "00000000-0000-4000-8000-000000000001",
});
const request = {
...base,
lease: lease!,
port: 43_127,
path: "/api/runner/v1/connect/00000000-0000-4000-8000-000000000001",
};
const first = await plugin.definition.onEnvironmentRunnerIngressEndpoint?.(request);
const second = await plugin.definition.onEnvironmentRunnerIngressEndpoint?.(request);
expect(second?.generation).toBe(first?.generation);
expect(second?.secretHeaders).not.toEqual(first?.secretHeaders);
sandbox.updatedAt = "2026-08-25T10:05:00.000Z";
const restarted = await plugin.definition.onEnvironmentRunnerIngressEndpoint?.(request);
expect(restarted?.generation).not.toBe(first?.generation);
});
it("bumps the plugin version so the server reconciles the stored manifest", () => {
// The bundled-plugin boot reconcile refreshes the stored manifest for an
// existing install only when the version changes. The duplex capability needs
// the bump to reach an existing install.
expect(manifest.version).toBe("0.1.5");
expect(manifest.version).toBe("0.1.7");
});
it("opens a duplex channel, forwards a host write, and closes it on lease release", async () => {
@@ -1074,7 +1159,7 @@ describe("Daytona sandbox provider plugin", () => {
});
});
it("deletes the sandbox if resume setup throws after the sandbox starts", async () => {
it("preserves the sandbox if resume setup throws after the sandbox starts", async () => {
process.env.DAYTONA_API_KEY = "host-key";
const sandbox = createMockSandbox({ id: "sandbox-resume", state: "stopped" });
sandbox.getWorkDir.mockRejectedValue(new Error("workdir lookup failed"));
@@ -1094,7 +1179,7 @@ describe("Daytona sandbox provider plugin", () => {
).rejects.toThrow("workdir lookup failed");
expect(sandbox.start).toHaveBeenCalled();
expect(sandbox.delete).toHaveBeenCalledTimes(1);
expect(sandbox.delete).not.toHaveBeenCalled();
});
it("marks missing reusable leases as expired on resume", async () => {
@@ -23,6 +23,8 @@ import type {
PluginEnvironmentDestroyLeaseParams,
PluginEnvironmentExecuteParams,
PluginEnvironmentExecuteResult,
PluginEnvironmentRunnerIngressEndpointParams,
PluginEnvironmentRunnerIngressEndpoint,
PluginEnvironmentGetInteractiveSetupParams,
PluginEnvironmentInteractiveSetupSession,
PluginEnvironmentLease,
@@ -1304,6 +1306,34 @@ const sandboxHandleCache = (() => {
return { get, seed, clear, reset, markFresh, findByProviderLeaseId };
})();
// Preview credentials can rotate without a sandbox restart, so they must not
// define endpoint generation. Daytona's lifecycle revision does: refreshData
// updates `updatedAt` after stop/start. When Daytona does not expose a
// lifecycle revision, the in-memory generation remains stable for the worker.
const runnerIngressGenerationStore = (() => {
const entries = new Map<
string,
{ revision: string | null; generation: string }
>();
function get(sandbox: Sandbox): string {
const revision = sandbox.updatedAt ?? sandbox.createdAt ?? null;
const current = entries.get(sandbox.id);
if (current && current.revision === revision) return current.generation;
const generation = createHash("sha256")
.update(`${sandbox.id}\0${revision ?? randomUUID()}`)
.digest("hex");
entries.set(sandbox.id, { revision, generation });
return generation;
}
function reset(): void {
entries.clear();
}
return { get, reset };
})();
// Advisory writable-set store. It holds, per lease scope, the sandbox
// directories that a sync operation declared read-write (`access: "rw"`). The
// store is advisory and best-effort in-memory state: it adds no security (the
@@ -1422,6 +1452,7 @@ export function __resetDaytonaSandboxHandleCacheForTest(): void {
sandboxHandleLeaseAdmissionStates.reset();
sandboxHandleWritableDirs.reset();
sandboxHandleSessionStore.reset();
runnerIngressGenerationStore.reset();
}
/**
@@ -2204,7 +2235,10 @@ const plugin = definePlugin({
};
} catch (error) {
evictSandboxHandle(scope);
await sandbox.delete(toTimeoutSeconds(config.timeoutMs)).catch(() => undefined);
// A timeout, rate limit, or provider 5xx does not prove this sandbox is
// lost. Preserve the exact resource and let the host retry its recorded
// lease; replacement is permitted only after an explicit not-found or
// an immutable workspace identity mismatch.
throw error;
}
}, { allowClosed: true });
@@ -2632,7 +2666,6 @@ const plugin = definePlugin({
},
});
const getDurationMs = timingNow() - getStart;
await ensureSandboxStarted(sandbox, toTimeoutSeconds(resolveTimeoutMs(params.timeoutMs, config)));
const scope: SandboxScope = {
driverKey: params.driverKey,
companyId: params.companyId,
@@ -2640,6 +2673,13 @@ const plugin = definePlugin({
providerLeaseId,
config,
};
if (sandbox.state !== "started") {
// A provider restart destroys Daytona process sessions. Drop the stale
// session id before starting the sandbox so runnerd recovery opens a
// new session instead of retrying a dead one for its whole grace.
sandboxHandleSessionStore.clear(scope);
}
await ensureSandboxStarted(sandbox, toTimeoutSeconds(resolveTimeoutMs(params.timeoutMs, config)));
// Dispatch the command. A normal command runs in the persistent session:
// the provider opens the one session on a cache miss and runs every command
// in it. The provider never falls back to a one-shot command to open a
@@ -2668,6 +2708,70 @@ const plugin = definePlugin({
});
},
async onEnvironmentRunnerIngressEndpoint(
params: PluginEnvironmentRunnerIngressEndpointParams,
): Promise<PluginEnvironmentRunnerIngressEndpoint> {
if (params.port !== 43_127) {
throw new Error("Daytona runner ingress must use fixed port 43127.");
}
if (!/^\/api\/runner\/v1\/connect\/[^/?#]+$/.test(params.path)) {
throw new Error("Daytona runner ingress path is invalid.");
}
const providerLeaseId = params.lease.providerLeaseId;
if (!providerLeaseId) {
throw new Error("Daytona runner ingress requires a provider lease id.");
}
const config = parseDriverConfig(params.config);
return await withSandboxActivityGate(
{
driverKey: params.driverKey,
companyId: params.companyId,
environmentId: params.environmentId,
providerLeaseId,
config,
},
async () => {
const sandbox = await getSandbox({
driverKey: params.driverKey,
companyId: params.companyId,
environmentId: params.environmentId,
providerLeaseId,
config,
});
await ensureSandboxStarted(sandbox, toTimeoutSeconds(config.timeoutMs));
await withLivenessTimeout(
"sandbox.refreshData",
config.livenessTimeoutMs,
() => sandbox.refreshData(),
);
const preview = await sandbox.getPreviewLink(params.port);
if (typeof preview.url !== "string" || typeof preview.token !== "string") {
throw new Error("Daytona returned an incomplete private preview endpoint.");
}
const url = new URL(preview.url);
if (
url.protocol !== "https:" ||
url.username ||
url.password ||
url.search ||
url.hash
) {
throw new Error("Daytona returned an invalid private preview URL.");
}
url.protocol = "wss:";
url.pathname = `${url.pathname.replace(/\/$/, "")}${params.path}`;
return {
kind: "authenticated_websocket",
websocketUrl: url.toString(),
secretHeaders: [
{ name: "X-Daytona-Preview-Token", value: preview.token },
],
generation: runnerIngressGenerationStore.get(sandbox),
};
},
);
},
// Opt-in native inbound transfer. Defining this hook (with onEnvironmentSyncOut)
// makes the worker advertise `environmentSyncIn`/`environmentSyncOut`, so the
// host runner routes Daytona workspace/asset transfers through the SDK's batch
@@ -2915,6 +3019,7 @@ const plugin = definePlugin({
await entry.session.close().catch(() => undefined);
}
sandboxHandleCache.reset();
runnerIngressGenerationStore.reset();
},
});
@@ -55,6 +55,8 @@ import type {
PluginEnvironmentDestroyLeaseParams,
PluginEnvironmentExecuteParams,
PluginEnvironmentExecuteResult,
PluginEnvironmentRunnerIngressEndpointParams,
PluginEnvironmentRunnerIngressEndpoint,
PluginEnvironmentSyncInParams,
PluginEnvironmentSyncOutParams,
PluginEnvironmentSyncResult,
@@ -399,6 +401,11 @@ export interface PluginDefinition {
params: PluginEnvironmentExecuteParams,
): Promise<PluginEnvironmentExecuteResult>;
/** Return an authenticated private WebSocket ingress for runnerd. */
onEnvironmentRunnerIngressEndpoint?(
params: PluginEnvironmentRunnerIngressEndpointParams,
): Promise<PluginEnvironmentRunnerIngressEndpoint>;
/**
* Optional, opt-in: called before execution to place host files/directories at
* target sandbox paths using a provider-native transport instead of the default
+2
View File
@@ -188,6 +188,8 @@ export type {
PluginEnvironmentRealizeWorkspaceResult,
PluginEnvironmentExecuteParams,
PluginEnvironmentExecuteResult,
PluginEnvironmentRunnerIngressEndpointParams,
PluginEnvironmentRunnerIngressEndpoint,
PluginSyncFileMapping,
PluginPostUploadCommand,
PluginSyncOperation,
+20
View File
@@ -614,6 +614,21 @@ export interface PluginEnvironmentLease {
expiresAt?: string | null;
}
/** Serializable provider result. The host adds refresh/close lifecycle methods. */
export interface PluginEnvironmentRunnerIngressEndpoint {
kind: "authenticated_websocket";
websocketUrl: string;
secretHeaders: Array<{ name: string; value: string }>;
generation: string;
}
export interface PluginEnvironmentRunnerIngressEndpointParams
extends PluginEnvironmentDriverBaseParams {
lease: PluginEnvironmentLease;
port: number;
path: string;
}
export interface PluginEnvironmentAcquireLeaseParams extends PluginEnvironmentDriverBaseParams {
runId: string;
workspaceMode?: string;
@@ -1350,6 +1365,10 @@ export interface HostToWorkerMethods {
params: PluginEnvironmentExecuteParams,
result: PluginEnvironmentExecuteResult,
];
environmentRunnerIngressEndpoint: [
params: PluginEnvironmentRunnerIngressEndpointParams,
result: PluginEnvironmentRunnerIngressEndpoint,
];
environmentSyncIn: [
params: PluginEnvironmentSyncInParams,
result: PluginEnvironmentSyncResult,
@@ -1440,6 +1459,7 @@ export const HOST_TO_WORKER_OPTIONAL_METHODS: readonly HostToWorkerMethodName[]
"environmentDestroyLease",
"environmentRealizeWorkspace",
"environmentExecute",
"environmentRunnerIngressEndpoint",
"environmentSyncIn",
"environmentSyncOut",
"environmentStartInteractiveSetup",
@@ -88,6 +88,7 @@ import type {
PluginEnvironmentAcquireLeaseParams,
PluginEnvironmentDestroyLeaseParams,
PluginEnvironmentExecuteParams,
PluginEnvironmentRunnerIngressEndpointParams,
PluginEnvironmentSyncInParams,
PluginEnvironmentSyncOutParams,
PluginEnvironmentRealizeWorkspaceParams,
@@ -1640,6 +1641,11 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
case "environmentExecute":
return handleEnvironmentExecute(params as PluginEnvironmentExecuteParams);
case "environmentRunnerIngressEndpoint":
return handleEnvironmentRunnerIngressEndpoint(
params as PluginEnvironmentRunnerIngressEndpointParams,
);
case "environmentSyncIn":
return handleEnvironmentSyncIn(params as PluginEnvironmentSyncInParams);
@@ -1729,6 +1735,9 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
if (plugin.definition.onEnvironmentDestroyLease) supportedMethods.push("environmentDestroyLease");
if (plugin.definition.onEnvironmentRealizeWorkspace) supportedMethods.push("environmentRealizeWorkspace");
if (plugin.definition.onEnvironmentExecute) supportedMethods.push("environmentExecute");
if (plugin.definition.onEnvironmentRunnerIngressEndpoint) {
supportedMethods.push("environmentRunnerIngressEndpoint");
}
if (plugin.definition.onEnvironmentSyncIn) supportedMethods.push("environmentSyncIn");
if (plugin.definition.onEnvironmentSyncOut) supportedMethods.push("environmentSyncOut");
if (plugin.definition.onEnvironmentStartInteractiveSetup) supportedMethods.push("environmentStartInteractiveSetup");
@@ -2043,6 +2052,15 @@ export function startWorkerRpcHost(options: WorkerRpcHostOptions): WorkerRpcHost
return plugin.definition.onEnvironmentExecute(params);
}
async function handleEnvironmentRunnerIngressEndpoint(
params: PluginEnvironmentRunnerIngressEndpointParams,
) {
if (!plugin.definition.onEnvironmentRunnerIngressEndpoint) {
throw methodNotImplemented("environmentRunnerIngressEndpoint");
}
return plugin.definition.onEnvironmentRunnerIngressEndpoint(params);
}
async function handleEnvironmentSyncIn(params: PluginEnvironmentSyncInParams) {
if (!plugin.definition.onEnvironmentSyncIn) {
throw methodNotImplemented("environmentSyncIn");