@parcha/agentrun-harness-acp 0.1.0-beta.46 → 0.1.0-beta.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,24 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.48 (2026-11-20)
6
+
7
+ - A harness module builds its harness the way the built-in harnesses are built: `entries(builtins, kit)` now gets a kit with `kit.adapterEntry(facts, adapter)` and `kit.acpEntry({ facts, recipe, proxy })`, so the harness is offered its wire's vendor's models, named on that vendor's and OpenRouter's key rows, and gated and named by its own facts. [HARNESS.md](../../HARNESS.md) is the guide, and `examples/harness-module` is a whole module (Goose under an id of its own). <!-- changes/harness-modules-kit.md -->
8
+ - The built-in harnesses read the same facts as before, with or without a module loaded.
9
+ - An adapter harness that loads skills itself gives `kit.adapterEntry` a `skillCheck`: the run's skills it accepts are taken out of the prompt and handed to its adapter as `launch.skills`.
10
+ - `kit.acpEntry`'s offer promises resume `"restart"` unless given `resume: "load"`, which its recipe must declare (`declares.load`); otherwise its first launch is refused (`HARNESS_RESUME_UNDECLARED`).
11
+ - `missing(env)`, on either builder, says what no model key fixes (a binary, say). It is asked before the key, so the harness's offer says it and names no key. An error it or the adapter throws with a `code` refuses the harness with its facts' install fix for that code, as the built-in Goose's are.
12
+ - `@parcha/agentrun-serve/conformance` adds `suiteHostTools`, and `@parcha/agentrun-harness-acp/testing` exports the fake ACP agent (`FAKE_ACP_AGENT`, `fakeAgentRecipe`), so a module's author runs the conformance suite with no binary, model or key. The run spec a subject hands `createAdapterLoop` names its harness's `facts`.
13
+ - An ACP agent's failure words cut the recipe's keys before they are shortened, so a cut that lands inside a key (the last 300 characters, or the start of the stderr tail the adapter keeps) leaves no piece of it. <!-- changes/acp-cut-keys-before-tail.md -->
14
+
15
+ ## 0.1.0-beta.47 (2026-11-19)
16
+
17
+ **Breaking:**
18
+
19
+ - The package no longer records a binary's first-seen digest itself: `fileDigestRecord`, `verifyFirstSeen`, the `DigestRecord` type and `ACP_CODES.binaryDrift` (`ACP_BINARY_DRIFT`) are gone. A binary no pin names has its first digest recorded by AgentRun's installer alone (`agentrun harness install`), and a later binary that differs is refused there and at `harness-check` with `HARNESS_BINARY_MISMATCH`. Code that called `verifyFirstSeen` pins the binary's sha256 and calls `verifyPinnedBinary`, or installs it through `agentrun harness install --recipe`. <!-- changes/acp-one-first-seen-pin.md -->
20
+
21
+ **Changes:**
22
+
5
23
  - New package `@parcha/agentrun-harness-acp` (private for now): any Agent Client Protocol agent as a harness adapter, from a recipe that says how to start it over stdio, what it declares (`session/load`, MCP over HTTP or stdio), where it keeps its sessions and who bills its model. Built on the official `@agentclientprotocol/sdk` 2.7.0.
