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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/CHANGELOG.md +238 -0
  2. package/README.md +739 -116
  3. package/dist/adapters.d.ts +35 -6
  4. package/dist/adapters.js +152 -26
  5. package/dist/agents.d.ts +18 -7
  6. package/dist/agents.js +19 -10
  7. package/dist/app.js +101 -26
  8. package/dist/background.d.ts +29 -0
  9. package/dist/background.js +397 -0
  10. package/dist/box-egress-vm.d.ts +125 -0
  11. package/dist/box-egress-vm.js +350 -0
  12. package/dist/box-egress.d.ts +99 -0
  13. package/dist/box-egress.js +259 -0
  14. package/dist/box-image.d.ts +1 -1
  15. package/dist/box-image.js +9 -7
  16. package/dist/box-relay-vm.d.ts +84 -0
  17. package/dist/box-relay-vm.js +410 -0
  18. package/dist/box-relay.d.ts +8 -5
  19. package/dist/box-relay.js +14 -9
  20. package/dist/boxes.d.ts +28 -5
  21. package/dist/boxes.js +44 -18
  22. package/dist/browser-cost.d.ts +41 -0
  23. package/dist/browser-cost.js +158 -0
  24. package/dist/cap.d.ts +130 -21
  25. package/dist/cap.js +339 -67
  26. package/dist/cli.js +30 -4
  27. package/dist/coding-tools.d.ts +7 -3
  28. package/dist/coding-tools.js +16 -10
  29. package/dist/console/THIRD-PARTY-NOTICES.txt +580 -0
  30. package/dist/console/assets/index-CnJBf7Lc.js +486 -0
  31. package/dist/console/assets/index-DUHbWcIP.css +1 -0
  32. package/dist/console/index.html +2 -2
  33. package/dist/content-filter.d.ts +7 -0
  34. package/dist/content-filter.js +23 -0
  35. package/dist/decision-rows.d.ts +11 -3
  36. package/dist/decision-rows.js +18 -11
  37. package/dist/decisions.d.ts +3 -3
  38. package/dist/decisions.js +4 -3
  39. package/dist/errors.d.ts +2 -0
  40. package/dist/errors.js +5 -2
  41. package/dist/files.d.ts +9 -1
  42. package/dist/files.js +10 -2
  43. package/dist/grade.d.ts +11 -11
  44. package/dist/grade.js +43 -55
  45. package/dist/graph-served.d.ts +23 -0
  46. package/dist/graph-served.js +75 -0
  47. package/dist/graph-view.d.ts +7 -5
  48. package/dist/graph-view.js +10 -3
  49. package/dist/harness-app.d.ts +4 -2
  50. package/dist/harness-app.js +110 -19
  51. package/dist/harness-opencode/adapter.d.ts +45 -0
  52. package/dist/harness-opencode/adapter.js +272 -0
  53. package/dist/harness-opencode/binary.d.ts +18 -0
  54. package/dist/harness-opencode/binary.js +87 -0
  55. package/dist/harness-opencode/config.d.ts +24 -0
  56. package/dist/harness-opencode/config.js +61 -0
  57. package/dist/harness-opencode/harness.d.ts +77 -0
  58. package/dist/harness-opencode/harness.js +620 -0
  59. package/dist/harness-opencode/host/mcp.d.ts +40 -0
  60. package/dist/harness-opencode/host/mcp.js +208 -0
  61. package/dist/harness-opencode/host/policy.d.ts +71 -0
  62. package/dist/harness-opencode/host/policy.js +419 -0
  63. package/dist/harness-opencode/host/server.d.ts +55 -0
  64. package/dist/harness-opencode/host/server.js +165 -0
  65. package/dist/harness-opencode/index.d.ts +9 -0
  66. package/dist/harness-opencode/index.js +6 -0
  67. package/dist/harness-opencode/verify.d.ts +32 -0
  68. package/dist/harness-opencode/verify.js +75 -0
  69. package/dist/harness-opencode/versions.d.ts +33 -0
  70. package/dist/harness-opencode/versions.js +64 -0
  71. package/dist/harness.d.ts +4 -1
  72. package/dist/harness.js +5 -2
  73. package/dist/host-check.d.ts +12 -0
  74. package/dist/host-check.js +34 -0
  75. package/dist/host-tools.d.ts +12 -2
  76. package/dist/host-tools.js +26 -12
  77. package/dist/host.js +6 -2
  78. package/dist/hosted-search.js +5 -1
  79. package/dist/import.d.ts +2 -2
  80. package/dist/import.js +4 -3
  81. package/dist/key-check.d.ts +3 -2
  82. package/dist/key-check.js +7 -3
  83. package/dist/key-refusal.js +8 -4
  84. package/dist/key-words.d.ts +37 -0
  85. package/dist/key-words.js +40 -0
  86. package/dist/learn/check.d.ts +10 -1
  87. package/dist/learn/check.js +19 -1
  88. package/dist/learn/grade.d.ts +6 -2
  89. package/dist/learn/grade.js +28 -14
  90. package/dist/learn/index.d.ts +3 -3
  91. package/dist/learn/index.js +3 -3
  92. package/dist/learn/notes.js +2 -1
  93. package/dist/learn/reflect.d.ts +2 -2
  94. package/dist/learn/reflect.js +53 -5
  95. package/dist/learn/secrets.js +28 -8
  96. package/dist/learn/skills.d.ts +19 -4
  97. package/dist/learn/skills.js +95 -6
  98. package/dist/learned-workflow.d.ts +59 -0
  99. package/dist/learned-workflow.js +191 -0
  100. package/dist/learning-routes.d.ts +30 -1
  101. package/dist/learning-routes.js +173 -19
  102. package/dist/learning-run.d.ts +8 -6
  103. package/dist/learning-run.js +70 -27
  104. package/dist/learning-words.d.ts +12 -5
  105. package/dist/learning-words.js +34 -13
  106. package/dist/learning.d.ts +52 -3
  107. package/dist/learning.js +204 -4
  108. package/dist/mcp-gateway.d.ts +96 -0
  109. package/dist/mcp-gateway.js +408 -0
  110. package/dist/mcp-meta.d.ts +17 -0
  111. package/dist/mcp-meta.js +38 -0
  112. package/dist/mcp-servers.d.ts +33 -9
  113. package/dist/mcp-servers.js +58 -10
  114. package/dist/mcp.js +5 -5
  115. package/dist/model.d.ts +13 -11
  116. package/dist/model.js +11 -10
  117. package/dist/openapi/agentrun-v2.openapi.json +1 -0
  118. package/dist/openapi.js +407 -54
  119. package/dist/page.d.ts +2 -0
  120. package/dist/page.js +3 -0
  121. package/dist/paid-calls.d.ts +5 -1
  122. package/dist/paid-calls.js +1 -1
  123. package/dist/pause.d.ts +2 -0
  124. package/dist/place.d.ts +29 -5
  125. package/dist/place.js +51 -11
  126. package/dist/print.d.ts +7 -0
  127. package/dist/print.js +13 -0
  128. package/dist/propose.d.ts +2 -0
  129. package/dist/propose.js +38 -8
  130. package/dist/request-start.d.ts +12 -4
  131. package/dist/request-start.js +139 -15
  132. package/dist/run-box.d.ts +56 -4
  133. package/dist/run-box.js +183 -23
  134. package/dist/runnable.d.ts +13 -3
  135. package/dist/runnable.js +63 -6
  136. package/dist/runs.d.ts +266 -37
  137. package/dist/runs.js +884 -90
  138. package/dist/secrets.d.ts +27 -0
  139. package/dist/secrets.js +38 -2
  140. package/dist/server.d.ts +141 -36
  141. package/dist/server.js +562 -118
  142. package/dist/sign-ins.d.ts +99 -0
  143. package/dist/sign-ins.js +288 -0
  144. package/dist/skills.d.ts +16 -4
  145. package/dist/skills.js +35 -7
  146. package/dist/stats.d.ts +7 -2
  147. package/dist/stats.js +28 -7
  148. package/dist/tool-gate.d.ts +281 -0
  149. package/dist/tool-gate.js +585 -0
  150. package/dist/tool-keys.d.ts +48 -11
  151. package/dist/tool-keys.js +46 -8
  152. package/dist/tool-plane.d.ts +116 -27
  153. package/dist/tool-plane.js +232 -50
  154. package/dist/tools.d.ts +69 -14
  155. package/dist/tools.js +148 -26
  156. package/dist/trigger-secrets.d.ts +32 -0
  157. package/dist/trigger-secrets.js +143 -0
  158. package/dist/triggers.d.ts +439 -0
  159. package/dist/triggers.js +863 -0
  160. package/dist/turn-end.d.ts +3 -2
  161. package/dist/turn-end.js +3 -2
  162. package/dist/usage-lines.d.ts +26 -0
  163. package/dist/usage-lines.js +28 -0
  164. package/dist/validate.d.ts +2 -0
  165. package/dist/validate.js +11 -2
  166. package/dist/web-fetch.js +3 -3
  167. package/dist/webhooks.d.ts +11 -4
  168. package/dist/webhooks.js +17 -1
  169. package/launcher/agentrun-serve +1 -1
  170. package/package.json +16 -14
  171. package/dist/console/assets/index-BN7oVcO4.js +0 -445
  172. package/dist/console/assets/index-By-jkqki.css +0 -1
