@parcha/agentrun-serve 0.1.0-beta.36 → 0.1.0-beta.37

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 (325) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +158 -52
  3. package/dist/attach-conformance-cli.d.ts +1 -0
  4. package/dist/attach-conformance-cli.js +18 -0
  5. package/dist/attach-conformance.d.ts +25 -0
  6. package/dist/attach-conformance.js +343 -0
  7. package/dist/browser-cost.d.ts +1 -1
  8. package/dist/browser-live.d.ts +20 -8
  9. package/dist/browser-live.js +50 -27
  10. package/dist/cap.d.ts +0 -17
  11. package/dist/cap.js +0 -91
  12. package/dist/catalog.d.ts +1 -12
  13. package/dist/catalog.js +3 -33
  14. package/dist/cli.js +13 -4
  15. package/dist/composio-preset.d.ts +36 -0
  16. package/dist/composio-preset.js +179 -0
  17. package/dist/computer-attach.d.ts +125 -0
  18. package/dist/computer-attach.js +330 -0
  19. package/dist/computer-calls.d.ts +48 -0
  20. package/dist/computer-calls.js +126 -0
  21. package/dist/computer-channel.d.ts +57 -0
  22. package/dist/computer-channel.js +115 -0
  23. package/dist/computer-commands.d.ts +1 -1
  24. package/dist/computer-held-routes.d.ts +35 -0
  25. package/dist/computer-held-routes.js +106 -0
  26. package/dist/computer-held.d.ts +48 -0
  27. package/dist/computer-held.js +87 -0
  28. package/dist/computer-keys.d.ts +21 -1
  29. package/dist/computer-keys.js +53 -11
  30. package/dist/computer-live.d.ts +160 -0
  31. package/dist/computer-live.js +643 -0
  32. package/dist/computer-view.d.ts +13 -0
  33. package/dist/computer-view.js +50 -3
  34. package/dist/computer-viewer.d.ts +6 -0
  35. package/dist/computer-viewer.js +297 -0
  36. package/dist/computers.d.ts +33 -7
  37. package/dist/computers.js +50 -8
  38. package/dist/console/assets/index-Cn6JX1uH.js +563 -0
  39. package/dist/console/assets/index-DRN62V5v.css +1 -0
  40. package/dist/console/index.html +2 -2
  41. package/dist/faux-computers.d.ts +9 -20
  42. package/dist/faux-computers.js +53 -25
  43. package/dist/github-connection.d.ts +10 -2
  44. package/dist/github-connection.js +65 -2
  45. package/dist/github-faux.js +1 -1
  46. package/dist/graph-view.d.ts +1 -1
  47. package/dist/harness.d.ts +1 -0
  48. package/dist/harness.js +35 -1
  49. package/dist/host-tools.d.ts +1 -1
  50. package/dist/hosted-search.d.ts +5 -4
  51. package/dist/hosted-search.js +2 -7
  52. package/dist/import-sources.d.ts +10 -0
  53. package/dist/import-sources.js +44 -2
  54. package/dist/import.d.ts +3 -3
  55. package/dist/import.js +37 -6
  56. package/dist/learn/check.d.ts +4 -1
  57. package/dist/learn/check.js +1 -1
  58. package/dist/learn/commit.d.ts +4 -2
  59. package/dist/learn/commit.js +5 -5
  60. package/dist/learn/folder.d.ts +6 -0
  61. package/dist/learn/folder.js +4 -1
  62. package/dist/learn/general.d.ts +66 -0
  63. package/dist/learn/general.js +73 -0
  64. package/dist/learn/grade.d.ts +4 -0
  65. package/dist/learn/grade.js +22 -1
  66. package/dist/learn/reflect.d.ts +10 -1
  67. package/dist/learn/reflect.js +14 -4
  68. package/dist/learn/skills.d.ts +33 -5
  69. package/dist/learn/skills.js +53 -7
  70. package/dist/learned-workflow.d.ts +24 -0
  71. package/dist/learned-workflow.js +66 -3
  72. package/dist/learning-batch.d.ts +283 -0
  73. package/dist/learning-batch.js +574 -0
  74. package/dist/learning-evals.d.ts +33 -0
  75. package/dist/learning-evals.js +98 -0
  76. package/dist/learning-routes.d.ts +25 -2
  77. package/dist/learning-routes.js +39 -6
  78. package/dist/learning-words.d.ts +6 -0
  79. package/dist/learning-words.js +6 -0
  80. package/dist/learning.d.ts +28 -15
  81. package/dist/learning.js +84 -44
  82. package/dist/live/stream.js +6 -3
  83. package/dist/live/translate.d.ts +4 -3
  84. package/dist/live/translate.js +8 -4
  85. package/dist/live-reach.d.ts +37 -0
  86. package/dist/live-reach.js +62 -0
  87. package/dist/mcp-gateway.d.ts +9 -0
  88. package/dist/mcp-gateway.js +60 -11
  89. package/dist/mcp-oauth.d.ts +57 -7
  90. package/dist/mcp-oauth.js +133 -18
  91. package/dist/mcp-private-hosts.d.ts +4 -4
  92. package/dist/mcp-private-hosts.js +20 -12
  93. package/dist/mcp-probe.d.ts +19 -2
  94. package/dist/mcp-probe.js +44 -9
  95. package/dist/mcp-secret-writes.js +4 -0
  96. package/dist/mcp-servers-store.d.ts +38 -15
  97. package/dist/mcp-servers-store.js +112 -20
  98. package/dist/mcp-store.d.ts +10 -4
  99. package/dist/mcp-store.js +17 -6
  100. package/dist/model-form.d.ts +26 -0
  101. package/dist/model-form.js +80 -0
  102. package/dist/model.js +23 -10
  103. package/dist/openapi.js +386 -21
  104. package/dist/page.d.ts +18 -0
  105. package/dist/page.js +48 -20
  106. package/dist/paid-calls.d.ts +1 -1
  107. package/dist/place-offers.d.ts +2 -3
  108. package/dist/place-offers.js +3 -7
  109. package/dist/place.js +1 -2
  110. package/dist/print.d.ts +15 -1
  111. package/dist/print.js +14 -3
  112. package/dist/propose.d.ts +3 -0
  113. package/dist/propose.js +13 -5
  114. package/dist/provider.js +3 -2
  115. package/dist/reflect-range.d.ts +8 -1
  116. package/dist/reflect-range.js +1 -1
  117. package/dist/run-launch.d.ts +14 -2
  118. package/dist/run-launch.js +9 -4
  119. package/dist/run-learning-served.d.ts +2 -2
  120. package/dist/run-reads-over-store.d.ts +1 -1
  121. package/dist/run-repo.d.ts +20 -0
  122. package/dist/run-repo.js +63 -0
  123. package/dist/run-timeline-served.d.ts +1 -1
  124. package/dist/run-view.d.ts +3 -3
  125. package/dist/run-view.js +14 -7
  126. package/dist/runner/adapter-loop.d.ts +23 -7
  127. package/dist/runner/adapter-loop.js +648 -62
  128. package/dist/runner/adapter-run-spec.d.ts +11 -3
  129. package/dist/runner/adapter-run-spec.js +77 -22
  130. package/dist/runner/adapters/pi-computer.d.ts +7 -0
  131. package/dist/runner/adapters/pi-computer.js +43 -0
  132. package/dist/runner/adapters/pi.d.ts +9 -4
  133. package/dist/runner/adapters/pi.js +76 -14
  134. package/dist/runner/beside.d.ts +7 -3
  135. package/dist/runner/beside.js +21 -11
  136. package/dist/runner/claim-secrets.d.ts +4 -0
  137. package/dist/runner/claim-secrets.js +6 -1
  138. package/dist/runner/cli-run-spec.d.ts +20 -3
  139. package/dist/runner/cli-run-spec.js +113 -43
  140. package/dist/runner/commands.d.ts +3 -1
  141. package/dist/runner/commands.js +28 -3
  142. package/dist/runner/computer-channel.d.ts +34 -0
  143. package/dist/runner/computer-channel.js +61 -0
  144. package/dist/runner/conformance/harness.js +80 -14
  145. package/dist/runner/conformance/subject.d.ts +1 -1
  146. package/dist/runner/dispatch.js +3 -0
  147. package/dist/runner/end-of-run.d.ts +22 -12
  148. package/dist/runner/end-of-run.js +38 -16
  149. package/dist/runner/github-app.d.ts +2 -1
  150. package/dist/runner/github-app.js +4 -2
  151. package/dist/runner/harness-loops.js +15 -1
  152. package/dist/runner/held-run.d.ts +65 -0
  153. package/dist/runner/held-run.js +158 -0
  154. package/dist/runner/journal-kinds.d.ts +20 -1
  155. package/dist/runner/journal-kinds.js +14 -0
  156. package/dist/runner/journal-reader.d.ts +5 -4
  157. package/dist/runner/journal-reader.js +12 -10
  158. package/dist/runner/learning-ask.d.ts +7 -1
  159. package/dist/runner/learning-ask.js +21 -6
  160. package/dist/runner/learning-dispatch.d.ts +22 -0
  161. package/dist/runner/learning-dispatch.js +77 -10
  162. package/dist/runner/learning-end.d.ts +22 -1
  163. package/dist/runner/learning-end.js +92 -12
  164. package/dist/runner/learning-factory.d.ts +1 -1
  165. package/dist/runner/learning-factory.js +11 -5
  166. package/dist/runner/learning-loop.d.ts +67 -7
  167. package/dist/runner/learning-loop.js +173 -21
  168. package/dist/runner/learning-seed.d.ts +7 -0
  169. package/dist/runner/learning-seed.js +13 -0
  170. package/dist/runner/live-ticker.js +1 -0
  171. package/dist/runner/loop-contract.d.ts +8 -1
  172. package/dist/runner/loop.d.ts +5 -1
  173. package/dist/runner/loop.js +2 -1
  174. package/dist/runner/main.d.ts +13 -1
  175. package/dist/runner/main.js +27 -5
  176. package/dist/runner/mcp-claim.d.ts +10 -7
  177. package/dist/runner/mcp-claim.js +113 -24
  178. package/dist/runner/mcp-github.js +1 -1
  179. package/dist/runner/mcp-run.d.ts +5 -5
  180. package/dist/runner/mcp-run.js +15 -3
  181. package/dist/runner/metrics.d.ts +11 -2
  182. package/dist/runner/metrics.js +12 -2
  183. package/dist/runner/pr-checkout.d.ts +1 -0
  184. package/dist/runner/pr-checkout.js +1 -1
  185. package/dist/runner/reflect-hook.d.ts +18 -0
  186. package/dist/runner/reflect-hook.js +20 -8
  187. package/dist/runner/runner.d.ts +26 -0
  188. package/dist/runner/runner.js +184 -15
  189. package/dist/runner/scratch-sweep.d.ts +13 -0
  190. package/dist/runner/scratch-sweep.js +62 -0
  191. package/dist/runner/sessions.d.ts +1 -1
  192. package/dist/runner/store-port.d.ts +4 -2
  193. package/dist/runner/store-secrets.js +4 -3
  194. package/dist/runner/subagent.js +3 -1
  195. package/dist/runner/workflow-host.d.ts +6 -1
  196. package/dist/runner/workflow-host.js +1 -1
  197. package/dist/runner/workflow-loop.d.ts +1 -1
  198. package/dist/runner/workflow-spec.d.ts +14 -2
  199. package/dist/runner/workflow-spec.js +56 -20
  200. package/dist/runs-over-store.d.ts +6 -1
  201. package/dist/runs-over-store.js +38 -9
  202. package/dist/seal-key.js +3 -3
  203. package/dist/sealed-settings-store.d.ts +5 -2
  204. package/dist/sealed-settings-store.js +10 -4
  205. package/dist/secret-writes.d.ts +5 -4
  206. package/dist/secret-writes.js +5 -4
  207. package/dist/server-secrets-store.d.ts +4 -3
  208. package/dist/server-secrets-store.js +15 -9
  209. package/dist/server-secrets.js +3 -2
  210. package/dist/server.d.ts +43 -14
  211. package/dist/server.js +472 -126
  212. package/dist/settings-wake.d.ts +21 -0
  213. package/dist/settings-wake.js +59 -0
  214. package/dist/standard-webhooks.d.ts +4 -1
  215. package/dist/standard-webhooks.js +8 -4
  216. package/dist/store/command-wake.d.ts +12 -0
  217. package/dist/store/command-wake.js +37 -0
  218. package/dist/store/dialect.d.ts +6 -0
  219. package/dist/store/dialect.js +5 -0
  220. package/dist/store/index.d.ts +1 -1
  221. package/dist/store/journal/storage.d.ts +3 -2
  222. package/dist/store/journal/storage.js +13 -5
  223. package/dist/store/postgres/dialect.js +4 -0
  224. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  225. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  226. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  227. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  228. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  229. package/dist/store/schema.d.ts +1 -1
  230. package/dist/store/schema.js +77 -8
  231. package/dist/store/sqlite/run-patch.d.ts +7 -5
  232. package/dist/store/sqlite/run-patch.js +28 -13
  233. package/dist/store/sqlite/store.js +272 -54
  234. package/dist/store/store.d.ts +268 -9
  235. package/dist/store/store.js +12 -1
  236. package/dist/store-reads/cap.d.ts +1 -1
  237. package/dist/store-reads/cap.js +8 -1
  238. package/dist/store-reads/decisions.d.ts +2 -2
  239. package/dist/store-reads/decisions.js +1 -1
  240. package/dist/store-reads/import-summary.d.ts +1 -1
  241. package/dist/store-reads/journal.d.ts +5 -4
  242. package/dist/store-reads/journal.js +73 -15
  243. package/dist/store-reads/learning.d.ts +20 -4
  244. package/dist/store-reads/learning.js +74 -18
  245. package/dist/store-reads/runs.d.ts +1 -1
  246. package/dist/store-reads/workflow.d.ts +1 -1
  247. package/dist/store-view.d.ts +5 -0
  248. package/dist/store-view.js +26 -11
  249. package/dist/template-eval.js +6 -4
  250. package/dist/template-github-permissions.d.ts +22 -8
  251. package/dist/template-github-permissions.js +35 -15
  252. package/dist/timeline/timeline.d.ts +27 -0
  253. package/dist/timeline/timeline.js +10 -9
  254. package/dist/timeline/util.d.ts +4 -0
  255. package/dist/timeline/util.js +14 -0
  256. package/dist/tool-budget.d.ts +19 -7
  257. package/dist/tool-budget.js +14 -8
  258. package/dist/tool-gate.d.ts +16 -9
  259. package/dist/tool-gate.js +53 -42
  260. package/dist/tool-plane.d.ts +16 -12
  261. package/dist/tool-plane.js +9 -4
  262. package/dist/tools.d.ts +13 -4
  263. package/dist/tools.js +13 -4
  264. package/dist/trigger-adapter.d.ts +4 -0
  265. package/dist/trigger-secrets-shown.d.ts +2 -2
  266. package/dist/trigger-secrets-shown.js +1 -1
  267. package/dist/trigger-signatures.d.ts +25 -6
  268. package/dist/trigger-signatures.js +41 -7
  269. package/dist/trigger-targets.d.ts +2 -0
  270. package/dist/trigger-targets.js +1 -0
  271. package/dist/trigger-webhook.js +5 -2
  272. package/dist/triggers.d.ts +7 -3
  273. package/dist/triggers.js +35 -5
  274. package/dist/turns.js +16 -1
  275. package/dist/validate.js +11 -1
  276. package/dist/web-fetch.d.ts +1 -1
  277. package/dist/web-search.d.ts +10 -5
  278. package/dist/web-search.js +7 -6
  279. package/dist/webhooks.d.ts +145 -102
  280. package/dist/webhooks.js +559 -322
  281. package/dist/workflow/decisions.d.ts +1 -1
  282. package/dist/workflow/node-runner.d.ts +2 -1
  283. package/dist/workflow/node.d.ts +2 -1
  284. package/dist/workflow/node.js +3 -1
  285. package/dist/workflow/pi-versions.d.ts +23 -0
  286. package/dist/workflow/pi-versions.js +57 -0
  287. package/dist/workflow/record-tool.d.ts +2 -1
  288. package/dist/workflow/store.d.ts +1 -1
  289. package/dist/workflow/task.js +3 -2
  290. package/dist/workflow-run.d.ts +1 -1
  291. package/dist/workspace/attached-computers.d.ts +41 -0
  292. package/dist/workspace/attached-computers.js +114 -0
  293. package/dist/workspace/computer-deps.d.ts +16 -9
  294. package/dist/workspace/computer-deps.js +19 -7
  295. package/dist/workspace/computer-for-claim.d.ts +17 -8
  296. package/dist/workspace/computer-for-claim.js +62 -21
  297. package/dist/workspace/computer-hold.d.ts +11 -27
  298. package/dist/workspace/computer-hold.js +36 -56
  299. package/dist/workspace/computer-ledger.d.ts +3 -1
  300. package/dist/workspace/computer-ledger.js +4 -0
  301. package/dist/workspace/computer-mcp.d.ts +25 -0
  302. package/dist/workspace/computer-mcp.js +41 -0
  303. package/dist/workspace/computer-ports.d.ts +4 -13
  304. package/dist/workspace/computer-ports.js +4 -107
  305. package/dist/workspace/computer-script.d.ts +37 -0
  306. package/dist/workspace/computer-script.js +138 -0
  307. package/dist/workspace/executors.d.ts +1 -1
  308. package/dist/workspace/index.d.ts +4 -2
  309. package/dist/workspace/index.js +3 -1
  310. package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
  311. package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
  312. package/dist/workspace/resolve-computer.d.ts +3 -0
  313. package/dist/workspace/resolve-computer.js +8 -2
  314. package/dist/workspace/run-tools.d.ts +32 -15
  315. package/dist/workspace/run-tools.js +23 -30
  316. package/package.json +19 -16
  317. package/templates/market-monitor/agent.md +1 -1
  318. package/dist/console/assets/index-BI4Byidu.js +0 -550
  319. package/dist/console/assets/index-C19gUF2n.css +0 -1
  320. package/dist/run-db.d.ts +0 -53
  321. package/dist/run-db.js +0 -116
  322. package/dist/workflow/readers.d.ts +0 -36
  323. package/dist/workflow/readers.js +0 -145
  324. package/dist/workflow/wal.d.ts +0 -11
  325. package/dist/workflow/wal.js +0 -106
