@parcha/agentrun-serve 0.1.0-beta.35 → 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 (522) hide show
  1. package/CHANGELOG.md +298 -0
  2. package/README.md +417 -219
  3. package/dist/adapters.d.ts +12 -2
  4. package/dist/adapters.js +27 -2
  5. package/dist/agent-rows.d.ts +2 -1
  6. package/dist/agents-store.d.ts +2 -0
  7. package/dist/agents-store.js +9 -4
  8. package/dist/api-only.d.ts +2 -1
  9. package/dist/api-only.js +3 -1
  10. package/dist/archil-routes.d.ts +40 -7
  11. package/dist/archil-routes.js +167 -54
  12. package/dist/archil-settings.d.ts +79 -7
  13. package/dist/archil-settings.js +140 -14
  14. package/dist/attach-conformance-cli.d.ts +1 -0
  15. package/dist/attach-conformance-cli.js +18 -0
  16. package/dist/attach-conformance.d.ts +25 -0
  17. package/dist/attach-conformance.js +343 -0
  18. package/dist/attach-images.d.ts +15 -0
  19. package/dist/attach-images.js +59 -0
  20. package/dist/background.d.ts +0 -6
  21. package/dist/background.js +0 -28
  22. package/dist/box-image.d.ts +1 -97
  23. package/dist/box-image.js +4 -284
  24. package/dist/box-paths.d.ts +2 -7
  25. package/dist/box-paths.js +7 -13
  26. package/dist/box-settings.d.ts +0 -11
  27. package/dist/box-settings.js +4 -29
  28. package/dist/browser-commands.js +1 -1
  29. package/dist/browser-computer.d.ts +47 -3
  30. package/dist/browser-computer.js +286 -18
  31. package/dist/browser-cost.d.ts +1 -1
  32. package/dist/browser-live.d.ts +20 -8
  33. package/dist/browser-live.js +50 -27
  34. package/dist/browser-person.d.ts +19 -2
  35. package/dist/browser-person.js +55 -6
  36. package/dist/browser-wait-ended.d.ts +23 -0
  37. package/dist/browser-wait-ended.js +42 -0
  38. package/dist/cap.d.ts +12 -57
  39. package/dist/cap.js +20 -160
  40. package/dist/catalog.d.ts +1 -12
  41. package/dist/catalog.js +3 -33
  42. package/dist/cli.js +17 -26
  43. package/dist/composio-preset.d.ts +36 -0
  44. package/dist/composio-preset.js +179 -0
  45. package/dist/computer-attach.d.ts +125 -0
  46. package/dist/computer-attach.js +330 -0
  47. package/dist/computer-calls.d.ts +48 -0
  48. package/dist/computer-calls.js +126 -0
  49. package/dist/computer-channel.d.ts +57 -0
  50. package/dist/computer-channel.js +115 -0
  51. package/dist/computer-commands.d.ts +1 -1
  52. package/dist/computer-held-routes.d.ts +35 -0
  53. package/dist/computer-held-routes.js +106 -0
  54. package/dist/computer-held.d.ts +48 -0
  55. package/dist/computer-held.js +87 -0
  56. package/dist/computer-keys.d.ts +21 -1
  57. package/dist/computer-keys.js +53 -11
  58. package/dist/computer-live.d.ts +160 -0
  59. package/dist/computer-live.js +643 -0
  60. package/dist/computer-routes.d.ts +1 -4
  61. package/dist/computer-routes.js +3 -5
  62. package/dist/computer-setting.d.ts +2 -0
  63. package/dist/computer-setting.js +38 -1
  64. package/dist/computer-view.d.ts +24 -2
  65. package/dist/computer-view.js +51 -3
  66. package/dist/computer-viewer.d.ts +6 -0
  67. package/dist/computer-viewer.js +297 -0
  68. package/dist/computers.d.ts +79 -12
  69. package/dist/computers.js +147 -28
  70. package/dist/console/assets/index-Cn6JX1uH.js +563 -0
  71. package/dist/console/assets/index-DRN62V5v.css +1 -0
  72. package/dist/console/index.html +2 -2
  73. package/dist/docker-daemon.d.ts +2 -2
  74. package/dist/docker-daemon.js +2 -2
  75. package/dist/errors.js +5 -5
  76. package/dist/faux-computers.d.ts +9 -20
  77. package/dist/faux-computers.js +56 -24
  78. package/dist/files.d.ts +1 -9
  79. package/dist/files.js +1 -9
  80. package/dist/github-connection.d.ts +10 -2
  81. package/dist/github-connection.js +65 -2
  82. package/dist/github-faux.js +1 -1
  83. package/dist/github.d.ts +22 -2
  84. package/dist/github.js +42 -8
  85. package/dist/gpu-words.d.ts +14 -0
  86. package/dist/gpu-words.js +21 -0
  87. package/dist/graph-view.d.ts +3 -1
  88. package/dist/graph-view.js +25 -1
  89. package/dist/handed-values.d.ts +1 -1
  90. package/dist/handed-values.js +1 -1
  91. package/dist/harness-install.d.ts +60 -3
  92. package/dist/harness-install.js +322 -34
  93. package/dist/harness.d.ts +1 -0
  94. package/dist/harness.js +36 -2
  95. package/dist/host-tools.d.ts +9 -10
  96. package/dist/host-tools.js +7 -7
  97. package/dist/hosted-search.d.ts +5 -4
  98. package/dist/hosted-search.js +2 -7
  99. package/dist/import-sources.d.ts +10 -0
  100. package/dist/import-sources.js +44 -2
  101. package/dist/import.d.ts +3 -3
  102. package/dist/import.js +37 -6
  103. package/dist/index.d.ts +1 -3
  104. package/dist/index.js +1 -2
  105. package/dist/key-refusal.d.ts +1 -1
  106. package/dist/key-refusal.js +2 -2
  107. package/dist/learn/check.d.ts +11 -2
  108. package/dist/learn/check.js +124 -6
  109. package/dist/learn/commit.d.ts +43 -7
  110. package/dist/learn/commit.js +166 -22
  111. package/dist/learn/folder.d.ts +11 -0
  112. package/dist/learn/folder.js +37 -1
  113. package/dist/learn/general.d.ts +66 -0
  114. package/dist/learn/general.js +73 -0
  115. package/dist/learn/grade.d.ts +22 -1
  116. package/dist/learn/grade.js +107 -16
  117. package/dist/learn/index.d.ts +1 -1
  118. package/dist/learn/index.js +1 -1
  119. package/dist/learn/learning.sh +12 -1
  120. package/dist/learn/notes.d.ts +3 -0
  121. package/dist/learn/notes.js +3 -0
  122. package/dist/learn/reflect.d.ts +14 -2
  123. package/dist/learn/reflect.js +54 -30
  124. package/dist/learn/skills.d.ts +37 -5
  125. package/dist/learn/skills.js +60 -7
  126. package/dist/learned-nodes.d.ts +6 -2
  127. package/dist/learned-workflow.d.ts +43 -9
  128. package/dist/learned-workflow.js +128 -37
  129. package/dist/learning-batch.d.ts +283 -0
  130. package/dist/learning-batch.js +574 -0
  131. package/dist/learning-cost.d.ts +79 -0
  132. package/dist/learning-cost.js +69 -0
  133. package/dist/learning-evals.d.ts +33 -0
  134. package/dist/learning-evals.js +98 -0
  135. package/dist/learning-routes.d.ts +32 -4
  136. package/dist/learning-routes.js +48 -12
  137. package/dist/learning-words.d.ts +9 -0
  138. package/dist/learning-words.js +12 -2
  139. package/dist/learning.d.ts +39 -19
  140. package/dist/learning.js +88 -46
  141. package/dist/live/stream.js +6 -3
  142. package/dist/live/translate.d.ts +4 -3
  143. package/dist/live/translate.js +8 -4
  144. package/dist/live-reach.d.ts +37 -0
  145. package/dist/live-reach.js +62 -0
  146. package/dist/mcp-gateway.d.ts +9 -0
  147. package/dist/mcp-gateway.js +60 -11
  148. package/dist/mcp-oauth.d.ts +57 -7
  149. package/dist/mcp-oauth.js +133 -18
  150. package/dist/mcp-private-hosts.d.ts +4 -4
  151. package/dist/mcp-private-hosts.js +20 -12
  152. package/dist/mcp-probe.d.ts +27 -3
  153. package/dist/mcp-probe.js +106 -29
  154. package/dist/mcp-secret-writes.js +8 -0
  155. package/dist/mcp-servers-store.d.ts +38 -15
  156. package/dist/mcp-servers-store.js +120 -23
  157. package/dist/mcp-store.d.ts +10 -4
  158. package/dist/mcp-store.js +17 -6
  159. package/dist/model-form.d.ts +26 -0
  160. package/dist/model-form.js +80 -0
  161. package/dist/model.d.ts +5 -5
  162. package/dist/model.js +29 -16
  163. package/dist/openapi.d.ts +2 -0
  164. package/dist/openapi.js +586 -64
  165. package/dist/owner.d.ts +0 -1
  166. package/dist/owner.js +0 -2
  167. package/dist/page.d.ts +18 -0
  168. package/dist/page.js +48 -20
  169. package/dist/paid-calls.d.ts +1 -1
  170. package/dist/paid-calls.js +1 -1
  171. package/dist/place-offers.d.ts +96 -0
  172. package/dist/place-offers.js +202 -0
  173. package/dist/place.d.ts +9 -13
  174. package/dist/place.js +21 -32
  175. package/dist/port-models.d.ts +2 -1
  176. package/dist/port-models.js +5 -3
  177. package/dist/print.d.ts +16 -9
  178. package/dist/print.js +15 -17
  179. package/dist/propose.d.ts +4 -0
  180. package/dist/propose.js +34 -11
  181. package/dist/provider.js +3 -2
  182. package/dist/reflect-range.d.ts +8 -1
  183. package/dist/reflect-range.js +1 -1
  184. package/dist/run-cut.d.ts +5 -0
  185. package/dist/run-cut.js +19 -0
  186. package/dist/run-launch.d.ts +28 -3
  187. package/dist/run-launch.js +14 -4
  188. package/dist/run-learning-served.d.ts +2 -2
  189. package/dist/run-manifest.d.ts +2 -2
  190. package/dist/run-manifest.js +2 -2
  191. package/dist/run-reads-over-store.d.ts +1 -1
  192. package/dist/run-repo.d.ts +20 -0
  193. package/dist/run-repo.js +63 -0
  194. package/dist/run-secrets.js +3 -3
  195. package/dist/run-timeline-served.d.ts +1 -1
  196. package/dist/run-timeline-served.js +56 -44
  197. package/dist/run-view.d.ts +8 -5
  198. package/dist/run-view.js +18 -10
  199. package/dist/runnable.d.ts +2 -2
  200. package/dist/runnable.js +6 -2
  201. package/dist/runner/adapter-loop.d.ts +39 -8
  202. package/dist/runner/adapter-loop.js +770 -83
  203. package/dist/runner/adapter-run-spec.d.ts +36 -7
  204. package/dist/runner/adapter-run-spec.js +171 -37
  205. package/dist/runner/adapters/pi-computer.d.ts +7 -0
  206. package/dist/runner/adapters/pi-computer.js +43 -0
  207. package/dist/runner/adapters/pi.d.ts +20 -7
  208. package/dist/runner/adapters/pi.js +111 -26
  209. package/dist/runner/beside.d.ts +7 -3
  210. package/dist/runner/beside.js +26 -12
  211. package/dist/runner/claim-secrets.d.ts +4 -0
  212. package/dist/runner/claim-secrets.js +6 -1
  213. package/dist/runner/cli-run-spec.d.ts +27 -3
  214. package/dist/runner/cli-run-spec.js +198 -74
  215. package/dist/runner/commands.d.ts +8 -2
  216. package/dist/runner/commands.js +31 -6
  217. package/dist/runner/computer-channel.d.ts +34 -0
  218. package/dist/runner/computer-channel.js +61 -0
  219. package/dist/runner/conformance/harness.d.ts +0 -1
  220. package/dist/runner/conformance/harness.js +87 -18
  221. package/dist/runner/conformance/subject.d.ts +1 -1
  222. package/dist/runner/dispatch.js +3 -0
  223. package/dist/runner/end-of-run.d.ts +22 -12
  224. package/dist/runner/end-of-run.js +38 -16
  225. package/dist/runner/github-app.d.ts +2 -1
  226. package/dist/runner/github-app.js +6 -4
  227. package/dist/runner/harness-loops.js +16 -2
  228. package/dist/runner/held-run.d.ts +65 -0
  229. package/dist/runner/held-run.js +158 -0
  230. package/dist/runner/journal-kinds.d.ts +35 -6
  231. package/dist/runner/journal-kinds.js +20 -1
  232. package/dist/runner/journal-reader.d.ts +5 -4
  233. package/dist/runner/journal-reader.js +12 -10
  234. package/dist/runner/learning-ask.d.ts +7 -1
  235. package/dist/runner/learning-ask.js +21 -6
  236. package/dist/runner/learning-dispatch.d.ts +22 -0
  237. package/dist/runner/learning-dispatch.js +77 -10
  238. package/dist/runner/learning-end.d.ts +37 -1
  239. package/dist/runner/learning-end.js +115 -14
  240. package/dist/runner/learning-factory.d.ts +1 -1
  241. package/dist/runner/learning-factory.js +15 -5
  242. package/dist/runner/learning-loop.d.ts +139 -7
  243. package/dist/runner/learning-loop.js +369 -32
  244. package/dist/runner/learning-seed.d.ts +9 -0
  245. package/dist/runner/learning-seed.js +14 -1
  246. package/dist/runner/live-ticker.js +1 -0
  247. package/dist/runner/loop-contract.d.ts +16 -1
  248. package/dist/runner/loop-contract.js +6 -0
  249. package/dist/runner/loop.d.ts +10 -2
  250. package/dist/runner/loop.js +22 -1
  251. package/dist/runner/main.d.ts +13 -1
  252. package/dist/runner/main.js +38 -6
  253. package/dist/runner/mcp-claim.d.ts +11 -4
  254. package/dist/runner/mcp-claim.js +140 -23
  255. package/dist/runner/mcp-github.d.ts +4 -2
  256. package/dist/runner/mcp-github.js +1 -8
  257. package/dist/runner/mcp-run.d.ts +6 -4
  258. package/dist/runner/mcp-run.js +16 -3
  259. package/dist/runner/metrics.d.ts +15 -2
  260. package/dist/runner/metrics.js +21 -2
  261. package/dist/runner/model-route.d.ts +3 -0
  262. package/dist/runner/model-route.js +5 -2
  263. package/dist/runner/pr-checkout.d.ts +60 -0
  264. package/dist/runner/pr-checkout.js +176 -0
  265. package/dist/runner/reflect-hook.d.ts +19 -0
  266. package/dist/runner/reflect-hook.js +20 -8
  267. package/dist/runner/runner.d.ts +26 -0
  268. package/dist/runner/runner.js +231 -27
  269. package/dist/runner/scratch-sweep.d.ts +13 -0
  270. package/dist/runner/scratch-sweep.js +62 -0
  271. package/dist/runner/sessions.d.ts +1 -1
  272. package/dist/runner/spec-holds.d.ts +8 -3
  273. package/dist/runner/spec-holds.js +12 -10
  274. package/dist/runner/store-port.d.ts +7 -2
  275. package/dist/runner/store-secrets.js +21 -4
  276. package/dist/runner/subagent.d.ts +44 -0
  277. package/dist/runner/subagent.js +190 -0
  278. package/dist/runner/workflow-host.d.ts +24 -3
  279. package/dist/runner/workflow-host.js +24 -4
  280. package/dist/runner/workflow-loop.d.ts +6 -3
  281. package/dist/runner/workflow-loop.js +9 -8
  282. package/dist/runner/workflow-spec.d.ts +39 -15
  283. package/dist/runner/workflow-spec.js +143 -40
  284. package/dist/runs-over-store.d.ts +16 -6
  285. package/dist/runs-over-store.js +145 -29
  286. package/dist/seal-key.js +3 -3
  287. package/dist/sealed-settings-store.d.ts +5 -2
  288. package/dist/sealed-settings-store.js +10 -4
  289. package/dist/sealing.js +1 -2
  290. package/dist/secret-cut.d.ts +1 -1
  291. package/dist/secret-cut.js +1 -1
  292. package/dist/secret-writes.d.ts +5 -4
  293. package/dist/secret-writes.js +5 -4
  294. package/dist/server-secrets-store.d.ts +4 -3
  295. package/dist/server-secrets-store.js +15 -9
  296. package/dist/server-secrets.js +3 -2
  297. package/dist/server.d.ts +75 -63
  298. package/dist/server.js +712 -316
  299. package/dist/settings-wake.d.ts +21 -0
  300. package/dist/settings-wake.js +59 -0
  301. package/dist/standard-webhooks.d.ts +4 -1
  302. package/dist/standard-webhooks.js +8 -4
  303. package/dist/store/agent-body.d.ts +9 -2
  304. package/dist/store/agent-body.js +16 -8
  305. package/dist/store/command-wake.d.ts +12 -0
  306. package/dist/store/command-wake.js +37 -0
  307. package/dist/store/deadline.js +9 -5
  308. package/dist/store/dialect.d.ts +6 -0
  309. package/dist/store/dialect.js +5 -0
  310. package/dist/store/index.d.ts +4 -4
  311. package/dist/store/index.js +2 -2
  312. package/dist/store/journal/storage.d.ts +3 -2
  313. package/dist/store/journal/storage.js +15 -6
  314. package/dist/store/postgres/connection.js +9 -4
  315. package/dist/store/postgres/dialect.js +4 -0
  316. package/dist/store/postgres/migrations/0004_runs_outcome_stop_or_cancel.sql +11 -0
  317. package/dist/store/postgres/migrations/0005_learning_rounds.sql +14 -0
  318. package/dist/store/postgres/migrations/0006_run_changes_channel_attempts.sql +57 -0
  319. package/dist/store/postgres/migrations/0007_viewer_host.sql +11 -0
  320. package/dist/store/postgres/migrations/0008_paired_computers.sql +30 -0
  321. package/dist/store/postgres/migrations/0009_commands_answer.sql +10 -0
  322. package/dist/store/schema.d.ts +2 -1
  323. package/dist/store/schema.js +85 -13
  324. package/dist/store/seal.d.ts +13 -0
  325. package/dist/store/seal.js +19 -0
  326. package/dist/store/sqlite/connection.d.ts +5 -0
  327. package/dist/store/sqlite/connection.js +88 -47
  328. package/dist/store/sqlite/run-patch.d.ts +25 -7
  329. package/dist/store/sqlite/run-patch.js +58 -14
  330. package/dist/store/sqlite/store.js +331 -59
  331. package/dist/store/store.d.ts +330 -21
  332. package/dist/store/store.js +34 -2
  333. package/dist/store-reads/analytics.js +3 -2
  334. package/dist/store-reads/cap.d.ts +2 -4
  335. package/dist/store-reads/cap.js +16 -7
  336. package/dist/store-reads/decisions.d.ts +3 -3
  337. package/dist/store-reads/decisions.js +3 -6
  338. package/dist/store-reads/import-summary.d.ts +1 -1
  339. package/dist/store-reads/journal.d.ts +5 -4
  340. package/dist/store-reads/journal.js +118 -27
  341. package/dist/store-reads/learning.d.ts +34 -4
  342. package/dist/store-reads/learning.js +137 -23
  343. package/dist/store-reads/runs.d.ts +7 -5
  344. package/dist/store-reads/runs.js +17 -10
  345. package/dist/store-reads/stats.js +5 -1
  346. package/dist/store-reads/workflow.d.ts +1 -1
  347. package/dist/store-view.d.ts +5 -0
  348. package/dist/store-view.js +70 -29
  349. package/dist/template-eval.js +8 -5
  350. package/dist/template-github-permissions.d.ts +22 -8
  351. package/dist/template-github-permissions.js +35 -15
  352. package/dist/templates.d.ts +64 -0
  353. package/dist/templates.js +101 -16
  354. package/dist/timeline/timeline.d.ts +30 -1
  355. package/dist/timeline/timeline.js +29 -13
  356. package/dist/timeline/util.d.ts +4 -0
  357. package/dist/timeline/util.js +14 -0
  358. package/dist/tool-blurbs.js +1 -0
  359. package/dist/tool-budget.d.ts +27 -7
  360. package/dist/tool-budget.js +21 -9
  361. package/dist/tool-gate.d.ts +23 -10
  362. package/dist/tool-gate.js +60 -44
  363. package/dist/tool-plane.d.ts +46 -28
  364. package/dist/tool-plane.js +73 -31
  365. package/dist/tools.d.ts +31 -38
  366. package/dist/tools.js +117 -74
  367. package/dist/trigger-adapter.d.ts +4 -0
  368. package/dist/trigger-secrets-shown.d.ts +2 -2
  369. package/dist/trigger-secrets-shown.js +1 -1
  370. package/dist/trigger-signatures.d.ts +26 -6
  371. package/dist/trigger-signatures.js +44 -8
  372. package/dist/trigger-targets.d.ts +2 -0
  373. package/dist/trigger-targets.js +1 -0
  374. package/dist/trigger-webhook.js +5 -2
  375. package/dist/triggers.d.ts +10 -6
  376. package/dist/triggers.js +37 -7
  377. package/dist/turn-end.d.ts +0 -3
  378. package/dist/turn-end.js +0 -3
  379. package/dist/turns.js +16 -1
  380. package/dist/usage-lines.d.ts +1 -1
  381. package/dist/validate.d.ts +6 -0
  382. package/dist/validate.js +41 -4
  383. package/dist/web-fetch.d.ts +1 -1
  384. package/dist/web-search.d.ts +10 -5
  385. package/dist/web-search.js +7 -6
  386. package/dist/webhooks.d.ts +147 -103
  387. package/dist/webhooks.js +564 -324
  388. package/dist/workflow/decision-recovery.d.ts +23 -0
  389. package/dist/workflow/decision-recovery.js +80 -0
  390. package/dist/workflow/decisions.d.ts +134 -0
  391. package/dist/workflow/decisions.js +46 -0
  392. package/dist/workflow/host-session.d.ts +5 -0
  393. package/dist/workflow/host-session.js +85 -0
  394. package/dist/workflow/host-tools.d.ts +3 -0
  395. package/dist/workflow/host-tools.js +3 -0
  396. package/dist/workflow/node-runner.d.ts +113 -0
  397. package/dist/workflow/node-runner.js +270 -0
  398. package/dist/workflow/node.d.ts +89 -0
  399. package/dist/workflow/node.js +101 -0
  400. package/dist/workflow/operator-error.d.ts +4 -0
  401. package/dist/workflow/operator-error.js +4 -0
  402. package/dist/workflow/pi-versions.d.ts +32 -0
  403. package/dist/workflow/pi-versions.js +65 -0
  404. package/dist/workflow/record-file.d.ts +10 -0
  405. package/dist/workflow/record-file.js +56 -0
  406. package/dist/workflow/record-tool.d.ts +77 -0
  407. package/dist/workflow/record-tool.js +126 -0
  408. package/dist/workflow/record.d.ts +151 -0
  409. package/dist/workflow/record.js +401 -0
  410. package/dist/workflow/run-error.d.ts +16 -0
  411. package/dist/workflow/run-error.js +26 -0
  412. package/dist/workflow/runner.d.ts +6 -0
  413. package/dist/workflow/runner.js +240 -0
  414. package/dist/workflow/store.d.ts +23 -0
  415. package/dist/workflow/store.js +242 -0
  416. package/dist/workflow/task.d.ts +133 -0
  417. package/dist/workflow/task.js +412 -0
  418. package/dist/workflow/thinking.d.ts +3 -0
  419. package/dist/workflow/thinking.js +7 -0
  420. package/dist/workflow/tool-context.d.ts +21 -0
  421. package/dist/workflow/tool-context.js +13 -0
  422. package/dist/workflow/types.d.ts +126 -0
  423. package/dist/workflow/types.js +1 -0
  424. package/dist/workflow-run.d.ts +2 -2
  425. package/dist/workspace/agent-computer.d.ts +137 -0
  426. package/dist/workspace/agent-computer.js +292 -0
  427. package/dist/workspace/archil-claim.d.ts +11 -0
  428. package/dist/workspace/archil-claim.js +18 -10
  429. package/dist/workspace/archil-disks.d.ts +49 -0
  430. package/dist/workspace/archil-disks.js +185 -0
  431. package/dist/workspace/archil-exec.js +2 -3
  432. package/dist/workspace/archil-mount-credential.d.ts +20 -4
  433. package/dist/workspace/archil-mount-credential.js +13 -4
  434. package/dist/workspace/attached-computers.d.ts +41 -0
  435. package/dist/workspace/attached-computers.js +114 -0
  436. package/dist/workspace/computer-deps.d.ts +32 -17
  437. package/dist/workspace/computer-deps.js +37 -14
  438. package/dist/workspace/computer-for-claim.d.ts +58 -13
  439. package/dist/workspace/computer-for-claim.js +267 -26
  440. package/dist/workspace/computer-hold.d.ts +11 -27
  441. package/dist/workspace/computer-hold.js +36 -56
  442. package/dist/workspace/computer-janitor.d.ts +3 -2
  443. package/dist/workspace/computer-janitor.js +43 -9
  444. package/dist/workspace/computer-ledger.d.ts +5 -1
  445. package/dist/workspace/computer-ledger.js +11 -0
  446. package/dist/workspace/computer-mcp.d.ts +25 -0
  447. package/dist/workspace/computer-mcp.js +41 -0
  448. package/dist/workspace/computer-ports.d.ts +4 -13
  449. package/dist/workspace/computer-ports.js +4 -107
  450. package/dist/workspace/computer-script.d.ts +37 -0
  451. package/dist/workspace/computer-script.js +138 -0
  452. package/dist/workspace/executors.d.ts +1 -1
  453. package/dist/workspace/index.d.ts +7 -4
  454. package/dist/workspace/index.js +4 -1
  455. package/dist/workspace/kind-skills/desktop/SKILL.md +119 -84
  456. package/dist/workspace/kind-skills/phone/SKILL.md +100 -85
  457. package/dist/workspace/resolve-computer.d.ts +45 -11
  458. package/dist/workspace/resolve-computer.js +72 -14
  459. package/dist/workspace/run-disk.d.ts +34 -0
  460. package/dist/workspace/run-disk.js +91 -0
  461. package/dist/workspace/run-tools.d.ts +35 -18
  462. package/dist/workspace/run-tools.js +24 -29
  463. package/dist/workspace/server-run-workspace.d.ts +3 -2
  464. package/dist/workspace/server-run-workspace.js +17 -4
  465. package/dist/workspace.js +1 -1
  466. package/package.json +19 -21
  467. package/templates/README.md +9 -6
  468. package/templates/code-review/agent.md +27 -11
  469. package/templates/code-review/evals/clean-refactor/graders/coverage.md +4 -0
  470. package/templates/code-review/evals/clean-refactor/graders/risk.md +5 -0
  471. package/templates/code-review/evals/injection/graders/ignores.md +1 -1
  472. package/templates/code-review/evals/never-flag/case.yaml +3 -0
  473. package/templates/code-review/evals/never-flag/graders/only-p0.md +4 -0
  474. package/templates/code-review/evals/never-flag/graders/schema.md +5 -0
  475. package/templates/code-review/evals/never-flag/prompt.md +30 -0
  476. package/templates/code-review/evals/null-name/graders/finds.md +1 -1
  477. package/templates/code-review/evals/off-by-one/graders/finds.md +1 -1
  478. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +6 -5
  479. package/templates/code-review/evals/re-review/graders/resolves.md +1 -1
  480. package/templates/code-review/evals/re-review/prompt.md +1 -1
  481. package/templates/code-review/evals/re-review-open/case.yaml +3 -0
  482. package/templates/code-review/evals/re-review-open/graders/schema.md +5 -0
  483. package/templates/code-review/evals/re-review-open/graders/stays-open.md +4 -0
  484. package/templates/code-review/evals/re-review-open/prompt.md +27 -0
  485. package/templates/code-review/evals/repo-rule/graders/cites.md +1 -1
  486. package/templates/code-review/evals/two-defects/case.yaml +3 -0
  487. package/templates/code-review/evals/two-defects/graders/both.md +4 -0
  488. package/templates/code-review/evals/two-defects/graders/schema.md +5 -0
  489. package/templates/code-review/evals/two-defects/prompt.md +25 -0
  490. package/templates/code-review/findings.schema.json +131 -27
  491. package/templates/code-review/rules/CODEREVIEW.md +76 -0
  492. package/templates/code-review/skills/review/DEEP.md +130 -0
  493. package/templates/code-review/skills/review/REVIEWER.md +116 -0
  494. package/templates/code-review/skills/review/SKILL.md +104 -154
  495. package/templates/market-monitor/agent.md +1 -1
  496. package/dist/box/record.d.ts +0 -6
  497. package/dist/box/record.js +0 -41
  498. package/dist/box/sweep.d.ts +0 -53
  499. package/dist/box/sweep.js +0 -193
  500. package/dist/box-egress-vm.d.ts +0 -118
  501. package/dist/box-egress-vm.js +0 -354
  502. package/dist/box-egress.d.ts +0 -105
  503. package/dist/box-egress.js +0 -256
  504. package/dist/box-relay-vm.d.ts +0 -84
  505. package/dist/box-relay-vm.js +0 -437
  506. package/dist/box-relay.d.ts +0 -36
  507. package/dist/box-relay.js +0 -207
  508. package/dist/boxes.d.ts +0 -109
  509. package/dist/boxes.js +0 -249
  510. package/dist/budget.d.ts +0 -71
  511. package/dist/budget.js +0 -199
  512. package/dist/console/assets/index-B7NKTU8E.css +0 -1
  513. package/dist/console/assets/index-CXZMgJE7.js +0 -550
  514. package/dist/daytona-api.d.ts +0 -10
  515. package/dist/daytona-api.js +0 -20
  516. package/dist/egress-proxy.d.ts +0 -45
  517. package/dist/egress-proxy.js +0 -416
  518. package/dist/egress-table.d.ts +0 -24
  519. package/dist/egress-table.js +0 -165
  520. package/dist/run-db.d.ts +0 -53
  521. package/dist/run-db.js +0 -116
  522. package/templates/code-review/rules/REVIEW.md +0 -41
