@parcha/agentrun-harness-acp 0.0.0-stage → 0.1.0-beta.47

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/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,36 @@
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 AcpArchivePin } 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. The one test of whether Cursor runs on a platform: the adapter's, serve's and their tests'. */
29
+ export declare function 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 = AcpArchivePin & {
32
+ readonly binarySha256: string;
33
+ readonly treeSha256: string;
34
+ };
35
+ /** Cursor as a harness adapter (id `cursor`): its pinned install checked, its recipe for the run's model and limits. */
36
+ export declare function cursorAdapter(options: CursorAdapterOptions): AgentAdapter;
package/dist/cursor.js ADDED
@@ -0,0 +1,80 @@
1
+ // Cursor as an AgentRun harness: its recipe (recipes/cursor.json), loaded and typed, and the adapter a host builds from
2
+ // it on a pinned install. Written for AgentRun.
3
+ //
4
+ // What the recipe holds was measured on Cursor 2026.11.13-eacade1 over ACP (harness S0):
5
+ // - `cursor-agent --disable-auto-update acp` in a private HOME, on CURSOR_API_KEY (handed by name at each start, never
6
+ // written anywhere of ours): Cursor's API-key login, the one its docs give for automation;
7
+ // - its config directory is $CURSOR_CONFIG_DIR, else $XDG_CONFIG_HOME/cursor, else $HOME/.cursor (its
8
+ // cursor-config/dist/paths.js): the adapter sets XDG_CONFIG_HOME to $HOME/.config, so the config and the sessions
9
+ // are under `$HOME/.config/cursor`, beside auth.json, and a file under ~/.cursor is never read;
10
+ // - `$HOME/.config/cursor/cli-config.json` denies Write(**) and allows nothing: Cursor asks permission (session/request_permission)
11
+ // before a shell command or an MCP call, and the host's gate answers, but it never asks before a file edit, so every
12
+ // edit is denied outright until it does;
13
+ // - our tools as one MCP server over HTTP, given at session/new (no mcp.json of Cursor's own);
14
+ // - its sessions in `$HOME/.config/cursor/acp-sessions`, mirrored so another runner's Cursor loads them (session/load);
15
+ // - the credential it derives from the key, `$HOME/.config/cursor/auth.json`, never mirrored, and its whole HOME removed
16
+ // when its process ends;
17
+ // - its model chosen among those session/new lists for the key (session/set_model), billed to the owner's Cursor plan:
18
+ // no request reaches a proxy of ours, so the run stops at the plan's limits of turns and tool calls;
19
+ // - its team administrator's switch against headless use, said as CURSOR_HEADLESS_DISABLED where Cursor says it.
20
+ import { normalize, sep } from "node:path";
21
+ import { acpAdapter } from "./adapter.js";
22
+ import { ACP_CODES } from "./facts.js";
23
+ import { CURSOR_LIMITS } from "./cursor-facts.js";
24
+ import { recipeFile } from "./goose.js";
25
+ import { acpPlatform, AcpBinaryRefused, CURSOR_PIN, verifyPinnedBinary, verifyPinnedBinaryAsync, verifyPinnedTree } from "./pinned-binary.js";
26
+ import { MODEL_ID, recipeProblems } from "./recipe.js";
27
+ /** Cursor's recipe for one run: its file, with the launcher, the run's model and its limits. Refused when it could not
28
+ * run. */
29
+ export function cursorRecipe(options) {
30
+ if (options.model !== undefined && (typeof options.model !== "string" || !MODEL_ID.test(options.model)))
31
+ throw new Error(`acp: the model ${JSON.stringify(String(options.model).slice(0, 80))} is not a model id`);
32
+ const limits = options.limits ?? CURSOR_LIMITS;
33
+ if (!Number.isInteger(limits.maxTurns) || limits.maxTurns < 1)
34
+ throw new Error(`acp: Cursor's maxTurns must be a whole number of at least 1, not ${JSON.stringify(limits.maxTurns)}`);
35
+ if (!Number.isInteger(limits.maxToolCalls) || limits.maxToolCalls < 0)
36
+ throw new Error(`acp: Cursor's maxToolCalls must be a whole number, not ${JSON.stringify(limits.maxToolCalls)}`);
37
+ const file = recipeFile("cursor");
38
+ const recipe = { ...file, command: options.command, billing: { kind: "plan", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls }, ...(options.model !== undefined ? { model: options.model } : {}) };
39
+ const problems = recipeProblems(recipe);
40
+ if (problems.length)
41
+ throw new Error(`acp: the cursor recipe cannot run: ${problems.join("; ")}`);
42
+ return recipe;
43
+ }
44
+ /** The folder Cursor was installed into, from its launcher's path and the pin's `cmd` (`./dist-package/cursor-agent`). */
45
+ export function cursorRootOf(binary, cmd) {
46
+ const tail = normalize(cmd);
47
+ const path = normalize(binary);
48
+ return path.endsWith(`${sep}${tail}`) ? path.slice(0, -(tail.length + 1)) : undefined;
49
+ }
50
+ /** Cursor's release pinned for `platform` (default this host's), with its launcher's and its tree's digests; undefined
51
+ * where none is pinned (CURSOR_PIN pins linux-x86_64 alone), where Cursor is refused ACP_BINARY_UNPINNED before any file
52
+ * of it is read. The one test of whether Cursor runs on a platform: the adapter's, serve's and their tests'. */
53
+ export function cursorRelease(platform = acpPlatform()) {
54
+ const release = platform ? CURSOR_PIN.archives[platform] : undefined;
55
+ return release?.binarySha256 && release.treeSha256 ? release : undefined;
56
+ }
57
+ /** Cursor as a harness adapter (id `cursor`): its pinned install checked, its recipe for the run's model and limits. */
58
+ export function cursorAdapter(options) {
59
+ const { binary, model, limits, ...rest } = options;
60
+ const platform = acpPlatform();
61
+ const release = cursorRelease(platform);
62
+ if (!release)
63
+ throw new AcpBinaryRefused(ACP_CODES.binaryUnpinned, `no digest is pinned for Cursor ${CURSOR_PIN.version} on ${platform ?? `${process.platform}-${process.arch}`}`);
64
+ const root = cursorRootOf(binary, release.cmd);
65
+ if (!root)
66
+ throw new AcpBinaryRefused(ACP_CODES.binaryMismatch, `the Cursor launcher at ${binary} is not at its pinned path ${release.cmd} inside its folder`);
67
+ const launcher = release.binarySha256;
68
+ const tree = release.treeSha256;
69
+ verifyPinnedBinary(binary, launcher);
70
+ return acpAdapter({
71
+ ...rest,
72
+ recipe: cursorRecipe({ command: binary, ...(model !== undefined ? { model } : {}), ...(limits ? { limits } : {}) }),
73
+ // Checked again before each process starts, the launcher and every file it runs: a file replaced since the adapter
74
+ // was made never runs unchecked. An unchanged file is not hashed again (the check remembers it by its identity).
75
+ beforeStart: async (command) => {
76
+ await verifyPinnedBinaryAsync(command, launcher);
77
+ await verifyPinnedTree(root, tree);
78
+ },
79
+ });
80
+ }
@@ -0,0 +1,39 @@
1
+ /** The codes the adapter's refusals start with (`<code>: <words>`), so a host tells them apart without reading words. */
2
+ export declare const ACP_CODES: Readonly<{
3
+ /** initialize advertised less than the recipe declares (session/load, MCP over HTTP). */
4
+ readonly capabilityMismatch: "ACP_CAPABILITY_MISMATCH";
5
+ /** initialize answered a protocol version the adapter does not speak. */
6
+ readonly protocolMismatch: "ACP_PROTOCOL_MISMATCH";
7
+ /** A plan-billed run reached the owner's limit of session/prompt turns. */
8
+ readonly turnLimit: "ACP_TURN_LIMIT";
9
+ /** A plan-billed run reached the owner's limit of tool calls. */
10
+ readonly toolCallLimit: "ACP_TOOL_CALL_LIMIT";
11
+ /** The agent's process ended, or never answered initialize. */
12
+ readonly agentExited: "ACP_AGENT_EXITED";
13
+ /** The agent stopped the turn at its own limit of requests (stopReason max_turn_requests). */
14
+ readonly agentTurnRequests: "ACP_MAX_TURN_REQUESTS";
15
+ /** The agent refused to go on (stopReason refusal). */
16
+ readonly refusal: "ACP_REFUSAL";
17
+ /** The agent's binary is not the pinned one: its sha256 differs from the pin's. */
18
+ readonly binaryMismatch: "ACP_BINARY_MISMATCH";
19
+ /** The agent's binary cannot be read to be checked. */
20
+ readonly binaryUnreadable: "ACP_BINARY_UNREADABLE";
21
+ /** No digest is pinned for the agent's binary on this platform, and none was given. */
22
+ readonly binaryUnpinned: "ACP_BINARY_UNPINNED";
23
+ /** A key the recipe runs on (recipe.keys) is not in the host's environment: the agent was not started. */
24
+ readonly keyMissing: "ACP_KEY_MISSING";
25
+ /** The run's model (recipe.model) is not one the agent lists for its key: no prompt was sent. */
26
+ readonly modelUnlisted: "ACP_MODEL_UNLISTED";
27
+ }>;
28
+ export interface AcpFacts {
29
+ readonly id: string;
30
+ readonly label: string;
31
+ /** A message mid-turn waits for the turn's end: ACP has no steer. */
32
+ readonly steer: false;
33
+ /** A call the agent started is never run again: one cut off is reported interrupted, never repeated. */
34
+ readonly rerunsStarted: false;
35
+ /** An answer cut at the output limit (stopReason max_tokens) ends the turn. */
36
+ readonly recoversCutAnswers: 0;
37
+ }
38
+ /** The facts of the ACP harness `id`. */
39
+ export declare function acpFacts(id: string, label?: string): AcpFacts;
package/dist/facts.js ADDED
@@ -0,0 +1,34 @@
1
+ // What an ACP harness is, as its adapter states it, and the codes its refusals carry. Narrower than the kernel's
2
+ // AdapterFacts: an ACP agent's wire, policy and install are its recipe's (S1's table makes those optional for plan
3
+ // harnesses), so this states only what the adapter itself guarantees. Written for AgentRun.
4
+ /** The codes the adapter's refusals start with (`<code>: <words>`), so a host tells them apart without reading words. */
5
+ export const ACP_CODES = Object.freeze({
6
+ /** initialize advertised less than the recipe declares (session/load, MCP over HTTP). */
7
+ capabilityMismatch: "ACP_CAPABILITY_MISMATCH",
8
+ /** initialize answered a protocol version the adapter does not speak. */
9
+ protocolMismatch: "ACP_PROTOCOL_MISMATCH",
10
+ /** A plan-billed run reached the owner's limit of session/prompt turns. */
11
+ turnLimit: "ACP_TURN_LIMIT",
12
+ /** A plan-billed run reached the owner's limit of tool calls. */
13
+ toolCallLimit: "ACP_TOOL_CALL_LIMIT",
14
+ /** The agent's process ended, or never answered initialize. */
15
+ agentExited: "ACP_AGENT_EXITED",
16
+ /** The agent stopped the turn at its own limit of requests (stopReason max_turn_requests). */
17
+ agentTurnRequests: "ACP_MAX_TURN_REQUESTS",
18
+ /** The agent refused to go on (stopReason refusal). */
19
+ refusal: "ACP_REFUSAL",
20
+ /** The agent's binary is not the pinned one: its sha256 differs from the pin's. */
21
+ binaryMismatch: "ACP_BINARY_MISMATCH",
22
+ /** The agent's binary cannot be read to be checked. */
23
+ binaryUnreadable: "ACP_BINARY_UNREADABLE",
24
+ /** No digest is pinned for the agent's binary on this platform, and none was given. */
25
+ binaryUnpinned: "ACP_BINARY_UNPINNED",
26
+ /** A key the recipe runs on (recipe.keys) is not in the host's environment: the agent was not started. */
27
+ keyMissing: "ACP_KEY_MISSING",
28
+ /** The run's model (recipe.model) is not one the agent lists for its key: no prompt was sent. */
29
+ modelUnlisted: "ACP_MODEL_UNLISTED",
30
+ });
31
+ /** The facts of the ACP harness `id`. */
32
+ export function acpFacts(id, label = id) {
33
+ return Object.freeze({ id, label, steer: false, rerunsStarted: false, recoversCutAnswers: 0 });
34
+ }
@@ -0,0 +1,6 @@
1
+ import type { AdapterFacts } from "@parcha/agentrun-kernel";
2
+ /** The command that installs the pinned Goose into an AgentRun server's data (`<data>/harnesses/goose`). */
3
+ export declare const GOOSE_INSTALL = "agentrun harness install goose";
4
+ /** The code a host's refusal carries when Goose is not installed where it looks. */
5
+ export declare const GOOSE_NOT_INSTALLED = "HARNESS_NOT_INSTALLED";
6
+ export declare const gooseFacts: AdapterFacts;
@@ -0,0 +1,32 @@
1
+ import { ACP_CODES } from "./facts.js";
2
+ import { goosePolicy, gooseToolName } from "./host/goose-proxy.js";
3
+ import { GOOSE_PIN } from "./pinned-binary.js";
4
+ /** The command that installs the pinned Goose into an AgentRun server's data (`<data>/harnesses/goose`). */
5
+ export const GOOSE_INSTALL = "agentrun harness install goose";
6
+ /** The code a host's refusal carries when Goose is not installed where it looks. */
7
+ export const GOOSE_NOT_INSTALLED = "HARNESS_NOT_INSTALLED";
8
+ const OURS = gooseToolName("");
9
+ export const gooseFacts = Object.freeze({
10
+ id: "goose",
11
+ label: "Goose",
12
+ wire: "anthropic-messages",
13
+ // ACP has no steer: a message mid-turn waits for the turn's end.
14
+ steer: false,
15
+ // A call Goose started is never run again: one cut off is reported interrupted, never repeated.
16
+ rerunsStarted: false,
17
+ // An answer cut at the output limit (stopReason max_tokens) ends the turn.
18
+ recoversCutAnswers: 0,
19
+ // One run's memory, measured with the server's (serve's host.ts): Goose's own process beside the run's.
20
+ runMib: 256,
21
+ // Goose asks for adaptive thinking at the model's own effort (high), whatever the run's level: no level is passed to it.
22
+ thinking: Object.freeze(["high"]),
23
+ // Its model is Anthropic's, on its own settings, never the gateway's default for the other harnesses.
24
+ ownModel: true,
25
+ // Anthropic's ids hold no dot; OpenRouter names the same models with dots (anthropic/claude-sonnet-5.5).
26
+ normalizeModel: (model) => (model.provider === "anthropic" ? { ...model, modelId: model.modelId.replaceAll(".", "-") } : model),
27
+ // Installed by its owner, never on first use: the archive the pin names, its digests checked (serve's harness-archive.ts).
28
+ install: Object.freeze({ npmLine: GOOSE_INSTALL, spec: `goose@${GOOSE_PIN.version}`, codes: Object.freeze({ install: GOOSE_NOT_INSTALLED, pins: ACP_CODES.binaryMismatch }) }),
29
+ // Its bundled extensions are off: the model calls only our MCP server's tools, as `agentrun__<host tool>`.
30
+ hostName: (given) => (given.startsWith(OURS) ? given.slice(OURS.length) : given),
31
+ policy: (options) => goosePolicy({ model: options.model, tools: options.tools, ...(options.auth ? { auth: options.auth } : {}), ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}) }),
32
+ });
@@ -0,0 +1,29 @@
1
+ import type { AgentAdapter } from "@parcha/agentrun-kernel";
2
+ import { type AcpAdapterOptions } from "./adapter.js";
3
+ import { type GooseProxyOptions } from "./host/goose-proxy.js";
4
+ import { type AcpRecipe } from "./recipe.js";
5
+ /** A recipe as its file holds it: everything but the binary, which the host's install puts where it does. */
6
+ export type AcpRecipeFile = Omit<AcpRecipe, "command">;
7
+ /** The recipes this package ships, by name. */
8
+ export type AcpRecipeName = "goose" | "cursor";
9
+ /** The recipe file `name`, as shipped beside this package's code. */
10
+ export declare function recipeFile(name: AcpRecipeName): AcpRecipeFile;
11
+ export interface GooseRecipeOptions {
12
+ /** The Goose binary, absolute: one that met its pin (verifyPinnedBinary). */
13
+ command: string;
14
+ /** The run's model, as the provider names it. */
15
+ model: string;
16
+ }
17
+ /** Goose's recipe for one run: its file, with the binary and the run's model. Refused when it could not run. */
18
+ export declare function gooseRecipe(options: GooseRecipeOptions): AcpRecipe;
19
+ export interface GooseAdapterOptions extends Omit<AcpAdapterOptions, "recipe" | "proxy" | "beforeStart">, Omit<GooseProxyOptions, "log"> {
20
+ /** The Goose binary, absolute. Its sha256 is checked when the adapter is made and again before every start of a Goose
21
+ * process (a restart included), and it is never run for the check. */
22
+ binary: string;
23
+ /** The sha256 it must have. Default: the pin's for this platform (GOOSE_PIN), refused with ACP_BINARY_UNPINNED where
24
+ * the pin has none. */
25
+ sha256?: string;
26
+ }
27
+ /** Goose as a harness adapter (id `goose`): its pinned binary checked, its recipe for the run's model, and a model proxy
28
+ * of its own for each Goose process, on the session's booking. */
29
+ export declare function gooseAdapter(options: GooseAdapterOptions): AgentAdapter;
package/dist/goose.js ADDED
@@ -0,0 +1,67 @@
1
+ // Goose as an AgentRun harness: its recipe (recipes/goose.json), loaded and typed, and the adapter a host builds from
2
+ // it on a pinned binary. Written for AgentRun.
3
+ //
4
+ // What the recipe holds was measured on Goose 1.59.2 over ACP:
5
+ // - `goose acp` in a private HOME, provider `anthropic` in approve mode (every tool call asks permission, and the
6
+ // adapter answers allow_once or reject_once, never an `always`); session naming and the keyring off;
7
+ // - every bundled extension off in `$HOME/.config/goose/config.yaml`, which leaves the model our MCP server's tools
8
+ // (`agentrun__<name>`) and `load_skill`, which Goose always offers. ACP's `_meta.enabledExtensions: []` is not used:
9
+ // it drops our MCP server too;
10
+ // - HTTP(S)_PROXY to a dead loopback port, loopback exempt: Goose downloads a model catalog from the internet at every
11
+ // start, and this blocks it while its model's requests (to the session's loopback proxy) go on;
12
+ // - its sessions in `$HOME/.local/share/goose/sessions` (sessions.db), mirrored so another runner's Goose loads them;
13
+ // - session/load and MCP over HTTP declared; its model billed through the host's proxy.
14
+ // The run's model is GOOSE_MODEL, set here; ANTHROPIC_HOST and ANTHROPIC_API_KEY are the proxy's (gooseProxy), never
15
+ // the recipe's.
16
+ import { readFileSync } from "node:fs";
17
+ import { acpAdapter } from "./adapter.js";
18
+ import { ACP_CODES } from "./facts.js";
19
+ import { gooseProxy } from "./host/goose-proxy.js";
20
+ import { acpPlatform, AcpBinaryRefused, GOOSE_PIN, verifyPinnedBinary, verifyPinnedBinaryAsync } from "./pinned-binary.js";
21
+ import { recipeProblems } from "./recipe.js";
22
+ /** The variables the proxy (ANTHROPIC_HOST, ANTHROPIC_API_KEY) and the loader (GOOSE_MODEL) set: a recipe file never
23
+ * names them. */
24
+ const SET_ELSEWHERE = new Set(["ANTHROPIC_HOST", "ANTHROPIC_API_KEY", "GOOSE_MODEL"]);
25
+ /** A model id as a provider names one: one line of letters, digits and `.-_:/`. */
26
+ const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}$/;
27
+ /** The recipe file `name`, as shipped beside this package's code. */
28
+ export function recipeFile(name) {
29
+ const parsed = JSON.parse(readFileSync(new URL(`../recipes/${name}.json`, import.meta.url), "utf8"));
30
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
31
+ throw new Error(`acp: the recipe file ${name}.json is not an object`);
32
+ if ("command" in parsed)
33
+ throw new Error(`acp: the recipe file ${name}.json names a command; the host's install gives it`);
34
+ return parsed;
35
+ }
36
+ /** Goose's recipe for one run: its file, with the binary and the run's model. Refused when it could not run. */
37
+ export function gooseRecipe(options) {
38
+ if (typeof options.model !== "string" || !MODEL_ID.test(options.model))
39
+ throw new Error(`acp: the model ${JSON.stringify(String(options.model).slice(0, 80))} is not a model id`);
40
+ const file = recipeFile("goose");
41
+ const named = Object.keys(file.env ?? {}).filter((name) => SET_ELSEWHERE.has(name));
42
+ if (named.length)
43
+ throw new Error(`acp: the goose recipe file names ${named.join(", ")}, which the proxy and the loader set`);
44
+ const recipe = { ...file, command: options.command, env: { ...file.env, GOOSE_MODEL: options.model } };
45
+ const problems = recipeProblems(recipe);
46
+ if (problems.length)
47
+ throw new Error(`acp: the goose recipe cannot run: ${problems.join("; ")}`);
48
+ return recipe;
49
+ }
50
+ /** Goose as a harness adapter (id `goose`): its pinned binary checked, its recipe for the run's model, and a model proxy
51
+ * of its own for each Goose process, on the session's booking. */
52
+ export function gooseAdapter(options) {
53
+ const { binary, sha256, model, provider, price, maxOutputTokens, fetch, ...rest } = options;
54
+ const platform = acpPlatform();
55
+ const pinned = sha256 ?? (platform ? GOOSE_PIN.archives[platform]?.binarySha256 : undefined);
56
+ if (!pinned)
57
+ throw new AcpBinaryRefused(ACP_CODES.binaryUnpinned, `no sha256 is pinned for Goose ${GOOSE_PIN.version}'s binary on ${platform ?? `${process.platform}-${process.arch}`}`);
58
+ verifyPinnedBinary(binary, pinned);
59
+ return acpAdapter({
60
+ ...rest,
61
+ recipe: gooseRecipe({ command: binary, model }),
62
+ // Checked again before each process starts: a binary replaced since the adapter was made never runs unchecked. An
63
+ // unchanged file is not hashed again (the check remembers it by its identity).
64
+ beforeStart: (command) => verifyPinnedBinaryAsync(command, pinned),
65
+ proxy: gooseProxy({ model, provider, ...(price ? { price } : {}), ...(maxOutputTokens ? { maxOutputTokens } : {}), ...(fetch ? { fetch } : {}), ...(rest.log ? { log: rest.log } : {}) }),
66
+ });
67
+ }
@@ -0,0 +1,80 @@
1
+ import type { GateAnswer, GateCall } from "@parcha/agentrun-kernel";
2
+ import type { DriveContext, HostTool, SessionState } from "@parcha/agentrun-kernel/kernel";
3
+ import type { ParentWatch } from "@parcha/agentrun-kernel/host";
4
+ import { type AcpRecipe } from "./recipe.js";
5
+ import type { ConfineChild } from "./host/child.js";
6
+ /** The agent's session id, one record each time a new agent session is opened. */
7
+ export declare const SESSION_STREAM = "acp.session";
8
+ /** One record per session/prompt sent (written just before it): the turns a plan-billed run counts. */
9
+ export declare const PROMPT_STREAM = "acp.prompt";
10
+ /** Our tools' calls as the MCP server took them (`seen`, before the gate) and as they ended (`answered`). */
11
+ export declare const CALL_STREAM = "acp.call";
12
+ /** The permission requests for the agent's own tools: `asked` before the gate is, `answered` with what it said. */
13
+ export declare const PERMISSION_STREAM = "acp.permission";
14
+ /** One record per tool call the agent announced (or MCP call it made unannounced): the calls a plan-billed run counts. */
15
+ export declare const TOOLS_STREAM = "acp.tools";
16
+ /** The model chosen for the agent's session (recipe.model, as the agent lists it), one record each time one is chosen. */
17
+ export declare const MODEL_STREAM = "acp.model";
18
+ /** How long a session waits for the agent to start and answer initialize, or open its session. */
19
+ export declare const START_MS = 60000;
20
+ /** How long an MCP call waits for the agent's tool_call that announces it. */
21
+ export declare const CALL_ID_WAIT_MS = 10000;
22
+ /** How long an agent past the plan's limit of tool calls has to end its turn after session/cancel before its process is
23
+ * ended: past the limit, each moment it goes on is spent on the owner's plan. */
24
+ export declare const LIMIT_STOP_MS = 3000;
25
+ /** How long a turn's end waits for the calls of ours still running in it to stop, once their signal is aborted. */
26
+ export declare const CALL_STOP_MS = 5000;
27
+ /** The most of an earlier call's input, and of its result or error, a context note quotes. */
28
+ export declare const NOTE_INPUT_CHARS = 1000;
29
+ export declare const NOTE_RESULT_CHARS = 2000;
30
+ export interface AcpHarnessOptions {
31
+ recipe: AcpRecipe;
32
+ /** The kernel's tools: exactly the host's. */
33
+ tools: HostTool[];
34
+ /** The session's instructions. */
35
+ instructions?: string;
36
+ /** The session's own directory: its private HOME, tmp and (with no `cwd`) work directory are made in it. */
37
+ dir: string;
38
+ /** The workspace the agent runs in (absolute), or `<dir>/work`. */
39
+ cwd?: string;
40
+ confine?: ConfineChild;
41
+ parentWatch?: ParentWatch;
42
+ /** The environment the child's allowlist reads. Default process.env. */
43
+ env?: Readonly<Record<string, string | undefined>>;
44
+ /** The host's gate (SessionIO.gate). Absent: every call runs. */
45
+ gate?: (call: GateCall) => Promise<GateAnswer>;
46
+ /** Proxy billing: what each agent process gets to reach the host's model proxy (its variables), closed with it.
47
+ * `halt` ends the drive the process serves. */
48
+ proxy?: (drive: {
49
+ halt(reason: unknown): void;
50
+ }) => Promise<{
51
+ env: Record<string, string>;
52
+ close(): Promise<void>;
53
+ }>;
54
+ /** Run before every start of the agent's process, a restart included: the host's check of the binary it runs. A throw
55
+ * refuses that start, so a binary replaced after the adapter was made is checked before it ever runs. */
56
+ beforeStart?: (command: string) => Promise<void>;
57
+ callIdWaitMs?: number;
58
+ startMs?: number;
59
+ log?: (message: string, fields?: Record<string, unknown>) => void;
60
+ }
61
+ /** What the adapter holds of the drive in flight, to stop its turn. */
62
+ export interface DriveControl {
63
+ /** Cancel the turn in flight (session/cancel): resolves true once the agent ended it within `ms`, with no end written
64
+ * for it (it stays open); false when the drive must be halted instead. */
65
+ interrupt(ms: number): Promise<boolean>;
66
+ }
67
+ /** The submissions a drive marked as sent to the agent (PROMPT_STREAM), with those a recovery's send carried. */
68
+ export declare function sentSubmissions(state: SessionState): Set<string>;
69
+ /** The conversation before the open turn (all of it with none open), as a new agent session reads it: each user
70
+ * message, each answer and each call of ours with its input and how it ended (its result, or its error), each cut to a
71
+ * bound (NOTE_INPUT_CHARS, NOTE_RESULT_CHARS) that says how much was left out. The inputs and results are quoted as
72
+ * the session's records hold them, as the kernel's recovery note quotes them. Empty when there is none. */
73
+ export declare function contextNote(state: SessionState): string | undefined;
74
+ /** The ACP harness. `control` is told of each drive call's stop hook while it runs. */
75
+ export declare function acpHarness(options: AcpHarnessOptions, control?: (drive: DriveControl | undefined) => void): {
76
+ name: string;
77
+ drive(ctx: DriveContext): Promise<void>;
78
+ /** End the agent's process and its MCP server. */
79
+ close(): Promise<void>;
80
+ };