@parcha/agentrun-serve 0.1.0-beta.29 → 0.1.0-beta.31

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.
Files changed (172) hide show
  1. package/CHANGELOG.md +238 -0
  2. package/README.md +739 -116
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +18 -7
  6. package/dist/agents.js +19 -10
  7. package/dist/app.js +101 -26
  8. package/dist/background.d.ts +29 -0
  9. package/dist/background.js +397 -0
  10. package/dist/box-egress-vm.d.ts +125 -0
  11. package/dist/box-egress-vm.js +350 -0
  12. package/dist/box-egress.d.ts +99 -0
  13. package/dist/box-egress.js +259 -0
  14. package/dist/box-image.d.ts +1 -1
  15. package/dist/box-image.js +9 -7
  16. package/dist/box-relay-vm.d.ts +84 -0
  17. package/dist/box-relay-vm.js +410 -0
  18. package/dist/box-relay.d.ts +8 -5
  19. package/dist/box-relay.js +14 -9
  20. package/dist/boxes.d.ts +28 -5
  21. package/dist/boxes.js +44 -18
  22. package/dist/browser-cost.d.ts +41 -0
  23. package/dist/browser-cost.js +158 -0
  24. package/dist/cap.d.ts +130 -21
  25. package/dist/cap.js +339 -67
  26. package/dist/cli.js +30 -4
  27. package/dist/coding-tools.d.ts +7 -3
  28. package/dist/coding-tools.js +16 -10
  29. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  30. package/dist/console/assets/index-CnJBf7Lc.js +486 -0
  31. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/content-filter.d.ts +7 -0
  34. package/dist/content-filter.js +23 -0
  35. package/dist/decision-rows.d.ts +11 -3
  36. package/dist/decision-rows.js +18 -11
  37. package/dist/decisions.d.ts +3 -3
  38. package/dist/decisions.js +4 -3
  39. package/dist/errors.d.ts +2 -0
  40. package/dist/errors.js +5 -2
  41. package/dist/files.d.ts +9 -1
  42. package/dist/files.js +10 -2
  43. package/dist/grade.d.ts +11 -11
  44. package/dist/grade.js +43 -55
  45. package/dist/graph-served.d.ts +23 -0
  46. package/dist/graph-served.js +75 -0
  47. package/dist/graph-view.d.ts +7 -5
  48. package/dist/graph-view.js +10 -3
  49. package/dist/harness-app.d.ts +4 -2
  50. package/dist/harness-app.js +110 -19
  51. package/dist/harness-opencode/adapter.d.ts +45 -0
  52. package/dist/harness-opencode/adapter.js +272 -0
  53. package/dist/harness-opencode/binary.d.ts +18 -0
  54. package/dist/harness-opencode/binary.js +87 -0
  55. package/dist/harness-opencode/config.d.ts +24 -0
  56. package/dist/harness-opencode/config.js +61 -0
  57. package/dist/harness-opencode/harness.d.ts +77 -0
  58. package/dist/harness-opencode/harness.js +620 -0
  59. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  60. package/dist/harness-opencode/host/mcp.js +208 -0
  61. package/dist/harness-opencode/host/policy.d.ts +71 -0
  62. package/dist/harness-opencode/host/policy.js +419 -0
  63. package/dist/harness-opencode/host/server.d.ts +55 -0
  64. package/dist/harness-opencode/host/server.js +165 -0
  65. package/dist/harness-opencode/index.d.ts +9 -0
  66. package/dist/harness-opencode/index.js +6 -0
  67. package/dist/harness-opencode/verify.d.ts +32 -0
  68. package/dist/harness-opencode/verify.js +75 -0
  69. package/dist/harness-opencode/versions.d.ts +33 -0
  70. package/dist/harness-opencode/versions.js +64 -0
  71. package/dist/harness.d.ts +4 -1
  72. package/dist/harness.js +5 -2
  73. package/dist/host-check.d.ts +12 -0
  74. package/dist/host-check.js +34 -0
  75. package/dist/host-tools.d.ts +12 -2
  76. package/dist/host-tools.js +26 -12
  77. package/dist/host.js +6 -2
  78. package/dist/hosted-search.js +5 -1
  79. package/dist/import.d.ts +2 -2
  80. package/dist/import.js +4 -3
  81. package/dist/key-check.d.ts +3 -2
  82. package/dist/key-check.js +7 -3
  83. package/dist/key-refusal.js +8 -4
  84. package/dist/key-words.d.ts +37 -0
  85. package/dist/key-words.js +40 -0
  86. package/dist/learn/check.d.ts +10 -1
  87. package/dist/learn/check.js +19 -1
  88. package/dist/learn/grade.d.ts +6 -2
  89. package/dist/learn/grade.js +28 -14
  90. package/dist/learn/index.d.ts +3 -3
  91. package/dist/learn/index.js +3 -3
  92. package/dist/learn/notes.js +2 -1
  93. package/dist/learn/reflect.d.ts +2 -2
  94. package/dist/learn/reflect.js +53 -5
  95. package/dist/learn/secrets.js +28 -8
  96. package/dist/learn/skills.d.ts +19 -4
  97. package/dist/learn/skills.js +95 -6
  98. package/dist/learned-workflow.d.ts +59 -0
  99. package/dist/learned-workflow.js +191 -0
  100. package/dist/learning-routes.d.ts +30 -1
  101. package/dist/learning-routes.js +173 -19
  102. package/dist/learning-run.d.ts +8 -6
  103. package/dist/learning-run.js +70 -27
  104. package/dist/learning-words.d.ts +12 -5
  105. package/dist/learning-words.js +34 -13
  106. package/dist/learning.d.ts +52 -3
  107. package/dist/learning.js +204 -4
  108. package/dist/mcp-gateway.d.ts +96 -0
  109. package/dist/mcp-gateway.js +408 -0
  110. package/dist/mcp-meta.d.ts +17 -0
  111. package/dist/mcp-meta.js +38 -0
  112. package/dist/mcp-servers.d.ts +33 -9
  113. package/dist/mcp-servers.js +58 -10
  114. package/dist/mcp.js +5 -5
  115. package/dist/model.d.ts +13 -11
  116. package/dist/model.js +11 -10
  117. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  118. package/dist/openapi.js +407 -54
  119. package/dist/page.d.ts +2 -0
  120. package/dist/page.js +3 -0
  121. package/dist/paid-calls.d.ts +5 -1
  122. package/dist/paid-calls.js +1 -1
  123. package/dist/pause.d.ts +2 -0
  124. package/dist/place.d.ts +29 -5
  125. package/dist/place.js +51 -11
  126. package/dist/print.d.ts +7 -0
  127. package/dist/print.js +13 -0
  128. package/dist/propose.d.ts +2 -0
  129. package/dist/propose.js +38 -8
  130. package/dist/request-start.d.ts +12 -4
  131. package/dist/request-start.js +139 -15
  132. package/dist/run-box.d.ts +56 -4
  133. package/dist/run-box.js +183 -23
  134. package/dist/runnable.d.ts +13 -3
  135. package/dist/runnable.js +63 -6
  136. package/dist/runs.d.ts +266 -37
  137. package/dist/runs.js +884 -90
  138. package/dist/secrets.d.ts +27 -0
  139. package/dist/secrets.js +38 -2
  140. package/dist/server.d.ts +141 -36
  141. package/dist/server.js +562 -118
  142. package/dist/sign-ins.d.ts +99 -0
  143. package/dist/sign-ins.js +288 -0
  144. package/dist/skills.d.ts +16 -4
  145. package/dist/skills.js +35 -7
  146. package/dist/stats.d.ts +7 -2
  147. package/dist/stats.js +28 -7
  148. package/dist/tool-gate.d.ts +281 -0
  149. package/dist/tool-gate.js +585 -0
  150. package/dist/tool-keys.d.ts +48 -11
  151. package/dist/tool-keys.js +46 -8
  152. package/dist/tool-plane.d.ts +116 -27
  153. package/dist/tool-plane.js +232 -50
  154. package/dist/tools.d.ts +69 -14
  155. package/dist/tools.js +148 -26
  156. package/dist/trigger-secrets.d.ts +32 -0
  157. package/dist/trigger-secrets.js +143 -0
  158. package/dist/triggers.d.ts +439 -0
  159. package/dist/triggers.js +863 -0
  160. package/dist/turn-end.d.ts +3 -2
  161. package/dist/turn-end.js +3 -2
  162. package/dist/usage-lines.d.ts +26 -0
  163. package/dist/usage-lines.js +28 -0
  164. package/dist/validate.d.ts +2 -0
  165. package/dist/validate.js +11 -2
  166. package/dist/web-fetch.js +3 -3
  167. package/dist/webhooks.d.ts +11 -4
  168. package/dist/webhooks.js +17 -1
  169. package/launcher/agentrun-serve +1 -1
  170. package/package.json +16 -14
  171. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  172. package/dist/console/assets/index-By-jkqki.css +0 -1
