@parcha/agentrun-serve 0.0.0-stage → 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.
Files changed (273) hide show
  1. package/CHANGELOG.md +748 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/README.md +2190 -2
  5. package/dist/adapters.d.ts +234 -0
  6. package/dist/adapters.js +585 -0
  7. package/dist/agents.d.ts +130 -0
  8. package/dist/agents.js +308 -0
  9. package/dist/app.d.ts +7 -0
  10. package/dist/app.js +384 -0
  11. package/dist/background.d.ts +28 -0
  12. package/dist/background.js +376 -0
  13. package/dist/bound-files.d.ts +4 -0
  14. package/dist/bound-files.js +164 -0
  15. package/dist/box/record.d.ts +6 -0
  16. package/dist/box/record.js +41 -0
  17. package/dist/box/sweep.d.ts +53 -0
  18. package/dist/box/sweep.js +193 -0
  19. package/dist/box-egress.d.ts +98 -0
  20. package/dist/box-egress.js +259 -0
  21. package/dist/box-image.d.ts +98 -0
  22. package/dist/box-image.js +285 -0
  23. package/dist/box-relay-vm.d.ts +80 -0
  24. package/dist/box-relay-vm.js +389 -0
  25. package/dist/box-relay.d.ts +45 -0
  26. package/dist/box-relay.js +227 -0
  27. package/dist/boxes.d.ts +72 -0
  28. package/dist/boxes.js +189 -0
  29. package/dist/browser-cost.d.ts +41 -0
  30. package/dist/browser-cost.js +158 -0
  31. package/dist/cap.d.ts +332 -0
  32. package/dist/cap.js +992 -0
  33. package/dist/catalog.d.ts +20 -0
  34. package/dist/catalog.js +53 -0
  35. package/dist/cli.d.ts +2 -0
  36. package/dist/cli.js +167 -0
  37. package/dist/coding-tools.d.ts +35 -0
  38. package/dist/coding-tools.js +87 -0
  39. package/dist/console/THIRD-PARTY-NOTICES.txt +1721 -0
  40. package/dist/console/assets/index-34jfpIbQ.js +481 -0
  41. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  42. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  43. package/dist/console/assets/jetbrains-mono-cyrillic-400-normal-CIEtRijs.woff +0 -0
  44. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-BB5xRk30.woff +0 -0
  45. package/dist/console/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
  46. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-BHyURHCj.woff +0 -0
  47. package/dist/console/assets/jetbrains-mono-cyrillic-ext-400-normal-C_uLvvQ5.woff2 +0 -0
  48. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-Dj6eZy5f.woff2 +0 -0
  49. package/dist/console/assets/jetbrains-mono-cyrillic-ext-600-normal-DpeVePZf.woff +0 -0
  50. package/dist/console/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  51. package/dist/console/assets/jetbrains-mono-greek-400-normal-CNojz0t3.woff +0 -0
  52. package/dist/console/assets/jetbrains-mono-greek-600-normal-3KAm9r92.woff +0 -0
  53. package/dist/console/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
  54. package/dist/console/assets/jetbrains-mono-latin-400-normal-B11XCQ5g.woff +0 -0
  55. package/dist/console/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  56. package/dist/console/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
  57. package/dist/console/assets/jetbrains-mono-latin-600-normal-DXv3JcnD.woff +0 -0
  58. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  59. package/dist/console/assets/jetbrains-mono-latin-ext-400-normal-DHMOLxAi.woff +0 -0
  60. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
  61. package/dist/console/assets/jetbrains-mono-latin-ext-600-normal-DiQlUoE6.woff +0 -0
  62. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-BeU3T8wf.woff +0 -0
  63. package/dist/console/assets/jetbrains-mono-vietnamese-400-normal-ByoDsISC.woff2 +0 -0
  64. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-CSpzN4cI.woff +0 -0
  65. package/dist/console/assets/jetbrains-mono-vietnamese-600-normal-Dtizs43-.woff2 +0 -0
  66. package/dist/console/assets/schibsted-grotesk-latin-400-normal-Cph9ettZ.woff2 +0 -0
  67. package/dist/console/assets/schibsted-grotesk-latin-400-normal-DfGZKnlb.woff +0 -0
  68. package/dist/console/assets/schibsted-grotesk-latin-600-normal-BGBUNdzT.woff2 +0 -0
  69. package/dist/console/assets/schibsted-grotesk-latin-600-normal-COje25QW.woff +0 -0
  70. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-4l4lq8zr.woff2 +0 -0
  71. package/dist/console/assets/schibsted-grotesk-latin-ext-400-normal-BGzXWJeR.woff +0 -0
  72. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-8_E36CQj.woff2 +0 -0
  73. package/dist/console/assets/schibsted-grotesk-latin-ext-600-normal-C27an7Zc.woff +0 -0
  74. package/dist/console/index.html +15 -0
  75. package/dist/content-filter.d.ts +7 -0
  76. package/dist/content-filter.js +23 -0
  77. package/dist/daytona-api.d.ts +21 -0
  78. package/dist/daytona-api.js +101 -0
  79. package/dist/decision-rows.d.ts +19 -0
  80. package/dist/decision-rows.js +123 -0
  81. package/dist/decisions.d.ts +94 -0
  82. package/dist/decisions.js +184 -0
  83. package/dist/effort-guidance.d.ts +5 -0
  84. package/dist/effort-guidance.js +14 -0
  85. package/dist/environment.d.ts +5 -0
  86. package/dist/environment.js +11 -0
  87. package/dist/errors.d.ts +74 -0
  88. package/dist/errors.js +69 -0
  89. package/dist/exa-keyless.d.ts +35 -0
  90. package/dist/exa-keyless.js +202 -0
  91. package/dist/fetch-page.d.ts +114 -0
  92. package/dist/fetch-page.js +182 -0
  93. package/dist/files.d.ts +65 -0
  94. package/dist/files.js +158 -0
  95. package/dist/grade.d.ts +93 -0
  96. package/dist/grade.js +328 -0
  97. package/dist/graph-served.d.ts +23 -0
  98. package/dist/graph-served.js +75 -0
  99. package/dist/graph-view.d.ts +102 -0
  100. package/dist/graph-view.js +219 -0
  101. package/dist/harness-app.d.ts +40 -0
  102. package/dist/harness-app.js +708 -0
  103. package/dist/harness-opencode/adapter.d.ts +45 -0
  104. package/dist/harness-opencode/adapter.js +272 -0
  105. package/dist/harness-opencode/binary.d.ts +18 -0
  106. package/dist/harness-opencode/binary.js +87 -0
  107. package/dist/harness-opencode/config.d.ts +24 -0
  108. package/dist/harness-opencode/config.js +61 -0
  109. package/dist/harness-opencode/harness.d.ts +77 -0
  110. package/dist/harness-opencode/harness.js +620 -0
  111. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  112. package/dist/harness-opencode/host/mcp.js +208 -0
  113. package/dist/harness-opencode/host/policy.d.ts +71 -0
  114. package/dist/harness-opencode/host/policy.js +419 -0
  115. package/dist/harness-opencode/host/server.d.ts +55 -0
  116. package/dist/harness-opencode/host/server.js +165 -0
  117. package/dist/harness-opencode/index.d.ts +9 -0
  118. package/dist/harness-opencode/index.js +6 -0
  119. package/dist/harness-opencode/verify.d.ts +32 -0
  120. package/dist/harness-opencode/verify.js +75 -0
  121. package/dist/harness-opencode/versions.d.ts +33 -0
  122. package/dist/harness-opencode/versions.js +64 -0
  123. package/dist/harness.d.ts +56 -0
  124. package/dist/harness.js +77 -0
  125. package/dist/home-path.d.ts +27 -0
  126. package/dist/home-path.js +78 -0
  127. package/dist/host-tools.d.ts +30 -0
  128. package/dist/host-tools.js +154 -0
  129. package/dist/host.d.ts +39 -0
  130. package/dist/host.js +85 -0
  131. package/dist/hosted-search.d.ts +27 -0
  132. package/dist/hosted-search.js +133 -0
  133. package/dist/import-sources.d.ts +104 -0
  134. package/dist/import-sources.js +629 -0
  135. package/dist/import-summary.d.ts +25 -0
  136. package/dist/import-summary.js +75 -0
  137. package/dist/import-worker.d.ts +26 -0
  138. package/dist/import-worker.js +41 -0
  139. package/dist/import.d.ts +145 -0
  140. package/dist/import.js +1222 -0
  141. package/dist/index.d.ts +7 -0
  142. package/dist/index.js +6 -0
  143. package/dist/key-check.d.ts +37 -0
  144. package/dist/key-check.js +112 -0
  145. package/dist/key-refusal.d.ts +51 -0
  146. package/dist/key-refusal.js +191 -0
  147. package/dist/learn/check.d.ts +108 -0
  148. package/dist/learn/check.js +277 -0
  149. package/dist/learn/grade.d.ts +80 -0
  150. package/dist/learn/grade.js +445 -0
  151. package/dist/learn/index.d.ts +7 -0
  152. package/dist/learn/index.js +11 -0
  153. package/dist/learn/invisible.d.ts +5 -0
  154. package/dist/learn/invisible.js +42 -0
  155. package/dist/learn/notes.d.ts +59 -0
  156. package/dist/learn/notes.js +147 -0
  157. package/dist/learn/reflect.d.ts +49 -0
  158. package/dist/learn/reflect.js +213 -0
  159. package/dist/learn/secrets.d.ts +18 -0
  160. package/dist/learn/secrets.js +131 -0
  161. package/dist/learn/skills.d.ts +97 -0
  162. package/dist/learn/skills.js +271 -0
  163. package/dist/learned-workflow.d.ts +59 -0
  164. package/dist/learned-workflow.js +191 -0
  165. package/dist/learning-routes.d.ts +196 -0
  166. package/dist/learning-routes.js +609 -0
  167. package/dist/learning-run.d.ts +306 -0
  168. package/dist/learning-run.js +819 -0
  169. package/dist/learning-words.d.ts +76 -0
  170. package/dist/learning-words.js +174 -0
  171. package/dist/learning.d.ts +418 -0
  172. package/dist/learning.js +946 -0
  173. package/dist/llm.d.ts +40 -0
  174. package/dist/llm.js +37 -0
  175. package/dist/llms.txt +37 -0
  176. package/dist/mcp-servers.d.ts +118 -0
  177. package/dist/mcp-servers.js +450 -0
  178. package/dist/mcp.d.ts +51 -0
  179. package/dist/mcp.js +392 -0
  180. package/dist/model.d.ts +186 -0
  181. package/dist/model.js +485 -0
  182. package/dist/monid.d.ts +74 -0
  183. package/dist/monid.js +277 -0
  184. package/dist/openapi/agentrun-v2.openapi.json +4806 -0
  185. package/dist/openapi.d.ts +10 -0
  186. package/dist/openapi.js +1727 -0
  187. package/dist/owner.d.ts +55 -0
  188. package/dist/owner.js +222 -0
  189. package/dist/packs.d.ts +71 -0
  190. package/dist/packs.js +180 -0
  191. package/dist/page.d.ts +32 -0
  192. package/dist/page.js +133 -0
  193. package/dist/paid-calls.d.ts +50 -0
  194. package/dist/paid-calls.js +110 -0
  195. package/dist/pause.d.ts +70 -0
  196. package/dist/pause.js +97 -0
  197. package/dist/pdf-pages.d.ts +44 -0
  198. package/dist/pdf-pages.js +147 -0
  199. package/dist/place.d.ts +69 -0
  200. package/dist/place.js +137 -0
  201. package/dist/print.d.ts +20 -0
  202. package/dist/print.js +29 -0
  203. package/dist/propose.d.ts +40 -0
  204. package/dist/propose.js +112 -0
  205. package/dist/quiet-sqlite-warning.d.ts +1 -0
  206. package/dist/quiet-sqlite-warning.js +14 -0
  207. package/dist/request-start.d.ts +22 -0
  208. package/dist/request-start.js +350 -0
  209. package/dist/result.d.ts +3 -0
  210. package/dist/result.js +5 -0
  211. package/dist/rows.d.ts +46 -0
  212. package/dist/rows.js +121 -0
  213. package/dist/run-box.d.ts +186 -0
  214. package/dist/run-box.js +590 -0
  215. package/dist/run-manifest.d.ts +27 -0
  216. package/dist/run-manifest.js +60 -0
  217. package/dist/runnable.d.ts +83 -0
  218. package/dist/runnable.js +170 -0
  219. package/dist/runs.d.ts +1062 -0
  220. package/dist/runs.js +3020 -0
  221. package/dist/secret-cut.d.ts +27 -0
  222. package/dist/secret-cut.js +109 -0
  223. package/dist/secrets.d.ts +62 -0
  224. package/dist/secrets.js +158 -0
  225. package/dist/server-lock.d.ts +44 -0
  226. package/dist/server-lock.js +140 -0
  227. package/dist/server.d.ts +722 -0
  228. package/dist/server.js +2118 -0
  229. package/dist/sessions.d.ts +4 -0
  230. package/dist/sessions.js +105 -0
  231. package/dist/sign-ins.d.ts +99 -0
  232. package/dist/sign-ins.js +288 -0
  233. package/dist/skills.d.ts +43 -0
  234. package/dist/skills.js +96 -0
  235. package/dist/stats.d.ts +106 -0
  236. package/dist/stats.js +103 -0
  237. package/dist/tool-gate.d.ts +266 -0
  238. package/dist/tool-gate.js +554 -0
  239. package/dist/tool-keys.d.ts +187 -0
  240. package/dist/tool-keys.js +315 -0
  241. package/dist/tool-plane.d.ts +228 -0
  242. package/dist/tool-plane.js +400 -0
  243. package/dist/tools.d.ts +202 -0
  244. package/dist/tools.js +372 -0
  245. package/dist/trigger-secrets.d.ts +32 -0
  246. package/dist/trigger-secrets.js +143 -0
  247. package/dist/triggers.d.ts +439 -0
  248. package/dist/triggers.js +863 -0
  249. package/dist/turn-end.d.ts +24 -0
  250. package/dist/turn-end.js +15 -0
  251. package/dist/turns.d.ts +34 -0
  252. package/dist/turns.js +202 -0
  253. package/dist/uploads.d.ts +104 -0
  254. package/dist/uploads.js +474 -0
  255. package/dist/usage-lines.d.ts +26 -0
  256. package/dist/usage-lines.js +28 -0
  257. package/dist/usage.d.ts +29 -0
  258. package/dist/usage.js +58 -0
  259. package/dist/validate.d.ts +57 -0
  260. package/dist/validate.js +184 -0
  261. package/dist/web-fetch.d.ts +64 -0
  262. package/dist/web-fetch.js +262 -0
  263. package/dist/web-search.d.ts +54 -0
  264. package/dist/web-search.js +136 -0
  265. package/dist/webhooks.d.ts +189 -0
  266. package/dist/webhooks.js +503 -0
  267. package/dist/workspace-paths.d.ts +33 -0
  268. package/dist/workspace-paths.js +104 -0
  269. package/dist/workspace.d.ts +88 -0
  270. package/dist/workspace.js +369 -0
  271. package/launcher/agentrun-serve +109 -0
  272. package/package.json +100 -4
  273. package/skills/agentrun-serve/SKILL.md +128 -0
