From f49907f42cf122edd4f36782adeb52ff15d42814 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 29 Sep 2026 09:42:28 -0500 Subject: [PATCH 1/6] Isolate pinned Cursor ACP configuration and preserve typed failures Co-Authored-By: Paperclip --- .../runner-cursor-capabilities.md | 57 +++++++++++- .../cursor-distributions.json | 18 ++-- .../scripts/cursor-runtime-patch.mjs | 58 +++++++++++++ .../materialize-cursor-distribution.mjs | 9 +- .../materialize-cursor-distribution.test.mjs | 31 ++++++- .../scripts/qualify-cursor-runtime-patch.mjs | 86 +++++++++++++++++++ .../src/drivers/acpx/cursor-installation.ts | 6 +- .../runtime-patch-initialization.json | 29 +++++++ .../runtime-patch-offline-proof.json | 50 +++++++++++ 9 files changed, 327 insertions(+), 17 deletions(-) create mode 100644 packages/paperclip-runner/scripts/cursor-runtime-patch.mjs create mode 100644 packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs create mode 100644 packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json create mode 100644 packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json diff --git a/doc/architecture/runner-cursor-capabilities.md b/doc/architecture/runner-cursor-capabilities.md index d08fa048837..cbaadb2e709 100644 --- a/doc/architecture/runner-cursor-capabilities.md +++ b/doc/architecture/runner-cursor-capabilities.md @@ -1,6 +1,6 @@ # Cursor ACP capability inventory -Evidence date: 2026-09-28. Candidate: `2026.09.26-dd393fe`. This profile is **not live-qualified**. One authorized task-context prompt on the initial free account returned an upgrade requirement, invoked no semantic tools, and supplied no usage receipt. Its cost is unknown; the account dashboard remained unchanged at coarse precision. The user then selected another account, whose exact-model local Runner Eval passed task-context and history tools with clean terminal settlement. Its dashboard attributed 56K rounded tokens to included usage and no incremental charge; ACP still supplied no token or dollar receipt. The local Product hello subsequently passed through the real browser, server, database, native runner, and authenticated completion tool. A second local Product case passed file creation, editing, command validation, an independent exact-byte matcher, and visible workspace artifact presentation. The merged-source local Product question and revision-bound Plan approval also passed browser response and semantic-tool continuation. A serialized follow-up passed pending semantic-question recovery across a server restart. A verified native ACP probe also denied a shell write before any observed side effect. Native Cursor questions/plans and their recovery, durable permission presentation, interruption, and Daytona execution remain required qualification gates. +Evidence updated: 2026-09-29. Candidate: `2026.09.26-dd393fe`. This profile is **not live-qualified**. One authorized task-context prompt on the initial free account returned an upgrade requirement, invoked no semantic tools, and supplied no usage receipt. Its cost is unknown; the account dashboard remained unchanged at coarse precision. The user then selected another account, whose exact-model local Runner Eval passed task-context and history tools with clean terminal settlement. Its dashboard attributed 56K rounded tokens to included usage and no incremental charge; ACP still supplied no token or dollar receipt. The local Product hello subsequently passed through the real browser, server, database, native runner, and authenticated completion tool. A second local Product case passed file creation, editing, command validation, an independent exact-byte matcher, and visible workspace artifact presentation. The merged-source local Product question and revision-bound Plan approval also passed browser response and semantic-tool continuation. A serialized follow-up passed pending semantic-question recovery across a server restart. A verified native ACP probe also denied a shell write before any observed side effect. Native Cursor questions/plans and their recovery, durable permission presentation, interruption, and Daytona execution remain required qualification gates. The reference is the runner's Codex app-server integration and its closed thread-item inventory in `src/provider-events.ts`. Cursor ACP and its private extension methods are the transport; the legacy Cursor adapter is unchanged. @@ -41,7 +41,7 @@ The reference is the runner's Codex app-server integration and its closed thread | Available commands | `available_commands_update`, including skills/slash commands | ACPX persists command metadata; runner canonical mapper deliberately emits no display event | Command picker and bounded command-discovery surface are not implemented | | Session metadata | `session_info_update` title after automatic naming | Capability documented | Runner owns normalized session identity; provider title is currently not surfaced | | Prompt media | Image=true, audio=false, embeddedContext=false in observed initialize | The shared runner turn contract accepts text only; it does not forward image attachment blocks to ACP | P1: implement bounded, validated attachment-to-ACP conversion with capability checks, then qualify the exact model. Audio/embedded context are explicitly unsupported by this advertisement | -| MCP and semantic tools | Session MCP injection supports stdio/HTTP/SSE; user/project config also loaded | Runner-owned authenticated MCP bridge only; fail closed on ambient project MCP | Exact tool discovery and company/token boundary remain live tests | +| MCP and semantic tools | Session MCP injection supports stdio/HTTP/SSE; user/project config also loaded | Runner-owned authenticated MCP bridge only; the owned distribution patch never initializes ambient MCP | Exact tool discovery and company/token boundary remain live tests | | Usage/cost | No `usage_update`/token-usage emission found in pinned ACP implementation; prompt result contains stopReason | Must report usage unavailable, never zero or estimates presented as actual | Dollar accounting unavailable without another explicit measured source. Live spend needs a measurable bound before starting | | Reviews, compaction, hooks, memory | Native mode changes, hooks present internally; no dedicated ACP counterparts to Codex context/hook/memory lifecycle found | No fabricated event families | Distinguish confirmed absence of ACP event mapping from unverified native internals | | Goal controls / lineage | No ACP goal or fork lineage protocol found | Unsupported | No equivalent of Codex native goals/thread lineage | @@ -54,7 +54,7 @@ Question and plan requests lack a session ID. The shared hook binds them to the Fixed launch arguments are `--disable-project-configs --disable-auto-update acp`, using the verified bundled Node and absolute verified `index.js`. Private HOME/XDG roots are required together with CURSOR_CONFIG_DIR, CURSOR_DATA_DIR, disabled compilation caching, `AGENT_CLI_CREDENTIAL_STORE=memory`, and `NO_OPEN_BROWSER=1`. Only explicitly bound CURSOR_API_KEY or CURSOR_AUTH_TOKEN may enter. The controller creates a provider/session-scoped credential-name binding from the explicit task environment, ignoring inherited or caller-supplied markers. Rust forwards it through the closed sidecar environment boundary. Before host admission, the sidecar rejects missing, stale, wrong-provider or unbound credentials and removes the marker before provider launch. Tests cover this full boundary and preserve legacy credential behavior. Do not use `--force`, `--trust`, or `--approve-mcps` to paper over governance. -`--disable-project-configs` only suppresses `.cursor/cli.json`. It does not suppress project MCP, Cursor/Claude hooks, or installed plugins. `assertCursorWorkspacePolicy` refuses ambient project execution config from the workspace through its nearest Git root, including symlinks and unreadable configuration. Ordinary Claude settings with neither hooks nor plugins remain admissible. Enterprise system hooks are checked too. The host repeats admission checks before native launch. Continuous protection of these config paths during execution remains a qualification requirement. Admission alone cannot prevent a concurrent file mutation. Team-provided remote hooks are another upstream boundary and remain unqualified under restrictive execution. +`--disable-project-configs` only suppresses `.cursor/cli.json`. It does not suppress project MCP, Cursor/Claude hooks, or installed plugins. `assertCursorWorkspacePolicy` refuses ambient project execution config from the workspace through its nearest Git root, including symlinks and unreadable configuration. Ordinary Claude settings with neither hooks nor plugins remain admissible. Enterprise system hooks are checked too. The host repeats admission checks before native launch. The vendor admission check alone cannot prevent a concurrent file mutation. The `paperclip-cursor-isolation-v1` distribution patch now removes local hook loading, asynchronous team hook synchronization, ambient MCP loader initialization, and ambient-client merging from the ACP source. The retained admission check remains defense in depth. This closes those discovery paths independently of filesystem polling; authenticated validation on the patched final runtime remains required. Artifact paths are never automatically read or uploaded. References require a present regular file under the physical workspace, reject traversal and symbolic links, and retain `registered:false`. Private/outside paths are omitted and produce a visible warning. This is metadata validation, not durable file ownership or a replacement for artifact registration checks. @@ -116,7 +116,7 @@ Credential setup uses [Cursor's documented browser login](https://cursor.com/doc `test/fixtures/cursor-acp/authenticated-qualification-attempts.json` retains sanitized per-attempt source, package, daemon, model, timing, cleanup, and cost evidence. The first canonical `get-task-context` attempt used pack source `e5159fb67ad28bf6a691bfa64ffddb332d96f8be`, exact Luna selection, one turn, a 60-second limit, a $0.50 declared envelope inside a $2 reservation, and zero retries. This is a Runner Eval against the mock control plane, not Product E2E or restrictive-permission qualification. -The provider returned only an upgrade requirement and then normal completion. Source inspection of pinned `5672.index.js` confirms that actionable authentication/entitlement errors are rendered as ordinary assistant text and lose their typed failure before ACP settlement. No text-matching terminal heuristic is used. This is a P1 native-wrapper gap: preserve typed errors upstream or through a verified owned hook. The semantic oracle must still fail a response that did not invoke the required tool. +The provider returned only an upgrade requirement and then normal completion. Source inspection of pinned `5672.index.js` confirms that actionable authentication/entitlement errors are rendered as ordinary assistant text and lose their typed failure before ACP settlement. No text-matching terminal heuristic is used. This was a native-wrapper gap in that unmodified candidate. The owned distribution patch described below preserves those typed errors as failed ACP RPC responses; the historical attempt is unchanged. The semantic oracle must still fail a response that did not invoke the required tool. The replacement-account attempt passed all four canonical `get-task-context` checks at source `01959b8a602683f13706807983f02c3cba9d36a0`, using newly rebuilt daemon source `f77ae83aeb6d802c73f1c955760017ae272eba29`. Both `get_task_context` and `get_task_history` returned successful authenticated semantic results. It took 29.291 seconds and exited cleanly. The Usage page showed a new `gpt-5.6-luna-medium` row at 19:28:55 UTC with 56K tokens, marked Included. Incremental cash was zero for that row; metered dollars remain unavailable. A conservative $0.07 list-price bound assumes at most 57K rounded tokens at the maximum listed $1.20/M rate and is not an invoice amount. There was no retry. @@ -162,3 +162,52 @@ This source audit follows pinned native update → ACPX runtime → `canonicalPr | Session list, model parameters, generic mode control | Confirmed native ACP methods | No operator UI or cross-session discovery API in this integration; recovery loads only the runner-owned exact session | P2: explicit company-scoped controls; authenticated model catalog first | True steering, native queueing, fork/resume, native usage receipts and interactive child questions are absent from this pinned ACP implementation as described above. Their absence is distinct from the implemented-but-unused fields in this table. Remote team hooks, provider-native artifact traces, interruption settlement and authenticated Linux/Daytona behavior remain unverified, not confirmed absent. + +## Owned runtime patch (2026-09-29) + +The candidate now materializes `paperclip-cursor-isolation-v1` on top of the +unchanged vendor `2026.09.26-dd393fe` archives. The materializer first verifies +the archive and **vendor** execution closure, requires exact single-occurrence +source anchors in an input-digest-pinned ACP chunk, applies the owned patch, +then verifies a separately pinned **patched** execution closure. Both identities +remain in the distribution manifest. Unknown, changed, already-patched, or +ambiguously matched source fails closed. The patch does not change the legacy +Cursor adapter or the vendor interactive CLI. + +The ACP shared-services initializer no longer initializes or loads its ambient +MCP loader. Each ACP session starts with an empty client lease and adds only the +explicit session MCP definitions, preserving native last-definition-wins behavior. +It never borrows an earlier or ambient lease, including when the session MCP list +is empty or invalid. Local hook config is an empty snapshot, and the remote team +hook fetch/install/update path cannot start. Newly created project config during +a session therefore cannot enter either removed discovery path. This is source +isolation, not an operating-system sandbox: explicitly allowed native shell +commands still have their granted filesystem/network powers. + +Typed `ActionRequiredError` instances now produce a failed JSON-RPC response +with data schema `paperclip.cursor.provider-error.v1`, kind `action_required`, +and the closed action enum `login`, `upgrade`, `payment`, `config`, or `unknown`. +Login and native `ConnectError` with the Unauthenticated code use ACP error +`-32000`; other action requirements use `-32603`. Provider-private error detail +is not copied into these responses. Ordinary assistant text is never examined to +infer an entitlement failure. Generic provider exceptions outside these typed +branches retain the vendor behavior and remain an upstream audit item. + +`qualify-cursor-runtime-patch.mjs` executes expressions extracted from each actual +input-digest-verified platform chunk. Its poisoned ambient loaders prove no +ambient access while owned MCP, empty sessions, and duplicate definitions work; +it also executes all typed error branches and ignores entitlement-shaped ordinary +errors. The entire patched chunks compile for macOS ARM64/x64 and Linux x64. +`runtime-patch-offline-proof.json` records these checks with zero provider calls. +All three authentic archives separately passed materialization and post-patch +closure verification. Seven materializer tests cover drift, ambiguous anchors, +closure tampering, links, archive tampering, identity consistency, and overwrites. +Both patched macOS binaries also returned ACP v1 from credential-free real-process +initialization and exited after explicit SIGTERM; x64 ran through the ARM host +compatibility layer. `runtime-patch-initialization.json` retains this distinction. +These are offline checks, not authenticated macOS x64 or Linux/Daytona qualification. + +Prior Product/Runner results above measured the earlier unpatched runtime. The +profile must retain pending qualification until the rebuilt final foundation +runtime passes the remaining native interaction, durable approval, cancellation, +recovery, accounting, and authenticated target-platform gates. diff --git a/packages/paperclip-runner/cursor-distributions.json b/packages/paperclip-runner/cursor-distributions.json index 5aee5d15fcd..64280bbb777 100644 --- a/packages/paperclip-runner/cursor-distributions.json +++ b/packages/paperclip-runner/cursor-distributions.json @@ -5,23 +5,27 @@ "darwin-arm64": { "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/darwin/arm64/agent-cli-package.tar.gz", "archiveSha256": "538827d96a779bab854a865c8e42859e8e87db34b5f69770261b90fc8cfff191", - "closureSha256": "77394184a89b0e7384971181da19c3c82d83a399b04e7944b3f94fe3d7e62b25", + "closureSha256": "89e28235685ab31d78779eccd5b6a7b2d9fec20181c439535f2fe492c5cd24da", "executable": "node", - "entrypoint": "index.js" + "entrypoint": "index.js", + "vendorClosureSha256": "77394184a89b0e7384971181da19c3c82d83a399b04e7944b3f94fe3d7e62b25" }, "darwin-x64": { "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/darwin/x64/agent-cli-package.tar.gz", "archiveSha256": "ed1771c44cbf0f8059c67cac0d939e6a60eb730bd066d7dc4cbb14de314cfb6e", - "closureSha256": "7c8775160af74e5fb8d25a30e8412c1a6476b0661529078a686e5118fd1c5e5f", + "closureSha256": "6729c65acb6b2f56690ebe54e63659f4dc31b2b5814aff8d59740767ab43ad17", "executable": "node", - "entrypoint": "index.js" + "entrypoint": "index.js", + "vendorClosureSha256": "7c8775160af74e5fb8d25a30e8412c1a6476b0661529078a686e5118fd1c5e5f" }, "linux-x64": { "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/linux/x64/agent-cli-package.tar.gz", "archiveSha256": "8085fd120f5c71f4eae7fea26a043718e5644e3071e4fab3220a0e58c51f9593", - "closureSha256": "bf04ef8ea6a63191067a6b3e15139aa2c793d8419daab246aa3f0a012e1bbcd9", + "closureSha256": "591623da24add49fc6572e6eba3039e21b40893024efc65fc547802e00cfec17", "executable": "node", - "entrypoint": "index.js" + "entrypoint": "index.js", + "vendorClosureSha256": "bf04ef8ea6a63191067a6b3e15139aa2c793d8419daab246aa3f0a012e1bbcd9" } - } + }, + "patchVersion": "paperclip-cursor-isolation-v1" } diff --git a/packages/paperclip-runner/scripts/cursor-runtime-patch.mjs b/packages/paperclip-runner/scripts/cursor-runtime-patch.mjs new file mode 100644 index 00000000000..439529e9ba5 --- /dev/null +++ b/packages/paperclip-runner/scripts/cursor-runtime-patch.mjs @@ -0,0 +1,58 @@ +import { createHash } from "node:crypto"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +// This is an owned ACP-only patch of the immutable vendor archive. The legacy +// Cursor adapter and the vendor's interactive CLI are not changed. +export const CURSOR_RUNTIME_PATCH_VERSION = "paperclip-cursor-isolation-v1"; +export const CURSOR_RUNTIME_PATCH_PINS = Object.freeze({ + "darwin-arm64": { file: "5672.index.js", before: "7784c8b16d4e639814c13b12be2a687f5dc2cd98cbf29ed0a10820778ab1bf62", after: "db997911906014ec9c522b48b6748bb39001e44d9a10730a433ab1e135aa0432" }, + "darwin-x64": { file: "9841.index.js", before: "3c0aaf6ecc4fceb0f95e1731deec75384984570d14d0871cecec11972b948ac4", after: "713aecb34c994d83ce46942f6b15bff173eb7b605f15a4653b24b9cc46dd3b5a" }, + "linux-x64": { file: "1699.index.js", before: "2de420f1b31e70ca74b083a1ce5b519c2abffa5789d71cc06e84d2c38acb7c07", after: "27e6e048b30afbf722c36cc3ef8ac4350957963291d15c34fdaea355d110ea2a" }, +}); +const digest = value => createHash("sha256").update(value).digest("hex"); + +export function replaceCursorPatchAnchor(source, before, after) { + if (source.split(before).length !== 2) throw new Error("Cursor runtime patch requires exactly one source anchor"); + return source.replace(before, () => after); +} + +/** Never exported as a general-purpose runtime hook; bytes are checked first. */ +export function patchCursorRuntimeSource(source, platform) { + const pin = CURSOR_RUNTIME_PATCH_PINS[platform]; + if (!pin || digest(source) !== pin.before) throw new Error("Cursor runtime patch input digest mismatch"); + const replace = (before, after) => { source = replaceCursorPatchAnchor(source, before, after); }; + // Do not even initialize the ambient loader: load() can start subprocesses. + replace(`te=r.aK.init(X,W.projectRoot,W.projectDir,!1,ee,new ${platform === "darwin-x64" ? "m" : "f"}.v)`, "te=null"); + replace("se=yield te.load(e),ie=new u.uz(se)", "se=new u.i9({}),ie=new u.uz(se)"); + // Session-scoped owned MCP stays functional, including an explicitly empty + // list. It never borrows clients from an earlier session or ambient lease. + const sessionMcp = platform === "darwin-arm64" ? "A" : "x"; + replace("if(0===i.length)return t.mcpLease;", `if(0===i.length)return new ${sessionMcp}.uz(new ${sessionMcp}.i9({}));`); + replace("if(0===r.length)return t.mcpLease;", `if(0===r.length)return new ${sessionMcp}.uz(new ${sessionMcp}.i9({}));`); + replace("u=Object.assign({},yield t.mcpLease.getClients(e))", "u=Object.create(null)"); + // Stop hook discovery at the source, including the asynchronous remote team + // refresh. A filesystem watcher would leave an execution race here. + replace("null!=re&&n.dashboardClient&&(ae=(0,y.a)({dashboardClient:n.dashboardClient,teamId:re}));", "void re;"); + replace("let ue=yield ce.load();", "let ue={errors:[],configDirs:{}};"); + // Use the exact SDK module already present in this verified vendor chunk. + const sdk = [...source.matchAll(/n\("([^"\n]+@agentclientprotocol\/sdk\/dist\/acp\.js)"\)/g)].map(match => match[1]); + if (new Set(sdk).size !== 1) throw new Error("Cursor runtime patch SDK identity is ambiguous"); + const errorType = `n(${JSON.stringify(sdk[0])}).GI`; + const oldAction = 'if(e instanceof r.ao){const t=null!==(u={login:"Please sign in to continue",upgrade:"Upgrade your plan to continue",payment:"Add a payment method to continue",config:"Check your settings to continue"}[e.action])&&void 0!==u?u:e.message;return void(yield this.sendAgentMessageChunk(`\\n\\n${t}`))}'; + const newAction = `if(e instanceof r.ao){const action=["login","upgrade","payment","config"].includes(e.action)?e.action:"unknown";throw new (${errorType})(action==="login"?-32000:-32603,"Cursor provider action required: "+action,{schema:"paperclip.cursor.provider-error.v1",kind:"action_required",action})}`; + replace(oldAction, newAction); + replace('if(e instanceof g.T&&e.code===m.C.Unauthenticated)return void(yield this.sendAgentMessageChunk("\\n\\nError: [unauthenticated] Backend rejected authentication. Verify this is a User API Key for the same endpoint/environment, then rerun with --debug for request-level auth logs."));'.replace('m.C.Unauthenticated', `${platform === "darwin-x64" ? "f" : "m"}.C.Unauthenticated`), + `if(e instanceof g.T&&e.code===${platform === "darwin-x64" ? "f" : "m"}.C.Unauthenticated)throw new (${errorType})(-32000,"Cursor provider authentication rejected",{schema:"paperclip.cursor.provider-error.v1",kind:"authentication_required"});`); + return source; +} + +export async function applyCursorRuntimePatch(directory, platform) { + const pin = CURSOR_RUNTIME_PATCH_PINS[platform]; + if (!pin) throw new Error("Cursor runtime patch platform is unsupported"); + const path = join(directory, pin.file); + const patched = patchCursorRuntimeSource(await readFile(path, "utf8"), platform); + if (digest(patched) !== pin.after) throw new Error("Cursor runtime patch output digest mismatch"); + await writeFile(path, patched); + return { patchVersion: CURSOR_RUNTIME_PATCH_VERSION, file: pin.file, sha256: pin.after }; +} diff --git a/packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs b/packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs index ef961305545..c34d99499a7 100644 --- a/packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs +++ b/packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs @@ -4,6 +4,8 @@ import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, writeFile import { dirname, join, resolve, sep } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; +import { applyCursorRuntimePatch, CURSOR_RUNTIME_PATCH_VERSION } from "./cursor-runtime-patch.mjs"; + const MANIFEST_PATH = fileURLToPath(new URL("../cursor-distributions.json", import.meta.url)); const MAX_ARCHIVE_BYTES = 256 * 1024 * 1024; const MAX_TREE_BYTES = 1024 * 1024 * 1024; @@ -14,7 +16,8 @@ export async function cursorDistribution(platform = process.platform, architectu const manifest = JSON.parse(await readFile(MANIFEST_PATH, "utf8")); const distribution = manifest.platforms[`${platform}-${architecture}`]; if (!distribution) throw new Error(`Cursor has no pinned distribution for ${platform}/${architecture}`); - return { ...distribution, version: manifest.version, platform, architecture }; + if (manifest.patchVersion !== CURSOR_RUNTIME_PATCH_VERSION || !/^[a-f0-9]{64}$/.test(distribution.vendorClosureSha256)) throw new Error("Cursor distribution must pin its owned runtime patch and vendor closure"); + return { ...distribution, version: manifest.version, patchVersion: manifest.patchVersion, platform, architecture }; } /** Hash every runtime file, including bundled Node, native addons and workers. */ @@ -102,6 +105,8 @@ export async function materializePinnedCursorDistribution(options = {}) { const extraction = spawnSync("/usr/bin/tar", ["-xzf", archivePath, "-C", unpacked, "--no-same-owner"], { encoding: "utf8", timeout: 120_000 }); if (extraction.status !== 0) throw new Error("Cursor archive extraction failed"); const packageRoot = join(unpacked, "dist-package"); + await verifyCursorDistribution(packageRoot, { ...distribution, closureSha256: distribution.vendorClosureSha256 }); + await applyCursorRuntimePatch(packageRoot, `${distribution.platform}-${distribution.architecture}`); const closure = await verifyCursorDistribution(packageRoot, distribution); // Record the pinned inventory for a later runtime lease. Its digest must be // checked against the checked-in distribution pin before trusting entries. @@ -109,7 +114,7 @@ export async function materializePinnedCursorDistribution(options = {}) { for (const entry of closure.entries) await chmod(join(packageRoot, ...entry.path.split("/")), entry.executable ? 0o500 : 0o400); await chmod(packageRoot, 0o700); await rename(packageRoot, destination); - return { version: distribution.version, platform: distribution.platform, architecture: distribution.architecture, destination, executable: join(destination, distribution.executable), entrypoint: join(destination, distribution.entrypoint), archiveSha256: distribution.archiveSha256, closureSha256: closure.sha256 }; + return { version: distribution.version, patchVersion: distribution.patchVersion, platform: distribution.platform, architecture: distribution.architecture, destination, executable: join(destination, distribution.executable), entrypoint: join(destination, distribution.entrypoint), archiveSha256: distribution.archiveSha256, closureSha256: closure.sha256 }; } finally { await rm(temporary, { recursive: true, force: true }); } } diff --git a/packages/paperclip-runner/scripts/materialize-cursor-distribution.test.mjs b/packages/paperclip-runner/scripts/materialize-cursor-distribution.test.mjs index 14b45bf10a9..529f3c43f65 100644 --- a/packages/paperclip-runner/scripts/materialize-cursor-distribution.test.mjs +++ b/packages/paperclip-runner/scripts/materialize-cursor-distribution.test.mjs @@ -1,10 +1,12 @@ import assert from "node:assert/strict"; -import { mkdtemp, mkdir, rm, symlink, writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, test } from "node:test"; import { cursorDistribution, cursorDistributionClosure, materializePinnedCursorDistribution, verifyCursorDistribution } from "./materialize-cursor-distribution.mjs"; +import { CURSOR_RUNTIME_PATCH_VERSION, CURSOR_RUNTIME_PATCH_PINS, patchCursorRuntimeSource, replaceCursorPatchAnchor } from "./cursor-runtime-patch.mjs"; + const roots = []; afterEach(async () => { await Promise.all(roots.splice(0).map(path => rm(path, { recursive: true, force: true }))); }); async function fixture() { const path = await mkdtemp(join(tmpdir(), "cursor-distribution-test-")); roots.push(path); return path; } @@ -15,6 +17,9 @@ test("pins complete archives and closures for every supported platform", async ( assert.equal(distribution.version, "2026.09.26-dd393fe"); assert.match(distribution.archiveSha256, /^[a-f0-9]{64}$/); assert.match(distribution.closureSha256, /^[a-f0-9]{64}$/); + assert.match(distribution.vendorClosureSha256, /^[a-f0-9]{64}$/); + assert.notEqual(distribution.closureSha256, distribution.vendorClosureSha256); + assert.equal(distribution.patchVersion, CURSOR_RUNTIME_PATCH_VERSION); assert.equal(distribution.url, `https://downloads.cursor.com/lab/${distribution.version}/${platform}/${architecture}/agent-cli-package.tar.gz`); } await assert.rejects(cursorDistribution("linux", "arm64"), /no pinned distribution/); @@ -52,3 +57,27 @@ test("refuses to overwrite any existing destination", async () => { const root = await fixture(); await writeFile(join(root, "existing"), "keep"); await assert.rejects(materializePinnedCursorDistribution({ destination: join(root, "existing") }), /already exists/); }); + + +test("the isolation patch refuses unsupported, drifted, missing or repeated vendor bytes", () => { + assert.throws(() => patchCursorRuntimeSource("not vendor bytes", "darwin-arm64"), /input digest mismatch/); + assert.throws(() => patchCursorRuntimeSource("not vendor bytes", "linux-arm64"), /input digest mismatch/); + assert.throws(() => replaceCursorPatchAnchor("absent", "anchor", "replacement"), /exactly one/); + assert.throws(() => replaceCursorPatchAnchor("anchor anchor", "anchor", "replacement"), /exactly one/); + assert.equal(replaceCursorPatchAnchor("before anchor after", "anchor", "$&"), "before $& after"); +}); + +test("retained executable vendor proof matches every checked-in patch identity", async () => { + const proof = JSON.parse(await readFile(new URL("../test/fixtures/cursor-acp/runtime-patch-offline-proof.json", import.meta.url), "utf8")); + assert.equal(proof.patchVersion, CURSOR_RUNTIME_PATCH_VERSION); + assert.equal(proof.providerCalls, 0); + assert.equal(proof.qualification, "offline-only"); + assert.deepEqual(proof.platforms.map(row => row.platform).sort(), Object.keys(CURSOR_RUNTIME_PATCH_PINS).sort()); + for (const row of proof.platforms) { + const pin = CURSOR_RUNTIME_PATCH_PINS[row.platform]; + assert.equal(row.sourceSha256, pin.before); + assert.equal(row.patchedSha256, pin.after); + for (const field of ["driftRejected", "fullChunkCompiles", "ownedMcpPreserved", "typedActionErrors", "assistantProseIgnored"]) assert.equal(row[field], true); + for (const field of ["ambientMcpAccesses", "hookConfigReads", "remoteTeamHookFetches"]) assert.equal(row[field], 0); + } +}); diff --git a/packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs b/packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs new file mode 100644 index 00000000000..8cda60b5e9c --- /dev/null +++ b/packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs @@ -0,0 +1,86 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { readFile } from "node:fs/promises"; +import { join } from "node:path"; +import { runInNewContext } from "node:vm"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { CURSOR_RUNTIME_PATCH_PINS, CURSOR_RUNTIME_PATCH_VERSION, patchCursorRuntimeSource } from "./cursor-runtime-patch.mjs"; + +const runGenerator = (_self, _args, _promise, fn) => (async () => { + const generator = fn(); let value; + while (true) { const next = generator.next(value); if (next.done) return next.value; value = await next.value; } +})(); +const trap = () => { throw new Error("Ambient configuration was accessed"); }; +function segment(source, start, end) { + const first = source.indexOf(start); assert.ok(first >= 0, `Missing ${start}`); + const last = source.indexOf(end, first); assert.ok(last > first, `Missing ${end}`); + return source.slice(first, last); +} + +/** Executes relevant expressions from the actual digest-verified vendor chunk. + * This is offline proof of the patch, not provider/tool availability evidence. */ +export async function qualifyCursorRuntimePatch(vendorRoot) { + const platforms = []; + for (const [platform, pin] of Object.entries(CURSOR_RUNTIME_PATCH_PINS)) { + const original = await readFile(join(vendorRoot, platform, "dist-package", pin.file), "utf8"); + const source = patchCursorRuntimeSource(original, platform); + assert.equal(createHash("sha256").update(source).digest("hex"), pin.after); + assert.throws(() => patchCursorRuntimeSource(original + "\n", platform), /digest mismatch/); + assert.throws(() => patchCursorRuntimeSource(source, platform), /digest mismatch/); + // Compiling the entire chunk catches minifier/scope syntax errors on every + // platform without loading native code or executing provider entrypoints. + const exported = {}; + runInNewContext(source, { exports: exported }); + assert.ok(exported.modules["./src/acp/shared-services.ts"]); + const Lease = class { constructor(value) { this.value = value; } }; + // Both formerly ambient expressions are evaluated with poisoned loaders. + const loader = segment(source, "te=null", ",ne="); + assert.equal(runInNewContext(`let ${loader};te`, { r: { aK: { init: trap } } }), null); + const empty = segment(source, "se=new u.i9({})", ",re=[]"); + assert.ok(runInNewContext(`let ${empty};ie`, { u: { i9: Lease, uz: Lease }, te: { load: trap } }) instanceof Lease); + // Execute the complete pinned session MCP merge function. Any access to the + // ambient lease fails, while owned injection and duplicate semantics survive. + const mcpSource = segment(source, "ee=yield function(e,t,n,o)", "}(e,n,").slice("ee=yield ".length) + "}"; + const make = runInNewContext(`(${mcpSource})`, { + j: runGenerator, R: runGenerator, A: { uz: Lease, i9: Lease, debugLog() {} }, + F: value => value.valid === false ? null : { serverName: value.name, config: value.config }, + x: { debugLog() {}, uz: Lease, i9: Lease }, N: name => `owned:${name}`, + $: async ({ serverName, serverConfig }) => ({ serverName, serverConfig }), + }); + const ambient = { get mcpLease() { return trap(); } }; + assert.deepEqual(Object.keys((await make({}, ambient, { mcpServers: [] }, "/workspace")).value.value), []); + assert.deepEqual(Object.keys((await make({}, ambient, { mcpServers: [{ valid: false }] }, "/workspace")).value.value), []); + const owned = (await make({}, ambient, { mcpServers: [{ name: "paperclip", config: "old" }, { name: "paperclip", config: "owned" }] }, "/workspace")).value.value; + assert.equal(owned.paperclip.serverConfig, "owned"); + assert.deepEqual(Object.keys(owned), ["paperclip"]); + // The remote team fetch and local config read are never evaluated, even + // after a caller mutates their simulated config during this active session. + const localHooks = segment(source, "let ue={errors:[],configDirs:{}};", "const he="); + for (let mutation = 0; mutation < 2; mutation++) { + const hooks = runInNewContext(`${localHooks}ue`, { ce: { load: trap } }); + assert.deepEqual(Object.keys(hooks), ["errors", "configDirs"]); + } + assert.ok(!source.includes("ae=(0,y.a)({dashboardClient:n.dashboardClient,teamId:re})")); + // Exercise typed native errors; ordinary assistant prose is never inspected. + const actionStart = "if(e instanceof r.ao)"; + const errors = segment(source, actionStart, "yield this.sendAgentMessageChunk(`\\n\\nError:"); + class ActionRequired extends Error { constructor(action) { super("private provider detail"); this.action = action; } } + class ConnectError extends Error { constructor() { super("private auth detail"); this.code = 16; } } + class ResponseError extends Error { constructor(code, message, data) { super(message); this.code = code; this.data = data; } } + const evaluate = error => runInNewContext(`(function(){${errors}})()`, { e: error, r: { ao: ActionRequired }, g: { T: ConnectError }, m: { C: { Unauthenticated: 16 } }, f: { C: { Unauthenticated: 16 } }, n: () => ({ GI: ResponseError }) }); + for (const action of ["login", "upgrade", "payment", "config", "other"]) { + assert.throws(() => evaluate(new ActionRequired(action)), error => error instanceof ResponseError + && error.code === (action === "login" ? -32000 : -32603) + && error.data.action === (action === "other" ? "unknown" : action) + && !error.message.includes("private")); + } + assert.throws(() => evaluate(new ConnectError()), error => error.code === -32000 && error.data.kind === "authentication_required"); + evaluate(new Error("Upgrade your plan to continue")); + platforms.push({ platform, file: pin.file, sourceSha256: pin.before, patchedSha256: pin.after, driftRejected: true, fullChunkCompiles: true, ambientMcpAccesses: 0, ownedMcpPreserved: true, hookConfigReads: 0, remoteTeamHookFetches: 0, typedActionErrors: true, assistantProseIgnored: true }); + } + return { schema: "paperclip.cursor.runtime-patch-proof.v1", patchVersion: CURSOR_RUNTIME_PATCH_VERSION, providerCalls: 0, qualification: "offline-only", platforms }; +} +if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) { + assert.equal(process.argv.length, 3, `Usage: node ${fileURLToPath(import.meta.url)} `); + console.log(JSON.stringify(await qualifyCursorRuntimePatch(process.argv[2]), null, 2)); +} diff --git a/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts b/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts index edda80afbbc..3924e814416 100644 --- a/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts @@ -8,9 +8,9 @@ import { resolveRunnerProviderAssetsRoot } from "./provider-assets-root.js"; export const CURSOR_PINNED_VERSION = "2026.09.26-dd393fe"; const CLOSURE_PINS = Object.freeze({ - "darwin-arm64": "77394184a89b0e7384971181da19c3c82d83a399b04e7944b3f94fe3d7e62b25", - "darwin-x64": "7c8775160af74e5fb8d25a30e8412c1a6476b0661529078a686e5118fd1c5e5f", - "linux-x64": "bf04ef8ea6a63191067a6b3e15139aa2c793d8419daab246aa3f0a012e1bbcd9", + "darwin-arm64": "89e28235685ab31d78779eccd5b6a7b2d9fec20181c439535f2fe492c5cd24da", + "darwin-x64": "6729c65acb6b2f56690ebe54e63659f4dc31b2b5814aff8d59740767ab43ad17", + "linux-x64": "591623da24add49fc6572e6eba3039e21b40893024efc65fc547802e00cfec17", }); /** Trusted package assets only: no workspace, PATH, executable override or env root. */ diff --git a/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json new file mode 100644 index 00000000000..bd751db3ce7 --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json @@ -0,0 +1,29 @@ +{ + "schema": "paperclip.cursor.patch-initialize-proof.v1", + "observedAt": "2026-09-29", + "patchVersion": "paperclip-cursor-isolation-v1", + "hostPlatform": "darwin-arm64", + "providerCalls": 0, + "authenticated": false, + "scope": "Direct patched vendor process initialization only; not a rebuilt Runner pack qualification. macOS x64 used host compatibility execution. Processes received SIGTERM after initialization.", + "results": [ + { + "platform": "darwin-arm64", + "providerCalls": 0, + "initialize": "passed", + "protocolVersion": 1, + "exitCode": 143, + "signal": null, + "error": "" + }, + { + "platform": "darwin-x64", + "providerCalls": 0, + "initialize": "passed", + "protocolVersion": 1, + "exitCode": 143, + "signal": null, + "error": "" + } + ] +} diff --git a/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json new file mode 100644 index 00000000000..d6fc6bc9118 --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json @@ -0,0 +1,50 @@ +{ + "schema": "paperclip.cursor.runtime-patch-proof.v1", + "patchVersion": "paperclip-cursor-isolation-v1", + "providerCalls": 0, + "qualification": "offline-only", + "platforms": [ + { + "platform": "darwin-arm64", + "file": "5672.index.js", + "sourceSha256": "7784c8b16d4e639814c13b12be2a687f5dc2cd98cbf29ed0a10820778ab1bf62", + "patchedSha256": "db997911906014ec9c522b48b6748bb39001e44d9a10730a433ab1e135aa0432", + "driftRejected": true, + "fullChunkCompiles": true, + "ambientMcpAccesses": 0, + "ownedMcpPreserved": true, + "hookConfigReads": 0, + "remoteTeamHookFetches": 0, + "typedActionErrors": true, + "assistantProseIgnored": true + }, + { + "platform": "darwin-x64", + "file": "9841.index.js", + "sourceSha256": "3c0aaf6ecc4fceb0f95e1731deec75384984570d14d0871cecec11972b948ac4", + "patchedSha256": "713aecb34c994d83ce46942f6b15bff173eb7b605f15a4653b24b9cc46dd3b5a", + "driftRejected": true, + "fullChunkCompiles": true, + "ambientMcpAccesses": 0, + "ownedMcpPreserved": true, + "hookConfigReads": 0, + "remoteTeamHookFetches": 0, + "typedActionErrors": true, + "assistantProseIgnored": true + }, + { + "platform": "linux-x64", + "file": "1699.index.js", + "sourceSha256": "2de420f1b31e70ca74b083a1ce5b519c2abffa5789d71cc06e84d2c38acb7c07", + "patchedSha256": "27e6e048b30afbf722c36cc3ef8ac4350957963291d15c34fdaea355d110ea2a", + "driftRejected": true, + "fullChunkCompiles": true, + "ambientMcpAccesses": 0, + "ownedMcpPreserved": true, + "hookConfigReads": 0, + "remoteTeamHookFetches": 0, + "typedActionErrors": true, + "assistantProseIgnored": true + } + ] +} From 4eec13c06b2585f7248937c517c909c69b257920 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 29 Sep 2026 09:44:37 -0500 Subject: [PATCH 2/6] Bind Cursor typed-error constructor outside the native turn scope Co-Authored-By: Paperclip --- packages/paperclip-runner/cursor-distributions.json | 6 +++--- .../scripts/cursor-runtime-patch.mjs | 12 ++++++++---- .../scripts/qualify-cursor-runtime-patch.mjs | 4 +++- .../src/drivers/acpx/cursor-installation.ts | 6 +++--- .../cursor-acp/runtime-patch-initialization.json | 6 ++++-- .../cursor-acp/runtime-patch-offline-proof.json | 6 +++--- 6 files changed, 24 insertions(+), 16 deletions(-) diff --git a/packages/paperclip-runner/cursor-distributions.json b/packages/paperclip-runner/cursor-distributions.json index 64280bbb777..bc724cded01 100644 --- a/packages/paperclip-runner/cursor-distributions.json +++ b/packages/paperclip-runner/cursor-distributions.json @@ -5,7 +5,7 @@ "darwin-arm64": { "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/darwin/arm64/agent-cli-package.tar.gz", "archiveSha256": "538827d96a779bab854a865c8e42859e8e87db34b5f69770261b90fc8cfff191", - "closureSha256": "89e28235685ab31d78779eccd5b6a7b2d9fec20181c439535f2fe492c5cd24da", + "closureSha256": "8a22016ca832ef8c8e6a83b955208d74c63f2c8dbe1dd688cbf27b81ad01886a", "executable": "node", "entrypoint": "index.js", "vendorClosureSha256": "77394184a89b0e7384971181da19c3c82d83a399b04e7944b3f94fe3d7e62b25" @@ -13,7 +13,7 @@ "darwin-x64": { "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/darwin/x64/agent-cli-package.tar.gz", "archiveSha256": "ed1771c44cbf0f8059c67cac0d939e6a60eb730bd066d7dc4cbb14de314cfb6e", - "closureSha256": "6729c65acb6b2f56690ebe54e63659f4dc31b2b5814aff8d59740767ab43ad17", + "closureSha256": "2c461f48feb274f8e7aabd6da67d1e9aefbe6e0b232fc0a111dce874378afcc8", "executable": "node", "entrypoint": "index.js", "vendorClosureSha256": "7c8775160af74e5fb8d25a30e8412c1a6476b0661529078a686e5118fd1c5e5f" @@ -21,7 +21,7 @@ "linux-x64": { "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/linux/x64/agent-cli-package.tar.gz", "archiveSha256": "8085fd120f5c71f4eae7fea26a043718e5644e3071e4fab3220a0e58c51f9593", - "closureSha256": "591623da24add49fc6572e6eba3039e21b40893024efc65fc547802e00cfec17", + "closureSha256": "4fe9461c19d1aec0cbbe4189159291fe62ef6910732a05fc5a25923afb1ce2c7", "executable": "node", "entrypoint": "index.js", "vendorClosureSha256": "bf04ef8ea6a63191067a6b3e15139aa2c793d8419daab246aa3f0a012e1bbcd9" diff --git a/packages/paperclip-runner/scripts/cursor-runtime-patch.mjs b/packages/paperclip-runner/scripts/cursor-runtime-patch.mjs index 439529e9ba5..dc594199a47 100644 --- a/packages/paperclip-runner/scripts/cursor-runtime-patch.mjs +++ b/packages/paperclip-runner/scripts/cursor-runtime-patch.mjs @@ -6,9 +6,9 @@ import { join } from "node:path"; // Cursor adapter and the vendor's interactive CLI are not changed. export const CURSOR_RUNTIME_PATCH_VERSION = "paperclip-cursor-isolation-v1"; export const CURSOR_RUNTIME_PATCH_PINS = Object.freeze({ - "darwin-arm64": { file: "5672.index.js", before: "7784c8b16d4e639814c13b12be2a687f5dc2cd98cbf29ed0a10820778ab1bf62", after: "db997911906014ec9c522b48b6748bb39001e44d9a10730a433ab1e135aa0432" }, - "darwin-x64": { file: "9841.index.js", before: "3c0aaf6ecc4fceb0f95e1731deec75384984570d14d0871cecec11972b948ac4", after: "713aecb34c994d83ce46942f6b15bff173eb7b605f15a4653b24b9cc46dd3b5a" }, - "linux-x64": { file: "1699.index.js", before: "2de420f1b31e70ca74b083a1ce5b519c2abffa5789d71cc06e84d2c38acb7c07", after: "27e6e048b30afbf722c36cc3ef8ac4350957963291d15c34fdaea355d110ea2a" }, + "darwin-arm64": { file: "5672.index.js", before: "7784c8b16d4e639814c13b12be2a687f5dc2cd98cbf29ed0a10820778ab1bf62", after: "c9e627bde091bd2559a45840f488d05dd7273100fa3ee3c32df1871e0357c0d4" }, + "darwin-x64": { file: "9841.index.js", before: "3c0aaf6ecc4fceb0f95e1731deec75384984570d14d0871cecec11972b948ac4", after: "360ee9a5ad74a7b7a2e880d642a22f6b8841967bb1660654b6cd2b90313de988" }, + "linux-x64": { file: "1699.index.js", before: "2de420f1b31e70ca74b083a1ce5b519c2abffa5789d71cc06e84d2c38acb7c07", after: "32f44c4981f5a26765e5101b389e3fcdb6e885b31a7ac876b68fd97afe078553" }, }); const digest = value => createHash("sha256").update(value).digest("hex"); @@ -38,7 +38,11 @@ export function patchCursorRuntimeSource(source, platform) { // Use the exact SDK module already present in this verified vendor chunk. const sdk = [...source.matchAll(/n\("([^"\n]+@agentclientprotocol\/sdk\/dist\/acp\.js)"\)/g)].map(match => match[1]); if (new Set(sdk).size !== 1) throw new Error("Cursor runtime patch SDK identity is ambiguous"); - const errorType = `n(${JSON.stringify(sdk[0])}).GI`; + const errorType = "paperclipCursorResponseError"; + // processPrompt(e,t,n) shadows the webpack require name n. Bind the SDK + // constructor at module scope rather than invoking that turn-ID argument. + const sessionClass = platform === "darwin-arm64" ? "B" : "z"; + replace(`n.d(t,{m:()=>${sessionClass}});var s=n("node:fs/promises")`, `n.d(t,{m:()=>${sessionClass}});const ${errorType}=n(${JSON.stringify(sdk[0])}).GI;var s=n("node:fs/promises")`); const oldAction = 'if(e instanceof r.ao){const t=null!==(u={login:"Please sign in to continue",upgrade:"Upgrade your plan to continue",payment:"Add a payment method to continue",config:"Check your settings to continue"}[e.action])&&void 0!==u?u:e.message;return void(yield this.sendAgentMessageChunk(`\\n\\n${t}`))}'; const newAction = `if(e instanceof r.ao){const action=["login","upgrade","payment","config"].includes(e.action)?e.action:"unknown";throw new (${errorType})(action==="login"?-32000:-32603,"Cursor provider action required: "+action,{schema:"paperclip.cursor.provider-error.v1",kind:"action_required",action})}`; replace(oldAction, newAction); diff --git a/packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs b/packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs index 8cda60b5e9c..2d447b7e914 100644 --- a/packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs +++ b/packages/paperclip-runner/scripts/qualify-cursor-runtime-patch.mjs @@ -67,7 +67,9 @@ export async function qualifyCursorRuntimePatch(vendorRoot) { class ActionRequired extends Error { constructor(action) { super("private provider detail"); this.action = action; } } class ConnectError extends Error { constructor() { super("private auth detail"); this.code = 16; } } class ResponseError extends Error { constructor(code, message, data) { super(message); this.code = code; this.data = data; } } - const evaluate = error => runInNewContext(`(function(){${errors}})()`, { e: error, r: { ao: ActionRequired }, g: { T: ConnectError }, m: { C: { Unauthenticated: 16 } }, f: { C: { Unauthenticated: 16 } }, n: () => ({ GI: ResponseError }) }); + const binding = segment(source, "const paperclipCursorResponseError=", ";var s="); + assert.equal(runInNewContext(`${binding};paperclipCursorResponseError`, { n: () => ({ GI: ResponseError }) }), ResponseError); + const evaluate = error => runInNewContext(`(function(){${errors}})()`, { e: error, r: { ao: ActionRequired }, g: { T: ConnectError }, m: { C: { Unauthenticated: 16 } }, f: { C: { Unauthenticated: 16 } }, n: 123, paperclipCursorResponseError: ResponseError }); for (const action of ["login", "upgrade", "payment", "config", "other"]) { assert.throws(() => evaluate(new ActionRequired(action)), error => error instanceof ResponseError && error.code === (action === "login" ? -32000 : -32603) diff --git a/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts b/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts index 3924e814416..14534fbd29a 100644 --- a/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts +++ b/packages/paperclip-runner/src/drivers/acpx/cursor-installation.ts @@ -8,9 +8,9 @@ import { resolveRunnerProviderAssetsRoot } from "./provider-assets-root.js"; export const CURSOR_PINNED_VERSION = "2026.09.26-dd393fe"; const CLOSURE_PINS = Object.freeze({ - "darwin-arm64": "89e28235685ab31d78779eccd5b6a7b2d9fec20181c439535f2fe492c5cd24da", - "darwin-x64": "6729c65acb6b2f56690ebe54e63659f4dc31b2b5814aff8d59740767ab43ad17", - "linux-x64": "591623da24add49fc6572e6eba3039e21b40893024efc65fc547802e00cfec17", + "darwin-arm64": "8a22016ca832ef8c8e6a83b955208d74c63f2c8dbe1dd688cbf27b81ad01886a", + "darwin-x64": "2c461f48feb274f8e7aabd6da67d1e9aefbe6e0b232fc0a111dce874378afcc8", + "linux-x64": "4fe9461c19d1aec0cbbe4189159291fe62ef6910732a05fc5a25923afb1ce2c7", }); /** Trusted package assets only: no workspace, PATH, executable override or env root. */ diff --git a/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json index bd751db3ce7..ea009e2bb8c 100644 --- a/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json +++ b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-initialization.json @@ -14,7 +14,8 @@ "protocolVersion": 1, "exitCode": 143, "signal": null, - "error": "" + "error": "", + "closureSha256": "8a22016ca832ef8c8e6a83b955208d74c63f2c8dbe1dd688cbf27b81ad01886a" }, { "platform": "darwin-x64", @@ -23,7 +24,8 @@ "protocolVersion": 1, "exitCode": 143, "signal": null, - "error": "" + "error": "", + "closureSha256": "2c461f48feb274f8e7aabd6da67d1e9aefbe6e0b232fc0a111dce874378afcc8" } ] } diff --git a/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json index d6fc6bc9118..cc56c4b6059 100644 --- a/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json +++ b/packages/paperclip-runner/test/fixtures/cursor-acp/runtime-patch-offline-proof.json @@ -8,7 +8,7 @@ "platform": "darwin-arm64", "file": "5672.index.js", "sourceSha256": "7784c8b16d4e639814c13b12be2a687f5dc2cd98cbf29ed0a10820778ab1bf62", - "patchedSha256": "db997911906014ec9c522b48b6748bb39001e44d9a10730a433ab1e135aa0432", + "patchedSha256": "c9e627bde091bd2559a45840f488d05dd7273100fa3ee3c32df1871e0357c0d4", "driftRejected": true, "fullChunkCompiles": true, "ambientMcpAccesses": 0, @@ -22,7 +22,7 @@ "platform": "darwin-x64", "file": "9841.index.js", "sourceSha256": "3c0aaf6ecc4fceb0f95e1731deec75384984570d14d0871cecec11972b948ac4", - "patchedSha256": "713aecb34c994d83ce46942f6b15bff173eb7b605f15a4653b24b9cc46dd3b5a", + "patchedSha256": "360ee9a5ad74a7b7a2e880d642a22f6b8841967bb1660654b6cd2b90313de988", "driftRejected": true, "fullChunkCompiles": true, "ambientMcpAccesses": 0, @@ -36,7 +36,7 @@ "platform": "linux-x64", "file": "1699.index.js", "sourceSha256": "2de420f1b31e70ca74b083a1ce5b519c2abffa5789d71cc06e84d2c38acb7c07", - "patchedSha256": "27e6e048b30afbf722c36cc3ef8ac4350957963291d15c34fdaea355d110ea2a", + "patchedSha256": "32f44c4981f5a26765e5101b389e3fcdb6e885b31a7ac876b68fd97afe078553", "driftRejected": true, "fullChunkCompiles": true, "ambientMcpAccesses": 0, From d01c2439e08ed97b3792ca18840d1c8e6b807c49 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 29 Sep 2026 09:45:26 -0500 Subject: [PATCH 3/6] Fence Copilot ACP connection policy before protocol dispatch Co-Authored-By: Paperclip --- .../runner-copilot-capabilities.md | 59 ++++++- .../scripts/probe-copilot-acp.py | 58 +++++-- .../acpx/codex-runtime-adapter.test.ts | 18 +++ .../src/drivers/acpx/codex-runtime-adapter.ts | 7 + .../src/drivers/acpx/copilot-policy.test.ts | 93 +++++++++++ .../src/drivers/acpx/copilot-policy.ts | 149 ++++++++++++++++++ .../acpx/copilot-protocol-guard.test.ts | 64 ++++++++ ...copilot-policy-conformance-2026-09-29.json | 126 +++++++++++++++ patches/acpx@0.13.1.patch | 116 ++++++++------ 9 files changed, 631 insertions(+), 59 deletions(-) create mode 100644 packages/paperclip-runner/src/drivers/acpx/copilot-policy.test.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/copilot-policy.ts create mode 100644 packages/paperclip-runner/src/drivers/acpx/copilot-protocol-guard.test.ts create mode 100644 packages/paperclip-runner/test/fixtures/copilot-policy-conformance-2026-09-29.json diff --git a/doc/architecture/runner-copilot-capabilities.md b/doc/architecture/runner-copilot-capabilities.md index d1ff73598a5..f2747a92154 100644 --- a/doc/architecture/runner-copilot-capabilities.md +++ b/doc/architecture/runner-copilot-capabilities.md @@ -11,6 +11,59 @@ Real executable offline probes cost $0; the live token receipt has no verified U the shared $100 hard stop and verifiable spend. Do not expose this profile as supported until the required local and Daytona qualification passes. +## Connection policy audit, 2026-09-29 + +The pinned server accepts permission-changing `session/set_config_option`, +`session/set_mode`, and leading-slash CLI commands. Entering autopilot enables +allow-all; loading an autopilot conversation enables it again. A clean launch +configuration alone therefore cannot establish safe restored-session policy. + +`copilot-policy.ts` and the optional ACPX `protocolGuardFactory` enforce policy +on each actual stdio connection, before bytes are delivered to the SDK or written +to the provider. Copilot admission requires the full new/load/resume result to +report the exact agent-mode URI and `allow_all: off`. Missing, duplicated, +unknown-authority, or custom-agent configuration fails closed. A connection may +select only its explicitly admitted model; a prompt requires proof of that +model. The guard rejects leading-slash commands, native mode/config controls, +and unsafe mode/config drift. Its authority is fresh for every connection and +remains invalid after a violation. It does not restore trust from cached ACPX +status. The stream errors, aborts outstanding response delivery, and terminates +the provider on violation; the existing runner owns bounded process cleanup. +Other providers do not install this guard. + +The native `ask_user` and `exit_plan_mode` tools are absent from both agent and +plan mode in the pinned deterministic tool catalogs. Forced model tool calls +return explicit tool-unavailable results rather than producing a blocking +request. No `--no-ask-user` or tool-exclusion flag was used. Agent mode is the +only admitted production mode. If any native input-request event nevertheless +arrives, the guard terminates the connection; it never presents a form whose +answer cannot be delivered. This narrows the blocking-input question for the +admitted pinned mode without claiming an upstream question responder exists. + +The [offline conformance record](../../packages/paperclip-runner/test/fixtures/copilot-policy-conformance-2026-09-29.json) +retains seven attempts and their evidence digests. A protected file outside the +working directory was denied before its contents reached the fixture model. +A durable conversation was closed and loaded, then requested permission for a +shell write; `reject_once` prevented the file. The initial attempt to load an +empty conversation failed with resource-not-found and remains retained. The +second attempt seeds one text turn before close/load; it is not a retry of a +measured behavior failure. This proves a local native close/load permission +boundary, not process-death recovery or a final packaged Product case. + +All these probes use the verified 1.0.88 ARM64 binary, an explicitly constructed +credential-free environment, `COPILOT_OFFLINE=true`, and a synthetic OpenAI-style +model at an ephemeral loopback HTTP server. The synthetic `gpt-4.1` ID does not +name an authenticated GitHub model selection. Counts include the setup turn. +There are zero paid provider calls and zero model spend. Raw evidence, including +the failed empty-session attempt, stays in the private +`copilot-policy-20260929` artifact directory. + +The prior Product question failure remains a model-behavior failure: the retained +snapshot contains the exact requested marker in the task instructions, the +answered Cobalt choice, and warm-session continuation. Copilot instead supplied +`[terminal marker]` to `paperclip_finish`. Neither the grader nor the terminal +marker requirement changed. A final-runtime rerun remains required. + ## Evidence and scope The audit inspected the exact `@github/copilot@1.0.88` platform archives, the @@ -144,8 +197,8 @@ Daytona claims require the separate live product qualification. | Tools / correlation | Standard `tool_call`/`tool_call_update`; parent identity in `_meta["github.com/copilot"].agentId`. HTTP/SSE MCP supported. | Shared tool activity, authenticated runner-owned MCP bridge. | Real create/bash/read_bash traffic and canonical authenticated get-task-context pass; Product semantic question and plan calls observed. Full adversarial company-boundary coverage remains pending. | | MCP transport selection | Both HTTP and SSE are advertised. | The assigned Paperclip gateway uses the controlled HTTP bridge. Arbitrary SSE endpoint configuration is not exposed. | Observed initialize; SSE remains unused, P2 only if a governed connection requires it. | | Scoped approvals | `session/request_permission`, actual options allow_once/allow_always/reject_once. | Shared durable permissions; only received decisions offered, policy enforced. | Real-service wire ID 0 denied before file creation, with no side effect through cleanup. Durable Product restrictive-mode recovery and wider tool denial remain unqualified. | -| Structured questions | Native `ask_user` callback and `user_input.requested`; current ACP adapter does not wire the responder. | Emits capability-gap notice if native notification arrives; cannot claim answer delivery. | Actual agent-mode tool list omits `ask_user` without a suppression flag. Paperclip semantic questions are available: restart case passes, while the separate question case failed its exact marker. P0 qualify other native blocking modes. | -| Plan approval | Native `exit_plan_mode` callback; notification contains plan content/actions but lacks qualified ACP responder. | Capability-gap notice only; never synthesize plan acceptance. | Agent-mode tool list omits exit_plan_mode. Paperclip semantic plan/revision approval passes through the UI; native plan mode still requires explicit qualification, P0. | +| Structured questions | Native `ask_user` callback and `user_input.requested`; current ACP adapter does not wire the responder. | Emits capability-gap notice if native notification arrives; cannot claim answer delivery. | Actual agent-mode tool list omits `ask_user` without a suppression flag. Paperclip semantic questions are available: restart case passes, while the separate question case failed its exact marker. Pinned offline agent/plan catalogs now prove both tools unavailable; the production guard admits agent mode and terminates any unexpected native blocking request. | +| Plan approval | Native `exit_plan_mode` callback; notification contains plan content/actions but lacks qualified ACP responder. | Capability-gap notice only; never synthesize plan acceptance. | Agent-mode tool list omits exit_plan_mode. Paperclip semantic plan/revision approval passes through the UI; Native plan-mode input is confirmed unavailable offline; production mode controls remain disabled. | | Plan progress | Standard plan from todos SQL; native `session.plan_changed` has operation only. | Existing ACP plan/activity; native operation preserved, `planContentAvailable:false`. | Source; plan document reads require native interface. P1. | | Models / reasoning / config | Source `session/set_model`, config options for model, reasoning, mode, custom agents, allow_all. | Explicit model admission. Mode/governance changes must remain policy-gated. | Authenticated catalog, exact set_model/config echo and real inference verified for gpt-5.6-luna. Other models and config-mode changes remain unqualified. | | Usage | Standard prompt usage and context usage; native assistant usage, AI-unit checkpoint. | Token/counter metadata with source; multiplier and nano-AI-units distinct from USD. | Real token counters retain GitHub provenance; authoritative per-turn USD is unavailable. External included-credit snapshots are separate, with additional cash billing disabled. CLI requested-cost coverage fails closed when unknown. Never double-count passthrough. | @@ -171,7 +224,7 @@ Reasons and priorities are explicit: | --- | --- | | Standard text/reasoning/tool/plan/config events | Standard ACP already transports the user-facing content. Additional native metadata is not assumed preserved. P2 compare native field inventory against normalization before adding fields; avoid duplicate output and raw reasoning. | | Standard ACP parent tool content and locations | Confirmed shared normalization gap: structured `content` diff/image blocks, `rawInput`, and locations after the first safe relative path are not carried into canonical tool events. Only bounded `rawOutput`, `inputUpdated`, tool lifecycle/identity, and that first path survive. P1 introduce validated diff/image artifact schemas and preserve every safe location with attribution; retain secret redaction and workspace containment rather than forwarding raw provider objects. The retained offline diff proves harness exposure only. | -| Native user/plan/elicitation requests and completions | No qualified ACP responder/correlation acknowledgment. P0 prove there is no blocking input before qualification; add an upstream responder or owned wrapper before displaying an answerable UI. | +| Native user/plan/elicitation requests and completions | No qualified ACP responder/correlation acknowledgment. The 2026-09-29 agent/plan probes prove these two native tools unavailable on the pinned offline surface; the connection guard fails closed if any native request appears. Add a versioned upstream responder before displaying an answerable UI. | | Native permission authorization internals, sandbox decisions, recovery | Standard permission callback is the policy decision boundary. P1 collect sanitized denial diagnostics; never let native carried-forward/assent events authorize actions. | | Native usage diagnostics omitted from subscribed assistant.usage | Quota snapshots, reasoning summaries, fusion/RTE payloads and upstream service/cache diagnostics are not normalized. P2 type/redact useful performance details; quotas and model multipliers cannot substitute for verifiable dollar spend. | | Native compaction summaries/checkpoint paths/custom instructions | Avoid copying private instruction/summary bodies or treating provider paths as task paths. P2 add explicit safe metadata schema/artifact retrieval where useful. | diff --git a/packages/paperclip-runner/scripts/probe-copilot-acp.py b/packages/paperclip-runner/scripts/probe-copilot-acp.py index 488f9a52e2e..83d5a545843 100644 --- a/packages/paperclip-runner/scripts/probe-copilot-acp.py +++ b/packages/paperclip-runner/scripts/probe-copilot-acp.py @@ -5,7 +5,9 @@ This proves a protocol fixture, never GitHub/model/Daytona qualification. import argparse,json,subprocess,tempfile,pathlib,os,select,time,threading,http.server,hashlib,shutil,contextlib,sys parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--package-root',required=True) -parser.add_argument('--scenario',choices=['deny-write','attached-shell'],default='deny-write') +parser.add_argument('--scenario',choices=['deny-write','deny-shell','deny-read','attached-shell','discover-inputs','native-question','native-plan'],default='deny-write') +parser.add_argument('--mode',choices=['agent','plan','autopilot'],default='agent') +parser.add_argument('--resume',action='store_true',help='Close and load the same native session before prompting') args=parser.parse_args() package_root=pathlib.Path(args.package_root).resolve() metadata=json.loads((package_root/'package.json').read_text()) @@ -14,6 +16,7 @@ assert metadata['version']=='1.0.88' and metadata['name'] in pins assert not (package_root/'copilot').is_symlink() assert hashlib.sha256((package_root/'copilot').read_bytes()).hexdigest()==pins[metadata['name']] model_tool_names=[] +model_tool_results=[] command='sleep 2; printf ACP_SHELL_DONE > settlement.txt' binary=str(package_root/'copilot') @@ -34,22 +37,31 @@ with contextlib.ExitStack() as cleanup: root=pathlib.Path(tempfile.mkdtemp(prefix='paperclip-copilot-offline-')) cleanup.callback(shutil.rmtree, root) calls=0 + total_model_calls=0 session=None + final_prompt_id=None + outside=root.parent/(root.name+'-protected.txt') + outside.write_text('PRIVATE_FIXTURE_SENTINEL') + cleanup.callback(outside.unlink,missing_ok=True) + tool_name={'deny-write':'create','deny-shell':'bash','deny-read':'view','attached-shell':'bash','native-question':'ask_user','native-plan':'exit_plan_mode'}.get(args.scenario) + tool_arguments={'deny-write':{'path':str(root/'denied.txt'),'file_text':'MUST NOT EXIST'},'deny-shell':{'command':'printf MUST_NOT_EXIST > denied.txt','description':'Denied command fixture'},'deny-read':{'path':str(outside)},'attached-shell':{'command':command,'description':'Bounded settlement fixture','mode':'async','detach':False},'native-question':{'question':'Choose one','choices':['A','B'],'allowFreeform':False},'native-plan':{'summary':'Fixture plan','planContent':'Do fixture work'}}.get(args.scenario) marker_at_prompt_result=False class Handler(http.server.BaseHTTPRequestHandler): def log_message(self,*args):pass def do_GET(self): self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(json.dumps({'data':[{'id':'gpt-4.1','object':'model','owned_by':'fixture'}]}).encode()) def do_POST(self): - global calls,model_tool_names + global calls,total_model_calls,model_tool_names,model_tool_results calls+=1 + total_model_calls+=1 data=json.loads(self.rfile.read(int(self.headers.get('Content-Length','0')))) - model_tool_names=[x.get('function',{}).get('name') for x in data.get('tools',[])] - if calls>4:raise RuntimeError('Fixture model exceeded its bounded request count') + model_tool_names=sorted(set(model_tool_names+[x.get('function',{}).get('name') for x in data.get('tools',[]) if x.get('function',{}).get('name')])) + model_tool_results.extend(x.get('content') for x in data.get('messages',[]) if x.get('role')=='tool') + if total_model_calls>5:raise RuntimeError('Fixture model exceeded its bounded request count') if data.get('stream'): self.send_response(200);self.send_header('Content-Type','text/event-stream');self.end_headers() values=[{'id':'fixture-1','object':'chat.completion.chunk','choices':[{'index':0,'delta':{'role':'assistant','content':'Fixture complete.'},'finish_reason':None}]},{'id':'fixture-1','object':'chat.completion.chunk','choices':[{'index':0,'delta':{},'finish_reason':'stop'}],'usage':{'prompt_tokens':10,'completion_tokens':3,'total_tokens':13}}] - if calls==1:values=[{'id':'fixture-1','object':'chat.completion.chunk','choices':[{'index':0,'delta':{'role':'assistant','tool_calls':[{'index':0,'id':'fixture-tool','type':'function','function':{'name':'create' if args.scenario=='deny-write' else 'bash','arguments':json.dumps({'path':str(root/'denied.txt'),'file_text':'MUST NOT EXIST'} if args.scenario=='deny-write' else {'command':command,'description':'Bounded settlement fixture','mode':'async','detach':False})}}]},'finish_reason':None}]},{'id':'fixture-1','object':'chat.completion.chunk','choices':[{'index':0,'delta':{},'finish_reason':'tool_calls'}]}] + if calls==1 and tool_name:values=[{'id':'fixture-1','object':'chat.completion.chunk','choices':[{'index':0,'delta':{'role':'assistant','tool_calls':[{'index':0,'id':'fixture-tool','type':'function','function':{'name':tool_name,'arguments':json.dumps(tool_arguments)}}]},'finish_reason':None}]},{'id':'fixture-1','object':'chat.completion.chunk','choices':[{'index':0,'delta':{},'finish_reason':'tool_calls'}]}] for value in values:self.wfile.write(('data: '+json.dumps(value)+'\n\n').encode()) self.wfile.write(b'data: [DONE]\n\n') else: @@ -58,8 +70,8 @@ with contextlib.ExitStack() as cleanup: cleanup.callback(server.server_close) threading.Thread(target=server.serve_forever,daemon=True).start() cleanup.callback(server.shutdown) - env={'PATH':'/usr/bin:/bin','HOME':str(root/'home'),'XDG_CONFIG_HOME':str(root/'config'),'XDG_CACHE_HOME':str(root/'cache'),'XDG_DATA_HOME':str(root/'data'),'COPILOT_HOME':str(root/'copilot'),'COPILOT_CACHE_HOME':str(root/'copilot-cache'),'COPILOT_AUTO_UPDATE':'false','COPILOT_OFFLINE':'true','COPILOT_PROVIDER_BASE_URL':f'http://127.0.0.1:{server.server_port}','COPILOT_PROVIDER_TYPE':'openai','COPILOT_PROVIDER_MODEL_ID':'gpt-4.1','COPILOT_MODEL':'gpt-4.1','NO_COLOR':'1'} - for key in ('HOME','XDG_CONFIG_HOME','XDG_CACHE_HOME','XDG_DATA_HOME','COPILOT_HOME','COPILOT_CACHE_HOME'):pathlib.Path(env[key]).mkdir() + env={'PATH':'/usr/bin:/bin','HOME':str(root/'home'),'XDG_CONFIG_HOME':str(root/'config'),'XDG_CACHE_HOME':str(root/'cache'),'XDG_DATA_HOME':str(root/'data'),'COPILOT_HOME':str(root/'copilot'),'COPILOT_CACHE_HOME':str(root/'copilot-cache'),'COPILOT_ALLOW_ALL':'false','COPILOT_PKG_CACHE_HOME':str(root/'extract'),'COPILOT_AUTO_UPDATE':'false','COPILOT_OFFLINE':'true','COPILOT_PROVIDER_BASE_URL':f'http://127.0.0.1:{server.server_port}','COPILOT_PROVIDER_TYPE':'openai','COPILOT_PROVIDER_MODEL_ID':'gpt-4.1','COPILOT_MODEL':'gpt-4.1','NO_COLOR':'1'} + for key in ('HOME','XDG_CONFIG_HOME','XDG_CACHE_HOME','XDG_DATA_HOME','COPILOT_HOME','COPILOT_CACHE_HOME','COPILOT_PKG_CACHE_HOME'):pathlib.Path(env[key]).mkdir() (root/'copilot/config.json').write_text(json.dumps({'trustedFolders':[],'disableAllHooks':True,'memory':False,'ide':{'autoConnect':False}})) p=subprocess.Popen([binary,'--acp','--stdio','--no-auto-update','--disable-builtin-mcps','--no-remote','--no-remote-export','--no-bash-env'],env=env,cwd=root,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) cleanup.callback(stop_process, p) @@ -93,20 +105,42 @@ with contextlib.ExitStack() as cleanup: request('initialize',{'protocolVersion':1,'clientCapabilities':{'_meta':{'github.com/copilot':{'events':['session.idle','session.plan_changed','session.background_tasks_changed','session.completion_receipt','user_input.requested','exit_plan_mode.requested','assistant.usage']}}},'clientInfo':{'name':'paperclip-offline-fixture','version':'1'}}) session=request('session/new',{'cwd':str(root),'mcpServers':[]}) if 'result' in session: - request('session/prompt',{'sessionId':session['result']['sessionId'],'prompt':[{'type':'text','text':'Reply with Fixture complete.'}]}) - marker_at_prompt_result=(root/('denied.txt' if args.scenario=='deny-write' else 'settlement.txt')).exists() + session_id=session['result']['sessionId'] + if args.mode!='agent': + request('session/set_mode',{'sessionId':session_id,'modeId':'https://agentclientprotocol.com/protocol/session-modes#'+args.mode}) + if args.resume: + # A native session with no conversation is not durably resumable. + calls=-1 + request('session/prompt',{'sessionId':session_id,'prompt':[{'type':'text','text':'Initialize the fixture conversation.'}]}) + calls=0 + request('session/close',{'sessionId':session_id}) + session=request('session/load',{'sessionId':session_id,'cwd':str(root),'mcpServers':[]}) + if 'error' in session:raise RuntimeError('Copilot rejected session load') + final_prompt_id=nextid+1 + request('session/prompt',{'sessionId':session_id,'prompt':[{'type':'text','text':'Reply with Fixture complete.'}]}) + marker_at_prompt_result=(root/('settlement.txt' if args.scenario=='attached-shell' else 'denied.txt')).exists() for _ in range(3):pump(.1) finally: failure=sys.exc_info()[1] try: - marker_exists=(root/('denied.txt' if args.scenario=='deny-write' else 'settlement.txt')).exists() - report={'schema':'paperclip.copilot-acp-evidence/v1','harnessVersion':'1.0.88','package':metadata['name'],'executableSha256':pins[metadata['name']],'modelSource':'deterministic loopback fixture, COPILOT_OFFLINE=true; not a live model qualification','scenario':args.scenario,'costUsd':0,'filesystemMarkerExistedAtPromptResult':marker_at_prompt_result,'filesystemMarkerExistedAfterPrompt':marker_exists,'modelCalls':calls,'modelToolNames':model_tool_names,'permissionResponses':permission_responses,'wire':wire} + marker_exists=(root/('settlement.txt' if args.scenario=='attached-shell' else 'denied.txt')).exists() + report={'schema':'paperclip.copilot-acp-evidence/v1','harnessVersion':'1.0.88','package':metadata['name'],'executableSha256':pins[metadata['name']],'modelSource':'deterministic loopback fixture, COPILOT_OFFLINE=true; not a live model qualification','scenario':args.scenario,'mode':args.mode,'resumed':args.resume,'costUsd':0,'filesystemMarkerExistedAtPromptResult':marker_at_prompt_result,'filesystemMarkerExistedAfterPrompt':marker_exists,'modelCalls':total_model_calls,'modelToolNames':model_tool_names,'modelToolResults':model_tool_results,'permissionResponses':permission_responses,'wire':wire} serialized=json.dumps(report,indent=2).replace(str(root),'/fixture/workspace').replace(str(root).lstrip('/'),'fixture/workspace').replace(binary,'/fixture/verified/copilot') print(serialized) except Exception: if failure is None:raise - if not session or 'result' not in session or responses.get(3,{}).get('result',{}).get('stopReason')!='end_turn': + if not session or 'result' not in session or responses.get(final_prompt_id,{}).get('result',{}).get('stopReason')!='end_turn': raise RuntimeError('Copilot did not complete the fixture turn') if marker_at_prompt_result != (args.scenario=='attached-shell') or marker_exists != marker_at_prompt_result: raise RuntimeError('Copilot violated the fixture filesystem expectation') + + if args.scenario.startswith('deny-') and not permission_responses: + raise RuntimeError('Copilot did not request permission before the denied operation') + if args.scenario=='deny-read' and any('PRIVATE_FIXTURE_SENTINEL' in str(result) for result in model_tool_results): + raise RuntimeError('Copilot leaked the denied file to the model') + if args.scenario in ('native-question','native-plan','discover-inputs') and any(name in model_tool_names for name in ('ask_user','exit_plan_mode')): + raise RuntimeError('Native blocking input is advertised without a qualified responder') + + if args.scenario in ('native-question','native-plan') and not any("Tool '"+str(tool_name)+"' does not exist" in str(result) for result in model_tool_results): + raise RuntimeError('Forced native input did not prove explicit tool unavailability') diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts index f79a3e291e4..8b7468c74ff 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.test.ts @@ -28,6 +28,24 @@ const HANDLE: AcpRuntimeHandle = { }; describe("Codex ACPX runtime adapter", () => { + it("installs per-connection policy authority only for Copilot and rejects native commands before a turn starts", async () => { + for (const agent of ["copilot", "codex", "claude", "grok"] as const) { + const runtime = fakeRuntime(); + let created!: AcpRuntimeOptions; + const options = openOptions(fakeCommand()); + options.profile = { ...options.profile, agent }; + const port = await openCodexAcpxRuntime(options, { + createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; }, + }); + if (agent === "copilot") { + expect(created.protocolGuardFactory).toBeTypeOf("function"); + expect(created.protocolGuardFactory!()).not.toBe(created.protocolGuardFactory!()); + expect(() => port.startTurn({ text: "\n/yolo on", requestId: "bad" })).toThrow(/admitted permission policy/); + expect(runtime.startTurn).not.toHaveBeenCalled(); + } else expect(created.protocolGuardFactory).toBeUndefined(); + await port.close({ reason: "test complete" }); + } + }); it("rejects forged permission session identifiers before delegating or applying full-auto policy", async () => { const pending = pendingExtensionTurn("turn-1"); const runtime = fakeRuntime(); vi.mocked(runtime.startTurn).mockReturnValue(pending.turn); diff --git a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts index fcc480f74f4..0be94cdf668 100644 --- a/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts +++ b/packages/paperclip-runner/src/drivers/acpx/codex-runtime-adapter.ts @@ -30,6 +30,7 @@ import { import type { AcpxModelStatus } from "./model-verification.js"; import { AcpxApprovalRequiredError, decideAcpxPermission } from "./permission-policy.js"; import { ACPX_CAPABILITY_PROFILES } from "./capability-profiles.js"; +import { assertCopilotPromptPolicy, createCopilotProtocolGuard } from "./copilot-policy.js"; const VERIFIED_COMMAND_SENTINEL = "paperclip-verified-acpx-command"; const DEFAULT_RUNTIME_CLOSE_TIMEOUT_MS = 2_000; @@ -315,6 +316,9 @@ export async function openQualifiedAcpxRuntime( elicitationModes: ["form"], ...(options.clientCapabilities === undefined ? {} : { clientCapabilities: structuredClone(options.clientCapabilities) }), extensionMethods: [...new Set([...extensionRequests, ...extensionNotifications])], + ...(options.profile.agent === "copilot" ? { + protocolGuardFactory: () => createCopilotProtocolGuard(options.profile.reportedModelId), + } : {}), onExtensionRequest: async (method, params, context) => { const active = extensionBoundary.active; if (!extensionRequests.has(method) || !active?.onRequest || !ownsExtensionTurn(active, params) || context.signal.aborted) { @@ -531,6 +535,7 @@ export async function openQualifiedAcpxRuntime( commandLaunches, permissionBoundary, extensionBoundary, + options.profile.agent === "copilot" ? assertCopilotPromptPolicy : undefined, ); } catch (error) { const cleanupReason = "ACPX runtime identity validation failed"; @@ -960,6 +965,7 @@ function runtimePort( commandLaunches: { count: number; refreshConsumedCommand?: () => Promise }, permissionBoundary: { active: AbortController | null; handler?: AcpRuntimeOptions["onPermissionRequest"] }, extensionBoundary: AcpxRuntimeExtensionBoundary, + assertPromptPolicy?: (text: string) => void, ): AcpxRuntimePort { extensionBoundary.sessionIds = new Set([identity.backendSessionId]); let extensionControls: Promise = Promise.resolve(); @@ -1317,6 +1323,7 @@ function runtimePort( } : {}), startTurn(input) { + assertPromptPolicy?.(input.text); if (extensionBoundary.active) throw new Error("ACPX runtime already has an active turn"); const approval = new AbortController(); const controller = new AbortController(); diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-policy.test.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-policy.test.ts new file mode 100644 index 00000000000..3365d15e915 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-policy.test.ts @@ -0,0 +1,93 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { + COPILOT_AGENT_MODE, assertCopilotConfigPolicy, assertCopilotControlPolicy, + assertCopilotPromptPolicy, assertCopilotSessionPolicy, assertCopilotSessionUpdatePolicy, + createCopilotProtocolGuard, +} from "./copilot-policy.js"; + +const fixture = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-acp-denial-1.0.88.json", import.meta.url), "utf8")); +const session = fixture.wire.find((message: { result?: { modes?: unknown } }) => message.result?.modes).result; + +describe("Copilot native policy fence", () => { + it("admits the pinned real-binary agent/manual snapshot", () => { + expect(() => assertCopilotSessionPolicy(session)).not.toThrow(); + expect(() => assertCopilotSessionUpdatePolicy({ sessionUpdate: "config_option_update", configOptions: session.configOptions })).not.toThrow(); + }); + it.each(["/yolo on", " /allow-all", "\n/autopilot", "\t/plan", "\ufeff/cwd /elsewhere", "/unknown-future-command", "/custom-skill"])("rejects native command dispatch %s", text => { + expect(() => assertCopilotPromptPolicy(text)).toThrowError(expect.objectContaining({ code: "COPILOT_POLICY_VIOLATION", retryable: false })); + }); + it("preserves ordinary prose mentioning commands and natural-language questions", () => { + for (const text of ["Explain /plan", "Ask me before proceeding", "Read this file: /workspace/file", "Plan the work\n/yolo on"]) { + expect(() => assertCopilotPromptPolicy(text)).not.toThrow(); + } + }); + it.each([undefined, null, {}, { modes: session.modes }, { configOptions: session.configOptions }, + { ...session, modes: { currentModeId: "https://agentclientprotocol.com/protocol/session-modes#autopilot" } }, + { ...session, modes: { currentModeId: "https://agentclientprotocol.com/protocol/session-modes#plan" } }, + ])("rejects missing or unsafe connection proof", state => { + expect(() => assertCopilotSessionPolicy(state)).toThrow(/admitted permission policy/); + }); + it("rejects bypass, duplicate, missing, custom-agent and future config authority", () => { + const config = session.configOptions; + for (const value of [[], [...config, config[0]], config.filter((option: { id: string }) => option.id !== "allow_all"), + config.map((option: { id: string }) => option.id === "allow_all" ? { ...option, currentValue: "on" } : option), + [...config, { id: "agent", currentValue: "privileged-agent" }], [...config, { id: "new-authority", currentValue: "off" }]]) { + expect(() => assertCopilotConfigPolicy(value)).toThrow(/admitted permission policy/); + } + }); + it("only permits selecting the admitted explicit model", () => { + expect(() => assertCopilotControlPolicy("session/set_model", { modelId: "gpt-5.6-luna" }, "gpt-5.6-luna")).not.toThrow(); + expect(() => assertCopilotControlPolicy("session/set_config_option", { configId: "model", value: "gpt-5.6-luna" }, "gpt-5.6-luna")).not.toThrow(); + for (const [method, params] of [["session/set_mode", { modeId: COPILOT_AGENT_MODE }], + ["session/set_config_option", { configId: "allow_all", value: "on" }], + ["session/set_config_option", { configId: "mode", value: COPILOT_AGENT_MODE }], + ["session/set_model", { modelId: "auto" }], ["session/set_model", { modelId: "other" }]] as const) { + expect(() => assertCopilotControlPolicy(method, params, "gpt-5.6-luna")).toThrow(/admitted permission policy/); + } + }); + it("rejects policy drift without logging provider strings", () => { + expect(() => assertCopilotSessionUpdatePolicy({ sessionUpdate: "current_mode_update", currentModeId: "secret-provider-value" })) + .toThrowError(expect.objectContaining({ message: expect.not.stringContaining("secret-provider-value") })); + expect(() => assertCopilotSessionUpdatePolicy({ sessionUpdate: "current_mode_update", currentModeId: COPILOT_AGENT_MODE })).not.toThrow(); + expect(() => assertCopilotSessionUpdatePolicy({ sessionUpdate: "config_option_update" })).toThrow(); + }); +}); + +describe("Copilot connection authority", () => { + const safe = { ...session, sessionId: "s", configOptions: [...session.configOptions, { id: "model", currentValue: "gpt-5.6-luna" }] }; + const request = (guard: ReturnType, method: string, params: unknown, id = 0) => guard("outbound", { jsonrpc: "2.0", id, method, params }); + const admit = (guard: ReturnType, method = "session/new") => { + request(guard, method, method === "session/new" ? {} : { sessionId: "s" }); + guard("inbound", { id: 0, result: safe }); + }; + it.each(["session/new", "session/load", "session/resume"])("requires fresh safe %s response on each connection", method => { + const guard = createCopilotProtocolGuard("gpt-5.6-luna"); + admit(guard, method); + expect(() => request(guard, "session/prompt", { sessionId: "s", prompt: [{ type: "text", text: "Complete task" }] }, 1)).not.toThrow(); + const reconnected = createCopilotProtocolGuard("gpt-5.6-luna"); + expect(() => request(reconnected, "session/prompt", { sessionId: "s", prompt: [{ type: "text", text: "Complete task" }] })).toThrow(); + }); + it("invalidates authority permanently when resumed policy or current policy drifts", () => { + for (const bad of [{ sessionUpdate: "current_mode_update", currentModeId: "autopilot" }, { sessionUpdate: "config_option_update", configOptions: [] }]) { + const guard = createCopilotProtocolGuard("gpt-5.6-luna"); admit(guard); + expect(() => guard("inbound", { method: "session/update", params: { sessionId: "s", update: bad } })).toThrow(); + expect(() => guard("inbound", { method: "session/update", params: { sessionId: "s", update: { sessionUpdate: "config_option_update", configOptions: safe.configOptions } } })).toThrow(); + } + }); + it("does not turn native unresolved input into delivered answers or successful continuation", () => { + for (const type of ["user_input.requested", "exit_plan_mode.requested", "elicitation.requested"]) { + const guard = createCopilotProtocolGuard("gpt-5.6-luna"); admit(guard); + expect(() => guard("inbound", { method: "github.com/copilot/sessionEvent", params: { sessionId: "s", type, data: { requestId: 0 } } })).toThrow(); + } + }); + it("requires the selected model before prompting, including reconnect", () => { + const guard = createCopilotProtocolGuard("gpt-5.6-luna"); request(guard, "session/load", { sessionId: "s" }); + guard("inbound", { id: 0, result: session }); + expect(() => request(guard, "session/prompt", { sessionId: "s", prompt: [{ type: "text", text: "Run" }] }, 1)).toThrow(); + }); + it("validates the joined wire text and preserves zero request IDs", () => { + const guard = createCopilotProtocolGuard("gpt-5.6-luna"); admit(guard); + expect(() => request(guard, "session/prompt", { sessionId: "s", prompt: [{ type: "text", text: " " }, { type: "text", text: "/yolo on" }] })).toThrow(); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-policy.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-policy.ts new file mode 100644 index 00000000000..51a892cd226 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-policy.ts @@ -0,0 +1,149 @@ +/** Policy for the exact native Copilot 1.0.88 ACP surface. */ +export const COPILOT_AGENT_MODE = "https://agentclientprotocol.com/protocol/session-modes#agent"; + +export class CopilotPolicyViolationError extends Error { + readonly code = "COPILOT_POLICY_VIOLATION"; + readonly retryable = false; + constructor() { + super("Copilot session configuration or command cannot preserve the admitted permission policy."); + this.name = "CopilotPolicyViolationError"; + } +} + +/** + * Native ACP interprets a leading slash as a CLI command, before inference. + * Reject every such command rather than maintaining an incomplete list of + * aliases/skills that can change mode, permissions, cwd, MCP or remote state. + * Apply to the final joined ACP text, including resumed prompts. + */ +export function assertCopilotPromptPolicy(text: string): void { + if (text.trimStart().startsWith("/")) throw new CopilotPolicyViolationError(); +} + +/** Only explicit model selection is a runner-owned configuration operation. */ +export function assertCopilotControlPolicy(method: string, params: unknown, expectedModel: string): void { + const input = record(params); + if (!expectedModel || expectedModel === "auto") throw new CopilotPolicyViolationError(); + if (method === "session/set_model" && input.modelId === expectedModel) return; + if (method === "session/set_config_option" && input.configId === "model" && input.value === expectedModel) return; + throw new CopilotPolicyViolationError(); +} + +/** + * Validate the actual new/load response on every connection, before prompting. + * Persisted ACPX status is insufficient: load can restore autopilot and turn + * allow-all back on inside the native server. Missing proof fails closed. + */ +export function assertCopilotSessionPolicy(response: unknown): void { + const state = record(response); + if (record(state.modes).currentModeId !== COPILOT_AGENT_MODE) throw new CopilotPolicyViolationError(); + assertCopilotConfigPolicy(state.configOptions); +} + +/** Copilot emits full config snapshots, not patches, in config_option_update. */ +export function assertCopilotConfigPolicy(value: unknown): void { + if (!Array.isArray(value) || value.length > 32) throw new CopilotPolicyViolationError(); + const options = new Map>(); + for (const candidate of value) { + const option = record(candidate); + if (typeof option.id !== "string" || options.has(option.id)) throw new CopilotPolicyViolationError(); + options.set(option.id, option); + if (!["mode", "allow_all", "model", "reasoning_effort", "agent"].includes(option.id)) throw new CopilotPolicyViolationError(); + if (option.id === "agent" && option.currentValue !== "") throw new CopilotPolicyViolationError(); + } + if (options.get("mode")?.currentValue !== COPILOT_AGENT_MODE || options.get("allow_all")?.currentValue !== "off") { + throw new CopilotPolicyViolationError(); + } +} + +/** Call synchronously for owned-session updates; any exception aborts authority. */ +export function assertCopilotSessionUpdatePolicy(value: unknown): void { + const update = record(value); + if (update.sessionUpdate === "current_mode_update" && update.currentModeId !== COPILOT_AGENT_MODE) { + throw new CopilotPolicyViolationError(); + } + if (update.sessionUpdate === "config_option_update") assertCopilotConfigPolicy(update.configOptions); +} + +/** One guard per actual stdio connection; never restore admission from disk. */ +export function createCopilotProtocolGuard(expectedModel: string): (direction: "inbound" | "outbound", value: unknown) => void { + const pending = new Map(); + const sessions = new Set(); + const models = new Map(); + const modelFrom = (result: unknown) => { + const options = record(result).configOptions; + return Array.isArray(options) ? record(options.find(option => record(option).id === "model")).currentValue : undefined; + }; + let failed = false; + return (direction, value) => { + if (failed) throw new CopilotPolicyViolationError(); + try { + const message = record(value); + const params = record(message.params); + const id = message.id; + const method = message.method; + if (direction === "outbound" && typeof method === "string") { + if (method.startsWith("session/") && !["session/new", "session/load", "session/resume"].includes(method)) { + if (typeof params.sessionId !== "string" || !sessions.has(params.sessionId)) throw new CopilotPolicyViolationError(); + } + if (method === "session/prompt") { + if (models.get(String(params.sessionId)) !== expectedModel) throw new CopilotPolicyViolationError(); + if (!Array.isArray(params.prompt) || params.prompt.some(block => record(block).type !== "text" || typeof record(block).text !== "string")) throw new CopilotPolicyViolationError(); + assertCopilotPromptPolicy(params.prompt.map(block => record(block).text).join("\n")); + } else if (method.startsWith("session/set_")) { + assertCopilotControlPolicy(method, params, expectedModel); + } else if (!["initialize", "authenticate", "session/new", "session/load", "session/resume", "session/cancel", "session/close"].includes(method)) { + throw new CopilotPolicyViolationError(); + } + if (typeof id === "string" || typeof id === "number") { + if (pending.has(id) || pending.size >= 128) throw new CopilotPolicyViolationError(); + pending.set(id, { method, ...(typeof params.sessionId === "string" ? { sessionId: params.sessionId } : {}) }); + } + } + if (direction === "inbound" && method === undefined && (typeof id === "string" || typeof id === "number")) { + const request = pending.get(id); + pending.delete(id); + if (request && message.error === undefined) { + if (["session/new", "session/load", "session/resume"].includes(request.method)) { + assertCopilotSessionPolicy(message.result); + const sessionId = request.sessionId ?? record(message.result).sessionId; + if (typeof sessionId !== "string" || !sessionId) throw new CopilotPolicyViolationError(); + sessions.add(sessionId); + models.set(sessionId, modelFrom(message.result)); + } else if (request.method === "session/set_config_option") { + assertCopilotConfigPolicy(record(message.result).configOptions); + if (request.sessionId) models.set(request.sessionId, modelFrom(message.result)); + } else if (request.method === "session/set_model" && request.sessionId) { + models.set(request.sessionId, expectedModel); + } else if (request.method === "session/close" && request.sessionId) sessions.delete(request.sessionId); + } + } + if (direction === "inbound" && method === "session/update") { + // Replay can precede load's response. It still cannot introduce unsafe + // configuration, and it cannot grant admission before that response. + assertCopilotSessionUpdatePolicy(params.update); + if (record(params.update).sessionUpdate === "config_option_update" && typeof params.sessionId === "string" && sessions.has(params.sessionId)) { + const model = modelFrom(params.update); + if (models.get(params.sessionId) === expectedModel && model !== expectedModel) throw new CopilotPolicyViolationError(); + models.set(params.sessionId, model); + } + } + if (direction === "inbound" && method === "github.com/copilot/sessionEvent") { + if (["user_input.requested", "exit_plan_mode.requested", "elicitation.requested"].includes(String(params.type))) throw new CopilotPolicyViolationError(); + const data = record(params.data); + if (params.type === "session.permissions_changed" && data.mode !== "manual") throw new CopilotPolicyViolationError(); + if (params.type === "session.mode_changed" && data.newMode !== "interactive" && data.newMode !== "agent") throw new CopilotPolicyViolationError(); + } + } catch { + failed = true; + sessions.clear(); + models.clear(); + pending.clear(); + throw new CopilotPolicyViolationError(); + } + }; +} + +function record(value: unknown): Record { + return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record : {}; +} diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-protocol-guard.test.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-protocol-guard.test.ts new file mode 100644 index 00000000000..2cc2bb36650 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-protocol-guard.test.ts @@ -0,0 +1,64 @@ +import { createRequire } from "node:module"; +import { pathToFileURL } from "node:url"; +import { describe, expect, it, vi } from "vitest"; +import { COPILOT_AGENT_MODE, createCopilotProtocolGuard } from "./copilot-policy.js"; + +// Exercise the installed, patched wire stream, not a mock observer. This is a +// pinned internal bundle export; the package-contract suite guards its version. +const bundle = new URL("./dist/live-checkpoint-BSIrfgVo.js", pathToFileURL(createRequire(import.meta.url).resolve("acpx/package.json"))); +const { k: AcpClient } = await import(bundle.href); +const safe = { sessionId: "s", modes: { currentModeId: COPILOT_AGENT_MODE }, configOptions: [ + { id: "mode", currentValue: COPILOT_AGENT_MODE }, { id: "allow_all", currentValue: "off" }, { id: "model", currentValue: "gpt-5.6-luna" }, +] }; + +function connection(guarded = true) { + const written: unknown[] = []; + let inbound!: ReadableStreamDefaultController; + const kill = vi.fn(); + const client = new AcpClient({ cwd: "/tmp", agentCommand: "fixture-never-spawned", permissionMode: "deny-all", + ...(guarded ? { protocolGuardFactory: () => createCopilotProtocolGuard("gpt-5.6-luna") } : {}), + }); + client.agent = { kill }; + const stream = client.createTappedStream({ + readable: new ReadableStream({ start(controller) { inbound = controller; } }), + writable: new WritableStream({ write(message) { written.push(message); } }), + }); + return { writer: stream.writable.getWriter(), reader: stream.readable.getReader(), inbound, written, kill }; +} + +describe("patched ACPX admission guard", () => { + it.each(["session/new", "session/load", "session/resume"])("rejects unsafe %s before it reaches the SDK", async method => { + const c = connection(); + await c.writer.write({ id: 0, method, params: { sessionId: "s" } }); + const read = c.reader.read(); + c.inbound.enqueue({ id: 0, result: { ...safe, modes: { currentModeId: "autopilot" } } }); + await expect(read).rejects.toMatchObject({ code: "COPILOT_POLICY_VIOLATION" }); + expect(c.kill).toHaveBeenCalledWith("SIGTERM"); + }); + it("rejects permission controls before any bytes reach the provider", async () => { + const c = connection(); + await c.writer.write({ id: 0, method: "session/new", params: {} }); + c.inbound.enqueue({ id: 0, result: safe }); await c.reader.read(); + await expect(c.writer.write({ id: 1, method: "session/set_config_option", params: { sessionId: "s", configId: "allow_all", value: "on" } })).rejects.toThrow(/admitted permission policy/); + expect(c.written).toHaveLength(1); expect(c.kill).toHaveBeenCalledOnce(); + c.inbound.close(); + }); + it("errors and stops the provider on drift even without a notification observer", async () => { + const c = connection(); + await c.writer.write({ id: 0, method: "session/new", params: {} }); + c.inbound.enqueue({ id: 0, result: safe }); await c.reader.read(); + await c.writer.write({ id: 1, method: "session/prompt", params: { sessionId: "s", prompt: [{ type: "text", text: "Perform task" }] } }); + const read = c.reader.read(); + c.inbound.enqueue({ method: "session/update", params: { sessionId: "s", update: { sessionUpdate: "current_mode_update", currentModeId: "autopilot" } } }); + await expect(read).rejects.toMatchObject({ code: "COPILOT_POLICY_VIOLATION" }); + expect(c.kill).toHaveBeenCalledWith("SIGTERM"); + }); + it("preserves unguarded provider wire behavior", async () => { + const c = connection(false); + const message = { method: "session/update", params: { update: { sessionUpdate: "current_mode_update", currentModeId: "other-provider-mode" } } }; + c.inbound.enqueue(message); + expect((await c.reader.read()).value).toEqual(message); + expect(c.kill).not.toHaveBeenCalled(); + c.inbound.close(); + }); +}); diff --git a/packages/paperclip-runner/test/fixtures/copilot-policy-conformance-2026-09-29.json b/packages/paperclip-runner/test/fixtures/copilot-policy-conformance-2026-09-29.json new file mode 100644 index 00000000000..4d99b27437f --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/copilot-policy-conformance-2026-09-29.json @@ -0,0 +1,126 @@ +{ + "schema": "paperclip.copilot-policy-conformance.v1", + "providerVersion": "1.0.88", + "platform": "darwin-arm64", + "executableSha256": "a9ff8babb10b7e443182ae96a8bc50a9c826ef1c773e1344c396eb5bf7f512c3", + "sourceBaseRevision": "9f4476feb87df5574edf121b86a1093efb006ac3", + "authentication": "none; explicit fresh environment contains no credential values", + "modelTransport": "COPILOT_OFFLINE=true; COPILOT_PROVIDER_TYPE=openai; COPILOT_PROVIDER_BASE_URL points only to ephemeral 127.0.0.1 Python HTTPServer; fixture model gpt-4.1 is synthetic", + "paidProviderCalls": 0, + "modelSpendUsd": 0, + "qualification": "offline protocol evidence only; no GitHub model, final pack, or Daytona qualification", + "attempts": [ + { + "evidenceFile": "agent-inputs.json", + "sha256": "3def3bcf95db103611722d5e04f803bed555c7c8274a1833c661ef9d87a4b757", + "scenario": "discover-inputs", + "mode": "agent", + "resumed": false, + "loopbackModelRequests": 1, + "nativeInputToolsAdvertised": [], + "forcedToolRejectedAsUnavailable": false, + "permissionRequestCount": 0, + "permissionRequestIds": [], + "markerPresent": false, + "rpcErrorCodes": [], + "disposition": "passed" + }, + { + "evidenceFile": "plan-inputs.json", + "sha256": "446ee3a2b9e5e4ac3249a8ae18a09f1c33fadc75f94a98d8c6f5fb50a8a73b61", + "scenario": "discover-inputs", + "mode": "plan", + "resumed": false, + "loopbackModelRequests": 1, + "nativeInputToolsAdvertised": [], + "forcedToolRejectedAsUnavailable": false, + "permissionRequestCount": 0, + "permissionRequestIds": [], + "markerPresent": false, + "rpcErrorCodes": [], + "disposition": "passed" + }, + { + "evidenceFile": "native-question.json", + "sha256": "1cdff42aa31e27a796ecceb4d4fea89c271737a0094982956bb228f03752e21d", + "scenario": "native-question", + "mode": "agent", + "resumed": false, + "loopbackModelRequests": 2, + "nativeInputToolsAdvertised": [], + "forcedToolRejectedAsUnavailable": true, + "permissionRequestCount": 0, + "permissionRequestIds": [], + "markerPresent": false, + "rpcErrorCodes": [], + "disposition": "passed" + }, + { + "evidenceFile": "native-plan.json", + "sha256": "fecfca013ea072e4e880c77b244b42843f25486206c2e8f64411216ad5c738ea", + "scenario": "native-plan", + "mode": "plan", + "resumed": false, + "loopbackModelRequests": 2, + "nativeInputToolsAdvertised": [], + "forcedToolRejectedAsUnavailable": true, + "permissionRequestCount": 0, + "permissionRequestIds": [], + "markerPresent": false, + "rpcErrorCodes": [], + "disposition": "passed" + }, + { + "evidenceFile": "deny-read.json", + "sha256": "88d1ad8865b3252963ce12178d6a3a3819f50a2c20ddf95ab557f1cacd127975", + "scenario": "deny-read", + "mode": "agent", + "resumed": false, + "loopbackModelRequests": 1, + "nativeInputToolsAdvertised": [], + "forcedToolRejectedAsUnavailable": false, + "permissionRequestCount": 1, + "permissionRequestIds": [ + 0 + ], + "markerPresent": false, + "rpcErrorCodes": [], + "disposition": "passed" + }, + { + "evidenceFile": "resumed-deny-shell.json", + "sha256": "3826ca1247b99c3000bff1e8e0e53d0244c0c22f8ec3089b6ca83bfba80ae3bb", + "scenario": "deny-shell", + "mode": "agent", + "resumed": true, + "loopbackModelRequests": 0, + "nativeInputToolsAdvertised": [], + "forcedToolRejectedAsUnavailable": false, + "permissionRequestCount": 0, + "permissionRequestIds": [], + "markerPresent": false, + "rpcErrorCodes": [ + -32002 + ], + "disposition": "probe_setup_failure" + }, + { + "evidenceFile": "resumed-deny-shell-attempt-2.json", + "sha256": "14bdd262303d9273c3612d502fefb4b6f887ce903af590a58bbaea3e00297ff6", + "scenario": "deny-shell", + "mode": "agent", + "resumed": true, + "loopbackModelRequests": 2, + "nativeInputToolsAdvertised": [], + "forcedToolRejectedAsUnavailable": false, + "permissionRequestCount": 1, + "permissionRequestIds": [ + 0 + ], + "markerPresent": false, + "rpcErrorCodes": [], + "disposition": "passed" + } + ], + "emptySessionLoadDiagnosis": "Copilot does not retain an empty conversation for load. Initial resource-not-found retained; second attempt seeds one loopback-only text turn before close/load. It then requests shell permission and rejects the write." +} diff --git a/patches/acpx@0.13.1.patch b/patches/acpx@0.13.1.patch index b61fdb87cd6..87d0ba1bdc0 100644 --- a/patches/acpx@0.13.1.patch +++ b/patches/acpx@0.13.1.patch @@ -1,5 +1,5 @@ diff --git a/dist/client-CxNllqui.d.ts b/dist/client-CxNllqui.d.ts -index 5e2113ac0..45aff03c3 100644 +index 5e2113a..45aff03 100644 --- a/dist/client-CxNllqui.d.ts +++ b/dist/client-CxNllqui.d.ts @@ -120,6 +120,8 @@ declare class AcpClient { @@ -20,7 +20,7 @@ index 5e2113ac0..45aff03c3 100644 private setSessionModelThroughConfig; private setSessionModelThroughLegacyMethod; diff --git a/dist/live-checkpoint-BSIrfgVo.js b/dist/live-checkpoint-BSIrfgVo.js -index d454fd7c5..330b80394 100644 +index d454fd7..bf3a537 100644 --- a/dist/live-checkpoint-BSIrfgVo.js +++ b/dist/live-checkpoint-BSIrfgVo.js @@ -1068,6 +1068,7 @@ function serializeSessionRecordForDisk(record) { @@ -268,10 +268,22 @@ index d454fd7c5..330b80394 100644 clientInfo: resolveClientInfo(launch.devinAcp) }); const initialized = launch.geminiAcp ? await withTimeout(initializePromise, resolveGeminiAcpStartupTimeoutMs()) : await initializePromise; -@@ -4358,6 +4430,36 @@ var AcpClient = class { +@@ -4358,6 +4430,48 @@ var AcpClient = class { throw normalizedError; } createTappedStream(base) { ++ // Policy admission is distinct from best-effort observation. Each new ++ // stdio connection gets fresh authority and a violation tears it down. ++ const protocolGuard = this.options.protocolGuardFactory?.(); ++ const enforceProtocol = (direction, message) => { ++ try { protocolGuard?.(direction, message); } ++ catch (error) { ++ abortResponseDeliveries(); ++ this.activePrompt?.elicitationController.abort(error); ++ try { this.agent?.kill("SIGTERM"); } catch {} ++ throw error; ++ } ++ }; + const deliveries = new Map(); + const scope = new AbortController(); + const abortResponseDeliveries = () => scope.abort(new Error("ACP response connection closed before delivery")); @@ -305,7 +317,7 @@ index d454fd7c5..330b80394 100644 const onAcpMessage = () => this.eventHandlers.onAcpMessage; const onAcpOutputMessage = () => this.eventHandlers.onAcpOutputMessage; const elicitationRequestIds = /* @__PURE__ */ new Set(); -@@ -4367,8 +4469,12 @@ var AcpClient = class { +@@ -4367,8 +4481,12 @@ var AcpClient = class { const shouldSuppressInboundReplaySessionUpdate = (message) => { return this.suppressReplaySessionUpdateMessages && isSessionUpdateNotification(message); }; @@ -319,7 +331,7 @@ index d454fd7c5..330b80394 100644 if (requestId !== void 0) { elicitationRequestIds.add(requestId); return; -@@ -4379,6 +4485,7 @@ var AcpClient = class { +@@ -4379,6 +4497,7 @@ var AcpClient = class { } }; return { @@ -327,9 +339,11 @@ index d454fd7c5..330b80394 100644 readable: new ReadableStream({ async start(controller) { const reader = base.readable.getReader(); try { -@@ -4387,10 +4494,17 @@ var AcpClient = class { +@@ -4386,16 +4505,27 @@ var AcpClient = class { + const { value, done } = await reader.read(); if (done) break; if (!value) continue; ++ enforceProtocol("inbound", value); observeInbound(value); - if (isExtensionNotification(value)) continue; + if (onCursorSubagentNotification(value)) continue; @@ -339,14 +353,23 @@ index d454fd7c5..330b80394 100644 + } controller.enqueue(value); } ++ controller.close(); ++ } catch (error) { ++ controller.error(error); } finally { + abortResponseDeliveries(); + for (const receipt of deliveries.values()) receipt.cleanup(); + deliveries.clear(); reader.releaseLock(); - controller.close(); +- controller.close(); } -@@ -4403,10 +4517,20 @@ var AcpClient = class { + } }), + writable: new WritableStream({ async write(message) { ++ enforceProtocol("outbound", message); + const promptOwner = promptRequestOwner(message); + if (promptOwner) bindPromptOwner(promptOwner); + const id = responseId(message); +@@ -4403,10 +4533,20 @@ var AcpClient = class { onAcpOutputMessage()?.("outbound", message); onAcpMessage()?.("outbound", message); } @@ -367,7 +390,7 @@ index d454fd7c5..330b80394 100644 writer.releaseLock(); } } }) -@@ -4422,7 +4546,10 @@ var AcpClient = class { +@@ -4422,7 +4562,10 @@ var AcpClient = class { const createPromise = this.runConnectionRequest(() => connection.newSession({ cwd: sessionCwd, mcpServers: this.options.mcpServers ?? [], @@ -379,7 +402,7 @@ index d454fd7c5..330b80394 100644 })); result = claudeAcp ? await withTimeout(createPromise, resolveClaudeAcpSessionCreateTimeoutMs()) : await createPromise; } catch (error) { -@@ -4864,7 +4991,7 @@ var AcpClient = class { +@@ -4864,7 +5007,7 @@ var AcpClient = class { } selectAuthMethod(methods) { for (const method of methods) { @@ -388,7 +411,7 @@ index d454fd7c5..330b80394 100644 if (envCredential) return { methodId: method.id, credential: envCredential, -@@ -4890,7 +5017,7 @@ var AcpClient = class { +@@ -4890,7 +5033,7 @@ var AcpClient = class { } readAgentSpecificEnvCredential(methodId) { if (!this.isGrokBuildAcpCommand() || methodId !== "xai.api_key") return; @@ -397,7 +420,7 @@ index d454fd7c5..330b80394 100644 return typeof value === "string" && value.trim().length > 0 ? value : void 0; } selectAgentManagedAuthMethod(methodId) { -@@ -4915,9 +5042,9 @@ var AcpClient = class { +@@ -4915,9 +5058,9 @@ var AcpClient = class { await connection.authenticate({ methodId: selected.methodId }); this.log(`authenticated with method ${selected.methodId} (${selected.source})`); } @@ -409,7 +432,7 @@ index d454fd7c5..330b80394 100644 if (hostResponse) return hostResponse; const { response, recorded } = await this.resolvePermissionRequestFromMode(params); if (!recorded) { -@@ -4926,14 +5053,81 @@ var AcpClient = class { +@@ -4926,14 +5069,81 @@ var AcpClient = class { } return response; } @@ -493,7 +516,7 @@ index d454fd7c5..330b80394 100644 })).then((response) => ({ kind: "response", response -@@ -4970,7 +5164,7 @@ var AcpClient = class { +@@ -4970,7 +5180,7 @@ var AcpClient = class { isElicitationSessionCancelling(sessionId) { return this.closing || this.cancellingSessionIds.has(sessionId); } @@ -502,7 +525,7 @@ index d454fd7c5..330b80394 100644 if (!this.options.onPermissionRequest) return; const signal = this.cancellationSignalForSession(params.sessionId); try { -@@ -4978,7 +5172,7 @@ var AcpClient = class { +@@ -4978,7 +5188,7 @@ var AcpClient = class { sessionId: params.sessionId, raw: params, inferredKind: inferToolKind(params) @@ -511,7 +534,7 @@ index d454fd7c5..330b80394 100644 return this.hostPermissionDecisionResponse(params, signal, decision); } catch (error) { return this.hostPermissionErrorResponse(params, signal, error); -@@ -5028,6 +5222,12 @@ var AcpClient = class { +@@ -5028,6 +5238,12 @@ var AcpClient = class { attachAgentLifecycleObservers(child) { child.once("exit", (exitCode, signal) => { this.recordAgentExit("process_exit", exitCode, signal); @@ -524,7 +547,7 @@ index d454fd7c5..330b80394 100644 }); child.once("close", (exitCode, signal) => { this.recordAgentExit("process_close", exitCode, signal); -@@ -5771,10 +5971,20 @@ function recordSessionUpdate(conversation, state, notification, timestamp = isoN +@@ -5771,10 +5987,20 @@ function recordSessionUpdate(conversation, state, notification, timestamp = isoN trimConversationForRuntime(conversation); return acpx; } @@ -547,7 +570,7 @@ index d454fd7c5..330b80394 100644 updateConversationTimestamp(conversation, timestamp); trimConversationForRuntime(conversation); return true; -@@ -6435,6 +6645,27 @@ async function withConnectedSession(options) { +@@ -6435,6 +6661,27 @@ async function withConnectedSession(options) { //#region src/runtime/engine/prompt-turn.ts const SESSION_REPLY_IDLE_MS = 1e3; const SESSION_REPLY_DRAIN_TIMEOUT_MS = 5e3; @@ -575,7 +598,7 @@ index d454fd7c5..330b80394 100644 async function runPromptTurn(params) { try { const promptPromise = params.client.prompt(params.sessionId, params.prompt, params.onPromptRequestStarted, params.onElicitation); -@@ -6444,7 +6675,21 @@ async function runPromptTurn(params) { +@@ -6444,7 +6691,21 @@ async function runPromptTurn(params) { idleMs: SESSION_REPLY_IDLE_MS, timeoutMs: SESSION_REPLY_DRAIN_TIMEOUT_MS }).catch(() => {}); @@ -597,7 +620,7 @@ index d454fd7c5..330b80394 100644 return { stopReason: response.stopReason, source: "rpc" -@@ -6518,4 +6763,4 @@ var LiveSessionCheckpoint = class { +@@ -6518,4 +6779,4 @@ var LiveSessionCheckpoint = class { //#endregion export { writeSessionRecord as $, PERMISSION_POLICY_ACTIONS as $t, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE as A, TimeoutError as At, getAcpxVersion as B, formatErrorMessage as Bt, mergeSessionOptions as C, PromptInputValidationError as Ct, applyLifecycleSnapshotToRecord as D, promptToDisplayText as Dt, applyConversation as E, parsePromptSource as Et, modelStateFromConfigOptions as F, normalizeAgentName$1 as Ft, findSession as G, toAcpErrorPayload as Gt, DEFAULT_HISTORY_LIMIT as H, normalizeOutputError as Ht, normalizeAgentCommandInput as I, resolveAgentArgv as It, listSessions as J, NON_INTERACTIVE_PERMISSION_POLICIES as Jt, findSessionByDirectoryWalk as K, AUTH_POLICIES as Kt, renderArgvIdentity as L, resolveAgentCommand as Lt, RequestedModelUnsupportedError as M, withTimeout as Mt, assertRequestedModelSupported as N, DEFAULT_AGENT_NAME as Nt, reconcileAgentSessionId as O, textPrompt as Ot, isRequestedModelUnsupportedError as P, listBuiltInAgents as Pt, resolveSessionRecord as Q, PERMISSION_MODES as Qt, runTimedExecFile as R, resolveCanonicalAgentName as Rt, advertisedModelState as S, parsePromptStopReason as St, sessionOptionsFromRecord as T, mergePromptSourceWithText as Tt, absolutePath as U, extractAcpError as Ut, permissionModeSatisfies as V, isRetryablePromptError as Vt, findGitRepositoryRoot as W, isAcpResourceNotFoundError as Wt, normalizeName as X, OUTPUT_ERROR_ORIGINS as Xt, listSessionsForAgent as Y, OUTPUT_ERROR_CODES as Yt, pruneSessions as Z, OUTPUT_FORMATS as Zt, createSessionConversation as _, sessionEventLockPath as _t, applyRequestedModelIfAdvertised as a, measurePerf as at, recordSessionUpdate as b, isAcpJsonRpcMessage as bt, setCurrentModelId as c, setPerfGauge as ct, setDesiredModelId as d, serializeSessionRecordForDisk as dt, SESSION_RECORD_SCHEMA as en, createAtomicWriteTempPath as et, syncAdvertisedModelState as f, normalizeRuntimeSessionId as ft, cloneSessionConversation as g, sessionEventActivePath as gt, cloneSessionAcpxState as h, sessionBaseDir$1 as ht, connectAndLoadSession as i, QueueProtocolError as in, incrementPerfCounter as it, REQUESTED_MODEL_UNSUPPORTED_REASONS as j, withInterrupt as jt, AcpClient as k, InterruptedError as kt, setDesiredConfigOption as l, startPerfTimer as lt, applyConfigOptionsToState as m, defaultSessionEventLog as mt, runPromptTurn as n, AgentSpawnError as nn, formatPerfMetric as nt, currentModelIdFromSetModelResponse as o, recordPerfDuration as ot, applyConfigOptionsToRecord as p, DEFAULT_EVENT_SEGMENT_MAX_BYTES as pt, isoNow$2 as q, EXIT_CODES as qt, withConnectedSession as r, QueueConnectionError as rn, getPerfMetricsSnapshot as rt, clearDesiredConfigOption as s, resetPerfMetrics as st, LiveSessionCheckpoint as t, AcpxOperationalError as tn, assertPersistedKeyPolicy as tt, setDesiredModeId as u, parseSessionRecord as ut, recordClientOperation as v, sessionEventSegmentPath as vt, persistSessionOptions as w, isPromptInput as wt, trimConversationForRuntime as x, parseJsonRpcErrorMessage as xt, recordPromptSubmission as y, extractSessionUpdateNotification as yt, splitCommandLine as z, exitCodeForOutputErrorCode as zt }; @@ -605,7 +628,7 @@ index d454fd7c5..330b80394 100644 \ No newline at end of file +//# sourceMappingURL=live-checkpoint-BSIrfgVo.js.map diff --git a/dist/runtime.d.ts b/dist/runtime.d.ts -index e8102acb0..d3a9ba626 100644 +index e8102ac..377c5d8 100644 --- a/dist/runtime.d.ts +++ b/dist/runtime.d.ts @@ -1,7 +1,8 @@ @@ -649,7 +672,7 @@ index e8102acb0..d3a9ba626 100644 } | { type: "tool_call"; text: string; -@@ -312,7 +323,49 @@ type AcpRuntimeOptions = { +@@ -312,7 +323,51 @@ type AcpRuntimeOptions = { elicitationModes?: readonly AcpElicitationMode[]; onPermissionRequest?: (req: AcpPermissionRequest, ctx: { signal: AbortSignal; @@ -685,6 +708,8 @@ index e8102acb0..d3a9ba626 100644 + signal: NodeJS.Signals | null; + exitedAt: string; + }) => void; ++ /** Synchronous admission guard. Exceptions fail the connection, never an observer. */ ++ protocolGuardFactory?: () => (direction: "inbound" | "outbound", message: unknown) => void; + onAcpMessage?: (direction: "inbound" | "outbound", message: unknown) => void; + /** Ephemeral full ACP notification callback; never written to session records. */ + onSessionNotification?: (notification: SessionNotification) => void; @@ -699,7 +724,7 @@ index e8102acb0..d3a9ba626 100644 }; type AcpFileSessionStoreOptions = { stateDir: string; -@@ -369,6 +422,7 @@ declare class AcpRuntimeManager { +@@ -369,6 +424,7 @@ declare class AcpRuntimeManager { private createAndSaveRuntimeRecord; private retainInitializedSessionOwner; startTurn(input: { @@ -707,7 +732,7 @@ index e8102acb0..d3a9ba626 100644 handle: AcpRuntimeHandle; text: string; attachments?: AcpRuntimeTurnAttachment[]; -@@ -414,6 +468,7 @@ declare class AcpRuntimeManager { +@@ -414,6 +470,7 @@ declare class AcpRuntimeManager { private cleanupRuntimeTurn; private finalizeRuntimeTurnRecord; runTurn(input: { @@ -716,7 +741,7 @@ index e8102acb0..d3a9ba626 100644 text: string; attachments?: AcpRuntimeTurnAttachment[]; diff --git a/dist/runtime.js b/dist/runtime.js -index a1f4a70a0..fe2484de6 100644 +index a1f4a70..09f659b 100644 --- a/dist/runtime.js +++ b/dist/runtime.js @@ -371,7 +371,7 @@ const PROMPT_EVENT_PARSERS = { @@ -763,7 +788,7 @@ index a1f4a70a0..fe2484de6 100644 function normalizeUsageCost(value) { if (!isRecord(value)) return; const amount = asOptionalFiniteNumber(value.amount); -@@ -812,7 +840,21 @@ var AcpRuntimeManager = class { +@@ -812,7 +840,22 @@ var AcpRuntimeManager = class { this.deps = deps; } createClient(options) { @@ -778,6 +803,7 @@ index a1f4a70a0..fe2484de6 100644 + onAgentExit: this.options.onAgentExit, + onAcpMessage: this.options.onAcpMessage, + clientCapabilities: this.options.clientCapabilities, ++ protocolGuardFactory: this.options.protocolGuardFactory, + extensionMethods: this.options.extensionMethods, + onExtensionRequest: this.options.onExtensionRequest, + onExtensionNotification: this.options.onExtensionNotification @@ -786,7 +812,7 @@ index a1f4a70a0..fe2484de6 100644 } createSessionOwner(input) { const owner = { -@@ -821,12 +863,16 @@ var AcpRuntimeManager = class { +@@ -821,12 +864,16 @@ var AcpRuntimeManager = class { pendingSessionUpdates: [] }; input.client.setEventHandlers({ @@ -803,7 +829,7 @@ index a1f4a70a0..fe2484de6 100644 const active = owner.activeTurn; if (active) { const { task, turn } = active; -@@ -863,6 +909,9 @@ var AcpRuntimeManager = class { +@@ -863,6 +910,9 @@ var AcpRuntimeManager = class { projection.checkpoint.request(); } routeOwnedClientOperation(owner, operation) { @@ -813,7 +839,7 @@ index a1f4a70a0..fe2484de6 100644 const active = owner.activeTurn; if (!active) return; const { task, turn } = active; -@@ -1008,6 +1057,8 @@ var AcpRuntimeManager = class { +@@ -1008,6 +1058,8 @@ var AcpRuntimeManager = class { record.closedAt = void 0; record.protocolVersion = owner.client.initializeResult?.protocolVersion; record.agentCapabilities = owner.client.initializeResult?.agentCapabilities; @@ -822,7 +848,7 @@ index a1f4a70a0..fe2484de6 100644 applyLifecycleSnapshotToRecord(record, owner.client.getAgentLifecycleSnapshot()); } async finishBufferedOwnerControl(owner, record) { -@@ -1086,6 +1137,11 @@ var AcpRuntimeManager = class { +@@ -1086,6 +1138,11 @@ var AcpRuntimeManager = class { record.closed = false; record.closedAt = void 0; this.closingActiveRecords.delete(record.acpxRecordId); @@ -834,7 +860,7 @@ index a1f4a70a0..fe2484de6 100644 await this.options.sessionStore.save(record); return record; } -@@ -1149,6 +1205,8 @@ var AcpRuntimeManager = class { +@@ -1149,6 +1206,8 @@ var AcpRuntimeManager = class { this.closingActiveRecords.delete(record.acpxRecordId); record.protocolVersion = client.initializeResult?.protocolVersion; record.agentCapabilities = client.initializeResult?.agentCapabilities; @@ -843,7 +869,7 @@ index a1f4a70a0..fe2484de6 100644 applyConfigOptionsToRecord(record, session.sessionResult); const modelApplication = await applyRequestedModelIfAdvertised({ client, -@@ -1301,6 +1359,7 @@ var AcpRuntimeManager = class { +@@ -1301,6 +1360,7 @@ var AcpRuntimeManager = class { client: turn.client, sessionId, prompt: task.promptInput, @@ -851,7 +877,7 @@ index a1f4a70a0..fe2484de6 100644 timeoutMs: task.input.timeoutMs ?? this.options.timeoutMs, conversation: turn.conversation, promptMessageId: turn.promptMessageId, -@@ -1469,6 +1528,10 @@ var AcpRuntimeManager = class { +@@ -1469,6 +1529,10 @@ var AcpRuntimeManager = class { setSessionConfigOption: async (configId, value) => { return (await task.state.activeController.setResolvedSessionConfigOption(configId, value)).response; }, @@ -862,7 +888,7 @@ index a1f4a70a0..fe2484de6 100644 setResolvedSessionConfigOption: async (configId, value) => await this.setRuntimeResolvedSessionConfigOption(task, turn, configId, value) }; } -@@ -1575,6 +1638,8 @@ var AcpRuntimeManager = class { +@@ -1575,6 +1639,8 @@ var AcpRuntimeManager = class { reconcileAgentSessionId(turn.record, turn.record.agentSessionId); turn.record.protocolVersion = turn.client.initializeResult?.protocolVersion; turn.record.agentCapabilities = turn.client.initializeResult?.agentCapabilities; @@ -871,7 +897,7 @@ index a1f4a70a0..fe2484de6 100644 turn.record.acpx = turn.acpxState; applyConversation(turn.record, turn.conversation); applyLifecycleSnapshotToRecord(turn.record, turn.client.getAgentLifecycleSnapshot()); -@@ -1707,6 +1772,17 @@ var AcpRuntimeManager = class { +@@ -1707,6 +1773,17 @@ var AcpRuntimeManager = class { }); await this.options.sessionStore.save(result.record); } @@ -889,7 +915,7 @@ index a1f4a70a0..fe2484de6 100644 async cancel(handle) { await this.activeControllers.get(handle.acpxRecordId ?? handle.sessionKey)?.requestCancelActivePrompt(); } -@@ -2055,6 +2131,7 @@ var AcpxRuntime = class { +@@ -2055,6 +2132,7 @@ var AcpxRuntime = class { const turnPromise = this.getManager().then((manager) => manager.startTurn({ handle, text: input.text, @@ -897,7 +923,7 @@ index a1f4a70a0..fe2484de6 100644 attachments: input.attachments, mode: input.mode, sessionMode: state.mode, -@@ -2087,6 +2164,7 @@ var AcpxRuntime = class { +@@ -2087,6 +2165,7 @@ var AcpxRuntime = class { yield* (await this.getManager()).runTurn({ handle, text: input.text, @@ -905,7 +931,7 @@ index a1f4a70a0..fe2484de6 100644 attachments: input.attachments, mode: input.mode, sessionMode: state.mode, -@@ -2119,6 +2197,14 @@ var AcpxRuntime = class { +@@ -2119,6 +2198,14 @@ var AcpxRuntime = class { const { handle, state } = this.resolveManagerHandle(input.handle); await (await this.getManager()).setConfigOption(handle, input.key, input.value, state.mode); } @@ -920,7 +946,7 @@ index a1f4a70a0..fe2484de6 100644 async cancel(input) { const { handle } = this.resolveManagerHandle(input.handle); await (await this.getManager()).cancel(handle); -@@ -2178,4 +2264,4 @@ function createRuntimeStore(options) { +@@ -2178,4 +2265,4 @@ function createRuntimeStore(options) { //#endregion export { ACPX_BACKEND_ID, AcpRuntimeError, AcpxRuntime, DEFAULT_AGENT_NAME, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE, REQUESTED_MODEL_UNSUPPORTED_REASONS, RequestedModelUnsupportedError, createAcpRuntime, createAgentRegistry, createFileSessionStore, createRuntimeStore, decodeAcpxRuntimeHandleState, encodeAcpxRuntimeHandleState, isAcpRuntimeError, isRequestedModelUnsupportedError }; @@ -928,7 +954,7 @@ index a1f4a70a0..fe2484de6 100644 \ No newline at end of file +//# sourceMappingURL=runtime.js.map diff --git a/dist/session-options-DwRDODlr.d.ts b/dist/session-options-DwRDODlr.d.ts -index c3da16452..5ccc8dda1 100644 +index c3da164..05030ec 100644 --- a/dist/session-options-DwRDODlr.d.ts +++ b/dist/session-options-DwRDODlr.d.ts @@ -1,4 +1,5 @@ @@ -946,7 +972,7 @@ index c3da16452..5ccc8dda1 100644 }; type AcpElicitationResponseMeta = { _meta?: Record | null; -@@ -116,6 +119,35 @@ type AcpClientOptions = { +@@ -116,6 +119,37 @@ type AcpClientOptions = { }; env?: Record; }; @@ -979,10 +1005,12 @@ index c3da16452..5ccc8dda1 100644 + signal: NodeJS.Signals | null; + exitedAt: string; + }) => void; ++ /** Synchronous admission guard. Exceptions fail the connection, never an observer. */ ++ protocolGuardFactory?: () => (direction: "inbound" | "outbound", message: unknown) => void; onAcpMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void; onAcpOutputMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void; onSessionUpdate?: (notification: SessionNotification) => void; -@@ -123,6 +155,8 @@ type AcpClientOptions = { +@@ -123,6 +157,8 @@ type AcpClientOptions = { onPermissionEscalation?: (event: PermissionEscalationEvent) => void; onPermissionRequest?: (req: AcpPermissionRequest, ctx: { signal: AbortSignal; @@ -991,7 +1019,7 @@ index c3da16452..5ccc8dda1 100644 }) => Promise; }; declare const SESSION_RECORD_SCHEMA: "acpx.session.v1"; -@@ -263,12 +297,15 @@ type SessionRecord = { +@@ -263,12 +299,15 @@ type SessionRecord = { lastAgentDisconnectReason?: string; protocolVersion?: number; agentCapabilities?: AgentCapabilities; @@ -1008,7 +1036,7 @@ index c3da16452..5ccc8dda1 100644 acpx?: SessionAcpxState; importedFrom?: SessionImportedFrom; }; -@@ -295,4 +332,4 @@ type SessionAgentOptions = { +@@ -295,4 +334,4 @@ type SessionAgentOptions = { }; //#endregion export { SessionRecord as _, AcpElicitationHandler as a, AcpElicitationResponse as c, AuthPolicy as d, McpServer$1 as f, PermissionStats as g, PermissionPolicy as h, AcpElicitationContext as i, AcpPermissionDecision as l, PermissionMode as m, SystemPromptOption as n, AcpElicitationMode as o, NonInteractivePermissionPolicy as p, AcpClientOptions as r, AcpElicitationRequest as s, SessionAgentOptions as t, AcpPermissionRequest as u, PromptInput as v }; From c368b73dd677358b56ba06847dc67b4a1117458a Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 29 Sep 2026 09:46:12 -0500 Subject: [PATCH 4/6] Clarify Cursor admission and patched runtime isolation boundaries Co-Authored-By: Paperclip --- .../src/drivers/acpx/cursor-launch-policy.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/paperclip-runner/src/drivers/acpx/cursor-launch-policy.ts b/packages/paperclip-runner/src/drivers/acpx/cursor-launch-policy.ts index 19dfa2f6d98..c0523bc3431 100644 --- a/packages/paperclip-runner/src/drivers/acpx/cursor-launch-policy.ts +++ b/packages/paperclip-runner/src/drivers/acpx/cursor-launch-policy.ts @@ -17,10 +17,11 @@ export function cursorPrivateEnvironment(paths: { agentHomeDirectory: string; da } /** - * Cursor's disable-project-configs flag covers cli.json only. Its MCP/hook - * loaders still read these paths. Refuse ambient execution configuration rather - * than mutating the user's project. The host must protect these paths throughout - * the run and keep the same check on recovery; admission alone is not a sandbox. + * The vendor's disable-project-configs flag covers cli.json only. Keep this + * admission refusal as defense in depth without mutating the user's project. + * The separately verified paperclip-cursor-isolation-v1 distribution removes + * ambient MCP and hook discovery at its source for the entire session. This + * check alone is not continuous filesystem protection or an OS sandbox. */ export async function assertCursorWorkspacePolicy(workspacePath: string, platform: NodeJS.Platform = process.platform): Promise { const paths: Array<{ path: string; inspectClaude?: boolean }> = []; From 526081b9d6c905de5e2da680e3a37c620899b380 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 29 Sep 2026 09:46:57 -0500 Subject: [PATCH 5/6] Version patched Cursor isolation as profile v3 Co-Authored-By: Paperclip --- .../runner-cursor-capabilities.md | 2 +- .../scripts/candidate-provider-pack.mjs | 2 +- .../src/drivers/acpx/qualified-profiles.ts | 4 +- .../cursor-acp/profile-v3-identity.json | 43 +++++++++++++++++++ 4 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 packages/paperclip-runner/test/fixtures/cursor-acp/profile-v3-identity.json diff --git a/doc/architecture/runner-cursor-capabilities.md b/doc/architecture/runner-cursor-capabilities.md index cbaadb2e709..9ed1201020c 100644 --- a/doc/architecture/runner-cursor-capabilities.md +++ b/doc/architecture/runner-cursor-capabilities.md @@ -88,7 +88,7 @@ Three real ACP stream tests prove child lifecycle/transcript preservation before The full `build-provider-pack.mjs --candidate-providers=cursor` path passed on source `25fb1b5b317e52a8ad50208d7681a1ee34bd939c` (foundation includes upstream master `18e8c121d`). It used standalone Node, pnpm 9.15.4, a fresh production deployment and the pinned vendor archive. The build checked portable Node relocation, fresh ACPX import and complete Cursor materialization. The retained manifest is `packages/paperclip-runner/test/fixtures/cursor-acp/provider-pack-darwin-arm64.json`; it contains only relative paths and digests. - Pack digest: `sha256:38bc6dd39c13b0f5478a1018e26deb61b0333ab0242f3d857e3c79d3a34b7682`. -- Cursor declaration: `sha256:1157a5d071abbd57ab132f22bace75c65e84cc47a045b0023475488755e14899`. +- Cursor declaration: `sha256:c91aa592ec867071ec4457b9b7230399ce42ad918787ceed99b4b651ea5607e2`. - macOS ARM64 closure: `sha256:77394184a89b0e7384971181da19c3c82d83a399b04e7944b3f94fe3d7e62b25`. - Resolved dependency lock: `sha256:9eea60187c6c808efb4d936a234a8d8000beac45253091abd4c5348132bd1408`, also the reviewed Daytona build digest for this branch. This digest was resolved from the clean tracked lock with the exact Docker resolution-only command. A second resolution from the clean tracked lock produced the identical digest; the frozen install applied the Cursor/Grok combined patch successfully. The image consumes the reviewed resolved-lock artifact without registry resolution. Image creation rejects a different digest before execution. diff --git a/packages/paperclip-runner/scripts/candidate-provider-pack.mjs b/packages/paperclip-runner/scripts/candidate-provider-pack.mjs index 3d2f73f16c8..cb0b5bb44a8 100644 --- a/packages/paperclip-runner/scripts/candidate-provider-pack.mjs +++ b/packages/paperclip-runner/scripts/candidate-provider-pack.mjs @@ -22,7 +22,7 @@ export async function materializeCandidateProviderPack({ provider, outputRoot }) if (provider === "cursor") { const result = await materializePinnedCursorDistribution({ destination: outputRoot }); return { version: result.version, - profileDigest: "sha256:1157a5d071abbd57ab132f22bace75c65e84cc47a045b0023475488755e14899", + profileDigest: "sha256:c91aa592ec867071ec4457b9b7230399ce42ad918787ceed99b4b651ea5607e2", closureDigest: `sha256:${result.closureSha256}` }; } throw new Error(`The ${provider} candidate distribution builder is not included in this source revision`); diff --git a/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts index b7b5f398987..1d88bf14da1 100644 --- a/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts +++ b/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts @@ -60,10 +60,10 @@ export const QUALIFIED_ACPX_PROFILES: Readonly< }, cursor: { driverKind: ACPX_DRIVER_KIND, protocolVersion: ACPX_DRIVER_PROTOCOL_VERSION, - acpxVersion: QUALIFIED_ACPX_VERSION, agent: "cursor", agentProfileVersion: 2, + acpxVersion: QUALIFIED_ACPX_VERSION, agent: "cursor", agentProfileVersion: 3, agentServerPackage: "cursor-agent", agentServerVersion: "2026.09.26-dd393fe", agentRuntimePackage: null, agentRuntimeVersion: null, - commandDigest: "sha256:1157a5d071abbd57ab132f22bace75c65e84cc47a045b0023475488755e14899", + commandDigest: "sha256:c91aa592ec867071ec4457b9b7230399ce42ad918787ceed99b4b651ea5607e2", // Authenticated discovery has not established a qualification model. Never // turn this empty declaration into a default; callers must select an ID. qualificationModel: "", reportedModelId: "", permissionPolicy: "interactive", diff --git a/packages/paperclip-runner/test/fixtures/cursor-acp/profile-v3-identity.json b/packages/paperclip-runner/test/fixtures/cursor-acp/profile-v3-identity.json new file mode 100644 index 00000000000..8389de78c23 --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/cursor-acp/profile-v3-identity.json @@ -0,0 +1,43 @@ +{ + "commandDigest": "sha256:c91aa592ec867071ec4457b9b7230399ce42ad918787ceed99b4b651ea5607e2", + "declaration": { + "schema": "paperclip.acpx_profile_declaration.v1", + "agent": "cursor", + "agentProfileVersion": 3, + "acpxVersion": "0.13.1", + "agentServerVersion": "2026.09.26-dd393fe", + "patchVersion": "paperclip-cursor-isolation-v1", + "distribution": { + "schema": "paperclip.cursor_distribution.v1", + "version": "2026.09.26-dd393fe", + "platforms": { + "darwin-arm64": { + "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/darwin/arm64/agent-cli-package.tar.gz", + "archiveSha256": "538827d96a779bab854a865c8e42859e8e87db34b5f69770261b90fc8cfff191", + "closureSha256": "8a22016ca832ef8c8e6a83b955208d74c63f2c8dbe1dd688cbf27b81ad01886a", + "executable": "node", + "entrypoint": "index.js", + "vendorClosureSha256": "77394184a89b0e7384971181da19c3c82d83a399b04e7944b3f94fe3d7e62b25" + }, + "darwin-x64": { + "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/darwin/x64/agent-cli-package.tar.gz", + "archiveSha256": "ed1771c44cbf0f8059c67cac0d939e6a60eb730bd066d7dc4cbb14de314cfb6e", + "closureSha256": "2c461f48feb274f8e7aabd6da67d1e9aefbe6e0b232fc0a111dce874378afcc8", + "executable": "node", + "entrypoint": "index.js", + "vendorClosureSha256": "7c8775160af74e5fb8d25a30e8412c1a6476b0661529078a686e5118fd1c5e5f" + }, + "linux-x64": { + "url": "https://downloads.cursor.com/lab/2026.09.26-dd393fe/linux/x64/agent-cli-package.tar.gz", + "archiveSha256": "8085fd120f5c71f4eae7fea26a043718e5644e3071e4fab3220a0e58c51f9593", + "closureSha256": "4fe9461c19d1aec0cbbe4189159291fe62ef6910732a05fc5a25923afb1ce2c7", + "executable": "node", + "entrypoint": "index.js", + "vendorClosureSha256": "bf04ef8ea6a63191067a6b3e15139aa2c793d8419daab246aa3f0a012e1bbcd9" + } + }, + "patchVersion": "paperclip-cursor-isolation-v1" + }, + "agentFilesBinding": "registered-runtime-context-v1" + } +} From 7bfaf3da4d8ccb1e128837d27a93a21dba99f206 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 29 Sep 2026 09:48:23 -0500 Subject: [PATCH 6/6] Version Copilot protocol policy as profile v3 Co-Authored-By: Paperclip --- .../scripts/build-copilot-distribution.mjs | 2 +- .../src/drivers/acpx/qualified-profiles.ts | 4 ++-- .../fixtures/copilot-profile-v3-identity.json | 15 +++++++++++++++ 3 files changed, 18 insertions(+), 3 deletions(-) create mode 100644 packages/paperclip-runner/test/fixtures/copilot-profile-v3-identity.json diff --git a/packages/paperclip-runner/scripts/build-copilot-distribution.mjs b/packages/paperclip-runner/scripts/build-copilot-distribution.mjs index 3077e9f9420..050c588934c 100644 --- a/packages/paperclip-runner/scripts/build-copilot-distribution.mjs +++ b/packages/paperclip-runner/scripts/build-copilot-distribution.mjs @@ -7,7 +7,7 @@ import { COPILOT_VERSION, materializePinnedCopilotBinary, resolveCopilotDistribu const MAX_ARCHIVE_BYTES = 128 * 1024 * 1024; const MAX_EXPANDED_BYTES = 384 * 1024 * 1024; -const PROFILE_DIGEST = "sha256:b18c01603dd0169d233140709cfaa8bf5304a03cf5de78ca4f625f30013e8457"; +const PROFILE_DIGEST = "sha256:4dbd3b0bead1dfcbe4b9b0d9a82a6660ae49c2b1a118862ec3ef654f3b76f8d7"; /** Build-time only; outputRoot is the exact runner-owned platform asset directory. */ export async function buildPinnedCopilotDistribution({ outputRoot, platform = process.platform, architecture = process.arch }, { fetchImpl = fetch } = {}) { diff --git a/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts index 1d88bf14da1..d333a9f8635 100644 --- a/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts +++ b/packages/paperclip-runner/src/drivers/acpx/qualified-profiles.ts @@ -71,10 +71,10 @@ export const QUALIFIED_ACPX_PROFILES: Readonly< }, copilot: { driverKind: ACPX_DRIVER_KIND, protocolVersion: ACPX_DRIVER_PROTOCOL_VERSION, - acpxVersion: QUALIFIED_ACPX_VERSION, agent: "copilot", agentProfileVersion: 2, + acpxVersion: QUALIFIED_ACPX_VERSION, agent: "copilot", agentProfileVersion: 3, agentServerPackage: "@github/copilot", agentServerVersion: "1.0.88", agentRuntimePackage: null, agentRuntimeVersion: null, - commandDigest: "sha256:b18c01603dd0169d233140709cfaa8bf5304a03cf5de78ca4f625f30013e8457", + commandDigest: "sha256:4dbd3b0bead1dfcbe4b9b0d9a82a6660ae49c2b1a118862ec3ef654f3b76f8d7", // Authenticated discovery has not established a qualification model. Never // turn this empty declaration into a default; callers must select an ID. qualificationModel: "", reportedModelId: "", permissionPolicy: "interactive", diff --git a/packages/paperclip-runner/test/fixtures/copilot-profile-v3-identity.json b/packages/paperclip-runner/test/fixtures/copilot-profile-v3-identity.json new file mode 100644 index 00000000000..b14ef739fb5 --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/copilot-profile-v3-identity.json @@ -0,0 +1,15 @@ +{ + "commandDigest": "sha256:4dbd3b0bead1dfcbe4b9b0d9a82a6660ae49c2b1a118862ec3ef654f3b76f8d7", + "declaration": { + "schema": "paperclip.acpx_profile_declaration.v1", + "agent": "copilot", + "agentProfileVersion": 3, + "acpxVersion": "0.13.1", + "agentServerVersion": "1.0.88", + "protocolPolicyRevision": "copilot-agent-manual-v1", + "acpxPatchSha256": "cefbc196b0c46b5e34aa991d2265cb7466a955b473f07a2ba123fa44ca398579", + "policySha256": "48aec06d6232175b07a9ef917eb7df3042a1bc99cf4254a02aedd86c2ac68355", + "distributionSourceSha256": "bb3dcf14972e82f6578c8250540cfbc6ec2ad953bea5d4f10d28c8b461011f3f", + "agentFilesBinding": "registered-runtime-context-v1" + } +}