mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-06 23:20:53 +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
@@ -1107,6 +1107,33 @@ describe("agent routes adapter validation", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("saves and reopens an explicit native Cursor Cloud setup without Codex defaults", async () => {
|
||||
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableNativeRunner: true });
|
||||
let existing = { ...(await mockAgentService.getById()), adapterType: "cursor_cloud", adapterConfig: {},
|
||||
status: "paused", lifecycleState: "paused", pauseReason: "setup", lifecycleHolds: ["setup"] };
|
||||
mockAgentService.getById.mockImplementation(async () => existing);
|
||||
mockAgentService.update.mockImplementation(async (_id, patch) => { existing = { ...existing, ...patch }; return existing; });
|
||||
const config = { model: "caller-model", repoUrl: "https://github.com/acme/repo", repoStartingRef: "feature",
|
||||
env: { CURSOR_API_KEY: { type: "secret_ref", secretId: "22222222-2222-4222-8222-222222222222", version: "latest" } } };
|
||||
const app = await createApp();
|
||||
const saved = await requestApp(app, baseUrl => request(baseUrl).patch(`/api/agents/${existing.id}`)
|
||||
.send({ adapterType: "cursor_cloud", runner: "paperclip", adapterConfig: config }));
|
||||
expect(saved.status, JSON.stringify(saved.body)).toBe(200);
|
||||
expect(saved.body).toMatchObject({ adapterType: "paperclip_runner", adapterConfig: {
|
||||
provider: "cursor_cloud", model: config.model, repoUrl: config.repoUrl, repoRef: "feature", env: config.env, lifecycleMode: "per_turn",
|
||||
} });
|
||||
expect(saved.body.adapterConfig).not.toHaveProperty("codexPermissionMode");
|
||||
const reopened = await requestApp(app, baseUrl => request(baseUrl).get(`/api/agents/${existing.id}/configuration`));
|
||||
expect(reopened.status, JSON.stringify(reopened.body)).toBe(200);
|
||||
expect(reopened.body.adapterConfig).toEqual(saved.body.adapterConfig);
|
||||
const resaved = await requestApp(app, baseUrl => request(baseUrl).patch(`/api/agents/${existing.id}`)
|
||||
.send({ adapterType: "paperclip_runner", runner: "paperclip", adapterConfig: reopened.body.adapterConfig }));
|
||||
expect(resaved.status, JSON.stringify(resaved.body)).toBe(200);
|
||||
const { resolvePaperclipRunnerNativeProviderInput } = await import("../services/native-runtime/provider-profile.js");
|
||||
expect(resolvePaperclipRunnerNativeProviderInput({ backend: "cursor_cloud_api", adapterConfig: resaved.body.adapterConfig }))
|
||||
.toMatchObject({ provider: "cursor_cloud", model: config.model, cursorCloud: { repos: [{ url: config.repoUrl, startingRef: "feature" }] } });
|
||||
});
|
||||
|
||||
it.each(["dotAttachmentAccess", "dotWorkspaceAccess", "dotBindingId", "homeMode"])("refuses an agent granting itself the operator-owned setting %s", async key => {
|
||||
const app = await createApp({ type: "agent", agentId: "11111111-1111-4111-8111-111111111111", companyId: "company-1", source: "agent_jwt" });
|
||||
const response = await requestApp(app, baseUrl => request(baseUrl).patch("/api/agents/11111111-1111-4111-8111-111111111111").send({ adapterConfig: { [key]: key === "homeMode" ? "preconfigured" : key === "dotBindingId" ? "another-binding" : true } }));
|
||||
|
||||
@@ -49,4 +49,35 @@ describe("saved harness verification", () => {
|
||||
] as const)("accepts %s with %j", (status, codes) => {
|
||||
expect(() => assertHarnessTestPassed(result(status, [...codes]))).not.toThrow();
|
||||
});
|
||||
|
||||
const cloudAccountResult = (modelListed = true): AdapterEnvironmentTestResult => ({
|
||||
adapterType: "paperclip_runner", status: "warn", testedAt: new Date().toISOString(),
|
||||
checks: [
|
||||
{ code: "cursor_cloud_account_ready", level: "info", message: "The bound key can read its catalog. No prompt was sent." },
|
||||
{ code: modelListed ? "cursor_cloud_model_listed" : "cursor_cloud_model_unlisted", level: modelListed ? "info" : "warn", message: "Exact model availability is decided by Cursor." },
|
||||
{ code: "cursor_cloud_model_identity_unverified", level: "warn", message: "Cursor does not acknowledge the effective model." },
|
||||
],
|
||||
});
|
||||
|
||||
it.each([true, false])("admits an authenticated experimental Cloud account with model listed=%s", modelListed => {
|
||||
expect(() => assertHarnessTestPassed(cloudAccountResult(modelListed))).not.toThrow();
|
||||
});
|
||||
|
||||
it("keeps an unverified Cloud warning blocked without an informational account receipt", () => {
|
||||
const unverified = cloudAccountResult();
|
||||
unverified.checks[0].level = "warn";
|
||||
expect(() => assertHarnessTestPassed(unverified)).toThrow("The harness test failed");
|
||||
});
|
||||
|
||||
it("does not accept the Cloud receipt from an unrelated adapter", () => {
|
||||
const unrelated = { ...cloudAccountResult(), adapterType: "test" };
|
||||
expect(() => assertHarnessTestPassed(unrelated)).toThrow("The harness test failed");
|
||||
});
|
||||
|
||||
it.each(["fail", "warn"] as const)("keeps a %s authentication failure blocked despite a Cloud account receipt", status => {
|
||||
const failed = cloudAccountResult();
|
||||
failed.status = status;
|
||||
failed.checks.push({ code: ADAPTER_AUTH_MISSING_CHECK_CODE, level: "error", message: "Authentication required" });
|
||||
expect(() => assertHarnessTestPassed(failed)).toThrow("The harness test failed");
|
||||
});
|
||||
});
|
||||
@@ -16407,6 +16407,25 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
runtimeGeneration: Number(oldWindow.generation) + 1 } as typeof endpoint.setup }).where(eq(chatEndpoints.id, endpoint.id));
|
||||
};
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } });
|
||||
let pauseRearm = false;
|
||||
let rearmEntered = false;
|
||||
let releaseRearm!: () => void;
|
||||
const rearmMayFinish = new Promise<void>(resolve => { releaseRearm = resolve; });
|
||||
const register = coordinator.register.bind(coordinator);
|
||||
const registration = vi.spyOn(coordinator, "register").mockImplementation((queue, task) => register(queue, {
|
||||
...task,
|
||||
hasPending: async () => {
|
||||
const pending = await task.hasPending();
|
||||
if (pauseRearm) {
|
||||
const window = (await f.checkpoint()).value as Record<string, unknown>;
|
||||
if (window.generation === Number(oldWindow.generation) + 1 && window.outcome === "epoch_initialized") {
|
||||
rearmEntered = true;
|
||||
await rearmMayFinish;
|
||||
}
|
||||
}
|
||||
return pending;
|
||||
},
|
||||
}));
|
||||
let release!: () => void;
|
||||
let pending: Promise<unknown> | undefined;
|
||||
try {
|
||||
@@ -16420,16 +16439,21 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
await held;
|
||||
expect((await f.checkpoint()).version).toBe(old.version);
|
||||
expect(f.requests).toEqual([]);
|
||||
release(); await pending;
|
||||
pauseRearm = true; release(); await pending;
|
||||
await expect.poll(async () => (await f.checkpoint()).value, { timeout: 5000 }).toMatchObject({
|
||||
generation: Number(oldWindow.generation) + 1, outcome: "epoch_initialized" });
|
||||
await expect.poll(() => rearmEntered, { timeout: 5000 }).toBe(true);
|
||||
expect(f.requests).toEqual([]);
|
||||
// The checkpoint commits before this coordinator pass rearms its deadline.
|
||||
expect(coordinator.nextWakeAt()).toBeNull();
|
||||
expect(idleWorkSnapshot().active).toBeGreaterThan(0);
|
||||
pauseRearm = false;
|
||||
releaseRearm();
|
||||
await expect.poll(() => {
|
||||
const next = coordinator.nextWakeAt();
|
||||
return next !== null && next < Date.now() + 90_000;
|
||||
}, { timeout: 5000 }).toBe(true);
|
||||
} finally { release?.(); await pending; await coordinator.stop(); }
|
||||
return { active: idleWorkSnapshot().active, bounded: next !== null && next < Date.now() + 90_000 };
|
||||
}, { timeout: 5000 }).toEqual({ active: 0, bounded: true });
|
||||
expect(f.requests).toEqual([]);
|
||||
} finally { releaseRearm(); release?.(); await pending; await coordinator.stop(); registration.mockRestore(); }
|
||||
});
|
||||
|
||||
it("preempts a future GitHub recovery window when only credential references change", async () => {
|
||||
|
||||
@@ -491,6 +491,26 @@ describe("HTTP logger redaction", () => {
|
||||
expect(log.res.headers["set-cookie"]).toBe("[Redacted]");
|
||||
});
|
||||
|
||||
it.each([200, 401, 403, 500])("redacts Runner tool scope credentials from HTTP %i logs", async status => {
|
||||
const capability = "runner-tool-scope-capability-canary";
|
||||
const chunks: string[] = [];
|
||||
const stream = new Writable({ write(chunk, _encoding, callback) { chunks.push(chunk.toString()); callback(); } });
|
||||
const app = express();
|
||||
app.use(createHttpLogger(pino({ redact: [...HTTP_LOG_REDACT_PATHS] }, stream)));
|
||||
const path = "/mcp/native-runs/00000000-0000-4000-8000-000000000762";
|
||||
app.post(path, (_req, res) => { res.status(status).json({ status }); });
|
||||
|
||||
await request(app).post(path)
|
||||
.set("X-Paperclip-Runner-Scope-Token", "Bearer " + capability)
|
||||
.send({}).expect(status);
|
||||
|
||||
expect(chunks.join("")).not.toContain(capability);
|
||||
const log = JSON.parse(chunks.join("").trim());
|
||||
expect(log.req.headers["x-paperclip-runner-scope-token"]).toBe("[Redacted]");
|
||||
expect(log.req.url).toBe(path);
|
||||
expect(log.res.statusCode).toBe(status);
|
||||
});
|
||||
|
||||
it.each([200, 403, 500])("redacts runtime GitHub capabilities from HTTP %i logs", async (status) => {
|
||||
const capability = "runtime-github-capability-canary";
|
||||
const chunks: string[] = [];
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import express from "express";
|
||||
import express, { type Request, type Response } from "express";
|
||||
import request from "supertest";
|
||||
import { privateHostnameGuard } from "../middleware/private-hostname-guard.js";
|
||||
|
||||
@@ -24,6 +24,47 @@ function createApp(opts: { enabled: boolean; allowedHostnames?: string[]; bindHo
|
||||
}
|
||||
|
||||
describe("privateHostnameGuard", () => {
|
||||
it.each([
|
||||
["IPv6 loopback", "[::1]:3100"],
|
||||
["mapped loopback", "[::ffff:7f00:1]:3100"],
|
||||
])("preserves %s admission", async (_name, host) => {
|
||||
expect((await request(createApp({ enabled: true })).get("/api/health").set("Host", host)).status).toBe(200);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: "same IPv4 socket", expected: 200 },
|
||||
{ name: "loopback caller", remote: "127.0.0.2", expected: 200 },
|
||||
{ name: "mapped socket forms", local: "::ffff:203.0.113.5", remote: "::ffff:127.0.0.1", expected: 200 },
|
||||
{ name: "mapped Host", host: "[::ffff:cb00:7105]:3100", expected: 200 },
|
||||
{ name: "IPv6 compression", host: "[2001:db8::a]:3100", local: "2001:db8:0:0:0:0:0:a", remote: "::1", expected: 200 },
|
||||
{ name: "IPv6 same caller", host: "[2001:db8::a]:3100", local: "2001:db8::a", remote: "2001:db8::a", expected: 200 },
|
||||
{ name: "remote caller", remote: "203.0.113.6", expected: 403 },
|
||||
{ name: "foreign numeric Host", host: "203.0.113.6:3100", expected: 403 },
|
||||
{ name: "unknown DNS Host", host: "unknown.example.test:3100", expected: 403 },
|
||||
{ name: "missing local socket", local: undefined, expected: 403 },
|
||||
{ name: "missing remote socket", remote: undefined, expected: 403 },
|
||||
{ name: "nonnumeric local socket", local: "controller.example.test", expected: 403 },
|
||||
{ name: "nonnumeric remote socket", remote: "localhost", expected: 403 },
|
||||
{ name: "page route", path: "/dashboard", expected: 403 },
|
||||
{ name: "API lookalike route", path: "/api-foreign", expected: 403 },
|
||||
{ name: "userinfo Host", host: "user@203.0.113.5:3100", expected: 403 },
|
||||
{ name: "Forwarded", headers: { forwarded: "for=127.0.0.1" }, expected: 403 },
|
||||
{ name: "forwarded Host", headers: { "x-forwarded-host": "203.0.113.5:3100" }, expected: 403 },
|
||||
{ name: "forwarded caller", headers: { "x-forwarded-for": "127.0.0.1" }, expected: 403 },
|
||||
{ name: "forwarded protocol", headers: { "x-forwarded-proto": "http" }, expected: 403 },
|
||||
{ name: "arbitrary forwarded metadata", headers: { "x-forwarded-extra": "" }, expected: 403 },
|
||||
])("limits direct local API admission: $name", scenario => {
|
||||
const values = { host: "203.0.113.5:3100", local: "203.0.113.5", remote: "203.0.113.5", path: "/api/health", headers: {}, ...scenario };
|
||||
const headers: Record<string, string> = { host: values.host, ...values.headers };
|
||||
const req = { path: values.path, headers, header: (name: string) => headers[name.toLowerCase()], accepts: () => "json",
|
||||
socket: { localAddress: values.local, remoteAddress: values.remote } } as unknown as Request;
|
||||
const res = { status: vi.fn().mockReturnThis(), type: vi.fn().mockReturnThis(), send: vi.fn(), json: vi.fn() } as unknown as Response;
|
||||
const next = vi.fn();
|
||||
privateHostnameGuard({ enabled: true, allowedHostnames: [], bindHost: "configured.example.test" })(req, res, next);
|
||||
if (scenario.expected === 200) { expect(next).toHaveBeenCalledOnce(); expect(res.status).not.toHaveBeenCalled(); }
|
||||
else { expect(next).not.toHaveBeenCalled(); expect(res.status).toHaveBeenCalledWith(403); }
|
||||
});
|
||||
|
||||
it("allows requests when disabled", async () => {
|
||||
const app = createApp({ enabled: false });
|
||||
const res = await request(app).get("/api/health").set("Host", "dotta-macbook-pro:3100");
|
||||
|
||||
@@ -1,11 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { once } from "node:events";
|
||||
import {
|
||||
buildRuntimeApiCandidateUrls,
|
||||
chooseLocalRuntimeApiUrl,
|
||||
choosePrimaryRuntimeApiUrl,
|
||||
collectReachableInterfaceHosts,
|
||||
resolveLocalRuntimeApiUrl,
|
||||
} from "../runtime-api.js";
|
||||
import { createPaperclipHttpServer } from "../http/server.js";
|
||||
import { registerRunnerPrpAuthority, runnerPrpWebSocketInternals } from "../realtime/runner-prp-ws.js";
|
||||
import type { DurablePrpControlPlane } from "../vendor/paperclip-runner/index.js";
|
||||
|
||||
describe("runtime API discovery", () => {
|
||||
it.each([
|
||||
["127.0.0.1", "http://127.0.0.1:3218"],
|
||||
["0.0.0.0", "http://127.0.0.1:3218"],
|
||||
["::", "http://[::1]:3218"],
|
||||
["::1", "http://[::1]:3218"],
|
||||
["2001:db8::123", "http://[2001:db8::123]:3218"],
|
||||
["[::1]", "http://[::1]:3218"],
|
||||
["192.0.2.12", "http://192.0.2.12:3218"],
|
||||
])("uses listener host %s and its selected port for local runtime transport", (bindHost, expected) => {
|
||||
expect(chooseLocalRuntimeApiUrl({ bindHost, port: 3218 })).toBe(expected);
|
||||
});
|
||||
|
||||
it("registers private runner WebSocket transport alongside a public HTTPS callback origin", async () => {
|
||||
const input = {
|
||||
authPublicBaseUrl: "https://callbacks.example.test",
|
||||
allowedHostnames: ["callbacks.example.test"],
|
||||
bindHost: "127.0.0.1",
|
||||
port: 3218,
|
||||
};
|
||||
expect(choosePrimaryRuntimeApiUrl(input)).toBe("https://callbacks.example.test");
|
||||
const server = createPaperclipHttpServer((_req, response) => response.end("ready"), {
|
||||
apiUrl: chooseLocalRuntimeApiUrl(input),
|
||||
});
|
||||
const runId = "00000000-0000-4000-8000-000000000887";
|
||||
try {
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
const registration = await registerRunnerPrpAuthority({
|
||||
companyId: "company-1", runId,
|
||||
authority: {} as DurablePrpControlPlane,
|
||||
});
|
||||
try {
|
||||
expect(registration.connectUrl).toBe(`${resolveLocalRuntimeApiUrl().replace("http:", "ws:")}/api/runner/v1/connect/${runId}`);
|
||||
} finally {
|
||||
await registration.release();
|
||||
}
|
||||
} finally {
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
runnerPrpWebSocketInternals.resetForTests();
|
||||
}
|
||||
});
|
||||
|
||||
it("prefers the explicit public base URL for the primary runtime URL", () => {
|
||||
expect(
|
||||
choosePrimaryRuntimeApiUrl({
|
||||
|
||||
@@ -18,6 +18,9 @@ import { decisionService, decisionRetentionService, toolAccessService, githubCon
|
||||
|
||||
import { companies, runDatabaseBackup, type Db } from "@paperclipai/db";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { resolveLocalRuntimeApiUrl } from "../runtime-api.js";
|
||||
import { onNativeWorkspaceFinalizationRelease, releaseNativeWorkspaceFinalization } from "../services/native-workspace-finalization-notifications.js";
|
||||
import { onRetainedNativeSessionCleanupRelease, releaseRetainedNativeSessionCleanup } from "../services/retained-native-session-cleanup-notifications.js";
|
||||
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { gzipSync } from "node:zlib";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -71,7 +74,7 @@ const {
|
||||
externalObjectsServiceFactoryMock,
|
||||
feedbackExportServiceMock,
|
||||
feedbackServiceFactoryMock,
|
||||
fakeServer,
|
||||
createFakeServer,
|
||||
heartbeatServiceFactoryMock,
|
||||
heartbeatServiceMock,
|
||||
issueThreadInteractionServiceFactoryMock,
|
||||
@@ -237,16 +240,40 @@ const {
|
||||
flushPendingFeedbackTraces: vi.fn(async () => ({ attempted: 0, sent: 0, failed: 0 })),
|
||||
};
|
||||
const feedbackServiceFactoryMock = vi.fn(() => feedbackExportServiceMock);
|
||||
const fakeServer = {
|
||||
on: vi.fn().mockReturnThis(),
|
||||
once: vi.fn().mockReturnThis(),
|
||||
off: vi.fn().mockReturnThis(),
|
||||
listen: vi.fn((_port: number, _host: string, callback?: () => void) => {
|
||||
callback?.();
|
||||
return fakeServer;
|
||||
}),
|
||||
close: vi.fn((callback?: (error?: Error) => void) => callback?.()),
|
||||
};
|
||||
function createFakeServer() {
|
||||
const lifecycleListeners = new Map<string, Map<() => void, boolean>>();
|
||||
const addListener = (event: string, listener: () => void, once: boolean) => {
|
||||
const listeners = lifecycleListeners.get(event) ?? new Map<() => void, boolean>();
|
||||
listeners.set(listener, once); lifecycleListeners.set(event, listeners);
|
||||
};
|
||||
const emit = (event: string) => {
|
||||
for (const [listener, once] of [...(lifecycleListeners.get(event) ?? [])]) {
|
||||
if (once) lifecycleListeners.get(event)?.delete(listener);
|
||||
listener();
|
||||
}
|
||||
};
|
||||
let boundAddress: { address: string; family: string; port: number } | null = null;
|
||||
const fakeServer = {
|
||||
listening: false,
|
||||
address: vi.fn(() => boundAddress),
|
||||
on: vi.fn((event: string, listener: () => void) => { addListener(event, listener, false); return fakeServer; }),
|
||||
once: vi.fn((event: string, listener: () => void) => { addListener(event, listener, true); return fakeServer; }),
|
||||
off: vi.fn((event: string, listener: () => void) => { lifecycleListeners.get(event)?.delete(listener); return fakeServer; }),
|
||||
resetBoundState() { fakeServer.listening = false; boundAddress = null; },
|
||||
resetFixture() { fakeServer.resetBoundState(); lifecycleListeners.clear(); },
|
||||
listen: vi.fn((port: number, host: string, callback?: () => void) => {
|
||||
boundAddress = { address: host === "::" || host === "::1" ? host : "127.0.0.1", family: host.includes(":") ? "IPv6" : "IPv4", port };
|
||||
fakeServer.listening = true;
|
||||
emit("listening");
|
||||
callback?.();
|
||||
return fakeServer;
|
||||
}),
|
||||
close: vi.fn((callback?: (error?: Error) => void) => {
|
||||
fakeServer.resetBoundState(); emit("close"); callback?.();
|
||||
}),
|
||||
};
|
||||
return fakeServer;
|
||||
}
|
||||
const loadConfigMock = vi.fn();
|
||||
|
||||
return {
|
||||
@@ -268,7 +295,7 @@ const {
|
||||
externalObjectsServiceFactoryMock,
|
||||
feedbackExportServiceMock,
|
||||
feedbackServiceFactoryMock,
|
||||
fakeServer,
|
||||
createFakeServer,
|
||||
heartbeatServiceFactoryMock,
|
||||
heartbeatServiceMock,
|
||||
issueThreadInteractionServiceFactoryMock,
|
||||
@@ -280,6 +307,8 @@ const {
|
||||
};
|
||||
});
|
||||
|
||||
let fakeServer = createFakeServer();
|
||||
|
||||
function buildTestConfig(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
deploymentMode: "authenticated",
|
||||
@@ -636,6 +665,11 @@ async function settleStartupHousekeeping() {
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
fakeServer.resetFixture();
|
||||
fakeServer = createFakeServer();
|
||||
});
|
||||
|
||||
describe("startServer feedback export wiring", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
@@ -1653,7 +1687,24 @@ describe("startServer feedback export wiring", () => {
|
||||
loadConfigMock.mockReturnValue(buildTestConfig({ heartbeatSchedulerEnabled: true }));
|
||||
let releaseCleanup!: () => void;
|
||||
const ready = new Promise<void>(resolve => { releaseCleanup = resolve; });
|
||||
const stop = vi.fn();
|
||||
const notificationDb = {};
|
||||
const notificationScope = { companyId: "held-startup-company" };
|
||||
const onRelease = vi.fn();
|
||||
const unsubscribe = owner === "retained cleanup"
|
||||
? onRetainedNativeSessionCleanupRelease(notificationDb, onRelease)
|
||||
: owner === "workspace finalization"
|
||||
? onNativeWorkspaceFinalizationRelease(notificationDb, onRelease)
|
||||
: undefined;
|
||||
const releaseNotification = owner === "retained cleanup"
|
||||
? () => releaseRetainedNativeSessionCleanup(notificationDb, notificationScope)
|
||||
: owner === "workspace finalization"
|
||||
? () => releaseNativeWorkspaceFinalization(notificationDb, notificationScope)
|
||||
: undefined;
|
||||
const stop = vi.fn(unsubscribe);
|
||||
if (releaseNotification) {
|
||||
releaseNotification();
|
||||
expect(onRelease).toHaveBeenCalledOnce();
|
||||
}
|
||||
const register = owner === "retained cleanup" ? heartbeatServiceMock.registerRetainedNativeSessionCleanupWork
|
||||
: owner === "workspace finalization" ? heartbeatServiceMock.registerNativeWorkspaceFinalizationWork
|
||||
: owner === "environment settlement" ? heartbeatServiceMock.registerNativeEnvironmentSettlementWork
|
||||
@@ -1682,15 +1733,26 @@ describe("startServer feedback export wiring", () => {
|
||||
const server = await starting;
|
||||
stopping = server.shutdown().then(() => { stopped = true; });
|
||||
await settleStartupHousekeeping();
|
||||
if (owner === "retained cleanup" || owner === "workspace finalization") expect(stop).toHaveBeenCalledOnce();
|
||||
if (releaseNotification) {
|
||||
expect(stop).toHaveBeenCalled();
|
||||
releaseNotification();
|
||||
expect(onRelease).toHaveBeenCalledOnce();
|
||||
}
|
||||
expect(stopped).toBe(false);
|
||||
releaseCleanup();
|
||||
await stopping;
|
||||
expect(stopped).toBe(true);
|
||||
if (releaseNotification) {
|
||||
releaseNotification();
|
||||
expect(onRelease).toHaveBeenCalledOnce();
|
||||
}
|
||||
} finally {
|
||||
releaseCleanup();
|
||||
await starting;
|
||||
await stopping;
|
||||
unsubscribe?.();
|
||||
timer.mockRestore();
|
||||
}
|
||||
expect(stopped).toBe(true);
|
||||
});
|
||||
|
||||
it("reports ready before startup housekeeping finishes and starts the scheduler after it", async () => {
|
||||
@@ -1788,14 +1850,17 @@ describe("startServer feedback export wiring", () => {
|
||||
heartbeatSchedulerEnabled: true,
|
||||
heartbeatSchedulerIntervalMs: 30000,
|
||||
}));
|
||||
heartbeatServiceMock.recoverNativeRunsAfterRestart.mockRejectedValueOnce(
|
||||
new Error("native recovery unavailable"),
|
||||
);
|
||||
heartbeatServiceMock.recoverNativeRunsAfterRestart.mockImplementationOnce(async () => {
|
||||
expect(fakeServer.listening).toBe(true);
|
||||
expect(resolveLocalRuntimeApiUrl()).toBe("http://127.0.0.1:3210");
|
||||
throw new Error("native recovery unavailable");
|
||||
});
|
||||
|
||||
await expect(startServer()).rejects.toThrow("native recovery unavailable");
|
||||
|
||||
expect(fakeServer.listen).toHaveBeenCalledTimes(1);
|
||||
expect(fakeServer.close).toHaveBeenCalledTimes(1);
|
||||
expect(() => resolveLocalRuntimeApiUrl()).toThrow("local_runtime_api_listener_unavailable");
|
||||
});
|
||||
|
||||
it("refuses authenticated public startup without an external database URL", async () => {
|
||||
|
||||
@@ -1,21 +1,55 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, agentWakeupRequests, companies, createDb, heartbeatRuns, issues, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
||||
import { taskInterruptionPresentation, taskInterruptionPresentations } from "../services/task-interruption-presentation.js";
|
||||
import { createRunSecretRedactionRegistry } from "../services/run-secret-redaction.js";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, agentWakeupRequests, companies, createDb, applyPendingMigrations, heartbeatRuns, issues, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
||||
import { taskInterruptionPresentation, taskInterruptionPresentations } from "../services/task-interruption-presentation.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { captureInterruptionQuery, seedInterruptionFixture } from "./helpers/task-interruption-fixture.js";
|
||||
|
||||
const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TASK_INTERRUPTION_TEST_DATABASE_URL");
|
||||
const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
const captureTaskInterruptionFailure = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../sentry.js", () => ({ captureTaskInterruptionFailure }));
|
||||
|
||||
describe("task interruption latest run query", () => {
|
||||
describe.skipIf(!support.supported)("task interruption latest run query", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
beforeAll(async () => { database = await startEmbeddedPostgresTestDatabase("interruption-query-"); db = createDb(database.connectionString); }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
beforeAll(async () => {
|
||||
if (externalDatabaseUrl) await applyPendingMigrations(externalDatabaseUrl);
|
||||
database = externalDatabaseUrl ? { connectionString: externalDatabaseUrl, cleanup: async () => {} }
|
||||
: await startEmbeddedPostgresTestDatabase("interruption-query-");
|
||||
db = createDb(database.connectionString);
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
|
||||
|
||||
it.each(["valid", "numeric_user", "numeric_audit"] as const)("retains bounded typed Stop evidence in the real batched projection (%s)", async variant => {
|
||||
const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Stopped task", issuePrefix: `S${companyId.slice(0, 7)}` });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Stopped agent", adapterType: "paperclip_runner" });
|
||||
const [issue] = await db.insert(issues).values({ companyId, title: "Keep this task in progress",
|
||||
status: "in_progress", assigneeAgentId: agentId }).returning();
|
||||
const nativeCancellation = { schema: "paperclip.native-cancellation.v1", companyId, runId, issueId: issue.id,
|
||||
scope: "run", reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true,
|
||||
intentAuditId: variant === "numeric_audit" ? 123 : randomUUID(), acknowledgementAuditId: randomUUID() };
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issue.id,
|
||||
scopeKind: "issue", status: "cancelled", runtimeMode: "native", driverKind: "cursor_cloud_api",
|
||||
resultJson: { cancelledByActorType: "user", cancelledByUserId: variant === "numeric_user" ? 123 : "board", nativeCancellation,
|
||||
executionCancellation: { state: "requested" }, unrelatedPayload: "x".repeat(128_000) } });
|
||||
const result = await taskInterruptionPresentations(db, companyId, [issue]);
|
||||
expect(result.get(issue.id)).toMatchObject(variant === "valid"
|
||||
? { state: "resolved", canRetry: false } : { state: "failed", canRetry: true });
|
||||
const query = await captureInterruptionQuery(db, taskInterruptionPresentations, companyId, [issue]);
|
||||
const [projected] = await db.$client.unsafe(query.sql, query.params as never[]);
|
||||
expect(projected.jsonb_build_object.nativeCancellation).toEqual({ ...nativeCancellation,
|
||||
intentAuditId: variant === "numeric_audit" ? null : nativeCancellation.intentAuditId });
|
||||
expect(projected.jsonb_build_object.cancelledByUserId).toBe(variant === "numeric_user" ? null : "board");
|
||||
expect(projected).toMatchObject({ company_id: companyId, native_issue_id: issue.id, runtime_mode: "native" });
|
||||
expect(projected.jsonb_build_object).not.toHaveProperty("unrelatedPayload");
|
||||
expect(JSON.stringify(projected.jsonb_build_object).length).toBeLessThan(4000);
|
||||
});
|
||||
|
||||
it("redacts registered run secrets from both task detail and list provider explanations", async () => {
|
||||
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "a".repeat(64));
|
||||
try {
|
||||
|
||||
@@ -103,6 +103,51 @@ describe("built-in runtime connection tool delivery", () => {
|
||||
});
|
||||
|
||||
|
||||
describe("native Cursor Cloud environment checks", () => {
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); });
|
||||
const context = { companyId: "company-test", adapterType: "paperclip_runner",
|
||||
config: { provider: "cursor_cloud", model: "caller-model", repoUrl: "https://github.com/acme/repo", env: { CURSOR_API_KEY: "bound-cloud-key" } } };
|
||||
|
||||
it("checks account access without a prompt and makes unavailable model attestation explicit", async () => {
|
||||
vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://callback.example.test");
|
||||
const fetch = vi.fn(async (url: unknown) => String(url).startsWith("https://callback.example.test/") ? new Response(null, { status: 401 }) : new Response(JSON.stringify({ items: [{ id: "caller-model", displayName: "Caller model" }] }), { headers: { "Content-Type": "application/json" } }));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
const result = await requireServerAdapter("paperclip_runner").testEnvironment!(context);
|
||||
expect(result.status).toBe("warn");
|
||||
expect(result.checks.map(check => check.code)).toEqual(["cursor_cloud_account_ready", "cursor_cloud_model_listed", "cursor_cloud_model_identity_unverified"]);
|
||||
expect(fetch).toHaveBeenCalledWith("https://api.cursor.com/v1/models", expect.objectContaining({ method: "GET", headers: expect.objectContaining({ Authorization: "Bearer bound-cloud-key" }) }));
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(JSON.stringify(result)).not.toContain("bound-cloud-key");
|
||||
});
|
||||
|
||||
it.each([undefined, "http://localhost:3100", "https://callback.example.test/path"])("rejects missing or invalid public callback origin %s before provider reads", async origin => {
|
||||
vi.stubEnv("PAPERCLIP_PUBLIC_URL", origin);
|
||||
const fetch = vi.fn(); vi.stubGlobal("fetch", fetch);
|
||||
const result = await requireServerAdapter("paperclip_runner").testEnvironment!(context);
|
||||
expect(result.status).toBe("fail");
|
||||
expect(result.checks[0]?.code).toBe("cursor_cloud_public_relay_unavailable");
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports an unreachable callback before checking provider credentials", async () => {
|
||||
vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://callback.example.test");
|
||||
const fetch = vi.fn(async () => { throw new Error("network unavailable"); }); vi.stubGlobal("fetch", fetch);
|
||||
const result = await requireServerAdapter("paperclip_runner").testEnvironment!(context);
|
||||
expect(result.checks[0]?.code).toBe("cursor_cloud_public_relay_unavailable");
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects remote controllers and missing credentials before provider reads", async () => {
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
const remote = await requireServerAdapter("paperclip_runner").testEnvironment!({ ...context, executionTarget: { kind: "remote", transport: "ssh", remoteCwd: "/workspace", ssh: {} } as never });
|
||||
expect(remote.checks[0]?.code).toBe("cursor_cloud_local_controller_required");
|
||||
const missing = await requireServerAdapter("paperclip_runner").testEnvironment!({ ...context, config: { ...context.config, env: {} } });
|
||||
expect(missing.checks[0]?.code).toBe("cursor_cloud_api_key_missing");
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("native ACPX environment checks", () => {
|
||||
beforeEach(() => {
|
||||
verifyApiKey.mockReset().mockResolvedValue(undefined);
|
||||
|
||||
@@ -413,6 +413,7 @@ const paperclipRunnerAdapter: ServerAdapterModule = {
|
||||
? "amazon-bedrock"
|
||||
: ctx.config.provider === "acpx"
|
||||
? "acpx"
|
||||
: ctx.config.provider === "cursor_cloud" ? "cursor"
|
||||
: "codex",
|
||||
summary: message,
|
||||
};
|
||||
@@ -439,9 +440,39 @@ const paperclipRunnerAdapter: ServerAdapterModule = {
|
||||
}],
|
||||
};
|
||||
}
|
||||
if (context.executionTarget?.kind === "remote" && context.executionTarget.transport === "sandbox" && context.executionTarget.runnerTask) {
|
||||
if (profile.provider !== "cursor_cloud" && context.executionTarget?.kind === "remote" && context.executionTarget.transport === "sandbox" && context.executionTarget.runnerTask) {
|
||||
return probePluginRunnerEnvironment(context);
|
||||
}
|
||||
if (profile.provider === "cursor_cloud") {
|
||||
const failure = (code: string, message: string) => ({ adapterType: "paperclip_runner", status: "fail" as const, testedAt: new Date().toISOString(), checks: [{ code, level: "error" as const, message }] });
|
||||
if (context.executionTarget?.kind === "remote") return failure("cursor_cloud_local_controller_required", "Select a local Paperclip controller. Cursor hosts the execution environment.");
|
||||
const configuredEnv = context.config.env;
|
||||
const binding = configuredEnv && typeof configuredEnv === "object" && !Array.isArray(configuredEnv)
|
||||
? (configuredEnv as Record<string, unknown>).CURSOR_API_KEY : undefined;
|
||||
const apiKey = typeof binding === "string" ? binding : binding && typeof binding === "object" && "type" in binding && binding.type === "plain" && "value" in binding && typeof binding.value === "string" ? binding.value : "";
|
||||
if (!apiKey.trim()) return failure("cursor_cloud_api_key_missing", "Bind a Cursor Cloud API key to CURSOR_API_KEY before testing.");
|
||||
try {
|
||||
const { remoteMcpRelayUrl } = await import("../services/native-runtime/remote-mcp-relay.js");
|
||||
const { resolveCursorCloudPublicOrigin } = await import("../services/native-runtime/cursor-cloud-runtime.js");
|
||||
const url = remoteMcpRelayUrl(resolveCursorCloudPublicOrigin() ?? "", "00000000-0000-4000-8000-000000000000");
|
||||
const response = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}", redirect: "error", signal: AbortSignal.timeout(5_000) });
|
||||
await response.body?.cancel();
|
||||
if (response.status !== 401) throw new Error("relay_unavailable");
|
||||
} catch {
|
||||
return failure("cursor_cloud_public_relay_unavailable", "Configure PAPERCLIP_PUBLIC_URL as a reachable HTTPS origin for /mcp/native-runs/. The callback must reject unauthenticated requests with HTTP 401. Expose only this callback path through the public proxy.");
|
||||
}
|
||||
try {
|
||||
const { CursorCloudClient } = await import("../vendor/paperclip-runner/index.js");
|
||||
const { items } = await new CursorCloudClient({ apiKey }).listModels();
|
||||
const listed = items.some(item => item.id === profile.model || item.aliases?.includes(profile.model));
|
||||
return { adapterType: "paperclip_runner", status: "warn" as const, testedAt: new Date().toISOString(), checks: [
|
||||
{ code: "cursor_cloud_account_ready", level: "info" as const, message: "The bound Cursor Cloud API key can read its model catalog. No prompt was sent." },
|
||||
{ code: listed ? "cursor_cloud_model_listed" : "cursor_cloud_model_unlisted", level: listed ? "info" as const : "warn" as const,
|
||||
message: listed ? "The selected model appears in this account's catalog." : "The selected model is absent from the recommended catalog. Cursor will decide whether this exact model is available when it runs." },
|
||||
{ code: "cursor_cloud_model_identity_unverified", level: "warn" as const, message: "This experimental integration forwards the selected model; Cursor does not acknowledge the effective model. Cloud commands use Cursor-managed permissions." },
|
||||
] };
|
||||
} catch { return failure("cursor_cloud_account_unavailable", "Cursor Cloud could not validate the bound key. Check its Cloud Agents access and retry."); }
|
||||
}
|
||||
if (profile.provider === "muse") {
|
||||
return { adapterType: "paperclip_runner", status: "warn" as const, testedAt: new Date().toISOString(),
|
||||
checks: [{ code: "muse_background_test_required", level: "warn" as const, message: "Muse manages its model and billing. Verify the paired receiver and independent background reply in Paperclip; this read-only check does not wake Muse." }] };
|
||||
@@ -602,6 +633,7 @@ const paperclipRunnerAdapter: ServerAdapterModule = {
|
||||
getRuntimeCommandSpec: (config) => config.provider === "claude_managed"
|
||||
|| config.provider === "aws_agentcore"
|
||||
|| config.provider === "acpx"
|
||||
|| config.provider === "cursor_cloud"
|
||||
? { command: "paperclip-runnerd", detectCommand: null, installCommand: null }
|
||||
: config.provider === "opencode"
|
||||
? buildNpmRuntimeCommandSpec(
|
||||
@@ -625,6 +657,7 @@ const paperclipRunnerAdapter: ServerAdapterModule = {
|
||||
{ value: "claude_managed", label: "Claude Managed" },
|
||||
{ value: "aws_agentcore", label: "AWS AgentCore" },
|
||||
{ value: "acpx", label: "ACP agents" },
|
||||
{ value: "cursor_cloud", label: "Cursor Cloud (experimental)" },
|
||||
],
|
||||
hint: "Select a local provider, company-qualified managed provider, or an ACP agent.",
|
||||
},
|
||||
@@ -633,6 +666,17 @@ const paperclipRunnerAdapter: ServerAdapterModule = {
|
||||
options: PAPERCLIP_RUNNER_ACPX_PROFILES.filter(profile => profile.qualified).map(profile => ({ value: profile.value, label: profile.label })),
|
||||
meta: { visibleWhen: { key: "provider", value: "acpx" } },
|
||||
},
|
||||
...[
|
||||
{ key: "repoUrl", label: "GitHub repository" },
|
||||
{ key: "repoRef", label: "Starting ref" },
|
||||
{ key: "prUrl", label: "Pull request URL" },
|
||||
{ key: "cloudEnvName", label: "Cursor cloud environment" },
|
||||
].map(field => ({ ...field, type: "text" as const, meta: { visibleWhen: { key: "provider", value: "cursor_cloud" } } })),
|
||||
...[
|
||||
{ key: "workOnCurrentBranch", label: "Work on current branch" },
|
||||
{ key: "autoCreatePR", label: "Auto-create pull request" },
|
||||
{ key: "skipReviewerRequest", label: "Skip reviewer request" },
|
||||
].map(field => ({ ...field, type: "toggle" as const, default: false, meta: { visibleWhen: { key: "provider", value: "cursor_cloud" } } })),
|
||||
{
|
||||
key: "codexPermissionMode",
|
||||
label: "Codex permission mode",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { nativeRunMcpRoutes } from "./routes/native-run-mcp.js";
|
||||
import { connectionEventWakeRoutes } from "./routes/connection-event-wake.js";
|
||||
import { registerGitHubReviewProjectionWork } from "./services/chat-channels/github/review-projection-work.js";
|
||||
import { finishServiceShutdown } from "./shutdown.js";
|
||||
@@ -556,6 +557,7 @@ export async function createApp(
|
||||
// must be reachable by remote adapters that intentionally do not receive an
|
||||
// agent API key. Every request revalidates the active heartbeat row.
|
||||
app.use(runtimeConnectionIntentRoutes(db));
|
||||
app.use(nativeRunMcpRoutes());
|
||||
const hostServicesDisposers = new Map<string, () => void>();
|
||||
let lifecyclePluginsReady = false;
|
||||
const agentLifecycle = startAgentLifecycle(db, createLifecycleDriver(db, workerManager), () => lifecyclePluginsReady && !isWarmStandby() && !isIdleTaskDrainActive());
|
||||
|
||||
@@ -1,12 +1,46 @@
|
||||
import { once } from "node:events";
|
||||
import dns from "node:dns";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { networkInterfaces, tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { request } from "node:http";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DurablePrpControlPlane } from "../vendor/paperclip-runner/index.js";
|
||||
import express from "express";
|
||||
import { DurablePrpControlPlane } from "../vendor/paperclip-runner/index.js";
|
||||
import { registerRunnerPrpAuthority, runnerPrpWebSocketInternals } from "../realtime/runner-prp-ws.js";
|
||||
import { resolveLocalRuntimeApiUrl } from "../runtime-api.js";
|
||||
import { createPaperclipHttpServer } from "./server.js";
|
||||
import { privateHostnameGuard } from "../middleware/private-hostname-guard.js";
|
||||
|
||||
async function guardedNativeRead(bindHost: string, configuredHost = bindHost) {
|
||||
const app = express();
|
||||
app.use(privateHostnameGuard({ enabled: true, bindHost: configuredHost, allowedHostnames: [] }));
|
||||
app.get("/api/native-read", (req, res) => {
|
||||
res.status(req.header("authorization") === "Bearer synthetic-readonly-run-token" ? 200 : 401).json({ readonly: true });
|
||||
});
|
||||
const server = createPaperclipHttpServer(app, { apiUrl: "https://advertised.example.test" });
|
||||
try {
|
||||
server.listen(0, bindHost);
|
||||
await once(server, "listening");
|
||||
const url = `${resolveLocalRuntimeApiUrl()}/api/native-read`;
|
||||
const authenticated = await fetch(url, { headers: { Authorization: "Bearer synthetic-readonly-run-token" } });
|
||||
expect(authenticated.status).toBe(200);
|
||||
expect(await authenticated.json()).toEqual({ readonly: true });
|
||||
const unauthenticated = await fetch(url);
|
||||
expect(unauthenticated.status).toBe(401);
|
||||
await unauthenticated.body?.cancel();
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
describe("Paperclip HTTP server runner transport", () => {
|
||||
afterEach(() => runnerPrpWebSocketInternals.resetForTests());
|
||||
afterEach(() => {
|
||||
runnerPrpWebSocketInternals.resetForTests();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it("registers native runner authority without a separate startup call", async () => {
|
||||
const server = createPaperclipHttpServer((_req, res) => res.end("ok"), {
|
||||
@@ -14,13 +48,16 @@ describe("Paperclip HTTP server runner transport", () => {
|
||||
});
|
||||
const handleUpgrade = vi.fn();
|
||||
const runId = "00000000-0000-4000-8000-000000000777";
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
const origin = resolveLocalRuntimeApiUrl();
|
||||
const authority = await registerRunnerPrpAuthority({
|
||||
companyId: "company-1", runId,
|
||||
authority: { handleUpgrade } as unknown as DurablePrpControlPlane,
|
||||
});
|
||||
expect(authority.connectUrl).toBe(`ws://127.0.0.1:3210/api/runner/v1/connect/${runId}`);
|
||||
expect(authority.connectUrl).toBe(`${origin.replace("http:", "ws:")}/api/runner/v1/connect/${runId}`);
|
||||
await authority.release();
|
||||
server.close();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
});
|
||||
|
||||
it("serves HTTP and rejects an unregistered runner over the real listener", async () => {
|
||||
@@ -48,4 +85,144 @@ describe("Paperclip HTTP server runner transport", () => {
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses native endpoints before listen and after close despite advertised fallback URLs", async () => {
|
||||
vi.stubEnv("PAPERCLIP_API_URL", "https://advertised.example.test");
|
||||
vi.stubEnv("PAPERCLIP_LISTEN_HOST", "controller.example.test");
|
||||
vi.stubEnv("PAPERCLIP_LISTEN_PORT", "3210");
|
||||
const server = createPaperclipHttpServer((_req, res) => res.end("ready"), {
|
||||
apiUrl: "https://advertised.example.test",
|
||||
});
|
||||
const binding = { companyId: "company-1", runId: "00000000-0000-4000-8000-000000000779",
|
||||
authority: {} as DurablePrpControlPlane };
|
||||
expect(() => resolveLocalRuntimeApiUrl()).toThrow();
|
||||
await expect(registerRunnerPrpAuthority(binding)).rejects.toThrow();
|
||||
server.listen(0, "127.0.0.1");
|
||||
await once(server, "listening");
|
||||
try {
|
||||
expect(resolveLocalRuntimeApiUrl()).toMatch(/^http:\/\/127\.0\.0\.1:\d+$/);
|
||||
} finally {
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
expect(() => resolveLocalRuntimeApiUrl()).toThrow();
|
||||
await expect(registerRunnerPrpAuthority(binding)).rejects.toThrow();
|
||||
expect(process.env.PAPERCLIP_API_URL).toBe("https://advertised.example.test");
|
||||
});
|
||||
|
||||
it("uses the actual numeric bind for bearer REST and PRP without a second hostname lookup", async () => {
|
||||
const hostname = "controller-bind.example.test";
|
||||
let lookups = 0;
|
||||
vi.spyOn(dns, "lookup").mockImplementation(((host, options, callback) => {
|
||||
if (host !== hostname || typeof options !== "object" || options.all !== true) {
|
||||
throw new Error("Expected only the listener's all-address lookup");
|
||||
}
|
||||
// node:net's listen path requests all addresses; dns.lookup's overloaded
|
||||
// declaration otherwise contextualizes this callback as its IPv4 form.
|
||||
const lookedUp = callback as (error: NodeJS.ErrnoException | null, addresses?: dns.LookupAddress[]) => void;
|
||||
lookups++;
|
||||
if (lookups > 1) return lookedUp(Object.assign(new Error("Unexpected second DNS authority"), { code: "ENOTFOUND" }));
|
||||
lookedUp(null, [{ address: "127.0.0.1", family: 4 }]);
|
||||
}) as typeof dns.lookup);
|
||||
vi.stubEnv("PAPERCLIP_API_URL", "https://advertised.example.test");
|
||||
vi.stubEnv("PAPERCLIP_LISTEN_HOST", hostname);
|
||||
vi.stubEnv("PAPERCLIP_LISTEN_PORT", "1");
|
||||
const server = createPaperclipHttpServer((req, res) => {
|
||||
res.statusCode = req.headers.authorization === "Bearer synthetic-run-token" ? 200 : 401;
|
||||
res.end("local-controller");
|
||||
}, { apiUrl: "https://advertised.example.test" });
|
||||
const directory = await mkdtemp(join(tmpdir(), "paperclip-bound-prp-"));
|
||||
const runId = "00000000-0000-4000-8000-000000000780";
|
||||
const authority = new DurablePrpControlPlane({ stateDirectory: directory,
|
||||
identity: { runnerInstanceId: "bound-runner", environmentLeaseId: "bound-lease", normalizedSessionId: "bound-session", runId, turnId: "bound-turn", itemId: "bound-item" },
|
||||
expectedRunnerVersion: "0.3.0", expectedRunnerDigest: `sha256:${"a".repeat(64)}` });
|
||||
let registration: Awaited<ReturnType<typeof registerRunnerPrpAuthority>> | undefined;
|
||||
try {
|
||||
server.listen(0, hostname);
|
||||
await once(server, "listening");
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Expected a TCP bind");
|
||||
const expected = `http://127.0.0.1:${address.port}`;
|
||||
expect(resolveLocalRuntimeApiUrl()).toBe(expected);
|
||||
expect(await (await fetch(resolveLocalRuntimeApiUrl(), { headers: { Authorization: "Bearer synthetic-run-token" } })).text()).toBe("local-controller");
|
||||
registration = await registerRunnerPrpAuthority({ companyId: "company-1", runId, authority });
|
||||
expect(registration.connectUrl).toBe(`${expected.replace("http:", "ws:")}/api/runner/v1/connect/${runId}`);
|
||||
const upgraded = await new Promise<number | undefined>((resolve, reject) => {
|
||||
const req = request(registration!.connectUrl.replace("ws:", "http:"), { headers: {
|
||||
Connection: "Upgrade", Upgrade: "websocket", "Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==",
|
||||
} });
|
||||
req.once("upgrade", (res, socket) => { socket.destroy(); resolve(res.statusCode); });
|
||||
req.once("response", res => { res.resume(); resolve(res.statusCode); });
|
||||
req.once("error", reject);
|
||||
req.setTimeout(1000, () => req.destroy(new Error("PRP upgrade unavailable")));
|
||||
req.end();
|
||||
});
|
||||
expect(upgraded).toBe(101);
|
||||
expect(lookups).toBe(1);
|
||||
expect(process.env.PAPERCLIP_API_URL).toBe("https://advertised.example.test");
|
||||
} finally {
|
||||
await registration?.release();
|
||||
await authority.stop();
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["0.0.0.0", "127.0.0.1"], ["::", "[::1]"], ["::1", "[::1]"],
|
||||
])("uses matching loopback for a real %s bind", async (host, connectHost) => {
|
||||
const server = createPaperclipHttpServer((_req, res) => res.end("bound"), { apiUrl: "https://advertised.example.test" });
|
||||
server.listen(0, host);
|
||||
await once(server, "listening");
|
||||
try {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Expected TCP bind");
|
||||
expect(resolveLocalRuntimeApiUrl()).toBe(`http://${connectHost}:${address.port}`);
|
||||
expect(await (await fetch(resolveLocalRuntimeApiUrl())).text()).toBe("bound");
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise<void>(resolve => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it("fails closed for unavailable or nonnumeric bound addresses and competing listeners", async () => {
|
||||
const first = createPaperclipHttpServer((_req, res) => res.end("first"), { apiUrl: "http://ignored.example.test" });
|
||||
const second = createPaperclipHttpServer((_req, res) => res.end("second"), { apiUrl: "http://ignored.example.test" });
|
||||
first.listen(0, "127.0.0.1");
|
||||
await once(first, "listening");
|
||||
try {
|
||||
const address = vi.spyOn(first, "address");
|
||||
for (const unavailable of [null, "/tmp/not-tcp.sock", { address: "changed.example.test", family: "IPv4", port: 3210 }]) {
|
||||
address.mockReturnValueOnce(unavailable);
|
||||
expect(() => resolveLocalRuntimeApiUrl()).toThrow();
|
||||
}
|
||||
second.listen(0, "127.0.0.1");
|
||||
await once(second, "listening");
|
||||
expect(() => resolveLocalRuntimeApiUrl()).toThrow("local_runtime_api_listener_ambiguous");
|
||||
await expect(registerRunnerPrpAuthority({ companyId: "company-1", runId: "00000000-0000-4000-8000-000000000781", authority: {} as DurablePrpControlPlane }))
|
||||
.rejects.toThrow("local_runtime_api_listener_ambiguous");
|
||||
} finally {
|
||||
await Promise.all([first, second].map(server => new Promise<void>(resolve => server.close(() => resolve()))));
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["127.0.0.1", "::1", "::ffff:127.0.0.1"])("routes a guarded native read through the real %s listener", async host => {
|
||||
await guardedNativeRead(host);
|
||||
});
|
||||
|
||||
it("routes a guarded native read after a configured hostname binds a local interface", async context => {
|
||||
const address = Object.values(networkInterfaces()).flatMap(entries => entries ?? [])
|
||||
.find(entry => !entry.internal && entry.family === "IPv4" && !entry.address.startsWith("127."))?.address;
|
||||
if (!address) { context.skip(); return; }
|
||||
const hostname = "guarded-controller.example.test";
|
||||
let lookups = 0;
|
||||
vi.spyOn(dns, "lookup").mockImplementation(((host, options, callback) => {
|
||||
if (host !== hostname || typeof options !== "object" || options.all !== true) throw new Error("Unexpected lookup in local fixture");
|
||||
const lookedUp = callback as (error: NodeJS.ErrnoException | null, addresses?: dns.LookupAddress[]) => void;
|
||||
if (++lookups !== 1) throw new Error("Repeated hostname lookup in local fixture");
|
||||
lookedUp(null, [{ address, family: 4 }]);
|
||||
}) as typeof dns.lookup);
|
||||
await guardedNativeRead(hostname);
|
||||
expect(lookups).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createServer, type RequestListener, type ServerOptions } from "node:http";
|
||||
import { setupPluginApiWebSocketServer } from "../realtime/plugin-api-ws.js";
|
||||
import { setupRunnerPrpWebSocketServer } from "../realtime/runner-prp-ws.js";
|
||||
import { registerLocalRuntimeApiServer } from "../runtime-api.js";
|
||||
|
||||
/** Create the HTTP listener used by both production and custom launchers. */
|
||||
export function createPaperclipHttpServer(
|
||||
@@ -8,9 +9,10 @@ export function createPaperclipHttpServer(
|
||||
options: { apiUrl: string; httpOptions?: ServerOptions },
|
||||
) {
|
||||
const server = createServer(options.httpOptions ?? {}, listener);
|
||||
registerLocalRuntimeApiServer(server);
|
||||
// Native execution uses the listener even when a launcher has no browser
|
||||
// realtime connection. Register it before any run can be admitted.
|
||||
setupRunnerPrpWebSocketServer(server, { apiUrl: options.apiUrl });
|
||||
setupRunnerPrpWebSocketServer(server);
|
||||
setupPluginApiWebSocketServer(server, listener);
|
||||
return server;
|
||||
}
|
||||
+4
-1
@@ -178,7 +178,7 @@ import {
|
||||
reconcileAdapterAvailability,
|
||||
} from "./services/adapter-registry-bootstrap.js";
|
||||
import { createFeedbackTraceShareClientFromConfig } from "./services/feedback-share-client.js";
|
||||
import { buildRuntimeApiCandidateUrls, choosePrimaryRuntimeApiUrl } from "./runtime-api.js";
|
||||
import { buildRuntimeApiCandidateUrls, choosePrimaryRuntimeApiUrl, resolveLocalRuntimeApiUrl } from "./runtime-api.js";
|
||||
import { isLoopbackHost, rewriteLoopbackUrlPort } from "./url-utils.js";
|
||||
import { createPluginWorkerManager } from "./services/plugin-worker-manager.js";
|
||||
import { createStorageServiceFromConfig } from "./storage/index.js";
|
||||
@@ -1132,6 +1132,9 @@ async function startServerWithDatabaseTeardown(
|
||||
});
|
||||
});
|
||||
startupListenerBound = true;
|
||||
// The factory publishes the verified numeric endpoint on listening. Native
|
||||
// recovery must never fall back to a configured/public URL if it is absent.
|
||||
resolveLocalRuntimeApiUrl();
|
||||
|
||||
try {
|
||||
const result = await workspaceOperationService(db as any)
|
||||
|
||||
@@ -19,6 +19,7 @@ export const HTTP_LOG_REDACT_PATHS = [
|
||||
'req.headers["x-paperclip-cloud-inspection"]',
|
||||
// Runtime GitHub capabilities authorize credential acquisition for a live run.
|
||||
'req.headers["x-paperclip-github-capability"]',
|
||||
'req.headers["x-paperclip-runner-scope-token"]',
|
||||
// Telegram's optional webhook verification header is a reusable bearer
|
||||
// secret sent on every provider callback.
|
||||
'req.headers["x-telegram-bot-api-secret-token"]',
|
||||
|
||||
@@ -1,8 +1,34 @@
|
||||
import type { Request, RequestHandler } from "express";
|
||||
import { isIP } from "node:net";
|
||||
|
||||
function numericAddress(value: string | undefined): string | null {
|
||||
const address = value?.trim().toLowerCase().replace(/^\[([^\]]+)\]$/, "$1");
|
||||
if (!address || isIP(address) === 0) return null;
|
||||
if (isIP(address) === 4) return address;
|
||||
try {
|
||||
const canonical = new URL(`http://[${address}]`).hostname.slice(1, -1);
|
||||
const mapped = /^::ffff:([\da-f]+):([\da-f]+)$/.exec(canonical);
|
||||
if (!mapped) return canonical;
|
||||
const high = parseInt(mapped[1]!, 16), low = parseInt(mapped[2]!, 16);
|
||||
return [high >> 8, high & 255, low >> 8, low & 255].join(".");
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
function isLoopbackHostname(hostname: string): boolean {
|
||||
const normalized = hostname.trim().toLowerCase();
|
||||
return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1";
|
||||
const address = numericAddress(normalized);
|
||||
return normalized === "localhost" || address === "127.0.0.1" || address === "::1";
|
||||
}
|
||||
|
||||
function isDirectLocalApiRequest(req: Request, hostname: string): boolean {
|
||||
if (req.path !== "/api" && !req.path.startsWith("/api/")) return false;
|
||||
if (Object.keys(req.headers ?? {}).some(key => key.toLowerCase() === "forwarded" || key.toLowerCase().startsWith("x-forwarded-"))) return false;
|
||||
// Only a numeric Host is eligible; URL userinfo or a DNS name cannot borrow
|
||||
// the listener's address. Socket metadata supplies the actual local authority.
|
||||
if (!/^(?:\[[\da-f:.]+\]|[\d.]+)(?::\d+)?$/i.test(req.header("host")?.trim() ?? "")) return false;
|
||||
const host = numericAddress(hostname), local = numericAddress(req.socket?.localAddress), remote = numericAddress(req.socket?.remoteAddress);
|
||||
if (!host || !local || !remote || host !== local) return false;
|
||||
return remote === local || remote === "::1" || remote.startsWith("127.");
|
||||
}
|
||||
|
||||
function extractHostname(req: Request): string | null {
|
||||
@@ -81,7 +107,7 @@ export function privateHostnameGuard(opts: {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isLoopbackHostname(hostname) || allowSet.has(hostname)) {
|
||||
if (isLoopbackHostname(hostname) || allowSet.has(hostname) || isDirectLocalApiRequest(req, hostname)) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { createServer } from "node:http";
|
||||
import { createServer as createUnboundServer } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { PassThrough } from "node:stream";
|
||||
@@ -16,12 +16,21 @@ import {
|
||||
setupRunnerPrpWebSocketServer,
|
||||
} from "./runner-prp-ws.js";
|
||||
|
||||
// Routing-only fixtures expose a bound address; HTTP server tests exercise the
|
||||
// real listen/close and DNS boundaries without replacing this router's logic.
|
||||
function createBoundServer(port: number) {
|
||||
const server = createUnboundServer();
|
||||
vi.spyOn(server, "listening", "get").mockReturnValue(true);
|
||||
vi.spyOn(server, "address").mockReturnValue({ address: "127.0.0.1", family: "IPv4", port });
|
||||
setupRunnerPrpWebSocketServer(server);
|
||||
return server;
|
||||
}
|
||||
|
||||
describe("runner PRP websocket route", () => {
|
||||
afterEach(() => runnerPrpWebSocketInternals.resetForTests());
|
||||
|
||||
it("routes only the registered run and releases it by generation", async () => {
|
||||
const server = createServer();
|
||||
setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3210" });
|
||||
const server = createBoundServer(3210);
|
||||
const handleUpgrade = vi.fn();
|
||||
const runId = "00000000-0000-4000-8000-000000000777";
|
||||
const registration = await registerRunnerPrpAuthority({
|
||||
@@ -68,8 +77,7 @@ describe("runner PRP websocket route", () => {
|
||||
"404 Not Found",
|
||||
],
|
||||
])("fails closed for %s", (path, expectedStatus) => {
|
||||
const server = createServer();
|
||||
setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3211" });
|
||||
const server = createBoundServer(3211);
|
||||
const socket = new PassThrough();
|
||||
const writes: Buffer[] = [];
|
||||
socket.on("data", (chunk) => writes.push(Buffer.from(chunk)));
|
||||
@@ -79,8 +87,7 @@ describe("runner PRP websocket route", () => {
|
||||
});
|
||||
|
||||
it("does not replace an active registration", async () => {
|
||||
const server = createServer();
|
||||
setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3212" });
|
||||
const server = createBoundServer(3212);
|
||||
const runId = "00000000-0000-4000-8000-000000000779";
|
||||
const authority = {
|
||||
handleUpgrade: vi.fn(),
|
||||
@@ -98,8 +105,7 @@ describe("runner PRP websocket route", () => {
|
||||
});
|
||||
|
||||
it("routes live commands only to the newest generation", async () => {
|
||||
const server = createServer();
|
||||
setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3214" });
|
||||
const server = createBoundServer(3214);
|
||||
const oldRunId = "00000000-0000-4000-8000-000000000781";
|
||||
const newRunId = "00000000-0000-4000-8000-000000000782";
|
||||
const oldQueueCommand = vi.fn(() => ({
|
||||
@@ -166,8 +172,7 @@ describe("runner PRP websocket route", () => {
|
||||
});
|
||||
|
||||
it("queues one company-bound, idempotent runtime request resolution", async () => {
|
||||
const server = createServer();
|
||||
setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3213" });
|
||||
const server = createBoundServer(3213);
|
||||
const queueCommand = vi.fn(() => ({ commandId: "command-resolution-1" }));
|
||||
const runId = "00000000-0000-4000-8000-000000000780";
|
||||
const registration = await registerRunnerPrpAuthority({
|
||||
@@ -266,8 +271,7 @@ describe("runner PRP websocket route", () => {
|
||||
"rejects a retained old route after real authority rotation (cached=%s)",
|
||||
async (cached) => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "runner-route-rotation-"));
|
||||
const server = createServer();
|
||||
setupRunnerPrpWebSocketServer(server, { apiUrl: "http://127.0.0.1:3214" });
|
||||
const server = createBoundServer(3214);
|
||||
const identity = {
|
||||
runnerInstanceId: "runner-route-test",
|
||||
environmentLeaseId: "environment-route-test",
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
} from "../services/native-runtime/runtime-request-resolution-authority.js";
|
||||
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { registerLocalRuntimeApiServer, resolveLocalRuntimeApiUrl, runtimeApiInternals } from "../runtime-api.js";
|
||||
|
||||
const CONNECT_PATH_PREFIX = "/api/runner/v1/connect/";
|
||||
const UUID_PATTERN =
|
||||
@@ -40,7 +41,6 @@ interface RunnerPrpUpgradeRequest extends IncomingMessage {
|
||||
|
||||
const registrations = new Map<string, RegisteredAuthority>();
|
||||
const currentLiveAuthorities = new Map<string, CurrentLiveAuthority>();
|
||||
let loopbackOrigin: string | null = null;
|
||||
|
||||
function liveAuthorityKey(input: {
|
||||
readonly companyId: string;
|
||||
@@ -70,19 +70,11 @@ function rejectUpgrade(
|
||||
|
||||
export function setupRunnerPrpWebSocketServer(
|
||||
server: Server,
|
||||
options: { readonly apiUrl: string },
|
||||
_options?: { readonly apiUrl: string },
|
||||
): void {
|
||||
const apiUrl = new URL(options.apiUrl);
|
||||
if (!["http:", "https:"].includes(apiUrl.protocol)) {
|
||||
throw new Error("runner_prp_websocket_api_url_invalid");
|
||||
}
|
||||
apiUrl.protocol = apiUrl.protocol === "https:" ? "wss:" : "ws:";
|
||||
apiUrl.username = "";
|
||||
apiUrl.password = "";
|
||||
apiUrl.pathname = "";
|
||||
apiUrl.search = "";
|
||||
apiUrl.hash = "";
|
||||
loopbackOrigin = apiUrl.toString().replace(/\/$/, "");
|
||||
// Older launchers may still pass an advertised apiUrl. Only the actual
|
||||
// bound listener can authorize native transport, including ephemeral ports.
|
||||
registerLocalRuntimeApiServer(server);
|
||||
server.on(
|
||||
"upgrade",
|
||||
(request: IncomingMessage, socket: Duplex, head: Buffer) => {
|
||||
@@ -121,9 +113,9 @@ export async function registerRunnerPrpAuthority(input: {
|
||||
readonly runId: string;
|
||||
readonly authority: DurablePrpControlPlane;
|
||||
}): Promise<{ readonly connectUrl: string; release(): Promise<void> }> {
|
||||
if (loopbackOrigin === null) {
|
||||
throw new Error("runner_prp_websocket_server_not_configured");
|
||||
}
|
||||
const apiUrl = new URL(resolveLocalRuntimeApiUrl());
|
||||
apiUrl.protocol = "ws:";
|
||||
const loopbackOrigin = apiUrl.origin;
|
||||
if (!UUID_PATTERN.test(input.runId) || input.companyId.length === 0) {
|
||||
throw new Error("runner_prp_authority_binding_invalid");
|
||||
}
|
||||
@@ -321,6 +313,6 @@ export const runnerPrpWebSocketInternals = {
|
||||
resetForTests(): void {
|
||||
registrations.clear();
|
||||
currentLiveAuthorities.clear();
|
||||
loopbackOrigin = null;
|
||||
runtimeApiInternals.resetForTests();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Router } from "express";
|
||||
import { RUNNER_TOOL_SCOPE_TOKEN_HEADER } from "../vendor/paperclip-runner/index.js";
|
||||
import { forwardRemoteMcpRequest } from "../services/native-runtime/remote-mcp-relay.js";
|
||||
|
||||
export function nativeRunMcpRoutes() {
|
||||
const router = Router();
|
||||
router.all("/mcp/native-runs/:runId", async (req, res, next) => {
|
||||
try {
|
||||
if (req.method !== "POST") { res.setHeader("Allow", "POST"); res.sendStatus(405); return; }
|
||||
const scopeAuthorization = req.headers[RUNNER_TOOL_SCOPE_TOKEN_HEADER];
|
||||
const result = await forwardRemoteMcpRequest({
|
||||
runId: String(req.params.runId),
|
||||
authorization: req.headers.authorization,
|
||||
scopeAuthorization: typeof scopeAuthorization === "string" ? scopeAuthorization : undefined,
|
||||
body: req.body,
|
||||
mcpSessionId: typeof req.headers["mcp-session-id"] === "string" ? req.headers["mcp-session-id"] : undefined,
|
||||
});
|
||||
res.setHeader("Cache-Control", "no-store");
|
||||
if (result.mcpSessionId) res.setHeader("Mcp-Session-Id", result.mcpSessionId);
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
res.status(result.status).type("application/json").send(result.body);
|
||||
} catch (error) { next(error); }
|
||||
});
|
||||
return router;
|
||||
}
|
||||
@@ -1,4 +1,19 @@
|
||||
import os from "node:os";
|
||||
import type { Server } from "node:http";
|
||||
import { isIP } from "node:net";
|
||||
|
||||
const runtimeApiListeners = new Set<Server>();
|
||||
const registeredRuntimeApiListeners = new WeakSet<Server>();
|
||||
|
||||
/** Track listener ownership without treating configured or advertised URLs as authority. */
|
||||
export function registerLocalRuntimeApiServer(server: Server): void {
|
||||
if (!registeredRuntimeApiListeners.has(server)) {
|
||||
registeredRuntimeApiListeners.add(server);
|
||||
server.on("listening", () => runtimeApiListeners.add(server));
|
||||
server.on("close", () => runtimeApiListeners.delete(server));
|
||||
}
|
||||
if (server.listening) runtimeApiListeners.add(server);
|
||||
}
|
||||
|
||||
function normalizeHost(value: string | null | undefined): string {
|
||||
return (value ?? "").trim();
|
||||
@@ -63,6 +78,34 @@ function parsePublicOrigin(rawUrl: string | null | undefined): string | null {
|
||||
return origin === "null" ? null : origin;
|
||||
}
|
||||
|
||||
export function chooseLocalRuntimeApiUrl(input: {
|
||||
bindHost: string;
|
||||
port: number;
|
||||
}): string {
|
||||
const bindHost = normalizeHost(input.bindHost).replace(/^\[([^\]]+)\]$/, "$1");
|
||||
if (isIP(bindHost) === 0 || !Number.isInteger(input.port) || input.port < 1 || input.port > 65535) {
|
||||
throw new Error("local_runtime_api_listener_address_invalid");
|
||||
}
|
||||
const connectHost = bindHost === "::" ? "::1"
|
||||
: bindHost === "0.0.0.0" ? "127.0.0.1"
|
||||
: bindHost;
|
||||
return formatOrigin("http:", connectHost, input.port);
|
||||
}
|
||||
|
||||
export function resolveLocalRuntimeApiUrl(): string {
|
||||
const listeners = [...runtimeApiListeners].filter(server => server.listening);
|
||||
if (listeners.length !== 1) {
|
||||
throw new Error(listeners.length ? "local_runtime_api_listener_ambiguous" : "local_runtime_api_listener_unavailable");
|
||||
}
|
||||
const address = listeners[0]!.address();
|
||||
if (!address || typeof address === "string") throw new Error("local_runtime_api_listener_unavailable");
|
||||
return chooseLocalRuntimeApiUrl({ bindHost: address.address, port: address.port });
|
||||
}
|
||||
|
||||
export const runtimeApiInternals = {
|
||||
resetForTests(): void { runtimeApiListeners.clear(); },
|
||||
};
|
||||
|
||||
export function choosePrimaryRuntimeApiUrl(input: {
|
||||
authPublicBaseUrl?: string | null;
|
||||
allowedHostnames: string[];
|
||||
|
||||
@@ -17,7 +17,8 @@ import type { LifecycleAgent } from "../modules/agent-lifecycle/index.js";
|
||||
|
||||
export function assertHarnessTestPassed(result: AdapterEnvironmentTestResult) {
|
||||
const verified = result.checks.some(check => check.level === "info" &&
|
||||
(/hello_probe_(passed|succeeded)$/.test(check.code) || check.code === "ai_connection_api_key_reverified" || check.code === "copilot_metadata_verified"));
|
||||
(/hello_probe_(passed|succeeded)$/.test(check.code) || check.code === "ai_connection_api_key_reverified" || check.code === "copilot_metadata_verified"
|
||||
|| (result.adapterType === "paperclip_runner" && check.code === "cursor_cloud_account_ready")));
|
||||
const authenticationFailed = result.checks.some(check =>
|
||||
check.code === ADAPTER_AUTH_MISSING_CHECK_CODE || check.code === "COPILOT_AUTH_REQUIRED" || /_hello_probe_auth_required$/.test(check.code));
|
||||
const incomplete = !verified && (result.status === "warn" || result.checks.some(check => check.code.includes("hello_probe")));
|
||||
|
||||
@@ -33,6 +33,41 @@ afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); Object.definePropert
|
||||
describe("server-owned Codex runner selection", () => {
|
||||
beforeEach(() => { state.activeTemplate.mockReset().mockResolvedValue(null); });
|
||||
beforeEach(() => { state.disabled = []; state.overridden.clear(); state.settings = {}; state.getEnvironment.mockReset(); state.bindings.mockReset().mockResolvedValue([]); state.managedEnvironment.mockReset(); state.kubernetesEnvironment.mockReset().mockResolvedValue(null); state.ensureKubernetesEnvironment.mockReset(); state.ssh.mockReset().mockResolvedValue({ stdout: "Linux\nx86_64\n" }); state.sandboxQualification.mockReset().mockResolvedValue(null); state.resolveEnvironment.mockReset().mockResolvedValue({ driver: "ssh", config: {} }); });
|
||||
it("uses the supplied managed adapter snapshot for Cursor availability", () => {
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "synthetic-cloud-test-token");
|
||||
expect(() => agentRunnerAvailability("cursor_cloud", target)).toThrow("fresh adapter settings snapshot");
|
||||
expect(agentRunnerAvailability("cursor_cloud", target, []).supportedRunners).toContain("paperclip");
|
||||
for (const disabled of ["cursor_cloud", "paperclip_runner"]) {
|
||||
expect(agentRunnerAvailability("cursor_cloud", target, [disabled]).supportedRunners,
|
||||
`the current ${disabled} disable must affect Cursor selection`).not.toContain("paperclip");
|
||||
}
|
||||
});
|
||||
it("keeps Cursor Cloud legacy by default and converts only an equivalent explicitly selected profile", () => {
|
||||
const config = { model: "caller-model", repoUrl: "https://github.com/acme/repo", repoStartingRef: "feature", runtimeEnvType: "cloud", env: { CURSOR_API_KEY: { type: "secret_ref", secretId: "saved-key", version: "latest" } }, instructionsFilePath: "/assigned/AGENTS.md", autoCreatePR: false };
|
||||
expect(agentRunnerAvailability("cursor_cloud", target)).toEqual({ supportedRunners: ["paperclip", "legacy"], defaultRunner: "legacy" });
|
||||
expect(resolveNewAgentRunner({ adapterType: "cursor_cloud", adapterConfig: config, target })).toEqual({ adapterType: "cursor_cloud", adapterConfig: config });
|
||||
const converted = resolveNewAgentRunner({ adapterType: "cursor_cloud", adapterConfig: config, runner: "paperclip", target });
|
||||
expect(converted).toEqual({ adapterType: "paperclip_runner", adapterConfig: { model: config.model, repoUrl: config.repoUrl, repoRef: "feature", cloudEnvType: "cloud", env: config.env, instructionsFilePath: config.instructionsFilePath, autoCreatePR: false, provider: "cursor_cloud", lifecycleMode: "per_turn" } });
|
||||
expect(resolveNewAgentRunner({ ...converted, runner: "legacy", target })).toEqual({ adapterType: "cursor_cloud", adapterConfig: config });
|
||||
});
|
||||
it("rejects unsupported Cursor Cloud conversions and remote controllers without changing the original", () => {
|
||||
const config = { model: "caller-model", repoUrl: "https://github.com/acme/repo" };
|
||||
for (const patch of [{ promptTemplate: "custom instructions" }, { runtimeEnvType: "pool" }, { model: "" }]) {
|
||||
expect(() => resolveNewAgentRunner({ adapterType: "cursor_cloud", adapterConfig: { ...config, ...patch }, runner: "paperclip", target })).toThrow();
|
||||
}
|
||||
expect(config).toEqual({ model: "caller-model", repoUrl: "https://github.com/acme/repo" });
|
||||
expect(agentRunnerAvailability("cursor_cloud", { ...target, driver: "ssh" })).toEqual({ supportedRunners: ["legacy"], defaultRunner: "legacy" });
|
||||
expect(() => resolveNewAgentRunner({ adapterType: "cursor_cloud", adapterConfig: config, runner: "paperclip", target: { ...target, driver: "ssh" } })).toThrow("unavailable");
|
||||
});
|
||||
it("keeps legacy Cursor Cloud environment bindings and rejects their unsupported native conversion", () => {
|
||||
const config = { model: "caller-model", repoUrl: "https://github.com/acme/repo",
|
||||
env: { CURSOR_API_KEY: { type: "secret_ref", secretId: "saved-key", version: "latest" }, GH_TOKEN: { type: "secret_ref", secretId: "hosted-key", version: "latest" } } };
|
||||
expect(resolveNewAgentRunner({ adapterType: "cursor_cloud", adapterConfig: config, runner: "legacy", target }))
|
||||
.toEqual({ adapterType: "cursor_cloud", adapterConfig: config });
|
||||
expect(() => resolveNewAgentRunner({ adapterType: "cursor_cloud", adapterConfig: config, runner: "paperclip", target }))
|
||||
.toThrow("Configure hosted secrets in your Cursor Cloud environment");
|
||||
expect(config.env.GH_TOKEN).toEqual({ type: "secret_ref", secretId: "hosted-key", version: "latest" });
|
||||
});
|
||||
it.each(["x64", "arm64"])("keeps detected musl/unknown Linux %s legacy and preserves saved execution", architecture => {
|
||||
for (const libc of ["musl", "unknown"] as const) {
|
||||
const target = { driver: "local", platform: "linux", architecture, libc };
|
||||
|
||||
@@ -51,6 +51,11 @@ function runnerAdaptersAvailable(harness: string, driver: string, disabledTypes:
|
||||
}
|
||||
|
||||
export function agentRunnerAvailability(harness: string, target: RunnerTarget = localAgentRunnerTarget(), disabledTypes: string[] = localDisabledTypes()): AgentRunnerAvailability {
|
||||
if (harness === "cursor_cloud") {
|
||||
const supported = target.driver === "local" && runnerAdaptersAvailable(harness, target.driver, disabledTypes)
|
||||
&& (!target.platform || paperclipRunnerSupportsPlatform(harness, target.platform, target.architecture ?? "", target.libc, target.glibcVersion));
|
||||
return { supportedRunners: supported ? ["paperclip", "legacy"] : ["legacy"], defaultRunner: "legacy" };
|
||||
}
|
||||
if (target.runnerTasks || target.managedCloudImage) {
|
||||
return runnerAdaptersAvailable(harness, target.driver, disabledTypes)
|
||||
? { supportedRunners: target.runnerTasks ? ["paperclip"] : ["paperclip", "legacy"], defaultRunner: "paperclip" }
|
||||
@@ -184,6 +189,17 @@ function resolveAgentRunner(input: AgentRunnerSelection): { adapterType: string;
|
||||
const choice = input.runner ?? "auto";
|
||||
const useNative = choice === "paperclip" || (choice === "auto" && availability.defaultRunner === "paperclip");
|
||||
if (!useNative) {
|
||||
if (harness === "cursor_cloud") {
|
||||
if (!native) return { adapterType, adapterConfig: config };
|
||||
if (config.lifecycleMode !== undefined && config.lifecycleMode !== "per_turn") incompatible(["lifecycleMode"]);
|
||||
for (const [current, legacy] of [["cloudEnvType", "runtimeEnvType"], ["cloudEnvName", "runtimeEnvName"], ["repoRef", "repoStartingRef"], ["prUrl", "repoPullRequestUrl"]]) {
|
||||
if (config[current] !== undefined) config[legacy] = config[current];
|
||||
delete config[current];
|
||||
}
|
||||
if (config.cursorCloudTimeoutMs !== undefined) incompatible(["cursorCloudTimeoutMs"]);
|
||||
for (const key of ["provider", "lifecycleMode", "idleTimeoutMs"]) delete config[key];
|
||||
return { adapterType: "cursor_cloud", adapterConfig: config };
|
||||
}
|
||||
if (harness === "grok_local") {
|
||||
if (!native) return { adapterType, adapterConfig: config };
|
||||
if (config.acpxPermissionMode !== undefined && config.acpxPermissionMode !== "approve-all") incompatible(["acpxPermissionMode"]);
|
||||
@@ -234,6 +250,25 @@ function resolveAgentRunner(input: AgentRunnerSelection): { adapterType: string;
|
||||
? "Paperclip Runner is unavailable for this sandbox. Choose an immutable OCI image digest and run its environment connection probe to qualify the OS, architecture and libc, or select Legacy runner in Advanced."
|
||||
: "Paperclip Runner is unavailable for this harness and environment. Select Legacy runner in Advanced.", { code: "agent_runner_unavailable" });
|
||||
if (native) return { adapterType, adapterConfig: normalizeLegacyRunnerProvider(config) };
|
||||
if (harness === "cursor_cloud") {
|
||||
const unsupported = ["promptTemplate", "bootstrapPromptTemplate"].filter(key => typeof config[key] === "string" && config[key].trim());
|
||||
if (unsupported.length) incompatible(unsupported);
|
||||
for (const [legacy, current] of [["runtimeEnvType", "cloudEnvType"], ["runtimeEnvName", "cloudEnvName"], ["repoStartingRef", "repoRef"], ["repoPullRequestUrl", "prUrl"]]) {
|
||||
if (config[legacy] !== undefined) {
|
||||
if (config[current] !== undefined && config[current] !== config[legacy]) incompatible([legacy, current]);
|
||||
config[current] = config[legacy];
|
||||
}
|
||||
delete config[legacy];
|
||||
}
|
||||
config = { ...config, provider: "cursor_cloud", lifecycleMode: "per_turn" };
|
||||
if (input.setupOnly && !config.model) return { adapterType: "paperclip_runner", adapterConfig: config };
|
||||
try { resolvePaperclipRunnerNativeProviderInput({ backend: "cursor_cloud_api", adapterConfig: config }); }
|
||||
catch (error) {
|
||||
if (error instanceof PaperclipRunnerProviderProfileError) throw unprocessable(error.message, { code: error.code });
|
||||
throw error;
|
||||
}
|
||||
return { adapterType: "paperclip_runner", adapterConfig: config };
|
||||
}
|
||||
if (harness === "grok_local") {
|
||||
config = resolveGrokRunnerConfig(config);
|
||||
try { resolvePaperclipRunnerNativeProviderInput({ backend: "acpx_runtime", adapterConfig: config }); }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { claimNativeSessionResumptions } from "../native-runtime/native-finalization-reconciler.js";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { agents, agentWakeupRequests, caseHandoffs, cases, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issueComments, issues, nativeRunFinalizations } from "@paperclipai/db";
|
||||
import { authUsers, agents, agentWakeupRequests, caseHandoffs, cases, chatCompletionDeliveries, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issueComments, issueThreadInteractions, issues, nativeRunFinalizations } from "@paperclipai/db";
|
||||
import { eq, inArray, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js";
|
||||
@@ -8,6 +8,9 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro
|
||||
import { createPostgresWakeQueueAdapter } from "../../modules/wake-queue/adapters/postgres.js";
|
||||
import { createReleaseIssueExecution } from "../../modules/wake-queue/application/use-cases.js";
|
||||
import { createHeartbeatQueue, type HeartbeatQueueDependencies } from "./queue.js";
|
||||
import { settleConversationTurn } from "../agent-conversations.js";
|
||||
import { chatCompletionDeliveryService, recordChatCompletion, recordChatHandoff } from "../chat-completion-delivery.js";
|
||||
import { instanceSettingsService } from "../instance-settings.js";
|
||||
import { createHeartbeatRunControl } from "./run-control.js";
|
||||
import { callbacks as runControlCallbacks } from "./__tests__/run-control-fixtures.js";
|
||||
|
||||
@@ -111,6 +114,138 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => {
|
||||
expect(deps.budgets.getInvocationBlock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not admit recovery after the conversation settles between precheck and admission", async () => {
|
||||
const [user] = await db.insert(authUsers).values({
|
||||
id: "queue-conversation-race-user", name: "Conversation owner", email: "queue-race@paperclip.test",
|
||||
createdAt: new Date(), updatedAt: new Date(),
|
||||
}).onConflictDoUpdate({ target: authUsers.id, set: { name: "Conversation owner" } }).returning();
|
||||
const [company] = await db.insert(companies).values({ name: "Conversation race", issuePrefix: "CR" }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Chat agent",
|
||||
status: "idle", adapterType: "process", adapterConfig: {} }).returning();
|
||||
const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Answered conversation",
|
||||
assigneeAgentId: agent.id, responsibleUserId: user.id, conversationAgentId: agent.id,
|
||||
conversationUserId: user.id, conversationState: "active", status: "in_progress" }).returning();
|
||||
const [completed] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id,
|
||||
status: "succeeded", finishedAt: new Date(), invocationSource: "on_demand", triggerDetail: "manual",
|
||||
contextSnapshot: { issueId: issue.id, conversationSessionGeneration: issue.conversationSessionGeneration },
|
||||
}).returning();
|
||||
await db.insert(issueComments).values({ companyId: company.id, issueId: issue.id, authorAgentId: agent.id,
|
||||
createdByRunId: completed.id, origin: "comment", body: "The requested answer." });
|
||||
|
||||
const deps = callbacks(db);
|
||||
deps.getAgent.mockResolvedValue(agent);
|
||||
deps.instanceSettings.getExperimental.mockResolvedValue({ enableAgentChat: true } as Awaited<ReturnType<typeof deps.instanceSettings.getExperimental>>);
|
||||
// Admit through the normal transaction, but hold dispatch so no adapter runs.
|
||||
deps.getSchedulingSuppression.mockResolvedValue({ suppressed: true, reason: "task_drain" });
|
||||
deps.getSchedulingSuppression.mockResolvedValueOnce({ suppressed: false, reason: null });
|
||||
const getIssueExecutionContext = deps.getIssueExecutionContext;
|
||||
const outsideStates: Array<{ status: string; conversationState: string | null }> = [];
|
||||
deps.getIssueExecutionContext = async (...args) => {
|
||||
const current = await getIssueExecutionContext(...args);
|
||||
if (current) outsideStates.push({ status: current.status, conversationState: current.conversationState });
|
||||
return current;
|
||||
};
|
||||
let reached!: () => void;
|
||||
let release!: () => void;
|
||||
const atBarrier = new Promise<void>(resolve => { reached = resolve; });
|
||||
const admissionMayContinue = new Promise<void>(resolve => { release = resolve; });
|
||||
deps.budgets.getInvocationBlock.mockImplementationOnce(async () => {
|
||||
reached();
|
||||
await admissionMayContinue;
|
||||
return null;
|
||||
});
|
||||
const pending = createHeartbeatQueue(db, deps).enqueueWakeup(agent.id, {
|
||||
source: "automation", triggerDetail: "system", reason: "issue.continuation_recovery",
|
||||
requestedByActorType: "system", payload: { issueId: issue.id },
|
||||
contextSnapshot: { issueId: issue.id, retryOfRunId: completed.id, source: "issue.continuation_recovery" },
|
||||
});
|
||||
try {
|
||||
await atBarrier;
|
||||
expect(outsideStates).toEqual([{ status: "in_progress", conversationState: "active" }]);
|
||||
expect(await settleConversationTurn(db, completed)).toBe(true);
|
||||
expect((await db.select().from(issues).where(eq(issues.id, issue.id)))[0])
|
||||
.toMatchObject({ status: "in_review", conversationState: "waiting" });
|
||||
} finally { release(); }
|
||||
const admitted = await pending;
|
||||
expect(deps.executeRun).not.toHaveBeenCalled();
|
||||
expect(admitted).toBeNull();
|
||||
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agent.id))).map(run => run.id))
|
||||
.toEqual([completed.id]);
|
||||
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, agent.id)))
|
||||
.toHaveLength(0);
|
||||
});
|
||||
|
||||
async function waitingConversationFixture() {
|
||||
const [user] = await db.insert(authUsers).values({ id: "queue-conversation-owner", name: "Owner",
|
||||
email: "queue-owner@paperclip.test", createdAt: new Date(), updatedAt: new Date() })
|
||||
.onConflictDoUpdate({ target: authUsers.id, set: { name: "Owner" } }).returning();
|
||||
const [company] = await db.insert(companies).values({ name: "Waiting conversation", issuePrefix: "WC" }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Chat agent", status: "idle", adapterType: "process" }).returning();
|
||||
const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Waiting for input",
|
||||
assigneeAgentId: agent.id, responsibleUserId: user.id, conversationAgentId: agent.id,
|
||||
conversationUserId: user.id, conversationState: "waiting", status: "in_review" }).returning();
|
||||
const deps = callbacks(db);
|
||||
deps.getAgent.mockResolvedValue(agent);
|
||||
deps.instanceSettings.getExperimental.mockResolvedValue({ enableAgentChat: true } as Awaited<ReturnType<typeof deps.instanceSettings.getExperimental>>);
|
||||
deps.getSchedulingSuppression.mockResolvedValue({ suppressed: true, reason: "task_drain" });
|
||||
deps.getSchedulingSuppression.mockResolvedValueOnce({ suppressed: false, reason: null });
|
||||
await instanceSettingsService(db).updateExperimental({ enableAgentChat: true });
|
||||
return { user, company, agent, issue, deps, queue: createHeartbeatQueue(db, deps) };
|
||||
}
|
||||
|
||||
it.each(["comment", "interaction", "ordinary task"] as const)("preserves admission for a current %s", async cause => {
|
||||
const f = await waitingConversationFixture();
|
||||
const context: Record<string, unknown> = { issueId: f.issue.id, source: "issue.continuation_recovery" };
|
||||
const payload: Record<string, unknown> = { issueId: f.issue.id };
|
||||
if (cause === "comment") {
|
||||
const [comment] = await db.insert(issueComments).values({ companyId: f.company.id, issueId: f.issue.id,
|
||||
authorUserId: f.user.id, body: "A new question" }).returning();
|
||||
context.wakeCommentId = comment.id;
|
||||
payload.commentId = comment.id;
|
||||
} else if (cause === "interaction") {
|
||||
const [interaction] = await db.insert(issueThreadInteractions).values({ companyId: f.company.id,
|
||||
issueId: f.issue.id, createdByAgentId: f.agent.id, kind: "ask_user_questions", status: "answered",
|
||||
resolvedByUserId: f.user.id, resolvedAt: new Date(),
|
||||
payload: { version: 1, questions: [{ id: "q", prompt: "Continue?", selectionMode: "single",
|
||||
options: [{ id: "a", label: "Continue" }] }] },
|
||||
result: { version: 1, answers: [{ questionId: "q", optionIds: ["a"] }] } }).returning();
|
||||
Object.assign(context, { source: "issue.interaction.respond", interactionId: interaction.id,
|
||||
interactionKind: interaction.kind, interactionStatus: interaction.status });
|
||||
Object.assign(payload, { mutation: "interaction", interactionId: interaction.id });
|
||||
} else {
|
||||
await db.update(issues).set({ conversationAgentId: null, conversationUserId: null,
|
||||
conversationState: null, status: "in_progress" }).where(eq(issues.id, f.issue.id));
|
||||
}
|
||||
const admitted = await f.queue.enqueueWakeup(f.agent.id, { source: "automation", triggerDetail: "system",
|
||||
reason: cause === "ordinary task" ? "issue.continuation_recovery" : "issue_commented",
|
||||
requestedByActorType: "system", payload, contextSnapshot: context });
|
||||
expect(admitted).toMatchObject({ agentId: f.agent.id, status: "queued" });
|
||||
expect(f.deps.executeRun).not.toHaveBeenCalled();
|
||||
expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.agentId, f.agent.id)))
|
||||
.toHaveLength(1);
|
||||
});
|
||||
|
||||
it("delivers a real task completion to its waiting conversation", async () => {
|
||||
const f = await waitingConversationFixture();
|
||||
const [source] = await db.insert(heartbeatRuns).values({ companyId: f.company.id, agentId: f.agent.id,
|
||||
status: "succeeded", finishedAt: new Date(), contextSnapshot: { issueId: f.issue.id, conversationSessionGeneration: 0 } }).returning();
|
||||
const [task] = await db.insert(issues).values({ companyId: f.company.id, title: "Handed-off task",
|
||||
status: "in_progress", createdByAgentId: f.agent.id }).returning();
|
||||
await recordChatHandoff(db, task, source.id);
|
||||
const recorded = await db.transaction(async tx => {
|
||||
const [done] = await tx.update(issues).set({ status: "done" }).where(eq(issues.id, task.id)).returning();
|
||||
return recordChatCompletion(tx, task, done);
|
||||
});
|
||||
expect(recorded).toBe(true);
|
||||
await chatCompletionDeliveryService(db, { wakeup: (agentId, options) => f.queue.enqueueWakeup(agentId, options) }).sweepPending();
|
||||
const [delivery] = await db.select().from(chatCompletionDeliveries).where(eq(chatCompletionDeliveries.companyId, f.company.id));
|
||||
expect(delivery).toMatchObject({ status: "queued" });
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, delivery.targetRunId!));
|
||||
expect(run).toMatchObject({ agentId: f.agent.id, status: "queued" });
|
||||
expect(run.contextSnapshot).toMatchObject({ issueId: f.issue.id, wakeReason: "chat_task_completed" });
|
||||
expect(f.deps.executeRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
async function fixture(status = "running") {
|
||||
const [company] = await db.insert(companies).values({ name: "Queue module", issuePrefix: "QM" }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Queue agent", role: "engineer", status: "idle", adapterType: "process", adapterConfig: {} }).returning();
|
||||
|
||||
@@ -2281,6 +2281,11 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
triggerDetail,
|
||||
payload,
|
||||
});
|
||||
const hasIndependentConversationWakeCause = () => Boolean(
|
||||
wakeCommentId || opts.taskRetryRequestId ||
|
||||
hasInteractionContinuationWakeContext(enrichedContextSnapshot) ||
|
||||
reason === CHAT_COMPLETION_WAKE_REASON,
|
||||
);
|
||||
// Keep each request's own server-derived origin, including coalesced wakes.
|
||||
// A run's merged context cannot establish which caller authored one receipt.
|
||||
// Overwrite caller-supplied nested context rather than trusting it.
|
||||
@@ -2334,7 +2339,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
if (isConversationExecutionWake(conversation, reason ?? readNonEmptyString(enrichedContextSnapshot.wakeReason))) return null;
|
||||
if (agent.id !== conversation!.conversationAgentId) return null;
|
||||
if (!(await instanceSettings.getExperimental()).enableAgentChat) return null;
|
||||
if (!wakeCommentId && !opts.taskRetryRequestId && isWaitingConversation(conversation) && !hasInteractionContinuationWakeContext(enrichedContextSnapshot) && reason !== CHAT_COMPLETION_WAKE_REASON) return null;
|
||||
if (isWaitingConversation(conversation) && !hasIndependentConversationWakeCause()) return null;
|
||||
}
|
||||
}
|
||||
if (agent.adapterType === "paperclip_runner") {
|
||||
@@ -3224,6 +3229,12 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
return { kind: "skipped" as const };
|
||||
}
|
||||
|
||||
// Completion can settle the conversation while admission is outside
|
||||
// the issue lock. Recheck the current state before persisting a wake.
|
||||
if (isWaitingConversation(issue) && !hasIndependentConversationWakeCause()) {
|
||||
return { kind: "skipped" as const };
|
||||
}
|
||||
|
||||
if (taskRetryActorId) {
|
||||
await assertTaskRetryConversationAllowed(tx as unknown as Db, issue, taskRetryActorId);
|
||||
if (await retireSupersededTaskRetry(tx as unknown as Db, {
|
||||
|
||||
@@ -722,7 +722,8 @@ export async function selectHeartbeatRuntime(db: Db, input: HeartbeatRuntimeSele
|
||||
instructionWorkingCopy: instructionCopy ? { rootPath: instructionCopy.executionRoot, entryPath: instructionCopy.entryFile, ...(isAgentDirectoryCopy(instructionCopy) ? { kind: "agent_files" as const } : {}) } : undefined,
|
||||
});
|
||||
getNativeFreshSessionHandoff = nativeReviewRequest ? undefined : getFreshSessionHandoff;
|
||||
const nativeProviderConfig = nativeRuntimeResolution.profile.backend === "codex_app_server"
|
||||
const nativeProviderConfig = nativeRuntimeResolution.profile.backend === "cursor_cloud_api"
|
||||
|| nativeRuntimeResolution.profile.backend === "codex_app_server"
|
||||
|| (nativeRuntimeResolution.profile.backend === "acpx_runtime" && ["claude_local", "grok_local"].includes(agentHarnessType(agent.adapterType, parseObject(agent.adapterConfig))))
|
||||
|| nativeRuntimeResolution.profile.backend === "opencode_server"
|
||||
|| (nativeRuntimeResolution.profile.backend === "acpx_runtime"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -7,6 +7,51 @@ const run = { id: "run", agentId: "agent", status: "failed", scheduledRetryAt: n
|
||||
resultJson: { projectAccessDenied: { projectId: "22222222-2222-4222-8222-222222222222" } } };
|
||||
const agent = { status: "idle", pauseReason: null };
|
||||
|
||||
function operatorStoppedRun() {
|
||||
return { ...run, status: "cancelled", runtimeMode: "native" as const, companyId: issue.companyId,
|
||||
nativeIssueId: issue.id, errorCode: "cancelled", resultJson: {
|
||||
cancelledByActorType: "user", cancelledByUserId: "board",
|
||||
executionCancellation: { state: "requested" },
|
||||
nativeCancellation: { schema: "paperclip.native-cancellation.v1", runId: run.id,
|
||||
companyId: issue.companyId, issueId: issue.id, scope: "run",
|
||||
reasonCode: "cancellation_run_only", dispatched: true, dispatchState: "acknowledged",
|
||||
intentAuditId: "intent", acknowledgementAuditId: "ack" },
|
||||
} };
|
||||
}
|
||||
|
||||
describe("intentional native Stop presentation", () => {
|
||||
const workingIssue = { ...issue, status: "in_progress" };
|
||||
it("does not offer a failed-attempt Retry for an audited operator Stop that keeps its task in progress", () => {
|
||||
expect(projectTaskInterruption(workingIssue, { run: operatorStoppedRun(), agent, paused: false, approval: false }))
|
||||
.toMatchObject({ state: "resolved", canRetry: false, userAction: null });
|
||||
expect(workingIssue.status).toBe("in_progress");
|
||||
});
|
||||
|
||||
it.each([{ runId: "foreign" }, { companyId: "foreign" }, { issueId: "foreign" },
|
||||
{ dispatchState: "pending" }, { dispatched: false }, { acknowledgementAuditId: undefined },
|
||||
{ intentAuditId: 123 }, { acknowledgementAuditId: {} },
|
||||
{ scope: "subtree" }])("retains failure presentation without the matching operator receipt %j", change => {
|
||||
const stopped = operatorStoppedRun();
|
||||
expect(projectTaskInterruption(workingIssue, { run: { ...stopped, resultJson: { ...stopped.resultJson,
|
||||
nativeCancellation: { ...stopped.resultJson.nativeCancellation, ...change } } }, agent, paused: false, approval: false }))
|
||||
.toMatchObject({ state: "failed", canRetry: true });
|
||||
});
|
||||
|
||||
it("keeps pause, approval, non-user cancellation and new input authoritative", () => {
|
||||
const stopped = operatorStoppedRun();
|
||||
expect(projectTaskInterruption(workingIssue, { run: stopped, agent, paused: true, approval: false }))
|
||||
.toMatchObject({ state: "waiting_for_user", userAction: "resume" });
|
||||
expect(projectTaskInterruption(workingIssue, { run: stopped, agent, paused: false, approval: true }))
|
||||
.toMatchObject({ state: "waiting_for_user", userAction: "approval" });
|
||||
expect(projectTaskInterruption(workingIssue, { run: { ...stopped, resultJson: {
|
||||
...stopped.resultJson, cancelledByActorType: "system" } }, agent, paused: false, approval: false }))
|
||||
.toMatchObject({ state: "failed", canRetry: true });
|
||||
expect(projectTaskInterruption(workingIssue, { run: stopped, agent, paused: false, approval: false,
|
||||
wait: { id: "new-input", requestedAt: new Date() } }))
|
||||
.toMatchObject({ state: "working", canRetry: false });
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves a provider explanation on a failed task without changing retry authority", () => {
|
||||
const providerFailure = { schema: "paperclip.provider-failure.v1", provider: "anthropic", phase: "startup",
|
||||
category: "rate_limit", message: "API error: 429 This request would exceed your account's rate limit.",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { and, desc, eq, inArray, isNull, sql, type SQL } from "drizzle-orm";
|
||||
import { agents, agentWakeupRequests, approvals, companies, heartbeatRuns, issueApprovals, issueRecoveryActions,
|
||||
issues, issueTreeHoldMembers, issueTreeHolds, projects, type Db } from "@paperclipai/db";
|
||||
import { unionAll } from "drizzle-orm/pg-core";
|
||||
@@ -9,6 +9,7 @@ import { readSystemRecovery } from "./system-recovery-state.js";
|
||||
import { PROJECT_ACCESS_DENIED } from "./project-access-denial.js";
|
||||
import { authorizationService } from "./authorization.js";
|
||||
import { taskWorkspaceProjectRequirements } from "./task-workspace-access.js";
|
||||
import { isAcknowledgedNativeStop } from "./acknowledged-native-stop.js";
|
||||
import { createRunSecretRedactionRegistry } from "./run-secret-redaction.js";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import { redactCurrentUserText } from "../log-redaction.js";
|
||||
@@ -17,7 +18,7 @@ import { logger } from "../middleware/logger.js";
|
||||
type ProjectionIssue = Pick<typeof issues.$inferSelect, "id" | "companyId" | "status" | "assigneeAgentId" | "projectId">;
|
||||
type ProjectionRun = Pick<typeof heartbeatRuns.$inferSelect,
|
||||
"id" | "status" | "scheduledRetryAt" | "errorCode" | "livenessState" | "resultJson"> &
|
||||
Partial<Pick<typeof heartbeatRuns.$inferSelect, "agentId" | "error">>;
|
||||
Partial<Pick<typeof heartbeatRuns.$inferSelect, "agentId" | "error" | "companyId" | "nativeIssueId" | "runtimeMode">>;
|
||||
type ProjectionState = {
|
||||
run?: ProjectionRun;
|
||||
action?: typeof issueRecoveryActions.$inferSelect;
|
||||
@@ -32,6 +33,10 @@ type ProjectionState = {
|
||||
approval: boolean;
|
||||
};
|
||||
|
||||
function boundedJsonString(value: SQL, limit: number) {
|
||||
return sql`case when jsonb_typeof(${value}) = 'string' then left(${value} #>> '{}', ${limit}) else null end`;
|
||||
}
|
||||
|
||||
/** Recognize old persisted failures without displaying arbitrary run error text. */
|
||||
function deniedProjectId(issue: ProjectionIssue, run?: ProjectionRun): string | null | undefined {
|
||||
const historical = run?.errorCode === "setup_failed" && run.error === "Project is outside this low-trust boundary.";
|
||||
@@ -61,6 +66,10 @@ export function projectTaskInterruption(issue: ProjectionIssue, input: Projectio
|
||||
: [agent?.pauseReason, project?.pauseReason, company?.pauseReason].some(reason => reason === "budget" || reason === "budget_exceeded")
|
||||
? "budget" : input.paused || project?.pausedAt || agent?.status === "paused" || company?.status === "paused" ? "resume" : null;
|
||||
if (userAction) return { ...base, responsibility: "user", state: "waiting_for_user", userAction };
|
||||
// Intentional Stop is not an unsuccessful attempt. This is presentation only;
|
||||
// physical containment and pending cleanup keep their execution-side gates.
|
||||
if (!wait && run.runtimeMode === "native" && run.companyId === issue.companyId && run.nativeIssueId === issue.id
|
||||
&& isAcknowledgedNativeStop({ ...run, companyId: run.companyId, nativeIssueId: run.nativeIssueId })) return base;
|
||||
if (["running", "queued"].includes(run.status)) return { ...base, state: "working" };
|
||||
const deniedProject = deniedProjectId(issue, run);
|
||||
let projectAccess: TaskInterruptionPresentation["projectAccess"];
|
||||
@@ -111,12 +120,27 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i
|
||||
const projectIds = selected.flatMap(issue => issue.projectId ? [issue.projectId] : []);
|
||||
const [runs, waits, agentRows, projectRows, pauseRows, approvalRows, companyRows] = await Promise.all([
|
||||
db.select({ issueId: requestedIssueId, id: heartbeatRuns.id, status: heartbeatRuns.status,
|
||||
agentId: heartbeatRuns.agentId, agentAdapter: agents.adapterType,
|
||||
agentId: heartbeatRuns.agentId, companyId: heartbeatRuns.companyId,
|
||||
nativeIssueId: heartbeatRuns.nativeIssueId, runtimeMode: heartbeatRuns.runtimeMode,
|
||||
agentAdapter: agents.adapterType,
|
||||
error: sql<string | null>`case when ${heartbeatRuns.errorCode} = 'setup_failed'
|
||||
and ${heartbeatRuns.error} = 'Project is outside this low-trust boundary.' then ${heartbeatRuns.error} else null end`,
|
||||
errorCode: heartbeatRuns.errorCode, livenessState: heartbeatRuns.livenessState, scheduledRetryAt: heartbeatRuns.scheduledRetryAt,
|
||||
resultJson: sql<Record<string, unknown>>`jsonb_build_object('configurationIncomplete', ${heartbeatRuns.resultJson}->'configurationIncomplete',
|
||||
'projectAccessDenied', ${heartbeatRuns.resultJson}->'projectAccessDenied',
|
||||
'cancelledByActorType', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'cancelledByActorType'`, 32)},
|
||||
'cancelledByUserId', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'cancelledByUserId'`, 160)},
|
||||
'nativeCancellation', jsonb_build_object(
|
||||
'schema', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'nativeCancellation'->'schema'`, 64)},
|
||||
'runId', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'nativeCancellation'->'runId'`, 160)},
|
||||
'companyId', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'nativeCancellation'->'companyId'`, 160)},
|
||||
'issueId', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'nativeCancellation'->'issueId'`, 160)},
|
||||
'scope', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'nativeCancellation'->'scope'`, 32)},
|
||||
'reasonCode', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'nativeCancellation'->'reasonCode'`, 64)},
|
||||
'dispatchState', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'nativeCancellation'->'dispatchState'`, 32)},
|
||||
'dispatched', coalesce(${heartbeatRuns.resultJson}->'nativeCancellation'->'dispatched' = 'true'::jsonb, false),
|
||||
'intentAuditId', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'nativeCancellation'->'intentAuditId'`, 160)},
|
||||
'acknowledgementAuditId', ${boundedJsonString(sql`${heartbeatRuns.resultJson}->'nativeCancellation'->'acknowledgementAuditId'`, 160)}),
|
||||
'providerFailure', ${heartbeatRuns.resultJson}->'providerFailure')`,
|
||||
}).from(requested).innerJoinLateral(latestRuns, sql`true`).innerJoin(heartbeatRuns, and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, latestRuns.id)))
|
||||
.leftJoin(agents, and(eq(agents.companyId, heartbeatRuns.companyId), eq(agents.id, heartbeatRuns.agentId)))
|
||||
|
||||
+8
@@ -10,6 +10,7 @@
|
||||
type RunnerModule = typeof import("@paperclipai/paperclip-runner");
|
||||
|
||||
export type {
|
||||
NativeCursorCloudConfig,
|
||||
AcpxCandidateAdmission,
|
||||
DotHarnessDriver,
|
||||
DotAssignment,
|
||||
@@ -87,6 +88,8 @@ const sourceUrl = new URL(
|
||||
);
|
||||
const runner = (await import(sourceUrl.href)) as RunnerModule;
|
||||
|
||||
export const CURSOR_CLOUD_DEFAULT_TIMEOUT_MS = runner.CURSOR_CLOUD_DEFAULT_TIMEOUT_MS;
|
||||
export const RUNNER_TOOL_SCOPE_TOKEN_HEADER = runner.RUNNER_TOOL_SCOPE_TOKEN_HEADER;
|
||||
export const DurablePrpControlPlane = runner.DurablePrpControlPlane;
|
||||
export const providerFailureFromError = runner.providerFailureFromError;
|
||||
export const decodeDurablePrpCheckpoint = runner.decodeDurablePrpCheckpoint;
|
||||
@@ -205,3 +208,8 @@ export const configuredEnvironment = runner.configuredEnvironment;
|
||||
export const probeNativeRunnerEnvironment = runner.probeNativeRunnerEnvironment;
|
||||
|
||||
export const resolveGrokDisableWebSearch = runner.resolveGrokDisableWebSearch;
|
||||
|
||||
export const CursorCloudClient = runner.CursorCloudClient;
|
||||
export const parseNativeCursorCloudConfig = runner.parseNativeCursorCloudConfig;
|
||||
|
||||
export const archiveCursorCloudSessionCheckpoint = runner.archiveCursorCloudSessionCheckpoint;
|
||||
Reference in new issue
Block a user