package/dist/tools.js CHANGED
@@ -1,5 +1,8 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
1
3
  import { pathToFileURL } from "node:url";
2
4
  import { defineExtension, defineTool } from "@earendil-works/pi-durable";
5
+ import { BACKGROUND_LOG_BYTES, BACKGROUND_MAX, BACKGROUND_PAGE_BYTES } from "./background.js";
3
6
  import { writeInWork } from "./workspace.js";
4
7
  import { FETCH_PAGE_TOOL, fetchOptions, HTML_READ_CHARS, TEXT_CAP } from "./fetch-page.js";
5
8
  import { DEFAULT_HARNESS, HARNESSES } from "./harness.js";
@@ -9,14 +12,20 @@ import { DOCUMENTS_ENV, PDF_PAGES_TOOL, pdfPages } from "./pdf-pages.js";
9
12
  import { monidTool } from "./monid.js";
10
13
  import { FAUX_ENV, workflowNodes } from "./model.js";
11
14
  import { bookedIn, booking } from "./paid-calls.js";
15
+ import { browserPrice, browserSpend } from "./browser-cost.js";
12
16
  import { forModel } from "./result.js";
13
17
  import { fetchFor, runPages, WEB_FETCH_TOOL, webFetchTool } from "./web-fetch.js";
14
18
  import { searchFor, WEB_SEARCH_TOOL, webSearchTool } from "./web-search.js";