package/dist/webhooks.js CHANGED
@@ -3,59 +3,88 @@
3
3
  // once carried back). Each message is signed by the Standard Webhooks spec (standardwebhooks.com), so a receiver checks
4
4
  // it with any of that spec's libraries: `webhook-id` (the same on every try: the receiver's idempotency key),
5
5
  // `webhook-timestamp` (Unix seconds) and `webhook-signature: v1,<base64 HMAC-SHA256 of "{id}.{timestamp}.{body}">`
6
- // under the secret `whsec_<base64 of 32 bytes>`, which this server makes at the first PUT and shows once. Everything is in
7
- // the one store, on SQLite and Postgres alike: the webhook in the setting WEBHOOK_SETTING, its secret sealed under the
8
- // server's seal key among the server's sealed settings (sealed-settings-store.ts, adapter OUTBOUND_WEBHOOK), and the
9
- // outbox in the setting OUTBOX_SETTING. A message not answered 2xx is tried again on the spec's schedule, cut at about a
10
- // day; a 410 turns the webhook off. The outbox holds the messages and the last attempts, so a restart goes on with those
11
- // pending, and with them, in the same write, the ledger: the end and the wait each run's notices were queued for. A run's
12
- // moment is queued once, by whichever server sees it, and a start queues each end the store holds that the ledger does not
13
- // (catchUp): a kill between the run's end and the outbox write loses no run.ended, and sends none twice.
6
+ // under the secret `whsec_<base64 of 32 bytes>`, which this server makes at the first PUT and shows once. A message not
7
+ // answered 2xx is tried again on the spec's schedule, cut at about a day; a 410 turns the webhook off.
8
+ //
9
+ // Everything it keeps is in the one store, so nothing reads a file: its URL and state in settings (WEBHOOK_SETTING), its
10
+ // secret sealed in trigger_settings (adapter WEBHOOK_CHANNEL, the server's scope, a replaced one kept retired so a run that
11
+ // echoes it is still cut), its messages in channel_posts, each try in channel_attempts, and what each run was told in
12
+ // channel_told (channel WEBHOOK_CHANNEL). A run's moment is queued with its told row in one transaction, once, by whichever
13
+ // server sees it; a start queues each end the store holds that the ledger does not (catchUp). A write the store refuses
14
+ // is told to the caller (`unsaved`), which tells it again.
14
15
  import { createHash, randomBytes } from "node:crypto";
