mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-07 07:55:47 +01:00
feat: connect experimental Cursor Cloud to native Runner (#18069)
## Thinking Path > - Paperclip helps people manage AI agents at work. > - Native Runner owns execution and task authority. > - Operators need an explicit native Cursor Cloud choice. > - Tools/files need company, task, session and run scope. > - This connects setup and lifecycle to Runner Core. > - Legacy agents retain their selected runtime/history. ## Linked Issues or Issue Description Depends on #18068. Managed-only API placement and API-owned Stop containment are in #18310. Refs #5664, #11803, #17299, and #17471. No duplicate native integration was found. ## What Changed - Add explicit native setup, Test, saved settings and dispatch with no-prompt account/catalog/callback checks. - Scope MCP to company, agent, task, session and run through authenticated HTTPS. Register verified artifacts/work products; preserve unpriced accounting, completion and budgets. - Connect Question/Plan continuation, cold handoff and admitted fresh sessions; recheck waiting admission under the task lock. - Present audited Stop intent while preserving physical containment proof; bound typed Stop metadata. Preserve title edits through preference/navigation readiness. - Select one live/history representation per run to prevent duplicate settled cards. Integrate upstream task/read-state/retry/schema contracts and repair two test fixtures. ## Verification Core #18068 merged normally as `3910352c923a`. Product head `5a60f541c982` has passing repository CI/build/browser checks, including required `ci / verify` and `ci / e2e`, plus a fresh exact-head Greptile 5/5 review with zero unresolved threads. Two non-required external app checks remain pending: Paperclip Review is queued waiting for its assigned agent; Superagent Security Scan is reviewing the diff. These are not claimed completed. The normal merge endpoint enforces the repository rules; no policy or status override is used. The dependent Top PR is addressing its fresh deferred-Stop review finding. Product `5a60f541c982` passed 270 UI and 20 selected Cloud/native/disk-full tests, UI/server typechecks, tokens and maps. Top’s clean normal merge passed tokens/maps/diff checks; its matrix is pending. Earlier receipts retain Core’s 47 Rust, 4 compiled-native retirement and 19 settlement controls, normal Runner build, and runtime 9af build/recursive typecheck. Reproduced loading/shutdown CI fixture failures passed 7/7 browser and 121/121 unit tests, including a broken-unsubscribe negative control. No timeout/oracle was relaxed. The actual-parent restack adopts 75 mainline paths, including schema/permission and generic runtime changes, beyond the prior two fixture repairs and client projection fix. The full difference from hosted `9af1a5de42a2` is therefore larger than four files; backend source also differs. The merged config-read checks match Core391, and the Cursor placement/runtime/relay/selection modules match frozen9af; selected affected regressions pass. Paid proof keeps its actual 9af source/image identity. The separately tested live/history card fix is not claimed deployed on that host. On 9af, original saved settings survived reopening and fresh no-prompt Test authenticated catalog/model/binding; no new Save is claimed. Fresh Linux admission passed. With `claude-sonnet-4-5`, Artifact downloaded exact 27 bytes and matched 121 canonical identities in complete S3-served history. First Stop’s strict quiet FAILED on a 10.373-second gap despite independent cancellation/no late artifact. One targeted unchanged-sampler retry retained all 24 samples: 35.076 seconds quiet / maximum gap 4.584 seconds, 67 ordered canonical identities, and separate CANCELLED/artifact-absent status after the original 180-second deadline. The pre-reload duplicate settled card is disclosed. Exact-ID cleanup for the three new provider agents is awaiting authorization, so full grades and the fresh Artifact’s post-cleanup download remain blocked. A historical deleted-provider artifact was newly downloaded on 9af; original F226 Question/Plan/reconnect and cleanup proof keep their identities. Retained failures: stale fixture 132/133; E8 48/135 with 87 reset-hook failures; Mac 17 SQL failures/skips; earlier title/startup/custody/Stop/deletion failures with unknown causes/bounded recoveries; `dea023` Stop’s warning/50 duplicate identities; pre-repair ACK and original Core CI failures. WSP’s 251-assertion, 7/8-suite attempt failed physical PostgreSQL teardown; the unchanged wrapper rerun passed 128. Retry alone establishes no cause or full local-suite pass. All paid attempts remain recorded; vendor dollar cost is UNKNOWN. ## Risks Experimental: Cursor independently acknowledges neither the effective model nor instruction digest before the first prompt. Explicit values are submitted and checked through behavior; unpriced provider dollar cost stays UNKNOWN. Callbacks need authenticated reachable HTTPS. Scope, revocation, budgets, completion and cleanup remain authoritative. Operator Stop intent is separate from physical containment. Saved legacy agents retain their selected runtime. Prior shared title-save/deletion failures remain disclosed. ## Model Used OpenAI Codex, GPT-6 family, assisted with reasoning, repository tools, code execution, browser verification, and delegated code review. The serving model’s exact API ID and context window are not exposed. No value is inferred from the model catalog. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used and the limits of available model metadata - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have linked public issues or described the issue in this PR - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My branch describes the change and contains no internal ticket ID - [x] I have run the scoped local tests reported above; pending gates are stated separately - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented the risks - [x] All required CI gates pass on the current head - [x] Fresh Greptile is 5/5 with no unresolved findings on the current head - [x] I will address all reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
3d5878980b
commit
27d35314be
111 files changed
+5953
-269
No files matched your search
@@ -0,0 +1,98 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { spawn } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import { lstat, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { readVerifiedWorkspaceFile, type NativeRunnerFileHandoffInput } from "./native-runner-file-handoff.js";
|
||||
|
||||
const { stageCursorCloudArtifact } = await import(new URL("../../../../packages/paperclip-runner/src/drivers/cursor-cloud/artifact-delivery.ts", import.meta.url).href);
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
for (const root of roots.splice(0)) await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function fixture() {
|
||||
const root = await mkdtemp(join(tmpdir(), "cursor-cloud-handoff-"));
|
||||
roots.push(root);
|
||||
const artifactRoot = join(root, "artifacts");
|
||||
const body = Buffer.from("verified cloud artifact\n");
|
||||
const args = {
|
||||
contentRef: "cursor-artifact:artifacts/result.txt", filename: "result.txt",
|
||||
title: "Cloud result", contentType: "text/plain", byteSize: body.length,
|
||||
sha256: createHash("sha256").update(body).digest("hex"),
|
||||
};
|
||||
const stage = () => stageCursorCloudArtifact({
|
||||
arguments: args, agentId: "owned-agent", runtimeDirectory: root, artifactRoot,
|
||||
client: {
|
||||
listArtifacts: async () => ({ items: [{ path: "artifacts/result.txt", sizeBytes: body.length, updatedAt: "2026-10-28" }] }),
|
||||
downloadArtifact: async () => body,
|
||||
},
|
||||
signal: new AbortController().signal,
|
||||
});
|
||||
const binding = {
|
||||
companyId: "company", issueId: "issue", runId: "run", agentId: "agent",
|
||||
workspaceRoot: artifactRoot, executionTargetKind: "local" as const,
|
||||
};
|
||||
return { root, artifactRoot, args, binding, body, stage };
|
||||
}
|
||||
|
||||
describe("Cursor Cloud staged artifact to Core handoff", () => {
|
||||
it("lets Core independently verify fresh and repeated provider staging", async () => {
|
||||
const f = await fixture();
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
const staged = await f.stage();
|
||||
const verified = await readVerifiedWorkspaceFile(f.binding, staged as unknown as NativeRunnerFileHandoffInput);
|
||||
expect(verified).toEqual({ body: f.body, contentType: "text/plain", filename: "result.txt", sha256: f.args.sha256, title: "Cloud result" });
|
||||
}
|
||||
});
|
||||
|
||||
it("recovers a crash after publication before alias removal through the unchanged verified reader", async () => {
|
||||
const f = await fixture();
|
||||
const target = join(f.artifactRoot, f.args.sha256, f.args.filename);
|
||||
const script = join(f.root, "crash-after-publication.mjs");
|
||||
await writeFile(script, `
|
||||
import fs from "node:fs/promises";
|
||||
import { syncBuiltinESMExports } from "node:module";
|
||||
const original = fs.link;
|
||||
fs.link = async (...args) => {
|
||||
await original(...args);
|
||||
if (String(args[1]) === ${JSON.stringify(target)}) {
|
||||
process.send("published-before-alias-removal");
|
||||
await new Promise(resolve => process.once("message", resolve));
|
||||
}
|
||||
};
|
||||
syncBuiltinESMExports();
|
||||
const { stageCursorCloudArtifact } = await import(${JSON.stringify(new URL("../../../../packages/paperclip-runner/src/drivers/cursor-cloud/artifact-delivery.ts", import.meta.url).href)});
|
||||
const bytes = Buffer.from(${JSON.stringify(f.body.toString("base64"))}, "base64");
|
||||
await stageCursorCloudArtifact({ arguments: ${JSON.stringify(f.args)}, agentId: "owned-agent", runtimeDirectory: ${JSON.stringify(f.root)}, artifactRoot: ${JSON.stringify(f.artifactRoot)},
|
||||
client: { listArtifacts: async () => ({ items: [{ path: "artifacts/result.txt", sizeBytes: bytes.length }] }), downloadArtifact: async () => bytes }, signal: new AbortController().signal });
|
||||
process.send("unexpected-completed");
|
||||
`, { mode: 0o600 });
|
||||
const child = spawn(process.execPath, ["--import", new URL("../../../../packages/paperclip-runner/node_modules/tsx/dist/loader.mjs", import.meta.url).pathname, script], { env: {}, stdio: ["ignore", "ignore", "pipe", "ipc"] });
|
||||
let stderr = ""; child.stderr?.on("data", bytes => { stderr = (stderr + bytes).slice(-4_096); });
|
||||
const exited = once(child, "exit");
|
||||
try {
|
||||
const message = await Promise.race([once(child, "message"), exited.then(() => { throw new Error(`publication crash fixture exited early: ${stderr}`); })]);
|
||||
expect(message[0]).toBe("published-before-alias-removal");
|
||||
expect((await lstat(target)).nlink).toBe(2);
|
||||
child.kill("SIGKILL"); expect(await exited).toEqual([null, "SIGKILL"]);
|
||||
const staged = await f.stage();
|
||||
const verified = await readVerifiedWorkspaceFile(f.binding, staged as unknown as NativeRunnerFileHandoffInput);
|
||||
expect(verified).toEqual({ body: f.body, contentType: "text/plain", filename: "result.txt", sha256: f.args.sha256, title: "Cloud result" });
|
||||
expect((await lstat(target)).nlink).toBe(1);
|
||||
} finally {
|
||||
if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
|
||||
await exited;
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps Core hash verification after provider staging", async () => {
|
||||
const f = await fixture();
|
||||
const staged = await f.stage();
|
||||
await writeFile(join(f.artifactRoot, f.args.sha256, "result.txt"), Buffer.alloc(f.body.length, 120));
|
||||
await expect(readVerifiedWorkspaceFile(f.binding, staged as unknown as NativeRunnerFileHandoffInput)).rejects.toThrow("paperclip_runner_file_handoff_hash_mismatch");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { projectPaperclipRunnerTaskConfig, resolvePaperclipRunnerNativeProviderInput, resolvePaperclipRunnerProviderProfile } from "./provider-profile.js";
|
||||
|
||||
const config = { provider: "cursor_cloud", model: "caller-custom-model", repoUrl: "https://github.com/acme/repo", env: { CURSOR_API_KEY: { type: "secret_ref", secretId: "company-secret", version: "latest" } } };
|
||||
|
||||
describe("Cursor Cloud native provider admission", () => {
|
||||
it("forwards the task-selected exact model without applying an effort policy", () => {
|
||||
const projected = projectPaperclipRunnerTaskConfig("cursor_cloud_api", config, { model: "task-selected-model", modelReasoningEffort: "high" });
|
||||
expect(resolvePaperclipRunnerNativeProviderInput({ backend: "cursor_cloud_api", adapterConfig: projected })).toMatchObject({ model: "task-selected-model" });
|
||||
expect(projected).not.toHaveProperty("modelReasoningEffort");
|
||||
});
|
||||
it("preserves the exact caller model and provider-owned remote configuration", () => {
|
||||
expect(resolvePaperclipRunnerProviderProfile(config)).toEqual({ provider: "cursor_cloud", backend: "cursor_cloud_api", model: "caller-custom-model" });
|
||||
expect(resolvePaperclipRunnerNativeProviderInput({ backend: "cursor_cloud_api", adapterConfig: { ...config, repoRef: "feature", autoCreatePR: true } })).toEqual({
|
||||
provider: "cursor_cloud", model: "caller-custom-model", cursorCloud: { schema: "paperclip.cursor-cloud.config.v1", repos: [{ url: config.repoUrl, startingRef: "feature" }], env: { type: "cloud" }, autoCreatePR: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("reads saved legacy repository fields and rejects conflicting aliases", () => {
|
||||
expect(resolvePaperclipRunnerNativeProviderInput({ backend: "cursor_cloud_api", adapterConfig: { ...config, repoStartingRef: "legacy", runtimeEnvType: "cloud" } })).toMatchObject({ cursorCloud: { repos: [{ startingRef: "legacy" }] } });
|
||||
expect(() => resolvePaperclipRunnerProviderProfile({ ...config, repoStartingRef: "legacy", repoRef: "different" })).toThrow(expect.objectContaining({ code: "paperclip_runner_cursor_cloud_config_invalid" }));
|
||||
});
|
||||
|
||||
it.each(["plain", "secret_ref"])("rejects selected hosted secrets instead of dropping their %s binding", type => {
|
||||
const env = { ...config.env, GH_TOKEN: type === "plain" ? { type, value: "unforwarded-test-value" } : { type, secretId: "hosted-secret", version: "latest" } };
|
||||
for (const admit of [
|
||||
() => resolvePaperclipRunnerProviderProfile({ ...config, env }),
|
||||
() => resolvePaperclipRunnerNativeProviderInput({ backend: "cursor_cloud_api", adapterConfig: { ...config, env } }),
|
||||
]) {
|
||||
expect(admit).toThrow("Configure hosted secrets in your Cursor Cloud environment");
|
||||
expect(admit).toThrow("GH_TOKEN");
|
||||
expect(admit).not.toThrow("unforwarded-test-value");
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["", undefined])("requires an explicit model (%s)", model => {
|
||||
expect(() => resolvePaperclipRunnerProviderProfile({ ...config, model })).toThrow(expect.objectContaining({ code: "paperclip_runner_cursor_cloud_model_required" }));
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ cloudEnvType: "pool" }, { lifecycleMode: "warm" }, { codexPermissionMode: "never" },
|
||||
{ acpxPermissionMode: "approve-all" }, { promptTemplate: "replace assigned instructions" },
|
||||
{ modelReasoningEffort: "high" }, { reasoningEffort: "high" }, { effort: "high" }, { modelParams: [{ key: "reasoning", value: "high" }] }, { homeMode: "preconfigured" },
|
||||
{ cursorCloudTimeoutMs: 3_600_001 }, { repoUrl: "https://user:secret@github.com/acme/repo" },
|
||||
])("rejects unsupported or unsafe configuration %j", patch => {
|
||||
expect(() => resolvePaperclipRunnerProviderProfile({ ...config, ...patch })).toThrow(expect.objectContaining({ code: "paperclip_runner_cursor_cloud_config_invalid" }));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createServer } from "node:http";
|
||||
import { mkdtemp, readFile, rm, stat } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { CURSOR_CLOUD_DEFAULT_TIMEOUT_MS, type NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
import { createCapabilityRunnerdProviderEnvironment } from "@paperclipai/paperclip-runner/live";
|
||||
import { prepareCursorCloudRuntime, resolveCursorCloudPublicOrigin } from "./cursor-cloud-runtime.js";
|
||||
import { forwardRemoteMcpRequest } from "./remote-mcp-relay.js";
|
||||
|
||||
const disposers: Array<() => void | Promise<void>> = [];
|
||||
afterEach(async () => {
|
||||
for (const dispose of disposers.splice(0).reverse()) await dispose();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
const runningDb = { select: () => ({ from: () => ({ where: () => ({ limit: async () => [{ status: "running", runtimeMode: "native" }] }) }) }) } as unknown as Db;
|
||||
|
||||
function execution(runId: string): NativeExecutionInput {
|
||||
return { binding: { companyId: "company", agentId: "agent", issueId: "issue", runId, executionWorkspaceId: "workspace" },
|
||||
provider: { kind: "cursor_cloud", model: "explicit-model", cursorCloud: { schema: "paperclip.cursor-cloud.config.v1", repos: [{ url: "https://github.com/acme/fixture" }] } },
|
||||
session: { normalizedSessionId: "same-cloud-session", lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
|
||||
} as NativeExecutionInput;
|
||||
}
|
||||
|
||||
async function prepare(root: string, current: NativeExecutionInput, authorityCurrent = () => true) {
|
||||
const runtime = prepareCursorCloudRuntime({ root, execution: current, db: runningDb, publicOrigin: "https://relay.example.test",
|
||||
environment: { CURSOR_API_KEY: "selected-key", OPENAI_API_KEY: "other-secret" }, authorityCurrent });
|
||||
disposers.push(runtime.unregister);
|
||||
const socketPath = runtime.environment.PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH;
|
||||
disposers.push(() => rm(dirname(socketPath), { recursive: true, force: true }));
|
||||
return runtime;
|
||||
}
|
||||
|
||||
async function directory(): Promise<string> {
|
||||
const root = await mkdtemp("/tmp/pc-cloud-runtime-");
|
||||
disposers.push(() => rm(root, { recursive: true, force: true }));
|
||||
return root;
|
||||
}
|
||||
|
||||
const invoke = (runId: string, token: string) => forwardRemoteMcpRequest({ runId, authorization: `Bearer ${token}`,
|
||||
body: { jsonrpc: "2.0", id: 1, method: "tools/list" } });
|
||||
|
||||
describe("Cursor Cloud controller runtime capability", () => {
|
||||
it("retains an exact recovery capability and rotates a later run without sharing either route", async () => {
|
||||
const root = await directory();
|
||||
const first = execution("first-run");
|
||||
let authority = true;
|
||||
const initial = await prepare(root, first, () => authority);
|
||||
const before = initial.environment;
|
||||
let calls = 0;
|
||||
const server = createServer((req, res) => {
|
||||
calls += 1;
|
||||
expect(req.headers.authorization).toMatch(/^Bearer [a-zA-Z0-9_-]{43}$/);
|
||||
res.setHeader("content-type", "application/json");
|
||||
res.end(JSON.stringify({ jsonrpc: "2.0", id: 1, result: { tools: [] } }));
|
||||
});
|
||||
await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(before.PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH, resolve); });
|
||||
disposers.push(() => new Promise<void>(resolve => server.close(() => resolve())));
|
||||
expect((await invoke(first.binding.runId, before.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN)).status).toBe(401);
|
||||
initial.register();
|
||||
expect((await invoke(first.binding.runId, before.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN)).status).toBe(200);
|
||||
authority = false;
|
||||
expect((await invoke(first.binding.runId, before.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN)).status).toBe(403);
|
||||
initial.unregister();
|
||||
const exact = await prepare(root, first);
|
||||
expect(exact.environment.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN).toBe(before.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN);
|
||||
exact.register(); exact.unregister();
|
||||
const next = execution("next-run");
|
||||
const subsequent = await prepare(root, next);
|
||||
const after = subsequent.environment;
|
||||
expect(after.PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH).toBe(before.PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH);
|
||||
expect(after.PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH).toBe(before.PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH);
|
||||
expect(after.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN).not.toBe(before.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN);
|
||||
expect(after.PAPERCLIP_CURSOR_CLOUD_RELAY_URL).toBe("https://relay.example.test/mcp/native-runs/next-run");
|
||||
subsequent.register();
|
||||
expect((await invoke(next.binding.runId, before.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN)).status).toBe(401);
|
||||
expect((await invoke(first.binding.runId, before.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN)).status).toBe(401);
|
||||
expect((await invoke(next.binding.runId, after.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN)).status).toBe(200);
|
||||
expect(calls).toBe(2);
|
||||
const projected = createCapabilityRunnerdProviderEnvironment({ provider: "cursor_cloud", options: { environment: after } as never,
|
||||
identity: { runnerInstanceId: "controller", environmentLeaseId: "workspace", runId: next.binding.runId,
|
||||
normalizedSessionId: next.session.normalizedSessionId!, turnId: "turn", itemId: "item" },
|
||||
codexHome: "/unused", runtimeContextPath: "/unused", hasRuntimeContext: false });
|
||||
expect(projected.PAPERCLIP_RUN_ID).toBe("next-run");
|
||||
expect(projected.PAPERCLIP_NORMALIZED_SESSION_ID).toBe("same-cloud-session");
|
||||
expect(projected.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN).toBe(after.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN);
|
||||
expect(projected).not.toHaveProperty("OPENAI_API_KEY");
|
||||
});
|
||||
|
||||
it("uses the full default deadline and preserves expired identity for cleanup while denying ordinary admission", async () => {
|
||||
const root = await directory();
|
||||
const current = execution("expiry-run");
|
||||
const now = Date.now();
|
||||
const clock = vi.spyOn(Date, "now").mockReturnValue(now);
|
||||
const initial = await prepare(root, current);
|
||||
const capabilityPath = join(root, "cursor-cloud", "relay-capability.json");
|
||||
const capability = JSON.parse(await readFile(capabilityPath, "utf8"));
|
||||
expect(capability.expiresAt).toBe(now + CURSOR_CLOUD_DEFAULT_TIMEOUT_MS + 120_000);
|
||||
expect(initial.environment.PAPERCLIP_CURSOR_CLOUD_RELAY_EXPIRES_AT).toBe(String(capability.expiresAt));
|
||||
expect((await stat(capabilityPath)).mode & 0o077).toBe(0);
|
||||
expect(await readFile(initial.environment.PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH, "utf8")).not.toContain("selected-key");
|
||||
clock.mockReturnValue(capability.expiresAt + 1);
|
||||
const recovered = await prepare(root, current);
|
||||
expect(recovered.environment.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN).toBe(capability.token);
|
||||
expect(() => recovered.register()).toThrow("expired");
|
||||
recovered.register({ cleanupOnly: true });
|
||||
expect((await invoke(current.binding.runId, capability.token)).status).toBe(401);
|
||||
});
|
||||
|
||||
it("derives the relay origin from normal auth public URL configuration", () => {
|
||||
vi.stubEnv("PAPERCLIP_PUBLIC_URL", "");
|
||||
vi.stubEnv("PAPERCLIP_AUTH_PUBLIC_BASE_URL", "https://normal-public-origin.example.test");
|
||||
expect(resolveCursorCloudPublicOrigin()).toBe("https://normal-public-origin.example.test");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { constants, existsSync, lstatSync, mkdirSync, openSync, closeSync, fstatSync, fsyncSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import { loadConfig } from "../../config.js";
|
||||
import { archiveCursorCloudSessionCheckpoint, CURSOR_CLOUD_DEFAULT_TIMEOUT_MS, type NativeExecutionInput, type PersistedNativeSession } from "../../vendor/paperclip-runner/index.js";
|
||||
import { createRemoteMcpRelayToken, registerRemoteMcpRelay, remoteMcpRelayUrl } from "./remote-mcp-relay.js";
|
||||
|
||||
export function resolveCursorCloudPublicOrigin(): string | undefined {
|
||||
return loadConfig().authPublicBaseUrl;
|
||||
}
|
||||
|
||||
export function prepareCursorCloudRuntime(input: {
|
||||
db: Db;
|
||||
execution: NativeExecutionInput;
|
||||
root: string;
|
||||
environment: NodeJS.ProcessEnv;
|
||||
publicOrigin?: string;
|
||||
authorityCurrent?: () => boolean;
|
||||
}) {
|
||||
const { execution } = input;
|
||||
if (execution.provider.kind !== "cursor_cloud") throw new Error("cursor_cloud_provider_required");
|
||||
if (!input.environment.CURSOR_API_KEY?.trim()) throw new Error("cursor_cloud_api_key_required: bind CURSOR_API_KEY to this agent");
|
||||
const origin = input.publicOrigin ?? resolveCursorCloudPublicOrigin();
|
||||
if (!origin) throw new Error("cursor_cloud_public_url_required: configure reachable HTTPS for the remote tool relay");
|
||||
const url = remoteMcpRelayUrl(origin, execution.binding.runId);
|
||||
const directory = join(input.root, "cursor-cloud");
|
||||
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
||||
const privateDirectory = (path: string) => {
|
||||
const stat = lstatSync(path);
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || (process.getuid && stat.uid !== process.getuid())) throw new Error("cursor_cloud_runtime_directory_unsafe");
|
||||
};
|
||||
privateDirectory(directory);
|
||||
const binding = { ...execution.binding, normalizedSessionId: execution.session.normalizedSessionId ?? `session-${execution.binding.runId}` };
|
||||
const bindingDigest = createHash("sha256").update(JSON.stringify(binding)).digest("hex");
|
||||
const capabilityPath = join(directory, "relay-capability.json");
|
||||
let capability: { bindingDigest: string; token: string; expiresAt: number };
|
||||
if (existsSync(capabilityPath)) {
|
||||
const fd = openSync(capabilityPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
const stat = fstatSync(fd);
|
||||
if (!stat.isFile() || stat.size > 4096 || (stat.mode & 0o077) !== 0 || (process.getuid && stat.uid !== process.getuid())) throw new Error("cursor_cloud_relay_capability_unsafe");
|
||||
capability = JSON.parse(readFileSync(fd, "utf8"));
|
||||
} finally { closeSync(fd); }
|
||||
if (capability.bindingDigest !== bindingDigest) capability = { bindingDigest, token: createRemoteMcpRelayToken(), expiresAt: Date.now() + (execution.provider.cursorCloud.timeoutMs ?? CURSOR_CLOUD_DEFAULT_TIMEOUT_MS) + 120_000 };
|
||||
} else capability = { bindingDigest, token: createRemoteMcpRelayToken(), expiresAt: Date.now() + (execution.provider.cursorCloud.timeoutMs ?? CURSOR_CLOUD_DEFAULT_TIMEOUT_MS) + 120_000 };
|
||||
if (typeof capability.token !== "string" || capability.token.length < 32 || !Number.isFinite(capability.expiresAt)) throw new Error("cursor_cloud_relay_capability_invalid");
|
||||
const savePrivate = (path: string, value: unknown) => {
|
||||
const prior = lstatSync(path, { throwIfNoEntry: false });
|
||||
if (prior && (!prior.isFile() || prior.isSymbolicLink() || (prior.mode & 0o077) !== 0 || (process.getuid && prior.uid !== process.getuid()))) throw new Error("cursor_cloud_runtime_file_unsafe");
|
||||
const pending = `${path}.${randomUUID()}.tmp`;
|
||||
const fd = openSync(pending, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
|
||||
try { writeFileSync(fd, JSON.stringify(value)); fsyncSync(fd); }
|
||||
finally { closeSync(fd); }
|
||||
try { renameSync(pending, path); }
|
||||
finally { rmSync(pending, { force: true }); }
|
||||
};
|
||||
savePrivate(capabilityPath, capability);
|
||||
const socketRoot = `/tmp/paperclip-cloud-${createHash("sha256").update(input.root).digest("hex").slice(0, 24)}`;
|
||||
if (!existsSync(socketRoot)) mkdirSync(socketRoot, { mode: 0o700 });
|
||||
privateDirectory(socketRoot);
|
||||
const socketPath = join(socketRoot, "mcp.sock");
|
||||
const artifactRoot = join(directory, "artifacts");
|
||||
mkdirSync(artifactRoot, { recursive: true, mode: 0o700 });
|
||||
privateDirectory(artifactRoot);
|
||||
const configPath = join(directory, "config.json");
|
||||
savePrivate(configPath, { ...execution.provider.cursorCloud, binding: {
|
||||
companyId: execution.binding.companyId, agentId: execution.binding.agentId,
|
||||
issueId: execution.binding.issueId, normalizedSessionId: binding.normalizedSessionId,
|
||||
} });
|
||||
let release: (() => void) | undefined;
|
||||
const register = (options?: { cleanupOnly?: boolean }) => {
|
||||
if (capability.expiresAt <= Date.now() && options?.cleanupOnly !== true) throw new Error("cursor_cloud_relay_capability_expired");
|
||||
release ??= registerRemoteMcpRelay({ runId: execution.binding.runId, socketPath, token: capability.token, expiresAt: capability.expiresAt,
|
||||
authorized: async () => {
|
||||
if (input.authorityCurrent && !input.authorityCurrent()) return false;
|
||||
const run = await input.db.select({ status: heartbeatRuns.status, runtimeMode: heartbeatRuns.runtimeMode }).from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.id, execution.binding.runId), eq(heartbeatRuns.companyId, execution.binding.companyId),
|
||||
eq(heartbeatRuns.agentId, execution.binding.agentId), eq(heartbeatRuns.issueId, execution.binding.issueId),
|
||||
)).limit(1).then(rows => rows[0]);
|
||||
return run?.status === "running" && run.runtimeMode === "native" && (!input.authorityCurrent || input.authorityCurrent());
|
||||
} });
|
||||
};
|
||||
const archiveCheckpoint = async (archiveRoot: string, previous: PersistedNativeSession | undefined) => {
|
||||
if (!previous?.identity || previous.sessionId !== binding.normalizedSessionId || previous.identity.companyId !== execution.binding.companyId
|
||||
|| previous.identity.agentId !== execution.binding.agentId || previous.identity.issueId !== execution.binding.issueId) throw new Error("cursor_cloud_replacement_binding_mismatch");
|
||||
await archiveCursorCloudSessionCheckpoint({ runtimeDirectory: directory, driverSessionId: previous.sessionId,
|
||||
ownerRunId: previous.identity.runId, binding: { companyId: execution.binding.companyId, agentId: execution.binding.agentId,
|
||||
issueId: execution.binding.issueId, normalizedSessionId: binding.normalizedSessionId }, socketPath,
|
||||
archiveDirectory: join(archiveRoot, "cursor-cloud") });
|
||||
};
|
||||
const unregister = () => { release?.(); release = undefined; };
|
||||
return { register, unregister, archiveCheckpoint, environment: { ...input.environment,
|
||||
PAPERCLIP_CURSOR_CLOUD_ARTIFACT_ROOT: artifactRoot, PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH: configPath, PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH: socketPath,
|
||||
PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN: capability.token, PAPERCLIP_CURSOR_CLOUD_RELAY_URL: url,
|
||||
PAPERCLIP_CURSOR_CLOUD_RELAY_EXPIRES_AT: String(capability.expiresAt),
|
||||
} };
|
||||
}
|
||||
@@ -32,6 +32,24 @@ describe("LCA-05 explicit native work mode", () => {
|
||||
expect(input.task.title).toBe(text);
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["standard", "planning", "ask"] as const)("preserves Cursor Cloud %s intent independently of its native harness mode", workMode => {
|
||||
const planningContext = workMode === "planning" ? { documentId: "plan-document", baseRevisionId: "plan-revision-3", baseRevisionNumber: 3,
|
||||
markdown: "# Pinned canonical plan", sha256: "a".repeat(64), reviewContext: { feedback: "Keep the requested scope" } } : null;
|
||||
const input = buildNativeExecutionInput({
|
||||
companyId: "10000000-0000-4000-8000-000000000001", runId: "50000000-0000-4000-8000-000000000005", agentId: "30000000-0000-4000-8000-000000000003",
|
||||
issue: { id: "20000000-0000-4000-8000-000000000002", identifier: "MODE-1", title: "Create the requested result", description: null, workMode },
|
||||
taskPrompt: "Follow the task's actual work mode.",
|
||||
workspace: { id: "50000000-0000-4000-8000-000000000005", cwd: "/workspace", repoUrl: null, repoRef: null, branchName: null }, normalizedSessionId: null,
|
||||
provider: "cursor_cloud", model: "explicit-cloud-model", cursorCloud: { schema: "paperclip.cursor-cloud.config.v1", repos: [{ url: "https://github.com/example/fixture" }] },
|
||||
planningContext,
|
||||
completionContract: { id: "70000000-0000-4000-8000-000000000007", sha256: `sha256:${"a".repeat(64)}`, schemaVersion: "paperclip.run-result.v1",
|
||||
contract: { revision: "1", objective: "Deliver the requested work", criteria: [{ id: "output", requirement: "Deliver the requested work" }] } },
|
||||
runtimeContext: nativeRuntimeContextFixture(),
|
||||
});
|
||||
expect(input).toMatchObject({ task: { workMode }, executionMode: workMode === "planning" ? "plan" : "default", planningContext });
|
||||
expect(buildNativeModelEnvelope(input)).toMatchObject({ task: { workMode }, executionMode: workMode === "planning" ? "plan" : "default", planningContext });
|
||||
});
|
||||
});
|
||||
|
||||
describe("native execution input external-chat framing", () => {
|
||||
|
||||
@@ -96,7 +96,7 @@ export interface BuildNativeExecutionInput {
|
||||
branchName: string | null;
|
||||
};
|
||||
normalizedSessionId: string | null;
|
||||
provider?: "codex" | "opencode" | "claude_managed" | "aws_agentcore" | "acpx" | "openai_dot" | "grok_bot" | "muse";
|
||||
provider?: "cursor_cloud" | "codex" | "opencode" | "claude_managed" | "aws_agentcore" | "acpx" | "openai_dot" | "grok_bot" | "muse";
|
||||
museBinding?: MuseBindingSnapshot;
|
||||
dotBinding?: DotBindingSnapshot;
|
||||
acpxAgent?: NativeAcpxAgent;
|
||||
@@ -112,6 +112,7 @@ export interface BuildNativeExecutionInput {
|
||||
grokEffort?: "minimal" | "low" | "medium" | "high" | "xhigh";
|
||||
grokDisableWebSearch?: boolean;
|
||||
model?: string | null;
|
||||
cursorCloud?: import("../../vendor/paperclip-runner/index.js").NativeCursorCloudConfig;
|
||||
managedProfile?: Extract<
|
||||
NativeExecutionInputV5["provider"],
|
||||
{ kind: "claude_managed" }
|
||||
@@ -309,7 +310,7 @@ export function buildNativeExecutionInput(input: BuildNativeExecutionInput): Nat
|
||||
},
|
||||
session: {
|
||||
normalizedSessionId: input.normalizedSessionId,
|
||||
driverKind: input.provider === "opencode"
|
||||
driverKind: input.provider === "cursor_cloud" ? "cursor_cloud_api" : input.provider === "opencode"
|
||||
? "opencode_server"
|
||||
: input.provider === "claude_managed"
|
||||
? "claude_managed_agents_api"
|
||||
@@ -321,7 +322,7 @@ export function buildNativeExecutionInput(input: BuildNativeExecutionInput): Nat
|
||||
protocolVersion: 1,
|
||||
lifecyclePolicy: input.lifecyclePolicy ?? { mode: "per_turn", idleTimeoutMs: null },
|
||||
},
|
||||
provider: input.provider === "claude_managed"
|
||||
provider: input.provider === "cursor_cloud" ? { kind: "cursor_cloud", model: input.model, cursorCloud: input.cursorCloud } : input.provider === "claude_managed"
|
||||
? {
|
||||
kind: "claude_managed",
|
||||
model: input.model,
|
||||
|
||||
@@ -262,6 +262,7 @@ describeEmbeddedPostgres("native question bridge", () => {
|
||||
|
||||
const stateDirectory = mkdtempSync(join(tmpdir(), "native-permission-authority-"));
|
||||
const server = createServer();
|
||||
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3213" });
|
||||
const authority = new DurablePrpControlPlane({
|
||||
stateDirectory,
|
||||
@@ -295,7 +296,7 @@ describeEmbeddedPostgres("native question bridge", () => {
|
||||
} finally {
|
||||
await registration.release();
|
||||
await authority.stop();
|
||||
server.close();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
rmSync(stateDirectory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -99,6 +99,8 @@ import {
|
||||
import { nativeRuntimeContextFixture } from "./runtime-context.test-fixture.js";
|
||||
import { prepareIsolatedCodexHome } from "../../vendor/paperclip-runner/testing.js";
|
||||
import { nativeToolContractFingerprintForTarget } from "./native-session-resume.js";
|
||||
import { forwardRemoteMcpRequest } from "./remote-mcp-relay.js";
|
||||
import { createCapabilityRunnerdProviderEnvironment } from "@paperclipai/paperclip-runner/live";
|
||||
import * as nativeSessionResume from "./native-session-resume.js";
|
||||
import * as nativeLeaseRenewal from "./native-execution-lease.js";
|
||||
import { buildNativeHeartbeatPreparationSpans, createNativeRunTrace } from "./native-run-trace.js";
|
||||
@@ -169,7 +171,9 @@ type RunnerTransportOptions = {
|
||||
environmentLeaseId: string;
|
||||
runId: string;
|
||||
};
|
||||
provider?: "codex" | "opencode" | "acpx";
|
||||
provider?: "cursor_cloud" | "codex" | "opencode" | "acpx";
|
||||
cursorCloud?: Extract<NativeExecutionInput["provider"], { kind: "cursor_cloud" }>["cursorCloud"];
|
||||
lifecyclePolicy?: NativeExecutionInput["session"]["lifecyclePolicy"];
|
||||
opencodePermissionMode?: "allow" | "ask" | "deny";
|
||||
acpxAgent?: "claude" | "codex";
|
||||
acpxPermissionMode?: "approve-all" | "approve-paperclip" | "approve-reads" | "deny-all";
|
||||
@@ -206,6 +210,7 @@ const durableRunnerState = (
|
||||
});
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
localRuntimeApiUrl: vi.fn(() => "http://127.0.0.1:43219"),
|
||||
createAssignedMcpTools: vi.fn(),
|
||||
execute: vi.fn(),
|
||||
cleanup: vi.fn(),
|
||||
@@ -262,6 +267,8 @@ const state = vi.hoisted(() => ({
|
||||
release: null as null | (() => void),
|
||||
}));
|
||||
|
||||
vi.mock("../../runtime-api.js", () => ({ resolveLocalRuntimeApiUrl: state.localRuntimeApiUrl }));
|
||||
|
||||
const accountingEvents = vi.hoisted(() => ({ committed: undefined as undefined | ((event: PrpEvent) => Promise<void>), duplicate: undefined as undefined | ((event: PrpEvent) => Promise<void>) }));
|
||||
vi.mock("./paperclip-control-plane-port.js", async importOriginal => {
|
||||
const original = await importOriginal<typeof import("./paperclip-control-plane-port.js")>();
|
||||
@@ -432,6 +439,7 @@ import {
|
||||
import { onNativeRunnerEvidence } from "./native-runner-evidence-signal.js";
|
||||
|
||||
beforeEach(() => {
|
||||
state.localRuntimeApiUrl.mockReset().mockReturnValue("http://127.0.0.1:43219");
|
||||
// These transport-wiring fixtures use a partial Db double and synthetic IDs.
|
||||
// The real selector/bootstrap proof is exercised with Postgres by the durable
|
||||
// discovery and diskless admission suites, not by this backend unit boundary.
|
||||
@@ -1600,6 +1608,14 @@ describe("native provider usage normalization", () => {
|
||||
expect(nativeUsageCostUsd({ runDelta: { inputTokens: 10, outputTokens: 1 }, providerCostUsd: 100 })).toBeUndefined();
|
||||
expect(nativeUsageCostUsd({ runDelta: { providerCostUsd: 0 } })).toBeUndefined();
|
||||
});
|
||||
it.each([0, 100])("keeps Cursor Cloud accounting unknown despite a facade price of %s", providerCostUsd => {
|
||||
const provider = { kind: "cursor_cloud", model: "explicit-cloud-model", cursorCloud: {
|
||||
schema: "paperclip.cursor-cloud.config.v1", repos: [{ url: "https://github.com/acme/fixture" }],
|
||||
} } as NativeExecutionInput["provider"];
|
||||
expect(nativeUsageCostUsd({ runDelta: { inputTokens: 0, outputTokens: 0, providerCostUsd } }, provider)).toBeUndefined();
|
||||
expect(nativeUsageBiller(provider)).toBe("cursor");
|
||||
expect(resolveNativeBilling(provider)).toEqual({ provider: "cursor", biller: "cursor", billingType: "unknown" });
|
||||
});
|
||||
it.each([["cursor", "cursor"], ["copilot", "github"], ["pi", "openrouter"]] as const)("keeps %s cost unknown and attributes its actual biller", (agent, biller) => {
|
||||
const provider = { kind: "acpx", agent, model: "exact-model" } as NativeExecutionInput["provider"];
|
||||
expect(nativeUsageBiller(provider)).toBe(biller);
|
||||
@@ -7455,6 +7471,134 @@ describe("native startup restart detachment", () => {
|
||||
});
|
||||
|
||||
describe("native terminal-turn accounting", () => {
|
||||
it.each(["turn.completed", "turn.interrupted"])("settles proven Cursor Cloud terminal accounting as complete and unpriced (%s)", async eventType => {
|
||||
const current = { ...execution, binding: { ...execution.binding, runId: "cursor-cloud-unpriced-accounting" },
|
||||
provider: { kind: "cursor_cloud", model: "explicit-cloud-model", cursorCloud: {
|
||||
schema: "paperclip.cursor-cloud.config.v1", repos: [{ url: "https://github.com/acme/fixture" }],
|
||||
} } } as NativeExecutionInput;
|
||||
const onUsage = vi.fn(async (_receipt: import("@paperclipai/adapter-utils").AdapterUsageCheckpoint) => {});
|
||||
const zero = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, providerCostUsd: 0 };
|
||||
state.execute.mockReset().mockImplementationOnce(async () => {
|
||||
await accountingEvents.committed!({ eventType: "item.completed", turnId: "cloud-turn", payload: {
|
||||
kind: "usage", usage: { runDelta: zero, runDeltaComplete: true },
|
||||
} } as unknown as PrpEvent);
|
||||
await accountingEvents.committed!({ eventType, turnId: "cloud-turn", payload: { error: null, status: eventType.slice("turn.".length) } } as unknown as PrpEvent);
|
||||
return { result: { summary: eventType === "turn.interrupted" ? "Waiting for an answer" : "Cloud work finished" }, terminal: { runTerminalState: "succeeded" }, turnId: "cloud-turn",
|
||||
normalizedSessionId: current.session.normalizedSessionId, providerSessionId: "remote-cloud-agent",
|
||||
driverKind: "cursor_cloud_api", driverVersion: "cursor-cloud-v1", nativeEventCount: 1,
|
||||
highestContiguousSourceSeq: 1, usage: { runDelta: zero, runDeltaComplete: true } };
|
||||
});
|
||||
const result = await executePaperclipNativeSession({ db: leaseDb(current), execution: current,
|
||||
runnerInstanceId: "cloud-accounting-controller", onUsage });
|
||||
expect(result).toMatchObject({ usageComplete: true, costUsd: null, costStatus: "unpriced", provider: "cursor", biller: "cursor",
|
||||
billingType: "unknown", resultJson: { providerAccounting: { usage: null, cost: null, externallyBilled: true } } });
|
||||
expect(result.usage).toBeUndefined();
|
||||
expect(result.costUsdExact).toBeUndefined();
|
||||
expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: true, costUsd: null, costStatus: "unpriced" }));
|
||||
expect(onUsage.mock.calls.at(-1)![0].usage).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each(["missing", "foreign-turn", "unproven", "ack-only", "recovered"])("keeps Cursor Cloud accounting bound to a proven matching terminal (%s)", async proof => {
|
||||
const current = { ...execution, binding: { ...execution.binding, runId: `cloud-terminal-${proof}` },
|
||||
provider: { kind: "cursor_cloud", model: "explicit-cloud-model", cursorCloud: {
|
||||
schema: "paperclip.cursor-cloud.config.v1", repos: [{ url: "https://github.com/acme/fixture" }],
|
||||
} } } as NativeExecutionInput;
|
||||
const terminal = { eventType: "turn.interrupted", turnId: proof === "foreign-turn" ? "prior-turn" : "cloud-turn",
|
||||
payload: { error: null, status: "interrupted", ...(proof === "unproven" ? { providerTerminalObserved: false } : {}) } } as unknown as PrpEvent;
|
||||
const onUsage = vi.fn(async (_receipt: AdapterUsageCheckpoint) => {});
|
||||
state.execute.mockReset().mockImplementationOnce(async () => {
|
||||
if (["foreign-turn", "unproven"].includes(proof)) await accountingEvents.committed!(terminal);
|
||||
if (proof === "ack-only") await accountingEvents.committed!({ eventType: "item.completed", turnId: "cloud-turn",
|
||||
payload: { kind: "interrupt_acknowledgement", acknowledged: true } } as unknown as PrpEvent);
|
||||
return { result: { summary: "Waiting for an answer" }, terminal: { runTerminalState: "succeeded" }, turnId: "cloud-turn",
|
||||
normalizedSessionId: current.session.normalizedSessionId, providerSessionId: "cloud-agent", driverKind: "cursor_cloud_api",
|
||||
driverVersion: "cursor-cloud-v1", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
const result = await executePaperclipNativeSession({ db: leaseDb(current, {}, {}, [], {}, "running", proof === "recovered" ? [terminal] : []),
|
||||
execution: current, runnerInstanceId: `cloud-terminal-${proof}`, onUsage });
|
||||
expect(result.usageComplete).toBe(proof === "recovered");
|
||||
expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ complete: proof === "recovered", costStatus: "unpriced", costUsd: null }));
|
||||
expect(result.usage).toBeUndefined();
|
||||
});
|
||||
|
||||
it("settles Cursor Cloud terminal receipts through the real ledger and scoped budget policies", async () => {
|
||||
const tables = await import("@paperclipai/db");
|
||||
const { eq } = await import("drizzle-orm");
|
||||
const { startRecoveryPostgres } = await import("../../__tests__/helpers/recovery-postgres.js");
|
||||
const { createRunUsageRecorder } = await vi.importActual<typeof import("../usage-receipts.js")>("../usage-receipts.js");
|
||||
const { accountRunCost } = await import("../run-cost-accounting.js");
|
||||
const { budgetService } = await import("../budgets.js");
|
||||
const { reserveRunBudget } = await import("../budget-reservations.js");
|
||||
const database = await startRecoveryPostgres("cursor-accounting-");
|
||||
const db = tables.createDb(database.connectionString);
|
||||
const directory = await mkdtemp(join(tmpdir(), "cursor-accounting-receipts-"));
|
||||
try {
|
||||
let scenarioIndex = 0;
|
||||
for (const scenario of ["complete-allow", "complete-block", "question-allow", "question-block", "missing", "foreign-turn", "unproven", "capture-failed", "replaced"]) {
|
||||
const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), issueId = randomUUID(), contractId = randomUUID();
|
||||
const policy = scenario.endsWith("block") ? "block" : "allow";
|
||||
const proven = !["missing", "foreign-turn", "unproven"].includes(scenario);
|
||||
const ready = proven && !["capture-failed", "replaced"].includes(scenario);
|
||||
await db.insert(tables.companies).values({ id: companyId, name: "Cursor accounting", issuePrefix: `CA${String.fromCharCode(65 + scenarioIndex++)}` });
|
||||
await db.insert(tables.agents).values({ id: agentId, companyId, name: "Cloud", adapterType: "paperclip_runner", status: "active" });
|
||||
await db.insert(tables.issues).values({ id: issueId, companyId, title: "Cloud accounting", status: "in_progress", assigneeAgentId: agentId });
|
||||
await db.insert(tables.completionContracts).values({ id: contractId, companyId, issueId, revision: 1, schemaVersion: "paperclip.completion-contract.v1",
|
||||
policyVersion: "v1", risk: "low", completionAuthority: "agent", incompleteCriteriaPolicy: "block", contractJson: {},
|
||||
canonicalSha256: "a".repeat(64), createdByActorType: "user", createdByActorId: "fixture" });
|
||||
await db.insert(tables.heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId,
|
||||
completionContractId: contractId, status: "running", runtimeMode: "native", costAccountingPending: true,
|
||||
usageJson: scenario === "capture-failed" ? { accountingCaptureFailed: true } : {} });
|
||||
await db.insert(tables.budgetPolicies).values(["company", "agent"].map(scopeType => ({ companyId,
|
||||
scopeType, scopeId: scopeType === "company" ? companyId : agentId, metric: "billed_cents", windowKind: "calendar_month_utc",
|
||||
amount: 1000, hardStopEnabled: true, isActive: true, unpricedUsagePolicy: policy })));
|
||||
const recorder = await createRunUsageRecorder(db, { companyId, runId, adapterType: "paperclip_runner" }, join(directory, runId));
|
||||
if (scenario === "replaced") await createRunUsageRecorder(db, { companyId, runId, adapterType: "paperclip_runner" }, join(directory, `${runId}-replacement`));
|
||||
const current = { ...execution, binding: { ...execution.binding, companyId, agentId, runId, issueId },
|
||||
provider: { kind: "cursor_cloud", model: "explicit-cloud-model", cursorCloud: {
|
||||
schema: "paperclip.cursor-cloud.config.v1", repos: [{ url: "https://github.com/acme/fixture" }],
|
||||
} } } as NativeExecutionInput;
|
||||
const turnId = `cloud-${scenario}`;
|
||||
state.execute.mockReset().mockImplementationOnce(async () => {
|
||||
if (scenario !== "missing") await accountingEvents.committed!({
|
||||
eventType: scenario.startsWith("complete") ? "turn.completed" : "turn.interrupted", turnId: scenario === "foreign-turn" ? "prior-cloud-turn" : turnId,
|
||||
payload: { error: null, status: scenario.startsWith("complete") ? "completed" : "interrupted",
|
||||
...(scenario === "unproven" ? { providerTerminalObserved: false } : {}) },
|
||||
} as unknown as PrpEvent);
|
||||
return { result: { summary: scenario.startsWith("question") ? "Waiting for an answer" : "Cloud finished" },
|
||||
terminal: { runTerminalState: "succeeded" }, turnId, normalizedSessionId: current.session.normalizedSessionId,
|
||||
providerSessionId: "cloud-agent", driverKind: "cursor_cloud_api", driverVersion: "cursor-cloud-v1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
const checkpoints: AdapterUsageCheckpoint[] = [];
|
||||
const result = await executePaperclipNativeSession({ db: leaseDb(current), execution: current,
|
||||
runnerInstanceId: `cloud-${scenario}`, onUsage: async checkpoint => { checkpoints.push(checkpoint); await recorder.capture(checkpoint); } });
|
||||
await recorder.complete(result);
|
||||
expect(result.usageComplete, scenario).toBe(proven);
|
||||
expect(checkpoints.every(checkpoint => checkpoint.usage === undefined && checkpoint.costUsd === null && checkpoint.costStatus === "unpriced"), scenario).toBe(true);
|
||||
const [before] = await db.select().from(tables.heartbeatRuns).where(eq(tables.heartbeatRuns.id, runId));
|
||||
expect(before.usageJson?.accountingReceiptReady, scenario).toBe(ready);
|
||||
const [nativeResult] = await db.insert(tables.nativeRunResults).values({ companyId, issueId, runId, completionContractId: contractId,
|
||||
serverFingerprint: scenario, schemaStatus: "accepted", resultJson: {}, canonicalSha256: "b".repeat(64) }).returning();
|
||||
await db.insert(tables.nativeRunFinalizations).values({ companyId, issueId, runId, phase: "committed", resultId: nativeResult.id });
|
||||
await db.update(tables.heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(),
|
||||
resultJson: scenario.startsWith("question") ? { runLiveness: { outcome: "governed_response_waiting" } } : {} }).where(eq(tables.heartbeatRuns.id, runId));
|
||||
expect(await accountRunCost(db, runId, {}, new Map()), scenario).toBe(ready);
|
||||
const [settled] = await db.select().from(tables.heartbeatRuns).where(eq(tables.heartbeatRuns.id, runId));
|
||||
expect(settled.costAccountingPending, scenario).toBe(!ready);
|
||||
const ledger = await db.select().from(tables.costEvents).where(eq(tables.costEvents.heartbeatRunId, runId));
|
||||
expect(ledger, scenario).toHaveLength(ready ? 1 : 0);
|
||||
if (ready) expect(ledger[0], scenario).toMatchObject({ costStatus: "unpriced", billingType: "unknown" });
|
||||
const block = await budgetService(db).getInvocationBlock(companyId, agentId);
|
||||
if (ready && policy === "allow") {
|
||||
expect(block, scenario).toBeNull();
|
||||
const nextRun = randomUUID();
|
||||
await db.insert(tables.heartbeatRuns).values({ id: nextRun, companyId, agentId, status: "queued", runtimeMode: "native" });
|
||||
await expect(reserveRunBudget(db, companyId, nextRun, null)).resolves.toMatchObject({ reused: false });
|
||||
} else expect(block, scenario).not.toBeNull();
|
||||
}
|
||||
} finally { await db.$client.end(); await database.cleanup(); await rm(directory, { recursive: true, force: true }); }
|
||||
}, 90_000);
|
||||
|
||||
it.each([false, true])("prices only complete direct Claude API turn accounting (%s)", async complete => {
|
||||
const { rehydrateRunnerdUsageNotification } = await import("@paperclipai/paperclip-runner/live");
|
||||
const { priceAnthropicReceipt } = await import("../anthropic-pricing.js");
|
||||
@@ -12595,6 +12739,229 @@ describe("runnerd provider runtime wiring", () => {
|
||||
await rm(isolatedStateDirectory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
function cursorCloudExecution(suffix: string): NativeExecutionInput {
|
||||
const current = scopedNativeExecution(`cursor-cloud-${suffix}`);
|
||||
return { ...current, schema: "paperclip.native-execution-input.v5",
|
||||
executionMode: "default", planningContext: null, runtimeContext: nativeRuntimeContextFixture(),
|
||||
provider: { kind: "cursor_cloud", model: "explicit-cloud-model", cursorCloud: {
|
||||
schema: "paperclip.cursor-cloud.config.v1", repos: [{ url: "https://github.com/acme/fixture", startingRef: "test-ref" }], timeoutMs: 60_000,
|
||||
} }, session: { ...current.session, driverKind: "cursor_cloud_api" } };
|
||||
}
|
||||
|
||||
function cursorCloudOrigin(): void {
|
||||
const prior = process.env.PAPERCLIP_PUBLIC_URL;
|
||||
process.env.PAPERCLIP_PUBLIC_URL = "https://cursor-relay.example.test";
|
||||
onTestFinished(() => { if (prior === undefined) delete process.env.PAPERCLIP_PUBLIC_URL; else process.env.PAPERCLIP_PUBLIC_URL = prior; });
|
||||
}
|
||||
|
||||
function cloudRelayProbe(current: NativeExecutionInput, environment: NodeJS.ProcessEnv) {
|
||||
return forwardRemoteMcpRequest({ runId: current.binding.runId,
|
||||
authorization: `Bearer ${environment.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN}`,
|
||||
body: { jsonrpc: "2.0", id: 1, method: "tools/list" } });
|
||||
}
|
||||
|
||||
function cursorCloudTransportOptions(): RunnerTransportOptions {
|
||||
state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!();
|
||||
const options = state.createTransport.mock.calls.at(-1)![0];
|
||||
onTestFinished(() => rm(dirname(options.environment!.PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH!), { recursive: true, force: true }));
|
||||
return options;
|
||||
}
|
||||
|
||||
async function cursorCloudTestDriver(current: NativeExecutionInput, environment: NodeJS.ProcessEnv, client?: unknown) {
|
||||
const sourceUrl = new URL("../../../../packages/paperclip-runner/src/drivers/cursor-cloud/cursor-cloud-driver.ts", import.meta.url);
|
||||
const { CursorCloudDriver } = await import(sourceUrl.href);
|
||||
const { binding, ...config } = JSON.parse(await readFile(environment.PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH!, "utf8"));
|
||||
return new CursorCloudDriver({ model: "explicit-cloud-model", config, binding, environment,
|
||||
runtimeDirectory: dirname(environment.PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH!), instructions: "Controlled replacement test.",
|
||||
relay: { url: environment.PAPERCLIP_CURSOR_CLOUD_RELAY_URL!, token: environment.PAPERCLIP_CURSOR_CLOUD_RELAY_TOKEN!,
|
||||
socketPath: environment.PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH!, expiresAt: Number(environment.PAPERCLIP_CURSOR_CLOUD_RELAY_EXPIRES_AT) },
|
||||
dynamicToolHandler: async () => { throw new Error("Unexpected tool call"); }, client: client as never });
|
||||
}
|
||||
|
||||
it("passes the verified listener endpoint to Core API tools", async () => {
|
||||
const previous = Object.fromEntries(["PAPERCLIP_API_URL", "PAPERCLIP_LISTEN_HOST", "PAPERCLIP_LISTEN_PORT", "PORT"]
|
||||
.map(key => [key, process.env[key]]));
|
||||
try {
|
||||
process.env.PAPERCLIP_API_URL = "https://callback-only.example.test";
|
||||
process.env.PAPERCLIP_LISTEN_HOST = "127.0.0.1";
|
||||
process.env.PAPERCLIP_LISTEN_PORT = "43219";
|
||||
process.env.PORT = "3100";
|
||||
state.localRuntimeApiUrl.mockReturnValueOnce("http://127.0.0.2:43229");
|
||||
const current = scopedNativeExecution("private-api-origin");
|
||||
state.createBackend.mockReturnValueOnce({ kind: "test", openSession: vi.fn() } as never);
|
||||
await createRunnerdBackend({ db: leaseDb(current), execution: current, runnerInstanceId: "private-api-controller" });
|
||||
expect(state.localRuntimeApiUrl).toHaveBeenCalled();
|
||||
expect(state.toolAuthorityDefinitions).toHaveBeenLastCalledWith(expect.objectContaining({ apiUrl: "http://127.0.0.2:43229" }));
|
||||
expect(process.env.PAPERCLIP_API_URL).toBe("https://callback-only.example.test");
|
||||
} finally {
|
||||
for (const [key, value] of Object.entries(previous)) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
[undefined, "43219"], ["127.0.0.1", undefined], ["127.0.0.1", "0"], ["127.0.0.1", "invalid"],
|
||||
])("does not fall back to an advertised API without a verified listener (%s:%s)", async (host, port) => {
|
||||
const previous = Object.fromEntries(["PAPERCLIP_API_URL", "PAPERCLIP_LISTEN_HOST", "PAPERCLIP_LISTEN_PORT"]
|
||||
.map(key => [key, process.env[key]]));
|
||||
try {
|
||||
process.env.PAPERCLIP_API_URL = "http://embedded-controller.example.test";
|
||||
if (host === undefined) delete process.env.PAPERCLIP_LISTEN_HOST;
|
||||
else process.env.PAPERCLIP_LISTEN_HOST = host;
|
||||
if (port === undefined) delete process.env.PAPERCLIP_LISTEN_PORT;
|
||||
else process.env.PAPERCLIP_LISTEN_PORT = port;
|
||||
state.localRuntimeApiUrl.mockImplementationOnce(() => { throw new Error("local_runtime_api_listener_unavailable"); });
|
||||
const current = scopedNativeExecution(`embedded-api-origin-${host}-${port}`);
|
||||
const previousBackends = state.createBackend.mock.calls.length;
|
||||
const previousDefinitions = state.toolAuthorityDefinitions.mock.calls.length;
|
||||
await expect(createRunnerdBackend({ db: leaseDb(current), execution: current, runnerInstanceId: "embedded-api-controller" }))
|
||||
.rejects.toThrow("local_runtime_api_listener_unavailable");
|
||||
expect(state.createBackend).toHaveBeenCalledTimes(previousBackends);
|
||||
expect(state.toolAuthorityDefinitions).toHaveBeenCalledTimes(previousDefinitions);
|
||||
expect(process.env.PAPERCLIP_API_URL).toBe("http://embedded-controller.example.test");
|
||||
} finally {
|
||||
for (const [key, value] of Object.entries(previous)) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("wires Cursor Cloud to the native facade with selected credentials and a separate artifact root", async () => {
|
||||
cursorCloudOrigin();
|
||||
const current = cursorCloudExecution("selected-transport");
|
||||
state.createBackend.mockReturnValueOnce({ kind: "test", openSession: vi.fn() } as never);
|
||||
await createRunnerdBackend({ db: leaseDb(current), execution: current, runnerInstanceId: "cursor-controller",
|
||||
runnerEnvironment: { CURSOR_API_KEY: "selected-company-cursor-key", OPENAI_API_KEY: "other-provider-secret", PRIVATE_HOST_VALUE: "private" } });
|
||||
const options = cursorCloudTransportOptions();
|
||||
expect(options).toMatchObject({ provider: "cursor_cloud", cursorCloud: current.provider.kind === "cursor_cloud" ? current.provider.cursorCloud : undefined });
|
||||
expect(options.lifecyclePolicy).toEqual({ mode: "per_turn", idleTimeoutMs: null });
|
||||
expect(options.adoptExistingRunner).toBeUndefined();
|
||||
const projected = createCapabilityRunnerdProviderEnvironment({ provider: "cursor_cloud", options: options as never,
|
||||
identity: options.prpIdentity as never,
|
||||
codexHome: "/unused", runtimeContextPath: "/private/runtime-context.json", hasRuntimeContext: true });
|
||||
expect(projected).toEqual({ CURSOR_API_KEY: "selected-company-cursor-key", PAPERCLIP_RUNNER_INSTANCE_ID: "cursor-controller",
|
||||
PAPERCLIP_RUN_ID: current.binding.runId, PAPERCLIP_NORMALIZED_SESSION_ID: current.session.normalizedSessionId,
|
||||
PAPERCLIP_NATIVE_RUNTIME_CONTEXT_PATH: "/private/runtime-context.json",
|
||||
...Object.fromEntries(Object.entries(options.environment!).filter(([key]) => key.startsWith("PAPERCLIP_CURSOR_CLOUD_"))),
|
||||
});
|
||||
expect(projected).not.toHaveProperty("OPENAI_API_KEY");
|
||||
expect(projected).not.toHaveProperty("PRIVATE_HOST_VALUE");
|
||||
const artifactRoot = projected.PAPERCLIP_CURSOR_CLOUD_ARTIFACT_ROOT!;
|
||||
expect(state.toolAuthorityDefinitions).toHaveBeenLastCalledWith(expect.objectContaining({ workspaceRoot: artifactRoot }));
|
||||
expect(artifactRoot).not.toBe(current.workspace.cwd);
|
||||
const config = JSON.parse(await readFile(projected.PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH!, "utf8"));
|
||||
expect(config).toMatchObject({ repos: [{ url: "https://github.com/acme/fixture", startingRef: "test-ref" }], binding: {
|
||||
companyId: current.binding.companyId, agentId: current.binding.agentId, issueId: current.binding.issueId,
|
||||
normalizedSessionId: current.session.normalizedSessionId,
|
||||
} });
|
||||
expect(JSON.stringify(config)).not.toContain("selected-company-cursor-key");
|
||||
expect((await cloudRelayProbe(current, projected)).status).toBe(401);
|
||||
expect(resolveNativeProviderEnvironment(current.provider, undefined, { CURSOR_API_KEY: "ambient-key" })).toEqual({});
|
||||
});
|
||||
|
||||
it.each(["settled", "active", "foreign", "unacknowledged", "live-owner"] as const)("archives the settled Cloud checkpoint before a real fresh-session replacement: %s", async mode => {
|
||||
cursorCloudOrigin();
|
||||
const current = cursorCloudExecution("fresh-replacement");
|
||||
let driver: Awaited<ReturnType<typeof cursorCloudTestDriver>>;
|
||||
const openSession = vi.fn(async () => driver.openSession({ runId: current.binding.runId,
|
||||
normalizedSessionId: current.session.normalizedSessionId!, workingDirectory: current.workspace.cwd! }));
|
||||
state.createBackend.mockReturnValueOnce({ kind: "test", openSession } as never);
|
||||
const backend = await createRunnerdBackend({ db: leaseDb(current), execution: current,
|
||||
runnerInstanceId: "cursor-replacement-controller", runnerEnvironment: { CURSOR_API_KEY: "synthetic-cursor-key" } });
|
||||
const environment = cursorCloudTransportOptions().environment!;
|
||||
const runtimeDirectory = dirname(environment.PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH!);
|
||||
const root = dirname(runtimeDirectory);
|
||||
const native = { id: "run-11111111-1111-4111-8111-111111111111", agentId: "", status: mode === "active" ? "RUNNING" : "ERROR",
|
||||
createdAt: "2026-10-29T00:00:00Z", updatedAt: "2026-10-29T00:00:00Z" };
|
||||
const createAgent = vi.fn(async (input: { agentId: string }) => { native.agentId = input.agentId; return { run: { ...native } }; });
|
||||
driver = await cursorCloudTestDriver(current, environment, { createAgent, getRun: async () => ({ ...native }), streamRun: async function* () {} });
|
||||
const prior = await driver.openSession({ runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!, workingDirectory: current.workspace.cwd! });
|
||||
await prior.startTurn({ message: { role: "user", text: "Fail the controlled turn." } });
|
||||
await vi.waitFor(async () => expect((await prior.read()).phase).toBe(mode === "active" ? "running" : "terminal"));
|
||||
if (mode !== "active" && mode !== "unacknowledged") await prior.acknowledgeTerminalDelivery((await prior.read()).pendingTerminalDelivery as { turnId: string; receiptId: string });
|
||||
const snapshot = await prior.snapshot();
|
||||
if (mode === "active") await prior.detachControllerForRestart!();
|
||||
else await prior.close({ reason: "confirmed failed terminal" });
|
||||
const liveOwner = mode === "live-owner" ? (await driver.recoverSession(snapshot)).session! : null;
|
||||
const checkpointName = (await readdir(runtimeDirectory)).find(name => /^checkpoint-.*\.json$/.test(name))!;
|
||||
const checkpoint = await readFile(join(runtimeDirectory, checkpointName), "utf8");
|
||||
const configBytes = await readFile(environment.PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH!, "utf8");
|
||||
const capability = await readFile(join(runtimeDirectory, "relay-capability.json"), "utf8");
|
||||
await writeFile(join(environment.PAPERCLIP_CURSOR_CLOUD_ARTIFACT_ROOT!, "keep.txt"), "Retained artifact");
|
||||
for (const name of ["runner", "control-plane"]) { await mkdir(join(root, name), { recursive: true, mode: 0o700 }); await writeFile(join(root, name, "retained.txt"), name); }
|
||||
const replacementInput = { identity: { ...current.binding, sessionId: current.session.normalizedSessionId }, workingDirectory: current.workspace.cwd };
|
||||
const previous = { backendKind: "test", driverKind: "cursor_cloud_api", sessionId: current.session.normalizedSessionId,
|
||||
identity: { ...current.binding, sessionId: current.session.normalizedSessionId, ...(mode === "foreign" ? { companyId: "foreign-company" } : {}) },
|
||||
providerSessionId: current.session.normalizedSessionId, activeTurnId: null, pendingRuntimeRequests: [], terminal: { runTerminalState: "failed" }, semanticResult: null };
|
||||
if (mode !== "settled") {
|
||||
try {
|
||||
await expect(backend.openReplacementSession!(replacementInput as never, previous as never)).rejects.toThrow();
|
||||
expect(openSession).not.toHaveBeenCalled(); expect(createAgent).toHaveBeenCalledOnce();
|
||||
expect(await readFile(join(runtimeDirectory, checkpointName), "utf8")).toBe(checkpoint);
|
||||
for (const name of ["runner", "control-plane"]) expect(await readFile(join(root, name, "retained.txt"), "utf8")).toBe(name);
|
||||
expect((await cloudRelayProbe(current, environment)).status).toBe(401);
|
||||
} finally { await liveOwner?.close({ reason: "replacement refusal test complete" }); }
|
||||
return;
|
||||
}
|
||||
const replaced = await backend.openReplacementSession!(replacementInput as never, previous as never);
|
||||
try {
|
||||
expect(openSession).toHaveBeenCalledOnce();
|
||||
expect(createAgent).toHaveBeenCalledOnce();
|
||||
expect(JSON.parse(await readFile(join(runtimeDirectory, checkpointName), "utf8"))).toMatchObject({ phase: "idle", agentId: null, runId: null });
|
||||
const archives = await readdir(join(root, "continuity-breaks")); expect(archives).toHaveLength(1);
|
||||
expect(await readFile(join(root, "continuity-breaks", archives[0]!, "cursor-cloud", checkpointName), "utf8")).toBe(checkpoint);
|
||||
expect(await readFile(environment.PAPERCLIP_CURSOR_CLOUD_CONFIG_PATH!, "utf8")).toBe(configBytes);
|
||||
expect(await readFile(join(runtimeDirectory, "relay-capability.json"), "utf8")).toBe(capability);
|
||||
expect(await readFile(join(environment.PAPERCLIP_CURSOR_CLOUD_ARTIFACT_ROOT!, "keep.txt"), "utf8")).toBe("Retained artifact");
|
||||
} finally { await replaced.close({ reason: "replacement test complete" }); }
|
||||
});
|
||||
|
||||
it.each(["open-failed", "replacement-failed", "recover-failed", "recover-missing", "close", "cancel", "detach"] as const)(
|
||||
"revokes Cursor Cloud relay admission after %s and admits an exact retry", async ending => {
|
||||
cursorCloudOrigin();
|
||||
const current = cursorCloudExecution(ending);
|
||||
const rawSession = { close: vi.fn(async () => undefined), cancel: vi.fn(() => ({ cleanup: Promise.resolve() })),
|
||||
detachControllerForRestart: vi.fn(async () => undefined) };
|
||||
let environment: NodeJS.ProcessEnv;
|
||||
let openingFailed = false;
|
||||
const admitted = async () => {
|
||||
expect((await cloudRelayProbe(current, environment)).status).toBe(503);
|
||||
};
|
||||
state.createBackend.mockReturnValueOnce({ kind: "test",
|
||||
openSession: async () => { await admitted(); if ((ending === "open-failed" || ending === "replacement-failed") && !openingFailed) { openingFailed = true; throw new Error("cloud-open-fixture-failed"); } return rawSession; },
|
||||
recoverSession: async () => { await admitted(); if (ending === "recover-failed") throw new Error("cloud-recover-fixture-failed");
|
||||
return ending === "recover-missing" ? { recovered: false, reason: "fixture checkpoint missing" } : { recovered: true, session: rawSession }; },
|
||||
} as never);
|
||||
const backend = await createRunnerdBackend({ db: leaseDb(current), execution: current,
|
||||
runnerInstanceId: "cursor-controller", runnerEnvironment: { CURSOR_API_KEY: "selected-company-cursor-key" } });
|
||||
environment = cursorCloudTransportOptions().environment!;
|
||||
expect((await cloudRelayProbe(current, environment)).status).toBe(401);
|
||||
if (ending === "open-failed") await expect(backend.openSession({} as never)).rejects.toThrow("cloud-open-fixture-failed");
|
||||
else if (ending === "replacement-failed") {
|
||||
const driver = await cursorCloudTestDriver(current, environment);
|
||||
const prior = await driver.openSession({ runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!, workingDirectory: current.workspace.cwd! });
|
||||
await prior.close({ reason: "pristine replacement fixture" });
|
||||
await expect(backend.openReplacementSession!({} as never, { sessionId: current.session.normalizedSessionId,
|
||||
identity: { ...current.binding, sessionId: current.session.normalizedSessionId } } as never)).rejects.toThrow("cloud-open-fixture-failed");
|
||||
}
|
||||
else if (ending === "recover-failed") await expect(backend.recoverSession!({} as never, { signal: new AbortController().signal })).rejects.toThrow("cloud-recover-fixture-failed");
|
||||
else if (ending === "recover-missing") expect(await backend.recoverSession!({} as never, { signal: new AbortController().signal })).toMatchObject({ recovered: false });
|
||||
else {
|
||||
const session = await backend.openSession({} as never);
|
||||
if (ending === "close") await session.close({ reason: "fixture close" });
|
||||
else if (ending === "cancel") await session.cancel!({ reason: "fixture cancel", signal: new AbortController().signal }).cleanup;
|
||||
else await session.detachControllerForRestart!();
|
||||
}
|
||||
expect((await cloudRelayProbe(current, environment)).status).toBe(401);
|
||||
const resumed = await backend.openSession({} as never);
|
||||
try { expect((await cloudRelayProbe(current, environment)).status).toBe(503); }
|
||||
finally { await resumed.close({ reason: "fixture retry complete" }); }
|
||||
},
|
||||
);
|
||||
|
||||
it.each((["codex", "claude"] as const).flatMap(provider => (["unchanged", "external-checkpoint", "changed", "runtime-context", "retirement-failed", "stale-owner", "active-owner", "missing-owner", "foreign-environment", "plugin-replaced", "plugin-managed-github"] as const).filter(scenario => provider === "codex" || scenario.startsWith("plugin-")).map(scenario => [provider, scenario] as const)))("rotates an owned warm %s remote runner before checking changed configuration: %s", async (provider, scenario) => {
|
||||
const plugin = scenario === "plugin-replaced" || scenario === "plugin-managed-github";
|
||||
const reusable = ["unchanged", "external-checkpoint", "plugin-managed-github"].includes(scenario);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { prepareCursorCloudRuntime } from "./cursor-cloud-runtime.js";
|
||||
import { resolveLocalRuntimeApiUrl } from "../../runtime-api.js";
|
||||
import { providerFailureFromError } from "../../vendor/paperclip-runner/index.js";
|
||||
import { nativeCancellationHasUnsettledOwner, notifyNativeCancellation, waitForNativeCancellation } from "./native-cancellation-delivery.js";
|
||||
import { readClaimedNativeStopRecovery } from "./native-cancellation-request.js";
|
||||
@@ -950,6 +952,7 @@ export function resolveNativeProviderEnvironment(
|
||||
if (provider.kind === "acpx" && ["pi", "cursor", "copilot", "kimi", "antigravity"].includes(provider.agent)) {
|
||||
return buildNativeProviderEnvironment({}, host);
|
||||
}
|
||||
if (provider.kind === "cursor_cloud") return {};
|
||||
return host;
|
||||
}
|
||||
|
||||
@@ -8375,6 +8378,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
identityRedactor.chunk("diagnostic", text) + identityRedactor.finish("diagnostic"),
|
||||
);
|
||||
if (
|
||||
input.execution.provider.kind !== "cursor_cloud" &&
|
||||
input.execution.provider.kind !== "codex" &&
|
||||
input.execution.provider.kind !== "opencode" &&
|
||||
input.execution.provider.kind !== "claude_managed" &&
|
||||
@@ -8891,16 +8895,33 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
let observedAccountingUsage: Record<string, unknown> | null = null;
|
||||
let observedAccountingTurn: string | undefined;
|
||||
let nativeAccountingComplete = false;
|
||||
const cursorCloudAccounting = input.execution.provider.kind === "cursor_cloud" ? new Map<string, boolean>() : null;
|
||||
const observeCursorCloudAccounting = (event: PrpEvent): boolean | undefined => {
|
||||
if (!cursorCloudAccounting || !event?.turnId) return;
|
||||
if (event.eventType === "turn.started") {
|
||||
cursorCloudAccounting.delete(event.turnId);
|
||||
return false;
|
||||
}
|
||||
if (["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"].includes(event.eventType)) {
|
||||
const complete = record(event.payload).providerTerminalObserved !== false;
|
||||
cursorCloudAccounting.set(event.turnId, complete);
|
||||
return complete;
|
||||
}
|
||||
};
|
||||
// OpenCode and ACPX report their current turn; Codex reports a cumulative run delta.
|
||||
// Rebuild per-turn state from the durable event log when a controller resumes.
|
||||
const turnAccounting = ["opencode", "acpx"].includes(input.execution.provider.kind) ? createNativeTurnAccounting(input.execution.provider) : null;
|
||||
if (turnAccounting) {
|
||||
if (turnAccounting || cursorCloudAccounting) {
|
||||
const history = await input.db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and(
|
||||
eq(heartbeatRunEvents.companyId, input.execution.binding.companyId), eq(heartbeatRunEvents.runId, input.execution.binding.runId),
|
||||
or(sql`${heartbeatRunEvents.payload}->'prpEvent'->'payload'->>'kind' = 'usage'`,
|
||||
inArray(heartbeatRunEvents.eventType, ["turn.started", "turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"])),
|
||||
)).orderBy(heartbeatRunEvents.seq);
|
||||
for (const row of history) turnAccounting.observe(record(row.payload).prpEvent as PrpEvent);
|
||||
for (const row of history) {
|
||||
const event = record(row.payload).prpEvent as PrpEvent;
|
||||
if (turnAccounting) turnAccounting.observe(event);
|
||||
else observeCursorCloudAccounting(event);
|
||||
}
|
||||
}
|
||||
let fallbackUsageRecorder: ReturnType<typeof createRunUsageRecorder> | undefined;
|
||||
const producerOwnsUsage = usesNativeUsageDelivery({ runnerd: input.useRunnerd === true,
|
||||
@@ -8912,14 +8933,14 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
}) : undefined;
|
||||
const persistAccountingUsage = async (usage: Record<string, unknown> | null, complete: boolean) => {
|
||||
if (producerOwnsUsage) return;
|
||||
const accountingUsage = normalizeNativeUsage(usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" });
|
||||
const accountingUsage = input.execution.provider.kind === "cursor_cloud" ? undefined : normalizeNativeUsage(usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" });
|
||||
const accountingCost = accountingUsage ? nativeUsageCostUsd(usage, input.execution.provider) : undefined;
|
||||
complete = complete && accountingUsage !== undefined;
|
||||
const costStatus = complete && usage?.accountingCostIncomplete !== true
|
||||
complete = complete && (cursorCloudAccounting !== null || accountingUsage !== undefined);
|
||||
const costStatus = cursorCloudAccounting !== null ? "unpriced" as const : complete && usage?.accountingCostIncomplete !== true
|
||||
? input.execution.provider.kind === "aws_agentcore" ? "estimated" as const : undefined
|
||||
: "unpriced" as const;
|
||||
const billing = resolveNativeBilling(input.execution.provider, input.runnerEnvironment, input.billingIdentity);
|
||||
const costUsdExact = typeof usage?.accountingCostUsdExact === "string" ? usage.accountingCostUsdExact : undefined;
|
||||
const costUsdExact = input.execution.provider.kind !== "cursor_cloud" && typeof usage?.accountingCostUsdExact === "string" ? usage.accountingCostUsdExact : undefined;
|
||||
const checkpoint: AdapterUsageCheckpoint = { usage: accountingUsage, ...billing, complete, usageBasis: "per_run", costUsdExact,
|
||||
model: input.execution.provider.model ?? "unknown", costUsd: accountingCost ?? null, costStatus };
|
||||
if (input.onUsage) await input.onUsage(checkpoint);
|
||||
@@ -8932,6 +8953,11 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
// appendEvent awaits this receipt before the runtime may commit completeRun.
|
||||
// Replayed events must rebuild it too after a stop between event and receipt.
|
||||
const observeAccountingEvent = async (event: PrpEvent) => {
|
||||
if (cursorCloudAccounting) {
|
||||
const complete = observeCursorCloudAccounting(event);
|
||||
if (complete !== undefined) await persistAccountingUsage(null, complete);
|
||||
return;
|
||||
}
|
||||
if (turnAccounting) {
|
||||
if (!turnAccounting.observe(event)) return;
|
||||
const snapshot = turnAccounting.snapshot();
|
||||
@@ -10018,7 +10044,8 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
// session.usage() may be an attachment baseline, a partial report, or a
|
||||
// cumulative session total. Use the observed run delta, and require its
|
||||
// turn to match the terminal result before certifying it as complete.
|
||||
if (turnAccounting) {
|
||||
if (cursorCloudAccounting) nativeAccountingComplete = native.turnId !== null && cursorCloudAccounting.get(native.turnId) === true;
|
||||
else if (turnAccounting) {
|
||||
const snapshot = turnAccounting.finish(native.turnId);
|
||||
observedAccountingUsage = snapshot.usage;
|
||||
nativeAccountingComplete = snapshot.complete && snapshot.turnId === native.turnId;
|
||||
@@ -10694,6 +10721,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
nativeResult: native.result as unknown as Record<string, unknown>,
|
||||
nativeTerminal: native.terminal as unknown as Record<string, unknown>,
|
||||
...((input.execution.schema === "paperclip.native-execution-input.v6" || input.execution.schema === "paperclip.native-execution-input.v8") ? { providerAccounting: { usage: null, cost: null, externallyBilled: true }, externalStopConfirmed: false } : {}),
|
||||
...(input.execution.provider.kind === "cursor_cloud" ? { providerAccounting: { usage: null, cost: null, externallyBilled: true } } : {}),
|
||||
...(providerFailure ? { nativeProviderFailure: providerFailure.diagnostic } : {}),
|
||||
...(unclassifiedTurnFailure ? { nativeTurnFailure: unclassifiedTurnFailure } : {}),
|
||||
...(providerExplanation ? { providerFailure: providerExplanation } : {}),
|
||||
@@ -10705,11 +10733,11 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
sessionDisplayId: native.providerSessionId ?? native.normalizedSessionId,
|
||||
...resolveNativeBilling(input.execution.provider, input.runnerEnvironment, input.billingIdentity),
|
||||
model: input.execution.provider.model,
|
||||
usage: normalizeNativeUsage(native.usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" }),
|
||||
usage: input.execution.provider.kind === "cursor_cloud" ? undefined : normalizeNativeUsage(native.usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" }),
|
||||
costUsd: input.execution.schema !== "paperclip.native-execution-input.v6" && input.execution.schema !== "paperclip.native-execution-input.v8" && normalizeNativeUsage(native.usage, { inputIncludesCacheReads: input.execution.provider.kind === "codex" })
|
||||
? nativeUsageCostUsd(native.usage, input.execution.provider) ?? null : null,
|
||||
costUsdExact: typeof native.usage?.accountingCostUsdExact === "string" ? native.usage.accountingCostUsdExact : undefined,
|
||||
costStatus: nativeAccountingComplete && native.usage?.accountingCostIncomplete !== true
|
||||
costUsdExact: input.execution.provider.kind !== "cursor_cloud" && typeof native.usage?.accountingCostUsdExact === "string" ? native.usage.accountingCostUsdExact : undefined,
|
||||
costStatus: input.execution.provider.kind !== "cursor_cloud" && nativeAccountingComplete && native.usage?.accountingCostIncomplete !== true
|
||||
? input.execution.provider.kind === "aws_agentcore" ? "estimated" : undefined
|
||||
: "unpriced",
|
||||
usageComplete: nativeAccountingComplete,
|
||||
@@ -10731,6 +10759,7 @@ async function executePaperclipNativeSessionWithinScope(
|
||||
/** Billing identity follows the selected runtime and resolved credentials.
|
||||
* Unknown authentication remains unknown; a provider name does not prove billing mode. */
|
||||
export function resolveNativeBilling(provider: NativeExecutionInput["provider"], env: NodeJS.ProcessEnv = {}, identity?: Pick<AdapterExecutionResult, "provider" | "biller" | "billingType">): Pick<AdapterExecutionResult, "provider" | "biller" | "billingType"> {
|
||||
if (provider.kind === "cursor_cloud") return { provider: "cursor", biller: "cursor", billingType: "unknown" };
|
||||
if (provider.kind === "grok_bot") return { provider: "grok_bot", biller: "unknown", billingType: "unknown" };
|
||||
if (identity) return identity.provider === "openai" && identity.billingType === "metered_api"
|
||||
? { ...identity, biller: inferOpenAiCompatibleBiller(env, identity.biller ?? "unknown") }
|
||||
@@ -12630,6 +12659,8 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
let recoveryPending = retainedTransition !== undefined;
|
||||
const target = input.runnerExecutionTarget ?? { kind: "local" as const };
|
||||
const remoteTarget = target.kind === "remote" ? target : null;
|
||||
const cloudArtifactRoot = input.execution.provider.kind === "cursor_cloud" ? join(runnerdStateRoot(input.execution), "cursor-cloud", "artifacts") : undefined;
|
||||
if (input.execution.provider.kind === "cursor_cloud" && remoteTarget) throw new Error("cursor_cloud_local_controller_required");
|
||||
const rawPluginTask = remoteTarget?.transport === "sandbox" ? remoteTarget.runnerTask : undefined;
|
||||
const pluginTask = rawPluginTask && input.executionContext ? (operation: unknown) => {
|
||||
const startupOperation = ["describe", "prepare", "check_project_auth", "connection"].includes(String(record(operation).kind));
|
||||
@@ -12672,7 +12703,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
// Codex and OpenCode send dynamic tool calls over authenticated PRP. Keep
|
||||
// the assigned gateway on the control plane instead of asking the sandbox to
|
||||
// reach the host's HTTP origin (which may be private or loopback-only).
|
||||
const relayAssignedMcp = Boolean(pluginTask) || input.execution.provider.kind === "opencode" || (remoteTarget !== null && input.execution.provider.kind === "codex") || input.execution.schema === "paperclip.native-execution-input.v6";
|
||||
const relayAssignedMcp = Boolean(pluginTask) || input.execution.provider.kind === "cursor_cloud" || input.execution.provider.kind === "opencode" || (remoteTarget !== null && input.execution.provider.kind === "codex") || input.execution.schema === "paperclip.native-execution-input.v6";
|
||||
const assignedMcpUrl = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_URL;
|
||||
const assignedMcpToken = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_TOKEN;
|
||||
const assignedMcpName = input.runnerEnvironment?.PAPERCLIP_NATIVE_MCP_NAME;
|
||||
@@ -12708,6 +12739,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
)).limit(1).then(rows => rows[0]) : undefined;
|
||||
input.executionContext?.signal.throwIfAborted();
|
||||
const authority = new PaperclipRunnerToolAuthority(input.db, {
|
||||
apiUrl: resolveLocalRuntimeApiUrl(),
|
||||
casesEnabled: input.casesEnabled === true,
|
||||
...(nativeReview ? { nativeReview } : {}),
|
||||
connectorAssignments,
|
||||
@@ -12731,7 +12763,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
externalAuthorizingUserId: input.execution.provider.kind === "muse"
|
||||
? await museRunnerBroker(input.db).authorizingUserIdForBinding(input.execution.provider.binding) : undefined,
|
||||
assertBridgeAuthority: input.execution.schema === "paperclip.native-execution-input.v6" || input.execution.schema === "paperclip.native-execution-input.v8" ? (database = input.db) => assertExternalNativeRunAuthority(input.db, input.execution, database) : undefined,
|
||||
workspaceRoot: input.dotWorkspaceRoot ?? remoteTarget?.remoteCwd ?? input.execution.workspace.cwd ?? undefined,
|
||||
workspaceRoot: cloudArtifactRoot ?? input.dotWorkspaceRoot ?? remoteTarget?.remoteCwd ?? input.execution.workspace.cwd ?? undefined,
|
||||
executionTargetKind: target.kind,
|
||||
installRemoteArtifact: !pluginTask && remoteTarget && remoteCommandRunner
|
||||
? createArtifactInstaller(remoteTarget.remoteCwd, remoteCommandRunner) : undefined,
|
||||
@@ -14108,6 +14140,10 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
}
|
||||
}
|
||||
if (preconfiguredHome) effectiveRunnerEnvironmentBase.PAPERCLIP_RUNNER_HOME_MODE = "preconfigured";
|
||||
const cursorCloudRuntime = input.execution.provider.kind === "cursor_cloud"
|
||||
? prepareCursorCloudRuntime({ db: input.db, execution: input.execution, root, environment: effectiveRunnerEnvironmentBase,
|
||||
authorityCurrent: () => sessionToolAuthorityEpochs.get(sessionScopeId) === authorityEpoch }) : null;
|
||||
if (cursorCloudRuntime) effectiveRunnerEnvironmentBase = cursorCloudRuntime.environment;
|
||||
const effectiveRunnerEnvironment: NodeJS.ProcessEnv = remoteRuntimeRoot
|
||||
? {
|
||||
...effectiveRunnerEnvironmentBase,
|
||||
@@ -14128,7 +14164,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
...effectiveRunnerEnvironmentBase,
|
||||
PAPERCLIP_WORKSPACE_CWD: input.execution.workspace.cwd,
|
||||
};
|
||||
const archiveContinuityState = async () => {
|
||||
const archiveContinuityState = async (previous?: PersistedNativeSession) => {
|
||||
if (hasRetainedWarmTransitionEvidence(root)) {
|
||||
throw new Error("native_runner_warm_transition_recovery_unproven");
|
||||
}
|
||||
@@ -14136,6 +14172,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
const archiveToken = `${archivedAt}-${randomUUID()}`;
|
||||
const archiveRoot = resolve(root, "continuity-breaks", archiveToken);
|
||||
mkdirSync(archiveRoot, { recursive: true, mode: 0o700 });
|
||||
await cursorCloudRuntime?.archiveCheckpoint(archiveRoot, previous);
|
||||
noteNativeRunnerEvidence(archivedAt);
|
||||
for (const name of [
|
||||
"control-plane",
|
||||
@@ -14294,7 +14331,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
event,
|
||||
}),
|
||||
provider:
|
||||
input.execution.provider.kind === "codex"
|
||||
input.execution.provider.kind === "cursor_cloud" ? "cursor_cloud" : input.execution.provider.kind === "codex"
|
||||
? "codex"
|
||||
: input.execution.provider.kind === "opencode"
|
||||
? "opencode"
|
||||
@@ -14339,6 +14376,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(input.execution.provider.kind === "cursor_cloud" ? { cursorCloud: input.execution.provider.cursorCloud } : {}),
|
||||
...(input.execution.provider.kind === "opencode"
|
||||
? {
|
||||
opencodePermissionMode: input.execution.provider.permissionMode,
|
||||
@@ -14597,6 +14635,15 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
});
|
||||
const boundManagedSessions = new WeakSet<NativeSession>();
|
||||
const wrapManagedSession = (session: NativeSession): NativeSession => {
|
||||
if (cursorCloudRuntime && !boundManagedSessions.has(session)) {
|
||||
boundManagedSessions.add(session);
|
||||
const close = session.close.bind(session);
|
||||
session.close = async (options) => { cursorCloudRuntime.unregister(); return close(options); };
|
||||
const cancel = session.cancel?.bind(session);
|
||||
if (cancel) session.cancel = (...args) => { cursorCloudRuntime.unregister(); return cancel(...args); };
|
||||
const detach = session.detachControllerForRestart?.bind(session);
|
||||
if (detach) session.detachControllerForRestart = async () => { cursorCloudRuntime.unregister(); return detach(); };
|
||||
}
|
||||
if (antigravityCredential?.home && antigravityCredential.credential && !boundManagedSessions.has(session)) {
|
||||
boundManagedSessions.add(session);
|
||||
const runtimeHome = resolve(resolvePaperclipInstanceRoot(), "runtime", "paperclip-runner", "acpx", "acpx",
|
||||
@@ -14701,28 +14748,38 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
},
|
||||
descriptor: () => backend.descriptor(),
|
||||
openSession: async (sessionInput) => {
|
||||
const session = await backend.openSession(sessionInput);
|
||||
const managed = wrapManagedSession(session);
|
||||
await recordAdmittedProviderPack(managed, sessionInput.identity, Boolean(adoptedProcess));
|
||||
return managed;
|
||||
cursorCloudRuntime?.register();
|
||||
try {
|
||||
const session = await backend.openSession(sessionInput);
|
||||
const managed = wrapManagedSession(session);
|
||||
await recordAdmittedProviderPack(managed, sessionInput.identity, Boolean(adoptedProcess));
|
||||
return managed;
|
||||
} catch (error) { cursorCloudRuntime?.unregister(); throw error; }
|
||||
},
|
||||
recoverSession: async (snapshot, options) => {
|
||||
const result = backend.recoverSession ? await backend.recoverSession(snapshot, options) : { recovered: false, reason: "driver does not support recovery" };
|
||||
const session = result.session ? wrapManagedSession(result.session) : undefined;
|
||||
if (result.recovered && session) await recordAdmittedProviderPack(session, snapshot.identity, Boolean(adoptedProcess));
|
||||
return session ? { ...result, session } : result;
|
||||
cursorCloudRuntime?.register({ cleanupOnly: true });
|
||||
try {
|
||||
const result = backend.recoverSession ? await backend.recoverSession(snapshot, options) : { recovered: false, reason: "driver does not support recovery" };
|
||||
const session = result.session ? wrapManagedSession(result.session) : undefined;
|
||||
if (result.recovered && session) await recordAdmittedProviderPack(session, snapshot.identity, Boolean(adoptedProcess));
|
||||
if (!result.recovered || !session) cursorCloudRuntime?.unregister();
|
||||
return session ? { ...result, session } : result;
|
||||
} catch (error) { cursorCloudRuntime?.unregister(); throw error; }
|
||||
},
|
||||
openReplacementSession: async (sessionInput) => {
|
||||
openReplacementSession: async (sessionInput, previous) => {
|
||||
await measureNativeRunnerSpan(
|
||||
input.trace,
|
||||
"provider.session.archive_before_replacement",
|
||||
archiveContinuityState,
|
||||
() => archiveContinuityState(previous),
|
||||
{ parentName: "native.session.execute" },
|
||||
);
|
||||
const session = await backend.openSession(sessionInput);
|
||||
const managed = wrapManagedSession(session);
|
||||
await recordAdmittedProviderPack(managed, sessionInput.identity, false);
|
||||
return managed;
|
||||
cursorCloudRuntime?.register();
|
||||
try {
|
||||
const session = await backend.openSession(sessionInput);
|
||||
const managed = wrapManagedSession(session);
|
||||
await recordAdmittedProviderPack(managed, sessionInput.identity, false);
|
||||
return managed;
|
||||
} catch (error) { cursorCloudRuntime?.unregister(); throw error; }
|
||||
},
|
||||
} satisfies ManagedRunnerdBackend;
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ describe("native turn accounting", () => {
|
||||
expect(usesNativeUsageDelivery({ runnerd: false, remote: true, provider })).toBe(false);
|
||||
expect(usesNativeUsageDelivery({ runnerd: true, remote: false, provider })).toBe(false);
|
||||
expect(usesNativeUsageDelivery({ runnerd: true, remote: true })).toBe(false);
|
||||
expect(usesNativeUsageDelivery({ runnerd: true, remote: true, provider: { kind: "cursor_cloud", model: "caller-model" } as never })).toBe(false);
|
||||
expect(usesNativeUsageDelivery({ runnerd: true, remote: true, provider: { kind: "muse", model: null } as never })).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ function nativeUsageMeasurement(usage: Record<string, unknown>) {
|
||||
}
|
||||
|
||||
export function nativeUsageBiller(provider: NativeExecutionInput["provider"]): string {
|
||||
if (provider.kind === "cursor_cloud") return "cursor";
|
||||
if (provider.kind === "acpx") {
|
||||
if (provider.agent === "cursor") return "cursor";
|
||||
if (provider.agent === "copilot") return "github";
|
||||
@@ -126,6 +127,7 @@ export function nativeUsageCostUsd(
|
||||
usage: Record<string, unknown> | null,
|
||||
provider?: NativeExecutionInput["provider"],
|
||||
) {
|
||||
if (provider?.kind === "cursor_cloud") return undefined;
|
||||
// The ACP normalization contract fills absent per-turn cost with zero and
|
||||
// reports actual cost cumulatively. Until it carries an authoritative run
|
||||
// delta with provenance, neither value is a candidate's billed USD receipt.
|
||||
|
||||
@@ -2,6 +2,8 @@ import * as connectorRuntime from "../connector-runtime.js";
|
||||
import * as cloudIdentity from "../cloud-runtime-identity.js";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createServer } from "node:http";
|
||||
import { createPaperclipHttpServer } from "../../http/server.js";
|
||||
import { LOW_TRUST_REVIEW_PRESET, upsertIssueDocumentSchema } from "@paperclipai/shared";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import {
|
||||
@@ -32,6 +34,7 @@ import { CURRENT_WAKE_COMMENTS_BINDING_SCHEMA, READ_CURRENT_WAKE_COMMENTS_TOOL_N
|
||||
import { NativeChatAttachmentReadScope, READ_CHAT_ATTACHMENT_TOOL_NAME } from "./chat-attachment-read.js";
|
||||
import { buildLowTrustSourceTrust, buildPromotedSourceTrust, LOW_TRUST_QUARANTINED_BODY } from "../source-trust.js";
|
||||
import { CAPABILITY_SEMANTIC_TOOL_CATALOG, runnerCodexDynamicToolsFit } from "../../vendor/paperclip-runner/index.js";
|
||||
import { resolveLocalRuntimeApiUrl } from "../../runtime-api.js";
|
||||
|
||||
describe("PaperclipRunnerToolAuthority", () => {
|
||||
const credentialDocumentBody = "Use a secret manager for credential handling.\nAuthorization: Bearer intentional-document-credential";
|
||||
@@ -101,6 +104,46 @@ describe("PaperclipRunnerToolAuthority", () => {
|
||||
await temporary?.cleanup();
|
||||
});
|
||||
|
||||
it("routes call_api through the private controller instead of the public callback origin", async () => {
|
||||
const privateRequests: Array<{ path: string | undefined; authenticated: boolean }> = [];
|
||||
const callbackRequests: string[] = [];
|
||||
const controller = createPaperclipHttpServer((request, response) => {
|
||||
privateRequests.push({ path: request.url, authenticated: /^Bearer /.test(request.headers.authorization ?? "") });
|
||||
response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ workProducts: [] }));
|
||||
}, { apiUrl: "https://advertised.example.test" });
|
||||
const callback = createServer((request, response) => {
|
||||
callbackRequests.push(request.url ?? "");
|
||||
response.writeHead(404).end();
|
||||
});
|
||||
await Promise.all([controller, callback].map(server => new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve))));
|
||||
try {
|
||||
const controllerAddress = controller.address();
|
||||
const callbackAddress = callback.address();
|
||||
if (!controllerAddress || typeof controllerAddress === "string" || !callbackAddress || typeof callbackAddress === "string") throw new Error("Expected owned TCP listeners");
|
||||
vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", "private-controller-test-secret");
|
||||
vi.stubEnv("PAPERCLIP_RUNNER_API_TOOLS_ENABLED", "true");
|
||||
vi.stubEnv("PAPERCLIP_API_URL", `http://127.0.0.1:${callbackAddress.port}`);
|
||||
vi.stubEnv("PAPERCLIP_AUTH_PUBLIC_BASE_URL", "https://callback-only.example.test");
|
||||
vi.stubEnv("PAPERCLIP_LISTEN_HOST", "127.0.0.1");
|
||||
vi.stubEnv("PAPERCLIP_LISTEN_PORT", String(controllerAddress.port));
|
||||
vi.stubEnv("PORT", "3100");
|
||||
const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId,
|
||||
apiUrl: resolveLocalRuntimeApiUrl() });
|
||||
const result = await authority.execute({ tool: "call_api", callId: "private-controller-read", arguments: {
|
||||
operationId: "GET /api/issues/{id}/work-products", pathParams: { id: issueId },
|
||||
} });
|
||||
expect(result).toMatchObject({ ok: true, status: 200 });
|
||||
expect(privateRequests).toEqual([{ path: `/api/issues/${issueId}/work-products`, authenticated: true }]);
|
||||
expect(callbackRequests).toEqual([]);
|
||||
expect(process.env.PAPERCLIP_API_URL).toBe(`http://127.0.0.1:${callbackAddress.port}`);
|
||||
} finally {
|
||||
await Promise.all([controller, callback].map(server => new Promise<void>((resolve, reject) => {
|
||||
server.closeAllConnections();
|
||||
server.close(error => error ? reject(error) : resolve());
|
||||
})));
|
||||
}
|
||||
});
|
||||
|
||||
it("registers pinned connector definitions without discovery and rejects revoked assignments at use", async () => {
|
||||
const connectorAssignments = connectorRuntime.connectorToolDefinitionsForSkills(new Set([
|
||||
"paperclipai/paperclip/slack", "paperclipai/paperclip/browser-use-cloud", "custom/agentmail",
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "../provider-profile-qualification.js";
|
||||
import { resolveAcpxQualification, resolveAntigravityCandidateAdmission, resolveKimiCandidateAdmission, type AcpxQualificationCandidate } from "./acpx-qualification.js";
|
||||
import { compatibleCodexModel } from "./codex-model-fallback.js";
|
||||
import { parseNativeCursorCloudConfig, type NativeCursorCloudConfig } from "../../vendor/paperclip-runner/index.js";
|
||||
|
||||
export const QUALIFIED_OPENCODE_RUNNER_VERSION = "1.18.34" as const;
|
||||
export const DEFAULT_OPENCODE_RUNNER_MODEL =
|
||||
@@ -42,6 +43,7 @@ export type QualifiedPaperclipRunnerAcpxAgent =
|
||||
type AdmittedPaperclipRunnerAcpxAgent = QualifiedPaperclipRunnerAcpxAgent | AcpxQualificationCandidate | "antigravity";
|
||||
|
||||
export type PaperclipRunnerProviderProfile =
|
||||
| { provider: "cursor_cloud"; backend: "cursor_cloud_api"; model: string }
|
||||
| { provider: "muse"; backend: "muse_external"; model: null; museBindingId: string }
|
||||
| { provider: "grok_bot"; backend: "grok_bot_mcp"; model: null; externalBindingId: string }
|
||||
| { provider: "openai_dot"; backend: "openai_dot_mcp"; model: null; dotBindingId: string }
|
||||
@@ -77,6 +79,7 @@ export type PaperclipRunnerProviderProfile =
|
||||
};
|
||||
|
||||
export type PaperclipRunnerNativeProviderInput =
|
||||
| { provider: "cursor_cloud"; model: string; cursorCloud: NativeCursorCloudConfig }
|
||||
| { provider: "muse"; model: null; museBinding: import("../../vendor/paperclip-runner/index.js").MuseBindingSnapshot }
|
||||
| { provider: "grok_bot"; model: null; dotBinding: import("../../vendor/paperclip-runner/index.js").DotBindingSnapshot }
|
||||
| { provider: "openai_dot"; model: null; dotBinding: import("../../vendor/paperclip-runner/index.js").DotBindingSnapshot }
|
||||
@@ -168,6 +171,39 @@ function optionalString(value: unknown): string | null {
|
||||
: null;
|
||||
}
|
||||
|
||||
export function resolvePaperclipRunnerCursorCloudConfig(config: Record<string, unknown>): NativeCursorCloudConfig {
|
||||
const unsupportedEnvironment = Object.keys(asRecord(config.env)).filter(key => key !== "CURSOR_API_KEY");
|
||||
if (unsupportedEnvironment.length) {
|
||||
throw new PaperclipRunnerProviderProfileError("paperclip_runner_cursor_cloud_config_invalid",
|
||||
`Cursor Cloud with Paperclip Runner only supports CURSOR_API_KEY in agent environment settings. Configure hosted secrets in your Cursor Cloud environment instead of ${unsupportedEnvironment.join(", ")}.`);
|
||||
}
|
||||
for (const [current, legacy] of [["cloudEnvType", "runtimeEnvType"], ["cloudEnvName", "runtimeEnvName"], ["repoRef", "repoStartingRef"], ["prUrl", "repoPullRequestUrl"]]) {
|
||||
if (config[current] !== undefined && config[legacy] !== undefined && config[current] !== config[legacy]) {
|
||||
throw new PaperclipRunnerProviderProfileError("paperclip_runner_cursor_cloud_config_invalid", `Choose one matching value for ${current} and ${legacy}.`);
|
||||
}
|
||||
}
|
||||
const unsupported = ["codexPermissionMode", "opencodePermissionMode", "acpxPermissionMode", "acpxSessionMode", "command", "extraArgs", "promptTemplate", "bootstrapPromptTemplate", "modelReasoningEffort", "reasoningEffort", "effort", "modelParams"]
|
||||
.filter(key => config[key] !== undefined && config[key] !== "" && !(Array.isArray(config[key]) && config[key].length === 0));
|
||||
if (config.lifecycleMode !== undefined && config.lifecycleMode !== "per_turn") unsupported.push("lifecycleMode");
|
||||
if (config.homeMode === "preconfigured") unsupported.push("homeMode");
|
||||
if (unsupported.length) throw new PaperclipRunnerProviderProfileError("paperclip_runner_cursor_cloud_config_invalid", `Cursor Cloud cannot honor these settings: ${unsupported.join(", ")}.`);
|
||||
const repoUrl = optionalString(config.repoUrl);
|
||||
const startingRef = optionalString(config.repoRef ?? config.repoStartingRef);
|
||||
const prUrl = optionalString(config.prUrl ?? config.repoPullRequestUrl);
|
||||
const envName = optionalString(config.cloudEnvName ?? config.runtimeEnvName);
|
||||
try {
|
||||
return parseNativeCursorCloudConfig({
|
||||
schema: "paperclip.cursor-cloud.config.v1",
|
||||
repos: repoUrl ? [{ url: repoUrl, ...(startingRef ? { startingRef } : {}), ...(prUrl ? { prUrl } : {}) }] : [],
|
||||
env: { type: config.cloudEnvType ?? config.runtimeEnvType ?? "cloud", ...(envName ? { name: envName } : {}) },
|
||||
...Object.fromEntries(["workOnCurrentBranch", "autoCreatePR", "skipReviewerRequest"].filter(key => config[key] !== undefined).map(key => [key, config[key]])),
|
||||
...(config.cursorCloudTimeoutMs !== undefined ? { timeoutMs: config.cursorCloudTimeoutMs } : {}),
|
||||
});
|
||||
} catch {
|
||||
throw new PaperclipRunnerProviderProfileError("paperclip_runner_cursor_cloud_config_invalid", "Cursor Cloud requires an HTTPS repository or named Cursor cloud environment, cloud-hosted execution, and supported settings. Its timeout must be between 1 second and 1 hour.");
|
||||
}
|
||||
}
|
||||
|
||||
/** Configuration can be saved before pairing; task admission requires a binding. */
|
||||
export function validatePaperclipRunnerDotConfig(config: Record<string, unknown>, requireBinding = true): string | null {
|
||||
const bindingId = optionalString(config.dotBindingId);
|
||||
@@ -201,9 +237,9 @@ export function validatePaperclipRunnerGrokConfig(config: Record<string, unknown
|
||||
return bindingId;
|
||||
}
|
||||
|
||||
/** A task may change a local Runner model (and Codex effort), but not provider identity. */
|
||||
/** A task may change a Runner model (and supported effort), but not provider identity. */
|
||||
export function projectPaperclipRunnerTaskConfig(
|
||||
backend: "codex_app_server" | "opencode_server" | "acpx_runtime",
|
||||
backend: "codex_app_server" | "opencode_server" | "acpx_runtime" | "cursor_cloud_api",
|
||||
agentConfig: unknown,
|
||||
taskOverrides: unknown,
|
||||
managedModel?: string,
|
||||
@@ -423,6 +459,13 @@ export function resolvePaperclipRunnerProviderProfile(
|
||||
);
|
||||
}
|
||||
|
||||
if (candidate === "cursor_cloud") {
|
||||
const model = optionalString(config.model);
|
||||
if (!model) throw new PaperclipRunnerProviderProfileError("paperclip_runner_cursor_cloud_model_required", "Cursor Cloud requires an explicit model. Select a model before testing or assigning work.");
|
||||
resolvePaperclipRunnerCursorCloudConfig(config);
|
||||
return { provider: "cursor_cloud", backend: "cursor_cloud_api", model };
|
||||
}
|
||||
|
||||
if (candidate === "muse") {
|
||||
const bindingId = validatePaperclipRunnerMuseConfig(config)!;
|
||||
return { provider: "muse", backend: "muse_external", model: null, museBindingId: bindingId };
|
||||
@@ -666,6 +709,9 @@ export function resolvePaperclipRunnerNativeProviderInput(input: {
|
||||
"Paperclip Runner provider changed after this run selected its native backend.",
|
||||
);
|
||||
}
|
||||
if (profile.provider === "cursor_cloud") {
|
||||
return { provider: "cursor_cloud", model: profile.model, cursorCloud: resolvePaperclipRunnerCursorCloudConfig(config) };
|
||||
}
|
||||
if (profile.provider === "muse") {
|
||||
if (!input.museBinding || input.museBinding.bindingId !== profile.museBindingId) throw new PaperclipRunnerProviderProfileError("paperclip_runner_muse_binding_unavailable", "Muse binding must be resolved by the server after normal admission.");
|
||||
return { provider: "muse", model: null, museBinding: input.museBinding };
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { ClientRequest, createServer } from "node:http";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import type { Socket } from "node:net";
|
||||
import { join } from "node:path";
|
||||
import { RUNNER_TOOL_SCOPE_TOKEN_HEADER } from "../../vendor/paperclip-runner/index.js";
|
||||
import { createRemoteMcpRelayToken, forwardRemoteMcpRequest, registerRemoteMcpRelay, remoteMcpRelayUrl } from "./remote-mcp-relay.js";
|
||||
|
||||
const cleanup: Array<() => void | Promise<void>> = [];
|
||||
afterEach(async () => { for (const dispose of cleanup.splice(0).reverse()) await dispose(); });
|
||||
|
||||
describe("native remote MCP relay", () => {
|
||||
it("forwards authenticated bytes to the owned socket and revokes after release", async () => {
|
||||
const root = await mkdtemp("/tmp/pc-relay-");
|
||||
cleanup.push(() => rm(root, { recursive: true, force: true }));
|
||||
const socketPath = join(root, "mcp.sock");
|
||||
const token = createRemoteMcpRelayToken();
|
||||
let calls = 0;
|
||||
const scopeAuthorization = `Bearer ${createRemoteMcpRelayToken()}`;
|
||||
const observedScopeHeaders: Array<string | string[] | undefined> = [];
|
||||
const server = createServer((req, res) => {
|
||||
expect(req.headers.authorization).toBe(`Bearer ${token}`);
|
||||
expect(req.url).toBe("/mcp");
|
||||
observedScopeHeaders.push(req.headers[RUNNER_TOOL_SCOPE_TOKEN_HEADER]);
|
||||
const chunks: Buffer[] = [];
|
||||
req.on("data", chunk => chunks.push(chunk));
|
||||
req.on("end", () => { calls++; res.setHeader("content-type", "application/json"); res.end(JSON.stringify({ jsonrpc: "2.0", id: JSON.parse(Buffer.concat(chunks).toString()).id, result: { accepted: true } })); });
|
||||
});
|
||||
await new Promise<void>(resolve => server.listen(socketPath, resolve));
|
||||
cleanup.push(() => new Promise<void>(resolve => server.close(() => resolve())));
|
||||
let active = true;
|
||||
const release = registerRemoteMcpRelay({ runId: "run", socketPath, token, expiresAt: Date.now() + 60_000, authorized: async () => active });
|
||||
cleanup.push(release);
|
||||
const body = { jsonrpc: "2.0", id: 0, method: "tools/call", params: { name: "paperclip_finish", arguments: {} } };
|
||||
const invoke = (authorization = `Bearer ${token}`) => forwardRemoteMcpRequest({ runId: "run", authorization, scopeAuthorization, body });
|
||||
expect((await invoke("Bearer forged")).status).toBe(401);
|
||||
const response = await invoke();
|
||||
expect(response.status).toBe(200);
|
||||
expect(observedScopeHeaders).toEqual([scopeAuthorization]);
|
||||
expect(JSON.parse(response.body.toString())).toEqual({ jsonrpc: "2.0", id: 0, result: { accepted: true } });
|
||||
active = false;
|
||||
expect((await invoke()).status).toBe(403);
|
||||
release();
|
||||
expect((await invoke()).status).toBe(401);
|
||||
expect(calls).toBe(1);
|
||||
});
|
||||
|
||||
it("rejects expired/cross-run credentials, duplicate owners and oversized bodies", async () => {
|
||||
const token = createRemoteMcpRelayToken();
|
||||
cleanup.push(registerRemoteMcpRelay({ runId: "expired", socketPath: "/tmp/unused.sock", token, expiresAt: Date.now() - 1, authorized: async () => true }));
|
||||
expect((await forwardRemoteMcpRequest({ runId: "expired", authorization: `Bearer ${token}`, body: {} })).status).toBe(401);
|
||||
expect((await forwardRemoteMcpRequest({ runId: "other-run", authorization: `Bearer ${token}`, body: {} })).status).toBe(401);
|
||||
const binding = { runId: "bound", socketPath: "/tmp/unused.sock", token, expiresAt: Date.now() + 60_000, authorized: async () => true };
|
||||
cleanup.push(registerRemoteMcpRelay(binding));
|
||||
expect(() => registerRemoteMcpRelay(binding)).toThrow("already_registered");
|
||||
expect((await forwardRemoteMcpRequest({ runId: "bound", authorization: `Bearer ${token}`, body: "x".repeat(1_048_576) })).status).toBe(413);
|
||||
});
|
||||
|
||||
it.each([false, true])("settles a timed-out Unix upstream once and closes its socket (headers sent: %s)", async headersSent => {
|
||||
const root = await mkdtemp("/tmp/pc-relay-timeout-");
|
||||
cleanup.push(() => rm(root, { recursive: true, force: true }));
|
||||
const socketPath = join(root, "mcp.sock");
|
||||
const sockets = new Set<Socket>();
|
||||
let calls = 0;
|
||||
let closed = 0;
|
||||
const server = createServer((req, res) => {
|
||||
calls++;
|
||||
req.resume();
|
||||
if (headersSent) res.write("partial response");
|
||||
});
|
||||
server.on("connection", socket => {
|
||||
sockets.add(socket);
|
||||
socket.on("close", () => { sockets.delete(socket); closed++; });
|
||||
});
|
||||
await new Promise<void>(resolve => server.listen(socketPath, resolve));
|
||||
cleanup.push(() => new Promise<void>(resolve => server.close(() => resolve())));
|
||||
cleanup.push(() => { for (const socket of sockets) socket.destroy(); });
|
||||
const token = createRemoteMcpRelayToken();
|
||||
cleanup.push(registerRemoteMcpRelay({ runId: "timeout", socketPath, token, expiresAt: Date.now() + 60_000, authorized: async () => true }));
|
||||
const originalSetTimeout = ClientRequest.prototype.setTimeout;
|
||||
const timeout = vi.spyOn(ClientRequest.prototype, "setTimeout").mockImplementation(function (this: ClientRequest, milliseconds, callback) {
|
||||
expect(milliseconds).toBe(120_000);
|
||||
return originalSetTimeout.call(this, 25, callback);
|
||||
});
|
||||
cleanup.push(() => { timeout.mockRestore(); });
|
||||
let settled = 0;
|
||||
const result = forwardRemoteMcpRequest({ runId: "timeout", authorization: `Bearer ${token}`, body: {} }).then(response => { settled++; return response; });
|
||||
expect(await result).toEqual({ status: headersSent ? 502 : 503, body: Buffer.alloc(0) });
|
||||
await vi.waitFor(() => expect(closed).toBe(1));
|
||||
expect(calls).toBe(1);
|
||||
expect(settled).toBe(1);
|
||||
expect(sockets.size).toBe(0);
|
||||
});
|
||||
|
||||
it("uses configured HTTPS only, with no authority from inbound hosts", () => {
|
||||
expect(remoteMcpRelayUrl("https://relay.example", "run/1")).toBe("https://relay.example/mcp/native-runs/run%2F1");
|
||||
for (const origin of ["http://localhost:3100", "https://user:pass@example.test", "https://example.test/path", "https://example.test/?token=secret"]) expect(() => remoteMcpRelayUrl(origin, "run")).toThrow("public_url_required");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { request } from "node:http";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { RUNNER_TOOL_SCOPE_TOKEN_HEADER } from "../../vendor/paperclip-runner/index.js";
|
||||
|
||||
export interface RemoteMcpRelayBinding {
|
||||
runId: string;
|
||||
socketPath: string;
|
||||
token: string;
|
||||
expiresAt: number;
|
||||
authorized(): Promise<boolean>;
|
||||
}
|
||||
|
||||
const bindings = new Map<string, RemoteMcpRelayBinding>();
|
||||
const digest = (value: string) => createHash("sha256").update(value).digest();
|
||||
const MAX_BODY = 1024 * 1024;
|
||||
const MAX_RESULT = 4 * 1024 * 1024;
|
||||
|
||||
export function registerRemoteMcpRelay(binding: RemoteMcpRelayBinding): () => void {
|
||||
if (!isAbsolute(binding.socketPath) || binding.token.length < 32 || !Number.isFinite(binding.expiresAt)) {
|
||||
throw new Error("native_mcp_relay_invalid_binding");
|
||||
}
|
||||
if (bindings.has(binding.runId)) throw new Error("native_mcp_relay_already_registered");
|
||||
bindings.set(binding.runId, binding);
|
||||
return () => { if (bindings.get(binding.runId) === binding) bindings.delete(binding.runId); };
|
||||
}
|
||||
|
||||
export function createRemoteMcpRelayToken(): string {
|
||||
return randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
export function remoteMcpRelayUrl(origin: string, runId: string): string {
|
||||
const url = new URL(origin);
|
||||
if (url.protocol !== "https:" || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
|
||||
throw new Error("cursor_cloud_public_url_required: configure PAPERCLIP_PUBLIC_URL with a reachable HTTPS origin");
|
||||
}
|
||||
return `${url.origin}/mcp/native-runs/${encodeURIComponent(runId)}`;
|
||||
}
|
||||
|
||||
export async function forwardRemoteMcpRequest(input: {
|
||||
runId: string;
|
||||
authorization: string | undefined;
|
||||
scopeAuthorization?: string;
|
||||
body: unknown;
|
||||
mcpSessionId?: string;
|
||||
}): Promise<{ status: number; body: Buffer; mcpSessionId?: string }> {
|
||||
const binding = bindings.get(input.runId);
|
||||
const supplied = input.authorization?.match(/^Bearer ([^\s]+)$/)?.[1];
|
||||
if (!binding || !supplied || !timingSafeEqual(digest(supplied), digest(binding.token)) || binding.expiresAt <= Date.now()) {
|
||||
return { status: 401, body: Buffer.alloc(0) };
|
||||
}
|
||||
if (!await binding.authorized() || bindings.get(input.runId) !== binding) {
|
||||
return { status: 403, body: Buffer.alloc(0) };
|
||||
}
|
||||
const body = Buffer.from(JSON.stringify(input.body ?? null));
|
||||
if (body.length > MAX_BODY) return { status: 413, body: Buffer.alloc(0) };
|
||||
return new Promise(resolve => {
|
||||
const upstream = request({ socketPath: binding.socketPath, path: "/mcp", method: "POST", headers: {
|
||||
"content-type": "application/json", accept: "application/json", authorization: `Bearer ${binding.token}`,
|
||||
"content-length": body.length,
|
||||
...(input.mcpSessionId ? { "mcp-session-id": input.mcpSessionId } : {}),
|
||||
...(input.scopeAuthorization ? { [RUNNER_TOOL_SCOPE_TOKEN_HEADER]: input.scopeAuthorization } : {}),
|
||||
} }, response => {
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
response.on("data", (chunk: Buffer) => {
|
||||
size += chunk.length;
|
||||
if (size > MAX_RESULT) { upstream.destroy(); resolve({ status: 502, body: Buffer.alloc(0) }); }
|
||||
else chunks.push(chunk);
|
||||
});
|
||||
response.on("end", () => resolve({ status: response.statusCode ?? 502, body: Buffer.concat(chunks), ...(typeof response.headers["mcp-session-id"] === "string" ? { mcpSessionId: response.headers["mcp-session-id"] } : {}) }));
|
||||
response.on("error", () => resolve({ status: 502, body: Buffer.alloc(0) }));
|
||||
});
|
||||
upstream.setTimeout(120_000, () => upstream.destroy());
|
||||
upstream.on("error", () => resolve({ status: 503, body: Buffer.alloc(0) }));
|
||||
upstream.end(body);
|
||||
});
|
||||
}
|
||||
@@ -236,6 +236,9 @@ describeEmbeddedPostgres("hidden runner PRP coordinator", () => {
|
||||
it("registers only an exact Codex native binding and exposes read-only tools", async () => {
|
||||
const seed = await seedNativeRun();
|
||||
const server = createServer();
|
||||
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Expected a bound TCP controller");
|
||||
setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3213" });
|
||||
const stateRoot = mkdtempSync(resolve(tmpdir(), "paperclip-runner-state-"));
|
||||
scratchDirectories.push(stateRoot);
|
||||
@@ -263,7 +266,7 @@ describeEmbeddedPostgres("hidden runner PRP coordinator", () => {
|
||||
});
|
||||
|
||||
expect(prepared.connectUrl).toBe(
|
||||
`ws://127.0.0.1:3213/api/runner/v1/connect/${seed.runId}`,
|
||||
`ws://127.0.0.1:${address.port}/api/runner/v1/connect/${seed.runId}`,
|
||||
);
|
||||
expect(prepared.bootstrapTicket).toMatch(/^bootstrap_/);
|
||||
expect(prepared.semanticTools.map((tool) => tool.name)).toEqual([
|
||||
@@ -297,7 +300,7 @@ describeEmbeddedPostgres("hidden runner PRP coordinator", () => {
|
||||
runId: seed.runId,
|
||||
}),
|
||||
).toBe(false);
|
||||
server.close();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
it("rechecks task ownership and returns semantic receipts", async () => {
|
||||
|
||||
@@ -21,6 +21,13 @@ const eligible = {
|
||||
} as const;
|
||||
|
||||
describe("resolveNativeRuntimeMode", () => {
|
||||
it("requires experimental opt-in and a local controller for Cursor Cloud while retaining its backend on recovery", () => {
|
||||
const adapterConfig = { provider: "cursor_cloud", model: "caller-model", repoUrl: "https://github.com/acme/repo" };
|
||||
expect(resolveNativeRuntimeMode({ ...eligible, adapterConfig })).toMatchObject({ kind: "native", profile: { backend: "cursor_cloud_api" } });
|
||||
expect(() => resolveNativeRuntimeMode({ ...eligible, enabled: false, adapterConfig })).toThrow(expect.objectContaining({ code: "paperclip_runner_rollout_disabled" }));
|
||||
expect(() => resolveNativeRuntimeMode({ ...eligible, adapterConfig, target: { kind: "remote" } })).toThrow(expect.objectContaining({ code: "paperclip_runner_cursor_cloud_local_controller_required" }));
|
||||
expect(resolveHeartbeatNativeRuntimeMode({ ...eligible, enabled: false, adapterConfig, persisted: { runtimeMode: "native", runtimeModeReason: "eligible_opt_in", runtimeModeResolvedAt: new Date(), driverKind: "cursor_cloud_api" } })).toMatchObject({ kind: "native", profile: { backend: "cursor_cloud_api" } });
|
||||
});
|
||||
it("keeps every direct built-in adapter outside native arbitration", () => {
|
||||
for (const adapterType of BUILTIN_ADAPTER_TYPES) {
|
||||
if (adapterType === "paperclip_runner") continue;
|
||||
|
||||
@@ -53,7 +53,8 @@ export type NativeRuntimeResolution =
|
||||
| "acpx_runtime"
|
||||
| "openai_dot_mcp"
|
||||
| "grok_bot_mcp"
|
||||
| "muse_external";
|
||||
| "muse_external"
|
||||
| "cursor_cloud_api";
|
||||
protocolVersion: 1;
|
||||
};
|
||||
authorityDecision: NativeStatusDecision;
|
||||
@@ -156,6 +157,9 @@ export function resolveNativeRuntimeMode(input: {
|
||||
"Paperclip Runner requires an active agent.",
|
||||
);
|
||||
}
|
||||
if (runnerProfile.provider === "cursor_cloud" && (input.target?.kind ?? "local") !== "local") {
|
||||
throw ineligible("paperclip_runner_cursor_cloud_local_controller_required", "Cursor Cloud currently requires a local Paperclip controller. Cursor hosts its execution environment.");
|
||||
}
|
||||
const allowedWorkModes = ["standard", "planning", "ask", "skill_test"];
|
||||
if (!input.issue || !allowedWorkModes.includes(input.issue.workMode)) {
|
||||
throw ineligible(
|
||||
@@ -268,6 +272,7 @@ export function resolveHeartbeatRuntimeMode(input: {
|
||||
: resolution.profile.backend === "muse_external" ? "muse"
|
||||
: resolution.profile.backend === "grok_bot_mcp" ? "grok_bot"
|
||||
: resolution.profile.backend === "openai_dot_mcp" ? "openai_dot"
|
||||
: resolution.profile.backend === "cursor_cloud_api" ? "cursor_cloud"
|
||||
: resolution.profile.backend === "acpx_runtime"
|
||||
? "acpx"
|
||||
: "codex",
|
||||
@@ -324,6 +329,7 @@ export function resolveHeartbeatNativeRuntimeMode(input: {
|
||||
: driverKind === "muse_external" ? "muse_external"
|
||||
: driverKind === "grok_bot_mcp" ? "grok_bot_mcp"
|
||||
: driverKind === "openai_dot_mcp" ? "openai_dot_mcp"
|
||||
: driverKind === "cursor_cloud_api" ? "cursor_cloud_api"
|
||||
: driverKind === "acpx_runtime"
|
||||
? "acpx_runtime"
|
||||
: driverKind === null
|
||||
|
||||
Reference in new issue
Block a user