15
- import { capabilityOf, explainsView, isUnavailable, NO_PARALLEL_KEY, PICKABLE, PROVIDERS, whyUnavailable, withDefaults } from "./tool-plane.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";
16
21
  import { PARALLEL_KEY_ENV } from "./decisions.js";
22
+ import { keyNeeded } from "./key-words.js";
23
+ import { handedSignIn } from "./secrets.js";
24
+ import { SIGN_IN_KEY, SIGN_IN_SAVED } from "./sign-ins.js";
17
25
  export const ASK_TOOL = "ask_person";
18
- /** Under `--faux` only: a module whose default export gives the browser's `{ provider, driver }`, in place of
19
- * Browserbase's (the tests' fake backend). */
26
+ /** Under `--faux` only: a module whose default export gives the browser's `{ provider, driver }` for the run's
27
+ * environment, the vendor its plane names (`browserbase`, `kernel`) and the saved sign-in it was handed for that
28
+ * vendor (`{ provider, ref, save }`, or undefined), in place of that vendor's (the tests' fake backend). */
20
29
  export const FAUX_BROWSER_ENV = "AGENTRUN_SERVE_FAUX_BROWSER";
21
30
  /** What the result of `ask_person` says; the person's page shows the question as a waiting row. */
22
31
  export const asked = (question) => `Asked the person: ${question.slice(0, 500)}. Waiting for their answer.`;
@@ -101,32 +110,115 @@ export const evidenceIn = (work) => {
101
110
  },
102
111
  };
103
112
  };