6
24
  - The agent runs in a private HOME with an environment allowlist (PATH, LANG, TZ and the recipe's own variables), in a process group of its own. Its session store is mirrored into the session's records, credential files left out, so another runner's agent loads it back.
7
25
  - The host's tools reach it as one loopback MCP server, over HTTP when it is declared and advertised, else stdio. Each call runs once through the kernel's tool bridge, under the agent's own tool call id.
@@ -19,3 +37,15 @@
19
37
  - The install downloads the pinned archive for this platform (`GOOSE_PIN`) with node's fetch, checks its sha256 before unpacking, unpacks it with the system `tar -xjf` (a fixed argument list, no shell) into a fresh folder beside `<data>/harnesses/goose`, checks the binary's sha256, then renames the folder into place and makes it read-only. A crash part way leaves the old folder or none, and the next install sweeps what it left. Every failure is named (`HARNESS_PLATFORM_UNSUPPORTED`, `HARNESS_DOWNLOAD_FAILED`, `HARNESS_ARCHIVE_MISMATCH`, `HARNESS_UNPACK_FAILED`, `HARNESS_BINARY_MISMATCH`, `HARNESS_INSTALL_BUSY`) with the command to try again. Run again with the pinned binary in place, it downloads nothing. No provider key reaches it.
20
38
  - Capabilities list Goose (label, its promises `resume: load`, `tool_gate: permission`, `billing: proxy`) only once the pinned binary is installed and verified, read at AgentRun's start: restart AgentRun after installing it. Before then an agent on goose saves with a warning, and its run is refused (`agent_not_runnable`), each naming `HARNESS_NOT_INSTALLED` and the install command.
21
39
  - `@parcha/agentrun-harness-acp` exports Goose's facts (`gooseFacts`), its install command (`GOOSE_INSTALL`) and its code (`GOOSE_NOT_INSTALLED`). The package is held from npm for now, so a serve installed from npm has no goose row until it ships.
40
+ - Cursor runs as a harness (`cursor`), over ACP, on its owner's own Cursor API key: install its pinned release with `agentrun harness install cursor` (or `agentrun-serve install-harness cursor`), set `CURSOR_API_KEY` where AgentRun starts, and restart. Each run is billed to your Cursor plan, under Cursor's terms, with no spend cap of AgentRun's: it stops after 20 turns or 100 tool calls (`AGENTRUN_CURSOR_MAX_TURNS`, `AGENTRUN_CURSOR_MAX_TOOL_CALLS`), and capabilities show its card (`harnesses[].card`). <!-- changes/cursor-harness.md -->
41
+ - Cursor makes no file edits: every Write is denied in its CLI config until Cursor asks before an edit, as it asks before a shell command or a tool. Its own shell commands, and any other call of its own, are asked first, of a person who can approve them, and refused where no one can (they run on AgentRun's host, never on the run's computer, so bash's setting is not theirs); AgentRun's tools over MCP go through the agent's tool settings.
42
+ - `CURSOR_API_KEY` is handed to Cursor's runs alone, read by name at each start. The credential Cursor derives from it (`auth.json`, which would hold its tokens and the key itself) is never written: its path is a folder Cursor cannot write a file at, and Cursor runs on the key in its environment, so a killed run or server leaves no credential on disk. Cursor's warning that it could not save one is left out of a failed run's words (a recipe's `quiet`). Its whole private HOME is deleted when its process ends.
43
+ - A model is `cursor/<model-id>` (`cursor/gpt-5.4-nano`; `cursor/default` for Cursor's own default), checked against the models Cursor lists for the key (`ACP_MODEL_UNLISTED`). A key whose Cursor team administrator turned headless CLI use off is refused as `CURSOR_HEADLESS_DISABLED`.
44
+ - The release is pinned by its archive's sha256, its launcher's, and a digest of every file it unpacks to; a drift in any of them refuses the run (`ACP_BINARY_MISMATCH`). The archive installer takes tar.gz as well as tar.bz2 (`ARCHIVE_FORMATS`), and so does a harness recipe's loader. A recipe may not take any id the server's harness table already has, `cursor` and `goose` included.
45
+ - Cursor's release is pinned for linux-x86_64 alone. On any other host, a Mac included, Cursor is refused `ACP_BINARY_UNPINNED` before any install is looked at. `cursorRelease(platform)` gives the release pinned for a platform, or none.
46
+ - A new Cursor pin needs a key walk on it first. The walk runs a turn, a hard kill mid-turn and the close on the real binary. At each point it counts the files of the session folder that hold the key or a JWT-shaped token, and it never prints them. CI refuses a pin that the walk's record does not name, so a release that starts saving its key somewhere else fails before it ships.
47
+ - Bring your own harness, door 1: a recipe. A JSON file names an ACP agent's registry release (the archive's URL and sha256, the binary inside it), its model billing (through AgentRun's model proxy, or the owner's plan with turn and tool-call limits), its literal env, files and session folders in the private HOME, and what it declares. `agentrun harness install --recipe FILE` installs the release, and `agentrun harness-check --recipe FILE --model PROVIDER/MODEL` runs it for real: the agent's own tools off, its environment an allowlist, the cap or plan limits, the pinned binary at every start, no side request (stage 2); a SIGKILL then resume, a denied call, one of AgentRun's tools over MCP, a second runner (stage 3). It writes a JSON report and prints the three facts a harness row carries: `resume`, `tool_gate`, `billing`. See [docs/harness-recipe.md](https://github.com/Parcha-ai/agentrun/blob/v0.1.0-beta.47/docs/harness-recipe.md) and [HARNESS-SCORECARD.md](https://github.com/Parcha-ai/agentrun/blob/main/HARNESS-SCORECARD.md), which rates 25 agents. <!-- changes/harness-recipe-door-one.md -->
48
+
49
+ The loader refuses a recipe that breaks one of five rules by its code: a key that is not the harness's own (`RECIPE_KEY_NOT_OWN`), a binary not pinned to a registry archive (`RECIPE_BINARY_UNPINNED`), a file or folder outside the private HOME (`RECIPE_PATH_OUTSIDE`), an install step of its own (`RECIPE_INSTALLS_ITSELF`), an environment beyond the allowlist (`RECIPE_ENV_NOT_ALLOWLIST`). A release whose registry entry lists no binary digest is pinned to the first one its owner's install records; a later binary that differs is refused, at an install and a check alike (`HARNESS_BINARY_MISMATCH`). A recipe's keys reach the agent the way a run's do, read by name at its start: `harness-check` on a host without one is refused before the agent starts (`ACP_KEY_MISSING`). The ACP adapter logs each permission the agent asks for (`acp: the agent asked permission`).
50
+ - `@parcha/agentrun-harness-acp`, the adapter that runs an Agent Client Protocol agent as a harness (Goose's among them), is no longer held: the next release publishes it, after the kernel and before the server. `@parcha/agentrun-serve` now depends on it, so a server installed from npm has the Goose row: its owner installs Goose's pinned binary with `agentrun-serve install-harness goose --data <dir>`, restarts the server, and Goose is offered. The package's archive holds `dist`, Goose's recipe (`recipes/goose.json`), the README, LICENSE and NOTICE; `scripts/verify-packages.mjs` imports its root and `./facts` in the clean consumer and reads the recipe from the installed package. <!-- changes/unhold-harness-acp.md -->
51
+ - The ACP adapter ties `agentrun: <tool>`, the tool's underscores as spaces (Goose 1.59.2's title), to our tool, so the host's gate is asked once per call, at the MCP call, not twice. <!-- changes/acp-goose-tool-title.md -->
package/NOTICE CHANGED
@@ -1,2 +1,4 @@
1
1
  AgentRun
2
2
  Copyright 2026 Parcha Labs, Inc.
3
+
4
+ The boxd computer provider (packages/computer/src/boxd.ts) was contributed by Michiel Voortman.
package/README.md CHANGED
@@ -39,5 +39,5 @@ const adapter = acpAdapter({
39
39
  });
40
40
  ```
41
41
 
42
- The tests run on a fake ACP agent (`test/fake-acp-agent.mjs`) that plays Goose (load, MCP over HTTP, a permission
42
+ The tests run on a fake ACP agent (`testing/fake-acp-agent.mjs`, exported as `@parcha/agentrun-harness-acp/testing`) that plays Goose (load, MCP over HTTP, a permission
43
43
  request for every tool) and Cursor (load, permission for shell and MCP but not edits), and an agent with no load.
@@ -0,0 +1,43 @@
1
+ import type { AgentAdapter, ModelPort } from "@parcha/agentrun-kernel";
2
+ import { type ParentWatch } from "@parcha/agentrun-kernel/host";
3
+ import { type AcpRecipe } from "./recipe.js";
4
+ import type { ConfineChild } from "./host/child.js";
5
+ export interface AcpAdapterOptions {
6
+ /** The agent: how to start it, what it declares, where it keeps its sessions, who bills its model. */
7
+ recipe: AcpRecipe;
8
+ /** Where sessions keep their private directories when the host lends none (`io.dir`): one per session key. */
9
+ sessionsDir?: string;
10
+ /** Start the agent under the host's confinement (a `setpriv --no-new-privs` prefix, say). */
11
+ confine?: ConfineChild;
12
+ parentWatch?: ParentWatch;
13
+ /** The environment the child's allowlist (PATH, LANG, TZ) reads. Default process.env. */
14
+ env?: Readonly<Record<string, string | undefined>>;
15
+ /** Proxy billing: what each agent process gets to reach the host's model proxy (its variables), closed with it, started
16
+ * on the session's booking. Required for a recipe billed `proxy` (Goose's is `gooseProxy`). */
17
+ proxy?: AcpProxy;
18
+ /** Run before every start of the agent's process, a restart included (Goose's: its pin, verifyPinnedBinaryAsync). A
19
+ * throw refuses that start. */
20
+ beforeStart?: (command: string) => Promise<void>;
21
+ /** How long an MCP call waits for the agent's tool_call that announces it. Default 10 s. */
22
+ callIdWaitMs?: number;
23
+ /** How long the agent may take to start and open its session. Default 60 s. */
24
+ startMs?: number;
25
+ log?: (message: string, fields?: Record<string, unknown>) => void;
26
+ }
27
+ /** What a proxy-billed agent process's proxy is started for: its session's booking and tools, and its drive's stop. */
28
+ export interface AcpProxySession {
29
+ /** The session's booking (`SessionIO.models`): every paid request is asked about before it leaves and booked once it
30
+ * answers, the runner's cap and books for every harness. */
31
+ readonly models: ModelPort;
32
+ /** The host's tools, by the names the session has them under. */
33
+ readonly tools: readonly string[];
34
+ /** Ends the agent's drive: its turn ends failed in `reason`'s words. */
35
+ halt(reason: unknown): void;
36
+ }
37
+ /** A proxy for one agent process: the variables that point it at the proxy, and the proxy's close. */
38
+ export type AcpProxy = (session: AcpProxySession) => Promise<{
39
+ env: Record<string, string>;
40
+ close(): Promise<void>;
41
+ }>;
42
+ /** The ACP agent `options.recipe` names, as a harness adapter under the recipe's id. */
43
+ export declare function acpAdapter(options: AcpAdapterOptions): AgentAdapter;
@@ -0,0 +1,201 @@
1
+ // Any ACP agent as an AgentRun harness adapter, from its recipe. Written for AgentRun.
2
+ //
3
+ // A session is the ACP harness (harness.ts) driven over the session's own records (the kernel's openDrive on the writer
4
+ // the runner lends, `io.writer`): the agent over stdio in a private HOME, the host's tools, exactly those `spec.tools`
5
+ // names, as one loopback MCP server, and each permission request for a tool of the agent's own through the host's gate.
6
+ // Its model is the agent's: a plan-billed agent's requests never reach the host, so the adapter bounds the run itself
7
+ // (the recipe's maxTurns and maxToolCalls); a proxy-billed one's go through the host's proxy (the `proxy` option), which
8
+ // asks the session's booking (`io.models`) before each paid request and books it once it answers.
9
+ import { createHash, randomUUID } from "node:crypto";
10
+ import { join } from "node:path";
11
+ import { toolSchemaProblems } from "@parcha/agentrun-kernel";
12
+ import { abortedOutcome, openDrive, pendingSubmissions, SessionHalt } from "@parcha/agentrun-kernel/kernel";
13
+ import { bridgeTool, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
14
+ import { serialWriter } from "@parcha/agentrun-kernel/host";
15
+ import { acpHarness, sentSubmissions } from "./harness.js";
16
+ import { recipeProblems } from "./recipe.js";
17
+ import { cutKeys, keysToCut } from "./host/key-cut.js";
18
+ /** A tool name every ACP agent we know keeps whole in its MCP client. */
19
+ const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
20
+ /** How long a stop waits for the agent to end the turn itself (session/cancel) before the drive is halted. */
21
+ const INTERRUPT_MS = 3_000;
22
+ /** The adapter's event for a harness live event, if it has one. */
23
+ function adapterEvent(event) {
24
+ const e = event;
25
+ if (e?.type === "text" && typeof e.delta === "string")
26
+ return { type: "text", delta: e.delta };
27
+ if (e?.type === "tool_start" && typeof e.name === "string")
28
+ return { type: "tool_start", callId: String(e.callId ?? ""), name: e.name, args: e.args, ...(typeof e.parent === "string" ? { parent: e.parent } : {}) };
29
+ if (e?.type === "tool_end" && typeof e.name === "string")
30
+ return { type: "tool_end", callId: String(e.callId ?? ""), name: e.name, isError: e.isError === true, ...(typeof e.result === "string" ? { result: e.result } : {}), ...(e.truncated === true ? { truncated: true } : {}) };
31
+ return undefined;
32
+ }
33
+ const turnsIn = (drive) => transcriptOf(drive.state()).filter((r) => r.data?.type === "turn");
34
+ /** The ACP agent `options.recipe` names, as a harness adapter under the recipe's id. */
35
+ export function acpAdapter(options) {
36
+ const recipe = options.recipe;
37
+ const problems = recipeProblems(recipe);
38
+ if (problems.length)
39
+ throw new Error(`acp: the recipe ${JSON.stringify(recipe?.id ?? "")} cannot run: ${problems.join("; ")}`);
40
+ if (recipe.billing.kind === "proxy" && !options.proxy)
41
+ throw new Error(`acp: the recipe ${recipe.id} is billed through the host's proxy, and the adapter was given no proxy option`);
42
+ const label = recipe.label ?? recipe.id;
43
+ return {
44
+ id: recipe.id,
45
+ check(spec) {
46
+ const problems = [];
47
+ if (spec.context === "fork")
48
+ problems.push(`${label} sessions cannot fork another session's transcript; declare context: "fresh"`);
49
+ const seen = new Set();
50
+ for (const tool of spec.tools) {
51
+ if (!TOOL_NAME.test(tool.name))
52
+ problems.push(`the tool name ${JSON.stringify(tool.name.slice(0, 80))} is not one an MCP client keeps whole (letters, digits, _ and -, at most 64)`);
53
+ if (seen.has(tool.name))
54
+ problems.push(`the tool ${tool.name} is given twice`);
55
+ seen.add(tool.name);
56
+ try {
57
+ problems.push(...toolSchemaProblems(tool.name, tool.inputSchema));
58
+ }
59
+ catch (error) {
60
+ problems.push(`${tool.name}: /: the tool's schema could not be checked (${String(error?.message ?? error).slice(0, 120)})`);
61
+ }
62
+ }
63
+ return problems;
64
+ },
65
+ async open(spec, io) {
66
+ const problems = this.check(spec);
67
+ if (problems.length)
68
+ throw new Error(`acp: ${problems.join("; ")}`);
69
+ const dir = io.dir ?? (options.sessionsDir ? join(options.sessionsDir, createHash("sha256").update(spec.key).digest("hex").slice(0, 32)) : undefined);
70
+ if (!dir)
71
+ throw new Error("acp: a session needs a private directory: the host lends one (io.dir), or pass sessionsDir");
72
+ const instructions = spec.system.join("\n\n");
73
+ let control;
74
+ const harness = acpHarness({
75
+ recipe,
76
+ tools: spec.tools.map((tool) => bridgeTool(tool)),
77
+ ...(instructions ? { instructions } : {}),
78
+ dir,
79
+ ...(io.cwd ? { cwd: io.cwd } : {}),
80
+ ...(options.confine ? { confine: options.confine } : {}),
81
+ ...(options.parentWatch ? { parentWatch: options.parentWatch } : {}),
82
+ ...(options.env ? { env: options.env } : {}),
83
+ ...(options.proxy ? { proxy: (drive) => options.proxy({ models: io.models, tools: spec.tools.map((tool) => tool.name), halt: drive.halt }) } : {}),
84
+ ...(options.beforeStart ? { beforeStart: options.beforeStart } : {}),
85
+ ...(options.callIdWaitMs !== undefined ? { callIdWaitMs: options.callIdWaitMs } : {}),
86
+ ...(options.startMs !== undefined ? { startMs: options.startMs } : {}),
87
+ ...(options.log ? { log: options.log } : {}),
88
+ // The host's gate: asked by the kernel's tool bridge for our tools, and by the harness for the agent's own.
89
+ ...(io.gate ? { gate: (call) => io.gate(call) } : {}),
90
+ }, (c) => void (control = c));
91
+ const live = (event) => {
92
+ const mapped = adapterEvent(event);
93
+ if (mapped)
94
+ io.onEvent(mapped);
95
+ };
96
+ // Every drive of this session writes through one serialized writer, so a drive opened after an interrupt reads only
97
+ // once the halted drive's last writes are in.
98
+ const writer = serialWriter(io.writer);
99
+ const open = () => openDrive({ writer, signal: io.signal, live });
100
+ let drive = await open();
101
+ const initial = drive.state();
102
+ // A turn is open while the session holds input no turn placed, or a turn with no end (its recovery note).
103
+ const holdsTurn = (folded) => Boolean(recoveryNote(folded)) || pendingSubmissions(folded).length > 0;
104
+ let state = holdsTurn(initial) ? "open_turn" : initial.submissions.length === 0 && turnsIn(drive).length === 0 ? "new" : "idle";
105
+ let running;
106
+ let closed = false;
107
+ let interrupted = false;
108
+ const run = () => {
109
+ const before = turnsIn(drive).length;
110
+ const current = drive;
111
+ state = "idle";
112
+ interrupted = false;
113
+ running = (async () => {
114
+ let outcome;
115
+ let cut;
116
+ try {
117
+ await harness.drive(current);
118
+ const ended = turnsIn(current).slice(before).at(-1)?.data;
119
+ if (ended?.stopReason === "length")
120
+ cut = { stopReason: "length" };
121
+ outcome = ended?.status ? { status: ended.status, ...(ended.error ? { error: ended.error } : {}) } : interrupted ? { status: "interrupted" } : { status: "failed", error: "the turn ended with no outcome in the session's records" };
122
+ }
123
+ catch (error) {
124
+ // Stopped by the session or its host: interrupted. Halted by anything else: failed, naming why, the recipe's keys
125
+ // cut before the words are shortened (key-cut.ts).
126
+ const keys = keysToCut((recipe.keys ?? []).map((name) => (options.env ?? process.env)[name]));
127
+ outcome = current.signal.aborted ? abortedOutcome(current.signal, io.signal) : { status: "failed", error: cutKeys(String(error?.message ?? error), keys).slice(0, 500) };
128
+ if (current.signal.aborted)
129
+ state = holdsTurn(current.state()) ? "open_turn" : "idle";
130
+ }
131
+ io.onEvent({ type: "turn_end", status: outcome.status, ...(cut && outcome.status === "completed" ? cut : {}) });
132
+ return outcome;
133
+ })();
134
+ return running;
135
+ };
136
+ // A drive that was halted holds the session no more: the next turn opens a fresh one, on the same writer.
137
+ const ready = async () => {
138
+ if (closed)
139
+ throw new Error("acp: the session is closed");
140
+ if (running)
141
+ await running;
142
+ if (drive.signal.aborted && !io.signal.aborted)
143
+ drive = await open();
144
+ };
145
+ return {
146
+ get state() {
147
+ return state;
148
+ },
149
+ async send(text) {
150
+ await ready();
151
+ // A submission of its own every time, as every process adapter's: the host's message id names its row, and a
152
+ // message sent again after a runner was lost is a new turn of the session's, never folded into the one placed.
153
+ await drive.submit({ id: randomUUID(), kind: "prompt", text });
154
+ void run();
155
+ },
156
+ async recover() {
157
+ if (state !== "open_turn")
158
+ throw new Error("acp: there is no turn to recover");
159
+ await ready();
160
+ void run();
161
+ },
162
+ async settleOpenTurn(settle = {}) {
163
+ if (state !== "open_turn")
164
+ throw new Error("acp: there is no turn to settle");
165
+ await ready();
166
+ // The turn's end in the session's own transcript: nothing is sent, the agent is not started. A prompt the turn
167
+ // placed and never sent (no send mark) is carried into the next message.
168
+ const folded = drive.state();
169
+ const sent = sentSubmissions(folded);
170
+ const unsent = (recoveryNote(folded)?.turn.placed ?? []).filter((id) => !sent.has(id));
171
+ await settleTurn(drive, { unsent, ...(settle.opening === undefined ? {} : { host: settle.opening }) });
172
+ state = "idle";
173
+ },
174
+ async turnEnd() {
175
+ if (!running)
176
+ throw new Error("acp: no turn is in flight");
177
+ return running;
178
+ },
179
+ async interrupt() {
180
+ // The agent is asked to end the turn (session/cancel), and no end is written for it: the turn stays open. If it
181
+ // does not end it within INTERRUPT_MS, the drive is halted, which ends the agent's process.
182
+ interrupted = true;
183
+ const stopped = control ? await control.interrupt(INTERRUPT_MS).catch(() => false) : false;
184
+ if (!stopped)
185
+ drive.halt?.(new SessionHalt("interrupted"));
186
+ await running?.catch(() => { });
187
+ if (holdsTurn(drive.state()))
188
+ state = "open_turn";
189
+ },
190
+ async close() {
191
+ if (closed)
192
+ return;
193
+ closed = true;
194
+ drive.halt?.(new SessionHalt("closed"));
195
+ await running?.catch(() => { });
196
+ await harness.close();
197
+ },
198
+ };
199
+ },
200
+ };
201
+ }
@@ -0,0 +1,39 @@
1
+ /** The MCP server's name, as the agent is given it. */
2
+ export declare const MCP_SERVER = "agentrun";
3
+ /** JSON text of `value` with every object's keys sorted: two argument objects that say the same are the same text. */
4
+ export declare function canonical(value: unknown): string;
5
+ /** The ACP tool kinds of a call with effects of its own (a shell, a file write, a delete, a move, a fetch): never one of
6
+ * our tools, whatever its title says. */
7
+ export declare const NATIVE_EFFECT_KINDS: ReadonlySet<string>;
8
+ /** The host tool an ACP tool call names, by the agent's own name for our MCP server's tools (Goose `agentrun__<tool>`, or
9
+ * as Goose 1.59.2 titles it, `agentrun: <tool>` with the tool's underscores as spaces; Cursor `agentrun-<tool>: <tool>`),
10
+ * when it is one of `tools` and its kind is not one with effects of its own. The title is the agent's text, so this alone
11
+ * is never evidence that a call is ours: a permission request also needs the tool_call that announced it
12
+ * (CallIds.announced). */
13
+ export declare function ourTool(update: {
14
+ title?: string | null;
15
+ name?: string | null;
16
+ kind?: string | null;
17
+ }, tools: ReadonlySet<string>): string | undefined;
18
+ /** The agent's announced calls of our tools, matched to the MCP calls that reach the server. */
19
+ export declare class CallIds {
20
+ private readonly seen;
21
+ private readonly waiting;
22
+ private readonly used;
23
+ private readonly tools;
24
+ /** The agent announced call `id` of `tool` with `input` (undefined: it reported none). */
25
+ add(id: string, tool: string, input: unknown): void;
26
+ /** Whether the agent announced `id` (matched or not). */
27
+ has(id: string): boolean;
28
+ /** The tool of ours the agent's tool_call `id` was announced as, or undefined when no such tool_call came. */
29
+ announced(id: string): string | undefined;
30
+ /** The id of an MCP call of `tool` with `args`: the agent's announced one, waited for at most `ms`; undefined when none
31
+ * came by then. */
32
+ take(tool: string, args: Record<string, unknown>, signal: AbortSignal, ms: number): Promise<string | undefined>;
33
+ }
34
+ /** The gate's id for a permission request of the agent's own tool: the same for the same request after a resume. */
35
+ export declare function permissionCallId(turn: string, request: {
36
+ title?: string | null;
37
+ kind?: string | null;
38
+ rawInput?: unknown;
39
+ }, nth: number): string;
package/dist/calls.js ADDED
@@ -0,0 +1,138 @@
1
+ // How an ACP agent's calls get their ids. Written for AgentRun.
2
+ // - A call of one of our tools reaches the adapter twice: as the agent's `tool_call` update (its own id, a title, the
3
+ // input it reports) over ACP, and as the MCP call itself over HTTP or stdio, which names no id. The two are matched by
4
+ // the host tool's name and the arguments' canonical JSON, first in first out, as OpenCode's calls are matched to the
5
+ // model's: the call runs under the agent's own id, which is the memo key a resumed session asks under again.
6
+ // - A permission request for one of the agent's own tools (a shell, an edit) is the host gate's call. Its id is made from
7
+ // what a second request for the same call after a resume says the same: the open turn, the tool's title, kind and input,
8
+ // and how many such requests came before it in the drive. Never from the agent's tool call id, which a new agent
9
+ // session (no load) mints afresh.
10
+ import { createHash } from "node:crypto";
11
+ /** The MCP server's name, as the agent is given it. */
12
+ export const MCP_SERVER = "agentrun";
13
+ const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
14
+ /** JSON text of `value` with every object's keys sorted: two argument objects that say the same are the same text. */
15
+ export function canonical(value) {
16
+ if (Array.isArray(value))
17
+ return `[${value.map(canonical).join(",")}]`;
18
+ if (isPlain(value))
19
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
20
+ return JSON.stringify(value) ?? "null";
21
+ }
22
+ /** The ACP tool kinds of a call with effects of its own (a shell, a file write, a delete, a move, a fetch): never one of
23
+ * our tools, whatever its title says. */
24
+ export const NATIVE_EFFECT_KINDS = new Set(["execute", "edit", "delete", "move", "fetch"]);
25
+ /** The host tool an ACP tool call names, by the agent's own name for our MCP server's tools (Goose `agentrun__<tool>`, or
26
+ * as Goose 1.59.2 titles it, `agentrun: <tool>` with the tool's underscores as spaces; Cursor `agentrun-<tool>: <tool>`),
27
+ * when it is one of `tools` and its kind is not one with effects of its own. The title is the agent's text, so this alone
28
+ * is never evidence that a call is ours: a permission request also needs the tool_call that announced it
29
+ * (CallIds.announced). */
30
+ export function ourTool(update, tools) {
31
+ if (typeof update.kind === "string" && NATIVE_EFFECT_KINDS.has(update.kind))
32
+ return undefined;
33
+ const candidates = [];
34
+ for (const said of [update.name, update.title]) {
35
+ if (typeof said !== "string")
36
+ continue;
37
+ const goose = new RegExp(`^${MCP_SERVER}__(.+)$`).exec(said);
38
+ if (goose)
39
+ candidates.push(goose[1]);
40
+ const cursor = new RegExp(`^${MCP_SERVER}(-[^:]*)?: (.+)$`).exec(said);
41
+ if (cursor)
42
+ candidates.push(cursor[2].trim(), ...(cursor[1] ? [] : [cursor[2].replace(/ /g, "_")]));
43
+ }
44
+ return candidates.find((name) => tools.has(name));
45
+ }
46
+ /** The agent's announced calls of our tools, matched to the MCP calls that reach the server. */
47
+ export class CallIds {
48
+ seen = new Map();
49
+ waiting = new Map();
50
+ used = new Set();
51
+ tools = new Map();
52
+ /** The agent announced call `id` of `tool` with `input` (undefined: it reported none). */
53
+ add(id, tool, input) {
54
+ if (this.used.has(id))
55
+ return;
56
+ if (!this.tools.has(id))
57
+ this.tools.set(id, tool);
58
+ // An announced call with no input is matched by its tool alone; one with input only by its tool and that input, so
59
+ // it never takes an MCP call of the same tool with other arguments that is waiting for its own announcement.
60
+ const key = input === undefined || input === null ? `${tool}\0*` : `${tool}\0${canonical(isPlain(input) ? input : {})}`;
61
+ const waiter = this.waiting.get(key)?.shift();
62
+ if (waiter) {
63
+ this.used.add(id);
64
+ waiter(id);
65
+ return;
66
+ }
67
+ const list = this.seen.get(key) ?? [];
68
+ if (!list.includes(id))
69
+ list.push(id);
70
+ this.seen.set(key, list);
71
+ }
72
+ /** Whether the agent announced `id` (matched or not). */
73
+ has(id) {
74
+ return this.used.has(id) || [...this.seen.values()].some((ids) => ids.includes(id));
75
+ }
76
+ /** The tool of ours the agent's tool_call `id` was announced as, or undefined when no such tool_call came. */
77
+ announced(id) {
78
+ return this.tools.get(id);
79
+ }
80
+ /** The id of an MCP call of `tool` with `args`: the agent's announced one, waited for at most `ms`; undefined when none
81
+ * came by then. */
82
+ async take(tool, args, signal, ms) {
83
+ const keys = [`${tool}\0${canonical(args)}`, `${tool}\0*`];
84
+ const ready = (from) => {
85
+ for (const key of from) {
86
+ const id = this.seen.get(key)?.shift();
87
+ if (id) {
88
+ this.used.add(id);
89
+ return id;
90
+ }
91
+ }
92
+ return undefined;
93
+ };
94
+ // Once the wait is over, the oldest announced call of the tool whose reported input differs from what reached MCP.
95
+ const loose = () => ready([...this.seen.keys()].filter((key) => key.startsWith(`${tool}\0`)));
96
+ const now = ready(keys);
97
+ if (now)
98
+ return now;
99
+ return new Promise((resolve, reject) => {
100
+ const lists = keys.map((key) => {
101
+ const list = this.waiting.get(key) ?? [];
102
+ this.waiting.set(key, list);
103
+ return list;
104
+ });
105
+ const drop = () => {
106
+ for (const list of lists) {
107
+ const at = list.indexOf(done);
108
+ if (at >= 0)
109
+ list.splice(at, 1);
110
+ }
111
+ };
112
+ const done = (id) => {
113
+ clearTimeout(timer);
114
+ signal.removeEventListener("abort", stop);
115
+ drop();
116
+ resolve(id);
117
+ };
118
+ const stop = () => {
119
+ clearTimeout(timer);
120
+ drop();
121
+ reject(signal.reason instanceof Error ? signal.reason : new Error("the call was stopped"));
122
+ };
123
+ const timer = setTimeout(() => {
124
+ signal.removeEventListener("abort", stop);
125
+ drop();
126
+ resolve(loose());
127
+ }, ms);
128
+ signal.addEventListener("abort", stop, { once: true });
129
+ for (const list of lists)
130
+ list.push(done);
131
+ });
132
+ }
133
+ }
134
+ /** The gate's id for a permission request of the agent's own tool: the same for the same request after a resume. */
135
+ export function permissionCallId(turn, request, nth) {
136
+ const digest = createHash("sha256").update(canonical({ turn, title: request.title ?? "", kind: request.kind ?? "", input: request.rawInput ?? null, nth })).digest("hex");
137
+ return `acp-perm-${digest.slice(0, 24)}`;
138
+ }
@@ -0,0 +1,27 @@
1
+ import type { AdapterFacts } from "@parcha/agentrun-kernel";
2
+ /** The command that installs the pinned Cursor CLI into an AgentRun server's data (`<data>/harnesses/cursor`). */
3
+ export declare const CURSOR_INSTALL = "agentrun harness install cursor";
4
+ /** The codes Cursor's own refusals carry. */
5
+ export declare const CURSOR_CODES: Readonly<{
6
+ /** Cursor's team administrator turned headless Cursor CLI use off (its dashboard's switch). Cursor checks it in print
7
+ * mode (`agent -p`); where it says so over ACP, a run is refused under this code. */
8
+ readonly headlessDisabled: "CURSOR_HEADLESS_DISABLED";
9
+ /** Cursor is not installed where the server looks. */
10
+ readonly notInstalled: "HARNESS_NOT_INSTALLED";
11
+ }>;
12
+ /** Where a run of Cursor stops, its spend being its owner's plan's and never metered by AgentRun: its session/prompt
13
+ * turns and its tool calls, each counted from the session's records across runners (ACP_CODES.turnLimit,
14
+ * ACP_CODES.toolCallLimit). The owner may set lower or higher ones (the server's AGENTRUN_CURSOR_MAX_TURNS and
15
+ * AGENTRUN_CURSOR_MAX_TOOL_CALLS). */
16
+ export declare const CURSOR_LIMITS: Readonly<{
17
+ maxTurns: 20;
18
+ maxToolCalls: 100;
19
+ }>;
20
+ export type CursorLimits = {
21
+ readonly maxTurns: number;
22
+ readonly maxToolCalls: number;
23
+ };
24
+ /** The card the owner reads before choosing Cursor: whose terms and key it runs on, who bills it and where it stops,
25
+ * that it edits no file, and how its team's switch is said. */
26
+ export declare function cursorCard(limits?: CursorLimits): string;
27
+ export declare const cursorFacts: AdapterFacts;
@@ -0,0 +1,55 @@
1
+ import { ACP_CODES } from "./facts.js";
2
+ import { CURSOR_PIN } from "./pinned-binary.js";
3
+ /** The command that installs the pinned Cursor CLI into an AgentRun server's data (`<data>/harnesses/cursor`). */
4
+ export const CURSOR_INSTALL = "agentrun harness install cursor";
5
+ /** The codes Cursor's own refusals carry. */
6
+ export const CURSOR_CODES = Object.freeze({
7
+ /** Cursor's team administrator turned headless Cursor CLI use off (its dashboard's switch). Cursor checks it in print
8
+ * mode (`agent -p`); where it says so over ACP, a run is refused under this code. */
9
+ headlessDisabled: "CURSOR_HEADLESS_DISABLED",
10
+ /** Cursor is not installed where the server looks. */
11
+ notInstalled: "HARNESS_NOT_INSTALLED",
12
+ });
13
+ /** Where a run of Cursor stops, its spend being its owner's plan's and never metered by AgentRun: its session/prompt
14
+ * turns and its tool calls, each counted from the session's records across runners (ACP_CODES.turnLimit,
15
+ * ACP_CODES.toolCallLimit). The owner may set lower or higher ones (the server's AGENTRUN_CURSOR_MAX_TURNS and
16
+ * AGENTRUN_CURSOR_MAX_TOOL_CALLS). */
17
+ export const CURSOR_LIMITS = Object.freeze({ maxTurns: 20, maxToolCalls: 100 });
18
+ const plural = (n, one) => `${n} ${one}${n === 1 ? "" : "s"}`;
19
+ /** The card the owner reads before choosing Cursor: whose terms and key it runs on, who bills it and where it stops,
20
+ * that it edits no file, and how its team's switch is said. */
21
+ export function cursorCard(limits = CURSOR_LIMITS) {
22
+ return [
23
+ "Cursor: runs Cursor's CLI on your Cursor API key, under Cursor's terms (cursor.com/terms and its Acceptable Use Policy). AgentRun does not resell Cursor.",
24
+ `Each run is billed to your Cursor plan, with no spend cap of AgentRun's: it stops after ${plural(limits.maxTurns, "turn")} or ${plural(limits.maxToolCalls, "tool call")}.`,
25
+ "Cursor makes no file edits: every Write is denied until Cursor asks before an edit, as it asks before a shell command or a tool.",
26
+ `If your Cursor team administrator turned headless CLI use off, its runs are refused (${CURSOR_CODES.headlessDisabled}).`,
27
+ ].join(" ");
28
+ }
29
+ export const cursorFacts = Object.freeze({
30
+ id: "cursor",
31
+ label: "Cursor",
32
+ // Its model is Cursor's, billed to the owner's plan on the owner's key: no request of it reaches a proxy of ours.
33
+ wire: "plan",
34
+ // ACP has no steer: a message mid-turn waits for the turn's end.
35
+ steer: false,
36
+ // A call Cursor started is never run again: one cut off is reported interrupted, never repeated.
37
+ rerunsStarted: false,
38
+ // An answer cut at the output limit (stopReason max_tokens) ends the turn.
39
+ recoversCutAnswers: 0,
40
+ // One run's memory: Cursor's own processes (its launcher, its node and its worker) peaked at 454 MiB resident, summed,
41
+ // on the S4 live runs through serve (RSS sampled each second; its largest one process 288 MiB), beside the run's.
42
+ runMib: 512,
43
+ // Cursor picks its own thinking per model (the model id's [reasoning=...]): no level is passed to it.
44
+ thinking: Object.freeze(["medium"]),
45
+ // Its model is one Cursor lists for the owner's key, never the host's default.
46
+ ownModel: true,
47
+ normalizeModel: (model) => model,
48
+ // Installed by its owner, never on first use: the archive the pin names, its digests checked (serve's harness-archive.ts).
49
+ install: Object.freeze({ npmLine: CURSOR_INSTALL, spec: `cursor@${CURSOR_PIN.version}`, codes: Object.freeze({ install: CURSOR_CODES.notInstalled, pins: ACP_CODES.binaryMismatch }) }),
50
+ // Its MCP calls are titled `agentrun-<tool>: <tool>` (its permission asks) or `agentrun: <tool>` (its updates).
51
+ hostName: (given) => /^agentrun(?:-[^:]*)?: (.+)$/.exec(given)?.[1]?.trim() ?? given,
52
+ policy: () => {
53
+ throw new Error("acp: Cursor is billed to its owner's plan: its model requests never reach a proxy, so it has no proxy policy");
54
+ },
55
+ });
@@ -0,0 +1,35 @@
1
+ import type { AgentAdapter } from "@parcha/agentrun-kernel";
2
+ import { type AcpAdapterOptions } from "./adapter.js";
3
+ import { type CursorLimits } from "./cursor-facts.js";
4
+ import { type PinnedRelease } from "./pinned-binary.js";
5
+ import { type AcpRecipe } from "./recipe.js";
6
+ export interface CursorRecipeOptions {
7
+ /** The Cursor launcher (`<install>/dist-package/cursor-agent`), absolute: one that met its pin. */
8
+ command: string;
9
+ /** The run's model, as Cursor lists it for the key (`gpt-5.4-nano`, or `gpt-5.4-nano[reasoning=medium]`). Absent:
10
+ * Cursor's own default. */
11
+ model?: string;
12
+ /** Where the run stops. Default CURSOR_LIMITS. */
13
+ limits?: CursorLimits;
14
+ }
15
+ /** Cursor's recipe for one run: its file, with the launcher, the run's model and its limits. Refused when it could not
16
+ * run. */
17
+ export declare function cursorRecipe(options: CursorRecipeOptions): AcpRecipe;
18
+ /** The folder Cursor was installed into, from its launcher's path and the pin's `cmd` (`./dist-package/cursor-agent`). */
19
+ export declare function cursorRootOf(binary: string, cmd: string): string | undefined;
20
+ export interface CursorAdapterOptions extends Omit<AcpAdapterOptions, "recipe" | "proxy" | "beforeStart">, Omit<CursorRecipeOptions, "command"> {
21
+ /** The Cursor launcher, absolute, inside the folder it was installed into. Its sha256 and the digest of every file of
22
+ * that folder are checked when the adapter is made and again before every start of a Cursor process, and nothing of
23
+ * it is run for the check. */
24
+ binary: string;
25
+ }
26
+ /** Cursor's release pinned for `platform` (default this host's), with its launcher's and its tree's digests; undefined
27
+ * where none is pinned (CURSOR_PIN pins linux-x86_64 alone), where Cursor is refused ACP_BINARY_UNPINNED before any file
28
+ * of it is read: pinnedRelease's tree test on CURSOR_PIN, the one the adapter, serve and their tests make. */
29
+ export declare const cursorRelease: (platform?: string | undefined) => CursorRelease | undefined;
30
+ /** A pinned Cursor release: its archive, with its launcher's sha256 and its tree's digest. */
31
+ export type CursorRelease = PinnedRelease & {
32
+ readonly treeSha256: string;
33
+ };
34
+ /** Cursor as a harness adapter (id `cursor`): its pinned install checked, its recipe for the run's model and limits. */
35
+ export declare function cursorAdapter(options: CursorAdapterOptions): AgentAdapter;