mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-04 11:01:16 +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
@@ -20,6 +20,7 @@ import {
|
||||
} from "../commands/test-drive.js";
|
||||
import type { RunOptions, StartedServer } from "../commands/run.js";
|
||||
import type { PaperclipConfig } from "../config/schema.js";
|
||||
import { PaperclipApiClient } from "../client/http.js";
|
||||
|
||||
const ORIGINAL_ENV = { ...process.env };
|
||||
const cleanupDirectories: string[] = [];
|
||||
@@ -477,12 +478,41 @@ describe("test-drive worktree setting reconciliation", () => {
|
||||
|
||||
describe("test-drive foreground lifecycle", () => {
|
||||
const server: StartedServer = {
|
||||
apiUrl: "http://127.0.0.1:3100/api",
|
||||
apiUrl: "http://127.0.0.1:3100",
|
||||
databaseUrl: "postgres://embedded",
|
||||
host: "127.0.0.1",
|
||||
listenPort: 3100,
|
||||
};
|
||||
|
||||
it.each([
|
||||
{ host: "127.0.0.1", listenPort: 3107, origin: "http://127.0.0.1:3107" },
|
||||
{ host: "::1", listenPort: 43210, origin: "http://[::1]:43210" },
|
||||
])("bootstraps and opens the selected local listener when $host advertises a public callback URL", async ({ host, listenPort, origin }) => {
|
||||
process.env.PAPERCLIP_HOME = "/tmp/test-drive-public-callback";
|
||||
process.env.PAPERCLIP_INSTANCE_ID = "default";
|
||||
process.env.PAPERCLIP_IN_WORKTREE = "false";
|
||||
const publicServer = { ...server, host, listenPort, apiUrl: "https://callbacks.example.test" };
|
||||
const requests: string[] = [];
|
||||
vi.spyOn(globalThis, "fetch").mockImplementation(async input => {
|
||||
const url = String(input);
|
||||
requests.push(url);
|
||||
return url === `${origin}/api/companies`
|
||||
? new Response(JSON.stringify([company("existing", "Existing")]), { status: 200 })
|
||||
: new Response(JSON.stringify({ error: "Unexpected bootstrap URL" }), { status: 404 });
|
||||
});
|
||||
const openBrowser = vi.fn(async () => true);
|
||||
|
||||
await testDriveCommand({ dataDir: "/tmp/test-drive-public-callback" }, {
|
||||
run: async options => options.afterStart?.(publicServer),
|
||||
createApi: apiBase => new PaperclipApiClient({ apiBase }),
|
||||
openBrowser,
|
||||
});
|
||||
|
||||
expect(requests).toEqual([`${origin}/api/companies`]);
|
||||
expect(openBrowser).toHaveBeenCalledExactlyOnceWith(origin);
|
||||
expect(publicServer.apiUrl).toBe("https://callbacks.example.test");
|
||||
});
|
||||
|
||||
it("skips service-manager integration for an auto-created directory and opens after initialization", async () => {
|
||||
process.env.PAPERCLIP_HOME = "/tmp/test-drive-lifecycle";
|
||||
process.env.PAPERCLIP_INSTANCE_ID = "default";
|
||||
|
||||
@@ -407,7 +407,8 @@ export async function bootstrapTestDrive(input: {
|
||||
}
|
||||
|
||||
function dashboardUrl(server: StartedServer): string {
|
||||
return server.apiUrl.replace(/\/api\/?$/, "");
|
||||
const host = server.host.includes(":") && !server.host.startsWith("[") ? `[${server.host}]` : server.host;
|
||||
return `http://${host}:${server.listenPort}`;
|
||||
}
|
||||
|
||||
export async function testDriveCommand(
|
||||
@@ -451,7 +452,8 @@ export async function testDriveCommand(
|
||||
skipServiceManagerCheck: !options.dataDir?.trim(),
|
||||
introLabel: "paperclipai test-drive",
|
||||
afterStart: async (server) => {
|
||||
const api = dependencies.createApi(server.apiUrl);
|
||||
const url = dashboardUrl(server);
|
||||
const api = dependencies.createApi(url);
|
||||
const result = await bootstrapTestDrive({
|
||||
api,
|
||||
options,
|
||||
@@ -472,7 +474,6 @@ export async function testDriveCommand(
|
||||
p.log.success("Run tasks in this worktree is enabled for this instance.");
|
||||
}
|
||||
|
||||
const url = dashboardUrl(server);
|
||||
if (options.browser === false) {
|
||||
p.log.success(`Paperclip is ready at ${pc.cyan(url)}.`);
|
||||
return;
|
||||
|
||||
@@ -51,6 +51,13 @@ existing campaigns. Private Cloud bundles are rejected. The output contains
|
||||
only index HTML and history/pointer JSON; it does not upload evidence or change
|
||||
retained campaign bundles.
|
||||
|
||||
The explicit-only [Cursor Cloud native cells](../tests/runner-e2e/README.md)
|
||||
cover task/artifact delivery, same-agent follow-up, active-run UI Stop and
|
||||
semantic Plan revision/approval from a local controller. They require explicit
|
||||
model/repository/key and a callback-only
|
||||
public HTTPS proxy. Controlled tests and discovery do not qualify hosted work.
|
||||
These cells remain private because raw evidence can contain provider session IDs.
|
||||
|
||||
The explicit-only [chat feature evals](../tests/runner-e2e/CHAT-FEATURES.md) promote
|
||||
two natural-language task scenarios into local native Codex subscription and
|
||||
OpenCode Product E2E cells. They
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -160,6 +160,21 @@ remaining operations before qualifying the whole capability.
|
||||
Gaps: Environment test path checks creation/configuration policy; missing provider auth
|
||||
must use its owner setup flow.
|
||||
|
||||
Scoped experimental Cursor Cloud native support uses the existing configuration
|
||||
and environment-test APIs with an explicit `cursor_cloud` Runner provider. Legacy
|
||||
records retain their runtime. Native admission requires a local controller,
|
||||
per-turn lifecycle, exact model, selected `CURSOR_API_KEY`, and repository or named
|
||||
Cloud environment. Hosted semantic calls use
|
||||
`POST /mcp/native-runs/{runId}` with a separate expiring run capability. The relay
|
||||
checks the current source company/agent/task/run and authority epoch, then forwards
|
||||
to the provider bridge and normal PRP/Core tool policy. It grants no board or
|
||||
cross-company access. Source/control evidence:
|
||||
[runtime helper](../../server/src/services/native-runtime/cursor-cloud-runtime.ts),
|
||||
[relay regressions](../../server/src/services/native-runtime/remote-mcp-relay.test.ts)
|
||||
and [provider client](../../packages/paperclip-runner/src/drivers/cursor-cloud/cloud-client.test.ts).
|
||||
Live provider authorization and task qualification remain `not-run`; see the
|
||||
[acceptance ledger](../../doc/plans/2026-10-28-cursor-cloud-native-runner.md).
|
||||
|
||||
Scoped source-only Claude CLI preparation: both the selected environment test
|
||||
and normal CLI execution use
|
||||
[versioned sandbox preparation](../../packages/adapters/claude-local/src/server/sandbox-cli-version.ts).
|
||||
|
||||
@@ -98,6 +98,16 @@ removing, or overriding adapters remains platform-managed.
|
||||
|
||||
Automated: [adapter validation routes](../../server/src/__tests__/agent-adapter-validation-routes.test.ts) and [model refresh](../../server/src/__tests__/adapter-model-refresh-routes.test.ts) cover server behavior.
|
||||
|
||||
Cursor Cloud keeps Legacy as its automatic default. Choose Paperclip Runner
|
||||
explicitly under Advanced for experimental native support on a local controller.
|
||||
Select an exact model, bind a Cursor API key, and configure the repository or
|
||||
named Cloud environment. Save/reopen and Test must retain those choices. Test
|
||||
requires a reachable HTTPS callback origin and checks account/model access without
|
||||
starting a paid prompt. Cursor owns native shell permissions and does not
|
||||
independently acknowledge the effective model. Use the
|
||||
[qualification ledger](../../doc/plans/2026-10-28-cursor-cloud-native-runner.md)
|
||||
to distinguish local controls from live task, continuation, Stop and artifact proof.
|
||||
|
||||
Claude native setup uses the existing Anthropic API-key or subscription connection
|
||||
flow. Record the selected account separately from successful execution; unavailable
|
||||
models/authentication and unsupported Legacy-only options must fail visibly.
|
||||
|
||||
@@ -68,6 +68,7 @@ describe("Paperclip Runner permission defaults", () => {
|
||||
});
|
||||
|
||||
it("recognizes only exact provider identifiers", () => {
|
||||
expect(isPaperclipRunnerProvider("cursor_cloud")).toBe(true);
|
||||
expect(isPaperclipRunnerProvider("codex")).toBe(true);
|
||||
expect(isPaperclipRunnerProvider("opencode")).toBe(true);
|
||||
expect(isPaperclipRunnerProvider("claude_managed")).toBe(true);
|
||||
@@ -78,12 +79,18 @@ describe("Paperclip Runner permission defaults", () => {
|
||||
});
|
||||
|
||||
it("keeps managed provider permissions under the qualified profile", () => {
|
||||
expect(resolvePaperclipRunnerPermissionMode("cursor_cloud", "never")).toBe("provider-managed");
|
||||
expect(resolvePaperclipRunnerPermissionMode("claude_managed", "never"))
|
||||
.toBe("provider-managed");
|
||||
expect(resolvePaperclipRunnerPermissionMode("aws_agentcore", "approve-all"))
|
||||
.toBe("provider-managed");
|
||||
});
|
||||
|
||||
it("converts Cursor Cloud without substituting an implicit model or adding command permission controls", () => {
|
||||
expect(paperclipRunnerTransitionConfig("cursor_cloud", "custom-model")).toEqual({ provider: "cursor_cloud", model: "custom-model", lifecycleMode: "per_turn" });
|
||||
expect(paperclipRunnerTransitionConfig("cursor_cloud", undefined)).toEqual({ provider: "cursor_cloud", model: "", lifecycleMode: "per_turn" });
|
||||
});
|
||||
|
||||
it("uses the Codex default for missing or blank models", () => {
|
||||
expect(resolvePaperclipRunnerModel("codex", undefined)).toBe(
|
||||
PAPERCLIP_RUNNER_DEFAULT_MODELS.codex,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export type PaperclipRunnerProvider =
|
||||
"codex" | "opencode" | "claude_managed" | "aws_agentcore" | "acpx" | "openai_dot" | "grok_bot" | "muse";
|
||||
"codex" | "opencode" | "claude_managed" | "aws_agentcore" | "acpx" | "openai_dot" | "grok_bot" | "muse" | "cursor_cloud";
|
||||
|
||||
export type CodexPermissionMode = "never" | "on-request" | "untrusted";
|
||||
export type OpenCodePermissionMode = "allow" | "ask" | "deny";
|
||||
@@ -106,6 +106,7 @@ export const PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES = {
|
||||
grok_bot: { configurable: false, defaultMode: "provider-managed", options: [], description: "Grok Bot uses first-party Paperclip tools and retains its native apps. Grok manages its model; spending, live steering, provider transcript streaming and remote interruption are unavailable." },
|
||||
muse: { configurable: false, defaultMode: "provider-managed", options: [], description: "Muse uses the admitted Paperclip tool catalog and its own approved tools. Provider usage is unavailable and remote stop is best effort." },
|
||||
openai_dot: { configurable: false, defaultMode: "provider-managed", options: [], description: "Dot uses the admitted Paperclip tool catalog. OpenAI manages its model and other tools; provider usage and global interruption are unavailable." },
|
||||
cursor_cloud: { configurable: false, defaultMode: "provider-managed", options: [], description: "Cursor manages commands and files in its cloud environment. Assigned Paperclip tools retain company permissions. Provider command approvals and verified model identity are unavailable." },
|
||||
acpx: {
|
||||
configurable: true,
|
||||
configKey: "acpxPermissionMode",
|
||||
@@ -150,7 +151,7 @@ export function isPaperclipRunnerProvider(
|
||||
value === "opencode" ||
|
||||
value === "claude_managed" ||
|
||||
value === "aws_agentcore" ||
|
||||
value === "acpx" || value === "openai_dot" || value === "grok_bot" || value === "muse"
|
||||
value === "acpx" || value === "openai_dot" || value === "grok_bot" || value === "muse" || value === "cursor_cloud"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -204,6 +205,9 @@ export function paperclipRunnerTransitionConfig(
|
||||
previousModel: unknown,
|
||||
providerOverride?: unknown,
|
||||
): Record<string, unknown> {
|
||||
if (previousAdapterType === "cursor_cloud" && (providerOverride === undefined || providerOverride === "cursor_cloud")) {
|
||||
return { provider: "cursor_cloud", model: typeof previousModel === "string" ? previousModel.trim() : "", lifecycleMode: "per_turn" };
|
||||
}
|
||||
const previousProvider =
|
||||
(["claude_local", "pi_local", "grok_local"].includes(previousAdapterType))
|
||||
? "acpx"
|
||||
|
||||
@@ -50,6 +50,17 @@ it("keeps Pi draft models empty and preserves saved native Pi settings", () => {
|
||||
expect(normalizePaperclipRunnerAdapterConfig("paperclip_runner", saved)).toMatchObject(saved);
|
||||
});
|
||||
|
||||
it("preserves Cursor Cloud settings without injecting Codex permission defaults", () => {
|
||||
const config = { provider: "cursor_cloud", model: "caller-model", repoUrl: "https://github.com/acme/repo",
|
||||
env: { CURSOR_API_KEY: { type: "secret_ref", secretId: "saved-key", version: "latest" } } };
|
||||
const saved = normalizePaperclipRunnerAdapterConfig("paperclip_runner", config);
|
||||
expect(saved).toMatchObject({ ...config, lifecycleMode: "per_turn" });
|
||||
expect(saved).not.toHaveProperty("codexPermissionMode");
|
||||
expect(normalizePaperclipRunnerAdapterConfig("paperclip_runner", saved)).toEqual(saved);
|
||||
expect(normalizePaperclipRunnerAdapterConfig("paperclip_runner", { ...config, codexPermissionMode: "never" }))
|
||||
.toHaveProperty("codexPermissionMode", "never");
|
||||
});
|
||||
|
||||
it.each([undefined, "", "kimi-for-coding"])("keeps Kimi draft model selection explicit: %s", model => {
|
||||
const config = { provider: "acpx", acpxAgent: "kimi", ...(model === undefined ? {} : { model }),
|
||||
acpxPermissionMode: "approve-reads", lifecycleMode: "warm" };
|
||||
|
||||
@@ -4284,7 +4284,7 @@ export function normalizePaperclipRunnerAdapterConfig(
|
||||
): Record<string, unknown> {
|
||||
if (adapterType !== "paperclip_runner") return config;
|
||||
config = normalizeLegacyRunnerProvider(config);
|
||||
if (config.provider === "openai_dot" || config.provider === "muse") {
|
||||
if (config.provider === "openai_dot" || config.provider === "muse" || config.provider === "cursor_cloud") {
|
||||
return normalizePaperclipOperationalSkillPreference(adapterType, { lifecycleMode: "per_turn", ...config });
|
||||
}
|
||||
const next: Record<string, unknown> = {
|
||||
|
||||
@@ -36,6 +36,16 @@ function makeValues(overrides: Partial<CreateConfigValues> = {}): CreateConfigVa
|
||||
}
|
||||
|
||||
describe("buildCodexLocalConfig", () => {
|
||||
it("round-trips native Cursor Cloud fields and credentials without adding local command permission defaults", () => {
|
||||
const cloud = { provider: "cursor_cloud", repoUrl: "https://github.com/acme/repo", repoRef: "feature", cloudEnvType: "cloud", autoCreatePR: true };
|
||||
const env = { CURSOR_API_KEY: { type: "secret_ref" as const, secretId: "company-key", version: "latest" as const } };
|
||||
const first = buildPaperclipRunnerConfig(makeValues({ model: "caller-custom-model", envBindings: env, adapterSchemaValues: cloud }));
|
||||
expect(first).toEqual({ ...cloud, model: "caller-custom-model", env, lifecycleMode: "per_turn" });
|
||||
const reopened = buildPaperclipRunnerConfig(makeValues({ model: "", envBindings: env, adapterSchemaValues: first }));
|
||||
expect(reopened).toEqual(first);
|
||||
expect(() => buildPaperclipRunnerConfig(makeValues({ model: "", adapterSchemaValues: cloud }))).toThrow("explicit model");
|
||||
});
|
||||
|
||||
it("round-trips qualified Kimi Code with its exact selected model", () => {
|
||||
const first = buildPaperclipRunnerConfig(makeValues({ model: "explicit-kimi-model", adapterSchemaValues: { provider: "acpx", acpxAgent: "kimi" } }));
|
||||
const reopened = buildPaperclipRunnerConfig(makeValues({ model: "", adapterSchemaValues: JSON.parse(JSON.stringify(first)) }));
|
||||
|
||||
@@ -111,6 +111,18 @@ export function buildPaperclipRunnerConfig(v: CreateConfigValues, context?: {
|
||||
return { provider, lifecycleMode: "per_turn", allowUnmeteredProvider: schemaValues.allowUnmeteredProvider === true, dotWorkspaceAccess: schemaValues.dotWorkspaceAccess === true, dotAttachmentAccess: schemaValues.dotAttachmentAccess === true,
|
||||
...(typeof schemaValues.dotBindingId === "string" ? { dotBindingId: schemaValues.dotBindingId } : {}) };
|
||||
}
|
||||
if (provider === "cursor_cloud") {
|
||||
const model = typeof config.model === "string" && config.model.trim()
|
||||
? config.model.trim() : typeof schemaValues.model === "string" ? schemaValues.model.trim() : "";
|
||||
if (!model) throw new Error("Cursor Cloud requires an explicit model before saving.");
|
||||
if (v.promptTemplate?.trim() || v.bootstrapPrompt?.trim()) throw new Error("Cursor Cloud with Paperclip Runner uses assigned instructions. Remove custom prompt templates before saving.");
|
||||
const cloudKeys = ["repoUrl", "repoRef", "prUrl", "cloudEnvType", "cloudEnvName", "runtimeEnvType", "runtimeEnvName", "repoStartingRef", "repoPullRequestUrl", "workOnCurrentBranch", "autoCreatePR", "skipReviewerRequest", "cursorCloudTimeoutMs"];
|
||||
return { provider, model, lifecycleMode: "per_turn",
|
||||
...(config.instructionsFilePath ? { instructionsFilePath: config.instructionsFilePath } : {}),
|
||||
...(config.env ? { env: config.env } : {}),
|
||||
...Object.fromEntries(cloudKeys.filter(key => schemaValues[key] !== undefined).map(key => [key, schemaValues[key]])),
|
||||
};
|
||||
}
|
||||
const selectedAcpxProfile = PAPERCLIP_RUNNER_ACPX_PROFILES.find(profile => profile.value === schemaValues.acpxAgent);
|
||||
const candidate = context?.candidateHarnesses?.find(candidate => candidate.agent === schemaValues.acpxAgent);
|
||||
const selectedModel = typeof v.model === "string" && v.model ? v.model : schemaValues.model;
|
||||
|
||||
@@ -215,19 +215,36 @@ the task waits for the next instruction. See the
|
||||
[Cursor release report](../../doc/plans/2026-10-03-cursor-production-readiness.md).
|
||||
|
||||
Cursor Cloud is a separate experimental native provider (`cursor_cloud`, driver
|
||||
`cursor_cloud_api`). Configure `NativeProviderConfig` with `kind: "cursor_cloud"`,
|
||||
an explicit `model`, and a `cursorCloud` object using the
|
||||
`paperclip.cursor-cloud.config.v1` schema. That object requires either a repository
|
||||
list or a named Cursor Cloud environment. The launch environment supplies
|
||||
`CURSOR_API_KEY` and the scoped tool relay configuration. Native Cloud supports
|
||||
per-turn Runner lifecycle only; Cursor executes tools in its hosted VM. Configure
|
||||
hosted shell secrets in the Cursor Cloud environment.
|
||||
`cursor_cloud_api`). In Cursor Cloud agent setup, select **Paperclip Runner** under
|
||||
Advanced, bind `CURSOR_API_KEY`, choose an explicit model, and supply a repository
|
||||
or named Cursor Cloud environment. Existing Cursor Cloud agents keep their saved
|
||||
Legacy selection. The initial controller target is local; Cursor executes tools
|
||||
in its hosted VM. Native Cloud requires per-turn Runner lifecycle.
|
||||
For direct Runner use, configure `NativeProviderConfig` with
|
||||
`kind: "cursor_cloud"`, an explicit `model`, and a `cursorCloud` object using
|
||||
`paperclip.cursor-cloud.config.v1`. Supply a repository list or a named Cursor
|
||||
Cloud environment; the launch environment provides `CURSOR_API_KEY` and the
|
||||
scoped tool relay configuration.
|
||||
Agent environment bindings support `CURSOR_API_KEY` only. Configure hosted shell
|
||||
secrets in the Cursor Cloud environment. Other selected process variables are
|
||||
rejected; they are not silently omitted from the hosted run.
|
||||
|
||||
Paperclip native tools use the injected `paperclip` MCP server with
|
||||
controller-managed authentication; they need no Paperclip REST credentials in the
|
||||
Cloud VM.
|
||||
Cloud VM. Cursor also loads account and team MCP servers. The driver directs
|
||||
Paperclip operations to the run-bound server; Cursor controls the other account
|
||||
tools. See [Cloud MCP configuration](https://cursor.com/docs/sdk/typescript).
|
||||
|
||||
The hosted agent needs a reachable HTTPS callback origin from the server's public
|
||||
URL configuration (for example `PAPERCLIP_PUBLIC_URL`). Forward only
|
||||
`POST /mcp/native-runs/:runId` through a callback proxy; keep the local trusted
|
||||
application private. The callback requires an expiring run capability and current
|
||||
company/run authority, then passes tool calls through normal PRP/Core dispatch.
|
||||
**Test** checks configuration, callback reachability and account/model access
|
||||
without launching a paid prompt. A passing Test does not qualify task completion.
|
||||
|
||||
Cloud v1 provides no independent acknowledgment of the effective model or exact
|
||||
instruction digest. Runner records submitted inputs and treats this support as
|
||||
instruction digest. Paperclip records submitted inputs and treats this support as
|
||||
experimental. Cursor manages its own shell permissions; native permission,
|
||||
question and plan callbacks and fixed per-run dollar limits are unavailable.
|
||||
Paperclip planning tasks retain their pinned planning context and existing tool
|
||||
@@ -235,14 +252,21 @@ restrictions while using Cloud's default harness. Plan documents and
|
||||
revision-bound Paperclip confirmations use the normal semantic tools; this does
|
||||
not enable Cursor's native Plan API or native plan-decision callbacks.
|
||||
Production usage and dollar cost remain unknown; the Cloud usage API is not yet
|
||||
projected through the Runner facade. Stop cancels the exact Cloud run and requires
|
||||
a terminal provider receipt. Unknown cancellation remains unconfirmed. Recovery
|
||||
reuses the saved Agent/Run and stream cursor, keeps the original deadline, and does
|
||||
not replay an ambiguous paid mutation. Tool callbacks require the capability of
|
||||
the current turn, including fresh MCP initialization. Recovery retains that
|
||||
capability in the private checkpoint. Older active checkpoints without it permit
|
||||
cleanup, but cannot resume tool access. Read-only observation retries transient
|
||||
stream failures within the original deadline, with bounded backoff.
|
||||
projected through the Runner facade.
|
||||
Budget policies can block further work after an unpriced run. If you accept
|
||||
unknown charges, clear **Block new work when usage has no reliable price** in
|
||||
both company and agent policies under **Costs → Budgets → Advanced settings**.
|
||||
Known-cost hard stops remain active, but cannot cap charges Cursor does not report.
|
||||
Paperclip semantic tools use their existing authorization. Stop cancels the exact
|
||||
Cloud run and requires a terminal provider receipt. Unknown cancellation remains
|
||||
unconfirmed. Recovery reuses the saved Agent/Run and stream cursor, keeps the
|
||||
original deadline, and does not replay an ambiguous paid mutation.
|
||||
|
||||
Tool callbacks require the capability of the current turn, including fresh MCP
|
||||
initialization. Recovery retains that capability in the private checkpoint.
|
||||
Older active checkpoints without it permit cleanup, but cannot resume tool
|
||||
access. Read-only observation retries transient stream failures within the
|
||||
original deadline, with bounded backoff.
|
||||
|
||||
Checkpoint acquisition and dead-owner takeover share a private, bounded local
|
||||
acquisition guard; no network work runs while it is held. Ordinary dead main-owner
|
||||
@@ -266,7 +290,9 @@ registration retains the charge and verified file for recovery. The bound surviv
|
||||
session changes and seeds existing retained usage. Exact existing-file recovery
|
||||
still verifies current provider bytes without another body/temp allocation at
|
||||
capacity. An uncertain ledger, retained pending reservation or ownership lock
|
||||
blocks new imports rather than resetting the budget.
|
||||
blocks new imports rather than resetting the budget. See the
|
||||
[local qualification record](../../doc/plans/2026-10-28-cursor-cloud-native-runner.md)
|
||||
for runnable acceptance cells and the remaining live qualification gates.
|
||||
|
||||
Google Antigravity is an **unqualified, pending** native ACPX integration. The
|
||||
explicit `paperclipai runtime setup antigravity` command installs the verified
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { agentHarnessType, agentRuntimeSettingsHarness, paperclipRunnerProfileForHarness } from "./agent-runner.js";
|
||||
|
||||
describe("Cursor Cloud harness identity", () => {
|
||||
it("retains its cloud identity across the explicit runner selection", () => {
|
||||
expect(paperclipRunnerProfileForHarness("cursor_cloud")).toEqual({ provider: "cursor_cloud" });
|
||||
expect(agentHarnessType("paperclip_runner", { provider: "cursor_cloud" })).toBe("cursor_cloud");
|
||||
expect(agentRuntimeSettingsHarness("paperclip_runner", { provider: "cursor_cloud" })).toBe("cursor_cloud");
|
||||
expect(agentHarnessType("cursor_cloud")).toBe("cursor_cloud");
|
||||
});
|
||||
});
|
||||
@@ -6,12 +6,13 @@ export interface AgentRunnerAvailability {
|
||||
defaultRunner: AgentRunner;
|
||||
}
|
||||
|
||||
export function paperclipRunnerProfileForHarness(harness: string): { provider: "codex" | "opencode" } | { provider: "acpx"; acpxAgent: "claude" | "pi" | "grok" } | undefined {
|
||||
export function paperclipRunnerProfileForHarness(harness: string): { provider: "codex" | "opencode" | "cursor_cloud" } | { provider: "acpx"; acpxAgent: "claude" | "pi" | "grok" } | undefined {
|
||||
if (harness === "codex_local") return { provider: "codex" };
|
||||
if (harness === "claude_local") return { provider: "acpx", acpxAgent: "claude" };
|
||||
if (harness === "pi_local") return { provider: "acpx", acpxAgent: "pi" };
|
||||
if (harness === "grok_local") return { provider: "acpx", acpxAgent: "grok" };
|
||||
if (harness === "opencode_local") return { provider: "opencode" };
|
||||
if (harness === "cursor_cloud") return { provider: "cursor_cloud" };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -300,7 +300,7 @@ for (const journey of [
|
||||
? "Read failed"
|
||||
: "Roadmap",
|
||||
);
|
||||
const replies = await json<Array<{ body: string; authorAgentId: string | null; createdByRunId: string | null }>>(await request.get(`/api/issues/${issue.id}/comments`));
|
||||
const replies = await json<Array<{ id: string; body: string; authorAgentId: string | null; createdByRunId: string | null }>>(await request.get(`/api/issues/${issue.id}/comments`));
|
||||
const reply = replies.find(comment => comment.authorAgentId === agent.id)!;
|
||||
expect(reply.createdByRunId).toBeTruthy();
|
||||
expect(originatingReview.sourceRunId).toBeTruthy();
|
||||
@@ -321,22 +321,23 @@ for (const journey of [
|
||||
queue.getByRole("button", { name: "Decline", exact: true }),
|
||||
).not.toBeVisible({ timeout: 20_000 });
|
||||
await page.bringToFront();
|
||||
expect(await page.evaluate(() => document.visibilityState)).toBe("visible");
|
||||
await page.reload();
|
||||
const resolvedReview = page.locator(`[id=${JSON.stringify(`interaction-${originatingReview.id}`)}]`);
|
||||
if (!["decline", "failure"].includes(journey)) {
|
||||
await expect(resolvedReview.getByRole("button", { name: "Show result details", exact: true }).filter({ hasText: "Succeeded" })).toBeVisible();
|
||||
} else {
|
||||
await expect(resolvedReview.getByText(journey === "decline" ? "Declined" : "Execution failed", { exact: false })).toBeVisible();
|
||||
}
|
||||
await expect(resolvedReview).toContainText("List fixture pages");
|
||||
const persistedReply = page.locator(`[id=${JSON.stringify(`comment-${reply.id}`)}]`);
|
||||
await expect(persistedReply).toBeVisible();
|
||||
await expect(persistedReply).toContainText(
|
||||
journey === "decline" ? "Review declined" : journey === "failure" ? "Read failed" : "Roadmap",
|
||||
);
|
||||
await expect(page.getByTestId("task-chat-history-content")).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(
|
||||
page
|
||||
.getByText(
|
||||
journey === "decline"
|
||||
? "Declined"
|
||||
: journey === "failure"
|
||||
? "Execution failed"
|
||||
: "Succeeded",
|
||||
{ exact: false },
|
||||
)
|
||||
.first(),
|
||||
).toBeVisible();
|
||||
await page.screenshot({
|
||||
path: testInfo.outputPath("resolved-review.png"),
|
||||
});
|
||||
|
||||
@@ -110,9 +110,17 @@ test("Classic startup does not guess a chat layout while personal preferences ar
|
||||
await page.goto(fixture.route);
|
||||
await expect(page.getByTestId("shell-configuration-loading")).toBeVisible();
|
||||
await expect(page.locator("[data-task-chat-shell]")).toHaveCount(0);
|
||||
await expect(page.getByTestId("issue-detail-header")).toHaveCount(0);
|
||||
const preparedOutlet = page.getByTestId("shell-prepared-outlet");
|
||||
await expect(preparedOutlet).toHaveAttribute("hidden", "");
|
||||
await expect(preparedOutlet).toHaveAttribute("inert", "");
|
||||
await expect(preparedOutlet).toHaveAttribute("aria-hidden", "true");
|
||||
await expect(page.getByTestId("issue-detail-header")).toBeHidden();
|
||||
await expect(page.getByRole("heading", { name: fixture.title, exact: true })).toHaveCount(0);
|
||||
release();
|
||||
await expect(page.getByTestId("issue-detail-header").getByRole("heading", { name: fixture.title, exact: true })).toBeVisible();
|
||||
await expect(preparedOutlet).not.toHaveAttribute("hidden", "");
|
||||
await expect(preparedOutlet).not.toHaveAttribute("inert", "");
|
||||
await expect(preparedOutlet).not.toHaveAttribute("aria-hidden", "true");
|
||||
await expect(page.locator("[data-task-chat-shell]")).toHaveCount(0);
|
||||
} finally {
|
||||
release();
|
||||
|
||||
@@ -47,6 +47,18 @@ injection in the uncertain-retry case. Task/run/document REST reads own grading.
|
||||
The fixture catalog is executable production-contract data. Keep it small,
|
||||
typed, deterministic, and free of raw credentials.
|
||||
|
||||
The explicit local `cursor-cloud` suite reuses the ordinary
|
||||
`plan_revision_acceptance` flow with three expected runs and one attempt. It
|
||||
checks the initial Plan, the requested revision and browser approval of that
|
||||
exact revision before completion. This is Paperclip semantic planning through
|
||||
the Cloud default harness; Cursor's native Plan API is outside this cell.
|
||||
Its ownership oracle requires draft/revision continuity followed by the exact
|
||||
accepted confirmation's explicit fresh-session transition, three distinct native
|
||||
runs and owned cleanup. The same-agent follow-up oracle is unchanged.
|
||||
The definition digest includes `catalog.ts` because Cloud's Plan and follow-up
|
||||
prompts derive from shared task definitions there. Earlier three-cell results
|
||||
retain their original definition and do not qualify the added Plan cell.
|
||||
|
||||
## Suites and matrices
|
||||
|
||||
A `RunnerSuiteFixture` declares one durable testing purpose: stable ID, label,
|
||||
|
||||
@@ -1,5 +1,57 @@
|
||||
# Paid runner full-stack E2E
|
||||
|
||||
The explicit-only `cursor-cloud` suite uses a local controller and hosted Cursor
|
||||
Cloud work. Its four required cells check a downloaded registered artifact,
|
||||
question/answer continuation on the same Cloud agent, UI Stop of an
|
||||
independently observed active Cloud run, and semantic Plan revision/approval.
|
||||
It is experimental and unqualified until all four real cells pass.
|
||||
Model acknowledgement and provider dollar cost remain
|
||||
unavailable; catalog discovery and support tests are not live acceptance.
|
||||
|
||||
Configure `PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_MODEL` with an exact account model,
|
||||
`PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REPO` with an owned disposable HTTPS repository,
|
||||
optional `PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REF`, and `CURSOR_API_KEY`.
|
||||
Set `PAPERCLIP_CURSOR_CLOUD_CALLBACK_PORT` to a dedicated free loopback port and
|
||||
point an HTTPS tunnel at **that port only**. After approving unpriced provider
|
||||
spend for these disposable tests, set
|
||||
`PAPERCLIP_CURSOR_CLOUD_ALLOW_UNPRICED_QUALIFICATION=1`. Missing opt-in blocks
|
||||
before credential loading or fixture creation. Each fresh Cursor Cloud fixture
|
||||
sets and reads back only its company and agent monthly billed-cost policies:
|
||||
1,000 cents, active hard stops, and `unpricedUsagePolicy: allow`. A failed or
|
||||
mismatched readback blocks task dispatch. The verified policy receipt is retained
|
||||
in `fixtures.json`. These limits still stop known billed costs; they do not cap
|
||||
unpriced usage. Provider cost remains unavailable, never inferred as zero.
|
||||
Set `PAPERCLIP_PUBLIC_URL` to the
|
||||
tunnel's origin. The E2E wrapper exposes only POST `/mcp/native-runs/:runId`
|
||||
through this listener; it rejects the UI and `/api/` paths. Public ingress is
|
||||
checked before fixtures or provider work. Never tunnel the local operator app.
|
||||
|
||||
Discover with `pnpm test:e2e:runner -- --list --suite cursor-cloud`. The smallest
|
||||
paid cell is `pnpm test:e2e:runner -- --id cursor-cloud.runner-cursor-cloud.local.task-artifact`.
|
||||
Select `cloud-followup`, `active-run-stop`, or `plan-revise-accept` explicitly for
|
||||
the other cells. The Plan cell reuses the production planning flow: publish a
|
||||
two-step Plan, request and review a three-step revision, then approve that exact
|
||||
revision in the browser before completion. Its three expected runs use
|
||||
Paperclip planning authority with Cursor's default harness; it does not exercise
|
||||
Cursor's native Plan API or native plan-decision callbacks.
|
||||
Draft and revision share one owned Cloud session. Approval must carry the exact
|
||||
revised interaction's fresh-session receipt and start a new owned Agent/session;
|
||||
all three turns require distinct Cloud runs. The follow-up cell keeps its
|
||||
separate same-Agent/session continuity requirement.
|
||||
The complete bounded checkpoint is `pnpm test:e2e:runner -- --suite cursor-cloud`.
|
||||
Each cell permits one attempt. Missing prerequisites setup-block before provider
|
||||
work. Teardown cancels observed active runs and deletes only agents named by
|
||||
run-owned persisted notices.
|
||||
After each owned Agent deletion, cleanup polls only its exact GET for up to
|
||||
30 seconds to confirm 404, including after an ambiguous deletion reply. It does
|
||||
not repeat DELETE; authorization failures, unknown read failures and continued
|
||||
presence still fail cleanup. Earlier cleanup failures keep their original grades.
|
||||
The Stop proof includes a 15-second quiet window
|
||||
over native run status, published artifact absence, and local non-continuation;
|
||||
it does not inspect the entire remote filesystem. Attempts remain private because
|
||||
ordinary run snapshots can contain native session identifiers. Use the existing
|
||||
local report generator; the public history publisher refuses this suite.
|
||||
|
||||
The [chat scenario catalog](chat-scenarios/README.md) plans conversational
|
||||
coverage across the product using human requests, assumed context and expected
|
||||
outcomes. It shares feature-map capability IDs and belongs to this Product E2E
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# Runner E2E security for a public repository
|
||||
|
||||
Native `cursor-cloud` acceptance uses a separate callback-only loopback listener.
|
||||
Its external HTTPS tunnel must never target the local_trusted operator app.
|
||||
Credential-free ingress checks require `/` and `/api/health` to return 404 and
|
||||
an unauthenticated callback POST to return 401 before fixture creation. Only
|
||||
capability authorization and MCP protocol headers reach the application; browser
|
||||
cookies are stripped. Native provider identifiers remain private. Dedicated
|
||||
observer evidence hashes them, and the public history publisher refuses this
|
||||
suite because ordinary diagnostic snapshots may retain them. Cleanup may cancel
|
||||
or delete only resources linked by exact local-run-owned persisted notices.
|
||||
|
||||
The deployment-targeted `file-input-answer` journey uploads a small synthetic
|
||||
CSV through the normal task composer. Its reference and numeric inputs are
|
||||
generated per attempt and occur only in the file. The independent fixture and
|
||||
|
||||
@@ -118,8 +118,9 @@ it("imports original grades when report evidence validation changes the selected
|
||||
expect(() => buildBraintrustExperiment(projectId, adjusted, changed)).toThrow();
|
||||
});
|
||||
|
||||
it("accepts current catalog model names including Cursor qualification parameters", () => {
|
||||
for (const model of new Set(runnerMatrix.map(cell => cell.profile.model))) {
|
||||
it("accepts configured catalog model names including Cursor qualification parameters", () => {
|
||||
const configured = runnerMatrix.filter(cell => cell.profile.provider !== "cursor_cloud" || cell.profile.model !== "");
|
||||
for (const model of new Set(configured.map(cell => cell.profile.model))) {
|
||||
const { campaign, originals } = fixture();
|
||||
const changed = originals.map(original => ({ ...original, model }));
|
||||
const selected = { ...campaign, results: campaign.results.map(result => ({ ...result, model })) };
|
||||
|
||||
@@ -286,11 +286,11 @@ describe("runner E2E catalog", () => {
|
||||
expect(localIntegrityTasks).toHaveLength(2);
|
||||
expect(openRouterBreadthTasks).toHaveLength(3);
|
||||
expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([
|
||||
1, 1, 2, 1, 3, 2, 2, 4, 4, 4, 4, 4, 4, 8, 10, 6, 63, 12, 6, 4, 2, 4, 2, 30, 3, 16, 16, 20, 2, 1, 6, 8, 46, 2, 23, 15, 52, 6, 6, 20, 26, 52, 5, 28, 18, 2, 6, 6, 13, 10, 4, 48, 16, 10, 2, 1, 1, 4, 116, 2, 1, 2,
|
||||
1, 1, 4, 2, 1, 3, 2, 2, 4, 4, 4, 4, 4, 4, 8, 10, 6, 63, 12, 6, 4, 2, 4, 2, 30, 3, 16, 16, 20, 2, 1, 6, 8, 46, 2, 23, 15, 52, 6, 6, 20, 26, 52, 5, 28, 18, 2, 6, 6, 13, 10, 4, 48, 16, 10, 2, 1, 1, 4, 116, 2, 1, 2,
|
||||
|
||||
]);
|
||||
expect(validateRunnerCatalog()).toHaveLength(798);
|
||||
expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(798);
|
||||
expect(validateRunnerCatalog()).toHaveLength(802);
|
||||
expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(802);
|
||||
expect(
|
||||
runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"),
|
||||
).toHaveLength(48);
|
||||
|
||||
@@ -9,6 +9,7 @@ import { TASK_WORKSPACES_SUITE, taskWorkspaceTask, taskWorkspaceProfile, taskWor
|
||||
import { repositoryProofTasks, repositoryProofProfile, repositoryProofDigest } from "./repository-verification.js";
|
||||
import { automaticRepositoryTask, automaticRepositoryDigest } from "./automatic-repository.js";
|
||||
import { nativeActiveStopTasks } from "./native-active-stop-tasks.js";
|
||||
import { CURSOR_CLOUD_SUITE, cursorCloudArtifactTask, cursorCloudStopTask, CURSOR_CLOUD_QUIET_WINDOW_MS, cursorCloudDefinitionDigest } from "./cursor-cloud-cases.js";
|
||||
import { kimiLifecycleTasks } from "./kimi-lifecycle-tasks.js";
|
||||
import { piControlTasks } from "./pi-controls-cases.js";
|
||||
import { cursorNativeTasks } from "./cursor-native-cases.js";
|
||||
@@ -1161,6 +1162,39 @@ const repositoryModelProfiles = [
|
||||
},
|
||||
];
|
||||
|
||||
export const cursorCloudProfile: RunnerProfileFixture = {
|
||||
id: "runner-cursor-cloud", label: "Native Cursor Cloud (experimental)", generation: "native", groups: [],
|
||||
adapterType: "paperclip_runner", provider: "cursor_cloud", model: process.env.PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_MODEL?.trim() ?? "",
|
||||
modelQualification: { source: "candidate_runner_profile", qualificationId: "cursor-cloud-explicit-acceptance-env" },
|
||||
credential: "CURSOR_API_KEY", supportedEnvironments: ["local"], expectedRuntimeMode: "native",
|
||||
expectedRuntimeMetadata: { adapterType: "paperclip_runner", provider: "cursor_cloud" },
|
||||
buildAgent(input) {
|
||||
const agent = commonAgent(input, this.id, "paperclip_runner", {
|
||||
provider: "cursor_cloud", model: this.model, lifecycleMode: "per_turn", cloudEnvType: "cloud",
|
||||
repoUrl: process.env.PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REPO?.trim() ?? "",
|
||||
...(process.env.PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REF?.trim() ? { repoRef: process.env.PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REF.trim() } : {}),
|
||||
autoCreatePR: false, workOnCurrentBranch: false, skipReviewerRequest: true, cursorCloudTimeoutMs: 360_000,
|
||||
env: { CURSOR_API_KEY: requiredSecret(input, "CURSOR_API_KEY") },
|
||||
});
|
||||
return { ...agent, budgetMonthlyCents: 1_000 };
|
||||
},
|
||||
};
|
||||
|
||||
export const cursorCloudFollowupTask: RunnerTaskFixture = {
|
||||
...openRouterBreadthTasks.find(task => task.id === "question-resume-complete")!,
|
||||
id: "cloud-followup", label: "Answer a question and continue the same Cloud agent", automaticRetryPolicy: "single_attempt",
|
||||
buildTitle: nonce => `Cursor Cloud follow-up ${nonce}`,
|
||||
};
|
||||
|
||||
const cursorCloudPlanningBase = runnerTasks.find(task => task.id === "plan-revise-accept")!;
|
||||
export const cursorCloudPlanningTask: RunnerTaskFixture = {
|
||||
...cursorCloudPlanningBase, automaticRetryPolicy: "single_attempt",
|
||||
buildPrompt: nonce => cursorCloudPlanningBase.buildPrompt(nonce).replace(
|
||||
"For a native runner, remain in the requested planning collaboration mode.",
|
||||
"For a native runner, follow the requested Paperclip planning authority. Cursor Cloud uses its default harness for this semantic Plan workflow; do not request Cursor native Plan mode.",
|
||||
),
|
||||
};
|
||||
|
||||
const daytonaControllerOutageEnvironment: EnvironmentFixture = {
|
||||
...daytonaWarmEnvironment,
|
||||
configurationKey: "warm-controller-outage-v1",
|
||||
@@ -1208,6 +1242,16 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [
|
||||
upgradeReadiness: "active-remote-workspace-recoverable-before-handoff",
|
||||
grading: "same-active-execution-ordinary-reads-saves-and-second-empty-home-continuation" },
|
||||
},
|
||||
{
|
||||
id: CURSOR_CLOUD_SUITE, label: "Native Cursor Cloud", manualOnly: true, groups: [],
|
||||
description: "Local Paperclip controller with hosted Cursor work: verified artifact, same-agent follow-up, real active-run Stop and semantic plan revision/approval.",
|
||||
profiles: [cursorCloudProfile], environments: runnerEnvironments.filter(environment => environment.id === "local"),
|
||||
tasks: [cursorCloudArtifactTask, cursorCloudFollowupTask, cursorCloudStopTask, cursorCloudPlanningTask], expectedMatrixSize: 4,
|
||||
definitionMetadata: { version: 3, definitionDigest: cursorCloudDefinitionDigest(), scheduling: "explicit-only", maximumAttemptsPerCell: 1,
|
||||
effectiveModelAcknowledged: false, commandPermissions: "provider-managed", costCoverage: "provider-cost-unavailable",
|
||||
quietWindowMs: CURSOR_CLOUD_QUIET_WINDOW_MS, repository: process.env.PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REPO ?? "",
|
||||
repositoryRef: process.env.PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REF ?? "", callbackExposure: "callback-path-only-loopback-proxy" },
|
||||
},
|
||||
{
|
||||
id: "daytona-restart-continuity", label: "Daytona warm controller outage continuity", manualOnly: true,
|
||||
description: "Keep the original active native runner, reusable warm sandbox, task tools and saved files through five minutes without a controller, then continue the completed session after another replacement.",
|
||||
@@ -2060,8 +2104,9 @@ function assertNoRawSecretValues(value: unknown, label: string) {
|
||||
|
||||
export function validateRunnerCatalog(): MatrixExecution[] {
|
||||
const connectionSuite = runnerSuites.find(suite => suite.id === "provider-connections")!;
|
||||
const allProfiles = [...connectionSuite.profiles, ...extendedHarnessProfiles, ...runnerProfiles, ...legacyAcpxProfiles, ...pendingContextIntegrityProfiles, ...openRouterBreadthProfiles, ...everydayProfiles.filter(p => !runnerProfiles.some(existing => existing.id === p.id))];
|
||||
const allProfiles = [cursorCloudProfile, ...connectionSuite.profiles, ...extendedHarnessProfiles, ...runnerProfiles, ...legacyAcpxProfiles, ...pendingContextIntegrityProfiles, ...openRouterBreadthProfiles, ...everydayProfiles.filter(p => !runnerProfiles.some(existing => existing.id === p.id))];
|
||||
const allTasks = [
|
||||
cursorCloudArtifactTask, cursorCloudFollowupTask, cursorCloudStopTask,
|
||||
repositorySkillsTask,
|
||||
...piNativeTasks,
|
||||
...copilotProtectionTasks,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { expect } from "@playwright/test";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { resolveDefaultAgentWorkspaceDir } from "../../server/src/home-paths.js";
|
||||
import { prepareChatBrief } from "./chat-stories.js";
|
||||
import { prepareChatBrief, publishChatBrief } from "./chat-stories.js";
|
||||
import { mutableIssueSnapshot } from "./chat-hardening.js";
|
||||
import { sendChatMessage, readChatOutputDocument, type ChatFlowInput, type ChatIssue, type ChatRun } from "./chat-flow.js";
|
||||
|
||||
@@ -125,7 +125,7 @@ export async function runActiveReassignment(context: Context) {
|
||||
await input.evidence("chat-active-reassignment.json", e);
|
||||
assertActiveHandoff(e);
|
||||
} finally {
|
||||
await writeFile(wait.gate, reference);
|
||||
await publishChatBrief(wait.gate, reference);
|
||||
await input.evidence("chat-reassignment-final.json", { task: await api.get(`/api/issues/${task.id}`), runs: await context.allRuns() });
|
||||
}
|
||||
}
|
||||
@@ -161,7 +161,7 @@ export async function runWorkerCrash(context: Context) {
|
||||
}, { timeout: 120_000 }).toBe(true);
|
||||
await input.evidence("chat-worker-settled-failure.json", failed);
|
||||
await input.capture("worker-failed", "Worker loss before a fresh user turn", "worker-failed.png");
|
||||
await writeFile(wait.gate, reference);
|
||||
await publishChatBrief(wait.gate, reference);
|
||||
if (failed.errorCode === "native_session_cleanup_quarantined") {
|
||||
// Preserve the red qualification result, but verify the stop is honest:
|
||||
// the UI/API must not offer an attempt which cannot pass cleanup admission.
|
||||
@@ -196,7 +196,7 @@ export async function runWorkerCrash(context: Context) {
|
||||
await expect(input.page.getByTestId("task-chat-run-failed-try-again")).toHaveCount(0);
|
||||
expect(await input.api.get(`/api/companies/${input.fixtures.company.id}/issues`)).toEqual([]);
|
||||
} finally {
|
||||
await writeFile(wait.gate, reference);
|
||||
await publishChatBrief(wait.gate, reference);
|
||||
await input.evidence("chat-worker-final.json", { runs: await context.allRuns(), comments: await context.comments().catch(error => ({ readError: String(error) })) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { assertInterruptedChat, prepareChatBrief } from "./chat-stories.js";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { assertInterruptedChat, prepareChatBrief, publishChatBrief } from "./chat-stories.js";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
@@ -8,6 +8,11 @@ import { promisify } from "node:util";
|
||||
import { runnerMatrix } from "./catalog.js";
|
||||
import { buildRunnerE2EProcessEnvironment } from "./harness-env.js";
|
||||
|
||||
vi.mock("node:fs/promises", async importOriginal => {
|
||||
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return { ...actual, writeFile: vi.fn(actual.writeFile) };
|
||||
});
|
||||
|
||||
const run = { id: "run", companyId: "company", agentId: "agent", status: "succeeded", runtimeMode: "native", contextSnapshot: { issueId: "chat" } };
|
||||
const valid = {
|
||||
first: "Read the brief", followup: "Change the launch day", reference: "BRIEF123", marker: "UPDATED123", issueId: "chat",
|
||||
@@ -26,7 +31,7 @@ describe("active chat follow-up oracle", () => {
|
||||
try {
|
||||
await expect.poll(() => readFile(ready, "utf8").catch(() => "")).toBe("waiting");
|
||||
} finally {
|
||||
await writeFile(gate, "BRIEF fixture result");
|
||||
await publishChatBrief(gate, "BRIEF fixture result");
|
||||
expect((await command).stdout.trim()).toBe("BRIEF fixture result");
|
||||
}
|
||||
} finally {
|
||||
@@ -74,6 +79,41 @@ describe("active chat follow-up oracle", () => {
|
||||
|
||||
|
||||
describe("bounded chat brief fixture", () => {
|
||||
it("publishes the complete brief atomically while a real worker is waiting", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "chat-brief-atomic-"));
|
||||
const actual = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
|
||||
let releaseWrite!: () => void;
|
||||
const pausedWrite = new Promise<void>(resolve => { releaseWrite = resolve; });
|
||||
let exposedEmptyWrite!: (file: Parameters<typeof writeFile>[0]) => void;
|
||||
const emptyWrite = new Promise<Parameters<typeof writeFile>[0]>(resolve => { exposedEmptyWrite = resolve; });
|
||||
let running: Promise<{ stdout: string; stderr: string }> | undefined;
|
||||
let publishing: Promise<void> | undefined;
|
||||
try {
|
||||
const brief = await prepareChatBrief(directory, "atomic", 5_000);
|
||||
running = promisify(execFile)(process.execPath, [brief.scriptPath]);
|
||||
await expect.poll(() => readFile(brief.ready, "utf8").catch(() => "")).toBe("waiting");
|
||||
vi.mocked(writeFile).mockImplementationOnce(async (file, data, options) => {
|
||||
await actual.writeFile(file, "");
|
||||
exposedEmptyWrite(file);
|
||||
await pausedWrite;
|
||||
await actual.writeFile(file, data, typeof options === "object" ? { ...options, flag: "w" } : options);
|
||||
});
|
||||
publishing = publishChatBrief(brief.gate, "A complete multiword brief.");
|
||||
const stagedFile = await emptyWrite;
|
||||
expect(await readFile(stagedFile, "utf8")).toBe("");
|
||||
await expect(readFile(brief.gate, "utf8")).rejects.toHaveProperty("code", "ENOENT");
|
||||
releaseWrite();
|
||||
await publishing;
|
||||
expect((await running).stdout.trim()).toBe("A complete multiword brief.");
|
||||
} finally {
|
||||
releaseWrite();
|
||||
await publishing;
|
||||
await running?.catch(() => undefined);
|
||||
vi.mocked(writeFile).mockImplementation(actual.writeFile);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("releases a waiting worker and rejects an unbounded wait", async () => {
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "chat-brief-bounded-"));
|
||||
try {
|
||||
@@ -82,7 +122,7 @@ describe("bounded chat brief fixture", () => {
|
||||
const brief = await prepareChatBrief(directory, "release", 2_000);
|
||||
const running = promisify(execFile)(process.execPath, [brief.scriptPath]);
|
||||
await expect.poll(() => readFile(brief.ready, "utf8").catch(() => "")).toBe("waiting");
|
||||
await writeFile(brief.gate, "Meet at half past ten.");
|
||||
await publishChatBrief(brief.gate, "Meet at half past ten.");
|
||||
expect((await running).stdout.trim()).toBe("Meet at half past ten.");
|
||||
const expires = await prepareChatBrief(directory, "expires", 1);
|
||||
await expect(promisify(execFile)(process.execPath, [expires.scriptPath])).rejects.toMatchObject({ code: 1 });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect } from "@playwright/test";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { sendChatMessage, type ChatFlowInput, type ChatIssue, type ChatRun } from "./chat-flow.js";
|
||||
@@ -58,6 +58,16 @@ export function assertInterruptedChat(input: {
|
||||
}
|
||||
}
|
||||
|
||||
export async function publishChatBrief(gate: string, content: string) {
|
||||
const staging = `${gate}.${randomUUID()}.tmp`;
|
||||
try {
|
||||
await writeFile(staging, content, { encoding: "utf8", flag: "wx" });
|
||||
await rename(staging, gate);
|
||||
} finally {
|
||||
await rm(staging, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareChatBrief(workspacePath: string, nonce: string, timeoutMs = 120_000) {
|
||||
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 300_000) throw new Error("Brief wait must be bounded between 1 and 300000ms");
|
||||
await mkdir(workspacePath, { recursive: true });
|
||||
@@ -106,7 +116,7 @@ export async function runChatInterruption(context: Context & { refreshIssue(): P
|
||||
activeAtFollowup = await input.api.get<ChatRun>(`/api/heartbeat-runs/${boundaryRun!.id}`);
|
||||
await input.evidence("chat-interruption-boundary.json", { first, followup, boundaryRun, activeAtFollowup, comments: await comments() });
|
||||
expect(activeAtFollowup.status, "Follow-up must persist while the first provider run is active").toBe("running");
|
||||
await writeFile(gate, reference, "utf8");
|
||||
await publishChatBrief(gate, reference);
|
||||
await expect.poll(async () => (await comments()).filter(comment => comment.authorAgentId).at(-1)?.body ?? "", { timeout: 240_000 }).toContain(marker);
|
||||
await idle(1); // Providers may queue a new run or steer the current run.
|
||||
const plan = revise ? await input.api.get<{ body: string }>(`/api/issues/${context.issue().id}/documents/plan`) : undefined;
|
||||
@@ -118,7 +128,7 @@ export async function runChatInterruption(context: Context & { refreshIssue(): P
|
||||
expect(await input.api.get(`/api/companies/${input.fixtures.company.id}/projects`)).toEqual([]);
|
||||
} finally {
|
||||
// Always release a provider that is still waiting, including failed UI runs.
|
||||
await writeFile(gate, reference, "utf8");
|
||||
await publishChatBrief(gate, reference);
|
||||
const chatPath = `/api/companies/${input.fixtures.company.id}/chats/${input.fixtures.agent.id}`;
|
||||
const current = await input.api.get<ChatIssue | null>(chatPath).catch(() => null);
|
||||
await input.evidence("chat-interruption-state.json", {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { resolveManagedProjectWorkspaceDir, resolveDefaultAgentWorkspaceDir } from "../../server/src/home-paths.js";
|
||||
import { pollUntil, type RunnerApi } from "./api.js";
|
||||
import { sendChatMessage, readChatOutputDocument, collectChatRunEvidence, type ChatFlowInput, type ChatRun } from "./chat-flow.js";
|
||||
import { arm as armDocumentGate, clear as clearDocumentGate, release as releaseDocumentGate, waitUntilHeld } from "./context-comment-gate.js";
|
||||
import { prepareChatBrief } from "./chat-stories.js";
|
||||
import { prepareChatBrief, publishChatBrief } from "./chat-stories.js";
|
||||
import { completionDelivery, completionOutputUsesReleasedBrief, type CompletionObservation } from "./completion-updates.js";
|
||||
|
||||
type Row = Record<string, any>;
|
||||
@@ -190,7 +190,7 @@ export async function runChatCompletionUpdate(context: {
|
||||
expect(reference.body).toContain(`REFERENCE${marker}`);
|
||||
await input.evidence("completion-busy-document-gate.json", { sourceRun: busyRun, document: reference, responseHeld: true });
|
||||
}
|
||||
await writeFile(wait.gate, brief);
|
||||
await publishChatBrief(wait.gate, brief);
|
||||
await pollUntil({ label: "delegated welcome note completed", deadlineAt: Date.now() + 180_000, intervalMs: 1000,
|
||||
load: () => api.get<Row>(`/api/issues/${task!.id}`), accept: t => t.status === "done" });
|
||||
if (busyRun) {
|
||||
@@ -227,7 +227,7 @@ export async function runChatCompletionUpdate(context: {
|
||||
// neither task records nor completion events are fabricated by the fixture.
|
||||
await input.evidence("completion-restart-boundary.json", { worker: await api.get(`/api/issues/${task!.id}`), runs: reportingRun.runs, sourceReferenceGateReady: true });
|
||||
await input.restart();
|
||||
await writeFile(completionWait!.gate, "The organizer is ready to receive the saved result. Report the completed work now.");
|
||||
await publishChatBrief(completionWait!.gate, "The organizer is ready to receive the saved result. Report the completed work now.");
|
||||
await page.goto(`/${f.company.issuePrefix}/chats/${f.agent.id}`, { waitUntil: "commit" });
|
||||
}
|
||||
for (const [index, item] of delegated.entries()) {
|
||||
@@ -253,9 +253,9 @@ export async function runChatCompletionUpdate(context: {
|
||||
expect(replies, `one correlated completion reply for ${item.id}`).toHaveLength(1);
|
||||
}
|
||||
} finally {
|
||||
await writeFile(wait.gate, `Reference: ${reference}`);
|
||||
await publishChatBrief(wait.gate, `Reference: ${reference}`);
|
||||
if (busy) await releaseDocumentGate(context.issue().id);
|
||||
if (completionWait) await writeFile(completionWait.gate, "The organizer is ready to receive the saved result.");
|
||||
if (completionWait) await publishChatBrief(completionWait.gate, "The organizer is ready to receive the saved result.");
|
||||
await context.refreshIssue();
|
||||
}
|
||||
}
|
||||
@@ -45,12 +45,15 @@ describe("context integrity final evidence contract", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects the former context-specific filenames", async () => {
|
||||
it.each([
|
||||
["context-specific", "context-integrity-final.png", "context-integrity.json"],
|
||||
["Cloud Stop custom-only", "cloud-stopped.png", "cursor-cloud-stop-settled.json"],
|
||||
])("rejects %s filenames without the shared final evidence", async (_label, screenshot, snapshot) => {
|
||||
const privateDir = await fixtureRoot();
|
||||
const uploadDir = `${privateDir}-upload`;
|
||||
try {
|
||||
await writeFile(path.join(privateDir, "context-integrity-final.png"), "png\n");
|
||||
await writeFile(path.join(privateDir, "snapshots", "context-integrity.json"), "{}\n");
|
||||
await writeFile(path.join(privateDir, screenshot), "png\n");
|
||||
await writeFile(path.join(privateDir, "snapshots", snapshot), "{}\n");
|
||||
const packaged = await packageEvidence({ privateDir, uploadDir, secrets: [], expectPassScreenshot: true });
|
||||
expect(packaged.missing).toContain("final-state.png");
|
||||
expect(packaged.missing).toContain(path.join("snapshots", "api-state.json"));
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { RunnerApi } from "./api.js";
|
||||
import { runnerMatrix } from "./catalog.js";
|
||||
import { setupLiveFixtures } from "./live-fixtures.js";
|
||||
|
||||
const optIn = "PAPERCLIP_CURSOR_CLOUD_ALLOW_UNPRICED_QUALIFICATION";
|
||||
const execution = runnerMatrix.find(cell => cell.id === "cursor-cloud.runner-cursor-cloud.local.cloud-followup")!;
|
||||
const companyId = "fixture-company", agentId = "fixture-agent";
|
||||
const policyDefaults = { companyId, metric: "billed_cents", windowKind: "calendar_month_utc",
|
||||
amount: 1_000, hardStopEnabled: true, isActive: true, unpricedUsagePolicy: "allow" };
|
||||
function fixtureApi(changeOverview?: (overview: Record<string, any>) => unknown) {
|
||||
const calls: Array<{ method: string; path: string; body?: any }> = [];
|
||||
const policies: Array<Record<string, any>> = [];
|
||||
const api = {
|
||||
async get(path: string) {
|
||||
calls.push({ method: "GET", path });
|
||||
if (path.endsWith("/environments?driver=local")) return [{ id: "local", driver: "local" }];
|
||||
if (path.endsWith("/budgets/overview")) {
|
||||
const overview = { companyId, policies };
|
||||
return changeOverview ? changeOverview(overview) : overview;
|
||||
}
|
||||
throw new Error(`Unexpected GET ${path}`);
|
||||
},
|
||||
async postSensitive(path: string) { calls.push({ method: "SECRET", path }); return { id: "fixture-secret" }; },
|
||||
async post(path: string, body: Record<string, any>) {
|
||||
calls.push({ method: "POST", path, body });
|
||||
if (path === "/api/companies") return { id: companyId, name: "Test" };
|
||||
if (path.endsWith("/agents")) return { ...body, id: agentId, companyId };
|
||||
if (path.endsWith("/budgets/policies")) {
|
||||
const policy = { ...policyDefaults, ...body, unpricedEventCount: 1, excludedDiagnostic: "not-evidence" };
|
||||
policies.push(policy);
|
||||
return policy;
|
||||
}
|
||||
throw new Error(`Unexpected POST ${path}`);
|
||||
},
|
||||
} as unknown as RunnerApi;
|
||||
return { api, calls };
|
||||
}
|
||||
function setup(api: RunnerApi, selected = execution) {
|
||||
return setupLiveFixtures({ api, execution: selected, executionNonce: "budget-control", workspacePath: "/tmp/cursor-budget-control",
|
||||
credentials: { [selected.profile.credential]: "synthetic-provider-key" } });
|
||||
}
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
describe("Cursor Cloud qualification budgets", () => {
|
||||
it.each([undefined, "", "0", "true"])("blocks missing exact opt-in %s before fixture or provider dispatch", async value => {
|
||||
vi.stubEnv(optIn, value);
|
||||
const { api, calls } = fixtureApi();
|
||||
await expect(setup(api)).rejects.toThrow(optIn);
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
it("verifies only the owned company and agent policies with known-cost hard stops intact", async () => {
|
||||
vi.stubEnv(optIn, "1");
|
||||
const { api, calls } = fixtureApi();
|
||||
const fixtures = await setup(api);
|
||||
expect(calls.find(call => call.path === "/api/companies")!.body.budgetMonthlyCents).toBe(1_000);
|
||||
expect(calls.find(call => call.path.endsWith("/agents"))!.body.budgetMonthlyCents).toBe(1_000);
|
||||
const writes = calls.filter(call => call.path.endsWith("/budgets/policies"));
|
||||
expect(writes.map(call => ({ path: call.path, body: call.body }))).toEqual([
|
||||
{ path: `/api/companies/${companyId}/budgets/policies`, body: { scopeType: "company", scopeId: companyId,
|
||||
metric: "billed_cents", windowKind: "calendar_month_utc", amount: 1_000, hardStopEnabled: true, isActive: true, unpricedUsagePolicy: "allow" } },
|
||||
{ path: `/api/companies/${companyId}/budgets/policies`, body: { scopeType: "agent", scopeId: agentId,
|
||||
metric: "billed_cents", windowKind: "calendar_month_utc", amount: 1_000, hardStopEnabled: true, isActive: true, unpricedUsagePolicy: "allow" } },
|
||||
]);
|
||||
expect(calls.at(-1)).toEqual({ method: "GET", path: `/api/companies/${companyId}/budgets/overview` });
|
||||
expect((fixtures as unknown as Record<string, unknown>).qualificationBudget).toEqual({
|
||||
schema: "paperclip.e2e.cursor-cloud.qualification-budget.v1", unpricedUsageOptIn: true,
|
||||
policies: [{ ...policyDefaults, scopeType: "company", scopeId: companyId }, { ...policyDefaults, scopeType: "agent", scopeId: agentId }],
|
||||
});
|
||||
await fixtures.teardown();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["missing agent", (value: any) => { value.policies.pop(); }],
|
||||
["foreign scope", (value: any) => { value.policies[1].scopeId = "foreign-agent"; }],
|
||||
["foreign company", (value: any) => { value.policies[1].companyId = "foreign-company"; }],
|
||||
["foreign overview", (value: any) => { value.companyId = "foreign-company"; }],
|
||||
["zero limit", (value: any) => { value.policies[0].amount = 0; }],
|
||||
["hard stop disabled", (value: any) => { value.policies[1].hardStopEnabled = false; }],
|
||||
["inactive guard", (value: any) => { value.policies[0].isActive = false; }],
|
||||
["unpriced block", (value: any) => { value.policies[1].unpricedUsagePolicy = "block"; }],
|
||||
["wrong metric", (value: any) => { value.policies[0].metric = "runs"; }],
|
||||
["wrong window", (value: any) => { value.policies[1].windowKind = "rolling_day"; }],
|
||||
["duplicate scope", (value: any) => { value.policies.push({ ...value.policies[1] }); }],
|
||||
["malformed policies", (value: any) => { value.policies = null; }],
|
||||
] as const)("fails closed before returning a dispatchable fixture: %s", async (_name, change) => {
|
||||
vi.stubEnv(optIn, "1");
|
||||
const { api, calls } = fixtureApi(value => { change(value); return value; });
|
||||
await expect(setup(api)).rejects.toThrow("budget policy readback");
|
||||
expect(calls.some(call => call.path.includes("/issues"))).toBe(false);
|
||||
});
|
||||
|
||||
it("propagates failed public policy readback before dispatch", async () => {
|
||||
vi.stubEnv(optIn, "1");
|
||||
const { api } = fixtureApi(() => { throw new Error("readback transport failed"); });
|
||||
await expect(setup(api)).rejects.toThrow("readback transport failed");
|
||||
});
|
||||
|
||||
it("does not change other providers or require their unpriced opt-in", async () => {
|
||||
vi.stubEnv(optIn, undefined);
|
||||
const { api, calls } = fixtureApi();
|
||||
const other = runnerMatrix.find(cell => cell.suite.id === "stock-harness" && cell.profile.id === "runner-codex" && cell.environment.id === "local")!;
|
||||
const fixtures = await setup(api, other);
|
||||
expect(calls.some(call => call.path.includes("/budgets/"))).toBe(false);
|
||||
expect(fixtures).not.toHaveProperty("qualificationBudget");
|
||||
await fixtures.teardown();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { BudgetOverview, BudgetPolicySummary } from "../../packages/shared/src/types/budget.js";
|
||||
import type { RunnerApi } from "./api.js";
|
||||
|
||||
const optIn = "PAPERCLIP_CURSOR_CLOUD_ALLOW_UNPRICED_QUALIFICATION";
|
||||
const amount = 1_000;
|
||||
type QualificationPolicy = Pick<BudgetPolicySummary, "companyId" | "scopeType" | "scopeId" | "metric" | "windowKind"
|
||||
| "amount" | "hardStopEnabled" | "isActive" | "unpricedUsagePolicy">;
|
||||
export interface CursorCloudQualificationBudget {
|
||||
schema: "paperclip.e2e.cursor-cloud.qualification-budget.v1";
|
||||
unpricedUsageOptIn: true;
|
||||
policies: QualificationPolicy[];
|
||||
}
|
||||
|
||||
export function assertCursorCloudQualificationBudgetOptIn(environment: NodeJS.ProcessEnv = process.env): void {
|
||||
if (environment[optIn] !== "1") {
|
||||
throw new Error(`Cursor Cloud acceptance setup-blocked: explicitly approve unpriced qualification spend with ${optIn}=1. Provider cost remains unavailable.`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function configureCursorCloudQualificationBudget(input: {
|
||||
api: Pick<RunnerApi, "get" | "post">; companyId: string; agentId: string;
|
||||
}): Promise<CursorCloudQualificationBudget> {
|
||||
assertCursorCloudQualificationBudgetOptIn();
|
||||
const { api, companyId, agentId } = input;
|
||||
const scopes = [{ scopeType: "company", scopeId: companyId }, { scopeType: "agent", scopeId: agentId }] as const;
|
||||
const companyPath = `/api/companies/${encodeURIComponent(companyId)}`;
|
||||
for (const scope of scopes) {
|
||||
await api.post(`${companyPath}/budgets/policies`, { ...scope, metric: "billed_cents", windowKind: "calendar_month_utc",
|
||||
amount, hardStopEnabled: true, isActive: true, unpricedUsagePolicy: "allow" });
|
||||
}
|
||||
const overview = await api.get<BudgetOverview>(`${companyPath}/budgets/overview`);
|
||||
if (!overview || overview.companyId !== companyId || !Array.isArray(overview.policies)) {
|
||||
throw new Error("Cursor Cloud acceptance budget policy readback did not match the owned fixture company.");
|
||||
}
|
||||
const policies = scopes.map(scope => {
|
||||
const matches = overview.policies.filter(policy => policy && policy.scopeType === scope.scopeType && policy.scopeId === scope.scopeId);
|
||||
const policy = matches[0];
|
||||
if (matches.length !== 1 || !policy || policy.companyId !== companyId || policy.metric !== "billed_cents"
|
||||
|| policy.windowKind !== "calendar_month_utc" || policy.amount !== amount || policy.hardStopEnabled !== true
|
||||
|| policy.isActive !== true || policy.unpricedUsagePolicy !== "allow") {
|
||||
throw new Error(`Cursor Cloud acceptance budget policy readback did not preserve the ${scope.scopeType} qualification limit.`);
|
||||
}
|
||||
return { companyId: policy.companyId, scopeType: policy.scopeType, scopeId: policy.scopeId, metric: policy.metric,
|
||||
windowKind: policy.windowKind, amount: policy.amount, hardStopEnabled: policy.hardStopEnabled,
|
||||
isActive: policy.isActive, unpricedUsagePolicy: policy.unpricedUsagePolicy };
|
||||
});
|
||||
return { schema: "paperclip.e2e.cursor-cloud.qualification-budget.v1", unpricedUsageOptIn: true, policies };
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { createServer } from "node:http";
|
||||
import { RUNNER_TOOL_SCOPE_TOKEN_HEADER } from "../../packages/paperclip-runner/src/drivers/runner-tool-bridge.js";
|
||||
|
||||
export async function startCursorCloudCallbackProxy(input: { port: number; appPort: number }) {
|
||||
if (!Number.isInteger(input.port) || input.port < 1024 || input.port > 65535 || input.port === input.appPort) throw new Error("Cursor Cloud requires a distinct callback-only loopback port");
|
||||
const server = createServer(async (request, response) => {
|
||||
const callbackPath = /^\/mcp\/native-runs\/[a-f0-9-]{36}$/u.test(request.url ?? "");
|
||||
if (request.method === "GET" && callbackPath) {
|
||||
response.writeHead(405, { Allow: "POST" }).end(); request.resume(); return;
|
||||
}
|
||||
if (request.method !== "POST" || !callbackPath) {
|
||||
response.writeHead(404).end(); request.resume(); return;
|
||||
}
|
||||
try {
|
||||
const chunks: Buffer[] = []; let bytes = 0;
|
||||
for await (const chunk of request) {
|
||||
bytes += chunk.length;
|
||||
if (bytes > 2 * 1024 * 1024) { response.writeHead(413).end(); request.destroy(); return; }
|
||||
chunks.push(Buffer.from(chunk));
|
||||
}
|
||||
const headers: Record<string, string> = { "content-type": "application/json" };
|
||||
for (const key of ["authorization", "mcp-session-id", "mcp-protocol-version", RUNNER_TOOL_SCOPE_TOKEN_HEADER]) {
|
||||
const value = request.headers[key]; if (typeof value === "string") headers[key] = value;
|
||||
}
|
||||
const upstream = await fetch(`http://127.0.0.1:${input.appPort}${request.url}`, {
|
||||
method: "POST", headers, body: Buffer.concat(chunks), redirect: "error", signal: AbortSignal.timeout(65_000),
|
||||
});
|
||||
response.writeHead(upstream.status, { "content-type": "application/json", "cache-control": "no-store", ...(upstream.headers.get("mcp-session-id") ? { "mcp-session-id": upstream.headers.get("mcp-session-id")! } : {}) });
|
||||
if (upstream.body) for await (const chunk of upstream.body) response.write(chunk);
|
||||
response.end();
|
||||
} catch { if (!response.headersSent) response.writeHead(502); response.end(); }
|
||||
});
|
||||
server.requestTimeout = 70_000; server.headersTimeout = 10_000;
|
||||
await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(input.port, "127.0.0.1", resolve); });
|
||||
return async () => { server.closeAllConnections(); await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve())); };
|
||||
}
|
||||
|
||||
export async function assertCursorCloudCallbackIngress(origin: string, fetcher: typeof fetch = fetch) {
|
||||
for (const [path, status, method] of [["/", 404, "GET"], ["/api/health", 404, "GET"], ["/mcp/native-runs/00000000-0000-4000-8000-000000000000", 401, "POST"]] as const) {
|
||||
const response = await fetcher(new URL(path, origin), { method, redirect: "error", signal: AbortSignal.timeout(10_000), ...(method === "POST" ? { body: "{}", headers: { "content-type": "application/json" } } : {}) });
|
||||
await response.body?.cancel();
|
||||
if (response.status !== status) throw new Error("Cursor Cloud acceptance setup-blocked: public origin must expose only /mcp/native-runs/ through the dedicated callback listener");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import type { RunnerTaskFixture } from "./types.js";
|
||||
|
||||
export const CURSOR_CLOUD_SUITE = "cursor-cloud";
|
||||
export const CURSOR_CLOUD_QUIET_WINDOW_MS = 15_000;
|
||||
export function cursorCloudDefinitionDigest() {
|
||||
const hash = createHash("sha256");
|
||||
for (const file of ["catalog.ts", "cursor-cloud-cases.ts", "cursor-cloud-observer.ts", "cursor-cloud-stop-flow.ts", "cursor-cloud-stop-observation.ts", "cursor-cloud-callback-proxy.ts", "prerequisites.ts", "cursor-cloud-budget.ts", "live-fixtures.ts", "runner.spec.ts", "registered-artifact.ts"]) hash.update(file).update(readFileSync(new URL(file, import.meta.url)));
|
||||
return hash.digest("hex");
|
||||
}
|
||||
export const cursorCloudArtifactName = (nonce: string) => `cursor-cloud-${nonce}.txt`;
|
||||
export const cursorCloudStopArtifactName = (nonce: string) => `cursor-cloud-after-stop-${nonce}.txt`;
|
||||
|
||||
export const cursorCloudArtifactTask: RunnerTaskFixture = {
|
||||
id: "task-artifact", label: "Complete a task with a verified Cloud artifact", groups: [],
|
||||
workMode: "standard", flow: "single_turn", expectedRunCount: 1, automaticRetryPolicy: "single_attempt",
|
||||
attemptTimeoutMs: { local: 600_000, daytona: 600_000 }, turnTimeoutMs: 480_000,
|
||||
expectedTerminalState: { issue: "done", run: "succeeded" },
|
||||
buildTitle: nonce => `Cursor Cloud artifact ${nonce}`,
|
||||
buildVisibleMarker: nonce => `CURSOR-CLOUD-DONE-${nonce}`,
|
||||
buildPrompt: nonce => [
|
||||
`Create exactly one file named ${cursorCloudArtifactName(nonce)} in this Cursor Cloud environment's provider-supported artifact output directory containing exactly ${JSON.stringify(`verified-${nonce}\n`)} as UTF-8 bytes. Use the environment's documented output directory; do not assume a legacy absolute path.`,
|
||||
"Verify the actual bytes with a read-only command; use one real LF byte at the end.",
|
||||
`Call list_cursor_cloud_artifacts to find the exact relative provider path for ${cursorCloudArtifactName(nonce)}. Use register_deliverable to register it under that exact filename title with contentRef cursor-artifact:<exact relative path returned by the helper>, mimeType text/plain, the actual byteSize and SHA-256 digest. Use the returned durable deliverable reference in your completion evidence.`,
|
||||
`Call paperclip_finish with reportedWorkDisposition done, summary CURSOR-CLOUD-DONE-${nonce}, the current completion contract revision, satisfied objective criterion, no remaining work, and actual validation evidence. Wait for acceptance, then emit exactly CURSOR-CLOUD-DONE-${nonce}.`,
|
||||
"Do not create PRs, other tasks, agents, or unrelated files.",
|
||||
].join("\n"),
|
||||
buildMatchers: (nonce, execution) => [
|
||||
{ kind: "message_exact", expected: `CURSOR-CLOUD-DONE-${nonce}` },
|
||||
{ kind: "issue_status", expected: "done" }, { kind: "run_status", expected: "succeeded" },
|
||||
{ kind: "runtime_mode", expected: "native" }, { kind: "environment", expected: execution.environment.id },
|
||||
{ kind: "artifact_exact", name: cursorCloudArtifactName(nonce), expected: `verified-${nonce}\n`, mimeType: "text/plain" },
|
||||
],
|
||||
};
|
||||
|
||||
export const cursorCloudStopTask: RunnerTaskFixture = {
|
||||
id: "active-run-stop", label: "Stop an independently observed active Cloud run", groups: [],
|
||||
workMode: "standard", flow: "cursor_cloud_stop", expectedRunCount: 1, automaticRetryPolicy: "single_attempt",
|
||||
attemptTimeoutMs: { local: 480_000, daytona: 480_000 }, turnTimeoutMs: 360_000,
|
||||
expectedTerminalState: { issue: "in_progress", run: "cancelled" },
|
||||
buildTitle: nonce => `Cursor Cloud active Stop ${nonce}`,
|
||||
buildVisibleMarker: nonce => `CURSOR-CLOUD-STOP-${nonce}`,
|
||||
buildPrompt: nonce => [
|
||||
"Begin one native foreground shell command now. This acceptance fixture will be stopped by the operator while that command is active.",
|
||||
`Find the environment's documented artifact output directory using read-only tools. Then run this exact foreground shell command, replacing only /ABSOLUTE_OUTPUT_DIRECTORY with that directory: sleep 180 && printf 'MUST_NOT_APPEAR\\n' > '/ABSOLUTE_OUTPUT_DIRECTORY/${cursorCloudStopArtifactName(nonce)}'. Do not add a wrapper, background operator, extra command, or change the quoted output bytes.`,
|
||||
"Keep the command in the foreground. Do not background it, finish the task, retry after cancellation, register a deliverable, or create any other work. The operator's Stop is authoritative.",
|
||||
].join("\n"),
|
||||
buildMatchers: () => [],
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { nativeRunMcpRoutes } from "../../server/src/routes/native-run-mcp.js";
|
||||
import { createRemoteMcpRelayToken, registerRemoteMcpRelay } from "../../server/src/services/native-runtime/remote-mcp-relay.js";
|
||||
import { RUNNER_TOOL_SCOPE_TOKEN_HEADER, startRunnerToolBridge } from "../../packages/paperclip-runner/src/drivers/runner-tool-bridge.js";
|
||||
import { assertCursorCloudCallbackIngress, startCursorCloudCallbackProxy } from "./cursor-cloud-callback-proxy.js";
|
||||
|
||||
const require = createRequire(resolve(import.meta.dirname, "../../server/package.json"));
|
||||
const { Client } = await import(require.resolve("@modelcontextprotocol/sdk/client/index.js"));
|
||||
const { StreamableHTTPClientTransport } = await import(require.resolve("@modelcontextprotocol/sdk/client/streamableHttp.js"));
|
||||
const { default: express } = await import(require.resolve("express"));
|
||||
const cleanup: Array<() => void | Promise<void>> = [];
|
||||
afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); });
|
||||
const listen = async (server: Server) => {
|
||||
await new Promise<void>((accept, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", accept); });
|
||||
return (server.address() as { port: number }).port;
|
||||
};
|
||||
const close = (server: Server) => new Promise<void>((accept, reject) => { server.closeAllConnections(); server.close(error => error ? reject(error) : accept()); });
|
||||
|
||||
it("serves the strict MCP SDK through the Cloud callback with isolated sessions and fenced tools", async () => {
|
||||
const root = await mkdtemp(join(process.platform === "darwin" ? "/tmp" : tmpdir(), "cloud-sdk-"));
|
||||
cleanup.push(() => rm(root, { recursive: true, force: true }));
|
||||
const token = createRemoteMcpRelayToken();
|
||||
const runId = "00000000-0000-4000-8000-000000000762";
|
||||
let active = true, scope: string | null = "turn-one";
|
||||
let scopeToken = createRemoteMcpRelayToken();
|
||||
const calls: Array<{ tool: string; callId: string }> = [];
|
||||
const task = { taskId: "fixture-task", completionContractRevision: "fixture-revision" };
|
||||
const artifacts = { items: [{ path: "fixture.txt", sizeBytes: 12 }] };
|
||||
const schema = { type: "object", properties: {}, additionalProperties: false };
|
||||
const bridge = await startRunnerToolBridge({ socketPath: join(root, "mcp.sock"), secret: token, preserveToolNames: true,
|
||||
sessionScope: () => scope,
|
||||
scopeToken: () => scopeToken,
|
||||
tools: [{ name: "get_task_context", inputSchema: schema }, { name: "list_cursor_cloud_artifacts", inputSchema: schema }],
|
||||
handler: async call => { calls.push({ tool: call.tool, callId: call.callId }); return call.tool === "get_task_context" ? task : artifacts; },
|
||||
});
|
||||
cleanup.push(() => bridge.close());
|
||||
const binding = { runId, socketPath: join(root, "mcp.sock"), token, expiresAt: Date.now() + 60_000, authorized: async () => active };
|
||||
cleanup.push(registerRemoteMcpRelay(binding));
|
||||
const app = express(); app.use(express.json()); app.use(nativeRunMcpRoutes());
|
||||
const server = createServer(app); const appPort = await listen(server); cleanup.push(() => close(server));
|
||||
const reservation = createServer(); const port = await listen(reservation); await close(reservation);
|
||||
cleanup.push(await startCursorCloudCallbackProxy({ port, appPort }));
|
||||
const origin = `http://127.0.0.1:${port}`;
|
||||
await assertCursorCloudCallbackIngress(origin);
|
||||
const requests: Array<{ http: string; rpc: unknown; method?: string; tool?: string; session?: string | null; status: number }> = [];
|
||||
const errors: string[] = [];
|
||||
const connect = async (suppliedScopeToken = scopeToken) => {
|
||||
const client = new Client({ name: "controlled-cloud-qualification", version: "1" });
|
||||
client.onerror = (error: unknown) => errors.push(error instanceof Error ? error.message : String(error));
|
||||
const transport = new StreamableHTTPClientTransport(new URL(`/mcp/native-runs/${runId}`, origin), {
|
||||
requestInit: { headers: { Authorization: `Bearer ${token}`, [RUNNER_TOOL_SCOPE_TOKEN_HEADER]: `Bearer ${suppliedScopeToken}` } },
|
||||
fetch: async (url: string | URL | Request, init?: RequestInit) => {
|
||||
expect(new URL(url instanceof Request ? url.url : String(url)).origin).toBe(origin);
|
||||
const body = typeof init?.body === "string" ? JSON.parse(init.body) : {};
|
||||
const response = await fetch(url, init);
|
||||
requests.push({ http: init?.method ?? "GET", rpc: body.id, method: body.method, tool: body.params?.name,
|
||||
session: new Headers(init?.headers).get("mcp-session-id"), status: response.status });
|
||||
return response;
|
||||
},
|
||||
});
|
||||
cleanup.push(() => client.close());
|
||||
await client.connect(transport);
|
||||
return { client, transport };
|
||||
};
|
||||
const first = await connect().catch(error => { throw new Error("First scoped MCP initialize returned HTTP " + String(requests.at(-1)?.status), { cause: error }); });
|
||||
const tools = await first.client.listTools();
|
||||
expect(tools.tools.map((tool: { name: string }) => tool.name)).toEqual(expect.arrayContaining(["get_task_context", "list_cursor_cloud_artifacts", "paperclip_finish", "paperclip_block"]));
|
||||
expect(tools.tools.find((tool: { name: string }) => tool.name === "get_task_context").inputSchema).toEqual(schema);
|
||||
expect(JSON.parse((await first.client.callTool({ name: "get_task_context", arguments: {} })).content[0].text)).toEqual(task);
|
||||
expect(JSON.parse((await first.client.callTool({ name: "list_cursor_cloud_artifacts", arguments: {} })).content[0].text)).toEqual(artifacts);
|
||||
const second = await connect(); await second.client.listTools();
|
||||
expect(JSON.parse((await second.client.callTool({ name: "get_task_context", arguments: {} })).content[0].text)).toEqual(task);
|
||||
const contextCalls = calls.filter(call => call.tool === "get_task_context");
|
||||
expect(contextCalls).toHaveLength(2);
|
||||
expect(contextCalls[0].callId).not.toBe(contextCalls[1].callId);
|
||||
expect(first.transport.sessionId).not.toBe(second.transport.sessionId);
|
||||
expect(requests.filter(request => request.method === "initialize").map(request => request.rpc)).toEqual([0, 0]);
|
||||
const contextRequests = requests.filter(request => request.tool === "get_task_context");
|
||||
expect(contextRequests).toHaveLength(2); expect(contextRequests[0].rpc).toBe(contextRequests[1].rpc);
|
||||
await expect.poll(() => requests.filter(request => request.http === "GET").length).toBe(2);
|
||||
expect(requests.filter(request => request.http === "GET").map(request => request.status)).toEqual([405, 405]);
|
||||
const methodProbe = await fetch(`${origin}/mcp/native-runs/${runId}`);
|
||||
expect(methodProbe.status).toBe(405); expect(methodProbe.headers.get("allow")).toBe("POST");
|
||||
expect(errors).toEqual([]);
|
||||
scope = "turn-two";
|
||||
await expect(first.client.callTool({ name: "get_task_context", arguments: {} })).rejects.toHaveProperty("code", 404);
|
||||
const oldScopeToken = scopeToken;
|
||||
scopeToken = createRemoteMcpRelayToken();
|
||||
await expect(connect(oldScopeToken)).rejects.toHaveProperty("code", 401);
|
||||
const current = await connect();
|
||||
await expect(current.client.listTools()).resolves.toHaveProperty("tools");
|
||||
active = false;
|
||||
await expect(second.client.callTool({ name: "get_task_context", arguments: {} })).rejects.toHaveProperty("code", 403);
|
||||
binding.expiresAt = Date.now() - 1;
|
||||
await expect(second.client.callTool({ name: "get_task_context", arguments: {} })).rejects.toHaveProperty("code", 401);
|
||||
expect(calls).toHaveLength(3);
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { CursorCloudClient, CursorCloudClientError, isCursorCloudRunActive } from "../../packages/paperclip-runner/src/drivers/cursor-cloud/cloud-client.js";
|
||||
import { pollUntil, type RunnerApi } from "./api.js";
|
||||
import { collectRunEvents } from "./run-observations.js";
|
||||
import type { CleanupCheck } from "./cleanup-verification.js";
|
||||
|
||||
type Row = Record<string, any>;
|
||||
const record = (value: unknown): Row => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Row : {};
|
||||
const uuid = "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}";
|
||||
export interface CursorCloudRemoteIdentity { agentId: string; runId: string | null; ownerRunId: string; normalizedSessionId: string }
|
||||
|
||||
export function readCursorCloudRemoteIdentity(events: readonly unknown[], ownerRunId: string): CursorCloudRemoteIdentity | undefined {
|
||||
let found: CursorCloudRemoteIdentity | undefined;
|
||||
for (const value of events) {
|
||||
const row = record(value), event = record(record(row.payload).prpEvent), payload = record(event.payload);
|
||||
if (row.runId !== ownerRunId || row.protocolSchemaVersion !== 1 || event.sourceKind !== "runner"
|
||||
|| event.schema !== "paperclip.prp.event.v1" || event.schemaVersion !== 1 || event.runId !== ownerRunId
|
||||
|| event.eventType !== "provider.notice.recorded" || typeof payload.summary !== "string" || payload.summary.length > 4096) continue;
|
||||
let identity: Row; try { identity = record(JSON.parse(payload.summary)); } catch { continue; }
|
||||
if (identity.schema !== "paperclip.cursor-cloud.remote-identity.v1") continue;
|
||||
if (identity.provider !== "cursor_cloud" || identity.ownerRunId !== ownerRunId
|
||||
|| typeof identity.agentId !== "string" || !new RegExp(`^bc-${uuid}$`, "u").test(identity.agentId)
|
||||
|| !(identity.runId === null || typeof identity.runId === "string" && new RegExp(`^run-${uuid}$`, "u").test(identity.runId))
|
||||
|| typeof identity.normalizedSessionId !== "string" || !identity.normalizedSessionId || identity.normalizedSessionId.length > 512) throw new Error("Cloud observer identity has an invalid owner or native identifier");
|
||||
if (found && (found.agentId !== identity.agentId || found.normalizedSessionId !== identity.normalizedSessionId || found.runId && identity.runId && found.runId !== identity.runId)) throw new Error("Cloud observer identity changed within one local run");
|
||||
found = { agentId: identity.agentId, runId: identity.runId ?? found?.runId ?? null, ownerRunId, normalizedSessionId: identity.normalizedSessionId };
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
export const cursorCloudIdentityProof = (identity: CursorCloudRemoteIdentity) => Object.fromEntries(
|
||||
Object.entries(identity).map(([key, value]) => [key === "ownerRunId" ? key : `${key}Sha256`, key === "ownerRunId" || value === null ? value : createHash("sha256").update(value).digest("hex")]),
|
||||
);
|
||||
|
||||
export class CursorCloudOwnedObserver {
|
||||
readonly identities = new Map<string, CursorCloudRemoteIdentity>();
|
||||
readonly client: CursorCloudClient;
|
||||
constructor(readonly api: RunnerApi, readonly companyId: string, readonly agentId: string, apiKey: string) {
|
||||
this.client = new CursorCloudClient({ apiKey, requestTimeoutMs: 10_000 });
|
||||
}
|
||||
async refresh() {
|
||||
const list = await this.api.get<Row[]>(`/api/companies/${this.companyId}/heartbeat-runs?limit=100`);
|
||||
if (list.length > 8) throw new Error("Cloud observer run bound exceeded");
|
||||
const rows = await Promise.all(list.map(row => this.api.get<Row>(`/api/heartbeat-runs/${row.id}`)));
|
||||
for (const run of rows) {
|
||||
if (run.companyId !== this.companyId || run.agentId !== this.agentId) throw new Error("Cloud observer refuses an unrelated run");
|
||||
const events = await collectRunEvents<Row>((afterSeq, limit) => this.api.get(`/api/heartbeat-runs/${run.id}/events?afterSeq=${afterSeq}&limit=${limit}`));
|
||||
const identity = readCursorCloudRemoteIdentity(events, run.id);
|
||||
if (identity) this.identities.set(run.id, identity);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
async assertContinuity(expectedRuns: number): Promise<CleanupCheck[]> {
|
||||
const rows = await this.refresh(), ids = rows.map(row => this.identities.get(row.id));
|
||||
const complete = rows.length === expectedRuns && ids.every(identity => identity?.runId);
|
||||
const sameAgent = complete && new Set(ids.map(identity => identity!.agentId)).size === 1;
|
||||
const distinctRuns = complete && new Set(ids.map(identity => identity!.runId)).size === expectedRuns;
|
||||
const sameSession = complete && new Set(ids.map(identity => identity!.normalizedSessionId)).size === 1;
|
||||
return [{ id: "cloud-owned-provider-continuity", passed: Boolean(sameAgent && distinctRuns && sameSession), detail: "Every local turn has its own durable Cloud run on the same owned Cloud agent and normalized session" }];
|
||||
}
|
||||
async assertPlanTransitions(ownerRunIds: readonly string[], acceptedInteractionId: string | null): Promise<CleanupCheck[]> {
|
||||
const rows = await this.refresh(), ids = ownerRunIds.map(id => this.identities.get(id));
|
||||
const complete = rows.length === 3 && ownerRunIds.length === 3 && new Set(ownerRunIds).size === 3
|
||||
&& rows.every(row => ownerRunIds.includes(row.id)) && ids.every(identity => identity?.runId);
|
||||
const distinctRuns = complete && new Set(ids.map(identity => identity!.runId)).size === 3;
|
||||
const draftContinued = complete && ids[0]!.agentId === ids[1]!.agentId
|
||||
&& ids[0]!.normalizedSessionId === ids[1]!.normalizedSessionId;
|
||||
const accepted = rows.find(row => row.id === ownerRunIds[2]), context = record(accepted?.contextSnapshot);
|
||||
const freshAccepted = complete && ids[2]!.agentId !== ids[1]!.agentId
|
||||
&& ids[2]!.normalizedSessionId !== ids[1]!.normalizedSessionId && !accepted?.sessionIdBefore
|
||||
&& context.forceFreshSession === true && context.workspaceRefreshReason === "accepted_plan_confirmation"
|
||||
&& context.source === "issue.interaction.accept" && context.interactionStatus === "accepted"
|
||||
&& Boolean(acceptedInteractionId) && context.interactionId === acceptedInteractionId;
|
||||
return [{ id: "cloud-owned-plan-session-transitions", passed: Boolean(distinctRuns && draftContinued && freshAccepted),
|
||||
detail: "Draft and revised Plan share an owned Cloud session; approval of the exact revised interaction starts a fresh owned session, with three distinct Cloud runs" }];
|
||||
}
|
||||
async cleanup(): Promise<CleanupCheck[]> {
|
||||
const errors: string[] = [];
|
||||
let reconciledReplies = 0;
|
||||
const failed = (stage: string, error: unknown) => errors.push(`${stage}:${error instanceof CursorCloudClientError ? `${error.code}${error.status ? `-${error.status}` : ""}` : "verification"}`);
|
||||
try {
|
||||
const rows = await this.refresh();
|
||||
if (rows.some(row => !this.identities.has(row.id))) errors.push("ownership:incomplete");
|
||||
} catch (error) { failed("ownership", error); }
|
||||
const agents = new Set([...this.identities.values()].map(identity => identity.agentId));
|
||||
for (const agentId of agents) {
|
||||
try {
|
||||
for (const identity of this.identities.values()) if (identity.agentId === agentId && identity.runId) {
|
||||
const run = await this.client.getRun(agentId, identity.runId);
|
||||
if (isCursorCloudRunActive(run.status)) {
|
||||
await this.client.cancelRun(agentId, identity.runId);
|
||||
await pollUntil({ label: "owned Cloud cleanup cancellation", deadlineAt: Date.now() + 30_000, intervalMs: 500,
|
||||
load: () => this.client.getRun(agentId, identity.runId!), accept: result => !isCursorCloudRunActive(result.status), retryOnError: () => false });
|
||||
}
|
||||
}
|
||||
} catch (error) { if (!(error instanceof CursorCloudClientError && error.status === 404)) failed("cancel", error); }
|
||||
finally {
|
||||
let uncertainReply: unknown;
|
||||
try { await this.client.deleteAgent(agentId); }
|
||||
catch (error) {
|
||||
if (!(error instanceof CursorCloudClientError && error.status === 404)) {
|
||||
if (error instanceof CursorCloudClientError && (["network_error", "timeout", "invalid_response"].includes(error.code) || (error.status !== undefined && error.status >= 500))) uncertainReply = error;
|
||||
else failed("delete", error);
|
||||
}
|
||||
}
|
||||
try {
|
||||
const deadlineAt = Date.now() + 30_000;
|
||||
await pollUntil({ label: "owned Cloud cleanup absence", deadlineAt, intervalMs: 1_000,
|
||||
load: async () => {
|
||||
try {
|
||||
await this.client.getAgent(agentId, { signal: AbortSignal.timeout(Math.max(1, deadlineAt - Date.now())) });
|
||||
return false;
|
||||
} catch (error) {
|
||||
if (error instanceof CursorCloudClientError && error.status === 404) return true;
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
accept: absent => absent,
|
||||
retryOnError: () => false,
|
||||
});
|
||||
if (uncertainReply) reconciledReplies += 1;
|
||||
} catch (error) {
|
||||
failed("absence", error);
|
||||
if (uncertainReply) failed("delete", uncertainReply);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [{ id: "cloud-owned-agent-cleanup", passed: errors.length === 0, detail: errors.length ? `Owned Cloud resource cleanup could not be confirmed (${errors.join(", ")})` : `Confirmed absence of ${agents.size} Cloud agent(s) bound by persisted runner notices${reconciledReplies ? `; reconciled ${reconciledReplies} ambiguous deletion reply/replies` : ""}; unrelated agents were untouched` }];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { CursorCloudClient } from "../../packages/paperclip-runner/src/drivers/cursor-cloud/cloud-client.js";
|
||||
import { CursorCloudDriver } from "../../packages/paperclip-runner/src/drivers/cursor-cloud/cursor-cloud-driver.js";
|
||||
import type { PrpEvent } from "../../packages/paperclip-runner/src/protocol/replay-contract.js";
|
||||
import { createCursorCloudReplayFaultFetch, gradeCursorCloudReplayFault, installCursorCloudReplayFault, readCursorCloudReplayFaultProofs, readCursorCloudReplayFaultReservation, withCursorCloudReplayFault, type CursorCloudReplayFaultProof } from "./cursor-cloud-replay-fault.js";
|
||||
|
||||
const agent = "bc-11111111-1111-4111-8111-111111111111", run = "run-22222222-2222-4222-8222-222222222222";
|
||||
const url = `https://api.cursor.com/v1/agents/${agent}/runs/${run}/stream`;
|
||||
const digest = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex");
|
||||
const expected = [{ agentIdSha256: digest(agent), runIdSha256: digest(run) }];
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))); });
|
||||
async function root() { const directory = await mkdtemp(join(process.platform === "darwin" ? "/tmp" : tmpdir(), "cc-replay-")); roots.push(directory); return directory; }
|
||||
function bytes(parts: readonly Uint8Array[], onCancel = vi.fn()) {
|
||||
let index = 0;
|
||||
return new Response(new ReadableStream<Uint8Array>({ pull(controller) { if (index < parts.length) controller.enqueue(parts[index++]!); else controller.close(); }, cancel: onCancel }, { highWaterMark: 0 }), { headers: { "content-type": "text/event-stream" } });
|
||||
}
|
||||
async function readUntilCut(response: Response) {
|
||||
const reader = response.body!.getReader(), chunks: Uint8Array[] = [];
|
||||
let failure: unknown;
|
||||
try { while (true) { const next = await reader.read(); if (next.done) break; chunks.push(next.value); } } catch (error) { failure = error; }
|
||||
return { value: Buffer.concat(chunks).toString("utf8"), failure };
|
||||
}
|
||||
function fixture(response: () => Response) {
|
||||
let proof: CursorCloudReplayFaultProof | undefined;
|
||||
const original = vi.fn(async () => response());
|
||||
return { original, fetch: createCursorCloudReplayFaultFetch({ fetch: original as typeof fetch, digest, record: value => { proof = value; } }), proof: () => proof! };
|
||||
}
|
||||
|
||||
describe("Cursor Cloud live replay fault framing", () => {
|
||||
it.each(["\n", "\r\n", "\r"])("cuts after exact complete native bytes across every chunk boundary (%j)", async newline => {
|
||||
const prefix = `: keepalive${newline}${newline}id: ignored${newline}${newline}`;
|
||||
const frame = `event: assistant${newline}id: old${newline}id: opaque-cursor${newline}data: {"text":"private provider canary 🌱"}${newline}${newline}`;
|
||||
const trailing = `event: done${newline}data: {}${newline}${newline}`;
|
||||
const complete = Buffer.from(prefix + frame + trailing);
|
||||
const cancellation = vi.fn();
|
||||
const f = fixture(() => bytes([...complete].map(byte => Uint8Array.of(byte)), cancellation));
|
||||
const first = await readUntilCut(await f.fetch(url));
|
||||
expect(first.value).toBe(prefix + frame); expect(first.failure).toBeInstanceOf(Error); expect(cancellation).toHaveBeenCalledTimes(1);
|
||||
expect(f.proof().cut).toMatchObject({ eventIdSha256: digest("opaque-cursor"), frameSha256: digest(frame), frameBytes: Buffer.byteLength(frame), event: "assistant" });
|
||||
await f.fetch(url, { headers: { "Last-Event-ID": "opaque-cursor" } });
|
||||
expect(gradeCursorCloudReplayFault([f.proof()], expected).passed).toBe(true);
|
||||
const serialized = JSON.stringify(f.proof());
|
||||
for (const privateValue of [agent, run, "opaque-cursor", "private provider canary"]) expect(serialized).not.toContain(privateValue);
|
||||
});
|
||||
it("forwards several frames from one chunk without delivering post-cut bytes", async () => {
|
||||
const prefix = 'event: status\nid: start\ndata: {"status":"RUNNING"}\n\n';
|
||||
const frame = 'event: tool_call\nid: cut\ndata: {"status":"running"}\n\n';
|
||||
const f = fixture(() => bytes([Buffer.from(prefix + frame + 'event: assistant\nid: later\ndata: {"text":"later"}\n\n')]));
|
||||
expect((await readUntilCut(await f.fetch(url))).value).toBe(prefix + frame);
|
||||
expect(f.proof().cutCount).toBe(1);
|
||||
});
|
||||
it("delivers the disconnect even when upstream cancellation never settles", async () => {
|
||||
const cancellation = vi.fn(() => new Promise<void>(() => {}));
|
||||
const f = fixture(() => bytes([Buffer.from('event: assistant\nid: cut\ndata: {"text":"working"}\n\n')], cancellation));
|
||||
const observed = await Promise.race([readUntilCut(await f.fetch(url)), new Promise<never>((_resolve, reject) => { const timer = setTimeout(() => reject(new Error("disconnect was suppressed by cancellation")), 250); timer.unref(); })]);
|
||||
expect(observed.failure).toBeInstanceOf(Error); expect(f.proof().cutCount).toBe(1); expect(cancellation).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("bounds individual frames without rejecting a larger chunk of valid frames", async () => {
|
||||
const prefix = ": " + "x".repeat(800_000) + "\n\n";
|
||||
const frame = 'event: assistant\nid: cursor\ndata: {"text":"' + "y".repeat(300_000) + '"}\n\n';
|
||||
const f = fixture(() => bytes([Buffer.from(prefix + frame)]));
|
||||
expect((await readUntilCut(await f.fetch(url))).value).toBe(prefix + frame); expect(f.proof().cutCount).toBe(1);
|
||||
});
|
||||
it.each([
|
||||
'id: alone\n\n: comment\n\n',
|
||||
'event: assistant\nid:\ndata: {"text":"no cursor"}\n\n',
|
||||
'event: assistant\nid: invalid\u0000id\ndata: {"text":"bad cursor"}\n\n',
|
||||
'event: assistant\nid: unfinished\ndata: {"text":"partial"}',
|
||||
'event: assistant\nid: malformed\ndata: not-json\n\n',
|
||||
'event: result\nid: terminal\ndata: {"status":"FINISHED"}\n\nevent: done\nid: done\ndata: {}\n\n',
|
||||
])("does not invent a cut for an undispatched, malformed or terminal frame", async content => {
|
||||
const f = fixture(() => bytes([Buffer.from(content)]));
|
||||
const observed = await readUntilCut(await f.fetch(url));
|
||||
expect(observed).toEqual({ value: content, failure: undefined });
|
||||
expect(f.proof().cutCount).toBe(0); expect(gradeCursorCloudReplayFault([f.proof()], expected).passed).toBe(false);
|
||||
});
|
||||
it("delegates fetch arguments unchanged and never intercepts a different route, host or method", async () => {
|
||||
const original = vi.fn(async (_resource: Parameters<typeof fetch>[0], _init?: Parameters<typeof fetch>[1]) => new Response("ordinary response"));
|
||||
const records = vi.fn();
|
||||
const wrapped = createCursorCloudReplayFaultFetch({ fetch: original as typeof fetch, digest, record: records });
|
||||
const init = { method: "POST", headers: { authorization: "Bearer private-auth-canary" }, body: "private-request-canary", redirect: "error" as const };
|
||||
await wrapped(url, init);
|
||||
expect(original.mock.calls[0]).toEqual([url, init]);
|
||||
const request = new Request(url.replace("api.cursor.com", "other.example.test"), { headers: init.headers });
|
||||
await wrapped(request); await wrapped(url + "?private-query-canary"); await wrapped(url.replace("https:", "http:"));
|
||||
expect(original.mock.calls[1]?.[0]).toBe(request); expect(records).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cursor Cloud replay evidence calibration", () => {
|
||||
async function goodProof() {
|
||||
const f = fixture(() => bytes([Buffer.from('event: assistant\nid: cursor\ndata: {"text":"working"}\n\n')]));
|
||||
await readUntilCut(await f.fetch(url)); await f.fetch(url, { headers: { "Last-Event-ID": "cursor" } }); return f.proof();
|
||||
}
|
||||
it.each(["missing", "no-cut", "repeated-cut", "agent", "run", "cursor", "failed-request", "not-sse", "extra-secret", "unowned", "missing-owned"])("fails closed for %s evidence", async reason => {
|
||||
const proof = await goodProof();
|
||||
if (reason === "no-cut") proof.cutCount = 0;
|
||||
if (reason === "repeated-cut") proof.cutCount = 2;
|
||||
if (reason === "agent") proof.reconnect!.agentIdSha256 = digest("foreign-agent");
|
||||
if (reason === "run") proof.reconnect!.runIdSha256 = digest("foreign-run");
|
||||
if (reason === "cursor") proof.reconnect!.lastEventIdSha256 = digest("wrong-cursor");
|
||||
if (reason === "failed-request") proof.reconnect!.httpStatus = 503;
|
||||
if (reason === "not-sse") proof.reconnect!.sseReady = false;
|
||||
if (reason === "extra-secret") Object.assign(proof, { token: "private-auth-canary" });
|
||||
const identities = reason === "unowned" ? [{ agentIdSha256: digest("foreign"), runIdSha256: digest("foreign") }]
|
||||
: reason === "missing-owned" ? [...expected, { agentIdSha256: digest("other"), runIdSha256: digest("other") }] : expected;
|
||||
expect(gradeCursorCloudReplayFault(reason === "missing" ? [] : [proof], identities).passed).toBe(false);
|
||||
});
|
||||
it("requires one cut total and distinct owned observations for every turn", async () => {
|
||||
const selected = await goodProof(), other = { agentIdSha256: digest(agent), runIdSha256: digest("other-owned-run") };
|
||||
const untouched = { schema: selected.schema, identity: other, streamRequests: 1, cutCount: 0, cut: null, reconnect: null };
|
||||
const owned = [...expected, other];
|
||||
expect(gradeCursorCloudReplayFault([selected, untouched], owned).passed).toBe(true);
|
||||
const secondCut = structuredClone(selected);
|
||||
secondCut.identity = other; Object.assign(secondCut.cut!, other); Object.assign(secondCut.reconnect!, other);
|
||||
expect(gradeCursorCloudReplayFault([selected, secondCut], owned).passed).toBe(false);
|
||||
expect(gradeCursorCloudReplayFault([selected, { ...untouched, identity: selected.identity }], owned).passed).toBe(false);
|
||||
expect(gradeCursorCloudReplayFault([selected, { ...untouched, identity: { ...other, runIdSha256: digest("foreign-run") } }], owned).passed).toBe(false);
|
||||
expect(gradeCursorCloudReplayFault([selected], owned).passed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cursor Cloud replay bundle treatment", () => {
|
||||
it("reserves exactly one cut across two real per-turn Node processes", async () => {
|
||||
const directory = await root(), bundlePath = join(directory, "proxy.cjs"), peerPath = join(directory, "peer.cjs"), evidenceDirectory = join(directory, "evidence");
|
||||
const secondRun = "run-33333333-3333-4333-8333-333333333333";
|
||||
await writeFile(peerPath, `globalThis.fetch = async (_input, init) => {
|
||||
globalThis.streamRequests = (globalThis.streamRequests ?? 0) + 1;
|
||||
if (init?.headers && new Headers(init.headers).get("Last-Event-ID") !== "shared-cursor") throw new Error("wrong resume cursor");
|
||||
return new Response('event: assistant\\nid: shared-cursor\\ndata: {"text":"private native content"}\\n\\nevent: result\\nid: terminal\\ndata: {}\\n\\n', {headers: {"content-type": "text/event-stream"}});
|
||||
};\n`);
|
||||
const original = Buffer.from(`#!/usr/bin/env node\n;(async () => {
|
||||
const target = "https://api.cursor.com/v1/agents/${agent}/runs/" + process.argv[2] + "/stream";
|
||||
let cut = false;
|
||||
try { await (await fetch(target)).text(); } catch { cut = true; }
|
||||
if (cut) await (await fetch(target, {headers: {"Last-Event-ID": "shared-cursor"}})).text();
|
||||
process.stdout.write(JSON.stringify({pid: process.pid, cut, requests: globalThis.streamRequests}));
|
||||
})().catch(error => { process.stderr.write(String(error)); process.exitCode = 1; });\n`);
|
||||
await writeFile(bundlePath, original, { mode: 0o600 });
|
||||
await withCursorCloudReplayFault({ bundlePath, evidenceDirectory }, async manifest => {
|
||||
const execute = (runId: string) => new Promise<{ code: number | null; output: string }>((resolve, reject) => {
|
||||
const child = spawn(process.execPath, ["--require", peerPath, bundlePath, runId], { stdio: ["ignore", "pipe", "pipe"], env: { PATH: process.env.PATH } });
|
||||
let output = ""; child.stdout.on("data", value => { output += value; }); child.stderr.on("data", value => { output += value; }); child.once("error", reject); child.once("exit", code => resolve({ code, output }));
|
||||
});
|
||||
const outcomes = await Promise.all([execute(run), execute(secondRun)]);
|
||||
expect(outcomes.map(outcome => outcome.code)).toEqual([0, 0]);
|
||||
const turns = outcomes.map(outcome => JSON.parse(outcome.output));
|
||||
expect(new Set(turns.map(turn => turn.pid)).size).toBe(2);
|
||||
expect(turns.filter(turn => turn.cut)).toHaveLength(1);
|
||||
expect(turns.map(turn => turn.requests).sort()).toEqual([1, 2]);
|
||||
const proofs = await readCursorCloudReplayFaultProofs(evidenceDirectory, manifest);
|
||||
expect(proofs).toHaveLength(2);
|
||||
const reservation = await readCursorCloudReplayFaultReservation(evidenceDirectory, manifest);
|
||||
const selected = (proofs as CursorCloudReplayFaultProof[]).find(proof => proof.cutCount === 1)!;
|
||||
expect(reservation).toMatchObject({ treatmentId: manifest.treatmentId, processId: turns.find(turn => turn.cut).pid, ...selected.identity });
|
||||
expect(gradeCursorCloudReplayFault(proofs, [...expected, { agentIdSha256: digest(agent), runIdSha256: digest(secondRun) }]).passed).toBe(true);
|
||||
expect(JSON.stringify(proofs)).not.toContain("private native content");
|
||||
});
|
||||
expect(await readFile(bundlePath)).toEqual(original);
|
||||
});
|
||||
it("runs a self-contained generated prelude, preserves shebang and restores exact bytes on failure", async () => {
|
||||
const directory = await root(), bundlePath = join(directory, "proxy.cjs"), evidenceDirectory = join(directory, "evidence");
|
||||
const original = Buffer.from(`#!/usr/bin/env node\nconst oldFetch = globalThis.fetch;\nif (oldFetch === undefined) throw new Error("missing fetch");\nprocess.stdout.write("proxy body ran");\n`);
|
||||
await writeFile(bundlePath, original, { mode: 0o700 });
|
||||
await expect(withCursorCloudReplayFault({ bundlePath, evidenceDirectory }, async manifest => {
|
||||
const treated = await readFile(bundlePath);
|
||||
expect(treated.toString().startsWith("#!/usr/bin/env node\n;")).toBe(true);
|
||||
expect(manifest.originalProxySha256).toBe(digest(original)); expect(manifest.instrumentedProxySha256).toBe(digest(treated));
|
||||
const result = await new Promise<{ code: number | null; output: string }>((resolve, reject) => {
|
||||
const child = spawn(process.execPath, [bundlePath], { stdio: ["ignore", "pipe", "pipe"], env: { PATH: process.env.PATH } });
|
||||
let output = ""; child.stdout.on("data", value => { output += value; }); child.stderr.on("data", value => { output += value; }); child.once("error", reject); child.once("exit", code => resolve({ code, output }));
|
||||
});
|
||||
expect(result).toEqual({ code: 0, output: "proxy body ran" });
|
||||
expect(await readCursorCloudReplayFaultProofs(evidenceDirectory, manifest)).toEqual([]);
|
||||
expect(await readFile(join(evidenceDirectory, `original-proxy-${manifest.treatmentId}.cjs`))).toEqual(original);
|
||||
throw new Error("intentional acceptance failure");
|
||||
})).rejects.toThrow("intentional acceptance failure");
|
||||
expect(await readFile(bundlePath)).toEqual(original);
|
||||
});
|
||||
it("refuses double installation and refuses to overwrite another writer during restore", async () => {
|
||||
const directory = await root(), bundlePath = join(directory, "proxy.cjs"), evidenceDirectory = join(directory, "evidence");
|
||||
await writeFile(bundlePath, "process.exit(0);\n");
|
||||
const treatment = await installCursorCloudReplayFault({ bundlePath, evidenceDirectory });
|
||||
await expect(installCursorCloudReplayFault({ bundlePath, evidenceDirectory })).rejects.toThrow("already installed");
|
||||
await writeFile(bundlePath, "other writer\n");
|
||||
await expect(treatment.restore()).rejects.toThrow("refusing to overwrite"); expect(await readFile(bundlePath, "utf8")).toBe("other writer\n");
|
||||
});
|
||||
it("serializes the prelude under the same tsx loader used by the paid launcher", async () => {
|
||||
const directory = await root(), bundlePath = join(directory, "proxy.cjs"), evidenceDirectory = join(directory, "evidence");
|
||||
const original = '#!/usr/bin/env node\nprocess.stdout.write("tsx proxy ran");\n';
|
||||
await writeFile(bundlePath, original);
|
||||
const code = `import {spawnSync} from "node:child_process";
|
||||
const {withCursorCloudReplayFault} = await import(${JSON.stringify(new URL("./cursor-cloud-replay-fault.ts", import.meta.url).href)});
|
||||
await withCursorCloudReplayFault(${JSON.stringify({ bundlePath, evidenceDirectory })}, async () => {
|
||||
const result = spawnSync(process.execPath, [${JSON.stringify(bundlePath)}], {encoding: "utf8"});
|
||||
if (result.status !== 0 || result.stdout !== "tsx proxy ran") throw new Error("tsx proxy prelude failed: " + result.stderr);
|
||||
}); process.stdout.write("tsx passed");`;
|
||||
const result = await new Promise<{ code: number | null; output: string }>((resolve, reject) => {
|
||||
const child = spawn(process.execPath, ["--import", new URL("../../cli/node_modules/tsx/dist/loader.mjs", import.meta.url).href, "--input-type=module", "--eval", code], { stdio: ["ignore", "pipe", "pipe"], env: { PATH: process.env.PATH } });
|
||||
let output = ""; child.stdout.on("data", value => { output += value; }); child.stderr.on("data", value => { output += value; }); child.once("error", reject); child.once("exit", code => resolve({ code, output }));
|
||||
});
|
||||
expect(result).toEqual({ code: 0, output: "tsx passed" }); expect(await readFile(bundlePath, "utf8")).toBe(original);
|
||||
});
|
||||
});
|
||||
|
||||
it("the actual driver reconnects the real client with its saved cursor and deduplicates the replayed frame without creating another prompt", async () => {
|
||||
const directory = await root(), events: PrpEvent[] = [], proofs: CursorCloudReplayFaultProof[] = [];
|
||||
const nativeRun = "run-33333333-3333-4333-8333-333333333333", time = "2026-10-28T00:00:00Z";
|
||||
let nativeAgent = "", creates = 0, streams = 0;
|
||||
const requests: Array<{ path: string; headers: Headers }> = [];
|
||||
const peer: typeof fetch = async (resource, init) => {
|
||||
const path = new URL(String(resource)).pathname, headers = new Headers(init?.headers); requests.push({ path, headers });
|
||||
if (path === "/v1/agents" && init?.method === "POST") {
|
||||
creates += 1; nativeAgent = JSON.parse(String(init.body)).agentId;
|
||||
return Response.json({ agent: { id: nativeAgent, status: "ACTIVE", env: { type: "cloud" }, url: "https://cursor.com/agents/example", createdAt: time, updatedAt: time }, run: { id: nativeRun, agentId: nativeAgent, status: "RUNNING", createdAt: time, updatedAt: time } }, { status: 201 });
|
||||
}
|
||||
if (path.endsWith("/stream")) {
|
||||
streams += 1;
|
||||
const first = 'event: assistant\nid: opaque-cursor\ndata: {"text":"Working."}\n\n';
|
||||
const withheld = 'event: assistant\nid: withheld\ndata: {"text":"must be replayed"}\n\n';
|
||||
return bytes([Buffer.from(first + withheld + (streams === 1 ? "" : `event: assistant\nid: new-cursor\ndata: {"text":"Recovered."}\n\nevent: result\nid: terminal\ndata: {"runId":"${nativeRun}","status":"FINISHED"}\n\n`))]);
|
||||
}
|
||||
if (path.endsWith(nativeRun)) return Response.json({ id: nativeRun, agentId: nativeAgent, status: streams < 2 ? "RUNNING" : "FINISHED", createdAt: time, updatedAt: time });
|
||||
throw new Error("Unexpected controlled request");
|
||||
};
|
||||
const client = new CursorCloudClient({ apiKey: "private-auth-canary", fetch: createCursorCloudReplayFaultFetch({ fetch: peer, digest, record: value => proofs.push(value) }) });
|
||||
const driver = new CursorCloudDriver({ model: "explicit-model", config: { schema: "paperclip.cursor-cloud.config.v1", repos: [{ url: "https://github.com/example/disposable", startingRef: "main" }] }, binding: { companyId: "company", agentId: "agent", issueId: "issue", normalizedSessionId: "session" }, runtimeDirectory: directory,
|
||||
relay: { url: "https://relay.example.test/mcp", token: "private-relay-canary", socketPath: join(directory, "mcp.sock"), expiresAt: Date.now() + 60_000 }, instructions: "Exact fixture instructions.", dynamicTools: [], dynamicToolHandler: async () => ({ success: true }), client, reconnectDelayMs: 1 });
|
||||
const session = await driver.openSession({ runId: "local-run", normalizedSessionId: "session", workingDirectory: directory });
|
||||
const pump = (async () => { for await (const event of session.events()) events.push(event); })();
|
||||
try {
|
||||
await session.startTurn({ message: { role: "user", text: "Recover this exact run." } });
|
||||
await vi.waitFor(() => expect(events.some(event => event.eventType === "turn.completed")).toBe(true));
|
||||
expect(creates).toBe(1); expect(streams).toBe(2);
|
||||
const streamRequests = requests.filter(request => request.path.endsWith("/stream"));
|
||||
expect(streamRequests[0]!.headers.has("Last-Event-ID")).toBe(false); expect(streamRequests[1]!.headers.get("Last-Event-ID")).toBe("opaque-cursor");
|
||||
expect(requests.every(request => request.headers.get("authorization") === "Bearer private-auth-canary")).toBe(true);
|
||||
expect(events.filter(event => event.eventType === "item.delta").map(event => event.payload.text)).toEqual(["Working.", "must be replayed", "Recovered."]);
|
||||
expect(events.every((event, index) => index === 0 || event.sourceSeq > events[index - 1]!.sourceSeq)).toBe(true);
|
||||
expect(gradeCursorCloudReplayFault([proofs.at(-1)!], [{ agentIdSha256: digest(nativeAgent), runIdSha256: digest(nativeRun) }]).passed).toBe(true);
|
||||
expect(JSON.stringify(proofs)).not.toContain("private-auth-canary"); expect(JSON.stringify(proofs)).not.toContain("opaque-cursor");
|
||||
} finally { await session.close({ reason: "test_cleanup" }); await pump; }
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, mkdir, open, readFile, readdir, rename, writeFile } from "node:fs/promises";
|
||||
import { isAbsolute, join } from "node:path";
|
||||
|
||||
const SCHEMA = "paperclip.cursor-cloud.replay-fault.v1";
|
||||
const MAX_FRAME_BYTES = 1_048_576;
|
||||
const sha256 = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex");
|
||||
type Cut = { agentIdSha256: string; runIdSha256: string; eventIdSha256: string; frameSha256: string; frameBytes: number; event: string };
|
||||
type Identity = Pick<Cut, "agentIdSha256" | "runIdSha256">;
|
||||
export interface CursorCloudReplayFaultProof {
|
||||
schema: typeof SCHEMA;
|
||||
identity: Identity | null;
|
||||
streamRequests: number;
|
||||
cutCount: number;
|
||||
cut: Cut | null;
|
||||
reconnect: { agentIdSha256: string; runIdSha256: string; lastEventIdSha256: string | null; cursorMatches: boolean; httpStatus: number; sseReady: boolean } | null;
|
||||
}
|
||||
export interface CursorCloudReplayFaultManifest {
|
||||
schema: "paperclip.cursor-cloud.replay-instrumentation.v1";
|
||||
treatmentId: string;
|
||||
originalProxySha256: string;
|
||||
instrumentedProxySha256: string;
|
||||
reservationFile: string;
|
||||
}
|
||||
export interface CursorCloudReplayFaultReservation extends Identity {
|
||||
schema: "paperclip.cursor-cloud.replay-reservation.v1";
|
||||
treatmentId: string;
|
||||
processId: number;
|
||||
}
|
||||
|
||||
export function createCursorCloudReplayFaultFetch(input: {
|
||||
fetch: typeof fetch;
|
||||
digest(value: string | Uint8Array): string;
|
||||
record(proof: CursorCloudReplayFaultProof): void;
|
||||
reserve?(identity: Identity): boolean;
|
||||
}): typeof fetch {
|
||||
const proof: CursorCloudReplayFaultProof = { schema: "paperclip.cursor-cloud.replay-fault.v1", identity: null, streamRequests: 0, cutCount: 0, cut: null, reconnect: null };
|
||||
let armed = false;
|
||||
const save = () => input.record(structuredClone(proof));
|
||||
const nativeRoute = /^\/v1\/agents\/(bc-[a-f0-9-]{36})\/runs\/(run-[a-f0-9-]{36})\/stream$/iu;
|
||||
const eligible = new Set(["assistant", "thinking", "tool_call"]);
|
||||
const limit = 1_048_576;
|
||||
function frameEnd(bytes: Uint8Array, ended: boolean): number | undefined {
|
||||
let line = 0;
|
||||
for (let i = 0; i < bytes.length; i += 1) {
|
||||
if (bytes[i] !== 10 && bytes[i] !== 13) continue;
|
||||
if (!ended && bytes[i] === 13 && i + 1 === bytes.length) return;
|
||||
const size = bytes[i] === 13 && bytes[i + 1] === 10 ? 2 : 1;
|
||||
if (i === line) return i + size;
|
||||
line = i + size;
|
||||
i += size - 1;
|
||||
}
|
||||
}
|
||||
function identify(frame: Uint8Array): { id: string; event: string } | undefined {
|
||||
let text: string;
|
||||
try { text = new TextDecoder("utf-8", { fatal: true }).decode(frame); } catch { return; }
|
||||
let id: string | undefined, event = "message";
|
||||
const data: string[] = [];
|
||||
for (const line of text.split(/\r\n|\r|\n/u)) {
|
||||
if (!line || line.startsWith(":")) continue;
|
||||
const colon = line.indexOf(":"), key = colon < 0 ? line : line.slice(0, colon);
|
||||
const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /u, "");
|
||||
if (key === "id" && !value.includes("\0")) id = value;
|
||||
if (key === "event") event = value;
|
||||
if (key === "data") data.push(value);
|
||||
}
|
||||
if (!id || id.length > 1_024 || !eligible.has(event) || !data.length) return;
|
||||
try { JSON.parse(data.join("\n")); } catch { return; }
|
||||
return { id, event };
|
||||
}
|
||||
return async (resource, init) => {
|
||||
let route: RegExpExecArray | null = null;
|
||||
try {
|
||||
const url = new URL(resource instanceof Request ? resource.url : String(resource));
|
||||
const method = init?.method ?? (resource instanceof Request ? resource.method : "GET");
|
||||
if (method.toUpperCase() === "GET" && url.origin === "https://api.cursor.com" && !url.search && !url.hash) route = nativeRoute.exec(url.pathname);
|
||||
} catch { }
|
||||
if (!route) return input.fetch(resource, init);
|
||||
const identity = { agentIdSha256: input.digest(route[1]!), runIdSha256: input.digest(route[2]!) };
|
||||
if (proof.identity && (proof.identity.agentIdSha256 !== identity.agentIdSha256 || proof.identity.runIdSha256 !== identity.runIdSha256)) throw new Error("Cursor replay proof cannot combine different native runs in one process");
|
||||
proof.identity = identity;
|
||||
if (proof.streamRequests >= 32) throw new Error("Cursor replay fault exceeded its bounded stream request count");
|
||||
proof.streamRequests += 1;
|
||||
const reconnect = proof.cutCount === 1 && proof.reconnect === null;
|
||||
if (reconnect) {
|
||||
const header = new Headers(init?.headers ?? (resource instanceof Request ? resource.headers : undefined)).get("Last-Event-ID");
|
||||
proof.reconnect = { agentIdSha256: input.digest(route[1]!), runIdSha256: input.digest(route[2]!), lastEventIdSha256: header === null ? null : input.digest(header),
|
||||
cursorMatches: header !== null && input.digest(header) === proof.cut!.eventIdSha256, httpStatus: 0, sseReady: false };
|
||||
}
|
||||
save();
|
||||
const response = await input.fetch(resource, init);
|
||||
const sseReady = response.ok && Boolean(response.body) && Boolean(response.headers.get("content-type")?.toLowerCase().startsWith("text/event-stream"));
|
||||
if (reconnect) { proof.reconnect!.httpStatus = response.status; proof.reconnect!.sseReady = sseReady; save(); }
|
||||
if (armed || !sseReady || !response.body) return response;
|
||||
armed = true;
|
||||
const reader = response.body.getReader();
|
||||
let pending = new Uint8Array(0), ended = false, cutNextRead = false;
|
||||
const wrapped = new ReadableStream<Uint8Array>({
|
||||
async pull(controller) {
|
||||
if (cutNextRead) {
|
||||
proof.cutCount += 1;
|
||||
save();
|
||||
controller.error(new Error("Injected Cursor Cloud SSE disconnect"));
|
||||
void reader.cancel().catch(() => {});
|
||||
return;
|
||||
}
|
||||
while (true) {
|
||||
const end = frameEnd(pending, ended);
|
||||
if (end !== undefined) {
|
||||
if (end > limit) { controller.error(new Error("Cursor replay fault frame exceeded its bound")); void reader.cancel().catch(() => {}); return; }
|
||||
const frame = pending.slice(0, end); pending = pending.slice(end);
|
||||
const found = identify(frame);
|
||||
if (found && (input.reserve?.(identity) ?? true)) {
|
||||
proof.cut = { agentIdSha256: input.digest(route![1]!), runIdSha256: input.digest(route![2]!), eventIdSha256: input.digest(found.id), frameSha256: input.digest(frame), frameBytes: frame.length, event: found.event };
|
||||
cutNextRead = true;
|
||||
}
|
||||
controller.enqueue(frame);
|
||||
return;
|
||||
}
|
||||
if (ended) { if (pending.length) controller.enqueue(pending); controller.close(); return; }
|
||||
if (pending.length > limit) { controller.error(new Error("Cursor replay fault frame exceeded its bound")); void reader.cancel().catch(() => {}); return; }
|
||||
const next = await reader.read();
|
||||
if (next.done) { ended = true; continue; }
|
||||
const joined = new Uint8Array(pending.length + next.value.length); joined.set(pending); joined.set(next.value, pending.length); pending = joined;
|
||||
}
|
||||
},
|
||||
cancel: reason => reader.cancel(reason),
|
||||
}, { highWaterMark: 0 });
|
||||
return new Response(wrapped, { status: response.status, statusText: response.statusText, headers: response.headers });
|
||||
};
|
||||
}
|
||||
|
||||
function prelude(evidenceDirectory: string, treatmentId: string): string {
|
||||
return `;(() => {
|
||||
const fs = require("node:fs"), crypto = require("node:crypto"), path = require("node:path");
|
||||
const __name = (value, name) => Object.defineProperty(value, "name", { value: name, configurable: true });
|
||||
const directory = ${JSON.stringify(evidenceDirectory)};
|
||||
const stat = fs.lstatSync(directory);
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || (process.getuid && stat.uid !== process.getuid())) throw new Error("Cursor replay evidence directory must be owned and private");
|
||||
const target = path.join(directory, ${JSON.stringify(`replay-${treatmentId}-`)} + process.pid + ".json");
|
||||
const reservation = path.join(directory, ${JSON.stringify(`reservation-${treatmentId}.json`)});
|
||||
let reserved;
|
||||
globalThis.fetch = (${createCursorCloudReplayFaultFetch.toString()})({
|
||||
fetch: globalThis.fetch.bind(globalThis),
|
||||
digest: value => crypto.createHash("sha256").update(value).digest("hex"),
|
||||
reserve: identity => {
|
||||
if (reserved !== undefined) return reserved;
|
||||
let fd;
|
||||
try { fd = fs.openSync(reservation, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600); }
|
||||
catch (error) { if (error.code === "EEXIST") return reserved = false; throw error; }
|
||||
try {
|
||||
fs.writeFileSync(fd, JSON.stringify({ schema: "paperclip.cursor-cloud.replay-reservation.v1", treatmentId: ${JSON.stringify(treatmentId)}, processId: process.pid, ...identity }));
|
||||
fs.fsyncSync(fd);
|
||||
} finally { fs.closeSync(fd); }
|
||||
return reserved = true;
|
||||
},
|
||||
record: proof => {
|
||||
const temporary = target + "." + crypto.randomUUID() + ".tmp";
|
||||
fs.writeFileSync(temporary, JSON.stringify(proof), { mode: 0o600, flag: "wx" });
|
||||
fs.renameSync(temporary, target);
|
||||
}
|
||||
});
|
||||
})();\n`;
|
||||
}
|
||||
|
||||
export async function installCursorCloudReplayFault(input: { bundlePath: string; evidenceDirectory: string }) {
|
||||
if (!isAbsolute(input.bundlePath) || !isAbsolute(input.evidenceDirectory)) throw new Error("Cursor replay instrumentation requires absolute owned paths");
|
||||
await mkdir(input.evidenceDirectory, { recursive: true, mode: 0o700 });
|
||||
const directory = await lstat(input.evidenceDirectory);
|
||||
if (!directory.isDirectory() || directory.isSymbolicLink() || (directory.mode & 0o077) !== 0 || (process.getuid && directory.uid !== process.getuid())) throw new Error("Cursor replay evidence directory must be owned and private");
|
||||
const handle = await open(input.bundlePath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
let original: Buffer, mode: number;
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
if (!stat.isFile() || stat.size > 8_388_608 || (process.getuid && stat.uid !== process.getuid())) throw new Error("Cursor replay proxy must be an owned bounded regular file");
|
||||
original = await handle.readFile(); mode = stat.mode & 0o777;
|
||||
} finally { await handle.close(); }
|
||||
if (original.includes(Buffer.from("paperclip.cursor-cloud.replay-fault.v1"))) throw new Error("Cursor replay instrumentation is already installed");
|
||||
const treatmentId = randomUUID();
|
||||
const newline = original.indexOf(10), shebangEnd = original.subarray(0, 2).toString() === "#!" ? (newline < 0 ? original.length : newline + 1) : 0;
|
||||
const head = original.subarray(0, shebangEnd), separator = shebangEnd && newline < 0 ? Buffer.from("\n") : Buffer.alloc(0);
|
||||
const instrumented = Buffer.concat([head, separator, Buffer.from(prelude(input.evidenceDirectory, treatmentId)), original.subarray(shebangEnd)]);
|
||||
const manifest: CursorCloudReplayFaultManifest = { schema: "paperclip.cursor-cloud.replay-instrumentation.v1", treatmentId, originalProxySha256: sha256(original), instrumentedProxySha256: sha256(instrumented), reservationFile: `reservation-${treatmentId}.json` };
|
||||
const replace = async (bytes: Buffer) => {
|
||||
const temporary = `${input.bundlePath}.${treatmentId}.tmp`;
|
||||
await writeFile(temporary, bytes, { flag: "wx", mode });
|
||||
await rename(temporary, input.bundlePath);
|
||||
};
|
||||
await writeFile(join(input.evidenceDirectory, `original-proxy-${treatmentId}.cjs`), original, { flag: "wx", mode: 0o600 });
|
||||
await writeFile(join(input.evidenceDirectory, `instrumentation-${treatmentId}.json`), JSON.stringify(manifest), { flag: "wx", mode: 0o600 });
|
||||
await replace(instrumented);
|
||||
let restored = false;
|
||||
return { manifest, async restore() {
|
||||
if (restored) return;
|
||||
if (sha256(await readFile(input.bundlePath)) !== manifest.instrumentedProxySha256) throw new Error("Cursor replay proxy changed during acceptance; refusing to overwrite it");
|
||||
await replace(original); restored = true;
|
||||
} };
|
||||
}
|
||||
|
||||
export async function withCursorCloudReplayFault<T>(input: { bundlePath: string; evidenceDirectory: string }, run: (manifest: CursorCloudReplayFaultManifest) => Promise<T>): Promise<T> {
|
||||
const treatment = await installCursorCloudReplayFault(input);
|
||||
try { return await run(treatment.manifest); } finally { await treatment.restore(); }
|
||||
}
|
||||
|
||||
export async function readCursorCloudReplayFaultProofs(evidenceDirectory: string, manifest: CursorCloudReplayFaultManifest): Promise<unknown[]> {
|
||||
const names = (await readdir(evidenceDirectory)).filter(name => new RegExp(`^replay-${manifest.treatmentId}-[1-9][0-9]*\\.json$`, "u").test(name));
|
||||
if (names.length > 16) throw new Error("Cursor replay proof file count exceeded its bound");
|
||||
return Promise.all(names.map(async name => {
|
||||
const handle = await open(join(evidenceDirectory, name), constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try { const stat = await handle.stat(); if (!stat.isFile() || stat.size > 16_384 || (stat.mode & 0o077) !== 0 || (process.getuid && stat.uid !== process.getuid())) throw new Error("Cursor replay proof file is unsafe"); return JSON.parse(await handle.readFile("utf8")) as unknown; }
|
||||
finally { await handle.close(); }
|
||||
}));
|
||||
}
|
||||
|
||||
export async function readCursorCloudReplayFaultReservation(evidenceDirectory: string, manifest: CursorCloudReplayFaultManifest): Promise<CursorCloudReplayFaultReservation> {
|
||||
if (manifest.reservationFile !== `reservation-${manifest.treatmentId}.json`) throw new Error("Cursor replay reservation does not match its treatment");
|
||||
const handle = await open(join(evidenceDirectory, manifest.reservationFile), constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
if (!stat.isFile() || stat.size > 4_096 || (stat.mode & 0o077) !== 0 || (process.getuid && stat.uid !== process.getuid())) throw new Error("Cursor replay reservation file is unsafe");
|
||||
const value = JSON.parse(await handle.readFile("utf8")) as CursorCloudReplayFaultReservation;
|
||||
if (value.schema !== "paperclip.cursor-cloud.replay-reservation.v1" || value.treatmentId !== manifest.treatmentId || !Number.isInteger(value.processId) || value.processId < 1
|
||||
|| !/^[a-f0-9]{64}$/u.test(value.agentIdSha256) || !/^[a-f0-9]{64}$/u.test(value.runIdSha256)
|
||||
|| Object.keys(value).length !== 5) throw new Error("Cursor replay reservation evidence is invalid");
|
||||
return value;
|
||||
} finally { await handle.close(); }
|
||||
}
|
||||
|
||||
export function gradeCursorCloudReplayFault(proofs: readonly unknown[], expected: readonly { agentIdSha256: string; runIdSha256: string }[]) {
|
||||
const digest = (value: unknown) => typeof value === "string" && /^[a-f0-9]{64}$/u.test(value);
|
||||
const record = (value: unknown): Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
const exact = (value: Record<string, unknown>, keys: readonly string[]) => Object.keys(value).length === keys.length && Object.keys(value).every(key => keys.includes(key));
|
||||
const valid = proofs.length > 0 && proofs.length <= 16 && expected.length > 0 && expected.length <= 16
|
||||
&& expected.every(identity => digest(identity.agentIdSha256) && digest(identity.runIdSha256)) && proofs.every(value => {
|
||||
const proof = record(value), identity = record(proof.identity), cut = record(proof.cut), resume = record(proof.reconnect);
|
||||
if (!exact(proof, ["schema", "identity", "streamRequests", "cutCount", "cut", "reconnect"]) || proof.schema !== SCHEMA
|
||||
|| !exact(identity, ["agentIdSha256", "runIdSha256"]) || ![identity.agentIdSha256, identity.runIdSha256].every(digest)
|
||||
|| !expected.some(owned => owned.agentIdSha256 === identity.agentIdSha256 && owned.runIdSha256 === identity.runIdSha256)
|
||||
|| !Number.isInteger(proof.streamRequests) || Number(proof.streamRequests) < 1 || Number(proof.streamRequests) > 32) return false;
|
||||
if (proof.cutCount === 0) return proof.cut === null && proof.reconnect === null;
|
||||
return proof.cutCount === 1 && Number(proof.streamRequests) >= 2
|
||||
&& exact(cut, ["agentIdSha256", "runIdSha256", "eventIdSha256", "frameSha256", "frameBytes", "event"])
|
||||
&& [cut.agentIdSha256, cut.runIdSha256, cut.eventIdSha256, cut.frameSha256].every(digest)
|
||||
&& cut.agentIdSha256 === identity.agentIdSha256 && cut.runIdSha256 === identity.runIdSha256
|
||||
&& Number.isInteger(cut.frameBytes) && Number(cut.frameBytes) > 0 && Number(cut.frameBytes) <= MAX_FRAME_BYTES && ["assistant", "thinking", "tool_call"].includes(String(cut.event))
|
||||
&& exact(resume, ["agentIdSha256", "runIdSha256", "lastEventIdSha256", "cursorMatches", "httpStatus", "sseReady"])
|
||||
&& resume.agentIdSha256 === cut.agentIdSha256 && resume.runIdSha256 === cut.runIdSha256 && resume.lastEventIdSha256 === cut.eventIdSha256
|
||||
&& resume.cursorMatches === true && resume.sseReady === true && Number.isInteger(resume.httpStatus) && Number(resume.httpStatus) >= 200 && Number(resume.httpStatus) < 300
|
||||
&& expected.some(identity => identity.agentIdSha256 === cut.agentIdSha256 && identity.runIdSha256 === cut.runIdSha256);
|
||||
}) && proofs.filter(value => record(value).cutCount === 1).length === 1
|
||||
&& proofs.length === expected.length
|
||||
&& new Set(proofs.map(value => { const identity = record(record(value).identity); return `${identity.agentIdSha256}/${identity.runIdSha256}`; })).size === proofs.length
|
||||
&& expected.every(identity => proofs.some(value => { const observed = record(record(value).identity); return identity.agentIdSha256 === observed.agentIdSha256 && identity.runIdSha256 === observed.runIdSha256; }));
|
||||
return { id: "cloud-live-sse-replay", passed: valid, detail: valid ? `Observed one injected stream cut, same-run cursor reconnect and successful SSE response across ${expected.length} owned run(s); workflow settlement is graded separately` : "Missing or inconsistent owned SSE cut/reconnect proof" };
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { pollUntil, type RunnerApi } from "./api.js";
|
||||
import { createTaskThroughUi } from "./user-actions.js";
|
||||
import { collectRunEvents } from "./run-observations.js";
|
||||
import { CursorCloudStopCommandObserver, readPendingCursorCloudStopExecution } from "./cursor-cloud-stop-observation.js";
|
||||
import { CursorCloudOwnedObserver, cursorCloudIdentityProof } from "./cursor-cloud-observer.js";
|
||||
import { CURSOR_CLOUD_QUIET_WINDOW_MS, cursorCloudStopArtifactName } from "./cursor-cloud-cases.js";
|
||||
import type { LiveFixtureValues } from "./live-fixtures.js";
|
||||
import type { MatrixExecution } from "./types.js";
|
||||
|
||||
type Row = Record<string, any>;
|
||||
export async function runCursorCloudStopFlow(input: {
|
||||
page: Page; api: RunnerApi; fixtures: LiveFixtureValues; execution: MatrixExecution; nonce: string;
|
||||
observer: CursorCloudOwnedObserver; deadlineAt: number;
|
||||
observe(issue: Row, runs: Row[]): void;
|
||||
capture(id: string, label: string, file: string): Promise<void>;
|
||||
evidence(name: string, value: unknown): Promise<void>;
|
||||
}) {
|
||||
const { page, api, fixtures, execution, nonce, observer } = input;
|
||||
const created = await createTaskThroughUi({ page, issuePrefix: fixtures.company.issuePrefix!, agentName: fixtures.agent.name,
|
||||
title: execution.task.buildTitle(nonce), prompt: execution.task.buildPrompt(nonce), workMode: "standard", requireExplicitTitle: true });
|
||||
let issue: Row = {}, runs: Row[] = [];
|
||||
const load = async () => {
|
||||
issue = await api.get<Row>(`/api/issues/${created.issueId}`); runs = await observer.refresh(); input.observe(issue, runs);
|
||||
if (runs.length > 1) throw new Error("Cloud Stop dispatched an extra local run");
|
||||
return { issue, runs };
|
||||
};
|
||||
let nativeObserver: CursorCloudStopCommandObserver | undefined;
|
||||
let nativeOwner: string | undefined;
|
||||
const readPendingBoundary = async () => {
|
||||
await load(); const local = runs[0], identity = local && observer.identities.get(local.id);
|
||||
if (!local || !identity?.runId) return undefined;
|
||||
if (local.runtimeMode !== "native") throw new Error("Cloud Stop requires the admitted native Runner");
|
||||
if (local.status !== "running") throw new Error("Cloud Stop boundary unexercised: local work ended before Stop");
|
||||
const owner = `${identity.agentId}/${identity.runId}`;
|
||||
if (nativeOwner && nativeOwner !== owner) throw new Error("Cloud Stop observer native ownership changed");
|
||||
if (!nativeObserver) {
|
||||
nativeOwner = owner;
|
||||
nativeObserver = new CursorCloudStopCommandObserver({ client: observer.client, agentId: identity.agentId, runId: identity.runId,
|
||||
artifactName: cursorCloudStopArtifactName(nonce), deadlineAt: input.deadlineAt });
|
||||
}
|
||||
const remote = await observer.client.getRun(identity.agentId, identity.runId);
|
||||
const events = await collectRunEvents<Row>((afterSeq, limit) => api.get(`/api/heartbeat-runs/${local.id}/events?afterSeq=${afterSeq}&limit=${limit}`));
|
||||
const pending = nativeObserver.pending();
|
||||
const executionId = readPendingCursorCloudStopExecution(events, local.id, pending);
|
||||
return executionId && pending && ["RUNNING", "WAITING_FOR_BACKGROUND_WORK"].includes(remote.status)
|
||||
? { identity, remoteStatus: remote.status, localRunId: local.id, executionId, commandSha256: pending.commandSha256 } : undefined;
|
||||
};
|
||||
try {
|
||||
const active = await pollUntil({ label: "independently active exact Cloud command", deadlineAt: input.deadlineAt, intervalMs: 500,
|
||||
retryOnError: () => false, load: readPendingBoundary, accept: Boolean });
|
||||
if (!active) throw new Error("Missing Cloud Stop boundary");
|
||||
const absent = async () => !(await observer.client.listArtifacts(active.identity.agentId)).items.some(item => item.path.split("/").at(-1) === cursorCloudStopArtifactName(nonce));
|
||||
expect(await absent(), "Delayed Cloud artifact must be absent before Stop").toBe(true);
|
||||
await input.evidence("cursor-cloud-stop-active.json", { identity: cursorCloudIdentityProof(active.identity), remoteStatus: active.remoteStatus, localRunId: active.localRunId, nativeToolStarted: true, executionId: active.executionId, commandSha256: active.commandSha256 });
|
||||
await page.goto(`/${fixtures.company.issuePrefix}/issues/${issue.identifier ?? issue.id}`);
|
||||
await input.capture("cloud-before-stop", "Cloud run independently active before Stop", "cloud-before-stop.png");
|
||||
const stop = page.getByTestId("task-chat-composer-stop").last(); await expect(stop).toBeVisible();
|
||||
const beforeStop = await readPendingBoundary();
|
||||
expect(beforeStop?.executionId, "The exact delayed command must still be running immediately before Stop").toBe(active.executionId);
|
||||
expect(beforeStop?.commandSha256).toBe(active.commandSha256);
|
||||
expect(nativeObserver!.pending()?.callId).toBe(active.executionId);
|
||||
const pendingCheckedAt = new Date().toISOString();
|
||||
await stop.click();
|
||||
await input.evidence("cursor-cloud-stop-pending-recheck.json", { checkedAt: pendingCheckedAt, executionId: beforeStop!.executionId,
|
||||
commandSha256: beforeStop!.commandSha256, identity: cursorCloudIdentityProof(beforeStop!.identity), remoteStatus: beforeStop!.remoteStatus });
|
||||
await pollUntil({ label: "Cloud and Paperclip cancellation", deadlineAt: input.deadlineAt, intervalMs: 500, retryOnError: () => false,
|
||||
load: async () => { await load(); return { local: runs[0], remote: await observer.client.getRun(active.identity.agentId, active.identity.runId!) }; },
|
||||
accept: value => value.local?.status === "cancelled" && value.remote.status === "CANCELLED",
|
||||
reject: value => ["FINISHED", "ERROR", "EXPIRED"].includes(value.remote.status) ? "Cloud run ended without verified cancellation" : undefined });
|
||||
const receipt = runs[0]!.resultJson?.nativeCancellation;
|
||||
expect(receipt).toMatchObject({ schema: "paperclip.native-cancellation.v1", companyId: fixtures.company.id, issueId: issue.id, runId: active.localRunId, scope: "run", dispatched: true, dispatchState: "acknowledged", reasonCode: "cancellation_run_only" });
|
||||
const samples: Array<{ elapsedMs: number; providerCancelled: boolean; artifactAbsent: boolean; localCancelled: boolean }> = [];
|
||||
const quietStart = Date.now();
|
||||
do {
|
||||
await load(); const remote = await observer.client.getRun(active.identity.agentId, active.identity.runId!);
|
||||
const sample = { elapsedMs: Date.now() - quietStart, providerCancelled: remote.status === "CANCELLED", artifactAbsent: await absent(), localCancelled: runs.length === 1 && runs[0]?.status === "cancelled" && issue.status !== "done" };
|
||||
samples.push(sample); expect(sample.providerCancelled && sample.artifactAbsent && sample.localCancelled, "Cloud Stop must stay cancelled without a late artifact or automatic continuation").toBe(true);
|
||||
if (sample.elapsedMs >= CURSOR_CLOUD_QUIET_WINDOW_MS) break;
|
||||
await page.waitForTimeout(1_000);
|
||||
} while (Date.now() < input.deadlineAt);
|
||||
expect(samples.at(-1)!.elapsedMs).toBeGreaterThanOrEqual(CURSOR_CLOUD_QUIET_WINDOW_MS);
|
||||
await input.capture("cloud-stopped", "Cloud run stays cancelled after Stop", "cloud-stopped.png");
|
||||
await input.evidence("cursor-cloud-stop-settled.json", { identity: cursorCloudIdentityProof(active.identity), quietWindowMs: CURSOR_CLOUD_QUIET_WINDOW_MS, samples, acknowledgementMatches: true, observationScope: "Cloud run status and published artifact list during the bounded quiet window" });
|
||||
return { issue, runs, checks: [{ id: "cloud-active-run-stop", passed: true, detail: "UI Stop cancelled the independently active exact Cloud run; no delayed artifact or automatic local continuation appeared during the recorded quiet window" }] };
|
||||
} finally { await nativeObserver?.close(); }
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { CursorCloudClient, type CursorCloudSseEvent } from "../../packages/paperclip-runner/src/drivers/cursor-cloud/cloud-client.js";
|
||||
import { cursorCloudStopTask } from "./cursor-cloud-cases.js";
|
||||
import { CursorCloudStopCommandObserver, CursorCloudStopCommandTracker, readPendingCursorCloudStopExecution } from "./cursor-cloud-stop-observation.js";
|
||||
|
||||
const localRunId = "local-run", agentId = "bc-11111111-1111-4111-8111-111111111111", nativeRunId = "run-22222222-2222-4222-8222-222222222222";
|
||||
const filename = "cursor-cloud-after-stop-nonce.txt";
|
||||
const command = "sleep 180 && printf 'MUST_NOT_APPEAR\\n' > '/artifacts/" + filename + "'";
|
||||
const digest = createHash("sha256").update(command).digest("hex");
|
||||
const pending = { callId: "delayed-command", toolName: "run_terminal_cmd", commandSha256: digest };
|
||||
const event = (type: string, executionId: string, seq: number) => ({ runId: localRunId, seq, protocolSchemaVersion: 1, payload: { prpEvent: {
|
||||
schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", runId: localRunId, eventType: `tool.execution.${type}`,
|
||||
payload: { schema: "paperclip.tool.execution.v1", executionId, transport: "builtin", name: "run_terminal_cmd", status: type === "completed" ? "succeeded" : "running" },
|
||||
} } });
|
||||
const native = (status: string, callId = pending.callId, requestedCommand = command): CursorCloudSseEvent => ({ event: "tool_call", data: { callId, name: pending.toolName, status, args: { command: requestedCommand } } });
|
||||
const observers: CursorCloudStopCommandObserver[] = [];
|
||||
afterEach(async () => { await Promise.all(observers.splice(0).map(observer => observer.close())); vi.restoreAllMocks(); });
|
||||
|
||||
async function wireObserver(deadlineAt = Date.now() + 60_000) {
|
||||
let writer: ReadableStreamDefaultController<Uint8Array> | undefined, signal: AbortSignal | undefined, sequence = 0;
|
||||
const cancelled = vi.fn();
|
||||
const fetcher = vi.fn<typeof fetch>(async (resource, init) => {
|
||||
expect(String(resource)).toBe(`https://api.cursor.com/v1/agents/${agentId}/runs/${nativeRunId}/stream`);
|
||||
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer fixture-key");
|
||||
signal = init?.signal ?? undefined;
|
||||
return new Response(new ReadableStream<Uint8Array>({ start(controller) {
|
||||
writer = controller;
|
||||
signal?.addEventListener("abort", () => { try { controller.error(new Error("owned observation aborted")); } catch {} }, { once: true });
|
||||
}, cancel: cancelled }), { headers: { "content-type": "text/event-stream" } });
|
||||
});
|
||||
const observer = new CursorCloudStopCommandObserver({ client: new CursorCloudClient({ apiKey: "fixture-key", fetch: fetcher }), agentId, runId: nativeRunId, artifactName: filename, deadlineAt });
|
||||
observers.push(observer);
|
||||
await vi.waitFor(() => expect(writer).toBeDefined());
|
||||
return { observer, fetcher, cancelled, signal: () => signal, send(value: CursorCloudSseEvent) {
|
||||
writer!.enqueue(new TextEncoder().encode(`id: ${++sequence}\nevent: ${value.event}\ndata: ${JSON.stringify(value.data)}\n\n`));
|
||||
}, lose() { writer!.error(new Error("native stream disconnected")); } };
|
||||
}
|
||||
|
||||
it("rejects a completed setup tool while the Cloud run remains active", () => {
|
||||
expect(readPendingCursorCloudStopExecution([event("started", "setup", 1), event("completed", "setup", 2)], localRunId)).toBeUndefined();
|
||||
});
|
||||
it("requires native evidence of the exact delayed command", () => {
|
||||
expect(readPendingCursorCloudStopExecution([event("started", "setup", 1)], localRunId, pending)).toBeUndefined();
|
||||
});
|
||||
it("matches exact native SSE command identity to persisted facade events after completed setup", async () => {
|
||||
const f = await wireObserver();
|
||||
f.send(native("running", "setup", "pwd")); f.send(native("completed", "setup", "pwd")); f.send(native("running"));
|
||||
await vi.waitFor(() => expect(f.observer.pending()).toEqual(pending));
|
||||
const rows = [event("started", "setup", 1), event("completed", "setup", 2), event("started", pending.callId, 3)];
|
||||
expect(readPendingCursorCloudStopExecution(rows, localRunId, f.observer.pending())).toBe(pending.callId);
|
||||
expect(f.fetcher).toHaveBeenCalledTimes(1);
|
||||
expect(JSON.stringify(f.observer.pending())).not.toContain(command);
|
||||
});
|
||||
it("rejects a native completion racing the final Stop recheck before its persisted completion arrives", async () => {
|
||||
const f = await wireObserver(), rows = [event("started", pending.callId, 1)];
|
||||
f.send(native("running")); await vi.waitFor(() => expect(f.observer.pending()).toEqual(pending));
|
||||
expect(readPendingCursorCloudStopExecution(rows, localRunId, f.observer.pending())).toBe(pending.callId);
|
||||
f.send(native("completed")); await vi.waitFor(() => expect(f.observer.pending()).toBeUndefined());
|
||||
expect(readPendingCursorCloudStopExecution(rows, localRunId, f.observer.pending())).toBeUndefined();
|
||||
f.send(native("running"));
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(f.observer.pending()).toBeUndefined();
|
||||
});
|
||||
it("rejects a persisted completion even when the native observer has not received it yet", () => {
|
||||
expect(readPendingCursorCloudStopExecution([event("started", pending.callId, 1), event("completed", pending.callId, 2)], localRunId, pending)).toBeUndefined();
|
||||
});
|
||||
it.each(["owner", "schema", "source", "tool", "changed-repeat", "terminal"])("rejects mismatched or settled %s execution evidence", reason => {
|
||||
const row = event("started", pending.callId, 1), rows = [row];
|
||||
if (reason === "owner") row.runId = "foreign";
|
||||
if (reason === "schema") row.protocolSchemaVersion = 2;
|
||||
if (reason === "source") row.payload.prpEvent.sourceKind = "provider";
|
||||
if (reason === "tool") row.payload.prpEvent.payload.name = "different-tool";
|
||||
if (reason === "changed-repeat") { const changed = event("started", pending.callId, 2); changed.payload.prpEvent.payload.name = "different-tool"; rows.push(changed); }
|
||||
if (reason === "terminal") row.payload.prpEvent.eventType = "turn.completed";
|
||||
expect(readPendingCursorCloudStopExecution(rows, localRunId, pending)).toBeUndefined();
|
||||
});
|
||||
it.each([command + " &", command.replace("180", "1"), command.replace(filename, "unrelated.txt"), "echo " + command,
|
||||
command.replace("/artifacts/", "../"), command.replace("/artifacts/", "/artifacts/../"), command + "; true"])("rejects commands outside the exact foreground fixture: %s", value => {
|
||||
const tracker = new CursorCloudStopCommandTracker(filename, nativeRunId); tracker.consume(native("running", pending.callId, value));
|
||||
expect(tracker.pending()).toBeUndefined();
|
||||
});
|
||||
it("fails closed when the native observation stream is lost after command admission", async () => {
|
||||
const f = await wireObserver(); f.send(native("running")); await vi.waitFor(() => expect(f.observer.pending()).toEqual(pending));
|
||||
f.lose(); await vi.waitFor(() => expect(() => f.observer.pending()).toThrow("stream was lost"));
|
||||
});
|
||||
it("clears pending commands on the exact native terminal result", async () => {
|
||||
const f = await wireObserver(); f.send(native("running")); await vi.waitFor(() => expect(f.observer.pending()).toEqual(pending));
|
||||
f.send({ event: "result", data: { runId: nativeRunId, status: "FINISHED" } });
|
||||
await vi.waitFor(() => expect(f.observer.pending()).toBeUndefined());
|
||||
});
|
||||
it("fails closed on a foreign run frame and closes its owned stream", async () => {
|
||||
const f = await wireObserver(); f.send({ event: "status", data: { runId: "run-33333333-3333-4333-8333-333333333333", status: "RUNNING" } });
|
||||
await vi.waitFor(() => expect(() => f.observer.pending()).toThrow("stream was lost"));
|
||||
await f.observer.close(); expect(f.cancelled).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it("aborts its attempt-owned observer at the existing fixture deadline", async () => {
|
||||
const f = await wireObserver(Date.now() + 100);
|
||||
await vi.waitFor(() => expect(() => f.observer.pending()).toThrow("deadline expired"));
|
||||
expect(f.signal()?.aborted).toBe(true);
|
||||
});
|
||||
it("rejects expired observation before opening a native stream", () => {
|
||||
const streamRun = vi.fn();
|
||||
expect(() => new CursorCloudStopCommandObserver({ client: { streamRun }, agentId, runId: nativeRunId, artifactName: filename, deadlineAt: Date.now() - 1 })).toThrow("deadline expired");
|
||||
expect(streamRun).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("admits the actual Stop prompt command after substituting only its documented output directory", () => {
|
||||
const prompt = cursorCloudStopTask.buildPrompt("nonce");
|
||||
const requested = prompt.split("with that directory: ")[1]!.split(". Do not add a wrapper")[0]!.replace("/ABSOLUTE_OUTPUT_DIRECTORY", "/artifacts");
|
||||
expect(requested).toBe(command);
|
||||
const tracker = new CursorCloudStopCommandTracker(filename, nativeRunId);
|
||||
tracker.consume(native("running", pending.callId, requested));
|
||||
expect(tracker.pending()).toEqual(pending);
|
||||
});
|
||||
|
||||
it("matches the observed argument-free running frame followed by the same command's argument update", async () => {
|
||||
const f = await wireObserver();
|
||||
f.send({ event: "tool_call", data: { callId: pending.callId, name: pending.toolName, status: "running" } });
|
||||
f.send(native("running"));
|
||||
await vi.waitFor(() => expect(f.observer.pending()).toEqual(pending));
|
||||
const rows = [event("started", pending.callId, 1), event("started", pending.callId, 2)];
|
||||
expect(readPendingCursorCloudStopExecution(rows, localRunId, f.observer.pending())).toBe(pending.callId);
|
||||
});
|
||||
it("accepts a route-owned status frame without a repeated native run ID", () => {
|
||||
const tracker = new CursorCloudStopCommandTracker(filename, nativeRunId);
|
||||
tracker.consume({ event: "status", data: { status: "RUNNING" } });
|
||||
tracker.consume(native("running"));
|
||||
expect(tracker.pending()).toEqual(pending);
|
||||
});
|
||||
it("settles a route-owned result without a repeated native run ID", () => {
|
||||
const tracker = new CursorCloudStopCommandTracker(filename, nativeRunId);
|
||||
tracker.consume(native("running"));
|
||||
tracker.consume({ event: "result", data: { status: "FINISHED" } });
|
||||
expect(tracker.pending()).toBeUndefined();
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import type { CursorCloudClient, CursorCloudSseEvent } from "../../packages/paperclip-runner/src/drivers/cursor-cloud/cloud-client.js";
|
||||
|
||||
export interface CursorCloudPendingCommand { callId: string; toolName: string; commandSha256: string }
|
||||
type Row = Record<string, any>;
|
||||
const record = (value: unknown): Row => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Row : {};
|
||||
|
||||
export class CursorCloudStopCommandTracker {
|
||||
readonly #pending = new Map<string, CursorCloudPendingCommand>();
|
||||
readonly #completed = new Set<string>();
|
||||
#terminal = false;
|
||||
constructor(readonly artifactName: string, readonly runId: string) {}
|
||||
consume(event: CursorCloudSseEvent): void {
|
||||
const data = record(event.data);
|
||||
if (["status", "result"].includes(event.event) && data.runId !== undefined && data.runId !== this.runId) throw new Error("Cloud Stop observer received a foreign native run");
|
||||
if (event.event === "done" || event.event === "result" || event.event === "status" && ["FINISHED", "ERROR", "CANCELLED", "EXPIRED"].includes(data.status)) {
|
||||
this.#terminal = true; this.#pending.clear(); return;
|
||||
}
|
||||
if (event.event !== "tool_call" || this.#terminal) return;
|
||||
if (typeof data.callId !== "string" || !data.callId || data.callId.length > 512 || typeof data.name !== "string" || !data.name || data.name.length > 512 || !["running", "completed", "error"].includes(data.status)) throw new Error("Cloud Stop observer received an invalid native tool event");
|
||||
if (data.status !== "running") {
|
||||
if (this.#completed.size >= 256) throw new Error("Cloud Stop observer tool bound exceeded");
|
||||
this.#completed.add(data.callId); this.#pending.delete(data.callId); return;
|
||||
}
|
||||
if (this.#completed.has(data.callId)) return;
|
||||
const command = record(data.args).command;
|
||||
if (typeof command !== "string" || command.length > 16_384) return;
|
||||
const match = /^sleep 180 && printf 'MUST_NOT_APPEAR\\n' > '([^'\n\r\0]+)'$/u.exec(command);
|
||||
if (!match || !match[1]!.startsWith("/") || match[1]!.split("/").includes("..") || match[1]!.split("/").at(-1) !== this.artifactName) return;
|
||||
this.#pending.set(data.callId, { callId: data.callId, toolName: data.name, commandSha256: createHash("sha256").update(command).digest("hex") });
|
||||
if (this.#pending.size > 1) throw new Error("Cloud Stop observer saw multiple delayed commands");
|
||||
}
|
||||
pending(): CursorCloudPendingCommand | undefined { return this.#terminal ? undefined : [...this.#pending.values()][0]; }
|
||||
}
|
||||
|
||||
export class CursorCloudStopCommandObserver {
|
||||
readonly #abort = new AbortController();
|
||||
readonly #tracker: CursorCloudStopCommandTracker;
|
||||
readonly #done: Promise<void>;
|
||||
readonly #timer: NodeJS.Timeout;
|
||||
#failure: Error | undefined;
|
||||
#closed = false;
|
||||
constructor(input: { client: Pick<CursorCloudClient, "streamRun">; agentId: string; runId: string; artifactName: string; deadlineAt: number }) {
|
||||
if (!Number.isFinite(input.deadlineAt) || input.deadlineAt <= Date.now() || input.deadlineAt - Date.now() > 480_000) throw new Error("Cloud Stop observer deadline expired");
|
||||
const tracker = new CursorCloudStopCommandTracker(input.artifactName, input.runId);
|
||||
this.#tracker = tracker;
|
||||
const timer = setTimeout(() => { this.#failure = new Error("Cloud Stop observer deadline expired"); this.#abort.abort(); }, input.deadlineAt - Date.now());
|
||||
this.#timer = timer;
|
||||
timer.unref();
|
||||
this.#done = (async () => {
|
||||
try {
|
||||
for await (const event of input.client.streamRun(input.agentId, input.runId, { signal: this.#abort.signal })) tracker.consume(event);
|
||||
if (!this.#closed) this.#failure = new Error("Cloud Stop native observation stream ended");
|
||||
} catch { if (!this.#closed) this.#failure ??= new Error("Cloud Stop native observation stream was lost"); }
|
||||
finally { clearTimeout(timer); }
|
||||
})();
|
||||
}
|
||||
pending(): CursorCloudPendingCommand | undefined {
|
||||
if (this.#failure) throw this.#failure;
|
||||
return this.#closed ? undefined : this.#tracker.pending();
|
||||
}
|
||||
async close(): Promise<void> { this.#closed = true; clearTimeout(this.#timer); this.#abort.abort(); await this.#done; }
|
||||
}
|
||||
|
||||
export function readPendingCursorCloudStopExecution(events: readonly Row[], runId: string, pending?: CursorCloudPendingCommand): string | undefined {
|
||||
if (!pending) return;
|
||||
const canonical = events.filter(row => row.runId === runId && row.protocolSchemaVersion === 1).map(row => row.payload?.prpEvent)
|
||||
.filter(event => event?.schema === "paperclip.prp.event.v1" && event.schemaVersion === 1 && event.sourceKind === "runner" && event.runId === runId);
|
||||
if (canonical.some(event => ["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"].includes(event.eventType))) return;
|
||||
const matches = canonical.filter(event => event.payload?.executionId === pending.callId);
|
||||
if (matches.some(event => event.eventType === "tool.execution.completed" || event.eventType === "tool.execution.progressed" && event.payload.status !== "running")) return;
|
||||
const starts = matches.filter(event => event.eventType === "tool.execution.started");
|
||||
return starts.length > 0 && starts.every(event => event.payload.schema === "paperclip.tool.execution.v1" && event.payload.transport === "builtin" && event.payload.status === "running" && event.payload.name === pending.toolName) ? pending.callId : undefined;
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { cursorCloudProfile, runnerMatrix } from "./catalog.js";
|
||||
import { parseRunnerSelectors, selectRunnerExecutions } from "./selectors.js";
|
||||
import { assertRunnerE2EPrerequisites } from "./prerequisites.js";
|
||||
import { readCursorCloudRemoteIdentity, cursorCloudIdentityProof, CursorCloudOwnedObserver } from "./cursor-cloud-observer.js";
|
||||
import { assertCursorCloudCallbackIngress, startCursorCloudCallbackProxy } from "./cursor-cloud-callback-proxy.js";
|
||||
import type { RunnerApi } from "./api.js";
|
||||
import { assertPublicCampaign } from "./history-publish.js";
|
||||
import { CursorCloudClientError } from "../../packages/paperclip-runner/src/drivers/cursor-cloud/cloud-client.js";
|
||||
|
||||
const cells = runnerMatrix.filter(cell => cell.suite.id === "cursor-cloud");
|
||||
const agentId = "bc-11111111-1111-4111-8111-111111111111", runId = "run-22222222-2222-4222-8222-222222222222";
|
||||
function notice(ownerRunId = "local-run") {
|
||||
return { runId: ownerRunId, protocolSchemaVersion: 1, payload: { prpEvent: { schema: "paperclip.prp.event.v1", schemaVersion: 1, runId: ownerRunId,
|
||||
sourceKind: "runner", eventType: "provider.notice.recorded", payload: { summary: JSON.stringify({ schema: "paperclip.cursor-cloud.remote-identity.v1", provider: "cursor_cloud", agentId, runId, ownerRunId, normalizedSessionId: "owned-session" }) } } } };
|
||||
}
|
||||
afterEach(() => { vi.useRealTimers(); vi.unstubAllEnvs(); });
|
||||
|
||||
describe("Cursor Cloud Product E2E registration", () => {
|
||||
it("registers artifact, follow-up, active Stop and semantic planning as single-attempt explicit local cells", () => {
|
||||
expect(cells.map(cell => cell.task.id)).toEqual(["task-artifact", "cloud-followup", "active-run-stop", "plan-revise-accept"]);
|
||||
for (const cell of cells) {
|
||||
expect(cell.requiredCredentials).toEqual(["CURSOR_API_KEY"]);
|
||||
expect(cell.environment.id).toBe("local"); expect(cell.task.automaticRetryPolicy).toBe("single_attempt");
|
||||
expect(cell.suite.manualOnly).toBe(true);
|
||||
expect(selectRunnerExecutions(parseRunnerSelectors(["--id", cell.id])).map(row => row.id)).toEqual([cell.id]);
|
||||
}
|
||||
expect(cells.map(cell => cell.task.expectedRunCount)).toEqual([1, 2, 1, 3]);
|
||||
expect(selectRunnerExecutions(parseRunnerSelectors(["--all"])).some(cell => cell.suite.id === "cursor-cloud")).toBe(false);
|
||||
expect(cells[0]!.task.buildMatchers("nonce", cells[0]!)).toContainEqual({ kind: "artifact_exact", name: "cursor-cloud-nonce.txt", expected: "verified-nonce\n", mimeType: "text/plain" });
|
||||
const plan = cells.find(cell => cell.task.id === "plan-revise-accept")!.task;
|
||||
expect(plan.workMode).toBe("planning");
|
||||
expect(plan.flow).toBe("plan_revision_acceptance");
|
||||
expect(plan.buildPlanMarkers?.("nonce")).toEqual({ draft: "PAPERCLIP_E2E_PLAN_DRAFT_nonce", revised: "PAPERCLIP_E2E_PLAN_REVISED_nonce" });
|
||||
expect(plan.buildRevisionRequest?.("nonce")).toContain("targetRevisionId");
|
||||
expect(plan.buildPrompt("nonce")).toContain("do not request Cursor native Plan mode");
|
||||
expect(plan.buildPrompt("nonce")).not.toContain("remain in the requested planning collaboration mode");
|
||||
});
|
||||
it("binds the exact explicit model and encrypted Cloud credential without native permission fiction", () => {
|
||||
vi.stubEnv("PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REPO", "https://github.com/owned/disposable");
|
||||
const profile = { ...cursorCloudProfile, model: "explicit-account-model" };
|
||||
const payload = profile.buildAgent({ executionId: "owned", environmentId: "local-env", environmentFixtureId: "local", workspacePath: "/tmp/owned",
|
||||
secretRefs: { CURSOR_API_KEY: { type: "secret_ref", secretId: "secret", version: "latest" } } });
|
||||
expect(payload.adapterConfig).toMatchObject({ provider: "cursor_cloud", model: "explicit-account-model", repoUrl: "https://github.com/owned/disposable", lifecycleMode: "per_turn", env: { CURSOR_API_KEY: { type: "secret_ref", secretId: "secret" } } });
|
||||
expect(payload.adapterConfig).not.toHaveProperty("codexPermissionMode"); expect(payload.adapterConfig).not.toHaveProperty("cwd");
|
||||
});
|
||||
it("refuses public publication of native provider identity snapshots", () => {
|
||||
expect(() => assertPublicCampaign({ results: [{ suiteId: "cursor-cloud" } as never] })).toThrow("Private");
|
||||
expect(() => assertPublicCampaign({ results: [{ suiteId: "core-compatibility" } as never] })).not.toThrow();
|
||||
});
|
||||
it("setup-blocks missing prerequisites before credential loading and accepts an explicitly configured local profile", () => {
|
||||
expect(() => assertRunnerE2EPrerequisites(cells, {})).toThrow("setup-blocked");
|
||||
const environment = { PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_MODEL: "explicit-model", PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REPO: "https://github.com/owned/disposable", PAPERCLIP_PUBLIC_URL: "https://callback.example.test", PAPERCLIP_CURSOR_CLOUD_CALLBACK_PORT: "43121", PAPERCLIP_CURSOR_CLOUD_ALLOW_UNPRICED_QUALIFICATION: "1" };
|
||||
const configured = cells.map(cell => ({ ...cell, profile: { ...cell.profile, model: "explicit-model" } }));
|
||||
expect(() => assertRunnerE2EPrerequisites(configured, environment)).not.toThrow();
|
||||
expect(() => assertRunnerE2EPrerequisites(configured, { ...environment, PAPERCLIP_CURSOR_CLOUD_ALLOW_UNPRICED_QUALIFICATION: undefined })).toThrow("ALLOW_UNPRICED_QUALIFICATION");
|
||||
expect(() => assertRunnerE2EPrerequisites(configured, { ...environment, PAPERCLIP_PUBLIC_URL: "http://localhost" })).toThrow("setup-blocked");
|
||||
expect(() => assertRunnerE2EPrerequisites(configured, { ...environment, PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REPO: "https://user:secret@example.test/repo" })).toThrow("setup-blocked");
|
||||
expect(() => assertRunnerE2EPrerequisites(cells, environment)).toThrow("exact configured model");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cloud observer evidence calibration", () => {
|
||||
function planObserver(change?: (rows: Array<Record<string, any>>, identities: Array<Record<string, any>>) => void) {
|
||||
const rows = [0, 1, 2].map(index => ({ id: `local-${index}`, companyId: "owned-company", agentId: "owned-agent", sessionIdBefore: null,
|
||||
contextSnapshot: index === 2 ? { forceFreshSession: true, workspaceRefreshReason: "accepted_plan_confirmation",
|
||||
source: "issue.interaction.accept", interactionStatus: "accepted", interactionId: "revised-confirmation" } : {} }));
|
||||
const identities = rows.map((row, index) => ({ agentId: index < 2 ? agentId : "bc-33333333-3333-4333-8333-333333333333",
|
||||
runId: `run-22222222-2222-4222-8222-22222222222${index}`, normalizedSessionId: index < 2 ? "planning-session" : "accepted-session" }));
|
||||
change?.(rows, identities);
|
||||
const api = { get: vi.fn(async (path: string) => {
|
||||
if (path.includes("companies/")) return rows;
|
||||
const index = rows.findIndex(row => path.includes(`/heartbeat-runs/${row.id}`));
|
||||
if (index < 0) throw new Error("Unknown owned fixture run");
|
||||
if (!path.includes("/events?")) return rows[index];
|
||||
const value = notice(rows[index]!.id);
|
||||
const identity = JSON.parse(value.payload.prpEvent.payload.summary);
|
||||
value.payload.prpEvent.payload.summary = JSON.stringify({ ...identity, ...identities[index] });
|
||||
return [{ ...value, seq: 1 }];
|
||||
}) } as unknown as RunnerApi;
|
||||
return new CursorCloudOwnedObserver(api, "owned-company", "owned-agent", "test-key");
|
||||
}
|
||||
it("allows only the revision-bound accepted Plan to rotate its owned Cloud session", async () => {
|
||||
const observer = planObserver();
|
||||
expect((await observer.assertContinuity(3))[0]?.passed).toBe(false);
|
||||
expect((await observer.assertPlanTransitions(["local-0", "local-1", "local-2"], "revised-confirmation"))[0]?.passed).toBe(true);
|
||||
});
|
||||
it.each(["early rotation", "same accepted agent", "same accepted session", "duplicate native run", "wrong interaction", "missing reset", "wrong source", "not accepted", "prior session"])("rejects %s during Plan transitions", async reason => {
|
||||
const observer = planObserver((rows, identities) => {
|
||||
if (reason === "early rotation") identities[1]!.normalizedSessionId = "unexplained-session";
|
||||
if (reason === "same accepted agent") identities[2]!.agentId = identities[1]!.agentId;
|
||||
if (reason === "same accepted session") identities[2]!.normalizedSessionId = identities[1]!.normalizedSessionId;
|
||||
if (reason === "duplicate native run") identities[2]!.runId = identities[1]!.runId;
|
||||
if (reason === "wrong interaction") rows[2]!.contextSnapshot.interactionId = "old-confirmation";
|
||||
if (reason === "missing reset") rows[2]!.contextSnapshot.forceFreshSession = false;
|
||||
if (reason === "wrong source") rows[2]!.contextSnapshot.source = "issue.comment";
|
||||
if (reason === "not accepted") rows[2]!.contextSnapshot.interactionStatus = "pending";
|
||||
if (reason === "prior session") rows[2]!.sessionIdBefore = "planning-session";
|
||||
});
|
||||
expect((await observer.assertPlanTransitions(["local-0", "local-1", "local-2"], "revised-confirmation"))[0]?.passed).toBe(false);
|
||||
});
|
||||
it("rejects missing, duplicate or reordered Plan turn ownership", async () => {
|
||||
for (const owners of [["local-0", "local-1"], ["local-0", "local-0", "local-2"], ["local-2", "local-1", "local-0"]]) {
|
||||
expect((await planObserver().assertPlanTransitions(owners, "revised-confirmation"))[0]?.passed).toBe(false);
|
||||
}
|
||||
expect((await planObserver().assertPlanTransitions(["local-0", "local-1", "local-2"], null))[0]?.passed).toBe(false);
|
||||
});
|
||||
it("requires persisted runner-owned identity and exports digests without native IDs", () => {
|
||||
const identity = readCursorCloudRemoteIdentity([notice()], "local-run")!;
|
||||
expect(identity).toMatchObject({ agentId, runId, ownerRunId: "local-run" });
|
||||
expect(JSON.stringify(cursorCloudIdentityProof(identity))).not.toContain(agentId);
|
||||
expect(readCursorCloudRemoteIdentity([], "local-run")).toBeUndefined();
|
||||
expect(readCursorCloudRemoteIdentity([notice("foreign-run")], "local-run")).toBeUndefined();
|
||||
});
|
||||
it.each(["provider", "text", "schema", "row", "owner", "native-id"])("rejects plausible wrong %s identity evidence", reason => {
|
||||
const value = notice(), event = value.payload.prpEvent;
|
||||
if (reason === "provider") event.sourceKind = "provider";
|
||||
if (reason === "text") event.eventType = "assistant.message";
|
||||
if (reason === "schema") event.schemaVersion = 2;
|
||||
if (reason === "row") value.runId = "other-run";
|
||||
if (["owner", "native-id"].includes(reason)) {
|
||||
const identity = JSON.parse(event.payload.summary); identity[reason === "owner" ? "ownerRunId" : "agentId"] = "foreign"; event.payload.summary = JSON.stringify(identity);
|
||||
expect(() => readCursorCloudRemoteIdentity([value], "local-run")).toThrow("invalid owner");
|
||||
} else expect(readCursorCloudRemoteIdentity([value], "local-run")).toBeUndefined();
|
||||
});
|
||||
it("refuses unrelated agents before any provider cleanup mutation", async () => {
|
||||
const api = { get: vi.fn(async (path: string) => path.includes("companies/") ? [{ id: "foreign" }] : { id: "foreign", companyId: "owned-company", agentId: "other-agent" }) } as unknown as RunnerApi;
|
||||
const observer = new CursorCloudOwnedObserver(api, "owned-company", "owned-agent", "test-key");
|
||||
const remove = vi.spyOn(observer.client, "deleteAgent");
|
||||
expect((await observer.cleanup())[0]?.passed).toBe(false); expect(remove).not.toHaveBeenCalled();
|
||||
});
|
||||
function ownedObserver() {
|
||||
const api = { get: vi.fn(async (path: string) => path.includes("/events?") ? [{ ...notice(), seq: 1 }] : path.includes("companies/") ? [{ id: "local-run" }] : { id: "local-run", companyId: "owned-company", agentId: "owned-agent" }) } as unknown as RunnerApi;
|
||||
const observer = new CursorCloudOwnedObserver(api, "owned-company", "owned-agent", "test-key");
|
||||
vi.spyOn(observer.client, "getRun").mockResolvedValue({ id: runId, agentId, status: "CANCELLED", createdAt: "2026-10-28T00:00:00Z", updatedAt: "2026-10-28T00:00:00Z" });
|
||||
return observer;
|
||||
}
|
||||
it("does not equate a deletion acknowledgment with remote absence", async () => {
|
||||
vi.useFakeTimers();
|
||||
const observer = ownedObserver();
|
||||
vi.spyOn(observer.client, "deleteAgent").mockResolvedValue({ id: agentId });
|
||||
const lookup = vi.spyOn(observer.client, "getAgent").mockResolvedValue({ id: agentId, status: "IDLE", env: { type: "cloud" }, url: "https://cursor.com/agents/test", createdAt: "2026-10-28T00:00:00Z", updatedAt: "2026-10-28T00:00:00Z" });
|
||||
const startedAt = Date.now();
|
||||
const completed = observer.cleanup();
|
||||
await vi.runAllTimersAsync();
|
||||
expect(await completed).toMatchObject([{ passed: false }]);
|
||||
expect(Date.now() - startedAt).toBeLessThanOrEqual(30_000);
|
||||
expect(lookup).toHaveBeenCalledWith(agentId, expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
});
|
||||
it.each(["timeout", "acknowledged"])("waits for authoritative absence after an %s delete without issuing another mutation", async outcome => {
|
||||
vi.useFakeTimers();
|
||||
const observer = ownedObserver();
|
||||
const remove = vi.spyOn(observer.client, "deleteAgent");
|
||||
if (outcome === "timeout") remove.mockRejectedValue(new CursorCloudClientError("timeout"));
|
||||
else remove.mockResolvedValue({ id: agentId });
|
||||
const lookup = vi.spyOn(observer.client, "getAgent")
|
||||
.mockResolvedValueOnce({ id: agentId, status: "IDLE", env: { type: "cloud" }, url: "https://cursor.com/agents/test", createdAt: "2026-10-28T00:00:00Z", updatedAt: "2026-10-28T00:00:00Z" })
|
||||
.mockRejectedValue(new CursorCloudClientError("http_error", { status: 404 }));
|
||||
const completed = observer.cleanup();
|
||||
await vi.runAllTimersAsync();
|
||||
expect(await completed).toMatchObject([{ passed: true }]);
|
||||
expect(remove).toHaveBeenCalledOnce();
|
||||
expect(lookup).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("reconciles an ambiguous deletion reply through authoritative absence", async () => {
|
||||
const observer = ownedObserver();
|
||||
vi.spyOn(observer.client, "deleteAgent").mockRejectedValue(new CursorCloudClientError("invalid_response"));
|
||||
vi.spyOn(observer.client, "getAgent").mockRejectedValue(new CursorCloudClientError("http_error", { status: 404 }));
|
||||
expect((await observer.cleanup())[0]?.passed).toBe(true);
|
||||
});
|
||||
it("retains a deletion authorization failure even if a later lookup hides the resource", async () => {
|
||||
const observer = ownedObserver();
|
||||
vi.spyOn(observer.client, "deleteAgent").mockRejectedValue(new CursorCloudClientError("http_error", { status: 403 }));
|
||||
vi.spyOn(observer.client, "getAgent").mockRejectedValue(new CursorCloudClientError("http_error", { status: 404 }));
|
||||
expect((await observer.cleanup())[0]?.passed).toBe(false);
|
||||
});
|
||||
it("does not accept an unavailable absence check", async () => {
|
||||
const observer = ownedObserver();
|
||||
vi.spyOn(observer.client, "deleteAgent").mockResolvedValue({ id: agentId });
|
||||
vi.spyOn(observer.client, "getAgent").mockRejectedValue(new CursorCloudClientError("timeout"));
|
||||
expect((await observer.cleanup())[0]?.passed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const listen = async (server: Server) => { await new Promise<void>((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); return (server.address() as { port: number }).port; };
|
||||
const close = (server: Server) => new Promise<void>((resolve, reject) => { server.closeAllConnections(); server.close(error => error ? reject(error) : resolve()); });
|
||||
it("exposes only the callback path over a real loopback connection and strips operator cookies", async () => {
|
||||
const requests: Array<{ path?: string; cookie?: string; auth?: string }> = [];
|
||||
const app = createServer((request, response) => { requests.push({ path: request.url, cookie: request.headers.cookie, auth: request.headers.authorization }); response.writeHead(401).end(); });
|
||||
const appPort = await listen(app), reservation = createServer(), proxyPort = await listen(reservation); await close(reservation);
|
||||
const stop = await startCursorCloudCallbackProxy({ appPort, port: proxyPort });
|
||||
try {
|
||||
const origin = `http://127.0.0.1:${proxyPort}`;
|
||||
await assertCursorCloudCallbackIngress(origin);
|
||||
const response = await fetch(`${origin}/mcp/native-runs/00000000-0000-4000-8000-000000000000`, { method: "POST", headers: { cookie: "operator-session", authorization: "Bearer owned-capability" }, body: "{}" });
|
||||
expect(response.status).toBe(401);
|
||||
expect(requests).toHaveLength(2); expect(requests.every(request => !request.cookie)).toBe(true);
|
||||
expect(requests.at(-1)?.auth).toBe("Bearer owned-capability");
|
||||
await expect(assertCursorCloudCallbackIngress("https://bad.example.test", async () => new Response("operator app", { status: 200 }))).rejects.toThrow("callback listener");
|
||||
} finally { await stop(); await close(app); }
|
||||
});
|
||||
@@ -11,10 +11,12 @@ import {
|
||||
} from "./daytona-image-content.js";
|
||||
|
||||
const repositoryRoot = path.resolve(import.meta.dirname, "../..");
|
||||
function lastDockerignoreRule(dockerignore: string, fixturePath: string) {
|
||||
function lastMatchingDockerignoreRule(dockerignore: string, fixturePath: string) {
|
||||
const segments = fixturePath.split("/");
|
||||
const ancestors = segments.map((_, index) => segments.slice(0, index + 1).join("/"));
|
||||
return dockerignore.split(/\r?\n/).filter(rule => rule && !rule.startsWith("#")).filter(rule => {
|
||||
const pattern = rule.startsWith("!") ? rule.slice(1) : rule;
|
||||
return path.matchesGlob(fixturePath, pattern) || fixturePath.startsWith(`${pattern}/`);
|
||||
const pattern = rule.replace(/^!/, "").replace(/^\//, "");
|
||||
return ancestors.some(candidate => path.matchesGlob(candidate, pattern));
|
||||
}).at(-1);
|
||||
}
|
||||
|
||||
@@ -36,7 +38,7 @@ describe("runner E2E Daytona image contract", () => {
|
||||
for (const input of attestationInputs) {
|
||||
await expect(readFile(path.join(repositoryRoot, input), "utf8")).resolves.toBeTruthy();
|
||||
// Docker's last matching rule wins, including the parent-directory exclusion.
|
||||
expect(lastDockerignoreRule(dockerignore, input)?.startsWith("!") ?? true, input).toBe(true);
|
||||
expect(lastMatchingDockerignoreRule(dockerignore, input)?.startsWith("!") ?? true, input).toBe(true);
|
||||
expect(DAYTONA_IMAGE_INPUT_PATHS.some(inputPath => input === inputPath || input.startsWith(`${inputPath}/`)), input).toBe(true);
|
||||
}
|
||||
});
|
||||
@@ -179,7 +181,7 @@ describe("runner E2E Daytona image contract", () => {
|
||||
expect(dockerignore).toContain("packages/paperclip-runner/dist");
|
||||
expect(dockerignore).toContain("packages/paperclip-runner/runner/target");
|
||||
expect(await readFile(path.join(repositoryRoot, ".github/docker-context-checks.Dockerfile"), "utf8")).toContain("node packages/paperclip-runner/scripts/generate-acpx-profiles.mjs --check");
|
||||
expect(lastDockerignoreRule(dockerignore, "packages/paperclip-runner/test-fixtures/pi-acp/private-live-session.json")?.startsWith("!")).toBe(false);
|
||||
expect(lastMatchingDockerignoreRule(dockerignore, "packages/paperclip-runner/test-fixtures/pi-acp/private-live-session.json")?.startsWith("!")).toBe(false);
|
||||
for (const developmentOnlyInput of [
|
||||
"packages/paperclip-runner/devtools",
|
||||
"packages/paperclip-runner/docs",
|
||||
@@ -194,6 +196,18 @@ describe("runner E2E Daytona image contract", () => {
|
||||
]) {
|
||||
expect(dockerignore).toContain(developmentOnlyInput);
|
||||
}
|
||||
for (const developmentOnlyFile of [
|
||||
"devtools/probe.mjs",
|
||||
"docs/development.md",
|
||||
"examples/demo.ts",
|
||||
"test/fixtures/copilot-live-denial.json",
|
||||
"test-fixtures/pi-acp/live-evidence.json",
|
||||
"test-support/helpers.ts",
|
||||
"runner/crates/runner/tests/contract.rs",
|
||||
"scripts/pi-smoke.mjs",
|
||||
]) {
|
||||
expect(lastMatchingDockerignoreRule(dockerignore, `packages/paperclip-runner/${developmentOnlyFile}`)?.startsWith("!")).toBe(false);
|
||||
}
|
||||
expect(workflow).toContain("--platform linux/amd64");
|
||||
expect(workflow).toContain(
|
||||
"Compute Daytona image content ID with pinned bases",
|
||||
|
||||
@@ -121,7 +121,7 @@ export function publicScreenshotPaths(campaign: RunnerE2ECampaign) {
|
||||
}
|
||||
|
||||
export function assertPublicCampaign(campaign: Pick<RunnerE2ECampaign, "results">) {
|
||||
if (campaign.results.some(result => result.productJourney?.privacy === "private" || result.antigravityJourney?.privacy === "private")) {
|
||||
if (campaign.results.some(result => result.productJourney?.privacy === "private" || result.antigravityJourney?.privacy === "private" || result.suiteId === "cursor-cloud")) {
|
||||
throw new Error("Private Product E2E campaigns cannot enter the public history publisher");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,6 +36,8 @@ import { githubJourneyCheckpoints, type GitHubReviewJourneyEvidence } from "./gi
|
||||
import { antigravityEvidenceFixture } from "./antigravity-journey-test-fixtures.js";
|
||||
import type { MatrixExecution, RunnerE2EResult } from "./types.js";
|
||||
|
||||
const publicExecution = runnerMatrix.find(execution => execution.id === "core-compatibility.runner-codex.local.message-marker")!;
|
||||
|
||||
const temporaryDirectories: string[] = [];
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
@@ -438,7 +440,7 @@ describe("historical publication security", () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "runner-landing-test-"));
|
||||
const output = path.join(root, "landing");
|
||||
temporaryDirectories.push(root);
|
||||
const execution = runnerMatrix[0]!;
|
||||
const execution = publicExecution;
|
||||
const campaignResult = {
|
||||
...result(execution, "passed"),
|
||||
screenshots: [
|
||||
@@ -557,7 +559,7 @@ describe("historical publication security", () => {
|
||||
it("admits declared PNG screenshots and the trusted summary only", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "runner-s3-test-"));
|
||||
temporaryDirectories.push(root);
|
||||
const execution = runnerMatrix[0]!;
|
||||
const execution = publicExecution;
|
||||
const campaign = buildRunnerCampaign({
|
||||
campaignId: "campaign-summary",
|
||||
generatedAt: "2026-08-28T00:01:00.000Z",
|
||||
@@ -694,7 +696,7 @@ describe("historical publication security", () => {
|
||||
});
|
||||
|
||||
it("requires trusted-fixture opt-in and rejects unsafe screenshot paths", () => {
|
||||
const execution = runnerMatrix[0]!;
|
||||
const execution = publicExecution;
|
||||
expect(() => buildRunnerCampaign({
|
||||
campaignId: "unsafe-screenshot",
|
||||
generatedAt: "2026-08-28T00:01:00.000Z",
|
||||
|
||||
@@ -13,6 +13,7 @@ import { codexSubscriptionAgentConfig, stageCodexSubscriptionFixture } from "./c
|
||||
import { caseReceiptTask, CASE_RECEIPT_BUDGET_CENTS, CASE_RECEIPT_RUN_TIMEOUT_MS } from "./case-receipt-cases.js";
|
||||
import { stageGrokSubscriptionFixture } from "./grok-subscription-fixture.js";
|
||||
import { pollUntil, RunnerApiHttpError, type RunnerApi } from "./api.js";
|
||||
import { assertCursorCloudQualificationBudgetOptIn, configureCursorCloudQualificationBudget, type CursorCloudQualificationBudget } from "./cursor-cloud-budget.js";
|
||||
import type {
|
||||
CredentialName,
|
||||
MatrixExecution,
|
||||
@@ -66,6 +67,7 @@ export interface LiveFixtureValues {
|
||||
agent: AgentRecord;
|
||||
project?: ProjectRecord;
|
||||
aiConnection?: ManagedAccountFixture;
|
||||
qualificationBudget?: CursorCloudQualificationBudget;
|
||||
setupProbe?: { leaseId: string; durationMs: number; defaultRunner?: string };
|
||||
setupLeases?: Array<{ leaseId: string; phase: "platform" | "adapter"; durationMs: number }>;
|
||||
setupLeaseAccountingIncomplete?: boolean;
|
||||
@@ -189,6 +191,9 @@ export async function setupLiveFixtures(input: {
|
||||
onCompanyCreated?: (companyId: string) => Promise<void>;
|
||||
}): Promise<LiveFixtureValues> {
|
||||
const { api, execution } = input;
|
||||
const cursorCloudQualification = execution.suite.id === "cursor-cloud" && execution.profile.provider === "cursor_cloud";
|
||||
if (cursorCloudQualification) assertCursorCloudQualificationBudgetOptIn();
|
||||
let qualificationBudget: CursorCloudQualificationBudget | undefined;
|
||||
const receiptSmoke = execution.suite.id === "case-handoffs" && execution.task.id === caseReceiptTask.id;
|
||||
const registry = new FixtureRegistry();
|
||||
let setupProbe: LiveFixtureValues["setupProbe"];
|
||||
@@ -218,7 +223,7 @@ export async function setupLiveFixtures(input: {
|
||||
: ["native-completion", "native-instruction-consolidation", "native-connection-guidance"].includes(execution.suite.id)
|
||||
|| (execution.suite.id === "everyday-workflows" && ["hire-reuse", "delegate-feedback"].includes(execution.task.id)) ? NATIVE_COMPLETION_BUDGET_CENTS
|
||||
: execution.suite.id === "task-titles" ? TASK_TITLE_BUDGET_CENTS
|
||||
: ["stock-harness", "task-workspaces", "case-handoffs", "feedback-persistence", "daytona-restart-continuity", "remote-workspace-storage", "rolling-web-deployment"].includes(execution.suite.id) ? 1_000 : 0,
|
||||
: ["cursor-cloud", "stock-harness", "task-workspaces", "case-handoffs", "feedback-persistence", "daytona-restart-continuity", "remote-workspace-storage", "rolling-web-deployment"].includes(execution.suite.id) ? 1_000 : 0,
|
||||
});
|
||||
await input.onCompanyCreated?.(company.id);
|
||||
return company;
|
||||
@@ -436,10 +441,14 @@ export async function setupLiveFixtures(input: {
|
||||
aiConnection: account.binding,
|
||||
};
|
||||
}
|
||||
return api.post<AgentRecord>(
|
||||
const createdAgent = await api.post<AgentRecord>(
|
||||
`/api/companies/${company.id}/agents`,
|
||||
codexSubscription ? codexSubscriptionAgentConfig(agent, process.env, company.id) : agent,
|
||||
);
|
||||
if (cursorCloudQualification) {
|
||||
qualificationBudget = await configureCursorCloudQualificationBudget({ api, companyId: company.id, agentId: createdAgent.id });
|
||||
}
|
||||
return createdAgent;
|
||||
},
|
||||
async teardown() {
|
||||
// Agent state is instance-local. Daytona environment teardown below is
|
||||
@@ -493,6 +502,7 @@ export async function setupLiveFixtures(input: {
|
||||
secretRefs: value<SecretReferenceMap>(setup.values, "secrets"),
|
||||
environment: value<EnvironmentRecord>(setup.values, "environment"),
|
||||
agent: value<AgentRecord>(setup.values, "agent"),
|
||||
...(qualificationBudget ? { qualificationBudget } : {}),
|
||||
...(setupProbe ? { setupProbe } : {}),
|
||||
...(setup.values.has("project")
|
||||
? { project: value<ProjectRecord>(setup.values, "project") }
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { MatrixExecution } from "./types.js";
|
||||
import { assertCursorCloudQualificationBudgetOptIn } from "./cursor-cloud-budget.js";
|
||||
import { supportsKimiLocalProviderFault } from "./kimi-local-provider-fault.js";
|
||||
|
||||
/** Explicit-only profiles blocked until complete identity/auth/session/billing qualification. */
|
||||
@@ -24,10 +25,44 @@ export function assertRemoteNativeEvidencePrerequisites(
|
||||
if (invalid.length) throw new Error(`Native Daytona evidence requires exact image executable digests: ${invalid.join(", ")}`);
|
||||
}
|
||||
|
||||
type RunnerE2EHost = Pick<NodeJS.Process, "platform" | "arch">;
|
||||
|
||||
function isRunnerE2EHost(value: NodeJS.ProcessEnv | RunnerE2EHost): value is RunnerE2EHost {
|
||||
return Object.keys(value).length === 2 && typeof value.platform === "string" && typeof value.arch === "string";
|
||||
}
|
||||
|
||||
export function assertRunnerE2EPrerequisites(
|
||||
executions: readonly MatrixExecution[],
|
||||
host: Pick<NodeJS.Process, "platform" | "arch"> = process,
|
||||
environmentOrHost: NodeJS.ProcessEnv | RunnerE2EHost = process.env,
|
||||
host: RunnerE2EHost = process,
|
||||
): void {
|
||||
let environment: NodeJS.ProcessEnv;
|
||||
if (isRunnerE2EHost(environmentOrHost)) {
|
||||
host = environmentOrHost;
|
||||
environment = process.env;
|
||||
} else {
|
||||
environment = environmentOrHost;
|
||||
}
|
||||
if (executions.some(execution => execution.suite.id === "cursor-cloud" && execution.profile.provider === "cursor_cloud")) {
|
||||
assertCursorCloudQualificationBudgetOptIn(environment);
|
||||
}
|
||||
if (executions.some(execution => execution.profile.provider === "cursor_cloud")) {
|
||||
const required = ["PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_MODEL", "PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REPO", "PAPERCLIP_PUBLIC_URL", "PAPERCLIP_CURSOR_CLOUD_CALLBACK_PORT"];
|
||||
const missing = required.filter(name => !environment[name]?.trim());
|
||||
if (missing.length) throw new Error(`Cursor Cloud acceptance setup-blocked: configure ${missing.join(", ")}. No provider credentials were loaded or sent.`);
|
||||
let repo: URL, origin: URL;
|
||||
try { repo = new URL(environment.PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_REPO!); origin = new URL(environment.PAPERCLIP_PUBLIC_URL!); }
|
||||
catch { throw new Error("Cursor Cloud acceptance setup-blocked: repository and public callback origin must be valid HTTPS URLs."); }
|
||||
const port = Number(environment.PAPERCLIP_CURSOR_CLOUD_CALLBACK_PORT);
|
||||
if (repo.protocol !== "https:" || repo.username || repo.password || repo.search || repo.hash
|
||||
|| origin.protocol !== "https:" || origin.username || origin.password || origin.search || origin.hash || origin.pathname !== "/"
|
||||
|| !Number.isInteger(port) || port < 1024 || port > 65535) {
|
||||
throw new Error("Cursor Cloud acceptance setup-blocked: use a credential-free HTTPS disposable repository, HTTPS callback origin, and dedicated loopback callback port (1024–65535).");
|
||||
}
|
||||
if (executions.some(execution => execution.profile.provider === "cursor_cloud" && (execution.environment.id !== "local" || execution.profile.model !== environment.PAPERCLIP_CURSOR_CLOUD_ACCEPTANCE_MODEL!.trim()))) {
|
||||
throw new Error("Cursor Cloud acceptance requires the exact configured model and a local controller.");
|
||||
}
|
||||
}
|
||||
if (!supportsKimiLocalProviderFault(host) && executions.some(execution =>
|
||||
execution.environment.id === "local" && execution.profile.qualificationCandidate === "kimi"
|
||||
&& execution.task.id === "native-write-provider-loss")) {
|
||||
|
||||
@@ -20,6 +20,9 @@ import { runNativeActiveStopFlow as runCopilotActiveStopFlow } from "./copilot-a
|
||||
import { nativeActiveStopTasks as copilotActiveStopTasks } from "./copilot-active-stop-tasks.js";
|
||||
import type { RestartRunnerIdentity } from "./process-tree-owner.js";
|
||||
import { runNativeActiveStopFlow } from "./native-active-stop-flow.js";
|
||||
import { runCursorCloudStopFlow } from "./cursor-cloud-stop-flow.js";
|
||||
import { CursorCloudOwnedObserver, cursorCloudIdentityProof } from "./cursor-cloud-observer.js";
|
||||
import { assertCursorCloudCallbackIngress } from "./cursor-cloud-callback-proxy.js";
|
||||
import { runKimiLifecycleFlow } from "./kimi-lifecycle.js";
|
||||
import { runPiControlsFlow } from "./pi-controls-flow.js";
|
||||
import { runCursorNativeFlow } from "./cursor-native-flow.js";
|
||||
@@ -629,7 +632,7 @@ for (const execution of executions) {
|
||||
if (trace) { try { await trace.configureCompany(api, id); } finally { await saveTrace(); } }
|
||||
};
|
||||
const api = new RunnerApi(request);
|
||||
const companyRunFlow = execution.suite.id === "task-titles" || ["plan_task_guidance", "blocker_guidance", "continuation_accounting", "continuation", "context_integrity", "repository_skills", "agent_chat", "everyday_workflow", "first_task", "instruction_persistence", "pi_native", "pi_controls", "copilot_protection", "cursor_native", "native_active_stop", "native_provider_loss", "kimi_native_lifecycle", "public_mcp", "case_handoff"].includes(execution.task.flow);
|
||||
const companyRunFlow = execution.suite.id === "task-titles" || execution.task.flow === "cursor_cloud_stop" || ["plan_task_guidance", "blocker_guidance", "continuation_accounting", "continuation", "context_integrity", "repository_skills", "agent_chat", "everyday_workflow", "first_task", "instruction_persistence", "pi_native", "pi_controls", "copilot_protection", "cursor_native", "native_active_stop", "native_provider_loss", "kimi_native_lifecycle", "public_mcp", "case_handoff"].includes(execution.task.flow);
|
||||
const publicMcpUsage = execution.task.flow === "public_mcp" ? assistantUsage(execution.profile.provider === "claude" ? "anthropic" : "openai", execution.profile.model) : undefined;
|
||||
let publicMcpUserId = "";
|
||||
const consoleDiagnostics: Array<Record<string, unknown>> = [];
|
||||
@@ -680,6 +683,7 @@ for (const execution of executions) {
|
||||
let startupReuse: RunnerE2EResult["startupReuse"];
|
||||
const turnSubmissionTimesMs: number[] = [];
|
||||
const screenshots: NonNullable<RunnerE2EResult["screenshots"]> = [];
|
||||
let cursorCloudObserver: CursorCloudOwnedObserver | undefined;
|
||||
let primaryError: unknown;
|
||||
let failureClassOverride: FailureClass | undefined;
|
||||
let cleanup: RunnerE2EResult["cleanup"] = "not_started";
|
||||
@@ -779,7 +783,7 @@ for (const execution of executions) {
|
||||
});
|
||||
};
|
||||
|
||||
const captureFailureApiState = async () => {
|
||||
const captureApiState = async (capturePhase: "failure" | "final" = "failure") => {
|
||||
if (!fixtures) return;
|
||||
if (execution.task.flow === "followup_stop_resume") {
|
||||
const captured = await captureFollowupStopFailureApiState({ api, companyId: fixtures.company.id,
|
||||
@@ -856,7 +860,7 @@ for (const execution of executions) {
|
||||
snapshotsDir,
|
||||
"api-state.json",
|
||||
{
|
||||
capturePhase: "failure",
|
||||
capturePhase,
|
||||
issue: currentIssue,
|
||||
runs: detailedRuns,
|
||||
comments,
|
||||
@@ -913,6 +917,7 @@ for (const execution of executions) {
|
||||
try {
|
||||
trace?.phase("setup");
|
||||
await saveTrace();
|
||||
if (execution.profile.provider === "cursor_cloud") await assertCursorCloudCallbackIngress(process.env.PAPERCLIP_PUBLIC_URL!);
|
||||
if (execution.task.flow === "public_mcp") publicMcpUserId = await establishPublicMcpSession(api, page, secrets);
|
||||
if (execution.suite.id === "stock-harness") {
|
||||
const receipt = verifyStockHarnessPreflight(process.env[STOCK_PREFLIGHT_ENV]);
|
||||
@@ -953,6 +958,10 @@ for (const execution of executions) {
|
||||
cleanupDeadlineAt: kimiLifecycleTiming?.cleanupDeadlineAt,
|
||||
onCompanyCreated,
|
||||
});
|
||||
if (execution.profile.provider === "cursor_cloud") {
|
||||
cursorCloudObserver = new CursorCloudOwnedObserver(api, fixtures.company.id, fixtures.agent.id, credentials.CURSOR_API_KEY!);
|
||||
registerBeforeEnvironmentTeardownAssertion(() => cursorCloudObserver!.cleanup());
|
||||
}
|
||||
await finishBudgetedEvalSetup({ executionId: execution.id, environmentId: execution.environment.id, agentId: fixtures.agent.id,
|
||||
companyId: fixtures.company.id, deadlineAt: startedAtMs + deadlineMs, api,
|
||||
observe: observations => writeSanitizedJson(snapshotsDir, "budgeted-setup.json", { observations }, secrets) });
|
||||
@@ -1032,6 +1041,7 @@ for (const execution of executions) {
|
||||
companyId: fixtures.company.id,
|
||||
environmentId: fixtures.environment.id,
|
||||
agentId: fixtures.agent.id,
|
||||
...(execution.suite.id === "cursor-cloud" && fixtures.qualificationBudget ? { qualificationBudget: fixtures.qualificationBudget } : {}),
|
||||
...(fixtures.setupProbe ? { setupProbe: { durationMs: fixtures.setupProbe.durationMs,
|
||||
...(fixtures.setupProbe.defaultRunner ? { defaultRunner: fixtures.setupProbe.defaultRunner } : {}) } } : {}),
|
||||
secretIds: Object.fromEntries(
|
||||
@@ -1191,6 +1201,15 @@ for (const execution of executions) {
|
||||
});
|
||||
issue = story.issue as IssueRecord; selectedRuns = story.runs as RunRecord[];
|
||||
matcherResults = story.checks.map(check => ({ matcher: { kind: "json_path" as const, path: `nativeProviderLoss.${check.id}`, expected: true }, passed: check.passed, detail: check.detail }));
|
||||
} else if (execution.task.flow === "cursor_cloud_stop") {
|
||||
const story = await runCursorCloudStopFlow({ page, api, fixtures, execution, nonce, observer: cursorCloudObserver!, deadlineAt: startedAtMs + deadlineMs,
|
||||
observe: (currentIssue, currentRuns) => { issue = currentIssue as IssueRecord; selectedRuns = currentRuns as RunRecord[]; },
|
||||
capture: captureScreenshot, evidence: (name, data) => writeSanitizedJson(snapshotsDir, name, data, secrets),
|
||||
});
|
||||
issue = story.issue as IssueRecord; selectedRuns = story.runs as RunRecord[];
|
||||
matcherResults = story.checks.map(check => ({ matcher: { kind: "json_path" as const, path: `cursorCloud.${check.id}`, expected: true }, passed: check.passed, detail: check.detail }));
|
||||
await captureApiState("final");
|
||||
await captureScreenshot("final-state", "Final visible task state", "final-state.png");
|
||||
} else if (execution.task.flow === "native_active_stop") {
|
||||
const story = await (execution.profile.qualificationCandidate === "copilot" ? runCopilotActiveStopFlow : runNativeActiveStopFlow)({
|
||||
page, api, fixtures, execution: execution.profile.qualificationCandidate === "copilot" && execution.task.id === "pending-permission-stop" ? { ...execution, task: copilotActiveStopTasks[0]! } : execution, nonce, workspacePath, deadlineAt: startedAtMs + deadlineMs,
|
||||
@@ -2358,6 +2377,14 @@ for (const execution of executions) {
|
||||
await writeSanitizedJson(snapshotsDir, "downloaded-response-proof.json", downloadedResponseProof, secrets);
|
||||
}
|
||||
}
|
||||
if (cursorCloudObserver) {
|
||||
const revisedInteraction = record(planLifecycleEvidence?.revisedInteraction);
|
||||
const checks = execution.task.flow === "plan_revision_acceptance"
|
||||
? await cursorCloudObserver.assertPlanTransitions(selectedRuns.map(run => run.id), typeof revisedInteraction.id === "string" ? revisedInteraction.id : null)
|
||||
: await cursorCloudObserver.assertContinuity(execution.task.expectedRunCount);
|
||||
await writeSanitizedJson(snapshotsDir, "cursor-cloud-provider-continuity.json", { identities: [...cursorCloudObserver.identities.values()].map(cursorCloudIdentityProof), checks }, secrets);
|
||||
matcherResults.push(...checks.map(check => ({ matcher: { kind: "json_path" as const, path: `cursorCloud.${check.id}`, expected: true }, passed: check.passed, detail: check.detail })));
|
||||
}
|
||||
const registeredArtifacts = await readRegisteredArtifacts(api, issue.id, run.id,
|
||||
taskMatchers.filter(matcher => matcher.kind === "artifact_exact").map(matcher => matcher.name));
|
||||
if (registeredArtifacts.length > 0) {
|
||||
@@ -2973,7 +3000,7 @@ for (const execution of executions) {
|
||||
failureClassOverride = "permanent_infrastructure";
|
||||
}
|
||||
try {
|
||||
await captureFailureApiState();
|
||||
await captureApiState();
|
||||
} catch (captureError) {
|
||||
const failureClass = classifyFailure(captureError);
|
||||
if (failureClass === "secret_leak") {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { isRollingWebDeployment } from "./controller-rolling-deployment.js";
|
||||
import { superviseRollingDeployment } from "./rolling-deployment-supervisor.js";
|
||||
import { readRestartRequest, type RestartRequest } from "./server-restart-request.js";
|
||||
import { startCursorCloudCallbackProxy } from "./cursor-cloud-callback-proxy.js";
|
||||
import { prepareControllerDatabase } from "./controller-database.js";
|
||||
import { readUpgradeArtifacts, verifyUpgradeArtifact, assertServingArtifact, upgradeArtifactKey, type ServingArtifact } from "./upgrade-artifacts.js";
|
||||
import { createControllerRecoveryObserver } from "./controller-recovery-observer.js";
|
||||
@@ -477,7 +478,9 @@ async function supervise() {
|
||||
}
|
||||
|
||||
let exitCode = 0;
|
||||
let closeCursorCloudCallbackProxy: (() => Promise<void>) | undefined;
|
||||
try {
|
||||
if (executionIds.some(id => id.startsWith("cursor-cloud."))) closeCursorCloudCallbackProxy = await startCursorCloudCallbackProxy({ port: Number(required("PAPERCLIP_CURSOR_CLOUD_CALLBACK_PORT")), appPort: Number(port) });
|
||||
await supervise();
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
@@ -505,5 +508,6 @@ catch (error) {
|
||||
exitCode = 1;
|
||||
appendLog(`Qualification database cleanup failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
||||
}
|
||||
await closeCursorCloudCallbackProxy?.();
|
||||
await new Promise<void>((resolve) => log.end(resolve));
|
||||
process.exitCode = exitCode;
|
||||
@@ -11,6 +11,7 @@ export const CREDENTIAL_NAMES = [
|
||||
"DAYTONA_API_KEY",
|
||||
"GITHUB_TOKEN",
|
||||
"CURSOR_AUTH_TOKEN",
|
||||
"CURSOR_API_KEY",
|
||||
"COPILOT_GITHUB_TOKEN",
|
||||
] as const;
|
||||
|
||||
@@ -52,7 +53,8 @@ export type RunnerTaskFlow =
|
||||
| "kimi_native_lifecycle"
|
||||
| "copilot_protection"
|
||||
| "native_provider_loss"
|
||||
| "cursor_native";
|
||||
| "cursor_native"
|
||||
| "cursor_cloud_stop";
|
||||
|
||||
export interface SecretReference {
|
||||
type: "secret_ref";
|
||||
|
||||
@@ -214,6 +214,56 @@ describe("Paperclip Runner Codex configuration", () => {
|
||||
expect(html).toContain("future-provider");
|
||||
expect(html).not.toContain('aria-label="Permission mode"');
|
||||
});
|
||||
it("shows cloud repository settings without local permission or warm-process controls", async () => {
|
||||
const html = await renderRunner({ provider: "cursor_cloud", repoUrl: "https://github.com/acme/repo", repoRef: "feature" });
|
||||
expect(html).toContain("GitHub repository");
|
||||
expect(html).toContain("Cursor cloud environment");
|
||||
expect(html).toContain("effective model identity is unavailable");
|
||||
expect(html).toContain("Agent environment settings support only CURSOR_API_KEY");
|
||||
expect(html).toContain("Configure hosted secrets in your Cursor Cloud environment");
|
||||
expect(html).toContain("https://github.com/acme/repo");
|
||||
expect(html).not.toContain('aria-label="Permission mode"');
|
||||
expect(html).not.toContain("Runner lifecycle");
|
||||
expect(html).not.toContain("Warm idle timeout");
|
||||
});
|
||||
it.each(["create", "edit"] as const)("clears hidden Codex settings when explicitly choosing Cursor Cloud during %s", async mode => {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const initial = { provider: "codex", model: "gpt-5.6-sol", codexPermissionMode: "never", lifecycleMode: "warm",
|
||||
modelReasoningEffort: "high", reasoningEffort: "high", effort: "high", modelParams: [{ id: "reasoning", value: "high" }], homeMode: "preconfigured" };
|
||||
let currentConfig: Record<string, unknown> = initial;
|
||||
let currentValues: CreateConfigValues = { ...defaultCreateValues, adapterType: "paperclip_runner", model: initial.model,
|
||||
thinkingEffort: "high", adapterSchemaValues: initial };
|
||||
function Fixture() {
|
||||
const [config, setConfig] = useState(currentConfig);
|
||||
const [values, setValues] = useState(currentValues);
|
||||
currentConfig = config;
|
||||
currentValues = values;
|
||||
return <CodexLocalConfigFields mode={mode} isCreate={mode === "create"} adapterType="paperclip_runner"
|
||||
values={mode === "create" ? values : null} set={patch => setValues(previous => ({ ...previous, ...patch }))}
|
||||
config={config} eff={(_group, _field, original) => original}
|
||||
mark={(_group, field, value) => setConfig(previous => ({ ...previous, [field]: value }))}
|
||||
models={[]} hideInstructionsFile />;
|
||||
}
|
||||
try {
|
||||
await act(async () => root.render(<QueryClientProvider client={new QueryClient()}><TooltipProvider><Fixture /></TooltipProvider></QueryClientProvider>));
|
||||
const picker = container.querySelector<HTMLButtonElement>('[aria-label="Harness"]')!;
|
||||
await act(async () => picker.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
|
||||
const cloudOption = [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(option => option.textContent?.includes("Cursor Cloud"));
|
||||
expect(cloudOption).toBeDefined();
|
||||
await act(async () => cloudOption!.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
|
||||
const saved = mode === "create" ? currentValues.adapterSchemaValues! : currentConfig;
|
||||
expect(saved.provider).toBe("cursor_cloud");
|
||||
expect(saved.lifecycleMode).toBe("per_turn");
|
||||
for (const key of ["modelReasoningEffort", "reasoningEffort", "effort", "modelParams", "homeMode", "codexPermissionMode"]) expect(saved[key], key).toBeUndefined();
|
||||
if (mode === "create") {
|
||||
expect(currentValues.thinkingEffort).toBe("");
|
||||
expect(buildPaperclipRunnerConfig({ ...currentValues, model: "caller-cloud-model" })).toMatchObject({ provider: "cursor_cloud", model: "caller-cloud-model", lifecycleMode: "per_turn" });
|
||||
}
|
||||
expect(container.textContent).toContain("Cursor manages command permissions");
|
||||
} finally { await act(async () => root.unmount()); container.remove(); }
|
||||
});
|
||||
it("keeps Dot out of the general harness picker and hides that picker for Dot", async () => {
|
||||
expect(await renderRunner({ provider: "codex" }, "Harness", true)).not.toContain("OpenAI Dot");
|
||||
const dot = await renderRunner({ provider: "openai_dot" });
|
||||
|
||||
@@ -49,6 +49,7 @@ const runnerHarnessOptions = [
|
||||
{ value: "claude_managed", label: "Claude Managed", adapter: "claude_local" },
|
||||
{ value: "aws_agentcore", label: "AWS AgentCore", adapter: "aws_agentcore" },
|
||||
{ value: "acpx", label: "ACP agents", adapter: "acpx_local" },
|
||||
{ value: "cursor_cloud", label: "Cursor Cloud (experimental)", adapter: "cursor_cloud" },
|
||||
{ value: "grok", label: "Grok Build", adapter: "grok_local" },
|
||||
];
|
||||
|
||||
@@ -101,6 +102,7 @@ export function CodexLocalConfigFields({
|
||||
? PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES[runnerProvider]
|
||||
: { configurable: false, defaultMode: "provider-managed", options: [], description: "Unknown provider configuration is preserved." };
|
||||
const isMuse = runnerProvider === "muse";
|
||||
const isCursorCloud = runnerProvider === "cursor_cloud";
|
||||
const isExternal = isMuse || runnerProvider === "openai_dot" || runnerProvider === "grok_bot";
|
||||
const configuredRunnerPermissionMode =
|
||||
runnerManaged && runnerPermissionCapability.configurable
|
||||
@@ -239,6 +241,7 @@ export function CodexLocalConfigFields({
|
||||
const provider = grok ? "acpx" : isPaperclipRunnerProvider(value)
|
||||
? value
|
||||
: "codex";
|
||||
const cloudResetKeys = ["codexPermissionMode", "opencodePermissionMode", "acpxPermissionMode", "acpxAgent", "command", "extraArgs", "idleTimeoutMs", "modelReasoningEffort", "reasoningEffort", "effort", "modelParams", "homeMode"];
|
||||
const model =
|
||||
provider === "openai_dot"
|
||||
? ""
|
||||
@@ -250,15 +253,18 @@ export function CodexLocalConfigFields({
|
||||
? defaultAwsAgentCoreModel
|
||||
: provider === "acpx"
|
||||
? grok ? "grok-4.7" : defaultAcpxClaudeModel
|
||||
: provider === "cursor_cloud" ? ""
|
||||
: DEFAULT_CODEX_LOCAL_MODEL;
|
||||
if (isCreate) {
|
||||
set!({
|
||||
model,
|
||||
...(provider === "cursor_cloud" ? { thinkingEffort: "" } : {}),
|
||||
adapterSchemaValues: {
|
||||
...values!.adapterSchemaValues,
|
||||
provider,
|
||||
acpxSessionMode: undefined,
|
||||
piThinkingLevel: undefined,
|
||||
...(provider === "cursor_cloud" ? { ...Object.fromEntries(cloudResetKeys.map(key => [key, undefined])), lifecycleMode: "per_turn" } : {}),
|
||||
...(provider === "acpx" ? { acpxAgent: grok ? "grok" : "claude" } : {}),
|
||||
},
|
||||
});
|
||||
@@ -274,6 +280,10 @@ export function CodexLocalConfigFields({
|
||||
if (provider === "acpx") {
|
||||
mark("adapterConfig", "acpxAgent", grok ? "grok" : "claude");
|
||||
}
|
||||
if (provider === "cursor_cloud") {
|
||||
mark("adapterConfig", "lifecycleMode", "per_turn");
|
||||
for (const key of cloudResetKeys) mark("adapterConfig", key, undefined);
|
||||
}
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -291,6 +301,27 @@ export function CodexLocalConfigFields({
|
||||
</Field>
|
||||
)}
|
||||
{runnerManaged && runnerProvider === "grok_bot" && <GrokBotConnection companyId={companyId} agentId={agentId} />}
|
||||
{runnerManaged && isCursorCloud && <>
|
||||
<p className="text-sm text-muted-foreground">Experimental. Runs in Cursor Cloud and requires a local Paperclip computer. Cursor manages command permissions; effective model identity is unavailable. Agent environment settings support only CURSOR_API_KEY. Configure hosted secrets in your Cursor Cloud environment.</p>
|
||||
{[
|
||||
{ key: "repoUrl", label: "GitHub repository", fallback: "", legacy: undefined, placeholder: "https://github.com/your-org/repo", hint: "Select a repository or a named Cursor cloud environment." },
|
||||
{ key: "repoRef", label: "Starting ref", fallback: config.repoStartingRef ?? "", legacy: "repoStartingRef", placeholder: "Repository default" },
|
||||
{ key: "prUrl", label: "Pull request URL", fallback: config.repoPullRequestUrl ?? "", legacy: "repoPullRequestUrl", placeholder: "Optional" },
|
||||
{ key: "cloudEnvName", label: "Cursor cloud environment", fallback: config.runtimeEnvName ?? "", legacy: "runtimeEnvName", placeholder: "Use instead of a repository" },
|
||||
].map(field => <Field key={field.key} configSection="adapter" label={field.label} hint={field.hint}>
|
||||
<DraftInput value={String(runnerSchemaValue(field.key, field.fallback))} placeholder={field.placeholder} className={inputClass}
|
||||
onCommit={value => {
|
||||
if (isCreate) set!({ adapterSchemaValues: { ...values!.adapterSchemaValues, [field.key]: value, ...(field.legacy ? { [field.legacy]: undefined } : {}) } });
|
||||
else { if (field.legacy) mark("adapterConfig", field.legacy, undefined); mark("adapterConfig", field.key, value); }
|
||||
}} />
|
||||
</Field>)}
|
||||
{[
|
||||
{ key: "workOnCurrentBranch", label: "Work on current branch" },
|
||||
{ key: "autoCreatePR", label: "Auto-create pull request" },
|
||||
{ key: "skipReviewerRequest", label: "Skip reviewer request" },
|
||||
].map(field => <ToggleField key={field.key} label={field.label}
|
||||
checked={runnerSchemaValue(field.key, false) === true} onChange={value => updateRunnerSchemaValue(field.key, value)} />)}
|
||||
</>}
|
||||
{runnerManaged && runnerProvider === "openai_dot" && <>
|
||||
<Field configSection="adapter" label="Dot connection" hint="A verified event round trip is required before assigning work.">
|
||||
<DotRunnerConnection companyId={companyId} agentId={agentId} bindingId={String(runnerSchemaValue("dotBindingId", ""))} onBinding={id => updateRunnerSchemaValue("dotBindingId", id)} />
|
||||
@@ -551,7 +582,7 @@ export function CodexLocalConfigFields({
|
||||
)}
|
||||
</Field>
|
||||
)}
|
||||
{runnerManaged && !isExternal && (
|
||||
{runnerManaged && !isExternal && !isCursorCloud && (
|
||||
<Field configSection="runPolicy"
|
||||
label="Runner lifecycle"
|
||||
hint="Turn by turn suspends after each run. Warm keeps the same provider process available between governed runs."
|
||||
@@ -572,7 +603,7 @@ export function CodexLocalConfigFields({
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{runnerManaged && !isExternal && runnerLifecycleMode === "warm" && (
|
||||
{runnerManaged && !isExternal && !isCursorCloud && runnerLifecycleMode === "warm" && (
|
||||
<Field configSection="runPolicy"
|
||||
label="Warm idle timeout (ms)"
|
||||
hint="After this much inactivity, runnerd checkpoints and suspends the provider session. The maximum is 24 hours."
|
||||
|
||||
@@ -217,7 +217,7 @@ export const heartbeatsApi = {
|
||||
`/workspace-operations/${operationId}/log?offset=${encodeURIComponent(String(offset))}&limitBytes=${encodeURIComponent(String(limitBytes))}`,
|
||||
),
|
||||
cancel: (runId: string) =>
|
||||
api.post<void>(`/heartbeat-runs/${runId}/cancel`, {}),
|
||||
api.post<HeartbeatRun | null>(`/heartbeat-runs/${runId}/cancel`, {}),
|
||||
resolveRuntimeRequest: (input: {
|
||||
runId: string;
|
||||
requestId: string;
|
||||
|
||||
@@ -979,6 +979,19 @@ describe("AgentConfigForm environment selector", () => {
|
||||
expect(result.container.textContent).toContain("is ignored. The agent can still run.");
|
||||
});
|
||||
|
||||
it.each(["cursor_cloud", "paperclip_runner"])("does not offer unsupported thinking effort for saved Cursor Cloud on %s", async adapterType => {
|
||||
const result = await renderForm([], { adapterType, adapterConfig: {
|
||||
...(adapterType === "paperclip_runner" ? { provider: "cursor_cloud", lifecycleMode: "per_turn" } : {}),
|
||||
model: "caller-model", repoUrl: "https://github.com/acme/repo",
|
||||
} });
|
||||
roots.push(result.root);
|
||||
expect(result.container.querySelector('[aria-label="Thinking effort"]')).toBeNull();
|
||||
if (adapterType === "paperclip_runner") {
|
||||
expect(result.container.querySelector('[aria-label="Model"]')).not.toBeNull();
|
||||
expect(result.container.textContent).toContain("Experimental");
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["codex", "claude", "grok"].flatMap(harness => ["modelReasoningEffort", "reasoningEffort", "effort"].map(key => ({ harness, key }))))("hydrates saved effort and clears explicit Auto for $harness ($key)", async ({ harness, key }) => {
|
||||
const profile = harness === "codex" ? { provider: "codex", model: "gpt-5.6-sol" } : { provider: "acpx", acpxAgent: harness, model: harness === "grok" ? "grok-4.7" : "claude-opus-5-5" };
|
||||
const result = await renderForm([], { adapterType: "paperclip_runner", adapterConfig: { ...profile, [key]: "high" } });
|
||||
|
||||
@@ -658,6 +658,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
const fieldsAdapterType = isRunnerHarness
|
||||
? (runner === "paperclip" || (runner === "auto" && runnerAvailability?.defaultRunner === "paperclip") ? "paperclip_runner" : harnessType)
|
||||
: adapterType;
|
||||
const isCursorCloudRunner = harnessType === "cursor_cloud" && fieldsAdapterType === "paperclip_runner";
|
||||
useEffect(() => {
|
||||
if (props.mode !== "create" || !isRunnerHarness) return;
|
||||
const resolvedRunner = runner === "auto" ? runnerAvailability?.defaultRunner : runner;
|
||||
@@ -694,6 +695,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
// inert while every run happens in the platform-managed environment.
|
||||
const showLegacyWorkingDirectoryField =
|
||||
isLocal
|
||||
&& !isCursorCloudRunner
|
||||
&& !hideHostPaths
|
||||
&& shouldShowLegacyWorkingDirectoryField({ isCreate, adapterConfig: config });
|
||||
const uiAdapter = useMemo(() => getUIAdapter(adapterType), [adapterType]);
|
||||
@@ -1480,7 +1482,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
: eff("adapterConfig", thinkingEffortKey, String(config[thinkingEffortKey] ?? ""));
|
||||
const showThinkingEffort = !(harnessType === "pi_local" && fieldsAdapterType === "paperclip_runner")
|
||||
&& adapterType !== "gemini_local"
|
||||
&& adapterType !== "cursor_cloud"
|
||||
&& harnessType !== "cursor_cloud"
|
||||
&& (adapterType !== "paperclip_runner" || isRunnerHarness);
|
||||
const codexSearchEnabled = adapterType === "codex_local"
|
||||
? (isCreate ? Boolean(val!.search) : eff("adapterConfig", "search", Boolean(config.search)))
|
||||
@@ -1969,8 +1971,8 @@ export function AgentConfigForm(props: AgentConfigFormProps) {
|
||||
open={modelOpen}
|
||||
onOpenChange={setModelOpen}
|
||||
defaultLabel={adapterType === "claude_local" ? `Default (${DEFAULT_CLAUDE_LOCAL_MODEL})` : undefined}
|
||||
allowDefault={adapterType !== "opencode_local" && adapterType !== "pi_local" && adapterType !== "paperclip_runner"}
|
||||
required={adapterType === "opencode_local" || adapterType === "pi_local" || runnerAcpxAgent === "antigravity"}
|
||||
allowDefault={adapterType !== "opencode_local" && adapterType !== "pi_local" && adapterType !== "paperclip_runner" && !isCursorCloudRunner}
|
||||
required={adapterType === "opencode_local" || adapterType === "pi_local" || isCursorCloudRunner || runnerAcpxAgent === "antigravity"}
|
||||
groupByProvider={!connectionModels && (adapterType === "opencode_local" || adapterType === "pi_local")}
|
||||
preserveOrder={Boolean(connectionModels) || adapterCuratesModelOrder(adapterType)}
|
||||
creatable
|
||||
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user