@@ -0,0 +1,585 @@
1
+ // The tool gate: one gate every tool call passes, on every harness (plan item 4, "approvals that pause and resume").
2
+ // Each tool has a permission: allow (it runs), deny (it is refused, and the model reads why), or ask (a person approves
3
+ // or denies it first). The run's tool paths call it: pi's tools, wrapped where the run's registry composes its agents'
4
+ // tools (app.ts), the kernel's host tools on claude-agent and codex (host-tools.ts), and the MCP gateway, which takes
5
+ // the same park (harness-app.ts) and registers an executor for its approved calls.
6
+ //
7
+ // An ask has one way to wait, every tool's alike (the owner's ruling of 11-04): it PARKS. The gated call answers at once
8
+ // with waitingText and the turn ends, as ask_person's does; the run goes needs_input with the pending approval. On an
9
+ // answer the gate runs the approved call itself (exactly once, through the journaled path: the kernel's host tool; an
10
+ // MCP call, the executor its gateway registers, which comes with the gateway) and resumes the session with a message
11
+ // naming the call. No CLI waits inside a tool call, so no CLI tool timeout applies. One call waits at a time: another
12
+ // asked meanwhile is refused.
13
+ //
14
+ // The answer: POST /v2/runs/{id}/approvals/{approval_id} { decision: "allow" | "deny", note? } -> 204. The first answer
15
+ // wins; the same answer again is 204, a conflicting one 409. Only the owner's password session answers (server.ts), never
16
+ // a token. A cancel marks pending approvals canceled. There is no ask timeout; a run nobody attends (a trigger's,
17
+ // later) is to deny what is set to ask, which is not built yet.
18
+ //
19
+ // In the run's process: the asked call's request is kept in the run's own store (an `agentrun.tool_approval`
20
+ // entry on its root conversation), so a restart keeps it. The server keeps a person's answer in the run's serve.json
21
+ // (runs.ts); the gate reads it there, runs an allowed call once through the kernel's journal (the intent-then-outcome
22
+ // effect any host tool's call is, on a session key of its own: a call a crash cut off runs again only where it is
23
+ // replay-safe, and is answered interrupted otherwise) on the run's own coding source, and resumes the session with one
24
+ // message that names the call and carries its result, or the refusal. A result is cut as every host tool's is
25
+ // (HOST_RESULT_MAX_CHARS); the gate spills nothing.
26
+ //
27
+ // A stop or a cancel wins over an answer (runs.ts supersede): the gate reads the answer again before it writes the
28
+ // call's intent, cuts an approved call in flight when its answer is withdrawn, and reads it again once the call is
29
+ // done. Two windows of milliseconds remain, the same class as a stop racing any tool call inside a turn:
30
+ // - A stop that lands between the read before the intent and drive.effect's intent lets a short call that does not
31
+ // heed its abort run. Its result is dropped (the read after the call), never resumed.
32
+ // - A stop that lands between the read after the call and resume()'s commit can start the resume turn on a stopped
33
+ // run: a stop, unlike a cancel, leaves no mark the resume is held to.
34
+ import { createHash } from "node:crypto";
35
+ import { readFileSync } from "node:fs";
36
+ import { join, posix, resolve, sep } from "node:path";
37
+ import { defineExtension, ROOT_CONVERSATION_ID, wrapTool } from "@earendil-works/pi-durable";
38
+ import { EffectFailure, INTERRUPTED_TEXT, openDrive } from "@parcha/agentrun-kernel/kernel";
39
+ import { boundResult } from "@parcha/agentrun-kernel/process";
40
+ import { readJson, RUN_META } from "./files.js";
41
+ import { LEARNED_DIR } from "./learning.js";
42
+ import { BOX_WORK } from "./place.js";
43
+ import { forModel } from "./result.js";
44
+ import { durableSessions } from "./sessions.js";
45
+ import { SHELL_TOOLS } from "./background.js";
46
+ import { LEGACY_NAMES, readToolSettings, SERVE_OWN_TOOLS, TABLE_TOOLS } from "./tool-plane.js";
47
+ /** What the gate does with a tool's calls. */
48
+ export const PERMISSIONS = ["allow", "ask", "deny"];
49
+ /** An MCP tool's gate name: `mcp:<server>/<tool>`. */
50
+ export const mcpToolName = (server, tool) => `mcp:${server}/${tool}`;
51
+ /** Whether `name` is an MCP tool's gate name. */
52
+ export const isMcpTool = (name) => /^mcp:[^/]+\/.+$/.test(name);
53
+ /** A third-party catalog tool, by its name: monid's (`monid.<tool>`) or an MCP server's (`mcp:<server>/<tool>`). */
54
+ export const isCatalogTool = (name) => name.startsWith("monid.") || isMcpTool(name);
55
+ /** The owner's defaults (11-01): a built-in kernel tool allow; a third-party catalog tool ask. */
56
+ export const defaultPermission = (name) => (isCatalogTool(name) ? "ask" : "allow");
57
+ /** The tools that run a command in the run's box (background.ts SHELL_TOOLS), each held to bash's setting: bash: deny
58
+ * refuses bash_background as it refuses bash, and none of them is a settings key of its own. Under bash: ask the
59
+ * watchers (SHELL_WATCHERS) run unasked. */
60
+ export const SHELL_FAMILY = Object.freeze(Object.fromEntries(SHELL_TOOLS.map((name) => [name, "bash"])));
61
+ /** The shell tool a call named `name` is, under claude-agent's host-tool name too (`mcp__hands__bash_background`), when
62
+ * it is one held to another's setting: its own name, which its request, its refusal and its approved call keep. */
63
+ const shellToolOf = (name) => {
64
+ const own = name.replace(/^mcp__hands__/, "");
65
+ return Object.hasOwn(SHELL_FAMILY, own) && SHELL_FAMILY[own] !== own ? own : undefined;
66
+ };
67
+ /** The shell tools that only watch or end a process the run already started, by its own id (background.ts: an id is
68
+ * digits under the run's own work/background/, and another's is "no background process"): under bash: ask they run
69
+ * unasked, so watching an approved process costs no approval per page. bash: deny still refuses them. */
70
+ export const SHELL_WATCHERS = new Set(["bash_output", "bash_list", "bash_signal"]);
71
+ /** Shell tool `name`'s permission, given bash's: a watcher's ask is allow; any other keeps bash's. */
72
+ const shellPermission = (name, bash) => (bash === "ask" && SHELL_WATCHERS.has(name) ? "allow" : bash);
73
+ /** The settings keys that may set `name`'s permission, most specific first: the tool's own name, then, for an MCP
74
+ * tool, its server's wildcard `mcp:<server>/*`. */
75
+ export function permissionKeys(name) {
76
+ if (!isMcpTool(name))
77
+ return [name];
78
+ return [name, `${name.slice(0, name.indexOf("/"))}/*`];
79
+ }
80
+ /** The browser's registrations on pi (pi-browser's BROWSER_TOOL_NAMES, which a test holds this list to): each is a call
81
+ * of the table's `browser`. */
82
+ const BROWSER_REGISTRATIONS = ["snapshot", "run", "screenshot", "browser_read", "browser_release", "browser_relaunch", "browser_request_handoff", "browser_downloads", "browser_upload"];
83
+ /** A CLI's own tools, by harness, and the table's tool each one is. */
84
+ const NATIVE_TOOLS = {
85
+ "claude-agent": { WebSearch: "web_search", WebFetch: "web_fetch", Bash: "bash", Read: "read", Write: "write", Edit: "edit" },
86
+ codex: { web_search: "web_search", shell: "bash" },
87
+ };
88
+ /** The MCP server through which claude-agent calls the kernel's host tools (`mcp__hands__<wire name>`). */
89
+ const HOST_TOOLS_SERVER = "hands";
90
+ /** The settings key a call named `name` on `harness` is held to: the one mapping from every name a call reaches the gate
91
+ * by. A settings key is itself (a table tool, `monid.<tool>`, `mcp:<server>/<tool>`); a CLI's own tool is the table's it
92
+ * is; an MCP alias, `mcp__<server>__<tool>` (claude-agent's host tools `mcp__hands__<wire name>`, mapped as their
93
+ * wire name) and on OpenCode `<server>_<tool>`, is `mcp:<server>/<tool>`; a catalog's wire name (`monid_run`) is its
94
+ * catalog name; the browser's registrations are `browser`. OpenCode's `<server>_<tool>` maps only for a server of
95
+ * `mcpServers` (the run's configured MCP servers), never by its shape, since a host tool's name has the same shape.
96
+ * Undefined: nothing maps it, and the gate asks. The key only: an MCP call enters the gate once, in the MCP gateway for a
97
+ * registration it marks (GATED_BY_GATEWAY), else where its tool is wrapped. */
98
+ export function settingsKeyOf(harness, name, mcpServers = []) {
99
+ // A legacy name the tool plane folds into a capability (fetch_page into web_fetch) is held to that capability's key,
100
+ // and a tool that runs a command in the box (bash_background and the rest) to bash's: before the table's own names.
101
+ if (Object.hasOwn(LEGACY_NAMES, name))
102
+ return LEGACY_NAMES[name];
103
+ if (Object.hasOwn(SHELL_FAMILY, name))
104
+ return SHELL_FAMILY[name];
105
+ if (TABLE_TOOLS.includes(name) || SERVE_OWN_TOOLS.includes(name) || isCatalogTool(name))
106
+ return name;
107
+ const native = NATIVE_TOOLS[harness]?.[name];
108
+ if (native)
109
+ return native;
110
+ const mcp = /^mcp__([a-z][a-z0-9-]*)__(.+)$/.exec(name);
111
+ if (mcp)
112
+ return mcp[1] === HOST_TOOLS_SERVER ? settingsKeyOf(harness, mcp[2], mcpServers) : mcpToolName(mcp[1], mcp[2]);
113
+ const monid = /^monid_([a-z]+)$/.exec(name);
114
+ if (monid)
115
+ return `monid.${monid[1]}`;
116
+ if (BROWSER_REGISTRATIONS.includes(name))
117
+ return "browser";
118
+ const alias = harness === "opencode" ? /^([a-z][a-z0-9-]*)_(.+)$/.exec(name) : null;
119
+ return alias && mcpServers.includes(alias[1]) ? mcpToolName(alias[1], alias[2]) : undefined;
120
+ }
121
+ /** `name`'s permission in force and the layer it came from, most specific first: the agent's exact key, the agent's
122
+ * server wildcard, the server's exact key, the server's server wildcard, then the default. Rules over a call's
123
+ * arguments are not in V1. */
124
+ export function permissionFrom(name, server, agent = {}) {
125
+ // A shell tool's permission is bash's (SHELL_FAMILY), from bash's layer, wherever it is read: the gate, capabilities, an
126
+ // agent's tools. A watcher (SHELL_WATCHERS) runs unasked only under an ask set as written in a layer: an ask that stands
127
+ // in for anything else (a value not offered, nothing set) stays an ask. No key of its own is read, so none lifts bash's.
128
+ if (Object.hasOwn(SHELL_FAMILY, name) && SHELL_FAMILY[name] !== name) {
129
+ const bash = settingFrom(SHELL_FAMILY[name], server, agent);
130
+ return { permission: bash.written ? shellPermission(name, bash.permission) : bash.permission, from: bash.from };
131
+ }
132
+ const { permission, from } = settingFrom(name, server, agent);
133
+ return { permission, from };
134
+ }
135
+ /** permissionFrom's own read, and whether the permission is `written`: a valid one set in a layer as it reads there, not
136
+ * a stand-in. A value that is no permission at all reads ask, never the value. */
137
+ function settingFrom(name, server, agent) {
138
+ for (const [from, layer] of [["agent", agent], ["server", server]]) {
139
+ for (const key of permissionKeys(name)) {
140
+ const setting = layer[key];
141
+ const set = setting?.permission;
142
+ if (!set)
143
+ continue;
144
+ if (!PERMISSIONS.includes(set))
145
+ return { permission: "ask", from, written: false };
146
+ return { permission: set, from, written: setting.fallback !== true };
147
+ }
148
+ }
149
+ return { permission: defaultPermission(name), from: "default", written: false };
150
+ }
151
+ /** `name`'s permission in force (permissionFrom): the one rule every path reads, the gate's, the tool plane's and a
152
+ * workflow's call nodes'. */
153
+ export const permissionOf = (name, server, agent = {}) => permissionFrom(name, server, agent).permission;
154
+ /** The mark a tool registration carries when its calls are gated by whoever registered it (the MCP gateway, which marks
155
+ * its registrations only when it holds this run's gate and park, and enters the gate in each call): RunGate.extension
156
+ * does not wrap it again. `Symbol.for`, so the mark is the same symbol whichever copy of this module set or reads it. */
157
+ export const GATED_BY_GATEWAY = Symbol.for("agentrun.gatedByGateway");
158
+ /** The refusal of a call whose tool is set to deny; of one held to another tool's setting (`heldTo`, a shell tool's
159
+ * bash), naming the setting to change. */
160
+ export const deniedText = (tool, heldTo) => heldTo && heldTo !== tool ? `Permission denied: ${tool} follows ${heldTo}'s setting, which is deny on this server. Don't retry it.` : `Permission denied: ${tool} is set to deny on this server. Don't retry it.`;
161
+ /** The refusal of an ask where no one can approve it: a server with accounts off, whose answer route takes no token. */
162
+ export const noApproverText = (tool) => `Permission denied: ${tool} needs the owner's approval, and this server has accounts off (AGENTRUN_ACCOUNTS=0), so no one can give it: set the tool to allow or deny in the agent's Tools.`;
163
+ /** Set by the server in a run's environment when no one can approve here (accounts off): the gate refuses each ask. */
164
+ export const NO_APPROVER_ENV = "AGENTRUN_SERVE_NO_APPROVER";
165
+ /** A parked call's answer: the run pauses here. */
166
+ export const waitingText = (tool) => `This ${tool} call waits for a person's approval; the run pauses here and continues with the result when they answer.`;
167
+ /** A call a person denied, with their reason when they gave one. */
168
+ export const refusedText = (tool, note) => `The user denied this ${tool} call.${note ? ` Reason: ${note}` : ""}`;
169
+ /** The Timeline row of a call that waits for an approval. */
170
+ export const APPROVAL_ROW = "tool_approval_requested";
171
+ /** A call's arguments shown on its approval, at most this many bytes. */
172
+ export const ARGS_PREVIEW_BYTES = 2048;
173
+ /** A gate of `policy` (the run's permission of a tool now) with no run behind it: allow and deny are enforced and
174
+ * executors are kept; an ask throws, since nothing here can park a call (a run's is RunGate), and spill returns
175
+ * the text as it is. */
176
+ export function gateOf(policy) {
177
+ const executors = new Map();
178
+ return {
179
+ async enter(tool) {
180
+ const permission = policy(tool);
181
+ if (permission === "allow")
182
+ return undefined;
183
+ if (permission === "deny")
184
+ return { text: deniedText(tool), isError: true };
185
+ throw new Error(`A gate with no run cannot ask a person about ${tool}.`);
186
+ },
187
+ executor(prefix, run) {
188
+ executors.set(prefix, run);
189
+ },
190
+ spill(_callId, text) {
191
+ return text;
192
+ },
193
+ };
194
+ }
195
+ /** The file in a run's directory that names the origin of the turn it runs now: written by the server alone, as it sends
196
+ * the learning lane's reflect turn (runs.ts's toLiveDoor), and gone before a person's turn is sent (runs.ts's personsTurn).
197
+ * The gate refuses that turn's writes under work/.learning/ (NOTE_ONLY_TEXT). */
198
+ export const TURN_ORIGIN_FILE = "turn-origin.json";
199
+ /** The run's store's record of a call that waits for approval (`phase: "requested"`), and of its answer acted on
200
+ * (`phase: "resolved"`), on its root conversation. */
201
+ export const APPROVAL_ENTRY = "agentrun.tool_approval";
202
+ /** The refusal of the end-of-run turn's write or edit under work/.learning/: its notes are kept only from its answer's
203
+ * note blocks (learn/reflect.ts parseReflection), which the host merges in its own store; a file there is never kept. */
204
+ export const NOTE_ONLY_TEXT = "A note is kept only from your answer: write it in a ```note block, not to a file.";
205
+ /** Whether `args.path`, as a file tool resolves it (a leading `@` dropped, Unicode spaces made plain, then lexically),
206
+ * names work/.learning/ or a path under it: by this machine's `work` or the box's (BOX_WORK). */
207
+ export function underLearning(work, args) {
208
+ const path = args?.path;
209
+ if (typeof path !== "string")
210
+ return false;
211
+ const plain = path.replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ").replace(/^@/, "");
212
+ const under = (base, at) => at === join(base, LEARNED_DIR) || at.startsWith(`${join(base, LEARNED_DIR)}${sep}`);
213
+ return under(resolve(work), resolve(work, plain)) || under(BOX_WORK, posix.resolve(BOX_WORK, plain));
214
+ }
215
+ /** `text` cut to at most ARGS_PREVIEW_BYTES. What is shown of a call's arguments is the whole of them redacted first, then
216
+ * cut (runs.ts), so a cut never leaves the head of a key no redaction recognizes. */
217
+ export function previewOf(text) {
218
+ const bytes = Buffer.from(text, "utf8");
219
+ return bytes.length <= ARGS_PREVIEW_BYTES ? bytes.toString("utf8") : `${bytes.subarray(0, ARGS_PREVIEW_BYTES - 3).toString("utf8").replace(/\uFFFD+$/, "")}…`;
220
+ }
221
+ /** `args` as JSON, at most ARGS_PREVIEW_BYTES: the request's own record of them, never shown as it is. */
222
+ export const argsPreview = (args) => previewOf(JSON.stringify(args ?? {}) ?? "");
223
+ /** How the gate's resume message starts: the server knows its row by it, and redacts the row whole (runs.ts). */
224
+ export const RESUME_PREFIX = "[tool approval] ";
225
+ /** The one message that resumes a session once a person answered: it names the call it answers (its tool, call id and
226
+ * arguments), so the model tells it from a person's new input, and carries the call's result, or the refusal. */
227
+ export function resumeText(request, shown, decision, result) {
228
+ // `shown`: the arguments as the server shows them, redacted whole then cut (runs.ts): never the call's own.
229
+ const args = shown.length > 300 ? `${shown.slice(0, 299)}…` : shown;
230
+ const head = `${RESUME_PREFIX}This answers your ${request.tool} call ${request.call_id} (arguments ${args}), which waited for a person's approval; it is not a new message from them.`;
231
+ return decision === "allow" ? `${head} They allowed it, and it ran${result.isError ? " and failed" : ""}. Its result:\n${result.text}` : `${head}\n${result.text}`;
232
+ }
233
+ /** The gate of the run `runId` at `where` (its directory, under the data directory's runs/), on its pinned revision:
234
+ * an agentic run's parks an asked call; a workflow's model node cannot. */
235
+ export function runGate(where, runId, revision) {
236
+ return new RunGate({ root: where.root, work: where.work, data: resolve(where.root, "..", ".."), runId, harness: revision.body.harness ?? "pi" }, (revision.body.toolSettings ?? {}), revision.kind === "agentic", process.env[NO_APPROVER_ENV] !== "1");
237
+ }
238
+ /** The gate in a run's process, park mode: its policy, the turn's origin, the calls that wait, and the answers acted on. */
239
+ export class RunGate {
240
+ where;
241
+ overrides;
242
+ parks;
243
+ approvers;
244
+ requests = new Map();
245
+ durable;
246
+ context;
247
+ coding;
248
+ /** The run's own tools beyond the table (its learned_workflow), on which an approved call of one runs. */
249
+ extra = [];
250
+ resume;
251
+ drive;
252
+ timer;
253
+ settling = false;
254
+ stop = new AbortController();
255
+ /** `where.data`: the server's data directory, its tool settings beside the store; `overrides`: the pinned revision's
256
+ * own; `parks`: whether an asked call parks the run (an agentic run's), which a workflow's model node cannot;
257
+ * `approvers`: whether anyone can answer an ask here (the owner's password session: accounts on). */
258
+ constructor(where, overrides = {}, parks = true, approvers = true) {
259
+ this.where = where;
260
+ this.overrides = overrides;
261
+ this.parks = parks;
262
+ this.approvers = approvers;
263
+ }
264
+ /** A tool's permission now (permissionOf): the revision's own over the server's setting, read at each call, so a change
265
+ * reaches a live run at its next call. */
266
+ policy = (tool) => {
267
+ const key = settingsKeyOf(this.where.harness ?? "pi", tool, this.where.mcpServers);
268
+ // A name nothing maps fails closed: it asks (refused where no one can approve), never allows.
269
+ if (key === undefined)
270
+ return "ask";
271
+ const server = this.serverSettings();
272
+ // No settings ever read: every tool asks, the shell watchers too (fail closed: an ask nothing read is never lifted),
273
+ // or keeps the revision's own deny.
274
+ if (server === undefined)
275
+ return permissionOf(key, {}, this.overrides) === "deny" ? "deny" : "ask";
276
+ // A shell tool under every harness's name for it is read as its own name, by bash's key (permissionFrom): a watcher's
277
+ // ask is allow only where bash's ask is set as written.
278
+ return permissionOf(shellToolOf(tool) ?? key, server, this.overrides);
279
+ };
280
+ lastGood;
281
+ told = new Set();
282
+ /** The server's settings now: read at each call, so a change reaches a live run; a file that does not read keeps the
283
+ * last good (undefined: none read yet). Each problem is said once, by file and field, never a value. */
284
+ serverSettings() {
285
+ const read = readToolSettings(this.where.data);
286
+ for (const line of read.problems) {
287
+ if (this.told.has(line))
288
+ continue;
289
+ this.told.add(line);
290
+ process.stderr.write(`agentrun-serve: the tool gate: ${line}\n`);
291
+ }
292
+ if (read.unreadable)
293
+ return this.lastGood;
294
+ this.lastGood = read.settings;
295
+ return this.lastGood;
296
+ }
297
+ /** The origin of the turn running now: what the server's internal path wrote for it; none for a person's turn. */
298
+ turnOrigin() {
299
+ try {
300
+ return JSON.parse(readFileSync(join(this.where.root, TURN_ORIGIN_FILE), "utf8"))?.origin === "reflect" ? "reflect" : undefined;
301
+ }
302
+ catch {
303
+ return undefined;
304
+ }
305
+ }
306
+ /** One model-initiated call at the gate: undefined when it may run; else its answer, refused at once (deny) or parked
307
+ * (ask). One call waits at a time: another asked meanwhile is answered so, not run. */
308
+ async enter(name, args, callId, park, options = {}) {
309
+ // Held to its settings key (settingsKeyOf), the name its request, a refusal and the approved call give; a shell tool
310
+ // held to bash's (SHELL_FAMILY) keeps its own name, so an approved bash_background runs bash_background, never bash.
311
+ const key = settingsKeyOf(this.where.harness ?? "pi", name, this.where.mcpServers) ?? name;
312
+ const tool = shellToolOf(name) ?? key;
313
+ // The end-of-run turn writes no file under work/.learning/, whatever the tool's permission: its notes are kept only
314
+ // from its answer (NOTE_ONLY_TEXT). Any other turn's write there follows its permission, as anywhere.
315
+ if ((key === "write" || key === "edit") && this.turnOrigin() === "reflect" && underLearning(this.where.work, args))
316
+ return { text: NOTE_ONLY_TEXT, isError: true };
317
+ const verdict = this.policy(name);
318
+ if (verdict === "allow")
319
+ return undefined;
320
+ if (verdict === "deny")
321
+ return { text: deniedText(tool, key), isError: true };
322
+ // No one can answer here: refused at once with why, never parked until a cancel.
323
+ if (!this.approvers)
324
+ return { text: noApproverText(tool), isError: true };
325
+ if (!this.parks)
326
+ return { text: `This ${tool} call needs a person's approval, which a workflow's model node cannot wait for; it was not run.`, isError: true };
327
+ // Named by the call, so a call run again after a crash parks as the same request.
328
+ const id = `ap_${createHash("sha256").update(JSON.stringify([callId, tool, args ?? null])).digest("hex").slice(0, 16)}`;
329
+ const other = [...this.requests.values()].find((held) => !held.resolved && held.id !== id);
330
+ if (other)
331
+ return { text: `This ${tool} call was not run: the ${other.tool} call ${other.call_id} already waits for a person's approval. Call it again once that one is answered.`, isError: true };
332
+ if (!this.requests.has(id)) {
333
+ const turn = park.turn?.();
334
+ const request = { id, tool, call_id: callId, args: args ?? null, args_preview: argsPreview(args), requested_at: new Date().toISOString(), ...(turn !== undefined ? { turn } : {}), ...(options.price !== undefined ? { price: options.price } : {}) };
335
+ // Held before the commit's await, in the tick of the look above: pi runs a turn's calls in parallel, and an ask
336
+ // entered meanwhile finds this one and is refused. A commit that fails lets it go.
337
+ this.requests.set(id, request);
338
+ try {
339
+ await park.commit((tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: APPROVAL_ENTRY, data: { phase: "requested", ...request } }));
340
+ }
341
+ catch (error) {
342
+ this.requests.delete(id);
343
+ throw error;
344
+ }
345
+ }
346
+ park.parked?.(callId);
347
+ this.watch();
348
+ return { text: waitingText(tool), isError: false, parked: true };
349
+ }
350
+ /** pi's `tools` behind the gate: wraps, by name, for the run's registry, which apply wherever it is selected (every
351
+ * agent selects it: the root by default, a workflow's model node by name, app.ts). */
352
+ extension(tools) {
353
+ // Every tool is wrapped, an mcp__ name too, except a registration marked GATED_BY_GATEWAY: the MCP gateway marks the
354
+ // ones whose calls it takes to this gate itself (gate.enter in its call), so such a call passes one gate, once. Nothing
355
+ // is skipped by its name: an unmarked mcp__ tool is gated here as any tool is.
356
+ const named = [...new Map(tools.filter((tool) => tool[GATED_BY_GATEWAY] !== true).map((tool) => [tool.name, tool])).values()];
357
+ return defineExtension({ name: "tool-gate", wraps: named.map((tool) => wrapTool(tool, (inner) => this.wrap(inner))) });
358
+ }
359
+ wrap(tool) {
360
+ const gate = this;
361
+ return {
362
+ ...tool,
363
+ async execute(args, api, context) {
364
+ const answer = await gate.enter(tool.name, args, api.callId, { commit: (change) => api.commit(change, context) });
365
+ // A parked call ends the turn, as ask_person's does.
366
+ if (answer)
367
+ return forModel(answer.text, answer.parked ? { control: { terminate: true } } : { isError: true });
368
+ return tool.execute(args, api, context);
369
+ },
370
+ };
371
+ }
372
+ /** Reads the requests the run's store holds, as the run's process opens, before its turns go on. `coding`: the run's
373
+ * coding source (coding-tools.ts), on which an approved coding call runs, as the run's own would; `extra`, the run's
374
+ * own tools beyond the table (its learned_workflow), on which an approved call of one runs. */
375
+ async load(durable, context, coding, extra = []) {
376
+ this.durable = durable;
377
+ this.context = context;
378
+ this.coding = coding;
379
+ this.extra = extra;
380
+ const root = await durable.harness.conversation(ROOT_CONVERSATION_ID, context);
381
+ for (let cursor; root;) {
382
+ const page = await root.entries({ order: "ascending" }, 500, cursor, context);
383
+ for (const entry of page.items)
384
+ this.note(entry);
385
+ if (page.next === undefined)
386
+ break;
387
+ cursor = page.next;
388
+ }
389
+ }
390
+ /** Whether a call waits for its answer, or for its answer to be acted on: a harness keeps the turn it ended closed. */
391
+ waiting() {
392
+ return [...this.requests.values()].some((held) => !held.resolved);
393
+ }
394
+ /** Whether a call of the turn that took `message` was parked, answered or not: that turn ended at the park, though a
395
+ * process that went before the next open settled it leaves it open in its session. */
396
+ parkedIn(message) {
397
+ return message !== undefined && [...this.requests.values()].some((held) => held.turn === message);
398
+ }
399
+ /** Acts on the answers from now on, resuming the session through `resume`; by default pi's root conversation. */
400
+ start(resume) {
401
+ this.resume = resume ?? this.submit;
402
+ this.watch();
403
+ }
404
+ note(entry) {
405
+ const data = entry.data;
406
+ if (entry.kind !== APPROVAL_ENTRY || typeof data?.id !== "string")
407
+ return;
408
+ const held = this.requests.get(data.id);
409
+ if (data.phase === "requested" && !held)
410
+ this.requests.set(data.id, data);
411
+ else if (data.phase === "resolved" && held)
412
+ held.resolved = true;
413
+ }
414
+ /** Reads the run's serve.json for answers while a call waits. */
415
+ watch() {
416
+ if (this.timer || !this.resume || !this.waiting())
417
+ return;
418
+ this.timer = setInterval(() => void this.settle(), 250);
419
+ this.timer.unref();
420
+ void this.settle();
421
+ }
422
+ /** pi's resume: an input to the root conversation under the request's own id, which pi takes once however often it
423
+ * is sent, then the mark. */
424
+ submit = async (id, content, mark) => {
425
+ const root = await this.durable.harness.root(this.context);
426
+ await root.submit({ type: "input", requestId: `approval-${id}`, content, whenBusy: "followUp" }, this.context);
427
+ await this.durable.harness.commit(mark, this.context);
428
+ };
429
+ async settle() {
430
+ // Acting on an answer already: an approved call may be in flight, which a stop or a cancel since cuts.
431
+ if (this.settling)
432
+ return void this.cutIfWithdrawn().catch(() => undefined);
433
+ const open = [...this.requests.values()].filter((held) => !held.resolved);
434
+ if (!open.length) {
435
+ clearInterval(this.timer);
436
+ this.timer = undefined;
437
+ return;
438
+ }
439
+ this.settling = true;
440
+ try {
441
+ const answers = (await readJson(join(this.where.root, RUN_META)))?.approvals;
442
+ for (const held of open) {
443
+ const answer = answers?.[held.id];
444
+ // Withdrawn with its run (a cancel, or a stop while it waited): never run and nothing resumed; resolved, so the
445
+ // run waits on it no more.
446
+ if (answer?.decision === "canceled" || answer?.decision === "withdrawn") {
447
+ await this.resolveSilently(held, answer.decision);
448
+ continue;
449
+ }
450
+ if (answer?.decision !== "allow" && answer?.decision !== "deny")
451
+ continue;
452
+ const decision = answer.decision;
453
+ // Read again just before acting: a stop or a cancel since overrides the answer (runs.ts supersede), and then
454
+ // nothing runs and nothing resumes. Once the call's intent is written, a stop takes its turn as any stop does.
455
+ const now = (await readJson(join(this.where.root, RUN_META)))?.approvals?.[held.id];
456
+ if (now?.decision !== decision) {
457
+ if (now?.decision === "canceled" || now?.decision === "withdrawn")
458
+ await this.resolveSilently(held, now.decision);
459
+ continue;
460
+ }
461
+ // An allow runs the call, unless its tool was set to deny since it asked.
462
+ const result = decision === "deny" ? { text: refusedText(held.tool, answer.note), isError: true } : this.policy(held.tool) === "deny" ? { text: deniedText(held.tool, settingsKeyOf(this.where.harness ?? "pi", held.tool, this.where.mcpServers)), isError: true } : await this.run(held);
463
+ // And again once the call is done: a stop or a cancel while it ran drops its result, which never reaches the model.
464
+ const after = (await readJson(join(this.where.root, RUN_META)))?.approvals?.[held.id];
465
+ if (after?.decision === "canceled" || after?.decision === "withdrawn") {
466
+ await this.resolveSilently(held, after.decision);
467
+ continue;
468
+ }
469
+ // The arguments the message names are the server's redacted ones: the gate never writes a held value there. The
470
+ // result is cut as every host tool's is (boundResult, HOST_RESULT_MAX_CHARS, in its words): an executor's (an
471
+ // MCP call's) comes uncut, and its journal keeps it whole.
472
+ await this.resume(held.id, resumeText(held, answer.args_shown ?? "(not shown)", decision, { ...result, text: boundResult(result.text).text }), (tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: APPROVAL_ENTRY, data: { phase: "resolved", id: held.id, decision } }));
473
+ held.resolved = true;
474
+ }
475
+ }
476
+ catch (error) {
477
+ // Tried again at the next tick: the call's effect answers from its journal, and the resume is taken once.
478
+ process.stderr.write(`agentrun-serve: an answered approval is not acted on yet: ${error?.message ?? error}\n`);
479
+ }
480
+ finally {
481
+ this.settling = false;
482
+ }
483
+ }
484
+ /** The approved call in flight, and its own abort: a stop or a cancel of the run cuts it (cutIfWithdrawn). */
485
+ inFlight;
486
+ /** Cuts the approved call in flight when a stop or a cancel since withdrew its answer (runs.ts supersede). */
487
+ async cutIfWithdrawn() {
488
+ const flying = this.inFlight;
489
+ if (!flying || flying.cut.signal.aborted)
490
+ return;
491
+ const now = (await readJson(join(this.where.root, RUN_META)))?.approvals?.[flying.id];
492
+ if (now?.decision === "canceled" || now?.decision === "withdrawn")
493
+ flying.cut.abort(new Error(INTERRUPTED_TEXT));
494
+ }
495
+ /** A call withdrawn with its run: resolved in the run's store with nothing run and nothing resumed. */
496
+ async resolveSilently(held, decision) {
497
+ await this.durable.harness.commit((tx) => tx.appendEntry(ROOT_CONVERSATION_ID, { kind: APPROVAL_ENTRY, data: { phase: "resolved", id: held.id, decision } }), this.context);
498
+ held.resolved = true;
499
+ }
500
+ /** The approved call, run once by the kernel through the journal any host tool's call goes through, as an effect of
501
+ * the run's own `approvals:` session, on the run's coding source: its intent is durable before it runs, its outcome
502
+ * after; a replay-safe call a crash cut off runs again, any other is answered interrupted and never runs again. */
503
+ async run(held) {
504
+ const runner = await this.runnerOf(held);
505
+ if ("refused" in runner)
506
+ return { text: runner.refused, isError: true };
507
+ this.drive ??= durableSessions(this.durable.harness, this.context)
508
+ .open(`approvals:${this.where.runId}`)
509
+ .then((writer) => openDrive({ writer, signal: this.stop.signal }))
510
+ .catch((error) => {
511
+ this.drive = undefined;
512
+ throw error;
513
+ });
514
+ try {
515
+ // Its own abort beside the drive's: a stop or a cancel of the run cuts this call, which runs outside any turn.
516
+ const cut = new AbortController();
517
+ this.inFlight = { id: held.id, cut };
518
+ try {
519
+ return await (await this.drive).effect(`approval:${held.id}`, { name: held.tool, replay: runner.replay, input: held.args }, async ({ signal }) => {
520
+ try {
521
+ const answer = await runner.call(AbortSignal.any([signal, cut.signal]));
522
+ // A host tool answers its own abort as an error result: still the stop's cut.
523
+ if (cut.signal.aborted)
524
+ throw new Error(INTERRUPTED_TEXT);
525
+ return { text: answer.text, isError: answer.isError === true };
526
+ }
527
+ catch (error) {
528
+ // Cut by a stop: its journal answers it interrupted, as a crash's cut call is.
529
+ if (cut.signal.aborted)
530
+ throw new Error(INTERRUPTED_TEXT);
531
+ throw error;
532
+ }
533
+ });
534
+ }
535
+ finally {
536
+ this.inFlight = undefined;
537
+ }
538
+ }
539
+ catch (error) {
540
+ // Its outcome (interrupted, or a throw), journaled; anything else (the drive fenced) is tried again.
541
+ if (error instanceof EffectFailure)
542
+ return { text: error.message, isError: true };
543
+ throw error;
544
+ }
545
+ }
546
+ executors = new Map();
547
+ /** Registers how an approved call of tools named `prefix…` runs (the MCP gateway's, "mcp:"): one per prefix and run.
548
+ * The gate runs it exactly once on its journaled path, as it runs a kernel host tool, with no deadline of its own: the
549
+ * executor bounds the call (Executor). */
550
+ executor(prefix, run) {
551
+ this.executors.set(prefix, run);
552
+ }
553
+ /** What runs an approved call: the executor its tool's prefix names, which may have effects anywhere, so a call a
554
+ * crash cut off is never run again; else the kernel's host tool of the name, as replay-safe as that tool is. Neither:
555
+ * refused, in words, and never run. */
556
+ async runnerOf(held) {
557
+ const prefix = [...this.executors.keys()].find((given) => held.tool.startsWith(given));
558
+ if (prefix) {
559
+ const executor = this.executors.get(prefix);
560
+ return { replay: "never", call: (signal) => executor(held.tool, held.args, held.call_id, signal) };
561
+ }
562
+ if (isMcpTool(held.tool))
563
+ return { refused: `The approved ${held.tool} call was not run: nothing in this run runs mcp: calls.` };
564
+ // Imported here, not at the top: host-tools reaches the web tools, which reach tool-plane, which reads this module's
565
+ // permission rule, and a cycle of top-level imports leaves one of them uninitialized for whichever loads first.
566
+ const { hostTools } = await import("./host-tools.js");
567
+ const [tool] = hostTools(this.durable, [held.tool], this.context, new Map(), this.coding, undefined, this.extra);
568
+ if (!tool)
569
+ return { refused: `The approved ${held.tool} call is not one the kernel runs outside the model's turn.` };
570
+ return { replay: tool.replay, call: (signal) => tool.call(held.args, { callId: held.call_id, signal }) };
571
+ }
572
+ }
573
+ /** `value` as JSON with every object's keys sorted, so the same arguments are the same text however they were built. */
574
+ const canonical = (value) => Array.isArray(value) ? `[${value.map(canonical).join(",")}]` : value !== null && typeof value === "object" ? `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}` : (JSON.stringify(value) ?? "null");
575
+ /** The digest a park by tool and arguments is matched on: the sha256 of the arguments' canonical JSON, in hex. */
576
+ export const argsDigest = (args) => createHash("sha256").update(canonical(args ?? {})).digest("hex");
577
+ /** Whether the tool result `result` ends the turn `parked` waits in (harness-app.ts asks it at each one): the parked
578
+ * call's own, by its id; or, for a park by tool and arguments, the next result of that tool with those arguments. */
579
+ export function endsTurn(parked, result) {
580
+ if (!parked)
581
+ return false;
582
+ if ("callId" in parked)
583
+ return parked.callId === result.callId;
584
+ return parked.tool === result.tool && parked.argsDigest === argsDigest(result.args);
585
+ }