104
- /** A Browserbase browser driven through Stagehand, on pi-browser's durable adapter: its sessions' custody lives in the
105
- * run's own store. No recording and no live view; a session the run still holds is released when the run is let go. */
113
+ /** The Browserbase contexts a run's browser may open: its agent's saved sign-in's alone, by its profile name, never one
114
+ * made here (nothing a run makes is kept for its agent). */
115
+ export const keptContexts = (ref) => ({
116
+ clear: false,
117
+ resolve: async (key) => {
118
+ if (ref && key.endsWith(`|profile:${SIGN_IN_KEY}`))
119
+ return ref;
120
+ throw new Error("this run's browser has no saved sign-in to open");
121
+ },
122
+ });
123
+ /** Kernel's provider, opening the agent's saved profile (`ref`, its name at Kernel) where a session asks for the
124
+ * profile `default`: the policy, the session's record and the model see only that name. */
125
+ export const keptProfile = (provider, ref) => ({
126
+ ...provider,
127
+ create: (spec, signal) => provider.create(spec.profile?.name === SIGN_IN_KEY ? { ...spec, profile: { ...spec.profile, name: ref } } : spec, signal),
128
+ });
129
+ /** `provider`, its sessions' profile as this launch was handed it, whatever the policy a conversation was made with (a
130
+ * follow-up's was made under an earlier launch, which may have had no sign-in, or another lease): with a sign-in, every
131
+ * session opens on the profile `default`, saving only as `kept.save` says; without one, none asks for a profile. */
132
+ export const asHanded = (provider, kept) => ({
133
+ ...provider,
134
+ create: (spec, signal) => provider.create(kept ? { ...spec, profile: { name: SIGN_IN_KEY, save: kept.save } } : spec.profile ? { ...spec, profile: undefined } : spec, signal),
135
+ });
136
+ /** 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
137
+ * the profile, asHanded, whatever its record names): let go by the run (its tool, its idle time, a relaunch, its close,
138
+ * its end), never one the vendor had already lost or never made. */
139
+ export const savedOnRelease = (row, change) => change === "released" && row.session.resourceId !== null && row.session.releaseReason !== null && !["lost", "create_failed"].includes(row.session.releaseReason);
140
+ /** A hosted browser driven through Stagehand, on pi-browser's durable adapter: Browserbase or Kernel (headless), the one
141
+ * the run's plane names (tool-plane.ts: picked, else Browserbase where the server holds its keys, else Kernel), kept
142
+ * for the run's life; a plane that names none (a run kept from before the pick) is Browserbase. Its sessions' custody
143
+ * lives in the run's own store. No recording and no live view; a session the run still holds is released when the run
144
+ * is let go. Where the plane says unavailable (its vendor's key gone since), each call is refused, saying why.
145
+ * Its session time is the run's spend, held under its cap before it runs (browser-cost.ts). A run handed its agent's
146
+ * saved sign-in for that vendor (sign-ins.ts, over its pipe) opens every session on it, as the profile `default`,
147
+ * saving only where it holds the agent's save lease; one that saved says so in its run directory. */
106
148
  const browserTool = {
107
- summary: "Drive a Browserbase browser: open pages, read and screenshot them, and act on them.",
108
- needs: ["BROWSERBASE_API_KEY", "BROWSERBASE_PROJECT_ID"],
149
+ 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.",
150
+ // Which vendor's keys it needs is the plane's to say (tool-plane.ts BROWSER_KEYS): neither alone is required.
151
+ needs: [],
109
152
  nodes: true,
110
153
  // Its downloads and uploads go through work/ by path (pi-browser), which a box's command could turn through a link.
111
154
  runnerOnly: true,
112
155
  bind: async (host) => {
113
- const [{ BACKGROUND_CONTEXT: context }, { createBrowserExtension }, { DEFAULT_BROWSER_POLICY }] = await Promise.all([
156
+ const [{ BACKGROUND_CONTEXT: context }, { createBrowserExtension }, { DEFAULT_BROWSER_POLICY, BrowserFailureError, browserFailure, workspaceFiles }] = await Promise.all([
114
157
  import("@earendil-works/chord/context"),
115
158
  import("@parcha/pi-browser/durable"),
116
159
  import("@parcha/pi-browser"),
117
160
  ]);
161
+ const vendor = planeOf(host.env).browser ?? "browserbase";
162
+ const refused = isUnavailable(vendor) ? new BrowserFailureError(browserFailure("browser_unavailable", `The browser does not run here: ${whyUnavailable(vendor)}.`)) : undefined;
163
+ const handed = handedSignIn();
164
+ const kept = !refused && handed?.provider === vendor ? handed : undefined;
118
165
  const faux = host.env[FAUX_ENV] ? host.env[FAUX_BROWSER_ENV] : undefined;
119
166
  const parts = faux
120
- ? (await import(pathToFileURL(faux).href)).default(host.env)
121
- : { provider: (await import("@parcha/pi-browser/providers/browserbase")).browserbaseProvider({ env: host.env }), driver: (await import("@parcha/pi-browser/driver/stagehand")).stagehandDriver() };
122
- const browser = createBrowserExtension({ provider: () => parts.provider, driver: parts.driver, evidence: evidenceIn(host.where.work), workspace: () => host.where.work });
123
- const extension = browser.extension;
167
+ ? (await import(pathToFileURL(faux).href)).default(host.env, vendor, kept)
168
+ : {
169
+ provider: refused
170
+ ? undefined
171
+ : vendor === "kernel"
172
+ ? ((kernel) => (kept ? keptProfile(kernel, kept.ref) : kernel))((await import("@parcha/pi-browser/providers/kernel")).kernelProvider({ env: host.env, headless: true }))
173
+ : (await import("@parcha/pi-browser/providers/browserbase")).browserbaseProvider({ env: host.env, profiles: keptContexts(kept?.ref) }),
174
+ driver: (await import("@parcha/pi-browser/driver/stagehand")).stagehandDriver(),
175
+ };
176
+ // The save flag every session carries is this launch's (asHanded), never the one stored with its conversation.
177
+ const handedProvider = parts.provider ? asHanded(parts.provider, kept) : undefined;
178
+ const provider = () => {
179
+ if (refused)
180
+ throw refused;
181
+ return handedProvider;
182
+ };
183
+ // Its session time is the run's spend, at its provider's price, and held under the run's cap (browser-cost.ts).
184
+ const providerName = parts.provider?.name ?? vendor;
185
+ const price = browserPrice(providerName, host.env);
186
+ const spend = browserSpend(providerName, price, DEFAULT_BROWSER_POLICY.idleReleaseS, (conversation, at) => browser.release(conversation, "close", at));
187
+ // browser_downloads is listed only with a workspace to copy into, and only a provider that keeps a session's downloads
188
+ // (Browserbase's; Kernel's keeps none) has any: without one, uploads still read the run's work/, through `files`.
189
+ const downloads = typeof parts.provider?.downloads === "object";
190
+ const files = downloads ? { workspace: () => host.where.work } : { files: workspaceFiles(host.where.work) };
191
+ // 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.
192
+ const saved = kept?.save
193
+ ? { onSession: (row, change) => void (savedOnRelease(row, change) && writeFileSync(join(host.where.root, SIGN_IN_SAVED), new Date().toISOString(), { mode: 0o600 })) }
194
+ : {};
195
+ // The pointer is cut from everything the browser hands the model (its results, their details, its failures): a
196
+ // vendor's refusal can quote it, as pi-browser's one-saver rule names Kernel's profile.
197
+ // A run handed its agent's sign-in tells the model its browser keeps it (`run`'s description): one with none claims
198
+ // cookies across pages only.
199
+ const browser = createBrowserExtension({ provider, driver: parts.driver, evidence: evidenceIn(host.where.work), ...files, ...saved, signIns: kept !== undefined, redact: { values: () => (kept ? [kept.ref] : []) }, prices: { sessionUsdPerHour: price.usdPerHour, sessionMinimumS: price.minimumS }, onCharge: spend.onCharge });
200
+ const tools = browser.tools.map(spend.capped);
201
+ const extension = { ...browser.extension, tools };
124
202
  host.install(extension);
125
203
  host.onConversation(async (tx, conversationId) => {
126
- Object.assign(await tx.doc(browser.docs.Config, conversationId), { label: "run", run: host.where.ref.id, policy: DEFAULT_BROWSER_POLICY });
204
+ // The profile is the host's choice, never the model's: the agent's one sign-in, when the run was handed it.
205
+ const policy = kept ? { ...DEFAULT_BROWSER_POLICY, profile: { name: SIGN_IN_KEY, save: kept.save } } : DEFAULT_BROWSER_POLICY;
206
+ Object.assign(await tx.doc(browser.docs.Config, conversationId), { label: "run", run: host.where.ref.id, policy });
207
+ });
208
+ host.beforeResume(async (harness) => {
209
+ // Its charges move what the process counts once each is committed, reconcile's own among them.
210
+ spend.watch(harness, browser.docs.Inventory.definition.kind);
211
+ // With its vendor's key gone there is no session to reconcile or release from here: each would only fail.
212
+ if (refused)
213
+ return;
214
+ // Every session custody still tracks across a restart is held from here; one kept is released an idle window on
215
+ // unless a call uses it.
216
+ await browser.reconcile(harness, () => true, context);
217
+ await spend.reopened(harness, browser.docs, context);
127
218
  });
128
- host.beforeResume(async (harness) => void (await browser.reconcile(harness, () => true, context)));
129
219
  host.beforeRelease(async (harness) => {
220
+ if (refused)
221
+ return;
130
222
  const held = await harness.snapshot(browser.docs.Inventory, context);
131
223
  for (const id of new Set(Object.values(held?.rows ?? {}).filter((row) => row.state !== "released").map((row) => row.conversationId))) {
132
224
  const conversation = await harness.conversation(id, context);
@@ -135,7 +227,7 @@ const browserTool = {
135
227
  }
136
228
  await browser.drain(harness, context);
137
229
  });
138
- return { tools: browser.tools, extensions: [extension] };
230
+ return { tools, extensions: [extension] };
139
231
  },
140
232
  };
141
233
  export const TOOLS = Object.freeze({
@@ -143,6 +235,12 @@ export const TOOLS = Object.freeze({
143
235
  write: fileTool("write", "Write a file in the run's work/."),
144
236
  edit: fileTool("edit", "Edit a file in the run's work/."),
145
237
  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),
238
+ // The background tools (background.ts): each call a short command in the run's box, on bash's environment.
239
+ 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 (a terminal with tty: true), 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),
240
+ 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),
241
+ bash_input: fileTool("bash_input", "Write text to a running background process's stdin, and close it if asked. Sandbox only.", true),
242
+ bash_signal: fileTool("bash_signal", "Send TERM, INT or KILL to a background process's process group. Sandbox only.", true),
243
+ bash_list: fileTool("bash_list", "List the run's background processes: id, state or exit code, output size and command. Sandbox only.", true),
146
244
  [ASK_TOOL]: {
147
245
  summary: "Ask the person who started the run; the turn ends until a message answers.",
148
246
  needs: [],
@@ -176,10 +274,27 @@ export const CALL_TOOLS = Object.keys(TOOLS).filter((name) => TOOLS[name].effect
176
274
  /** Whether `name` is one of `allowed`, or a legacy name for one (fetch_page, web_fetch's): a revision that names it
177
275
  * still saves and runs, though the table lists it no more. */
178
276
  export const allows = (allowed, name) => allowed.includes(capabilityOf(name));
179
- /** The tools a run's learned workflow draft may name (learn/check.ts): those of the agent's `granted` tools a workflow's
180
- * model or call node runs here (NODE_TOOLS, CALL_TOOLS), each as granted and by its capability's name. A harness's own
181
- * tool (Bash, exec_command, apply_patch) is never one, so the DSL refuses a draft that names it. */
182
- export const learnedWorkflowTools = (granted) => [...new Set(granted.filter((name) => allows(NODE_TOOLS, name) || allows(CALL_TOOLS, name)).flatMap((name) => [name, capabilityOf(name)]))];
277
+ /** The tools a run's learned workflow may name (learn/check.ts at learn time, learned-workflow.ts at a call): those of the
278
+ * agent's `granted` tools a workflow's call node runs here (CALL_TOOLS), each as granted and by its capability's name,
279
+ * and with the run's `plane`, none it resolves unavailable (its agent's own tool of the name does not run either). A
280
+ * learned model node runs without tools (learn/skills.ts MODEL_NODE_TOOLS), and a harness's own tool (Bash,
281
+ * exec_command, apply_patch) is never one, so the DSL refuses a draft that names it. */
282
+ export const learnedWorkflowTools = (granted, plane) => [...new Set(granted.filter((name) => allows(CALL_TOOLS, name) && !isUnavailable(plane?.[capabilityOf(name)])).flatMap((name) => [name, capabilityOf(name)]))];
283
+ /** The tools a learned draft may name (learnedWorkflowTools) that the gate allows: `permission` is what the gate holds a
284
+ * tool to now (tool-gate.ts permissionOf, or the run's gate's policy), by its capability's settings key, as the gate
285
+ * 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
286
+ * in `gated` with its setting, which the checker and a learned workflow's check before it runs refuse a draft for. */
287
+ export const learnedDraftTools = (granted, permission, plane) => {
288
+ const gated = {};
289
+ const tools = learnedWorkflowTools(granted, plane).filter((name) => {
290
+ const setting = permission(capabilityOf(name));
291
+ if (setting === "allow")
292
+ return true;
293
+ gated[name] = setting;
294
+ return false;
295
+ });
296
+ return { tools, gated };
297
+ };
183
298
  /** The tools a workflow names (`nodes` from workflowNodes): on its model nodes (`tools`), and on its `call` nodes
184
299
  * `via: "tool"` (`tool`). */
185
300
  export function workflowTools(nodes) {
@@ -226,8 +341,8 @@ export function toolRefusal(names, env, where = "agent") {
226
341
  const lacking = Object.entries(missing);
227
342
  if (!lacking.length)
228
343
  return undefined;
229
- const said = lacking.map(([name, vars]) => `the tool ${name} needs ${vars.join(" and ")}`).join("; ");
230
- return { message: `This server's environment does not set what the revision's tools need: ${said}.`, unbound: [], missing };
344
+ const said = lacking.map(([name, vars]) => `The tool ${name} needs ${keyNeeded(vars)}.`).join(" ");
345
+ return { message: `This server holds no key for what the revision's tools need. ${said}`, unbound: [], missing };
231
346
  }
232
347
  /** Every tool as capabilities show it, the server's one tool catalog: available here, or the variables it is missing
233
348
  * (names only), and the harnesses that run it (another harness than pi runs only the host tools, host-tools.ts). A tool
@@ -235,8 +350,11 @@ export function toolRefusal(names, env, where = "agent") {
235
350
  * sets none), the default, and what it resolves to on each harness under the server's `settings`: available where any
236
351
  * is not unavailable, and missing PARALLEL_API_KEY where Parallel is picked without it. An unavailable tool says why
237
352
  * (`reason`). `noBox`: why no box can run a sandbox-only tool here (place.ts noBoxReason), which leaves it
238
- * unavailable with that reason; undefined, a box can. */
239
- export const toolsView = (env, settings = {}, noBox) => {
353
+ * unavailable with that reason; undefined, a box can. `refused`: the variables of the keys this server was started with
354
+ * that their provider refused at the start (ToolKeys.refused), each with why: a tool that needs one is unavailable,
355
+ * saying that. Each tool also gives its permission under the server's settings (tool-gate.ts), the owner's default
356
+ * and the permissions it may be set to. */
357
+ export const toolsView = (env, settings = {}, noBox, refused = {}) => {
240
358
  const views = explainsView(env, settings);
241
359
  const picked = withDefaults(settings);
242
360
  return Object.entries(TOOLS).map(([name, entry]) => {
@@ -244,10 +362,14 @@ export const toolsView = (env, settings = {}, noBox) => {
244
362
  const plane = view?.resolves;
245
363
  const missing = plane && Object.values(plane).includes(NO_PARALLEL_KEY) ? [PARALLEL_KEY_ENV] : missingEnv(entry, env);
246
364
  const boxless = entry.sandboxOnly ? noBox : undefined;
247
- const available = (plane ? Object.values(plane).some((resolution) => !isUnavailable(resolution)) : missing.length === 0) && boxless === undefined;
365
+ // The browser needs the keys of the vendor it resolves to: one refused at the start leaves it unavailable, never on the
366
+ // other vendor, as a refused Parallel key never moves web_search elsewhere.
367
+ const needs = name === "browser" ? [...new Set(Object.values(plane ?? {}).flatMap(browserNeeds))] : entry.needs;
368
+ const refusal = needs.map((name) => (Object.hasOwn(refused, name) ? refused[name] : undefined)).find((why) => why !== undefined);
369
+ const available = (plane ? Object.values(plane).some((resolution) => !isUnavailable(resolution)) : missing.length === 0) && boxless === undefined && refusal === undefined;
248
370
  // Unavailable says why: a sandbox-only tool no box here can run, why none can (`noBox`); on a tool a user picks a
249
371
  // provider for, the resolutions' own words (`web_search is turned off in settings`); else the variables it needs.
250
- const reason = available ? undefined : boxless ?? (plane ? [...new Set(Object.values(plane).filter(isUnavailable).map(whyUnavailable))].join("; ") : `Needs ${missing.join(", ")}`);
251
- 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], ...(plane ? { providers: [...PROVIDERS[name]], provider: picked[name].provider, default_provider: PROVIDERS[name][0], resolves: plane, why: view.why } : {}) };
372
+ const reason = available ? undefined : refusal ?? boxless ?? (plane ? [...new Set(Object.values(plane).filter(isUnavailable).map(whyUnavailable))].join("; ") : `Needs ${keyNeeded(missing)}`);
373
+ 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 } : {}) };
252
374
  });
253
375
  };
@@ -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;
@@ -0,0 +1,143 @@
1
+ // Each webhook trigger's signing secret (triggers.ts): `whsec_` and 32 random bytes in base64, as the Standard Webhooks
2
+ // spec gives one, made at the trigger's create or a rotation, shown that once, and kept in DIR/trigger-secrets.json only
3
+ // sealed under the seal key (tool-keys.ts), each bound to its trigger by its AAD. With no seal key none is kept, never in
4
+ // the clear, so no webhook trigger is made.
5
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
6
+ import { readFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { seal, unseal } from "@parcha/pi-durable-agent";
9
+ import { ApiError } from "./errors.js";
10
+ import { writeDurableSync } from "./files.js";
11
+ import { SEAL_KEY_ENV, sealKeyOf } from "./tool-keys.js";
12
+ import { isObject } from "./validate.js";
13
+ export const TRIGGER_SECRETS_FILE = "trigger-secrets.json";
14
+ const aad = (triggerId) => `trigger-secret|${triggerId}`;
15
+ /** The sealed secrets `file` keeps, by trigger id: none when there is no file, and why not when it does not read. */
16
+ function sealedIn(file) {
17
+ let text;
18
+ try {
19
+ text = readFileSync(file, "utf8");
20
+ }
21
+ catch (error) {
22
+ return error.code === "ENOENT" ? { sealed: {} } : { unreadable: error.message };
23
+ }
24
+ try {
25
+ const doc = JSON.parse(text);
26
+ if (!isObject(doc) || doc.v !== 1 || !isObject(doc.secrets) || !Object.values(doc.secrets).every((v) => typeof v === "string"))
27
+ return { unreadable: "not a trigger secrets file of version 1" };
28
+ return { sealed: doc.secrets };
29
+ }
30
+ catch (error) {
31
+ return { unreadable: error.message };
32
+ }
33
+ }
34
+ const opened = (key, sealed) => Object.fromEntries(Object.entries(sealed).flatMap(([id, value]) => {
35
+ try {
36
+ return [[id, unseal(key, Buffer.from(value, "base64"), aad(id)).toString("utf8")]];
37
+ }
38
+ catch {
39
+ return [];
40
+ }
41
+ }));
42
+ /** The trigger secrets data directory `data` keeps, opened with the seal key of `env` (those that open): what an import
43
+ * cuts out of everything it writes. */
44
+ export function triggerSecretsIn(data, env) {
45
+ const key = sealKeyOf(env[SEAL_KEY_ENV]);
46
+ const read = sealedIn(join(data, TRIGGER_SECRETS_FILE));
47
+ return key && "sealed" in read ? Object.values(opened(key, read.sealed)) : [];
48
+ }
49
+ export class TriggerSecrets {
50
+ file;
51
+ key;
52
+ /** Opened, by trigger id: read once at start, then kept with every write. */
53
+ secrets;
54
+ sealed = {};
55
+ /** Why the file does not read: no secret is made or rotated, none signs, and the file is never written over. */
56
+ unreadable;
57
+ constructor(data, env, say = () => { }) {
58
+ this.file = join(data, TRIGGER_SECRETS_FILE);
59
+ this.key = sealKeyOf(env[SEAL_KEY_ENV]);
60
+ const read = sealedIn(this.file);
61
+ if ("sealed" in read)
62
+ this.sealed = read.sealed;
63
+ else {
64
+ this.unreadable = read.unreadable;
65
+ say({ condition: "trigger_secrets_unreadable", file: this.file, error: read.unreadable });
66
+ }
67
+ this.secrets = this.key ? opened(this.key, this.sealed) : {};
68
+ }
69
+ get sealing() {
70
+ return this.key ? "sealed" : "unavailable";
71
+ }
72
+ /** A new secret for `triggerId`, written sealed before it is answered: its only showing. */
73
+ mint(triggerId) {
74
+ if (this.unreadable)
75
+ throw new ApiError("store_unreadable", `${TRIGGER_SECRETS_FILE} in the data directory does not read (${this.unreadable}); it is never written over, so no webhook trigger's secret is made or rotated. Fix it or move it away, then restart.`);
76
+ if (!this.key)
77
+ throw new ApiError("no_sealing_key", `This server was handed no seal key (${SEAL_KEY_ENV}), so it keeps no webhook trigger's secret: it never keeps one in the clear.`);
78
+ const secret = `whsec_${randomBytes(32).toString("base64")}`;
79
+ this.write({ ...this.sealed, [triggerId]: seal(this.key, Buffer.from(secret, "utf8"), aad(triggerId)).toString("base64") });
80
+ this.secrets[triggerId] = secret;
81
+ return secret;
82
+ }
83
+ value(triggerId) {
84
+ return this.secrets[triggerId];
85
+ }
86
+ /** A deleted trigger's secret goes; with the file unreadable it stays in it, unread, as the file is never written over. */
87
+ remove(triggerId) {
88
+ if (this.unreadable || !(triggerId in this.sealed))
89
+ return;
90
+ const { [triggerId]: _, ...rest } = this.sealed;
91
+ this.write(rest);
92
+ delete this.secrets[triggerId];
93
+ }
94
+ /** Every secret held, for the redaction of what is shown. */
95
+ values() {
96
+ return Object.values(this.secrets);
97
+ }
98
+ write(sealed) {
99
+ writeDurableSync(this.file, `${JSON.stringify({ v: 1, secrets: sealed }, null, 2)}\n`);
100
+ this.sealed = sealed;
101
+ }
102
+ }
103
+ /** How far a request's `webhook-timestamp` may be from this server's clock, either way. */
104
+ export const HOOK_TOLERANCE_S = 300;
105
+ /** A webhook-id: printable ASCII with no space, as the spec's `msg_...` ids are; it goes into a firing's key and history. */
106
+ const HOOK_ID = /^[\x21-\x7e]{1,255}$/;
107
+ /** The longest `webhook-signature` list read: room for many keys during a rotation, never an unbounded loop. */
108
+ const MAX_SIGNATURES_CHARS = 2048;
109
+ /** The fewest bytes a signing key may have (the spec's secrets are 24 to 64; this server makes 32): a shorter one,
110
+ * an empty one above all, signs nothing. */
111
+ const MIN_KEY_BYTES = 24;
112
+ /** Why a request's webhook headers are refused before its body is read, or undefined when they may be checked:
113
+ * present, a webhook-id of printable ASCII, a bounded signature list, a timestamp within HOOK_TOLERANCE_S. */
114
+ export function hookHeadersRefusal(headers, nowMs) {
115
+ const [id, timestamp, signatures] = ["webhook-id", "webhook-timestamp", "webhook-signature"].map((name) => headers[name]);
116
+ if (typeof id !== "string" || typeof timestamp !== "string" || typeof signatures !== "string")
117
+ return "missing_headers";
118
+ if (!HOOK_ID.test(id) || signatures.length > MAX_SIGNATURES_CHARS)
119
+ return "malformed_headers";
120
+ if (!/^\d{1,12}$/.test(timestamp) || Math.abs(nowMs / 1000 - Number(timestamp)) > HOOK_TOLERANCE_S)
121
+ return "stale_timestamp";
122
+ return undefined;
123
+ }
124
+ /** Why a request to /v2/hooks/{id} is not signed by `secret` under the Standard Webhooks spec, or undefined when it is:
125
+ * `webhook-signature` lists `v1,<base64 HMAC-SHA256 of "{webhook-id}.{webhook-timestamp}.{body}">` signatures, space
126
+ * separated, under the secret's bytes, and any one that matches passes; the timestamp is within HOOK_TOLERANCE_S. */
127
+ export function hookRefusal(secret, headers, body, nowMs) {
128
+ const early = hookHeadersRefusal(headers, nowMs);
129
+ if (early)
130
+ return early;
131
+ const [id, timestamp, signatures] = ["webhook-id", "webhook-timestamp", "webhook-signature"].map((name) => headers[name]);
132
+ const key = Buffer.from(secret.slice("whsec_".length), "base64");
133
+ const expected = createHmac("sha256", key).update(`${id}.${timestamp}.`).update(body).digest();
134
+ // Compared all the same, so a short key costs what a good one does; it fails after.
135
+ const matched = signatures.split(" ").some((part) => {
136
+ const [version, signature] = part.split(",");
137
+ const given = Buffer.from(signature ?? "", "base64");
138
+ return version === "v1" && given.length === expected.length && timingSafeEqual(given, expected);
139
+ });
140
+ if (key.length < MIN_KEY_BYTES)
141
+ return "short_key";
142
+ return matched ? undefined : "bad_signature";
143
+ }