package/dist/learning.js CHANGED
@@ -57,7 +57,8 @@ export function learningOf(env, given) {
57
57
  return value;
58
58
  }
59
59
  /** How much of what a run learned its instructions hold under `# Learned` by default, in UTF-8 bytes (learnedParts): its
60
- * notes whole while they fit, else the index and the notes changed last, whole, while they fit. */
60
+ * notes whole while they fit, else the notes that bear most on the run whole while they fit, then a line for each of
61
+ * the next while they fit; the rest are left out, and the run's log names them. */
61
62
  export const LEARNING_BUDGET = 8000;
62
63
  export const LEARNING_BUDGET_ENV = "AGENTRUN_SERVE_LEARNING_BUDGET";
63
64
  /** The learning budget: `given` (`--learning-budget`), else AGENTRUN_SERVE_LEARNING_BUDGET, else LEARNING_BUDGET. Any
@@ -74,7 +75,11 @@ export function learningBudgetOf(env, given) {
74
75
  * checks and is kept (propose.ts), `merged` once it is on main (runner/learning-loop.ts), or `dropped` with a
75
76
  * reason from the closed list. A learning fault never refuses a run: it starts with nothing learned, `seed_failed`. */
76
77
  export const LEARNING_STATES = ["seeded", "reflecting", "proposed", "merged", "dropped"];
