Skip to content

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

feat(dot): run cloud assignments in managed sandboxes (#15691)

Dotta556daf9a99e8
diff --git a/doc/openai-dot-runner.md b/doc/openai-dot-runner.md
index 6f8afba36f..8d2c911b60 100644
--- a/doc/openai-dot-runner.md
+++ b/doc/openai-dot-runner.md
@@ -403,7 +403,7 @@ are available. The assignment catalog is read on each new assignment.
The [2026-10-08 cloud Runner and invitation decision](plans/2026-10-08-cloud-dot-runner-and-external-invitations.md) keeps remote agents on the new Runner infrastructure. In addition to shared assignment lifecycle handling, this preserves a sandbox boundary for future tools that may access Paperclip workspaces. The first cloud version gives Dot no Paperclip workspace file or command tools; Dot works on its own computer.
-The self-hosted entry is **New Agent → Invite an external agent → Dot / Hermes / Other**. Dot receives a copyable setup prompt and live connection checks, with readiness requiring a confirmed event round trip. The same components have Storybook journeys with fixture data. Cloud execution remains disabled pending qualification. Hermes continues to use the existing external-agent invitation prompt.
+The entry is **New Agent → Invite an external agent → Dot / Hermes / Other**. Dot receives a copyable setup prompt and live connection checks, with readiness requiring a confirmed event round trip. The same components have Storybook journeys with fixture data. Cloud assignments use the selected managed sandbox Runner; idle MCP traffic does not allocate a sandbox. Hermes continues to use the existing external-agent invitation prompt.
## Agent avatar
@@ -418,8 +418,32 @@ The setup prompt asks Dot to upload its own current image only if it can obtain
### Invite from the agent picker
-In a self-hosted instance, enable **OpenAI Dot** and **Assistant connections (MCP)**, then choose **New Agent → Invite an external agent → Dot**. Copy the setup prompt into your Dot. Paperclip creates a scoped Runner agent and watches connection, event subscription, and a harmless event round trip. If your company requires hire approval, approve the agent before copying its pairing prompt. The test event is sent automatically after the callback is verified; Retry test event remains available if confirmation times out.
+Enable **OpenAI Dot** and **Assistant connections (MCP)**, then choose **New Agent → Invite an external agent → Dot**. Copy the setup prompt into your Dot. Paperclip creates a scoped Runner agent and watches connection, event subscription, and a harmless event round trip. If your company requires hire approval, approve the agent before copying its pairing prompt. The test event is sent automatically after the callback is verified; Retry test event remains available if confirmation times out.
Reopening setup resumes the operator's unfinished invitation. Pairing codes are not stored in browser persistence. After refreshing or when an open prompt expires, setup automatically prepares a fresh prompt to copy. It first checks current connection state and replaces only the pending capability, without revoking an established connection. A failed renewal offers a retry rather than looping. If another browser window replaces the prompt, the current window asks before replacing it again. Hermes and Other continue to use the ordinary external-agent invitation flow.
-Cloud Dot execution is still gated. The external launcher hooks do not yet enable managed cloud execution or qualify tenant MCP routing. See [the cloud Runner plan](plans/2026-10-08-cloud-dot-runner-and-external-invitations.md).
+Cloud instances require a managed sandbox environment and the current Runner artifact. Dot cannot fall back to a process on the control-plane host or to the legacy session backend. The control plane retains OAuth, signed events, mailbox state, and authorization. One sandbox owns an admitted assignment, including later messages and tool operations; completion and cancellation use the existing managed lease cleanup. Dot-initiated work creates a visible task and follows the same admission path.
+
+The first managed version does not expose Paperclip workspace tools, even when the Runner itself has a sandbox directory. Keep `dotWorkspaceAccess` off. Assigned app tools still execute through their existing control-plane gateway and scoped grants. The Runner receives no OpenAI credential.
+
+The Cloud front door must forward the dedicated `/mcp/runner` protocol endpoints, OAuth discovery/authorization/token routes, and `/dot-connect/:requestId` pairing page without requiring a browser stack session. The page uses `/api/dot-mcp/requests/:requestId` for read and one-use pairing preview/approval. These aliases reject personal assistant request IDs. Regular `/mcp-connect` consent and assistant connection management retain normal sign-in. Deploy the corresponding Cloud ingress change with the tenant app; upgrading only the UI is insufficient.
+
+Remote startup checks `externalProviderCapabilities` for `openai_dot_mcp`, verifies the artifact digest, and uses the existing authenticated Runner transport. Before dispatch, it also requires the sandbox process marker and Linux boot/start fingerprint; a connected transport alone is insufficient. A pre-Dot artifact is rejected before dispatch. Linux controllers use their packaged Linux artifact; a development controller on another platform must set `PAPERCLIP_RUNNER_REMOTE_BINARY_PATH` to a current binary built for the sandbox platform.
+
+Recovery reads the checkpoint from the owning execution target and validates run/session/turn authority before retaining a controller copy. Missing state after dispatch fails closed for reconciliation. It never creates a replacement OpenAI Dot thread. See [the cloud Runner plan](plans/2026-10-08-cloud-dot-runner-and-external-invitations.md).
+
+An active managed Dot bridge allows a five-minute controller reconnect gap. Recovery must still prove the same sandbox lease, Runner process generation, durable session, and assignment; it cannot substitute a new process or Dot conversation. A verified shutdown receipt is authoritative even when the remote process monitor has no exit code. Remote process birth comes from the sandbox, never a colliding PID on the controller.
+
+A normal task comment for an accepted Dot assignment is recorded once in its durable mailbox and its wake receipt points to the existing run. The receipt stays deferred until Dot receives a successful `get_task_history` result containing that exact comment ID. A webhook or inbox reference alone does not consume it. If the assignment finishes first, normal queued admission preserves the unread comment for the next turn, including after controller recovery. Comments already read during the assignment do not execute again. Explicit fresh-session requests, interactions, and idle task admission retain their existing wake policy.
+
+### Managed qualification
+
+`server/src/__tests__/dot-runner.test.ts` includes an opt-in private Daytona test using the actual Rust Runner and authenticated preview ingress. It covers signed readiness, no workspace catalog, assigned app tools, task-document writes, duplicate receipts, normal completion, and sandbox deletion. The ordinary suite also covers OAuth revocation, membership loss, budget and ownership fences, admission, and local Rust recovery.
+
+To run the live test, install/build the bundled Daytona plugin dependencies, supply `DAYTONA_API_KEY`, set `PAPERCLIP_DOT_DAYTONA_LIVE=1`, and set `PAPERCLIP_DOT_DAYTONA_IMAGE` to an immutable image digest. Optionally set `PAPERCLIP_DOT_DAYTONA_RUNNER_BINARY` to a current Linux Runner artifact and `PAPERCLIP_DOT_DAYTONA_EVIDENCE` to a local evidence output path. Then run:
+
+```sh
+pnpm exec vitest run server/src/__tests__/dot-runner.test.ts -t 'private Daytona Rust'
+```
+
+The fixture creates a private, bounded sandbox and deletes it in `finally`. Default tests do not contact Daytona. This test uses a scripted MCP client; a separate real OpenAI Dot walkthrough is required to qualify provider behavior.
diff --git a/doc/plans/2026-10-08-cloud-dot-runner-and-external-invitations.md b/doc/plans/2026-10-08-cloud-dot-runner-and-external-invitations.md
index fc7d8b4266..8fcda070ad 100644
--- a/doc/plans/2026-10-08-cloud-dot-runner-and-external-invitations.md
+++ b/doc/plans/2026-10-08-cloud-dot-runner-and-external-invitations.md
@@ -2,7 +2,7 @@
Date: 2026-10-08
-Status: the live self-hosted invitation flow is implemented. The shared square picker and animated dialog now create/resume scoped invitations, preserve company approval, watch server state, and send the event test automatically. Dot driver launcher/checkpoint hooks are qualified with a real Rust process. **Cloud execution remains disabled:** the existing managed-environment and Cloud MCP guards are unchanged pending sandbox and tenant-ingress qualification.
+Status: managed Dot execution and dedicated tenant ingress are implemented. The live invitation flow remains shared across self-hosted and Cloud instances. Private Daytona qualification passed with the actual Rust Runner, signed readiness, task tools, document writes, and normal finalization. A real OpenAI Dot also completed an operator-assigned task through a managed Daytona Runner. Coordinated tenant-app and Cloud front-door deployment is still required; these local qualifications are not evidence of a deployed Cloud rollout.
## Decision: remote agents use the new Runner infrastructure
@@ -72,11 +72,11 @@ The shared presentation lives in `ui/src/components/new-agent/ExternalAgentInvit
Run `pnpm --filter @paperclipai/ui storybook`, then open the journey group. Copying in the interactive Dot story advances simulated checks; the fixed-state stories remain still for inspection. These stories illustrate the live UX with simulated connection evidence; they do not prove a live cloud pairing.
-## Remaining implementation and qualification
+## Managed implementation and qualification
The live invitation controller, owner-scoped pending-invitation lookup, atomic creation, pending-code replacement, automatic event test, feature gating, and watcher are implemented. Active run controllers poll durable operation rows under their current controller generation and lease, so an operation reserved by another HTTP replica reaches its owning Runner. Idle-initiated work already uses normal admission.
-Before shipping cloud, connect Dot's qualified launcher hooks to managed job dispatch and qualify the dedicated tenant MCP ingress. Keep the present cloud restrictions until those paths are proven. The optional external launcher uses target-owned provider checkpoints and refuses recovery when identity or state is missing; it does not invent a replacement Dot thread. Preserve company isolation, approval rules, budget stops, assignment authority, and mutation receipts. Qualify real OAuth installation, event round trip, assignment execution, unsolicited Dot work, restart/reconnect, cancellation, and expired/revoked credentials against a real sandbox provider. No cloud-ready claim follows from this Storybook pass.
+Managed dispatch now uses the existing remote launcher, artifact verification, authenticated PRP transport, sandbox lease, and normal finalization. Cloud rejects local/legacy execution before startup. The current artifact must advertise the Dot capability; the older pinned image used during qualification required an explicitly staged current Linux artifact. Dedicated tenant OAuth and pairing routes are public protocol lanes, with no minted Cloud browser identity. Shared personal consent and management routes retain their existing session gate. The optional external launcher uses target-owned provider checkpoints and refuses recovery when identity or state is missing; it does not invent a replacement Dot thread. Preserve company isolation, approval rules, budget stops, assignment authority, and mutation receipts. Qualify real OAuth installation, event round trip, assignment execution, unsolicited Dot work, restart/reconnect, cancellation, and expired/revoked credentials against a real sandbox provider. No cloud-ready claim follows from this Storybook pass.
## Implemented invitation semantics
@@ -88,3 +88,14 @@ Before shipping cloud, connect Dot's qualified launcher hooks to managed job dis
- Hermes and Other share the existing external-agent invitation API and unchanged onboarding prompt. Dot is no longer a separate card in the harness picker.
Verification: a disposable authenticated local instance exercised the natural New Agent entry, Dot prompt copy, Back, Hermes, refresh/resume, and pending-prompt replacement. Signed callback verification, nonce confirmation, scoped OAuth, actual Rust execution, duplicate receipts, and recovery have automated coverage. No real OpenAI Dot or managed cloud sandbox was connected during this implementation pass.
+
+
+## Release qualification (2026-10-09)
+
+- A fresh private Daytona sandbox ran the current Rust Runner through provider preview ingress. Signed event readiness, app-tool relay, a document write, duplicate mutation receipts, authority fences, completion finalization, and deletion passed.
+- The existing approved OpenAI Dot connection received an operator assignment, accepted it, saved and verified a task document, and completed through the normal Runner result path. A Dot-initiated idle request also completed through normal managed admission after the broker was wired to the app-configured heartbeat service. Both managed execution leases expired after completion. Failed admission receipts now report the terminal outcome instead of telling Dot to wait indefinitely. New admission also retires stranded offers whose runs are terminal, with a durable authority fence and no claim that OpenAI globally stopped.
+- Cloud front-door tests cover exact protocol paths, unauthenticated code-based pairing, stripped spoofed Cloud identity headers, wrong methods, unrelated consent/management routes, and unregistered tenant hosts. Public static access is limited to fingerprinted build assets and the displayed provider brand images.
+- Onboarding tests preserve personal assistant behavior and reject personal OAuth requests through dedicated Dot aliases. The invitation is available under the standalone Dot experimental flag in Cloud.
+- A real accepted Dot assignment survived an intentional controller gap longer than one minute in Daytona. The sandbox PID, process birth/fingerprint, Runner instance, durable session, and assignment stayed unchanged; controller generation advanced to 2. Dot received the ordinary issue-comment follow-up, wrote/read its exact report, and completed the original run. One mailbox reference and one coalesced wake were recorded; no second run appeared, and the lease expired. Launch now requires verifiable process identity before dispatch and allows a five-minute reconnect gap. Missing process evidence fails closed.
+- A real cancellation fenced an accepted assignment, expired the managed lease, and received Dot's control acknowledgement. The receipt correctly kept `externalStopConfirmed: false`. Clean remote shutdown is recognized by its authenticated receipt even when the process monitor has no OS exit code.
+- Deploy both components together and smoke-test a real Cloud tenant before enabling broadly. No long-running idle sandbox or Paperclip workspace access is added. These managed tests qualify the implementation and real provider, not a deployed Cloud tenant.
diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs b/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs
index e8b2d5a2f7..2ee732c0a6 100644
--- a/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs
+++ b/packages/paperclip-runner/runner/crates/runner-core/src/bin/paperclip-runnerd.rs
@@ -120,6 +120,7 @@ fn build_metadata() -> serde_json::Value {
"packageVersion": env!("CARGO_PKG_VERSION"),
"binaryContractVersion": 2,
"durableSessionCapabilities": ["unlimited_runtime", "connection_lease_renewal"],
+ "externalProviderCapabilities": ["openai_dot_mcp"],
"nativeExecutionVersion": 1,
"harnessDriverVersion": 1,
"prp": {
@@ -445,6 +446,10 @@ mod tests {
let metadata = build_metadata();
assert_eq!(metadata["schema"], RUNNERD_BUILD_METADATA_SCHEMA);
assert_eq!(metadata["binaryContractVersion"], 2);
+ assert_eq!(
+ metadata["externalProviderCapabilities"],
+ json!(["openai_dot_mcp"])
+ );
assert_eq!(
metadata["durableSessionCapabilities"],
json!(["unlimited_runtime", "connection_lease_renewal"])
diff --git a/packages/paperclip-runner/src/drivers/dot/runnerd-dot-driver.test.ts b/packages/paperclip-runner/src/drivers/dot/runnerd-dot-driver.test.ts
index 72bd5aa98d..a830166b5d 100644
--- a/packages/paperclip-runner/src/drivers/dot/runnerd-dot-driver.test.ts
+++ b/packages/paperclip-runner/src/drivers/dot/runnerd-dot-driver.test.ts
@@ -78,7 +78,10 @@ it("admits the heartbeat descriptor with the real Dot capabilities and no broker
} finally { spawnSpy.mockRestore(); }
});
-it.each(["shutdown", "unexpected exit"] as const)("classifies a real Rust %s before the next command poll", async kind => {
+it.each([
+ { kind: "shutdown", remote: false }, { kind: "unexpected exit", remote: false },
+ { kind: "shutdown", remote: true }, { kind: "unexpected exit", remote: true },
+])("classifies a real Rust $kind before the next command poll (remote=$remote)", async ({ kind, remote }) => {
const root = await mkdtemp(join(tmpdir(), "dot-driver-exit-"));
await writeFile(join(root, "AGENTS.md"), "Use only the synthetic counter.");
const input = execution(root);
@@ -86,7 +89,9 @@ it.each(["shutdown", "unexpected exit"] as const)("classifies a real Rust %s bef
let exited = false;
const spawn = controlPlane.spawnRunner;
const spawnSpy = vi.spyOn(controlPlane, "spawnRunner").mockImplementation(options => {
- handle = spawn(options);
+ const process = spawn(options);
+ // Managed monitors preserve process identity but have no OS exit status.
+ handle = remote ? { ...process, completion: process.completion.then(result => ({ ...result, code: null })) } : process;
void handle.completion.then(() => { exited = true; });
return handle;
});
@@ -111,7 +116,7 @@ it.each(["shutdown", "unexpected exit"] as const)("classifies a real Rust %s bef
if (kind === "shutdown") {
await expect(session.close({ reason: "Test complete" })).resolves.toBeUndefined();
expect(exited).toBe(true);
- expect((await handle!.completion).code).toBe(0);
+ expect((await handle!.completion).code).toBe(remote ? null : 0);
} else {
handle!.child.kill("SIGTERM");
await handle!.completion;
diff --git a/packages/paperclip-runner/src/drivers/dot/runnerd-dot-driver.ts b/packages/paperclip-runner/src/drivers/dot/runnerd-dot-driver.ts
index d56a15a33f..73298784ee 100644
--- a/packages/paperclip-runner/src/drivers/dot/runnerd-dot-driver.ts
+++ b/packages/paperclip-runner/src/drivers/dot/runnerd-dot-driver.ts
@@ -138,12 +138,14 @@ class RunnerdDotSession implements HarnessSession {
signal?.throwIfAborted();
if (!o.adoptExistingRunner) {
this.#process = spawnRunner({
- processLauncher: o.runnerProcessLauncher, connectUrl: registration?.connectUrl ?? core.connectUrl,
+ processLauncher: o.runnerProcessLauncher, connectUrl: registration?.connectUrl ?? (registration?.connection ? undefined : core.connectUrl),
connection: registration?.connection, stateDirectory: runnerState, identity: o.identity,
ticket: core.issueBootstrapTicket(60_000), runnerBinaryPath: binary,
runnerVersion: artifact.version, runnerDigest: artifact.digest,
maxOutboxBytes: 16 * 1024 * 1024, p0ReserveBytes: 1024 * 1024,
- maxRuntimeMs: 0, reconnectGraceMs: 60_000,
+ // A managed controller rollout can outlast a minute. Task authority
+ // remains gated by the current controller lease throughout the gap.
+ maxRuntimeMs: 0, reconnectGraceMs: o.runnerProcessLauncher ? 300_000 : 60_000,
// No agent, OAuth, ChatGPT or provider API credentials are inherited.
environment: { PATH: process.env.PATH },
});
@@ -154,11 +156,13 @@ class RunnerdDotSession implements HarnessSession {
if (this.#closed) return;
// Rust exits after the authenticated shutdown receipt is committed and
// ACKed. That exit can precede the SDK's next command poll.
- if (result.code === 0 && core.getCommand("dot_shutdown")?.status === "completed") return;
+ // Remote monitors do not report an exit code. The authenticated,
+ // persisted receipt is the evidence of shutdown, for either launcher.
+ if (core.getCommand("dot_shutdown")?.status === "completed") return;
this.#failure ??= new Error(`dot_runner_process_exited_recovery_required: code=${result.code} signal=${result.signal}`);
this.#wake();
}, () => {
- if (this.#closed) return;
+ if (this.#closed || core.getCommand("dot_shutdown")?.status === "completed") return;
this.#failure ??= new Error("dot_runner_process_exited_recovery_required");
this.#wake();
});
@@ -169,6 +173,9 @@ class RunnerdDotSession implements HarnessSession {
if (!this.#closed) { this.#failure = error instanceof Error ? error : new Error("dot_runner_transport_failed"); this.#wake(); }
});
const checkpoint = await readProviderCheckpoint(o);
+ if (!checkpoint && this.#events.some(event => event.eventType === "external_provider.dispatch_requested")) {
+ throw new Error("dot_provider_checkpoint_missing_reconciliation_required");
+ }
if (checkpoint && (checkpoint.schema !== "paperclip.runner.dot-provider-state.v1"
|| checkpoint.runId !== o.identity.runId || checkpoint.sessionId !== o.identity.normalizedSessionId
|| checkpoint.turnId !== o.identity.turnId)) throw new Error("dot_runner_checkpoint_authority_mismatch");
@@ -223,6 +230,11 @@ class RunnerdDotSession implements HarnessSession {
async interrupt() { await this.#command("run.cancel", {}, "dot_cancel"); }
async snapshot(): Promise<PersistedHarnessSession> {
const state = await this.read();
+ // Target-owned state is authoritative. Also retain the controller's recovery
+ // evidence through the supplied reader after this authenticated snapshot.
+ if (this.options.readProviderState && !await readProviderCheckpoint(this.options)) {
+ throw new Error("dot_provider_checkpoint_missing_reconciliation_required");
+ }
const proposed = this.#events.findLast(event => event.eventType === "run.result.proposed");
const result = proposed ? validatePrpStructuredRunResult(proposed.payload) : null;
const terminal = this.#events.findLast(event => event.eventType === "run.terminal");
diff --git a/server/src/__tests__/agent-test-environment-routes.test.ts b/server/src/__tests__/agent-test-environment-routes.test.ts
index d78375724a..62fbd70b57 100644
--- a/server/src/__tests__/agent-test-environment-routes.test.ts
+++ b/server/src/__tests__/agent-test-environment-routes.test.ts
@@ -93,6 +93,10 @@ vi.mock("../services/instance-settings.js", () => ({
instanceSettingsService: () => mockInstanceSettingsService,
}));
+vi.mock("../services/dot-runner-broker.js", () => ({
+ dotRunnerBroker: () => ({ enabled: async () => true, bindingForAgent: async () => null }),
+}));
+
const testEnvironmentSpy = vi.fn();
const externalAdapter: ServerAdapterModule = {
@@ -249,6 +253,35 @@ describe("agent test-environment route", () => {
await unregisterTestAdapter("external_test");
});
+ it("accepts a managed Dot environment without allocating an idle sandbox", async () => {
+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://paperclip.example");
+ mockInstanceSettingsService.get.mockResolvedValue({ defaultEnvironmentId: "11111111-1111-4111-8111-111111111111" });
+ const app = await createApp();
+ try {
+ const res = await request(app).post("/api/companies/company-1/adapters/paperclip_runner/test-environment")
+ .send({ adapterConfig: { provider: "openai_dot", allowUnmeteredProvider: true } });
+ expect(res.status, JSON.stringify(res.body)).toBe(200);
+ expect(res.body.checks).toContainEqual(expect.objectContaining({ code: "dot_controller", level: "info" }));
+ expect(mockEnvironmentRuntime.acquireRunLease).not.toHaveBeenCalled();
+ expect(testEnvironmentSpy).not.toHaveBeenCalled();
+ } finally { vi.unstubAllEnvs(); }
+ });
+
+ it("fails the Cloud Dot check without a managed sandbox instead of probing the host", async () => {
+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://paperclip.example");
+ vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "test-cloud");
+ const app = await createApp();
+ try {
+ const res = await request(app).post("/api/companies/company-1/adapters/paperclip_runner/test-environment")
+ .send({ adapterConfig: { provider: "openai_dot", allowUnmeteredProvider: true } });
+ expect(res.status, JSON.stringify(res.body)).toBe(200);
+ expect(res.body.status).toBe("fail");
+ expect(res.body.checks).toContainEqual(expect.objectContaining({ code: "dot_controller", level: "error" }));
+ expect(mockEnvironmentRuntime.acquireRunLease).not.toHaveBeenCalled();
+ expect(testEnvironmentSpy).not.toHaveBeenCalled();
+ } finally { vi.unstubAllEnvs(); }
+ });
+
it("tests the instance default sandbox when the agent inherits its environment", async () => {
const environmentId = "11111111-1111-4111-8111-111111111111";
mockInstanceSettingsService.get.mockResolvedValue({ defaultEnvironmentId: environmentId });
diff --git a/server/src/__tests__/dot-oauth-onboarding.test.ts b/server/src/__tests__/dot-oauth-onboarding.test.ts
index 53e24b5606..cec355039e 100644
--- a/server/src/__tests__/dot-oauth-onboarding.test.ts
+++ b/server/src/__tests__/dot-oauth-onboarding.test.ts
@@ -161,6 +161,7 @@ describe("Dot onboarding with an operator-issued pairing capability", () => {
const authorization = await request(app).get("/mcp/runner/oauth/authorize").query(f.input);
expect(authorization.status).toBe(303);
expect(new URL(authorization.headers.location).origin).toBe(browserOrigin);
+ expect(new URL(authorization.headers.location).pathname).toMatch(/^\/dot-connect\/pcmcp_request_[A-Za-z0-9_-]{43}$/);
const path = `/api/mcp/requests/${f.id}/dot-pairing`;
expect((await request(app).post(path).set("Origin", "https://other.example").send({ pairingCode: f.pairing.pairingCode })).status).toBe(403);
const approval = await request(app).post(path).set("Origin", browserOrigin).send({ pairingCode: f.pairing.pairingCode });
@@ -175,13 +176,14 @@ describe("Dot onboarding with an operator-issued pairing capability", () => {
for (const invalid of ["http://browser.example", "https://[email protected]", "https://browser.example/path", "https://browser.example?next=evil", "https://browser.example#fragment"])
expect(() => publicMcpConfig({ PAPERCLIP_PUBLIC_URL: config.origin, PAPERCLIP_MCP_AUTHORIZATION_ORIGIN: invalid })).toThrow();
});
- it("connects without a board session, binds the exact agent, and consumes the capability once", async () => {
+ it.each(["mcp", "dot-mcp"])("connects via %s without a board session, binds the exact agent, and consumes the capability once", async prefix => {
const f = await fixture();
const personal = createPublicMcpOAuth(db, { ...config, resource: config.origin + "/mcp/paperclip" });
const app = express(); app.use(express.json());
app.use((req, _res, next) => { req.actor = { type: "none" }; next(); });
app.use("/api", publicMcpManagementRoutes(personal, f.oauth));
- const path = `/api/mcp/requests/${f.id}/dot-pairing`;
+ const path = `/api/${prefix}/requests/${f.id}/dot-pairing`;
+ expect((await request(app).get(`/api/${prefix}/requests/${f.id}`)).body.agentConnection).toBe(true);
expect((await request(app).post(path).send({ pairingCode: f.pairing.pairingCode })).status).toBe(403);
const preview = await request(app).post(path + "/preview").set("Origin", config.origin).send({ pairingCode: f.pairing.pairingCode });
expect(preview.status).toBe(200);
@@ -208,6 +210,20 @@ describe("Dot onboarding with an operator-issued pairing capability", () => {
await expect(f.oauth.consentDotPairing(f.id, f.pairing.pairingCode)).rejects.toThrow();
await expect(f.oauth.consentDotPairing(await f.begin(), f.pairing.pairingCode)).rejects.toThrow();
});
+ it("does not expose personal assistant requests through the public Dot pairing lane", async () => {
+ const f = await fixture();
+ const personal = createPublicMcpOAuth(db, { ...config, resource: config.origin + "/mcp/paperclip" });
+ const client = await personal.register({ client_name: "Personal", redirect_uris: [callback], grant_types: ["authorization_code"] }, randomUUID());
+ const id = (await personal.authorize({ ...f.input, client_id: client.client_id, resource: config.origin + "/mcp/paperclip", scope: "paperclip:read" })).split("/").at(-1)!;
+ const app = express(); app.use(express.json());
+ app.use((req, _res, next) => { req.actor = { type: "none" }; next(); });
+ app.use("/api", publicMcpManagementRoutes(personal, f.oauth));
+ expect((await request(app).get(`/api/dot-mcp/requests/${id}`)).status).toBe(404);
+ for (const suffix of ["", "/preview"]) {
+ expect((await request(app).post(`/api/dot-mcp/requests/${id}/dot-pairing${suffix}`).set("Origin", config.origin).send({ pairingCode: f.pairing.pairingCode })).status).toBe(404);
+ }
+ expect((await request(app).get(`/api/mcp/requests/${id}`)).status).toBe(200);
+ });
it.each(["expired-code", "expired-request", "revoked", "paused", "viewer", "wrong-company", "dot-disabled", "mcp-disabled"])("rejects %s without creating a grant", async failure => {
const f = await fixture();
let id = f.id;
diff --git a/server/src/__tests__/dot-runner.test.ts b/server/src/__tests__/dot-runner.test.ts
index fe7caa79c8..3d0341e918 100644
--- a/server/src/__tests__/dot-runner.test.ts
+++ b/server/src/__tests__/dot-runner.test.ts
@@ -30,6 +30,9 @@ import { setupRunnerPrpWebSocketServer } from "../realtime/runner-prp-ws.js";
import { finalizeNativeRun } from "../services/native-runtime/native-run-finalizer.js";
import { resolveHeartbeatNativeRuntimeMode, resolveNativeRuntimeMode } from "../services/native-runtime/runtime-mode.js";
import { heartbeatService } from "../services/heartbeat.js";
+import { consumeDotHistoryReceipt, publishActiveDotComment } from "../services/dot-assignment-follow-up.js";
+import { createPostgresWakeQueueAdapter } from "../modules/wake-queue/adapters/postgres.js";
+import { createReleaseIssueExecution } from "../modules/wake-queue/application/use-cases.js";
describe("durable Dot Runner integration", () => {
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
@@ -94,7 +97,7 @@ describe("durable Dot Runner integration", () => {
})).toMatchObject({ kind: "native", profile: { backend: "openai_dot_mcp" } });
});
- async function fixture() {
+ async function fixture(options: { cloudOrigin?: string } = {}) {
const userId = randomUUID();
await db.insert(authUsers).values({ id: userId, name: "Dot operator", email: userId + "@example.test", createdAt: new Date(), updatedAt: new Date() });
const [company] = await db.insert(companies).values({ name: "Dot test", issuePrefix: "DT" + randomBytes(3).toString("hex") }).returning();
@@ -132,7 +135,7 @@ describe("durable Dot Runner integration", () => {
if (body.type === "verification") { verifications++; return Response.json({ challenge: body.challenge }); }
received.push(body); return new Response(null, { status: 204 });
};
- const events = createPublicMcpEvents(db, oauth, async () => { throw new Error("personal API dispatch forbidden"); }, { enableDotRunner: true, fetch: fetcher });
+ const events = createPublicMcpEvents(db, oauth, async () => { throw new Error("personal API dispatch forbidden"); }, { enableDotRunner: true, fetch: fetcher, ...options });
const subscription = { name: "paperclip.dot.mailbox_updated", arguments: { companyId: company!.id, bindingId: pairing.bindingId }, delivery: { mode: "webhook", url: "https://example.com/dot-hook", secret } };
await events.subscribe(principal, subscription);
await events.tick();
@@ -146,6 +149,14 @@ describe("durable Dot Runner integration", () => {
return { company: company!, agent: agent!, userId, broker, principal, oauth, events, subscription, received, snapshot, tokens, client, verifications: () => verifications };
}
+ it("keeps scoped Dot events on tenant OAuth when the Cloud personal broker is configured", async () => {
+ const f = await fixture({ cloudOrigin: "https://cloud-broker.example" });
+ expect(f.verifications()).toBe(1);
+ expect(f.received.at(-1)?.data.kind).toBe("readiness_challenge");
+ await f.broker.revoke(f.company.id, f.agent.id, f.userId);
+ await expect(f.events.subscribe(f.principal, f.subscription)).rejects.toThrow();
+ }, 30000);
+
async function offeredWork(f: Awaited<ReturnType<typeof fixture>>) {
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id,
status: "queued", invocationSource: "assignment", triggerDetail: "system" }).returning();
@@ -282,6 +293,139 @@ describe("durable Dot Runner integration", () => {
} finally { await f.events.unsubscribe(f.principal, f.subscription); await f.events.stop(); }
});
+ it("coalesces a normal comment wake into the accepted Dot mailbox without a second run", async () => {
+ const f = await fixture(), { run, assignment } = await offeredWork(f);
+ const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Active Dot comment",
+ status: "in_progress", assigneeAgentId: f.agent.id, executionRunId: run.id, checkoutRunId: run.id }).returning();
+ await db.update(heartbeatRuns).set({ nativeIssueId: task!.id, issueId: task!.id, status: "running",
+ runtimeMode: "native", nativeSessionId: assignment.normalizedSessionId }).where(eq(heartbeatRuns.id, run.id));
+ await db.update(dotRunnerAssignments).set({ status: "accepted" }).where(eq(dotRunnerAssignments.id, assignment.id));
+ const [comment] = await db.insert(issueComments).values({ companyId: f.company.id, issueId: task!.id,
+ authorUserId: f.userId, body: "Continue the same assignment" }).returning();
+ try {
+ const admitted = await heartbeatService(db).wakeup(f.agent.id, { source: "assignment", triggerDetail: "system",
+ reason: "issue_commented", payload: { issueId: task!.id, commentId: comment!.id },
+ requestedByActorType: "user", requestedByActorId: f.userId,
+ contextSnapshot: { issueId: task!.id, wakeCommentId: comment!.id, wakeReason: "issue_commented" } });
+ expect(admitted?.id).toBe(run.id);
+ await f.events.tick(); await f.events.tick();
+ expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, f.agent.id))).toHaveLength(1);
+ const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, f.agent.id));
+ expect(wakes).toHaveLength(1);
+ expect(wakes[0]).toMatchObject({ status: "deferred_issue_execution", runId: null, finishedAt: null });
+ const mailbox = await db.select().from(dotMailboxItems).where(and(eq(dotMailboxItems.assignmentId, assignment.id), eq(dotMailboxItems.kind, "follow_up")));
+ expect(mailbox).toHaveLength(1);
+ expect(mailbox[0]!.references).toEqual({ assignmentId: assignment.id, commentId: comment!.id });
+ expect(f.received.filter(event => event.data?.kind === "follow_up")).toHaveLength(1);
+ await f.broker.mailbox(f.principal);
+ expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakes[0]!.id)))[0]?.status).toBe("deferred_issue_execution");
+ const [receipt] = await db.insert(dotRunnerOperations).values({ companyId: f.company.id,
+ assignmentId: assignment.id, requestId: randomUUID(), digest: "history", status: "completed",
+ command: { action: "tool", input: { name: "get_task_history", arguments: {} } },
+ outcome: { status: "completed", isError: false, result: { comments: [{ id: comment!.id }] } } }).returning();
+ await consumeDotHistoryReceipt(db, receipt!);
+ await consumeDotHistoryReceipt(db, receipt!);
+ expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakes[0]!.id)))[0]).toMatchObject({ status: "coalesced", runId: run.id });
+ expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, f.agent.id))).toHaveLength(1);
+ } finally {
+ await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, run.id));
+ await db.update(dotRunnerAssignments).set({ status: "fenced" }).where(eq(dotRunnerAssignments.id, assignment.id));
+ await f.events.unsubscribe(f.principal, f.subscription); await f.events.stop();
+ }
+ }, 30000);
+
+ it.each(["finish before delivery", "read before wake admission", "partial history", "failed history"])(
+ "preserves comment delivery when %s", async scenario => {
+ const f = await fixture(), { run, assignment } = await offeredWork(f);
+ await db.update(companies).set({ defaultResponsibleUserId: f.userId }).where(eq(companies.id, f.company.id));
+ const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Dot comment race",
+ status: "in_progress", assigneeAgentId: f.agent.id, responsibleUserId: f.userId,
+ executionRunId: run.id, checkoutRunId: run.id }).returning();
+ await db.update(heartbeatRuns).set({ nativeIssueId: task!.id, issueId: task!.id, status: "running",
+ contextSnapshot: { issueId: task!.id }, runtimeMode: "native", nativeSessionId: assignment.normalizedSessionId }).where(eq(heartbeatRuns.id, run.id));
+ await db.update(dotRunnerAssignments).set({ status: "accepted" }).where(eq(dotRunnerAssignments.id, assignment.id));
+ const comments = await db.insert(issueComments).values([1, 2].map(index => ({ companyId: f.company.id,
+ issueId: task!.id, authorUserId: f.userId, body: "Input " + index }))).returning();
+ const [history] = await db.insert(dotRunnerOperations).values({ companyId: f.company.id,
+ assignmentId: assignment.id, requestId: randomUUID(), digest: "history", status: "completed",
+ command: { action: "tool", input: { name: "get_task_history", arguments: {} } },
+ outcome: { status: "completed", isError: scenario === "failed history",
+ result: { comments: [{ id: comments[0]!.id }] } } }).returning();
+ try {
+ if (scenario === "read before wake admission") await consumeDotHistoryReceipt(db, history!);
+ for (const comment of comments) await heartbeatService(db).wakeup(f.agent.id, {
+ source: "assignment", triggerDetail: "system", reason: "issue_commented",
+ payload: { issueId: task!.id, commentId: comment.id }, requestedByActorType: "user", requestedByActorId: f.userId,
+ contextSnapshot: { issueId: task!.id, wakeCommentId: comment.id, wakeReason: "issue_commented" },
+ });
+ if (scenario === "finish before delivery") {
+ const requestId = randomUUID();
+ await db.insert(dotRunnerOperations).values({ companyId: f.company.id, assignmentId: assignment.id,
+ requestId, digest: "finish", command: { action: "finish" }, status: "admitted" });
+ const port = f.broker.port({ binding: { companyId: f.company.id, agentId: f.agent.id, runId: run.id }, provider: { binding: f.snapshot } });
+ await port.settle({ sourceEventId: randomUUID(), payload: { requestId,
+ binding: { ...f.snapshot, runId: run.id, normalizedSessionId: assignment.normalizedSessionId,
+ turnId: assignment.turnId, assignmentRevision: assignment.revision }, outcome: { status: "completed" } } } as Parameters<typeof port.settle>[0]);
+ await f.events.tick();
+ expect(f.received.filter(event => event.data?.kind === "follow_up")).toHaveLength(0);
+ }
+ await consumeDotHistoryReceipt(db, history!);
+ let wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, f.agent.id));
+ expect(wakes).toHaveLength(scenario === "read before wake admission" ? 2 : 1);
+ const pending = wakes.find(wake => wake.status === "deferred_issue_execution")!;
+ expect(pending.payload?._paperclipWakeContext).toMatchObject({ wakeCommentIds:
+ ["finish before delivery", "failed history"].includes(scenario)
+ ? comments.map(comment => comment.id) : [comments[1]!.id] });
+ if (scenario === "read before wake admission") expect(wakes.find(wake => wake.payload?.commentId === comments[0]!.id)?.status).toBe("coalesced");
+ if (scenario === "finish before delivery") {
+ await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, run.id));
+ await db.update(issues).set({ status: "done" }).where(eq(issues.id, task!.id));
+ const release = createReleaseIssueExecution({ issueLock: createPostgresWakeQueueAdapter(db, {
+ resolveResponsibleUserId: async () => f.userId,
+ getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }),
+ resolveSessionBeforeForWakeup: async () => null,
+ }), recovery: {
+ escalateStrandedAssignedIssue: async () => { throw new Error("unexpected escalation"); },
+ escalateStrandedRecoveryIssueInPlace: async () => { throw new Error("unexpected escalation"); },
+ } });
+ await release({ companyId: f.company.id, runId: run.id, now: new Date(), suppressImmediateRecovery: true });
+ await release({ companyId: f.company.id, runId: run.id, now: new Date(), suppressImmediateRecovery: true });
+ const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, f.agent.id));
+ expect(runs).toHaveLength(2);
+ expect(runs.find(row => row.id !== run.id)).toMatchObject({ status: "queued",
+ contextSnapshot: { wakeCommentIds: comments.map(comment => comment.id) } });
+ wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, f.agent.id));
+ expect(wakes).toHaveLength(1);
+ expect(wakes[0]).toMatchObject({ status: "queued", runId: runs.find(row => row.id !== run.id)!.id });
+ }
+ } finally {
+ await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.agentId, f.agent.id));
+ await db.update(dotRunnerAssignments).set({ status: "fenced" }).where(eq(dotRunnerAssignments.id, assignment.id));
+ await f.events.unsubscribe(f.principal, f.subscription); await f.events.stop();
+ }
+ }, 30000);
+
+ it.each(["foreign comment", "self comment", "revoked binding", "fenced assignment", "expired assignment", "prior generation"])(
+ "refuses active comment delivery for %s", async kind => {
+ const f = await fixture(), { run, assignment } = await offeredWork(f);
+ const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Bounded follow-up", assigneeAgentId: f.agent.id }).returning();
+ await db.update(heartbeatRuns).set({ nativeIssueId: task!.id, status: "running", runtimeMode: "native",
+ nativeSessionId: assignment.normalizedSessionId }).where(eq(heartbeatRuns.id, run.id));
+ await db.update(dotRunnerAssignments).set({ status: "accepted" }).where(eq(dotRunnerAssignments.id, assignment.id));
+ const [comment] = await db.insert(issueComments).values({ companyId: f.company.id, issueId: task!.id,
+ ...(kind === "self comment" ? { authorAgentId: f.agent.id } : { authorUserId: f.userId }), body: "Bounded input" }).returning();
+ if (kind === "revoked binding") await db.update(dotAgentBindings).set({ revokedAt: new Date() }).where(eq(dotAgentBindings.id, f.snapshot.bindingId));
+ if (kind === "fenced assignment") await db.update(dotRunnerAssignments).set({ status: "fenced" }).where(eq(dotRunnerAssignments.id, assignment.id));
+ if (kind === "expired assignment") await db.update(dotRunnerAssignments).set({ expiresAt: new Date(0) }).where(eq(dotRunnerAssignments.id, assignment.id));
+ if (kind === "prior generation") await db.update(dotAgentBindings).set({ generation: f.snapshot.bindingGeneration + 1 }).where(eq(dotAgentBindings.id, f.snapshot.bindingId));
+ try {
+ expect(await db.transaction(tx => publishActiveDotComment(tx as unknown as typeof db, {
+ companyId: f.company.id, agentId: f.agent.id, bindingId: f.snapshot.bindingId, runId: run.id,
+ issueId: task!.id, commentId: kind === "foreign comment" ? randomUUID() : comment!.id }))).toBe(false);
+ expect(await db.select().from(dotMailboxItems).where(and(eq(dotMailboxItems.assignmentId, assignment.id), eq(dotMailboxItems.kind, "follow_up")))).toHaveLength(0);
+ } finally { await f.events.stop(); }
+ }, 30000);
+
it("serializes tool-result writes and cursor reads with the binding mailbox lock", async () => {
const f = await fixture();
const { run, assignment } = await offeredWork(f);
@@ -317,6 +461,23 @@ describe("durable Dot Runner integration", () => {
await f.events.unsubscribe(f.principal, f.subscription); await f.events.stop();
}, 30000);
+ it.each(["succeeded", "failed", "cancelled", "timed_out"] as const)("fences a stranded %s assignment before new admission without claiming external stop", async status => {
+ const f = await fixture();
+ const { run, assignment } = await offeredWork(f);
+ try {
+ await expect(f.broker.snapshot(f.company.id, f.agent.id, f.snapshot.bindingId)).rejects.toThrow("active assignment");
+ await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, run.id));
+ await f.broker.snapshot(f.company.id, f.agent.id, f.snapshot.bindingId);
+ await f.broker.snapshot(f.company.id, f.agent.id, f.snapshot.bindingId);
+ expect((await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.id, assignment.id)))[0]?.status).toBe("fenced");
+ const inbox = await f.broker.mailbox(f.principal);
+ const fences = inbox.items.filter(item => item.assignmentId === assignment.id && item.kind === "authority_revoked");
+ expect(fences).toHaveLength(1);
+ expect(fences[0]?.references).toMatchObject({ assignmentId: assignment.id, runId: run.id, externalStopConfirmed: false });
+ await expect(createDotRunnerMcpTools(db).callTool(f.principal, "paperclip_dot_accept", { assignmentId: assignment.id, requestId: randomUUID() })).rejects.toThrow("revoked");
+ } finally { await f.events.unsubscribe(f.principal, f.subscription); await f.events.stop(); }
+ }, 30000);
+
it("allows paused Dot fence delivery and acknowledgements without task authority", async () => {
const f = await fixture();
const { run, assignment } = await offeredWork(f);
@@ -503,117 +664,170 @@ describe("durable Dot Runner integration", () => {
await f.events.unsubscribe(f.principal, f.subscription);
}, 30000);
- it("signed readiness, normal native authority, one document write and finalization through real Rust", async () => {
- const f = await fixture();
- const [issue] = await db.insert(issues).values({ companyId: f.company.id, title: "Save the arithmetic report", description: "Save 17 + 25 = 42 as a task document.",
- status: "in_progress", workMode: "standard", assigneeAgentId: f.agent.id }).returning();
- const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, status: "running", invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId: issue!.id } }).returning();
- await db.update(issues).set({ executionRunId: run!.id, checkoutRunId: run!.id }).where(eq(issues.id, issue!.id));
- const prepared = await prepareNativeHeartbeatRun({ db, run: run!, issue: issue!, environmentLeaseId: randomUUID() });
- await db.insert(nativeRunFinalizations).values({ runId: run!.id, companyId: f.company.id, issueId: issue!.id, phase: "observed" });
- const [boundRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run!.id));
- const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.id, boundRun!.completionContractId!));
- const runtimeContext = nativeRuntimeContextFixture();
- await writeFile(join(root, "AGENTS.md"), "Use Paperclip tools to save the report.");
- runtimeContext.instructions.bundle.rootPath = root;
- runtimeContext.aggregateDigest = canonicalNativeRuntimeContextDigest(runtimeContext);
- const execution = buildNativeExecutionInput({ companyId: f.company.id, agentId: f.agent.id, runId: run!.id, issue: issue!,
- taskPrompt: issue!.description!, normalizedSessionId: prepared.normalizedSessionId, provider: "openai_dot", dotBinding: f.snapshot,
- workspace: { id: randomUUID(), cwd: root, repoUrl: null, repoRef: null, branchName: null }, runtimeContext,
- completionContract: { id: contract!.id, sha256: contract!.canonicalSha256,
- schemaVersion: contract!.schemaVersion, contract: contract!.contractJson as unknown as StrictCompletionContractInput } });
- await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, run!.id));
- const server = createServer(); await new Promise<void>(done => server.listen(0, "127.0.0.1", done));
- const address = server.address(); if (!address || typeof address === "string") throw new Error("Missing test server");
- setupRunnerPrpWebSocketServer(server, { apiUrl: `http://127.0.0.1:${address.port}` });
- const observed: Array<Record<string, any>> = [];
- const appCall = vi.fn().mockResolvedValue({ status: "completed", result: { content: [{ type: "text", text: "synthetic gateway result" }] } });
- const gatewayTools = [{ name: "fixture:read_status", displayName: "Read fixture status", description: "Read a synthetic app", parametersSchema: { type: "object", properties: {}, additionalProperties: false }, risk: "read" }];
- registerAssignedMcpGateway(db, { listToolsForNamedGateway: vi.fn().mockResolvedValue(gatewayTools), executeTool: appCall } as unknown as ToolGatewayService);
- await db.update(agents).set({ adapterConfig: { ...f.agent.adapterConfig, dotWorkspaceAccess: true, dotAttachmentAccess: true } }).where(eq(agents.id, f.agent.id));
- const resultPromise = executePaperclipNativeSession({ db, execution, dotWorkspaceRoot: root, runnerInstanceId: prepared.runnerInstanceId,
- runnerEnvironment: { PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned", PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3217/mcp/gateways/dot-fixture", PAPERCLIP_NATIVE_MCP_TOKEN: "fixture-gateway-secret" },
- useRunnerd: true, turnTimeoutMs: 45000, onEvent: async event => { observed.push(event); }, onLog: async () => {} });
- // Attach a handler immediately: a bootstrap error must never become an unhandled rejection.
- let startupError: unknown;
- let startupOutcome: unknown;
- void resultPromise.then(result => { startupOutcome = result; }, () => {});
- void resultPromise.catch(error => { startupError = error; });
+ it.each([
+ { name: "local Rust", managed: false },
+ ...(process.env.PAPERCLIP_DOT_DAYTONA_LIVE === "1" ? [{ name: "private Daytona Rust", managed: true }] : []),
+ ])("signed readiness, native tools and finalization through $name", async ({ managed }) => {
+ const remote = managed ? await (await import("./helpers/dot-daytona.js")).startDotDaytona(root) : null;
try {
- await vi.waitFor(async () => { if (startupError) throw startupError; expect(await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId, run!.id))).toHaveLength(1); }, { timeout: 30000, interval: 50 });
- const [assignment] = await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId, run!.id));
- await f.events.tick();
- expect(JSON.stringify(f.received)).not.toContain("17 + 25");
- const work = await f.broker.read(f.principal, assignment!.id);
- expect(work.accounting).toEqual({ usage: null, cost: null });
- expect(work.status).toBe("offered");
- expect(observed.filter(event => event.eventType === "turn.started")).toHaveLength(0);
- expect(JSON.stringify(work)).not.toContain(root);
- expect((work.tools as Array<{ operationId: string }>).some(tool => tool.operationId === "register_deliverable")).toBe(true);
- expect(await f.broker.operation(f.principal, assignment!.id, randomUUID(), "tool", { name: "write_document", arguments: {} })).toMatchObject({ status: "rejected" });
- await f.broker.operation(f.principal, assignment!.id, randomUUID(), "accept", {});
- expect(JSON.stringify(work)).not.toContain("fixture-gateway-secret");
- const app = (work.tools as Array<{ operationId: string }>).find(tool => tool.operationId.startsWith("app_"))!;
- expect(app).toBeTruthy();
- const missingReadId = randomUUID();
- await f.broker.operation(f.principal, assignment!.id, missingReadId, "tool", { name: "workspace_read", arguments: { path: "missing-fixture.txt", offset: 0 } });
- await vi.waitFor(async () => expect(await f.broker.operationStatus(f.principal, assignment!.id, missingReadId)).toMatchObject({ status: "completed", isError: true, result: { outcome: "failed", code: "runner_bridge_file_not_found" } }), { timeout: 10000 });
- // A definite read failure must not poison later calls or finalization.
- const attachmentListId = randomUUID();
- expect((work.tools as Array<{ operationId: string }>).some(tool => tool.operationId === "read_task_attachment")).toBe(true);
- await f.broker.operation(f.principal, assignment!.id, attachmentListId, "tool", { name: "list_task_attachments", arguments: {} });
- await vi.waitFor(async () => expect(await f.broker.operationStatus(f.principal, assignment!.id, attachmentListId)).toMatchObject({ status: "completed", isError: false, result: { attachments: [] } }), { timeout: 10000 });
- const appRequestId = randomUUID();
- await f.broker.operation(f.principal, assignment!.id, appRequestId, "tool", { name: app.operationId, arguments: {} });
- await vi.waitFor(async () => expect(await f.broker.operationStatus(f.principal, assignment!.id, appRequestId)).toMatchObject({ status: "completed", isError: false }), { timeout: 10000 });
- expect(appCall).toHaveBeenCalledWith(expect.objectContaining({ gatewayPublicId: "dot-fixture", sessionToken: "fixture-gateway-secret", tool: "fixture:read_status" }));
- await db.update(agents).set({ budgetMonthlyCents: 100, spentMonthlyCents: 100 }).where(eq(agents.id, f.agent.id));
- await expect(f.broker.read(f.principal, assignment!.id)).rejects.toThrow("execution authority");
- await db.update(agents).set({ budgetMonthlyCents: 0, spentMonthlyCents: 0, status: "paused" }).where(eq(agents.id, f.agent.id));
- await expect(f.broker.read(f.principal, assignment!.id)).rejects.toThrow("authority");
- await db.update(agents).set({ status: "active" }).where(eq(agents.id, f.agent.id));
- await db.update(issues).set({ executionRunId: null, checkoutRunId: null }).where(eq(issues.id, issue!.id));
- await expect(f.broker.read(f.principal, assignment!.id)).rejects.toThrow("execution authority");
+ const f = await fixture();
+ const [issue] = await db.insert(issues).values({ companyId: f.company.id, title: "Save the arithmetic report", description: "Save 17 + 25 = 42 as a task document.",
+ status: "in_progress", workMode: "standard", assigneeAgentId: f.agent.id }).returning();
+ const [run] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id, status: "running", invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId: issue!.id } }).returning();
await db.update(issues).set({ executionRunId: run!.id, checkoutRunId: run!.id }).where(eq(issues.id, issue!.id));
- const writeId = randomUUID();
- const args = { name: "write_document", arguments: { key: "report", title: "Arithmetic", body: "17 + 25 = 42.", baseRevisionId: null, idempotencyKey: writeId } };
- await f.broker.operation(f.principal, assignment!.id, writeId, "tool", args);
- await vi.waitFor(async () => expect(await f.broker.operationStatus(f.principal, assignment!.id, writeId)).toMatchObject({ status: "completed", isError: false }), { timeout: 10000 });
- await f.broker.operation(f.principal, assignment!.id, writeId, "tool", args);
- await expect(f.broker.operation(f.principal, assignment!.id, writeId, "tool", { ...args, arguments: { ...args.arguments, body: "changed" } })).rejects.toThrow("different arguments");
- const document = await documentService(db).getIssueDocumentByKey(issue!.id, "report");
- expect(document?.body).toBe("17 + 25 = 42.");
- const result = { reportedWorkDisposition: "completed", summary: "Saved the arithmetic report.",
- completionClaim: { contractRevision: execution.completionContract.contract.revision, objectiveSatisfied: true,
- criteria: execution.completionContract.contract.criteria.map(c => ({ criterionId: c.id, status: "passed", evidenceRefs: [] })), remainingWork: [] },
- evidence: [], verification: [{ commandOrCheck: "17 + 25", status: "pass" }] };
- const completionId = randomUUID();
- await f.broker.operation(f.principal, assignment!.id, completionId, "tool", { name: "paperclip_finish", arguments: result });
- await vi.waitFor(async () => expect(await f.broker.operationStatus(f.principal, assignment!.id, completionId)).toMatchObject({ status: "completed", isError: false }), { timeout: 10000 });
- expect(await f.broker.operationStatus(f.principal, assignment!.id, completionId)).toMatchObject({ result: { completionReport: {
- schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", artifacts: [], attentionRequests: [],
- verification: [{ commandOrCheck: "17 + 25", status: "passed" }],
- } } });
- await f.broker.operation(f.principal, assignment!.id, randomUUID(), "finish", { result });
- await resultPromise;
- // The heartbeat records its controller workspace settlement before the
- // ordinary status finalizer commits the task disposition.
- await db.insert(workspaceOperations).values({ companyId: f.company.id, heartbeatRunId: run!.id, issueId: issue!.id,
- phase: "workspace_finalize", status: "succeeded", exitCode: 0, cwd: root, finishedAt: new Date() });
- await finalizeNativeRun({ db, runId: run!.id, workspaceFinalizeStatus: "succeeded" });
- await finalizeNativeRun({ db, runId: run!.id, workspaceFinalizeStatus: "succeeded" });
- expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, run!.id))).toHaveLength(1);
- expect((await db.select().from(issues).where(eq(issues.id, issue!.id)))[0]?.status).toBe("done");
- expect(await db.select().from(dotRunnerOperations).where(eq(dotRunnerOperations.requestId, writeId))).toHaveLength(1);
- expect(startupOutcome).toMatchObject({ exitCode: 0, model: null, nativeFinalization: { providerSessionId: null, driverKind: "openai_dot_mcp" } });
- expect(observed.filter(event => event.eventType === "turn.started")).toHaveLength(1);
- } catch (error) {
- if (startupError) throw startupError;
- await Promise.race([resultPromise.catch(() => {}), new Promise(resolve => setTimeout(resolve, 1000))]);
- if (startupError) throw startupError;
- throw error;
- } finally { await f.events.unsubscribe(f.principal, f.subscription); await f.events.stop(); server.closeAllConnections(); await new Promise<void>(done => server.close(() => done())); }
- }, 90000);
+ const prepared = await prepareNativeHeartbeatRun({ db, run: run!, issue: issue!, environmentLeaseId: randomUUID() });
+ await db.insert(nativeRunFinalizations).values({ runId: run!.id, companyId: f.company.id, issueId: issue!.id, phase: "observed" });
+ const [boundRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run!.id));
+ const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.id, boundRun!.completionContractId!));
+ const runtimeContext = nativeRuntimeContextFixture();
+ await writeFile(join(root, "AGENTS.md"), "Use Paperclip tools to save the report.");
+ runtimeContext.instructions.bundle.rootPath = root;
+ runtimeContext.aggregateDigest = canonicalNativeRuntimeContextDigest(runtimeContext);
+ const execution = buildNativeExecutionInput({ companyId: f.company.id, agentId: f.agent.id, runId: run!.id, issue: issue!,
+ taskPrompt: issue!.description!, normalizedSessionId: prepared.normalizedSessionId, provider: "openai_dot", dotBinding: f.snapshot,
+ workspace: { id: randomUUID(), cwd: root, repoUrl: null, repoRef: null, branchName: null }, runtimeContext,
+ completionContract: { id: contract!.id, sha256: contract!.canonicalSha256,
+ schemaVersion: contract!.schemaVersion, contract: contract!.contractJson as unknown as StrictCompletionContractInput } });
+ await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, run!.id));
+ const server = createServer(); await new Promise<void>(done => server.listen(0, "127.0.0.1", done));
+ const address = server.address(); if (!address || typeof address === "string") throw new Error("Missing test server");
+ setupRunnerPrpWebSocketServer(server, { apiUrl: `http://127.0.0.1:${address.port}` });
+ const observed: Array<Record<string, any>> = [];
+ const appCall = vi.fn().mockResolvedValue({ status: "completed", result: { content: [{ type: "text", text: "synthetic gateway result" }] } });
+ const gatewayTools = [{ name: "fixture:read_status", displayName: "Read fixture status", description: "Read a synthetic app", parametersSchema: { type: "object", properties: {}, additionalProperties: false }, risk: "read" }];
+ registerAssignedMcpGateway(db, { listToolsForNamedGateway: vi.fn().mockResolvedValue(gatewayTools), executeTool: appCall } as unknown as ToolGatewayService);
+ await db.update(agents).set({ adapterConfig: { ...f.agent.adapterConfig, dotWorkspaceAccess: true, dotAttachmentAccess: true } }).where(eq(agents.id, f.agent.id));
+ vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "fixture-cloud");
+ try {
+ for (const useRunnerd of [false, true]) {
+ await expect(executePaperclipNativeSession({ db, execution, runnerInstanceId: prepared.runnerInstanceId,
+ useRunnerd, turnTimeoutMs: 1000, onEvent: async () => {} }))
+ .rejects.toThrow("dot_cloud_requires_managed_runner");
+ }
+ } finally { vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", ""); }
+ const resultPromise = executePaperclipNativeSession({ db, execution,
+ ...(remote ? { runnerExecutionTarget: remote.target, runnerRemoteBinaryPath: remote.runnerBinary, runnerIngressAuthorized: true }
+ : { dotWorkspaceRoot: root }),
+ runnerInstanceId: prepared.runnerInstanceId,
+ runnerEnvironment: { PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned", PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3217/mcp/gateways/dot-fixture", PAPERCLIP_NATIVE_MCP_TOKEN: "fixture-gateway-secret" },
+ useRunnerd: true, turnTimeoutMs: 45000, onEvent: async event => { observed.push(event); }, onLog: async () => {} });
+ // Attach a handler immediately: a bootstrap error must never become an unhandled rejection.
+ let startupError: unknown;
+ let startupOutcome: unknown;
+ void resultPromise.then(result => { startupOutcome = result; }, () => {});
+ void resultPromise.catch(error => { startupError = error; });
+ try {
+ await vi.waitFor(async () => { if (startupError) throw startupError; expect(await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId, run!.id))).toHaveLength(1); }, { timeout: 30000, interval: 50 });
+ const [assignment] = await db.select().from(dotRunnerAssignments).where(eq(dotRunnerAssignments.runId, run!.id));
+ await f.events.tick();
+ expect(JSON.stringify(f.received)).not.toContain("17 + 25");
+ const work = await f.broker.read(f.principal, assignment!.id);
+ expect(work.accounting).toEqual({ usage: null, cost: null });
+ expect(work.status).toBe("offered");
+ expect(observed.filter(event => event.eventType === "turn.started")).toHaveLength(0);
+ expect(JSON.stringify(work)).not.toContain(root);
+ expect((work.tools as Array<{ operationId: string }>).some(tool => tool.operationId === "register_deliverable")).toBe(true);
+ expect(await f.broker.operation(f.principal, assignment!.id, randomUUID(), "tool", { name: "write_document", arguments: {} })).toMatchObject({ status: "rejected" });
+ await f.broker.operation(f.principal, assignment!.id, randomUUID(), "accept", {});
+ expect(JSON.stringify(work)).not.toContain("fixture-gateway-secret");
+ const app = (work.tools as Array<{ operationId: string }>).find(tool => tool.operationId.startsWith("app_"))!;
+ expect(app).toBeTruthy();
+ if (remote) {
+ expect((work.tools as Array<{ operationId: string }>).some(tool => tool.operationId.startsWith("workspace_"))).toBe(false);
+ } else {
+ const missingReadId = randomUUID();
+ await f.broker.operation(f.principal, assignment!.id, missingReadId, "tool", { name: "workspace_read", arguments: { path: "missing-fixture.txt", offset: 0 } });
+ await vi.waitFor(async () => expect(await f.broker.operationStatus(f.principal, assignment!.id, missingReadId)).toMatchObject({ status: "completed", isError: true, result: { outcome: "failed", code: "runner_bridge_file_not_found" } }), { timeout: 10000 });
+ }
+ // A definite read failure must not poison later calls or finalization.
+ const attachmentListId = randomUUID();
+ expect((work.tools as Array<{ operationId: string }>).some(tool => tool.operationId === "read_task_attachment")).toBe(true);
+ await f.broker.operation(f.principal, assignment!.id, attachmentListId, "tool", { name: "list_task_attachments", arguments: {} });
+ await vi.waitFor(async () => expect(await f.broker.operationStatus(f.principal, assignment!.id, attachmentListId)).toMatchObject({ status: "completed", isError: false, result: { attachments: [] } }), { timeout: 10000 });
+ const appRequestId = randomUUID();
+ await f.broker.operation(f.principal, assignment!.id, appRequestId, "tool", { name: app.operationId, arguments: {} });
+ await vi.waitFor(async () => expect(await f.broker.operationStatus(f.principal, assignment!.id, appRequestId)).toMatchObject({ status: "completed", isError: false }), { timeout: 10000 });
+ expect(appCall).toHaveBeenCalledWith(expect.objectContaining({ gatewayPublicId: "dot-fixture", sessionToken: "fixture-gateway-secret", tool: "fixture:read_status" }));
+ await db.update(agents).set({ budgetMonthlyCents: 100, spentMonthlyCents: 100 }).where(eq(agents.id, f.agent.id));
+ await expect(f.broker.read(f.principal, assignment!.id)).rejects.toThrow("execution authority");
+ await db.update(agents).set({ budgetMonthlyCents: 0, spentMonthlyCents: 0, status: "paused" }).where(eq(agents.id, f.agent.id));
+ await expect(f.broker.read(f.principal, assignment!.id)).rejects.toThrow("authority");
+ await db.update(agents).set({ status: "active" }).where(eq(agents.id, f.agent.id));
+ await db.update(issues).set({ executionRunId: null, checkoutRunId: null }).where(eq(issues.id, issue!.id));
+ await expect(f.broker.read(f.principal, assignment!.id)).rejects.toThrow("execution authority");
+ await db.update(issues).set({ executionRunId: run!.id, checkoutRunId: run!.id }).where(eq(issues.id, issue!.id));
+ const writeId = randomUUID();
+ const args = { name: "write_document", arguments: { key: "report", title: "Arithmetic", body: "17 + 25 = 42.", baseRevisionId: null, idempotencyKey: writeId } };
+ await f.broker.operation(f.principal, assignment!.id, writeId, "tool", args);
+ await vi.waitFor(async () => expect(await f.broker.operationStatus(f.principal, assignment!.id, writeId)).toMatchObject({ status: "completed", isError: false }), { timeout: 10000 });
+ await f.broker.operation(f.principal, assignment!.id, writeId, "tool", args);
+ await expect(f.broker.operation(f.principal, assignment!.id, writeId, "tool", { ...args, arguments: { ...args.arguments, body: "changed" } })).rejects.toThrow("different arguments");
+ const document = await documentService(db).getIssueDocumentByKey(issue!.id, "report");
+ expect(document?.body).toBe("17 + 25 = 42.");
+ const result = { reportedWorkDisposition: "completed", summary: "Saved the arithmetic report.",
+ completionClaim: { contractRevision: execution.completionContract.contract.revision, objectiveSatisfied: true,
+ criteria: execution.completionContract.contract.criteria.map(c => ({ criterionId: c.id, status: "passed", evidenceRefs: [] })), remainingWork: [] },
+ evidence: [], verification: [{ commandOrCheck: "17 + 25", status: "pass" }] };
+ const completionId = randomUUID();
+ await f.broker.operation(f.principal, assignment!.id, completionId, "tool", { name: "paperclip_finish", arguments: result });
+ await vi.waitFor(async () => expect(await f.broker.operationStatus(f.principal, assignment!.id, completionId)).toMatchObject({ status: "completed", isError: false }), { timeout: 10000 });
+ expect(await f.broker.operationStatus(f.principal, assignment!.id, completionId)).toMatchObject({ result: { completionReport: {
+ schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", artifacts: [], attentionRequests: [],
+ verification: [{ commandOrCheck: "17 + 25", status: "passed" }],
+ } } });
+ await f.broker.operation(f.principal, assignment!.id, randomUUID(), "finish", { result });
+ await resultPromise;
+ // The heartbeat records its controller workspace settlement before the
+ // ordinary status finalizer commits the task disposition.
+ await db.insert(workspaceOperations).values({ companyId: f.company.id, heartbeatRunId: run!.id, issueId: issue!.id,
+ phase: "workspace_finalize", status: "succeeded", exitCode: 0, cwd: root, finishedAt: new Date() });
+ await finalizeNativeRun({ db, runId: run!.id, workspaceFinalizeStatus: "succeeded" });
+ await finalizeNativeRun({ db, runId: run!.id, workspaceFinalizeStatus: "succeeded" });
+ expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, run!.id))).toHaveLength(1);
+ expect((await db.select().from(issues).where(eq(issues.id, issue!.id)))[0]?.status).toBe("done");
+ expect(await db.select().from(dotRunnerOperations).where(eq(dotRunnerOperations.requestId, writeId))).toHaveLength(1);
+ expect(startupOutcome).toMatchObject({ exitCode: 0, model: null, nativeFinalization: { providerSessionId: null, driverKind: "openai_dot_mcp" } });
+ expect(observed.filter(event => event.eventType === "turn.started")).toHaveLength(1);
+ } catch (error) {
+ if (startupError) throw startupError;
+ await Promise.race([resultPromise.catch(() => {}), new Promise(resolve => setTimeout(resolve, 1000))]);
+ if (startupError) throw startupError;
+ throw error;
+ } finally { await f.events.unsubscribe(f.principal, f.subscription); await f.events.stop(); server.closeAllConnections(); await new Promise<void>(done => server.close(() => done())); }
+ } finally { await remote?.close(); }
+ }, 360000);
+
+ it.each(["failed", "cancelled", "timed_out"])("reports %s admission without creating another wake or waiting for a nonexistent assignment", async status => {
+ const f = await fixture();
+ const { run } = await offeredWork(f);
+ await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, run.id));
+ const requestId = randomUUID(), issueId = randomUUID();
+ await db.insert(agentWakeupRequests).values({ companyId: f.company.id, agentId: f.agent.id,
+ source: "assignment", status: "admitted", runId: run.id, payload: { issueId },
+ idempotencyKey: `dot-work:${f.snapshot.bindingId}:${f.snapshot.bindingGeneration}:${requestId}` });
+ const result = await f.broker.requestWork(f.principal, issueId, requestId);
+ expect(result).toMatchObject({ status: "admission_failed", runId: run.id, admissionStatus: status });
+ expect(result.message).toContain("Stop waiting");
+ expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, f.agent.id))).toHaveLength(1);
+ });
+
+ it("uses the app-configured heartbeat for Dot-originated managed admission and cancellation", async () => {
+ const f = await fixture();
+ const wakeup = vi.fn().mockResolvedValue(null);
+ const cancelRun = vi.fn().mockResolvedValue(null);
+ createDotRunnerMcpTools(db, { wakeup, cancelRun });
+ try {
+ const requestId = randomUUID();
+ const intake = await f.broker.requestTurn(f.principal, "Managed intake context test", requestId);
+ expect(wakeup).toHaveBeenCalledExactlyOnceWith(f.agent.id, expect.objectContaining({
+ source: "assignment", requestedByActorType: "agent", requestedByActorId: f.agent.id,
+ durableDotRequest: expect.objectContaining({ issueId: intake.issueId, requestId }),
+ }));
+ const assignment = await offeredWork(f);
+ await f.broker.revoke(f.company.id, f.agent.id, f.userId);
+ expect(cancelRun).toHaveBeenCalledExactlyOnceWith(assignment.run.id, "Dot connection revoked");
+ } finally { dotRunnerBroker(db, { heartbeat: heartbeatService(db) }); }
+ });
it("revocation, membership loss and a foreign company cannot recover authority", async () => {
const f = await fixture(); const other = await fixture();
diff --git a/server/src/__tests__/helpers/dot-daytona.ts b/server/src/__tests__/helpers/dot-daytona.ts
new file mode 100644
index 0000000000..d4869cf344
--- /dev/null
+++ b/server/src/__tests__/helpers/dot-daytona.ts
@@ -0,0 +1,97 @@
+import { createRequire } from "node:module";
+import { createHash, randomUUID } from "node:crypto";
+import { readFile, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils";
+import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
+import { shellQuote } from "@paperclipai/adapter-utils/ssh";
+
+/** Opt-in, bounded live fixture. Every invocation owns and deletes its sandbox. */
+export async function startDotDaytona(localRoot: string) {
+ const image = process.env.PAPERCLIP_DOT_DAYTONA_IMAGE;
+ if (!image || !/@sha256:[a-f0-9]{64}$/.test(image)) throw new Error("Dot live tests require an immutable Daytona image digest");
+ const require = createRequire(new URL("../../../../packages/plugins/sandbox-providers/daytona/package.json", import.meta.url));
+ const { Daytona } = require("@daytonaio/sdk");
+ const sandbox = await new Daytona({ apiKey: process.env.DAYTONA_API_KEY }).create({
+ image, public: false, autoStopInterval: 10, ttlMinutes: 20,
+ labels: { "paperclip-test": "dot-managed-runner" },
+ }, { timeout: 180 });
+ const workspace = "/home/daytona/dot-managed-test";
+ const executeSource = `
+ const {spawn} = require('node:child_process');
+ const input = JSON.parse(process.argv[1]);
+ const child = spawn(input.command, input.args || [], {
+ cwd: input.cwd, env: {...process.env, ...input.env}, timeout: input.timeoutMs || 30000
+ });
+ const stdout = [], stderr = [];
+ child.stdout.on('data', chunk => stdout.push(chunk));
+ child.stderr.on('data', chunk => stderr.push(chunk));
+ child.on('error', error => stderr.push(Buffer.from(error.message)));
+ child.on('close', (exitCode, signal) => process.stdout.write(JSON.stringify({
+ exitCode, signal, timedOut: signal === 'SIGTERM', pid: null,
+ startedAt: new Date().toISOString(),
+ stdout: Buffer.concat(stdout).toString(), stderr: Buffer.concat(stderr).toString()
+ })));
+ child.stdin.on('error', error => { if (error.code !== 'EPIPE') stderr.push(Buffer.from(error.message)); });
+ child.stdin.end(input.stdin || '');
+ `;
+ const runner: CommandManagedRuntimeRunner = {
+ execute: async input => {
+ const command = `node --input-type=commonjs -e ${shellQuote(executeSource)} ${shellQuote(JSON.stringify(input))}`;
+ const result = await sandbox.process.executeCommand(command, undefined, undefined, Math.ceil((input.timeoutMs ?? 30000) / 1000) + 10);
+ if (result.exitCode !== 0) throw new Error(`Daytona command transport failed (exit ${result.exitCode})`);
+ return JSON.parse(result.result);
+ },
+ syncIn: async operations => {
+ const results = [];
+ for (const operation of operations) {
+ let bytesTransferred = 0;
+ for (const file of operation.files) {
+ if (file.kind !== "file") throw new Error("Dot test stages only the verified runner artifact");
+ await sandbox.fs.createFolder(dirname(file.targetPath), "700");
+ const bytes = await readFile(file.sourcePath);
+ await sandbox.fs.uploadFile(bytes, file.targetPath);
+ await sandbox.fs.setFilePermissions(file.targetPath, { mode: (file.mode ?? 0o600).toString(8) });
+ bytesTransferred += bytes.length;
+ }
+ results.push({ operationId: operation.operationId, filesTransferred: operation.files.length, bytesTransferred });
+ }
+ return { operations: results };
+ },
+ };
+ try {
+ const setup = await runner.execute({ command: "mkdir", args: ["-p", workspace], timeoutMs: 10000 });
+ if (setup.exitCode !== 0) throw new Error("Daytona test workspace creation failed");
+ const binary = process.env.PAPERCLIP_DOT_DAYTONA_RUNNER_BINARY
+ ? await readFile(process.env.PAPERCLIP_DOT_DAYTONA_RUNNER_BINARY)
+ : await sandbox.fs.downloadFile("/usr/local/bin/paperclip-runnerd");
+ const runnerBinary = join(localRoot, "daytona-paperclip-runnerd");
+ await writeFile(runnerBinary, binary, { mode: 0o700 });
+ const qualificationBinary = join(workspace, "qualification-runnerd");
+ await sandbox.fs.uploadFile(binary, qualificationBinary);
+ await sandbox.fs.setFilePermissions(qualificationBinary, { mode: "700" });
+ const metadata = await runner.execute({ command: qualificationBinary, args: ["--build-metadata"], timeoutMs: 10000 });
+ if (metadata.exitCode !== 0) throw new Error("Daytona qualification runner build metadata missing");
+ const evidence = { image, sandboxId: sandbox.id, binarySha256: createHash("sha256").update(binary).digest("hex"), metadata: JSON.parse(metadata.stdout) };
+ const evidencePath = process.env.PAPERCLIP_DOT_DAYTONA_EVIDENCE;
+ if (evidencePath) await writeFile(evidencePath, JSON.stringify(evidence, null, 2));
+ const target: AdapterSandboxExecutionTarget = {
+ kind: "remote", transport: "sandbox", providerKey: "daytona", environmentId: randomUUID(),
+ leaseId: randomUUID(), remoteCwd: workspace, runner,
+ effectiveCapabilities: { runnerWebSocketIngress: true } as AdapterSandboxExecutionTarget["effectiveCapabilities"],
+ getRunnerIngressEndpoint: async ({ port, path }) => {
+ const preview = await sandbox.getPreviewLink(port);
+ const url = new URL(preview.url);
+ url.protocol = "wss:";
+ url.pathname = `${url.pathname.replace(/\/$/, "")}${path}`;
+ return { kind: "authenticated_websocket", websocketUrl: url.toString(),
+ secretHeaders: [{ name: "X-Daytona-Preview-Token", value: preview.token }],
+ generation: "dot-test", refresh: () => target.getRunnerIngressEndpoint!({ leaseId: target.leaseId!, port, path }), close: async () => {} };
+ },
+ };
+ return { target, runnerBinary, evidence, close: async () => {
+ await sandbox.delete();
+ if (evidencePath) await writeFile(evidencePath, JSON.stringify({ ...evidence, cleanup: "deleted" }, null, 2));
+ } };
+ } catch (error) { await sandbox.delete(); throw error; }
+}
diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts
index ed79f9537f..0833032985 100644
--- a/server/src/__tests__/openapi-routes.test.ts
+++ b/server/src/__tests__/openapi-routes.test.ts
@@ -85,6 +85,7 @@ const apiPrefixes: Record<string, string> = {
const ROUTE_LITERAL_PATTERN =
/router\.(get|post|put|patch|delete)\(\s*["'`]([^"'`]+)["'`]/g;
+const ROUTE_ARRAY_PATTERN = /router\.(get|post|put|patch|delete)\(\s*\[([^\]]+)\]/g;
const ROUTER_METHOD_PATTERN = /router\.(get|post|put|patch|delete)\(/;
const HTTP_METHODS = new Set([
"get",
@@ -106,6 +107,8 @@ const explicitOpenApiOperationCoverageExclusions = new Set([
"POST /api/customer-success/v1/read",
// OAuth discovery and protocol endpoints have their own metadata contract;
// browser connection-management operations remain documented in the board API.
+ // Markdown rendering of the separately documented assistant setup page.
+ "GET /api/mcp/setup.md",
"GET /.well-known/oauth-authorization-server",
"POST /mcp/oauth/register",
"POST /mcp/oauth/device_authorization",
@@ -215,6 +218,14 @@ function loadActualRoutes() {
}
}
+ for (const match of source.matchAll(ROUTE_ARRAY_PATTERN)) {
+ for (const literal of match[2].matchAll(/["'`]([^"'`]+)["'`]/g)) {
+ const operation = `${match[1].toUpperCase()} ${normalizeExpressPath(resolveMountedPath(file, prefix, literal[1]))}`;
+ if (explicitOpenApiOperationCoverageExclusions.has(operation)) excludedRoutes.add(operation);
+ else routes.add(operation);
+ }
+ }
+
if (file === "public-mcp.ts") {
// The shared gateway mounts these protocol paths for each OAuth resource.
if (source.includes("router.get(metadataPath,")) {
@@ -288,6 +299,19 @@ describe("openapi routes", () => {
expect(properties).toHaveProperty("budgetMonthlyCents");
});
+ it("documents public Dot pairing capabilities while ordinary consent keeps board authentication", () => {
+ const spec = buildOpenApiSpec() as any;
+ for (const [method, path] of [
+ ["get", "/api/dot-mcp/requests/{id}"],
+ ["post", "/api/dot-mcp/requests/{id}/dot-pairing"],
+ ["post", "/api/dot-mcp/requests/{id}/dot-pairing/preview"],
+ ]) {
+ expect(spec.paths[path][method].security).toEqual([]);
+ expect(spec.paths[path][method].responses["404"]).toBeDefined();
+ }
+ expect(spec.paths["/api/mcp/requests/{id}/consent"].post.security).not.toEqual([]);
+ });
+
it("documents manager-only task privacy hints without protected scope identity", () => {
const spec = buildOpenApiSpec() as any;
const operation = spec.paths["/api/issues/{id}/privacy-constraints"].get;
diff --git a/server/src/app.ts b/server/src/app.ts
index fdf1d385de..524483caa9 100644
--- a/server/src/app.ts
+++ b/server/src/app.ts
@@ -1022,7 +1022,7 @@ export async function createApp(
const dotOAuth = createPublicMcpOAuth(db, { ...publicMcpOAuth.config, resource: publicMcpOAuth.config.origin + "/mcp/runner" });
dotMcpEvents = createPublicMcpEvents(db, dotOAuth, dispatch, { enableDotRunner: true, isBackgroundWorkEnabled: () => !isWarmStandby() && !isIdleTaskDrainActive() });
dotMcpEvents.start();
- publicMcpIngress.use(publicMcpIngressRoutes(dotOAuth, createPublicMcpExecutor(db, dotOAuth, dispatch), dotMcpEvents, createDotRunnerMcpTools(db)));
+ publicMcpIngress.use(publicMcpIngressRoutes(dotOAuth, createPublicMcpExecutor(db, dotOAuth, dispatch), dotMcpEvents, createDotRunnerMcpTools(db, connectionIntentHeartbeat)));
api.use(publicMcpManagementRoutes(publicMcpOAuth, dotOAuth));
api.use(dotRunnerRoutes(db, publicMcpOAuth.config.origin + "/mcp/runner"));
}
diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts
index 0484bce3ca..23a2936072 100644
--- a/server/src/routes/agents.ts
+++ b/server/src/routes/agents.ts
@@ -5,6 +5,7 @@ import { createAgentLifecycle } from "../services/agent-lifecycle.js";
import { agentIdentityService } from "../services/agent-identity.js";
import { aiConnectionRouterService, poolMemberRuntimeConfig } from "../services/ai-connection-router.js";
import { connectionIntentService } from "../services/connection-intents.js";
+import { isCloudManagedInstance } from "../services/cloud-instance.js";
import { dotRunnerBroker } from "../services/dot-runner-broker.js";
import { publicMcpConfig } from "../services/public-mcp/oauth.js";
import { connectionIntentDeliveryService } from "../services/connection-intent-delivery.js";
@@ -3148,12 +3149,22 @@ export function agentRoutes(
const binding = savedAgentId ? await dotRunnerBroker(db).bindingForAgent(companyId, savedAgentId) : null;
let resource: ReturnType<typeof publicMcpConfig> = null;
try { resource = publicMcpConfig(process.env); } catch { /* diagnostic below */ }
+ let environment = requestedEnvironmentId ? await environmentsSvc.getById(requestedEnvironmentId) : null;
+ const managedOnly = isCloudManagedInstance() || (await instanceSettings.getExperimental()).enableManagedSandboxOnly === true;
+ if (managedOnly && (!environment || environment.driver === "local")) {
+ environment = await environmentsSvc.findManagedSandboxEnvironment(companyId);
+ }
+ const controllerAvailable = !managedOnly || environment?.driver === "sandbox";
const checks: AdapterEnvironmentCheck[] = [
{ code: "dot_enabled", level: dotEnabled ? "info" : "error", message: dotEnabled ? "Dot is enabled." : "Enable OpenAI Dot and Assistant connections (MCP) in experimental settings." },
{ code: "dot_public_endpoint", level: resource?.origin.startsWith("https://") ? "info" : "error", message: resource?.origin.startsWith("https://") ? "Public HTTPS MCP origin is configured." : "Configure a stable public HTTPS PAPERCLIP_PUBLIC_URL." },
{ code: "dot_unmetered", level: inputAdapterConfig.allowUnmeteredProvider === true ? "info" : "error", message: "Dot usage and provider cost are unavailable. Explicit externally billed provider acknowledgement is required." },
{ code: "dot_binding", level: binding?.status === "ready" && binding.subscriptionVerified && binding.id === inputAdapterConfig.dotBindingId ? "info" : "warn", message: binding?.status === "ready" && binding.subscriptionVerified ? "Binding has a verified event subscription and completed readiness challenge." : "Save this agent, pair it, subscribe to mailbox events and complete the event test." },
- { code: "dot_controller", level: requestedEnvironmentId && (await environmentsSvc.getById(requestedEnvironmentId))?.driver !== "local" ? "error" : "info", message: "Dot currently requires a self-hosted local Runner controller." },
+ { code: "dot_controller", level: controllerAvailable ? "info" : "error", message: controllerAvailable
+ ? environment?.driver === "sandbox" ? "Dot assignments use the selected managed sandbox Runner." : "Dot assignments use the selected Runner environment."
+ : "Restore the managed sandbox before assigning Dot work. Dot cannot run on the Cloud control-plane host." },
+ ...(environment?.driver === "sandbox" && inputAdapterConfig.dotWorkspaceAccess === true
+ ? [{ code: "dot_workspace", level: "error" as const, message: "Managed Dot runners do not expose workspace access. Turn off workspace access before assigning work." }] : []),
];
res.json({ adapterType: type, status: checks.some(c => c.level === "error") ? "fail" : checks.some(c => c.level === "warn") ? "warn" : "pass", testedAt: new Date().toISOString(), checks });
return;
diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts
index b9fe16afcc..83c6f0b04a 100644
--- a/server/src/routes/openapi.ts
+++ b/server/src/routes/openapi.ts
@@ -1712,7 +1712,10 @@ function resolveOperationAuthLevel(
const key = operationKey(method, path);
if (key === "GET /api/mcp/requests/{id}" || key === "GET /api/mcp/device"
|| key === "POST /api/mcp/requests/{id}/dot-pairing"
- || key === "POST /api/mcp/requests/{id}/dot-pairing/preview") return "public";
+ || key === "POST /api/mcp/requests/{id}/dot-pairing/preview"
+ || key === "GET /api/dot-mcp/requests/{id}"
+ || key === "POST /api/dot-mcp/requests/{id}/dot-pairing"
+ || key === "POST /api/dot-mcp/requests/{id}/dot-pairing/preview") return "public";
if (path === "/api/mcp/setup" || path === "/api/mcp/device/consent" || path.startsWith("/api/mcp/requests/") || path.startsWith("/api/mcp/connections")) return "board";
if (/^\/api\/companies\/\{companyId\}\/agents\/\{agentId\}\/dot-binding(?:\/event-test)?$/.test(path)) return "board";
if (path === "/api/companies/{companyId}/dot-invitations") return "board";
@@ -11837,6 +11840,19 @@ registerCurrentRoute({
body: z.object({ pairingCode: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict(),
responses: { 200: r.ok(), 400: r.badRequest, 403: r.forbidden, 409: r.conflict },
});
+registerCurrentRoute({
+ method: "get", path: "/api/dot-mcp/requests/{id}", tags: ["tool-gateway"],
+ summary: "Describe a dedicated Dot connection request; personal requests are unavailable",
+ responses: { 200: r.ok(), 404: r.notFound },
+});
+for (const suffix of ["/dot-pairing/preview", "/dot-pairing"]) registerCurrentRoute({
+ method: "post", path: "/api/dot-mcp/requests/{id}" + suffix, tags: ["tool-gateway"],
+ summary: suffix.endsWith("preview")
+ ? "Preview exact Dot agent access using a same-origin one-use pairing capability"
+ : "Consume a same-origin one-use pairing capability and approve its exact Dot agent connection",
+ body: z.object({ pairingCode: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict(),
+ responses: { 200: r.ok(), 400: r.badRequest, 403: r.forbidden, 404: r.notFound, 409: r.conflict },
+});
registerCurrentRoute({
method: "post", path: "/api/mcp/requests/{id}/consent", tags: ["tool-gateway"],
summary: "Approve or deny assistant access using a same-origin browser session",
diff --git a/server/src/routes/public-mcp.ts b/server/src/routes/public-mcp.ts
index f98f80b92b..e5c9bda60f 100644
--- a/server/src/routes/public-mcp.ts
+++ b/server/src/routes/public-mcp.ts
@@ -197,7 +197,11 @@ export function publicMcpIngressRoutes(oauth: PublicMcpOAuth, execute: ReturnTyp
export function publicMcpManagementRoutes(oauth: PublicMcpOAuth, agentOAuth?: PublicMcpOAuth) {
const router = Router();
- const requestOAuth = async (id: string) => agentOAuth && await agentOAuth.ownsRequest(id) ? agentOAuth : oauth;
+ const requestOAuth = async (id: string, dotOnly = false) => {
+ if (agentOAuth && await agentOAuth.ownsRequest(id)) return agentOAuth;
+ if (dotOnly) throw new McpOAuthError("invalid_request", "Dot connection request is expired or unavailable.", 404);
+ return oauth;
+ };
const deviceOAuth = async (code: string) => agentOAuth && await agentOAuth.ownsDevice(code) ? agentOAuth : oauth;
const realUser: RequestHandler = (req, _res, next) => {
if (req.actor.type !== "board" || !req.actor.userId || !["session", "cloud_tenant"].includes(req.actor.source ?? "")) {
@@ -210,7 +214,7 @@ export function publicMcpManagementRoutes(oauth: PublicMcpOAuth, agentOAuth?: Pu
if (origin !== oauth.config.origin && origin !== oauth.config.authorizationOrigin) throw new McpOAuthError("access_denied", "Connection changes require the Paperclip browser origin.", 403);
next();
};
- router.use("/mcp", (_req, res, next) => { res.setHeader("Cache-Control", "no-store"); next(); });
+ router.use(["/mcp", "/dot-mcp"], (_req, res, next) => { res.setHeader("Cache-Control", "no-store"); next(); });
router.get("/mcp/device", authRateLimit(), async (req, res) => {
const code = z.string().regex(/^[A-Za-z0-9 -]{8,12}$/).safeParse(req.query.user_code);
if (!code.success) throw new McpOAuthError("invalid_request", "Enter the code shown by your assistant.");
@@ -221,23 +225,23 @@ export function publicMcpManagementRoutes(oauth: PublicMcpOAuth, agentOAuth?: Pu
if (!parsed.success) throw new McpOAuthError("invalid_request", "Enter your code and choose the requested access.");
res.json(await (await deviceOAuth(parsed.data.userCode)).consentDevice(parsed.data.userCode, req.actor, parsed.data));
});
- router.get("/mcp/requests/:id", async (req, res) => {
+ router.get(["/mcp/requests/:id", "/dot-mcp/requests/:id"], async (req, res) => {
let setupUrl: string | null = null;
if (process.env.PAPERCLIP_CLOUD_API_ORIGIN) {
const base = new URL(process.env.PAPERCLIP_CLOUD_API_ORIGIN);
if (base.protocol === "https:") setupUrl = new URL("/orgs/new", base).toString();
}
- res.json(await (await requestOAuth(String(req.params.id))).describeRequest(String(req.params.id), req.actor, setupUrl));
+ res.json(await (await requestOAuth(String(req.params.id), req.path.startsWith("/dot-mcp/"))).describeRequest(String(req.params.id), req.actor, setupUrl));
});
- router.post("/mcp/requests/:id/dot-pairing/preview", sameOrigin, authRateLimit(), async (req, res) => {
+ router.post(["/mcp/requests/:id/dot-pairing/preview", "/dot-mcp/requests/:id/dot-pairing/preview"], sameOrigin, authRateLimit(), async (req, res) => {
const parsed = z.object({ pairingCode: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict().safeParse(req.body);
if (!parsed.success) throw new McpOAuthError("invalid_request", "Enter the one-use code from the Dot setup prompt.");
- res.json(await (await requestOAuth(String(req.params.id))).describeDotPairing(String(req.params.id), parsed.data.pairingCode));
+ res.json(await (await requestOAuth(String(req.params.id), req.path.startsWith("/dot-mcp/"))).describeDotPairing(String(req.params.id), parsed.data.pairingCode));
});
- router.post("/mcp/requests/:id/dot-pairing", sameOrigin, authRateLimit(), async (req, res) => {
+ router.post(["/mcp/requests/:id/dot-pairing", "/dot-mcp/requests/:id/dot-pairing"], sameOrigin, authRateLimit(), async (req, res) => {
const parsed = z.object({ pairingCode: z.string().regex(/^[A-Za-z0-9_-]{32}$/) }).strict().safeParse(req.body);
if (!parsed.success) throw new McpOAuthError("invalid_request", "Enter the one-use code from the Dot setup prompt.");
- res.json(await (await requestOAuth(String(req.params.id))).consentDotPairing(String(req.params.id), parsed.data.pairingCode));
+ res.json(await (await requestOAuth(String(req.params.id), req.path.startsWith("/dot-mcp/"))).consentDotPairing(String(req.params.id), parsed.data.pairingCode));
});
router.post("/mcp/requests/:id/consent", realUser, sameOrigin, async (req, res) => {
const parsed = mcpConsentSchema.safeParse(req.body);
@@ -253,6 +257,6 @@ export function publicMcpManagementRoutes(oauth: PublicMcpOAuth, agentOAuth?: Pu
if (!z.uuid().safeParse(req.params.id).success) throw new McpOAuthError("invalid_request", "Invalid connection ID.");
await oauth.revokeConnection(String(req.params.id), req.actor.userId!); res.status(204).end();
});
- router.use("/mcp", oauthErrors);
+ router.use(["/mcp", "/dot-mcp"], oauthErrors);
return router;
}
diff --git a/server/src/services/dot-assignment-follow-up.ts b/server/src/services/dot-assignment-follow-up.ts
new file mode 100644
index 0000000000..f77969b303
--- /dev/null
+++ b/server/src/services/dot-assignment-follow-up.ts
@@ -0,0 +1,103 @@
+import { and, eq, gt, gte, inArray, isNull, sql } from "drizzle-orm";
+import { dotAgentBindings, dotMailboxItems, dotRunnerAssignments, dotRunnerOperations, agentWakeupRequests, heartbeatRuns, issueComments, type Db } from "@paperclipai/db";
+import { queuedCommentIdsFromWakePayload, withQueuedCommentIdsInWakePayload } from "./issue-queued-comment-queue.js";
+
+/** Call inside the issue admission transaction, while its execution lock is held.
+ * The caller preserves explicit fresh-session and durable actor receipt policy.
+ */
+export async function publishActiveDotComment(db: Db, input: {
+ companyId: string; agentId: string; bindingId: string;
+ runId: string; issueId: string; commentId: string;
+}): Promise<false | { assignmentId: string; consumed: boolean }> {
+ // Mailbox writers and cursor readers share the binding lock. An event is a
+ // reference to task input; it never grants tools or steers the provider.
+ const [binding] = await db.select().from(dotAgentBindings).where(and(
+ eq(dotAgentBindings.id, input.bindingId), eq(dotAgentBindings.companyId, input.companyId),
+ eq(dotAgentBindings.agentId, input.agentId), eq(dotAgentBindings.status, "ready"),
+ isNull(dotAgentBindings.revokedAt))).for("update");
+ if (!binding) return false;
+ const [assignment] = await db.select({ id: dotRunnerAssignments.id }).from(dotRunnerAssignments)
+ .innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, dotRunnerAssignments.runId),
+ eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, input.agentId),
+ eq(heartbeatRuns.nativeIssueId, input.issueId), eq(heartbeatRuns.status, "running"),
+ eq(heartbeatRuns.runtimeMode, "native"), sql`${heartbeatRuns.nativeSessionId}::text = ${dotRunnerAssignments.normalizedSessionId}`))
+ .innerJoin(issueComments, and(eq(issueComments.id, input.commentId),
+ eq(issueComments.companyId, input.companyId), eq(issueComments.issueId, input.issueId), isNull(issueComments.deletedAt),
+ gte(issueComments.createdAt, dotRunnerAssignments.createdAt),
+ sql`(${issueComments.authorAgentId} is null or ${issueComments.authorAgentId} <> ${input.agentId})`))
+ .where(and(eq(dotRunnerAssignments.companyId, input.companyId), eq(dotRunnerAssignments.agentId, input.agentId),
+ eq(dotRunnerAssignments.bindingId, binding.id), eq(dotRunnerAssignments.bindingGeneration, binding.generation),
+ eq(dotRunnerAssignments.runId, input.runId), eq(dotRunnerAssignments.status, "accepted"),
+ gt(dotRunnerAssignments.expiresAt, new Date()))).limit(1);
+ if (!assignment) return false;
+ // Same key as the event scanner: either path may discover the comment first.
+ await db.insert(dotMailboxItems).values({ companyId: input.companyId, bindingId: binding.id,
+ bindingGeneration: binding.generation, assignmentId: assignment.id, kind: "follow_up",
+ sourceEventId: `dot-follow-up:${assignment.id}:${input.commentId}`,
+ references: { assignmentId: assignment.id, commentId: input.commentId } }).onConflictDoNothing();
+ const [item] = await db.select({ references: dotMailboxItems.references }).from(dotMailboxItems).where(and(
+ eq(dotMailboxItems.bindingId, binding.id), eq(dotMailboxItems.bindingGeneration, binding.generation),
+ eq(dotMailboxItems.sourceEventId, `dot-follow-up:${assignment.id}:${input.commentId}`)));
+ return { assignmentId: assignment.id, consumed: item?.references.consumed === true };
+}
+
+/** A successful history receipt exposes exact comment IDs to Dot. Merely
+ * writing a mailbox item, delivering its webhook, or reading its reference
+ * does not consume a comment. Keep its wake deferred until this boundary.
+ */
+export async function consumeDotHistoryReceipt(db: Db, operation: typeof dotRunnerOperations.$inferSelect): Promise<void> {
+ const input = operation.command.input as Record<string, unknown> | undefined;
+ const result = operation.outcome?.result as { comments?: Array<{ id?: unknown }> } | undefined;
+ if (operation.status !== "completed" || operation.command.action !== "tool" || input?.name !== "get_task_history"
+ || operation.outcome?.status !== "completed" || operation.outcome?.isError === true || !Array.isArray(result?.comments)) return;
+ const ids = result.comments.flatMap(comment => typeof comment?.id === "string" ? [comment.id] : []);
+ if (!ids.length) return;
+ await db.transaction(async tx => {
+ const [source] = await tx.select().from(dotRunnerAssignments).where(and(
+ eq(dotRunnerAssignments.id, operation.assignmentId), eq(dotRunnerAssignments.companyId, operation.companyId)));
+ if (!source) return;
+ const [binding] = await tx.select().from(dotAgentBindings).where(and(
+ eq(dotAgentBindings.id, source.bindingId), eq(dotAgentBindings.companyId, source.companyId),
+ eq(dotAgentBindings.agentId, source.agentId), eq(dotAgentBindings.generation, source.bindingGeneration),
+ eq(dotAgentBindings.status, "ready"), isNull(dotAgentBindings.revokedAt))).for("update");
+ if (!binding) return;
+ const [current] = await tx.select({ issueId: heartbeatRuns.nativeIssueId })
+ .from(dotRunnerAssignments).innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, dotRunnerAssignments.runId),
+ eq(heartbeatRuns.companyId, source.companyId), eq(heartbeatRuns.agentId, source.agentId),
+ eq(heartbeatRuns.status, "running"), eq(heartbeatRuns.runtimeMode, "native"),
+ sql`${heartbeatRuns.nativeSessionId}::text = ${dotRunnerAssignments.normalizedSessionId}`))
+ .where(and(eq(dotRunnerAssignments.id, source.id), eq(dotRunnerAssignments.status, "accepted"),
+ gt(dotRunnerAssignments.expiresAt, new Date())));
+ if (!current?.issueId) return; // A receipt read after completion cannot eat queued work.
+ const comments = await tx.select({ id: issueComments.id }).from(issueComments).where(and(
+ eq(issueComments.companyId, source.companyId), eq(issueComments.issueId, current.issueId),
+ inArray(issueComments.id, ids), isNull(issueComments.deletedAt), gte(issueComments.createdAt, source.createdAt),
+ sql`(${issueComments.authorAgentId} is null or ${issueComments.authorAgentId} <> ${source.agentId})`));
+ if (!comments.length) return;
+ // Materialize consumption even if the comment wake has not yet been admitted.
+ // Admission, event scanning and receipt reads all serialize on this binding.
+ for (const comment of comments) await tx.insert(dotMailboxItems).values({
+ companyId: source.companyId, bindingId: binding.id, bindingGeneration: binding.generation,
+ assignmentId: source.id, kind: "follow_up", sourceEventId: `dot-follow-up:${source.id}:${comment.id}`,
+ references: { assignmentId: source.id, commentId: comment.id, consumed: true },
+ }).onConflictDoUpdate({ target: [dotMailboxItems.bindingId, dotMailboxItems.bindingGeneration, dotMailboxItems.sourceEventId],
+ set: { references: sql`${dotMailboxItems.references} || '{"consumed":true}'::jsonb` } });
+ const now = new Date();
+ const wakes = await tx.select().from(agentWakeupRequests).where(and(
+ eq(agentWakeupRequests.companyId, source.companyId), eq(agentWakeupRequests.agentId, source.agentId),
+ isNull(agentWakeupRequests.runId), eq(agentWakeupRequests.status, "deferred_issue_execution"),
+ sql`${agentWakeupRequests.payload}->>'dotAssignmentFollowUp' = ${source.id}`)).for("update");
+ const consumed = new Set(comments.map(comment => comment.id));
+ for (const wake of wakes) {
+ const queued = queuedCommentIdsFromWakePayload(wake.payload);
+ const remaining = queued.filter(id => !consumed.has(id));
+ if (!queued.length || remaining.length === queued.length) continue;
+ await tx.update(agentWakeupRequests).set({
+ ...(remaining.length ? { payload: withQueuedCommentIdsInWakePayload(wake.payload, remaining) }
+ : { status: "coalesced", runId: source.runId, finishedAt: now }),
+ updatedAt: now,
+ }).where(and(eq(agentWakeupRequests.id, wake.id), eq(agentWakeupRequests.companyId, source.companyId),
+ eq(agentWakeupRequests.status, "deferred_issue_execution")));
+ }
+ });
+}
diff --git a/server/src/services/dot-runner-broker.ts b/server/src/services/dot-runner-broker.ts
index 9650cf3caf..934762384a 100644
--- a/server/src/services/dot-runner-broker.ts
+++ b/server/src/services/dot-runner-broker.ts
@@ -1,9 +1,11 @@
import { updateAgentConfigurationInTransaction } from "./agent-configuration-transaction.js";
+import type { heartbeatService } from "./heartbeat.js";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { and, asc, eq, gt, inArray, isNull, sql } from "drizzle-orm";
import { z } from "zod";
import { setAgentAvatarSchema, type SetAgentAvatarInput } from "@paperclipai/shared";
import { setAgentProfileAvatar } from "./agent-profile-avatar.js";
+import { consumeDotHistoryReceipt } from "./dot-assignment-follow-up.js";
import { getStorageService } from "../storage/index.js";
import { agents, companies, heartbeatRuns, issues, agentWakeupRequests, nativeRunFinalizations, mcpOauthGrants,
mcpEventSubscriptions, dotAgentBindings as bindings, dotRunnerAssignments as assignments,
@@ -21,8 +23,17 @@ import { getNativeReviewAssignment, readNativeReviewAssignmentContext } from "./
const hash = (text: string) => createHash("sha256").update(text).digest("hex");
const fail = (message: string) => new McpOAuthError("access_denied", message, 409);
+type DotHeartbeat = Pick<ReturnType<typeof heartbeatService>, "wakeup" | "cancelRun">;
const instances = new WeakMap<Db, ReturnType<typeof createBroker>>();
-export function dotRunnerBroker(db: Db) {
+const heartbeatContexts = new WeakMap<Db, DotHeartbeat>();
+async function admissionHeartbeat(db: Db): Promise<DotHeartbeat> {
+ const configured = heartbeatContexts.get(db);
+ if (configured) return configured;
+ const { heartbeatService } = await import("./heartbeat.js");
+ return heartbeatService(db);
+}
+export function dotRunnerBroker(db: Db, options?: { heartbeat?: DotHeartbeat }) {
+ if (options?.heartbeat) heartbeatContexts.set(db, options.heartbeat);
let service = instances.get(db);
if (!service) { service = createBroker(db); instances.set(db, service); }
return service;
@@ -171,6 +182,33 @@ function createBroker(db: Db) {
hasPendingChallenge: !!b.challengeHash && !!b.challengeExpiresAt && b.challengeExpiresAt > new Date(),
assignment: active ? { ...active, attentionRequired: active.status === "accepted" && active.lastActivityAt.getTime() < Date.now() - 15 * 60_000 } : null };
},
+ async reconcileTerminalAssignments(companyId: string, agentId: string, bindingId: string) {
+ // A controller can fail before reconnecting to the Runner. Its terminal
+ // run already denies tools, but the mailbox must also retire that offer.
+ // This is an authority fence, never evidence that OpenAI stopped work.
+ return db.transaction(async tx => {
+ const [binding] = await tx.select().from(bindings).where(and(
+ eq(bindings.id, bindingId),
+ eq(bindings.companyId, companyId), eq(bindings.agentId, agentId), isNull(bindings.revokedAt))).for("update");
+ if (!binding) return;
+ const terminal = await tx.select({ assignment: assignments }).from(assignments)
+ .innerJoin(heartbeatRuns, and(eq(heartbeatRuns.id, assignments.runId),
+ eq(heartbeatRuns.companyId, assignments.companyId), eq(heartbeatRuns.agentId, assignments.agentId)))
+ .where(and(eq(assignments.companyId, companyId), eq(assignments.agentId, agentId),
+ eq(assignments.bindingId, binding.id), eq(assignments.bindingGeneration, binding.generation),
+ inArray(assignments.status, ["offered", "accepted"]),
+ inArray(heartbeatRuns.status, ["succeeded", "failed", "cancelled", "timed_out"])));
+ for (const { assignment } of terminal) {
+ await tx.update(assignments).set({ status: "fenced" }).where(eq(assignments.id, assignment.id));
+ await tx.insert(mailbox).values({ companyId, bindingId, bindingGeneration: binding.generation,
+ assignmentId: assignment.id, kind: "authority_revoked", sourceEventId: randomUUID(),
+ references: { assignmentId: assignment.id, runId: assignment.runId, externalStopConfirmed: false } });
+ await logActivity(tx as unknown as Db, { companyId, actorType: "system", actorId: "dot-runner",
+ action: "dot.assignment_fenced", entityType: "agent", entityId: agentId,
+ details: { assignmentId: assignment.id, runId: assignment.runId, reason: "run_terminal", externalStopConfirmed: false } });
+ }
+ });
+ },
async snapshot(companyId: string, agentId: string, bindingId: string): Promise<DotBindingSnapshot> {
if (!await enabled()) throw fail("OpenAI Dot is disabled for new work.");
const state = await this.bindingForAgent(companyId, agentId);
@@ -179,6 +217,7 @@ function createBroker(db: Db) {
const [grant] = binding?.grantId ? await db.select().from(mcpOauthGrants).where(eq(mcpOauthGrants.id, binding.grantId)) : [];
if (!grant) throw fail("Dedicated Dot grant is unavailable.");
await principalBinding({ grant, actor: { type: "agent", agentId, companyId }, company: { id: companyId, name: "", issuePrefix: "", status: "active" } });
+ await this.reconcileTerminalAssignments(companyId, agentId, bindingId);
const [active] = await db.select({ id: assignments.id }).from(assignments).where(and(eq(assignments.bindingId, bindingId), inArray(assignments.status, ["offered", "accepted"])));
if (active) throw fail("Dot already has an active assignment. Reconcile it before assigning another task.");
return { companyId, agentId, bindingId, bindingGeneration: state.generation,
@@ -237,7 +276,11 @@ function createBroker(db: Db) {
const deadline = Date.now() + 1500;
while (Date.now() < deadline) {
const [receipt] = await db.select().from(operations).where(eq(operations.id, row.id));
- if (receipt?.outcome) { await authorizeAssignment(principal, assignmentId, true); return receipt.outcome; }
+ if (receipt?.outcome) {
+ await authorizeAssignment(principal, assignmentId, true);
+ await consumeDotHistoryReceipt(db, receipt);
+ return receipt.outcome;
+ }
await new Promise(r => setTimeout(r, 50));
}
return { status: "pending", assignmentId, requestId, message: "Use paperclip_dot_operation_status or retry with the same requestId. Do not create a new request ID." };
@@ -312,7 +355,7 @@ function createBroker(db: Db) {
if (!assignment) await new Promise(resolve => setTimeout(resolve, 50));
} while (!assignment && Date.now() < deadline);
return { ...wake, issueId: task.id, identifier: task.identifier, assignment: assignment ?? null,
- instruction: "Drain the inbox now. If assignment is present, read and accept it, then use its catalog. If admission is still pending, retry paperclip_dot_request_turn with exactly the same requestId and prompt to check this intake; never create a second request. Events also notify queued work. This intake supplies normal run authority; no human needs to create a preliminary task." };
+ instruction: wake.status === "admission_failed" ? wake.message : "Drain the inbox now. If assignment is present, read and accept it, then use its catalog. If admission is still pending, retry paperclip_dot_request_turn with exactly the same requestId and prompt to check this intake; never create a second request. Events also notify queued work. This intake supplies normal run authority; no human needs to create a preliminary task." };
},
async requestWork(principal: McpPrincipal, issueId: string, requestId: string) {
const b = await principalBinding(principal);
@@ -320,8 +363,15 @@ function createBroker(db: Db) {
if (!await enabled() || !(await this.bindingForAgent(b.companyId, b.agentId))?.subscriptionVerified) throw fail("Dot admission is unavailable.");
const key = `dot-work:${b.id}:${b.generation}:${requestId}`;
const receipt = async () => (await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, b.companyId), eq(agentWakeupRequests.agentId, b.agentId), eq(agentWakeupRequests.idempotencyKey, key))).limit(1))[0];
- const replay = (row: typeof agentWakeupRequests.$inferSelect) => {
+ const replay = async (row: typeof agentWakeupRequests.$inferSelect) => {
if (row.payload?.issueId !== issueId) throw fail("requestId was reused for another task.");
+ const [run] = row.runId ? await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns).where(and(
+ eq(heartbeatRuns.id, row.runId), eq(heartbeatRuns.companyId, b.companyId), eq(heartbeatRuns.agentId, b.agentId),
+ )).limit(1) : [];
+ if (run && ["failed", "cancelled", "timed_out"].includes(run.status)) {
+ return { status: "admission_failed", runId: row.runId, admissionStatus: run.status,
+ message: "The previous admission ended without an active assignment. Stop waiting for its mailbox event. Inspect the task's run and use normal task recovery after resolving the failure. This request ID retains its original receipt." };
+ }
return { status: "requested", runId: row.runId, message: "Normal admission determines when this task can run. Read the mailbox after its event." };
};
// A retry is a receipt read, including after the task yielded or finished.
@@ -333,9 +383,9 @@ function createBroker(db: Db) {
// Different issue locks cannot admit the same request concurrently.
const hex = hash(key);
const receiptId = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-${((parseInt(hex[16]!, 16) & 3) | 8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
- const { heartbeatService } = await import("./heartbeat.js");
+ const heartbeat = await admissionHeartbeat(db);
try {
- const run = await heartbeatService(db).wakeup(b.agentId, { source: "assignment", triggerDetail: "system", reason: "issue_assigned",
+ const run = await heartbeat.wakeup(b.agentId, { source: "assignment", triggerDetail: "system", reason: "issue_assigned",
payload: { issueId, dotRequestId: requestId }, contextSnapshot: { issueId }, idempotencyKey: key, requestedByActorType: "agent", requestedByActorId: b.agentId,
allowRunCoalescing: false, durableDotRequest: { id: receiptId, companyId: b.companyId, agentId: b.agentId, issueId, requestId, idempotencyKey: key, requestedAt: new Date() } });
const reserved = await receipt();
@@ -359,6 +409,7 @@ function createBroker(db: Db) {
await authorizeAssignment(principal, assignmentId, true);
const [row] = await db.select().from(operations).where(and(eq(operations.assignmentId, assignmentId), eq(operations.requestId, requestId), eq(operations.companyId, principal.grant.companyId)));
if (!row) throw fail("Operation does not exist.");
+ await consumeDotHistoryReceipt(db, row);
return row.outcome ?? { status: row.status, requestId };
},
async controlAck(principal: McpPrincipal, assignmentId: string, requestId: string) {
@@ -443,8 +494,7 @@ function createBroker(db: Db) {
});
await Promise.all(runs.map(async ({ runId }) => {
await ports.get(runId)?.revoke?.().catch(() => {});
- const { heartbeatService } = await import("./heartbeat.js");
- await heartbeatService(db).cancelRun(runId, "Dot connection revoked");
+ await (await admissionHeartbeat(db)).cancelRun(runId, "Dot connection revoked");
}));
},
async assertRunAuthority(execution: { binding: { runId: string }; provider: { binding: DotBindingSnapshot } }) {
@@ -557,8 +607,8 @@ function createBroker(db: Db) {
};
}
-export function createDotRunnerMcpTools(db: Db): PublicMcpToolExtension {
- const broker = dotRunnerBroker(db);
+export function createDotRunnerMcpTools(db: Db, heartbeat?: DotHeartbeat): PublicMcpToolExtension {
+ const broker = dotRunnerBroker(db, { heartbeat });
const request = { assignmentId: z.uuid(), requestId: z.uuid() };
const definitions = [
{ name: "paperclip_dot_set_avatar", description: "Update only your bound Paperclip agent's avatar, including while idle after pairing. If you can obtain your own avatar, send its PNG/JPEG/WebP bytes as raw base64 (max 512 KiB, static image). Do not send a URL or invent an image. Use imageBase64: null to restore the Paperclip character. Repeating the same image is safe. No active assignment is needed.", schema: setAgentAvatarSchema },
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index 7a0c1436c8..ab9caa3280 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -4546,9 +4546,6 @@ export function heartbeatService(
const executionForcedToKubernetes =
isExecutionForcedToKubernetes(executionPolicy);
let selectedEnvironmentId = environmentResolution.environmentId;
- if (isDotRun && (executionForcedToKubernetes || managedSandboxOnly || selectedEnvironmentId && selectedEnvironmentId !== localEnvironment.id)) {
- throw new ConfigurationIncompleteFailure("Dot currently requires a self-hosted local Runner controller; this environment policy is not supported.", { provider: "openai_dot", reason: "controller_environment_unsupported" });
- }
if (executionForcedToKubernetes) {
let kubernetesEnvironment =
await environmentsSvc.findKubernetesEnvironment(agent.companyId);
@@ -8169,7 +8166,7 @@ export function heartbeatService(
}).syncIssueSafely,
onSpawn: async (meta) => {
markDispatchStarted();
- await persistRunProcessMetadata(run.id, meta);
+ await persistRunProcessMetadata(run.id, { ...meta, targetKind: executionTarget?.kind ?? "local" });
},
});
},
diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts
index 9332de4437..de6ed04a96 100644
--- a/server/src/services/heartbeat/queue.ts
+++ b/server/src/services/heartbeat/queue.ts
@@ -1,5 +1,6 @@
import { isAgentAwaitingSetup } from "../../modules/agent-lifecycle/index.js";
import { normalizeAgentNameKey } from "./retries.js";
+import { publishActiveDotComment } from "../dot-assignment-follow-up.js";
import {
type WakeupOptions,
mergeCoalescedContextSnapshot,
@@ -1764,7 +1765,14 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
await db.update(agentWakeupRequests).set({ updatedAt: new Date() }).where(and(
eq(agentWakeupRequests.id, wake.id), eq(agentWakeupRequests.status, "deferred_issue_execution"),
));
- if (!latest || latest.runtimeMode !== "legacy" || !isHeartbeatRunTerminalStatus(latest.status)) continue;
+ if (!latest || !isHeartbeatRunTerminalStatus(latest.status)) continue;
+ if (latest.runtimeMode === "native" && typeof wake.payload?.dotAssignmentFollowUp === "string") {
+ await releaseIssueExecutionAndPromote(latest, { suppressImmediateRecovery: true }).catch(err => {
+ logger.warn({ err, queueId: wake.id }, "failed to promote unread Dot comment after recovery");
+ });
+ continue;
+ }
+ if (latest.runtimeMode !== "legacy") continue;
const cancelledAdmission = latest.status === "cancelled" && !latest.startedAt &&
latest.errorCode === "execution_reconciliation_required";
if ((latest.status !== "cancelled" || cancelledAdmission) && await getExecutionBlocker(db, wake.companyId, String(wake.payload?.issueId))) {
@@ -3609,6 +3617,43 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
// deferred wake that could later replay the same reconciliation.
if (reconciledSourceRunId) return { kind: "deferred" as const };
+ // Offer the input to the active Dot, but keep a durable queued wake
+ // until it reads the comment. A finish racing the event tick must
+ // leave unread input available for the next assignment.
+ const dotBindingId = readNonEmptyString(parseObject(agent.adapterConfig).dotBindingId);
+ const dotFollowUp = agent.adapterType === "paperclip_runner" && parseObject(agent.adapterConfig).provider === "openai_dot"
+ && dotBindingId && activeExecutionRun.agentId === agentId && issue.assigneeAgentId === agentId
+ && reason === "issue_commented" && wakeCommentId && opts.allowRunCoalescing !== false
+ && enrichedContextSnapshot.forceFreshSession !== true && !explicitResumeSession && !opts.manualUserWake
+ && !enrichedContextSnapshot.interactionId && !payload?.interactionId && !receiptRequest
+ ? await publishActiveDotComment(tx as unknown as Db, { companyId: agent.companyId, agentId,
+ bindingId: dotBindingId, runId: activeExecutionRun.id, issueId: issue.id, commentId: wakeCommentId }) : false;
+ if (dotFollowUp) {
+ const [pending] = dotFollowUp.consumed ? [] : await tx.select().from(agentWakeupRequests).where(and(
+ eq(agentWakeupRequests.companyId, agent.companyId), eq(agentWakeupRequests.agentId, agentId),
+ isNull(agentWakeupRequests.runId), eq(agentWakeupRequests.status, "deferred_issue_execution"),
+ sql`${agentWakeupRequests.payload}->>'dotAssignmentFollowUp' = ${dotFollowUp.assignmentId}`,
+ opts.requestedByActorType ? eq(agentWakeupRequests.requestedByActorType, opts.requestedByActorType) : isNull(agentWakeupRequests.requestedByActorType),
+ opts.requestedByActorId ? eq(agentWakeupRequests.requestedByActorId, opts.requestedByActorId) : isNull(agentWakeupRequests.requestedByActorId),
+ )).for("update").limit(1);
+ if (pending) await tx.update(agentWakeupRequests).set({
+ payload: withQueuedCommentIdsInWakePayload(pending.payload,
+ [...new Set([...queuedCommentIdsFromWakePayload(pending.payload), wakeCommentId!])]),
+ coalescedCount: pending.coalescedCount + 1, updatedAt: new Date(),
+ }).where(and(eq(agentWakeupRequests.id, pending.id), eq(agentWakeupRequests.companyId, agent.companyId),
+ eq(agentWakeupRequests.agentId, agentId), eq(agentWakeupRequests.status, "deferred_issue_execution")));
+ else await tx.insert(agentWakeupRequests).values({ companyId: agent.companyId, agentId, source, triggerDetail,
+ reason, payload: withQueuedCommentIdsInWakePayload({ ...payload, issueId: issue.id,
+ dotAssignmentFollowUp: dotFollowUp.assignmentId,
+ [DEFERRED_WAKE_CONTEXT_KEY]: enrichedContextSnapshot }, [wakeCommentId!]),
+ status: dotFollowUp.consumed ? "coalesced" : "deferred_issue_execution",
+ runId: dotFollowUp.consumed ? activeExecutionRun.id : null,
+ requestedByActorType: opts.requestedByActorType ?? null,
+ requestedByActorId: opts.requestedByActorId ?? null, idempotencyKey: opts.idempotencyKey ?? null,
+ finishedAt: dotFollowUp.consumed ? new Date() : null });
+ return { kind: "coalesced" as const, run: activeExecutionRun };
+ }
+
const admissionScope = wakeQueue.createAdmissionTransactionScope(
agent.companyId,
tx as unknown as Db,
diff --git a/server/src/services/heartbeat/run-lifecycle.test.ts b/server/src/services/heartbeat/run-lifecycle.test.ts
index 414315fbae..37b26e22b5 100644
--- a/server/src/services/heartbeat/run-lifecycle.test.ts
+++ b/server/src/services/heartbeat/run-lifecycle.test.ts
@@ -8,7 +8,7 @@ import { publishLiveEvent } from "../live-events.js";
import { getHeartbeatRunRuntimeStatus } from "../heartbeat-run-runtime-status.js";
import { createHeartbeatRunState } from "./run-state.js";
import { createHeartbeatRunPreparation } from "./run-preparation.js";
-import { createHeartbeatLifecycle, type HeartbeatLifecycleDependencies } from "./run-lifecycle.js";
+import { createHeartbeatLifecycle, persistHeartbeatRunProcessMetadata, type HeartbeatLifecycleDependencies } from "./run-lifecycle.js";
vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() }));
@@ -117,6 +117,16 @@ describe.skipIf(!support.supported)("heartbeat lifecycle database wiring", () =>
return { company, agent, wake, run };
}
+ it("preserves sandbox process birth instead of inspecting a colliding controller PID", async () => {
+ const { run } = await fixture();
+ const remoteBirth = "2026-10-09T00:00:00.000Z";
+ const persisted = await persistHeartbeatRunProcessMetadata(db, run.id, {
+ pid: process.pid, processGroupId: null, startedAt: remoteBirth, targetKind: "remote",
+ });
+ expect(persisted?.processStartedAt?.toISOString()).toBe(remoteBirth);
+ expect(persisted?.processPid).toBe(process.pid);
+ });
+
it("keeps one terminal outcome and reports only the winner of competing writes", async () => {
const { run } = await fixture();
const deps = callbacks(db);
diff --git a/server/src/services/heartbeat/run-lifecycle.ts b/server/src/services/heartbeat/run-lifecycle.ts
index 55215e6301..865aaca7b7 100644
--- a/server/src/services/heartbeat/run-lifecycle.ts
+++ b/server/src/services/heartbeat/run-lifecycle.ts
@@ -543,9 +543,10 @@ function buildRunEventRuntimeProgress(input: {
export async function persistHeartbeatRunProcessMetadata(
db: Db,
runId: string,
- meta: { pid: number; processGroupId: number | null; startedAt: string },
+ meta: { pid: number; processGroupId: number | null; startedAt: string; targetKind?: "local" | "remote" },
) {
- const observedStartedAt = await readProcessStartedAt(meta.pid).catch(
+ // A sandbox PID belongs to a different host and may collide with a local PID.
+ const observedStartedAt = meta.targetKind === "remote" ? null : await readProcessStartedAt(meta.pid).catch(
() => null,
);
const startedAt = new Date(observedStartedAt ?? meta.startedAt);
@@ -2097,7 +2098,7 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl
async function persistRunProcessMetadata(
runId: string,
- meta: { pid: number; processGroupId: number | null; startedAt: string },
+ meta: { pid: number; processGroupId: number | null; startedAt: string; targetKind?: "local" | "remote" },
) {
return persistHeartbeatRunProcessMetadata(db, runId, meta);
}
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 e61211cee1..4280e1566c 100644
--- a/server/src/services/native-runtime/native-session-executor.test.ts
+++ b/server/src/services/native-runtime/native-session-executor.test.ts
@@ -828,7 +828,7 @@ describe("remote runner process supervision", () => {
expect(handle.child.exitCode).toBeNull();
});
- it("terminates a detached runner when its process identity cannot be adopted", async () => {
+ it.each(["missing marker", "missing fingerprint"])("terminates a detached runner with %s before admitting managed work", async kind => {
vi.useFakeTimers();
try {
let launchNonce = "";
@@ -847,10 +847,10 @@ describe("remote runner process supervision", () => {
}
if (label === "paperclip-runner-process-identity") {
return {
- exitCode: 3,
+ exitCode: kind === "missing fingerprint" ? 0 : 3,
signal: null,
timedOut: false,
- stdout: "",
+ stdout: kind === "missing fingerprint" ? `${launchNonce}\n4321\n2026-09-06T00:00:00.000Z\nrunner-remote\n` : "",
stderr: "",
};
}
@@ -881,6 +881,7 @@ describe("remote runner process supervision", () => {
stateDirectory: "/runtime",
diagnosticsDirectory: "/runtime/diagnostics",
runnerInstanceId: "runner-remote",
+ requireProcessStartFingerprint: true,
});
const handle = launcher({
@@ -2521,6 +2522,14 @@ describe("remote runner build metadata", () => {
).not.toThrow();
});
+ it("requires an explicit Dot bridge capability only for remote Dot execution", () => {
+ expect(() => assertRemoteRunnerBuildMetadata(current, "listen_ws", "openai_dot_mcp"))
+ .toThrow("runner_remote_dot_capability_missing");
+ expect(() => assertRemoteRunnerBuildMetadata({ ...current, externalProviderCapabilities: ["openai_dot_mcp"] },
+ "listen_ws", "openai_dot_mcp")).not.toThrow();
+ expect(() => assertRemoteRunnerBuildMetadata(current, "listen_ws")).not.toThrow();
+ });
+
it("fails before dispatch when a preinstalled runner uses the stale contract", () => {
expect(() =>
assertRemoteRunnerBuildMetadata(
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index 14dd0fb692..b5e5f29835 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -1,5 +1,6 @@
import { configuredEnvironment } from "../../vendor/paperclip-runner/index.js";
import { agents } from "@paperclipai/db";
+import { isCloudManagedInstance } from "../cloud-instance.js";
import { dotRunnerBroker } from "../dot-runner-broker.js";
import { CURSOR_DISTRIBUTION_PINS, QUALIFIED_ACPX_PROFILES, QUALIFIED_ACPX_VERSION } from "../../vendor/paperclip-runner/index.js";
import { isProviderMode } from "../../vendor/paperclip-runner/index.js";
@@ -7534,6 +7535,11 @@ export async function executePaperclipNativeSession(input: {
await retireSupersededWarmNativeSessions(
ownerScope, nativeSessionScopeKey(input.execution),
);
+ if (input.execution.provider.kind === "openai_dot" && isCloudManagedInstance()
+ && (!input.useRunnerd || input.runnerExecutionTarget?.kind !== "remote"
+ || input.runnerExecutionTarget.transport !== "sandbox")) {
+ throw new Error("dot_cloud_requires_managed_runner");
+ }
if (!input.useRunnerd) {
return await executePaperclipNativeSessionWithinScope(input);
}
@@ -7555,7 +7561,6 @@ export async function executePaperclipNativeSession(input: {
await closingWarmNativeSessions.get(sessionScopeId);
if (input.execution.provider.kind === "openai_dot") {
- if (input.runnerExecutionTarget?.kind === "remote") throw new Error("dot_requires_local_runner_controller");
return await executePaperclipNativeSessionWithinScope(input);
}
const workspaceRoot = input.execution.workspace.cwd;
@@ -10140,6 +10145,7 @@ function readRemoteProviderPackIdentity(packRoot: string, verifyControllerFiles:
export function assertRemoteRunnerBuildMetadata(
value: unknown,
requiredMode: "dial_wss" | "listen_ws",
+ requiredExternalProvider?: "openai_dot_mcp",
): void {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new Error("runner_remote_artifact_metadata_invalid");
@@ -10156,6 +10162,10 @@ export function assertRemoteRunnerBuildMetadata(
// Older sandbox images share binary contract v2, but reject the zero
// lifetime now used by the controller and cannot renew connection leases.
// Reject them before launch so preparation stages the bundled runner instead.
+ if (requiredExternalProvider && (!Array.isArray(metadata.externalProviderCapabilities)
+ || !metadata.externalProviderCapabilities.includes(requiredExternalProvider))) {
+ throw new Error("runner_remote_dot_capability_missing: install the current Paperclip Runner artifact");
+ }
const sessionCapabilities = Array.isArray(metadata.durableSessionCapabilities)
? metadata.durableSessionCapabilities
: [];
@@ -10771,7 +10781,8 @@ async function waitForRemoteRunnerProcessIdentity(input: {
identityPath: string;
nonce: string;
runnerInstanceId: string;
-}): Promise<{ pid: number; startedAt: string }> {
+ requireProcessStartFingerprint?: boolean;
+}): Promise<{ pid: number; startedAt: string; processStartFingerprint?: string }> {
const deadline = Date.now() + REMOTE_RUNNER_PROCESS_IDENTITY_WAIT_MS;
while (Date.now() < deadline) {
const result = await input.runner
@@ -10791,7 +10802,7 @@ async function waitForRemoteRunnerProcessIdentity(input: {
result && result.exitCode === 0 && !result.timedOut
? parseRemoteRunnerProcessIdentity(result.stdout, input)
: null;
- if (identity) return identity;
+ if (identity && (!input.requireProcessStartFingerprint || identity.processStartFingerprint)) return identity;
await new Promise<void>((resolve) => setTimeout(resolve, 100));
}
throw new Error("runner_remote_process_identity_unavailable");
@@ -10830,6 +10841,7 @@ export function createRemoteRunnerProcessLauncher(input: {
diagnosticsDirectory: string;
runnerInstanceId: string;
ensureArtifact?: () => Promise<void>;
+ requireProcessStartFingerprint?: boolean;
onSpawn?: (meta: {
pid: number;
processGroupId: number | null;
@@ -10965,6 +10977,7 @@ export function createRemoteRunnerProcessLauncher(input: {
identityPath: input.processIdentityPath,
nonce: identityNonce,
runnerInstanceId: input.runnerInstanceId,
+ requireProcessStartFingerprint: input.requireProcessStartFingerprint,
});
} catch {
const cleanupStartedAtMs = Date.now();
@@ -11205,6 +11218,129 @@ export async function createRunnerdBackend(input: {
}
}
+/** Dot uses the same managed process launcher and authenticated PRP transports.
+ * Its execution contract still exposes no workspace, shell, or provider secrets. */
+async function prepareRemoteDotRunner({ input, target, runner, root, identity }: {
+ input: Parameters<typeof createRunnerdBackend>[0];
+ target: Extract<AdapterExecutionTarget, { kind: "remote" }>;
+ runner: CommandManagedRuntimeRunner;
+ root: string;
+ identity: NonNullable<NonNullable<Parameters<typeof createNativeSessionBackend>[1]>["dotRunnerOptions"]>["identity"];
+}) {
+ const runnerBinary = input.runnerRemoteBinaryPath?.trim() || resolvePaperclipRunnerBinary();
+ const remoteRoot = posix.join(target.remoteCwd, ".paperclip-runtime", "paperclip-runner");
+ const remoteBinary = posix.join(remoteRoot, "bin", "paperclip-runnerd");
+ const runnerStateDirectory = posix.join(remoteRoot, "sessions",
+ createHash("sha256").update(identity.normalizedSessionId).digest("hex"), "runner");
+ const requiredMode = resolveRemoteRunnerTransportMode({ target, runnerIngressAuthorized: input.runnerIngressAuthorized === true });
+ const artifact = readRunnerdArtifactBinding(runnerBinary);
+ const prepare = async () => {
+ if (input.restartRecovery?.kind !== "reattach_remote_runner") {
+ if (!input.runnerRemoteBinaryPath?.trim()) {
+ const platform = await runner.execute({ command: "sh", args: ["-c", "uname -s; uname -m"], bypassSession: true, timeoutMs: 10000 });
+ const [os, arch] = platform.stdout.trim().split(/\r?\n/);
+ if (platform.exitCode !== 0 || platform.timedOut || os !== (process.platform === "darwin" ? "Darwin" : "Linux")
+ || ![process.arch === "x64" ? "x86_64" : "aarch64", process.arch].includes(arch)) {
+ throw new Error("runner_remote_artifact_platform_mismatch: configure PAPERCLIP_RUNNER_REMOTE_BINARY_PATH for the sandbox platform");
+ }
+ }
+ await stageRemoteRunnerFile({ target, runner, sourcePath: runnerBinary, targetPath: remoteBinary, mode: 0o700 });
+ }
+ const metadata = await runner.execute({ command: remoteBinary, args: ["--build-metadata"], bypassSession: true, timeoutMs: 30000 });
+ if (metadata.exitCode !== 0 || metadata.timedOut) throw new Error("runner_remote_artifact_verification_failed");
+ assertRemoteRunnerBuildMetadata(JSON.parse(metadata.stdout), requiredMode, "openai_dot_mcp");
+ const checksum = await runner.execute({ command: "sh", args: ["-c",
+ 'if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1"; else shasum -a 256 "$1"; fi', "paperclip-dot-artifact", remoteBinary],
+ bypassSession: true, timeoutMs: 10000 });
+ if (checksum.exitCode !== 0 || checksum.timedOut || `sha256:${checksum.stdout.trim().split(/\s+/)[0]}` !== artifact.digest) {
+ throw new Error("runner_remote_artifact_verification_failed");
+ }
+ };
+ const readProviderState = async () => {
+ const result = await runner.execute({ command: "sh", args: ["-c",
+ 'set -eu; if test ! -e "$1" && test ! -L "$1"; then exit 3; fi; test -f "$1" && test ! -L "$1"; test "$(wc -c < "$1")" -le 33554432; base64 < "$1"',
+ "paperclip-dot-checkpoint", posix.join(runnerStateDirectory, "dot-provider-state.json")], bypassSession: true, timeoutMs: 10000 });
+ if (result.exitCode === 3 && !result.timedOut) return null;
+ if (result.exitCode !== 0 || result.timedOut) throw new Error("dot_provider_checkpoint_unavailable");
+ const state = record(JSON.parse(Buffer.from(result.stdout.replace(/\s+/g, ""), "base64").toString("utf8")));
+ if (state.schema !== "paperclip.runner.dot-provider-state.v1" || state.runId !== identity.runId
+ || state.sessionId !== identity.normalizedSessionId || state.turnId !== identity.turnId) throw new Error("dot_runner_checkpoint_authority_mismatch");
+ // Retain inspectable recovery evidence on the controller without changing
+ // which execution target is authoritative for replay.
+ mkdirSync(join(root, "runner"), { recursive: true, mode: 0o700 });
+ const saved = join(root, "runner", "dot-provider-state.json");
+ const temporary = `${saved}.${randomUUID()}.tmp`;
+ writeFileSync(temporary, JSON.stringify(state), { mode: 0o600 });
+ renameSync(temporary, saved);
+ return state;
+ };
+ let spawned: () => void = () => {};
+ const processStarted = new Promise<void>(resolve => { spawned = resolve; });
+ // A transport handshake alone does not prove a recoverable process owner.
+ // Do not attach the Dot broker until the exact sandbox marker is validated.
+ let identityReady: () => void = () => {};
+ let identityFailed: (error: unknown) => void = () => {};
+ const processIdentityReady = new Promise<void>((resolve, reject) => { identityReady = resolve; identityFailed = reject; });
+ void processIdentityReady.catch(() => {});
+ const adoptExistingRunner = input.restartRecovery?.kind === "reattach_remote_runner"
+ ? await verifyRemoteRunnerReattachment({ claim: input.restartRecovery, target, identity: { ...identity },
+ runId: input.execution.binding.runId, normalizedSessionId: nativeSessionKey(input.execution) }) : undefined;
+ if (adoptExistingRunner) { spawned(); identityReady(); }
+ const launch = createRemoteRunnerProcessLauncher({ target, runner, remoteBinary,
+ processIdentityPath: posix.join(runnerStateDirectory, "runner-process.identity"), stateDirectory: runnerStateDirectory,
+ diagnosticsDirectory: posix.join(remoteRoot, "diagnostics"), runnerInstanceId: input.runnerInstanceId,
+ requireProcessStartFingerprint: true,
+ onSpawn: async meta => { await input.onSpawn?.(meta); identityReady(); },
+ onLog: input.onLog, trace: input.trace, onRunnerProcessSpawned: () => spawned() });
+ const runnerProcessLauncher: typeof launch = spec => {
+ const handle = launch(spec);
+ void handle.completion.then(() => identityFailed(new Error("runner_remote_process_identity_unavailable")), identityFailed);
+ return handle;
+ };
+ const controlPlaneRegistration: NonNullable<NonNullable<NonNullable<Parameters<typeof createNativeSessionBackend>[1]>["dotRunnerOptions"]>["controlPlaneRegistration"]> = async authority => {
+ let transport: PaperclipRunnerTransport;
+ // Validate outbound URL before staging; provider ingress needs the staged
+ // listener binary before requesting the provider's private endpoint.
+ if (requiredMode === "dial_wss") {
+ transport = await resolvePaperclipRunnerTransport({ target, runId: input.execution.binding.runId,
+ localConnectUrl: "ws://127.0.0.1/unused", runnerPublicUrl: input.runnerPublicUrl,
+ runnerCaBundlePath: input.runnerCaBundlePath, runnerIngressAuthorized: input.runnerIngressAuthorized === true });
+ await prepare();
+ } else {
+ await prepare();
+ transport = await resolvePaperclipRunnerTransport({ target, runId: input.execution.binding.runId,
+ localConnectUrl: "ws://127.0.0.1/unused", runnerIngressAuthorized: input.runnerIngressAuthorized === true });
+ }
+ await input.onLog?.("stderr", `[paperclip-runner] Dot controller target=remote transport=${transport.mode}\n`);
+ if (transport.mode !== "provider_ingress") {
+ const registration = await registerRunnerPrpAuthority({ companyId: input.execution.binding.companyId,
+ issueId: input.execution.binding.issueId, agentId: input.execution.binding.agentId,
+ runId: input.execution.binding.runId, authority });
+ let caBundlePath = transport.mode === "direct_outbound" ? transport.caBundlePath : undefined;
+ if (caBundlePath) {
+ const remoteCaBundlePath = posix.join(remoteRoot, "bin", "runner-ca-bundle.pem");
+ await stageRemoteRunnerFile({ target, runner, sourcePath: caBundlePath, targetPath: remoteCaBundlePath, mode: 0o600 });
+ caBundlePath = remoteCaBundlePath;
+ }
+ return { ...registration, ready: async () => { await processIdentityReady; }, connection: { mode: "connect" as const, connectUrl: transport.connectUrl,
+ ...(caBundlePath ? { caBundlePath } : {}) } };
+ }
+ let outbound: ReturnType<typeof connectRunnerPrpIngress> | null = null;
+ let activation: Promise<void> | null = null;
+ return { connection: { mode: "listen" as const, listenAddress: transport.listenAddress,
+ listenPort: transport.listenPort, listenPath: transport.listenPath },
+ activate: () => { activation = (async () => { await processStarted;
+ outbound = connectRunnerPrpIngress({ authority, endpoint: transport.ingress }); })();
+ void activation.catch(() => {}); },
+ ready: async () => { await activation; if (!outbound) throw new Error("runner_ingress_unavailable"); await outbound.ready; await processIdentityReady; },
+ get failure() { return outbound?.failure; },
+ startupFailureCode: "runner_ingress_unavailable" as const,
+ release: async () => { if (outbound) await outbound.close(); else await transport.ingress.close(); },
+ };
+ };
+ return { runnerBinary, runnerStateDirectory, runnerProcessLauncher, readProviderState, controlPlaneRegistration, adoptExistingRunner };
+}
+
async function createRunnerdBackendWithinSessionClaim(
input: Parameters<typeof createRunnerdBackend>[0],
sessionScopeId: string,
@@ -11330,24 +11466,31 @@ async function createRunnerdBackendWithinSessionClaim(
input.execution.binding.executionWorkspaceId;
mkdirSync(root, { recursive: true, mode: 0o700 });
if (input.execution.schema === "paperclip.native-execution-input.v6") {
- if (target.kind !== "local") throw new Error("dot_runner_requires_local_controller: Dot has no mounted workspace or sandbox process");
+ if (target.kind === "remote" && input.dotWorkspaceRoot) throw new Error("dot_remote_workspace_access_unavailable");
+ const remoteDot = target.kind === "remote"
+ ? await prepareRemoteDotRunner({ input, target, runner: remoteCommandRunner!, root,
+ identity: { runnerInstanceId: effectiveRunnerInstanceId, environmentLeaseId: effectiveEnvironmentLeaseId,
+ runId: input.execution.binding.runId, normalizedSessionId: nativeSessionKey(input.execution),
+ turnId: `turn-${input.execution.binding.runId}`, itemId: `item-${input.execution.binding.runId}` } })
+ : null;
const recoveredProcess = input.restartRecovery?.kind === "reattach_existing_runner" ? input.restartRecovery.process : null;
const backend = createNativeSessionBackend(input.execution, {
onSpawn: input.onSpawn, dynamicTools,
dynamicToolHandler: async call => { await dotRunnerBroker(input.db).assertRunAuthority(input.execution as import("../../vendor/paperclip-runner/index.js").NativeExecutionInputV6); return authorityEpoch.execute(call); },
completionFeedback: async result => { await dotRunnerBroker(input.db).assertRunAuthority(input.execution as import("../../vendor/paperclip-runner/index.js").NativeExecutionInputV6); await authorityEpoch.definitions(); return nativeCompletionFeedback(input.db, input.execution.binding.runId, result); },
dotRunnerOptions: {
- stateDirectory: root, runnerBinary: resolvePaperclipRunnerBinary(),
+ stateDirectory: root, runnerBinary: remoteDot?.runnerBinary ?? resolvePaperclipRunnerBinary(),
+ ...(remoteDot ?? {}),
identity: { runnerInstanceId: effectiveRunnerInstanceId, environmentLeaseId: effectiveEnvironmentLeaseId,
runId: input.execution.binding.runId, normalizedSessionId: nativeSessionKey(input.execution),
turnId: `turn-${input.execution.binding.runId}`, itemId: `item-${input.execution.binding.runId}` },
port: dotRunnerBroker(input.db).port(input.execution),
- controlPlaneRegistration: async authority => registerRunnerPrpAuthority({ companyId: input.execution.binding.companyId,
+ controlPlaneRegistration: remoteDot?.controlPlaneRegistration ?? (async authority => registerRunnerPrpAuthority({ companyId: input.execution.binding.companyId,
issueId: input.execution.binding.issueId, agentId: input.execution.binding.agentId,
- runId: input.execution.binding.runId, authority }),
- adoptExistingRunner: recoveredProcess ? { ...recoveredProcess,
+ runId: input.execution.binding.runId, authority })),
+ adoptExistingRunner: remoteDot?.adoptExistingRunner ?? (recoveredProcess ? { ...recoveredProcess,
isAlive: () => verifiedRecoveryProcessIsAlive(recoveredProcess),
- signal: signal => signalVerifiedRecoveryProcess(recoveredProcess, signal) } : undefined,
+ signal: signal => signalVerifiedRecoveryProcess(recoveredProcess, signal) } : undefined),
},
});
const prior = sessionToolAuthorityEpochs.get(sessionScopeId); if (prior) prior.revoke();
diff --git a/server/src/services/public-mcp/events.ts b/server/src/services/public-mcp/events.ts
index 39c1ce0704..69571814fb 100644
--- a/server/src/services/public-mcp/events.ts
+++ b/server/src/services/public-mcp/events.ts
@@ -49,14 +49,16 @@ const dotEventDefinition = {
export function createPublicMcpEvents(db: Db, oauth: PublicMcpOAuth, api: ApiDispatch, options: { fetch?: EventFetch; now?: () => number; cloudOrigin?: string; enableDotPrototype?: boolean; enableDotRunner?: boolean; isBackgroundWorkEnabled?: () => boolean } = {}) {
const fetcher = options.fetch ?? eventFetch;
const now = options.now ?? Date.now;
- const cloudOrigin = options.cloudOrigin ?? process.env.PAPERCLIP_CLOUD_API_ORIGIN;
+ // Dedicated tenant Dot grants are authenticated locally, including background
+ // deliveries. They never use the personal connection's Cloud broker proof.
+ const cloudOrigin = options.enableDotRunner ? undefined : options.cloudOrigin ?? process.env.PAPERCLIP_CLOUD_API_ORIGIN;
if (cloudOrigin && (new URL(cloudOrigin).protocol !== "https:" || new URL(cloudOrigin).origin !== cloudOrigin)) throw new Error("MCP Events requires a fixed HTTPS Cloud origin.");
const encrypt = async (value: Destination) => (await localEncryptedProvider.createSecret({ value: JSON.stringify(value) })).material;
const decrypt = async (s: Subscription): Promise<Destination> => JSON.parse(await localEncryptedProvider.resolveVersion({ material: s.deliveryMaterial, externalRef: null, providerVersionRef: null }));
async function authorize(principal: McpPrincipal, args: z.infer<typeof resourceFilters>) {
if (args.bindingId) {
- if (!options.enableDotRunner || cloudOrigin) throw new McpEventError(-32602, "Dot requires the direct self-hosted agent endpoint; the Cloud agent broker is not qualified.");
+ if (!options.enableDotRunner) throw new McpEventError(-32602, "Dot requires the dedicated agent endpoint.");
await dotRunnerBroker(db).authorizeBinding(principal, args.companyId, args.bindingId); return;
}
if (args.companyId !== principal.grant.companyId || !principal.grant.scopes.includes("paperclip:read")) throw new McpEventError(-32602, "This task is outside the authorized company.");
@@ -240,7 +242,8 @@ export function createPublicMcpEvents(db: Db, oauth: PublicMcpOAuth, api: ApiDis
.orderBy(asc(dotMailboxItems.id)).limit(100);
for (const { item, assignment } of rows) {
const wanted = item.kind === "readiness_challenge" ? !!b.challengeHash && !!b.challengeExpiresAt && b.challengeExpiresAt > new Date(now())
- : item.kind === "authority_revoked" || !!assignment && ["offered", "accepted"].includes(assignment.status) && assignment.expiresAt > new Date(now());
+ : item.kind === "authority_revoked" || (item.kind !== "follow_up" || item.references.consumed !== true)
+ && !!assignment && ["offered", "accepted"].includes(assignment.status) && assignment.expiresAt > new Date(now());
await db.insert(deliveries).values({ subscriptionId: s.id, mailboxItemId: item.id, nextAttemptAt: new Date(now()),
event: wanted ? { eventId: "evt_dot_" + item.id + "_" + s.startsAt.getTime(), name: names[4], timestamp: new Date(now()).toISOString(),
data: { companyId: b.companyId, bindingId: b.id, bindingGeneration: b.generation, mailboxItemId: item.id, kind: item.kind }, cursor: null } : {},
diff --git a/server/src/services/public-mcp/oauth.ts b/server/src/services/public-mcp/oauth.ts
index 16d5e88181..27ccce17cd 100644
--- a/server/src/services/public-mcp/oauth.ts
+++ b/server/src/services/public-mcp/oauth.ts
@@ -383,7 +383,7 @@ export function createPublicMcpOAuth(db: Db, config: PublicMcpConfig, options: {
state: p.state ?? null, challenge: p.code_challenge, expiresAt: new Date(now.getTime() + 10 * minute),
});
});
- return authorizationOrigin + "/mcp-connect/" + id;
+ return authorizationOrigin + (agentConnection ? "/dot-connect/" : "/mcp-connect/") + id;
},
async describeRequest(id: string, actor: Request["actor"], setupUrl: string | null): Promise<McpConnectionRequest> {
await assertEnabled();
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 4d3babdf57..e4b49bfcad 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -802,6 +802,7 @@ export function App() {
<Route path="auth" element={<AuthPage />} />
<Route path="board-claim/:token" element={<BoardClaimPage />} />
<Route path="mcp-connect/:id" element={<McpConnectPage />} />
+ <Route path="dot-connect/:id" element={<McpConnectPage agentPairingOnly />} />
<Route path="mcp-device" element={<McpDevicePage />} />
<Route path="assistant-connections" element={<AssistantConnectionsPage />} />
<Route path="cli-auth/:id" element={<CliAuthPage />} />
diff --git a/ui/src/components/NewAgentDialog.test.tsx b/ui/src/components/NewAgentDialog.test.tsx
index 224174ce68..66a141d578 100644
--- a/ui/src/components/NewAgentDialog.test.tsx
+++ b/ui/src/components/NewAgentDialog.test.tsx
@@ -274,15 +274,16 @@ it("waits for company approval before issuing a Dot capability", async () => {
expect(dotApi.pair).not.toHaveBeenCalled();
});
-it("keeps cloud Dot gated until managed execution is qualified", async () => {
+it("allows the scoped Dot invitation on cloud when its prerequisites are enabled", async () => {
await act(async () => {
cache.setQueryData(queryKeys.instance.experimentalSettings, { enableOpenAiDot: true, enablePublicMcp: true });
cache.setQueryData(queryKeys.health, { status: "ok", cloud: { managed: true } });
});
await click("Invite an external agent");
- expect([...document.querySelectorAll("button")].find(b => b.textContent?.startsWith("Dot"))?.disabled).toBe(true);
- expect(document.body.textContent).toContain("Dot cloud execution is not available yet");
- expect(dotApi.create).not.toHaveBeenCalled();
+ const dot = [...document.querySelectorAll("button")].find(b => b.textContent?.startsWith("Dot"))!;
+ expect(dot.disabled).toBe(false);
+ await act(async () => dot.click());
+ expect(dotApi.create).toHaveBeenCalledWith("company-1");
});
async function openDotSetup() {
diff --git a/ui/src/components/new-agent/ExternalAgentInviteDialog.tsx b/ui/src/components/new-agent/ExternalAgentInviteDialog.tsx
index 657d6eb7d8..4a511c56aa 100644
--- a/ui/src/components/new-agent/ExternalAgentInviteDialog.tsx
+++ b/ui/src/components/new-agent/ExternalAgentInviteDialog.tsx
@@ -3,7 +3,6 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { accessApi } from "@/api/access";
import { dotInvitationsApi, type DotInvitation, type DotPairing } from "@/api/dotInvitations";
import { instanceSettingsApi } from "@/api/instanceSettings";
-import { useCloudInstance } from "@/hooks/useCloudInstance";
import { useCompany } from "@/context/CompanyContext";
import { queryKeys } from "@/lib/queryKeys";
import { buildAgentOnboardingPrompt } from "@/lib/agent-onboarding-prompt";
@@ -19,7 +18,6 @@ export function ExternalAgentInviteDialog({ companyId, onClose, onBack }: {
onBack: () => void;
}) {
const cache = useQueryClient();
- const cloud = Boolean(useCloudInstance());
const { selectedCompany } = useCompany();
const [preset, setPreset] = useState<ExternalAgentPreset | null>(null);
const [invitation, setInvitation] = useState<DotInvitation | null>(null);
@@ -30,7 +28,6 @@ export function ExternalAgentInviteDialog({ companyId, onClose, onBack }: {
const experimental = useQuery({ queryKey: queryKeys.instance.experimentalSettings, queryFn: instanceSettingsApi.getExperimental });
const dotDisabledReason = experimental.isPending ? "Loading available agents…"
: experimental.error ? "Unable to load experimental settings. Try again after refreshing."
- : cloud ? "Dot cloud execution is not available yet. Hermes and Other use the existing external agent invitation."
: !experimental.data?.enableOpenAiDot || !experimental.data.enablePublicMcp
? "Enable OpenAI Dot and Assistant connections (MCP) in experimental settings." : undefined;
const key = ["dot-binding", companyId, invitation?.agent.id];
diff --git a/ui/src/lib/new-agent-adapters.ts b/ui/src/lib/new-agent-adapters.ts
index 1ed4b06ccd..c68461cc83 100644
--- a/ui/src/lib/new-agent-adapters.ts
+++ b/ui/src/lib/new-agent-adapters.ts
@@ -16,7 +16,7 @@ export function isNewAgentAdapterAllowed(
}: { cloud: boolean; nativeRunnerEnabled: boolean; openAiDotEnabled?: boolean; runnerProvider?: string },
) {
if (type === "openai_dot" || (type === "paperclip_runner" && runnerProvider === "openai_dot")) {
- return !cloud && openAiDotEnabled;
+ return openAiDotEnabled;
}
if (type === "paperclip_runner") return nativeRunnerEnabled;
if (cloud) return CLOUD_ADAPTERS.has(type);
diff --git a/ui/src/pages/McpConnect.test.tsx b/ui/src/pages/McpConnect.test.tsx
index dfc2cbc568..e316e867ee 100644
--- a/ui/src/pages/McpConnect.test.tsx
+++ b/ui/src/pages/McpConnect.test.tsx
@@ -33,12 +33,12 @@ beforeEach(() => {
vi.clearAllMocks();
});
-function setup(device = false) {
+function setup(device = false, agentPairingOnly = false) {
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
- const render = () => flushSync(() => root.render(<QueryClientProvider client={client}>{device ? <McpDevicePage initialCode="MIST-YPED" /> : <McpConnectPage />}</QueryClientProvider>));
+ const render = () => flushSync(() => root.render(<QueryClientProvider client={client}>{device ? <McpDevicePage initialCode="MIST-YPED" /> : <McpConnectPage agentPairingOnly={agentPairingOnly} />}</QueryClientProvider>));
render();
return {
client, container, render,
@@ -61,10 +61,10 @@ it("lets a person correct an invalid device code without reloading", async () =>
} finally { page.cleanup(); }
});
-it("lets Dot use the operator pairing capability without signing into a board account", async () => {
+it.each([false, true])("lets Dot use the operator pairing capability without signing into a board account (dedicated=%s)", async dedicated => {
Object.assign(route, { agentConnection: true, requiresSignIn: true });
vi.mocked(api.post).mockImplementationOnce(async () => ({ company: { id: "company-one", name: "Dot Test Drive" }, agent: { id: "agent-one", name: "Dot" }, permissions: "Assigned work only", accessDuration: "Ongoing until revoked", pairingExpiresAt: new Date(Date.now() + 60000).toISOString() }) as never);
- const page = setup();
+ const page = setup(false, dedicated);
try {
await vi.waitFor(() => expect(page.container.querySelector("#dot-pairing-code")).not.toBeNull());
const input = page.container.querySelector<HTMLInputElement>("#dot-pairing-code")!;
@@ -80,7 +80,7 @@ it("lets Dot use the operator pairing capability without signing into a board ac
expect(page.container.textContent).toContain("Ongoing until revoked");
expect(connect.disabled).toBe(false);
flushSync(() => connect.click());
- await vi.waitFor(() => expect(api.post).toHaveBeenCalledWith("/mcp/requests/request-one/dot-pairing", { pairingCode: "x".repeat(32) }));
+ await vi.waitFor(() => expect(api.post).toHaveBeenCalledWith(`${dedicated ? "/dot-mcp" : "/mcp"}/requests/request-one/dot-pairing`, { pairingCode: "x".repeat(32) }));
} finally { page.cleanup(); }
});
diff --git a/ui/src/pages/McpConnect.tsx b/ui/src/pages/McpConnect.tsx
index 120c92998c..0933e7c93b 100644
--- a/ui/src/pages/McpConnect.tsx
+++ b/ui/src/pages/McpConnect.tsx
@@ -28,9 +28,9 @@ function ClientOrigin({ origin }: { origin: string }) {
</div>;
}
-export function McpConnectPage() {
+export function McpConnectPage({ agentPairingOnly = false }: { agentPairingOnly?: boolean } = {}) {
const { id = "" } = useParams();
- return <McpConnectRequest key={id} id={id} />;
+ return <McpConnectRequest key={id} id={id} agentPairingOnly={agentPairingOnly} />;
}
export function McpDevicePage({ initialCode }: { initialCode?: string } = {}) {
@@ -45,24 +45,25 @@ export function McpDevicePage({ initialCode }: { initialCode?: string } = {}) {
</form></Card></div>;
}
-function McpConnectRequest({ id, device = false, onEditCode }: { id: string; device?: boolean; onEditCode?: () => void }) {
+function McpConnectRequest({ id, device = false, agentPairingOnly = false, onEditCode }: { id: string; device?: boolean; agentPairingOnly?: boolean; onEditCode?: () => void }) {
+ const requestPrefix = agentPairingOnly ? "/dot-mcp/requests" : "/mcp/requests";
const [companyId, setCompanyId] = useState("");
const [pairingCode, setPairingCode] = useState("");
const [pairingPreview, setPairingPreview] = useState<McpDotPairingPreview | null>(null);
const [pairingPreviewError, setPairingPreviewError] = useState("");
const [writeEnabled, setWriteEnabled] = useState(true);
const [deviceResult, setDeviceResult] = useState<"approved" | "denied" | null>(null);
- const request = useQuery({ queryKey: [device ? "mcp-device" : "mcp-request", id], queryFn: () => api.get<McpConnectionRequest>(device ? `/mcp/device?user_code=${encodeURIComponent(id)}` : `/mcp/requests/${encodeURIComponent(id)}`), retry: false });
+ const request = useQuery({ queryKey: [device ? "mcp-device" : agentPairingOnly ? "dot-mcp-request" : "mcp-request", id], queryFn: () => api.get<McpConnectionRequest>(device ? `/mcp/device?user_code=${encodeURIComponent(id)}` : `${requestPrefix}/${encodeURIComponent(id)}`), retry: false });
const data = request.data;
useEffect(() => {
setPairingPreview(null); setPairingPreviewError("");
if (!data?.agentConnection || device || !/^[A-Za-z0-9_-]{32}$/.test(pairingCode.trim())) return;
let current = true;
- void api.post<McpDotPairingPreview>(`/mcp/requests/${encodeURIComponent(id)}/dot-pairing/preview`, { pairingCode: pairingCode.trim() })
+ void api.post<McpDotPairingPreview>(`${requestPrefix}/${encodeURIComponent(id)}/dot-pairing/preview`, { pairingCode: pairingCode.trim() })
.then(preview => { if (current) setPairingPreview(preview); })
.catch(error => { if (current) setPairingPreviewError(error instanceof Error ? error.message : "Unable to verify this pairing code."); });
return () => { current = false; };
- }, [id, device, data?.agentConnection, pairingCode]);
+ }, [id, device, requestPrefix, data?.agentConnection, pairingCode]);
const selectedCompanyId = data?.requestedCompanyId ?? (companyId || data?.companies[0]?.id || "");
// Pin the default once loaded so a refetch cannot silently switch organizations.
useEffect(() => {
@@ -80,11 +81,11 @@ function McpConnectRequest({ id, device = false, onEditCode }: { id: string; dev
onSuccess: ({ redirectUrl, status }) => { if (device && status) setDeviceResult(status); else if (redirectUrl) window.location.assign(redirectUrl); },
});
const pairDot = useMutation({
- mutationFn: () => api.post<{ redirectUrl: string }>(`/mcp/requests/${encodeURIComponent(id)}/dot-pairing`, { pairingCode: pairingCode.trim() }),
+ mutationFn: () => api.post<{ redirectUrl: string }>(`${requestPrefix}/${encodeURIComponent(id)}/dot-pairing`, { pairingCode: pairingCode.trim() }),
onSuccess: ({ redirectUrl }) => { setPairingCode(""); window.location.assign(redirectUrl); },
});
if (deviceResult) return <div className="mx-auto max-w-xl py-10"><Card className="block space-y-4 p-6"><Paperclip className="size-8" /><h1 className="text-xl font-semibold">{deviceResult === "approved" ? "Access approved" : "Connection declined"}</h1><p className="text-sm">{deviceResult === "approved" ? "Return to your assistant. It will finish connecting automatically." : "No access was granted. You can start a new connection from your assistant."}</p><Button variant="outline" asChild><Link to="/">Back to Paperclip</Link></Button></Card></div>;
- const returnPath = device ? `/mcp-device?user_code=${encodeURIComponent(id)}` : `/mcp-connect/${id}`;
+ const returnPath = device ? `/mcp-device?user_code=${encodeURIComponent(id)}` : `${agentPairingOnly ? "/dot-connect" : "/mcp-connect"}/${id}`;
return <div className="mx-auto max-w-xl py-10">
<Card className="block space-y-4 p-6">
<div className="flex items-center gap-3">