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