77
- export const LEARNING_REASONS = ["seed_failed", "no_budget", "unknown_cost", "cancelled", "crashed", "reflect_timeout", "reflect_failed", "empty", "unparsed", "propose_failed", "checker", "grader", "grade_failed"];
78
+ export const LEARNING_REASONS = ["seed_failed", "no_budget", "unknown_cost", "cancelled", "crashed", "reflect_timeout", "reflect_failed", "empty", "unparsed", "propose_failed", "checker", "grader", "grade_failed", "use"];
79
+ /** A run's own `learning` on its start (POST /agents/{agent_id}/runs): it starts from what its agent learned, as a run that
80
+ * learns does, and keeps nothing (no end-of-run turn, no proposal, no grade, no merge, at any end), so runs of one agent
81
+ * read one learned state however many run at once. Its learning ends `dropped`, reason `use`. */
82
+ export const RUN_LEARNING_USE = "use";
78
83
  /** The variable that names the grader's model, as `--grade-model` does. */
79
84
  export const GRADE_MODEL_ENV = "AGENTRUN_SERVE_GRADE_MODEL";
80
85
  /** The model this server grades on, by name: `given` (`--grade-model`), else GRADE_MODEL_ENV, else its strong tier
@@ -407,23 +412,55 @@ export async function layLearned(work, seed, shown) {
407
412
  }
408
413
  /** All of `candidates` fit whole: every note within the budget, and an index that names no note main does not hold. */
409
414
  const allFit = ({ notes, indexComplete, budget }) => indexComplete && notes.reduce((sum, { bytes }) => sum + bytes, 0) <= budget;
415
+ /** Past the budget: the first `bearing` notes in `ranked`'s order (those that bear on the run), each whole while it fits
416
+ * what is left of the budget (one that does not is passed over for the next), then one rule line for each of the rest,
417
+ * in the same order, while it fits what the whole notes leave and no more than a run reads of the index (INDEX_LINES,
418
+ * INDEX_BYTES), the section's own lines counted. Whole notes come first: lines never take the room a whole note fits in, so past ~50 notes a run still
419
+ * reads the ones that bear on it whole (Run B, 11-12: past 8 KB of lines every run got lines alone). The rest are left
420
+ * out, and learnedParts names them. */
421
+ const withinBudget = (ranked, budget, read = true, bearing = ranked.length) => {
422
+ const whole = [];
423
+ // The section's own lines (its intro, the read-tool line when the run has the read tool, the blank lines around the
424
+ // rule lines) come first.
425
+ let room = budget - FRAME_BYTES(read);
426
+ for (const { note, bytes } of ranked.slice(0, bearing))
427
+ if (bytes <= room)
428
+ (room -= bytes), whole.push(note);
429
+ if (whole.length === ranked.length)
430
+ return { whole, index: false };
431
+ const taken = new Set(whole);
432
+ const lines = [];
433
+ let lineBytes = 0;
434
+ for (const { note, lineBytes: bytes } of ranked) {
435
+ if (taken.has(note) || lines.length >= INDEX_LINES || bytes > room || lineBytes + bytes > INDEX_BYTES)
436
+ continue;
437
+ room -= bytes;
438
+ lineBytes += bytes;
439
+ lines.push(note);
440
+ }
441
+ return { whole, index: false, lines };
442
+ };
410
443
  /** The selector by recency: every note whole while all fit the budget and the index names no note main does not hold
411
- * whole; else the index, then the newest notes that fit what it leaves, each whole. */
444
+ * whole; notes that fit with an index that names one it lacks, the index, then the newest notes that fit what it
445
+ * leaves, each whole; past the budget, the newest notes whole while they fit, then a line for each of the next while
446
+ * they fit (withinBudget). */
412
447
  export const byRecency = (candidates) => {
413
448
  const { notes, indexBytes, budget } = candidates;
414
449
  if (allFit(candidates))
415
450
  return { whole: notes.map(({ note }) => note), index: false };
451
+ if (notes.reduce((sum, { bytes }) => sum + bytes, 0) > budget)
452
+ return withinBudget(notes, budget, candidates.read);
416
453
  let left = budget - indexBytes;
417
454
  return { whole: notes.filter(({ bytes }) => bytes <= left && ((left -= bytes), true)).map(({ note }) => note), index: true };
418
455
  };
