Skip to content

The open-source app everyone uses to manage agents at work

Connect native Runner admission to plugin-owned workspaces (#16978)

Nicky Leach00331e0254ed
diff --git a/doc/plugins/PLUGIN_AUTHORING_GUIDE.md b/doc/plugins/PLUGIN_AUTHORING_GUIDE.md
index e6913a203d..94ca672bd0 100644
--- a/doc/plugins/PLUGIN_AUTHORING_GUIDE.md
+++ b/doc/plugins/PLUGIN_AUTHORING_GUIDE.md
@@ -798,3 +798,14 @@ A plugin can declare `supportsTasks` on an environment driver and implement
`onEnvironmentTask`. See the [task API](PLUGIN_ENVIRONMENT_TASKS.md) for the
operations, validation, and lease rules. This hook does not add a shell or file
transfer API. Native agent execution is a separate integration.
+
+## Plugin-provided Runner execution
+
+Plugins can [provide Runner execution through environment drivers](PLUGIN_RUNNER_EXECUTION.md).
+Core can select this path for `paperclip_runner` agents assigned to a saved plugin
+environment. The plugin owns project volumes and starts Runner from structured
+task launch inputs. Core connects PRP and verifies cancellation and durable cleanup.
+Resource transfer and credential synchronization use a separate workflow.
+Persistent computers keep their agent home and session files between runs. No remote shell, file-command,
+or workspace hook is required. The guide defines the task operations, lease
+hooks, artifact qualification, and supported per-turn lifecycle.
diff --git a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md
index 505e2f579c..6a4affe8a9 100644
--- a/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md
+++ b/doc/plugins/PLUGIN_ENVIRONMENT_TASKS.md
@@ -3,8 +3,8 @@
An environment driver can provide a Runner task through a worker hook.
The task API has no shell command or file transfer operation.
-This API is a server and worker contract. The agent environment test can verify
-a task-capable provider. Native heartbeat dispatch is a separate integration.
+This API is a server and worker contract. The [native execution integration](PLUGIN_RUNNER_EXECUTION.md)
+connects a task-capable environment to a Runner run.
## Declare the hook
diff --git a/doc/plugins/PLUGIN_RUNNER_EXECUTION.md b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md
new file mode 100644
index 0000000000..12a68da5a0
--- /dev/null
+++ b/doc/plugins/PLUGIN_RUNNER_EXECUTION.md
@@ -0,0 +1,139 @@
+# Plugin Runner execution
+
+Core can run `paperclip_runner` tasks in a plugin environment.
+The plugin owns the execution host and its files.
+Core owns run identity, selected policy, assigned tools, and the PRP journal.
+
+## Required hooks
+
+Set `supportsTasks: true` on the environment driver.
+Declare the `environment.drivers.register` capability.
+Implement these hooks:
+
+- `onEnvironmentAcquireLease`
+- `onEnvironmentTask`
+- `onEnvironmentReleaseLease`
+- `onEnvironmentDestroyLease`
+
+Task execution does not require `onEnvironmentExecute` or
+`onEnvironmentRealizeWorkspace`. The task API has no shell or file transfer
+operation. Use a separate workflow to install and save agent files.
+
+Core supports per-turn workspace sessions with Codex, OpenCode, and ACPX.
+OpenCode and ACPX require the existing qualified provider profiles.
+Workspace-free providers and warm process retention are not supported here.
+The plugin owns project workspace preparation. Core does not prepare or reuse
+a Core Git worktree for a task-only environment.
+For plugin-backed project storage, Core uses the workspace provider contract.
+The storage plugin must also provide the selected execution environment.
+Its declared workspace modes and strategies remain in effect.
+Core passes the pinned workspace binding with each task operation.
+Core rejects configured workspace services for task-only environments.
+Fresh retries that import retained files are not supported for plugin storage.
+An agent-owned workspace cannot move to another agent or environment.
+Core also rejects reuse of a local workspace in a task-only environment.
+Keep its original owner, or use the workspace storage provider contract.
+
+## Prepare and launch
+
+1. Return an opaque task ID from lease acquisition as `providerLeaseId`.
+2. Return the installed Runner version and SHA-256 digest from `describe`.
+3. Return `launchPreparationVersion: 1` from `describe`.
+4. Handle `prepare` with the [launch preparation contract](../runner-launch-preparation.md).
+5. Save the result under its configuration ID.
+6. Handle `submit` with that ID in `preparedLaunchId`.
+7. Return an authenticated WSS endpoint from `connection`.
+
+Preparation must not start a process. It must preserve Core's provider, model,
+policy, instructions, and resource assignment identities. Resolve assigned
+resources to execution-host paths. Use `bindRunnerLaunchResources` and
+`createRunnerProviderLaunch` when the built-in descriptor builder is suitable.
+
+Core checks the returned requirements digest and descriptor before it registers
+PRP or submits the task. A failed check does not enable a fallback launch.
+Recovery within the same run must return the exact saved configuration.
+
+The plugin supplies executable paths and the provider workspace in the
+descriptor. It owns the process environment and account installation.
+For example, a persistent computer can use these locations:
+
+```text
+HOME=/home/agent
+AGENT_HOME=/home/agent/.agents
+CODEX_HOME=/home/agent/.codex
+instructions=/home/agent/.agents/AGENTS.md
+skills=/home/agent/.agents/skills/<name>/SKILL.md
+```
+
+These are execution-host locations. Core does not copy the home for each run.
+The plugin must declare `projectAuthCheckVersion: 1` for all native tasks.
+Core requires `check_project_auth` to allow the exact prepared configuration
+before it sends credentials. The plugin must reject conflicting project or
+parent authentication settings. It must keep the checked configuration fixed
+until submission. See [managed account validation](PLUGIN_ENVIRONMENT_TASKS.md#managed-account-validation).
+
+Core sends authorized project IDs, the PRP identity, launch limits, and the
+bootstrap ticket through `submit`. It does not send a process command.
+The plugin must submit each task at most once. A lost reply requires status
+reconciliation for the same task.
+
+## Credentials and tools
+
+Core can transfer a selected Codex account or a direct Claude credential.
+Other managed routes fail closed until they have a typed credential contract.
+Do not put credentials in task metadata, journals, logs, or errors.
+
+Assigned MCP tools run through the Core gateway over PRP.
+The gateway credentials stay on Core.
+The plugin must preserve the MCP binding identity in the prepared context.
+
+Core records credential writeback authority before dispatch.
+After process termination, Core saves refreshed credentials before it completes
+the task. A failed save retains the task grants for cleanup.
+
+## Stop and recovery
+
+A terminal phase does not prove process termination.
+Return `executionStopped: true` only after the task and its descendants stop.
+Return `sessionStateAvailable: true` only when the suspended state remains usable.
+Keep retained state when Core completes the task.
+Core checks managed plugin workspaces through their storage provider before
+completion, including after a restart. Core does not inspect these folders locally.
+If this check fails, Core defers the run and continues recovery for other runs.
+Core keeps known branch and owner error codes with the repair instructions.
+
+The task contract exposes two checkpoint operations:
+
+- `read_state` returns the exact Runner durable state for the supplied identity.
+- `archive_state` moves a suspended Runner authority checkpoint under the supplied
+ archive key. It returns the same state on retry. It keeps provider session files.
+
+These operations do not accept paths. Core checks the active lease and retained
+source task before it calls the plugin. The existing Runner transport validates
+state identity and suspension before it rotates authority.
+
+Core checks company, agent, environment, workspace, driver, and termination
+receipts before it supplies `resumeFrom`. For same-run controller recovery, Core
+first stops and releases the old task. A failed stop prevents replacement.
+A new run prepares its current assignments. Provider compatibility checks remain
+in the existing backends. Missing or incompatible retained state fails closed.
+
+## Setup verification
+
+Core creates a private probe lease with an expiry.
+It runs the same describe, prepare, submit, and WSS/PRP path.
+The probe checks provider authentication and the selected model with tools denied.
+Core bounds Runner lifetime to the remaining probe time.
+It then requires suspension, confirmed termination, and task cleanup.
+For a new agent-owned computer, the saved-agent lifecycle runs verification
+after it saves the agent. Core does not require a computer before this save.
+
+## Verification
+
+- [Lease and SDK RPC integration](../../server/src/__tests__/plugin-runner-task.integration.test.ts)
+- [Real Runner setup and recovery](../../server/src/services/native-runtime/plugin-runner-probe.test.ts)
+- [Task ownership and cancellation](../../server/src/services/native-runtime/plugin-runner-task.test.ts)
+- [Credential transfer](../../server/src/services/native-runtime/plugin-runner-credentials.test.ts)
+
+The Runner fixture uses a synthetic Codex provider and local sockets.
+It does not qualify a deployed plugin, live account, or production WSS proxy.
diff --git a/doc/runner-launch-preparation.md b/doc/runner-launch-preparation.md
index 4495d364bc..653edb25e4 100644
--- a/doc/runner-launch-preparation.md
+++ b/doc/runner-launch-preparation.md
@@ -48,6 +48,6 @@ unsettled checkpoint and prevents reuse.
## Plugin task protocol
The [environment task API](plugins/PLUGIN_ENVIRONMENT_TASKS.md#launch-preparation)
-defines the plugin preparation exchange. This callback does not implement a
-plugin task process owner or a Launcher endpoint. Those integrations are
-separate changes.
+defines the plugin preparation exchange. The [native plugin integration](plugins/PLUGIN_RUNNER_EXECUTION.md)
+connects the callback to task execution. A Launcher implementation remains the
+execution owner's responsibility.
diff --git a/maps/agent-access-map/execution-environments.md b/maps/agent-access-map/execution-environments.md
index 69bd94a2d6..210291cf46 100644
--- a/maps/agent-access-map/execution-environments.md
+++ b/maps/agent-access-map/execution-environments.md
@@ -165,6 +165,17 @@ remaining operations before qualifying the whole capability.
Gaps: Choosing among permitted targets differs from creating/configuring host targets;
test authorized and denied selection.
+Scoped plugin execution update: `paperclip_runner` supports a saved plugin
+environment through the server-selected lease and the SDK `environmentTask` RPC.
+This is an execution path, not a new agent-callable management endpoint. Host
+company/project checks and native PRP authorization remain required; declaring a
+plugin capability does not authorize the agent to change its environment.
+The [integration fixture](../../server/src/__tests__/plugin-runner-task.integration.test.ts)
+exercises the host and SDK with synthetic tasks and a mocked WebSocket.
+The task API does not transfer files or reveal guest filesystem paths.
+This source update does not qualify live agent access, warm retention, or a provider.
+See the [execution contract](../../doc/plugins/PLUGIN_RUNNER_EXECUTION.md).
+
## `images`
Capability ID: `execution-environments/images`.
@@ -189,3 +200,16 @@ own policy and access review.
Gaps: No default agent custom-image administration/terminal path; this is a policy
decision before adding a tool.
+
+The task-only setup path uses a Core-issued expiring probe identity and a real,
+read-only Runner hello. The plugin checks project authentication before provider startup.
+[Setup probe coverage](../../server/src/services/native-runtime/plugin-runner-probe.test.ts)
+uses the real Runner and a synthetic Codex provider through loopback PRP; TLS
+termination is replaced by the fixture. It does not qualify a live plugin provider.
+
+The plugin prepares execution-host resources and the provider descriptor. Core validates the result, then supplies task identity and PRP launch limits.
+
+Managed account transfer requires `projectAuthCheckVersion: 1` and a successful
+`check_project_auth` result for the exact prepared configuration, provider, and
+project set. New preparation removes old validation. Core checks the saved
+validation again in the dispatch update.
diff --git a/maps/feature-map/execution-environments.md b/maps/feature-map/execution-environments.md
index 61d0022cbe..cbe6739bf3 100644
--- a/maps/feature-map/execution-environments.md
+++ b/maps/feature-map/execution-environments.md
@@ -80,6 +80,17 @@ execution. Remote-driver probes and a real bounded run need their own evidence.
### `remote-execution`
+For `paperclip_runner`, a saved plugin environment can provide per-turn Runner
+execution when its manifest and worker expose the Runner task API. The task
+contract starts a provider-owned Runner without shell or workspace hooks. Core
+resolves the saved lease, connects through PRP, and verifies stop before lease
+cleanup. The provider owns the installed agent home and retained session files;
+data transfer is outside task execution. See the
+[plugin contract](../../doc/plugins/PLUGIN_RUNNER_EXECUTION.md).
+The [fake-provider integration](../../server/src/__tests__/plugin-runner-task.integration.test.ts)
+checks acquisition, SDK dispatch, scope denial, stop proof and deletion recovery.
+Its WebSocket is mocked; it does not qualify a live provider or a real Runner handshake.
+
Automated: [execution target](../../server/src/__tests__/environment-execution-target.test.ts) and [custom images](../../server/src/__tests__/environment-custom-images-service.test.ts) cover contracts; [SSH live test](../../server/src/__tests__/environment-live-ssh.test.ts) requires its own external setup.
The [environment runtime regression](../../server/src/__tests__/environment-runtime.test.ts)
@@ -98,6 +109,14 @@ Manual: Run a bounded command in the intended target, inspect its output and wor
- The local option may appear only when editing an existing local environment; availability follows current UI/provider capabilities.
- Workspace service reachability and environment reachability are separate checks.
+The task-only setup path uses a Core-issued expiring probe identity and a real,
+read-only Runner hello. The plugin checks project authentication before provider startup.
+[Setup probe coverage](../../server/src/services/native-runtime/plugin-runner-probe.test.ts)
+uses the real Runner and a synthetic Codex provider through loopback PRP; TLS
+termination is replaced by the fixture. It does not qualify a live plugin provider.
+
+The plugin prepares execution-host resources and the provider descriptor. Core validates the result, then supplies task identity and PRP launch limits.
+
### Storybook verification
#### `configuration`
@@ -135,3 +154,8 @@ Scope: ui
Storybook: Custom-image setup/capture/progress, terminal connect/disconnect/failure, unsupported capability and active-image drift.
Production: Execute owned provider setup/capture/probe/terminal transport with correct saved image identity, authority, cleanup and shutdown; terminal screenshot cannot prove operation.
Sources: Source: [CompanyEnvironments.tsx](../../ui/src/pages/CompanyEnvironments.tsx), [environment-custom-images.ts](../../server/src/services/environment-custom-images.ts). Tests: [CompanyEnvironments.test.tsx](../../ui/src/pages/CompanyEnvironments.test.tsx), [environment-custom-images-service.test.ts](../../server/src/__tests__/environment-custom-images-service.test.ts)
+
+Managed account transfer requires `projectAuthCheckVersion: 1` and a successful
+`check_project_auth` result for the exact prepared configuration, provider, and
+project set. New preparation removes old validation. Core checks the saved
+validation again in the dispatch update.
diff --git a/packages/plugins/sdk/src/types.ts b/packages/plugins/sdk/src/types.ts
index a81b7b56d9..7fd9ce0cbb 100644
--- a/packages/plugins/sdk/src/types.ts
+++ b/packages/plugins/sdk/src/types.ts
@@ -1720,6 +1720,8 @@ export interface PluginAgentRuntimeState {
agent: Agent;
instructionsRootPath: string | null;
instructionsEntryFile: string;
+ /** Default entry content when the agent has no instruction directory. */
+ instructionsEntryContent?: string;
instanceSecrets: Record<string, string>;
}
diff --git a/packages/shared/src/environment-support.test.ts b/packages/shared/src/environment-support.test.ts
index 0b462267ba..f0bc2520cd 100644
--- a/packages/shared/src/environment-support.test.ts
+++ b/packages/shared/src/environment-support.test.ts
@@ -13,6 +13,7 @@ describe("isSandboxProviderSupportedForAdapter", () => {
"local",
"ssh",
"sandbox",
+ "plugin",
]);
});
diff --git a/packages/shared/src/environment-support.ts b/packages/shared/src/environment-support.ts
index ab10a20e17..3a61f86a51 100644
--- a/packages/shared/src/environment-support.ts
+++ b/packages/shared/src/environment-support.ts
@@ -81,6 +81,7 @@ export function adapterSupportsRemoteManagedEnvironments(adapterType: string): b
}
export function supportedEnvironmentDriversForAdapter(adapterType: string): EnvironmentDriver[] {
+ if (adapterType === "paperclip_runner") return ["local", "ssh", "sandbox", "plugin"];
return adapterSupportsRemoteManagedEnvironments(adapterType)
? ["local", "ssh", "sandbox"]
: ["local"];
@@ -194,7 +195,7 @@ export function getEnvironmentCapabilities(
local: "supported",
ssh: "supported",
sandbox: "supported",
- plugin: "unsupported",
+ plugin: adapterTypes.includes("paperclip_runner") ? "supported" : "unsupported",
},
sandboxProviders,
};
diff --git a/server/src/__tests__/agent-runtime-hooks.test.ts b/server/src/__tests__/agent-runtime-hooks.test.ts
index 10a93c5ae6..69fb20f5df 100644
--- a/server/src/__tests__/agent-runtime-hooks.test.ts
+++ b/server/src/__tests__/agent-runtime-hooks.test.ts
@@ -155,6 +155,13 @@ describeDatabase("agent runtime synchronization hooks", () => {
expect(await fs.readFile(path.join(state!.instructionsRootPath!, state!.instructionsEntryFile), "utf8")).toBe("restored instructions");
});
+ it("supplies default instructions when the agent has no instruction directory", async () => {
+ await db.update(agents).set({ adapterConfig: { promptTemplate: "Fallback task instructions" } }).where(eq(agents.id, agentId));
+ expect(await pluginAgentRuntimeState(db, pluginId, companyId, agentId)).toMatchObject({
+ instructionsRootPath: null, instructionsEntryFile: "AGENTS.md", instructionsEntryContent: "Fallback task instructions",
+ });
+ });
+
it("resolves instructions without reading or hashing bundle contents", async () => {
const [agent] = await db.select().from(agents).where(eq(agents.id, agentId));
const root = resolveManagedInstructionsRoot(agent);
diff --git a/server/src/__tests__/ai-connections.test.ts b/server/src/__tests__/ai-connections.test.ts
index 69550ec9f3..183052c510 100644
--- a/server/src/__tests__/ai-connections.test.ts
+++ b/server/src/__tests__/ai-connections.test.ts
@@ -15,7 +15,7 @@ import { mkdtemp, realpath, rm, access, readFile, writeFile, stat } from "node:f
import os from "node:os";
import path from "node:path";
import { and, eq, sql } from "drizzle-orm";
-import { createDb, companies, agents, agentTaskSessions, heartbeatRuns, companyMemberships, connectionGrants, toolApplications, connectionGrantDelegations, connectionGrantMembers, toolConnections, toolConnectionInstalls, aiConnectionDefaults, aiProviderDefaults, adapterAuthSessions, environments, issues, issueThreadInteractions, issueRecoveryActions, connectionIntentDeliveries, agentWakeupRequests, companySecrets, companySecretVersions, userSecretDefinitions, principalPermissionGrants } from "@paperclipai/db";
+import { createDb, companies, agents, agentTaskSessions, heartbeatRuns, companyMemberships, connectionGrants, toolApplications, connectionGrantDelegations, connectionGrantMembers, toolConnections, toolConnectionInstalls, aiConnectionDefaults, aiProviderDefaults, adapterAuthSessions, environments, plugins, issues, issueThreadInteractions, issueRecoveryActions, connectionIntentDeliveries, agentWakeupRequests, companySecrets, companySecretVersions, userSecretDefinitions, principalPermissionGrants } from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "@paperclipai/db/test-embedded-postgres";
import { fetchCompanyQuotaWindows } from "../services/quota-windows.js";
import { quotaCredentialRecoveryPath, quotaCredentialRecovery, quotaCredentialHash } from "../services/quota-credential-recovery.js";
@@ -72,6 +72,36 @@ beforeAll(async () => {
afterAll(async () => { await database?.cleanup(); vi.unstubAllEnvs(); if (home) await rm(home, { recursive: true, force: true }); });
describe("managed AI connections", () => {
+ it("defers a new plugin agent's Copilot check until its saved-agent lifecycle can acquire the computer", async () => {
+ const { errorHandler } = await import("../middleware/index.js");
+ const owner = "copilot-plugin-bootstrap", pluginId = randomUUID();
+ const pluginKey = `test.bootstrap.${pluginId}`;
+ await db.insert(companyMemberships).values({ companyId, principalId: owner, principalType: "user", status: "active", membershipRole: "member" });
+ await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "@test/bootstrap", version: "1.0.0", apiVersion: 1,
+ categories: ["automation"], status: "ready", manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0",
+ displayName: "Bootstrap", description: "Bootstrap fixture", author: "Test", categories: ["automation"],
+ capabilities: ["environment.drivers.register"], entrypoints: { worker: "worker.js" },
+ environmentDrivers: [{ driverKey: "tasks", displayName: "Tasks", supportsTasks: true, configSchema: { type: "object" } }] } });
+ const [environment] = await db.insert(environments).values({ companyId, name: "Agent computer", driver: "plugin",
+ config: { pluginKey, driverKey: "tasks", driverConfig: {} } }).returning();
+ const token = "github_pat_fixture_plugin_bootstrap";
+ const account = await service.save(companyId, owner, { provider: "github", method: "api_key", ownership: "personal", name: "Bootstrap", apiKey: token, agentIds: [], allAgents: false }, token);
+ await service.setDefault(companyId, owner, account.grantId);
+ const probe = vi.spyOn(copilotProbe, "probeCopilotExecutionTarget").mockRejectedValue(new Error("No computer exists before the agent is saved"));
+ const app = express(); app.use(express.json());
+ app.use((req, _res, next) => { req.actor = { type: "board", source: "local_implicit", userId: owner, companyIds: [companyId], isInstanceAdmin: true }; next(); });
+ app.use("/api", agentRoutes(db)); app.use(errorHandler);
+ try {
+ const response = await request(app).post(`/api/companies/${companyId}/agents`).send({ name: "Plugin bootstrap", role: "general",
+ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "copilot", model: "gpt-5.6-luna" },
+ defaultEnvironmentId: environment.id, runtimeConfig: { aiConnection: { provider: "github", method: "api_key", mode: "responsible_user" } } });
+ expect(response.status, JSON.stringify(response.body)).toBe(201);
+ expect(response.body.defaultEnvironmentId).toBe(environment.id);
+ expect(response.body.lifecycleState).toBe("preparing");
+ expect(probe).not.toHaveBeenCalled();
+ } finally { probe.mockRestore(); }
+ });
+
it.each(["create", "hire", "edit"])("refuses Copilot %s before probing or persisting when forced Kubernetes is missing", async action => {
const { errorHandler } = await import("../middleware/index.js");
const owner = `copilot-kubernetes-${action}`, id = randomUUID();
diff --git a/server/src/__tests__/environment-run-orchestrator.test.ts b/server/src/__tests__/environment-run-orchestrator.test.ts
index 4807b47d65..92c241f397 100644
--- a/server/src/__tests__/environment-run-orchestrator.test.ts
+++ b/server/src/__tests__/environment-run-orchestrator.test.ts
@@ -391,6 +391,21 @@ describe("environmentRunOrchestrator — realizeForRun", () => {
expect(result.executionTarget).toBeNull();
});
+ it("forwards authorized project IDs to task-only providers without staging directories", async () => {
+ const environment = makeEnvironment("plugin" as Environment["driver"]);
+ mockResolveEnvironmentExecutionTarget.mockResolvedValue({ kind: "remote", transport: "sandbox",
+ providerKey: "plugin", remoteCwd: "provider/project", runnerTask: vi.fn() });
+ const runtime = makeMockRuntime({ supportsTasks: vi.fn().mockResolvedValue(true) });
+ const orchestrator = environmentRunOrchestrator(mockDb, { environmentRuntime: runtime });
+ const input = { ...makeRealizeInput({ environment }), adapterType: "paperclip_runner",
+ runnerTaskProjectIds: ["anchor", "authorized-reference", "anchor"] };
+ input.executionWorkspace.projectId = "anchor";
+ const result = await orchestrator.realizeForRun(input);
+ expect(result.executionTarget).toMatchObject({ runnerTaskProjectIds: ["anchor", "authorized-reference"] });
+ expect(runtime.realizeWorkspace).not.toHaveBeenCalled();
+ expect(runtime.execute).not.toHaveBeenCalled();
+ });
+
it("persisted metadata is updated on lease and execution workspace after realization", async () => {
const persistedExecutionWorkspace = makePersistedExecutionWorkspace();
const updatedLease = makeLease({
diff --git a/server/src/__tests__/heartbeat-plugin-environment.test.ts b/server/src/__tests__/heartbeat-plugin-environment.test.ts
index 3965b0ef72..99c5abfa58 100644
--- a/server/src/__tests__/heartbeat-plugin-environment.test.ts
+++ b/server/src/__tests__/heartbeat-plugin-environment.test.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { mkdtemp, rm } from "node:fs/promises";
+import { mkdtemp, rm, stat } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
@@ -93,6 +93,59 @@ describeEmbeddedPostgres("heartbeat plugin environments", () => {
await stopDb?.();
});
+ it("dispatches a plugin-only project without Core workspace files through the native heartbeat boundary", async () => {
+ const companyId = randomUUID(), projectId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), sourceId = randomUUID();
+ const environmentId = randomUUID(), pluginId = randomUUID(), pluginKey = `test.tasks.${pluginId}`;
+ const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-task-heartbeat-")); tempRoots.push(root);
+ await db.insert(companies).values({ id: companyId, name: "Task fixture", issuePrefix: "TASK", defaultResponsibleUserId: "task-user" });
+ await grantResponsibleUser(companyId, "task-user");
+ await db.insert(projects).values({ id: projectId, companyId, name: "Task fixture", status: "active",
+ executionWorkspacePolicy: { enabled: true, storageProviderPluginId: pluginId } });
+ const pluginOnlyCwd = path.join(root, "plugin-only", "project");
+ await db.insert(projectWorkspaces).values([
+ { id: sourceId, companyId, projectId, name: "Primary", cwd: pluginOnlyCwd, isPrimary: true },
+ { companyId, projectId, name: "Extra", cwd: null, repoUrl: "/unavailable-controller-repository.git", isPrimary: false },
+ ]);
+ await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "@test/tasks", version: "1.0.0", apiVersion: 1,
+ categories: ["automation"], status: "ready", manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0",
+ displayName: "Tasks", description: "Task fixture", author: "Paperclip", categories: ["automation"],
+ capabilities: ["environment.drivers.register", "workspaces.manage", "events.subscribe"], resourceLifecycle: ["project"],
+ workspaceProvider: { modes: ["shared_workspace", "isolated_workspace", "operator_branch"], strategies: ["project_primary", "git_worktree"] },
+ entrypoints: { worker: "worker.js" },
+ environmentDrivers: [{ driverKey: "tasks", displayName: "Tasks", supportsTasks: true, configSchema: { type: "object" } }] } });
+ await db.insert(environments).values({ id: environmentId, companyId, name: "Tasks", driver: "plugin", status: "active",
+ config: { pluginKey, driverKey: "tasks", driverConfig: {} } });
+ await db.insert(agents).values({ id: agentId, companyId, name: "Task agent", role: "engineer", status: "idle",
+ adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: "gpt-6.1-sol" }, runtimeConfig: {},
+ defaultEnvironmentId: environmentId, permissions: {} });
+ await db.insert(issues).values({ id: issueId, companyId, projectId, projectWorkspaceId: sourceId, title: "Task-only dispatch", status: "in_progress",
+ assigneeAgentId: agentId, issueNumber: 1, identifier: "TASK-1" });
+ const call = vi.fn(async (_id: string, method: string, params?: any) => {
+ if (method === "workspaceOperation") return { kind: "prepared", binding: { pluginId, projectId,
+ executionWorkspaceId: params.executionWorkspaceId, projectWorkspaceId: params.operation.source.id,
+ sourceRevision: params.operation.source.revision, workspaceRef: "provider:heartbeat-workspace" },
+ branchName: params.operation.branchName, baseSha: "a".repeat(40), created: true, branchCreatedByRuntime: false };
+ if (method === "environmentAcquireLease") return { providerLeaseId: "heartbeat-task-attempt", metadata: { remoteCwd: "/project" } };
+ if (method === "environmentReleaseLease" || method === "environmentDestroyLease") return undefined;
+ throw new Error(`Unexpected task provider call: ${method}`);
+ });
+ const workerManager = { isRunning: () => true, getWorker: () => ({ supportedMethods: ["workspaceOperation", "environmentTask", "environmentAcquireLease", "environmentReleaseLease", "environmentDestroyLease"] }), call } as unknown as PluginWorkerManager;
+ const entered = vi.fn(() => { throw new Error("synthetic_native_boundary_reached"); });
+ const heartbeat = heartbeatService(db, { pluginWorkerManager: workerManager, nativeSessionBackendFactory: entered });
+ heartbeats.push(heartbeat);
+ const run = await heartbeat.wakeup(agentId, { source: "on_demand", triggerDetail: "manual", contextSnapshot: { issueId, projectId } });
+ expect(run).not.toBeNull();
+ await vi.waitFor(async () => { expect((await heartbeat.getRun(run!.id))?.status).toBe("failed"); }, { timeout: 10_000 });
+ expect(entered).toHaveBeenCalledWith(expect.objectContaining({ binding: expect.objectContaining({ runId: run!.id, companyId, issueId }) }));
+ expect((await heartbeat.getRun(run!.id))?.error).toContain("synthetic_native_boundary_reached");
+ await heartbeat.drainActiveRunExecutions();
+ expect(call).toHaveBeenCalledWith(pluginId, "environmentDestroyLease", expect.objectContaining({ providerLeaseId: "heartbeat-task-attempt" }));
+ expect(call.mock.calls.every(([, method]) => ["workspaceOperation", "environmentAcquireLease", "environmentDestroyLease"].includes(method))).toBe(true);
+ expect(call.mock.calls.filter(([, method]) => method === "workspaceOperation")).toHaveLength(1);
+ expect(adapterExecute).not.toHaveBeenCalled();
+ await expect(stat(pluginOnlyCwd)).rejects.toMatchObject({ code: "ENOENT" });
+ }, 20_000);
+
it("acquires plugin environment leases through the heartbeat execution path", async () => {
const companyId = randomUUID();
const projectId = randomUUID();
diff --git a/server/src/__tests__/plugin-runner-task.integration.test.ts b/server/src/__tests__/plugin-runner-task.integration.test.ts
index 644d332a7f..45f347726b 100644
--- a/server/src/__tests__/plugin-runner-task.integration.test.ts
+++ b/server/src/__tests__/plugin-runner-task.integration.test.ts
@@ -1,18 +1,28 @@
import * as pluginProbe from "../services/native-runtime/plugin-runner-probe.js";
import { randomUUID } from "node:crypto";
import { PassThrough } from "node:stream";
+import { setTimeout as delay } from "node:timers/promises";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
-import { agents, companies, createDb, environmentLeases, environments, plugins } from "@paperclipai/db";
+import { agents, companies, createDb, environmentLeases, environments, heartbeatRuns, plugins, projects } from "@paperclipai/db";
import { definePlugin } from "../../../packages/plugins/sdk/src/define-plugin.js";
import { startWorkerRpcHost } from "../../../packages/plugins/sdk/src/worker-rpc-host.js";
import { createRequest, parseMessage, serializeMessage, isJsonRpcSuccessResponse, isJsonRpcErrorResponse } from "../../../packages/plugins/sdk/src/protocol.js";
-import { type PluginEnvironmentTaskOperation } from "@paperclipai/plugin-sdk";
+import { environmentTaskOperationSchema, type PluginEnvironmentTaskOperation } from "@paperclipai/plugin-sdk";
import type { PaperclipPluginManifestV1 } from "@paperclipai/shared";
import { agentEnvironmentTestService } from "../services/agent-environment-test.js";
+import { heartbeatService } from "../services/heartbeat.js";
+import { remoteExecutionHasStopped } from "../services/remote-execution-termination.js";
+import { resolvePluginTaskResume } from "../services/environment-task-runtime.js";
+import { environmentRuntimeService } from "../services/environment-runtime.js";
+import { environmentRunOrchestrator } from "../services/environment-run-orchestrator.js";
+import { createRunnerProviderLaunch, runnerLaunchRequirementsDigest, type RunnerProviderLaunchRequirements } from "@paperclipai/paperclip-runner";
+import { createPluginRunnerTaskOwner } from "../services/native-runtime/plugin-runner-task.js";
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
+const ingress = vi.hoisted(() => ({ connect: vi.fn() }));
+vi.mock("../realtime/runner-prp-outbound.js", () => ({ connectRunnerPrpIngress: ingress.connect }));
const support = await getEmbeddedPostgresTestSupport();
const databaseSuite = support.supported ? describe : describe.skip;
@@ -54,9 +64,9 @@ databaseSuite("Core plugin Runner task lifecycle", () => {
});
afterAll(async () => { await stopDb?.(); });
- it("uses a bounded setup lease through SDK RPC and releases it after stop proof", async () => {
- const companyId = randomUUID(), agentId = randomUUID();
- const environmentId = randomUUID(), pluginId = randomUUID();
+ it("uses an acquired lease through SDK RPC, native dispatch, connection, stop proof and release", async () => {
+ const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID();
+ const environmentId = randomUUID(), pluginId = randomUUID(), projectId = randomUUID();
const manifest: PaperclipPluginManifestV1 = {
id: "test.runner-tasks", apiVersion: 1, version: "1.0.0", displayName: "Runner tasks",
description: "Synthetic task provider", author: "Paperclip", categories: ["automation"],
@@ -66,6 +76,8 @@ databaseSuite("Core plugin Runner task lifecycle", () => {
await db.insert(companies).values({ id: companyId, name: "Fixture", status: "active" });
await db.insert(agents).values({ id: agentId, companyId, name: "Fixture", role: "engineer", status: "active",
adapterType: "paperclip_runner", adapterConfig: {}, runtimeConfig: {}, permissions: {} });
+ await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "manual", status: "running" });
+ await db.insert(projects).values({ id: projectId, companyId, name: "Fixture", status: "active" });
const [environment] = await db.insert(environments).values({ id: environmentId, name: "Fixture", driver: "plugin", status: "active",
config: { pluginKey: manifest.id, driverKey: "tasks", driverConfig: {} } }).returning();
await db.insert(plugins).values({ id: pluginId, pluginKey: manifest.id, packageName: "@test/runner-tasks",
@@ -82,8 +94,18 @@ databaseSuite("Core plugin Runner task lifecycle", () => {
switch (params.operation.kind) {
case "describe": return { kind: "description", launchPreparationVersion: 1, projectAuthCheckVersion: 1, taskId: params.taskId,
runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } };
+ case "prepare": return { kind: "prepared", taskId: params.taskId, launch: {
+ configurationId: `config-${params.taskId}`, requirementsDigest: runnerLaunchRequirementsDigest(params.operation.requirements as RunnerProviderLaunchRequirements),
+ provider: createRunnerProviderLaunch(params.operation.requirements as RunnerProviderLaunchRequirements, {
+ options: { codexArgs: [] }, root: "/runner", cwd: "/workspace", codexHome: "/account",
+ codexCommand: "/bin/codex", providerNodeCommand: "/bin/node", opencodeProxyPath: "", acpxSidecarPath: "",
+ }),
+ } };
case "check_project_auth": return { kind: "project_auth", taskId: params.taskId,
configurationId: params.operation.configurationId, provider: params.operation.provider, allowed: true };
+ case "read_state": return { kind: "state", taskId: params.taskId, state: {
+ schema: "paperclip.runner.durable.state.v1", ...params.operation.identity, lifecycle: "suspended",
+ } };
case "submit": stopRequested = false; executionStopped = false; return { kind: "accepted", taskId: params.taskId };
case "status": return { kind: "status", taskId: params.taskId, phase: stopRequested ? "cancelled" : "running", executionStopped, sessionStateAvailable: executionStopped };
case "connection": return { kind: "connection", taskId: params.taskId, endpoint: {
@@ -99,17 +121,17 @@ databaseSuite("Core plugin Runner task lifecycle", () => {
const { supportedMethods } = await harness.initialize();
const workers = { isRunning: () => true, getWorker: () => ({ supportedMethods }),
call: (_id: string, method: string, params: unknown) => harness.call(method, params) } as unknown as PluginWorkerManager;
- try {
- const setup = agentEnvironmentTestService(db, workers);
- await setup.assertAdapterTestEnvironmentForCompany(companyId, environmentId, "paperclip_runner");
- const probe = await setup.resolveAdapterTestExecutionContext({ companyId, agentId, adapterType: "paperclip_runner", environmentId });
- expect(probe.fallbackChecks).toEqual([]);
- expect(probe.executionTarget).toMatchObject({ runnerTaskProbe: { runId: expect.any(String), sessionId: expect.any(String) } });
- if (probe.executionTarget?.kind !== "remote" || probe.executionTarget.transport !== "sandbox" || !probe.executionTarget.runnerTaskProbe) throw new Error("Probe task target unavailable");
- await expect(probe.executionTarget.runnerTask!({ kind: "describe" }))
- .resolves.toMatchObject({ kind: "description" });
- const [probeLease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, probe.executionTarget.leaseId!));
- expect(probeLease.heartbeatRunId).toBeNull();
+ const runtime = environmentRuntimeService(db, { pluginWorkerManager: workers });
+ const setup = agentEnvironmentTestService(db, workers);
+ await setup.assertAdapterTestEnvironmentForCompany(companyId, environmentId, "paperclip_runner");
+ const probe = await setup.resolveAdapterTestExecutionContext({ companyId, agentId, adapterType: "paperclip_runner", environmentId });
+ expect(probe.fallbackChecks).toEqual([]);
+ expect(probe.executionTarget).toMatchObject({ runnerTaskProbe: { runId: expect.any(String), sessionId: expect.any(String) } });
+ if (probe.executionTarget?.kind !== "remote" || probe.executionTarget.transport !== "sandbox" || !probe.executionTarget.runnerTaskProbe) throw new Error("Probe task target unavailable");
+ await expect(probe.executionTarget.runnerTask!({ kind: "describe" }))
+ .resolves.toMatchObject({ kind: "description" });
+ const [probeLease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, probe.executionTarget.leaseId!));
+ expect(probeLease.heartbeatRunId).toBeNull();
const selected = { identity: "core-selected-revision", sessionIdentity: "core-selected-account", home: "/core-owned-home" };
const verify = vi.spyOn(pluginProbe, "probePluginRunnerEnvironment").mockResolvedValue({ adapterType: "paperclip_runner", status: "pass", testedAt: new Date().toISOString(), checks: [] });
try {
@@ -117,21 +139,174 @@ databaseSuite("Core plugin Runner task lifecycle", () => {
{ provider: "openai" } as any, selected as any);
expect(verify).toHaveBeenCalledWith(expect.anything(), { identity: selected.identity, accountIdentity: selected.sessionIdentity, home: "/core-owned-home/provider" });
} finally { verify.mockRestore(); }
+ await probe.executionTarget.runnerTask!({ kind: "check_project_auth", configurationId: "probe-config", provider: "openai", projectIds: [] });
+ await probe.executionTarget.runnerTask!({ kind: "submit", preparedLaunchId: "probe-config", bootstrapTicket: "synthetic-probe-ticket", projectIds: [],
+ runner: { protocolMin: 1, protocolMax: 3, harness: "codex", runnerId: "probe-runner", leaseId: probeLease.id,
+ runId: probe.executionTarget.runnerTaskProbe.runId, sessionId: probe.executionTarget.runnerTaskProbe.sessionId, turnId: "probe-turn", itemId: "probe-item" },
+ launch: { runnerVersion: "fixture", runnerDigest: `sha256:${"a".repeat(64)}`,
+ maxOutboxBytes: 262144, p0ReserveBytes: 65536, maxRuntimeMs: 0,
+ lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
+ });
+ const probeSubmit = calls.find((op): op is Extract<PluginEnvironmentTaskOperation, { kind: "submit" }> => op.kind === "submit")!;
+ expect(probeSubmit.launch?.maxRuntimeMs).toBeGreaterThan(0);
+ expect(probeSubmit.launch?.maxRuntimeMs).toBeLessThanOrEqual(120_000);
+ executionStopped = true;
+ await probe.release(); released.mockClear(); complete.mockClear(); calls.length = 0;
+ const orchestrator = environmentRunOrchestrator(db, { environmentRuntime: runtime });
+ const acquired = await orchestrator.acquireForRun({ companyId, selectedEnvironmentId: environmentId, localEnvironmentId: randomUUID(),
+ agentId, issueId: null, heartbeatRunId: runId, persistedExecutionWorkspace: null,
+ executionWorkspaceSettings: null, adapterType: "paperclip_runner" });
+ const realization = await orchestrator.realizeForRun({ companyId, environment: acquired.environment, lease: acquired.lease,
+ adapterType: "paperclip_runner", issueId: null, heartbeatRunId: runId,
+ executionWorkspace: { baseCwd: "/local/project", cwd: "/local/project", source: "project_primary", projectId,
+ workspaceId: null, repoUrl: null, repoRef: null, strategy: "project_primary", branchName: null, worktreePath: null,
+ warnings: [], created: false, branchCreatedByRuntime: false },
+ effectiveExecutionWorkspaceMode: null, persistedExecutionWorkspace: null });
+ const target = realization.executionTarget;
+ expect(target).toMatchObject({ kind: "remote", transport: "sandbox", remoteCwd: "/local/project", leaseId: acquired.lease.id });
+ if (target?.kind !== "remote" || target.transport !== "sandbox" || !target.runnerTask) throw new Error("Missing plugin target");
+ expect(target.runner).toBeUndefined();
+ await expect(target.runnerTask({ kind: "describe" }))
+ .resolves.toMatchObject({ kind: "description", runner: { version: "fixture" } });
+ const onDispatched = vi.fn(), checkpoint = vi.fn(async () => {}), close = vi.fn(async () => {});
+ ingress.connect.mockReturnValue({ ready: Promise.resolve(), close });
+ const owner = createPluginRunnerTaskOwner({ task: target.runnerTask, projectAuthCheckVersion: 1,
+ credentialIdentity: "revision", accountIdentity: "account", credential: { type: "codex-auth-json", authJson: '{"OPENAI_API_KEY":"synthetic-account-key"}' }, projectIds: target.runnerTaskProjectIds ?? [], harness: "codex",
+ onSessionRetained: checkpoint, onDispatched, pollMs: 1 });
+ const identity = { runnerInstanceId: randomUUID(), environmentLeaseId: acquired.lease.id, runId,
+ normalizedSessionId: randomUUID(), turnId: "turn", itemId: "item" };
+ const requirements: RunnerProviderLaunchRequirements = { schema: "paperclip.runner.launch-requirements.v1", identity,
+ provider: "codex", model: "fixture", instructions: "Core policy", runtimeContext: null, settings: {},
+ approvalPolicy: "never", readOnly: false, preparedConversation: false, includeCollaborationModeInstructions: false };
+ const prepared = await owner.driver.prepareLaunch!(requirements);
+ // Re-preparation invalidates the old credential validation before the worker reply.
+ await runtime.task({ companyId, leaseId: acquired.lease.id, operation: environmentTaskOperationSchema.parse({
+ kind: "prepare", requirements, projectIds: [projectId],
+ }) });
+ await expect(runtime.task({ companyId, leaseId: acquired.lease.id, operation: {
+ kind: "submit", projectIds: [projectId], preparedLaunchId: prepared.configurationId, bootstrapTicket: "synthetic-ticket",
+ accountIdentity: "account", credential: { type: "codex-auth-json", authJson: '{"OPENAI_API_KEY":"never-transfer-stale-proof"}' },
+ runner: { protocolMin: 1, protocolMax: 3, harness: "codex", runnerId: identity.runnerInstanceId,
+ leaseId: identity.environmentLeaseId, runId: identity.runId, sessionId: identity.normalizedSessionId,
+ turnId: identity.turnId, itemId: identity.itemId },
+ } })).rejects.toThrow("validation unavailable");
+ expect(calls.some(op => op.kind === "submit")).toBe(false);
+ await owner.driver.prepareLaunch!(requirements);
+ const registration = await owner.registration({} as never, runId);
+ const handle = owner.launcher({ command: "ignored", args: [], cwd: "/ignored", environment: { OPENAI_API_KEY: "synthetic-launch-key" },
+ nativeRunner: { identity, ticket: "synthetic-bootstrap-ticket",
+ connection: registration.connection, stateDirectory: "/runner/state", runnerVersion: "fixture", runnerDigest: `sha256:${"a".repeat(64)}`,
+ maxOutboxBytes: 262144, p0ReserveBytes: 65536, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } } });
+ let settled = false;
+ void handle.completion.then(() => { settled = true; });
+ try {
+ registration.activate(); await registration.ready();
+ expect(onDispatched).toHaveBeenCalledOnce();
+ expect(ingress.connect).toHaveBeenCalledWith(expect.objectContaining({ endpoint: expect.objectContaining({ websocketUrl: "wss://runner.example.test/connect" }) }));
+ const submit = calls.find(operation => operation.kind === "submit");
+ expect(submit).toMatchObject({ kind: "submit", projectIds: [projectId], runner: { leaseId: acquired.lease.id, runId },
+ launch: { runnerVersion: "fixture" } });
+ const [saved] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, acquired.lease.id));
+ expect(saved.metadata?.runnerTaskDispatched).toBe(true);
+ expect(JSON.stringify(saved.metadata)).not.toMatch(/synthetic-account-key|synthetic-launch-key|synthetic-bootstrap-ticket|synthetic-fixture/);
+ await expect(runtime.task({ companyId: randomUUID(), leaseId: acquired.lease.id, operation: { kind: "stop" } })).rejects.toThrow("lease unavailable");
+ const before = calls.filter(value => value.kind === "submit").length;
+ await expect(runtime.task({ companyId, leaseId: acquired.lease.id, operation: { ...submit!, projectIds: [randomUUID()] } as never })).rejects.toThrow("project unavailable");
+ expect(calls.filter(value => value.kind === "submit")).toHaveLength(before);
+ handle.child.kill("SIGTERM");
+ await vi.waitFor(() => expect(stopRequested).toBe(true));
+ await delay(10); expect(settled).toBe(false);
+ executionStopped = true; await handle.completion;
+ await registration.release(); expect(complete).not.toHaveBeenCalled();
+ await registration.checkpoint("settled");
+ expect(checkpoint).toHaveBeenCalledOnce(); expect(complete).toHaveBeenCalledOnce();
+ await runtime.releaseRunLeases(runId, "released");
+ expect(released).toHaveBeenCalledOnce(); expect(close).toHaveBeenCalledOnce();
+ expect(await remoteExecutionHasStopped(db, companyId, runId)).toBe(true);
- await probe.executionTarget.runnerTask!({ kind: "check_project_auth", configurationId: "probe-config", provider: "openai", projectIds: [] });
- await probe.executionTarget.runnerTask!({ kind: "submit", preparedLaunchId: "probe-config", bootstrapTicket: "synthetic-probe-ticket", projectIds: [],
- runner: { protocolMin: 1, protocolMax: 3, harness: "codex", runnerId: "probe-runner", leaseId: probeLease.id,
- runId: probe.executionTarget.runnerTaskProbe.runId, sessionId: probe.executionTarget.runnerTaskProbe.sessionId, turnId: "probe-turn", itemId: "probe-item" },
- launch: { runnerVersion: "fixture", runnerDigest: `sha256:${"a".repeat(64)}`,
- maxOutboxBytes: 262144, p0ReserveBytes: 65536, maxRuntimeMs: 0,
- lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
- });
- const probeSubmit = calls.find((op): op is Extract<PluginEnvironmentTaskOperation, { kind: "submit" }> => op.kind === "submit")!;
- expect(probeSubmit.launch?.maxRuntimeMs).toBeGreaterThan(0);
- expect(probeSubmit.launch?.maxRuntimeMs).toBeLessThanOrEqual(120_000);
+ // A controller that dies after dispatch leaves only the lease marker.
+ const second = await runtime.acquireRunLease({ companyId, environment: environment as never, agentId,
+ issueId: null, heartbeatRunId: runId, persistedExecutionWorkspace: null, adapterType: "paperclip_runner" });
+ if (submit?.kind !== "submit") throw new Error("Missing submit fixture");
+ await runtime.task({ companyId, leaseId: second.lease.id, operation: { kind: "check_project_auth", configurationId: "second-config", provider: "openai", projectIds: [projectId] } });
+ await runtime.task({ companyId, leaseId: second.lease.id,
+ operation: { ...submit, credential: undefined, accountIdentity: undefined, credentialIdentity: undefined,
+ preparedLaunchId: "second-config", runner: { ...submit.runner, leaseId: second.lease.id } } });
+ await runtime.task({ companyId, leaseId: second.lease.id, operation: { kind: "complete" } });
+ const errors = vi.fn();
+ await runtime.releaseRunLeases(runId, "released", errors);
+ expect(errors).toHaveBeenCalledOnce();
+ expect(released).toHaveBeenCalledOnce(); // No release while termination is unknown.
+ const [pending] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, second.lease.id));
+ expect(pending).toMatchObject({ status: "pending_cleanup", metadata: { runnerTaskDispatched: true } });
+ await db.delete(environments).where(eq(environments.id, environmentId));
executionStopped = true;
- await probe.release();
- expect(released).toHaveBeenCalledOnce();
- } finally { harness.stop(); }
+ releaseFailure = true;
+ const recovery = heartbeatService(db, { environmentRuntime: runtime, pluginWorkerManager: workers });
+ expect((await recovery.sweepPendingCleanupLeases()).destroyed).toBe(0);
+ const [retryable] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, second.lease.id));
+ expect(retryable.status).toBe("pending_cleanup");
+ releaseFailure = false;
+ await db.update(environmentLeases).set({ metadata: { ...retryable.metadata, pendingCleanupRetryAfterMs: 0 } }).where(eq(environmentLeases.id, second.lease.id));
+ const sweep = await recovery.sweepPendingCleanupLeases();
+ expect(released).toHaveBeenCalledTimes(2);
+ expect(sweep.destroyed).toBe(1);
+ const [cleaned] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, second.lease.id));
+ expect(cleaned).toMatchObject({ status: "expired", cleanupStatus: "success", environmentId: null,
+ metadata: { runnerTaskDispatched: false, remoteExecutionTermination: { state: "stopped" } } });
+ } finally { executionStopped = true; handle.child.kill(); await handle.completion.catch(() => {}); harness.stop(); }
});
+
+ it.each([false, true])("replaces a same-run task only after the provider confirms termination (%s)", async stopped => {
+ const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), pluginId = randomUUID(), environmentId = randomUUID(), oldLeaseId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Task recovery", issuePrefix: `R${companyId.slice(0, 7)}` });
+ await db.insert(agents).values({ id: agentId, companyId, name: "Fixture", adapterType: "paperclip_runner" });
+ await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "manual", status: "running" });
+ await db.insert(environments).values({ id: environmentId, name: `Recovery ${environmentId}`, driver: "plugin", status: "active", config: { pluginKey: pluginId, driverKey: "tasks", driverConfig: {} } });
+ await db.insert(plugins).values({ id: pluginId, pluginKey: pluginId, packageName: "fixture-recovery", version: "1.0.0", status: "ready", manifestJson: {
+ capabilities: ["environment.drivers.register"], environmentDrivers: [{ driverKey: "tasks", supportsTasks: true }],
+ } as never });
+ const priorIdentity = { runnerInstanceId: "runner", environmentLeaseId: oldLeaseId, runId, normalizedSessionId: "session" };
+ const runner = { runnerId: "runner", leaseId: oldLeaseId, runId, sessionId: "session", turnId: "turn", itemId: "item", harness: "codex", protocolMin: 1, protocolMax: 3 };
+ await db.insert(environmentLeases).values({ id: oldLeaseId, companyId, environmentId, heartbeatRunId: runId, status: "active", provider: `plugin:${pluginId}:tasks`, providerLeaseId: "old-task",
+ metadata: { driver: "plugin", pluginId, pluginKey: pluginId, driverKey: "tasks", agentId, runnerTaskLease: true, runnerTaskDispatched: true, runnerTaskIdentity: runner } });
+ const operations: string[] = [];
+ const workers = { isRunning: () => true, getWorker: () => ({ supportedMethods: ["environmentTask", "environmentReleaseLease", "environmentAcquireLease"] }),
+ call: async (_id: string, method: string, params: any) => {
+ operations.push(method === "environmentTask" ? params.operation.kind : method);
+ if (method === "environmentAcquireLease") {
+ expect(await remoteExecutionHasStopped(db, companyId, runId)).toBe(true);
+ return { providerLeaseId: "new-task", metadata: {} };
+ }
+ if (method === "environmentReleaseLease") return;
+ if (params.operation.kind === "check_project_auth") return { kind: "project_auth", taskId: params.taskId, configurationId: params.operation.configurationId, provider: params.operation.provider, allowed: true };
+ if (params.operation.kind === "status") return { kind: "status", taskId: "old-task", phase: "cancelled", executionStopped: stopped, sessionStateAvailable: stopped };
+ return { kind: "accepted", taskId: params.taskId };
+ } } as unknown as PluginWorkerManager;
+ const runtime = environmentRuntimeService(db, { pluginWorkerManager: workers });
+ const acquire = environmentRunOrchestrator(db, { environmentRuntime: runtime }).acquireForRun({
+ companyId, selectedEnvironmentId: environmentId, localEnvironmentId: randomUUID(), adapterType: "paperclip_runner", agentId,
+ issueId: null, heartbeatRunId: runId, persistedExecutionWorkspace: null, executionWorkspaceSettings: null, recoverPluginTask: true,
+ });
+ if (!stopped) {
+ await expect(acquire).rejects.toThrow("termination_unconfirmed");
+ expect(operations).not.toContain("environmentAcquireLease");
+ expect(operations).not.toContain("complete");
+ return;
+ }
+ const next = await acquire;
+ expect(operations).toEqual(["stop", "status", "complete", "environmentReleaseLease", "environmentAcquireLease"]);
+ expect(next.lease.id).not.toBe(oldLeaseId);
+ await expect(resolvePluginTaskResume(db, { companyId, leaseId: next.lease.id, priorIdentity })).resolves.toBe("old-task");
+ await expect(runtime.task({ companyId, leaseId: next.lease.id, operation: { kind: "submit", projectIds: [], bootstrapTicket: "fixture", runner } })).rejects.toThrow("identity mismatch");
+ await runtime.task({ companyId, leaseId: next.lease.id, operation: { kind: "check_project_auth", configurationId: "recovery-config", provider: "openai", projectIds: [] } });
+ await expect(runtime.task({ companyId, leaseId: next.lease.id, operation: { kind: "submit", preparedLaunchId: "recovery-config", projectIds: [], bootstrapTicket: "fixture", runner, resumeFrom: "old-task" } })).resolves.toMatchObject({ kind: "accepted" });
+ const competingId = randomUUID();
+ await db.insert(environmentLeases).values({ id: competingId, companyId, environmentId, heartbeatRunId: runId, status: "active", provider: `plugin:${pluginId}:tasks`, providerLeaseId: "competing-task" });
+ await expect(resolvePluginTaskResume(db, { companyId, leaseId: next.lease.id, priorIdentity })).rejects.toThrow("not authorized");
+ await db.delete(environmentLeases).where(eq(environmentLeases.id, competingId));
+ await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, oldLeaseId));
+ await expect(resolvePluginTaskResume(db, { companyId, leaseId: next.lease.id, priorIdentity })).rejects.toThrow("not authorized");
+ });
+
});
diff --git a/server/src/__tests__/task-workspace-api.test.ts b/server/src/__tests__/task-workspace-api.test.ts
index aaebec4154..48794edaef 100644
--- a/server/src/__tests__/task-workspace-api.test.ts
+++ b/server/src/__tests__/task-workspace-api.test.ts
@@ -65,6 +65,17 @@ const support = await getEmbeddedPostgresTestSupport();
expect(runs).toHaveLength(1);
expect(runs[0]).toMatchObject({ id: f.runId, status: "running" });
});
+ it("rejects repository preparation on an environment-owned workspace before queuing a receipt", async () => {
+ const f = await server.fixture({ conversation: true, disableWakeOnDemand: true });
+ const [workspace] = await server.db.insert(executionWorkspaces).values({ companyId: f.companyId, sourceIssueId: f.issueId,
+ name: "Plugin workspace", cwd: ".", mode: "adapter_managed", strategyType: "adapter_managed", providerType: "adapter_managed" }).returning();
+ await server.db.update(issues).set({ projectId: null, projectWorkspaceId: null, executionWorkspaceId: workspace.id }).where(eq(issues.id, f.issueId));
+ const call = (tool: string, args: Record<string, unknown>) => f.authority.execute({ tool, arguments: args, callId: randomUUID() });
+ await expect(call("get_workspace", {})).resolves.toMatchObject({ capabilities: { prepareRepository: "unsupported" } });
+ await expect(call("prepare_repository", { repository: { kind: "url", url: "https://github.com/public/example" }, requestKey: "unsupported-plugin" }))
+ .rejects.toThrow("environment-owned workspace");
+ expect(await server.db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.executionWorkspaceId, workspace.id))).toEqual([]);
+ });
it("allows a projectless task to use a directory also configured by an unrelated protected project", async () => {
const f = await server.fixture({ conversation: true, disableWakeOnDemand: true });
const [project] = await server.db.insert(projects).values({ companyId: f.companyId, name: "Protected physical source",
diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts
index 372531d971..fefd2afed4 100644
--- a/server/src/routes/agents.ts
+++ b/server/src/routes/agents.ts
@@ -3139,7 +3139,13 @@ export function agentRoutes(
if (test || binding.provider === "github") {
const testEnvironmentId = await resolveAdapterTestEnvironmentId(companyId, environmentId, binding.provider === "github");
if (testEnvironmentId) await assertAdapterTestEnvironmentForCompany(companyId, testEnvironmentId, adapterType);
- const target = await resolveAdapterTestExecutionContext({ companyId, adapterType, agentId: newAgent ? undefined : agentId, environmentId: testEnvironmentId });
+ const hasSavedAgent = !newAgent || (isUuidLike(agentId) && Boolean(await svc.getById(agentId)));
+ if (!hasSavedAgent && !test && testEnvironmentId && (await environmentsSvc.getById(testEnvironmentId))?.driver === "plugin") {
+ // The lifecycle verifies the saved agent after its plugin can create the agent-owned computer.
+ return { connectionId: selection.connection.id };
+ }
+ const target = await resolveAdapterTestExecutionContext({ companyId, adapterType,
+ agentId: hasSavedAgent ? agentId : undefined, environmentId: testEnvironmentId });
try {
if (!target.executionTarget && target.fallbackChecks.length > 0) throw unprocessable("The agent environment is not available for adoption");
await withManagedAiProbe(db, { companyId, agentId, responsibleUserId: userId, adapterType, binding, config, allowUninstalledPersonal: newAgent, allowUninstalledShared, allowLegacyValidation: true }, async managed => {
diff --git a/server/src/routes/task-workspaces.ts b/server/src/routes/task-workspaces.ts
index 93677c7631..64b71897a1 100644
--- a/server/src/routes/task-workspaces.ts
+++ b/server/src/routes/task-workspaces.ts
@@ -33,7 +33,7 @@ export function taskWorkspaceRoutes(db: Db) {
router.get("/issues/:id/workspace", async (req, res) => {
const issue = await task(req);
const view = await workspaces.inspectTaskWorkspace(issue.companyId, issue.id, req.actor);
- res.json({ ...view, repositories: issue.executionWorkspaceId ? await workspaces.listTaskRepositories(issue.companyId, issue.executionWorkspaceId) : [], capabilities: { prepareRepository: "next_normal_admission", selectWorkspace: "next_normal_admission" }, fileLocations: { taskFiles: "workspace", personalInstructionsAndMemory: "AGENT_HOME", providerHome: "runtime_managed" } });
+ res.json({ ...view, repositories: issue.executionWorkspaceId ? await workspaces.listTaskRepositories(issue.companyId, issue.executionWorkspaceId) : [], capabilities: { prepareRepository: view.workspace?.providerType === "adapter_managed" ? "unsupported" : "next_normal_admission", selectWorkspace: "next_normal_admission" }, fileLocations: { taskFiles: "workspace", personalInstructionsAndMemory: "AGENT_HOME", providerHome: "runtime_managed" } });
});
router.put("/issues/:id/workspace", validate(selectTaskWorkspaceSchema), async (req, res) => {
const issue = await task(req, true);
diff --git a/server/src/services/environment-run-orchestrator.ts b/server/src/services/environment-run-orchestrator.ts
index 8016bb567a..8757efe6cf 100644
--- a/server/src/services/environment-run-orchestrator.ts
+++ b/server/src/services/environment-run-orchestrator.ts
@@ -15,7 +15,9 @@
* and transport logic.
*/
-import type { Db } from "@paperclipai/db";
+import { environmentLeases, type Db } from "@paperclipai/db";
+import { and, eq } from "drizzle-orm";
+import { remoteExecutionHasStopped } from "./remote-execution-termination.js";
import type {
Environment,
EnvironmentLease,
@@ -276,6 +278,8 @@ export function environmentRunOrchestrator(
executionWorkspaceSettings: IssueExecutionWorkspaceSettings | null;
/** Existing live runner recovery must use its original active lease, including ephemeral leases. */
reattachRemoteLease?: { leaseId: string; providerLeaseId: string; remoteCwd: string };
+ /** A new controller must stop the previous plugin task before allocating a replacement. */
+ recoverPluginTask?: boolean;
}): Promise<EnvironmentAcquisitionResult> {
// Step 1: Resolve environment
const selectedEnvironment = await resolveEnvironment({
@@ -288,6 +292,20 @@ export function environmentRunOrchestrator(
selectedEnvironment, input.adapterType, input.adapterConfig, input.admittedLifecycleMode,
);
+ if (input.recoverPluginTask && environment.driver === "plugin" && input.adapterType === "paperclip_runner") {
+ const prior = await db.select().from(environmentLeases).where(and(
+ eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.heartbeatRunId, input.heartbeatRunId),
+ ));
+ if (prior.some(lease => lease.metadata?.runnerTaskLease !== true || lease.environmentId !== environment.id ||
+ lease.issueId !== input.issueId || lease.executionWorkspaceId !== (input.persistedExecutionWorkspace?.id ?? null) ||
+ lease.metadata?.agentId !== input.agentId)) throw new Error("native_plugin_recovery_lease_mismatch");
+ const errors: unknown[] = [];
+ await environmentRuntime.releaseRunLeases(input.heartbeatRunId, "released", (_id, error) => { errors.push(error); });
+ if (errors.length || (prior.length && !await remoteExecutionHasStopped(db, input.companyId, input.heartbeatRunId))) {
+ throw new Error("native_plugin_recovery_termination_unconfirmed", { cause: errors[0] });
+ }
+ }
+
// Step 2: Acquire lease
const acquisitionInput = {
companyId: input.companyId,
@@ -346,7 +364,7 @@ export function environmentRunOrchestrator(
});
// Step 4: Resolve execution transport
- const executionTransport = await resolveTransport({
+ const executionTransport = environment.driver === "plugin" && input.adapterType === "paperclip_runner" ? null : await resolveTransport({
companyId: input.companyId,
adapterType: input.adapterType,
environment,
@@ -383,6 +401,7 @@ export function environmentRunOrchestrator(
executionWorkspace: RealizedExecutionWorkspace;
effectiveExecutionWorkspaceMode: string | null;
persistedExecutionWorkspace: ExecutionWorkspace | null;
+ runnerTaskProjectIds?: readonly string[];
/**
* The host duplex observability recorder for this run. The orchestrator threads
* it to `resolveEnvironmentExecutionTarget`, which stamps it on the sandbox
@@ -426,6 +445,10 @@ export function environmentRunOrchestrator(
// Step 2: Realize workspace in the environment via the runtime driver
let workspaceRealization: Record<string, unknown> = {};
let realizedWorkspaceCwd: string | null = null;
+ const pluginTaskWorkspace = environment.driver === "plugin" && adapterType === "paperclip_runner";
+ if (pluginTaskWorkspace && !await environmentRuntime.supportsTasks({ lease })) {
+ throw new EnvironmentRunError("unsupported_adapter_environment", "Plugin environment does not provide native Runner task execution");
+ }
if (ENVIRONMENT_DRIVER_TRAITS[environment.driver].realizesWorkspace) {
try {
const remoteCwd =
@@ -478,7 +501,7 @@ export function environmentRunOrchestrator(
// for `local`. Keep the step for `ssh`, which runs the command on the
// remote host that shares the workspace path.
const driverSkipsHostProvision =
- environment.driver === "local" || environment.driver === "sandbox";
+ environment.driver === "local" || environment.driver === "sandbox" || pluginTaskWorkspace;
if (provisionCommand && environment.driver === "sandbox") {
logger.info(
{
@@ -569,7 +592,7 @@ export function environmentRunOrchestrator(
!("runnerTask" in executionTarget) || typeof executionTarget.runnerTask !== "function")) {
throw new Error("Managed workspace execution requires the native plugin task bridge");
}
- const realizationMode = workspaceRealization.mode === "in_place" ? "in_place" : "copy";
+ const realizationMode = pluginTaskWorkspace || workspaceRealization.mode === "in_place" ? "in_place" : "copy";
const authoritativeRoot =
typeof workspaceRealization.authoritativeRoot === "string" && workspaceRealization.authoritativeRoot.trim().length > 0
? workspaceRealization.authoritativeRoot.trim()
@@ -592,6 +615,11 @@ export function environmentRunOrchestrator(
if (executionTarget) {
executionTarget = {
...executionTarget,
+ ...(executionTarget.kind === "remote" && executionTarget.transport === "sandbox" && executionTarget.runnerTask
+ ? { runnerTaskProjectIds: [...new Set([executionWorkspace.projectId,
+ ...input.runnerTaskProjectIds ?? [],
+ ...(executionWorkspace.additionalWorkspaces ?? []).map(workspace => workspace.projectId)]
+ .filter((id): id is string => Boolean(id)))] } : {}),
...(executionTarget.kind === "remote" && realizationMode === "in_place"
? { remoteCwd: authoritativeRoot }
: {}),
diff --git a/server/src/services/execution-workspace-repositories.ts b/server/src/services/execution-workspace-repositories.ts
index f0eec1af1b..c969962a5a 100644
--- a/server/src/services/execution-workspace-repositories.ts
+++ b/server/src/services/execution-workspace-repositories.ts
@@ -153,6 +153,7 @@ export function executionWorkspaceRepositoryService(db: Db) {
const [workspace] = await measureRunPhase("workspace.sources.inventory", async () => tx.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, issue.executionWorkspaceId!), eq(executionWorkspaces.companyId, input.companyId), taskWorkspaceSelectableCondition())).for("no key update"));
if (!workspace) throw conflict("Execution workspace is unavailable");
await assertTaskWorkspaceExecutionAccess(tx, input.actor, input.companyId, { issueId: input.issueId, workspaceId: workspace.id });
+ if (workspace.providerType === "adapter_managed") throw conflict("Repository preparation is unavailable for this environment-owned workspace");
const anonymousOnly = await requiresAnonymousAcquisition(tx, { issue, workspace,
agentId: input.actor.agentId, runId: input.actor.runId });
const source = resolveAcquisitionSource(parsed.repository, available, anonymousOnly);
diff --git a/server/src/services/heartbeat-github-launchers.test.ts b/server/src/services/heartbeat-github-launchers.test.ts
index 5bb4038bac..10626f369b 100644
--- a/server/src/services/heartbeat-github-launchers.test.ts
+++ b/server/src/services/heartbeat-github-launchers.test.ts
@@ -11,6 +11,16 @@ import { prepareHeartbeatGitHubLaunchers } from "./heartbeat-github-launchers.js
const target = { kind: "remote" as const, transport: "sandbox" as const, providerKey: "daytona", remoteCwd: "/workspace" };
describe("heartbeat GitHub launcher lifetime", () => {
+ it("leaves a task provider's runtime untouched", async () => {
+ const prepare = vi.fn(), mint = vi.fn();
+ const env = { OPENAI_API_KEY: "selected-credential" };
+ const result = await prepareHeartbeatGitHubLaunchers({ native: true, githubConfigured: true, agentId: "agent",
+ runId: "run", target: { ...target, runnerTask: async () => ({}) }, cwd: "/core/workspace",
+ env, brokerUrl: "https://paperclip.test", createBrokerToken: mint }, prepare);
+ expect(result).toEqual({ env, cleanupLocation: null });
+ expect(prepare).not.toHaveBeenCalled();
+ expect(mint).not.toHaveBeenCalled();
+ });
it.each([target, null])("defers native managed authorization/staging to the session owner (%j)", async (target) => {
const prepare = vi.fn();
const mint = vi.fn();
diff --git a/server/src/services/heartbeat-github-launchers.ts b/server/src/services/heartbeat-github-launchers.ts
index 83786a48eb..df24082f12 100644
--- a/server/src/services/heartbeat-github-launchers.ts
+++ b/server/src/services/heartbeat-github-launchers.ts
@@ -15,6 +15,10 @@ export async function prepareHeartbeatGitHubLaunchers(
prepareLaunchers = prepareGitHubOperationLaunchers,
cleanupLaunchers = cleanupGitHubOperationLaunchers,
) {
+ if (input.target?.kind === "remote" && input.target.transport === "sandbox" && input.target.runnerTask) {
+ // Provider-owned tasks decide their own runtime layout and command environment.
+ return { env: input.env, cleanupLocation: null };
+ }
// Native configured access is owned by the provider session supervisor.
// Defer staging until it has acquired that session; never mutate a live
// process's authorization from heartbeat preparation.
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index 537510275d..0d2d33e61d 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -1003,6 +1003,7 @@ export function heartbeatService(
sweepOrphanedActiveLeases,
drainRunningRunsForShutdown,
} = createHeartbeatRecovery(db, {
+ pluginWorkerManager: options.pluginWorkerManager,
enterShutdown: () => { shutdownInProgress = true; },
scheduleBoundedRetryForRun,
appendRunEvent,
@@ -3011,7 +3012,7 @@ export function heartbeatService(
// and the per-failure reason for a partial sync.
const referencedProjectObservability =
buildReferencedProjectRunObservability({
- syncedProjectIds: resolvedWorkspace.additionalWorkspaces.map(
+ syncedProjectIds: resolvedWorkspace.runnerTaskProjectIds?.filter(id => id !== resolvedWorkspace.projectId) ?? resolvedWorkspace.additionalWorkspaces.map(
(additional) => additional.projectId,
),
failures: resolvedWorkspace.referencedProjectFailures,
diff --git a/server/src/services/heartbeat/instruction-working-copy.test.ts b/server/src/services/heartbeat/instruction-working-copy.test.ts
index a3f57cce7c..b29d226b49 100644
--- a/server/src/services/heartbeat/instruction-working-copy.test.ts
+++ b/server/src/services/heartbeat/instruction-working-copy.test.ts
@@ -49,6 +49,18 @@ function fixture(executionTarget: Input["workspace"]["executionTarget"] = null,
beforeEach(() => { vi.clearAllMocks(); native.claim.mockResolvedValue(null); });
describe("instruction working-copy extraction boundary", () => {
+ it("leaves the persistent agent home with the task provider", async () => {
+ const task = vi.fn();
+ const f = fixture({ kind: "remote", transport: "sandbox", providerKey: "plugin", remoteCwd: "/unused", leaseId: "task-lease",
+ runnerTask: task, runnerLifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } });
+ await f.controller.prepare(f.prepare);
+ await f.controller.collectStoppedInstructions();
+ expect(f.controller.nativeInstructionWorkingCopy()).toBeUndefined();
+ expect(f.copies.prepare).not.toHaveBeenCalled();
+ expect(f.copies.collectStopped).not.toHaveBeenCalled();
+ expect(task).not.toHaveBeenCalled();
+ });
+
it.each([
["copilot", false, true], ["copilot", true, true],
["cursor", false, true], ["cursor", true, true],
diff --git a/server/src/services/heartbeat/instruction-working-copy.ts b/server/src/services/heartbeat/instruction-working-copy.ts
index 558b7b0a58..449dcbd53c 100644
--- a/server/src/services/heartbeat/instruction-working-copy.ts
+++ b/server/src/services/heartbeat/instruction-working-copy.ts
@@ -79,6 +79,7 @@ export function createHeartbeatInstructionWorkingCopy(input: InstructionWorkingC
let nativeInstructionReservation: Awaited<ReturnType<typeof reserveWarmNativeInstructionDirectory>> = null;
let instructionCopy: Awaited<ReturnType<typeof instructionCopies.prepare>> = null;
let instructionSave: Record<string, unknown> | null = null;
+ const task = executionTarget?.kind === "remote" && executionTarget.transport === "sandbox" ? executionTarget.runnerTask : undefined;
const instructionPreparationKey = createHash("sha256").update(JSON.stringify({
adapterType: agent.adapterType, adapterConfig: agent.adapterConfig, runtimeConfig: agent.runtimeConfig, sessionConfigMetadata,
duplexBridge: adapterExecutionTargetEnablesSandboxDuplexBridge(executionTarget),
@@ -127,7 +128,7 @@ export function createHeartbeatInstructionWorkingCopy(input: InstructionWorkingC
nativeRuntimeResolution: Selection["nativeRuntimeResolution"];
hasInstructionFilesystem: boolean;
}) {
- if (hasInstructionFilesystem) {
+ if (hasInstructionFilesystem && !task) {
try {
// Missing contract fields on a restored session mean the deployed
// legacy format. New sessions opt into whole-directory persistence.
diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts
index dad4a0ea53..8964c628b9 100644
--- a/server/src/services/heartbeat/recovery.ts
+++ b/server/src/services/heartbeat/recovery.ts
@@ -1,3 +1,4 @@
+import type { WorkspaceWorkers } from "../plugin-workspaces.js";
import { createHeartbeatAgentStatus } from "./agent-status.js";
import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js";
import { preserveCancelledNativeWorkspaces } from "../native-runtime/native-failed-workspace-recovery.js";
@@ -99,6 +100,7 @@ export interface HeartbeatRecoveryDependencies extends Pick<HeartbeatRetryDepend
Awaited<ReturnType<ReturnType<typeof createHeartbeatRunState>["getRun"]>> | null
>;
environmentRuntime: ReturnType<typeof environmentRuntimeService>;
+ pluginWorkerManager?: WorkspaceWorkers;
environmentsSvc: Pick<ReturnType<typeof environmentService>, "getById" | "getLeaseById" | "releaseLease">;
instructionCopies: Pick<ReturnType<typeof agentInstructionWorkingCopyService>, "recoverStopped" | "recoverCaptured">;
runtimeEnv: Record<string, string | undefined>;
@@ -919,6 +921,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
// whether any provider authority needs to be reopened.
await reconcileNativeFinalizations(db, undefined, {
environmentRuntime,
+ pluginWorkerManager: dependencies.pluginWorkerManager,
onWorkspaceSettled: settleRecoveredNativeWorkspace,
});
await preserveCancelledNativeWorkspaces(db);
@@ -1960,6 +1963,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
// mode, never the current feature flag.
await reconcileNativeFinalizations(db, undefined, {
environmentRuntime,
+ pluginWorkerManager: dependencies.pluginWorkerManager,
onWorkspaceSettled: settleRecoveredNativeWorkspace,
}).catch((error) => {
logger.warn(
diff --git a/server/src/services/heartbeat/runtime-execution.test.ts b/server/src/services/heartbeat/runtime-execution.test.ts
index 361fe422b6..2b4e91c57c 100644
--- a/server/src/services/heartbeat/runtime-execution.test.ts
+++ b/server/src/services/heartbeat/runtime-execution.test.ts
@@ -2,13 +2,14 @@ import { randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issues, nativeRunFinalizations, runUsageReceipts, workspaceOperations, type Db } from "@paperclipai/db";
+import { agents, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issues, executionWorkspaces, nativeRunFinalizations, runUsageReceipts, workspaceOperations, type Db } from "@paperclipai/db";
import { eq, sql } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { trace } from "@opentelemetry/api";
import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace";
import { createRunPreparationTiming, measureRunPhase, measureWorkspaceSyncPhase, withRunExecutionTiming } from "../execution-preparation-timing.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
+import * as pluginWorkspaces from "../plugin-workspaces.js";
import * as legacyRecovery from "../legacy-execution-recovery.js";
import { createAgentIdentityRedactor } from "../agent-identity-redaction.js";
import { createAdapterExecutionControl } from "../adapter-execution-control.js";
@@ -202,6 +203,28 @@ describe.skipIf(!support.supported)("heartbeat runtime execution boundary", () =
expectCleanup(input);
});
+ it.each(["expected", "wrong"])("finalizes a plugin worktree through its owner (branch: %s)", async branch => {
+ const { input } = await fixture(true);
+ const [workspace] = await db.insert(executionWorkspaces).values({ companyId: input.agent.companyId,
+ name: "Plugin worktree", providerType: "plugin", providerRef: "provider:opaque-worktree", cwd: "/workspaces/plugin-only",
+ mode: "isolated_workspace", strategyType: "git_worktree", branchName: "task-branch" }).returning();
+ input.workspace.persistedExecutionWorkspace = workspace;
+ const inspect = vi.spyOn(pluginWorkspaces, "inspectPluginWorkspace").mockResolvedValue({ kind: "inspection",
+ branchName: branch === "expected" ? "task-branch" : "other-branch", headSha: "a".repeat(40),
+ hasDirtyTrackedFiles: true, hasUntrackedFiles: false, hasLocalOnlyData: true, isMergedIntoBase: false, remotelyRecoverable: false });
+ try {
+ const result = executeHeartbeatRuntime(db, input);
+ if (branch === "expected") {
+ await expect(result).resolves.toMatchObject({ dispatched: true });
+ expect(await finalizations()).toMatchObject([{ status: "succeeded" }]);
+ } else {
+ await expect(result).rejects.toThrow("plugin_workspace_branch_mismatch");
+ expect((await finalizations()).some(row => row.status === "succeeded")).toBe(false);
+ }
+ expect(inspect).toHaveBeenCalledWith(db, undefined, expect.objectContaining({ id: workspace.id, providerRef: workspace.providerRef }));
+ } finally { inspect.mockRestore(); }
+ });
+
it("retains the same-run retry signal without recording a failed workspace", async () => {
const { input, run } = await fixture(true);
await db.update(heartbeatRuns).set({ nativeIssueId: input.task.issueId }).where(eq(heartbeatRuns.id, run.id));
diff --git a/server/src/services/heartbeat/runtime-execution.ts b/server/src/services/heartbeat/runtime-execution.ts
index cc304a6afb..039dbe6934 100644
--- a/server/src/services/heartbeat/runtime-execution.ts
+++ b/server/src/services/heartbeat/runtime-execution.ts
@@ -1,5 +1,6 @@
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
import { writeExecutionControl } from "../execution-control-notifications.js";
+import { inspectPluginWorkspaceForFinalization } from "../native-runtime/native-plugin-workspace-finalization.js";
import { AsyncLocalStorage } from "node:async_hooks";
import { measureRunPhase } from "../execution-preparation-timing.js";
import { parseNativeSessionGoalControl } from "./scheduling.js";
@@ -274,6 +275,7 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe
}
let adapterFinalizeOutcome: "succeeded" | "failed" | null = null;
let preserveRunGatewayTokens = false;
+ let pluginWorkspaceFinalization: Record<string, unknown> | null = null;
const inspectFinalizeWorkspaceBranch = async () => {
const workspaceRecord = persistedExecutionWorkspace?.id
? await executionWorkspacesSvc.getStoredById(
@@ -281,7 +283,10 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe
persistedExecutionWorkspace.id,
)
: persistedExecutionWorkspace;
- if (workspaceRecord?.strategyType !== "git_worktree") return null;
+ pluginWorkspaceFinalization = workspaceRecord
+ ? await inspectPluginWorkspaceForFinalization(db, options.pluginWorkerManager, workspaceRecord, agent.id)
+ : null;
+ if (pluginWorkspaceFinalization || workspaceRecord?.strategyType !== "git_worktree") return null;
const worktreePath =
readNonEmptyString(workspaceRecord.providerRef) ??
@@ -478,6 +483,7 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe
}
}
return { status, metadata: {
+ ...(pluginWorkspaceFinalization ? { pluginWorkspace: pluginWorkspaceFinalization } : {}),
...(finalizeBranchMetadata ? { managedGitWorktreeBranch: finalizeBranchMetadata } : {}),
...(finalizeBranchRepairMetadata ? { managedGitWorktreeBranchRepair: finalizeBranchRepairMetadata } : {}),
} };
@@ -633,6 +639,8 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe
managedGitHub: !useHostGitHub && githubSelection.configured,
billingIdentity: managedAiRuntime ? { provider: managedAiRuntime.attribution.provider, biller: managedAiRuntime.attribution.provider === "openai" ? resolveManagedOpenAiBilling(managedAiRuntime.config.managedAiRouting)?.biller ?? managedAiRuntime.attribution.provider : managedAiRuntime.attribution.provider, billingType: managedAiRuntime.attribution.method === "subscription" ? "subscription_included" : "metered_api" } : undefined,
managedAiCredentialIdentity: managedAiRuntime?.identity,
+ managedAiAccountIdentity: managedAiRuntime?.sessionIdentity,
+ managedAiCredentialWriteback: managedAiRuntime?.credentialWriteback,
managedAiCredentialHome: managedAiRuntime ? String((managedAiRuntime.config.env as Record<string, unknown>).CODEX_HOME) : undefined,
dotWorkspaceRoot: nativeExecution.provider.kind === "openai_dot" && resolvedConfig.dotWorkspaceAccess === true ? executionWorkspace.cwd : undefined,
runnerEnvironment: {
@@ -661,6 +669,7 @@ export async function executeHeartbeatRuntime(db: Db, input: HeartbeatRuntimeExe
}
: {}),
},
+ onTaskDispatched: markDispatchStarted,
runnerExecutionTarget: executionTarget,
runnerIngressAuthorized: isRunnerIngressAuthorized(
nativeRuntimeResolution,
diff --git a/server/src/services/heartbeat/workspace-preparation.test.ts b/server/src/services/heartbeat/workspace-preparation.test.ts
index 490190dd3e..7ab1f9d78f 100644
--- a/server/src/services/heartbeat/workspace-preparation.test.ts
+++ b/server/src/services/heartbeat/workspace-preparation.test.ts
@@ -12,7 +12,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vites
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { environmentRunOrchestrator } from "../environment-run-orchestrator.js";
import { environmentService } from "../environments.js";
-import { executionWorkspaceService } from "../execution-workspaces.js";
+import { executionWorkspaceService, toExecutionWorkspace } from "../execution-workspaces.js";
import { instanceSettingsService } from "../instance-settings.js";
import { workspaceOperationService } from "../workspace-operations.js";
import { nativeWorkspaceSyncInternals, prepareNativeWorkspaceSync } from "../native-runtime/native-workspace-sync.js";
@@ -23,6 +23,7 @@ import { nativeRuntimeContextFixture } from "../native-runtime/runtime-context.t
import * as managedRepositoryCheckout from "../managed-repository-checkout.js";
import { isolatedRemoteSourcePath } from "../isolated-remote-workspace-source.js";
import { cleanupExecutionWorkspaceArtifacts } from "../workspace-runtime.js";
+import { buildProjectMentionHref } from "@paperclipai/shared";
import { trace } from "@opentelemetry/api";
import { buildExecutionWorkspaceAdapterConfig } from "../execution-workspace-policy.js";
import { createLocalDiskStorageProvider } from "../../storage/local-disk-provider.js";
@@ -364,7 +365,7 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",
expect((await readIssue(issue.id)).executionWorkspaceId).toBeNull();
});
- it.each(["sandbox", "ssh", "local", null] as const)("uses the selected %s placement for controller provisioning", async driver => {
+ it.each(["sandbox", "ssh", "plugin", "local", null] as const)("uses the selected %s placement for controller provisioning", async driver => {
const { input, source, issue, envOrchestrator } = await fixture(true);
const marker = join(source, "host-provision-ran");
const provisionCommand = `printf host > '${marker}'`;
@@ -377,11 +378,115 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",
const bound = await readIssue(issue.id);
const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, bound.executionWorkspaceId!));
expect(await readFile(join(workspace.cwd!, "README.md"), "utf8")).toBe("source content\n");
- if (driver === "sandbox" || driver === "ssh") await expect(readFile(marker, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
+ if (driver === "sandbox" || driver === "ssh" || driver === "plugin") await expect(readFile(marker, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
else expect(await readFile(marker, "utf8")).toBe("host");
expect(input.config.mergedConfig).toEqual(originalConfig);
});
+ it("keeps a plugin workspace ledger across runs without preparing Core repositories", async () => {
+ const { input, issue, envOrchestrator, source } = await fixture();
+ input.agent.adapterType = "paperclip_runner";
+ input.environment.selectedEnvironmentForConfig = { ...input.environment.localEnvironment, driver: "plugin" };
+ const guestOnly = join(home, "guest-only", issue.projectId!);
+ await db.update(projectWorkspaces).set({ cwd: guestOnly }).where(eq(projectWorkspaces.id, issue.projectWorkspaceId!));
+ const copy = vi.spyOn(input.services.executionWorkspacesSvc, "prepareTaskRepositoriesForAdmission").mockRejectedValue(new Error("Core must not prepare repositories"));
+ const restoredCopy = vi.spyOn(input.services.executionWorkspacesSvc, "prepareConfiguredRepositoryCopy").mockRejectedValue(new Error("Core must not restore repositories"));
+ const stopped = new Error("Plugin realization boundary");
+ const realize = vi.spyOn(envOrchestrator, "realizeForRun").mockRejectedValue(stopped);
+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toBe(stopped);
+ const firstId = (await readIssue(issue.id)).executionWorkspaceId!;
+ const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, firstId));
+ expect(workspace).toMatchObject({ cwd: `/workspaces/${issue.projectWorkspaceId}`, strategyType: "project_primary", providerType: "adapter_managed" });
+ await reuse(input, toExecutionWorkspace(workspace));
+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toBe(stopped);
+ expect((await readIssue(issue.id)).executionWorkspaceId).toBe(firstId);
+ expect(realize).toHaveBeenCalledTimes(2);
+ expect(copy).not.toHaveBeenCalled(); expect(restoredCopy).not.toHaveBeenCalled();
+ await expect(access(guestOnly)).rejects.toMatchObject({ code: "ENOENT" });
+ input.environment.selectedEnvironmentForConfig = input.environment.localEnvironment;
+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toMatchObject({
+ resultJson: { reason: "plugin_workspace_owner_mismatch" },
+ });
+ expect(realize).toHaveBeenCalledTimes(2);
+ input.environment.selectedEnvironmentForConfig = { ...input.environment.localEnvironment, driver: "plugin" };
+ const [localWorkspace] = await db.update(executionWorkspaces).set({ providerType: "local_fs", cwd: source, metadata: {} })
+ .where(eq(executionWorkspaces.id, firstId)).returning();
+ await reuse(input, toExecutionWorkspace(localWorkspace));
+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toMatchObject({
+ resultJson: { reason: "plugin_workspace_owner_mismatch" },
+ });
+ expect(realize).toHaveBeenCalledTimes(2);
+ expect(await readFile(join(source, "README.md"), "utf8")).toBe("source content\n");
+ });
+
+ it.each(["services", "fresh"] as const)("rejects unsupported %s before plugin workspace preparation or acquisition", async mode => {
+ const { input, envOrchestrator } = await fixture();
+ input.agent.adapterType = "paperclip_runner";
+ input.environment.selectedEnvironmentForConfig = { ...input.environment.localEnvironment, driver: "plugin" };
+ if (mode === "services") input.config.mergedConfig.workspaceRuntime = { services: [{ name: "preview", command: "must-not-run-on-core" }] };
+ else input.task.freshWorkspace = { mode: "fresh_isolated_workspace", retryIntentId: input.run.id,
+ sourceRunId: input.run.id, retainedSourceIds: [] };
+ const acquire = vi.spyOn(envOrchestrator, "acquireForRun");
+ const resolve = vi.spyOn(input.services, "resolveWorkspaceForRun");
+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toMatchObject({
+ resultJson: { reason: mode === "services" ? "plugin_workspace_services_unsupported" : "fresh_workspace_storage_unsupported" },
+ });
+ expect(resolve).not.toHaveBeenCalled();
+ expect(acquire).not.toHaveBeenCalled();
+ });
+
+ it("admits the metadata-only agent-default strategy for a plugin workspace", async () => {
+ const { input, envOrchestrator } = await fixture();
+ input.agent.adapterType = "paperclip_runner";
+ input.environment.selectedEnvironmentForConfig = { ...input.environment.localEnvironment, driver: "plugin" };
+ input.policy.requestedExecutionWorkspaceMode = "agent_default";
+ input.policy.effectiveExecutionWorkspaceMode = "agent_default";
+ const stopped = new Error("Plugin agent-default admission reached");
+ const realize = vi.spyOn(envOrchestrator, "realizeForRun").mockRejectedValue(stopped);
+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toBe(stopped);
+ expect(realize).toHaveBeenCalledWith(expect.objectContaining({ executionWorkspace: expect.objectContaining({ strategy: "adapter_managed", cwd: `/workspaces/${input.task.issueId}` }),
+ persistedExecutionWorkspace: expect.objectContaining({ strategyType: "adapter_managed", providerType: "adapter_managed" }) }));
+ });
+
+ it("rejects Core Git worktree preparation for a plugin-owned workspace", async () => {
+ const { input, envOrchestrator } = await fixture(true);
+ input.agent.adapterType = "paperclip_runner";
+ input.environment.selectedEnvironmentForConfig = { ...input.environment.localEnvironment, driver: "plugin" };
+ const acquire = vi.spyOn(envOrchestrator, "acquireForRun");
+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toMatchObject({
+ code: "workspace_validation_failed", resultJson: { reason: "plugin_workspace_strategy_unsupported" },
+ });
+ expect(acquire).not.toHaveBeenCalled();
+ });
+
+ it.each([true, false])("forwards only authorized plugin project IDs without staging (remote enabled: %s)", async enabled => {
+ const { input, issue, envOrchestrator } = await fixture();
+ vi.stubEnv("PAPERCLIP_MULTI_PROJECT_WORKSPACE_SYNC", "true");
+ vi.stubEnv("PAPERCLIP_MULTI_PROJECT_WORKSPACE_SYNC_REMOTE", String(enabled));
+ input.agent = { ...input.agent, adapterType: "paperclip_runner" };
+ input.environment.selectedEnvironmentForConfig = { ...input.environment.localEnvironment, driver: "plugin" };
+ const [readable, privateProject] = await db.insert(projects).values([
+ { companyId: issue.companyId, name: "Readable reference" },
+ { companyId: issue.companyId, name: "Private reference", visibility: "private" },
+ ]).returning();
+ const unavailableCwd = join(home, readable.id, "must-not-stage");
+ await db.insert(projectWorkspaces).values({ companyId: issue.companyId, projectId: readable.id, name: "Provider-only storage", cwd: unavailableCwd });
+ await db.update(issues).set({ description: [readable, privateProject].map(project => `[project](${buildProjectMentionHref(project.id)})`).join(" ") }).where(eq(issues.id, issue.id));
+ const stopped = new Error("Fixture reached plugin realization");
+ const realize = vi.spyOn(envOrchestrator, "realizeForRun").mockRejectedValue(stopped);
+ try {
+ await expect(prepareHeartbeatWorkspace(db, input)).rejects.toBe(stopped);
+ expect(realize).toHaveBeenCalledWith(expect.objectContaining({
+ runnerTaskProjectIds: enabled ? [issue.projectId, readable.id] : undefined,
+ executionWorkspace: expect.objectContaining({ additionalWorkspaces: [] }),
+ }));
+ await expect(access(unavailableCwd)).rejects.toMatchObject({ code: "ENOENT" });
+ } finally {
+ vi.stubEnv("PAPERCLIP_MULTI_PROJECT_WORKSPACE_SYNC", "true");
+ vi.stubEnv("PAPERCLIP_MULTI_PROJECT_WORKSPACE_SYNC_REMOTE", "true");
+ }
+ });
+
it("checks current repository admission before publishing configured sibling repositories", async () => {
const { input, source, issue } = await fixture();
await db.insert(projectWorkspaces).values({ companyId: issue.companyId, projectId: issue.projectId!,
@@ -526,6 +631,7 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",
it.each([
{ transport: "local", descriptor: "absent" },
{ transport: "ssh", descriptor: "absent" },
+ { transport: "task", descriptor: "absent" },
{ transport: "daytona", descriptor: "valid" },
{ transport: "daytona", descriptor: "absent" },
{ transport: "daytona", descriptor: "corrupt" },
@@ -544,7 +650,8 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",
: transport === "ssh" ? { kind: "remote", transport: "ssh", remoteCwd,
spec: { host: "fixture.invalid", port: 22, username: "fixture", remoteWorkspacePath: remoteCwd,
privateKey: null, knownHosts: null, strictHostKeyChecking: true, remoteCwd } }
- : { kind: "remote", transport: "sandbox", providerKey: "daytona", remoteCwd };
+ : { kind: "remote", transport: "sandbox", providerKey: "daytona", remoteCwd,
+ ...(transport === "task" ? { runnerTask: vi.fn() } : {}) };
const realize = input.services.envOrchestrator.realizeForRun;
vi.spyOn(input.services.envOrchestrator, "realizeForRun").mockImplementation(async args => ({
...await realize(args), executionTarget: target,
@@ -569,7 +676,7 @@ describe.skipIf(!support.supported)("heartbeat workspace preparation boundary",
if (transport !== "daytona" || descriptor === "valid") {
const result = await prepareHeartbeatWorkspace(db, input);
expect(result.executionTarget).toEqual(target);
- if (transport === "ssh") expect(reserve).not.toHaveBeenCalled();
+ if (transport === "ssh" || transport === "task") expect(reserve).not.toHaveBeenCalled();
else expect(reserve).toHaveBeenCalledWith({ companyId: issue.companyId, issueId: issue.id,
workspaceId: first.persistedExecutionWorkspace!.id, cwd: admittedRoot, agentId: input.agent.id, runId: input.run.id });
if (transport !== "daytona") {
diff --git a/server/src/services/heartbeat/workspace-preparation.ts b/server/src/services/heartbeat/workspace-preparation.ts
index a0b4fae0ff..21e0d0c44d 100644
--- a/server/src/services/heartbeat/workspace-preparation.ts
+++ b/server/src/services/heartbeat/workspace-preparation.ts
@@ -215,6 +215,27 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
resolveReusedGitWorkspaceAnchor,
appendRunEvent,
} = input.services;
+ const pluginTaskWorkspace = selectedEnvironmentForConfig?.driver === "plugin" && agent.adapterType === "paperclip_runner";
+ if (fresh && !isDotRun && pluginTaskWorkspace) {
+ throw new WorkspaceValidationFailure("A fresh attempt is unavailable for this workspace storage provider. The existing workspace is retained.",
+ { reason: "fresh_workspace_storage_unsupported" });
+ }
+ const pluginConfig = parseObject(selectedEnvironmentForConfig?.config);
+ const taskWorkspaceOwner = pluginTaskWorkspace ? { agentId: agent.id, environmentId: selectedEnvironmentForConfig.id,
+ pluginKey: pluginConfig.pluginKey ?? null, driverKey: pluginConfig.driverKey ?? null } : null;
+ for (const workspace of [existingExecutionWorkspace, reusableExistingExecutionWorkspace]) {
+ const owner = parseObject(workspace?.metadata?.runnerTaskWorkspaceOwner);
+ if ((pluginTaskWorkspace && workspace && workspace.providerType !== "plugin" && Object.keys(owner).length === 0)
+ || (Object.keys(owner).length > 0 && (!taskWorkspaceOwner || Object.entries(taskWorkspaceOwner).some(([key, value]) => owner[key] !== value)))) {
+ throw new WorkspaceValidationFailure("The retained workspace belongs to a different agent, environment, or storage provider.",
+ { reason: "plugin_workspace_owner_mismatch" });
+ }
+ }
+ const workspaceServices = parseObject(mergedConfig.workspaceRuntime).services;
+ if (pluginTaskWorkspace && Array.isArray(workspaceServices) && workspaceServices.length > 0) {
+ throw new WorkspaceValidationFailure("The selected plugin environment does not support Core workspace services.",
+ { reason: "plugin_workspace_services_unsupported" });
+ }
const {
selectedEnvironmentDriver: lowTrustPreflightEnvironmentDriver,
workspace: resolvedWorkspace,
@@ -249,7 +270,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
return { cwd, source: "agent_home" as const, projectId: null, workspaceId: null, repoUrl: null, repoRef: null,
workspaceHints: [], warnings: [], baseCwdFallback: false, materializationFailures: [], additionalWorkspaces: [], referencedProjectFailures: [] };
}
- if (useIsolatedTaskDirectory && issueRef) {
+ if (useIsolatedTaskDirectory && issueRef && !pluginTaskWorkspace) {
const cwd = await materializeIsolatedTaskDirectory({
companyId: agent.companyId,
issueId: issueRef.id,
@@ -282,7 +303,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
},
});
}
- if (nativeChatWorkspaceScope && !nativeChatWorkspaceScope.projectId) {
+ if (nativeChatWorkspaceScope && !nativeChatWorkspaceScope.projectId && !pluginTaskWorkspace) {
const cwd = await materializeNativeChatTaskRoot(
nativeChatWorkspaceScope,
);
@@ -309,7 +330,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
useProjectWorkspace:
requestedExecutionWorkspaceMode !== "agent_default",
configuredCwd: readNonEmptyString(mergedConfig.cwd),
- anchorWorkspace: requestedShouldReuseExisting && reusableExistingExecutionWorkspace?.strategyType === "git_worktree"
+ anchorWorkspace: !pluginTaskWorkspace && requestedShouldReuseExisting && reusableExistingExecutionWorkspace?.strategyType === "git_worktree"
? await resolveReusedGitWorkspaceAnchor({
agent,
workspace: reusableExistingExecutionWorkspace,
@@ -346,6 +367,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
? {
...workspace,
additionalWorkspaces: [],
+ runnerTaskProjectIds: undefined,
referencedProjectFailures: [],
}
: workspace;
@@ -388,7 +410,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
sourceWorkspaceId: resolvedWorkspace.workspaceId,
boundWorkspace: reusableExistingExecutionWorkspace ?? existingExecutionWorkspace,
}));
- const skipHostProvision = copyOnlyProvisioning || hostProvisionDriver === "sandbox" || hostProvisionDriver === "ssh";
+ const skipHostProvision = copyOnlyProvisioning || hostProvisionDriver === "sandbox" || hostProvisionDriver === "ssh" || hostProvisionDriver === "plugin";
const hostExecutionWorkspaceConfig = isDotRun ? {} :
stripHostWorkspaceProvision({
config: fresh ? { ...mergedConfig, workspaceStrategy: { type: "project_primary" } } : mergedConfig,
@@ -403,6 +425,11 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
repoRef: resolvedWorkspace.repoRef,
additionalWorkspaces: resolvedWorkspace.additionalWorkspaces,
} satisfies ExecutionWorkspaceInput;
+ const latestWorkspaceStrategyType = resolveEffectiveWorkspaceStrategyType(requestedExecutionWorkspaceMode, hostExecutionWorkspaceConfig);
+ if (pluginTaskWorkspace && !pluginPrepared && latestWorkspaceStrategyType === "git_worktree") {
+ throw new WorkspaceValidationFailure("The selected plugin environment does not support Core Git worktree preparation.",
+ { reason: "plugin_workspace_strategy_unsupported" });
+ }
if (!pluginPrepared) await timeWorkspace("workspace_base_validation", () => assertGitWorktreeBaseWorkspaceReady({
requestedExecutionWorkspaceMode,
config: hostExecutionWorkspaceConfig,
@@ -421,10 +448,6 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
Object.keys(workspaceStrategyForFingerprint).length > 0
? workspaceStrategyForFingerprint
: null;
- const latestWorkspaceStrategyType = resolveEffectiveWorkspaceStrategyType(
- requestedExecutionWorkspaceMode,
- hostExecutionWorkspaceConfig,
- );
const selectedEnvironmentConfigForFingerprint = parseObject(
selectedEnvironmentForConfig?.config,
);
@@ -513,6 +536,11 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
requestedShouldReuseExisting,
workspaceConfigFreshness,
});
+ if (pluginTaskWorkspace && !pluginPrepared && workspaceReuseProvisioningPolicy.shouldRestoreExistingWorkspace
+ && reusableExistingExecutionWorkspace?.strategyType === "git_worktree") {
+ throw new WorkspaceValidationFailure("The selected plugin environment cannot reuse a Core Git worktree.",
+ { reason: "plugin_workspace_strategy_unsupported" });
+ }
const workspaceOperationRecorder = workspaceOperationsSvc.createRecorder({
companyId: agent.companyId,
heartbeatRunId: run.id,
@@ -565,7 +593,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
warnings: [], created: false, branchCreatedByRuntime: false,
baseRefSha: pluginPrepared.metadata?.workspaceProviderBaseSha as string | null,
} as RealizedExecutionWorkspace, reusedExecutionWorkspace: Boolean(reusableExistingExecutionWorkspace), policy: workspaceReuseProvisioningPolicy }
- : isDotRun ? { executionWorkspace: { ...executionWorkspaceBase, strategy: "project_primary" as const, cwd: resolvedWorkspace.cwd, branchName: null, worktreePath: null, warnings: [], created: false, branchCreatedByRuntime: false } as RealizedExecutionWorkspace, reusedExecutionWorkspace: false, policy: workspaceReuseProvisioningPolicy } : await timeWorkspace("workspace_provision", () => provisionExecutionWorkspaceForFreshnessDecision<RealizedExecutionWorkspace>(
+ : isDotRun || pluginTaskWorkspace ? { executionWorkspace: { ...executionWorkspaceBase, strategy: pluginTaskWorkspace ? latestWorkspaceStrategyType : "project_primary" as const, cwd: resolvedWorkspace.cwd, branchName: null, worktreePath: null, warnings: [], created: false, branchCreatedByRuntime: false } as RealizedExecutionWorkspace, reusedExecutionWorkspace: pluginTaskWorkspace && workspaceReuseProvisioningPolicy.shouldRestoreExistingWorkspace && Boolean(reusableExistingExecutionWorkspace), policy: workspaceReuseProvisioningPolicy } : await timeWorkspace("workspace_provision", () => provisionExecutionWorkspaceForFreshnessDecision<RealizedExecutionWorkspace>(
{
requestedShouldReuseExisting,
existingExecutionWorkspaceId:
@@ -814,6 +842,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
const nextExecutionWorkspaceMetadata = {
...baseExecutionWorkspaceMetadata,
...(pluginPrepared?.metadata ?? {}),
+ ...(taskWorkspaceOwner && !pluginPrepared ? { runnerTaskWorkspaceOwner: taskWorkspaceOwner } : {}),
...(copyOnlyProvisioning ? { [CONTROLLER_PROVISION_COPY_ONLY]: true } : {}),
...(persistedWorktreeInstanceRoot
? {
@@ -839,7 +868,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
repoUrl: executionWorkspace.repoUrl,
baseRef: executionWorkspace.repoRef,
branchName: branchNameForInitialPersistence,
- providerType:
+ providerType: pluginTaskWorkspace ? "adapter_managed" :
executionWorkspace.strategy === "git_worktree"
? "git_worktree"
: "local_fs",
@@ -868,7 +897,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
: requestedExecutionWorkspaceMode === "agent_default"
? "adapter_managed"
: "shared_workspace",
- strategyType:
+ strategyType: pluginTaskWorkspace ? latestWorkspaceStrategyType :
executionWorkspace.strategy === "git_worktree"
? "git_worktree"
: "project_primary",
@@ -881,7 +910,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
repoUrl: executionWorkspace.repoUrl,
baseRef: executionWorkspace.repoRef,
branchName: branchNameForInitialPersistence,
- providerType:
+ providerType: pluginTaskWorkspace ? "adapter_managed" :
executionWorkspace.strategy === "git_worktree"
? "git_worktree"
: "local_fs",
@@ -977,14 +1006,14 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
}
await bindIssueToPersistedExecutionWorkspace(persistedExecutionWorkspace);
const projectRepositoryPaths: string[] = [];
- if (!pluginPrepared && !isDotRun && persistedExecutionWorkspace && issueId && !persistedNativeExecutionInput && !nativeRecoveryExecutionWorkspaceId) {
+ if (!pluginPrepared && !pluginTaskWorkspace && !isDotRun && persistedExecutionWorkspace && issueId && !persistedNativeExecutionInput && !nativeRecoveryExecutionWorkspaceId) {
const taskRepositories = await timeWorkspace("workspace_repository_admission", () =>
executionWorkspacesSvc.prepareTaskRepositoriesForAdmission({ companyId: agent.companyId,
issueId, workspaceId: persistedExecutionWorkspace!.id, cwd: executionWorkspace.cwd,
agentId: agent.id, runId: run.id, responsibleUserId }));
projectRepositoryPaths.push(...taskRepositories.map(repository => repository.relativePath));
}
- if (!pluginPrepared && executionWorkspace.projectId
+ if (!pluginPrepared && !pluginTaskWorkspace && executionWorkspace.projectId
&& (resolvedWorkspace.source === "project_primary" || Boolean(reusableExistingExecutionWorkspace?.projectWorkspaceId))
&& !resolvedWorkspace.baseCwdFallback && !persistedNativeExecutionInput && !nativeRecoveryExecutionWorkspaceId) {
const repositoryRows = await db.select().from(projectWorkspaces).where(and(
@@ -1051,6 +1080,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
adapterType: agent.adapterType,
adapterConfig: parseObject(agent.adapterConfig),
admittedLifecycleMode: persistedNativeExecutionInput?.session.lifecyclePolicy.mode,
+ recoverPluginTask: runOptions.nativeRestartRecovery?.kind === "resume_dead_runner" || runOptions.nativeRestartRecovery?.kind === "bootstrap_incomplete",
issueId: issueId ?? null,
heartbeatRunId: run.id,
agentId: agent.id,
@@ -1147,6 +1177,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
executionWorkspace,
effectiveExecutionWorkspaceMode,
persistedExecutionWorkspace,
+ runnerTaskProjectIds: resolvedWorkspace.runnerTaskProjectIds,
duplexObservabilityRecorder,
}));
nativeRunnerPreparationSpans.push({
@@ -1181,8 +1212,9 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace
await bindIssueToPersistedExecutionWorkspace(persistedExecutionWorkspace);
const workspaceRealization = realizationResult.workspaceRealization;
const executionTarget = realizationResult.executionTarget;
- if (!pluginPrepared && !isDotRun && issueId && (persistedNativeExecutionInput || nativeRecoveryExecutionWorkspaceId)
- && !(executionTarget?.kind === "remote" && executionTarget.transport === "ssh")) {
+ if (!pluginPrepared && !pluginTaskWorkspace && !isDotRun && issueId && (persistedNativeExecutionInput || nativeRecoveryExecutionWorkspaceId)
+ && !(executionTarget?.kind === "remote" && (executionTarget.transport === "ssh"
+ || (executionTarget.transport === "sandbox" && executionTarget.runnerTask)))) {
const workspaceId = persistedNativeExecutionInput?.binding.executionWorkspaceId ?? nativeRecoveryExecutionWorkspaceId!;
const reference = readNativeWorkspaceSyncReference(parseObject(run.runnerProfileJson).nativeWorkspaceSync);
if (!reference && executionTarget?.kind === "remote" && executionTarget.transport === "sandbox") {
diff --git a/server/src/services/heartbeat/workspaces.test.ts b/server/src/services/heartbeat/workspaces.test.ts
index bad33936d0..ee48bdf31d 100644
--- a/server/src/services/heartbeat/workspaces.test.ts
+++ b/server/src/services/heartbeat/workspaces.test.ts
@@ -127,6 +127,37 @@ describe("heartbeat workspace module", () => {
expect(await fs.stat(missingCwd).catch(() => null)).toBeNull();
});
+ it("resolves plugin project identity without Core files", async () => {
+ const repoUrl = "/unavailable-controller-source.git";
+ const missingCwd = path.join(testRoot, "exists-only-on-plugin");
+ const configured = { ...workspace("selected", "project-one", missingCwd), repoUrl };
+ const database = databaseWithResults([configured], [{ id: "project-one" }]);
+ const stat = vi.spyOn(fs, "stat"); const mkdir = vi.spyOn(fs, "mkdir");
+ try {
+ const result = await createHeartbeatWorkspaceResolver(database.db).resolveWorkspaceForRun(
+ { ...agent(), adapterType: "paperclip_runner" }, { projectId: "project-one" }, null,
+ { executionEnvironmentDriver: "plugin" });
+ expect(result).toMatchObject({ cwd: "/workspaces/selected", projectId: "project-one", workspaceId: "selected", repoUrl,
+ source: "project_primary", baseCwdFallback: false, additionalWorkspaces: [] });
+ expect(stat).not.toHaveBeenCalled(); expect(mkdir).not.toHaveBeenCalled();
+ } finally { stat.mockRestore(); mkdir.mockRestore(); }
+ });
+ it("keeps a projectless plugin scope without creating an agent directory on Core", async () => {
+ const mkdir = vi.spyOn(fs, "mkdir");
+ try {
+ const result = await createHeartbeatWorkspaceResolver(databaseWithResults().db).resolveWorkspaceForRun(
+ { ...agent(), adapterType: "paperclip_runner" }, {}, null, { executionEnvironmentDriver: "plugin" });
+ expect(result).toMatchObject({ cwd: "/workspaces/agent-one", projectId: null, workspaceId: null });
+ expect(mkdir).not.toHaveBeenCalled();
+ } finally { mkdir.mockRestore(); }
+ });
+ it("rejects plugin project scope outside the company", async () => {
+ const database = databaseWithResults([], []);
+ await expect(createHeartbeatWorkspaceResolver(database.db).resolveWorkspaceForRun(
+ { ...agent(), adapterType: "paperclip_runner" }, { projectId: "foreign" }, null,
+ { executionEnvironmentDriver: "plugin" })).rejects.toMatchObject({ code: "workspace_validation_failed" });
+ });
+
it("fails closed with workspace diagnostics when a configured directory is unavailable", async () => {
const missingCwd = path.join(testRoot, "missing-configured-workspace");
const database = databaseWithResults([workspace("selected", "project-one", missingCwd)]);
diff --git a/server/src/services/heartbeat/workspaces.ts b/server/src/services/heartbeat/workspaces.ts
index 90ac28d9f0..fa12c39490 100644
--- a/server/src/services/heartbeat/workspaces.ts
+++ b/server/src/services/heartbeat/workspaces.ts
@@ -1343,6 +1343,8 @@ export type ResolvedWorkspaceForRun = {
* workspace only, exactly as before.
*/
additionalWorkspaces: ResolvedAdditionalWorkspace[];
+ /** Authorized project IDs for plugin-owned storage; no Core filesystem staging. */
+ runnerTaskProjectIds?: string[];
/**
* Structured record of every referenced project that the run dropped or failed, paired with the
* layer that dropped it. Run preparation reads this to emit the requested-vs-synced observability
@@ -1354,7 +1356,7 @@ export type ResolvedWorkspaceForRun = {
/** The anchor workspace shape, before the additional referenced workspaces are attached. */
type ResolvedAnchorWorkspaceForRun = Omit<
ResolvedWorkspaceForRun,
- "additionalWorkspaces" | "referencedProjectFailures"
+ "additionalWorkspaces" | "referencedProjectFailures" | "runnerTaskProjectIds"
>;
/**
@@ -3404,7 +3406,7 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
agent: typeof agents.$inferSelect,
context: Record<string, unknown>,
previousSessionParams: Record<string, unknown> | null,
- opts?: { useProjectWorkspace?: boolean | null; configuredCwd?: string | null },
+ opts?: { useProjectWorkspace?: boolean | null; configuredCwd?: string | null; executionEnvironmentDriver?: string | null },
): Promise<ResolvedAnchorWorkspaceForRun> {
const issueId =
readNonEmptyString(context.issueId) ?? readNonEmptyString(context.taskId);
@@ -3473,6 +3475,24 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
repoRef: readNonEmptyString(workspace.repoRef),
}));
+ if (opts?.executionEnvironmentDriver === "plugin" && agent.adapterType === "paperclip_runner") {
+ if (workspaceProjectId) {
+ const project = await db.select({ id: projects.id }).from(projects).where(and(
+ eq(projects.companyId, agent.companyId), eq(projects.id, workspaceProjectId),
+ )).then(rows => rows[0] ?? null);
+ if (!project) throw new WorkspaceValidationFailure("The selected plugin project is unavailable.", { reason: "plugin_project_unavailable" });
+ }
+ if (configuredSourceId && projectWorkspaceRows.length === 0) {
+ throw new WorkspaceValidationFailure("The selected project workspace is unavailable.", { reason: "configured_workspace_unavailable" });
+ }
+ const selected = projectWorkspaceRows[0];
+ // This is a logical scope. Preparation resolves the execution-host path.
+ return { cwd: `/workspaces/${selected?.id ?? issueId ?? agent.id}`, source: workspaceProjectId ? "project_primary" : issueId ? "task_session" : "agent_home",
+ projectId: workspaceProjectId ?? null, workspaceId: selected?.id ?? null,
+ repoUrl: selected?.repoUrl ?? null, repoRef: selected?.repoRef ?? null,
+ workspaceHints, warnings: [], baseCwdFallback: false, materializationFailures: [] };
+ }
+
if (projectWorkspaceRows.length > 0 || configuredSourceId) {
const preferredWorkspace = preferredProjectWorkspaceId
? (projectWorkspaceRows.find(
@@ -3682,6 +3702,21 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
readNonEmptyString(context.issueId) ?? readNonEmptyString(context.taskId);
const responsibleUserId = readNonEmptyString(context.responsibleUserId)
?? readNonEmptyString(context.responsible_user_id);
+ const referencedOptions: ResolveRunReferencedProjectsOptions = {
+ companyId: agent.companyId,
+ actor: { type: "agent", agentId: agent.id, companyId: agent.companyId, source: "agent_key",
+ runId: readNonEmptyString(context.executionIdentityRunId),
+ onBehalfOfUserId: responsibleUserId === "local-board" ? null : responsibleUserId },
+ issues: issueService(db), projects: projectService(db), access: authorizationService(db),
+ };
+ if (executionEnvironmentDriver === "plugin" && agent.adapterType === "paperclip_runner" &&
+ issueId && isMultiProjectWorkspaceSyncRemoteEnabled()) {
+ const referenced = await resolveRunReferencedProjects(issueId, anchor.projectId, referencedOptions);
+ return { ...anchor, additionalWorkspaces: [],
+ runnerTaskProjectIds: [anchor.projectId, ...referenced.additional.map(project => project.projectId)]
+ .filter((id): id is string => id !== null),
+ referencedProjectFailures: referenced.failures, warnings: [...anchor.warnings, ...referenced.warnings] };
+ }
const resolveGitAuth = createGitRemoteAuthProvider(db, agent.companyId, {
issueId,
heartbeatRunId: readNonEmptyString(context.executionIdentityRunId),
@@ -3698,18 +3733,7 @@ export function createHeartbeatWorkspaceResolver(db: Db) {
executionEnvironmentDriver,
),
remoteReferencedSyncEnabled: isMultiProjectWorkspaceSyncRemoteEnabled(),
- companyId: agent.companyId,
- actor: {
- type: "agent",
- agentId: agent.id,
- companyId: agent.companyId,
- source: "agent_key",
- runId: readNonEmptyString(context.executionIdentityRunId),
- onBehalfOfUserId: responsibleUserId === "local-board" ? null : responsibleUserId,
- },
- issues: issueService(db),
- projects: projectService(db),
- access: authorizationService(db),
+ ...referencedOptions,
resolveProjectWorkspace: (project) =>
resolveAdditionalProjectWorkspace(
{ companyId: agent.companyId, project },
diff --git a/server/src/services/native-runtime/native-finalization-reconciler.ts b/server/src/services/native-runtime/native-finalization-reconciler.ts
index da49986802..ec391457b0 100644
--- a/server/src/services/native-runtime/native-finalization-reconciler.ts
+++ b/server/src/services/native-runtime/native-finalization-reconciler.ts
@@ -1,3 +1,4 @@
+import type { WorkspaceWorkers } from "../plugin-workspaces.js";
import { recoverLegacyUnsafeWorkspaceExports } from "./native-workspace-export-recovery.js";
import { hasPendingNativeChildCompletion } from "./native-child-completion-delivery.js";
import { dismissAutomaticCompletionReviews, decisionHasRetiredAutomaticReview } from "./automatic-completion-reviews.js";
@@ -626,6 +627,7 @@ export async function claimNativeSessionResumptions(input: {
}
type NativeReconciliationOptions = {
+ pluginWorkerManager?: WorkspaceWorkers;
environmentRuntime?: EnvironmentRuntimeService;
onWorkspaceSettled?: (input: {
runId: string;
@@ -1042,6 +1044,7 @@ async function reconcileNativeFinalizationsPass(
db,
runId: row.runId,
environmentRuntime: options.environmentRuntime,
+ pluginWorkerManager: options.pluginWorkerManager,
});
// Busy is ownership, not another failed export or retry-budget debit.
if (!operation) continue;
@@ -1051,11 +1054,13 @@ async function reconcileNativeFinalizationsPass(
const unrecoverable = operation.stderrExcerpt?.includes(
"workspace_sync_out_unrecoverable",
);
+ const pluginFailure = operation.stderrExcerpt?.trim();
+ const pluginRepair = pluginFailure === "plugin_workspace_branch_mismatch" || pluginFailure === "plugin_workspace_owner_mismatch";
const failure = await recordNativeFinalizationFailure({
db,
runId: row.runId,
error: new Error(
- unrecoverable
+ pluginRepair ? `native_${pluginFailure}` : unrecoverable
? "native_workspace_sync_out_unrecoverable"
: "native_workspace_sync_out_failed",
),
diff --git a/server/src/services/native-runtime/native-plugin-workspace-finalization.ts b/server/src/services/native-runtime/native-plugin-workspace-finalization.ts
new file mode 100644
index 0000000000..3d94e756df
--- /dev/null
+++ b/server/src/services/native-runtime/native-plugin-workspace-finalization.ts
@@ -0,0 +1,25 @@
+import type { Db, executionWorkspaces } from "@paperclipai/db";
+import { inspectPluginWorkspace, type WorkspaceWorkers } from "../plugin-workspaces.js";
+
+/** Validate retained plugin files without interpreting a provider reference as a Core path. */
+export async function inspectPluginWorkspaceForFinalization(
+ db: Db,
+ workers: WorkspaceWorkers | undefined,
+ workspace: typeof executionWorkspaces.$inferSelect,
+ agentId: string,
+): Promise<Record<string, unknown> | null> {
+ if (workspace.providerType === "plugin") {
+ const inspection = await inspectPluginWorkspace(db, workers, workspace);
+ if (workspace.strategyType === "git_worktree"
+ && (!workspace.branchName || inspection.branchName !== workspace.branchName)) {
+ throw new Error("plugin_workspace_branch_mismatch");
+ }
+ return { providerType: workspace.providerType, inspection };
+ }
+ const owner = workspace.metadata?.runnerTaskWorkspaceOwner;
+ if (workspace.providerType === "adapter_managed" && owner && typeof owner === "object" && !Array.isArray(owner)) {
+ if ((owner as Record<string, unknown>).agentId !== agentId) throw new Error("plugin_workspace_owner_mismatch");
+ return { providerType: workspace.providerType, owner };
+ }
+ return null;
+}
diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts
index 2e3229fe01..25e29408be 100644
--- a/server/src/services/native-runtime/native-restart-recovery.ts
+++ b/server/src/services/native-runtime/native-restart-recovery.ts
@@ -11,6 +11,7 @@ import { and, desc, eq, inArray, isNotNull, isNull, lte, or, sql } from "drizzle
import type { Db } from "@paperclipai/db";
import {
agents,
+ environmentLeases,
heartbeatRunEvents,
heartbeatRuns,
issues,
@@ -627,11 +628,16 @@ export async function claimNativeRestartRecoveries(input: {
const remoteWorkspace = readNativeWorkspaceSyncReference(
profile.nativeWorkspaceSync,
);
+ const [pluginTask] = await tx.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
+ eq(environmentLeases.companyId, row.run.companyId), eq(environmentLeases.heartbeatRunId, row.run.id),
+ sql`${environmentLeases.metadata}->>'runnerTaskLease' = 'true'`,
+ )).limit(1);
const remoteSandbox = profile.nativeWorkspaceSync != null;
+ const remoteProcess = remoteSandbox || !!pluginTask;
const runnerPidAlive =
- !remoteSandbox && processIsAlive(row.run.processPid);
+ !remoteProcess && processIsAlive(row.run.processPid);
const runnerGroupAlive =
- !remoteSandbox && processGroupIsAlive(row.run.processGroupId);
+ !remoteProcess && processGroupIsAlive(row.run.processGroupId);
const observedRunnerStart =
row.run.processPid && runnerPidAlive
? await observedProcessStart(row.run.processPid)
@@ -754,7 +760,7 @@ export async function claimNativeRestartRecoveries(input: {
}
}
const providerProcesses = await evaluateNativeProviderProcesses({
- identities: (remoteSandbox ? [] : providerProcessIdentities).filter(
+ identities: (remoteProcess ? [] : providerProcessIdentities).filter(
(identity) => identity.pid !== row.run.processPid,
),
});
diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts
index 61f97aefb8..ae77de9063 100644
--- a/server/src/services/native-runtime/native-run-finalizer.ts
+++ b/server/src/services/native-runtime/native-run-finalizer.ts
@@ -601,6 +601,9 @@ export async function recordNativeFinalizationFailure(input: {
message,
nextAction:
input.failureScope === "workspace"
+ && (message === "native_plugin_workspace_branch_mismatch" || message === "native_plugin_workspace_owner_mismatch")
+ ? "Repair the plugin workspace branch or owner, then resume finalization without another provider turn."
+ : input.failureScope === "workspace"
? input.permanent
? "Restore the exact sandbox containing the unexported workspace changes, or resolve the task manually from durable evidence."
: "Retry workspace export and merge from the retained sandbox; do not submit another provider turn."
diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts
index 682186ee2f..98605fe1e8 100644
--- a/server/src/services/native-runtime/native-session-executor.test.ts
+++ b/server/src/services/native-runtime/native-session-executor.test.ts
@@ -1,3 +1,6 @@
+import * as environmentTaskRuntime from "../environment-task-runtime.js";
+import * as pluginTaskRuntime from "./plugin-runner-task.js";
+import { environmentTaskOperationSchema } from "@paperclipai/plugin-sdk";
import { trace } from "@opentelemetry/api";
import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace";
import { configuredEnvironment, configuredEnvironmentProjection } from "../../vendor/paperclip-runner/index.js";
@@ -25,7 +28,7 @@ import {
import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
import { tmpdir } from "node:os";
import { inspect } from "node:util";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import {
heartbeatRuns,
heartbeatRunEvents,
@@ -11022,6 +11025,96 @@ describe("runnerd provider runtime wiring", () => {
}
});
+ it.each(["verified", "wrong-state", "no-stop-proof"] as const)("admits only an authorized same-run plugin crash checkpoint: %s", async mode => {
+ const current = scopedNativeExecution(`plugin-crash-${mode}`);
+ const identity = { runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!,
+ runnerInstanceId: "plugin-runner", environmentLeaseId: "old-task-lease", turnId: "old-turn", itemId: "old-item" };
+ const root = await initializeScopedRunnerRoot(current, identity.runnerInstanceId);
+ await mkdir(join(root, "control-plane"), { recursive: true });
+ const journal = JSON.stringify(durableControlPlaneState(identity));
+ await writeFile(join(root, "control-plane/control-plane-state.json"), journal);
+ const resume = vi.spyOn(environmentTaskRuntime, "resolvePluginTaskResume").mockImplementation(async () => {
+ if (mode === "no-stop-proof") throw new Error("Plugin Runner retained session is not authorized");
+ return "prior-task";
+ });
+ const task = vi.fn(async (operation: any) => {
+ environmentTaskOperationSchema.parse(operation);
+ if (operation.kind === "read_state") return { kind: "state", taskId: "next-task", state: {
+ ...durableRunnerState(identity, "ready"), ...(mode === "wrong-state" ? { itemId: "other" } : {}),
+ } };
+ return { kind: "description", launchPreparationVersion: 1, projectAuthCheckVersion: 1, taskId: "next-task",
+ runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } };
+ });
+ state.createBackend.mockClear();
+ try {
+ const backend = createRunnerdBackend({ db: leaseDb(current), execution: current, runnerInstanceId: identity.runnerInstanceId,
+ runnerIngressAuthorized: true, runnerExecutionTarget: { kind: "remote", transport: "sandbox", remoteCwd: ".", leaseId: "new-task-lease", runnerTask: task },
+ restartRecovery: { kind: "resume_dead_runner", runId: current.binding.runId, leaseOwner: "controller", controllerGeneration: 2,
+ providerAttempt: 2, restartKind: "hard", recoveryRequestId: null } });
+ if (mode === "verified") {
+ await expect(backend).resolves.toBeDefined();
+ expect(state.createBackend).toHaveBeenCalledOnce();
+ expect(JSON.parse(await readFile(join(root, "plugin-runner-state.json"), "utf8"))).toMatchObject({ ...identity, lifecycle: "ready" });
+ } else {
+ await expect(backend).rejects.toThrow(mode === "wrong-state" ? "checkpoint identity mismatch" : "not authorized");
+ expect(state.createBackend).not.toHaveBeenCalled();
+ }
+ expect(await readFile(join(root, "control-plane/control-plane-state.json"), "utf8")).toBe(journal);
+ if (mode === "no-stop-proof") expect(task).not.toHaveBeenCalled();
+ else expect(task).toHaveBeenCalledWith({ kind: "read_state", identity, resumeFrom: "prior-task" });
+ } finally { resume.mockRestore(); }
+ });
+
+ it.each(["codex", "opencode", "acpx"] as const)("uses a task-only %s driver without exposing Core paths or transferring the agent home", async (kind) => {
+ const taskExecution = { ...execution, provider: kind === "codex" ? execution.provider
+ : kind === "opencode" ? { kind, model: "openai/test", permissionMode: "deny" }
+ : { kind, agent: "claude", model: "claude-sonnet-4-6", permissionMode: "deny-all", claudeEffort: "high" } } as NativeExecutionInput;
+ const assignedMcpTools = { definitions: () => [], has: () => false, execute: vi.fn() };
+ state.createAssignedMcpTools.mockResolvedValueOnce(assignedMcpTools);
+ const launcher = vi.fn();
+ const registration = vi.fn();
+ const driver = { prepareLaunch: vi.fn(), runnerProcessLauncher: launcher, controlPlaneRegistration: registration };
+ const owner = vi.spyOn(pluginTaskRuntime, "createPluginRunnerTaskOwner").mockReturnValue({ launcher, registration, driver });
+ const task = vi.fn(async (operation: unknown) => {
+ environmentTaskOperationSchema.parse(operation);
+ return { kind: "description", launchPreparationVersion: 1, projectAuthCheckVersion: 1, taskId: "task", runner: { version: "fixture", digest: `sha256:${"a".repeat(64)}` } };
+ });
+ const target = { kind: "remote", transport: "sandbox", providerKey: "plugin", leaseId: "plugin-task-lease",
+ remoteCwd: "/unused", runnerTask: task, runnerTaskProjectIds: ["10000000-0000-4000-8000-000000000001"] } as const;
+ const updates: Array<{ table: unknown; values: Record<string, unknown> }> = [];
+ state.createBackend.mockClear(); state.createTransport.mockClear();
+ try {
+ await expect(createRunnerdBackend({ db: leaseDb(execution), execution: taskExecution, runnerInstanceId: "runner", runnerExecutionTarget: target }))
+ .rejects.toThrow("runner_ingress_unavailable");
+ await createRunnerdBackend({ db: leaseDb(execution, {}, {}, updates), execution: taskExecution, runnerInstanceId: "runner", runnerExecutionTarget: target,
+ runnerIngressAuthorized: true,
+ runnerEnvironment: { HOME: "/controller/private", PATH: "/controller/bin", OPENAI_API_KEY: "fixture-secret",
+ PAPERCLIP_NATIVE_MCP_NAME: "assigned", PAPERCLIP_NATIVE_MCP_URL: "http://localhost/mcp/gateways/assigned-test",
+ PAPERCLIP_NATIVE_MCP_TOKEN: "fixture-mcp-secret" } });
+ expect(state.toolAuthorityDefinitions).toHaveBeenCalledWith(expect.objectContaining({ assignedMcpTools }));
+ expect(state.createAssignedMcpTools).toHaveBeenCalledWith(expect.objectContaining({ gatewayPublicId: "assigned-test", bearerToken: "fixture-mcp-secret" }));
+ expect(owner).toHaveBeenCalledWith(expect.objectContaining({ task, projectIds: target.runnerTaskProjectIds,
+ credentialIdentity: undefined }));
+ expect(state.createBackend.mock.calls.at(-1)![1]).toMatchObject({ workingDirectoryAuthority: "remote_runner", environment: {} });
+ state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!();
+ const options = state.createTransport.mock.calls.at(-1)![0];
+ expect(options).toMatchObject({ ...driver, runnerArtifact: { version: "fixture" },
+ prpIdentity: { environmentLeaseId: "plugin-task-lease" } });
+ if (kind === "acpx") expect(options).toMatchObject({ acpxAgent: "claude", claudeEffort: "high" });
+ for (const key of ["environment", "codexCommand", "codexArgs", "runnerRuntimePaths", "readRunnerState", "archiveExternalRunnerState"]) {
+ expect(options).not.toHaveProperty(key);
+ }
+ expect(task.mock.calls).toEqual([[{ kind: "describe" }]]);
+ expect(owner.mock.calls.at(-1)![0]).not.toHaveProperty("assets");
+ const identity: Record<string, unknown> = options.prpIdentity!;
+ await owner.mock.calls.at(-1)![0].onSessionRetained!({ schema: "paperclip.runner.durable.state.v1", lifecycle: "suspended", ...identity });
+ const metadata = updates.find(update => update.values.metadata)?.values.metadata as SQL;
+ expect(JSON.parse(new PgDialect().sqlToQuery(metadata).params[0] as string)).toMatchObject({
+ runnerTaskIdentity: { turnId: identity.turnId, itemId: identity.itemId },
+ });
+ } finally { owner.mockRestore(); }
+ });
+
it("keeps assigned MCP credentials on the control plane for remote Codex", async () => {
const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test");
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index 60d6e9a1d4..962ab16599 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -2,6 +2,11 @@ import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
import { writeExecutionControl } from "../execution-control-notifications.js";
import { notifyExecutionRunWork } from "../execution-control-notifications.js";
import { createRunUsageRecorder } from "../usage-receipts.js";
+import { registerPluginTaskCredentialHandoff, type PluginTaskCredentialWritebackBinding } from "../plugin-task-credential-writeback.js";
+import { resolvePluginTaskResume } from "../environment-task-runtime.js";
+import { environmentTaskResultSchema } from "@paperclipai/plugin-sdk";
+import { preparePluginRunnerCredentials } from "./plugin-runner-credentials.js";
+import { createPluginRunnerTaskOwner } from "./plugin-runner-task.js";
import { applyObservabilityEnvironment, type ProviderObservabilityLaunch } from "@paperclipai/adapter-utils/agent-observability";
import { museRunnerBroker } from "../muse-runner-broker.js";
import { nativeCaseHandoffResult } from "./native-case-handoff.js";
@@ -1981,12 +1986,34 @@ function migrateLegacyRunnerdStateRoot(input: {
return input.scoped;
}
+function savePluginRunnerCheckpoint(root: string, state: Record<string, unknown>, identity: Record<string, unknown>) {
+ const fields = ["runnerInstanceId", "environmentLeaseId", "runId", "normalizedSessionId", "turnId", "itemId"];
+ if (state.schema !== RUNNERD_STATE_SCHEMA || !RUNNERD_STATE_LIFECYCLES.has(String(state.lifecycle))
+ || fields.some(key => typeof identity[key] !== "string" || state[key] !== identity[key])) {
+ throw new Error("Plugin Runner checkpoint identity mismatch");
+ }
+ const path = resolve(root, "plugin-runner-state.json");
+ const temporary = `${path}.${randomUUID()}.tmp`;
+ // Keep only the verified lifecycle identity. Provider state stays on the execution host.
+ writeFileSync(temporary, JSON.stringify({ schema: state.schema, lifecycle: state.lifecycle,
+ ...Object.fromEntries(fields.map(key => [key, state[key]])) }), { flag: "wx", mode: 0o600 });
+ renameSync(temporary, path);
+}
+
function runnerdAuthorityLifecycle(
root: string,
identity: RunnerdDurableIdentity,
): "absent" | "suspended" | "not_suspended" | "indeterminate" {
const runnerRoot = resolve(root, "runner");
- if (!existsSync(runnerRoot)) return "absent";
+ if (!existsSync(runnerRoot)) {
+ try {
+ const state = record(JSON.parse(readBoundedNativeFile(resolve(root, "plugin-runner-state.json"),
+ NATIVE_RUNNER_STATE_MAX_BYTES, "runner_state_too_large").toString("utf8")));
+ if (state.schema !== RUNNERD_STATE_SCHEMA || !RUNNERD_STATE_LIFECYCLES.has(String(state.lifecycle))
+ || !Object.entries(identity).every(([key, value]) => state[key] === value)) return "indeterminate";
+ return state.lifecycle === "suspended" ? "suspended" : "not_suspended";
+ } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "indeterminate"; }
+ }
if (!isSafeNativeStateDirectory(runnerRoot)) return "indeterminate";
const statePath = resolve(runnerRoot, "runner-state.json");
if (!existsSync(statePath)) {
@@ -4855,6 +4882,16 @@ async function migrateRunnerdStateRootForExecution(input: {
}
throw new Error("runner_state_identity_mismatch: session_scope_mismatch");
}
+ const taskTarget = input.runnerExecutionTarget;
+ if (input.restartRecovery?.kind === "resume_dead_runner" && durableIdentityMatchesExecution(identity, input.execution)
+ && taskTarget?.kind === "remote" && taskTarget.transport === "sandbox" && taskTarget.runnerTask && taskTarget.leaseId) {
+ const resumeFrom = await resolvePluginTaskResume(input.db, { companyId: input.execution.binding.companyId,
+ leaseId: taskTarget.leaseId, priorIdentity: identity });
+ const result = environmentTaskResultSchema.parse(await taskTarget.runnerTask({ kind: "read_state", identity, resumeFrom }));
+ if (result.kind !== "state") throw new Error("Plugin Runner checkpoint unavailable");
+ // The new lease and source termination receipt authorize this exact same-run recovery.
+ savePluginRunnerCheckpoint(scoped, result.state, identity);
+ }
if (input.restartRecovery?.kind === "bootstrap_incomplete") {
if (runnerdStateProvesIncompleteBootstrap(scoped)) {
quarantineRunnerdStateRoot(scoped, "identity_indeterminate");
@@ -7562,7 +7599,10 @@ export async function executePaperclipNativeSession(input: {
/** Private grant materialization; never a user-configured host path. */
managedAiCredentialHome?: string;
managedAiCredentialIdentity?: string;
+ managedAiAccountIdentity?: string;
+ managedAiCredentialWriteback?: PluginTaskCredentialWritebackBinding;
billingIdentity?: Pick<AdapterExecutionResult, "provider" | "biller" | "billingType">;
+ onTaskDispatched?: () => Promise<void> | void;
runnerExecutionTarget?: AdapterExecutionTarget | null;
/** Resolved per-run authorization; not an independent instance setting. */
runnerIngressAuthorized?: boolean;
@@ -8769,8 +8809,9 @@ async function executePaperclipNativeSessionWithinScope(
controller,
});
try {
+ const usesPluginTask = input.runnerExecutionTarget?.kind === "remote" && input.runnerExecutionTarget.transport === "sandbox" && !!input.runnerExecutionTarget.runnerTask;
const prepareRunnerEnvironment = async () => {
- if (input.managedGitHub && input.execution.schema !== "paperclip.native-execution-input.v6" && input.execution.schema !== "paperclip.native-execution-input.v8") {
+ if (!usesPluginTask && input.managedGitHub && input.execution.schema !== "paperclip.native-execution-input.v6" && input.execution.schema !== "paperclip.native-execution-input.v8") {
if (!input.execution.workspace.cwd) throw new Error("native_workspace_required");
githubAccess ??= await timeController("github_access", () => createNativeGitHubAccess({
scope: input.execution.binding,
@@ -8785,7 +8826,7 @@ async function executePaperclipNativeSessionWithinScope(
}
return input.runnerEnvironment;
};
- const overlapGitHubPreparation = input.managedGitHub && input.useRunnerd && input.backend === undefined
+ const overlapGitHubPreparation = !usesPluginTask && input.managedGitHub && input.useRunnerd && input.backend === undefined
&& input.runnerExecutionTarget?.kind === "remote" && input.execution.provider.kind === "codex"
&& input.execution.schema !== "paperclip.native-execution-input.v6"
&& input.execution.schema !== "paperclip.native-execution-input.v8";
@@ -11417,6 +11458,10 @@ export async function createRunnerdBackend(input: {
prepareRunnerEnvironment?: () => Promise<NodeJS.ProcessEnv | undefined>;
/** Private grant materialization; never a user-configured host path. */
managedAiCredentialHome?: string;
+ managedAiCredentialIdentity?: string;
+ managedAiAccountIdentity?: string;
+ managedAiCredentialWriteback?: PluginTaskCredentialWritebackBinding;
+ onTaskDispatched?: () => Promise<void> | void;
runnerExecutionTarget?: AdapterExecutionTarget | null;
/** Resolved per-run authorization; not an independent instance setting. */
runnerIngressAuthorized?: boolean;
@@ -11597,6 +11642,11 @@ async function createRunnerdBackendWithinSessionClaim(
let recoveryPending = retainedTransition !== undefined;
const target = input.runnerExecutionTarget ?? { kind: "local" as const };
const remoteTarget = target.kind === "remote" ? target : null;
+ const pluginTask = remoteTarget?.transport === "sandbox" ? remoteTarget.runnerTask : undefined;
+ if (pluginTask && input.runnerIngressAuthorized !== true) throw new Error("runner_ingress_unavailable");
+ if (pluginTask && (input.execution.schema === "paperclip.native-execution-input.v6" || input.execution.schema === "paperclip.native-execution-input.v8" || input.execution.session.lifecyclePolicy.mode !== "per_turn")) {
+ throw new Error("Plugin Runner tasks currently require a per-turn workspace session");
+ }
const remoteCommandRunner = remoteTarget
? remoteTarget.transport === "ssh"
? createNativeSshCommandRunner({
@@ -11605,7 +11655,7 @@ async function createRunnerdBackendWithinSessionClaim(
})
: remoteTarget.runner
: null;
- if (remoteTarget && !remoteCommandRunner) {
+ if (remoteTarget && !remoteCommandRunner && !pluginTask) {
throw new Error(
"runner_transport_ineligible: remote process runner is unavailable",
);
@@ -11628,7 +11678,7 @@ async function createRunnerdBackendWithinSessionClaim(
// Remote Codex already sends dynamic tool calls over authenticated PRP. Keep
// the assigned gateway on the control plane instead of asking the sandbox to
// reach the host's HTTP origin (which may be private or loopback-only).
- const relayAssignedMcp = (remoteTarget !== null && input.execution.provider.kind === "codex") || input.execution.schema === "paperclip.native-execution-input.v6";
+ const relayAssignedMcp = Boolean(pluginTask) || (remoteTarget !== null && input.execution.provider.kind === "codex") || input.execution.schema === "paperclip.native-execution-input.v6";
const assignedMcpUrl = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_URL;
const assignedMcpToken = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_TOKEN;
const assignedMcpName = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_NAME;
@@ -11687,7 +11737,7 @@ async function createRunnerdBackendWithinSessionClaim(
assertBridgeAuthority: input.execution.schema === "paperclip.native-execution-input.v6" || input.execution.schema === "paperclip.native-execution-input.v8" ? (database = input.db) => assertExternalNativeRunAuthority(input.db, input.execution, database) : undefined,
workspaceRoot: input.dotWorkspaceRoot ?? remoteTarget?.remoteCwd ?? input.execution.workspace.cwd ?? undefined,
executionTargetKind: target.kind,
- readRemoteWorkspaceFile: remoteTarget && remoteCommandRunner
+ readRemoteWorkspaceFile: !pluginTask && remoteTarget && remoteCommandRunner
? (file) => readVerifiedRemoteWorkspaceFile({ runner: remoteCommandRunner, workspaceRoot: remoteTarget.remoteCwd, ...file })
: undefined,
currentWakeComments: currentWakeComments ?? undefined,
@@ -11720,10 +11770,83 @@ async function createRunnerdBackendWithinSessionClaim(
const effectiveRunnerInstanceId =
durableBinding?.runnerInstanceId ?? input.runnerInstanceId;
const effectiveEnvironmentLeaseId =
- durableBinding?.environmentLeaseId ??
+ (pluginTask ? remoteTarget?.leaseId : undefined) ?? durableBinding?.environmentLeaseId ??
input.durableEnvironmentLeaseId ??
input.execution.binding.executionWorkspaceId;
mkdirSync(root, { recursive: true, mode: 0o700 });
+ if (pluginTask && remoteTarget?.transport === "sandbox" && input.execution.schema !== "paperclip.native-execution-input.v6" && input.execution.schema !== "paperclip.native-execution-input.v8") {
+ const provider = input.execution.provider;
+ if (provider.kind !== "codex" && provider.kind !== "opencode" && provider.kind !== "acpx") throw new Error("Plugin Runner tasks require a workspace harness");
+ const description = environmentTaskResultSchema.parse(await pluginTask({ kind: "describe" }));
+ if (description.kind !== "description" || description.launchPreparationVersion !== 1 || description.projectAuthCheckVersion !== 1) throw new Error("Plugin Runner launch preparation v1 unavailable");
+ const prior = durableBinding ? durableIdentity as RunnerdDurableIdentity : undefined;
+ const resumeFrom = prior && prior.environmentLeaseId !== remoteTarget.leaseId
+ ? await resolvePluginTaskResume(input.db, { companyId: input.execution.binding.companyId,
+ leaseId: remoteTarget.leaseId!, priorIdentity: prior }) : undefined;
+ const credentials = await preparePluginRunnerCredentials({
+ provider: provider.kind === "acpx" ? provider.agent : provider.kind,
+ identity: input.managedAiCredentialIdentity, accountIdentity: input.managedAiAccountIdentity,
+ home: input.managedAiCredentialHome, environment: input.runnerEnvironment ?? {},
+ });
+ if (credentials.needsWriteback && !input.managedAiCredentialWriteback) throw new Error("Plugin Runner credential writeback authority unavailable");
+ if (input.managedAiCredentialWriteback && credentials.accountIdentity) {
+ if (!remoteTarget.leaseId) throw new Error("Plugin Runner credential lease unavailable");
+ await registerPluginTaskCredentialHandoff(input.db, { companyId: input.execution.binding.companyId, leaseId: remoteTarget.leaseId },
+ credentials.accountIdentity, input.managedAiCredentialWriteback);
+ }
+ const owner = createPluginRunnerTaskOwner({ ...credentials, projectAuthCheckVersion: description.projectAuthCheckVersion, task: pluginTask, projectIds: remoteTarget.runnerTaskProjectIds ?? [],
+ harness: provider.kind === "acpx" ? provider.agent : provider.kind, resumeFrom, priorIdentity: prior ? {
+ runnerInstanceId: prior.runnerInstanceId, environmentLeaseId: prior.environmentLeaseId,
+ runId: prior.runId, normalizedSessionId: prior.normalizedSessionId,
+ turnId: typeof prior.turnId === "string" ? prior.turnId : "",
+ itemId: typeof prior.itemId === "string" ? prior.itemId : "",
+ } : undefined,
+ credentialIdentity: input.managedAiCredentialIdentity,
+ onSessionRetained: async state => {
+ savePluginRunnerCheckpoint(root, state, state);
+ await input.db.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({
+ runnerTaskSessionRetained: true, runnerTaskIdentity: {
+ runnerId: state.runnerInstanceId, leaseId: state.environmentLeaseId,
+ runId: state.runId, sessionId: state.normalizedSessionId, turnId: state.turnId, itemId: state.itemId,
+ },
+ })}::jsonb` })
+ .where(and(eq(environmentLeases.id, remoteTarget.leaseId!), eq(environmentLeases.companyId, input.execution.binding.companyId)));
+ }, onDispatched: input.onTaskDispatched,
+ });
+ const executeTool = (call: Parameters<SessionToolAuthorityEpoch["execute"]>[0]) => {
+ const current = sessionToolAuthorityEpochs.get(sessionScopeId);
+ if (!current) throw new Error("native_session_tool_authority_unavailable");
+ return current.execute(call);
+ };
+ const backend = createNativeSessionBackend(input.execution, {
+ runnerInstanceId: prior?.runnerInstanceId ?? effectiveRunnerInstanceId, environment: {},
+ workingDirectoryAuthority: "remote_runner", dynamicTools, dynamicToolHandler: executeTool,
+ completionFeedback: async result => { await authorityEpoch.definitions(); return nativeCompletionFeedback(input.db, input.execution.binding.runId, result); },
+ codexTransportFactory: recovery => createRunnerdCodexTransport({ provider: provider.kind, stateDirectory: root,
+ ...owner.driver, runnerArtifact: description.runner,
+ ...(provider.kind === "acpx" ? { acpxAgent: provider.agent,
+ acpxCandidateProfile: provider.agent === "pi" ? undefined : resolveAcpxQualification(provider, process.env),
+ acpxPermissionMode: provider.permissionMode, acpxMode: provider.mode, piThinkingLevel: provider.piThinkingLevel,
+ claudeEffort: "claudeEffort" in provider ? provider.claudeEffort : undefined,
+ acpxPermissionModePinned: true } : {}),
+ ...(provider.kind === "opencode" ? { opencodePermissionMode: provider.permissionMode } : {}),
+ runnerReconnectGraceMs: 120_000, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
+ runtimeContext: "runtimeContext" in input.execution ? input.execution.runtimeContext : null,
+ externallySandboxed: true, baseInstructions: recovery?.baseInstructions,
+ resumeDynamicTools: dynamicTools, resumeCompletionContract: { revision: input.execution.completionContract.contract.revision,
+ criterionIds: input.execution.completionContract.contract.criteria.map(criterion => criterion.id) },
+ resumeActiveTurnId: recovery?.persistedSession?.activeTurnId ?? null, resumeProviderSession: recovery?.persistedSession,
+ prpIdentity: { runnerInstanceId: prior?.runnerInstanceId ?? effectiveRunnerInstanceId,
+ environmentLeaseId: prior?.environmentLeaseId ?? effectiveEnvironmentLeaseId,
+ runId: input.execution.binding.runId, normalizedSessionId: nativeSessionKey(input.execution),
+ turnId: `turn-${input.execution.binding.runId}`, itemId: `item-${input.execution.binding.runId}` },
+ }).transport,
+ });
+ sessionToolAuthorityEpochs.get(sessionScopeId)?.revoke();
+ sessionToolAuthorityEpochs.set(sessionScopeId, authorityEpoch);
+ return { ...backend, descriptor: () => backend.descriptor(), openSession: session => backend.openSession(session),
+ recoverSession: (snapshot, options) => backend.recoverSession!(snapshot, options), bindManagedSession: session => session };
+ }
if (input.execution.schema === "paperclip.native-execution-input.v6" || input.execution.schema === "paperclip.native-execution-input.v8") {
if (target.kind === "remote" && input.dotWorkspaceRoot) throw new Error("dot_remote_workspace_access_unavailable");
const remoteDot = target.kind === "remote"
diff --git a/server/src/services/native-runtime/native-workspace-finalizer.test.ts b/server/src/services/native-runtime/native-workspace-finalizer.test.ts
index bdc1ec177e..c674bcfb4e 100644
--- a/server/src/services/native-runtime/native-workspace-finalizer.test.ts
+++ b/server/src/services/native-runtime/native-workspace-finalizer.test.ts
@@ -1,3 +1,4 @@
+import * as pluginWorkspaces from "../plugin-workspaces.js";
import * as platformProof from "./native-workspace-platform-proof.js";
import { currentNativeControllerIdentity } from "./native-restart-recovery.js";
import { nativeSha256 } from "./canonical.js";
@@ -723,6 +724,46 @@ describe("native workspace finalization recovery", () => {
} finally { release(); await first; spy.mockRestore(); }
});
+ it.each(["plugin", "adapter_managed"])("resumes accepted work without Core files for %s storage", async providerType => {
+ const [workspace] = await db.insert(executionWorkspaces).values({ companyId, projectId,
+ name: "Plugin-only work", providerType, providerRef: "provider:opaque-worktree", cwd: "/workspaces/plugin-only",
+ mode: "isolated_workspace", strategyType: providerType === "plugin" ? "git_worktree" : "project_primary",
+ branchName: "task-branch", metadata: providerType === "plugin" ? {} : { runnerTaskWorkspaceOwner: { agentId } } }).returning();
+ const seeded = await seedRun({ executionWorkspaceId: workspace.id, title: "Plugin result before controller restart" });
+ const inspect = vi.spyOn(pluginWorkspaces, "inspectPluginWorkspace").mockResolvedValue({ kind: "inspection",
+ branchName: "task-branch", headSha: "a".repeat(40), hasDirtyTrackedFiles: true, hasUntrackedFiles: false,
+ hasLocalOnlyData: true, isMergedIntoBase: false, remotelyRecoverable: false });
+ try {
+ expect(await resumeNativeWorkspaceFinalization({ db, runId: seeded.runId })).toMatchObject({ status: "succeeded" });
+ if (providerType === "plugin") expect(inspect).toHaveBeenCalledWith(db, undefined, expect.objectContaining({ id: workspace.id }));
+ else expect(inspect).not.toHaveBeenCalled();
+ } finally { inspect.mockRestore(); }
+ });
+
+ it.each(["synthetic plugin unavailable", "plugin_workspace_branch_mismatch", "plugin_workspace_owner_mismatch"])("defers plugin failure without aborting other result recovery: %s", async message => {
+ const [unavailable, healthy] = await db.insert(executionWorkspaces).values([
+ { companyId, projectId, name: "Unavailable plugin", providerType: "plugin", providerRef: "provider:unavailable",
+ mode: "isolated_workspace", strategyType: "git_worktree", branchName: "task-branch" },
+ { companyId, projectId, name: "Healthy task", providerType: "adapter_managed", cwd: "/workspaces/healthy-task",
+ mode: "shared_workspace", strategyType: "project_primary", metadata: { runnerTaskWorkspaceOwner: { agentId } } },
+ ]).returning();
+ const blocked = await seedRun({ executionWorkspaceId: unavailable.id, title: "Plugin is unavailable after restart" });
+ const ready = await seedRun({ executionWorkspaceId: healthy.id, title: "Other result can recover" });
+ const inspect = vi.spyOn(pluginWorkspaces, "inspectPluginWorkspace").mockRejectedValue(new Error(message));
+ const code = message.startsWith("plugin_workspace_") ? message : "plugin_workspace_inspection_failed";
+ try {
+ await expect(reconcileNativeFinalizations(db, [blocked.runId, ready.runId])).resolves.toBeDefined();
+ const [retry] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, blocked.runId));
+ expect(retry).toMatchObject({ phase: "retryable_failure", nextAttemptAt: expect.any(Date), resultId: expect.any(String),
+ failureCode: code === message ? `native_${code}` : "native_workspace_sync_out_failed" });
+ if (code === message) expect(retry.failureDetail?.nextAction).toContain("Repair the plugin workspace");
+ expect(await db.select().from(workspaceOperations).where(eq(workspaceOperations.heartbeatRunId, blocked.runId)))
+ .toMatchObject([{ status: "failed", stderrExcerpt: `${code}\n` }]);
+ expect(await db.select().from(workspaceOperations).where(eq(workspaceOperations.heartbeatRunId, ready.runId)))
+ .toMatchObject([{ status: "succeeded" }]);
+ } finally { inspect.mockRestore(); }
+ });
+
it("records directory-only recovery without inventing an execution-workspace foreign key", async () => {
const cwd = path.join(workspaceRoot, "directory-only");
await fs.mkdir(cwd);
diff --git a/server/src/services/native-runtime/native-workspace-finalizer.ts b/server/src/services/native-runtime/native-workspace-finalizer.ts
index f0d7b657f1..9e0220004c 100644
--- a/server/src/services/native-runtime/native-workspace-finalizer.ts
+++ b/server/src/services/native-runtime/native-workspace-finalizer.ts
@@ -1,3 +1,5 @@
+import { inspectPluginWorkspaceForFinalization } from "./native-plugin-workspace-finalization.js";
+import type { WorkspaceWorkers } from "../plugin-workspaces.js";
import { restoreNativeWorkspaceBestEffort } from "./native-workspace-best-effort.js";
import { withNativeWorkspaceFinalizationOwnership } from "./native-workspace-finalization-ownership.js";
import fs from "node:fs/promises";
@@ -51,9 +53,11 @@ export async function resumeNativeWorkspaceFinalization(input: {
db: Db;
runId: string;
environmentRuntime?: EnvironmentRuntimeService;
+ pluginWorkerManager?: WorkspaceWorkers;
}) {
const bound = await input.db.select({
companyId: heartbeatRuns.companyId,
+ agentId: heartbeatRuns.agentId,
runtimeMode: heartbeatRuns.runtimeMode,
runnerProfileJson: heartbeatRuns.runnerProfileJson,
issueId: nativeRunFinalizations.issueId,
@@ -237,6 +241,22 @@ export async function resumeNativeWorkspaceFinalization(input: {
return workspaceSyncFailure(code);
}
}
+ let pluginWorkspace: Record<string, unknown> | null;
+ try {
+ pluginWorkspace = workspace
+ ? await inspectPluginWorkspaceForFinalization(input.db, input.pluginWorkerManager, workspace, bound.agentId)
+ : null;
+ } catch (error) {
+ await ownership.assertHeld();
+ const message = error instanceof Error ? error.message : null;
+ const code = message === "plugin_workspace_branch_mismatch" || message === "plugin_workspace_owner_mismatch"
+ ? message : "plugin_workspace_inspection_failed";
+ return { status: "failed", exitCode: 1, stderr: `${code}\n` };
+ }
+ await ownership.assertHeld();
+ if (pluginWorkspace) return { status: "succeeded", exitCode: 0,
+ system: "Native workspace finalization used the plugin workspace owner.\n",
+ metadata: { pluginWorkspace } };
if (!cwd) {
return {
status: "failed",
diff --git a/server/src/services/native-runtime/native-workspace-sync.ts b/server/src/services/native-runtime/native-workspace-sync.ts
index d6b716e341..f3e30fa033 100644
--- a/server/src/services/native-runtime/native-workspace-sync.ts
+++ b/server/src/services/native-runtime/native-workspace-sync.ts
@@ -885,7 +885,7 @@ export async function prepareNativeWorkspaceSync(input: {
onCheckpoint?: (metrics: WorkspaceCheckpointMetrics) => Promise<void>;
onEvent?: (event: AdapterRuntimeEvent) => Promise<void>;
}): Promise<PreparedNativeWorkspaceSync | null> {
- if (input.target?.kind !== "remote" || input.target.transport !== "sandbox") {
+ if (input.target?.kind !== "remote" || input.target.transport !== "sandbox" || input.target.runnerTask) {
return null;
}
const target = input.target;
diff --git a/server/src/services/plugin-agent-runtime-state.ts b/server/src/services/plugin-agent-runtime-state.ts
index 11615783b0..e8e64c54d3 100644
--- a/server/src/services/plugin-agent-runtime-state.ts
+++ b/server/src/services/plugin-agent-runtime-state.ts
@@ -50,9 +50,12 @@ export async function pluginAgentRuntimeState(db: Db, pluginId: string, companyI
versionSelections: skillVersionSelectionMap(preference.desiredSkillEntries, { versionPinsEnabled: settings.enableBetaSkills }),
}));
const connectionAssignments = await pluginAgentConnectionAssignments(db, companyId, agentId, { publicMcp: settings.enablePublicMcp, chatConnectors: settings.enableChatConnectors });
+ const fallback = !state.instructionsRootPath ? await agentInstructionsService().exportFiles(state.agent, { rejectSymlinks: true }) : null;
+ const entryFile = fallback?.entryFile ?? state.instructionsEntryFile;
+ const entryContent = fallback?.files[entryFile];
const current = await readState(db, pluginId, companyId, agentId);
if (!current) return null;
- if (current.revision === state.revision) return { ...current, skills, connectionAssignments };
+ if (current.revision === state.revision) return { ...current, instructionsEntryFile: entryFile, ...(entryContent === undefined ? {} : { instructionsEntryContent: entryContent }), skills, connectionAssignments };
}
throw conflict("Agent runtime changed while resolving synchronization inputs; retry");
}