@parcha/agentrun-harness-acp 0.1.0-beta.62 → 0.1.0-beta.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.64 (2026-11-26)
6
+
7
+ - Under Cursor's recipe, AgentRun's MCP server now goes by a name of each start's own (`ar` and 6 random hex digits), as it already did under Antigravity's, and a call is AgentRun's only when its `providerIdentifier` says that name. Before, the server was named `agentrun`, so a second MCP server named exactly `agentrun` (in a workspace's `.cursor/mcp.json`, or the owner's own Cursor configuration) with a tool named like one of AgentRun's had its call read as AgentRun's: its permission request was answered `allow_once` on the title tie without the host's gate. Such a call is now the agent's own, and the host's gate decides it. A recipe whose `announces` reads the server from a field (`server`) gets the same. Goose's server keeps the name `agentrun`: its configuration is written whole at each start, and its proxy offers its model AgentRun's tools alone. <!-- changes/acp-cursor-own-server-name.md -->
8
+ - Under any recipe that declares the title tie (`quirks.permissionTie`), AgentRun's MCP server now goes by a name of each start's own (`ar` and 6 random hex digits), with the default `agentrun__` prefix, Goose's permission file and the proxy's tool policy (a proxy-billed recipe) reading that name. Before, a recipe of the owner's own with the tie and the default prefix kept `agentrun`, so a second MCP server named exactly `agentrun` with a tool named like one of AgentRun's had its call answered `allow_once` on the tie without the host's gate, or, with Goose's permission file, run unasked. The host gate's question about a call the recipe's server field (Cursor's `providerIdentifier`) names as another server's now carries that server's name (`server`), so a call titled `agentrun-look_up: look_up` can be told from AgentRun's own. Cursor's tool names in events and meta tools now read the start's own server name, not `agentrun`. <!-- changes/acp-tie-own-server-name.md -->
9
+ - On Goose and Cursor, a permission request for a tool the agent is not given is now refused at once, and the run goes on. Before, the request went to the host's gate like any other, and since there is no grant for a person to approve, the run parked (`parked`, with no summary) on a question nobody could answer usefully. Now the ACP adapter answers it `reject_once` without asking the gate or journaling it, and the run's timeline gets a line saying `tool "<name>" isn't granted to this agent`. ACP's permission answer carries no words, so the agent reads its own vendor's refusal; the line is for the person. A run that parked on such a request before this change is answered the same way when it resumes: the waiting request gets a settled deny in those words, the agent's recovery note says it was refused with no person asked, and the gate is not asked. Under Cursor's and agy's recipes, which give our server a new name at each start, the waiting request's title is read against the name of the start that asked, which the adapter now records with it; a request recorded without that name still goes to the gate, since its title cannot be tied to a server of ours. An agent that calls such a tool without asking now gets those same words from the adapter's MCP server, which said `unknown tool: <name>` before. A tool the agent is given whose setting asks (a write behind the gate) still asks a person and parks as before, and a native call with effects of its own (a shell, an edit) still goes to the gate whatever its title says. claude-agent, codex and pi never asked about such a tool: their tool bridge answers a call of a tool it does not hold `unknown tool: <name>` before the gate. serve's computer claim drops its `refuseKind` hook, which nothing called once every CLI harness got the browser. <!-- changes/acp-ungranted-tool-refused.md -->
10
+ - pi's turn budget now outlasts a process that stops in the turn, as Claude's, Codex's, ACP's and OpenCode's do: a pi session opened again takes the turn back from its conversation (its last answer's usage and calls, and each result handed since) before a call claims, so the calls a resume answers split what their answer left instead of each taking its whole bound. A read of the turn that fails runs no call: the call is an error naming why, and the next call reads again. <!-- changes/turn-budget-resume-pi-scripts.md -->
11
+ - A result goes back to the harness only once its length is in the session's journal (`TurnBudget.kept`): a process that stops right after it was handed no longer loses its part of the turn, which a resumed call would claim again. A length the journal could not keep fails the call instead of handing its result.
12
+ - A result settles at the length it was handed: a result of at most 400 characters, whole under any bound, and a refusal's words now hold what they took, so the calls after them split only what is left.
13
+ - A code-mode script's JSON read too large for its bound is handed as a note alone (`[read cut: this result is M characters of JSON, past the N ...]`), since part of a JSON document does not parse: on a 16k-32k window, a script that parses it fails naming the cut instead of on a character in the middle, and the model reads that it should ask for less. A read that is not JSON keeps its start and its note, as before.
14
+ - A failed call's error refused for a window too small to cut it in keeps its first line (as much as fits beside the note in the 400 characters a result always keeps whole), so the model reads what went wrong.
15
+ - A raise that reaches an agentic run's claim while that claim takes a retry of the raise that resumed the run (a raise covering the run's next park, during the retry's commit) waits for the run's next claim too, as one reaching a claim parking the run again does. Before, the claim could take it and park, the run left with nothing to wake it.
16
+ - The run's view shows the cap park a run stands at as its runner reads it: a raise entry clears only the park it names. A raise that names none (checked against the run while it worked) no longer hides a park journaled before it.
17
+
18
+ ## 0.1.0-beta.63 (2026-11-26)
19
+
20
+ - Cursor is now told at each session's start that its own Write tool is refused, so it writes a file with a shell command (which asks the person first) and never stops at that refusal without an answer; a shell command the person denies is their answer, not asked again. An ACP recipe can carry `instructions`, given to the agent after the session's own, by the same route. A conversation begun before its recipe had them (or changed them) gets them once, ahead of its next prompt, when an agent with no system prompt loads it. They count as given only once a copy of the agent's history taken after it answered the prompt that carried them is kept, so a runner that stops before that gives them again on the next load; this covers a session's own instructions in its first prompt too. <!-- changes/cursor-write-through-shell.md -->
21
+ - A tool result is held to the model's context window, not only to the fixed 120,000-character bound: a model with a small window (an Ollama model at 65,536 tokens, a 16k one) is never handed a result that fills its context. <!-- changes/tool-result-window-bound.md -->
22
+ - `boundResult(text, budget?)` takes the model's window (`{ contextWindow, baseInputTokens? }`): a result may take at most a quarter of what the window leaves (`RESULT_WINDOW_SHARE`), at three characters a token (`RESULT_CHARS_PER_TOKEN`), and never more than `HOST_RESULT_MAX_CHARS`. Past that it is cut with a note saying it was cut to fit the window and how to read on; a window too small for any cut refuses the result in words, and a result of at most 400 characters (`RESULT_ALWAYS_WHOLE_CHARS`) always stands whole, so bounding a bound changes nothing. With no window the bound is exactly as before. `resultMaxChars(budget)` gives the bound, and `boundTo(text, max)` cuts to a given bound, saying how (`ResultBound`: the characters kept, the whole length, the bound).
23
+ - `SessionSpec.contextWindow` carries the session model's window, and each harness adapter (Claude, Codex, ACP, OpenCode) takes a `contextWindow` option for when the host passes none; Codex and OpenCode are told that window in place of their 272,000 guess. A Codex script cut off by a crash is answered within the same bound (`recoveryMaxChars`), not `EXEC_RECOVERY_MAX_CHARS`.
24
+ - agentrun-serve puts the run's model window from its catalog on every session, and pi now holds every tool result to it too: a host tool's and a pi-native one's (web_fetch, web_search, the browser's), which before reached the model up to pi's own output limits. What a host tool streams while it runs is held to the bound too (`boundedProgress`), since pi writes a call cut off past its restart limit from that text, without its hooks.
25
+ - A turn's results together fit what the window has left (`TurnBudget`, `ResultBudget.turn`): from what the context already holds (the last request's input tokens and its answer's output, else the session's system prompt and tool schemas counted with o200k), less the room kept for the model's answer (`answerReserve`: a quarter of the window, at most `ANSWER_RESERVE_MAX_TOKENS`, 16,384 tokens), each call the model made takes the smaller of its own bound and what is left over the calls still unanswered, so parallel calls split it, and below the least a cut keeps a result is refused in words. The kernel owns the rule; the session's model proxy reports each answer's facts (`ModelProxyOptions.turn`, its calls counted from the stream by `toolCallsIn`) for Claude, Codex, OpenCode and Goose, and pi and Claude Code on a person's login report them from their own hooks (pi's afterResponse, the login's stream booking). `windowBudget(window, system?)` builds the budget with its turn. A call whose result goes to the harness's own tool rather than the model (`ToolBridgeOptions.outsideTurn`: Codex's code-mode script calls) takes the per-result bound alone, outside the turn's split.
26
+ - The bridge records each cut it hands a harness (`bound:<callId>`, `boundKey`), and a replay of the call is cut by that record. Codex compares a nested call's two records on those lengths, never on the note's words; `boundOf` is gone. A session written before the record still agrees where Codex got the host's bound's cut, as before.
27
+ - On Claude, Codex, ACP and OpenCode, a turn's budget outlasts a process that stops in the turn (a park, a crash): each answer's facts and each result's length as it was handed go to the session's journal as they happen (`journalTurn`, `TURN_STREAM`), and a budget that has read no answer yet takes them back before any call claims (`TurnBudget.restore`). The calls a resume answers split what their answer left, and a result handed before the stop keeps its part. Codex's recovered script outputs claim their room in the turn too and are held to that claim (`ResultBudget.maxChars`). pi's turn budget is not journaled yet: a pi session opened again starts a fresh one, and each result there keeps its per-result bound.
28
+
5
29
  ## 0.1.0-beta.62 (2026-11-26)
6
30
 
7
31
  - A late MCP call of a call that ended first (a cancel can report a call failed while its MCP call is on its way) takes its own announcement again before a live one that names no tool or reports no input, such as the agent's own think, whether that one was announced before the MCP call or while it held. Before, it could take that one's id: on a recipe with no announces field the think's, and on any recipe one announced during the hold. <!-- changes/acp-ended-own-first.md -->
package/README.md CHANGED
@@ -16,6 +16,14 @@ entries.
16
16
  nothing: a recipe's `allowFile` (Goose's `.config/goose/permission.yaml`) lists them for the agent at each start, and
17
17
  the gate asks at the MCP call. A recipe that declares `quirks.permissionTie: "title"` (Cursor's, whose allowlist asks
18
18
  for every MCP call, and Antigravity's, since agy asks for every MCP call) has its request for one of the host's announced calls answered `allow_once` without the gate.
19
+ - A request for a tool of the host's MCP server that the agent is not given (one its start does not list, named in its
20
+ title or name as the agent names the host's tools) is answered `reject_once` at once: no gate, nothing journaled, so
21
+ nothing parks, and the run gets a notice, `tool "<name>" isn't granted to this agent`. ACP's answer carries no words,
22
+ so the agent reads its own refusal; the notice is for the person. Such a request a parked run left waiting is
23
+ refused the same way on the resume, settled, before the agent starts: its title is read against the server name of
24
+ the start that asked, recorded with it, since Cursor's and agy's recipes name the server per start. A native call of a kind with effects (a shell, an
25
+ edit) is the gate's whatever its title. An agent that calls such a tool without asking is answered by the MCP server
26
+ itself, in the same words.
19
27
  - An agent's `tool_call` is matched to the MCP call it makes by the tool and the arguments. Which tool it names is read
20
28
  from the field its recipe's `announces` declares (Goose's `_meta.goose.toolCall.toolName`, Cursor's `rawInput`, agy's `name`),
21
29
  never from its title; a call that field names as another tool is the agent's own.
package/dist/adapter.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { AgentAdapter, ModelPort } from "@parcha/agentrun-kernel";
2
+ import { type TurnBudget } from "@parcha/agentrun-kernel/process";
2
3
  import { type ParentWatch } from "@parcha/agentrun-kernel/host";
3
4
  import { type AcpRecipe } from "./recipe.js";
4
5
  import type { ConfineChild } from "./host/child.js";