419
456
  /** The default selector, by relevance, past the budget: while the notes fit it, recency's choice (byRecency). Else each
420
457
  * note is scored against the run's input (learn/relevance.ts: BM25 over its name, description and body, a code
421
458
  * review's changed paths' words weighed PATH_WEIGHT; no model call), and the run reads the notes that bear on it most
422
- * whole, in score order, while they fit, then one rule line for each of the rest, best first, in place of the index; the lines count toward the
423
- * budget before the whole notes, as the index did, and no more of them than a run reads of the index (loadedIndex). An
424
- * input with no word any note holds reads by recency. */
459
+ * whole, best first, while they fit the budget, then one rule line for each of the next while they fit what is left
460
+ * (withinBudget), a note that bears on it in no word a line at most; the rest are left out. An input with no word any
461
+ * note holds reads by recency. */
425
462
  export const byRelevance = (candidates, run) => {
426
- // Within the budget, nothing changes: recency's choice (every note whole, or the index where it names a note main lacks).
463
+ // Within the budget, nothing changes: recency's choice (every note whole).
427
464
  if (candidates.notes.reduce((sum, { bytes }) => sum + bytes, 0) <= candidates.budget)
428
465
  return byRecency(candidates, run);
429
466
  const { notes, budget } = candidates;
@@ -432,26 +469,8 @@ export const byRelevance = (candidates, run) => {
432
469
  return byRecency(candidates, run);
433
470
  // Best first; a tie keeps recency (the candidates' order).
434
471
  const ranked = notes.map((candidate, i) => ({ ...candidate, score: scores[i], at: i })).sort((a, b) => b.score - a.score || a.at - b.at);
435
- // The lines of the rest, as the index was read (learn/notes.ts loadedIndex): the first INDEX_LINES, within INDEX_BYTES.
436
- const linesOf = (whole) => {
437
- let bytes = 0;
438
- return ranked.filter(({ note }) => !whole.has(note)).slice(0, INDEX_LINES).filter(({ lineBytes }) => (bytes += lineBytes) <= INDEX_BYTES);
439
- };
440
- const lineBytesOf = (whole) => linesOf(whole).reduce((sum, { lineBytes }) => sum + lineBytes, 0);
441
- // Promoted whole, best first, while the whole notes and the lines served of the rest fit: the room kept for lines is
442
- // only what is served of them (past INDEX_LINES or INDEX_BYTES a line is never served), never every note's.
443
- const whole = new Set();
444
- let wholeBytes = 0;
445
- for (const { note, bytes, score } of ranked) {
446
- if (score <= 0)
447
- break;
448
- whole.add(note);
449
- if (wholeBytes + bytes + lineBytesOf(whole) <= budget)
450
- wholeBytes += bytes;
451
- else
452
- whole.delete(note);
453
- }
454
- return { whole: ranked.filter(({ note }) => whole.has(note)).map(({ note }) => note), index: false, lines: linesOf(whole).map(({ note }) => note) };
472
+ // Only a note that bears on the run is read whole; one that shares no word with it is a line at most.
473
+ return withinBudget(ranked, budget, candidates.read, ranked.filter(({ score }) => score > 0).length);
455
474
  };
456
475
  /** The lines before what a run learned, under `# Learned` after LEARNS, and the one that names `.learning/` to an agent
457
476
  * that can read it. */
@@ -459,9 +478,18 @@ const KEPT = "Follow a note when it applies to what you are doing.";
459
478
  const WHOLE_INTRO = `What you learned in earlier runs: each note whole, newest first. ${KEPT}`;
460
479
  const SOME_INTRO = `What you learned in earlier runs: the index, one line per note, then the newest notes whole. ${KEPT}`;
461
480
  const INDEX_INTRO = `What you learned in earlier runs, one line per note. ${KEPT}`;
462
- const LINES_INTRO = `What you learned in earlier runs: the notes that bear most on this run whole, then one line for each of the rest. ${KEPT}`;
481
+ const LINES_INTRO = `What you learned in earlier runs: the notes that bear most on this run whole, then one line each for more of them. ${KEPT}`;
482
+ const BEST_INTRO = `What you learned in earlier runs: the notes that bear most on this run, each whole. ${KEPT}`;
483
+ const LINES_ONLY_INTRO = `What you learned in earlier runs: one line each for the notes that bear most on this run. ${KEPT}`;
463
484
  const READ_LINE = `The notes not given whole here are files in \`${LEARNED_DIR}/\` in your working directory: open one with the read tool when it applies.`;
464
485
  const oneLine = (text) => text.replace(/\s+/g, " ").trim();
486
+ /** What a run whose notes are all past a budget that holds none of them reads in place of them: that they are there, and,
487
+ * with the read tool, where. Never "Nothing learned yet." while it has notes. */
488
+ const NONE_FIT = "You learned notes in earlier runs, but none fit this run's learning budget, so none is given here.";
489
+ const NONE_FIT_READ = `You learned notes in earlier runs, but none fit this run's learning budget. They are files in \`${LEARNED_DIR}/\` in your working directory: open one with the read tool when it applies.`;
490
+ /** The most a section past the budget takes beside its notes and lines: its longest intro, the read-tool line when the run
491
+ * has the read tool (`read`), and the blank lines between its parts (withinBudget). */
492
+ const FRAME_BYTES = (read) => Math.max(...[LINES_INTRO, BEST_INTRO, LINES_ONLY_INTRO].map((intro) => Buffer.byteLength(intro))) + (read ? Buffer.byteLength(READ_LINE) + 2 : 0) + 4;
465
493
  /** A note as one rule line: its name and file, then its description, cut of the host's secrets. */
466
494
  const ruleLine = (note, shown) => `- ${shown.text(oneLine(note.name))} (${shown.name(note.file)}): ${shown.text(oneLine(note.description))}`;
467
495
  /** A note as a run reads it whole: its name and file, its description, then its body, each cut of the host's secrets. */
@@ -472,8 +500,10 @@ const wholeNote = (note, shown) => [`## ${shown.text(oneLine(note.name))} (${sho
472
500
  * the index, nor counted toward the budget (readSeed reads active notes alone, and servedIndex drops their lines). Its
473
501
  * active notes, newest first (`seed.recent`, else by name), each whole while all fit `budget`; past it, the selector's
474
502
  * choice (byRelevance by default). An agent with the read tool is told the rest are in `.learning/`, one without is not.
503
+ * Notes past a budget that holds none of them (0 among them) are said to be there (NONE_FIT), never "Nothing learned yet.".
475
504
  * Every text is cut of the host's secrets. A run "was given" `given`; of them, it "read" those whose file it opened
476
- * (store-reads/learning.ts notesReadOf). Whether it applied one given whole is not measured. */
505
+ * (store-reads/learning.ts notesReadOf). Whether it applied one given whole is not measured. `left`: the active notes
506
+ * the section names in no way, over the budget, which the run's log names (runner/learning-seed.ts). */
477
507
  export function learnedParts(seed, options) {
478
508
  const { budget, read, shown, select = byRelevance, run = {} } = options;
479
509
  const active = new Map(activeOf(seed).map((note) => [note.file, note]));
@@ -481,7 +511,7 @@ export function learnedParts(seed, options) {
481
511
  const index = servedIndex(seed);
482
512
  const lines = index === undefined ? [] : loadedIndex(index).split("\n").filter((entry) => entry.trim() !== "");
483
513
  if (!notes.length && !lines.length)
484
- return { section: undefined, given: [] };
514
+ return { section: undefined, given: [], left: [] };
485
515
  const blocks = new Map(notes.map((note) => [note, wholeNote(note, shown)]));
486
516
  // Each part's bytes, and the blank line before it.
487
517
  const size = (text) => Buffer.byteLength(text) + 2;
@@ -493,38 +523,45 @@ export function learnedParts(seed, options) {
493
523
  indexBytes: shownIndex ? size(shownIndex) : 0,
494
524
  indexComplete: lines.every((entry) => active.has(linkedFiles(entry)[0] ?? "")),
495
525
  budget,
526
+ read,
496
527
  }, run);
497
528
  const chosen = new Set(choice.whole);
498
529
  const whole = choice.whole.filter((note) => blocks.has(note)).map((note) => blocks.get(note));
499
530
  // Rule lines in place of the index: the whole notes first, then a line for each of the rest the selector names.
500
531
  if (choice.lines) {
501
532
  // The whole section fits the budget, its intro, blank lines and read-tool line counted: while it does not, the last
502
- // whole note goes to the head of the lines (what the selector ranked best of the rest), the lines capped again as the
503
- // index is read. Lines alone may pass the budget, as the index may.
533
+ // line goes, then the last whole note (whole notes are what a run reads past the budget, so they go last). The lines
534
+ // are capped as the index is read.
504
535
  const wholeNotes = choice.whole.filter((note) => blocks.has(note));
505
536
  // The lines as the index is read (learn/notes.ts loadedIndex): the first INDEX_LINES, within INDEX_BYTES, each line
506
- // and its newline counted. Applied again after every demotion, so a note demoted to a line never takes them past it.
537
+ // and its newline counted.
507
538
  const capped = (list) => {
508
539
  let bytes = 0;
509
540
  return list.slice(0, INDEX_LINES).filter((note) => (bytes += Buffer.byteLength(ruleLine(note, shown)) + 1) <= INDEX_BYTES);
510
541
  };
511
- let lined = capped(choice.lines.filter((note) => blocks.has(note) && !chosen.has(note)));
512
- const render = () => [LINES_INTRO, ...wholeNotes.map((note) => blocks.get(note)), lined.map((note) => ruleLine(note, shown)).join("\n"), ...(read && lined.length ? [READ_LINE] : [])].filter(Boolean).join("\n\n");
542
+ const lined = capped(choice.lines.filter((note) => blocks.has(note) && !chosen.has(note)));
543
+ const render = () => [!wholeNotes.length ? LINES_ONLY_INTRO : lined.length ? LINES_INTRO : BEST_INTRO, ...wholeNotes.map((note) => blocks.get(note)), lined.map((note) => ruleLine(note, shown)).join("\n"), ...(read && wholeNotes.length < notes.length ? [READ_LINE] : [])].filter(Boolean).join("\n\n");
513
544
  let section = render();
514
- while (Buffer.byteLength(section) > budget && wholeNotes.length) {
515
- lined = capped([wholeNotes.pop(), ...lined]);
545
+ while (Buffer.byteLength(section) > budget && (lined.length || wholeNotes.length)) {
546
+ if (lined.length)
547
+ lined.pop();
548
+ else
549
+ wholeNotes.pop();
516
550
  section = render();
517
551
  }
518
552
  const served = new Set([...wholeNotes, ...lined]);
519
- return { section, given: notes.filter((note) => served.has(note)) };
553
+ // Notes, none of which fit the budget (0 among them): the run is told they are there, never that it learned nothing.
554
+ if (!served.size)
555
+ return { section: notes.length ? (read ? NONE_FIT_READ : NONE_FIT) : undefined, given: [], left: notes };
556
+ return { section, given: notes.filter((note) => served.has(note)), left: notes.filter((note) => !served.has(note)) };
520
557
  }
521
558
  if (!choice.index)
522
- return { section: [WHOLE_INTRO, ...whole].join("\n\n"), given: notes.filter((note) => chosen.has(note)) };
559
+ return { section: [WHOLE_INTRO, ...whole].join("\n\n"), given: notes.filter((note) => chosen.has(note)), left: notes.filter((note) => !chosen.has(note)) };
523
560
  // Given: each note whole here, and each the index names by its file, by any of a line's links (a hand-edited line may
524
561
  // name more than one; linkedFiles, as servedIndex reads them).
525
562
  const indexed = new Set(lines.flatMap((entry) => linkedFiles(entry).filter((file) => active.has(file))));
526
563
  const given = notes.filter((note) => indexed.has(note.file) || chosen.has(note));
527
- return { section: [whole.length ? SOME_INTRO : INDEX_INTRO, shownIndex, ...(read && whole.length < notes.length ? [READ_LINE] : []), ...whole].filter(Boolean).join("\n\n"), given };
564
+ return { section: [whole.length ? SOME_INTRO : INDEX_INTRO, shownIndex, ...(read && whole.length < notes.length ? [READ_LINE] : []), ...whole].filter(Boolean).join("\n\n"), given, left: notes.filter((note) => !given.includes(note)) };
528
565
  }
529
566
  /** The run's skills folder, `.agents/skills`, as its Workspace names it. */
530
567
  const SKILLS_PATH = RUN_SKILLS.join("/");
@@ -729,16 +766,19 @@ export async function readPin(runDir) {
729
766
  }
730
767
  /** The heading of what a run learned, in its instructions. */
731
768
  export const LEARNED_HEADING = "# Learned";
769
+ /** What a run that only uses what its agent learned (RUN_LEARNING_USE) is told first under it, in place of LEARNS: it is
770
+ * never asked what to keep. */
771
+ const USES = "You learned from earlier runs, below. This run keeps nothing new: when the person asks you to remember something, tell them in one short sentence that this run can't keep it.";
732
772
  /** What every run that learns is told first under it, notes or none: a run not told it learns saves what the person
733
773
  * asks it to remember in a file, or says it cannot, and that is never kept. */
734
774
  const LEARNS = "You learn from your runs. When this run ends you are asked what to keep for later runs, anything the person asked you to remember included, and only your answer then is kept: a file you write is not. So when the person asks you to remember something, don't put it in a file or say you can't: tell them in one short sentence at the start of your reply that you will keep it for later runs. When what they asked sets how your reply starts or ends, follow it from your reply's first line to its last and leave that sentence out. A secret (a password, key or token) is never kept, so say so instead.";
735
775
  /** What a run that starts with no note is told in place of what it learned. */
736
776
  const NOTHING_YET = "Nothing learned yet.";
737
777
  /** A run's instructions with its # Learned section laid in main's position: the revision's instructions, then the heading,
738
- * LEARNS, and the section text — "Nothing learned yet." when the run learns but its section is empty (no notes yet, or a
739
- * seed that could not be read). Shared so the runner (laying launch.learning.section, read with no folder) and app.ts
740
- * (withLearned) lay the same bytes. */
741
- export const laidLearned = (instructions, section) => `${instructions.trim()}\n\n${LEARNED_HEADING}\n\n${LEARNS}\n\n${section || NOTHING_YET}`;
778
+ * LEARNS (USES for a run that only `use`s what its agent learned), and the section text — "Nothing learned yet." when the
779
+ * run learns but its section is empty (no notes yet, or a seed that could not be read). Shared so the runner (laying
780
+ * launch.learning.section, read with no folder) and app.ts (withLearned) lay the same bytes. */
781
+ export const laidLearned = (instructions, section, use = false) => `${instructions.trim()}\n\n${LEARNED_HEADING}\n\n${use ? USES : LEARNS}\n\n${section || NOTHING_YET}`;
742
782
  /** A run's instructions, with `# Learned` after them when its pin in `runDir` says it learns: that it learns, then what
743
783
  * the pin says it learned, or that it has learned nothing yet. A run with no pin (its agent does not learn, its seed
744
784
  * failed, a workflow's run) is never asked what to keep, so it is told nothing. And its skill files: the revision's
@@ -3,7 +3,7 @@
3
3
  // stored commit (live/translate.ts), in commit order, each batch naming its commit's seq so a reader that comes back
4
4
  // resumes from it; and beside them, never inside a commit's batch, what the runner holds before pi stores it (the run's
5
5
  // run_live row: a running tool, a partial answer), in the same vocabulary.
6
- import { RUN_RESUMED } from "../timeline/index.js";
6
+ import { REQUEST_ENDED, REQUEST_STARTED, RUN_RESUMED } from "../timeline/index.js";
7
7
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
8
8
  import { FINAL_STATES } from "../store/store.js";
9
9
  import { emptyState, snapshotOf, translate } from "./translate.js";
@@ -12,8 +12,11 @@ import { emptyState, snapshotOf, translate } from "./translate.js";
12
12
  * row — but it is not a live stream event: a takeover ends the door's watch, so a reader meets the note only in a
13
13
  * reconnect's snapshot, never as a commit on the open stream. The live view polls across a takeover, so without this it
14
14
  * would stream the note's entry_appended; dropping it keeps a run taken over mid-turn streaming the same events as one
15
- * that was not. The note stays in state.entries (translate pushed it before returning), so the next snapshot carries it. */
16
- const delivered = (events) => events.filter((event) => !(event.type === "entry_appended" && event.entry?.kind === RUN_RESUMED));
15
+ * that was not. The note stays in state.entries (translate pushed it before returning), so the next snapshot carries it.
16
+ * A request's start and end marks (REQUEST_STARTED, REQUEST_ENDED) are the same: bookkeeping the timeline reads for a
17
+ * request's cost, no event a watcher is shown. */
18
+ const NOT_STREAMED = new Set([RUN_RESUMED, REQUEST_STARTED, REQUEST_ENDED]);
19
+ const delivered = (events) => events.filter((event) => !(event.type === "entry_appended" && NOT_STREAMED.has(event.entry?.kind)));
17
20
  const PAGE = 500;
18
21
  /** The journals each store's watches read, by (run, epoch), with how many watches hold each. store.journal hands out one
19
22
  * journal per (run, epoch) and keeps it until it is closed: two watches of one run share it, and the last one to end
@@ -1,4 +1,4 @@
1
- import type { JsonValue } from "@earendil-works/chord";
1
+ import type { JsonValue } from "@earendil-works/chord/json";
2
2
  import { type EntryRecord, type SubmissionRecord } from "@earendil-works/pi-durable";
3
3
  import type { JournalCommit } from "../store/journal/storage.js";
4
4
  export type LiveEvent = {
@@ -36,8 +36,9 @@ export interface LiveState {
36
36
  }>;
37
37
  /** An answer streamed as a partial (held): its stored message is only its end. */
38
38
  partial: boolean;
39
- /** Where the run's end-of-run turn began (end-of-run.ts reflectFrom), once its input is placed: its messages from there
40
- * on carry the learning label, a tag the reader puts on (the run writes nothing for it). */
39
+ /** Where the run's end-of-run turn under way began (end-of-run.ts reflectRanges), once its input is placed, until the
40
+ * run's end closes it: its messages from there on carry the learning label, a tag the reader puts on (the run writes
41
+ * nothing for it). A follow-up's messages, after that end, carry none; its next end's turn begins anew. */
41
42
  reflectFrom?: number;
42
43
  }
43
44
  export declare function emptyState(): LiveState;
@@ -1,6 +1,6 @@
1
1
  import { AgentDoc, UsageDoc } from "@earendil-works/pi-durable";
2
2
  import { HOST_PHASE, RUN_RESUMED } from "../timeline/index.js";
3
- import { REFLECT_LABEL, reflectFrom } from "../runner/end-of-run.js";
3
+ import { inReflect, REFLECT_LABEL, reflectRanges } from "../runner/end-of-run.js";
4
4
  import { KINDS } from "../runner/journal-kinds.js";
5
5
  import { PI_STOP } from "../runner/pi-stop.js";
6
6
  export function emptyState() {
@@ -106,9 +106,13 @@ export function translate(state, commit) {
106
106
  const entries = commit.entries.filter(mine);
107
107
  const tasks = commit.tasks.filter(mine);
108
108
  const submissions = commit.submissions.filter(mine);
109
- // The end-of-run turn's input placed in this commit: its messages from there on are the turn's.
110
- state.reflectFrom ??= reflectFrom(submissions, entries);
111
- const tag = (entry) => (state.reflectFrom !== undefined && Number(entry.id) >= state.reflectFrom ? { agent_label: REFLECT_LABEL } : {});
109
+ // The end-of-run turn under way, and any whose input was placed in this commit: their messages, up to the run's end that
110
+ // closes each, are the turn's. One still open after this commit carries on to the next.
111
+ const endAt = (from) => entries.find((entry) => entry.kind === KINDS.end && Number(entry.id) >= from);
112
+ const carried = state.reflectFrom === undefined ? [] : [{ from: state.reflectFrom, ...(endAt(state.reflectFrom) ? { until: Number(endAt(state.reflectFrom).id) } : {}) }];
113
+ const ranges = [...carried, ...reflectRanges(submissions, entries)];
114
+ state.reflectFrom = ranges.filter((range) => range.until === undefined).at(-1)?.from;
115
+ const tag = (entry) => (inReflect(ranges, Number(entry.id)) ? { agent_label: REFLECT_LABEL } : {});
112
116
  for (const entry of entries) {
113
117
  const message = modelOf(entry);
114
118
  if (message?.role === "assistant" && Array.isArray(message.content)) {
@@ -0,0 +1,37 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ /** The header the proxy's proof travels in. */
3
+ export declare const LIVE_PROOF_HEADER = "x-agentrun-live";
4
+ /** How far a proof's time may be from the endpoint's clock. */
5
+ export declare const LIVE_PROOF_MS = 60000;
6
+ /** Where every viewer answers when its runner is on the server's own machine. */
7
+ export declare const LOOPBACK = "127.0.0.1";
8
+ export declare const isLiveHost: (host: unknown) => host is string;
9
+ /** What the server needs to reach a runner's viewer: the hosts it dials (its runners'), and the proof's key. */
10
+ export type LiveReach = {
11
+ readonly hosts: ReadonlySet<string>;
12
+ readonly key: Buffer;
13
+ };
14
+ /** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS) and the seal key. A name that is not a host is left
15
+ * out. */
16
+ export declare function liveReachOf(env: {
17
+ readonly AGENTRUN_RUNNER_HOSTS?: string | undefined;
18
+ }, sealKey: Buffer): LiveReach;
19
+ /** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners'; else nowhere. */
20
+ export declare function dialHost(host: string | undefined, reach: LiveReach | undefined): string | undefined;
21
+ /** The proxy's proof for viewer `viewerId`, at `at` (ms). */
22
+ export declare const liveProof: (reach: Pick<LiveReach, "key">, viewerId: string, at?: number) => string;
23
+ /** Where a runner's viewers answer: the host the server reaches it at (put in each row), the address they listen on,
24
+ * and the proof's key. */
25
+ export type RunnerLive = {
26
+ readonly host: string;
27
+ readonly bind: string;
28
+ readonly key: Buffer;
29
+ };
30
+ /** The runner's live host, from its environment (AGENTRUN_RUNNER_LIVE_HOST, AGENTRUN_RUNNER_LIVE_BIND) and the seal key;
31
+ * undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. */
32
+ export declare function runnerLiveOf(env: {
33
+ readonly AGENTRUN_RUNNER_LIVE_HOST?: string | undefined;
34
+ readonly AGENTRUN_RUNNER_LIVE_BIND?: string | undefined;
35
+ }, sealKey: Buffer): RunnerLive | undefined;
36
+ /** Whether `req` carries a good, fresh proof for viewer `viewerId` under `live`'s key. */
37
+ export declare function provenFor(req: Pick<IncomingMessage, "headers">, live: Pick<RunnerLive, "key">, viewerId: string, now?: number): boolean;
@@ -0,0 +1,62 @@
1
+ // A live viewer on a runner on another host than its server (one image, a server and its runners apart). The runner says
2
+ // where it answers (AGENTRUN_RUNNER_LIVE_HOST: a host name or IPv4 address the server reaches it at; the viewers listen
3
+ // on AGENTRUN_RUNNER_LIVE_BIND, that host by default) and puts that host in each viewer's row. The server dials a row's
4
+ // host only when it is one of its runners' (AGENTRUN_RUNNER_HOSTS, a comma list), else the row reads as no viewer: a
5
+ // store writer that is no runner can't aim the server's socket elsewhere. Each request the server makes of a runner's
6
+ // viewer (the HEAD that asks whether it answers, and the proxied WebSocket) carries the proxy's proof: an HMAC of the
7
+ // viewer's id and the time, under a key derived from the seal key the server and its runners already share. A runner's
8
+ // endpoint off loopback takes no request without a good, fresh proof for its own viewer. The proof is not the viewer's:
9
+ // the hello's token still decides who watches. The hop is plain HTTP, for a private network (the server and its
10
+ // runners' own); TLS on it is a later step.
11
+ import { createHmac, hkdfSync, timingSafeEqual } from "node:crypto";
12
+ /** The header the proxy's proof travels in. */
13
+ export const LIVE_PROOF_HEADER = "x-agentrun-live";
14
+ /** How far a proof's time may be from the endpoint's clock. */
15
+ export const LIVE_PROOF_MS = 60_000;
16
+ /** A host a row may name: a DNS name or an IPv4 address, nothing with a port, a path or a scheme. */
17
+ const HOST = /^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
18
+ /** Where every viewer answers when its runner is on the server's own machine. */
19
+ export const LOOPBACK = "127.0.0.1"; // key-gate: loopback-rule where a viewer on the same machine as its server answers
20
+ /** The derived key's label: the seal key itself is never a MAC key. */
21
+ const LABEL = "agentrun live proxy v1";
22
+ export const isLiveHost = (host) => typeof host === "string" && HOST.test(host);
23
+ const proofKey = (sealKey) => Buffer.from(hkdfSync("sha256", sealKey, Buffer.alloc(0), LABEL, 32));
24
+ const mac = (key, viewerId, at) => createHmac("sha256", key).update(`${viewerId}\n${at}`).digest("hex");
25
+ /** The server's reach, from its environment (AGENTRUN_RUNNER_HOSTS) and the seal key. A name that is not a host is left
26
+ * out. */
27
+ export function liveReachOf(env, sealKey) {
28
+ const hosts = new Set((env.AGENTRUN_RUNNER_HOSTS ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(isLiveHost));
29
+ return { hosts, key: proofKey(sealKey) };
30
+ }
31
+ /** Where the server dials `host` (a row's): loopback with none; the host when it is one of its runners'; else nowhere. */
32
+ export function dialHost(host, reach) {
33
+ if (host === undefined || host === LOOPBACK)
34
+ return LOOPBACK;
35
+ return reach?.hosts.has(host.toLowerCase()) ? host : undefined;
36
+ }
37
+ /** The proxy's proof for viewer `viewerId`, at `at` (ms). */
38
+ export const liveProof = (reach, viewerId, at = Date.now()) => `${at}.${mac(reach.key, viewerId, at)}`;
39
+ /** The runner's live host, from its environment (AGENTRUN_RUNNER_LIVE_HOST, AGENTRUN_RUNNER_LIVE_BIND) and the seal key;
40
+ * undefined with none (or one that is not a host): its viewers answer on loopback, as on a server's own machine. */
41
+ export function runnerLiveOf(env, sealKey) {
42
+ // Lower case, as a URL's hostname reads a DNS name and the server's runners' hosts are read (liveReachOf): one form for
43
+ // the links, the origins and the rows.
44
+ const host = env.AGENTRUN_RUNNER_LIVE_HOST?.trim().toLowerCase();
45
+ if (!isLiveHost(host) || host === LOOPBACK)
46
+ return undefined;
47
+ const bind = env.AGENTRUN_RUNNER_LIVE_BIND?.trim().toLowerCase();
48
+ return { host, bind: bind && (isLiveHost(bind) || bind === "0.0.0.0") ? bind : host, key: proofKey(sealKey) };
49
+ }
50
+ /** Whether `req` carries a good, fresh proof for viewer `viewerId` under `live`'s key. */
51
+ export function provenFor(req, live, viewerId, now = Date.now()) {
52
+ const said = req.headers[LIVE_PROOF_HEADER];
53
+ const match = typeof said === "string" ? /^(\d{1,16})\.([0-9a-f]{64})$/.exec(said) : null;
54
+ if (!match)
55
+ return false;
56
+ const at = Number(match[1]);
57
+ if (!Number.isSafeInteger(at) || Math.abs(now - at) > LIVE_PROOF_MS)
58
+ return false;
59
+ const want = Buffer.from(mac(live.key, viewerId, at), "hex");
60
+ const got = Buffer.from(match[2], "hex");
61
+ return got.length === want.length && timingSafeEqual(got, want);
62
+ }
@@ -69,6 +69,15 @@ export interface McpGatewayOptions {
69
69
  };
70
70
  /** The run's commit to its store: an unpriced call's "not metered" is written on its root. */
71
71
  commit?: () => McpCommit | undefined;
72
+ /** Where each request to a server may go, asked before anything is sent to it: the runner's MCP claim passes the
73
+ * address rule (mcp-oauth.ts mcpServerAt) with the owner's private-network hosts read now, and a fetch dialled at the
74
+ * address it checked (`send`; none, `fetch` as it is). A refusal is said to the model, nothing sent. None: every
75
+ * request goes as `fetch` sends it. */
76
+ reach?: (url: string, signal: AbortSignal) => Promise<{
77
+ refused: string;
78
+ } | {
79
+ send?: typeof fetch;
80
+ }>;
72
81
  /** The claim's per-call check of a server's credential (its custody stamp): awaited before each call is checked for
73
82
  * sending, it may drop the credential (`credentials[server].unopened`), which the call then refuses unsent; one that
74
83
  * throws (a store read failed, the call was stopped) refuses the call unsent too, in words, and the run goes on. Only
@@ -142,6 +142,26 @@ export function mcpPinOf(names, source) {
142
142
  }
143
143
  return pin;
144
144
  }
145
+ /** A request's address refused by the guarded fetch below, before anything left: thrown only there, and told apart by
146
+ * its class, never by its words. A server's error answer can carry the same words after it ran the call (the SDK puts
147
+ * the body of a failed POST in its error's message), and reading them as this refusal would say a call that may have
148
+ * run was never sent. */
149
+ class AddressRefused extends Error {
150
+ reason;
151
+ constructor(reason) {
152
+ super(`its address is refused here: ${reason}`);
153
+ this.reason = reason;
154
+ }
155
+ }
156
+ /** The reason of the address refusal an error is, or a cause the SDK wrapped it in: the one request's own, so a
157
+ * refusal of one call is never read as another's. */
158
+ function addressRefusal(error) {
159
+ for (let e = error, depth = 0; e && depth < 8; e = e.cause, depth++) {
160
+ if (e instanceof AddressRefused)
161
+ return e.reason;
162
+ }
163
+ return undefined;
164
+ }
145
165
  /** Why a connection failed, in a few words: the network's own code, read down the error's causes (the SDK wraps fetch's
146
166
  * error, which wraps the socket's), else the deepest message, cut short. */
147
167
  function unreachable(error) {
@@ -181,7 +201,8 @@ export function mcpGateway(options) {
181
201
  const clients = new Map();
182
202
  const pins = new Map(Object.entries(options.pin));
183
203
  const credentials = { get: (server) => (Object.hasOwn(options.credentials, server) ? options.credentials[server] : undefined) };
184
- /** Each server's last HTTP status, which tells a refused credential from another failure. */
204
+ /** Each server's last HTTP status, which tells a refused credential from another failure. (An address refusal is never
205
+ * kept here: it is read from each call's own error, since calls to one server run at once.) */
185
206
  const statuses = new Map();
186
207
  const send = options.fetch ?? fetch;
187
208
  /** The credential values each call in flight took or its server's requests sent while it was out, one set per call, by
@@ -216,11 +237,22 @@ export function mcpGateway(options) {
216
237
  const scrubberOf = (server, headers, values) => (text) => scrub(text, [...Object.values(headers), ...values, ...Object.values(credentials.get(server)?.headers ?? {})]);
217
238
  /** The fetch one server's client sends with: its credential added, no redirect followed, at most MAX_RESPONSE read. */
218
239
  const guarded = (server, headers, status) => async (input, init = {}) => {
240
+ // Its address checked first, every request: a name that resolves somewhere private now is refused before anything
241
+ // (its credential among it) leaves, and the request is dialled at the address checked.
242
+ let through = send;
243
+ if (options.reach) {
244
+ const at = await options.reach(input instanceof Request ? input.url : String(input), init.signal ?? AbortSignal.timeout(options.bounds?.connectMs ?? CONNECT_MS));
245
+ if ("refused" in at) {
246
+ throw new AddressRefused(at.refused);
247
+ }
248
+ if (at.send)
249
+ through = at.send;
250
+ }
219
251
  const sent = new Headers(init.headers);
220
252
  // Live credentials: the server's headers as they are at this request, held for the scrub before they leave.
221
253
  for (const [name, value] of Object.entries(hold(server, typeof headers === "function" ? headers() : headers)))
222
254
  sent.set(name, value);
223
- const response = await send(input, { ...init, headers: sent, redirect: "manual" });
255
+ const response = await through(input, { ...init, headers: sent, redirect: "manual" });
224
256
  status.last = response.status;
225
257
  if (response.status >= 300 && response.status < 400)
226
258
  throw new Error(`it answered a redirect (HTTP ${response.status}), which is never followed`);
@@ -296,7 +328,7 @@ export function mcpGateway(options) {
296
328
  * it, in `call` below: the one place every harness's call passes before anything is sent. */
297
329
  /** `sending`, when given, runs once the server is connected and right before the call leaves: its refusal (a text)
298
330
  * keeps the call from leaving. A call that never got that far (a failed connect, a stop) never ran it. */
299
- const forward = async (server, url, headers, tool, args, signal, sending) => {
331
+ const forward = async (server, url, headers, tool, args, signal, sending, outcome = {}) => {
300
332
  let connected = false;
301
333
  // Read at each use: a token refreshed while the call is out, and sent, is scrubbed with the one it took.
302
334
  const held = callSet(server);
@@ -319,6 +351,15 @@ export function mcpGateway(options) {
319
351
  return said(`The call to the MCP server ${server} was stopped.`, true);
320
352
  // The next call connects again (a server that dropped its session, say); this one is never sent again.
321
353
  clients.delete(server);
354
+ // Its address refused before the request left (reach): nothing reached it. Read from this call's own error, never
355
+ // from the server's shared state: another call's refusal says nothing of whether this one was sent.
356
+ const refused = addressRefusal(error);
357
+ if (refused !== undefined) {
358
+ // `sending` may have run already (the connection was open): the request's own address check refused it, so the call
359
+ // never left and `outcome` says so, for the caller that books a price only for a call that went.
360
+ outcome.unsent = true;
361
+ return said(`The MCP server ${server}'s address is refused here: ${refused}. Nothing was sent.`, true);
362
+ }
322
363
  const status = statuses.get(server)?.last;
323
364
  // An OAuth token that expired mid-run is not refreshed here (no channel to serve for it): the next launch does.
324
365
  if (status === 401 || status === 403)
@@ -376,11 +417,18 @@ export function mcpGateway(options) {
376
417
  const listed = pinnedTools.find((t) => t.name === tool);
377
418
  // Whether the call left for the server: only then is it booked, at its price or as not metered.
378
419
  let went = false;
379
- const call = (mark = async () => undefined) => forward(server, url, credentials.get(server)?.headers ?? {}, listed, args, signal, async () => {
380
- const refused = await mark();
381
- went = refused === undefined;
382
- return refused;
383
- });
420
+ const call = async (mark = async () => undefined) => {
421
+ const outcome = {};
422
+ const result = await forward(server, url, credentials.get(server)?.headers ?? {}, listed, args, signal, async () => {
423
+ const refused = await mark();
424
+ went = refused === undefined;
425
+ return refused;
426
+ }, outcome);
427
+ // The request's own address check refused it after the mark: it never left, so nothing is booked.
428
+ if (outcome.unsent)
429
+ went = false;
430
+ return result;
431
+ };
384
432
  const name = mcpToolName(server, tool);
385
433
  const label = { tool: name, charged_by: server, call: callId };
386
434
  const commit = options.commit?.();
@@ -404,9 +452,10 @@ export function mcpGateway(options) {
404
452
  servers: [...pins].map(([name, pinned]) => ({ name, tools: pinned.tools })),
405
453
  heldValues: () => [...new Set([...inFlight.values()].flatMap((calls) => [...calls].flatMap((values) => [...values])))],
406
454
  async call(server, tool, args, { signal, callId }) {
407
- const why = unsendable(server, tool);
408
- if (why)
409
- return said(why, true);
455
+ // Only what no sign-in can change is refused here: the rest (a credential that did not open, a server since removed)
456
+ // is read by sent() after beforeCall, which opens the row again, so a call after the owner signs in again goes.
457
+ if (!pins.get(server)?.tools.some((t) => t.name === tool))
458
+ return said(`${tool} is not a tool of the MCP server ${server} in this run.`, true);
410
459
  return sent(server, tool, args, callId ?? `mcp_${randomUUID()}`, signal);
411
460
  },
412
461
  };