@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.
@@ -0,0 +1,76 @@
1
+ // The MCP server over stdio, for an ACP agent that takes no MCP over HTTP: a bridge the agent starts as its stdio MCP
2
+ // server, which forwards each JSON-RPC line to the adapter's loopback HTTP server (mcp.ts) and writes back what it
3
+ // answers, its progress notifications among them. Written for AgentRun.
4
+ // - Its endpoint and key come in its environment (AGENTRUN_MCP_URL, AGENTRUN_MCP_KEY), which the adapter gives the agent
5
+ // for it in session/new; nothing else is read.
6
+ // - `notifications/cancelled` aborts the request it names, so a call the agent gave up on is aborted on the server too.
7
+ // - It ends when its stdin does.
8
+ import { createInterface } from "node:readline";
9
+ const url = process.env.AGENTRUN_MCP_URL ?? "";
10
+ const key = process.env.AGENTRUN_MCP_KEY ?? "";
11
+ const inFlight = new Map();
12
+ const write = (message) => void process.stdout.write(`${JSON.stringify(message)}\n`);
13
+ async function forward(message) {
14
+ const controller = new AbortController();
15
+ if (message.id !== undefined)
16
+ inFlight.set(message.id, controller);
17
+ try {
18
+ const response = await fetch(url, {
19
+ method: "POST",
20
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json", accept: "application/json, text/event-stream" },
21
+ body: JSON.stringify(message),
22
+ signal: controller.signal,
23
+ });
24
+ if (response.status === 202 || message.id === undefined) {
25
+ await response.body?.cancel();
26
+ return;
27
+ }
28
+ if (!(response.headers.get("content-type") ?? "").includes("text/event-stream")) {
29
+ const text = await response.text();
30
+ write(text ? JSON.parse(text) : { jsonrpc: "2.0", id: message.id, error: { code: -32603, message: `the server answered ${response.status}` } });
31
+ return;
32
+ }
33
+ // An event stream: each event's data is one message, written as it comes.
34
+ let buffer = "";
35
+ const decoder = new TextDecoder();
36
+ for await (const chunk of response.body) {
37
+ buffer += decoder.decode(chunk, { stream: true });
38
+ for (let at = buffer.indexOf("\n\n"); at >= 0; at = buffer.indexOf("\n\n")) {
39
+ const event = buffer.slice(0, at);
40
+ buffer = buffer.slice(at + 2);
41
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(line.startsWith("data: ") ? 6 : 5)).join("\n");
42
+ if (data)
43
+ write(JSON.parse(data));
44
+ }
45
+ }
46
+ }
47
+ catch (error) {
48
+ if (message.id !== undefined && !controller.signal.aborted)
49
+ write({ jsonrpc: "2.0", id: message.id, error: { code: -32603, message: String(error?.message ?? error).slice(0, 300) } });
50
+ }
51
+ finally {
52
+ if (message.id !== undefined)
53
+ inFlight.delete(message.id);
54
+ }
55
+ }
56
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
57
+ lines.on("line", (line) => {
58
+ if (!line.trim())
59
+ return;
60
+ let message;
61
+ try {
62
+ message = JSON.parse(line);
63
+ }
64
+ catch {
65
+ write({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "the line is not JSON" } });
66
+ return;
67
+ }
68
+ if (message.method === "notifications/cancelled")
69
+ inFlight.get(message.params?.requestId)?.abort();
70
+ void forward(message);
71
+ });
72
+ lines.on("close", () => {
73
+ for (const controller of inFlight.values())
74
+ controller.abort();
75
+ process.exit(0);
76
+ });
@@ -0,0 +1,40 @@
1
+ /** A tool as the MCP server lists it. */
2
+ export interface McpTool {
3
+ name: string;
4
+ description: string;
5
+ inputSchema: Record<string, unknown>;
6
+ }
7
+ /** A call's answer, as the bridge gives it. */
8
+ export interface McpAnswer {
9
+ text: string;
10
+ isError: boolean;
11
+ images?: readonly {
12
+ mimeType: string;
13
+ data: string;
14
+ }[];
15
+ }
16
+ export interface McpServerOptions {
17
+ tools: readonly McpTool[];
18
+ /** The key the agent sends (`Authorization: Bearer <key>`). */
19
+ key: string;
20
+ /** Run one call: the host tool's own name, the arguments the agent sent, and a signal that aborts when the client goes. */
21
+ call(name: string, args: Record<string, unknown>, signal: AbortSignal): Promise<McpAnswer>;
22
+ /** How often a running call reports progress. Default 15 s. */
23
+ progressMs?: number;
24
+ log?: (message: string, fields?: Record<string, unknown>) => void;
25
+ }
26
+ export interface McpServer {
27
+ /** The endpoint: `/mcp` on the loopback interface, on the port the system chose. */
28
+ readonly url: string;
29
+ /** Waits, at most `ms`, for the calls under way to settle (a host tool's own run, whatever became of its client):
30
+ * true when none is left. */
31
+ settle(ms: number): Promise<boolean>;
32
+ /** Stops the server: the calls under way are aborted, then waited for, at most CLOSE_SETTLE_MS, so none outlives the
33
+ * drive that started it unless it ignores its abort that long. One still running then is let go: its timer stopped,
34
+ * no longer counted by settle(), and its answer, if it ever comes, written nowhere. */
35
+ close(): Promise<void>;
36
+ }
37
+ /** How long close() waits for the calls it aborted to settle. */
38
+ export declare const CLOSE_SETTLE_MS = 5000;
39
+ /** Start the server on the loopback interface, on a port of the system's choosing. */
40
+ export declare function startMcpServer(options: McpServerOptions): Promise<McpServer>;
@@ -0,0 +1,210 @@
1
+ // The session's host tools as an MCP server on the loopback interface, for the ACP agent's MCP client. Copied from
2
+ // OpenCode's (packages/serve/src/harness-opencode/host/mcp.ts), not shared. Written for AgentRun.
3
+ //
4
+ // An ACP agent reaches a tool that is not its own only through MCP. The adapter gives it this one server, `agentrun`, on
5
+ // session/new, so the model is offered the host's tools under the agent's own name for an MCP tool (Goose's
6
+ // `agentrun__<name>`, Cursor's `agentrun-<name>: <name>`). The transport is MCP's streamable HTTP, the subset an agent's
7
+ // client uses (an agent that takes MCP over stdio only reaches it through the adapter's bridge, mcp-stdio.ts):
8
+ // - `POST /mcp` with one JSON-RPC message and the session's own key as a bearer token (compared in constant time):
9
+ // `initialize`, `ping` and `tools/list` are answered as JSON, a notification gets 202, and `tools/call` is answered as
10
+ // an event stream that carries a progress notification every `progressMs` while the call runs, then its result. A call
11
+ // may wait on a person (`ask_person`) far longer than an MCP client's request timeout, and a client that honours
12
+ // progress resets that timeout on each notification.
13
+ // - `GET /mcp` (a stream of the server's own notifications, which this server never sends) is 405, as the
14
+ // specification allows; any other path or method is 404.
15
+ // The server never runs a tool itself: `call` does, through the kernel's tool bridge, so each call is an effect whose
16
+ // intent is durable before it runs. A client that goes away before the answer aborts the call's signal.
17
+ import { createServer } from "node:http";
18
+ import { sameKey } from "@parcha/agentrun-kernel/host";
19
+ /** How long close() waits for the calls it aborted to settle. */
20
+ export const CLOSE_SETTLE_MS = 5_000;
21
+ /** The MCP protocol versions this server speaks; a client's own is answered in kind when it is one of them. */
22
+ const VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
23
+ const MAX_BODY = 8 * 1024 * 1024;
24
+ /** Where the server listens and the agent connects to it: this machine only, on the port the system chose. */
25
+ const ADDRESS = "http://127.0.0.1/mcp"; // key-gate: loopback-rule the MCP server of the ACP adapter listens here and the agent connects here, 127.0.0.1 only
26
+ const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
27
+ function json(res, status, body) {
28
+ if (body === undefined)
29
+ return void res.writeHead(status).end();
30
+ const text = JSON.stringify(body);
31
+ res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(text) }).end(text);
32
+ }
33
+ const error = (id, code, message) => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
34
+ async function bodyOf(req) {
35
+ let size = 0;
36
+ const chunks = [];
37
+ for await (const chunk of req) {
38
+ size += chunk.length;
39
+ if (size > MAX_BODY)
40
+ return undefined;
41
+ chunks.push(chunk);
42
+ }
43
+ return Buffer.concat(chunks).toString("utf8");
44
+ }
45
+ /** Start the server on the loopback interface, on a port of the system's choosing. */
46
+ export async function startMcpServer(options) {
47
+ if (!options.key)
48
+ throw new Error("acp: the MCP server needs the session's key");
49
+ const tools = options.tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema }));
50
+ const known = new Set(tools.map((t) => t.name));
51
+ const progressMs = options.progressMs ?? 15_000;
52
+ // Each call under way: its abort, and what stops its progress timer.
53
+ const open = new Set();
54
+ // Each call's own run (options.call), until it settles: what settle() and close() wait for.
55
+ const running = new Set();
56
+ const settle = async (ms) => {
57
+ if (running.size === 0)
58
+ return true;
59
+ let timer;
60
+ const done = await Promise.race([Promise.allSettled([...running]).then(() => true), new Promise((resolve) => (timer = setTimeout(() => resolve(false), ms)))]);
61
+ clearTimeout(timer);
62
+ return done && running.size === 0;
63
+ };
64
+ let closed = false;
65
+ const server = createServer((req, res) => {
66
+ void handle(req, res).catch((err) => {
67
+ options.log?.("acp: the MCP server failed a request", { error: String(err?.message ?? err).slice(0, 200) });
68
+ if (!res.headersSent)
69
+ json(res, 500, error(null, -32603, "internal error"));
70
+ else
71
+ res.end();
72
+ });
73
+ });
74
+ async function handle(req, res) {
75
+ const path = (req.url ?? "").split("?")[0];
76
+ if (path !== "/mcp")
77
+ return json(res, 404);
78
+ const auth = String(req.headers.authorization ?? "");
79
+ if (!sameKey(auth.startsWith("Bearer ") ? auth.slice(7) : "", options.key))
80
+ return json(res, 401);
81
+ if (req.method === "GET")
82
+ return void res.writeHead(405, { allow: "POST" }).end();
83
+ if (req.method === "DELETE")
84
+ return json(res, 200);
85
+ if (req.method !== "POST")
86
+ return json(res, 404);
87
+ if (closed)
88
+ return json(res, 503);
89
+ const text = await bodyOf(req);
90
+ if (text === undefined)
91
+ return json(res, 413, error(null, -32600, "the request is too large"));
92
+ let message;
93
+ try {
94
+ message = JSON.parse(text);
95
+ }
96
+ catch {
97
+ return json(res, 400, error(null, -32700, "the body is not JSON"));
98
+ }
99
+ if (!isPlain(message) || message.jsonrpc !== "2.0" || typeof message.method !== "string") {
100
+ // A response or a batch: this server sends no requests and takes one message at a time.
101
+ return json(res, 400, error(isPlain(message) ? message.id : null, -32600, "one JSON-RPC request or notification at a time"));
102
+ }
103
+ const { id, method } = message;
104
+ const params = isPlain(message.params) ? message.params : {};
105
+ if (id === undefined)
106
+ return json(res, 202);
107
+ switch (method) {
108
+ case "initialize": {
109
+ const asked = typeof params.protocolVersion === "string" ? params.protocolVersion : "";
110
+ const protocolVersion = VERSIONS.includes(asked) ? asked : VERSIONS[1];
111
+ return json(res, 200, { jsonrpc: "2.0", id, result: { protocolVersion, capabilities: { tools: { listChanged: false } }, serverInfo: { name: "agentrun", version: "1" } } });
112
+ }
113
+ case "ping":
114
+ return json(res, 200, { jsonrpc: "2.0", id, result: {} });
115
+ case "tools/list":
116
+ return json(res, 200, { jsonrpc: "2.0", id, result: { tools } });
117
+ case "tools/call":
118
+ return call(id, params, req, res);
119
+ default:
120
+ return json(res, 200, error(id, -32601, `no method ${method.slice(0, 80)}`));
121
+ }
122
+ }
123
+ async function call(id, params, req, res) {
124
+ const name = typeof params.name === "string" ? params.name : "";
125
+ if (!known.has(name))
126
+ return json(res, 200, { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: `unknown tool: ${name.slice(0, 80)}` }], isError: true } });
127
+ const args = isPlain(params.arguments) ? params.arguments : {};
128
+ const meta = isPlain(params._meta) ? params._meta : {};
129
+ const token = typeof meta.progressToken === "string" || typeof meta.progressToken === "number" ? meta.progressToken : undefined;
130
+ const controller = new AbortController();
131
+ let timer;
132
+ // Its progress stops, and nothing more is written, once its client is gone or the server has let it go. The call
133
+ // itself still runs until it settles (`running`), so the drive's settle waits for its real outcome.
134
+ let gone = false;
135
+ const release = () => {
136
+ gone = true;
137
+ if (timer)
138
+ clearInterval(timer);
139
+ timer = undefined;
140
+ };
141
+ const entry = { controller, release };
142
+ open.add(entry);
143
+ // The client going away (its abort, its process ending) stops the call; a finished answer does not.
144
+ let answered = false;
145
+ res.on("close", () => {
146
+ release();
147
+ if (!answered)
148
+ controller.abort(new Error("the MCP client went away before the answer"));
149
+ });
150
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
151
+ const send = (body) => void (gone || res.write(`event: message\ndata: ${JSON.stringify(body)}\n\n`));
152
+ let progress = 0;
153
+ if (token !== undefined)
154
+ timer = setInterval(() => {
155
+ progress += 1;
156
+ send({ jsonrpc: "2.0", method: "notifications/progress", params: { progressToken: token, progress } });
157
+ }, progressMs);
158
+ try {
159
+ const work = options.call(name, args, controller.signal);
160
+ running.add(work);
161
+ void work.then(() => running.delete(work), () => running.delete(work));
162
+ const answer = await work;
163
+ const content = [{ type: "text", text: answer.text }, ...(answer.images ?? []).map((image) => ({ type: "image", data: image.data, mimeType: image.mimeType }))];
164
+ answered = true;
165
+ send({ jsonrpc: "2.0", id, result: { content, isError: answer.isError } });
166
+ }
167
+ catch (err) {
168
+ answered = true;
169
+ // The drive is stopping (an interrupt, a halt): the call has no answer the log holds, so none is given.
170
+ send(error(id, -32603, String(err?.message ?? err).slice(0, 500)));
171
+ }
172
+ finally {
173
+ // A call the server let go (close()) settles here to nothing: its entry is gone, and so is its response.
174
+ const ended = gone;
175
+ release();
176
+ open.delete(entry);
177
+ if (!ended)
178
+ res.end();
179
+ }
180
+ }
181
+ await new Promise((resolve, reject) => {
182
+ server.once("error", reject);
183
+ server.listen(0, new URL(ADDRESS).hostname, () => resolve());
184
+ });
185
+ const address = server.address();
186
+ if (!address || typeof address === "string")
187
+ throw new Error("acp: the MCP server has no port");
188
+ const url = new URL(ADDRESS);
189
+ url.port = String(address.port);
190
+ return {
191
+ url: url.href,
192
+ settle,
193
+ async close() {
194
+ if (closed)
195
+ return;
196
+ closed = true;
197
+ for (const { controller } of open)
198
+ controller.abort(new Error("the session's MCP server closed"));
199
+ if (!(await settle(CLOSE_SETTLE_MS)))
200
+ options.log?.("acp: a host tool call was still running when the MCP server closed", { running: running.size });
201
+ // Past the window, a call that ignores its abort is let go: nothing of it stays live in this process.
202
+ for (const { release } of open)
203
+ release();
204
+ open.clear();
205
+ running.clear();
206
+ server.closeAllConnections?.();
207
+ await new Promise((resolve) => server.close(() => resolve()));
208
+ },
209
+ };
210
+ }
@@ -0,0 +1,12 @@
1
+ export { acpAdapter, type AcpAdapterOptions, type AcpProxy, type AcpProxySession } from "./adapter.js";
2
+ export { ACP_CODES, acpFacts, type AcpFacts } from "./facts.js";
3
+ export { homePath, MODEL_ID, recipeProblems, RESERVED_ENV, type AcpBilling, type AcpRecipe, type AcpRefusal } from "./recipe.js";
4
+ export { CALL_STREAM, contextNote, MODEL_STREAM, PERMISSION_STREAM, PROMPT_STREAM, SESSION_STREAM, sentSubmissions, TOOLS_STREAM } from "./harness.js";
5
+ export { STATE_STREAM, type StateRecord } from "./state.js";
6
+ export type { ConfineChild } from "./host/child.js";
7
+ export { GOOSE_INSTALL, GOOSE_NOT_INSTALLED, gooseFacts } from "./goose-facts.js";
8
+ export { gooseAdapter, gooseRecipe, recipeFile, type AcpRecipeFile, type AcpRecipeName, type GooseAdapterOptions, type GooseRecipeOptions } from "./goose.js";
9
+ export { applyGoose, GOOSE_BETAS, GOOSE_OWN_TOOLS, gooseProxy, goosePolicy, gooseRoutes, gooseToolName, gooseUsage, limitGooseOutput, type GoosePolicyOptions, type GooseProvider, type GooseProxyOptions } from "./host/goose-proxy.js";
10
+ export { acpPlatform, AcpBinaryRefused, CURSOR_PIN, GOOSE_PIN, pinnedRelease, treeDigest, verifyPinnedBinary, verifyPinnedBinaryAsync, verifyPinnedTree, type AcpArchivePin, type AcpBinaryPin, type AcpPlatform, type PinnedRelease } from "./pinned-binary.js";
11
+ export { CURSOR_CODES, CURSOR_INSTALL, CURSOR_LIMITS, cursorCard, cursorFacts, type CursorLimits } from "./cursor-facts.js";
12
+ export { cursorAdapter, cursorRecipe, cursorRelease, cursorRootOf, type CursorAdapterOptions, type CursorRecipeOptions, type CursorRelease } from "./cursor.js";
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ // Any Agent Client Protocol agent as an AgentRun harness. Written for AgentRun.
2
+ export { acpAdapter } from "./adapter.js";
3
+ export { ACP_CODES, acpFacts } from "./facts.js";
4
+ export { homePath, MODEL_ID, recipeProblems, RESERVED_ENV } from "./recipe.js";
5
+ export { CALL_STREAM, contextNote, MODEL_STREAM, PERMISSION_STREAM, PROMPT_STREAM, SESSION_STREAM, sentSubmissions, TOOLS_STREAM } from "./harness.js";
6
+ export { STATE_STREAM } from "./state.js";
7
+ export { GOOSE_INSTALL, GOOSE_NOT_INSTALLED, gooseFacts } from "./goose-facts.js";
8
+ export { gooseAdapter, gooseRecipe, recipeFile } from "./goose.js";
9
+ export { applyGoose, GOOSE_BETAS, GOOSE_OWN_TOOLS, gooseProxy, goosePolicy, gooseRoutes, gooseToolName, gooseUsage, limitGooseOutput } from "./host/goose-proxy.js";
10
+ export { acpPlatform, AcpBinaryRefused, CURSOR_PIN, GOOSE_PIN, pinnedRelease, treeDigest, verifyPinnedBinary, verifyPinnedBinaryAsync, verifyPinnedTree } from "./pinned-binary.js";
11
+ export { CURSOR_CODES, CURSOR_INSTALL, CURSOR_LIMITS, cursorCard, cursorFacts } from "./cursor-facts.js";
12
+ export { cursorAdapter, cursorRecipe, cursorRelease, cursorRootOf } from "./cursor.js";
@@ -0,0 +1,73 @@
1
+ /** A platform as the ACP registry names it (`distribution.binary.<platform>`). */
2
+ export type AcpPlatform = "darwin-aarch64" | "darwin-x86_64" | "linux-aarch64" | "linux-x86_64" | "windows-aarch64" | "windows-x86_64";
3
+ /** One platform's release of a pinned agent. */
4
+ export interface AcpArchivePin {
5
+ /** The archive's URL, as the registry lists it. */
6
+ readonly url: string;
7
+ /** How it is packed. */
8
+ readonly format: "tar.bz2" | "tar.gz" | "zip";
9
+ /** The archive's sha256, as the registry lists it. */
10
+ readonly sha256: string;
11
+ /** The binary's path inside the archive (the registry's `cmd`). */
12
+ readonly cmd: string;
13
+ /** The sha256 of the binary the archive unpacks to, where it was measured. Absent: unmeasured on this platform, so an
14
+ * installer records the first one it unpacks from the verified archive (agentrun-serve's binaryRecord). */
15
+ readonly binarySha256?: string;
16
+ /** The digest of every file the archive unpacks to (treeDigest), for an agent whose binary is a launcher of the code
17
+ * beside it (Cursor's `cursor-agent` runs its own `node` on `index.js` and a hundred chunks): checked by the installer
18
+ * and again before every start, so no file of it changes unseen. */
19
+ readonly treeSha256?: string;
20
+ }
21
+ /** A pinned release of an ACP agent. */
22
+ export interface AcpBinaryPin {
23
+ /** The agent's id in the registry. */
24
+ readonly id: string;
25
+ readonly version: string;
26
+ /** Where its digests were read, and when (ISO 8601). */
27
+ readonly source: {
28
+ readonly url: string;
29
+ readonly readAt: string;
30
+ };
31
+ readonly archives: Readonly<Partial<Record<AcpPlatform, AcpArchivePin>>>;
32
+ }
33
+ /** Goose 1.59.2, as the registry listed it when read (`source`). The linux-x86_64 binary's digest was measured on the
34
+ * binary its verified archive unpacked to; the darwin-aarch64 archive is pinned by the registry's digest alone. */
35
+ export declare const GOOSE_PIN: AcpBinaryPin;
36
+ /** Cursor's CLI 2026.11.13 (build eacade1), the release its ACP registry entry pointed to when read (`source`). The
37
+ * registry lists no digest for Cursor, so the archive is pinned by the first sha256 seen for it (2026-11-16, harness S0;
38
+ * downloaded again 2026-11-19 and the same), its launcher and its whole tree by what that archive unpacked to. A drift
39
+ * of any of them is refused. A new pin takes the key walk on it (test/cursor-key-walk.test.mjs, on the real binary and
40
+ * the owner's key, AGENTRUN_RECORD_CURSOR_WALK=1): Cursor's credential design rests on Cursor tolerating a failed save,
41
+ * and CI refuses a pin cursor-walk.json does not name. */
42
+ export declare const CURSOR_PIN: AcpBinaryPin;
43
+ /** This host's platform as the registry names it, or undefined for one it does not list. */
44
+ export declare function acpPlatform(platform?: string, arch?: string): AcpPlatform | undefined;
45
+ /** A release pinned with its binary's digest (and, for an agent pinned by its tree, the tree's). */
46
+ export type PinnedRelease = AcpArchivePin & {
47
+ readonly binarySha256: string;
48
+ readonly treeSha256?: string;
49
+ };
50
+ /** `pin`'s release for `platform` (default this host's) with its binary's digest, and its tree's when `tree`; undefined
51
+ * where none is pinned so, where the agent is refused ACP_BINARY_UNPINNED (unpinned) before any file of it is read. */
52
+ export declare function pinnedRelease(pin: AcpBinaryPin, platform?: string | undefined, tree?: boolean): PinnedRelease | undefined;
53
+ /** A binary the adapter will not start: its code says why (ACP_CODES.binaryMismatch, binaryUnreadable). */
54
+ export declare class AcpBinaryRefused extends Error {
55
+ readonly code: string;
56
+ constructor(code: string, message: string);
57
+ }
58
+ /** The refusal of `label` `version` on a host its pin names no release for. */
59
+ export declare const unpinned: (label: string, version: string, platform?: string | undefined) => AcpBinaryRefused;
60
+ /** Refuses the binary at `path` unless its sha256 is `sha256`. Reads it (once per file identity in this process),
61
+ * never runs it. */
62
+ export declare function verifyPinnedBinary(path: string, sha256: string): void;
63
+ /** verifyPinnedBinary without holding the event loop: the host's own check, while it goes on answering. */
64
+ export declare function verifyPinnedBinaryAsync(path: string, sha256: string): Promise<void>;
65
+ /** The digest of the tree at `root`: the sha256 of one line per entry under it, in byte order of its path from `root`
66
+ * (`/`-separated): `<path>\0file\0<sha256>\n` for a file, `<path>\0link\0<target>\n` for a symbolic link, and
67
+ * `<path>\0dir\n` for a directory. Modes and times are not in it. Each file's sha256 is the kernel's, kept once per
68
+ * file identity in this process, so a tree checked before is read again only where a file changed. Off the event loop;
69
+ * rejects on anything else under `root` (a socket, a device). */
70
+ export declare function treeDigest(root: string): Promise<string>;
71
+ /** Refuses the tree at `root` unless its digest (treeDigest) is `sha256`: ACP_CODES.binaryMismatch, or binaryUnreadable
72
+ * when it cannot be read. Never runs anything in it. */
73
+ export declare function verifyPinnedTree(root: string, sha256: string): Promise<void>;
@@ -0,0 +1,160 @@
1
+ // An ACP agent's binary, checked against what the adapter was tested with, before it is ever started. Written for
2
+ // AgentRun.
3
+ // - A pin is a release as the public ACP registry lists it (https://cdn.agentclientprotocol.com/registry/v1/latest/
4
+ // registry.json): its version and, per platform, its archive's URL and sha256, and the sha256 of the binary the archive
5
+ // unpacks to where it was measured. An installer verifies the archive, then the binary; a host checks the binary
6
+ // again at each start (`verifyPinnedBinary`).
7
+ // - An agent the registry lists with no digest (Cursor) is pinned here by what its first download held; a binary no
8
+ // pin names has its first digest recorded by the server's installer alone (agentrun-serve, harness-archive.ts
9
+ // installArchive's binaryRecord), the one first-seen path.
10
+ // Every check reads the file's bytes (the kernel's chunked sha256, kept once per file identity) and never executes it.
11
+ import { createHash } from "node:crypto";
12
+ import { lstat, readdir, readlink } from "node:fs/promises";
13
+ import { join } from "node:path";
14
+ import { checkedOnce, checkedOnceAsync } from "@parcha/agentrun-kernel/host";
15
+ import { ACP_CODES } from "./facts.js";
16
+ /** Goose 1.59.2, as the registry listed it when read (`source`). The linux-x86_64 binary's digest was measured on the
17
+ * binary its verified archive unpacked to; the darwin-aarch64 archive is pinned by the registry's digest alone. */
18
+ export const GOOSE_PIN = Object.freeze({
19
+ id: "goose",
20
+ version: "1.59.2",
21
+ source: Object.freeze({ url: "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json", readAt: "2026-11-17T22:28:02Z" }),
22
+ archives: Object.freeze({
23
+ "linux-x86_64": Object.freeze({
24
+ url: "https://github.com/block/goose/releases/download/v1.59.2/goose-x86_64-unknown-linux-gnu.tar.bz2",
25
+ format: "tar.bz2",
26
+ sha256: "36efe207ae4f8de3030ed8fdcfe3b7c5d13f23d6cb73d6fde747543f022ce218",
27
+ cmd: "./goose",
28
+ binarySha256: "b90833d7f1e8f9aa36e163a8f3d27fdd69d462ac9b4a68105a091e1a2da56993",
29
+ }),
30
+ "darwin-aarch64": Object.freeze({
31
+ url: "https://github.com/block/goose/releases/download/v1.59.2/goose-aarch64-apple-darwin.tar.bz2",
32
+ format: "tar.bz2",
33
+ sha256: "a4eac98999639741ee5a4cc7a3043952a4a22fc2004b7340e34ec927df0e8257",
34
+ cmd: "./goose",
35
+ }),
36
+ }),
37
+ });
38
+ /** Cursor's CLI 2026.11.13 (build eacade1), the release its ACP registry entry pointed to when read (`source`). The
39
+ * registry lists no digest for Cursor, so the archive is pinned by the first sha256 seen for it (2026-11-16, harness S0;
40
+ * downloaded again 2026-11-19 and the same), its launcher and its whole tree by what that archive unpacked to. A drift
41
+ * of any of them is refused. A new pin takes the key walk on it (test/cursor-key-walk.test.mjs, on the real binary and
42
+ * the owner's key, AGENTRUN_RECORD_CURSOR_WALK=1): Cursor's credential design rests on Cursor tolerating a failed save,
43
+ * and CI refuses a pin cursor-walk.json does not name. */
44
+ export const CURSOR_PIN = Object.freeze({
45
+ id: "cursor",
46
+ version: "2026.11.13-eacade1",
47
+ source: Object.freeze({ url: "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json", readAt: "2026-11-16T21:22:32Z" }),
48
+ archives: Object.freeze({
49
+ "linux-x86_64": Object.freeze({
50
+ url: "https://downloads.cursor.com/lab/2026.11.13-eacade1/linux/x64/agent-cli-package.tar.gz",
51
+ format: "tar.gz",
52
+ sha256: "c02e4321f20d691ee03af94d29948dc3a81c6c34e7328da7bb1afade4c75812f",
53
+ cmd: "./dist-package/cursor-agent",
54
+ binarySha256: "2ccc9a8e167797641448b5e5c936f006ba137a2555f117f38c5eb76a5238a233",
55
+ treeSha256: "b224cfc7d2aa702ae4c9335fba6a4fc4b04250584bf615a8dcefa946ac5e64f6",
56
+ }),
57
+ }),
58
+ });
59
+ /** This host's platform as the registry names it, or undefined for one it does not list. */
60
+ export function acpPlatform(platform = process.platform, arch = process.arch) {
61
+ const os = platform === "darwin" ? "darwin" : platform === "linux" ? "linux" : platform === "win32" ? "windows" : undefined;
62
+ const cpu = arch === "arm64" ? "aarch64" : arch === "x64" ? "x86_64" : undefined;
63
+ return os && cpu ? `${os}-${cpu}` : undefined;
64
+ }
65
+ /** `pin`'s release for `platform` (default this host's) with its binary's digest, and its tree's when `tree`; undefined
66
+ * where none is pinned so, where the agent is refused ACP_BINARY_UNPINNED (unpinned) before any file of it is read. */
67
+ export function pinnedRelease(pin, platform = acpPlatform(), tree = false) {
68
+ const release = platform ? pin.archives[platform] : undefined;
69
+ return release?.binarySha256 && (!tree || release.treeSha256) ? release : undefined;
70
+ }
71
+ /** A binary the adapter will not start: its code says why (ACP_CODES.binaryMismatch, binaryUnreadable). */
72
+ export class AcpBinaryRefused extends Error {
73
+ code;
74
+ constructor(code, message) {
75
+ super(`${code}: ${message}`);
76
+ this.code = code;
77
+ this.name = "AcpBinaryRefused";
78
+ }
79
+ }
80
+ /** The refusal of `label` `version` on a host its pin names no release for. */
81
+ export const unpinned = (label, version, platform = acpPlatform()) => new AcpBinaryRefused(ACP_CODES.binaryUnpinned, `no digest is pinned for ${label} ${version} on ${platform ?? `${process.platform}-${process.arch}`}`);
82
+ const SHA256 = /^[0-9a-f]{64}$/;
83
+ /** The check's one step: the file's sha256. */
84
+ const digestOf = (path) => function* () {
85
+ return yield { kind: "sha256", path };
86
+ };
87
+ /** Why reading `path` failed, as a refusal. */
88
+ const unreadable = (path, error) => new AcpBinaryRefused(ACP_CODES.binaryUnreadable, `the binary at ${path} cannot be read (${String(error?.code ?? error?.message ?? error)})`);
89
+ /** Refuses the binary at `path` unless its sha256 is `sha256`. Reads it (once per file identity in this process),
90
+ * never runs it. */
91
+ export function verifyPinnedBinary(path, sha256) {
92
+ if (!SHA256.test(sha256))
93
+ throw new Error(`acp: the pinned sha256 ${JSON.stringify(sha256)} is not 64 lowercase hex digits`);
94
+ let found;
95
+ try {
96
+ found = checkedOnce(path, sha256, digestOf(path), (d) => d === sha256);
97
+ }
98
+ catch (error) {
99
+ throw unreadable(path, error);
100
+ }
101
+ if (found !== sha256)
102
+ throw new AcpBinaryRefused(ACP_CODES.binaryMismatch, `the binary at ${path} has sha256 ${found}, and the pin is ${sha256}`);
103
+ }
104
+ /** verifyPinnedBinary without holding the event loop: the host's own check, while it goes on answering. */
105
+ export async function verifyPinnedBinaryAsync(path, sha256) {
106
+ if (!SHA256.test(sha256))
107
+ throw new Error(`acp: the pinned sha256 ${JSON.stringify(sha256)} is not 64 lowercase hex digits`);
108
+ let found;
109
+ try {
110
+ found = await checkedOnceAsync(path, sha256, digestOf(path), (d) => d === sha256);
111
+ }
112
+ catch (error) {
113
+ throw unreadable(path, error);
114
+ }
115
+ if (found !== sha256)
116
+ throw new AcpBinaryRefused(ACP_CODES.binaryMismatch, `the binary at ${path} has sha256 ${found}, and the pin is ${sha256}`);
117
+ }
118
+ /** The digest of the tree at `root`: the sha256 of one line per entry under it, in byte order of its path from `root`
119
+ * (`/`-separated): `<path>\0file\0<sha256>\n` for a file, `<path>\0link\0<target>\n` for a symbolic link, and
120
+ * `<path>\0dir\n` for a directory. Modes and times are not in it. Each file's sha256 is the kernel's, kept once per
121
+ * file identity in this process, so a tree checked before is read again only where a file changed. Off the event loop;
122
+ * rejects on anything else under `root` (a socket, a device). */
123
+ export async function treeDigest(root) {
124
+ const lines = [];
125
+ const walk = async (dir, prefix) => {
126
+ for (const name of (await readdir(dir)).sort()) {
127
+ const path = join(dir, name);
128
+ const rel = prefix ? `${prefix}/${name}` : name;
129
+ const entry = await lstat(path);
130
+ if (entry.isSymbolicLink())
131
+ lines.push(`${rel}\0link\0${await readlink(path)}\n`);
132
+ else if (entry.isDirectory()) {
133
+ lines.push(`${rel}\0dir\n`);
134
+ await walk(path, rel);
135
+ }
136
+ else if (entry.isFile())
137
+ lines.push(`${rel}\0file\0${await checkedOnceAsync(path, "tree", digestOf(path), () => true)}\n`);
138
+ else
139
+ throw new Error(`${path} is neither a file, a directory nor a link`);
140
+ }
141
+ };
142
+ await walk(root, "");
143
+ lines.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
144
+ return createHash("sha256").update(lines.join("")).digest("hex");
145
+ }
146
+ /** Refuses the tree at `root` unless its digest (treeDigest) is `sha256`: ACP_CODES.binaryMismatch, or binaryUnreadable
147
+ * when it cannot be read. Never runs anything in it. */
148
+ export async function verifyPinnedTree(root, sha256) {
149
+ if (!SHA256.test(sha256))
150
+ throw new Error(`acp: the pinned tree sha256 ${JSON.stringify(sha256)} is not 64 lowercase hex digits`);
151
+ let found;
152
+ try {
153
+ found = await treeDigest(root);
154
+ }
155
+ catch (error) {
156
+ throw new AcpBinaryRefused(ACP_CODES.binaryUnreadable, `the files at ${root} cannot be read (${String(error?.code ?? error?.message ?? error)})`);
157
+ }
158
+ if (found !== sha256)
159
+ throw new AcpBinaryRefused(ACP_CODES.binaryMismatch, `the files at ${root} have the tree sha256 ${found}, and the pin is ${sha256}: one of them changed since it was installed`);
160
+ }