@@ -0,0 +1,202 @@
1
+ import type { TSchema } from "@earendil-works/pi-ai";
2
+ import { type Extension, type Harness, type ToolRegistration, type Tx } from "@earendil-works/pi-durable";
3
+ import type { AppContext } from "@parcha/pi-durable-disk";
4
+ import type { Revision } from "@parcha/pi-durable-agent";
5
+ import type { CodingSource } from "./coding-tools.js";
6
+ import { type Complete } from "./llm.js";
7
+ import { type Ledger } from "./paid-calls.js";
8
+ import { type Plane, type Tooling, type ToolSettingsMap } from "./tool-plane.js";
9
+ export declare const ASK_TOOL = "ask_person";
10
+ /** Under `--faux` only: a module whose default export gives the browser's `{ provider, driver }` for the run's
11
+ * environment, the vendor its plane names (`browserbase`, `kernel`) and the saved sign-in it was handed for that
12
+ * vendor (`{ provider, ref, save }`, or undefined), in place of that vendor's (the tests' fake backend). */
13
+ export declare const FAUX_BROWSER_ENV = "AGENTRUN_SERVE_FAUX_BROWSER";
14
+ /** What the result of `ask_person` says; the person's page shows the question as a waiting row. */
15
+ export declare const asked: (question: string) => string;
16
+ export declare const askPerson: ToolRegistration<TSchema, import("@earendil-works/chord").JsonValue>;
17
+ /** What a tool's binding gets from the run's process. */
18
+ export type ToolHost = {
19
+ where: AppContext;
20
+ /** The run's environment: the server's, without the server's token. */
21
+ env: NodeJS.ProcessEnv;
22
+ /** The run's coding tools, by its place (coding-tools.ts codingSource). */
23
+ coding: CodingSource;
24
+ /** Installs an extension in the run's registry, before the run opens. */
25
+ install(extension: Extension): void;
26
+ /** Runs in the commit that creates each of the run's conversations. */
27
+ onConversation(write: (tx: Tx, conversationId: number) => void | Promise<void>): void;
28
+ /** Runs once the run's Harness is open, before anything in it resumes. */
29
+ beforeResume(settle: (harness: Harness) => void | Promise<void>): void;
30
+ /** Runs when the run's process lets the run go (its work done, or a SIGTERM), while the Harness is still open. */
31
+ beforeRelease(stop: (harness: Harness) => void | Promise<void>): void;
32
+ };
33
+ /** What a name stands for in the run: the pi tools it offers, and the extensions a conversation selects for them. */
34
+ export type ToolBinding = {
35
+ tools: readonly ToolRegistration[];
36
+ extensions: readonly Extension[];
37
+ };
38
+ /** What a call node's effect gets from the run's process: its signal, environment and work directory, one completion
39
+ * on the run's models (the `llm` tool's), and the ledger its paid requests are booked in (paid-calls.ts). */
40
+ export type EffectRun = {
41
+ signal: AbortSignal;
42
+ env: NodeJS.ProcessEnv;
43
+ work: string;
44
+ complete?: Complete;
45
+ ledger?: Ledger;
46
+ };
47
+ export type ToolEntry = {
48
+ /** One line, for capabilities. */
49
+ summary: string;
50
+ /** The environment variables it needs, by name. */
51
+ needs: readonly string[];
52
+ /** Whether a workflow's model node may name it. */
53
+ nodes: boolean;
54
+ /** What the name stands for, bound in the run's process once. */
55
+ bind(host: ToolHost): Promise<ToolBinding>;
56
+ /** What a workflow's `call` node `via: "tool"` naming it runs: its interpolated `args` in, the value its `out` schema
57
+ * checks out. Absent, no call node may name it. */
58
+ effect?(args: Record<string, unknown>, run: EffectRun): Promise<unknown>;
59
+ /** Only a workflow's call node runs it: no agent and no model node may name it. */
60
+ callOnly?: true;
61
+ /** Only an agent whose place is a sandbox may name it: it runs in the box (runnable.ts). */
62
+ sandboxOnly?: true;
63
+ /** No agent whose place is a sandbox may name it: it writes the run's work/ from this machine by paths a box's command
64
+ * could turn through a link (runnable.ts). */
65
+ runnerOnly?: true;
66
+ };
67
+ /** Where the browser files what it reads: `work/evidence/`, so the run's files show it and the agent can read it back. A
68
+ * text body follows one line of the read's facts; a capture's bytes go beside its facts. Each read takes the next free
69
+ * number, reserved by an exclusive create, so reads at once (parallel nodes, one turn's calls) and the reads of a later
70
+ * process never overwrite one another. */
71
+ export declare const evidenceIn: (work: string) => {
72
+ file: (label: string, record: {
73
+ tool: string;
74
+ facts: Record<string, unknown>;
75
+ body: string | Uint8Array;
76
+ ext?: string;
77
+ }) => Promise<{
78
+ path: string;
79
+ bodyLine: number;
80
+ bodyPath?: undefined;
81
+ } | {
82
+ path: string;
83
+ bodyPath: string;
84
+ bodyLine?: undefined;
85
+ }>;
86
+ };
87
+ /** The Browserbase contexts a run's browser may open: its agent's saved sign-in's alone, by its profile name, never one
88
+ * made here (nothing a run makes is kept for its agent). */
89
+ export declare const keptContexts: (ref: string | undefined) => {
90
+ clear: boolean;
91
+ resolve: (key: string) => Promise<string>;
92
+ };
93
+ /** Kernel's provider, opening the agent's saved profile (`ref`, its name at Kernel) where a session asks for the
94
+ * profile `default`: the policy, the session's record and the model see only that name. */
95
+ export declare const keptProfile: <P extends {
96
+ create(spec: {
97
+ profile?: {
98
+ name: string;
99
+ save: boolean;
100
+ };
101
+ }, signal: AbortSignal): unknown;
102
+ }>(provider: P, ref: string) => P;
103
+ /** `provider`, its sessions' profile as this launch was handed it, whatever the policy a conversation was made with (a
104
+ * follow-up's was made under an earlier launch, which may have had no sign-in, or another lease): with a sign-in, every
105
+ * session opens on the profile `default`, saving only as `kept.save` says; without one, none asks for a profile. */
106
+ export declare const asHanded: <P extends {
107
+ create(spec: {
108
+ profile?: {
109
+ name: string;
110
+ save: boolean;
111
+ };
112
+ }, signal: AbortSignal): unknown;
113
+ }>(provider: P, kept: {
114
+ save: boolean;
115
+ } | undefined) => P;
116
+ /** Whether a session's change is one that saved to the run's sign-in, in a run that saves (every session of it runs on
117
+ * the profile, asHanded, whatever its record names): let go by the run (its tool, its idle time, a relaunch, its close,
118
+ * its end), never one the vendor had already lost or never made. */
119
+ export declare const savedOnRelease: (row: {
120
+ session: {
121
+ resourceId: string | null;
122
+ releaseReason: string | null;
123
+ };
124
+ }, change: string) => boolean;
125
+ export declare const TOOLS: Readonly<Record<string, ToolEntry>>;
126
+ /** Every name a revision may name, those a workflow's model node may, and those a workflow's call node may run. */
127
+ export declare const BOUND_TOOLS: readonly string[];
128
+ export declare const NODE_TOOLS: readonly string[];
129
+ export declare const CALL_TOOLS: readonly string[];
130
+ /** Whether `name` is one of `allowed`, or a legacy name for one (fetch_page, web_fetch's): a revision that names it
131
+ * still saves and runs, though the table lists it no more. */
132
+ export declare const allows: (allowed: readonly string[], name: string) => boolean;
133
+ /** The tools a run's learned workflow may name (learn/check.ts at learn time, learned-workflow.ts at a call): those of the
134
+ * agent's `granted` tools a workflow's call node runs here (CALL_TOOLS), each as granted and by its capability's name,
135
+ * and with the run's `plane`, none it resolves unavailable (its agent's own tool of the name does not run either). A
136
+ * learned model node runs without tools (learn/skills.ts MODEL_NODE_TOOLS), and a harness's own tool (Bash,
137
+ * exec_command, apply_patch) is never one, so the DSL refuses a draft that names it. */
138
+ export declare const learnedWorkflowTools: (granted: readonly string[], plane?: Plane) => string[];
139
+ /** The tools a learned draft may name (learnedWorkflowTools) that the gate allows: `permission` is what the gate holds a
140
+ * tool to now (tool-gate.ts permissionOf, or the run's gate's policy), by its capability's settings key, as the gate
141
+ * holds a legacy name. One set to ask or deny is left out of `tools`, so the end-of-run prompt never offers it, and named
142
+ * in `gated` with its setting, which the checker and a learned workflow's check before it runs refuse a draft for. */
143
+ export declare const learnedDraftTools: (granted: readonly string[], permission: (name: string) => string, plane?: Plane) => {
144
+ tools: string[];
145
+ gated: Record<string, string>;
146
+ };
147
+ /** The tools a workflow names (`nodes` from workflowNodes): on its model nodes (`tools`), and on its `call` nodes
148
+ * `via: "tool"` (`tool`). */
149
+ export declare function workflowTools(nodes: readonly Record<string, unknown>[]): {
150
+ nodes: string[];
151
+ calls: string[];
152
+ };
153
+ /** The tools a revision grants its run: an agentic revision's `tools`; a workflow revision's `tools` with those its model
154
+ * and call nodes name, which its run binds whether `tools` lists them or not. */
155
+ export declare function grantedTools(revision: {
156
+ kind: string;
157
+ tools?: readonly string[];
158
+ workflow?: unknown;
159
+ }): Promise<string[]>;
160
+ /** The table's entry for `name`, or undefined for a name it does not hold. */
161
+ export declare const toolOf: (name: string) => ToolEntry | undefined;
162
+ /** What a stored revision's tools resolve from (tool-plane.ts): the tools it grants, its harness, model and settings. */
163
+ export declare function toolingOf(revision: Revision): Promise<Tooling>;
164
+ /** The variables `entry` needs that `env` does not set, by name. */
165
+ export declare const missingEnv: (entry: ToolEntry, env: NodeJS.ProcessEnv) => string[];
166
+ /** What keeps `names` from being bound here: names outside the table (or, for a workflow's model nodes, that a node may
167
+ * not name), and the variables each tool in it needs that `env` does not set. Undefined when nothing does. */
168
+ export declare function toolRefusal(names: readonly string[], env: NodeJS.ProcessEnv, where?: "agent" | "nodes" | "calls"): {
169
+ message: string;
170
+ unbound: string[];
171
+ missing: Record<string, string[]>;
172
+ } | undefined;
173
+ /** Every tool as capabilities show it, the server's one tool catalog: available here, or the variables it is missing
174
+ * (names only), and the harnesses that run it (another harness than pi runs only the host tools, host-tools.ts). A tool
175
+ * a user picks a provider for (tool-plane.ts) gives the providers offered, the server's (`provider`, the default where it
176
+ * sets none), the default, and what it resolves to on each harness under the server's `settings`: available where any
177
+ * is not unavailable, and missing PARALLEL_API_KEY where Parallel is picked without it. An unavailable tool says why
178
+ * (`reason`). `noBox`: why no box can run a sandbox-only tool here (place.ts noBoxReason), which leaves it
179
+ * unavailable with that reason; undefined, a box can. `refused`: the variables of the keys this server was started with
180
+ * that their provider refused at the start (ToolKeys.refused), each with why: a tool that needs one is unavailable,
181
+ * saying that. Each tool also gives its permission under the server's settings (tool-gate.ts), the owner's default
182
+ * and the permissions it may be set to. */
183
+ export declare const toolsView: (env: NodeJS.ProcessEnv, settings?: ToolSettingsMap, noBox?: string, refused?: Readonly<Record<string, string>>) => {
184
+ providers?: ("browserbase" | "kernel" | "chrome" | "auto" | "off" | "parallel" | "native" | "exa-keyless")[] | undefined;
185
+ provider?: string | undefined;
186
+ default_provider?: "kernel" | "auto" | undefined;
187
+ resolves?: Record<"pi" | "claude-agent" | "codex" | "opencode", import("./tool-plane.js").Resolution> | undefined;
188
+ why?: Record<"pi" | "claude-agent" | "codex" | "opencode", string> | undefined;
189
+ harnesses: ("pi" | "claude-agent" | "codex" | "opencode")[];
190
+ permission: "ask" | "deny" | "allow";
191
+ default_permission: "ask" | "deny" | "allow";
192
+ permissions: ("ask" | "deny" | "allow")[];
193
+ missing?: string[] | undefined;
194
+ reason?: string | undefined;
195
+ available: boolean;
196
+ sandbox_only?: boolean | undefined;
197
+ call_only?: boolean | undefined;
198
+ name: string;
199
+ summary: string;
200
+ nodes: boolean;
201
+ calls: boolean;
202
+ }[];
package/dist/tools.js ADDED
@@ -0,0 +1,372 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { defineExtension, defineTool } from "@earendil-works/pi-durable";
5
+ import { BACKGROUND_LOG_BYTES, BACKGROUND_MAX, BACKGROUND_PAGE_BYTES } from "./background.js";
6
+ import { writeInWork } from "./workspace.js";
7
+ import { FETCH_PAGE_TOOL, fetchOptions, HTML_READ_CHARS, TEXT_CAP } from "./fetch-page.js";
8
+ import { DEFAULT_HARNESS, HARNESSES } from "./harness.js";
9
+ import { REPLAY } from "./host-tools.js";
10
+ import { LLM_TOOL } from "./llm.js";
11
+ import { DOCUMENTS_ENV, PDF_PAGES_TOOL, pdfPages } from "./pdf-pages.js";
12
+ import { monidTool } from "./monid.js";
13
+ import { FAUX_ENV, workflowNodes } from "./model.js";
14
+ import { bookedIn, booking } from "./paid-calls.js";
15
+ import { browserPrice, browserSpend } from "./browser-cost.js";
16
+ import { forModel } from "./result.js";
17
+ import { fetchFor, runPages, WEB_FETCH_TOOL, webFetchTool } from "./web-fetch.js";
18
+ import { searchFor, WEB_SEARCH_TOOL, webSearchTool } from "./web-search.js";
19
+ import { browserNeeds, capabilityOf, explainsView, isUnavailable, NO_PARALLEL_KEY, permissionsOf, PICKABLE, planeOf, PROVIDERS, whyUnavailable, withDefaults } from "./tool-plane.js";
20
+ import { defaultPermission, permissionOf } from "./tool-gate.js";
21
+ import { PARALLEL_KEY_ENV } from "./decisions.js";
22
+ import { handedSignIn } from "./secrets.js";
23
+ import { SIGN_IN_KEY, SIGN_IN_SAVED } from "./sign-ins.js";
24
+ export const ASK_TOOL = "ask_person";
25
+ /** Under `--faux` only: a module whose default export gives the browser's `{ provider, driver }` for the run's
26
+ * environment, the vendor its plane names (`browserbase`, `kernel`) and the saved sign-in it was handed for that
27
+ * vendor (`{ provider, ref, save }`, or undefined), in place of that vendor's (the tests' fake backend). */
28
+ export const FAUX_BROWSER_ENV = "AGENTRUN_SERVE_FAUX_BROWSER";
29
+ /** What the result of `ask_person` says; the person's page shows the question as a waiting row. */
30
+ export const asked = (question) => `Asked the person: ${question.slice(0, 500)}. Waiting for their answer.`;
31
+ export const askPerson = defineTool({
32
+ name: ASK_TOOL,
33
+ description: "Ask the person who started this run a question you cannot answer yourself. Call it alone. It ends your turn; the person's reply comes as their next message.",
34
+ parameters: {
35
+ type: "object",
36
+ additionalProperties: false,
37
+ properties: { question: { type: "string", minLength: 1, description: "The question, in one or two plain sentences." } },
38
+ required: ["question"],
39
+ },
40
+ replay: "safe",
41
+ execute: async (args) => {
42
+ const { question } = args;
43
+ return forModel(asked(question), { details: { question }, control: { terminate: true } });
44
+ },
45
+ });
46
+ /** `tool` alone in an extension named `name`, installed in the run's registry. */
47
+ function installTool(host, name, tool) {
48
+ const extension = defineExtension({ name, tools: [tool] });
49
+ host.install(extension);
50
+ return { tools: [tool], extensions: [extension] };
51
+ }
52
+ const callOnly = (summary, effect) => ({
53
+ summary, needs: [], nodes: false, callOnly: true, effect,
54
+ bind: async () => { throw new Error("a call-only tool binds no agent tool"); },
55
+ });
56
+ /** web_fetch, bound under `name`: its own, or a legacy name for it (LEGACY_NAMES, fetch_page). */
57
+ const webFetchEntry = (name) => ({
58
+ summary: `Read one public web page from a public host through the guarded direct fetch, or through Parallel's extract where Parallel is picked (falling back to the direct fetch, saying why, when Parallel answers no page), a part at a time (offset, max_chars; the page fetched once a run): { ok, url, status, title, text, chars, truncated?, original_chars?, beyond_read?, offset?, next_offset?, html_chars?, converted?, links, links_omitted?, via, parallel?, refused?, error? }; html_chars, the page's whole length, when its HTML was cut at ${HTML_READ_CHARS.toLocaleString("en-US")} characters before it was read, so its text is only the start of the page; converted: "text" when the text is plain text, its conversion to markdown having run out of time; a private or local address, a port other than 80 or 443, or a scheme other than http(s) is refused, never sent to Parallel.`,
59
+ needs: [],
60
+ nodes: true,
61
+ bind: async (host) => {
62
+ const tool = booking(webFetchTool(host.env, name));
63
+ const extension = defineExtension({ name: name.replaceAll("_", "-"), tools: [tool] });
64
+ host.install(extension);
65
+ return { tools: [tool], extensions: [extension] };
66
+ },
67
+ // A call node's Page is the workflow's, not a model's context: it reads the most of a part by default, from the page
68
+ // the run read (runPages) where it holds the URL. Its request to Parallel, when it makes one, is booked under the call
69
+ // (paid-calls.ts); a part from what the run read makes none and books nothing.
70
+ effect: async (args, run) => bookedIn(run.ledger, async () => fetchFor(run.env, args.url, { ...(await fetchOptions(run.env, FAUX_ENV)), offset: args.offset, maxChars: args.max_chars ?? TEXT_CAP, pages: runPages, signal: run.signal })),
71
+ });
72
+ /** A coding tool, from the run's coding source: a name it does not hold (bash on the runner) binds no tool. */
73
+ const fileTool = (name, summary, sandboxOnly = false) => ({
74
+ summary,
75
+ needs: [],
76
+ nodes: !sandboxOnly,
77
+ ...(sandboxOnly ? { sandboxOnly: true } : {}),
78
+ bind: async (host) => {
79
+ const tools = host.coding.tools.filter((tool) => tool.name === name);
80
+ return { tools, extensions: tools.length ? [host.coding.extension] : [] };
81
+ },
82
+ });
83
+ /** Where the browser files what it reads: `work/evidence/`, so the run's files show it and the agent can read it back. A
84
+ * text body follows one line of the read's facts; a capture's bytes go beside its facts. Each read takes the next free
85
+ * number, reserved by an exclusive create, so reads at once (parallel nodes, one turn's calls) and the reads of a later
86
+ * process never overwrite one another. */
87
+ export const evidenceIn = (work) => {
88
+ let seq = 0;
89
+ return {
90
+ file: async (label, record) => {
91
+ const facts = JSON.stringify({ label, tool: record.tool, ...record.facts });
92
+ const text = typeof record.body === "string";
93
+ for (;;) {
94
+ const name = `${String(++seq).padStart(4, "0")}-${record.tool}`;
95
+ try {
96
+ // Never through a link a box's command planted in work/ (files.ts).
97
+ await writeInWork(work, ["evidence"], text ? `${name}.md` : `${name}.json`, text ? `${facts}\n\n${record.body}` : `${facts}\n`);
98
+ }
99
+ catch (error) {
100
+ if (error.code === "EEXIST")
101
+ continue;
102
+ throw error;
103
+ }
104
+ if (text)
105
+ return { path: `evidence/${name}.md`, bodyLine: 3 };
106
+ await writeInWork(work, ["evidence"], `${name}.${record.ext ?? "bin"}`, record.body);
107
+ return { path: `evidence/${name}.json`, bodyPath: `evidence/${name}.${record.ext ?? "bin"}` };
108
+ }
109
+ },
110
+ };
111
+ };
112
+ /** The Browserbase contexts a run's browser may open: its agent's saved sign-in's alone, by its profile name, never one
113
+ * made here (nothing a run makes is kept for its agent). */
114
+ export const keptContexts = (ref) => ({
115
+ clear: false,
116
+ resolve: async (key) => {
117
+ if (ref && key.endsWith(`|profile:${SIGN_IN_KEY}`))
118
+ return ref;
119
+ throw new Error("this run's browser has no saved sign-in to open");
120
+ },
121
+ });
122
+ /** Kernel's provider, opening the agent's saved profile (`ref`, its name at Kernel) where a session asks for the
123
+ * profile `default`: the policy, the session's record and the model see only that name. */
124
+ export const keptProfile = (provider, ref) => ({
125
+ ...provider,
126
+ create: (spec, signal) => provider.create(spec.profile?.name === SIGN_IN_KEY ? { ...spec, profile: { ...spec.profile, name: ref } } : spec, signal),
127
+ });
128
+ /** `provider`, its sessions' profile as this launch was handed it, whatever the policy a conversation was made with (a
129
+ * follow-up's was made under an earlier launch, which may have had no sign-in, or another lease): with a sign-in, every
130
+ * session opens on the profile `default`, saving only as `kept.save` says; without one, none asks for a profile. */
131
+ export const asHanded = (provider, kept) => ({
132
+ ...provider,
133
+ create: (spec, signal) => provider.create(kept ? { ...spec, profile: { name: SIGN_IN_KEY, save: kept.save } } : spec.profile ? { ...spec, profile: undefined } : spec, signal),
134
+ });
135
+ /** Whether a session's change is one that saved to the run's sign-in, in a run that saves (every session of it runs on
136
+ * the profile, asHanded, whatever its record names): let go by the run (its tool, its idle time, a relaunch, its close,
137
+ * its end), never one the vendor had already lost or never made. */
138
+ export const savedOnRelease = (row, change) => change === "released" && row.session.resourceId !== null && row.session.releaseReason !== null && !["lost", "create_failed"].includes(row.session.releaseReason);
139
+ /** A hosted browser driven through Stagehand, on pi-browser's durable adapter: Browserbase or Kernel (headless), the one
140
+ * the run's plane names (tool-plane.ts: picked, else Browserbase where the server holds its keys, else Kernel), kept
141
+ * for the run's life; a plane that names none (a run kept from before the pick) is Browserbase. Its sessions' custody
142
+ * lives in the run's own store. No recording and no live view; a session the run still holds is released when the run
143
+ * is let go. Where the plane says unavailable (its vendor's key gone since), each call is refused, saying why.
144
+ * Its session time is the run's spend, held under its cap before it runs (browser-cost.ts). A run handed its agent's
145
+ * saved sign-in for that vendor (sign-ins.ts, over its pipe) opens every session on it, as the profile `default`,
146
+ * saving only where it holds the agent's save lease; one that saved says so in its run directory. */
147
+ const browserTool = {
148
+ summary: "Drive a hosted browser, Browserbase's or Kernel's (picked in tool settings, else whichever's key the server holds): open pages, read and screenshot them, and act on them.",
149
+ // Which vendor's keys it needs is the plane's to say (tool-plane.ts BROWSER_KEYS): neither alone is required.
150
+ needs: [],
151
+ nodes: true,
152
+ // Its downloads and uploads go through work/ by path (pi-browser), which a box's command could turn through a link.
153
+ runnerOnly: true,
154
+ bind: async (host) => {
155
+ const [{ BACKGROUND_CONTEXT: context }, { createBrowserExtension }, { DEFAULT_BROWSER_POLICY, BrowserFailureError, browserFailure, workspaceFiles }] = await Promise.all([
156
+ import("@earendil-works/chord/context"),
157
+ import("@parcha/pi-browser/durable"),
158
+ import("@parcha/pi-browser"),
159
+ ]);
160
+ const vendor = planeOf(host.env).browser ?? "browserbase";
161
+ const refused = isUnavailable(vendor) ? new BrowserFailureError(browserFailure("browser_unavailable", `The browser does not run here: ${whyUnavailable(vendor)}.`)) : undefined;
162
+ const handed = handedSignIn();
163
+ const kept = !refused && handed?.provider === vendor ? handed : undefined;
164
+ const faux = host.env[FAUX_ENV] ? host.env[FAUX_BROWSER_ENV] : undefined;
165
+ const parts = faux
166
+ ? (await import(pathToFileURL(faux).href)).default(host.env, vendor, kept)
167
+ : {
168
+ provider: refused
169
+ ? undefined
170
+ : vendor === "kernel"
171
+ ? ((kernel) => (kept ? keptProfile(kernel, kept.ref) : kernel))((await import("@parcha/pi-browser/providers/kernel")).kernelProvider({ env: host.env, headless: true }))
172
+ : (await import("@parcha/pi-browser/providers/browserbase")).browserbaseProvider({ env: host.env, profiles: keptContexts(kept?.ref) }),
173
+ driver: (await import("@parcha/pi-browser/driver/stagehand")).stagehandDriver(),
174
+ };
175
+ // The save flag every session carries is this launch's (asHanded), never the one stored with its conversation.
176
+ const handedProvider = parts.provider ? asHanded(parts.provider, kept) : undefined;
177
+ const provider = () => {
178
+ if (refused)
179
+ throw refused;
180
+ return handedProvider;
181
+ };
182
+ // Its session time is the run's spend, at its provider's price, and held under the run's cap (browser-cost.ts).
183
+ const providerName = parts.provider?.name ?? vendor;
184
+ const price = browserPrice(providerName, host.env);
185
+ const spend = browserSpend(providerName, price, DEFAULT_BROWSER_POLICY.idleReleaseS, (conversation, at) => browser.release(conversation, "close", at));
186
+ // browser_downloads is listed only with a workspace to copy into, and only a provider that keeps a session's downloads
187
+ // (Browserbase's; Kernel's keeps none) has any: without one, uploads still read the run's work/, through `files`.
188
+ const downloads = typeof parts.provider?.downloads === "object";
189
+ const files = downloads ? { workspace: () => host.where.work } : { files: workspaceFiles(host.where.work) };
190
+ // A session that saved to the sign-in, let go: its time, for the sign-in's verified_at when the run's lease ends.
191
+ const saved = kept?.save
192
+ ? { onSession: (row, change) => void (savedOnRelease(row, change) && writeFileSync(join(host.where.root, SIGN_IN_SAVED), new Date().toISOString(), { mode: 0o600 })) }
193
+ : {};
194
+ // The pointer is cut from everything the browser hands the model (its results, their details, its failures): a
195
+ // vendor's refusal can quote it, as pi-browser's one-saver rule names Kernel's profile.
196
+ const browser = createBrowserExtension({ provider, driver: parts.driver, evidence: evidenceIn(host.where.work), ...files, ...saved, redact: { values: () => (kept ? [kept.ref] : []) }, prices: { sessionUsdPerHour: price.usdPerHour, sessionMinimumS: price.minimumS }, onCharge: spend.onCharge });
197
+ const tools = browser.tools.map(spend.capped);
198
+ const extension = { ...browser.extension, tools };
199
+ host.install(extension);
200
+ host.onConversation(async (tx, conversationId) => {
201
+ // The profile is the host's choice, never the model's: the agent's one sign-in, when the run was handed it.
202
+ const policy = kept ? { ...DEFAULT_BROWSER_POLICY, profile: { name: SIGN_IN_KEY, save: kept.save } } : DEFAULT_BROWSER_POLICY;
203
+ Object.assign(await tx.doc(browser.docs.Config, conversationId), { label: "run", run: host.where.ref.id, policy });
204
+ });
205
+ host.beforeResume(async (harness) => {
206
+ // Its charges move what the process counts once each is committed, reconcile's own among them.
207
+ spend.watch(harness, browser.docs.Inventory.definition.kind);
208
+ // With its vendor's key gone there is no session to reconcile or release from here: each would only fail.
209
+ if (refused)
210
+ return;
211
+ // Every session custody still tracks across a restart is held from here; one kept is released an idle window on
212
+ // unless a call uses it.
213
+ await browser.reconcile(harness, () => true, context);
214
+ await spend.reopened(harness, browser.docs, context);
215
+ });
216
+ host.beforeRelease(async (harness) => {
217
+ if (refused)
218
+ return;
219
+ const held = await harness.snapshot(browser.docs.Inventory, context);
220
+ for (const id of new Set(Object.values(held?.rows ?? {}).filter((row) => row.state !== "released").map((row) => row.conversationId))) {
221
+ const conversation = await harness.conversation(id, context);
222
+ if (conversation)
223
+ await browser.release(conversation, "close", context);
224
+ }
225
+ await browser.drain(harness, context);
226
+ });
227
+ return { tools, extensions: [extension] };
228
+ },
229
+ };
230
+ export const TOOLS = Object.freeze({
231
+ read: fileTool("read", "Read a file in the run's work/."),
232
+ write: fileTool("write", "Write a file in the run's work/."),
233
+ edit: fileTool("edit", "Edit a file in the run's work/."),
234
+ bash: fileTool("bash", "Run a bash command in the run's box, from its work/, never on this server itself: only an agent whose place is a sandbox names it. Its output's tail; 300 s unless the call names a timeout.", true),
235
+ // The background tools (background.ts): each call a short command in the run's box, on bash's environment.
236
+ bash_background: fileTool("bash_background", `Start a command in the background in the run's box, from its work/, and get its id at once: its stdout and stderr go to work/background/<id>/output.log (the first ${BACKGROUND_LOG_BYTES / (1024 * 1024)} MiB), its stdin is a pipe, and the run's end ends it; at most ${BACKGROUND_MAX} run at once. Only an agent whose place is a sandbox names it.`, true),
237
+ bash_output: fileTool("bash_output", `Read a background process's output from a byte offset, at most ${BACKGROUND_PAGE_BYTES / 1024} KiB a call, with whether it still runs, its exit code and the next offset. Sandbox only.`, true),
238
+ bash_input: fileTool("bash_input", "Write text to a running background process's stdin, and close it if asked. Sandbox only.", true),
239
+ bash_signal: fileTool("bash_signal", "Send TERM, INT or KILL to a background process's process group. Sandbox only.", true),
240
+ bash_list: fileTool("bash_list", "List the run's background processes: id, state or exit code, output size and command. Sandbox only.", true),
241
+ [ASK_TOOL]: {
242
+ summary: "Ask the person who started the run; the turn ends until a message answers.",
243
+ needs: [],
244
+ nodes: false,
245
+ bind: async (host) => installTool(host, "person", askPerson),
246
+ },
247
+ [WEB_FETCH_TOOL]: webFetchEntry(WEB_FETCH_TOOL),
248
+ [WEB_SEARCH_TOOL]: {
249
+ summary: "Search the web: codex's own search (claude-agent's where it is picked), on pi the model provider's hosted search (Anthropic, OpenAI), with none of those Parallel's Search API where the server holds its key, else Exa's keyless search; or the provider picked: { query, n? } -> { provider, query, results: [{ url, title, snippet, published? }], text? }, provider naming the one that served it, 1 to 25 results, each snippet at most 3,000 characters; { error } when the search gives no answer.",
250
+ needs: [],
251
+ nodes: true,
252
+ bind: async (host) => installTool(host, "web-search", booking(webSearchTool(host.env))),
253
+ effect: async (args, run) => bookedIn(run.ledger, () => searchFor(run.env, args, run.signal)),
254
+ },
255
+ browser: browserTool,
256
+ // monid's catalog on one key (monid.ts): every harness calls each by its wire name, `monid_discover` and the rest.
257
+ "monid.discover": monidTool("discover"),
258
+ "monid.inspect": monidTool("inspect"),
259
+ "monid.run": monidTool("run"),
260
+ [PDF_PAGES_TOOL]: callOnly("A workflow call: { path, maxPages?, dpi? } -> { name, pageCount, dpi, pages: [{ page, image }], text }; the document's first pages drawn as PNGs under work/pages/<stem>/<dpi>/ (the dpi lowered so a page's long side is at most 1568 px), from the server's documents (--documents) or the run's work directory.", (args, run) => pdfPages(args, { work: run.work, documents: run.env[DOCUMENTS_ENV], signal: run.signal })),
261
+ [LLM_TOOL]: callOnly("A workflow call: { prompt, system?, maxTokens?, tier? } -> { text, model, usage, cost_usd }; one completion on the model of the tier (default), no tools and no loop.", (args, run) => {
262
+ if (!run.complete)
263
+ throw new Error("llm: this run has no model to complete on");
264
+ return run.complete(args, run.signal);
265
+ }),
266
+ });
267
+ /** Every name a revision may name, those a workflow's model node may, and those a workflow's call node may run. */
268
+ export const BOUND_TOOLS = Object.keys(TOOLS).filter((name) => !TOOLS[name].callOnly);
269
+ export const NODE_TOOLS = BOUND_TOOLS.filter((name) => TOOLS[name].nodes);
270
+ export const CALL_TOOLS = Object.keys(TOOLS).filter((name) => TOOLS[name].effect !== undefined);
271
+ /** Whether `name` is one of `allowed`, or a legacy name for one (fetch_page, web_fetch's): a revision that names it
272
+ * still saves and runs, though the table lists it no more. */
273
+ export const allows = (allowed, name) => allowed.includes(capabilityOf(name));
274
+ /** The tools a run's learned workflow may name (learn/check.ts at learn time, learned-workflow.ts at a call): those of the
275
+ * agent's `granted` tools a workflow's call node runs here (CALL_TOOLS), each as granted and by its capability's name,
276
+ * and with the run's `plane`, none it resolves unavailable (its agent's own tool of the name does not run either). A
277
+ * learned model node runs without tools (learn/skills.ts MODEL_NODE_TOOLS), and a harness's own tool (Bash,
278
+ * exec_command, apply_patch) is never one, so the DSL refuses a draft that names it. */
279
+ export const learnedWorkflowTools = (granted, plane) => [...new Set(granted.filter((name) => allows(CALL_TOOLS, name) && !isUnavailable(plane?.[capabilityOf(name)])).flatMap((name) => [name, capabilityOf(name)]))];
280
+ /** The tools a learned draft may name (learnedWorkflowTools) that the gate allows: `permission` is what the gate holds a
281
+ * tool to now (tool-gate.ts permissionOf, or the run's gate's policy), by its capability's settings key, as the gate
282
+ * holds a legacy name. One set to ask or deny is left out of `tools`, so the end-of-run prompt never offers it, and named
283
+ * in `gated` with its setting, which the checker and a learned workflow's check before it runs refuse a draft for. */
284
+ export const learnedDraftTools = (granted, permission, plane) => {
285
+ const gated = {};
286
+ const tools = learnedWorkflowTools(granted, plane).filter((name) => {
287
+ const setting = permission(capabilityOf(name));
288
+ if (setting === "allow")
289
+ return true;
290
+ gated[name] = setting;
291
+ return false;
292
+ });
293
+ return { tools, gated };
294
+ };
295
+ /** The tools a workflow names (`nodes` from workflowNodes): on its model nodes (`tools`), and on its `call` nodes
296
+ * `via: "tool"` (`tool`). */
297
+ export function workflowTools(nodes) {
298
+ const named = new Set();
299
+ const calls = new Set();
300
+ for (const node of nodes) {
301
+ if (node.node === "call" && node.via === "tool" && typeof node.tool === "string")
302
+ calls.add(node.tool);
303
+ else if (Array.isArray(node.tools))
304
+ for (const name of node.tools)
305
+ if (typeof name === "string")
306
+ named.add(name);
307
+ }
308
+ return { nodes: [...named], calls: [...calls] };
309
+ }
310
+ /** The tools a revision grants its run: an agentic revision's `tools`; a workflow revision's `tools` with those its model
311
+ * and call nodes name, which its run binds whether `tools` lists them or not. */
312
+ export async function grantedTools(revision) {
313
+ if (revision.kind !== "workflow")
314
+ return [...(revision.tools ?? [])];
315
+ const { inspectWorkflow } = await import("@parcha/agentrun-dsl");
316
+ const named = workflowTools(workflowNodes(revision.workflow, inspectWorkflow(revision.workflow)));
317
+ return [...new Set([...(revision.tools ?? []), ...named.nodes, ...named.calls])];
318
+ }
319
+ /** The table's entry for `name`, or undefined for a name it does not hold. */
320
+ export const toolOf = (name) => (Object.hasOwn(TOOLS, name) ? TOOLS[name] : name === FETCH_PAGE_TOOL ? webFetchEntry(FETCH_PAGE_TOOL) : undefined);
321
+ /** What a stored revision's tools resolve from (tool-plane.ts): the tools it grants, its harness, model and settings. */
322
+ export async function toolingOf(revision) {
323
+ const tools = await grantedTools(revision.kind === "agentic" ? { kind: "agentic", tools: revision.body.tools } : { kind: "workflow", tools: revision.body.tools, workflow: revision.body.workflow });
324
+ return { tools, ...(revision.kind === "workflow" ? { workflow: true } : {}), ...(revision.body.harness ? { harness: revision.body.harness } : {}), ...(revision.kind === "agentic" && revision.body.model ? { model: revision.body.model } : {}), ...(revision.body.toolSettings ? { overrides: revision.body.toolSettings } : {}) };
325
+ }
326
+ /** The variables `entry` needs that `env` does not set, by name. */
327
+ export const missingEnv = (entry, env) => entry.needs.filter((name) => !env[name]);
328
+ /** What keeps `names` from being bound here: names outside the table (or, for a workflow's model nodes, that a node may
329
+ * not name), and the variables each tool in it needs that `env` does not set. Undefined when nothing does. */
330
+ export function toolRefusal(names, env, where = "agent") {
331
+ const allowed = where === "nodes" ? NODE_TOOLS : where === "calls" ? CALL_TOOLS : BOUND_TOOLS;
332
+ const unbound = names.filter((name) => !allows(allowed, name));
333
+ if (unbound.length) {
334
+ const said = { agent: "agentrun-serve binds the tools", nodes: "A workflow's model nodes get the tools", calls: "A workflow's call nodes run the tools" }[where];
335
+ return { message: `${said} ${allowed.join(", ")}; this ${where === "agent" ? "revision" : "workflow"} also ${where === "calls" ? "calls" : "names"} ${unbound.join(", ")}.`, unbound, missing: {} };
336
+ }
337
+ const missing = Object.fromEntries(names.map((name) => [name, missingEnv(toolOf(name), env)]).filter(([, vars]) => vars.length));
338
+ const lacking = Object.entries(missing);
339
+ if (!lacking.length)
340
+ return undefined;
341
+ const said = lacking.map(([name, vars]) => `the tool ${name} needs ${vars.join(" and ")}`).join("; ");
342
+ return { message: `This server's environment does not set what the revision's tools need: ${said}.`, unbound: [], missing };
343
+ }
344
+ /** Every tool as capabilities show it, the server's one tool catalog: available here, or the variables it is missing
345
+ * (names only), and the harnesses that run it (another harness than pi runs only the host tools, host-tools.ts). A tool
346
+ * a user picks a provider for (tool-plane.ts) gives the providers offered, the server's (`provider`, the default where it
347
+ * sets none), the default, and what it resolves to on each harness under the server's `settings`: available where any
348
+ * is not unavailable, and missing PARALLEL_API_KEY where Parallel is picked without it. An unavailable tool says why
349
+ * (`reason`). `noBox`: why no box can run a sandbox-only tool here (place.ts noBoxReason), which leaves it
350
+ * unavailable with that reason; undefined, a box can. `refused`: the variables of the keys this server was started with
351
+ * that their provider refused at the start (ToolKeys.refused), each with why: a tool that needs one is unavailable,
352
+ * saying that. Each tool also gives its permission under the server's settings (tool-gate.ts), the owner's default
353
+ * and the permissions it may be set to. */
354
+ export const toolsView = (env, settings = {}, noBox, refused = {}) => {
355
+ const views = explainsView(env, settings);
356
+ const picked = withDefaults(settings);
357
+ return Object.entries(TOOLS).map(([name, entry]) => {
358
+ const view = PICKABLE.includes(name) ? views[name] : undefined;
359
+ const plane = view?.resolves;
360
+ const missing = plane && Object.values(plane).includes(NO_PARALLEL_KEY) ? [PARALLEL_KEY_ENV] : missingEnv(entry, env);
361
+ const boxless = entry.sandboxOnly ? noBox : undefined;
362
+ // The browser needs the keys of the vendor it resolves to: one refused at the start leaves it unavailable, never on the
363
+ // other vendor, as a refused Parallel key never moves web_search elsewhere.
364
+ const needs = name === "browser" ? [...new Set(Object.values(plane ?? {}).flatMap(browserNeeds))] : entry.needs;
365
+ const refusal = needs.map((name) => (Object.hasOwn(refused, name) ? refused[name] : undefined)).find((why) => why !== undefined);
366
+ const available = (plane ? Object.values(plane).some((resolution) => !isUnavailable(resolution)) : missing.length === 0) && boxless === undefined && refusal === undefined;
367
+ // Unavailable says why: a sandbox-only tool no box here can run, why none can (`noBox`); on a tool a user picks a
368
+ // provider for, the resolutions' own words (`web_search is turned off in settings`); else the variables it needs.
369
+ const reason = available ? undefined : refusal ?? boxless ?? (plane ? [...new Set(Object.values(plane).filter(isUnavailable).map(whyUnavailable))].join("; ") : `Needs ${missing.join(", ")}`);
370
+ return { name, summary: entry.summary, nodes: entry.nodes, calls: entry.effect !== undefined, ...(entry.callOnly ? { call_only: true } : {}), ...(entry.sandboxOnly ? { sandbox_only: true } : {}), available, ...(reason ? { reason } : {}), ...(missing.length ? { missing } : {}), harnesses: name in REPLAY ? [...HARNESSES] : [DEFAULT_HARNESS], permission: permissionOf(name, settings), default_permission: defaultPermission(name), permissions: [...permissionsOf(name)], ...(plane ? { providers: [...PROVIDERS[name]], provider: picked[name].provider, default_provider: PROVIDERS[name][0], resolves: plane, why: view.why } : {}) };
371
+ });
372
+ };
@@ -0,0 +1,32 @@
1
+ export declare const TRIGGER_SECRETS_FILE = "trigger-secrets.json";
2
+ /** The trigger secrets data directory `data` keeps, opened with the seal key of `env` (those that open): what an import
3
+ * cuts out of everything it writes. */
4
+ export declare function triggerSecretsIn(data: string, env: NodeJS.ProcessEnv): string[];
5
+ export declare class TriggerSecrets {
6
+ private readonly file;
7
+ private readonly key;
8
+ /** Opened, by trigger id: read once at start, then kept with every write. */
9
+ private secrets;
10
+ private sealed;
11
+ /** Why the file does not read: no secret is made or rotated, none signs, and the file is never written over. */
12
+ private readonly unreadable?;
13
+ constructor(data: string, env: NodeJS.ProcessEnv, say?: (fields: Record<string, string>) => void);
14
+ get sealing(): "sealed" | "unavailable";
15
+ /** A new secret for `triggerId`, written sealed before it is answered: its only showing. */
16
+ mint(triggerId: string): string;
17
+ value(triggerId: string): string | undefined;
18
+ /** A deleted trigger's secret goes; with the file unreadable it stays in it, unread, as the file is never written over. */
19
+ remove(triggerId: string): void;
20
+ /** Every secret held, for the redaction of what is shown. */
21
+ values(): string[];
22
+ private write;
23
+ }
24
+ /** How far a request's `webhook-timestamp` may be from this server's clock, either way. */
25
+ export declare const HOOK_TOLERANCE_S = 300;
26
+ /** Why a request's webhook headers are refused before its body is read, or undefined when they may be checked:
27
+ * present, a webhook-id of printable ASCII, a bounded signature list, a timestamp within HOOK_TOLERANCE_S. */
28
+ export declare function hookHeadersRefusal(headers: Record<string, string | string[] | undefined>, nowMs: number): string | undefined;
29
+ /** Why a request to /v2/hooks/{id} is not signed by `secret` under the Standard Webhooks spec, or undefined when it is:
30
+ * `webhook-signature` lists `v1,<base64 HMAC-SHA256 of "{webhook-id}.{webhook-timestamp}.{body}">` signatures, space
31
+ * separated, under the secret's bytes, and any one that matches passes; the timestamp is within HOOK_TOLERANCE_S. */
32
+ export declare function hookRefusal(secret: string, headers: Record<string, string | string[] | undefined>, body: Buffer, nowMs: number): string | undefined;