diff --git a/cli/src/__tests__/test-drive.test.ts b/cli/src/__tests__/test-drive.test.ts index b3876a3ec52..4618d8956f2 100644 --- a/cli/src/__tests__/test-drive.test.ts +++ b/cli/src/__tests__/test-drive.test.ts @@ -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"; diff --git a/cli/src/commands/test-drive.ts b/cli/src/commands/test-drive.ts index 4a8a4311d5c..344d790dff2 100644 --- a/cli/src/commands/test-drive.ts +++ b/cli/src/commands/test-drive.ts @@ -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; diff --git a/doc/evals.md b/doc/evals.md index d0ea2fa5ec3..7d62a82f9f5 100644 --- a/doc/evals.md +++ b/doc/evals.md @@ -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 diff --git a/doc/plans/2026-10-28-cursor-cloud-native-runner.md b/doc/plans/2026-10-28-cursor-cloud-native-runner.md new file mode 100644 index 00000000000..fbdecbf71c0 --- /dev/null +++ b/doc/plans/2026-10-28-cursor-cloud-native-runner.md @@ -0,0 +1,1115 @@ +# Cursor Cloud on native Paperclip Runner — 2026-10-28 + +Owner: the lead integration agent in this task; delegated owners cover the Cloud +API client and this research/acceptance record. The lead owns integration, +qualification, review, and the final handoff. + +Original source baseline: `25f1070fbdabd96b26cdf199e624a77905f3ca37`. +Current qualification checkout branch: `codex/cursor-cloud-qualified-base`. +Target: a reviewable PR with experimental, local-first native Runner support. +Merge, package publication, production rollout, and automatic conversion of +existing agents are separate actions, not completed or implied by this record. + +Current delivery: [Runner core PR #18068](https://github.com/paperclipai/paperclip/pull/18068) +and dependent [product PR #18069](https://github.com/paperclipai/paperclip/pull/18069). +Neither PR is merged. Product PR #18069's Verification section owns the latest +candidate, check status and final acceptance decision. + +## Review correction checkpoint — 2026-10-29 20:25 UTC + +All six original acceptance gates have passed on their recorded candidates; +these results do not establish a pass for subsequent runtime changes. + +| Gate | Retained live evidence | +| --- | --- | +| C1 Ordinary setup | Fresh Advanced → Paperclip Runner setup, saved reload and real catalog Test on `27172d6ee899`; saved trial retested on `3f4d92f3751e` | +| C2 Task and C6 artifact | `cursor-cloud-local-20261028-artifact-sonnet-2`, source `b18b743cd45d`, eight strict matchers and exact registered/downloaded bytes; owned remote cleanup confirmed | +| C3 Continuation and C5 replay | `cursor-cloud-local-20261029-followup-sonnet-11`, source `7591c52a8c32`, two runs on one owned Agent, one answered question, one injected stream cut and matching-cursor reconnect, unique ordered events, settled receipts and owned cleanup | +| C4 Active Stop | `cursor-cloud-local-20261029-stop-sonnet-3`, source `27172d6ee899`, independently observed foreground command, ordinary UI Stop, terminal cancellation, 15-second quiet window, zero accounting debt and owned cleanup | + +The original failed Stop attempts remain failed: Stop-1 lacked the required +standard final API/screenshot package, and Stop-2 did not complete its observation +window after a status-read timeout. Stop-3 does not establish Stop-2's cause. + +Final review corrections cover semantic planning, bounded status-read recovery, +atomic artifact staging and checkpoint acquisition. The planning repair retains +the pinned Paperclip context and tool restrictions while using the Cloud default +harness. Its two separate rejection gates have RED/GREEN proof; 2,390 affected +tests and Core typecheck pass, with an additional real-Rust/private-facade Plan +control. The Cloud driver, checkpoint and artifact suites pass 45, 38 and 15 +controls respectively. Completed Product E2E support checks pass 4,905 tests +(two skipped) plus 137 source-contract tests. These are controlled results. + +The explicit Cloud suite now also registers the ordinary semantic +`plan-revise-accept` cell. Its oracle requires draft/revision continuity and a +fresh owned session tied to approval of the exact revised confirmation. The +existing same-Agent follow-up oracle remains unchanged. The new Plan cell and a +fresh artifact cell are **unattempted at this checkpoint**, pending final source, +artifact and local-trial readiness. Historical artifact staging byte identity is +invalidated by the staging repair. Preserve the earlier grades and record the +new runtime identities and evidence impact before carrying other passes forward. + +The local trial is intentionally stopped during dependency/source refresh; its +database was backed up before the additive upstream migration. No new provider +work has started in this review-correction phase. Existing experimental-model +acknowledgment and unpriced-cost limits still apply. No merge, publication or +deployment is implied. + +## Historical pre-qualification snapshot — 2026-10-29 + +The following is the retained **pre-qualification snapshot**, +with production source `77b423471668d1ad55cbd4b66841d8a2b3acadf9` and Core +`53112a12cbd8d4850ff6d88b9d739f93b49f28f9`. The latest candidate and live +verdict belong in Product PR #18069's Verification section; keep the dated +snapshots here as historical evidence. A later passing attempt never rewrites +an earlier failed grade. Core has a fresh exact-head 5/5 review; current checks +and final live qualification are still pending. + +The combined source contains the reviewed asynchronous Cloud authority fix, +safe checkpoint retirement for fresh sessions, ordinary Advanced Runner setup +forwarding, and the reproduced title-editor readiness/navigation fixes. Before +this combined candidate, Product `b0296016d5be` passed recursive typecheck and +build, and `3a4a7c558d73` passed all 1,000 native-session-executor tests. +New focused checks passed: 25 Core checkpoint archive controls; 13 Product +replacement/relay/non-Cloud controls; five relay/artifact cases; 341 UI cases, +then 232 affected editor/detail cases after the cached-route fix; UI typecheck +and token gates; and the unchanged original title-outage browser test. These +are bounded code gates, not complete live acceptance. Build and typecheck the +combined frozen source before another paid attempt. + +The saved local trial retains the real private key binding, native Cloud runtime +and explicit Sonnet model. Its earlier save/reload and key/catalog Test passed. +The trial is temporarily paused to isolate the qualification bundle and callback +port. Restore its ordinary idle state, serving candidate and callback listener +after the live campaign, then retest ordinary setup and saved configuration. +Candidate `b18b743cd45d` retains the earlier ordinary task and exact artifact +passes. Continuation, full replay and active Stop remain unqualified at this +snapshot; the next Sonnet-11 attempt has not been activated. + +Native create is working again. On 2026-10-29 a bare HTTP control and the unchanged +client plus original observer each returned 201, completed the exact expected +reply, and independently confirmed owned Agent/Run absence after deletion. +The official [Multiple services degraded incident](https://status.x.ai/history?incident=automations%2Fps_d25569b21cabd283) +covered Cloud Agents on 2026-10-28 from 21:15 to 23:13 UTC. The three late failed +minimal controls occurred inside that window. This is the likely explanation +for those HTTP 500 responses; request-level causation remains unproven. No +credential, account, model, SDK, request-schema or header change was needed to +restore successful creation. + +The tenth continuation attempt reached a successful first turn, answered its +semantic question, committed a matching interrupted terminal and settled the +explicitly unpriced accounting receipt. Its second local turn failed before a +second native create at the local Runner authority-rotation boundary. The +bounded cold-handoff repair passes real Rust/private-facade checks. The original +failed/cleanup-failure grade remains retained. The next paid attempt requires +exact source/artifact readiness; active Stop remains held until strict +continuation/full replay passes. Both PRs stay draft while gates remain open. + +## Release outcome and authority + +An operator selects Cursor Cloud in native Runner, saves an API-key binding and +explicit model, assigns an ordinary task, sees real provider activity, and gets +an independently verified result through Paperclip. Cursor executes in its hosted +environment; the first Paperclip controller/Runner acceptance environment is the +local development stack. Local-first does not mean that Cursor's model or tools +execute on the operator's computer. + +The user authorized implementation and a reviewable PR. On 2026-10-28 the user +also approved the experimental exception below and selected local-first delivery. +This adds a native integration for a harness already available through the legacy +direct adapter. Preserve that adapter, historical records, and saved runtime +selection. Do not migrate existing agents as a side effect. + +**Authorized experimental exception:** the Cloud interface does not acknowledge +the effective model or instruction digest before starting the first prompt. +Proceed with explicit submitted model selection, recorded exact instruction +content/digest, visible experimental treatment, and honest evidence labels. +Do not describe a submitted value or an SDK echo as a native acknowledgment. +This exception does not relax company authorization, semantic-tool policy, +credential isolation, Stop fencing, result acceptance, or existing budget gates. + +Native Cursor permission requests, native questions, native plan decisions, and +fixed per-run dollar enforcement are unsupported in this release. Paperclip +semantic tools remain a distinct contract. Cursor-native tools are not governed +by a Paperclip per-command approval callback. + +Authentication uses an explicitly bound Cursor user/service-account API key. +Authenticated catalog, repository access and real hosted execution were observed +on 2026-10-28. Task and artifact acceptance passed on the candidate recorded below. +Record binding identifiers only; +never put key values in this plan or evidence. Select the acceptance model from +the real account's catalog and record it before a paid attempt. It is a test +choice, not a product allowlist. No paid calls were made by the research owner. +The user explicitly delegated disposable repository/model selection and approved +the test spend on 2026-10-28. The initial operational reservation was $10 for the +small acceptance cells. The user subsequently delegated proportionate test +spending. Actual spend remains unknown; do not infer it from prompt count or +call the reservation a provider-enforced limit. Each campaign permits one +attempt per cell and no automatic paid retries. This is a planning limit, not a native +Cloud dollar cap: provider cost remains unknown until a billing receipt is +available. Diagnose the first divergence before another paid attempt. + +## Architecture and compatibility boundaries + +- Provider-owned code owns HTTP v1 requests, SSE decoding/replay, native identity, + status mapping, model parameters, provider errors, and cancellation. +- Native Runner owns normalized events and the semantic transport. The selected + design is a Node sidecar behind the existing Rust Codex-style facade, following + the OpenCode pattern. A public MCP relay forwards to the sidecar-owned Unix + HTTP bridge, which emits `item/tool/call` through Rust and existing PRP to Core + authority, then returns the result. Do not add a parallel PRP command. Controlled transport checks and real tools in the recorded C2 candidate + exercised this bridge. The remaining live cells retain separate gates. + A cloud VM cannot call the local controller's loopback address. Choose and + record the relay's authentication, reachability, expiry, and cleanup contract + before a live run. Do not substitute SDK in-process custom tools: those are + local-agent functionality. +- The controller remains authoritative for company/run/session identity, + authorization, audit, revisions, budgets, task completion, and durable effects. + A replayed or late remote call must pass current source-run authority. +- New provider-neutral shared fields require a concrete consumer and an absent/ + disabled-provider behavior. Keep Cursor payloads and SDK types in provider code. +- Persist the durable Cloud agent ID separately from each Cloud run ID and the + local Paperclip run/session identity. Recovery must observe the existing run + before creating paid work. Refresh scoped MCP credentials on continuation. +- Stop must cancel the owned Cloud run, verify provider terminal state, close + local stream/relay resources, and fence later effects. A local socket close or + terminal Paperclip row alone does not prove remote work stopped. +- Preserve legacy direct invocations, transcripts, cancellation, and finalization. + A direct run starts no runnerd process or PRP connection. Visiting/saving an + existing agent does not change its runtime. +- The first supported controller platform is the actual local host used for + acceptance; record OS/architecture and installed runtime identity when tested. + SSH, Daytona, self-hosted Cursor workers, all-platform claims, and fleet rollout + are outside this campaign. Source execution alone does not prove packaging. + +## Research dossier + +Research date: 2026-10-28, with a primary-source refresh on 2026-10-29. Public +documentation is mutable; the original inspected shipped SDK is exactly +`@cursor/sdk@1.0.28`. The refresh inspected `@cursor/sdk@1.2.0` and the unchanged +OpenAPI digest below; it found no request-schema or transport change needed +for the observed successful v1 creates. Evidence labels below distinguish +**documented**, **source-observed**, **unverified**, and **product-qualified**. +The dossier describes the inspected provider contract. Authenticated observations +and exact product results are recorded separately in the ledger below. + +Official references: + +- [Cloud API reference](https://cursor.com/docs/cloud-agent/api/endpoints) and + [OpenAPI schema](https://cursor.com/docs-static/cloud-agents-openapi.yaml). +- [API authentication and rate limits](https://cursor.com/docs/api). +- [TypeScript SDK](https://cursor.com/docs/sdk/typescript). +- [Cloud environment setup](https://cursor.com/docs/cloud-agent/setup), + [capabilities](https://cursor.com/docs/cloud-agent/capabilities), and + [secrets/network](https://cursor.com/docs/cloud-agent/security-network). +- [Local CLI ACP](https://cursor.com/docs/cli/acp), a separate interface. + +The Cloud API is v1 public beta: durable agents contain per-prompt runs. Creation +starts work immediately. Follow-ups, steering, SSE, cancellation, artifacts, and +usage have first-class APIs. Replay is run-scoped and retention-bounded. Agent +git state spans runs, so it cannot independently attribute a change to one turn. +The downloaded OpenAPI SHA-256 is +`dd3b836c4e95ad68892274280e53c348619cdd2051988793d2a85e8213d9a489`. +Current prose and schema differ on agent `IDLE` and some newer fields; preserve +unknowns and verify actual responses rather than assuming agreement. + +Installed SDK findings, reproducible by inspecting its distributed +`dist/esm/options.d.ts`, `cloud-api-client.d.ts`, and `642.js`: + +1. The Cloud run constructor assigns its model from a caller argument. `send()` + passes the chosen input; a fresh get/list does not. `run.model` and + `result.model` therefore do not establish provider model admission. +2. Cloud model validation checks catalog membership/aliases and tolerates some + discovery failures. It is not native model acknowledgment. +3. The status mapper handles `CREATING`/`RUNNING`, `FINISHED`, and `CANCELLED`; + every other value maps to error. It does not recognize the documented active + `WAITING_FOR_BACKGROUND_WORK` state. Unmodified reuse is unsafe. +4. This Cloud SDK chunk has no steering implementation. A provider-owned HTTP + client or a deliberately qualified SDK upgrade must cover the chosen API. +5. Host callback `customTools` are local only; per-send Cloud use is rejected. + Tool restrictions are also local only. Cloud MCP means a reachable remote + server or a server process inside the VM. +6. The inspected public Agent/Run API responses have neither an effective-model + field nor an instruction-digest receipt. There is no pre-prompt admit phase + or native human-decision response endpoint in that schema. + +The SDK chunk SHA-256 is +`67a4eacc8435774d52a1d0f0a2d608c00b7f4f62ffa9cb46fe0b71523304a7bf`. +No workstation path is needed to understand or reproduce these findings: inspect +the published package version and named distribution files. + +## Capability inventory + +`Required` means part of this release; `Outside` means discovered but not part of +this campaign; `Unsupported` means no product promise. Controlled checks establish +their tested boundary; authenticated observation and product qualification are +distinct evidence levels. Exact candidate identities and failed attempts are +in the ledger. Cloud v1 means the documented API as researched above; SDK means +the exact inspected 1.0.28 package. + +| Capability/field | Exact harness/version/mode | Native evidence | Transport/wrapper | Runner mapping | Durable product/UI | Qualification | Loss/reason/next action | +| --- | --- | --- | --- | --- | --- | --- | --- | +| Auth/key identity | Cloud v1 | Authenticated catalog and hosted work observed | Bound Bearer auth | Native admission implemented | Saved secret reference/Test | C1 passed | Required; no credential value in evidence | +| Entitlement/repository access | Cloud v1 | Private fixture access and hosted clone observed | Typed API errors | Actionable admission failure | Reopen/reconnect | C1/C2 passed | Required setup | +| Protocol/version discovery | Cloud v1 beta | Documented; mutable | Strict v1 client and SSE decoder | Versioned driver/launch profile | Diagnostic identity | Controlled checks and live traffic | Retain exact candidate; no provider version negotiation claim | +| Model catalog/parameters | Cloud v1 | Authenticated catalog observed | HTTP discovery and explicit submitted values | No model fallback | Saved model/params | C1 passed; explicit Sonnet submitted live | Qualification model is not an allowlist or effective-model acknowledgment | +| Exact model acknowledgment | Cloud v1 / SDK | Source-observed absent/echo | No receipt | Submitted identity only | Visible experimental limit | Unsupported | Authorized exception | +| Default/Auto routing | Cloud v1 | Documented | Provider routing | Preserve caller choice | No fixed-model claim | Unverified | Outside acceptance model | +| Agent/Plan modes | Cloud v1 | Agent request observed | Always explicit Agent mode | Plan rejected | Agent-only Cloud configuration | Agent observed in C2 | Native Plan decisions unsupported | +| Reasoning/context params | Cloud v1 | Documented catalog shape | Per-model values | Preserve values | Selected configuration | Unverified | Outside required cells | +| Exact instructions on create | Cloud v1 | No digest receipt | Full inline text and submitted digest | Content bound to checkpoint | Experimental limit | Controlled serialization; C2 behavior observed | Native acknowledgment unavailable | +| Instructions on continuation | Cloud v1 | No digest receipt | Current full revision or fixed per-turn control guidance | Active digest changes fenced | Saved current instructions | Controlled revised/unchanged-turn checks | Required C3 remains unqualified | +| Assigned skills | Cloud v1 | Bounded text assets inline | Virtual read-only file bundle | No local path/mount assumption | Submitted instruction bundle | Controlled asset checks | Binary assets, scripts by local path and persistent directory unsupported | +| MCP discovery/execution | Cloud v1 | Authenticated SDK discovery and real tools observed | Scoped HTTPS relay to private Unix bridge | Normal Rust/PRP semantic transport | Authorized Core receipts | C2 passed; real question observed in C3 | Required real tool result | +| MCP refresh/reconnect | Cloud v1 / SDK | Run-scoped inline configuration | Re-supply on every turn | Fresh expiring tool capability | Current source-run authority | Controlled follow-up/revocation checks | Required live C3 remains unqualified | +| Runtime secrets | Cloud v1 | Key and scoped callback auth observed live | Bound auth key and scoped MCP headers only | Reject other selected process variables | Hosted shell secrets configured in Cursor | C1/C2 passed; controlled rejection checks | Hosted envVars unsupported | +| Host callback tools | SDK 1.0.28 Cloud | Source-observed local only | No Cloud callbacks | Use relay | No callback claim | Unverified | Unsupported route | +| Assistant text/boundaries | Cloud v1 | Real SSE and durable PRP rows observed | Typed SSE | Ordered canonical events | Task transcript | C2 passed | Required normal task | +| Thinking visibility | Cloud v1 | Documented event | SSE | Existing visibility policy | Policy-controlled rendering | Unverified | Outside required cells | +| Tool identity/arguments/results | Cloud v1 | Real tool names, statuses and bounded results observed | SSE with stable call identity | Builtin facade; Core raw-argument policy retained | Activity and semantic receipts | C2 passed; controlled projection checks | Native truncation/redaction is not lossless raw capture | +| Tool errors/partial deltas | Cloud v1 | Running frames and argument updates observed | Bounded typed projection | Consistent repeated starts accepted | Native activity and error status | Controlled projection/Stop observer checks | No broader lossless-delta promise | +| Shell output/background work | Cloud v1 / SDK | Native command traffic observed | Active/background status handling | Preserve active wait | Running until terminal proof | Controlled status checks | C4 must observe actual pending command | +| Native permission approval | Cloud v1 | No API callback | Native tools auto-run | No interception | Explicit limitation | Unverified | Unsupported | +| Native question | Cloud v1 | No response contract found | No API callback | None | No supported claim | Unverified | Unsupported | +| Native plan decision | Cloud v1 | No response contract found | No API callback | None | No supported claim | Unverified | Unsupported | +| Semantic tool authorization | Paperclip native | Existing controller contract | Run/session/company/agent/epoch-bound relay | Normal semantic dispatcher | Durable audit/effects | C2 accepted effects; controlled negative/expiry checks | No parallel authorization path | +| Semantic questions/approval/plans | Paperclip native | Separate existing contracts | Normal semantic relay | Structured question delivered | Real browser answer persisted | Question and answer observed in C3 | Complete continuation still unqualified; no native equivalence or broader decision claim | +| Todos/plans/revisions | Cloud v1 | Rich events not qualified | Provider translation | No invented capability | Existing generic surface only | Unverified | Outside required cells | +| Active steering/queue | Cloud v1; SDK absent | Provider API documented | Not exposed by this driver | Descriptor explicitly disables both | No active steering/queue promise | Unsupported in this release | Ordinary follow-up is separate | +| Ordinary follow-up | Cloud v1 | Documented | Existing Agent/new Run | Stable session identity and refreshed callback | Same task continuation | Controlled same-Agent and governed-yield tests | Required C3 awaits live confirmation of the bounded timing repair | +| Interruption/replacement | Cloud v1 | Cancel/new-run primitives | Provider-owned sequencing | Ownership fence | Stop then continue | Unverified | No implicit simultaneous turn | +| Load/resume/history | Cloud v1 | Durable Agent/Run API observed | Exact owned identity lookup | Saved deadline and cursor; durable terminal acknowledgment | Persisted separate Agent/Run IDs | Controlled native crash/recovery checks | Ambiguous follow-up identity remains fenced | +| Fork/compaction | Cloud v1 | Not qualified | No promised route | None promised | None promised | Unverified | Outside/unknown | +| SSE replay | Cloud v1 | Real event IDs and exact cursor reconnect observed | Last-Event-ID | Ordered source-sequence deduplication | Durable event/effect identity | Controlled checks; partial live C5 transport proof | Full C5 requires normal two-turn settlement | +| Expired replay | Cloud v1 | Documented 410 | Exact owned terminal lookup | No new paid prompt; bounded reconciliation | Incomplete history remains explicit | Controlled expired-stream check | No live retention-expiry claim | +| Subagents/children | Cloud v1 | Custom agents documented | Rich identities not qualified | No attachment promise | No invented parent/child UI | Unverified | Outside required cells | +| File edits/diffs | Cloud v1 | Tools/git documented | Provider stream/git snapshot | Activity only until proven | Independent result check | Unverified | Do not trust agent summary | +| Images/inbound media | Cloud v1 | Images documented | Prompt attachment | Bound existing input | No broader media claim | Unverified | Outside required cells | +| Artifacts | Cloud v1 | Native listing and signed download observed | Exact-host HTTPS and bounded bytes | Verified private staging and relative Core reference | Registered/downloadable result | C6 passed; exact 24 bytes/SHA/MIME | Core containment, symlink and hash guards retained | +| Usage/cache/subagent totals | Cloud v1 / SDK | Authenticated token response observed diagnostically | Client usage API available | Quantitative production facade not wired | Usage/cost unknown | Production accounting unsupported | Confirmed terminal closure settles explicitly unpriced; receipt/budget controls pass | +| Settled dollar cost | Current SDK docs | Documented eventual fields | API/schema divergence | Unknown until receipt | No fabricated zero | Unverified | Outside fixed-dollar guarantee | +| Per-run dollar ceiling | Cloud v1 | No enforcement contract | No admitted native cap | Existing budget gates only | Explicit limitation | Unverified | Unsupported | +| Idle/heartbeat/retry behavior | Cloud v1 | Partial documentation | Stream/recovery policy | Bounded activity | Quiet idle state | Unverified | No idle polling loop claim | +| Cancel/terminal status | Cloud v1 | Cancellation and terminal API reads observed | Exact Run cancel plus lookup | Unconfirmed termination stays fenced | Durable cancellation | Cleanup observed; native Stop/recovery controls pass | Required active-work C4 unrun | +| Late callbacks/effects | Paperclip native | Existing authority contract | Expiry/revocation and current actor authority | Fence stopped generation | Stale mutation rejected | Controlled relay/authority checks | C4 still requires bounded live observation | +| Native process/VM cleanup | Cloud v1 | Hosted lifecycle opaque | Delete plus independent exact Agent/Run 404 | No host-PID proof | Exact API absence recorded | Observed after retained campaigns | No physical remote VM cleanup claim | +| Local relay/stream cleanup | New integration | Exact owned process exit observed | Socket close/expiry | Bounded shutdown and receipt acknowledgment | No lingering owned local work | Packaged/native controls and live cleanup | Required C4 still unrun | +| Config/command discovery | Cloud v1 | Limited API inventory | Provider-specific | No arbitrary CLI promise | Normal configuration | Unverified | Outside required cells | + +## Finite acceptance ledger + +These six cells are the release's ordinary-user denominator. Each live attempt +must name the exact application/Runner commit, dirty state, client/profile +identity, local OS/architecture, provider API contract, credential binding, +model/params/mode, fixture/grader revision, run IDs, cost/reservation, and cleanup. +Keep original failures and new attempts together. A later patch requires an +evidence-impact decision before carrying a prior pass forward. + +| Gate | Local-first cell | Required independent observation | Candidate/attempts | Verdict | Next action/owner | +| --- | --- | --- | --- | --- | --- | +| C1 Setup | Fresh configure; save/reopen/Test/reconnect | Correct saved runtime/model/binding; useful credential failure; real account test; no launch merely on read | Served `ed4ef4796586` passed save/reload, explicit Sonnet and real key/catalog Test with only the authorized effective-model acknowledgment warning. Ordinary UI cleared the paused manager. The trial is temporarily paused during the current campaign. The ordinary Advanced Runner mapping is now repaired and controlled; its final browser acceptance remains pending | Passed on recorded saved trial | Restore the final app/callback, complete ordinary setup and reopen/Test; configuration Test does not prove native create succeeds | +| C2 Task delivery | Ordinary task using real semantic tools | Provider activity; exact submitted content; authorized tool result; durable task finish accepted by controller; independently checked output; cleanup | `cursor-cloud-local-20261028-artifact-sonnet-2`, source `b18b743cd45d`, explicit `claude-sonnet-4-5`, all 8 matchers passed; result SHA-256 `eea3414ff54c7de99f4fc533cd4d88d415bc501dc56e95aa73a8c8f7fe09f270`; original failed campaigns retained below | Passed on recorded candidate | Assess pending recovery changes before carrying this pass forward | +| C3 Continuation | Follow-up on existing task/session | Same Cloud agent, distinct Cloud run; current instructions/tool grants; visible reply and durable result without duplicate work | Seven failed live campaigns (1/2/3/4/7/9/10) retain original grades. Attempts 5/6/8 stopped at local infrastructure. Sonnet-10 completed the first turn and accounting settlement but failed local authority rotation before a second native create; the cold-handoff repair passes controlled real-boundary checks. The separate stale-response repair passed 60 Cloud cases, including 14 old-driver red controls | Unqualified | Build and freeze the combined candidate, then one bounded Sonnet-11 attempt; no automatic paid retry | +| C4 Stop | Stop while provider work is actually pending | Cancel exact run; observe provider terminal state; close local resources; later relay calls/replays cannot mutate task; bounded observation recorded | Supporting controlled cancellation and race checks pass; no live active-command Stop has been attempted | Unqualified; live cell unattempted | After C3/full C5 passes, verify real pending command identity before ordinary UI Stop | +| C5 Replay | Disconnect/reconnect and retention expiry | Resume cursor; stable order; no duplicate effect/reply; expired stream reconciles through known run without a new paid prompt | Failed campaigns retain exact cuts/cursors and ordered unique events. Sonnet-10 recorded one cut, matching-cursor 200 reconnect and 61 unique ordered canonical events, but failed before second-turn admission | Partial transport proof; unqualified | Requires normal two-turn completion on the new frozen candidate | +| C6 Artifact | Download provider-produced result | Listed relative artifact; safe retrieval; independently verified bytes; usable Paperclip result access after settlement; cleanup recorded | Same Sonnet-2 result as C2; one registered/downloaded artifact, exact 24-byte fixture and MIME verified; SHA-256 `475af2a29ebe3347d92d24efaa58ee6e50a96c1e25297a4410ea12407aa5c1d9`; exact owned Agent and Run each returned 404 after cleanup | Passed on recorded candidate | Keep the original artifact bytes/receipt and repeat if the output path changes | + +Pre-qualification snapshot total: **3 passed on recorded candidates and 3 +unqualified of 6 required**. See Product PR #18069 Verification for the later +current verdict. C1 retains its saved-trial candidate; C2/C6 retain their original +candidate identities. C4 has no live attempt. At this snapshot the release was +not qualified. +A user-approved 30-day key now authenticates to the real Cloud model catalog and +is bound privately in the ready local trial. The user approved the callback +tunnel and access to the new private README-only fixture repository. Both are +configured, and a fresh authenticated repository preflight confirms access. +The saved product Test passed after reopening across a controller restart. An +initial Test failure was traced to test-drive intentionally discarding ambient +PAPERCLIP_* routing variables; saving auth.publicBaseUrl in its isolated instance +configuration supplied the callback origin. This was setup repair, with no +production-code change or provider prompt. Task delivery retains its earlier +pre-prompt and hosted failures alongside the passing Sonnet artifact attempt. +The first four continuation attempts retain their original failed grades and +exact owned Agent/Run absence after cleanup or later reconciliation. The fourth +keeps its original cleanup-failure grade. Later blocks and create failures are +recorded separately below. The direct controls and latest cleanup report no +remaining active owned native work. No accepted Run ID existed for the create +500 controls, so no Run lookup or Run-404 evidence was invented. +The original cleanup-uncertainty grades remain retained. Hosted billing is +unknown; no zero-cost claim is made. +No source, simulation, protocol test, or screenshot qualifies a live cell. + +Required supporting verification, reported separately from those six cells: + +- Credential-free client/driver checks cover status mapping, SSE chunking and + duplicates, transient errors, unavailable features, cancellation races, unknown + usage, replay expiry, and malformed provider data. They must exercise the + selected implementation rather than mirror its internals. +- Semantic relay checks prove source-run/company binding, denied operations, + credential expiry/revocation, tool-result delivery, and no late mutation. +- Focused regressions preserve legacy Cursor Cloud and another existing native + provider, with absent/disabled integration behavior. +- Exercise the clean installed package/runtime resolution used by the local + release. Record actual installed artifacts and dependencies. A source checkout + or startup probe alone is insufficient. +- Before PR-ready handoff run `pnpm -r typecheck`, `pnpm test:run`, and + `pnpm build`; report any unrun checks precisely. Run relevant token/map/catalog + checks if those owned surfaces change. Follow the repository PR template and + resolve applicable review feedback. + +## Resumable state and next gate + +| Item | Verified state | Owner | Exact next action | +| --- | --- | --- | --- | +| Research | Official docs and original SDK 1.0.28 inspected; SDK 1.2.0/OpenAPI refresh on October 29 confirms unchanged successful v1 requests | Research owner | Keep original and refreshed findings tied to their evidence dates | +| Experimental exception | User-approved 2026-10-28 | Lead | Preserve honest admission/cost limits in product and PR | +| API client | Implemented by client owner; supporting controlled wire proof reported separately | Client owner | Preserve exact pinned contract and run live acceptance | +| Native driver/semantic relay | Earlier real C2 tools passed; current cold-handoff repair passes real Rust/private-facade tests. Generation/authority fencing now passes 60 Cloud controls | Lead | Build and freeze the combined exact artifact identity | +| Credentials/model/budget | Real key privately bound; catalog/repository access and hosted execution observed; scoped tunnel approved; cost unknown | Lead | Preserve explicit model and owned cleanup for each paid attempt | +| Candidate/evidence | Production source `77b423471668`, Core `53112a12cbd8`; controlled repair gates above pass. Final combined build, current CI and live gates remain pending at this snapshot; both PRs draft | Lead | Freeze exact source/artifacts, run C3/full C5 then C4, prove private package closure and restore the trial; record the current ledger in Product PR Verification | + +Native create is available again under unchanged requests. The remaining gates +are exact-candidate artifact readiness, continuation/full replay, active +Stop, current private package proof and the saved local trial restoration. +Latest-head CI must also be green. A generic retained-Codex replay ACK test has +an unchanged local failure; its bounded investigation is recorded below and +must not be silently relabeled as passing. +Each paid task must be small, have a known output, +retain run/evidence identity, and have cleanup already wired. Diagnose the first +divergence before another paid attempt. Record active jobs and cleanup obligations +here before interruption; there are no active provider jobs recorded by the +research owner. + +The driver-owned supporting check used the real sidecar stdio, Cloud HTTP/SSE +client with a controlled peer, private Unix MCP bridge, and exact accepted Core +tool result. It covers fresh creation, same-Agent follow-up, a revised idle +instruction bundle delivered once, unchanged follow-up without repeated bundle, +strict active recovery identity, replay cursor deduplication, initialized MCP +session isolation, ambiguous initial-create recovery without another prompt, +Stop cancellation plus native terminal lookup, killed-owner stale-socket +recovery through the actual initialized driver under umask 022, persisted +absolute deadline cleanup, expired relay rejection before +mutation, provider-owned artifact discovery, verified artifact bytes, and +reconciliation HTTP 401/403/404/422 preserving uncertain initial-create identity. +The final local command ran the four driver/asset/artifact/proxy test files with +default Vitest deadlines; all 26 passed in 4.18 seconds. The proxy fixture uses +explicit bounded five-second readiness waits. Earlier attempts had four +default-five-second test timeouts and one default-one-second readiness timeout +during host contention; they remain failed supporting attempts, and no +production or repository-wide test timeout was increased. Client token usage +retrieval exists, but the production facade does not deliver those receipts, so +its descriptor marks production usage accounting unsupported and the UI must +retain unknown usage/cost. A follow-up whose HTTP response loses the native Run +identity remains deliberately fenced: it is not retried or cancelled by guessing +an Agent's unrelated latest Run. This limitation needs explicit live evidence or +an improved provider identity contract before stronger recovery claims. + +## Local milestone evidence — 2026-10-28 + +Entries below retain earlier state and pending decisions at each milestone. +The ledger above is the dated pre-qualification snapshot; the later current +release decision is recorded in Product PR #18069 Verification. + +### Native create recovery and local cold handoff — 2026-10-29 + +The independent bare HTTP control returned 201/FINISHED with the exact expected +31-byte reply. The paired original client/observer control did the same. Both +had independently verified owned Agent and Run 404 responses after cleanup. +Their comparison receipt SHA-256 is +`4991f87568eb2619277ba062bb9b1c27d16eb5425edcf78e736e17b24d6e6d07`. +The official incident window and these unchanged successful requests support a +service-outage explanation for the earlier late 500 responses, without proving +a request-level vendor root cause. Usage and cost remain unknown. + +Sonnet-10 on source `f7bfb75f794a567175d9938d2c8c0ad4dea4669a` reached +first-turn success, one applied question answer, the matching canonical +interrupted terminal and accounting-ready receipt sequence 4. The second local +turn failed at `native_runner_prp_run_rotation_unavailable` before a second +native create. One SSE cut and matching-cursor reconnect returned 200; 61 unique +canonical events stayed ordered. The original FAIL/cleanup_failure result is +retained with SHA-256 +`963c331d5061836560774d8ffc06d82a42d2c3a4ae2b9324e7ff9e9d89b3b2ff`. +Later exact owned Agent/Run lookups returned 404; all six owned local process +identities exited, the fixture PostgreSQL stopped and the callback port was +released. Reconciliation does not rewrite the original grade. + +Repair `45ab2610fa7d1d2f9731cd88dcacb87e4c32c222` admits locally owned +Cloud cold authority rotation separately from warm recovery. The new authority +refreshes current instructions; same-authority recovery retains the admitted +instructions. The Rust backend accepts that changed Cloud instruction field +only after confirmed owned shutdown and a freshly validated receipt have +atomically persisted durable prepared state. Every other provider-profile field +remains exactly compared; ambiguous stop, foreign ownership and retained ACK +debt stay fenced. Real Rust/private-facade cases verify distinct per-turn process +and Run identity with the same Agent, fresh relay/tool grants and exact +instruction serialization. The final merged candidate passed 9 facade cases, +14 existing transport controls, 12 Cloud Rust and 7 native Cloud cases, and 107 +profile/history controls. Published identity bytes remain unchanged; new current +identities account for the changed bound source inputs. + +One generic retained bare-Codex replay case failed at the existing two-second +old-authority ACK fence (`native_cleanup_maintenance_unproven`); its cohort was +18/19. The unchanged isolated case also failed using a pristine upstream Rust +binary with the merged controller. Selected controller ACK and maintenance code +is byte-identical to upstream. That mixed-controller experiment does not prove +a full pristine baseline, and an instrumented diagnostic pass does not replace +the unchanged failure. No timeout, guard, oracle or skip was changed. Generic +ACK latency work is deferred; local verification remains nongreen for that +case and latest-head CI is required. + +The Product `3a4a7c558d73` title-editor CI failure occurred after a successful +heading click and before the first textarea fill. No outage or persistence +assertion ran. Seven relevant source paths match pinned upstream; a loading +readiness remount is a hypothesis awaiting deterministic reproduction. The +separate Core review race allowed a delayed old native read to settle a newer +turn. Repair `9283dcdb3207` passed 60 Cloud tests, including 14 controls that +independently failed against the original driver. Captured logical/native +authority fences launch, reads, stream output, errors and Stop. Controlled +passes do not substitute for current live qualification. + +### Reviewed setup, fresh replacement and editor repairs — 2026-10-29 + +Core `53112a12cbd8` adds the checkpoint owner's archive helper through the +existing vendor boundary. It acquires the existing exclusive lock, validates the +exact binding/session/owner and admits only pristine idle or confirmed terminal +state with no pending create, deadline or terminal ACK debt. It archives only +the exact checkpoint and durably syncs the destination chain. Live ownership, +foreign/corrupt/missing or ambiguous state stays fenced. All 25 filesystem and +lock controls passed; directory durability and pristine-history audit gaps were +repaired before the commit. Published provider identities remain unchanged. + +Product `9550dc119d` calls that helper before moving generic continuity state. +The real-driver server regression first failed with the original checkpoint +already-exists error, then passed with exact old checkpoint preservation and a +fresh Core session open. The 13-case cohort covers positive replacement, +active/foreign/unacknowledged/live-owner refusal, relay cleanup and non-Cloud +compatibility; five relay/artifact cases and direct server typecheck also passed. +No PostgreSQL or real provider was used for these controls. + +Product `5d16e75d84` forwards ordinary Cursor Cloud Advanced Runner selection to +both Run Test and Finish setup. Its regression first observed the missing +Runner field. The same commit retains the active loading title editor until +editing actually ends, using the existing InlineEditor editing callback for +single-line edits. The unchanged Product and pinned upstream UI both reproduced +the original editor replacement before the fix. The repaired actual-hook case +retained the same connected/focused input and saved through the ordinary path. +All 341 affected UI cases, UI typecheck and token gates passed. The unchanged +browser case then edited a title through a simulated outage, recovered its write +and preserved it on reload: 1/1 passed, 5.6 seconds, no retry. The initial command +collected zero tests because of an anchored title filter; that harness failure +is retained separately and is not a browser-test pass. + +Product `77b4234716` keys the early editor by issue. A separate red regression +proved that navigation from actively edited A to cached B while preferences +were pending reused A's input. The fixed case retires A, preserves B's own +input/focus/draft through readiness and keeps A's stored draft separate, with no +save on cancellation. The two affected files passed 232 tests, UI typecheck and +token gates. The earlier unchanged browser pass retains its original patch +identity; this later edit changes only cross-task editor lifetime. + +Earlier Core `314b9a2cc894` CI failed because a Rust integration constructor +omitted the new optional launch-profile field. The separate test-only None fix +passed workspace test compilation and the integration case, and Core `9283` +Rust CI passed. Core `9283` also retained an unclassified decision-expiry timing +failure (nextWakeAt 90 seconds earlier; 2,092 passed, one failed, four skipped). +Product `b029` retained an E2E failure after a verified first continuation when +the reloaded conversation was still loading; the later always-allow scenario +never ran. Do not silently call these old failures green or infer a cause. +Require the final exact-head checks and reviews. + +### Final local handoff and unresolved native create — 2026-10-28 + +All later campaigns and direct controls below pin served source +`ed4ef4796586723c47ba39cc4e0620dc489e4123`. Product code +`146376c108f82c4130cabd112d6566a5f44b453a` has identical production, Runner and +README bytes. Its only other differences are four test-only chat brief fixture +files. Those files do not change the Cloud live definition or runtime inputs. +A deterministic partial-write regression first failed, then atomic publication +at every brief writer passed. Full credential-free support passed 4,725 tests +with two skipped, plus 137 Node checks. E2E typecheck passed. Full recursive +typecheck passed at merged code `e1aeeaa2e4`; the later fixture-only change was +covered by the E2E typecheck. Current Core and Product code CI/review passed; +this final documentation update still needs its own latest-head gates. + +The separate older full repository test run was stopped at its exact owned +coordinator after about 2 hours 35 minutes, with exit 130 and known failures. +It remains partial and not green. The host had exhausted its System V semaphore +capacity. That fact does not establish the cause of every earlier test failure. +No unaffected local suite was rerun for this documentation update. + +| Later campaign | First measured boundary | Native work and retained grade | +| --- | --- | --- | +| Sonnet-5 | Local package-manager resolution | No fixture/native job admitted; no canonical live result. Retain the local tooling block | +| Sonnet-6 | Sandboxed tsx IPC listener denied | No fixture/native job admitted; no canonical live result. Retain the local tooling block | +| Sonnet-7 | One native create POST returned HTTP 500; exact proposed Agent GET returned 404 | No accepted Run, question, SSE stream or cut. Original candidate-failure result retained; cleanup passed after ordinary Board intervention | +| Sonnet-8 | Embedded PostgreSQL initdb exited 1 while host semaphore capacity was 87,381/87,381 across 5,140 sets | Zero native requests. Keep the original failed/cleanup-failure grade despite later local retirement; the exact failing syscall stderr was not retained | +| Sonnet-9 | One native create POST returned HTTP 500 after host recovery; exact proposed Agent GET returned 404 | No accepted Run, question, SSE stream or cut. Original candidate-failure result retained; cleanup passed after ordinary Board intervention | + +Canonical result SHA-256 values remain: + +- Sonnet-7: `d39a52de698ed89289d78ac598edaa645c03cba2b99aac3517feaf817d8e3671`. +- Sonnet-8: `847c7d6732b70a20b31c47ee6d23b0032e2c02399050769e12ae82d63cf63907`. +- Sonnet-9: `bc8b717e6c24645301354edb63b364c57a0e129604d627e2d96d6cc87a8bf723`. + +The 500 campaigns do not test the repaired terminal accounting or cancellation +composition. Their capture remains pending without a matching committed +terminal. Vendor usage and dollar cost remain unknown, not measured zero. +Each create was issued once. No automatic paid mutation retry occurred. + +Three minimal native controls omitted MCP. Bearer and Basic auth each returned +HTTP 200 from `/v1/me` for the same hashed user and key metadata. Sonnet minimal +create returned HTTP 500 under both schemes. A catalog-supported +`gpt-5.4-mini` Bearer control also returned 500, with a generic provider message +and no provider error code. Its create response arrived in about 7.23 seconds; +the exact proposed Agent lookup returned 404 in about 0.25 seconds. Request +metadata matched except for fresh ownership identity and selected model. +All three direct controls had one create POST, no cancel or DELETE, no +mutation retry, no accepted Run identity and no remaining active owned work. +No Run lookup was fabricated when the provider supplied no Run identity. + +These controls show that the failure persists without Paperclip MCP, across +both successful authentication schemes, and across Sonnet and the selected +Mini model. They do not identify an account, repository, entitlement, +provisioning or service root cause. Read-only account UI inspection showed a +connected GitHub account and no visible blocking notice; it supplied neither a +confirmed cause nor a campaign billing receipt. No account setting or payment +was changed. No additional native creates are planned. + +| Diagnostic evidence | SHA-256 | +| --- | --- | +| Same-identity auth/create comparison | `75fb7a722f9593c464dba4dd19b8299c644c0cd88d1a9eb8558edde1451a1bd1` | +| Minimal Sonnet Bearer control | `da538d42435d2fdbaa8609c0e081996f321df536245942feae369f9e3ca9e599` | +| Minimal Sonnet Basic control | `0f58432420baae4017ed34b686e80a6414ba58a0f47ea1c873205513c6d2fcee` | +| Minimal Mini Bearer control | `546a36f418f15eb403e31876f3b920d31eb80529af35d05a027dabb512c11a59` | +| Sonnet/Mini comparison | `5223faf425827ab4cefdd1a7cca739f35ba84538b73ed4eb6db36491ba8d0453` | + +Final ordinary UI verification retained the explicit native Cloud/Sonnet and +private secret binding across save/reload, then passed the real no-prompt +key/catalog Test. The only warning was the user-approved lack of independent +effective-model acknowledgment. Clearing the paused manager through the UI +persisted `reportsTo: null`; the trial is idle and server health/recovery are +ready. Temporary plaintext credential material was removed after the encrypted +secret and real Test were validated; the valid 30-day binding remains available. +The private local app and separate callback listener remain running for the +user's test drive. No callback exposure of the board or general API was added: +public root and API probes returned 404, unauthenticated callback POST returned +401, and callback GET returned 405 with `Allow: POST`. + +The final sanitized trial-state receipt has SHA-256 +`a66701bc674e43bc0150b233c7ae962d32437f19823b0c21df82aec82e40f5a6`. +The private screenshot shown to the user has SHA-256 +`e38c7e65561e333b1b9237c92fbdca6ce6c919bdcf9512c7936342189434b93e`. +Neither a ready configuration Test nor this screenshot qualifies C3/C5/C4. + +The latest private Runner archive and compiled-consumer proofs passed on the +recorded macOS arm64 host with Node 26.4.0. The tarball has 1,696 entries, +14,031,063 bytes and no bundled `node_modules` or symlinks. Extracted stdio/Unix +MCP checks exercised a synthetic accepted tool result, terminal retention and +ACK, clean exit and socket removal. The separate compiled consumer loaded 175 +modules inside its extracted closure and made zero parent or child provider +requests; no turn was submitted. These prove the tested private package +closure, not ordinary public installation or live Cloud acceptance. + +| Current package/runtime artifact | SHA-256 | +| --- | --- | +| Private Runner archive | `eb7fbb3d65752de71bbc29f411e5d2c62904184134fdfe3a3b8791cb30901d7c` | +| Local daemon | `519ca52449ec584311107460f155d6b951272001447e15e9a4ac1790989463cc` | +| Cloud CJS proxy | `15e1c48df44e4e3bc48eb8814430cf2e37c800c4c4c8c00915bee8a8b8fe8c23` | +| Cloud ESM proxy | `1a1c92e3985f2af42baff74a6f30e08075709980289f1c1b595fd902acf16eeb` | +| Full compiled transport | `be516371bbd21d7f3a0b4d16713166b43e02b22bf67d67823bedd3ce52dc9590` | +| Compiled 175-module closure | `d65d92fe16a8486e7468b60a4ffa75b504b1eb6fa2ca2d56d31ab9151e1133f5` | +| Observed 26-file Node dynamic closure | `ce8e6d8d7e9845600a853d7d675810268c29126b6deaafdcc1337a4213c05c48` | + +Node is still an operator-supplied observed host runtime, not a newly bundled +or pinned release distribution. The archive proof report has SHA-256 +`a1aecad1bbf8054aa86006251d8ac606a4f2eed33b0265bdee225bc13dbbe20a`; +the compiled-consumer report has SHA-256 +`89f8fa290e840439707df57311cfdd5cd4a89fddb323de6f1b9afa3160d3017e`. +Earlier archive identities below remain historical. Source, package, CI and +controlled proof do not replace the three unqualified live gates. No merge, +public package publication or production rollout was performed. + +### Earlier controlled repair evidence + +The controlled reproduction separated transport delivery from the governed-wait +deadline. Actual Rust/private Node proxy cases delivered the applied question +response and canonical interrupted terminal with both immediate and 18-second +cancellation, without a Stop command. The same real backend under +`executeNativeSession` passed immediate cancellation but failed the 18-second +case at `governed_wait_provider_terminal_unproven`. Cloud permits 20 seconds +for cancellation; the generic governed drain allowed 15 seconds. + +Core repair `9c54295c5060` adds a trusted, optional terminal-drain bound to the +existing cancellation result. The Cloud backend supplies 30 seconds from its +20-second cancellation budget plus handoff margin. Other providers retain the +15-second default. The runtime validates the bound, preserves the existing +operation cap and consumption-owner abort, and still requires the matching +canonical terminal. The same real governed case now passes at both delays. +Fourteen negative, default, operation-cap and recovery controls, 326 affected +unit cases and eight bundle/Grok checks passed. Missing, foreign and explicitly +unconfirmed terminal evidence still fails. No accounting or budget fence changed. +Copilot advances to immutable v73 because shared identity inputs changed; v72 +bytes and decoding are preserved. Grok v8 bytes are unchanged. This asserts no +new Copilot or Grok live qualification. Fresh Core review and CI are required. + +Old Product head `3115d0bf2c` also failed its Copilot v71 source attestation and +the two already-repaired Cloud launch fixtures. One browser test copied whole +page text instead of YAML. Its unchanged isolated case passed, then its complete +six-case browser file passed on the aligned Product source. The original CI +failure remains retained and its cause is unclassified; new-head CI is still +required. No speculative UI or browser-test edit was made. + +The fourth continuation campaign used clean source `de3c7d6b6c27`, with the +same explicit Sonnet selection, omitted parameters, fixture repository/ref, +allow-unpriced opt-in, deadlines and zero automatic retries. Full build passed +and its build stamp matched the source. All source and test files matched +Product `cacb45fd5bfd`; only this qualification document differed. The Runner +package source and exact CJS/daemon bytes were unchanged from the previous +packaged proof. + +The exact question tool was applied. An interrupt command was issued, followed +by a Stop command issued about 15 seconds later. Those command timestamps do +not establish completion times or a fast interrupt acknowledgment. The exact +native stop receipt records `providerExitConfirmed: true`, `remoteStopped: true` +and status `FINISHED`. +The matching Node checkpoint retained its interrupted terminal-delivery batch. +No canonical turn terminal reached Core before the governed-wait drain failed. +The checkpoint's later last-write time is not asserted to be terminal creation +time. The 15-second drain and 20-second Cloud cancellation bounds require a +controlled composition check; the live timing alone does not prove its cause. +This is a candidate terminal-handoff divergence; it is not evidence of a +provider provisioning failure. No eligible replay frame was cut, no answer or +second run completed, and C4 remained on hold. Missing canonical evidence +correctly leaves accounting pending; do not weaken that boundary. + +The ordinary result remains FAIL/cleanup_failure, SHA-256 +`2965928841f50408cc07eb705c9a785680acf2a106735a37ab9a9f1a4f3536f7`. +Its original cleanup could not confirm deletion. Later independent exact owned +Agent/Run lookups both returned 404. That reconciliation does not replace the +original grade. The wrapper restored the exact original CJS and released the +callback port and source/dist freeze. No further paid work is active. + +Before that attempt, the accounting repair passed ten focused tests, including +nine scenarios through the actual PostgreSQL receipt, ledger and budget path. +Matching completed and interrupted terminals settle as complete and explicitly +unpriced, with no fabricated counters or zero dollar cost. Allow-unpriced +permits the next reservation only after ledger settlement; block still blocks. +Missing, foreign and explicitly unconfirmed terminals, capture failures and +replaced recorders retain pending debt. Saved canonical evidence also restores +collection closure on recovery. Generic receipt, ledger and budget code is +unchanged. Full recursive typecheck passed at Product `cacb45fd5bfd`. + +The third continuation campaign on `69edecfd84ae` saved and independently +verified explicit allow-unpriced policies before dispatch. It discovered the +correct MCP server, created the exact structured question and received the +browser answer. The committed matching `turn.interrupted` carried +`error: null` and `status: interrupted`; native cancellation was confirmed and +the exact owned Node process had exited. Nevertheless, Core emitted incomplete +Cursor accounting because numeric usage was absent. The run remained pending +with no accounting receipt, and the normal budget gate paused the company. +The original ordinary result is FAIL/candidate_failure, SHA-256 +`0326c611f99557fbcd0fb6dcda6bacdbcda6f4fe8079189abef2f0cd748d9596`. +Cleanup passed; independent final Agent/Run reads returned 404, the exact +shipping CJS was restored and the callback port was released. One real cut and +cursor reconnect occurred, but no second run completed, so C3/C5 remain +unqualified and C4 is unattempted. + +This is an accounting-producer defect. A confirmed matching committed terminal +must close collection as explicitly unpriced when Cursor supplies no numeric +usage. Missing or mismatched terminals, explicitly unconfirmed provider +termination and capture failures must remain pending. Receipt, ledger and +budget enforcement retain their existing contracts. Prove these boundaries +through the actual accounting path before another paid campaign; do not mutate +the failed measured company to bypass its pending incident. + +The second continuation campaign on `9683ba4678ee` found the run-bound catalog, +created the required structured question and received the real browser answer. +Its next run could not enqueue because the fixture company and agent policies +blocked unpriced usage. A budget incident paused the company after the first +unknown-cost turn; retrying the response could not bypass that policy. The +original result remains FAIL/candidate_failure, SHA-256 +`1dfdd92bef4e69dd09bfde0eb7294f219d5a8bfd8e9803b4e747c2e33791aa93`. +Cleanup passed and exact owned Agent/Run each returned 404. The original CJS was +restored. C5 again exercised a real cut/reconnect, but no second turn completed. + +This is a qualification-policy mismatch, not a reason to change production +budget enforcement. The bounded fixtures now require explicit +`PAPERCLIP_CURSOR_CLOUD_ALLOW_UNPRICED_QUALIFICATION=1`, upsert only their owned +company and agent monthly billed-cent policies, and verify both saved policies +before dispatch. Each remains active with a 1,000-cent known-cost hard stop; +unknown pricing is explicitly allowed under the user's test-spending approval. +It is not a provider dollar cap. Cost reporting remains unknown. Missing opt-in, +failed readback and changed guards block setup. The red controls, 71 passing +fixture/registration cases, 19 strengthened budget controls and full E2E +typecheck are retained. No production default changed. The separate saved local +trial received the same explicit policy through the public API and verified +readback; its actual vendor cost remains unknown. + +Only fixture policy/evidence changed after `9683ba4678ee`; the model prompt, +provider CJS and native daemon are unchanged. Retain all prior grades at their +original definition hashes and run a fresh company/Agent campaign. Do not +unpause the failed measured company or relabel its result. + +The first live continuation/replay campaign failed its required question on +`62fb0252e931`. Cursor queried unrelated inherited account MCP namespaces, both +requiring authentication, and never selected the injected `paperclip` server. +It then ended with objective unsatisfied and no structured question. The +ordinary fixture retained its failed grade and cleanup passed; exact Agent/Run +reads returned 404. No second run or Stop attempt occurred. One real SSE cut +reconnected to the same owned run using the exact cursor, with ordered unique +retained events, but this does not pass the complete C3/C5 contract. Original +CJS bytes were restored after finalization. + +Code and retained C2 traffic identify a product guidance gap. The request names +the injected server, but model-facing instructions did not identify it. C2 +found it by a broad tool search; C3 selected similarly named account servers. +Neither unrelated name comes from the repository, and the current semantic +question tool remains available. [Cursor's SDK documentation](https://cursor.com/docs/sdk/typescript) +confirms that Cloud also loads account/team MCP servers; local setting-source +filters do not apply. The repair now binds one provider server-name constant, +directs discovery to that server on every turn, distinguishes semantic questions +from native callbacks, and explains controller-managed authentication without +VM REST credentials. Two serialized-request regressions first failed; all 46 +Cloud cases then passed. This is a supported correction hypothesis, not a claim +that model causality has been proved. Keep the outcome oracle unchanged and use +a fresh campaign because active checkpoints reject instruction-digest changes. + +Core CI also exposed a real Copilot source-attestation mismatch after shared +bridge/contract changes. The immutable identity advanced to v72 while preserving +the original v71 bytes and decoder. Eighty-six identity/compatibility controls +passed. This refresh does not assert a new Copilot live qualification. The final +Core source has a green full build, 436 selected TypeScript cases, 33 native +backend integrations and eight bundle/profile checks; fresh remote gates for +that source remain pending. Earlier Copilot CI and local failures stay retained. + +A further recovery race was reproduced during review: the native run could +finish between two startup reads, causing Rust to reject the valid terminal +batch against an older active-turn cache. The repair validates active state and +terminal delivery from one snapshot and updates the cache only after validation. +The proxy likewise returns one captured state view after the queued checkpoint +commit. Both native and proxy red controls reproduced the mismatch; all 33 +native integrations and 46 Cloud/facade cases then passed. A paused-write test +also proves thread/read cannot return the random terminal receipt before it is +durable: the response stays blocked while disk remains running, then returns +the exact receipt found in the committed checkpoint. Preserve these controls +and the earlier review grades; a new review is still required for this repair. + +The saved local test-drive was restarted on `abb79acfb016` and returned healthy. +The ordinary UI retained the explicit Sonnet model and organization-secret +reference, passed the account/catalog Test with its expected experimental +warning, and completed Finish setup. Independent API state confirms +`paperclip_runner`, provider `cursor_cloud`, model `claude-sonnet-4-5`, +`secret_ref`, lifecycle `ready` and idle status. Setup sent no provider prompt. +The callback-only tunnel again returned 404 for root/API and 401 for an +unauthenticated native-run request. This validates C1's saved setup on the +repaired application; the later Stop receipt repair changes no setup behavior. + +Final inspection found one related Stop receipt gap: shutdown could close Node +before Rust consumed its retained terminal batch, blocking a later same-Agent +turn. Retained Node/Rust red controls reproduced it. The repair retains the +batch through the shutdown receipt, persists and acknowledges it before process +exit, avoids double settlement, and retries a matching receipt on attachment. +All 33 native backend integrations and 46 controlled Cloud/proxy/facade cases +passed, as did Node typecheck and unchanged Grok v8 identity. The complete +repaired candidate must be rebuilt before the remaining live cells. + +Both recovery findings now have retained red/green controls. Recovery arms the +saved absolute deadline before any read, retries only transient read failures +under that obligation, and aborts pending reads during Stop. Terminal delivery +is persisted privately before publication. Rust imports and deduplicates that +delivery into its durable outbox, saves the receipt, then acknowledges the Node +checkpoint. New work cannot supersede unacknowledged terminal delivery. The +actual Rust regression reproduced the lost-turn failure and then passed crash +before final delivery and partial final delivery with lost acknowledgment. All +32 native backend integrations and 362 selected TypeScript cases passed. Node +typecheck and the existing Grok v8 immutable identity passed; no Grok identity +refresh or new Grok live qualification is asserted. + +The selected CI launch fixture now builds a private proxy, because that lane +does not contain a shared dist bundle. Its missing-dist failure and two passing +real-facade controls are retained. The product test roots also preserve short +Darwin socket paths while using the platform temporary directory elsewhere. +Stop qualification now observes the exact native delayed command, joins its +identity to an unfinished Core execution, and checks again immediately before +UI Stop. Retained native traffic showed argument-free running frames followed +by running argument updates for the same call. The observer accepts consistent +updates and rejects completion, changed ownership, stream loss and expiry. +Its original failures and 73 passing focused controls remain recorded. + +Evidence impact: the recovery repair changes terminal settlement and the Rust +artifact identity. Rebuild and qualify final settlement through the remaining +two-turn continuation cell. It does not change provider artifact discovery, +download, staging, Core file verification or registration, so retain C6's exact +Sonnet-2 artifact evidence. C2 keeps its original candidate identity; do not +relabel that result as a new run. The Stop prompt and observer changed, so only +the new fixture can establish C4. No live replay or Stop pass exists yet. + +`cursor-cloud-local-20261028-artifact-sonnet-2` passed on source `b18b743cd45d`. +The same explicit Sonnet model, omitted parameters, repository/ref, fixture and +deadlines were used after the path repair. All eight ordinary matchers passed: +continuity, exact final marker, task done, run succeeded, native/local execution, +exact registered artifact bytes and MIME, and cleanup. Independent saved state +contains one accepted result with objective satisfied and one registered, +downloadable 24-byte artifact. Its SHA-256 is +`475af2a29ebe3347d92d24efaa58ee6e50a96c1e25297a4410ea12407aa5c1d9`. +The exact owned Cloud Agent and Run each returned 404 after cleanup. The +canonical result SHA-256 is +`eea3414ff54c7de99f4fc533cd4d88d415bc501dc56e95aa73a8c8f7fe09f270`. +This passes C2/C6 for this candidate; vendor cost remains unknown. + +The production stager now returns a path relative to the admitted artifact root +for both fresh and repeated staging. The provider's 33 focused controls passed. +The product regression first reproduced the exact rejection through the actual +Core file reader, then passed normal/repeated handoff and post-staging hash +tamper rejection. A static test import initially failed the server TypeScript +root boundary and emitted eight unwanted source-side files. Only those +untracked emitted files were removed; the established dynamic test import fixed +the compile boundary. Full builds then passed in both the serving checkout and +the independent Product PR checkout. The latter also passed full workspace +typecheck, 1,085 focused tests across 18 files, 46 E2E support tests, token gates +and map gates. These do not replace the unresolved full test gate. + +The repaired CJS proxy is +`dbb219296765add55e7568c4494885f64b9ca5cd7a09128247929995a5e20aa6`. +Its 1,696-entry private tarball (14,012,533 bytes) has SHA-256 +`b25e463011ab6cab7c2b2d9dd53c1b91422025441ab68a66ed0a03880731e551`. +The controlled extracted-package protocol and shutdown proof passed. A first +parity check used the wrong working directory, changing esbuild's source labels; +the unchanged check from the canonical package build directory matched both +shipped bundles exactly. No runtime bytes changed during the live attempt. + +Core review at this stage scored 3/5 and identified two recovery defects: +terminal checkpoint persistence can precede durable delivery of terminal events, +and recovery reads can fail before the saved absolute deadline is armed. The +Core owner is repairing both with regressions. Continuation/replay and Stop are +held until the repaired candidate is built and its evidence impact is recorded. +Diagnose any new divergence before another paid attempt. + +Campaign 5 (`8e4c587102`, explicit `gpt-5.4-mini`) created the exact expected +24-byte file, but native artifact download metadata was rejected before Core +registration. A separate small native diagnostic observed the actual signed +download host, `agent-stores.s3.us-east-1.amazonaws.com`, and independently +verified six expected bytes. The client now accepts that exact host, retaining +the existing HTTPS and bounded-download restrictions. The original red host +regression and failed product grade remain retained. Both owned native Agent +and Run were independently absent after cleanup. + +Campaign 6 (`3050fa41a933`, same Mini model) independently downloaded and verified +the expected native file. Cursor made no semantic task calls and ended with +Paperclip requiring review. The ordinary 600-second fixture deadline graded +the attempt FAIL; its cleanup matcher passed and exact owned native Agent/Run +lookups returned 404. File creation/download alone does not pass C2 or C6. + +One explicit model control uses the same runtime, fixture, repository and +deadlines with catalog model `claude-sonnet-4-5`, omitting model parameters. +Official MCP SDK discovery observed 56 tools through the exact owned callback, +including completion, artifact discovery and registration, without invoking a +task tool. Sonnet called the semantic tools and supplied correct file metadata. +The downloaded and staged 24 bytes match the fixture, but Core rejected the +absolute staged reference with `paperclip_runner_file_handoff_path_denied`. +The provider stager must return a reference relative to its admitted artifact +root; Core's existing containment, symlink and hash checks remain authoritative. +This is an observed integration defect. Preserve the original campaign result +and run a real stage-to-Core regression before a new hosted attempt. + +The current clean private Runner tarball has 1,696 entries, 14,012,523 bytes, +and SHA-256 `bd7b95a988f2ebebdc4fe2e52f19638d4cfb825d3538b89405c1f861e46818e3`. +Its CJS proxy is `fd6ab6b82b66e5b9bd1a60f70ddca34b7fb44d24c21827c77376931afa52640d`; +its daemon is `ba78c864a2a688e53d82e26a2c048ad1ab803c4715c1b847324e84a074deffec`. +After installing only the declared selected dependency closure in an extracted +consumer, the actual compiled transport, Rust daemon and guarded Node proxy +opened and closed successfully: 175 loaded modules remained inside that +consumer, no vendor request occurred, exit was zero and the owned socket was +removed. A sandboxed listener attempt failed with EPERM; the unchanged check +passed with local-listener permission. This is package-boundary proof, not a +public Paperclip install or a passing live task. Rebuild identity after the +pending stager repair before carrying it forward. + +The Core PR uses fixed fetched master `d30c8f42b842` and independent dependencies. +Its full workspace build, 357 focused TypeScript cases, 129 Rust integration +cases and eight bundle/profile checks passed. Its CJS matches the serving +candidate; its independently compiled daemon has different bytes, so binary +equivalence is not claimed. The full repository test gate remains unresolved: +a frozen two-file control passed all 981 native executor cases and the original +chat authority case, but found 21 other chat failures (2,581 passed overall). +Diagnostics and baseline classification are in progress; the failed grade stays +in the record. + +Campaign 3 (`cb5cc2493a`) reached private PRP admission, then failed session open +because the outer Runner launch allowlist omitted six private Cloud config/relay +bindings. Its original failure is retained. The corrected regression reproduced +the exact error through transport, sanitized spawn, Rust and the built Node +proxy, then opened/closed that entire chain without any provider request. Four +spawn-boundary controls and the full launch check passed. Reserved configured +environment prefixes remain blocked. + +Current master `7f10cc058568` was integrated before the first hosted prompt, +preserving its Stop, recovery, human-input and E2E evidence changes. Only an +additive documentation conflict required resolution. Its declared editor +dependencies were installed with pinned pnpm 9; the resolved dependency lock +was retained privately and the tracked lockfile restored per contribution rules. + +Campaign 4 (`5de3610003`) reached real Cloud work and delivered 16 semantic calls +and results to Core. Native discovery emitted some `Invalid arguments` results, +but subsequent dispatch succeeded; those errors do not establish an MCP outage. +The concrete remaining failure was internal `call_api` traffic sent to the +callback-only origin, repeatedly returning 404. The six-minute provider deadline +cancelled the run. The later cleanup readback confirmed its exact owned Agent +and Run absent; this reconciliation does not replace the original failed grade. +No useful artifact or accepted finish was obtained. + +Two observed defects are repaired on candidate `8e4c587102`: Core authority now +uses the actual selected private listener for internal HTTP calls, and the +provider facade preserves native tool names, actual status and bounded/redacted +result output. Native calls use the builtin facade without inventing MCP/process +transport or widening raw argument logging. Six Core routing controls and real +Rust/PRP tool projection checks passed. The official MCP SDK also completed exact +discovery and tool calls through the callback route, relay and Unix bridge. +Returning GET 405 instead of 404 removed unsupported-stream error notifications; +this was protocol noise, not a demonstrated cause of the failed task. Cleanup +now independently verifies remote absence and retains authorization failures. +The combined 18 MCP/observer checks and E2E typecheck passed. + +The required full build passed on `8e4c587102`. Earlier full test runs that spanned +source changes remain incomplete and are not green qualification. Two failures +in such a run passed individually in fresh processes on this frozen candidate; +cache versus test-order effects remain unresolved pending full-file controls. +One existing Rust receipt-limit check failed under the concurrent target and +passed unchanged in isolation; its exact cause is not asserted. All 31 native +backend checks passed. Keep these original failures in the verification record. + +Candidate `2264a82646dda33e159bf1b95c528f4e383b987c` froze the Runner and +product integration in two local commits. The first `task-artifact` campaign, +`cursor-cloud-local-20261028-artifact-1`, found a setup divergence before any +provider prompt: `assertHarnessTestPassed` rejected the successful Cloud +account-catalog receipt because the experimental result has warning status. +The normal saved Test reported its correct informational checks, but lifecycle +verification kept the fresh agent paused, so ordinary task dispatch never +started. The original attempt is retained and was stopped for diagnosis rather +than allowed to consume its task deadline. No Cloud Agent/Run ownership notice +existed at diagnosis. Teardown later observed one local queued run, but no +Cloud checkpoint/create intent existed anywhere in the retained private runtime +tree. Interrupting the waiting browser worker retained its original failed grade +and unconfirmed-cleanup result; its server and database exited. This is not a +passing remote-cleanup observation. C1's connection proof remains valid, but +usable fresh-agent admission is not yet qualified. + +The lifecycle regression first failed both listed/unlisted model cases (28 other +cases passed). The fix recognizes the informational Cloud account-ready receipt +for the native Runner adapter while preserving the experimental warning and +all authentication/failure guards. All 30 focused cases then passed. This does +not turn the recommended model catalog into an allowlist or claim a prompt +response. Evidence impact: the Runner/runtime package bytes are unchanged; +repeat fresh-agent setup and the artifact cell against the new application +candidate, retaining the original setup failure. + +The second campaign, `cursor-cloud-local-20261028-artifact-2`, used candidate +`c011eb97cf10124b679a0c07779137db5750f320`. Fresh-agent lifecycle reached ready +and ordinary task dispatch reached native Runner. Its first divergence was +local PRP admission: `run.prepare` timed out, with zero control-plane connections +and repeated WebSocket 404/500 responses. Startup had advertised the public +callback-only origin to the local Runner. The narrow proxy correctly refused +that unrelated route. No Cloud checkpoint/create intent or remote ownership +notice existed, and no owned Runner/sidecar process remained after teardown. +The original failed result and cleanup-uncertainty grade remain retained; no +provider prompt or vendor cost is asserted from a local running row. Correct +the server's private PRP listener origin while retaining its public callback +origin, then rerun the same bounded artifact cell. + +The startup fix now supplies the actual private HTTP listener host and selected +port to PRP registration. Public auth/runtime URLs retain their existing meaning; +remote transports retain their separate advertised endpoints. Twenty-six focused +runtime-origin, HTTP and PRP tests passed, and server typecheck passed. The next +artifact attempt must verify this boundary through the full product. + +A test-only replay injector is ready for C5. Its 28 controlled tests exercise the +actual Driver/Client, one SSE cut after a complete native event, exact saved +Last-Event-ID, ordered withheld-frame recovery and deduplication. It preserves +and restores exact proxy bundle bytes and records only owned identity/cursor +digests. This is supporting proof only. A future live treatment must record both +bundle hashes, require the normal product result and grade real reconnect proof; +it adds no provider prompt to the selected continuation cell. + +The local restart also reproduced a test-drive bootstrap bug: it used the public +callback-only `server.apiUrl` and stopped after a 404. Bootstrap API and browser +now derive their local origin from the actual started listener. Both IPv4/IPv6 +regressions first failed; all 38 CLI tests and CLI typecheck then passed. The +same saved local instance remains the user-facing test environment. Repository +comment-policy cleanup changed no logic; in-memory CJS/ESM proxy bundles remained +byte-identical and the existing Grok identity check still passed. Rebuild and +record the final Rust artifact identity before carrying package proof forward. + +The isolated development instance completed the ordinary Cursor Cloud setup path +through Save & exit, roster, agent overview, and Harness / Runtime reload. The +saved agent retained native Runner, repository, explicit model placeholder, and +organization-secret reference. It stayed paused with no provider session or run. +Missing-model and missing-key checks were visible. Test then reported the missing +public callback, before any provider prompt. These are local configuration +controls, not a successful authenticated Cloud setup or task. + +That walkthrough exposed two defects now covered by regressions: shared +normalization injected `codexPermissionMode` after valid Cloud conversion, causing +HTTP 422 on save; the generic runtime form also exposed unsupported Thinking +effort. The fixed route regression executes PATCH, GET, resave and actual provider +parsing. Explicit incompatible user configuration remains rejected. Existing +Codex, Claude, Grok, Dot and Pi cases retain their behavior. + +Supporting verification on the current source includes: + +- 275 Runner tests across provider, native backend/launch/contracts and the + existing semantic bridge; this includes the 26 driver-owned cases above and + 12 real loopback Cloud-client cases. +- Eleven executor cases cover actual Cloud admission, selected transport and + credentials, owned artifact root, relay revocation and unknown accounting. + Three runtime-helper cases exercise private files and a real Unix HTTP peer; + three relay cases cover authentication, scope, expiry and revocation. +- Three explicit Product E2E cells are discoverable: task/artifact, same-Agent + question follow-up and active-run UI Stop. Their 86 supporting cases and + complete E2E TypeScript check passed. Missing configuration blocks before + credentials or provider work. The suite refuses public history publication. +- Rust provider lifecycle and shutdown tests passed, including a regression that + first reproduced process reuse and then proved a fresh sidecar with the same + durable thread. Per-turn product execution does not retain a warm daemon. +- The Grok immutable profile advanced to v8 because its bound shared Runner + configuration source changed. The historical v7 identity is preserved and + remains decodable; this is an identity refresh, not new live qualification. +- `pnpm -r typecheck` and `pnpm build` passed. The first build stopped at the stale + Grok identity; the next exposed invalid new test fixture types. Both failures + were corrected. An earlier full test run was interrupted; the final + `pnpm test:run` run is pending and cannot yet be claimed green. +- Token gates, map structural checks, and generated protocol checks passed. + +The clean private Runner candidate tarball contained 1,696 entries and no +`node_modules` or symlinks. Its extracted proxy completed real stdio and Unix MCP +framing, exact synthetic tool input/result, controlled HTTP/SSE terminal lookup, +confirmed shutdown, socket cleanup and exit zero. Both proxy bundles matched +source and referenced only Node builtins. This proves that candidate's runtime +closure, not an ordinary public Paperclip installation or live Cursor work. + +| Candidate artifact | SHA-256 | +| --- | --- | +| Private Runner tarball (14,012,694 bytes) | `7d06c80239725b36241db7fb96a6127efc757ae367b0f20843641a0544b9ed3d` | +| Packaged local daemon | `4492f56745b93392b89e016d2907478ebabcf1025099f79222d66a38dfc8f083` | +| Cloud CJS proxy | `2ccfd84f1acd7e2d15b85b1b772e46a6497b1febbe80c0fb85d6b4f59e909687` | +| Cloud ESM proxy | `a582f2b9c1075cfc2185b7d9351072dd06c6d4ae1744f7110873945a10053429` | + +The observed controller platform was macOS 26.5.2 build 25F84, arm64, with Node +26.4.0. Node remains an operator-supplied runtime. Its observed 26-file dynamic +library closure digest was +`ce8e6d8d7e9845600a853d7d675810268c29126b6deaafdcc1337a4213c05c48`; +it is not a newly bundled or pinned Node distribution. Retest artifact identity +after a build input changes. No merge, public package install, publication, or +deployment has been performed. + +The tarball proof was refreshed after the README's hosted-secret guidance changed. +README.md was the only changed extracted entry; all runtime artifact and Node +closure hashes remained identical. The full controlled packaged round trip and +shutdown proof passed again. The earlier tarball digest +`38bc7632101bdc890591dd58dfb9c75a0956a0c5f1db64c55d963af86c01a1ba` +is retained as historical evidence, not the current candidate archive. + +Rollback means disabling fresh experimental admission or selecting the existing +legacy runtime for future work. Do not rewrite persisted run selection or erase +history. Existing native runs still need their cancellation, reconciliation, and +finalization paths. No merge, publication, deployment, or live completion claim +has been made by this plan. diff --git a/maps/agent-access-map/runs-adapters.md b/maps/agent-access-map/runs-adapters.md index 2b8bff89cca..8fc0e9e281c 100644 --- a/maps/agent-access-map/runs-adapters.md +++ b/maps/agent-access-map/runs-adapters.md @@ -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). diff --git a/maps/feature-map/runs-adapters.md b/maps/feature-map/runs-adapters.md index 1832e1b0af1..89636044630 100644 --- a/maps/feature-map/runs-adapters.md +++ b/maps/feature-map/runs-adapters.md @@ -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. diff --git a/packages/adapter-utils/src/paperclip-runner-permissions.test.ts b/packages/adapter-utils/src/paperclip-runner-permissions.test.ts index fbf45cdf552..b06823c854c 100644 --- a/packages/adapter-utils/src/paperclip-runner-permissions.test.ts +++ b/packages/adapter-utils/src/paperclip-runner-permissions.test.ts @@ -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, diff --git a/packages/adapter-utils/src/paperclip-runner-permissions.ts b/packages/adapter-utils/src/paperclip-runner-permissions.ts index 433c674e1de..18ead96ff13 100644 --- a/packages/adapter-utils/src/paperclip-runner-permissions.ts +++ b/packages/adapter-utils/src/paperclip-runner-permissions.ts @@ -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 { + 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" diff --git a/packages/adapter-utils/src/server-utils.test.ts b/packages/adapter-utils/src/server-utils.test.ts index fcbe8c8510f..655edbfaac2 100644 --- a/packages/adapter-utils/src/server-utils.test.ts +++ b/packages/adapter-utils/src/server-utils.test.ts @@ -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" }; diff --git a/packages/adapter-utils/src/server-utils.ts b/packages/adapter-utils/src/server-utils.ts index 674017364fb..294ce96bbf6 100644 --- a/packages/adapter-utils/src/server-utils.ts +++ b/packages/adapter-utils/src/server-utils.ts @@ -4284,7 +4284,7 @@ export function normalizePaperclipRunnerAdapterConfig( ): Record { 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 = { diff --git a/packages/adapters/codex-local/src/ui/build-config.test.ts b/packages/adapters/codex-local/src/ui/build-config.test.ts index 71635eb0452..7bf6e308b8a 100644 --- a/packages/adapters/codex-local/src/ui/build-config.test.ts +++ b/packages/adapters/codex-local/src/ui/build-config.test.ts @@ -36,6 +36,16 @@ function makeValues(overrides: Partial = {}): 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)) })); diff --git a/packages/adapters/codex-local/src/ui/build-config.ts b/packages/adapters/codex-local/src/ui/build-config.ts index 37b8216d31a..ee42d795930 100644 --- a/packages/adapters/codex-local/src/ui/build-config.ts +++ b/packages/adapters/codex-local/src/ui/build-config.ts @@ -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; diff --git a/packages/paperclip-runner/README.md b/packages/paperclip-runner/README.md index d0ad4ec7bea..a7e77abe79b 100644 --- a/packages/paperclip-runner/README.md +++ b/packages/paperclip-runner/README.md @@ -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 diff --git a/packages/shared/src/agent-runner.test.ts b/packages/shared/src/agent-runner.test.ts new file mode 100644 index 00000000000..b430f3355cf --- /dev/null +++ b/packages/shared/src/agent-runner.test.ts @@ -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"); + }); +}); diff --git a/packages/shared/src/agent-runner.ts b/packages/shared/src/agent-runner.ts index 496c3a3c82a..e9d02159f80 100644 --- a/packages/shared/src/agent-runner.ts +++ b/packages/shared/src/agent-runner.ts @@ -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; } diff --git a/server/src/__tests__/agent-adapter-validation-routes.test.ts b/server/src/__tests__/agent-adapter-validation-routes.test.ts index 37e87a37261..75c8f730ed7 100644 --- a/server/src/__tests__/agent-adapter-validation-routes.test.ts +++ b/server/src/__tests__/agent-adapter-validation-routes.test.ts @@ -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 } })); diff --git a/server/src/__tests__/agent-harness-verification.test.ts b/server/src/__tests__/agent-harness-verification.test.ts index 8d5a68cca20..307e63929ea 100644 --- a/server/src/__tests__/agent-harness-verification.test.ts +++ b/server/src/__tests__/agent-harness-verification.test.ts @@ -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"); + }); }); diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index 109b25df894..a24284fb64f 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -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(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; + if (window.generation === Number(oldWindow.generation) + 1 && window.outcome === "epoch_initialized") { + rearmEntered = true; + await rearmMayFinish; + } + } + return pending; + }, + })); let release!: () => void; let pending: Promise | 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 () => { diff --git a/server/src/__tests__/http-log-redaction.test.ts b/server/src/__tests__/http-log-redaction.test.ts index 9e075c7c9f4..7dec45253d7 100644 --- a/server/src/__tests__/http-log-redaction.test.ts +++ b/server/src/__tests__/http-log-redaction.test.ts @@ -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[] = []; diff --git a/server/src/__tests__/private-hostname-guard.test.ts b/server/src/__tests__/private-hostname-guard.test.ts index e1f8a696e47..9481dd8ccf2 100644 --- a/server/src/__tests__/private-hostname-guard.test.ts +++ b/server/src/__tests__/private-hostname-guard.test.ts @@ -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 = { 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"); diff --git a/server/src/__tests__/runtime-api.test.ts b/server/src/__tests__/runtime-api.test.ts index 6640af4d000..782f2e6aaef 100644 --- a/server/src/__tests__/runtime-api.test.ts +++ b/server/src/__tests__/runtime-api.test.ts @@ -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(resolve => server.close(() => resolve())); + runnerPrpWebSocketInternals.resetForTests(); + } + }); + it("prefers the explicit public base URL for the primary runtime URL", () => { expect( choosePrimaryRuntimeApiUrl({ diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index fbcff811fed..f53c3a62804 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -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 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 = {}) { 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(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 () => { diff --git a/server/src/__tests__/task-interruption-query.test.ts b/server/src/__tests__/task-interruption-query.test.ts index 8e44c6f60c2..3983ab50572 100644 --- a/server/src/__tests__/task-interruption-query.test.ts +++ b/server/src/__tests__/task-interruption-query.test.ts @@ -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>; let db: ReturnType; - 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 { diff --git a/server/src/adapters/registry.test.ts b/server/src/adapters/registry.test.ts index 3e7f6a4d63e..a1cea55ab57 100644 --- a/server/src/adapters/registry.test.ts +++ b/server/src/adapters/registry.test.ts @@ -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); diff --git a/server/src/adapters/registry.ts b/server/src/adapters/registry.ts index c3cf5ca769c..7540a1e672a 100644 --- a/server/src/adapters/registry.ts +++ b/server/src/adapters/registry.ts @@ -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).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", diff --git a/server/src/app.ts b/server/src/app.ts index 17b4e63e127..75a3ee1c207 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -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 void>(); let lifecyclePluginsReady = false; const agentLifecycle = startAgentLifecycle(db, createLifecycleDriver(db, workerManager), () => lifecyclePluginsReady && !isWarmStandby() && !isIdleTaskDrainActive()); diff --git a/server/src/http/server.test.ts b/server/src/http/server.test.ts index ec7d7a50cb6..b548858d23f 100644 --- a/server/src/http/server.test.ts +++ b/server/src/http/server.test.ts @@ -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(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(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(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(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> | 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((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(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(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(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); + }); }); diff --git a/server/src/http/server.ts b/server/src/http/server.ts index 232f2ce8324..cbf2948c3ca 100644 --- a/server/src/http/server.ts +++ b/server/src/http/server.ts @@ -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; } diff --git a/server/src/index.ts b/server/src/index.ts index ce02001ecf9..6f9dc17b683 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -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) diff --git a/server/src/middleware/http-log-redaction.ts b/server/src/middleware/http-log-redaction.ts index 21acd2a633f..ea663cf9d68 100644 --- a/server/src/middleware/http-log-redaction.ts +++ b/server/src/middleware/http-log-redaction.ts @@ -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"]', diff --git a/server/src/middleware/private-hostname-guard.ts b/server/src/middleware/private-hostname-guard.ts index fff52698377..28b0cb33e95 100644 --- a/server/src/middleware/private-hostname-guard.ts +++ b/server/src/middleware/private-hostname-guard.ts @@ -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; } diff --git a/server/src/realtime/runner-prp-ws.test.ts b/server/src/realtime/runner-prp-ws.test.ts index 8263701b3f7..7fb3e124e42 100644 --- a/server/src/realtime/runner-prp-ws.test.ts +++ b/server/src/realtime/runner-prp-ws.test.ts @@ -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", diff --git a/server/src/realtime/runner-prp-ws.ts b/server/src/realtime/runner-prp-ws.ts index ad5f9b4a9e6..f1dbefcd48c 100644 --- a/server/src/realtime/runner-prp-ws.ts +++ b/server/src/realtime/runner-prp-ws.ts @@ -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(); const currentLiveAuthorities = new Map(); -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 }> { - 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(); }, }; diff --git a/server/src/routes/native-run-mcp.ts b/server/src/routes/native-run-mcp.ts new file mode 100644 index 00000000000..f64186aa44a --- /dev/null +++ b/server/src/routes/native-run-mcp.ts @@ -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; +} diff --git a/server/src/runtime-api.ts b/server/src/runtime-api.ts index 6efa34ca14c..4c4f87868a6 100644 --- a/server/src/runtime-api.ts +++ b/server/src/runtime-api.ts @@ -1,4 +1,19 @@ import os from "node:os"; +import type { Server } from "node:http"; +import { isIP } from "node:net"; + +const runtimeApiListeners = new Set(); +const registeredRuntimeApiListeners = new WeakSet(); + +/** 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[]; diff --git a/server/src/services/agent-harness-verification.ts b/server/src/services/agent-harness-verification.ts index ed585faf18d..9a203f04e50 100644 --- a/server/src/services/agent-harness-verification.ts +++ b/server/src/services/agent-harness-verification.ts @@ -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"))); diff --git a/server/src/services/agent-runner-selection.test.ts b/server/src/services/agent-runner-selection.test.ts index 22114120f57..41b722e36e6 100644 --- a/server/src/services/agent-runner-selection.test.ts +++ b/server/src/services/agent-runner-selection.test.ts @@ -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 }; diff --git a/server/src/services/agent-runner-selection.ts b/server/src/services/agent-runner-selection.ts index 843d69b699a..68802917de8 100644 --- a/server/src/services/agent-runner-selection.ts +++ b/server/src/services/agent-runner-selection.ts @@ -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 }); } diff --git a/server/src/services/heartbeat/queue.test.ts b/server/src/services/heartbeat/queue.test.ts index a284c214f09..65ff52365cb 100644 --- a/server/src/services/heartbeat/queue.test.ts +++ b/server/src/services/heartbeat/queue.test.ts @@ -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>); + // 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(resolve => { reached = resolve; }); + const admissionMayContinue = new Promise(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>); + 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 = { issueId: f.issue.id, source: "issue.continuation_recovery" }; + const payload: Record = { 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(); diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 5f8bd897f65..d6902a99374 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -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, { diff --git a/server/src/services/heartbeat/runtime-selection.ts b/server/src/services/heartbeat/runtime-selection.ts index 6fab2c82c42..8ea310b1eb7 100644 --- a/server/src/services/heartbeat/runtime-selection.ts +++ b/server/src/services/heartbeat/runtime-selection.ts @@ -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" diff --git a/server/src/services/native-runtime/cursor-cloud-artifact-handoff.test.ts b/server/src/services/native-runtime/cursor-cloud-artifact-handoff.test.ts new file mode 100644 index 00000000000..76519ce403c --- /dev/null +++ b/server/src/services/native-runtime/cursor-cloud-artifact-handoff.test.ts @@ -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"); + }); +}); diff --git a/server/src/services/native-runtime/cursor-cloud-profile.test.ts b/server/src/services/native-runtime/cursor-cloud-profile.test.ts new file mode 100644 index 00000000000..51e28dfc051 --- /dev/null +++ b/server/src/services/native-runtime/cursor-cloud-profile.test.ts @@ -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" })); + }); +}); diff --git a/server/src/services/native-runtime/cursor-cloud-runtime.test.ts b/server/src/services/native-runtime/cursor-cloud-runtime.test.ts new file mode 100644 index 00000000000..c62fc3c4fce --- /dev/null +++ b/server/src/services/native-runtime/cursor-cloud-runtime.test.ts @@ -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> = []; +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 { + 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((resolve, reject) => { server.once("error", reject); server.listen(before.PAPERCLIP_CURSOR_CLOUD_RELAY_SOCKET_PATH, resolve); }); + disposers.push(() => new Promise(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"); + }); +}); diff --git a/server/src/services/native-runtime/cursor-cloud-runtime.ts b/server/src/services/native-runtime/cursor-cloud-runtime.ts new file mode 100644 index 00000000000..ce4db554d3e --- /dev/null +++ b/server/src/services/native-runtime/cursor-cloud-runtime.ts @@ -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), + } }; +} diff --git a/server/src/services/native-runtime/native-execution-input.test.ts b/server/src/services/native-runtime/native-execution-input.test.ts index af389f7e866..6f9644b97ff 100644 --- a/server/src/services/native-runtime/native-execution-input.test.ts +++ b/server/src/services/native-runtime/native-execution-input.test.ts @@ -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", () => { diff --git a/server/src/services/native-runtime/native-execution-input.ts b/server/src/services/native-runtime/native-execution-input.ts index f613d644a97..9e71e45cf50 100644 --- a/server/src/services/native-runtime/native-execution-input.ts +++ b/server/src/services/native-runtime/native-execution-input.ts @@ -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, diff --git a/server/src/services/native-runtime/native-question-bridge.test.ts b/server/src/services/native-runtime/native-question-bridge.test.ts index 22cfdc19004..971ccc16ac5 100644 --- a/server/src/services/native-runtime/native-question-bridge.test.ts +++ b/server/src/services/native-runtime/native-question-bridge.test.ts @@ -262,6 +262,7 @@ describeEmbeddedPostgres("native question bridge", () => { const stateDirectory = mkdtempSync(join(tmpdir(), "native-permission-authority-")); const server = createServer(); + await new Promise(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(resolve => server.close(() => resolve())); rmSync(stateDirectory, { recursive: true, force: true }); } }); diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 1ee386fce17..04e4ce3f093 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -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["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), duplicate: undefined as undefined | ((event: PrpEvent) => Promise) })); vi.mock("./paperclip-control-plane-port.js", async importOriginal => { const original = await importOriginal(); @@ -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("../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>; + 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); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 5ff6c625147..c68407087e2 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -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 | null = null; let observedAccountingTurn: string | undefined; let nativeAccountingComplete = false; + const cursorCloudAccounting = input.execution.provider.kind === "cursor_cloud" ? new Map() : 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 | undefined; const producerOwnsUsage = usesNativeUsageDelivery({ runnerd: input.useRunnerd === true, @@ -8912,14 +8933,14 @@ async function executePaperclipNativeSessionWithinScope( }) : undefined; const persistAccountingUsage = async (usage: Record | 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, nativeTerminal: native.terminal as unknown as Record, ...((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): Pick { + 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(); 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; } diff --git a/server/src/services/native-runtime/native-usage-accounting.test.ts b/server/src/services/native-runtime/native-usage-accounting.test.ts index 7e40c08fd3f..16286d47417 100644 --- a/server/src/services/native-runtime/native-usage-accounting.test.ts +++ b/server/src/services/native-runtime/native-usage-accounting.test.ts @@ -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); }); diff --git a/server/src/services/native-runtime/native-usage-accounting.ts b/server/src/services/native-runtime/native-usage-accounting.ts index 9bbeb41ba93..8ef04b1da17 100644 --- a/server/src/services/native-runtime/native-usage-accounting.ts +++ b/server/src/services/native-runtime/native-usage-accounting.ts @@ -46,6 +46,7 @@ function nativeUsageMeasurement(usage: Record) { } 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 | 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. diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index 5fab72c4c2c..5b4f8a640bc 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -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(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((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", diff --git a/server/src/services/native-runtime/provider-profile.ts b/server/src/services/native-runtime/provider-profile.ts index 2483ee5242f..301c9b590c5 100644 --- a/server/src/services/native-runtime/provider-profile.ts +++ b/server/src/services/native-runtime/provider-profile.ts @@ -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): 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, requireBinding = true): string | null { const bindingId = optionalString(config.dotBindingId); @@ -201,9 +237,9 @@ export function validatePaperclipRunnerGrokConfig(config: Record void | Promise> = []; +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 = []; + 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(resolve => server.listen(socketPath, resolve)); + cleanup.push(() => new Promise(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(); + 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(resolve => server.listen(socketPath, resolve)); + cleanup.push(() => new Promise(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"); + }); +}); diff --git a/server/src/services/native-runtime/remote-mcp-relay.ts b/server/src/services/native-runtime/remote-mcp-relay.ts new file mode 100644 index 00000000000..e3ed1f02bd5 --- /dev/null +++ b/server/src/services/native-runtime/remote-mcp-relay.ts @@ -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; +} + +const bindings = new Map(); +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); + }); +} diff --git a/server/src/services/native-runtime/runner-prp-coordinator.test.ts b/server/src/services/native-runtime/runner-prp-coordinator.test.ts index 34b30505405..d2336bc0746 100644 --- a/server/src/services/native-runtime/runner-prp-coordinator.test.ts +++ b/server/src/services/native-runtime/runner-prp-coordinator.test.ts @@ -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(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(resolve => server.close(() => resolve())); }); it("rechecks task ownership and returns semantic receipts", async () => { diff --git a/server/src/services/native-runtime/runtime-mode.test.ts b/server/src/services/native-runtime/runtime-mode.test.ts index 7baeaee0483..b8089e6f25d 100644 --- a/server/src/services/native-runtime/runtime-mode.test.ts +++ b/server/src/services/native-runtime/runtime-mode.test.ts @@ -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; diff --git a/server/src/services/native-runtime/runtime-mode.ts b/server/src/services/native-runtime/runtime-mode.ts index 3de349db718..a469e1d2d12 100644 --- a/server/src/services/native-runtime/runtime-mode.ts +++ b/server/src/services/native-runtime/runtime-mode.ts @@ -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 diff --git a/server/src/services/task-interruption-presentation.test.ts b/server/src/services/task-interruption-presentation.test.ts index 7c2b98bc963..bf534b439d8 100644 --- a/server/src/services/task-interruption-presentation.test.ts +++ b/server/src/services/task-interruption-presentation.test.ts @@ -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.", diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index fc0b5574abc..eabc90cb86d 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -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; type ProjectionRun = Pick & - Partial>; + Partial>; 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`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>`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))) diff --git a/server/src/vendor/paperclip-runner/index.ts b/server/src/vendor/paperclip-runner/index.ts index 3df1e702c6e..3664aff24d0 100644 --- a/server/src/vendor/paperclip-runner/index.ts +++ b/server/src/vendor/paperclip-runner/index.ts @@ -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; diff --git a/tests/e2e/connection-reviews.spec.ts b/tests/e2e/connection-reviews.spec.ts index bf36a6db886..a695776b390 100644 --- a/tests/e2e/connection-reviews.spec.ts +++ b/tests/e2e/connection-reviews.spec.ts @@ -300,7 +300,7 @@ for (const journey of [ ? "Read failed" : "Roadmap", ); - const replies = await json>(await request.get(`/api/issues/${issue.id}/comments`)); + const replies = await json>(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"), }); diff --git a/tests/e2e/task-loading-frame.spec.ts b/tests/e2e/task-loading-frame.spec.ts index aeb03694b03..f607b245059 100644 --- a/tests/e2e/task-loading-frame.spec.ts +++ b/tests/e2e/task-loading-frame.spec.ts @@ -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(); diff --git a/tests/runner-e2e/FIXTURES.md b/tests/runner-e2e/FIXTURES.md index bfdefb69712..6e653494ad6 100644 --- a/tests/runner-e2e/FIXTURES.md +++ b/tests/runner-e2e/FIXTURES.md @@ -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, diff --git a/tests/runner-e2e/README.md b/tests/runner-e2e/README.md index d8d3a42d750..49c359a300e 100644 --- a/tests/runner-e2e/README.md +++ b/tests/runner-e2e/README.md @@ -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 diff --git a/tests/runner-e2e/SECURITY.md b/tests/runner-e2e/SECURITY.md index ccefe71924b..5abc39cb853 100644 --- a/tests/runner-e2e/SECURITY.md +++ b/tests/runner-e2e/SECURITY.md @@ -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 diff --git a/tests/runner-e2e/braintrust-experiment.test.ts b/tests/runner-e2e/braintrust-experiment.test.ts index 806bfc64a0a..da4c648c2a4 100644 --- a/tests/runner-e2e/braintrust-experiment.test.ts +++ b/tests/runner-e2e/braintrust-experiment.test.ts @@ -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 })) }; diff --git a/tests/runner-e2e/catalog.test.ts b/tests/runner-e2e/catalog.test.ts index f171e3c5b00..bf76e7c8c3f 100644 --- a/tests/runner-e2e/catalog.test.ts +++ b/tests/runner-e2e/catalog.test.ts @@ -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); diff --git a/tests/runner-e2e/catalog.ts b/tests/runner-e2e/catalog.ts index d6b65064441..4100e707f9d 100644 --- a/tests/runner-e2e/catalog.ts +++ b/tests/runner-e2e/catalog.ts @@ -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, diff --git a/tests/runner-e2e/chat-qualification.ts b/tests/runner-e2e/chat-qualification.ts index 6486e4b35cc..737957dd834 100644 --- a/tests/runner-e2e/chat-qualification.ts +++ b/tests/runner-e2e/chat-qualification.ts @@ -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) })) }); } } diff --git a/tests/runner-e2e/chat-stories.test.ts b/tests/runner-e2e/chat-stories.test.ts index 762d6fae37e..3979b9f1219 100644 --- a/tests/runner-e2e/chat-stories.test.ts +++ b/tests/runner-e2e/chat-stories.test.ts @@ -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(); + 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("node:fs/promises"); + let releaseWrite!: () => void; + const pausedWrite = new Promise(resolve => { releaseWrite = resolve; }); + let exposedEmptyWrite!: (file: Parameters[0]) => void; + const emptyWrite = new Promise[0]>(resolve => { exposedEmptyWrite = resolve; }); + let running: Promise<{ stdout: string; stderr: string }> | undefined; + let publishing: Promise | 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 }); diff --git a/tests/runner-e2e/chat-stories.ts b/tests/runner-e2e/chat-stories.ts index a28adac861c..73aa77a4f88 100644 --- a/tests/runner-e2e/chat-stories.ts +++ b/tests/runner-e2e/chat-stories.ts @@ -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(`/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(chatPath).catch(() => null); await input.evidence("chat-interruption-state.json", { diff --git a/tests/runner-e2e/completion-update-flow.ts b/tests/runner-e2e/completion-update-flow.ts index b3a852f823a..956f8971ada 100644 --- a/tests/runner-e2e/completion-update-flow.ts +++ b/tests/runner-e2e/completion-update-flow.ts @@ -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; @@ -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(`/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(); } } diff --git a/tests/runner-e2e/context-integrity-evidence.test.ts b/tests/runner-e2e/context-integrity-evidence.test.ts index 53f5e2453dd..30ad02e92c4 100644 --- a/tests/runner-e2e/context-integrity-evidence.test.ts +++ b/tests/runner-e2e/context-integrity-evidence.test.ts @@ -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")); diff --git a/tests/runner-e2e/cursor-cloud-budget.test.ts b/tests/runner-e2e/cursor-cloud-budget.test.ts new file mode 100644 index 00000000000..537ae665134 --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-budget.test.ts @@ -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) => unknown) { + const calls: Array<{ method: string; path: string; body?: any }> = []; + const policies: Array> = []; + 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) { + 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).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(); + }); +}); diff --git a/tests/runner-e2e/cursor-cloud-budget.ts b/tests/runner-e2e/cursor-cloud-budget.ts new file mode 100644 index 00000000000..efe400deea2 --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-budget.ts @@ -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; +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; companyId: string; agentId: string; +}): Promise { + 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(`${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 }; +} diff --git a/tests/runner-e2e/cursor-cloud-callback-proxy.ts b/tests/runner-e2e/cursor-cloud-callback-proxy.ts new file mode 100644 index 00000000000..0c3e315df66 --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-callback-proxy.ts @@ -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 = { "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((resolve, reject) => { server.once("error", reject); server.listen(input.port, "127.0.0.1", resolve); }); + return async () => { server.closeAllConnections(); await new Promise((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"); + } +} diff --git a/tests/runner-e2e/cursor-cloud-cases.ts b/tests/runner-e2e/cursor-cloud-cases.ts new file mode 100644 index 00000000000..b6723bdc373 --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-cases.ts @@ -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:, 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: () => [], +}; diff --git a/tests/runner-e2e/cursor-cloud-mcp-sdk.test.ts b/tests/runner-e2e/cursor-cloud-mcp-sdk.test.ts new file mode 100644 index 00000000000..3ed20ddbdc6 --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-mcp-sdk.test.ts @@ -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> = []; +afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close(); }); +const listen = async (server: Server) => { + await new Promise((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((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); +}); diff --git a/tests/runner-e2e/cursor-cloud-observer.ts b/tests/runner-e2e/cursor-cloud-observer.ts new file mode 100644 index 00000000000..61b24faacc9 --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-observer.ts @@ -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; +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(); + 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(`/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(`/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((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 { + 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 { + 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 { + 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` }]; + } +} diff --git a/tests/runner-e2e/cursor-cloud-replay-fault.test.ts b/tests/runner-e2e/cursor-cloud-replay-fault.test.ts new file mode 100644 index 00000000000..a2e34c1771a --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-replay-fault.test.ts @@ -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({ 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(() => {})); + 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((_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[0], _init?: Parameters[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; } +}); diff --git a/tests/runner-e2e/cursor-cloud-replay-fault.ts b/tests/runner-e2e/cursor-cloud-replay-fault.ts new file mode 100644 index 00000000000..29257ab3bab --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-replay-fault.ts @@ -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; +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({ + 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(input: { bundlePath: string; evidenceDirectory: string }, run: (manifest: CursorCloudReplayFaultManifest) => Promise): Promise { + const treatment = await installCursorCloudReplayFault(input); + try { return await run(treatment.manifest); } finally { await treatment.restore(); } +} + +export async function readCursorCloudReplayFaultProofs(evidenceDirectory: string, manifest: CursorCloudReplayFaultManifest): Promise { + 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 { + 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 => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + const exact = (value: Record, 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" }; +} diff --git a/tests/runner-e2e/cursor-cloud-stop-flow.ts b/tests/runner-e2e/cursor-cloud-stop-flow.ts new file mode 100644 index 00000000000..1000e2defc5 --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-stop-flow.ts @@ -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; +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; + evidence(name: string, value: unknown): Promise; +}) { + 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(`/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((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(); } +} diff --git a/tests/runner-e2e/cursor-cloud-stop-observation.test.ts b/tests/runner-e2e/cursor-cloud-stop-observation.test.ts new file mode 100644 index 00000000000..b61a8ed61be --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-stop-observation.test.ts @@ -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 | undefined, signal: AbortSignal | undefined, sequence = 0; + const cancelled = vi.fn(); + const fetcher = vi.fn(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({ 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(); +}); diff --git a/tests/runner-e2e/cursor-cloud-stop-observation.ts b/tests/runner-e2e/cursor-cloud-stop-observation.ts new file mode 100644 index 00000000000..08bdc9efeb0 --- /dev/null +++ b/tests/runner-e2e/cursor-cloud-stop-observation.ts @@ -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; +const record = (value: unknown): Row => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Row : {}; + +export class CursorCloudStopCommandTracker { + readonly #pending = new Map(); + readonly #completed = new Set(); + #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; + readonly #timer: NodeJS.Timeout; + #failure: Error | undefined; + #closed = false; + constructor(input: { client: Pick; 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 { 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; +} diff --git a/tests/runner-e2e/cursor-cloud.test.ts b/tests/runner-e2e/cursor-cloud.test.ts new file mode 100644 index 00000000000..aae385482b8 --- /dev/null +++ b/tests/runner-e2e/cursor-cloud.test.ts @@ -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>, identities: Array>) => 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((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((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); } +}); diff --git a/tests/runner-e2e/daytona-image.test.ts b/tests/runner-e2e/daytona-image.test.ts index 11d40efc150..b1a0306ae46 100644 --- a/tests/runner-e2e/daytona-image.test.ts +++ b/tests/runner-e2e/daytona-image.test.ts @@ -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", diff --git a/tests/runner-e2e/history-publish.ts b/tests/runner-e2e/history-publish.ts index 1d40262c2c2..92067916fd8 100644 --- a/tests/runner-e2e/history-publish.ts +++ b/tests/runner-e2e/history-publish.ts @@ -121,7 +121,7 @@ export function publicScreenshotPaths(campaign: RunnerE2ECampaign) { } export function assertPublicCampaign(campaign: Pick) { - 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"); } } diff --git a/tests/runner-e2e/history.test.ts b/tests/runner-e2e/history.test.ts index 1f480f6e24b..f1ea0be69e7 100644 --- a/tests/runner-e2e/history.test.ts +++ b/tests/runner-e2e/history.test.ts @@ -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", diff --git a/tests/runner-e2e/live-fixtures.ts b/tests/runner-e2e/live-fixtures.ts index f6726c67f75..f97c42e5dc6 100644 --- a/tests/runner-e2e/live-fixtures.ts +++ b/tests/runner-e2e/live-fixtures.ts @@ -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; }): Promise { 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( + const createdAgent = await api.post( `/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(setup.values, "secrets"), environment: value(setup.values, "environment"), agent: value(setup.values, "agent"), + ...(qualificationBudget ? { qualificationBudget } : {}), ...(setupProbe ? { setupProbe } : {}), ...(setup.values.has("project") ? { project: value(setup.values, "project") } diff --git a/tests/runner-e2e/prerequisites.ts b/tests/runner-e2e/prerequisites.ts index 807e568c1a6..140a1f0b5ad 100644 --- a/tests/runner-e2e/prerequisites.ts +++ b/tests/runner-e2e/prerequisites.ts @@ -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; + +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 = 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")) { diff --git a/tests/runner-e2e/runner.spec.ts b/tests/runner-e2e/runner.spec.ts index e87e1a04585..730eebfb2a2 100644 --- a/tests/runner-e2e/runner.spec.ts +++ b/tests/runner-e2e/runner.spec.ts @@ -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> = []; @@ -680,6 +683,7 @@ for (const execution of executions) { let startupReuse: RunnerE2EResult["startupReuse"]; const turnSubmissionTimesMs: number[] = []; const screenshots: NonNullable = []; + 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") { diff --git a/tests/runner-e2e/server.ts b/tests/runner-e2e/server.ts index a68737020a3..7698c6a0d8e 100644 --- a/tests/runner-e2e/server.ts +++ b/tests/runner-e2e/server.ts @@ -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) | 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((resolve) => log.end(resolve)); process.exitCode = exitCode; diff --git a/tests/runner-e2e/types.ts b/tests/runner-e2e/types.ts index 4dab61023ca..5ab04bac2c4 100644 --- a/tests/runner-e2e/types.ts +++ b/tests/runner-e2e/types.ts @@ -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"; diff --git a/ui/src/adapters/codex-local/config-fields.test.tsx b/ui/src/adapters/codex-local/config-fields.test.tsx index 9db025c1a7c..6b8da1ebccc 100644 --- a/ui/src/adapters/codex-local/config-fields.test.tsx +++ b/ui/src/adapters/codex-local/config-fields.test.tsx @@ -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 = 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 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()); + const picker = container.querySelector('[aria-label="Harness"]')!; + await act(async () => picker.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }))); + const cloudOption = [...document.querySelectorAll('[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" }); diff --git a/ui/src/adapters/codex-local/config-fields.tsx b/ui/src/adapters/codex-local/config-fields.tsx index b1747d4a423..148caa904d9 100644 --- a/ui/src/adapters/codex-local/config-fields.tsx +++ b/ui/src/adapters/codex-local/config-fields.tsx @@ -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({ )} {runnerManaged && runnerProvider === "grok_bot" && } + {runnerManaged && isCursorCloud && <> +

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.

+ {[ + { 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 => + { + 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); } + }} /> + )} + {[ + { key: "workOnCurrentBranch", label: "Work on current branch" }, + { key: "autoCreatePR", label: "Auto-create pull request" }, + { key: "skipReviewerRequest", label: "Skip reviewer request" }, + ].map(field => updateRunnerSchemaValue(field.key, value)} />)} + } {runnerManaged && runnerProvider === "openai_dot" && <> updateRunnerSchemaValue("dotBindingId", id)} /> @@ -551,7 +582,7 @@ export function CodexLocalConfigFields({ )} )} - {runnerManaged && !isExternal && ( + {runnerManaged && !isExternal && !isCursorCloud && ( )} - {runnerManaged && !isExternal && runnerLifecycleMode === "warm" && ( + {runnerManaged && !isExternal && !isCursorCloud && runnerLifecycleMode === "warm" && ( - api.post(`/heartbeat-runs/${runId}/cancel`, {}), + api.post(`/heartbeat-runs/${runId}/cancel`, {}), resolveRuntimeRequest: (input: { runId: string; requestId: string; diff --git a/ui/src/components/AgentConfigForm.render.test.tsx b/ui/src/components/AgentConfigForm.render.test.tsx index 9ebdee50e10..7cba9d2a5d6 100644 --- a/ui/src/components/AgentConfigForm.render.test.tsx +++ b/ui/src/components/AgentConfigForm.render.test.tsx @@ -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" } }); diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx index d0ac255e123..d5f65b5d45e 100644 --- a/ui/src/components/AgentConfigForm.tsx +++ b/ui/src/components/AgentConfigForm.tsx @@ -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 diff --git a/ui/src/components/InlineEditor.test.tsx b/ui/src/components/InlineEditor.test.tsx index 8261aa07588..e913741bd06 100644 --- a/ui/src/components/InlineEditor.test.tsx +++ b/ui/src/components/InlineEditor.test.tsx @@ -92,6 +92,70 @@ describe("InlineEditor", () => { container.remove(); }); + it.each(["unchanged", "escape", "save", "failure"])("reports single-line editing through %s without an initial closed notification", async (exit) => { + const onEditingChange = vi.fn(); + let resolve!: () => void; + let reject!: (error: Error) => void; + const onSave = vi.fn(() => new Promise((done, fail) => { resolve = done; reject = fail; })); + const root = createRoot(container); + try { + await act(async () => root.render(signedIn("user-1", ))); + expect(onEditingChange).not.toHaveBeenCalled(); + await act(async () => container.querySelector("span")!.click()); + expect(onEditingChange.mock.calls).toEqual([[true]]); + const input = container.querySelector("textarea")!; + if (exit === "save" || exit === "failure") act(() => setNativeTextareaValue(input, "Edited title")); + await act(async () => input.dispatchEvent(new KeyboardEvent("keydown", { key: exit === "escape" ? "Escape" : "Enter", bubbles: true }))); + if (exit === "save" || exit === "failure") { + expect(onSave).toHaveBeenCalledWith("Edited title"); + expect(onEditingChange.mock.calls).toEqual([[true]]); + if (exit === "failure") { + await act(async () => reject(new Error("Save unavailable"))); + expect(onEditingChange.mock.calls).toEqual([[true]]); + expect(container.querySelector("textarea")?.value).toBe("Edited title"); + return; + } + await act(async () => resolve()); + } + expect(onEditingChange.mock.calls).toEqual([[true], [false]]); + expect(container.querySelector("textarea")).toBeNull(); + } finally { act(() => root.unmount()); } + }); + + it("reports a restored single-line edit and retires it before a late save completes", async () => { + const onEditingChange = vi.fn(); + let resolve!: () => void; + const onSave = vi.fn(() => new Promise((done) => { resolve = done; })); + localStorage.setItem("paperclip:inline-draft:v2:user-1:restored-callback", JSON.stringify({ version: 1, draft: "Restored title", base: "Original" })); + const root = createRoot(container); + try { + await act(async () => root.render(signedIn("user-1", ))); + expect(onEditingChange.mock.calls).toEqual([[true]]); + expect(container.querySelector("textarea")?.value).toBe("Restored title"); + act(() => root.unmount()); + expect(onEditingChange.mock.calls).toEqual([[true], [false]]); + await act(async () => resolve()); + expect(onEditingChange.mock.calls).toEqual([[true], [false]]); + } finally { localStorage.removeItem("paperclip:inline-draft:v2:user-1:restored-callback"); } + }); + + it("keeps one edit notification bound to the callback that opened it", async () => { + const opened = vi.fn(); + const next = vi.fn(); + const onSave = vi.fn(); + const root = createRoot(container); + try { + await act(async () => root.render()); + await act(async () => container.querySelector("span")!.click()); + await act(async () => root.render()); + expect(opened.mock.calls).toEqual([[true]]); + expect(next).not.toHaveBeenCalled(); + await act(async () => container.querySelector("textarea")!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }))); + expect(opened.mock.calls).toEqual([[true], [false]]); + expect(next).not.toHaveBeenCalled(); + } finally { act(() => root.unmount()); } + }); + it("calls onSave with empty string when nullable and the field is cleared (single-line)", () => { const onSave = vi.fn().mockResolvedValue(undefined); const root = createRoot(container); diff --git a/ui/src/components/InlineEditor.tsx b/ui/src/components/InlineEditor.tsx index bf55535ec4d..dce54904685 100644 --- a/ui/src/components/InlineEditor.tsx +++ b/ui/src/components/InlineEditor.tsx @@ -33,7 +33,7 @@ interface InlineEditorProps { * own affordance opens the editor (the description bubble's pencil, PAP-375). */ defaultEditing?: boolean; - /** Notified when the multiline editor swaps between display and edit mode. */ + /** Notified when the editor swaps between display and edit mode. */ onEditingChange?: (editing: boolean) => void; /** * Keep unsaved edits in browser storage under this key, so a reload or an @@ -91,6 +91,16 @@ function OwnedInlineEditor({ draftOwner, }: InlineEditorProps & { draftOwner: string | undefined }) { const [editing, setEditing] = useState(false); + const editingChangeCallback = useRef(onEditingChange); + editingChangeCallback.current = onEditingChange; + useEffect(() => { + if (multiline || !editing) return; + const notify = editingChangeCallback.current; + notify?.(true); + // Report only an edit that actually opened. This also retires the old + // account's edit on unmount, without a late save notifying its new owner. + return () => notify?.(false); + }, [editing, multiline]); const [multilineEditing, setMultilineEditing] = useState(multiline && defaultEditing); const [multilineFocused, setMultilineFocused] = useState(false); const [draft, setDraft] = useState(value); diff --git a/ui/src/components/new-agent/NewAgentSetup.tsx b/ui/src/components/new-agent/NewAgentSetup.tsx index 39a70f2ec02..e9c319587fb 100644 --- a/ui/src/components/new-agent/NewAgentSetup.tsx +++ b/ui/src/components/new-agent/NewAgentSetup.tsx @@ -78,6 +78,9 @@ import { import { adapterCuratesModelOrder } from "../../lib/model-utils"; const controlClass = nativeSelectClassName; +const nativeSetupHarnesses: Record = { + codex: "codex_local", claude: "claude_local", opencode: "opencode_local", pi: "pi_local", cursor_cloud: "cursor_cloud", +}; const blocking = (result: AdapterEnvironmentTestResult) => result.status === "fail" || result.checks.some((check) => check.code === ADAPTER_AUTH_MISSING_CHECK_CODE); @@ -98,9 +101,9 @@ export function NewAgentSetup() { key={`${selectedCompanyId}:${params.get("name")}:${params.get("adapterType")}:${params.get("runnerProvider") ?? "codex"}:${params.get("runner") ?? "auto"}`} companyId={selectedCompanyId} name={params.get("name") ?? ""} - adapterType={params.get("adapterType") === "paperclip_runner" && ["codex", "claude", "opencode", "pi"].includes(params.get("runnerProvider") ?? "codex") ? params.get("runnerProvider") === "claude" ? "claude_local" : params.get("runnerProvider") === "opencode" ? "opencode_local" : params.get("runnerProvider") === "pi" ? "pi_local" : "codex_local" : params.get("adapterType") ?? ""} - initialRunner={params.get("runner") ?? (params.get("adapterType") === "paperclip_runner" && ["codex", "claude", "opencode", "pi"].includes(params.get("runnerProvider") ?? "codex") ? "paperclip" : params.has("setupAgentId") && ["codex_local", "claude_local", "opencode_local", "pi_local"].includes(params.get("adapterType") ?? "") ? "legacy" : "auto")} - preserveNativeHarness={params.get("adapterType") === "paperclip_runner" && ["codex", "claude", "opencode", "pi"].includes(params.get("runnerProvider") ?? "codex")} + adapterType={params.get("adapterType") === "paperclip_runner" && Object.hasOwn(nativeSetupHarnesses, params.get("runnerProvider") ?? "codex") ? nativeSetupHarnesses[params.get("runnerProvider") ?? "codex"] : params.get("adapterType") ?? ""} + initialRunner={params.get("runner") ?? (params.get("adapterType") === "paperclip_runner" && Object.hasOwn(nativeSetupHarnesses, params.get("runnerProvider") ?? "codex") ? "paperclip" : params.has("setupAgentId") && ["codex_local", "claude_local", "opencode_local", "pi_local", "cursor_cloud"].includes(params.get("adapterType") ?? "") ? "legacy" : "auto")} + preserveNativeHarness={params.get("adapterType") === "paperclip_runner" && Object.hasOwn(nativeSetupHarnesses, params.get("runnerProvider") ?? "codex")} runnerProvider={params.get("runnerProvider") ?? "codex"} createdAgentId={params.get("createdAgentId")} setupAgentId={params.get("setupAgentId")} @@ -160,7 +163,8 @@ function Setup({ const chooseProvider = multiProvider || brandType === "hermes_local"; const hasCredentialField = isKimi || chooseProvider || Boolean(SETUP_CREDENTIAL_KEYS[adapterType]); - const showModel = !isDot && !["cursor_cloud", "hermes_gateway"].includes(adapterType); + const nativeCursorCloud = adapterType === "cursor_cloud" && runner === "paperclip"; + const showModel = !isDot && adapterType !== "hermes_gateway" && (adapterType !== "cursor_cloud" || nativeCursorCloud); const [allowUnmeteredProvider, setAllowUnmeteredProvider] = useState(false); const [gatewayUrl, setGatewayUrl] = useState(""); const [kimiModel, setKimiModel] = useState(""); @@ -295,12 +299,12 @@ function Setup({ const companySecrets = useQuery({ queryKey: queryKeys.secrets.list(companyId), queryFn: () => secretsApi.list(companyId), - enabled: hasCredentialField && adapterType !== "cursor_cloud", + enabled: hasCredentialField && (adapterType !== "cursor_cloud" || nativeCursorCloud), }); const userSecrets = useQuery({ queryKey: queryKeys.secrets.myUserSecrets(companyId), queryFn: () => secretsApi.listMyUserSecrets(companyId), - enabled: hasCredentialField && adapterType !== "cursor_cloud", + enabled: hasCredentialField && (adapterType !== "cursor_cloud" || nativeCursorCloud), retry: false, }); const forced = resolveForcedKubernetesEnvironment( @@ -390,7 +394,7 @@ function Setup({ ); const selectedBinding = adapterType === "cursor_cloud" - ? null + ? nativeCursorCloud ? providerBinding : null : (providerBinding ?? (savedOrganizationKey ? { @@ -409,6 +413,7 @@ function Setup({ adapterType === "kimi_local" && Boolean(apiKey.trim() || selectedBinding); const cloud = Boolean(useCloudInstance()); const available = + (!nativeCursorCloud || experimental.data?.enableNativeRunner === true) && isNewAgentAdapterAllowed(adapterType, { cloud, nativeRunnerEnabled: experimental.data?.enableNativeRunner === true, @@ -544,6 +549,7 @@ function Setup({ return config; } function preparedConfig(nextConnection = connection, setupRunner?: AgentRunner) { + if (nativeCursorCloud && !model.trim()) throw new Error("Enter the exact Cursor Cloud model ID."); if (isKimi && !model.trim()) throw new Error("Enter the exact Kimi model ID."); if (isKimi && !apiKey.trim() && !selectedBinding) throw new Error("Enter KIMI_API_KEY or select an organization secret."); if (brandType === "antigravity_runtime" && (!model.trim() || model !== model.trim() || /\s/.test(model) || ["auto", "default"].includes(model.toLowerCase()))) @@ -625,12 +631,12 @@ function Setup({ const agent = savedAgent.data; if (agent.pauseReason !== "setup") { setScreen("saved"); return; } const config = agent.adapterConfig; - if (multiProvider) setRunner(agent.adapterType === "paperclip_runner" ? "paperclip" : "legacy"); + if (multiProvider || adapterType === "cursor_cloud") setRunner(agent.adapterType === "paperclip_runner" ? "paperclip" : "legacy"); setModel(typeof config.model === "string" && config.model ? config.model : antigravityCandidate?.model ?? ""); setEffort(String(config.modelReasoningEffort ?? config.reasoningEffort ?? config.effort ?? config.thinkingEffort ?? config.piThinkingLevel ?? config.thinking ?? "")); setEnvironmentOverride(agent.defaultEnvironmentId ?? ""); setRepository(typeof config.repoUrl === "string" ? config.repoUrl : ""); - setBranch(typeof config.repoStartingRef === "string" ? config.repoStartingRef : ""); + setBranch(typeof config.repoRef === "string" ? config.repoRef : typeof config.repoStartingRef === "string" ? config.repoStartingRef : ""); setGatewayUrl(typeof config.apiBaseUrl === "string" ? config.apiBaseUrl : ""); setAllowUnmeteredProvider(config.allowUnmeteredProvider === true); const kimiApi = config.kimiApi as { model?: string; protocol?: string; baseUrl?: string } | undefined; @@ -740,7 +746,7 @@ function Setup({ agentId: created?.id, adapterType: requestAdapterType, providerAdapter: brandType, - ...(["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && (qualified || runner !== "auto") ? { runner: qualified?.runner ?? runner } : {}), + ...(["codex_local", "claude_local", "opencode_local", "pi_local", "cursor_cloud"].includes(adapterType) && (qualified || runner !== "auto") ? { runner: qualified?.runner ?? runner } : {}), adapterConfig: config, testCredentials: pendingCredentials(nextConnection), aiConnection: runtimeAiBinding ?? nextConnection?.aiConnection, @@ -797,7 +803,7 @@ function Setup({ role: created.role, reportsTo: created.reportsTo, adapterType: requestAdapterType, - ...(["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) && runner !== "auto" ? { runner } : {}), + ...(["codex_local", "claude_local", "opencode_local", "pi_local", "cursor_cloud"].includes(adapterType) && runner !== "auto" ? { runner } : {}), adapterConfig: config, defaultEnvironmentId: environmentOverride || @@ -1226,8 +1232,8 @@ function Setup({ }} open={modelOpen} onOpenChange={setModelOpen} - allowDefault={!isKimi && !multiProvider && !accountBoundCatalog} - required={isKimi || multiProvider || accountBoundCatalog} + allowDefault={!isKimi && !multiProvider && !accountBoundCatalog && !nativeCursorCloud} + required={isKimi || multiProvider || accountBoundCatalog || nativeCursorCloud} creatable={brandType !== "copilot_runtime"} groupByProvider={multiProvider && !connectionModels} preserveOrder={Boolean(connectionModels) || adapterCuratesModelOrder(brandType)} @@ -1339,7 +1345,7 @@ function Setup({ - {adapterType !== "cursor_cloud" && ( + {(adapterType !== "cursor_cloud" || nativeCursorCloud) && (
)} {adapterType === "cursor_cloud" && ( + <> + {nativeCursorCloud &&

Experimental. Requires a local Paperclip computer. Cursor manages cloud command permissions; the effective model is not acknowledged.

}
+ )} - {["codex_local", "claude_local", "opencode_local", "pi_local"].includes(adapterType) &&
+ {["codex_local", "claude_local", "opencode_local", "pi_local", "cursor_cloud"].includes(adapterType) &&
Advanced { void adapters.refetch(); }} @@ -1471,9 +1480,7 @@ function Setup({ onChange={value => { setRunner(value); resetTest(); }} />
} - {!["cursor_cloud", "hermes_gateway"].includes( - adapterType, - ) && ( + {adapterType !== "hermes_gateway" && (adapterType !== "cursor_cloud" || nativeCursorCloud) && (

Environment