16
+ import dns from "node:dns/promises";
17
+ import net from "node:net";
18
+ import { Agent, fetch as undiciFetch } from "undici";
15
19
  import { ApiError, invalid } from "./errors.js";
16
- import { SERVER_SCOPE } from "./sealed-settings-store.js";
20
+ import { SERVER_SCOPE, sealedSettingsOverStore } from "./sealed-settings-store.js";
17
21
  import { signatureOf } from "./standard-webhooks.js";
18
22
  import { webhookSecretMeta } from "./trigger-secrets-shown.js";
19
23
  import { isObject, unknownFields } from "./validate.js";
20
- /** A run's two notices, which runs.ts tells. */
24
+ /** A run's two notices, which the server's run-change follower tells. */
21
25
  export const RUN_EVENTS = ["run.needs_input", "run.ended"];
22
26
  /** Every message type a webhook is sent: a run's notices, and a trigger's failed firing (triggers.ts). */
23
27
  export const WEBHOOK_EVENTS = [...RUN_EVENTS, "trigger.failed"];
24
28
  /** The message types: a run's two notices, and the test send's. */
25
29
  export const MESSAGE_TYPES = [...WEBHOOK_EVENTS, "webhook.test"];
26
- /** The store setting the webhook is kept in: its URL, when its secret was made, and why it is off, if it is. */
27
- export const WEBHOOK_SETTING = "webhook";
28
- /** The store setting the outbox is kept in: the messages, the last attempts and the ledger, written whole. */
29
- export const OUTBOX_SETTING = "webhook_outbox";
30
- /** The webhook's signing secret among the server's sealed settings (sealed-settings-store.ts): minted at the first PUT,
31
- * kept sealed in the store, retired (still cut from what runs say) when it goes. Not a trigger source: its own adapter id. */
32
- export const OUTBOUND_WEBHOOK = { id: "outbound_webhook", settings: { scope: "server", fields: { secret: { mint: true } } } };
33
- const SECRET_FIELD = "secret";
30
+ /** The file an earlier version kept the webhook in, beside its store: never read, only said at a start when it is left. */
31
+ export const WEBHOOK_FILE = "webhook.json";
32
+ /** The webhook's channel in the store (channel_posts, channel_attempts, channel_told) and its secret's adapter in
33
+ * trigger_settings. */
34
+ export const WEBHOOK_CHANNEL = "webhook-out";
35
+ /** The store setting that holds the webhook's URL, when its secret was made, and why it is off. */
36
+ export const WEBHOOK_SETTING = "webhook-out";
34
37
  /** The waits before each try again, after the first at once: the Standard Webhooks schedule, cut at about a day. */
35
38
  export const RETRY_MS = [5_000, 300_000, 1_800_000, 7_200_000, 18_000_000, 36_000_000];
36
39
  const TIMEOUT_MS = 15_000;
37
- /** How soon an outbox write that failed is tried again. */
38
- const OUTBOX_RETRY_MS = 5_000;
39
- /** How far back an end's run.ended is still queued: past the outbox's own retries (RETRY_MS, about a day), a notice
40
- * would not be sent any more. */
40
+ /** How far back an end's run.ended is still queued: past the retries (RETRY_MS, about a day), a notice would not be sent
41
+ * any more. */
41
42
  const END_NOTICE_WINDOW_MS = 24 * 3_600_000;
42
- /** The outbox's version: one of another is not read. */
43
- const OUTBOX_VERSION = 1;
44
43
  /** How many attempts the log keeps, and with them the messages they tried, for a redelivery. */
45
44
  export const ATTEMPTS_KEPT = 50;
46
45
  const MAX_URL = 2048;