@@ -22,6 +23,10 @@ export interface AcpAdapterOptions {
22
23
  callIdWaitMs?: number;
23
24
  /** How long the agent may take to start and open its session. Default 60 s. */
24
25
  startMs?: number;
26
+ /** The model's context window, in tokens: the host's bound on one tool result is its share of it (the kernel's
27
+ * resultMaxChars), under HOST_RESULT_MAX_CHARS. A session's own (SessionSpec.contextWindow) wins. Absent, and none on
28
+ * the session: the host's bound alone. */
29
+ contextWindow?: number;
25
30
  log?: (message: string, fields?: Record<string, unknown>) => void;
26
31
  /** Log each call the agent announces, ids and names only (AcpHarnessOptions.debug). */
27
32
  debug?: boolean;
@@ -33,8 +38,12 @@ export interface AcpProxySession {
33
38
  readonly models: ModelPort;
34
39
  /** The host's tools, by the names the session has them under. */
35
40
  readonly tools: readonly string[];
41
+ /** Our MCP server's name at this start (mcpServerName): the agent names each tool `<server>__<tool>`. */
42
+ readonly server?: string;
36
43
  /** Ends the agent's drive: its turn ends failed in `reason`'s words. */
37
44
  halt(reason: unknown): void;
45
+ /** The session's turn budget (ResultBudget.turn): a proxy opens it with each answer's facts (ModelProxyOptions.turn). */
46
+ readonly turn?: TurnBudget;
38
47
  }
39
48
  /** A proxy for one agent process: the variables that point it at the proxy, and the proxy's close. */
40
49
  export type AcpProxy = (session: AcpProxySession) => Promise<{
package/dist/adapter.js CHANGED
@@ -10,7 +10,7 @@ import { createHash, randomUUID } from "node:crypto";
10
10
  import { join } from "node:path";
11
11
  import { toolSchemaProblems } from "@parcha/agentrun-kernel";
12
12
  import { abortedOutcome, openDrive, pendingSubmissions, SessionHalt } from "@parcha/agentrun-kernel/kernel";
13
- import { bridgeTool, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
13
+ import { bridgeTool, recoveryNote, settleTurn, transcriptOf, windowBudget } from "@parcha/agentrun-kernel/process";
14
14
  import { serialWriter } from "@parcha/agentrun-kernel/host";
15
15
  import { acpHarness, sentSubmissions } from "./harness.js";
16
16
  import { recipeProblems } from "./recipe.js";
@@ -74,16 +74,21 @@ export function acpAdapter(options) {
74
74
  throw new Error("acp: a session needs a private directory: the host lends one (io.dir), or pass sessionsDir");
75
75
  const instructions = spec.system.join("\n\n");
76
76
  let control;
77
+ // Each tool result held to the model's share of its window (the session's, else this adapter's; none: the host's
78
+ // bound), and a turn's results to what it has left, which a proxy reads from each answer.
79
+ const budget = windowBudget(spec.contextWindow ?? options.contextWindow, spec.system);
80
+ const turn = budget.resultBudget?.turn;
77
81
  const harness = acpHarness({
78
82
  recipe,
79
83
  tools: spec.tools.map((tool) => bridgeTool(tool)),
84
+ ...budget,
80
85
  ...(instructions ? { instructions } : {}),
81
86
  dir,
82
87
  ...(io.cwd ? { cwd: io.cwd } : {}),
83
88
  ...(options.confine ? { confine: options.confine } : {}),
84
89
  ...(options.parentWatch ? { parentWatch: options.parentWatch } : {}),
85
90
  ...(options.env ? { env: options.env } : {}),
86
- ...(options.proxy ? { proxy: (drive) => options.proxy({ models: io.models, tools: spec.tools.map((tool) => tool.name), halt: drive.halt }) } : {}),
91
+ ...(options.proxy ? { proxy: (drive) => options.proxy({ models: io.models, tools: spec.tools.map((tool) => tool.name), server: drive.server, halt: drive.halt, ...(turn ? { turn } : {}) }) } : {}),
87
92
  ...(options.beforeStart ? { beforeStart: options.beforeStart } : {}),
88
93
  ...(options.callIdWaitMs !== undefined ? { callIdWaitMs: options.callIdWaitMs } : {}),
89
94
  ...(options.startMs !== undefined ? { startMs: options.startMs } : {}),
package/dist/calls.d.ts CHANGED
@@ -1,32 +1,59 @@
1
- /** The MCP server's name, as the agent is given it (under agy's recipe, the start of it: mcpServerName). */
1
+ /** Our MCP server's name, as the agent is given it under a recipe without the title tie (Goose's); under one with it,
2
+ * or whose announces could take another server's call as ours, the start's own name instead (mcpServerName). */
2
3
  export declare const MCP_SERVER = "agentrun";
4
+ /** The pattern of a start's own name for our MCP server (mcpServerName): `ar` and 6 hex digits. */
5
+ export declare const START_SERVER = "ar[0-9a-f]{6}";
3
6
  /** JSON text of `value` with every object's keys sorted: two argument objects that say the same are the same text. */
4
7
  export declare function canonical(value: unknown): string;
5
8
  /** The ACP tool kinds of a call with effects of its own (a shell, a file write, a delete, a move, a fetch): never one of
6
9
  * our tools, whatever its title says. */
7
10
  export declare const NATIVE_EFFECT_KINDS: ReadonlySet<string>;
8
- /** The host tool a permission request's title or name gives, by a name for our MCP server's tools (`agentrun__<tool>`),
9
- * Cursor's own title for one (`agentrun-<tool>: <tool>`), or agy's (Antigravity's) name and title for one
10
- * (`mcp_agentrun_<tool>`, titled `Run mcp_agentrun_<tool>`, the whole text), when it is one of `tools` and its kind is
11
+ /** The host tool a permission request's title or name gives, by a name for our MCP server's tools (`<server>__<tool>`),
12
+ * Cursor's own title for one (`<server>-<tool>: <tool>`), or agy's (Antigravity's) name and title for one
13
+ * (`mcp_<server>_<tool>`, titled `Run mcp_<server>_<tool>`, the whole text), when it is one of `tools` and its kind is
11
14
  * not one with effects of its own. Read for the title tie alone (quirks.permissionTie: Cursor's and agy's), and only
12
15
  * beside the call's announcement: the title is the agent's text, so a request is tied only when it is for a call the
13
16
  * recipe's announces field named as the same tool (CallIds.announced). Nothing else reads a title. `server` is the name
14
- * our MCP server was given to the agent under at this start (mcpServerName): agy's name and title carry it. */
17
+ * our MCP server was given to the agent under at this start (mcpServerName), which each of these forms carries: under
18
+ * the tie, the start's own. */
15
19
  export declare function ourTool(update: {
16
20
  title?: string | null;
17
21
  name?: string | null;
18
22
  kind?: string | null;
19
23
  }, tools: ReadonlySet<string>, server?: string): string | undefined;
24
+ /** The tool of our MCP server a permission request names that `tools` does not hold, as the request names it: by any
25
+ * form ourTool reads, or Goose 1.59's title (`<server>: <tool, its underscores as spaces>`, a summary after ` · `), which
26
+ * is matched to a tool of `tools` with its underscores as spaces. Undefined when the request names no tool of our
27
+ * server, names one `tools` holds, or is of a kind with effects of its own (a native call, the gate's whatever its
28
+ * title). The agent could never call such a tool: our server does not list it, so the request is refused at once
29
+ * (harness.ts onPermission), never asked of a person. A title is the agent's text, so this only ever refuses. */
30
+ export declare function ungrantedTool(update: {
31
+ title?: string | null;
32
+ name?: string | null;
33
+ kind?: string | null;
34
+ }, tools: ReadonlySet<string>, server?: string): string | undefined;
20
35
  /** Whether a recipe's announces names our server by a prefix that joins it to a tool's name with one `_` or `-` (agy's
21
36
  * `mcp_agentrun_`): a join another server's own name may hold, so a server `agentrun_look` with a tool `up`
22
37
  * (`mcp_agentrun_look_up`) would spell our `look_up`. Not Goose's default `agentrun__`, nor a recipe that reads the
23
38
  * server from a field of its own (Cursor's). */
24
39
  export declare function joinsByOne(announces: AcpAnnounces | undefined): boolean;
25
- /** The name our MCP server is given to the agent under at one start: under a recipe whose prefix joins by one character
26
- * (joinsByOne), `ar` and 6 random hex digits, no `_` or `-`, which no server set up before the start can spell; under
27
- * any other, `agentrun`. As long as `agentrun`, no longer: each of our tools is named with it, under the agent's cap
28
- * (TOOL_NAME_CAP), so a tool fits as it would under `agentrun`. */
29
- export declare function mcpServerName(announces: AcpAnnounces | undefined): string;
40
+ /** Whether a recipe's announces read our server's name from a field of the agent's own (Cursor's
41
+ * `rawInput.providerIdentifier`): a second server named exactly `agentrun` (a workspace's or the owner's own MCP
42
+ * configuration) would say the same there. */
43
+ export declare function namesServer(announces: AcpAnnounces | undefined): boolean;
44
+ /** The name our MCP server is given to the agent under at one start: under a recipe that names it per start
45
+ * (namedPerStart), `ar` and 6 random hex digits, no `_` or `-`, which no server set up before the start can spell. It
46
+ * is the start's own, not secret from the agent: its model reads it in its tool list. Under any other (Goose's
47
+ * `agentrun__`, no tie, whose configuration is all ours and whose proxy offers its model our tools alone), `agentrun`.
48
+ * As long as `agentrun`, no longer: each of our tools is named with it, under the agent's cap (TOOL_NAME_CAP), so a
49
+ * tool fits as it would under `agentrun`. */
50
+ export declare function mcpServerName(announces: AcpAnnounces | undefined, tie?: string): string;
51
+ /** Whether a recipe gives our MCP server a name of each start's own (mcpServerName): one that declares the title tie
52
+ * (`tie`, quirks.permissionTie: the tie answers a request for one of our tools' calls without the host's gate, so
53
+ * another server must never pass for ours), whose prefix joins by one character (joinsByOne) or that reads the
54
+ * server's name from a field (namesServer). A title an earlier start's agent wrote names that start's server, never
55
+ * this one's. */
56
+ export declare function namedPerStart(announces: AcpAnnounces | undefined, tie?: string): boolean;
30
57
  /** The most characters a tool's name may hold where the agent names it (agy's, as the model APIs' tool names: 64). */
31
58
  export declare const TOOL_NAME_CAP = 64;
32
59
  /** Of `tools`, those whose name as the agent names them at this start (`announces` as announcesAt reads them: its prefix
@@ -36,10 +63,14 @@ export declare function namesTooLong(announces: AcpAnnounces | undefined, tools:
36
63
  /** The run's notice for the tools `label` (an agent naming ours `<prefix><tool>`) is not given at a start: those
37
64
  * namesTooLong names, which it could never call. */
38
65
  export declare function toolsLeftOut(label: string, prefix: string, tools: readonly string[]): string;
66
+ /** The run's notice for a permission request `label` (the agent) made for `tool`, a tool of our server it is not given
67
+ * (ungrantedTool): refused at once, no person asked. */
68
+ export declare function toolNotGranted(label: string, tool: string): string;
39
69
  /** The recipe's `announces` as one start reads them, our MCP server given to the agent as `server` (mcpServerName): its
40
- * prefix names that server (`mcp_agentrun_` reads `mcp_<server>_`). ANNOUNCES_PREFIX ends a prefix at our server's
70
+ * prefix names that server (`mcp_agentrun_` reads `mcp_<server>_`; no prefix, the default `agentrun__`, reads
71
+ * `<server>__`), and its `server` field must say that name (`named`). ANNOUNCES_PREFIX ends a prefix at our server's
41
72
  * name, so the last `agentrun` in it is that name. */
42
- export declare function announcesAt(announces: AcpAnnounces | undefined, server: string): AcpAnnounces | undefined;
73
+ export declare function announcesAt(announces: AcpAnnounces | undefined, server: string): StartAnnounces | undefined;
43
74
  /** Whether an input schema may name an argument `name`: in its `properties`, or in those of a schema it composes (allOf,
44
75
  * anyOf, oneOf, at any depth), or behind a `$ref` to its own `$defs` or `definitions`. A `$ref` it cannot read (another
45
76
  * document's, or a def it lacks) may, so it counts; a `$ref` that comes back to itself adds nothing. */
@@ -48,7 +79,8 @@ export declare function declaresProperty(schema: unknown, name: string): boolean
48
79
  * path of field names into the update (`_meta.goose.toolCall.toolName`, `rawInput.toolName`, `name`).
49
80
  * - `tool`: the tool's name. With `server`, our tool's own name; without, the name as the model calls it, our server's
50
81
  * prefix and the tool's (`prefix`, stripped).
51
- * - `server`: the MCP server's name, which must be ours (`agentrun`).
82
+ * - `server`: the MCP server's name, which must be ours: the name of each start's own (mcpServerName), never
83
+ * `agentrun`, which a second server could be named too.
52
84
  * - `prefix`: without `server`, what comes before our tool's name in `tool` (default `agentrun__`; agy's
53
85
  * `mcp_agentrun_`). It names our server (ANNOUNCES_PREFIX), so a name without it is never ours. One that joins our
54
86
  * server's name to the tool's with one `_` or `-` gives the server a name of each start's own (mcpServerName), which
@@ -64,6 +96,12 @@ export interface AcpAnnounces {
64
96
  readonly args?: string;
65
97
  readonly extras?: readonly string[];
66
98
  }
99
+ /** A recipe's announces as one start reads them (announcesAt): with `named`, the name its `server` field must say, our
100
+ * server's at that start (mcpServerName); without, `agentrun`. Never a recipe's own field (announcesProblems refuses
101
+ * any key but those of AcpAnnounces). */
102
+ export type StartAnnounces = AcpAnnounces & {
103
+ readonly named?: string;
104
+ };
67
105
  /** The prefix a recipe's announces.prefix may be: our server's name, with at most one word and a `_` or `-` before it,
68
106
  * and one or two `_` or `-` after it (`agentrun__`, `mcp_agentrun_`). */
69
107
  export declare const ANNOUNCES_PREFIX: RegExp;
@@ -82,7 +120,12 @@ export declare function announcedField(update: unknown, announces: AcpAnnounces
82
120
  /** The tool of ours an agent's update names in the field its recipe declares (`announces`): its name; null when the
83
121
  * field names a tool that is not ours (another server's, one without our prefix, or one of our server's that `tools`
84
122
  * does not list); undefined when the recipe declares no field or the update does not carry it. A title is never read. */
85
- export declare function announcedTool(update: unknown, announces: AcpAnnounces | undefined, tools: ReadonlySet<string>): string | null | undefined;
123
+ export declare function announcedTool(update: unknown, announces: StartAnnounces | undefined, tools: ReadonlySet<string>): string | null | undefined;
124
+ /** The server an agent's update names its call under, in the field its recipe declares (`announces.server`: Cursor's
125
+ * rawInput.providerIdentifier), when it is not ours (`named`): clipped to ANNOUNCED_FIELD_CHARS, for the host gate's
126
+ * question about the call, so the person can tell it is another server's, whatever its title says. Undefined when the
127
+ * recipe declares no such field, the update does not carry a name in it, or it names ours. */
128
+ export declare function otherServer(update: unknown, announces: StartAnnounces | undefined): string | undefined;
86
129
  /** An agent's update about one of its calls, as the adapter reads it. */
87
130
  export interface AcpCallUpdate {
88
131
  readonly toolCallId: string;
@@ -95,14 +138,14 @@ export interface AcpCallUpdate {
95
138
  * one with no arguments on a recipe whose field names calls, which waits for the update that names it. On a recipe
96
139
  * without the field, one reporting no input at all is kept as a call that names nothing (CallIds.add). `declared`: for
97
140
  * each tool, the recipe's extras its input schema declares (declaresProperty), matched with and without (addAnnounced). */
98
- export declare function announceCall(calls: CallIds, update: AcpCallUpdate, announces: AcpAnnounces | undefined, tools: ReadonlySet<string>, declared?: ReadonlyMap<string, ReadonlySet<string>>): void;
141
+ export declare function announceCall(calls: CallIds, update: AcpCallUpdate, announces: StartAnnounces | undefined, tools: ReadonlySet<string>, declared?: ReadonlyMap<string, ReadonlySet<string>>): void;
99
142
  /** A tool_call_update naming a call its tool_call left unnamed with no input (Cursor's MCP calls: a tool_call titled
100
143
  * "MCP: tool" with rawInput {}, then this update with rawInput {providerIdentifier, toolName, args}): kept as that
101
144
  * tool, under the id its tool_call already counted, by the recipe's field. Only a call announceCall held for its name
102
145
  * (CallIds.held): one whose tool_call reported input, or named a tool, is never named later, so a native read whose
103
146
  * update echoes the model's arguments stays the agent's own. The tool_call's kind was checked before it was held;
104
147
  * the update's is checked here: a shell renamed by a later update is never ours. */
105
- export declare function nameCall(calls: CallIds, update: AcpCallUpdate, announces: AcpAnnounces | undefined, tools: ReadonlySet<string>, declared?: ReadonlyMap<string, ReadonlySet<string>>): void;
148
+ export declare function nameCall(calls: CallIds, update: AcpCallUpdate, announces: StartAnnounces | undefined, tools: ReadonlySet<string>, declared?: ReadonlyMap<string, ReadonlySet<string>>): void;
106
149
  /** How long an MCP call that matches an announcement only without an extra (addAnnounced) holds for its own (take): an
107
150
  * MCP call can reach MCP a little before the agent's announcement of it, and in that while the other's may be the only
108
151
  * one there. */
@@ -136,7 +179,8 @@ export declare class CallIds {
136
179
  * which it is kept too; the first MCP call either matches takes it, and it is gone from both. A call already waiting
137
180
  * is handed it only where it is the call's own first key, its tool and its whole arguments. One that matches it only
138
181
  * without the extra may be another call's, whose own announcement is on its way, and one naming no tool or reporting
139
- * no input may come second to the call's own ended one, so for those the call tries again as take says (wake). */
182
+ * no input may come second to the call's own ended one, or to a live guess under its first key (an `also` form, its
183
+ * own MCP call maybe on its way), so for those the call tries again as take says (wake). */
140
184
  add(id: string, tool: string | undefined, input: unknown, also?: unknown): void;
141
185
  /** `id` out of every list it is kept in (keyOf), waiting for its MCP call no more. */
142
186
  private unlist;
package/dist/calls.js CHANGED
@@ -12,8 +12,11 @@
12
12
  // and how many such requests came before it in the drive. Never from the agent's tool call id, which a new agent
13
13
  // session (no load) mints afresh.
14
14
  import { createHash, randomBytes } from "node:crypto";
15
- /** The MCP server's name, as the agent is given it (under agy's recipe, the start of it: mcpServerName). */
15
+ /** Our MCP server's name, as the agent is given it under a recipe without the title tie (Goose's); under one with it,
16
+ * or whose announces could take another server's call as ours, the start's own name instead (mcpServerName). */
16
17
  export const MCP_SERVER = "agentrun";
18
+ /** The pattern of a start's own name for our MCP server (mcpServerName): `ar` and 6 hex digits. */
19
+ export const START_SERVER = "ar[0-9a-f]{6}";
17
20
  const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18
21
  /** JSON text of `value` with every object's keys sorted: two argument objects that say the same are the same text. */
19
22
  export function canonical(value) {
@@ -26,13 +29,14 @@ export function canonical(value) {
26
29
  /** 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
27
30
  * our tools, whatever its title says. */
28
31
  export const NATIVE_EFFECT_KINDS = new Set(["execute", "edit", "delete", "move", "fetch"]);
29
- /** The host tool a permission request's title or name gives, by a name for our MCP server's tools (`agentrun__<tool>`),
30
- * Cursor's own title for one (`agentrun-<tool>: <tool>`), or agy's (Antigravity's) name and title for one
31
- * (`mcp_agentrun_<tool>`, titled `Run mcp_agentrun_<tool>`, the whole text), when it is one of `tools` and its kind is
32
+ /** The host tool a permission request's title or name gives, by a name for our MCP server's tools (`<server>__<tool>`),
33
+ * Cursor's own title for one (`<server>-<tool>: <tool>`), or agy's (Antigravity's) name and title for one
34
+ * (`mcp_<server>_<tool>`, titled `Run mcp_<server>_<tool>`, the whole text), when it is one of `tools` and its kind is
32
35
  * not one with effects of its own. Read for the title tie alone (quirks.permissionTie: Cursor's and agy's), and only
33
36
  * beside the call's announcement: the title is the agent's text, so a request is tied only when it is for a call the
34
37
  * recipe's announces field named as the same tool (CallIds.announced). Nothing else reads a title. `server` is the name
35
- * our MCP server was given to the agent under at this start (mcpServerName): agy's name and title carry it. */
38
+ * our MCP server was given to the agent under at this start (mcpServerName), which each of these forms carries: under
39
+ * the tie, the start's own. */
36
40
  export function ourTool(update, tools, server = MCP_SERVER) {
37
41
  if (typeof update.kind === "string" && NATIVE_EFFECT_KINDS.has(update.kind))
38
42
  return undefined;
@@ -54,6 +58,36 @@ export function ourTool(update, tools, server = MCP_SERVER) {
54
58
  }
55
59
  return candidates.find((name) => tools.has(name));
56
60
  }
61
+ /** The tool of our MCP server a permission request names that `tools` does not hold, as the request names it: by any
62
+ * form ourTool reads, or Goose 1.59's title (`<server>: <tool, its underscores as spaces>`, a summary after ` · `), which
63
+ * is matched to a tool of `tools` with its underscores as spaces. Undefined when the request names no tool of our
64
+ * server, names one `tools` holds, or is of a kind with effects of its own (a native call, the gate's whatever its
65
+ * title). The agent could never call such a tool: our server does not list it, so the request is refused at once
66
+ * (harness.ts onPermission), never asked of a person. A title is the agent's text, so this only ever refuses. */
67
+ export function ungrantedTool(update, tools, server = MCP_SERVER) {
68
+ if (typeof update.kind === "string" && NATIVE_EFFECT_KINDS.has(update.kind))
69
+ return undefined;
70
+ const named = [];
71
+ const spaced = [];
72
+ for (const said of [update.name, update.title]) {
73
+ if (typeof said !== "string")
74
+ continue;
75
+ for (const form of [new RegExp(`^${server}__(.+)$`), new RegExp(`^${server}-[^:]*: (.+)$`), new RegExp(`^(?:Run )?mcp_${server}_(.+)$`)]) {
76
+ const hit = form.exec(said);
77
+ if (hit)
78
+ named.push(hit[1].trim());
79
+ }
80
+ const goose = new RegExp(`^${server}: (.+?)(?: · .*)?$`).exec(said);
81
+ if (goose)
82
+ spaced.push(goose[1].trim());
83
+ }
84
+ if (named.some((name) => tools.has(name)))
85
+ return undefined;
86
+ const given = new Set([...tools].map((tool) => tool.replace(/_/g, " ")));
87
+ if (spaced.some((name) => given.has(name)))
88
+ return undefined;
89
+ return named[0] ?? spaced[0];
90
+ }
57
91
  /** Whether a recipe's announces names our server by a prefix that joins it to a tool's name with one `_` or `-` (agy's
58
92
  * `mcp_agentrun_`): a join another server's own name may hold, so a server `agentrun_look` with a tool `up`
59
93
  * (`mcp_agentrun_look_up`) would spell our `look_up`. Not Goose's default `agentrun__`, nor a recipe that reads the
@@ -61,12 +95,28 @@ export function ourTool(update, tools, server = MCP_SERVER) {
61
95
  export function joinsByOne(announces) {
62
96
  return announces !== undefined && announces.server === undefined && announces.prefix !== undefined && new RegExp(`${MCP_SERVER}[_-]$`).test(announces.prefix);
63
97
  }
64
- /** The name our MCP server is given to the agent under at one start: under a recipe whose prefix joins by one character
65
- * (joinsByOne), `ar` and 6 random hex digits, no `_` or `-`, which no server set up before the start can spell; under
66
- * any other, `agentrun`. As long as `agentrun`, no longer: each of our tools is named with it, under the agent's cap
67
- * (TOOL_NAME_CAP), so a tool fits as it would under `agentrun`. */
68
- export function mcpServerName(announces) {
69
- return joinsByOne(announces) ? `ar${randomBytes(3).toString("hex")}` : MCP_SERVER;
98
+ /** Whether a recipe's announces read our server's name from a field of the agent's own (Cursor's
99
+ * `rawInput.providerIdentifier`): a second server named exactly `agentrun` (a workspace's or the owner's own MCP
100
+ * configuration) would say the same there. */
101
+ export function namesServer(announces) {
102
+ return announces?.server !== undefined;
103
+ }
104
+ /** The name our MCP server is given to the agent under at one start: under a recipe that names it per start
105
+ * (namedPerStart), `ar` and 6 random hex digits, no `_` or `-`, which no server set up before the start can spell. It
106
+ * is the start's own, not secret from the agent: its model reads it in its tool list. Under any other (Goose's
107
+ * `agentrun__`, no tie, whose configuration is all ours and whose proxy offers its model our tools alone), `agentrun`.
108
+ * As long as `agentrun`, no longer: each of our tools is named with it, under the agent's cap (TOOL_NAME_CAP), so a
109
+ * tool fits as it would under `agentrun`. */
110
+ export function mcpServerName(announces, tie) {
111
+ return namedPerStart(announces, tie) ? `ar${randomBytes(3).toString("hex")}` : MCP_SERVER;
112
+ }
113
+ /** Whether a recipe gives our MCP server a name of each start's own (mcpServerName): one that declares the title tie
114
+ * (`tie`, quirks.permissionTie: the tie answers a request for one of our tools' calls without the host's gate, so
115
+ * another server must never pass for ours), whose prefix joins by one character (joinsByOne) or that reads the
116
+ * server's name from a field (namesServer). A title an earlier start's agent wrote names that start's server, never
117
+ * this one's. */
118
+ export function namedPerStart(announces, tie) {
119
+ return tie === "title" || joinsByOne(announces) || namesServer(announces);
70
120
  }
71
121
  /** The most characters a tool's name may hold where the agent names it (agy's, as the model APIs' tool names: 64). */
72
122
  export const TOOL_NAME_CAP = 64;
@@ -85,14 +135,23 @@ export function toolsLeftOut(label, prefix, tools) {
85
135
  const one = tools.length === 1;
86
136
  return `${label} names each of our tools ${prefix}<tool>, at most ${TOOL_NAME_CAP} characters in all, so a tool's own name may be at most ${TOOL_NAME_CAP - prefix.length}; ${tools.map((tool) => JSON.stringify(tool)).join(", ")} ${one ? "is" : "are"} longer, so ${one ? "it is" : "they are"} left out of the tools it is given at this start`;
87
137
  }
138
+ /** The run's notice for a permission request `label` (the agent) made for `tool`, a tool of our server it is not given
139
+ * (ungrantedTool): refused at once, no person asked. */
140
+ export function toolNotGranted(label, tool) {
141
+ return `tool ${JSON.stringify(tool.slice(0, 80))} isn't granted to this agent: ${label} asked to run it and was refused at once, with no person asked, and the run goes on`;
142
+ }
88
143
  /** The recipe's `announces` as one start reads them, our MCP server given to the agent as `server` (mcpServerName): its
89
- * prefix names that server (`mcp_agentrun_` reads `mcp_<server>_`). ANNOUNCES_PREFIX ends a prefix at our server's
144
+ * prefix names that server (`mcp_agentrun_` reads `mcp_<server>_`; no prefix, the default `agentrun__`, reads
145
+ * `<server>__`), and its `server` field must say that name (`named`). ANNOUNCES_PREFIX ends a prefix at our server's
90
146
  * name, so the last `agentrun` in it is that name. */
91
147
  export function announcesAt(announces, server) {
92
- if (!announces || announces.prefix === undefined || server === MCP_SERVER)
148
+ if (!announces || server === MCP_SERVER)
93
149
  return announces;
94
- const at = announces.prefix.lastIndexOf(MCP_SERVER);
95
- return at < 0 ? announces : { ...announces, prefix: `${announces.prefix.slice(0, at)}${server}${announces.prefix.slice(at + MCP_SERVER.length)}` };
150
+ if (announces.server !== undefined)
151
+ return { ...announces, named: server };
152
+ const prefix = announces.prefix ?? `${MCP_SERVER}__`;
153
+ const at = prefix.lastIndexOf(MCP_SERVER);
154
+ return at < 0 ? announces : { ...announces, prefix: `${prefix.slice(0, at)}${server}${prefix.slice(at + MCP_SERVER.length)}` };
96
155
  }
97
156
  /** Whether an input schema may name an argument `name`: in its `properties`, or in those of a schema it composes (allOf,
98
157
  * anyOf, oneOf, at any depth), or behind a `$ref` to its own `$defs` or `definitions`. A `$ref` it cannot read (another
@@ -160,7 +219,7 @@ export function announcedTool(update, announces, tools) {
160
219
  return undefined;
161
220
  let tool = said;
162
221
  if (announces.server !== undefined) {
163
- if (at(update, announces.server) !== MCP_SERVER)
222
+ if (at(update, announces.server) !== (announces.named ?? MCP_SERVER))
164
223
  return null;
165
224
  }
166
225
  else {
@@ -171,6 +230,16 @@ export function announcedTool(update, announces, tools) {
171
230
  }
172
231
  return tools.has(tool) ? tool : null;
173
232
  }
233
+ /** The server an agent's update names its call under, in the field its recipe declares (`announces.server`: Cursor's
234
+ * rawInput.providerIdentifier), when it is not ours (`named`): clipped to ANNOUNCED_FIELD_CHARS, for the host gate's
235
+ * question about the call, so the person can tell it is another server's, whatever its title says. Undefined when the
236
+ * recipe declares no such field, the update does not carry a name in it, or it names ours. */
237
+ export function otherServer(update, announces) {
238
+ if (announces?.server === undefined)
239
+ return undefined;
240
+ const said = at(update, announces.server);
241
+ return typeof said === "string" && said !== "" && said !== (announces.named ?? MCP_SERVER) ? said.slice(0, ANNOUNCED_FIELD_CHARS) : undefined;
242
+ }
174
243
  /** The arguments an update reports for its call: at the recipe's `announces.args`, or its rawInput, without the
175
244
  * recipe's `extras` that hold text (agy's toolSummary), but for those the tool's schema declares (`kept`). */
176
245
  function announcedArgs(update, announces, kept) {
@@ -274,7 +343,8 @@ export class CallIds {
274
343
  * which it is kept too; the first MCP call either matches takes it, and it is gone from both. A call already waiting
275
344
  * is handed it only where it is the call's own first key, its tool and its whole arguments. One that matches it only
276
345
  * without the extra may be another call's, whose own announcement is on its way, and one naming no tool or reporting
277
- * no input may come second to the call's own ended one, so for those the call tries again as take says (wake). */
346
+ * no input may come second to the call's own ended one, or to a live guess under its first key (an `also` form, its
347
+ * own MCP call maybe on its way), so for those the call tries again as take says (wake). */
278
348
  add(id, tool, input, also) {
279
349
  if (this.used.has(id))
280
350
  return;
@@ -370,7 +440,9 @@ export class CallIds {
370
440
  // announcement whose own first key is this one counts as its own: one kept here only read without an extra
371
441
  // (addAnnounced) is a guess, and a live one under a later key comes first, as before. So a retry announced with
372
442
  // less than its call's whole arguments (no tool, or no input), after a call with these arguments ended, takes the
373
- // ended one's id after the hold: the same tool with the same arguments, the order the two came in lost. Beyond this: an
443
+ // ended one's id after the hold: the same tool with the same arguments, the order the two came in lost. The retry's
444
+ // own announcement then stays live, under its key with no tool or no input, until its call settles, and a later MCP
445
+ // call of the same tool with the same arguments may take its id meanwhile. Beyond this: an
374
446
  // announcement that comes more than the grace after its own MCP call (that call takes the other's), and a call torn
375
447
  // until the wait is over, more than ms behind the other's MCP call (it takes the oldest, which may be the other's);
376
448
  // in both the other's MCP call falls back once its wait is over. Two calls with the same arguments, one ended, can
@@ -1,3 +1,4 @@
1
+ import { START_SERVER } from "./calls.js";
1
2
  import { ACP_CODES } from "./facts.js";
2
3
  import { CURSOR_PIN } from "./pinned-binary.js";
3
4
  /** The command that installs the pinned Cursor CLI into an AgentRun server's data (`<data>/harnesses/cursor`). */
@@ -26,6 +27,8 @@ export function cursorCard(limits = CURSOR_LIMITS) {
26
27
  `If your Cursor team administrator turned headless CLI use off, its runs are refused (${CURSOR_CODES.headlessDisabled}).`,
27
28
  ].join(" ");
28
29
  }
30
+ /** A title Cursor gives one of our tools' calls, our server under its start's own name: the tool's name after it. */
31
+ const HOST_TITLE = new RegExp(`^${START_SERVER}(?:-[^:]*)?: (.+)$`);
29
32
  export const cursorFacts = Object.freeze({
30
33
  id: "cursor",
31
34
  label: "Cursor",
@@ -47,8 +50,9 @@ export const cursorFacts = Object.freeze({
47
50
  normalizeModel: (model) => model,
48
51
  // Installed by its owner, never on first use: the archive the pin names, its digests checked (serve's harness-archive.ts).
49
52
  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,
53
+ // Its MCP calls are titled `<server>-<tool>: <tool>` (its permission asks) or `<server>: <tool>` (its updates), our
54
+ // server under its start's own name (calls.ts mcpServerName): one under any other is another server's, and keeps its words.
55
+ hostName: (given) => HOST_TITLE.exec(given)?.[1]?.trim() ?? given,
52
56
  policy: () => {
53
57
  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
58
  },
package/dist/harness.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { GateAnswer, GateCall } from "@parcha/agentrun-kernel";
2
2
  import type { DriveContext, HostTool, SessionState } from "@parcha/agentrun-kernel/kernel";
3
+ import { type ResultBudget } from "@parcha/agentrun-kernel/process";
3
4
  import type { ParentWatch } from "@parcha/agentrun-kernel/host";
4
5
  import { type AcpRecipe } from "./recipe.js";
5
6
  import type { ConfineChild } from "./host/child.js";
@@ -21,6 +22,13 @@ export declare const REASK_LIMIT = 3;
21
22
  export declare const TOOLS_STREAM = "acp.tools";
22
23
  /** The model chosen for the agent's session (recipe.model, as the agent lists it), one record each time one is chosen. */
23
24
  export declare const MODEL_STREAM = "acp.model";
25
+ /** Instructions a prompt carried ahead of its words (an agent with no system prompt), one record each time, written only
26
+ * with a copy of the agent's history taken after it answered that prompt: `sessionId` the session, `text` the recipe's
27
+ * part, `whole` when the session's own came too (its first prompt). A loaded session is given the recipe's again when
28
+ * they differ from the last of its records (a recipe that gained or changed them since), and all of them when it was
29
+ * opened to get them in a prompt (SESSION_STREAM `prompted`) and has no `whole` record: a crash before the copy
30
+ * leaves a history without them. */
31
+ export declare const INSTRUCTIONS_STREAM = "acp.instructions";
24
32
  /** How long a session waits for the agent to start and answer initialize, or open its session. */
25
33
  export declare const START_MS = 60000;
26
34
  /** How long an MCP call waits for the agent's tool_call that announces it. */
@@ -49,10 +57,14 @@ export interface AcpHarnessOptions {
49
57
  env?: Readonly<Record<string, string | undefined>>;
50
58
  /** The host's gate (SessionIO.gate). Absent: every call runs. */
51
59
  gate?: (call: GateCall) => Promise<GateAnswer>;
60
+ /** What the session's model can take of one tool result (its context window): the tool bridge holds every result to
61
+ * it (boundResult's budget). Absent: the host's bound alone (HOST_RESULT_MAX_CHARS). */
62
+ resultBudget?: ResultBudget;
52
63
  /** Proxy billing: what each agent process gets to reach the host's model proxy (its variables), closed with it.
53
64
  * `halt` ends the drive the process serves. */
54
65
  proxy?: (drive: {
55
66
  halt(reason: unknown): void;
67
+ server: string;
56
68
  }) => Promise<{
57
69
  env: Record<string, string>;
58
70
  close(): Promise<void>;
package/dist/harness.js CHANGED
@@ -18,8 +18,8 @@ import { chmodSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
18
18
  import { dirname, isAbsolute, join, normalize } from "node:path";
19
19
  import { fileURLToPath } from "node:url";
20
20
  import { PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
21
- import { askGate, journalRecords, NativeJournal, openTurn, placeSubmissions, recoveryNote, resumeUnstartedCalls, toolBridge, toolKey, transcriptOf } from "@parcha/agentrun-kernel/process";
22
- import { announceCall, announcedField, announcesAt, CallIds, declaresProperty, joinsByOne, mcpServerName, nameCall, namesTooLong, ourTool, permissionCallId, toolsLeftOut } from "./calls.js";
21
+ import { askGate, journalRecords, journalTurn, NativeJournal, openTurn, placeSubmissions, recoveryNote, resumeUnstartedCalls, toolBridge, toolKey, transcriptOf } from "@parcha/agentrun-kernel/process";
22
+ import { announceCall, announcedField, announcesAt, CallIds, declaresProperty, joinsByOne, mcpServerName, MCP_SERVER, namedPerStart, nameCall, namesTooLong, otherServer, ourTool, permissionCallId, toolNotGranted, toolsLeftOut, ungrantedTool } from "./calls.js";
23
23
  import { ACP_CODES } from "./facts.js";
24
24
  import { allowFileText, homePath } from "./recipe.js";
25
25
  import { restoreState, STATE_STREAM, StateMirror } from "./state.js";
@@ -44,6 +44,13 @@ export const REASK_LIMIT = 3;
44
44
  export const TOOLS_STREAM = "acp.tools";
45
45
  /** The model chosen for the agent's session (recipe.model, as the agent lists it), one record each time one is chosen. */
46
46
  export const MODEL_STREAM = "acp.model";
47
+ /** Instructions a prompt carried ahead of its words (an agent with no system prompt), one record each time, written only
48
+ * with a copy of the agent's history taken after it answered that prompt: `sessionId` the session, `text` the recipe's
49
+ * part, `whole` when the session's own came too (its first prompt). A loaded session is given the recipe's again when
50
+ * they differ from the last of its records (a recipe that gained or changed them since), and all of them when it was
51
+ * opened to get them in a prompt (SESSION_STREAM `prompted`) and has no `whole` record: a crash before the copy
52
+ * leaves a history without them. */
53
+ export const INSTRUCTIONS_STREAM = "acp.instructions";
47
54
  /** How long a session waits for the agent to start and answer initialize, or open its session. */
48
55
  export const START_MS = 60_000;
49
56
  /** How long an MCP call waits for the agent's tool_call that announces it. */
@@ -168,7 +175,7 @@ export function acpHarness(options, control) {
168
175
  const offered = options.tools.filter((tool) => !tool.deferred);
169
176
  /** Those the agent names past its cap under our server's name (namesTooLong), which it could never call: never listed,
170
177
  * and each start says so (toolsLeftOut). The name's length is the same at every start (mcpServerName). */
171
- const capped = joinsByOne(recipe.announces) ? namesTooLong(announcesAt(recipe.announces, mcpServerName(recipe.announces)), offered.map((tool) => tool.name)) : [];
178
+ const capped = joinsByOne(recipe.announces) ? namesTooLong(announcesAt(recipe.announces, mcpServerName(recipe.announces, recipe.quirks?.permissionTie)), offered.map((tool) => tool.name)) : [];
172
179
  const listed = offered.filter((tool) => !capped.includes(tool.name));
173
180
  const names = new Set(listed.map((tool) => tool.name));
174
181
  /** For each tool, the recipe's announces.extras its own input schema declares: kept in its arguments (announceCall). */
@@ -210,17 +217,19 @@ export function acpHarness(options, control) {
210
217
  /** Why an agent that ended did: its last words on stderr, else the error's, else that it said nothing. On a hushed run,
211
218
  * its exit status alone. */
212
219
  const whyEnded = (agent, error) => hushed ? `${agent.ended() ?? "its end is not known yet"}; what it printed is kept nowhere on this run` : lastWords(agent.stderrTail()) || lastWords(message(error)) || "it said nothing";
213
- /** Mirror the agent's session store into `journal` (the caller flushes). A failure is said and never thrown: the next
214
- * point takes the mirror again, and a turn's outcome is never lost to it. */
220
+ /** Mirror the agent's session store into `journal` (the caller flushes); true once taken. A failure is said and never
221
+ * thrown: the next point takes the mirror again, and a turn's outcome is never lost to it. */
215
222
  const mirrorInto = (rt, journal) => {
216
223
  // A HOME removed with its process holds nothing to take: read now, it would say the agent deleted its whole store.
217
224
  if (rt.wiped)
218
- return;
225
+ return false;
219
226
  try {
220
227
  rt.mirror.take(journal);
228
+ return true;
221
229
  }
222
230
  catch (error) {
223
231
  log("acp: the mirror of the agent's session store failed; the next point takes it again", { error: said(error) });
232
+ return false;
224
233
  }
225
234
  };
226
235
  /** The open turn's limit of tool calls, counted from the records: past it, the turn is cancelled with a named reason. */
@@ -240,6 +249,13 @@ export function acpHarness(options, control) {
240
249
  }
241
250
  return turn?.limitHit ?? `${ACP_CODES.toolCallLimit}: the plan's limit of ${plan.maxToolCalls} tool calls is reached`;
242
251
  };
252
+ /** A call an update names under another server than ours, by the recipe's server field (otherServer): kept for the
253
+ * host gate's question about it (permissionGateCall's `server`). A later update may name it again. */
254
+ const noteServer = (rt, update) => {
255
+ const other = otherServer(update, rt.announces);
256
+ if (other)
257
+ rt.others.set(update.toolCallId, other);
258
+ };
243
259
  /** Debug only (serve's AGENTRUN_LOG=debug), on a recipe that declares announces: a call the agent announced, by its
244
260
  * ids and names, never its input or the agent's text. The word at the recipe's field is quoted only when it names a
245
261
  * tool of ours: on Cursor's recipe it sits inside the call's input, so another call's is "native" (null: none).
@@ -273,6 +289,7 @@ export function acpHarness(options, control) {
273
289
  countCall(rt, cur, update.toolCallId);
274
290
  // Kept for the MCP call it may be, named by the recipe's announces field, never by its title (announceCall).
275
291
  announceCall(rt.calls, update, rt.announces, names, declared);
292
+ noteServer(rt, update);
276
293
  logAnnounced(rt, update);
277
294
  return;
278
295
  }
@@ -282,6 +299,7 @@ export function acpHarness(options, control) {
282
299
  // A call the agent named only after announcing it with no input (Cursor's): by the recipe's field (nameCall).
283
300
  const held = rt.calls.held(update.toolCallId);
284
301
  nameCall(rt.calls, update, rt.announces, names, declared);
302
+ noteServer(rt, update);
285
303
  if (held && !rt.calls.held(update.toolCallId))
286
304
  logAnnounced(rt, update);
287
305
  // Its status is the agent's word only: what it changes is the mirror of the agent's session store.
@@ -302,8 +320,10 @@ export function acpHarness(options, control) {
302
320
  };
303
321
  /** The gate's call for a permission request of the agent's own tool: the same when the agent asks and when a resume
304
322
  * asks about it again (settlePermissions), so both reach the one approval. Under its journal id (`callId`); its args
305
- * carry the toolCallId the agent first asked under, so a host (harness-check) ties the question to the request. */
306
- const permissionGateCall = (callId, toolCallId, kind, title, input) => ({ callId, tool: `acp_${kind.replace(/[^A-Za-z0-9_]/g, "_")}`, args: { title, kind, input, ...(toolCallId ? { toolCallId } : {}) } });
323
+ * carry the toolCallId the agent first asked under, so a host (harness-check) ties the question to the request, and
324
+ * the server another than ours an update named the call under (`server`, otherServer), so the person can tell a call
325
+ * titled as one of our tools (`agentrun-look_up: look_up`) is that server's. */
326
+ const permissionGateCall = (callId, toolCallId, kind, title, input, server) => ({ callId, tool: `acp_${kind.replace(/[^A-Za-z0-9_]/g, "_")}`, args: { title, kind, input, ...(toolCallId ? { toolCallId } : {}), ...(server ? { server } : {}) } });
307
327
  /** The recovery note's line for a settled answer: the request as the agent asked it (its kind, title and input, so an
308
328
  * agent started without session/load can ask for the same call) and what the person said. */
309
329
  const answerLine = (asked, answer) => {
@@ -311,6 +331,8 @@ export function acpHarness(options, control) {
311
331
  const input = asked?.input === undefined || asked.input === null ? "" : JSON.stringify(asked.input);
312
332
  const shown = input ? ` Its input: ${clip(input, 1500)}${input.length > 1500 ? " (cut here: ask with the whole input you first sent)" : ""}.` : "";
313
333
  const named = `${kind} ${JSON.stringify(clip(asked?.title ?? kind, 300))}.${shown}`;
334
+ if (answer.ungranted)
335
+ return `- ${named} Refused, with no person asked: ${clip(answer.words ?? "", 500)}.`;
314
336
  return answer.answer === "deny"
315
337
  ? `- ${named} The person refused it.${answer.words ? ` Their words: ${clip(answer.words, 500).replace(/\n/g, " ")}` : ""}`
316
338
  : `- ${named} The person allowed it once. Ask for it again exactly as before (the same kind, title and input) and it runs; any other request waits for the person again.`;
@@ -337,7 +359,24 @@ export function acpHarness(options, control) {
337
359
  for (const request of waiting) {
338
360
  const kind = request.kind ?? "other";
339
361
  const title = request.title ?? kind;
340
- const refused = await askGate(gate, permissionGateCall(request.callId, request.toolCallId, kind, title, request.input ?? null), ctx.signal);
362
+ // A request for a tool of ours this start does not give the agent (ungrantedTool), left waiting by a run that
363
+ // parked on it: refused here as onPermission refuses a new one, never asked of a person. Settled, so the agent's
364
+ // ask again takes the deny. Its title names our server as the start that asked was given it (`ours`, recorded
365
+ // with it): under a recipe that names the server per start (Cursor's, agy's) a request recorded without that name
366
+ // is the gate's, as its title cannot be tied to a server of ours.
367
+ const ours = request.ours ?? (namedPerStart(recipe.announces, recipe.quirks?.permissionTie) ? undefined : MCP_SERVER);
368
+ const ungranted = ours === undefined ? undefined : ungrantedTool({ title, kind }, names, ours);
369
+ if (ungranted !== undefined) {
370
+ const words = toolNotGranted(recipe.label ?? recipe.id, ungranted);
371
+ const answer = { type: "answered", callId: request.callId, answer: "deny", words, settled: true, turn: turnId, ungranted: true };
372
+ journal.append(PERMISSION_STREAM, answer);
373
+ await journal.flush();
374
+ ctx.live({ type: "notice", text: words });
375
+ said.push(answerLine(request, answer));
376
+ records.push(answer);
377
+ continue;
378
+ }
379
+ const refused = await askGate(gate, permissionGateCall(request.callId, request.toolCallId, kind, title, request.input ?? null, request.server), ctx.signal);
341
380
  const answer = { type: "answered", callId: request.callId, answer: refused ? "deny" : "allow", ...(refused?.deny ? { words: refused.deny } : {}), settled: true, turn: turnId };
342
381
  journal.append(PERMISSION_STREAM, answer);
343
382
  await journal.flush();
@@ -380,10 +419,19 @@ export function acpHarness(options, control) {
380
419
  if (mine && rt.calls.announced(request.toolCall.toolCallId) === mine)
381
420
  return choose("allow_once");
382
421
  }
422
+ // A tool of our server the agent is not given (ungrantedTool): no grant to ask a person for, so it is refused at
423
+ // once, before anything is journaled (a resume has nothing to ask again), and the run is told which tool.
424
+ const ungranted = ungrantedTool(request.toolCall, names, rt.server);
425
+ if (ungranted !== undefined) {
426
+ log("acp: refused a permission request for a tool the agent is not given", { toolCallId: request.toolCall.toolCallId, tool: ungranted.slice(0, 80) });
427
+ cur.ctx.live({ type: "notice", text: toolNotGranted(recipe.label ?? recipe.id, ungranted) });
428
+ return choose("reject_once");
429
+ }
383
430
  const call = request.toolCall;
384
431
  const kind = typeof call.kind === "string" && call.kind ? call.kind : "other";
385
432
  const title = typeof call.title === "string" ? call.title : kind;
386
433
  const input = call.rawInput ?? null;
434
+ const server = rt.others.get(call.toolCallId);
387
435
  // The request's id is the open turn's: the turn, what it asks, and which of the turn's requests that ask the same it
388
436
  // is. Of the ids this process has not taken and no agent was handed an answer for (`given`: an allow-once is used
389
437
  // once), it takes the first one answered (a resume took the answer; the agent asks again for it), else the first
@@ -421,7 +469,7 @@ export function acpHarness(options, control) {
421
469
  const unasked = all.find((r) => r?.type === "answered" && r.settled && r.turn === turnId && r.answer === "allow" && !givenIds.has(r.callId));
422
470
  if (unasked)
423
471
  cur.journal.append(PERMISSION_STREAM, { type: "reasked", callId, turn: turnId, instead: unasked.callId });
424
- cur.journal.append(PERMISSION_STREAM, { type: "asked", callId, toolCallId: call.toolCallId, title, kind, input });
472
+ cur.journal.append(PERMISSION_STREAM, { type: "asked", callId, toolCallId: call.toolCallId, title, kind, input, ours: rt.server, ...(server ? { server } : {}) });
425
473
  await cur.journal.flush();
426
474
  }
427
475
  else if (options.gate) {
@@ -433,9 +481,10 @@ export function acpHarness(options, control) {
433
481
  let refused;
434
482
  if (options.gate) {
435
483
  // The toolCallId the request was first asked under, as the journal has it: the same question a resume asks.
436
- const askedAs = records.find((r) => r.type === "asked")?.toolCallId ?? call.toolCallId;
484
+ const askedRecord = records.find((r) => r.type === "asked");
485
+ const askedAs = askedRecord?.toolCallId ?? call.toolCallId;
437
486
  try {
438
- refused = await askGate(options.gate, permissionGateCall(callId, askedAs, kind, title, input), AbortSignal.any([cur.signal, connection, turn.stop.signal]));
487
+ refused = await askGate(options.gate, permissionGateCall(callId, askedAs, kind, title, input, askedRecord?.server ?? server), AbortSignal.any([cur.signal, connection, turn.stop.signal]));
439
488
  }
440
489
  catch {
441
490
  // Parked, and the session let go (or the turn was cancelled): nothing is answered, nothing recorded.
@@ -513,7 +562,7 @@ export function acpHarness(options, control) {
513
562
  if (absent.length)
514
563
  throw new Error(`${ACP_CODES.keyMissing}: ${recipe.label ?? recipe.id} runs on ${absent.join(" and ")}, which this host does not hold; the agent was not started`);
515
564
  // A tool of ours the agent would name past its cap is not listed (capped); the run is told which, and goes on.
516
- const serverName = mcpServerName(recipe.announces);
565
+ const serverName = mcpServerName(recipe.announces, recipe.quirks?.permissionTie);
517
566
  if (capped.length) {
518
567
  const words = toolsLeftOut(recipe.label ?? recipe.id, announcesAt(recipe.announces, serverName)?.prefix ?? "", capped);
519
568
  log("acp: tools left out of the agent's listing, named past its cap", { tools: capped });
@@ -531,7 +580,7 @@ export function acpHarness(options, control) {
531
580
  const own = new Set();
532
581
  // The recipe's allowFile (Goose's permission file): the tools this start lists, in the agent's own form, and nothing
533
582
  // else, so the agent runs them unasked and our gate asks at the MCP call.
534
- const allowed = recipe.allowFile ? { [recipe.allowFile.path]: allowFileText(recipe.allowFile.form, listed.map((tool) => tool.name)) } : {};
583
+ const allowed = recipe.allowFile ? { [recipe.allowFile.path]: allowFileText(recipe.allowFile.form, listed.map((tool) => tool.name), serverName) } : {};
535
584
  for (const [path, text] of [...Object.entries(recipe.files ?? {}), ...Object.entries(allowed)]) {
536
585
  const clean = homePath(path);
537
586
  if (!clean)
@@ -554,7 +603,7 @@ export function acpHarness(options, control) {
554
603
  const stopped = new AbortController();
555
604
  const signal = AbortSignal.any([ctx.signal, stopped.signal]);
556
605
  const key = randomBytes(32).toString("base64url");
557
- const rt = { ctx, loading: false, fresh: true, wiped: false, firstBlocks: [], calls: new CallIds(), server: serverName, announces: announcesAt(recipe.announces, serverName), counted: new Set(), claimed: new Set(), ownIds: new Set(), sessionId: "", mirror: new StateMirror(home, (recipe.state ?? []).map((p) => homePath(p)), own, records, log, (words) => (rt.current?.ctx ?? ctx).live({ type: "notice", text: words })) };
606
+ const rt = { ctx, loading: false, fresh: true, wiped: false, firstBlocks: [], calls: new CallIds(), others: new Map(), server: serverName, announces: announcesAt(recipe.announces, serverName), counted: new Set(), claimed: new Set(), ownIds: new Set(), sessionId: "", mirror: new StateMirror(home, (recipe.state ?? []).map((p) => homePath(p)), own, records, log, (words) => (rt.current?.ctx ?? ctx).live({ type: "notice", text: words })) };
558
607
  const mcp = await startMcpServer({ tools: listed.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })), key, log, call: (name, args, callSignal) => onMcpCall(rt, name, args, callSignal) });
559
608
  let proxy;
560
609
  let agent;
@@ -593,7 +642,7 @@ export function acpHarness(options, control) {
593
642
  if (recipe.billing.kind === "proxy") {
594
643
  if (!options.proxy)
595
644
  throw new Error("acp: proxy billing needs the adapter's proxy option");
596
- proxy = await options.proxy({ halt: (reason) => ctx.halt?.(reason) });
645
+ proxy = await options.proxy({ halt: (reason) => ctx.halt?.(reason), server: serverName });
597
646
  // A stop while the proxy started: the drive's end ran before there was a proxy to close. It is closed here, and
598
647
  // the agent is never started.
599
648
  if (signal.aborted) {
@@ -669,7 +718,8 @@ export function acpHarness(options, control) {
669
718
  const server = recipe.declares.mcp === "http"
670
719
  ? { type: "http", name: rt.server, url: mcp.url, headers: [{ name: "Authorization", value: `Bearer ${key}` }] }
671
720
  : { name: rt.server, command: process.execPath, args: [STDIO_BRIDGE], env: [{ name: "AGENTRUN_MCP_URL", value: mcp.url }, { name: "AGENTRUN_MCP_KEY", value: key }] };
672
- const instructions = options.instructions?.trim() ? options.instructions : undefined;
721
+ // The session's own, then the recipe's (how it runs the agent, which the agent cannot see).
722
+ const instructions = [options.instructions, recipe.instructions].filter((each) => !!each?.trim()).join("\n\n") || undefined;
673
723
  const systemPrompt = instructions && caps.sessionCapabilities?.systemPrompt ? { mode: "append", content: [{ type: "text", text: instructions }] } : undefined;
674
724
  const last = journalRecords(ctx.state(), SESSION_STREAM).map((r) => r.data?.sessionId).filter((id) => typeof id === "string").at(-1);
675
725
  /** What session/load or session/new answered: the models it lists, for one. */
@@ -691,14 +741,33 @@ export function acpHarness(options, control) {
691
741
  rt.loading = false;
692
742
  }
693
743
  }
744
+ // session/load carries no instructions for an agent with no system prompt: they are in its history once a copy of
745
+ // it taken after the prompt that carried them says so (INSTRUCTIONS_STREAM). The session's own come again when
746
+ // that prompt was cut (a crash before the copy); the recipe's too, or when they came or changed since (an upgrade).
747
+ const recipeTold = recipe.instructions?.trim() ? recipe.instructions : undefined;
748
+ if (!rt.fresh && instructions && !systemPrompt) {
749
+ const prompted = journalRecords(ctx.state(), SESSION_STREAM).some((r) => r.data?.sessionId === last && r.data?.prompted === true);
750
+ const given = journalRecords(ctx.state(), INSTRUCTIONS_STREAM).map((r) => r.data).filter((d) => d?.sessionId === last);
751
+ if (prompted && !given.some((d) => d?.whole === true)) {
752
+ rt.firstBlocks.push(`Instructions for this session, from the host that runs you:\n\n${instructions}`);
753
+ rt.told = { text: recipeTold, whole: true };
754
+ }
755
+ else if (recipeTold && given.map((d) => d?.text).at(-1) !== recipeTold) {
756
+ rt.firstBlocks.push(`Instructions for this session, from the host that runs you:\n\n${recipeTold}`);
757
+ rt.told = { text: recipeTold };
758
+ }
759
+ }
694
760
  if (rt.fresh) {
695
761
  const opened = await ask("session/new", () => live.connection.agent.request("session/new", { cwd: root, mcpServers: [server], ...(systemPrompt ? { systemPrompt } : {}) }));
696
762
  rt.sessionId = opened.sessionId;
697
- journal.append(SESSION_STREAM, { sessionId: opened.sessionId });
763
+ // `prompted`: its instructions go in its first prompt, so a load checks they reached its history.
764
+ journal.append(SESSION_STREAM, { sessionId: opened.sessionId, ...(instructions && !systemPrompt ? { prompted: true } : {}) });
698
765
  mirrorInto(rt, journal);
699
766
  await journal.flush();
700
- if (instructions && !systemPrompt)
767
+ if (instructions && !systemPrompt) {
701
768
  rt.firstBlocks.push(`Instructions for this session, from the host that runs you:\n\n${instructions}`);
769
+ rt.told = { text: recipeTold, whole: true };
770
+ }
702
771
  const context = contextNote(ctx.state());
703
772
  if (context)
704
773
  rt.firstBlocks.push(context);
@@ -741,11 +810,14 @@ export function acpHarness(options, control) {
741
810
  };
742
811
  async function driveOnce(ctx) {
743
812
  const journal = new NativeJournal(ctx);
813
+ // The turn's budget kept on this drive's journal: a resume answers the calls it left on its answer's facts.
814
+ journalTurn(options.resultBudget?.turn, journal);
744
815
  const gate = options.gate;
745
816
  // The gate is asked once the call's `seen` record is in the log: a call the gate parks is found again on a resume.
746
817
  const bridge = toolBridge(ctx, options.tools, {
747
818
  ...(gate ? { gate: async (call) => (await journal.flush(), gate(call)) } : {}),
748
819
  beforeNever: () => journal.flush(),
820
+ ...(options.resultBudget ? { budget: options.resultBudget } : {}),
749
821
  });
750
822
  const cur = { ctx, journal, bridge, signal: ctx.signal, inflight: new Set() };
751
823
  // A resumed session: each call of ours the agent made and the records never answered goes through the bridge before
@@ -818,6 +890,10 @@ export function acpHarness(options, control) {
818
890
  }
819
891
  // The send's mark, in the log first: a crash between the two reads "marked, maybe sent", never sent twice.
820
892
  journal.append(PROMPT_STREAM, { submission, ...(covers.length ? { covers: [...covers] } : {}) });
893
+ // The instructions this prompt carries are recorded given only with a copy of the agent's history taken after it
894
+ // answered (below): a crash before that leaves a copy without them, and the next load gives them again.
895
+ const telling = agent.told;
896
+ agent.told = undefined;
821
897
  await journal.flush();
822
898
  const prompt = [...agent.firstBlocks.splice(0), ...body].map((text) => ({ type: "text", text }));
823
899
  let ended;
@@ -859,7 +935,8 @@ export function acpHarness(options, control) {
859
935
  }
860
936
  if (ctx.signal.aborted)
861
937
  throw ctx.signal.reason;
862
- mirrorInto(agent, journal);
938
+ if (mirrorInto(agent, journal) && telling && answer !== undefined)
939
+ journal.append(INSTRUCTIONS_STREAM, { sessionId: agent.sessionId, ...telling });
863
940
  // Cancelled by the session's interrupt: no end is written, the turn stays open (its host settles it).
864
941
  if (interrupting) {
865
942
  await journal.flush();
@@ -3,8 +3,9 @@ import type { AcpProxy } from "../adapter.js";
3
3
  /** Goose's own tools that stay on with every bundled extension off: `load_skill`, which its agent always offers and which
4
4
  * reads skill files only. */
5
5
  export declare const GOOSE_OWN_TOOLS: readonly string[];
6
- /** A host tool's name as Goose offers it to its model: the MCP server's name, two underscores, the tool's. */
7
- export declare const gooseToolName: (name: string) => string;
6
+ /** A host tool's name as Goose offers it to its model: the MCP server's name at this start (`agentrun` under Goose's own
7
+ * recipe; a start's own under a recipe with the title tie: mcpServerName), two underscores, the tool's. */
8
+ export declare const gooseToolName: (name: string, server?: string) => string;
8
9
  /** The `anthropic-beta` value Goose 1.59.2 sends with each Messages request, recorded behind a fake origin (the package's
9
10
  * Goose test records it again on every run with the binary). */
10
11
  export declare const GOOSE_BETAS: ReadonlySet<string>;
@@ -15,6 +16,8 @@ export interface GoosePolicyOptions {
15
16
  model: string;
16
17
  /** The session's host tools, by their names (`spec.tools`). */
17
18
  tools: readonly string[];
19
+ /** Our MCP server's name at this start (AcpProxySession.server). Default `agentrun`. */
20
+ server?: string;
18
21
  /** The most output tokens one request may ask for. Default 128 000, what Goose asks for. */
19
22
  maxOutputTokens?: number;
20
23
  /** How the provider takes its credential. Default `x-api-key` (Anthropic's API). */
@@ -26,8 +26,9 @@ import { MCP_SERVER } from "../calls.js";
26
26
  /** Goose's own tools that stay on with every bundled extension off: `load_skill`, which its agent always offers and which
27
27
  * reads skill files only. */
28
28
  export const GOOSE_OWN_TOOLS = Object.freeze(["load_skill"]);
29
- /** A host tool's name as Goose offers it to its model: the MCP server's name, two underscores, the tool's. */
30
- export const gooseToolName = (name) => `${MCP_SERVER}__${name}`;
29
+ /** A host tool's name as Goose offers it to its model: the MCP server's name at this start (`agentrun` under Goose's own
30
+ * recipe; a start's own under a recipe with the title tie: mcpServerName), two underscores, the tool's. */
31
+ export const gooseToolName = (name, server = MCP_SERVER) => `${server}__${name}`;
31
32
  /** The `anthropic-beta` value Goose 1.59.2 sends with each Messages request, recorded behind a fake origin (the package's
32
33
  * Goose test records it again on every run with the binary). */
33
34
  export const GOOSE_BETAS = new Set(["thinking-binding-controls-2026-08-01"]);
@@ -104,7 +105,7 @@ export function applyGoose(body, options) {
104
105
  blocks(message.content, "a message's content");
105
106
  }
106
107
  blocks(body.system, "system");
107
- const allowed = new Set([...options.tools.map(gooseToolName), ...GOOSE_OWN_TOOLS]);
108
+ const allowed = new Set([...options.tools.map((name) => gooseToolName(name, options.server)), ...GOOSE_OWN_TOOLS]);
108
109
  if (body.tools !== undefined) {
109
110
  if (!Array.isArray(body.tools))
110
111
  refuse(400, "tools is not a list");
@@ -316,8 +317,9 @@ export function goosePolicy(options) {
316
317
  export function gooseProxy(options) {
317
318
  return async (session) => {
318
319
  const proxy = await startModelProxy({
319
- policy: goosePolicy({ model: options.model, tools: session.tools, ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}), ...(options.provider.auth ? { auth: options.provider.auth } : {}) }),
320
+ policy: goosePolicy({ model: options.model, tools: session.tools, ...(session.server ? { server: session.server } : {}), ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}), ...(options.provider.auth ? { auth: options.provider.auth } : {}) }),
320
321
  hooks: session.models,
322
+ ...(session.turn ? { turn: session.turn } : {}),
321
323
  model: options.model,
322
324
  origin: options.provider.origin,
323
325
  credential: async () => (await options.provider.credential()) ?? "",
package/dist/host/mcp.js CHANGED
@@ -123,7 +123,7 @@ export async function startMcpServer(options) {
123
123
  async function call(id, params, req, res) {
124
124
  const name = typeof params.name === "string" ? params.name : "";
125
125
  if (!known.has(name))
126
- return json(res, 200, { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: `unknown tool: ${name.slice(0, 80)}` }], isError: true } });
126
+ return json(res, 200, { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: `tool ${JSON.stringify(name.slice(0, 80))} isn't granted to this agent` }], isError: true } });
127
127
  const args = isPlain(params.arguments) ? params.arguments : {};
128
128
  const meta = isPlain(params._meta) ? params._meta : {};
129
129
  const token = typeof meta.progressToken === "string" || typeof meta.progressToken === "number" ? meta.progressToken : undefined;
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { acpAdapter, type AcpAdapterOptions, type AcpProxy, type AcpProxySession
2
2
  export { ACP_CODES, acpFacts, type AcpFacts } from "./facts.js";
3
3
  export { ALLOW_FILE_FORMS, allowFileText, announcesProblems, AUTH_METHOD, homePath, MODEL_ID, recipeProblems, RESERVED_ENV, type AcpAllowFile, type AcpAllowForm, type AcpBilling, type AcpRecipe, type AcpRefusal } from "./recipe.js";
4
4
  export { ANNOUNCES_PATH, type AcpAnnounces } from "./calls.js";
5
- export { CALL_STREAM, contextNote, MODEL_STREAM, PERMISSION_STREAM, PROMPT_STREAM, REASK_LIMIT, SESSION_STREAM, sentSubmissions, TOOLS_STREAM } from "./harness.js";
5
+ export { CALL_STREAM, contextNote, INSTRUCTIONS_STREAM, MODEL_STREAM, PERMISSION_STREAM, PROMPT_STREAM, REASK_LIMIT, SESSION_STREAM, sentSubmissions, TOOLS_STREAM } from "./harness.js";
6
6
  export { STATE_BUDGET, STATE_STREAM, stateBudgetPassed, stateFiles, type StateRecord } from "./state.js";
7
7
  export type { ConfineChild } from "./host/child.js";
8
8
  export { GOOSE_INSTALL, GOOSE_NOT_INSTALLED, gooseFacts } from "./goose-facts.js";
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ export { acpAdapter } from "./adapter.js";
3
3
  export { ACP_CODES, acpFacts } from "./facts.js";
4
4
  export { ALLOW_FILE_FORMS, allowFileText, announcesProblems, AUTH_METHOD, homePath, MODEL_ID, recipeProblems, RESERVED_ENV } from "./recipe.js";
5
5
  export { ANNOUNCES_PATH } from "./calls.js";
6
- export { CALL_STREAM, contextNote, MODEL_STREAM, PERMISSION_STREAM, PROMPT_STREAM, REASK_LIMIT, SESSION_STREAM, sentSubmissions, TOOLS_STREAM } from "./harness.js";
6
+ export { CALL_STREAM, contextNote, INSTRUCTIONS_STREAM, MODEL_STREAM, PERMISSION_STREAM, PROMPT_STREAM, REASK_LIMIT, SESSION_STREAM, sentSubmissions, TOOLS_STREAM } from "./harness.js";
7
7
  export { STATE_BUDGET, STATE_STREAM, stateBudgetPassed, stateFiles } from "./state.js";
8
8
  export { GOOSE_INSTALL, GOOSE_NOT_INSTALLED, gooseFacts } from "./goose-facts.js";
9
9
  export { gooseAdapter, gooseRecipe, recipeFile } from "./goose.js";
package/dist/recipe.d.ts CHANGED
@@ -26,9 +26,9 @@ export declare const AUTH_METHOD: RegExp;
26
26
  declare const ALLOW_FORMS: {
27
27
  /** Goose 1.59.2's permission file (PermissionConfig under `user`, every field present: none has a default, and a
28
28
  * file that does not parse stops Goose at its start): each tool always allowed by the name Goose calls it,
29
- * `agentrun__<tool>`, nothing asked before or never allowed. Written as JSON, which YAML reads. Goose's own tools are
30
- * not named, so they still ask. */
31
- "goose-permission": (tools: readonly string[]) => string;
29
+ * `<server>__<tool>` (`server`: our MCP server's name at this start, mcpServerName), nothing asked before or never
30
+ * allowed. Written as JSON, which YAML reads. Goose's own tools are not named, so they still ask. */
31
+ "goose-permission": (tools: readonly string[], server: string) => string;
32
32
  };
33
33
  /** The forms an allowFile may take, by name: a recipe loader's check (serve's) reads them from here. */
34
34
  export declare const ALLOW_FILE_FORMS: readonly string[];
@@ -39,8 +39,8 @@ export type AcpAllowFile = {
39
39
  readonly path: string;
40
40
  readonly form: AcpAllowForm;
41
41
  };
42
- /** The text of an allowFile in `form` for a start whose MCP server lists `tools`. */
43
- export declare function allowFileText(form: AcpAllowForm, tools: readonly string[]): string;
42
+ /** The text of an allowFile in `form` for a start whose MCP server, given to the agent as `server`, lists `tools`. */
43
+ export declare function allowFileText(form: AcpAllowForm, tools: readonly string[], server?: string): string;
44
44
  export interface AcpRecipe {
45
45
  /** The harness's id: the adapter's. */
46
46
  readonly id: string;
@@ -85,6 +85,10 @@ export interface AcpRecipe {
85
85
  * (`gpt-5.4-nano`): chosen with session/set_model among those session/new lists, before the first prompt. One it
86
86
  * does not list is refused with ACP_CODES.modelUnlisted. Absent: the agent's own default. */
87
87
  readonly model?: string;
88
+ /** What the agent is told at each session's start about how the recipe runs it, which it cannot see for itself
89
+ * (Cursor: its own Write tool is refused, so a file is written with a shell command): after the session's own
90
+ * instructions, by the same route (the system prompt the agent advertises, else ahead of the first prompt). */
91
+ readonly instructions?: string;
88
92
  /** Files written into its private HOME before it starts, by their path in HOME (`.config/goose/config.yaml`). */
89
93
  readonly files?: Readonly<Record<string, string>>;
90
94
  /** A file in HOME, written at each start from the tools that start's MCP server lists, that tells the agent to run
package/dist/recipe.js CHANGED
@@ -16,15 +16,15 @@ export const AUTH_METHOD = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
16
16
  const ALLOW_FORMS = {
17
17
  /** Goose 1.59.2's permission file (PermissionConfig under `user`, every field present: none has a default, and a
18
18
  * file that does not parse stops Goose at its start): each tool always allowed by the name Goose calls it,
19
- * `agentrun__<tool>`, nothing asked before or never allowed. Written as JSON, which YAML reads. Goose's own tools are
20
- * not named, so they still ask. */
21
- "goose-permission": (tools) => `${JSON.stringify({ user: { always_allow: tools.map((tool) => `${MCP_SERVER}__${tool}`), ask_before: [], never_allow: [] } })}\n`,
19
+ * `<server>__<tool>` (`server`: our MCP server's name at this start, mcpServerName), nothing asked before or never
20
+ * allowed. Written as JSON, which YAML reads. Goose's own tools are not named, so they still ask. */
21
+ "goose-permission": (tools, server) => `${JSON.stringify({ user: { always_allow: tools.map((tool) => `${server}__${tool}`), ask_before: [], never_allow: [] } })}\n`,
22
22
  };
23
23
  /** The forms an allowFile may take, by name: a recipe loader's check (serve's) reads them from here. */
24
24
  export const ALLOW_FILE_FORMS = Object.freeze(Object.keys(ALLOW_FORMS));
25
- /** The text of an allowFile in `form` for a start whose MCP server lists `tools`. */
26
- export function allowFileText(form, tools) {
27
- return ALLOW_FORMS[form](tools);
25
+ /** The text of an allowFile in `form` for a start whose MCP server, given to the agent as `server`, lists `tools`. */
26
+ export function allowFileText(form, tools, server = MCP_SERVER) {
27
+ return ALLOW_FORMS[form](tools, server);
28
28
  }
29
29
  /** `path` in HOME, normalized, or undefined when it leaves HOME (absolute, `..`, or a `$HOME/` prefix spelled out). */
30
30
  export function homePath(path) {
@@ -63,6 +63,9 @@ export function recipeProblems(recipe) {
63
63
  problems.push("the command must be an absolute path");
64
64
  if (!recipe.declares || typeof recipe.declares.load !== "boolean" || (recipe.declares.mcp !== "http" && recipe.declares.mcp !== "stdio"))
65
65
  problems.push('declares needs load (true or false) and mcp ("http" or "stdio")');
66
+ const told = recipe.instructions;
67
+ if (told !== undefined && (typeof told !== "string" || !told.trim()))
68
+ problems.push("the instructions must be words, when there are any");
66
69
  const billing = recipe.billing;
67
70
  if (billing?.kind === "plan") {
68
71
  if (!Number.isInteger(billing.maxTurns) || billing.maxTurns < 1)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-harness-acp",
3
- "version": "0.1.0-beta.62",
3
+ "version": "0.1.0-beta.64",
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",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@agentclientprotocol/sdk": "2.7.0",
52
- "@parcha/agentrun-kernel": "0.1.0-beta.62",
52
+ "@parcha/agentrun-kernel": "0.1.0-beta.64",
53
53
  "zod": "4.6.6"
54
54
  },
55
55
  "publishConfig": {
@@ -6,6 +6,7 @@
6
6
  "files": {
7
7
  ".config/cursor/cli-config.json":"{\"version\":1,\"permissions\":{\"allow\":[],\"deny\":[\"Write(**)\"]},\"approvalMode\":\"allowlist\"}\n"
8
8
  },
9
+ "instructions": "Your own file-writing tool (Write) is turned off here: every write with it is refused, and asking does not turn it on. To create or change a file, run a shell command that writes it (a heredoc such as cat > name <<'EOF' ... EOF, or a short script); a shell command asks the person first. When Write refuses a write, write the file with a shell command instead: never stop at that refusal or answer without the file. When the person denies a shell command, that is their answer: do not ask again for the same write; stop and say what you could not do.",
9
10
  "state": [".config/cursor/acp-sessions"],
10
11
  "credentials": [".config/cursor/auth.json"],
11
12
  "refusals": [
@@ -7,8 +7,8 @@
7
7
  // load: advertise session/load and keep sessions in $HOME/.fake-acp/sessions (default true);
8
8
  // advertiseLoad / advertiseHttp: what initialize says, when it should differ from what the agent does;
9
9
  // http: advertise MCP over HTTP (default true); the client then picks the transport;
10
- // style: "goose" (titles agentrun__<tool>, every tool asks permission, allow_always offered first) or "cursor"
11
- // (titles agentrun-<tool>: <tool>; MCP and execute ask, edits do not; a refused native call still reports
10
+ // style: "goose" (titles <server>__<tool>, every tool asks permission, allow_always offered first) or "cursor"
11
+ // (titles <server>-<tool>: <tool>, <server> the name the client gave its MCP server; MCP and execute ask, edits do not; a refused native call still reports
12
12
  // completed), or "goose-1.59" (as "goose", but titled as Goose 1.59.2 titles a call of an extension's tool:
13
13
  // `agentrun: <tool, its underscores as spaces>`), or "antigravity" (an MCP call as agy 1.5.14 announces and asks
14
14
  // about it: named `mcp_<server>_<tool>`, titled `Run mcp_<server>_<tool>`, <server> the name the client gave
@@ -25,18 +25,21 @@
25
25
  // ignoreCancel: log session/cancel and go on as if it never came (an agent that keeps spending);
26
26
  // keepMcpOnCancel: on session/cancel, answer the prompt `cancelled` at once and leave an MCP call in flight open;
27
27
  // announce: with style "cursor", "late" (the default): an MCP call as Cursor 2026.11.13 announces it, a tool_call
28
- // titled "MCP: tool" with no input, then a tool_call_update titled `agentrun: <tool>` whose rawInput is
29
- // {providerIdentifier, toolName, args}; its permission request is titled `agentrun-<tool>: <tool>`.
30
- // "early": one tool_call titled `agentrun-<tool>: <tool>` with the arguments as its rawInput, naming the
28
+ // titled "MCP: tool" with no input, then a tool_call_update titled `<server>: <tool>` whose rawInput is
29
+ // {providerIdentifier: <server>, toolName, args}; its permission request is titled `<server>-<tool>: <tool>`,
30
+ // <server> the name the client gave its MCP server.
31
+ // "early": one tool_call titled `<server>-<tool>: <tool>` with the arguments as its rawInput, naming the
31
32
  // tool in no field (no Cursor release measured sends this);
32
33
  // lateTitle: with announce "late", that update's title instead (a release that words it otherwise);
33
34
  // (a call step's `ask`, {kind, title}: what its permission request says instead of the call's own kind and title;)
34
35
  // (a native step's `lateInput`: a tool_call_update after its tool_call with that rawInput, a release that echoes the
35
- // model's arguments in a later update;)
36
+ // model's arguments in a later update; in it and in the step's title, `<server>` is the name the client gave its MCP
37
+ // server, so a test can name the start's own server, whatever name the start gave it;)
36
38
  // (a native step's `narrate`: text the agent writes after the call's tool_call and before it ends, as Cursor
37
39
  // 2026.11.13 does;)
38
40
  // (styles "goose" and "goose-1.59": each tool_call names its tool in _meta.goose.toolCall.toolName, as Goose 1.59.2
39
- // does: `agentrun__<tool>` for ours, a native step's `toolName` or `developer__<kind>` for the agent's own;)
41
+ // does: `<server>__<tool>` for ours, a native step's `toolName` or `developer__<kind>` for the agent's own; a native
42
+ // step whose `toolName` the permission file always allows runs unasked, as Goose's would;)
40
43
  // models: the models session/new and session/load list ({modelId, name}), the first current; session/set_model
41
44
  // takes one of them and refuses any other;
42
45
  // writeAuth: at session/new and session/load, write $HOME/.config/cursor/auth.json holding the sha256 of the
@@ -130,7 +133,7 @@ const pgid = (() => {
130
133
  })();
131
134
  said({ type: "start", env: Object.keys(process.env).sort(), home, cwd: process.cwd(), pgid, ...(config.cursorDirs ? { cursorDir, deniesWrite } : {}) });
132
135
  /** The title of a call of our `tool`, the client's MCP server given as `server` (agy names it in its title). */
133
- const titleOf = (tool, server = "agentrun") => (style === "cursor" ? `agentrun-${tool}: ${tool}` : style === "antigravity" ? `Run mcp_${server}_${tool}` : style === "goose-1.59" ? `agentrun: ${tool.replace(/_/g, " ")}${config.titleSummary ? ` · ${config.titleSummary}` : ""}` : `agentrun__${tool}`);
136
+ const titleOf = (tool, server = "agentrun") => (style === "cursor" ? `${server}-${tool}: ${tool}` : style === "antigravity" ? `Run mcp_${server}_${tool}` : style === "goose-1.59" ? `agentrun: ${tool.replace(/_/g, " ")}${config.titleSummary ? ` · ${config.titleSummary}` : ""}` : `${server}__${tool}`);
134
137
  const late = style === "cursor" && config.announce !== "early";
135
138
  /** Goose's field naming a tool_call's tool, on its first tool_call only, in the shape goose-acp's goose_tool_call_meta
136
139
  * builds (conversion.rs:65-91 at v1.59.2): `toolName` the name the model called, `extensionName` the part before `__`
@@ -298,17 +301,17 @@ async function takeTurn(client, session, prompt, signal) {
298
301
  const reported = "toolSummary" in args ? args : { ...args, toolSummary: `Call ${s.call}` };
299
302
  const update = style === "antigravity"
300
303
  ? { toolCallId: id, name: `mcp_${session.server}_${s.call}`, title: titleOf(s.call, session.server), kind: "other", status: "pending", rawInput: reported, args: reported }
301
- : { toolCallId: id, title: titleOf(s.call), kind: "other", status: "pending", rawInput: args };
304
+ : { toolCallId: id, title: titleOf(s.call, session.server), kind: "other", status: "pending", rawInput: args };
302
305
  const entry = { kind: "call", id, tool: s.call, args, status: "pending" };
303
306
  session.history.push(entry);
304
307
  save(session);
305
308
  if (late) {
306
309
  // Cursor 2026.11.13: the call is announced with no name, then named by an update, then asked about by its own title.
307
310
  await notify({ sessionUpdate: "tool_call", toolCallId: id, title: "MCP: tool", kind: "other", status: "pending", rawInput: {} });
308
- await notify({ sessionUpdate: "tool_call_update", toolCallId: id, title: config.lateTitle ?? `agentrun: ${s.call}`, rawInput: { providerIdentifier: "agentrun", toolName: s.call, args } });
311
+ await notify({ sessionUpdate: "tool_call_update", toolCallId: id, title: config.lateTitle ?? `${session.server}: ${s.call}`, rawInput: { providerIdentifier: session.server, toolName: s.call, args } });
309
312
  await notify({ sessionUpdate: "tool_call_update", toolCallId: id, status: "in_progress" });
310
- } else await notify({ sessionUpdate: "tool_call", ...update, ...gooseMeta(`agentrun__${s.call}`) });
311
- if (askMcp && !alwaysAllowed.has(`agentrun__${s.call}`) && !(await permitted(client, session, { ...(late ? { toolCallId: id, title: titleOf(s.call), kind: "other", status: "pending" } : update), ...(s.ask ?? {}) }))) {
313
+ } else await notify({ sessionUpdate: "tool_call", ...update, ...gooseMeta(`${session.server}__${s.call}`) });
314
+ if (askMcp && !alwaysAllowed.has(`${session.server}__${s.call}`) && !(await permitted(client, session, { ...(late ? { toolCallId: id, title: titleOf(s.call, session.server), kind: "other", status: "pending" } : update), ...(s.ask ?? {}) }))) {
312
315
  if (signal.aborted) return { stopReason: "cancelled" };
313
316
  entry.status = "failed";
314
317
  entry.result = "the client refused the call";
@@ -349,16 +352,18 @@ async function takeTurn(client, session, prompt, signal) {
349
352
  const id = `native_${step - 1}`;
350
353
  // A model that, taking a step again (after a restart), writes another command for it (retitled).
351
354
  const again = s.retitled?.length ? tally(step - 1) : 0;
352
- const title = again > 0 ? s.retitled[Math.min(again, s.retitled.length) - 1] : (s.title ?? s.native);
355
+ const named = (value) => JSON.parse(JSON.stringify(value).replaceAll("<server>", session.server));
356
+ const title = again > 0 ? s.retitled[Math.min(again, s.retitled.length) - 1] : named(s.title ?? s.native);
353
357
  const update = { toolCallId: id, title, kind: s.native, status: "pending", rawInput: again > 0 ? { ...(s.input ?? {}), command: title } : (s.input ?? {}), ...(style === "antigravity" ? { name: s.toolName ?? s.native } : {}) };
354
358
  const entry = { kind: "native", id, title: update.title, status: "pending" };
355
359
  session.history.push(entry);
356
360
  save(session);
357
361
  // {announce: false}: a permission request for a call no tool_call announced.
358
362
  if (s.announce !== false) await notify({ sessionUpdate: "tool_call", ...update, ...gooseMeta(s.toolName ?? `developer__${s.native}`) });
359
- if (s.lateInput) await notify({ sessionUpdate: "tool_call_update", toolCallId: id, rawInput: s.lateInput });
363
+ if (s.lateInput) await notify({ sessionUpdate: "tool_call_update", toolCallId: id, rawInput: named(s.lateInput) });
360
364
  if (s.narrate) await notify({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: s.narrate } });
361
- const allowed = deniesWrite && EDITS.has(s.native) ? false : askNative.has(s.native) ? await permitted(client, session, update) : true;
365
+ // Goose runs a tool its permission file always allows by the name it calls it (s.toolName), unasked.
366
+ const allowed = deniesWrite && EDITS.has(s.native) ? false : s.toolName !== undefined && alwaysAllowed.has(s.toolName) ? true : askNative.has(s.native) ? await permitted(client, session, update) : true;
362
367
  if (signal.aborted) return { stopReason: "cancelled" };
363
368
  if (allowed && config.nativeLog) appendFileSync(config.nativeLog, `${update.title}\n`);
364
369
  entry.status = allowed ? "completed" : "failed";