@parcha/agentrun-harness-acp 0.1.0-beta.47 → 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 +11 -1
- package/README.md +1 -1
- package/dist/adapter.js +5 -2
- package/dist/cursor.d.ts +4 -5
- package/dist/cursor.js +14 -41
- package/dist/goose.js +4 -8
- package/dist/harness.js +16 -9
- package/dist/host/agent.d.ts +2 -0
- package/dist/host/agent.js +24 -6
- package/dist/host/key-cut.d.ts +10 -0
- package/dist/host/key-cut.js +29 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/pinned-binary.d.ts +10 -0
- package/dist/pinned-binary.js +8 -0
- package/dist/testing.d.ts +16 -0
- package/dist/testing.js +26 -0
- package/package.json +7 -2
- package/testing/fake-acp-agent.mjs +388 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,16 @@
|
|
|
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
|
+
|
|
5
15
|
## 0.1.0-beta.47 (2026-11-19)
|
|
6
16
|
|
|
7
17
|
**Breaking:**
|
|
@@ -34,7 +44,7 @@
|
|
|
34
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.
|
|
35
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.
|
|
36
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.
|
|
37
|
-
- 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/
|
|
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 -->
|
|
38
48
|
|
|
39
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`).
|
|
40
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 -->
|
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 (`
|
|
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.
|
package/dist/adapter.js
CHANGED
|
@@ -14,6 +14,7 @@ import { bridgeTool, recoveryNote, settleTurn, transcriptOf } from "@parcha/agen
|
|
|
14
14
|
import { serialWriter } from "@parcha/agentrun-kernel/host";
|
|
15
15
|
import { acpHarness, sentSubmissions } from "./harness.js";
|
|
16
16
|
import { recipeProblems } from "./recipe.js";
|
|
17
|
+
import { cutKeys, keysToCut } from "./host/key-cut.js";
|
|
17
18
|
/** A tool name every ACP agent we know keeps whole in its MCP client. */
|
|
18
19
|
const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
19
20
|
/** How long a stop waits for the agent to end the turn itself (session/cancel) before the drive is halted. */
|
|
@@ -120,8 +121,10 @@ export function acpAdapter(options) {
|
|
|
120
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" };
|
|
121
122
|
}
|
|
122
123
|
catch (error) {
|
|
123
|
-
// Stopped by the session or its host: interrupted. Halted by anything else: failed, naming why
|
|
124
|
-
|
|
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) };
|
|
125
128
|
if (current.signal.aborted)
|
|
126
129
|
state = holdsTurn(current.state()) ? "open_turn" : "idle";
|
|
127
130
|
}
|
package/dist/cursor.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { AgentAdapter } from "@parcha/agentrun-kernel";
|
|
2
2
|
import { type AcpAdapterOptions } from "./adapter.js";
|
|
3
3
|
import { type CursorLimits } from "./cursor-facts.js";
|
|
4
|
-
import { type
|
|
4
|
+
import { type PinnedRelease } from "./pinned-binary.js";
|
|
5
5
|
import { type AcpRecipe } from "./recipe.js";
|
|
6
6
|
export interface CursorRecipeOptions {
|
|
7
7
|
/** The Cursor launcher (`<install>/dist-package/cursor-agent`), absolute: one that met its pin. */
|
|
@@ -25,11 +25,10 @@ export interface CursorAdapterOptions extends Omit<AcpAdapterOptions, "recipe" |
|
|
|
25
25
|
}
|
|
26
26
|
/** Cursor's release pinned for `platform` (default this host's), with its launcher's and its tree's digests; undefined
|
|
27
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
|
|
29
|
-
export declare
|
|
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
30
|
/** A pinned Cursor release: its archive, with its launcher's sha256 and its tree's digest. */
|
|
31
|
-
export type CursorRelease =
|
|
32
|
-
readonly binarySha256: string;
|
|
31
|
+
export type CursorRelease = PinnedRelease & {
|
|
33
32
|
readonly treeSha256: string;
|
|
34
33
|
};
|
|
35
34
|
/** Cursor as a harness adapter (id `cursor`): its pinned install checked, its recipe for the run's model and limits. */
|
package/dist/cursor.js
CHANGED
|
@@ -1,39 +1,20 @@
|
|
|
1
1
|
// Cursor as an AgentRun harness: its recipe (recipes/cursor.json), loaded and typed, and the adapter a host builds from
|
|
2
2
|
// it on a pinned install. Written for AgentRun.
|
|
3
3
|
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
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.
|
|
4
|
+
// Cursor's config directory is $CURSOR_CONFIG_DIR, else $XDG_CONFIG_HOME/cursor, else $HOME/.cursor (its
|
|
5
|
+
// cursor-config/dist/paths.js, Cursor 2026.11.13-eacade1): the adapter sets XDG_CONFIG_HOME to $HOME/.config, so the
|
|
6
|
+
// recipe's config and sessions are under `$HOME/.config/cursor`, and a file under ~/.cursor is never read.
|
|
20
7
|
import { normalize, sep } from "node:path";
|
|
21
8
|
import { acpAdapter } from "./adapter.js";
|
|
22
9
|
import { ACP_CODES } from "./facts.js";
|
|
23
10
|
import { CURSOR_LIMITS } from "./cursor-facts.js";
|
|
24
11
|
import { recipeFile } from "./goose.js";
|
|
25
|
-
import { acpPlatform, AcpBinaryRefused, CURSOR_PIN,
|
|
26
|
-
import {
|
|
12
|
+
import { acpPlatform, AcpBinaryRefused, CURSOR_PIN, pinnedRelease, unpinned, verifyPinnedBinary, verifyPinnedTree } from "./pinned-binary.js";
|
|
13
|
+
import { recipeProblems } from "./recipe.js";
|
|
27
14
|
/** Cursor's recipe for one run: its file, with the launcher, the run's model and its limits. Refused when it could not
|
|
28
15
|
* run. */
|
|
29
16
|
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
17
|
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
18
|
const file = recipeFile("cursor");
|
|
38
19
|
const recipe = { ...file, command: options.command, billing: { kind: "plan", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls }, ...(options.model !== undefined ? { model: options.model } : {}) };
|
|
39
20
|
const problems = recipeProblems(recipe);
|
|
@@ -49,32 +30,24 @@ export function cursorRootOf(binary, cmd) {
|
|
|
49
30
|
}
|
|
50
31
|
/** Cursor's release pinned for `platform` (default this host's), with its launcher's and its tree's digests; undefined
|
|
51
32
|
* 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
|
|
53
|
-
export
|
|
54
|
-
const release = platform ? CURSOR_PIN.archives[platform] : undefined;
|
|
55
|
-
return release?.binarySha256 && release.treeSha256 ? release : undefined;
|
|
56
|
-
}
|
|
33
|
+
* of it is read: pinnedRelease's tree test on CURSOR_PIN, the one the adapter, serve and their tests make. */
|
|
34
|
+
export const cursorRelease = (platform = acpPlatform()) => pinnedRelease(CURSOR_PIN, platform, true);
|
|
57
35
|
/** Cursor as a harness adapter (id `cursor`): its pinned install checked, its recipe for the run's model and limits. */
|
|
58
36
|
export function cursorAdapter(options) {
|
|
59
37
|
const { binary, model, limits, ...rest } = options;
|
|
60
|
-
const
|
|
61
|
-
const release = cursorRelease(platform);
|
|
38
|
+
const release = cursorRelease();
|
|
62
39
|
if (!release)
|
|
63
|
-
throw
|
|
40
|
+
throw unpinned("Cursor", CURSOR_PIN.version);
|
|
64
41
|
const root = cursorRootOf(binary, release.cmd);
|
|
65
42
|
if (!root)
|
|
66
43
|
throw new AcpBinaryRefused(ACP_CODES.binaryMismatch, `the Cursor launcher at ${binary} is not at its pinned path ${release.cmd} inside its folder`);
|
|
67
|
-
|
|
68
|
-
const tree = release.treeSha256;
|
|
69
|
-
verifyPinnedBinary(binary, launcher);
|
|
44
|
+
verifyPinnedBinary(binary, release.binarySha256);
|
|
70
45
|
return acpAdapter({
|
|
71
46
|
...rest,
|
|
72
47
|
recipe: cursorRecipe({ command: binary, ...(model !== undefined ? { model } : {}), ...(limits ? { limits } : {}) }),
|
|
73
|
-
// Checked again before each process starts,
|
|
74
|
-
// was made never runs unchecked. An unchanged file is not hashed again (the
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
await verifyPinnedTree(root, tree);
|
|
78
|
-
},
|
|
48
|
+
// Checked again before each process starts, every file it runs, the launcher among them (the tree's digest covers
|
|
49
|
+
// it): a file replaced since the adapter was made never runs unchecked. An unchanged file is not hashed again (the
|
|
50
|
+
// check remembers it by its identity).
|
|
51
|
+
beforeStart: () => verifyPinnedTree(root, release.treeSha256),
|
|
79
52
|
});
|
|
80
53
|
}
|
package/dist/goose.js
CHANGED
|
@@ -15,15 +15,12 @@
|
|
|
15
15
|
// the recipe's.
|
|
16
16
|
import { readFileSync } from "node:fs";
|
|
17
17
|
import { acpAdapter } from "./adapter.js";
|
|
18
|
-
import { ACP_CODES } from "./facts.js";
|
|
19
18
|
import { gooseProxy } from "./host/goose-proxy.js";
|
|
20
|
-
import {
|
|
21
|
-
import { recipeProblems } from "./recipe.js";
|
|
19
|
+
import { GOOSE_PIN, pinnedRelease, unpinned, verifyPinnedBinary, verifyPinnedBinaryAsync } from "./pinned-binary.js";
|
|
20
|
+
import { MODEL_ID, recipeProblems } from "./recipe.js";
|
|
22
21
|
/** The variables the proxy (ANTHROPIC_HOST, ANTHROPIC_API_KEY) and the loader (GOOSE_MODEL) set: a recipe file never
|
|
23
22
|
* names them. */
|
|
24
23
|
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
24
|
/** The recipe file `name`, as shipped beside this package's code. */
|
|
28
25
|
export function recipeFile(name) {
|
|
29
26
|
const parsed = JSON.parse(readFileSync(new URL(`../recipes/${name}.json`, import.meta.url), "utf8"));
|
|
@@ -51,10 +48,9 @@ export function gooseRecipe(options) {
|
|
|
51
48
|
* of its own for each Goose process, on the session's booking. */
|
|
52
49
|
export function gooseAdapter(options) {
|
|
53
50
|
const { binary, sha256, model, provider, price, maxOutputTokens, fetch, ...rest } = options;
|
|
54
|
-
const
|
|
55
|
-
const pinned = sha256 ?? (platform ? GOOSE_PIN.archives[platform]?.binarySha256 : undefined);
|
|
51
|
+
const pinned = sha256 ?? pinnedRelease(GOOSE_PIN)?.binarySha256;
|
|
56
52
|
if (!pinned)
|
|
57
|
-
throw
|
|
53
|
+
throw unpinned("Goose", GOOSE_PIN.version);
|
|
58
54
|
verifyPinnedBinary(binary, pinned);
|
|
59
55
|
return acpAdapter({
|
|
60
56
|
...rest,
|
package/dist/harness.js
CHANGED
|
@@ -24,6 +24,7 @@ import { ACP_CODES } from "./facts.js";
|
|
|
24
24
|
import { homePath } from "./recipe.js";
|
|
25
25
|
import { restoreState, STATE_STREAM, StateMirror } from "./state.js";
|
|
26
26
|
import { startAgent } from "./host/agent.js";
|
|
27
|
+
import { cutKeys, keysToCut } from "./host/key-cut.js";
|
|
27
28
|
import { startMcpServer } from "./host/mcp.js";
|
|
28
29
|
/** The agent's session id, one record each time a new agent session is opened. */
|
|
29
30
|
export const SESSION_STREAM = "acp.session";
|
|
@@ -155,12 +156,17 @@ export function acpHarness(options, control) {
|
|
|
155
156
|
const refusal = recipe.refusals?.find((r) => text.includes(r.says));
|
|
156
157
|
return refusal && `${refusal.code}: ${refusal.words}`;
|
|
157
158
|
};
|
|
158
|
-
/**
|
|
159
|
-
*
|
|
159
|
+
/** The values of the recipe's keys, read by name as the agent's start reads them: cut from anything the agent says
|
|
160
|
+
* before it is shortened (key-cut.ts), so no cut lands inside one. */
|
|
161
|
+
const heldKeys = () => keysToCut((recipe.keys ?? []).map((name) => (options.env ?? process.env)[name]));
|
|
162
|
+
/** An error's words, the recipe's keys cut, its first 300 characters. */
|
|
163
|
+
const said = (error) => cutKeys(message(error), heldKeys()).slice(0, 300);
|
|
164
|
+
/** `text` (the agent's stderr, or an error carrying it) as a failure's words: the terminal's escapes out, the recipe's
|
|
165
|
+
* keys cut, and every line holding words the recipe calls quiet (recipe.quiet) left out, the last 300 characters of what
|
|
166
|
+
* is left. */
|
|
160
167
|
// eslint-disable-next-line no-control-regex
|
|
161
168
|
const ESCAPES = /\u001b\[[0-9;?]*[A-Za-z]/g;
|
|
162
|
-
const lastWords = (text) => text
|
|
163
|
-
.replace(ESCAPES, "")
|
|
169
|
+
const lastWords = (text) => cutKeys(text.replace(ESCAPES, ""), heldKeys())
|
|
164
170
|
.split("\n")
|
|
165
171
|
.filter((line) => !(recipe.quiet ?? []).some((words) => line.includes(words)))
|
|
166
172
|
.join("\n")
|
|
@@ -178,7 +184,7 @@ export function acpHarness(options, control) {
|
|
|
178
184
|
rt.mirror.take(journal);
|
|
179
185
|
}
|
|
180
186
|
catch (error) {
|
|
181
|
-
log("acp: the mirror of the agent's session store failed; the next point takes it again", { error:
|
|
187
|
+
log("acp: the mirror of the agent's session store failed; the next point takes it again", { error: said(error) });
|
|
182
188
|
}
|
|
183
189
|
};
|
|
184
190
|
/** The open turn's limit of tool calls, counted from the records: past it, the turn is cancelled with a named reason. */
|
|
@@ -446,7 +452,7 @@ export function acpHarness(options, control) {
|
|
|
446
452
|
rmSync(dir, { recursive: true, force: true });
|
|
447
453
|
}
|
|
448
454
|
catch (error) {
|
|
449
|
-
log("acp: the agent's private HOME could not be removed", { dir, error:
|
|
455
|
+
log("acp: the agent's private HOME could not be removed", { dir, error: said(error) });
|
|
450
456
|
}
|
|
451
457
|
}
|
|
452
458
|
}
|
|
@@ -485,6 +491,7 @@ export function acpHarness(options, control) {
|
|
|
485
491
|
...(options.env ? { from: options.env } : {}),
|
|
486
492
|
...(options.confine ? { confine: options.confine } : {}),
|
|
487
493
|
...(options.parentWatch ? { parentWatch: options.parentWatch } : {}),
|
|
494
|
+
keys: Object.values(keyEnv),
|
|
488
495
|
signal,
|
|
489
496
|
onUpdate: (notification) => onUpdate(rt, notification),
|
|
490
497
|
onPermission: (request, connection) => onPermission(rt, request, connection),
|
|
@@ -503,7 +510,7 @@ export function acpHarness(options, control) {
|
|
|
503
510
|
throw new Error(named);
|
|
504
511
|
if (!live.alive() || live.connection.signal.aborted)
|
|
505
512
|
throw new Error(`${ACP_CODES.agentExited}: the agent ended during ${what}: ${whyEnded(live, error)}`);
|
|
506
|
-
throw new Error(`acp: ${what} failed: ${
|
|
513
|
+
throw new Error(`acp: ${what} failed: ${said(error)}`);
|
|
507
514
|
});
|
|
508
515
|
const init = await ask("initialize", () => live.connection.agent.request("initialize", { protocolVersion: PROTOCOL_VERSION, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, clientInfo: { name: "agentrun", version: "1" } }));
|
|
509
516
|
if (init.protocolVersion !== PROTOCOL_VERSION)
|
|
@@ -535,7 +542,7 @@ export function acpHarness(options, control) {
|
|
|
535
542
|
catch (error) {
|
|
536
543
|
if (signal.aborted || !live.alive())
|
|
537
544
|
throw error;
|
|
538
|
-
log("acp: the agent did not load its session; a new one starts with the conversation so far", { error:
|
|
545
|
+
log("acp: the agent did not load its session; a new one starts with the conversation so far", { error: said(error) });
|
|
539
546
|
}
|
|
540
547
|
finally {
|
|
541
548
|
rt.loading = false;
|
|
@@ -708,7 +715,7 @@ export function acpHarness(options, control) {
|
|
|
708
715
|
outcome = { status: "failed", error: turn.limitHit };
|
|
709
716
|
else if (failure !== undefined) {
|
|
710
717
|
const named = refusalIn(`${agent.agent.stderrTail()}\n${message(failure)}`);
|
|
711
|
-
outcome = { status: "failed", error: named ?? (agent.agent.alive() && !agent.agent.connection.signal.aborted ? `acp: session/prompt failed: ${
|
|
718
|
+
outcome = { status: "failed", error: named ?? (agent.agent.alive() && !agent.agent.connection.signal.aborted ? `acp: session/prompt failed: ${said(failure)}` : `${ACP_CODES.agentExited}: the agent ended during the turn: ${whyEnded(agent.agent, failure)}`) };
|
|
712
719
|
}
|
|
713
720
|
else {
|
|
714
721
|
const reason = answer?.stopReason;
|
package/dist/host/agent.d.ts
CHANGED
|
@@ -11,6 +11,8 @@ export interface AgentProcessOptions {
|
|
|
11
11
|
from?: Readonly<Record<string, string | undefined>>;
|
|
12
12
|
confine?: ConfineChild;
|
|
13
13
|
parentWatch?: ParentWatch;
|
|
14
|
+
/** The key values in `env` (the recipe's keys): cut from its stderr before the tail is shortened. */
|
|
15
|
+
keys?: readonly string[];
|
|
14
16
|
signal: AbortSignal;
|
|
15
17
|
/** Each session/update the agent sends, in the order it sent them. */
|
|
16
18
|
onUpdate(update: SessionNotification): void;
|
package/dist/host/agent.js
CHANGED
|
@@ -2,27 +2,45 @@
|
|
|
2
2
|
// JSON-RPC, the official SDK's ndJsonStream). Written for AgentRun.
|
|
3
3
|
// - It starts with the environment allowlist (child.ts), in its own process group, watched by this process
|
|
4
4
|
// (parentWatched) inside the host's confinement: a SIGKILLed host leaves no agent behind.
|
|
5
|
-
// - Its stderr is kept, its tail only, for a failure's words; nothing it prints reaches the log whole.
|
|
5
|
+
// - Its stderr is kept, its tail only, for a failure's words; nothing it prints reaches the log whole. The keys it was
|
|
6
|
+
// handed are cut from the tail before it is shortened, and a key's end at the head of a cut tail goes too (key-cut.ts).
|
|
6
7
|
// - kill() ends its whole group; so does an abort of `signal`.
|
|
7
8
|
import { spawn } from "node:child_process";
|
|
8
9
|
import { Readable, Writable } from "node:stream";
|
|
9
10
|
import { client, ndJsonStream } from "@agentclientprotocol/sdk";
|
|
10
11
|
import { parentWatched } from "@parcha/agentrun-kernel/host";
|
|
11
12
|
import { childEnv, confined } from "./child.js";
|
|
13
|
+
import { cutKeyEndAtHead, cutKeys, keysToCut } from "./key-cut.js";
|
|
12
14
|
const STDERR_TAIL = 8 * 1024;
|
|
13
15
|
/** Start the agent and open the client connection over its stdio. */
|
|
14
16
|
export function startAgent(options) {
|
|
15
17
|
const run = confined(parentWatched({ command: options.command, args: [...options.args] }, options.parentWatch), options.confine);
|
|
16
18
|
const child = spawn(run.command, run.args, { cwd: options.cwd, env: childEnv(options.from ?? process.env, options.env), detached: true, stdio: ["pipe", "pipe", "pipe"] });
|
|
17
|
-
|
|
19
|
+
// What it printed, raw, kept a key's length beyond the tail: a key split across chunks, or across the tail's start, is
|
|
20
|
+
// still whole here, and cut whole (stderrTail). `cut`: whether its start was ever dropped.
|
|
21
|
+
const keys = keysToCut(options.keys ?? []);
|
|
22
|
+
const keep = STDERR_TAIL + (keys[0]?.length ?? 0);
|
|
23
|
+
let raw = "";
|
|
24
|
+
let cut = false;
|
|
25
|
+
const take = (text) => {
|
|
26
|
+
raw += text;
|
|
27
|
+
if (raw.length > keep) {
|
|
28
|
+
raw = raw.slice(-keep);
|
|
29
|
+
cut = true;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
const stderrTail = () => {
|
|
33
|
+
const text = cutKeys(raw, keys);
|
|
34
|
+
return (cut ? cutKeyEndAtHead(text, keys) : text).slice(-STDERR_TAIL);
|
|
35
|
+
};
|
|
18
36
|
child.stderr.setEncoding("utf8");
|
|
19
|
-
child.stderr.on("data",
|
|
37
|
+
child.stderr.on("data", take);
|
|
20
38
|
// A write to a stdin the agent closed is its exit's to report, never an unhandled error.
|
|
21
39
|
child.stdin.on("error", () => { });
|
|
22
40
|
let done = false;
|
|
23
41
|
const exited = new Promise((resolve) => {
|
|
24
42
|
child.once("error", (err) => {
|
|
25
|
-
|
|
43
|
+
take(`\n${String(err.message)}`);
|
|
26
44
|
done = true;
|
|
27
45
|
resolve({ code: null, signal: null });
|
|
28
46
|
});
|
|
@@ -52,6 +70,6 @@ export function startAgent(options) {
|
|
|
52
70
|
.onNotification("session/update", ({ params }) => options.onUpdate(params))
|
|
53
71
|
.onRequest("session/request_permission", ({ params, signal }) => options.onPermission(params, signal));
|
|
54
72
|
const connection = app.connect(ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout)));
|
|
55
|
-
void exited.then(() => connection.close(new Error(`the agent's process ended: ${
|
|
56
|
-
return { connection, pid: child.pid, exited, alive: () => !done, stderrTail
|
|
73
|
+
void exited.then(() => connection.close(new Error(`the agent's process ended: ${stderrTail().trim().slice(-300) || "it printed nothing"}`)));
|
|
74
|
+
return { connection, pid: child.pid, exited, alive: () => !done, stderrTail, kill };
|
|
57
75
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** A value shorter than this matches too much text by chance and is left as it is (as a host's redactor leaves it). */
|
|
2
|
+
export declare const KEY_CUT_MIN = 8;
|
|
3
|
+
export declare const KEY_CUT = "[redacted]";
|
|
4
|
+
/** The values worth cutting: those at least KEY_CUT_MIN long, longest first (a key holding another is cut whole). */
|
|
5
|
+
export declare const keysToCut: (values: readonly (string | undefined)[]) => string[];
|
|
6
|
+
/** `text` with each of `keys` (keysToCut) replaced, as written. */
|
|
7
|
+
export declare function cutKeys(text: string, keys: readonly string[]): string;
|
|
8
|
+
/** `text`, a tail whose start was cut, without the end of a key at its head: the longest piece that ends one of `keys`
|
|
9
|
+
* and starts the text goes (a key's end matches no key, so no cut of whole keys finds it). */
|
|
10
|
+
export declare function cutKeyEndAtHead(text: string, keys: readonly string[]): string;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The keys the adapter handed an agent (its recipe's keys, read by name), cut from what the agent says before any of it is
|
|
2
|
+
// shortened: a cut inside a key would leave a piece that no longer matches it, so nothing downstream (a host's own
|
|
3
|
+
// redactor, which still runs over what it keeps) could find it. Written for AgentRun.
|
|
4
|
+
/** A value shorter than this matches too much text by chance and is left as it is (as a host's redactor leaves it). */
|
|
5
|
+
export const KEY_CUT_MIN = 8;
|
|
6
|
+
export const KEY_CUT = "[redacted]";
|
|
7
|
+
/** The values worth cutting: those at least KEY_CUT_MIN long, longest first (a key holding another is cut whole). */
|
|
8
|
+
export const keysToCut = (values) => [...new Set(values.filter((value) => typeof value === "string" && value.length >= KEY_CUT_MIN))].sort((a, b) => b.length - a.length);
|
|
9
|
+
/** `text` with each of `keys` (keysToCut) replaced, as written. */
|
|
10
|
+
export function cutKeys(text, keys) {
|
|
11
|
+
let out = text;
|
|
12
|
+
for (const key of keys)
|
|
13
|
+
out = out.split(key).join(KEY_CUT);
|
|
14
|
+
return out;
|
|
15
|
+
}
|
|
16
|
+
/** `text`, a tail whose start was cut, without the end of a key at its head: the longest piece that ends one of `keys`
|
|
17
|
+
* and starts the text goes (a key's end matches no key, so no cut of whole keys finds it). */
|
|
18
|
+
export function cutKeyEndAtHead(text, keys) {
|
|
19
|
+
let drop = 0;
|
|
20
|
+
for (const key of keys) {
|
|
21
|
+
for (let n = Math.min(key.length - 1, text.length); n > drop; n--) {
|
|
22
|
+
if (text.startsWith(key.slice(-n))) {
|
|
23
|
+
drop = n;
|
|
24
|
+
break;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return text.slice(drop);
|
|
29
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -7,6 +7,6 @@ export type { ConfineChild } from "./host/child.js";
|
|
|
7
7
|
export { GOOSE_INSTALL, GOOSE_NOT_INSTALLED, gooseFacts } from "./goose-facts.js";
|
|
8
8
|
export { gooseAdapter, gooseRecipe, recipeFile, type AcpRecipeFile, type AcpRecipeName, type GooseAdapterOptions, type GooseRecipeOptions } from "./goose.js";
|
|
9
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, treeDigest, verifyPinnedBinary, verifyPinnedBinaryAsync, verifyPinnedTree, type AcpArchivePin, type AcpBinaryPin, type AcpPlatform } from "./pinned-binary.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
11
|
export { CURSOR_CODES, CURSOR_INSTALL, CURSOR_LIMITS, cursorCard, cursorFacts, type CursorLimits } from "./cursor-facts.js";
|
|
12
12
|
export { cursorAdapter, cursorRecipe, cursorRelease, cursorRootOf, type CursorAdapterOptions, type CursorRecipeOptions, type CursorRelease } from "./cursor.js";
|
package/dist/index.js
CHANGED
|
@@ -7,6 +7,6 @@ export { STATE_STREAM } from "./state.js";
|
|
|
7
7
|
export { GOOSE_INSTALL, GOOSE_NOT_INSTALLED, gooseFacts } from "./goose-facts.js";
|
|
8
8
|
export { gooseAdapter, gooseRecipe, recipeFile } from "./goose.js";
|
|
9
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, treeDigest, verifyPinnedBinary, verifyPinnedBinaryAsync, verifyPinnedTree } from "./pinned-binary.js";
|
|
10
|
+
export { acpPlatform, AcpBinaryRefused, CURSOR_PIN, GOOSE_PIN, pinnedRelease, treeDigest, verifyPinnedBinary, verifyPinnedBinaryAsync, verifyPinnedTree } from "./pinned-binary.js";
|
|
11
11
|
export { CURSOR_CODES, CURSOR_INSTALL, CURSOR_LIMITS, cursorCard, cursorFacts } from "./cursor-facts.js";
|
|
12
12
|
export { cursorAdapter, cursorRecipe, cursorRelease, cursorRootOf } from "./cursor.js";
|
package/dist/pinned-binary.d.ts
CHANGED
|
@@ -42,11 +42,21 @@ export declare const GOOSE_PIN: AcpBinaryPin;
|
|
|
42
42
|
export declare const CURSOR_PIN: AcpBinaryPin;
|
|
43
43
|
/** This host's platform as the registry names it, or undefined for one it does not list. */
|
|
44
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;
|
|
45
53
|
/** A binary the adapter will not start: its code says why (ACP_CODES.binaryMismatch, binaryUnreadable). */
|
|
46
54
|
export declare class AcpBinaryRefused extends Error {
|
|
47
55
|
readonly code: string;
|
|
48
56
|
constructor(code: string, message: string);
|
|
49
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;
|
|
50
60
|
/** Refuses the binary at `path` unless its sha256 is `sha256`. Reads it (once per file identity in this process),
|
|
51
61
|
* never runs it. */
|
|
52
62
|
export declare function verifyPinnedBinary(path: string, sha256: string): void;
|
package/dist/pinned-binary.js
CHANGED
|
@@ -62,6 +62,12 @@ export function acpPlatform(platform = process.platform, arch = process.arch) {
|
|
|
62
62
|
const cpu = arch === "arm64" ? "aarch64" : arch === "x64" ? "x86_64" : undefined;
|
|
63
63
|
return os && cpu ? `${os}-${cpu}` : undefined;
|
|
64
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
|
+
}
|
|
65
71
|
/** A binary the adapter will not start: its code says why (ACP_CODES.binaryMismatch, binaryUnreadable). */
|
|
66
72
|
export class AcpBinaryRefused extends Error {
|
|
67
73
|
code;
|
|
@@ -71,6 +77,8 @@ export class AcpBinaryRefused extends Error {
|
|
|
71
77
|
this.name = "AcpBinaryRefused";
|
|
72
78
|
}
|
|
73
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}`}`);
|
|
74
82
|
const SHA256 = /^[0-9a-f]{64}$/;
|
|
75
83
|
/** The check's one step: the file's sha256. */
|
|
76
84
|
const digestOf = (path) => function* () {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { AcpRecipe } from "./recipe.js";
|
|
2
|
+
/** The fake agent's file: `node FAKE_ACP_AGENT <config.json>` starts it (its header says what the config holds). */
|
|
3
|
+
export declare const FAKE_ACP_AGENT: string;
|
|
4
|
+
/** How the fake plays an agent: `load` it resumes with session/load (else a crash restarts the turn); `http` our tools
|
|
5
|
+
* reach it over HTTP (else stdio); `style` how it names our tools and what it asks permission for ("goose": every tool
|
|
6
|
+
* asks; "cursor": MCP and shell calls ask, edits do not); `askMcp` whether an MCP call asks first (default: the
|
|
7
|
+
* style's). */
|
|
8
|
+
export interface FakeAgentPlay {
|
|
9
|
+
readonly load?: boolean;
|
|
10
|
+
readonly http?: boolean;
|
|
11
|
+
readonly style?: "goose" | "cursor";
|
|
12
|
+
readonly askMcp?: boolean;
|
|
13
|
+
}
|
|
14
|
+
/** The fake agent as the recipe of harness `id`, its config written into `dir`, driven by `script` (the conformance
|
|
15
|
+
* suite's ScriptStep list). Billed `plan`: the fake calls no model, so no proxy is started. */
|
|
16
|
+
export declare function fakeAgentRecipe(id: string, dir: string, script: readonly unknown[], play?: FakeAgentPlay): AcpRecipe;
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// What a harness author tests an ACP harness on (`@parcha/agentrun-harness-acp/testing`, HARNESS.md): the fake ACP agent,
|
|
2
|
+
// a stdio agent on the official SDK whose model is a script, and its recipe. No binary, no model, no network beyond
|
|
3
|
+
// loopback: the conformance suite's script drives it, so an author's module runs the suite before any real agent is in it.
|
|
4
|
+
// Written for AgentRun.
|
|
5
|
+
import { writeFileSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
/** The fake agent's file: `node FAKE_ACP_AGENT <config.json>` starts it (its header says what the config holds). */
|
|
9
|
+
export const FAKE_ACP_AGENT = fileURLToPath(new URL("../testing/fake-acp-agent.mjs", import.meta.url));
|
|
10
|
+
/** The fake agent as the recipe of harness `id`, its config written into `dir`, driven by `script` (the conformance
|
|
11
|
+
* suite's ScriptStep list). Billed `plan`: the fake calls no model, so no proxy is started. */
|
|
12
|
+
export function fakeAgentRecipe(id, dir, script, play = {}) {
|
|
13
|
+
const load = play.load ?? true;
|
|
14
|
+
const http = play.http ?? true;
|
|
15
|
+
const config = join(dir, `${id}-fake-agent.json`);
|
|
16
|
+
writeFileSync(config, JSON.stringify({ script, load, http, style: play.style ?? "goose", ...(play.askMcp === undefined ? {} : { askMcp: play.askMcp }) }));
|
|
17
|
+
return {
|
|
18
|
+
id,
|
|
19
|
+
label: `${id} (the fake ACP agent)`,
|
|
20
|
+
command: process.execPath,
|
|
21
|
+
args: [FAKE_ACP_AGENT, config],
|
|
22
|
+
state: [".fake-acp"],
|
|
23
|
+
declares: { load, mcp: http ? "http" : "stdio" },
|
|
24
|
+
billing: { kind: "plan", maxTurns: 100, maxToolCalls: 100 },
|
|
25
|
+
};
|
|
26
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-harness-acp",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.48",
|
|
4
4
|
"description": "Any Agent Client Protocol agent as an AgentRun harness: the agent over stdio in a private HOME, the host's tools as one loopback MCP server, its permission asks through the host's gate, durable in AgentRun's own store.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentrun",
|
|
@@ -26,11 +26,16 @@
|
|
|
26
26
|
"types": "./dist/facts.d.ts",
|
|
27
27
|
"default": "./dist/facts.js"
|
|
28
28
|
},
|
|
29
|
+
"./testing": {
|
|
30
|
+
"types": "./dist/testing.d.ts",
|
|
31
|
+
"default": "./dist/testing.js"
|
|
32
|
+
},
|
|
29
33
|
"./package.json": "./package.json"
|
|
30
34
|
},
|
|
31
35
|
"files": [
|
|
32
36
|
"dist",
|
|
33
37
|
"recipes",
|
|
38
|
+
"testing",
|
|
34
39
|
"README.md",
|
|
35
40
|
"CHANGELOG.md",
|
|
36
41
|
"LICENSE",
|
|
@@ -44,7 +49,7 @@
|
|
|
44
49
|
},
|
|
45
50
|
"dependencies": {
|
|
46
51
|
"@agentclientprotocol/sdk": "2.7.0",
|
|
47
|
-
"@parcha/agentrun-kernel": "0.1.0-beta.
|
|
52
|
+
"@parcha/agentrun-kernel": "0.1.0-beta.48",
|
|
48
53
|
"zod": "4.6.6"
|
|
49
54
|
},
|
|
50
55
|
"publishConfig": {
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// A stand-in ACP agent for the adapter's tests and the conformance suite: a stdio agent on the official SDK whose "model"
|
|
3
|
+
// is a script. No binary, no model, no network beyond loopback. Its one argument is a JSON config file:
|
|
4
|
+
// script: the model's steps, the conformance suite's ScriptStep ({call, args} | {say, cut} | {sayLastSteer} |
|
|
5
|
+
// {sayLastResult}) plus {native: kind, title, input}, a tool of the agent's own (a shell, an edit);
|
|
6
|
+
// load: advertise session/load and keep sessions in $HOME/.fake-acp/sessions (default true);
|
|
7
|
+
// advertiseLoad / advertiseHttp: what initialize says, when it should differ from what the agent does;
|
|
8
|
+
// http: advertise MCP over HTTP (default true); the client then picks the transport;
|
|
9
|
+
// style: "goose" (titles agentrun__<tool>, every tool asks permission, allow_always offered first) or "cursor"
|
|
10
|
+
// (titles agentrun-<tool>: <tool>; MCP and execute ask, edits do not; a refused native call still reports
|
|
11
|
+
// completed), or "goose-1.59" (as "goose", but titled as Goose 1.59.2 titles a call of an extension's tool:
|
|
12
|
+
// `agentrun: <tool, its underscores as spaces>`);
|
|
13
|
+
// askMcp: ask permission before an MCP call (default: by style); askNative: the native kinds that ask;
|
|
14
|
+
// nativeLog: a file each native call that runs appends its title to;
|
|
15
|
+
// countFile: a file each event (new, load, prompt, cancel, mcp, permission) is appended to, one JSON line;
|
|
16
|
+
// systemPrompt: advertise sessionCapabilities.systemPrompt;
|
|
17
|
+
// ignoreCancel: log session/cancel and go on as if it never came (an agent that keeps spending);
|
|
18
|
+
// keepMcpOnCancel: on session/cancel, answer the prompt `cancelled` at once and leave an MCP call in flight open;
|
|
19
|
+
// announce: "late" (with style "cursor"): an MCP call as Cursor 2026.11.13 announces it, a tool_call titled
|
|
20
|
+
// "MCP: tool" with no input, then a tool_call_update titled `agentrun: <tool>` whose rawInput is
|
|
21
|
+
// {providerIdentifier, toolName, args}; its permission request is titled `agentrun-<tool>: <tool>`;
|
|
22
|
+
// models: the models session/new and session/load list ({modelId, name}), the first current; session/set_model
|
|
23
|
+
// takes one of them and refuses any other;
|
|
24
|
+
// writeAuth: at session/new and session/load, write $HOME/.config/cursor/auth.json holding the sha256 of the
|
|
25
|
+
// CURSOR_API_KEY it was handed (a credential derived from the key, as Cursor writes one); authFile: that
|
|
26
|
+
// file's path in HOME instead. A write that fails (the path is a folder) is said on stderr and the session
|
|
27
|
+
// goes on, as Cursor's does;
|
|
28
|
+
// leak: {path, what}: at the same points, also write `path` (under HOME) holding what a release that saves its key
|
|
29
|
+
// elsewhere would: "key" the CURSOR_API_KEY as is, "base64" it in base64, "token" a JWT-shaped token (made
|
|
30
|
+
// here, no real one). For the key walk's red: a leak its guard must see;
|
|
31
|
+
// failNew: at session/new, print these words on stderr and exit 1 (Cursor's own refusals, the team admin's switch);
|
|
32
|
+
// cursorDirs: keep sessions and read the CLI config where Cursor 2026.11.13 does (cursor-config/dist/paths.js): its
|
|
33
|
+
// config directory is $CURSOR_CONFIG_DIR, else $XDG_CONFIG_HOME/cursor, else $HOME/.cursor; sessions in
|
|
34
|
+
// <dir>/acp-sessions, and an edit, write, delete or move refused unasked when <dir>/cli-config.json denies
|
|
35
|
+
// Write(**) (Cursor reports it completed all the same).
|
|
36
|
+
// A script step {hang: true} is a model that never answers (until a cancel the agent heeds).
|
|
37
|
+
// The step the model takes is the number it took before: its session's history (calls, native calls, answers), plus the
|
|
38
|
+
// calls a recovery or context note names that its history does not hold, as a resumed model reads its conversation.
|
|
39
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
40
|
+
import { spawn } from "node:child_process";
|
|
41
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
42
|
+
import { dirname, join } from "node:path";
|
|
43
|
+
import { createInterface } from "node:readline";
|
|
44
|
+
import { Readable, Writable } from "node:stream";
|
|
45
|
+
import { agent, ndJsonStream, RequestError } from "@agentclientprotocol/sdk";
|
|
46
|
+
|
|
47
|
+
const config = JSON.parse(readFileSync(process.argv[2], "utf8"));
|
|
48
|
+
const script = config.script ?? [];
|
|
49
|
+
const style = config.style ?? "goose";
|
|
50
|
+
const loads = config.load ?? true;
|
|
51
|
+
const askMcp = config.askMcp ?? true;
|
|
52
|
+
const askNative = new Set(config.askNative ?? (style === "cursor" ? ["execute"] : ["execute", "edit", "delete", "move", "fetch", "other"]));
|
|
53
|
+
const home = process.env.HOME ?? "/nonexistent";
|
|
54
|
+
/** Cursor's config directory, by its own rule (cursorDirs). */
|
|
55
|
+
const cursorDir = process.env.CURSOR_CONFIG_DIR?.trim() || (process.env.XDG_CONFIG_HOME?.trim() ? join(process.env.XDG_CONFIG_HOME, "cursor") : join(home, ".cursor"));
|
|
56
|
+
const store = config.cursorDirs ? join(cursorDir, "acp-sessions") : join(home, ".fake-acp", "sessions");
|
|
57
|
+
/** Whether Cursor's CLI config, where Cursor reads it, denies every Write (read at start, as Cursor reads it). */
|
|
58
|
+
const deniesWrite = (() => {
|
|
59
|
+
if (!config.cursorDirs) return false;
|
|
60
|
+
try {
|
|
61
|
+
return JSON.parse(readFileSync(join(cursorDir, "cli-config.json"), "utf8")).permissions?.deny?.includes("Write(**)") === true;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
})();
|
|
66
|
+
const EDITS = new Set(["edit", "delete", "move"]);
|
|
67
|
+
|
|
68
|
+
const said = (event) => config.countFile && appendFileSync(config.countFile, `${JSON.stringify({ at: Date.now(), pid: process.pid, ...event })}\n`);
|
|
69
|
+
const save = (session) => {
|
|
70
|
+
if (!loads) return;
|
|
71
|
+
mkdirSync(store, { recursive: true });
|
|
72
|
+
writeFileSync(join(store, `${session.id}.json`), JSON.stringify({ id: session.id, history: session.history }));
|
|
73
|
+
};
|
|
74
|
+
const sessions = new Map();
|
|
75
|
+
// What it was started with: the names in its environment (never their values), its HOME and its directory.
|
|
76
|
+
const pgid = (() => {
|
|
77
|
+
try {
|
|
78
|
+
return Number(readFileSync("/proc/self/stat", "utf8").replace(/^.*\) /s, "").split(" ")[2]);
|
|
79
|
+
} catch {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
})();
|
|
83
|
+
said({ type: "start", env: Object.keys(process.env).sort(), home, cwd: process.cwd(), pgid, ...(config.cursorDirs ? { cursorDir, deniesWrite } : {}) });
|
|
84
|
+
const titleOf = (tool) => (style === "cursor" ? `agentrun-${tool}: ${tool}` : style === "goose-1.59" ? `agentrun: ${tool.replace(/_/g, " ")}` : `agentrun__${tool}`);
|
|
85
|
+
const late = style === "cursor" && config.announce === "late";
|
|
86
|
+
const models = config.models ? { currentModelId: config.models[0].modelId, availableModels: config.models } : undefined;
|
|
87
|
+
/** The credential Cursor derives from its key, in its private HOME: here the key's sha256, never the key. */
|
|
88
|
+
function writeAuth() {
|
|
89
|
+
if (config.leak) {
|
|
90
|
+
const key = process.env.CURSOR_API_KEY ?? "";
|
|
91
|
+
const part = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
92
|
+
const held = { key, base64: Buffer.from(key).toString("base64"), token: `${part({ alg: "HS256", typ: "JWT" })}.${part({ sub: "fake", exp: 4102444800 })}.${part({ fake: "signature" })}` }[config.leak.what];
|
|
93
|
+
const file = join(home, config.leak.path);
|
|
94
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
95
|
+
writeFileSync(file, JSON.stringify({ held }));
|
|
96
|
+
}
|
|
97
|
+
if (!config.writeAuth) return;
|
|
98
|
+
const file = join(home, config.authFile ?? ".config/cursor/auth.json");
|
|
99
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
100
|
+
const keySha = createHash("sha256").update(process.env.CURSOR_API_KEY ?? "").digest("hex");
|
|
101
|
+
try {
|
|
102
|
+
writeFileSync(file, JSON.stringify({ keySha }));
|
|
103
|
+
} catch (error) {
|
|
104
|
+
// As Cursor 2026.11.13 does (src/utils/credential-persistence.ts): a credential it cannot save is said on stderr, and
|
|
105
|
+
// the session goes on with the one it holds in memory.
|
|
106
|
+
process.stderr.write(`\u001b[33m⚠ Cursor couldn't save your credentials. This session continues with the credentials it already has.\u001b[0m\nError: ${error.code}: illegal operation on a directory, open '${file}'\n`);
|
|
107
|
+
said({ type: "auth", file, keySha, saved: false, code: error.code });
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
said({ type: "auth", file, keySha, saved: true });
|
|
111
|
+
}
|
|
112
|
+
const steps = (history) => history.filter((h) => h.kind === "call" || h.kind === "native" || h.kind === "say").length;
|
|
113
|
+
const text = (blocks) => blocks.filter((b) => b.type === "text").map((b) => b.text);
|
|
114
|
+
|
|
115
|
+
/** The calls a note names (`- name(...), call <id>:`), a nested one's (`<id>/<key>`) left out. */
|
|
116
|
+
const namedCalls = (note) => [...note.matchAll(/, call ([^\s:/]+):/g)].map((m) => m[1]);
|
|
117
|
+
/** A note's answers said so far (`- assistant: …`, a context note's). */
|
|
118
|
+
const notedAnswers = (note) => note.split("\n").filter((line) => line.startsWith("- assistant: ")).length;
|
|
119
|
+
/** The last quoted message in a note (`> ` lines). */
|
|
120
|
+
function lastQuote(note) {
|
|
121
|
+
const groups = [];
|
|
122
|
+
let current;
|
|
123
|
+
for (const line of note.split("\n")) {
|
|
124
|
+
if (line.startsWith("> ") || line === ">") {
|
|
125
|
+
if (!current) groups.push((current = []));
|
|
126
|
+
current.push(line.replace(/^> ?/, ""));
|
|
127
|
+
} else current = undefined;
|
|
128
|
+
}
|
|
129
|
+
return groups.at(-1)?.join("\n");
|
|
130
|
+
}
|
|
131
|
+
/** The last call's result in a recovery note: the 4-space lines under its head, or what follows `failed: `. */
|
|
132
|
+
function lastNotedResult(note) {
|
|
133
|
+
const lines = note.split("\n");
|
|
134
|
+
let result;
|
|
135
|
+
for (let i = 0; i < lines.length; i++) {
|
|
136
|
+
const head = /^- .*, call [^\s:]+: (.*)$/.exec(lines[i]);
|
|
137
|
+
if (!head) continue;
|
|
138
|
+
const body = [];
|
|
139
|
+
for (let j = i + 1; j < lines.length && lines[j].startsWith(" "); j++) body.push(lines[j].slice(4));
|
|
140
|
+
result = body.length ? body.join("\n") : head[1].replace(/^failed: /, "");
|
|
141
|
+
}
|
|
142
|
+
return result;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** One MCP connection: streamable HTTP, or a stdio server the agent starts. */
|
|
146
|
+
async function mcpClient(server) {
|
|
147
|
+
let next = 1;
|
|
148
|
+
if (server.type === "http") {
|
|
149
|
+
const headers = Object.fromEntries((server.headers ?? []).map((h) => [h.name, h.value]));
|
|
150
|
+
const post = async (body, signal) => {
|
|
151
|
+
const response = await fetch(server.url, { method: "POST", headers: { ...headers, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify(body), signal });
|
|
152
|
+
if (response.status === 202) return undefined;
|
|
153
|
+
const raw = await response.text();
|
|
154
|
+
if ((response.headers.get("content-type") ?? "").includes("text/event-stream")) {
|
|
155
|
+
const messages = raw.split("\n").filter((l) => l.startsWith("data: ")).map((l) => JSON.parse(l.slice(6)));
|
|
156
|
+
return messages.find((m) => m.id === body.id);
|
|
157
|
+
}
|
|
158
|
+
return JSON.parse(raw);
|
|
159
|
+
};
|
|
160
|
+
const request = async (method, params, signal) => {
|
|
161
|
+
const answer = await post({ jsonrpc: "2.0", id: next++, method, params }, signal);
|
|
162
|
+
if (answer?.error) throw new Error(answer.error.message);
|
|
163
|
+
return answer?.result;
|
|
164
|
+
};
|
|
165
|
+
await request("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "fake-acp", version: "1" } });
|
|
166
|
+
await post({ jsonrpc: "2.0", method: "notifications/initialized" });
|
|
167
|
+
return { request, close() {} };
|
|
168
|
+
}
|
|
169
|
+
const child = spawn(server.command, server.args ?? [], { env: { ...Object.fromEntries((server.env ?? []).map((e) => [e.name, e.value])), PATH: process.env.PATH ?? "" }, stdio: ["pipe", "pipe", "inherit"] });
|
|
170
|
+
const waiting = new Map();
|
|
171
|
+
createInterface({ input: child.stdout }).on("line", (line) => {
|
|
172
|
+
let message;
|
|
173
|
+
try {
|
|
174
|
+
message = JSON.parse(line);
|
|
175
|
+
} catch {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
waiting.get(message.id)?.(message);
|
|
179
|
+
waiting.delete(message.id);
|
|
180
|
+
});
|
|
181
|
+
const request = (method, params, signal) => new Promise((resolve, reject) => {
|
|
182
|
+
const id = next++;
|
|
183
|
+
waiting.set(id, (m) => (m.error ? reject(new Error(m.error.message)) : resolve(m.result)));
|
|
184
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
|
|
185
|
+
signal?.addEventListener("abort", () => {
|
|
186
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: id } })}\n`);
|
|
187
|
+
waiting.delete(id);
|
|
188
|
+
reject(new Error("cancelled"));
|
|
189
|
+
}, { once: true });
|
|
190
|
+
});
|
|
191
|
+
await request("initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "fake-acp", version: "1" } });
|
|
192
|
+
child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`);
|
|
193
|
+
return { request, close: () => child.kill() };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function openSession(id, params, history) {
|
|
197
|
+
const servers = params.mcpServers ?? [];
|
|
198
|
+
const server = servers.find((s) => s.name === "agentrun") ?? servers[0];
|
|
199
|
+
const mcp = server ? await mcpClient(server) : undefined;
|
|
200
|
+
const session = { id, history, mcp, turn: undefined, system: params.systemPrompt ? text(params.systemPrompt.content ?? []).join("\n") : undefined };
|
|
201
|
+
sessions.set(id, session);
|
|
202
|
+
return session;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Ask the client about a call; true when it allowed it once. */
|
|
206
|
+
async function permitted(client, session, update) {
|
|
207
|
+
const options = style === "cursor"
|
|
208
|
+
? [{ optionId: "allow-once", name: "Allow once", kind: "allow_once" }, { optionId: "allow-always", name: "Always allow", kind: "allow_always" }, { optionId: "reject-once", name: "Reject", kind: "reject_once" }]
|
|
209
|
+
: [{ optionId: "allow_always", name: "Always Allow", kind: "allow_always" }, { optionId: "allow_once", name: "Allow Once", kind: "allow_once" }, { optionId: "reject_once", name: "Deny Once", kind: "reject_once" }, { optionId: "reject_always", name: "Always Deny", kind: "reject_always" }];
|
|
210
|
+
const answer = await client.request("session/request_permission", { sessionId: session.id, toolCall: update, options });
|
|
211
|
+
const chosen = answer.outcome.outcome === "selected" ? options.find((o) => o.optionId === answer.outcome.optionId) : undefined;
|
|
212
|
+
said({ type: "permission", toolCallId: update.toolCallId, title: update.title, outcome: answer.outcome.outcome, kind: chosen?.kind });
|
|
213
|
+
return chosen?.kind === "allow_once" || chosen?.kind === "allow_always";
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function takeTurn(client, session, prompt, signal) {
|
|
217
|
+
const blocks = text(prompt);
|
|
218
|
+
const said_ = blocks.at(-1) ?? "";
|
|
219
|
+
const notes = blocks.filter((b) => b.includes("[Recovery]") || b.includes("[Context]")).join("\n");
|
|
220
|
+
const known = new Set(session.history.filter((h) => h.kind === "call").map((h) => h.id));
|
|
221
|
+
const extra = [...new Set(namedCalls(notes))].filter((id) => !known.has(id));
|
|
222
|
+
let step = steps(session.history) + extra.length + notedAnswers(notes);
|
|
223
|
+
session.history.push({ kind: "user", text: said_ });
|
|
224
|
+
save(session);
|
|
225
|
+
const notify = (update) => client.notify("session/update", { sessionId: session.id, update });
|
|
226
|
+
let lastResult = lastNotedResult(notes) ?? [...session.history].reverse().find((h) => (h.kind === "call" || h.kind === "native") && h.result !== undefined)?.result;
|
|
227
|
+
for (;;) {
|
|
228
|
+
if (signal.aborted) return { stopReason: "cancelled" };
|
|
229
|
+
const s = script[step];
|
|
230
|
+
if (!s) return { stopReason: "end_turn" };
|
|
231
|
+
step++;
|
|
232
|
+
if ("call" in s) {
|
|
233
|
+
const id = `call_${step - 1}`;
|
|
234
|
+
const args = s.args ?? {};
|
|
235
|
+
const update = { toolCallId: id, title: titleOf(s.call), kind: "other", status: "pending", rawInput: args };
|
|
236
|
+
const entry = { kind: "call", id, tool: s.call, args, status: "pending" };
|
|
237
|
+
session.history.push(entry);
|
|
238
|
+
save(session);
|
|
239
|
+
if (late) {
|
|
240
|
+
// Cursor 2026.11.13: the call is announced with no name, then named by an update, then asked about by its own title.
|
|
241
|
+
await notify({ sessionUpdate: "tool_call", toolCallId: id, title: "MCP: tool", kind: "other", status: "pending", rawInput: {} });
|
|
242
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, title: `agentrun: ${s.call}`, rawInput: { providerIdentifier: "agentrun", toolName: s.call, args } });
|
|
243
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: "in_progress" });
|
|
244
|
+
} else await notify({ sessionUpdate: "tool_call", ...update });
|
|
245
|
+
if (askMcp && !(await permitted(client, session, late ? { toolCallId: id, title: titleOf(s.call), kind: "other", status: "pending" } : update))) {
|
|
246
|
+
if (signal.aborted) return { stopReason: "cancelled" };
|
|
247
|
+
entry.status = "failed";
|
|
248
|
+
entry.result = "the client refused the call";
|
|
249
|
+
lastResult = entry.result;
|
|
250
|
+
save(session);
|
|
251
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: "failed" });
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
said({ type: "mcp", tool: s.call, toolCallId: id });
|
|
255
|
+
let answer;
|
|
256
|
+
try {
|
|
257
|
+
if (config.keepMcpOnCancel) {
|
|
258
|
+
// The prompt's answer does not wait for the call: a cancel ends the turn with the MCP request still open.
|
|
259
|
+
const call = session.mcp.request("tools/call", { name: s.call, arguments: args, _meta: { progressToken: id } });
|
|
260
|
+
call.catch(() => {});
|
|
261
|
+
const cancelled = new Promise((resolve) => (signal.aborted ? resolve("cancelled") : signal.addEventListener("abort", () => resolve("cancelled"), { once: true })));
|
|
262
|
+
answer = await Promise.race([call, cancelled]);
|
|
263
|
+
if (answer === "cancelled") return { stopReason: "cancelled" };
|
|
264
|
+
} else answer = await session.mcp.request("tools/call", { name: s.call, arguments: args, _meta: { progressToken: id } }, signal);
|
|
265
|
+
} catch (error) {
|
|
266
|
+
entry.status = "failed";
|
|
267
|
+
save(session);
|
|
268
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: "failed" });
|
|
269
|
+
if (signal.aborted) return { stopReason: "cancelled" };
|
|
270
|
+
lastResult = String(error?.message ?? error);
|
|
271
|
+
entry.result = lastResult;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
const result = (answer?.content ?? []).filter((c) => c.type === "text").map((c) => c.text).join("");
|
|
275
|
+
entry.status = answer?.isError ? "failed" : "completed";
|
|
276
|
+
entry.result = result;
|
|
277
|
+
lastResult = result;
|
|
278
|
+
save(session);
|
|
279
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: entry.status, content: [{ type: "content", content: { type: "text", text: result } }] });
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if ("native" in s) {
|
|
283
|
+
const id = `native_${step - 1}`;
|
|
284
|
+
const update = { toolCallId: id, title: s.title ?? s.native, kind: s.native, status: "pending", rawInput: s.input ?? {} };
|
|
285
|
+
const entry = { kind: "native", id, title: update.title, status: "pending" };
|
|
286
|
+
session.history.push(entry);
|
|
287
|
+
save(session);
|
|
288
|
+
await notify({ sessionUpdate: "tool_call", ...update });
|
|
289
|
+
const allowed = deniesWrite && EDITS.has(s.native) ? false : askNative.has(s.native) ? await permitted(client, session, update) : true;
|
|
290
|
+
if (signal.aborted) return { stopReason: "cancelled" };
|
|
291
|
+
if (allowed && config.nativeLog) appendFileSync(config.nativeLog, `${update.title}\n`);
|
|
292
|
+
entry.status = allowed ? "completed" : "failed";
|
|
293
|
+
entry.result = allowed ? `ran ${update.title}` : "the client refused the call";
|
|
294
|
+
lastResult = entry.result;
|
|
295
|
+
save(session);
|
|
296
|
+
// Cursor reports a refused call completed: the client must never trust it.
|
|
297
|
+
await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: style === "cursor" ? "completed" : entry.status });
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if ("die" in s) {
|
|
301
|
+
// Killed mid-turn (SIGKILL), as a host's kill takes it: no answer, no exit of its own.
|
|
302
|
+
said({ type: "die" });
|
|
303
|
+
process.kill(process.pid, "SIGKILL");
|
|
304
|
+
}
|
|
305
|
+
if ("hang" in s) {
|
|
306
|
+
said({ type: "hang" });
|
|
307
|
+
await new Promise((resolve) => (signal.aborted ? resolve() : signal.addEventListener("abort", resolve, { once: true })));
|
|
308
|
+
return { stopReason: "cancelled" };
|
|
309
|
+
}
|
|
310
|
+
let words;
|
|
311
|
+
if ("say" in s) words = s.say;
|
|
312
|
+
else if ("sayLastResult" in s) words = lastResult ?? "";
|
|
313
|
+
else if ("sayLastSteer" in s) words = (notes.includes("[Recovery]") ? lastQuote(blocks.find((b) => b.includes("[Recovery]"))) : undefined) ?? said_;
|
|
314
|
+
else words = "";
|
|
315
|
+
session.history.push({ kind: "say", text: words });
|
|
316
|
+
save(session);
|
|
317
|
+
if (words) await notify({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: words } });
|
|
318
|
+
return { stopReason: s.cut ? "max_tokens" : "end_turn" };
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const app = agent({ name: "fake-acp" })
|
|
323
|
+
.onRequest("initialize", () => ({
|
|
324
|
+
protocolVersion: 1,
|
|
325
|
+
agentCapabilities: {
|
|
326
|
+
loadSession: config.advertiseLoad ?? loads,
|
|
327
|
+
mcpCapabilities: { http: config.advertiseHttp ?? config.http ?? true, sse: false },
|
|
328
|
+
...(config.systemPrompt ? { sessionCapabilities: { systemPrompt: {} } } : {}),
|
|
329
|
+
},
|
|
330
|
+
agentInfo: { name: "fake-acp", version: "1.0.0" },
|
|
331
|
+
}))
|
|
332
|
+
.onRequest("session/new", async ({ params }) => {
|
|
333
|
+
if (config.failNew) {
|
|
334
|
+
process.stderr.write(`${config.failNew}\n`);
|
|
335
|
+
process.exit(1);
|
|
336
|
+
}
|
|
337
|
+
const id = `sess_${randomUUID()}`;
|
|
338
|
+
const session = await openSession(id, params, []);
|
|
339
|
+
save(session);
|
|
340
|
+
writeAuth();
|
|
341
|
+
said({ type: "new", sessionId: id, mcp: params.mcpServers.map((s) => s.type ?? "stdio"), system: session.system });
|
|
342
|
+
return { sessionId: id, ...(models ? { models } : {}) };
|
|
343
|
+
})
|
|
344
|
+
// Not in the SDK's stable methods: Cursor's own (unstable ACP) method, so its params are taken as they come.
|
|
345
|
+
.onRequest("session/set_model", (params) => params ?? {}, async ({ params }) => {
|
|
346
|
+
if (!models?.availableModels.some((m) => m.modelId === params.modelId)) throw RequestError.invalidParams({ modelId: params.modelId });
|
|
347
|
+
said({ type: "set_model", sessionId: params.sessionId, modelId: params.modelId });
|
|
348
|
+
return {};
|
|
349
|
+
})
|
|
350
|
+
.onRequest("session/load", async ({ params, client }) => {
|
|
351
|
+
const file = join(store, `${params.sessionId}.json`);
|
|
352
|
+
if (!loads || !existsSync(file)) throw RequestError.resourceNotFound(params.sessionId);
|
|
353
|
+
const { history } = JSON.parse(readFileSync(file, "utf8"));
|
|
354
|
+
const session = await openSession(params.sessionId, params, history);
|
|
355
|
+
said({ type: "load", sessionId: params.sessionId, steps: steps(history) });
|
|
356
|
+
// The history goes back to the client as it happened: a client keeps it off its timeline.
|
|
357
|
+
for (const h of history) {
|
|
358
|
+
if (h.kind === "user") await client.notify("session/update", { sessionId: session.id, update: { sessionUpdate: "user_message_chunk", content: { type: "text", text: h.text } } });
|
|
359
|
+
if (h.kind === "say" && h.text) await client.notify("session/update", { sessionId: session.id, update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: h.text } } });
|
|
360
|
+
if (h.kind === "call" || h.kind === "native") {
|
|
361
|
+
await client.notify("session/update", { sessionId: session.id, update: { sessionUpdate: "tool_call", toolCallId: h.id, title: h.kind === "call" ? titleOf(h.tool) : h.title, status: "pending", rawInput: h.args ?? {} } });
|
|
362
|
+
await client.notify("session/update", { sessionId: session.id, update: { sessionUpdate: "tool_call_update", toolCallId: h.id, status: h.status === "pending" ? "failed" : h.status } });
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
writeAuth();
|
|
366
|
+
return models ? { models } : {};
|
|
367
|
+
})
|
|
368
|
+
.onRequest("session/prompt", async ({ params, client }) => {
|
|
369
|
+
const session = sessions.get(params.sessionId);
|
|
370
|
+
if (!session) throw RequestError.resourceNotFound(params.sessionId);
|
|
371
|
+
const controller = new AbortController();
|
|
372
|
+
session.turn = controller;
|
|
373
|
+
said({ type: "prompt", sessionId: session.id, text: text(params.prompt) });
|
|
374
|
+
try {
|
|
375
|
+
return await takeTurn(client, session, params.prompt, controller.signal);
|
|
376
|
+
} finally {
|
|
377
|
+
session.turn = undefined;
|
|
378
|
+
}
|
|
379
|
+
})
|
|
380
|
+
.onNotification("session/cancel", ({ params }) => {
|
|
381
|
+
said({ type: "cancel", sessionId: params.sessionId });
|
|
382
|
+
if (!config.ignoreCancel) sessions.get(params.sessionId)?.turn?.abort(new Error("cancelled"));
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
const connection = app.connect(ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin)));
|
|
386
|
+
await connection.closed;
|
|
387
|
+
for (const session of sessions.values()) session.mcp?.close();
|
|
388
|
+
process.exit(0);
|