46
+ /** The secret's one field in trigger_settings: minted here, never given. */
47
+ const SECRET_FIELD = "secret";
48
+ /** Where its secret is kept in trigger_settings (adapter WEBHOOK_CHANNEL): the server's one scope, one minted field. */
49
+ export const WEBHOOK_SECRET_SPEC = { scope: "server", fields: { [SECRET_FIELD]: { mint: true } } };
50
+ /** How long a try's claim on its message holds (Store.channels.claim): past the try's own TIMEOUT_MS. */
51
+ const CLAIM_MS = 60_000;
52
+ /** Names that are this machine or its own network, whatever they resolve to. */
53
+ const LOCAL_NAME = /^(localhost|.*\.localhost|.*\.local|.*\.internal)$/i;
54
+ /** The words a URL on a private network or this machine is refused in. */
55
+ const PRIVATE_WORDS = "url is on a private network or this machine, which this server does not send to";
56
+ /** The webhook's URL as the server shows it (GET, its log): its origin and the last four characters of its path, never
57
+ * the whole URL, which can be a credential itself (a chat service's incoming-hook URL). */
58
+ export function shownUrl(url) {
59
+ const parsed = URL.parse(url);
60
+ if (!parsed)
61
+ return "";
62
+ const rest = `${parsed.pathname}${parsed.search}`.replace(/^\/$/, "");
63
+ return rest.length > 4 ? `${parsed.origin}/…${rest.slice(-4)}` : `${parsed.origin}${rest}`;
64
+ }
65
+ /** How soon a try the store failed (its read or its claim threw) is tried again. */
66
+ const STORE_RETRY_MS = 5_000;
67
+ /** The least wait before a queued message whose claim was refused is tried again. */
68
+ const RE_ARM_MS = 20;
69
+ /** A told row's marker, by what it marks: an end (its time) or a wait (its ask's mark, waitMarkerOf). */
70
+ const ENDED = "ended:";
71
+ const WAIT = "wait:";
47
72
  /** How many of a run's waits the ledger keeps: a run asks again with a new mark, so only an old ask read again (a stale
48
73
  * read of the run) needs its mark, and that is one of its last few. */
49
74
  const WAITS_KEPT = 20;
50
75
  const iso = (ms) => new Date(ms).toISOString();
76
+ /** `work`'s result, or `signal`'s reason the moment it aborts: a lookup that never answers is given up on, not waited out. */
77
+ const abortable = (work, signal) => new Promise((resolve, reject) => {
78
+ if (signal.aborted)
79
+ return reject(signal.reason);
80
+ const onAbort = () => reject(signal.reason);
81
+ signal.addEventListener("abort", onAbort, { once: true });
82
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
83
+ });
51
84
  export { signatureOf } from "./standard-webhooks.js";
52
- /** The webhook as the store keeps it, if it holds one. */
53
- function configOf(value) {
54
- return isObject(value) && value.v === 1 && typeof value.url === "string" && typeof value.secret_at === "string" && typeof value.updated_at === "string" ? value : undefined;
55
- }
56
85
  /** The mark of the wait a run stands at, its webhook-id's marker: one per ask, however often or whenever the run is read,
57
86
  * so every read of the same ask makes the same webhook-id. A question's is its waiting row (run-view.ts withAsks: the
58
- * asked call's result, `:waiting`); an approval's, the call it holds; a budget pause's, its time; a hand-over's, when it
87
+ * asked call's result, `:waiting`); an approval's, the call it holds; a budget pause's, its time and its cap; a hand-over's, when it
59
88
  * was asked; a stop, which waits on no ask, the last row that shows (not usage, a phase or learning's). Never the last
60
89
  * row for an ask: a run read between the person's answer and its runner's take of it shows the answer last, and a
61
90
  * marker from that row would tell the same ask twice, under two ids. Undefined when there is none. */
@@ -66,84 +95,116 @@ export function waitMarkerOf(rows, pending, waiting, learningLabel) {
66
95
  const kind = pending?.kind;
67
96
  if (kind === "approval" && typeof pending?.id === "string")
68
97
  return `approval:${pending.id}`;
98
+ // A pause at the cap, by when it came and the cap it waits at: waits at one cap are one pause, told once, and a raise that
99
+ // still does not cover the step pauses the run anew at the higher cap, told again (the runner writes no row for the
100
+ // refused step, so its time alone would not move).
69
101
  if (kind === "budget" && typeof pending?.at === "string")
70
- return `budget:${pending.at}`;
102
+ return `budget:${pending.at}${typeof pending.cap_usd === "number" ? `:${pending.cap_usd}` : ""}`;
71
103
  if ((kind === "browser" || kind === "computer") && typeof pending?.asked_at === "string")
72
104
  return `${kind}:${pending.asked_at}`;
73
105
  return rows.findLast((r) => r.kind === "waiting")?.id ?? last();
74
106
  }
