Admit and bind Cursor native session modes in profile v5

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-09-29 16:23:41 -05:00
1 parent 17c6da5e32
commit 4af314a055
14 files changed
+592 -14

No files matched your search

+44 -2
View File
@@ -2,7 +2,7 @@
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.
Current source uses **profile v4**, with the instruction admission correction described below. Prior paid results and packaged v3 builds remain historical and cannot qualify the current source.
Current source uses **profile v5**, with native session-mode admission and the instruction correction described below. All prior paid results (including v4) and packaged builds remain historical and cannot qualify v5. The earlier mode-selection limitation below describes the pre-v5 implementation.
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.
@@ -38,7 +38,7 @@ The reference is the runner's Codex app-server integration and its closed thread
| Session continuity | `session/new`, `session/load`; load replays historical messages, reasoning, tools, images and children | Existing session load/recovery boundary with identity fencing | Duplicate replay suppression and provider-death recovery need authenticated proof |
| Session discovery | `session/list` implemented, cwd filter absolute; pagination cursor rejected | Discovered and reported | Currently unused: runner recovers only its exact recorded session; arbitrary history browsing needs company-scoped discovery API |
| Fork/resume methods | `session/fork` and `session/resume` absent in agent implementation and return method-not-found | Unsupported | Session load is available; do not infer fork from SDK schema |
| Modes | `agent`, `plan`, `ask`; `session/set_mode` and `current_mode_update` | Existing review/mode activity plumbing can display changes | Generic operator mode-selection surface not implemented in this provider slice |
| Modes | `agent`, `plan`, `ask`; `session/set_config_option` returns exact mode; native mode updates are observable | v5 admits an explicit selected mode, binds recovery identity, and gates every prompt against native acknowledgement | Default Agent; mode is independent of permission policy. Plan acceptance does not switch to Agent. Native callback availability and Plan-mode completion remain unqualified |
| Model selection | `session/set_model`, config option `model`, model-parameter options, `config_option_update`; `cursor/list_available_models` extension | Exact requested model must be selected/verified by shared admission | Authenticated listing and exact Luna variant echo passed. Native parameterized picker metadata and separate parameter changes also passed; this richer configuration path is not exposed by the runner. See the authenticated discovery evidence below |
| 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 |
@@ -312,3 +312,45 @@ ACPX contracts, seven materializer cases, and the runner TypeScript compile pass
No paid calls or billing mutations were made. A new final-source provider pack
and daemon, authenticated instruction semantics, and the remaining live gates
are still required before qualification.
## Cursor profile v5: admitted native session modes (2026-09-29)
The explicit `acpxSessionMode` configuration selects `agent` (the default),
`plan`, or `ask` for Cursor. The provider/sidecar field is `cursorMode`; it is
separate from ACPX's persistent/oneshot session lifecycle. Other providers reject
this field. Mode is included in the immutable session key and recovery identity;
a missing or changed mode cannot reopen an existing v5 session.
Admission checks the pinned native `session/new` or `session/load` response's
mode configuration and mode state. If necessary, it sets the selected mode using
`session/set_config_option` and requires its exact echoed configuration before
admitting a prompt. A bare `session/set_mode` response or asynchronous
`current_mode_update` alone is not acknowledgement. Every new native connection
gets a fresh guard: a mismatched automatic reload blocks prompt delivery, and an
unsolicited active mode change fails closed. Explicit startup/reopen admission
can reassert the selected mode within the existing admission deadline and renews
the consumed launch lease after each temporary control connection.
The pinned CLI maps Agent to native `default`, Plan to `plan`, and Ask to
`search`, and carries that metadata into the native UserMessage mode. The
inspectable `mode-v5-offline-proof.json` executes the pinned native methods with
storage, transport, and enum-converter doubles. Real ACPX fixture tests separately
prove cold-manager load/control ordering and automatic reconnect rejection before
prompt bytes. Neither is paid model/tool qualification.
Native mode does not change Paperclip permission policy, company governance, or
filesystem isolation. The native descriptions say Plan is read-only planning and
Ask has no edits or command execution; these descriptions are not an OS sandbox
claim. Native ACP CreatePlan acceptance does not itself mutate session mode in
the pinned handler. An approved plan therefore stays in the selected Plan mode;
there is no implicit promotion to Agent mode. Actual native question/plan callback
availability, Plan-mode governed completion, and accepted/revised artifact flows
remain pending Product qualification. Existing v4 paid results and macOS x64
Rosetta build evidence remain historical and do not qualify v5.
[The v5 declaration](../../packages/paperclip-runner/test/fixtures/cursor-acp/profile-v5-identity.json)
binds digest `sha256:aa8c0b2b84786982bcd06b7634bf95be6f2bc42bb8def48a8751dc50cf739b6b`.
Profile v5 retains the native distribution closures and instruction patch. Its
canonical declaration adds the admitted mode policy and binds ACPX patch
`79aad2d688b03362e8cfcbf7a08f78a8383869f6882a9c9ed66f1d18efb94f2b`, which preserves
identified empty rich-input chunks at the native parser boundary.
@@ -0,0 +1,63 @@
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { pathToFileURL } from "node:url";
import { runInNewContext } from "node:vm";
const PINNED_ARM_CHUNK = "c01657c111f65153d7a40a923f01a5a86d393d1cd6893eaa03f71b9604d2af0c";
const hash = source => createHash("sha256").update(source).digest("hex");
function segment(source, start, end) {
const first = source.indexOf(start); assert.ok(first >= 0, `Missing native method ${start}`);
const last = source.indexOf(end, first + start.length); assert.ok(last > first, `Missing method boundary ${end}`);
return source.slice(first, last);
}
const awaiter = (self, args, _promise, fn) => {
const iterator = fn.apply(self, args ?? []);
const next = value => { const result = iterator.next(value); return result.done ? Promise.resolve(result.value) : Promise.resolve(result.value).then(next); };
return next();
};
/** Executes the pinned native mode methods with dependency doubles. No network,
* model call, or claim that a selected mode exposes a particular tool. */
export async function qualifyCursorMode(source) {
assert.equal(hash(source), PINNED_ARM_CHUNK, "Native source identity changed");
const toAcp = mode => ({ default: "agent", plan: "plan", search: "ask" })[mode];
const scope = { S: awaiter, T: { ACP_MODE_CONFIG_ID: "mode" }, p: { mb: toAcp }, _: { mb: toAcp }, i: { GI: { invalidParams: value => new Error(value.message) } }, w: { debugLog() {} } };
const method = (start, end, name) => runInNewContext(`({${segment(source, start, end)}}).${name}`, scope);
const setConfig = method("setSessionConfigOption(e)", "unstable_setSessionModel(e)", "setSessionConfigOption");
const mapMode = method("mapAcpModeToCliMode(e)", "clientSupportsParameterizedModelPicker()", "mapAcpModeToCliMode");
const modes = method("buildModesStateFromCliMode(e)", "buildModesState(e)", "buildModesStateFromCliMode");
const configs = method("buildConfigOptions(e,t)", "buildModelsState(e)", "buildConfigOptions");
const setMode = method("setMode(e){", "getCliMode(){", "setMode");
const getCliMode = method("getCliMode(){", "sendCurrentModeUpdate(e)", "getCliMode");
const rows = [];
for (const selected of ["agent", "plan", "ask"]) {
const metadata = new Map([["mode", "default"]]); const updates = [];
const store = { getMetadata: key => metadata.get(key), setMetadata: (key, value) => metadata.set(key, value) };
const makeSession = () => ({ agentStore: store, setMode, getCliMode, sendCurrentModeUpdate: async value => updates.push(value) });
const session = makeSession();
const host = { sessions: new Map([["native", { session }]]), sharedServices: {}, mapAcpModeToCliMode: mapMode, buildModesStateFromCliMode: modes, buildConfigOptions: configs, getModelPickerMode: () => "variants", getAcpAvailableModels: async () => [], buildVariantModelConfigOptions: async () => [] };
const response = await setConfig.call(host, { sessionId: "native", configId: "mode", value: selected });
assert.equal(response.configOptions[0].currentValue, selected);
assert.equal(updates.at(-1), selected);
// A reconstructed native session reads the same admitted metadata. Actual
// database durability is deliberately outside this dependency-double proof.
const loaded = makeSession();
assert.equal((await configs.call(host, "native", loaded))[0].currentValue, selected);
class Data { constructor(value) { Object.assign(this, value); } }
const promptPart = segment(source, 'r=null!==(o=this.agentStore.getMetadata("mode"))', ',u=new a.h');
const action = runInNewContext(`(function(){let o;const ${promptPart};return d;})`, { _: { cT: value => ({ nativeModeInput: value }) }, c: { UserMessageAction: Data, UserMessage: Data }, N: "offline fixture", n: {}, crypto: { randomUUID: () => "fixture" } }).call(loaded);
assert.equal(action.userMessage.mode.nativeModeInput, metadata.get("mode"));
rows.push({ selected, nativeMetadata: metadata.get("mode"), configAcknowledgement: selected, currentModeNotification: selected, reconstructedSessionAcknowledgement: selected, userMessageModeInput: action.userMessage.mode.nativeModeInput });
}
const planHandler = segment(source, '"./src/acp/interaction-handlers/create-plan-handler.ts"(e,t,n)', '},"./src/acp/resource-link-security.ts"');
assert.doesNotMatch(planHandler, /setMode\(|setMetadata\("mode"/);
return { schema: "paperclip.cursor.native-mode-offline-proof.v1", sourceSha256: hash(source), rows, planHandlerHasModeMutation: false, boundary: "pinned native config/session/UserMessage methods; storage, mode enum converter and transport doubled; no inference" };
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const [sourcePath, outputPath] = process.argv.slice(2);
if (!sourcePath || !outputPath) throw new Error("Usage: node qualify-cursor-mode.mjs PINNED_ARM_CHUNK OUTPUT_JSON");
const proof = await qualifyCursorMode(await readFile(sourcePath, "utf8"));
await writeFile(outputPath, `${JSON.stringify(proof, null, 2)}\n`);
}
@@ -90,7 +90,7 @@ describe("Codex ACPX runtime adapter", () => {
const guard = created.protocolGuardFactory!();
const binding = cursorInstructionBinding(options.systemInstructions);
guard("outbound", { id: 0, method: "session/load", params: { sessionId: "backend-1" } });
guard("inbound", { id: 0, result: mode === "missing" ? {} : { _meta: { paperclipCursorInstructions: {
guard("inbound", { id: 0, result: mode === "missing" ? {} : { modes: { currentModeId: "agent" }, configOptions: [{ id: "mode", currentValue: "agent" }], _meta: { paperclipCursorInstructions: {
schema: "paperclip.cursor.instructions.v1", digest: binding.digest, byteLength: binding.byteLength,
} } } });
if (mode === "unsupported") throw new Error("Exact model unsupported");
@@ -107,6 +107,32 @@ describe("Codex ACPX runtime adapter", () => {
expect(runtime.setConfigOption).toHaveBeenCalledExactlyOnceWith({ handle: HANDLE, key: "model", value: options.profile.reportedModelId });
expect(runtime.startTurn).not.toHaveBeenCalled();
});
it.each(["plan", "ask"] as const)("admission explicitly selects %s and renews temporary command authority", async selected => {
const runtime = fakeRuntime(); const options = openOptions(fakeCommand());
options.profile = { ...options.profile, agent: "cursor" }; options.cursorMode = selected;
options.refreshConsumedCommand = vi.fn(async () => undefined);
let created!: AcpRuntimeOptions;
const binding = cursorInstructionBinding(options.systemInstructions);
const configs = (mode: string) => [{ id: "mode", currentValue: mode }];
vi.mocked(runtime.setConfigOption).mockImplementation(async input => {
const guard = created.protocolGuardFactory!();
guard("outbound", { id: 0, method: "session/load", params: { sessionId: "backend-1" } });
guard("inbound", { id: 0, result: { modes: { currentModeId: "agent" }, configOptions: configs("agent"), _meta: { paperclipCursorInstructions: {
schema: "paperclip.cursor.instructions.v1", digest: binding.digest, byteLength: binding.byteLength,
} } } });
guard("outbound", { id: 1, method: "session/set_config_option", params: { sessionId: "backend-1", configId: input.key, value: input.value } });
guard("inbound", { id: 1, result: { configOptions: configs(input.key === "mode" ? selected : "agent") } });
});
const port = await openCodexAcpxRuntime(options, {
createRegistry: () => registry(), createStore: () => store(), createRuntime: value => { created = value; return runtime; },
});
expect(vi.mocked(runtime.setConfigOption).mock.calls.map(([call]) => [call.key, call.value])).toEqual([["model", options.profile.reportedModelId], ["mode", selected]]);
expect(options.refreshConsumedCommand).toHaveBeenCalledTimes(2);
expect(await port.identity()).toMatchObject({ cursorMode: selected });
expect(runtime.startTurn).not.toHaveBeenCalled();
await port.close({ reason: "mode fixture cleanup" });
});
it("routes only profile-allowed extensions to the owning turn and expires late responses", async () => {
const runtime = fakeRuntime();
const first = pendingExtensionTurn("turn-1");
@@ -123,7 +149,7 @@ describe("Codex ACPX runtime adapter", () => {
const guard = value.protocolGuardFactory!();
const binding = cursorInstructionBinding(options.systemInstructions);
guard("outbound", { id: 0, method: "session/new", params: {} });
guard("inbound", { id: 0, result: { sessionId: "backend-1", _meta: { paperclipCursorInstructions: { schema: "paperclip.cursor.instructions.v1", digest: binding.digest, byteLength: binding.byteLength } } } });
guard("inbound", { id: 0, result: { sessionId: "backend-1", modes: { currentModeId: "agent" }, configOptions: [{ id: "mode", currentValue: "agent" }], _meta: { paperclipCursorInstructions: { schema: "paperclip.cursor.instructions.v1", digest: binding.digest, byteLength: binding.byteLength } } } });
return runtime;
},
});
@@ -32,6 +32,7 @@ import { AcpxApprovalRequiredError, decideAcpxPermission } from "./permission-po
import { ACPX_CAPABILITY_PROFILES } from "./capability-profiles.js";
import { assertCopilotPromptPolicy, createCopilotProtocolGuard } from "./copilot-policy.js";
import { admitCursorInstructions, createCursorInstructionAdmission } from "./cursor-instructions.js";
import { createCursorModeAdmission, resolveCursorSessionMode } from "./cursor-mode.js";
const VERIFIED_COMMAND_SENTINEL = "paperclip-verified-acpx-command";
const DEFAULT_RUNTIME_CLOSE_TIMEOUT_MS = 2_000;
@@ -299,12 +300,18 @@ export async function openQualifiedAcpxRuntime(
);
};
const commandLaunches = { count: 0, refreshConsumedCommand: options.refreshConsumedCommand };
const selectedCursorMode = resolveCursorSessionMode(options.profile.agent, options.cursorMode);
const cursorMode = selectedCursorMode ? createCursorModeAdmission(selectedCursorMode) : null;
const cursorInstructions = options.profile.agent === "cursor"
? createCursorInstructionAdmission(options.systemInstructions)
: null;
const runtimeOptions: GoalAwareAcpRuntimeOptions = {
cwd: options.cwd,
...(cursorInstructions ? { protocolGuardFactory: () => cursorInstructions.createGuard() } : {}),
...(cursorInstructions && cursorMode ? { protocolGuardFactory: () => {
const instructions = cursorInstructions.createGuard();
const mode = cursorMode.createGuard();
return (direction: "inbound" | "outbound", message: unknown) => { instructions(direction, message); mode(direction, message); };
} } : {}),
sessionStore,
agentRegistry: createRegistry({
// Preserve Claude's ACP capability identity. This is metadata only: the
@@ -491,6 +498,15 @@ export async function openQualifiedAcpxRuntime(
await commandLaunches.refreshConsumedCommand?.();
},
});
if (cursorMode && !cursorMode.isReady()) {
if (!runtime.setConfigOption) throw new Error("Cursor mode admission requires native mode configuration");
await runtime.setConfigOption({ handle: ensuredHandle, key: "mode", value: selectedCursorMode! });
cursorInstructions.assertReady();
cursorMode.assertReady();
await children.verifyLifetimeOwnership();
options.signal?.throwIfAborted();
await commandLaunches.refreshConsumedCommand?.();
}
return ensuredHandle;
}) : ensuredSession)
.catch((error: unknown) => {
@@ -506,6 +522,7 @@ export async function openQualifiedAcpxRuntime(
? await raceRuntimeHandshakeWithAbort(boundedHandshake, options.signal)
: await boundedHandshake;
cursorInstructions?.assertReady();
cursorMode?.assertReady();
// A provider can answer only after the verified sentinel is armed, but do
// not admit the session until the owner has observed that exact handoff.
await children.verifyLifetimeOwnership();
@@ -560,7 +577,7 @@ export async function openQualifiedAcpxRuntime(
return runtimePort(
runtime,
handle,
requireIdentity(handle),
{ ...requireIdentity(handle), ...(selectedCursorMode ? { cursorMode: selectedCursorMode } : {}) },
baseStore,
children,
runtimeCloseTimeoutMs,
@@ -0,0 +1,180 @@
import { describe, expect, it } from "vitest";
import { createCursorModeAdmission, resolveCursorSessionMode } from "./cursor-mode.js";
const config = (mode: string) => [{ id: "mode", type: "select", currentValue: mode, options: ["agent", "plan", "ask"].map(value => ({ value, name: value })) }];
const session = (mode: string) => ({ sessionId: "native", modes: { currentModeId: mode }, configOptions: config(mode) });
const prompt = { id: 9, method: "session/prompt", params: { sessionId: "native" } };
function opened(expected: "agent" | "plan" | "ask", initial = expected) {
const admission = createCursorModeAdmission(expected); const guard = admission.createGuard();
guard("outbound", { id: 0, method: "session/new", params: {} });
guard("inbound", { id: 0, result: session(initial) });
return { admission, guard };
}
describe("Cursor native mode admission", () => {
it("defaults only Cursor and rejects unadmitted aliases and other providers", () => {
expect(resolveCursorSessionMode("cursor", undefined)).toBe("agent");
expect(resolveCursorSessionMode("codex", undefined)).toBeUndefined();
for (const mode of ["code", "architect", "search", "chat", "", null]) expect(() => resolveCursorSessionMode("cursor", mode)).toThrow();
expect(() => resolveCursorSessionMode("pi", "agent")).toThrow(/only supported/);
});
it.each(["agent", "plan", "ask"] as const)("admits %s only after correlated native acknowledgements", expected => {
const { admission, guard } = opened(expected);
admission.assertReady(); guard("outbound", prompt);
const reloaded = admission.createGuard();
expect(admission.assertReady).toThrow();
expect(() => guard("outbound", prompt)).toThrow(/replaced/);
reloaded("outbound", { id: 1, method: "session/load", params: { sessionId: "native" } });
reloaded("inbound", { id: 1, result: session(expected) });
admission.assertReady(); reloaded("outbound", prompt);
});
it("permits explicit initial configuration and does not use an update as its acknowledgement", () => {
const { admission, guard } = opened("plan", "agent");
expect(admission.isReady()).toBe(false);
guard("outbound", { id: 2, method: "session/set_config_option", params: { sessionId: "native", configId: "mode", value: "plan" } });
guard("inbound", { method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "current_mode_update", currentModeId: "plan" } } });
expect(admission.isReady()).toBe(false);
guard("inbound", { id: 2, result: { configOptions: config("plan") } });
admission.assertReady(); guard("outbound", prompt);
});
it.each(["missing", "conflicting", "wrong"])("gates a reloaded prompt with %s mode acknowledgement", kind => {
const { admission } = opened("plan"); const guard = admission.createGuard();
guard("outbound", { id: 2, method: "session/load", params: { sessionId: "native" } });
const result = kind === "missing" ? {} : kind === "conflicting" ? { ...session("plan"), modes: { currentModeId: "ask" } } : session("agent");
if (kind === "wrong") guard("inbound", { id: 2, result });
else expect(() => guard("inbound", { id: 2, result })).toThrow(/mode admission/);
expect(() => guard("outbound", prompt)).toThrow(/mode admission/);
});
it("rejects late mode drift and keeps the connection failed closed", () => {
const { admission, guard } = opened("plan");
expect(() => guard("inbound", { method: "session/update", params: { sessionId: "native", update: { sessionUpdate: "current_mode_update", currentModeId: "agent" } } })).toThrow(/drifted/);
expect(admission.assertReady).toThrow(/drifted/);
expect(() => guard("outbound", prompt)).toThrow(/drifted/);
});
it("rejects wrong config echoes, uncorrelated acknowledgements and cross-session control", () => {
const forged = createCursorModeAdmission("plan"); const g = forged.createGuard();
g("inbound", { id: 2, result: session("plan") }); expect(forged.assertReady).toThrow();
const { guard } = opened("plan", "agent");
guard("outbound", { id: 2, method: "session/set_config_option", params: { sessionId: "native", configId: "mode", value: "plan" } });
expect(() => guard("inbound", { id: 2, result: { configOptions: config("agent") } })).toThrow(/did not apply/);
const other = opened("plan").guard;
expect(() => other("outbound", { id: 3, method: "session/set_config_option", params: { sessionId: "other", configId: "mode", value: "plan" } })).toThrow(/different session/);
});
it("does not mistake a bare set_mode response for configuration proof", () => {
const { admission, guard } = opened("plan", "agent");
guard("outbound", { id: 4, method: "session/set_mode", params: { sessionId: "native", modeId: "plan" } });
guard("inbound", { id: 4, result: {} }); expect(admission.assertReady).toThrow();
});
});
// Real ACPX runtime/SDK transport with a credential-free deterministic peer.
// This proves reconnection ordering and zero prompt bytes on rejection, not
// Cursor model tool selection or a paid provider interaction.
it.each(["plan", "agent", "missing"])("actual runtime auto-load observes %s mode before prompt delivery", async loadedMode => {
const { spawn } = await import("node:child_process");
const { mkdtemp, rm } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const { createAcpRuntime, createAgentRegistry, createRuntimeStore } = await import("acpx/runtime");
const dir = await mkdtemp(join(tmpdir(), "cursor-mode-runtime-"));
const children: ReturnType<typeof spawn>[] = [];
const methods: string[] = [];
const admission = createCursorModeAdmission("plan");
const peer = String.raw`
const send=x=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...x})+'\n');
let mode=process.env.MODE;
const config=()=>[{id:'mode',name:'Mode',type:'select',currentValue:mode,options:['agent','plan','ask'].map(value=>({value,name:value}))}];
require('node:readline').createInterface({input:process.stdin}).on('line',line=>{
const m=JSON.parse(line);
if(m.method==='initialize')send({id:m.id,result:{protocolVersion:1,agentCapabilities:{loadSession:true},authMethods:[]}});
else if(m.method==='session/new'||m.method==='session/load')send({id:m.id,result:{sessionId:'native',...(mode==='missing'?{}:{modes:{currentModeId:mode,availableModes:['agent','plan','ask'].map(id=>({id,name:id}))},configOptions:config()})}});
else if(m.method==='session/prompt')send({id:m.id,result:{stopReason:'end_turn'}});
});`;
const runtime = createAcpRuntime({ cwd: dir, agentRegistry: createAgentRegistry({ overrides: { cursor: "fixture" } }), sessionStore: createRuntimeStore({ stateDir: join(dir, "state") }), permissionMode: "deny-all",
protocolGuardFactory: () => admission.createGuard(),
onAcpMessage: (direction, value) => { if (direction === "outbound") methods.push((value as { method: string }).method); },
spawnAgent: () => { const child = spawn(process.execPath, ["-e", peer], { cwd: dir, env: { MODE: children.length ? loadedMode : "plan" }, stdio: ["pipe", "pipe", "pipe"] }); children.push(child); return child; },
});
let handle;
try {
handle = await runtime.ensureSession({ sessionKey: "mode-recovery", agent: "cursor", mode: "persistent", cwd: dir });
admission.assertReady();
const exited = new Promise(resolve => children[0].once("exit", resolve)); children[0].kill("SIGTERM"); await exited;
const turn = runtime.startTurn({ handle, text: "fixture", mode: "prompt", requestId: "reloaded", timeoutMs: 2000 });
const drain = (async () => { for await (const _event of turn.events) { /* drain */ } })();
const result = await turn.result; await drain;
expect(children).toHaveLength(2); expect(methods).toContain("session/load");
if (loadedMode === "plan") { expect(result.status).toBe("completed"); expect(methods.filter(m => m === "session/prompt")).toHaveLength(1); }
else { expect(result.status).toBe("failed"); expect(methods).not.toContain("session/prompt"); }
} finally {
if (handle) await runtime.close({ handle, reason: "fixture cleanup" }).catch(() => {});
for (const child of children) if (child.exitCode === null) child.kill("SIGKILL");
await rm(dir, { recursive: true, force: true });
}
});
it.each(["valid", "unsupported", "wrong-echo"])("actual cold manager requires %s mode control before a prompt", async behavior => {
const { spawn } = await import("node:child_process");
const { mkdtemp, rm } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const { createAcpRuntime, createAgentRegistry, createRuntimeStore } = await import("acpx/runtime");
const dir = await mkdtemp(join(tmpdir(), "cursor-mode-cold-"));
const children: ReturnType<typeof spawn>[] = []; const methods: string[] = [];
const peer = String.raw`
const fs=require('node:fs'), path=process.env.STATE;
let mode=fs.existsSync(path)?fs.readFileSync(path,'utf8'):'agent';
const send=x=>process.stdout.write(JSON.stringify({jsonrpc:'2.0',...x})+'\n');
const configs=()=>[{id:'mode',name:'Mode',type:'select',currentValue:mode,options:['agent','plan','ask'].map(value=>({value,name:value}))},{id:'model',name:'Model',type:'select',currentValue:'fixture',options:[{value:'fixture',name:'Fixture'}]}];
require('node:readline').createInterface({input:process.stdin}).on('line',line=>{
const m=JSON.parse(line);
if(m.method==='initialize')send({id:m.id,result:{protocolVersion:1,agentCapabilities:{loadSession:true},authMethods:[]}});
else if(m.method==='session/new'||m.method==='session/load')send({id:m.id,result:{sessionId:'native',modes:{currentModeId:mode,availableModes:['agent','plan','ask'].map(id=>({id,name:id}))},configOptions:configs()}});
else if(m.method==='session/set_config_option'){
if(m.params.configId==='mode') {
if(process.env.BEHAVIOR==='unsupported')return send({id:m.id,error:{code:-32602,message:'Unsupported native mode'}});
if(process.env.BEHAVIOR!=='wrong-echo'){mode=m.params.value;fs.writeFileSync(path,mode);}
}
send({id:m.id,result:{configOptions:configs()}});
}
else if(m.method==='session/prompt')send({id:m.id,result:{stopReason:'end_turn'}});
});`;
const create = (mode: "agent" | "plan") => {
const admission = createCursorModeAdmission(mode);
const runtime = createAcpRuntime({ cwd: dir, agentRegistry: createAgentRegistry({ overrides: { cursor: "fixture" } }), sessionStore: createRuntimeStore({ stateDir: join(dir, "state") }), permissionMode: "deny-all",
protocolGuardFactory: () => admission.createGuard(),
onAcpMessage: (direction, value) => { if (direction === "outbound") methods.push((value as { method: string }).method); },
spawnAgent: () => { const child = spawn(process.execPath, ["-e", peer], { cwd: dir, env: { STATE: join(dir, "mode"), BEHAVIOR: behavior }, stdio: ["pipe", "pipe", "pipe"] }); children.push(child); return child; },
});
return { runtime, admission };
};
const first = create("agent"); let second: ReturnType<typeof create> | undefined;
let firstHandle; let secondHandle;
const options = { sessionKey: "cold-mode", agent: "cursor", mode: "persistent" as const, cwd: dir };
try {
firstHandle = await first.runtime.ensureSession(options); first.admission.assertReady();
await first.runtime.close({ handle: firstHandle, reason: "retire first manager" }); firstHandle = undefined;
second = create("plan"); const count = children.length;
secondHandle = await second.runtime.ensureSession(options); expect(children).toHaveLength(count);
await second.runtime.setConfigOption({ handle: secondHandle, key: "model", value: "fixture" });
expect(second.admission.isReady()).toBe(false);
const selected = second.runtime.setConfigOption({ handle: secondHandle, key: "mode", value: "plan" });
if (behavior !== "valid") {
await expect(selected).rejects.toThrow(behavior === "unsupported" ? /Unsupported native mode/ : /did not apply/);
expect(methods).not.toContain("session/prompt");
} else {
await selected; second.admission.assertReady();
const turn = second.runtime.startTurn({ handle: secondHandle, text: "fixture", mode: "prompt", requestId: "cold-mode-turn", timeoutMs: 2000 });
const drain = (async () => { for await (const _event of turn.events) { /* drain */ } })();
expect((await turn.result).status).toBe("completed"); await drain;
expect(methods.filter(m => m === "session/set_config_option")).toHaveLength(2);
expect(methods.filter(m => m === "session/load")).toHaveLength(3);
expect(methods.filter(m => m === "session/prompt")).toHaveLength(1);
}
} finally {
if (firstHandle) await first.runtime.close({ handle: firstHandle, reason: "cleanup" }).catch(() => {});
if (second && secondHandle) await second.runtime.close({ handle: secondHandle, reason: "cleanup" }).catch(() => {});
for (const child of children) if (child.exitCode === null) child.kill("SIGKILL");
await rm(dir, { recursive: true, force: true });
}
});
@@ -0,0 +1,97 @@
export type CursorSessionMode = "agent" | "plan" | "ask";
export function resolveCursorSessionMode(agent: string, mode: unknown): CursorSessionMode | undefined {
if (agent !== "cursor") {
if (mode !== undefined) throw new Error("Cursor session mode is only supported by Cursor");
return undefined;
}
if (mode === undefined) return "agent";
if (mode !== "agent" && mode !== "plan" && mode !== "ask") throw new Error("Invalid Cursor session mode");
return mode;
}
function object(value: unknown): Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
}
/** Native mode is independent of permissions. Every connection must prove its
* current mode before a prompt; a persisted ACPX preference is not proof. */
export function createCursorModeAdmission(expected: CursorSessionMode) {
type State = { sessionId: string | null; mode: CursorSessionMode | null; error: Error | null };
let current: State | null = null;
const failure = (detail: string) => new Error(`Cursor mode admission failed: ${detail}`);
const assertReady = () => {
if (current?.error) throw current.error;
if (!current?.sessionId || current.mode !== expected) throw failure("native mode does not acknowledge the selected mode");
};
const readMode = (result: Record<string, unknown>, session: boolean): CursorSessionMode => {
const configs = Array.isArray(result.configOptions) ? result.configOptions.filter(value => object(value).id === "mode") : [];
if (configs.length !== 1) throw failure("native mode configuration is missing or ambiguous");
const mode = object(configs[0]).currentValue;
if (mode !== "agent" && mode !== "plan" && mode !== "ask") throw failure("native mode is unsupported");
if (session && object(result.modes).currentModeId !== mode) throw failure("native mode acknowledgements conflict");
return mode;
};
return {
assertReady,
isReady() { assertNoError(); return current?.sessionId != null && current.mode === expected; },
createGuard() {
const state: State = { sessionId: null, mode: null, error: null };
current = state;
const pending = new Map<string | number, { method: string; sessionId: unknown; selectsMode: boolean }>();
return (direction: "inbound" | "outbound", value: unknown): void => {
if (current !== state) throw failure("connection authority was replaced");
assertNoError();
const message = object(value);
const params = object(message.params);
try {
if (direction === "outbound") {
const method = message.method;
if (method === "session/prompt") {
assertReady();
if (params.sessionId !== state.sessionId) throw failure("prompt belongs to a different session");
} else if (method === "session/new" || method === "session/load" || method === "session/set_config_option") {
if (typeof message.id !== "string" && typeof message.id !== "number") throw failure("uncorrelated mode request");
if (pending.has(message.id)) throw failure("duplicate mode request identity");
if (method === "session/new" || method === "session/load") {
if (pending.size) throw failure("overlapping session admission");
state.sessionId = null; state.mode = null;
} else {
if (!state.sessionId || params.sessionId !== state.sessionId) throw failure("configuration belongs to a different session");
if (params.configId === "mode" && params.value !== expected) throw failure("configuration changes the selected mode");
}
pending.set(message.id, { method, sessionId: params.sessionId, selectsMode: params.configId === "mode" });
} else if (method === "session/set_mode") {
if (!state.sessionId || params.sessionId !== state.sessionId || params.modeId !== expected) throw failure("mode control changes the selected mode");
// This method only returns {}; require a later config/session
// acknowledgement rather than treating that empty result as proof.
state.mode = null;
}
return;
}
if (message.method === "session/update" && object(params.update).sessionUpdate === "current_mode_update") {
if (!state.sessionId || params.sessionId !== state.sessionId) throw failure("mode update belongs to a different session");
if (object(params.update).currentModeId !== expected) throw failure("native mode drifted from the selected mode");
return; // Notifications alone never admit a prompt.
}
if (message.method !== undefined || (typeof message.id !== "string" && typeof message.id !== "number")) return;
const request = pending.get(message.id);
if (!request) return;
pending.delete(message.id);
if (message.error !== undefined) { state.mode = null; return; }
const result = object(message.result);
const session = request.method !== "session/set_config_option";
const sessionId = request.method === "session/new" ? result.sessionId : request.sessionId;
if (typeof sessionId !== "string" || !sessionId.trim()) throw failure("mode acknowledgement has no session identity");
const mode = readMode(result, session);
if (!session && (request.selectsMode || state.mode === expected) && mode !== expected) throw failure("configuration did not apply the selected mode");
state.sessionId = sessionId; state.mode = mode;
} catch (error) {
state.error = error instanceof Error ? error : failure("invalid mode acknowledgement");
throw state.error;
}
};
},
};
function assertNoError() { if (current?.error) throw current.error; }
}
@@ -63,10 +63,13 @@ describe("qualified ACPX profiles", () => {
});
});
it("binds Cursor v4 to inspectable native instructions, closures and exact ACPX guard patch", () => {
const identity = JSON.parse(readFileSync(new URL("../../../test/fixtures/cursor-acp/profile-v4-identity.json", import.meta.url), "utf8"));
it("binds Cursor v5 to inspectable native instructions, closures and exact ACPX guard patch", () => {
const identity = JSON.parse(readFileSync(new URL("../../../test/fixtures/cursor-acp/profile-v5-identity.json", import.meta.url), "utf8"));
const distribution = JSON.parse(readFileSync(new URL("../../../cursor-distributions.json", import.meta.url), "utf8"));
expect(identity.declaration.distribution).toEqual(distribution);
expect(identity.declaration.sessionModeAdmission).toBe("native-config-ack-recovery-bound-v1");
expect(identity.declaration.sessionModes).toEqual(["agent", "plan", "ask"]);
expect(identity.declaration.defaultSessionMode).toBe("agent");
expect(identity.declaration.agentProfileVersion).toBe(QUALIFIED_ACPX_PROFILES.cursor.agentProfileVersion);
expect(identity.commandDigest).toBe(QUALIFIED_ACPX_PROFILES.cursor.commandDigest);
expect(identity.commandDigest).toBe(`sha256:${createHash("sha256").update(JSON.stringify(identity.declaration)).digest("hex")}`);
@@ -61,10 +61,10 @@ export const QUALIFIED_ACPX_PROFILES: Readonly<
},
cursor: {
driverKind: ACPX_DRIVER_KIND, protocolVersion: ACPX_DRIVER_PROTOCOL_VERSION,
acpxVersion: QUALIFIED_ACPX_VERSION, agent: "cursor", agentProfileVersion: 4,
acpxVersion: QUALIFIED_ACPX_VERSION, agent: "cursor", agentProfileVersion: 5,
agentServerPackage: "cursor-agent", agentServerVersion: "2026.09.26-dd393fe",
agentRuntimePackage: null, agentRuntimeVersion: null,
commandDigest: "sha256:b1440d559ebc4eef5c7a582f1c81fc153270cfbafa1731a8ee76d83713bdf61b",
commandDigest: "sha256:aa8c0b2b84786982bcd06b7634bf95be6f2bc42bb8def48a8751dc50cf739b6b",
// 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",
@@ -26,6 +26,22 @@ afterEach(async () => {
});
describe("ACPX recovery identity", () => {
it("binds Cursor mode on recovery and rejects missing or changed persisted mode", async () => {
const fixture = await recoveryFixture();
const input = { ...fixture.input, profile: resolveQualifiedAcpxProfile("cursor", fixture.input.requestedModel) };
const agent = await createAcpxRecoveryBinding(input);
const plan = await createAcpxRecoveryBinding({ ...input, cursorMode: "plan" });
expect(agent.cursorMode).toBe("agent");
expect(plan.profileSessionKey).not.toBe(agent.profileSessionKey);
const expected = { ...fixture.expected, profileDigest: plan.commandDigest, cursorMode: "plan" as const };
const record = createAcpxIdentityRecord(expected, plan);
expect(acpxProviderSessionIdentity(record, plan).cursorMode).toBe("plan");
expect(() => verifyExpectedAcpxIdentity({ ...expected, cursorMode: undefined }, plan, record)).toThrow(/immutable session/);
expect(() => verifyExpectedAcpxIdentity(expected, agent, record)).toThrow(/immutable session/);
expect(() => verifyExpectedAcpxIdentity(expected, plan, { ...record, cursorMode: undefined })).toThrow(/persisted runtime record/);
await expect(createAcpxRecoveryBinding({ ...fixture.input, cursorMode: "plan" })).rejects.toThrow(/only supported/);
});
it("derives one stable, filesystem-safe runtime directory name", () => {
expect(acpxRuntimeSessionDirectoryName("session/1")).toMatch(
/^session_1-[0-9a-f]{16}$/,
@@ -1,3 +1,4 @@
import { resolveCursorSessionMode, type CursorSessionMode } from "./cursor-mode.js";
import { createHash } from "node:crypto";
import { realpath, stat } from "node:fs/promises";
import { dirname, join, resolve } from "node:path";
@@ -19,6 +20,7 @@ export interface AcpxRecoveryBinding {
requestedModel: string;
effectiveModel: string;
permissionMode: NativeAcpxPermissionMode;
cursorMode?: CursorSessionMode;
profileSessionKey: string;
}
@@ -33,6 +35,7 @@ export interface AcpxIdentityRecord {
requestedModel: string;
effectiveModel: string;
permissionMode: NativeAcpxPermissionMode;
cursorMode?: CursorSessionMode;
providerLifetimeFenceCandidates: readonly [number, number, number];
}
@@ -43,9 +46,11 @@ export async function createAcpxRecoveryBinding(input: {
profile: QualifiedAcpxProfile;
requestedModel: string;
permissionMode: NativeAcpxPermissionMode;
cursorMode?: CursorSessionMode;
providerPolicy?: { readOnly: boolean; readRoots?: readonly string[]; protectedPaths?: readonly string[] };
}): Promise<AcpxRecoveryBinding> {
validateIdentity(input.normalizedSessionId, "normalized session");
const cursorMode = resolveCursorSessionMode(input.profile.agent, input.cursorMode);
if (input.providerPolicy !== undefined && typeof input.providerPolicy.readOnly !== "boolean") throw new Error("ACPX recovery requires a valid task execution policy");
if (input.requestedModel !== input.profile.qualificationModel) {
throw new Error("ACPX recovery requested an unqualified model");
@@ -89,6 +94,7 @@ export async function createAcpxRecoveryBinding(input: {
requestedModel: input.requestedModel,
profileDigest,
permissionMode: input.permissionMode,
...(cursorMode ? { cursorMode } : {}),
}),
).replace("sha256:", "paperclip-");
return {
@@ -101,6 +107,7 @@ export async function createAcpxRecoveryBinding(input: {
requestedModel: input.requestedModel,
effectiveModel: input.requestedModel,
permissionMode: input.permissionMode,
...(cursorMode ? { cursorMode } : {}),
profileSessionKey,
};
}
@@ -121,6 +128,7 @@ export function createAcpxIdentityRecord(
requestedModel: binding.requestedModel,
effectiveModel: binding.effectiveModel,
permissionMode: binding.permissionMode,
...(binding.cursorMode ? { cursorMode: binding.cursorMode } : {}),
providerLifetimeFenceCandidates: Object.freeze([
...expected.providerLifetimeFenceCandidates,
]) as readonly [number, number, number],
@@ -146,6 +154,7 @@ export function acpxProviderSessionIdentity(
requestedModel: record.requestedModel,
effectiveModel: record.effectiveModel,
permissionMode: record.permissionMode,
...(record.cursorMode ? { cursorMode: record.cursorMode } : {}),
providerLifetimeFenceCandidates: record.providerLifetimeFenceCandidates,
};
verifyExpectedAcpxIdentity(identity, binding, record);
@@ -170,7 +179,8 @@ export function verifyExpectedAcpxIdentity(
expected.workspaceDigest !== binding.workspaceDigest ||
expected.requestedModel !== binding.requestedModel ||
expected.effectiveModel !== binding.effectiveModel ||
expected.permissionMode !== binding.permissionMode
expected.permissionMode !== binding.permissionMode ||
expected.cursorMode !== binding.cursorMode
) {
throw new Error(
"ACPX recovery identity conflicts with the immutable session configuration",
@@ -189,6 +199,7 @@ export function verifyExpectedAcpxIdentity(
record.requestedModel !== binding.requestedModel ||
record.effectiveModel !== binding.effectiveModel ||
record.permissionMode !== binding.permissionMode ||
record.cursorMode !== binding.cursorMode ||
!sameFenceCandidates(
record.providerLifetimeFenceCandidates,
expected.providerLifetimeFenceCandidates,
@@ -213,6 +224,7 @@ function parsePersistedRecord(value: unknown): AcpxIdentityRecord {
"requestedModel",
"effectiveModel",
"permissionMode",
"cursorMode",
"providerLifetimeFenceCandidates",
]);
return validatedRecord(record);
@@ -239,6 +251,7 @@ function validatedRecord(value: Record<string, unknown>): AcpxIdentityRecord {
if (!isPermissionMode(value.permissionMode)) {
throw new Error("ACPX identity permission mode is invalid");
}
if (value.cursorMode !== undefined) resolveCursorSessionMode("cursor", value.cursorMode);
validateFenceCandidates(value.providerLifetimeFenceCandidates);
return value as unknown as AcpxIdentityRecord;
}
@@ -267,6 +280,7 @@ function validateExpected(expected: AcpxExpectedSessionIdentity): void {
) {
throw new Error("Expected ACPX permission mode is invalid");
}
if (expected.cursorMode !== undefined) resolveCursorSessionMode("cursor", expected.cursorMode);
validateFenceCandidates(expected.providerLifetimeFenceCandidates);
}
@@ -195,6 +195,31 @@ afterEach(async () => {
});
describe("ACPX runtime host", () => {
it.each([undefined, "plan", "ask"] as const)("requires observed Cursor mode %s in the host identity", async selected => {
const fixture = await hostFixture();
const mode = selected ?? "agent";
const options = { ...fixture.options, agent: "cursor" as const, model: "explicit-test-model", cursorMode: selected, permissionMode: "approve-all" as const, environment: { CURSOR_API_KEY: "test" } };
const openRuntime = vi.fn(async (launch: AcpxRuntimePortOpenOptions) => {
expect(launch.cursorMode).toBe(mode);
return runtimePort({ getStatus: async () => ({ models: { currentModelId: options.model } }), identity: async () => ({ acpxRecordId: "record-1", backendSessionId: "backend-1", agentSessionId: "agent-1", cursorMode: mode }) });
});
const host = await AcpxRuntimeHost.open(options, fixture.dependencies({ openRuntime }));
expect(host.identity().cursorMode).toBe(mode);
await host.close({ reason: "mode test complete" });
});
it("rejects missing observed Cursor mode and mode supplied to another provider", async () => {
const fixture = await hostFixture();
const port = runtimePort({ getStatus: async () => ({ models: { currentModelId: "explicit-test-model" } }) });
const openRuntime = vi.fn(async () => port);
const options = { ...fixture.options, agent: "cursor" as const, model: "explicit-test-model", permissionMode: "approve-all" as const, environment: { CURSOR_API_KEY: "test" } };
await expect(AcpxRuntimeHost.open(options, fixture.dependencies({ openRuntime }))).rejects.toThrow(/Cursor mode does not match/);
expect(port.close).toHaveBeenCalled();
openRuntime.mockClear();
await expect(AcpxRuntimeHost.open({ ...options, agent: "codex", model: "gpt-5.6-sol", cursorMode: "plan" }, fixture.dependencies({ openRuntime }))).rejects.toThrow(/only supported/);
expect(openRuntime).not.toHaveBeenCalled();
});
it.each([
{ PAPERCLIP_NATIVE_MCP_NAME: "paperclip-assigned" },
{ PAPERCLIP_NATIVE_MCP_NAME: "paperclip", PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1:3211/mcp", PAPERCLIP_NATIVE_MCP_TOKEN: "x".repeat(40) },
@@ -842,7 +867,7 @@ describe("ACPX runtime host", () => {
const opened: AcpxRuntimePortOpenOptions[] = [];
const dependencies = fixture.dependencies({ openRuntime: async launch => {
opened.push(launch);
return runtimePort({ getStatus: async () => ({ models: { currentModelId: model } }) });
return runtimePort({ getStatus: async () => ({ models: { currentModelId: model } }), identity: async () => ({ acpxRecordId: "record-1", backendSessionId: "backend-1", agentSessionId: "agent-1", ...(agent === "cursor" ? { cursorMode: launch.cursorMode } : {}) }) });
} });
// Missing trusted context must not turn ambient values into authority.
const withoutCopy = await AcpxRuntimeHost.open(options, dependencies);
@@ -1830,6 +1855,7 @@ describe("ACPX runtime host", () => {
function runtimePort(
input: {
identity?: AcpxRuntimePort["identity"];
getStatus?: AcpxRuntimePort["getStatus"];
setModel?: NonNullable<AcpxRuntimePort["setModel"]>;
startTurn?: AcpxRuntimePort["startTurn"];
@@ -1837,11 +1863,11 @@ function runtimePort(
} = {},
): AcpxRuntimePort & { close: ReturnType<typeof vi.fn> } {
return {
identity: async () => ({
identity: input.identity ?? (async () => ({
acpxRecordId: "record-1",
backendSessionId: "backend-1",
agentSessionId: "agent-1",
}),
})),
getStatus:
input.getStatus ??
(async () => ({
@@ -1,3 +1,4 @@
import { resolveCursorSessionMode, type CursorSessionMode } from "./cursor-mode.js";
import { dirname, join } from "node:path";
import { bindAcpxAgentFiles } from "./agent-files-binding.js";
import { assertAcpxProfileEnvironment, assertAcpxProfileWorkspace, classifyAcpxProfileError, verifyAcpxProfileInstallation } from "./profile-installation.js";
@@ -77,6 +78,7 @@ const ACPX_ADMISSION_CLEANUP_RETRY_DELAY_MS = 10;
const ACPX_ADMISSION_CLEANUP_RESCHEDULE_MS = 1_000;
export interface AcpxRuntimePortIdentity {
cursorMode?: CursorSessionMode;
acpxRecordId: string;
backendSessionId: string;
agentSessionId: string;
@@ -153,6 +155,7 @@ export interface AcpxRuntimePortOpenOptions {
stateDirectory: string;
providerSessionKey: string;
permissionMode: NativeAcpxPermissionMode;
cursorMode?: CursorSessionMode;
permissionPolicy: ReturnType<typeof acpxRuntimePermissionPolicy>;
launchEnvironment: Readonly<NodeJS.ProcessEnv>;
/** Kernel credential-home quorum inherited by the provider sentinel. */
@@ -226,6 +229,7 @@ export interface OpenAcpxRuntimeHostOptions {
agent: QualifiedAcpxAgent;
model: string;
permissionMode: NativeAcpxPermissionMode;
cursorMode?: CursorSessionMode;
systemInstructions?: string;
runtimeContext?: NativeRuntimeContextSnapshot | null;
environment?: NodeJS.ProcessEnv;
@@ -334,6 +338,7 @@ export class AcpxRuntimeHost {
profile,
requestedModel: options.model,
permissionMode: options.permissionMode,
cursorMode: resolveCursorSessionMode(options.agent, options.cursorMode),
...(["cursor", "copilot", "pi"].includes(options.agent) && options.providerPolicy !== undefined
? { providerPolicy: options.providerPolicy } : {}),
}),
@@ -562,6 +567,7 @@ export class AcpxRuntimeHost {
stateDirectory: sandbox.stateDirectory,
providerSessionKey: binding.profileSessionKey,
permissionMode: binding.permissionMode,
cursorMode: binding.cursorMode,
permissionPolicy: acpxRuntimePermissionPolicy(
binding.permissionMode,
),
@@ -619,6 +625,9 @@ export class AcpxRuntimeHost {
),
dependencies.retainAdmissionCleanup,
);
if (runtimeIdentity.cursorMode !== binding.cursorMode) {
throw new Error("ACPX runtime Cursor mode does not match the admitted session configuration");
}
const observedIdentity: AcpxExpectedSessionIdentity = {
kind: "acpx",
normalizedSessionId: binding.normalizedSessionId,
@@ -0,0 +1,32 @@
{
"schema": "paperclip.cursor.native-mode-offline-proof.v1",
"sourceSha256": "c01657c111f65153d7a40a923f01a5a86d393d1cd6893eaa03f71b9604d2af0c",
"rows": [
{
"selected": "agent",
"nativeMetadata": "default",
"configAcknowledgement": "agent",
"currentModeNotification": "agent",
"reconstructedSessionAcknowledgement": "agent",
"userMessageModeInput": "default"
},
{
"selected": "plan",
"nativeMetadata": "plan",
"configAcknowledgement": "plan",
"currentModeNotification": "plan",
"reconstructedSessionAcknowledgement": "plan",
"userMessageModeInput": "plan"
},
{
"selected": "ask",
"nativeMetadata": "search",
"configAcknowledgement": "ask",
"currentModeNotification": "ask",
"reconstructedSessionAcknowledgement": "ask",
"userMessageModeInput": "search"
}
],
"planHandlerHasModeMutation": false,
"boundary": "pinned native config/session/UserMessage methods; storage, mode enum converter and transport doubled; no inference"
}
@@ -0,0 +1,53 @@
{
"commandDigest": "sha256:aa8c0b2b84786982bcd06b7634bf95be6f2bc42bb8def48a8751dc50cf739b6b",
"declaration": {
"schema": "paperclip.acpx_profile_declaration.v1",
"agent": "cursor",
"agentProfileVersion": 5,
"acpxVersion": "0.13.1",
"agentServerVersion": "2026.09.26-dd393fe",
"patchVersion": "paperclip-cursor-instructions-v2",
"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": "912a37edb67fd7737809c24049dce2db20b1330f98b15a6e43809f0e0943cb6c",
"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": "322f54c7bd533b202a311ce8e2c8916bfe0202790ef8a40fbb36bb89cbd506cb",
"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": "a375fc771dfe86b9b24532f95956ec4b02c5f4f24d80f5db06565160eb3b672c",
"executable": "node",
"entrypoint": "index.js",
"vendorClosureSha256": "bf04ef8ea6a63191067a6b3e15139aa2c793d8419daab246aa3f0a012e1bbcd9"
}
},
"patchVersion": "paperclip-cursor-instructions-v2"
},
"agentFilesBinding": "registered-runtime-context-v1",
"instructionBinding": "native-global-rules-v1",
"instructionAdmission": "synchronous-protocol-guard-v1",
"acpxPatchSha256": "79aad2d688b03362e8cfcbf7a08f78a8383869f6882a9c9ed66f1d18efb94f2b",
"sessionModeAdmission": "native-config-ack-recovery-bound-v1",
"sessionModes": [
"agent",
"plan",
"ask"
],
"defaultSessionMode": "agent"
}
}