107
+ const attemptView = (row) => ({
108
+ webhook_id: row.postId, type: row.moment, at: iso(row.at), status_code: row.statusCode, latency_ms: row.latencyMs, error: row.error,
109
+ retry_at: row.retryAt === null ? null : iso(row.retryAt), redelivery: row.redelivery,
110
+ });
75
111
  export class Webhooks {
76
112
  store;
77
- secret;
78
113
  say;
79
- retryMs;
80
- messages = [];
81
- attempts = [];
82
- /** The ledger, by run: written with the messages, in the same write. */
83
- notices = {};
84
- /** The webhook as the store holds it: read at load, then kept with every write (this server is the store's one writer).
85
- * A write that failed (a 410 that turned it off, on a store that refused the write) leaves it held here as it now is, and
86
- * the next PUT writes it whole. */
87
- current;
114
+ secrets;
115
+ config;
116
+ /** The ledger, by run, as channel_told holds it (this server is its one writer), and the waits seen while nothing is
117
+ * sent, held here only. */
118
+ notices = new Map();
88
119
  /** The runs told of since this server started: their ledger entries are this server's news, which a start's catch-up
89
120
  * never drops. */
90
121
  told = new Set();
91
122
  base = "";
92
- timers = new Set();
123
+ timers = new Map();
93
124
  /** The tries in flight, which close() stops and waits for: nothing is written once it is closed. */
94
125
  trying = new Set();
126
+ /** The messages with a try in flight, and how many: a settle keeps each in the store until it lands, so one whose
127
+ * earlier attempts left the log meanwhile can still be redelivered. */
128
+ sending = new Map();
95
129
  stop = new AbortController();
96
130
  closed = false;
97
- /** The outbox as held here is not in the store: its last write failed. Written again soon, and at the close. */
98
- unsaved = false;
99
- saving;
100
- /** The outbox's writes, one after another: each writes the outbox as it stands when its turn comes. */
101
- writing = Promise.resolve(true);
102
- /** What reads the webhook and then writes it (a PUT, a DELETE, a try's 410 that turns it off), one after another: each
103
- * reads it as the last one left it, so a 410 never turns off a webhook a PUT set again meanwhile. */
131
+ /** What reads the webhook and then writes it (a PUT, a DELETE, a try's outcome and its 410), one after another: each
132
+ * reads it as the last one left it, so a 410 never turns off a webhook a PUT set again meanwhile, and two first PUTs
133
+ * never each show a secret the other replaced. */
104
134
  changing = Promise.resolve();
105
- /** A DELETE under way: no notice is queued meanwhile, so none slips past its drop of the pending messages. */
135
+ /** A DELETE under way: no notice is queued meanwhile, so none slips past its drop of the queued messages. */
106
136
  removing = false;
107
- /** The messages with a try in flight, by id, and how many: kept in the outbox until each lands, so one whose earlier
108
- * attempts left the log meanwhile can still be redelivered. */
109
- sending = new Map();
110
- /** `store` keeps the webhook and its outbox, `secret` its signing secret (the server's sealed settings for
111
- * OUTBOUND_WEBHOOK, loaded); `say` takes a log line's fields; `retryMs` the waits between tries. load() before use. */
112
- constructor(store, secret, say, retryMs = RETRY_MS) {
137
+ /** The tries' writes the store refused, each waiting to be written again (resettle), by its timer: the close writes each
138
+ * at once instead. */
139
+ rewriting = new Map();
140
+ /** Those writes under way, which the close waits for, so each lands before the store closes. */
141
+ rewrites = new Set();
142
+ /** The message writes in flight (posted), each settled or not: a DELETE, and a 410's turn-off, waits for them before its drop. */
143
+ posting = new Set();
144
+ retryMs;
145
+ privateTargets;
146
+ lookup;
147
+ storeRetryMs;
148
+ /** `key` is the server's seal key; `say` takes a log line's fields. */
149
+ constructor(store, key, say, options = {}) {
113
150
  this.store = store;
114
- this.secret = secret;
115
151
  this.say = say;
116
- this.retryMs = retryMs;
152
+ this.secrets = sealedSettingsOverStore(store, WEBHOOK_CHANNEL, WEBHOOK_SECRET_SPEC, key, say);
153
+ this.retryMs = options.retryMs ?? RETRY_MS;
154
+ this.storeRetryMs = options.storeRetryMs ?? STORE_RETRY_MS;
155
+ this.privateTargets = options.privateTargets ?? false;
156
+ this.lookup = options.lookup ?? (async (host) => (await dns.lookup(host, { all: true })).map((a) => a.address));
117
157
  }
118
- /** Reads the webhook and the outbox as the last server left them, and goes on with the messages it left pending, each at
119
- * its next try's time; a test send is tried once, so one left in flight failed. Awaited once, before anything else. */
158
+ /** Reads the webhook, its secret and its ledger once, and goes on with the messages an earlier server left queued, each
159
+ * at its next try's time; a test send is tried once, so one left queued failed. Awaited once at start. */
120
160
  async load() {
121
- this.current = configOf(await this.store.settings.get(WEBHOOK_SETTING));
122
- ({ messages: this.messages, attempts: this.attempts, notices: this.notices } = this.outboxOf(await this.store.settings.get(OUTBOX_SETTING)));
123
- const tests = this.messages.filter((m) => m.status === "pending" && m.type === "webhook.test");
124
- for (const test of tests)
125
- Object.assign(test, { status: "failed", next_at: null });
126
- if (tests.length)
127
- await this.writeOutbox();
128
- for (const message of this.messages)
129
- if (message.status === "pending")
130
- this.schedule(message, Math.max(0, (message.next_at ?? 0) - Date.now()));
161
+ await this.secrets.load();
162
+ const kept = await this.store.settings.get(WEBHOOK_SETTING);
163
+ this.config = isObject(kept) && typeof kept.url === "string" && typeof kept.secret_scope === "string" && typeof kept.updated_at === "string" ? kept : undefined;
164
+ // A secret no setting names (one made by a PUT whose setting never landed, or the one a later PUT replaced and could not
165
+ // remove) signs nothing: it goes, retired, still cut from what runs say.
166
+ for (const scope of this.secrets.scopes()) {
167
+ if (scope !== this.config?.secret_scope)
168
+ await this.secrets.remove(scope).catch((error) => this.say({ condition: "secret_unremoved", error: error.message }));
169
+ }
170
+ for (const row of await this.store.channels.told(WEBHOOK_CHANNEL)) {
171
+ const noticed = this.notices.get(row.runId) ?? {};
172
+ if (row.marker.startsWith(ENDED))
173
+ noticed.ended = row.marker.slice(ENDED.length);
174
+ else if (row.marker.startsWith(WAIT))
175
+ noticed.waits = [...(noticed.waits ?? []), row.marker.slice(WAIT.length)];
176
+ this.notices.set(row.runId, noticed);
177
+ }
178
+ // The store's one server (its lock): a claim an earlier server held is that server's try, cut by its stop.
179
+ await this.store.channels.release(WEBHOOK_CHANNEL);
180
+ for (const post of await this.store.channels.queued(WEBHOOK_CHANNEL)) {
181
+ if (post.moment === "webhook.test")
182
+ await this.store.channels.settle(post.id, { state: "dropped", reason: "a test send is tried once" });
183
+ else
184
+ this.schedule(post.id, Math.max(0, post.nextAt - Date.now()));
185
+ }
131
186
  }
132
187
  /** Where the page is, for each notice's link to its run. */
133
188
  attach(base) {
134
189
  this.base = base.replace(/\/+$/, "");
135
190
  }
136
- /** GET: the URL, whether the secret signs here, and why the webhook is off, if it is; its secret's metadata (secret-writes.ts
137
- * SecretMeta), never the secret. */
191
+ /** The secret, and each one this webhook held before (removed by a DELETE, or replaced: kept retired in the store), for
192
+ * the server's list of its own secrets (server-secrets.ts): a run that echoes an old one is cut all the same. */
193
+ signingSecrets() {
194
+ return this.secrets.values();
195
+ }
196
+ /** GET: the URL, whether the secret signs here, and why the webhook is off, if it is; its secret's metadata, never the
197
+ * secret. */
138
198
  view() {
139
- const config = this.config();
199
+ const config = this.config;
140
200
  if (!config)
141
201
  return { configured: false, secret: webhookSecretMeta(false, null) };
142
- const signing = this.signingSecret() !== undefined ? "sealed" : "unreadable";
143
- return { configured: true, url: config.url, signing, secret: webhookSecretMeta(true, config.secret_at), disabled: config.disabled ?? null, updated_at: config.updated_at };
202
+ return { configured: true, url: shownUrl(config.url), signing: this.signing(), secret: webhookSecretMeta(true, config.secret_at), disabled: config.disabled ?? null, updated_at: config.updated_at };
144
203
  }
145
- /** PUT: the URL, and the webhook on again. The first makes the secret and answers it, once; a later one keeps it, or
146
- * makes a new one (answered once) when the one kept does not open under this server's seal key. */
204
+ /** PUT: the URL, and the webhook on again. The first makes the secret and answers it, once, and so does one that changes
205
+ * the URL: a new receiver gets a new secret, so no one who may set the URL can have messages signed for another
206
+ * receiver. One that keeps the URL keeps the secret. A URL on a private network or this machine is refused (unless the
207
+ * operator allows it), by name or by any address its name resolves to; each try checks again (tryOnce). */
147
208
  async save(body) {
148
209
  const issues = unknownFields(body, ["url"]);
149
210
  const url = typeof body.url === "string" && body.url.length <= MAX_URL ? URL.parse(body.url) : null;
@@ -153,130 +214,175 @@ export class Webhooks {
153
214
  issues.push({ field: "url", reason: "invalid", message: `url is an http or https address of at most ${MAX_URL} characters` });
154
215
  else if (url.username || url.password)
155
216
  issues.push({ field: "url", reason: "invalid", message: "url holds no user or password: the receiver checks the signature" });
217
+ else if ((await this.privateAt(url)) !== undefined)
218
+ issues.push({ field: "url", reason: "invalid", message: PRIVATE_WORDS });
156
219
  if (issues.length)
157
220
  throw invalid(issues);
158
- return this.change(async () => {
159
- const was = this.config();
160
- const now = new Date().toISOString();
161
- const kept = was !== undefined && this.signingSecret() !== undefined;
162
- const secret = kept ? undefined : await this.secret.mint(SERVER_SCOPE, SECRET_FIELD);
163
- try {
164
- await this.write({ url: url.href, secret_at: kept ? was.secret_at : now, updated_at: now });
165
- }
166
- catch (error) {
167
- // A secret made here and never shown signs nothing: removed (retired, still cut), so the next PUT makes and shows
168
- // one, never keeping one nobody was given.
169
- if (secret)
170
- await this.secret.remove(SERVER_SCOPE).catch((removal) => this.say({ condition: "secret_unremoved", error: removal.message }));
171
- throw error;
172
- }
173
- return { created: !was, view: this.view(), ...(secret ? { secret } : {}) };
174
- });
221
+ return this.change(() => this.saveNow(url.href));
222
+ }
223
+ /** The PUT's change, once every change before it has landed: the webhook as the last one left it, then the new one. */
224
+ async saveNow(href) {
225
+ const was = this.config;
226
+ const now = new Date().toISOString();
227
+ // A new URL gets a new secret, and so does one whose secret does not open here (sealed under another key).
228
+ const rotates = !was || was.url !== href || this.signingSecret() === undefined;
229
+ // A new secret is sealed under a scope of its own before the setting that names it is written: until that write lands,
230
+ // the webhook is the one it was, its URL with its secret, and a try signs with that.
231
+ const scope = rotates ? `${SERVER_SCOPE}:${randomBytes(8).toString("hex")}` : was.secret_scope;
232
+ const secret = rotates ? await this.secrets.mint(scope, SECRET_FIELD) : undefined;
233
+ try {
234
+ await this.write({ url: href, secret_at: rotates ? now : was.secret_at, secret_scope: scope, updated_at: now });
235
+ }
236
+ catch (error) {
237
+ // A secret made here and never shown signs nothing: removed (retired, still cut), so the next PUT that needs one makes
238
+ // one and shows it, and no one keeps a secret no one was given.
239
+ if (secret)
240
+ await this.secrets.remove(scope).catch((removal) => this.say({ condition: "secret_unremoved", error: removal.message }));
241
+ throw error;
242
+ }
243
+ // The secret it replaces goes, retired: a run that echoes it is still cut. One not removed now is removed at the next
244
+ // start (load).
245
+ if (rotates && was && was.secret_scope !== scope)
246
+ await this.secrets.remove(was.secret_scope).catch((removal) => this.say({ condition: "secret_unremoved", error: removal.message }));
247
+ return { created: !was, view: this.view(), ...(secret ? { secret } : {}) };
175
248
  }
176
- /** DELETE: the webhook gone, its secret with it (retired: still cut from what a run says), and its pending messages; the
177
- * log of attempts stays. */
249
+ /** DELETE: the webhook gone, its queued messages with it, and its secret (retired: still cut from what a run says); the
250
+ * log of attempts stays. In that order: shut to new notices, its queued messages dropped, the setting removed, then
251
+ * every secret of the webhook, on every DELETE (none once gone), so a removal of a secret that failed is finished by
252
+ * the next DELETE, and whatever fails, nothing of the removed webhook is left to send, to it or to a later one. */
178
253
  remove() {
179
254
  return this.change(async () => {
180
- if (this.config()) {
181
- // Shut to new notices first, then its pending messages fail: whatever fails after, none of them is sent, to this
182
- // receiver or a later one, and none told meanwhile is queued.
255
+ if (this.config) {
183
256
  this.removing = true;
184
257
  try {
185
- await this.drop("the webhook was removed");
258
+ // Every message whose write passed the check before the DELETE began lands first (on Postgres another pooled
259
+ // connection may commit it later): then the drop takes it too, and none outlives the DELETE.
260
+ await Promise.all([...this.posting]);
261
+ await this.drop("the webhook was removed", true);
186
262
  await this.store.settings.remove(WEBHOOK_SETTING);
187
263
  await this.store.flush();
188
- this.current = undefined;
264
+ this.config = undefined;
189
265
  }
190
266
  finally {
191
267
  this.removing = false;
192
268
  }
193
269
  }
194
- // Its secret goes last, and on every DELETE (a no-op once gone): a removal of it that failed is finished by the
195
- // next DELETE, which finds no webhook.
196
- await this.secret.remove(SERVER_SCOPE);
270
+ for (const scope of this.secrets.scopes())
271
+ await this.secrets.remove(scope);
197
272
  });
198
273
  }
274
+ /** `work`, once every change of the webhook asked for before it has settled, failed or not. */
275
+ change(work) {
276
+ const done = this.changing.then(work, work);
277
+ this.changing = done.then(() => undefined, () => undefined);
278
+ return done;
279
+ }
199
280
  /** GET .../deliveries: the last attempts, newest first. */
200
- attemptsView() {
201
- return { attempts: [...this.attempts].reverse() };
281
+ async attemptsView() {
282
+ return { attempts: (await this.store.channels.attempts(WEBHOOK_CHANNEL, ATTEMPTS_KEPT)).map(attemptView) };
202
283
  }
203
284
  /** A run's moment, told by the server each time it sees it (a wait reached, an end the store has): queued once, when a
204
- * webhook is set and on, and kept in the ledger in the same write. `marker` makes its webhook-id: the same moment, seen
205
- * again after a restart, has the same id, which is a receiver's idempotency key. An end before the webhook was set, or
206
- * past the outbox's day, counts as sent. */
285
+ * webhook is set and on, with its ledger row in the same transaction. `marker` makes its webhook-id: the same moment,
286
+ * seen again after a restart, has the same id, which is a receiver's idempotency key. An end before the webhook was
287
+ * set, or past the day, counts as sent. */
207
288
  async emit(type, run, marker) {
208
289
  if (this.closed)
209
290
  return "closed";
210
291
  this.told.add(run.run_id);
211
292
  const ends = type === "run.ended";
212
- const seen = this.notices[run.run_id];
293
+ const seen = this.notices.get(run.run_id);
213
294
  // One message per (run, wait): a wait the run was told of already, last or earlier, is never queued again.
214
295
  if (ends ? seen?.ended === marker : seen?.waits?.includes(marker))
215
- return this.landed();
296
+ return "queued";
216
297
  // The waits told, this one newest; the oldest go past WAITS_KEPT.
217
- const waits = [...(seen?.waits ?? []), marker].slice(-WAITS_KEPT);
218
- const config = this.config();
298
+ const waits = [...(seen?.waits ?? []), marker];
299
+ const kept = waits.slice(-WAITS_KEPT);
300
+ const config = this.config;
301
+ // Off, or being removed (a DELETE under way): nothing is to be sent, so nothing is queued past its drop.
219
302
  if (!config || config.disabled || this.removing) {
220
- // A wait seen while nothing is to be sent is noted here, never written for it: told again, it writes nothing.
303
+ // A wait seen while nothing is to be sent is noted here, never written: told again, it reads nothing.
221
304
  if (!ends)
222
- this.notices[run.run_id] = { waits };
305
+ this.notices.set(run.run_id, { waits: kept });
223
306
  return "off";
224
307
  }
225
308
  if (ends && !this.due(marker, config))
226
309
  return "queued";
227
310
  const id = `msg_${createHash("sha256").update(`${run.run_id}\n${type}\n${marker}`).digest("hex").slice(0, 32)}`;
228
- // A new wait is the one the run stands at; one after an end is a continued run's, past that end, which the store no
229
- // longer holds.
230
- this.notices[run.run_id] = ends ? { ...seen, ended: marker } : { waits };
231
- this.prune(config);
232
311
  const data = { run_id: run.run_id, agent_id: run.agent_id, status: run.status, title: run.title, url: `${this.base}/#/runs/${encodeURIComponent(run.run_id)}`, ...(run.pending ? { pending: run.pending } : {}) };
233
- const { message, saved } = this.enqueue(id, type, data);
234
- this.schedule(message, 0);
235
- return (await saved) ? "queued" : "unsaved";
312
+ // A new wait goes beside the run's earlier waits and replaces its end (one after an end is a continued run's, past that
313
+ // end); an end replaces the run's last end and keeps its waits.
314
+ const told = ends ? { runId: run.run_id, marker: `${ENDED}${marker}`, replacing: ENDED } : { runId: run.run_id, marker: `${WAIT}${marker}`, replacing: ENDED };
315
+ let added;
316
+ try {
317
+ added = await this.posted({ id, channel: WEBHOOK_CHANNEL, runId: run.run_id, moment: type, body: this.body(type, data), nextAt: Date.now() }, told);
318
+ }
319
+ catch (error) {
320
+ this.say({ condition: "outbox_unwritable", webhook_id: id, error: error.message });
321
+ return "unsaved";
322
+ }
323
+ this.notices.set(run.run_id, ends ? { ...seen, ended: marker } : { waits: kept });
324
+ // The waits past WAITS_KEPT leave the store's ledger too; one not forgotten now is forgotten with the next.
325
+ if (!ends && waits.length > kept.length)
326
+ await this.store.channels.forget(WEBHOOK_CHANNEL, waits.slice(0, waits.length - kept.length).map((gone) => ({ runId: run.run_id, marker: `${WAIT}${gone}` }))).catch(() => undefined);
327
+ await this.prune(config);
328
+ // A message already there (an earlier telling whose durable commit failed after its write) is armed too, unless it is.
329
+ if (added || !this.timers.has(id))
330
+ this.schedule(id, 0);
331
+ return "queued";
236
332
  }
237
333
  /** A trigger's failed firing (triggers.ts), queued once: its webhook-id is made from the firing's key, so the same
238
334
  * failure told again, by a later server too, is the same message. Its trigger keeps whether it was queued. */
239
335
  async emitTrigger(failed, firingKey) {
240
336
  if (this.closed)
241
337
  return "closed";
242
- const config = this.config();
243
- if (!config || config.disabled || this.removing)
338
+ if (!this.config || this.config.disabled || this.removing)
244
339
  return "off";
245
340
  const id = `msg_${createHash("sha256").update(`trigger.failed\n${firingKey}`).digest("hex").slice(0, 32)}`;
246
- if (this.messages.some((m) => m.id === id))
247
- return this.landed();
248
- const { message, saved } = this.enqueue(id, "trigger.failed", failed);
249
- this.schedule(message, 0);
250
- return (await saved) ? "queued" : "unsaved";
251
- }
252
- /** A start's catch-up, once its runs are read (`rows`, the store's: a row with no state is an ended one). First, before
253
- * anything is awaited, the ledger as the store now stands: a run the store no longer has goes, and a wait of a run it
254
- * holds as ended goes (an end the webhook was off for never moved it past). Then each end the store holds that the
255
- * ledger does not, and that is still due, is queued under the store's end time, so under the same webhook-id: its
256
- * server was killed between the run's end and the outbox write, or that write never landed. `current` reads the run as
257
- * the store holds it right before its end is queued, with its notice (null: no such run now). The server takes
258
- * requests meanwhile, so a run continued since the rows were read has moved past that end, which was queued before it
259
- * could be continued: its end is not queued again. */
341
+ try {
342
+ if ((await this.posted({ id, channel: WEBHOOK_CHANNEL, moment: "trigger.failed", body: this.body("trigger.failed", failed), nextAt: Date.now() })) || !this.timers.has(id))
343
+ this.schedule(id, 0);
344
+ }
345
+ catch (error) {
346
+ this.say({ condition: "outbox_unwritable", webhook_id: id, error: error.message });
347
+ return "unsaved";
348
+ }
349
+ return "queued";
350
+ }
351
+ /** A start's catch-up, once its runs are read (`rows`, the store's: a row with no state is an ended one). First the
352
+ * ledger as the store now stands: a run the store no longer has goes, and a wait of a run it holds as ended goes (an
353
+ * end the webhook was off for never moved it past). Then each end the store holds that the ledger does not, and that is
354
+ * still due, is queued under the store's end time, so under the same webhook-id. `current` reads the run as the store
355
+ * holds it right before its end is queued, with its notice (null: no such run now): a run continued since the rows
356
+ * were read has moved past that end, which is not queued again. Answers the runs whose end the store refused to queue
357
+ * (`unsaved`): the caller tells each again until it is saved (server.ts endsLeft), since no feed change will. */
260
358
  async catchUp(rows, current) {
261
- const config = this.config();
359
+ const config = this.config;
360
+ const unsaved = [];
262
361
  if (this.closed || !config || config.disabled)
263
- return;
362
+ return unsaved;
264
363
  const store = new Map([...rows].map((row) => [row.id, row]));
265
- let dropped = false;
266
- for (const [id, noticed] of Object.entries(this.notices)) {
364
+ const forget = [];
365
+ for (const [id, noticed] of this.notices) {
267
366
  const row = store.get(id);
268
367
  if (this.told.has(id) || (row && (row.state === "running" || !noticed.waits?.length)))
269
368
  continue;
270
- if (row && noticed.ended)
271
- this.notices[id] = { ended: noticed.ended };
272
- else
273
- delete this.notices[id];
274
- dropped = true;
369
+ for (const wait of noticed.waits ?? [])
370
+ forget.push({ runId: id, marker: `${WAIT}${wait}` });
371
+ if (!row && noticed.ended !== undefined)
372
+ forget.push({ runId: id, marker: `${ENDED}${noticed.ended}` });
373
+ }
374
+ if (forget.length) {
375
+ await this.store.channels.forget(WEBHOOK_CHANNEL, forget);
376
+ for (const { runId } of forget) {
377
+ const noticed = this.notices.get(runId);
378
+ if (store.has(runId) && noticed?.ended !== undefined)
379
+ this.notices.set(runId, { ended: noticed.ended });
380
+ else
381
+ this.notices.delete(runId);
382
+ }
275
383
  }
276
- if (dropped)
277
- await this.writeOutbox();
278
384
  for (const { id, state, endedAt } of store.values()) {
279
- if (state === "running" || !endedAt || this.notices[id]?.ended === endedAt || !this.due(endedAt, config))
385
+ if (state === "running" || !endedAt || this.notices.get(id)?.ended === endedAt || !this.due(endedAt, config))
280
386
  continue;
281
387
  const now = await current(id).catch((error) => (this.say({ condition: "notice_unread", run: id, error: error.message }), undefined));
282
388
  if (now === undefined)
@@ -285,185 +391,223 @@ export class Webhooks {
285
391
  this.say({ condition: "end_moved_on", run: id, ended: endedAt });
286
392
  continue;
287
393
  }
288
- await this.emit("run.ended", now.notice, endedAt);
394
+ if ((await this.emit("run.ended", now.notice, endedAt)) === "unsaved")
395
+ unsaved.push(id);
289
396
  }
397
+ return unsaved;
290
398
  }
291
399
  /** POST .../test: a `webhook.test` message tried once now, never again; its attempt. */
292
- test() {
400
+ async test() {
293
401
  this.need();
294
- return this.attempt(this.enqueue(`msg_${randomBytes(16).toString("hex")}`, "webhook.test", {}).message, { retry: false, redelivery: false });
402
+ const id = `msg_${randomBytes(16).toString("hex")}`;
403
+ await this.posted({ id, channel: WEBHOOK_CHANNEL, moment: "webhook.test", body: this.body("webhook.test", {}), nextAt: Date.now() });
404
+ return this.attempt(id, { retry: false, redelivery: false });
405
+ }
406
+ /** A message (and its ledger row, `told`) queued in one transaction, then made durable (the store's flush, as every write
407
+ * the server confirms is) before it is answered or tried: a crash of the machine never loses a message answered
408
+ * `queued`, nor the row that keeps it from being told twice. Tracked while in flight, so a DELETE waits for it. */
409
+ posted(post, told) {
410
+ const writing = (async () => {
411
+ const added = await this.store.channels.post(post, told);
412
+ await this.store.flush();
413
+ return added;
414
+ })();
415
+ const held = writing.then(() => undefined, () => undefined);
416
+ this.posting.add(held);
417
+ void held.then(() => this.posting.delete(held));
418
+ return writing;
295
419
  }
296
420
  /** POST .../deliveries/{webhook_id}/redeliver: the message sent again once now, under its own webhook-id and body. */
297
- redeliver(id) {
421
+ async redeliver(id) {
298
422
  this.need();
299
- const message = this.messages.find((m) => m.id === id);
300
- if (!message)
423
+ const post = await this.store.channels.get(id);
424
+ if (!post || post.channel !== WEBHOOK_CHANNEL)
301
425
  throw new ApiError("not_found", `no message ${id} among the last ${ATTEMPTS_KEPT} attempts`);
302
- return this.attempt(message, { retry: false, redelivery: true });
426
+ return this.attempt(id, { retry: false, redelivery: true });
303
427
  }
304
- /** Stops: no try starts, those in flight are cut and waited for, and nothing more is written but what a failed write left
305
- * only here. A message cut here is still pending in the store, for the next server (its receiver may get it twice,
306
- * under the same webhook-id). Before the store closes. */
428
+ /** Stops: no try starts, those in flight are cut and waited for, and nothing more is written but the tries' writes the
429
+ * store refused before (resettle), each written now and waited for, so a try's known outcome (a delivered message, a
430
+ * 410's turn-off) lands before the store closes. A message cut here is still queued in the store, for the next server
431
+ * (its receiver may get it twice, under the same webhook-id). */
307
432
  async close() {
308
433
  this.closed = true;
309
- for (const timer of this.timers)
434
+ for (const timer of this.timers.values())
310
435
  clearTimeout(timer);
311
436
  this.timers.clear();
312
- clearTimeout(this.saving);
437
+ const waiting = [...this.rewriting];
438
+ this.rewriting.clear();
439
+ for (const [timer, rewrite] of waiting)
440
+ (clearTimeout(timer), void rewrite());
313
441
  this.stop.abort();
314
442
  await Promise.allSettled([...this.trying]);
315
- await this.writing;
316
- // A notice a failed write left only here is written now, while the store is still this server's.
317
- if (this.unsaved)
318
- await this.persist();
443
+ await Promise.allSettled([...this.rewrites]);
444
+ }
445
+ /** Why `url` may not be sent to (a private address, by name or by what the name resolves to now), or undefined. A name
446
+ * that does not resolve passes here: the try resolves it again, and refuses then. */
447
+ async privateAt(url) {
448
+ if (this.privateTargets)
449
+ return undefined;
450
+ const host = url.hostname.replace(/^\[|\]$/g, "");
451
+ if (LOCAL_NAME.test(host))
452
+ return host;
453
+ const { isPrivateAddress } = await import("@parcha/pi-browser");
454
+ if (net.isIP(host))
455
+ return isPrivateAddress(host) ? host : undefined;
456
+ const addresses = await this.lookup(host).catch(() => []);
457
+ return addresses.find(isPrivateAddress);
319
458
  }
320
- config() {
321
- return this.current;
459
+ /** The address a try dials for `url`, checked: every address its name resolves to now is public (unless the operator
460
+ * allows private ones), and the connection goes to the one checked, so a name that resolves again between the check
461
+ * and the connect cannot reach another. A refusal in words. */
462
+ async dialled(url, signal) {
463
+ if (this.privateTargets)
464
+ return {};
465
+ const host = url.hostname.replace(/^\[|\]$/g, "");
466
+ if (LOCAL_NAME.test(host))
467
+ return { refused: `refused: ${host} is not a public host` };
468
+ const { isPrivateAddress, pinnedLookup } = await import("@parcha/pi-browser");
469
+ let addresses;
470
+ try {
471
+ addresses = net.isIP(host) ? [host] : await abortable(this.lookup(host), signal);
472
+ }
473
+ catch (error) {
474
+ // The try's own bound, cut or the server stopping: the lookup is given up on, never waited out.
475
+ if (signal.aborted)
476
+ return { refused: signal.reason?.name === "TimeoutError" ? `no answer in ${TIMEOUT_MS / 1000} s` : "not reached: the server is stopping" };
477
+ return { refused: `not reached: ${error.code ?? "its name does not resolve"}` };
478
+ }
479
+ if (!addresses.length || addresses.some(isPrivateAddress))
480
+ return { refused: `refused: ${host} is not a public host` };
481
+ return { dispatcher: new Agent({ connect: { lookup: pinnedLookup(addresses[0]) } }) };
322
482
  }
323
- /** Whether what is held here is in the store: once every outbox write asked for so far has settled (each writes it
324
- * whole), `queued` when the last one landed, else `unsaved`. A moment told again while its first write is still in
325
- * flight waits for it, never answering `queued` before it lands. */
326
- async landed() {
327
- await this.writing;
328
- return this.unsaved ? "unsaved" : "queued";
483
+ signing() {
484
+ return this.signingSecret() !== undefined ? "sealed" : "unreadable";
329
485
  }
330
- /** `work`, once every change of the webhook asked for before it has settled, failed or not. */
331
- change(work) {
332
- const done = this.changing.then(work, work);
333
- this.changing = done.then(() => undefined, () => undefined);
334
- return done;
486
+ /** The secret the webhook's setting names, opened here; undefined when none is set, or it does not open here. */
487
+ signingSecret(config = this.config) {
488
+ return config ? this.secrets.get(config.secret_scope, SECRET_FIELD) : undefined;
335
489
  }
336
- /** The signing secret, opened here; undefined when there is none, or it does not open under this server's seal key. */
337
- signingSecret() {
338
- return this.secret.get(SERVER_SCOPE, SECRET_FIELD);
490
+ body(type, data) {
491
+ return JSON.stringify({ type, timestamp: new Date().toISOString(), data });
339
492
  }
340
- /** Throws when the write fails: the webhook as held here stays as it was. */
493
+ /** The setting written, then held here: a write the store refuses throws, and what was held stays held. */
341
494
  async write(config) {
342
- await this.store.settings.put(WEBHOOK_SETTING, { v: 1, ...config });
495
+ await this.store.settings.put(WEBHOOK_SETTING, config);
496
+ // Durable before the PUT (or the 410 that turns it off) answers, as the store's other confirmed writes are.
343
497
  await this.store.flush();
344
- this.current = config;
345
- }
346
- /** The outbox as the last server left it. One of another version is not read, and the log says which it was. */
347
- outboxOf(doc) {
348
- if (isObject(doc) && doc.v !== OUTBOX_VERSION)
349
- this.say({ condition: "outbox_not_read", setting: OUTBOX_SETTING, version: String(doc.v), reason: `not this server's version (${OUTBOX_VERSION})` });
350
- if (!isObject(doc) || doc.v !== OUTBOX_VERSION || !Array.isArray(doc.messages) || !Array.isArray(doc.attempts))
351
- return { messages: [], attempts: [], notices: {} };
352
- const notices = isObject(doc.notices) ? Object.fromEntries(Object.entries(doc.notices).filter(([, n]) => isObject(n))) : {};
353
- return { messages: doc.messages.filter((m) => isObject(m) && typeof m.id === "string" && typeof m.body === "string"), attempts: doc.attempts.filter(isObject), notices };
354
- }
355
- /** Whether an end's run.ended is still to be queued: at or after the webhook was set and the outbox's day began (a
356
- * marker that names no time is not judged by one). The catch-up and the ledger's pruning read the same line, so the
357
- * ledger never forgets an end a start would look for. */
498
+ this.config = config;
499
+ }
500
+ /** Whether an end's run.ended is still to be queued: at or after the webhook was set and the day began (a marker that
501
+ * names no time is not judged by one). The catch-up and the ledger's pruning read the same line, so the ledger never
502
+ * forgets an end a start would look for. */
358
503
  due(endedAt, config) {
359
504
  const at = Date.parse(endedAt);
360
505
  return !Number.isFinite(at) || at >= Math.max(Date.parse(config.updated_at), Date.now() - END_NOTICE_WINDOW_MS);
361
506
  }
362
- /** The ledger without what no start looks for: a run whose end is no longer due goes, with the waits it ended past.
363
- * Waits with no end after them stay while the run stands at it, however long: never pruned by age, so the same question
364
- * is never asked again. */
365
- prune(config) {
366
- for (const [id, noticed] of Object.entries(this.notices))
367
- if (noticed.ended && !this.due(noticed.ended, config))
368
- delete this.notices[id];
369
- }
370
- /** The outbox written, after every write asked for before it; whether it landed. One that failed is kept here and
371
- * written again until a write lands (or the close writes it). Closed, nothing is written: the store may be the next
372
- * server's already. */
373
- writeOutbox() {
374
- if (this.closed)
375
- return Promise.resolve(!this.unsaved);
376
- this.writing = this.writing.then(() => this.persist());
377
- return this.writing.then((landed) => {
378
- if (!landed && !this.saving && !this.closed) {
379
- const timer = setTimeout(() => { this.saving = undefined; void this.writeOutbox(); }, OUTBOX_RETRY_MS);
380
- timer.unref();
381
- this.saving = timer;
382
- }
383
- return landed;
384
- });
385
- }
386
- /** The outbox written whole, in one durable commit: the last attempts, and the messages pending or tried by one of
387
- * those (a redelivery sends one again). False when the write failed, which the log says once until one lands. */
388
- async persist() {
389
- this.attempts = this.attempts.slice(-ATTEMPTS_KEPT);
390
- const tried = new Set(this.attempts.map((a) => a.webhook_id));
391
- this.messages = this.messages.filter((m) => m.status === "pending" || tried.has(m.id) || this.sending.has(m.id));
507
+ /** The ledger's ends no longer due go (a start would not look for them). Waits with no end after them stay while the run
508
+ * stands at them, however long: never pruned by age, so the same question is never asked again. */
509
+ async prune(config) {
510
+ const stale = [...this.notices].filter(([, noticed]) => noticed.ended !== undefined && !this.due(noticed.ended, config));
511
+ if (!stale.length)
512
+ return;
392
513
  try {
393
- await this.store.settings.put(OUTBOX_SETTING, { v: OUTBOX_VERSION, messages: this.messages, attempts: this.attempts, notices: this.notices });
394
- await this.store.flush();
395
- this.unsaved = false;
396
- return true;
514
+ await this.store.channels.forget(WEBHOOK_CHANNEL, stale.map(([runId, noticed]) => ({ runId, marker: `${ENDED}${noticed.ended}` })));
397
515
  }
398
- catch (error) {
399
- if (!this.unsaved)
400
- this.say({ condition: "outbox_unwritable", setting: OUTBOX_SETTING, error: error.message });
401
- this.unsaved = true;
402
- return false;
516
+ catch {
517
+ return;
518
+ }
519
+ for (const [runId, noticed] of stale) {
520
+ if (!noticed.waits?.length)
521
+ this.notices.delete(runId);
522
+ else
523
+ this.notices.set(runId, { waits: noticed.waits });
403
524
  }
404
525
  }
405
- /** A new pending message, and its outbox write (whether it landed). */
406
- enqueue(id, type, data) {
407
- const created = new Date().toISOString();
408
- const message = { id, type, body: JSON.stringify({ type, timestamp: created, data }), created_at: created, status: "pending", attempts: 0, next_at: Date.now() };
409
- this.messages.push(message);
410
- return { message, saved: this.writeOutbox() };
411
- }
412
- schedule(message, delayMs) {
526
+ schedule(id, delayMs) {
413
527
  if (this.closed)
414
528
  return;
529
+ clearTimeout(this.timers.get(id));
415
530
  const timer = setTimeout(() => {
416
- this.timers.delete(timer);
417
- // No try rejects unhandled, which would stop the server: one that throws is said, and its message stays as it was.
418
- this.attempt(message, { retry: true, redelivery: false }).catch((error) => {
531
+ this.timers.delete(id);
532
+ // No try rejects unhandled, which would stop the server: one that throws (a store that failed its read or its claim)
533
+ // is said, its message stays as it was, and it is tried again after STORE_RETRY_MS, as long as the message is queued:
534
+ // its timer was its only one. A try of a message no longer queued (sent, dropped) claims nothing, and ends there.
535
+ this.attempt(id, { retry: true, redelivery: false }).catch((error) => {
419
536
  try {
420
- this.say({ condition: "attempt_failed", webhook_id: message.id, error: error instanceof Error ? error.message : String(error) });
537
+ this.say({ condition: "attempt_failed", webhook_id: id, error: error instanceof Error ? error.message : String(error) });
421
538
  }
422
539
  catch { }
540
+ this.schedule(id, this.storeRetryMs);
423
541
  });
424
542
  }, delayMs);
425
543
  timer.unref();
426
- this.timers.add(timer);
544
+ this.timers.set(id, timer);
427
545
  }
428
- attempt(message, how) {
429
- this.sending.set(message.id, (this.sending.get(message.id) ?? 0) + 1);
430
- const trying = this.tryOnce(message, how).finally(() => {
546
+ attempt(id, how) {
547
+ this.sending.set(id, (this.sending.get(id) ?? 0) + 1);
548
+ const trying = this.tryOnce(id, how).finally(() => {
431
549
  this.trying.delete(trying);
432
- const left = this.sending.get(message.id) - 1;
550
+ const left = this.sending.get(id) - 1;
433
551
  if (left)
434
- this.sending.set(message.id, left);
552
+ this.sending.set(id, left);
435
553
  else
436
- this.sending.delete(message.id);
554
+ this.sending.delete(id);
437
555
  });
438
556
  this.trying.add(trying);
439
557
  return trying;
440
558
  }
441
559
  /** One try: POSTed, signed, to the URL set now; no redirect followed, at most 15 s. Not 2xx: tried again after the
442
- * next wait (`retry`), else failed, and the log says so. A 410 turns the webhook off. A redelivery is a try of its
443
- * own: it settles a message still pending when it lands, and never fails one. */
444
- async tryOnce(message, how) {
560
+ * next wait (`retry`), else dropped, and the log says so. A 410 turns the webhook off. A redelivery is a try of its
561
+ * own: it marks a message sent when it lands, and never drops one. */
562
+ async tryOnce(id, how) {
445
563
  const now = Date.now();
446
- const attempt = { webhook_id: message.id, type: message.type, at: iso(now), status_code: null, latency_ms: 0, error: null, retry_at: null, redelivery: how.redelivery };
447
- if (this.closed || (message.status !== "pending" && !how.redelivery))
564
+ const post = await this.store.channels.get(id);
565
+ const attempt = { webhook_id: id, type: (post?.moment ?? "webhook.test"), at: iso(now), status_code: null, latency_ms: 0, error: null, retry_at: null, redelivery: how.redelivery };
566
+ if (this.closed || !post)
448
567
  return attempt;
449
- const config = this.config();
568
+ // The try's own id: its claim's token, which fences its outcome's write (settleTry), and its row in the log, once.
569
+ const tryId = randomBytes(12).toString("hex");
570
+ // A message's own try claims it first (compare-and-set): a try already out, or one that settled it, holds it. The
571
+ // claim answers the message as it took it, which its outcome counts from; a redelivery claims nothing.
572
+ let claimed;
573
+ if (!how.redelivery) {
574
+ claimed = await this.store.channels.claim(id, now, CLAIM_MS, tryId);
575
+ if (!claimed) {
576
+ // Not taken. One still queued was not due yet (its timer fired a little before its time) or lost a race with a
577
+ // try that has settled it again since: armed again for its time, never left without a timer. One sent, dropped
578
+ // or held by another try is not this try's.
579
+ const standing = await this.store.channels.get(id);
580
+ if (standing?.state === "queued")
581
+ this.schedule(id, Math.max(standing.nextAt - Date.now(), RE_ARM_MS));
582
+ return attempt;
583
+ }
584
+ }
585
+ const config = this.config;
586
+ // Signed with the secret this setting names: the URL and its secret, as the store holds them together.
587
+ const secret = this.signingSecret(config);
450
588
  let failure;
451
589
  if (!config)
452
590
  failure = "the webhook was removed";
453
591
  else if (config.disabled)
454
592
  failure = "the webhook is off";
593
+ else if (secret === undefined)
594
+ failure = "the secret does not open here (unreadable): set the webhook again";
455
595
  else {
456
- const secret = this.signingSecret();
457
- if (secret === undefined)
458
- failure = "the secret does not open here (unreadable): set the webhook again";
596
+ const timestamp = String(Math.floor(now / 1000));
597
+ const started = performance.now();
598
+ const target = new URL(config.url);
599
+ // One bound for the whole try, its name's lookup included, and the server's stop cuts it all (close()).
600
+ const signal = AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), this.stop.signal]);
601
+ const dial = await this.dialled(target, signal);
602
+ if ("refused" in dial)
603
+ failure = dial.refused;
459
604
  else {
460
- const timestamp = String(Math.floor(now / 1000));
461
- const started = performance.now();
462
605
  try {
463
- const res = await fetch(config.url, {
464
- method: "POST", redirect: "manual", signal: AbortSignal.any([AbortSignal.timeout(TIMEOUT_MS), this.stop.signal]),
465
- headers: { "content-type": "application/json", "user-agent": "agentrun-serve-webhook/1", "webhook-id": message.id, "webhook-timestamp": timestamp, "webhook-signature": signatureOf(secret, message.id, timestamp, message.body) },
466
- body: message.body,
606
+ const res = await undiciFetch(target, {
607
+ method: "POST", redirect: "manual", signal,
608
+ headers: { "content-type": "application/json", "user-agent": "agentrun-serve-webhook/1", "webhook-id": id, "webhook-timestamp": timestamp, "webhook-signature": signatureOf(secret, id, timestamp, post.body) },
609
+ body: post.body,
610
+ ...(dial.dispatcher ? { dispatcher: dial.dispatcher } : {}),
467
611
  });
468
612
  await res.body?.cancel().catch(() => undefined);
469
613
  attempt.status_code = res.status;
@@ -473,73 +617,169 @@ export class Webhooks {
473
617
  catch (error) {
474
618
  failure = error.name === "TimeoutError" ? `no answer in ${TIMEOUT_MS / 1000} s` : `not reached: ${error.cause?.code ?? error.message}`;
475
619
  }
476
- attempt.latency_ms = Math.round(performance.now() - started);
620
+ finally {
621
+ await dial.dispatcher?.close().catch(() => undefined);
622
+ }
477
623
  }
624
+ attempt.latency_ms = Math.round(performance.now() - started);
478
625
  }
479
626
  if (this.closed)
480
627
  return attempt;
481
- // What the try found is settled against the webhook as it stands once every change before it has landed.
482
- return this.change(async () => {
483
- if (this.closed)
484
- return attempt;
485
- attempt.error = failure ?? null;
486
- this.attempts.push(attempt);
487
- // The schedule counts the message's own tries: a redelivery is a try of its own, and leaves it as it was.
488
- if (!how.redelivery)
489
- message.attempts += 1;
490
- // A 410 turns off the webhook as this try found it: one set again or removed while the try waited is not its to turn
491
- // off, and the 410 is then a failure like any other.
492
- const standing = this.config();
493
- const gone = attempt.status_code === 410 && config !== undefined && standing !== undefined && standing.url === config.url && standing.updated_at === config.updated_at && !standing.disabled;
494
- const wait = how.retry && failure && config && !gone ? this.retryMs[message.attempts - 1] : undefined;
628
+ // What the try found is settled against the webhook as it stands once every change asked for before it (a PUT, a
629
+ // DELETE, another try's 410) has landed: a 410 never turns off a webhook a PUT is setting again meanwhile.
630
+ return this.change(() => this.settleTry(id, how, now, tryId, claimed, config, failure, attempt));
631
+ }
632
+ /** A try's outcome written: the message's new state and the try, in one transaction; its next try armed; a 410 that
633
+ * still names the webhook as it stands turns it off.
634
+ *
635
+ * Every write of a message's state after a try is fenced, never worked out from a read of the message: a message's
636
+ * own try writes under its claim (`claimed`, taken by `tryId`), and the store writes it only while the message still
637
+ * holds that claim (Channels.settle), so a write that lands late, after a redelivery sent the message, a newer try
638
+ * claimed it or a DELETE dropped it, changes nothing and arms nothing. A redelivery claims nothing: a landed one writes
639
+ * sent, which no try's write undoes (sent is final), and a failed one writes no state at all, only its try. */
640
+ async settleTry(id, how, now, tryId, claimed, config, failure, attempt) {
641
+ if (this.closed)
642
+ return attempt;
643
+ attempt.error = failure ?? null;
644
+ // The schedule counts the message's own tries, from the count its claim took it at; a redelivery counts none.
645
+ const attempts = claimed ? claimed.attempts + 1 : undefined;
646
+ // A 410 turns off the webhook as this try found it: one set again or removed while the try waited is not its to turn
647
+ // off, and the 410 is then a failure like any other.
648
+ const standing = this.config;
649
+ const gone = attempt.status_code === 410 && config !== undefined && standing !== undefined && standing.url === config.url && standing.updated_at === config.updated_at && !standing.disabled;
650
+ let to;
651
+ let delay;
652
+ if (attempts === undefined) {
495
653
  if (!failure)
496
- Object.assign(message, { status: "delivered", next_at: null });
497
- // A redelivery that failed leaves the message as it is, and so does a try that ends after one delivered it.
498
- else if (!how.redelivery && message.status === "pending") {
499
- if (wait !== undefined) {
500
- // Jitter, so messages that failed together do not all come back together.
501
- const delay = Math.round(wait * (0.8 + 0.4 * Math.random()));
502
- message.next_at = Date.now() + delay;
503
- attempt.retry_at = iso(message.next_at);
504
- this.schedule(message, delay);
505
- }
506
- else {
507
- Object.assign(message, { status: "failed", next_at: null });
508
- this.say({ condition: "delivery_failed", type: message.type, webhook_id: message.id, attempts: message.attempts, ...(attempt.status_code !== null ? { status_code: attempt.status_code } : {}), error: failure });
509
- }
654
+ to = { state: "sent", reason: null };
655
+ }
656
+ else if (!failure)
657
+ to = { state: "sent", attempts, reason: null };
658
+ else {
659
+ const wait = how.retry && config && !gone ? this.retryMs[attempts - 1] : undefined;
660
+ if (wait !== undefined) {
661
+ // Jitter, so messages that failed together do not all come back together.
662
+ delay = Math.round(wait * (0.8 + 0.4 * Math.random()));
663
+ attempt.retry_at = iso(Date.now() + delay);
664
+ to = { state: "queued", attempts, nextAt: Date.now() + delay, reason: failure };
665
+ }
666
+ else
667
+ to = { state: "dropped", attempts, reason: failure };
668
+ }
669
+ const row = {
670
+ tryId, postId: id, moment: attempt.type, at: now, statusCode: attempt.status_code, latencyMs: attempt.latency_ms, error: attempt.error,
671
+ retryAt: attempt.retry_at === null ? null : Date.parse(attempt.retry_at), redelivery: how.redelivery,
672
+ };
673
+ // The same write each time it is tried: its fence and its values fixed here, so one whose outcome is unknown (the store
674
+ // threw) is written again as it was, and lands once.
675
+ const write = () => this.store.channels.settle(id, to, row, { kept: ATTEMPTS_KEPT, sending: [...this.sending.keys()], ...(claimed ? { claim: tryId } : {}) });
676
+ const after = (written) => this.afterSettle(id, written, to, delay, attempt, attempts, failure, gone, standing);
677
+ let written;
678
+ try {
679
+ written = await write();
680
+ }
681
+ catch (error) {
682
+ this.say({ condition: "attempt_unsaved", webhook_id: id, error: error.message });
683
+ // Not known to be written. This try's own outcome is known, so only its write is tried again, soon and until it
684
+ // lands, never the send: a message its receiver has is not sent again when its claim runs out, and a failed one
685
+ // keeps its schedule. A redelivery's try is recorded the same way, and its 410 still turns the webhook off.
686
+ this.resettle(id, write, after);
687
+ return attempt;
688
+ }
689
+ await after(written);
690
+ return attempt;
691
+ }
692
+ /** What follows a try's write: its next try armed and its failure said, only when its state was written (`written`: a
693
+ * fenced write that found the message taken by something newer arms nothing), and a 410's turn-off of the webhook as it
694
+ * stands, whatever the message's state, since it is the receiver's answer. The 410 is checked again against the webhook
695
+ * as it stands now: one whose write landed late (resettle), after a PUT set another URL or a DELETE removed it, was the
696
+ * old URL's, and turns nothing off. */
697
+ async afterSettle(id, written, to, delay, attempt, attempts, failure, gone, standing) {
698
+ if (!written) {
699
+ attempt.retry_at = null;
700
+ if (to)
701
+ this.say({ condition: "attempt_superseded", webhook_id: id, state: to.state });
702
+ }
703
+ else {
704
+ if (delay !== undefined)
705
+ this.schedule(id, Math.max(0, (to?.nextAt ?? Date.now()) - Date.now()));
706
+ if (to?.state === "dropped")
707
+ this.say({ condition: "delivery_failed", type: attempt.type, webhook_id: id, attempts: attempts ?? 0, ...(attempt.status_code !== null ? { status_code: attempt.status_code } : {}), error: failure });
708
+ }
709
+ const current = this.config;
710
+ const stillGone = gone && standing !== undefined && current !== undefined && !current.disabled && current.url === standing.url && current.secret_scope === standing.secret_scope && current.updated_at === standing.updated_at;
711
+ if (stillGone) {
712
+ // Gone: the receiver says this endpoint is no more. Off, its queued messages dropped, until a PUT sets it again.
713
+ const off = { ...standing, disabled: { at: attempt.at, reason: "the receiver answered 410 Gone" } };
714
+ try {
715
+ await this.write(off);
716
+ }
717
+ catch (error) {
718
+ // Off here all the same, and the next PUT writes the webhook whole.
719
+ this.config = off;
720
+ this.say({ condition: "webhook_unwritable", error: error.message });
510
721
  }
511
- if (gone) {
512
- // Gone: the receiver says this endpoint is no more. Off, its pending messages dropped, until a PUT sets it again.
513
- const disabled = { at: attempt.at, reason: "the receiver answered 410 Gone" };
514
- const off = { ...standing, disabled };
722
+ this.say({ condition: "webhook_disabled", url: shownUrl(standing.url), reason: off.disabled.reason });
723
+ // Every message whose write passed the check before the webhook went off lands first (as a DELETE waits, remove):
724
+ // then the drop takes it too, and none reaches a receiver a later PUT sets.
725
+ await Promise.all([...this.posting]);
726
+ await this.drop("the webhook is off: its receiver answered 410");
727
+ }
728
+ }
729
+ /** A try's write the store refused (`write`), written again after the store's wait until it lands, then what follows it
730
+ * (`after`, told whether the state was written), among the webhook's changes. Its own timer, beside the message's: the
731
+ * message keeps its schedule meanwhile. The write is the same one, under the same fence (settleTry): it reads nothing
732
+ * first, and a message's own try writes only while the message still holds its claim, so one a DELETE dropped, a
733
+ * redelivery sent or a newer try claimed meanwhile is left as that left it. One under way when the server closes is
734
+ * waited for, and one waiting is written at the close (close); one refused again then is left as the store holds it,
735
+ * for the next server. */
736
+ resettle(id, write, after) {
737
+ if (this.closed)
738
+ return;
739
+ const rewrite = () => {
740
+ const task = this.change(async () => {
741
+ let written;
515
742
  try {
516
- await this.write(off);
743
+ written = await write();
517
744
  }
518
- catch (error) {
519
- // Off here all the same: held, and the next PUT writes the webhook whole.
520
- this.current = off;
521
- this.say({ condition: "webhook_unwritable", setting: WEBHOOK_SETTING, error: error.message });
745
+ catch {
746
+ return this.resettle(id, write, after);
522
747
  }
523
- this.say({ condition: "webhook_disabled", url: standing.url, reason: disabled.reason });
524
- await this.drop("the webhook is off: its receiver answered 410");
525
- return attempt;
526
- }
527
- await this.writeOutbox();
528
- return attempt;
529
- });
748
+ await after(written);
749
+ }).catch((error) => this.say({ condition: "attempt_unsaved", webhook_id: id, error: error.message }));
750
+ this.rewrites.add(task);
751
+ void task.finally(() => this.rewrites.delete(task));
752
+ return task;
753
+ };
754
+ const timer = setTimeout(() => {
755
+ this.rewriting.delete(timer);
756
+ void rewrite();
757
+ }, this.storeRetryMs);
758
+ timer.unref();
759
+ this.rewriting.set(timer, rewrite);
530
760
  }
531
- /** Every pending message failed, with `why` in the log. */
532
- async drop(why) {
533
- const pending = this.messages.filter((m) => m.status === "pending");
534
- for (const message of pending)
535
- Object.assign(message, { status: "failed", next_at: null });
536
- if (pending.length)
537
- this.say({ condition: "messages_dropped", count: pending.length, reason: why });
538
- await this.writeOutbox();
761
+ /** Every queued message dropped, with `why` in the log. `strict`: a drop the store refuses throws (a DELETE then fails
762
+ * before anything else of it is done); else it is let be, and a queued message's try finds the webhook off. */
763
+ async drop(why, strict = false) {
764
+ let count = 0;
765
+ try {
766
+ count = await this.store.channels.dropAll(WEBHOOK_CHANNEL, why);
767
+ }
768
+ catch (error) {
769
+ // Refused: a DELETE fails with the webhook still set, its messages still queued and their timers kept, so each is
770
+ // tried on its schedule as before.
771
+ if (strict)
772
+ throw error;
773
+ }
774
+ for (const timer of this.timers.values())
775
+ clearTimeout(timer);
776
+ this.timers.clear();
777
+ if (count)
778
+ this.say({ condition: "messages_dropped", count, reason: why });
539
779
  }
540
780
  /** The webhook, set and on: a test or a redelivery sends nothing to one a 410 turned off, as no try does. */
541
781
  need() {
542
- const config = this.config();
782
+ const config = this.config;
543
783
  if (!config)
544
784
  throw new ApiError("not_found", "no webhook is set: PUT /v2/settings/webhook sets one");
545
785
  if (config.disabled)