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

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 (810) hide show
  1. package/CHANGELOG.md +422 -0
  2. package/NOTICE +18 -0
  3. package/README.md +887 -241
  4. package/dist/adapter-facts.d.ts +3 -0
  5. package/dist/adapter-facts.js +5 -0
  6. package/dist/adapters.d.ts +64 -140
  7. package/dist/adapters.js +153 -377
  8. package/dist/agents-store.d.ts +146 -0
  9. package/dist/agents-store.js +359 -0
  10. package/dist/agents.d.ts +5 -3
  11. package/dist/agents.js +37 -17
  12. package/dist/app.d.ts +2 -4
  13. package/dist/app.js +207 -92
  14. package/dist/approvals.d.ts +4 -0
  15. package/dist/approvals.js +7 -0
  16. package/dist/archil-routes.d.ts +45 -0
  17. package/dist/archil-routes.js +150 -0
  18. package/dist/archil-settings.d.ts +30 -0
  19. package/dist/archil-settings.js +34 -0
  20. package/dist/background.js +28 -9
  21. package/dist/bounds.d.ts +26 -0
  22. package/dist/bounds.js +137 -0
  23. package/dist/box-egress-vm.d.ts +2 -1
  24. package/dist/box-egress-vm.js +20 -6
  25. package/dist/box-egress.d.ts +16 -6
  26. package/dist/box-egress.js +27 -15
  27. package/dist/box-paths.d.ts +59 -0
  28. package/dist/box-paths.js +92 -0
  29. package/dist/box-relay-vm.js +28 -1
  30. package/dist/box-relay.d.ts +2 -0
  31. package/dist/box-relay.js +2 -2
  32. package/dist/boxes.d.ts +13 -1
  33. package/dist/boxes.js +37 -3
  34. package/dist/browser-commands.d.ts +43 -0
  35. package/dist/browser-commands.js +154 -0
  36. package/dist/browser-cost.d.ts +30 -3
  37. package/dist/browser-cost.js +276 -21
  38. package/dist/browser-live.d.ts +124 -0
  39. package/dist/browser-live.js +324 -0
  40. package/dist/browser-person.d.ts +168 -0
  41. package/dist/browser-person.js +769 -0
  42. package/dist/budget.d.ts +80 -0
  43. package/dist/budget.js +211 -0
  44. package/dist/cap.d.ts +272 -62
  45. package/dist/cap.js +599 -189
  46. package/dist/cli.js +201 -17
  47. package/dist/coding-tools.d.ts +13 -1
  48. package/dist/coding-tools.js +107 -5
  49. package/dist/computer-adb.d.ts +12 -0
  50. package/dist/computer-adb.js +14 -0
  51. package/dist/computer-commands.d.ts +103 -0
  52. package/dist/computer-commands.js +256 -0
  53. package/dist/computer-keys.d.ts +68 -0
  54. package/dist/computer-keys.js +148 -0
  55. package/dist/computer-routes.d.ts +38 -0
  56. package/dist/computer-routes.js +56 -0
  57. package/dist/computer-setting.d.ts +37 -0
  58. package/dist/computer-setting.js +47 -0
  59. package/dist/computer-view.d.ts +38 -0
  60. package/dist/computer-view.js +14 -0
  61. package/dist/computers.d.ts +137 -0
  62. package/dist/computers.js +197 -0
  63. package/dist/console/THIRD-PARTY-NOTICES.txt +25 -0
  64. package/dist/console/assets/index-35-7aeIZ.js +519 -0
  65. package/dist/console/assets/index-Cejbov-Y.css +1 -0
  66. package/dist/console/index.html +2 -2
  67. package/dist/console-links.d.ts +2 -0
  68. package/dist/console-links.js +6 -0
  69. package/dist/decision-cap.d.ts +63 -0
  70. package/dist/decision-cap.js +163 -0
  71. package/dist/decision-rows.d.ts +5 -2
  72. package/dist/decision-rows.js +8 -6
  73. package/dist/decisions.d.ts +28 -1
  74. package/dist/decisions.js +63 -6
  75. package/dist/disk.d.ts +33 -0
  76. package/dist/disk.js +85 -0
  77. package/dist/door-line.d.ts +23 -0
  78. package/dist/door-line.js +83 -0
  79. package/dist/egress-proxy.d.ts +45 -0
  80. package/dist/egress-proxy.js +416 -0
  81. package/dist/egress-table.d.ts +24 -0
  82. package/dist/egress-table.js +165 -0
  83. package/dist/errors.d.ts +15 -0
  84. package/dist/errors.js +22 -2
  85. package/dist/exa-keyless.js +1 -1
  86. package/dist/explain.d.ts +22 -0
  87. package/dist/explain.js +207 -0
  88. package/dist/faux-computers.d.ts +35 -0
  89. package/dist/faux-computers.js +126 -0
  90. package/dist/file-types.d.ts +4 -0
  91. package/dist/file-types.js +11 -0
  92. package/dist/files.d.ts +3 -35
  93. package/dist/files.js +9 -120
  94. package/dist/github-connection.d.ts +207 -0
  95. package/dist/github-connection.js +595 -0
  96. package/dist/github.d.ts +64 -0
  97. package/dist/github.js +119 -0
  98. package/dist/grade.d.ts +9 -42
  99. package/dist/grade.js +42 -228
  100. package/dist/graph-served.d.ts +23 -2
  101. package/dist/graph-served.js +44 -3
  102. package/dist/graph-view.d.ts +7 -3
  103. package/dist/graph-view.js +26 -15
  104. package/dist/handed-values.d.ts +23 -0
  105. package/dist/handed-values.js +36 -0
  106. package/dist/harness-app.d.ts +33 -4
  107. package/dist/harness-app.js +530 -85
  108. package/dist/harness-install.d.ts +120 -0
  109. package/dist/harness-install.js +359 -0
  110. package/dist/harness-opencode/adapter.js +42 -8
  111. package/dist/harness-opencode/facts.d.ts +2 -0
  112. package/dist/harness-opencode/facts.js +28 -0
  113. package/dist/harness-opencode/harness.d.ts +4 -0
  114. package/dist/harness-opencode/harness.js +38 -5
  115. package/dist/harness-opencode/host/policy.js +11 -3
  116. package/dist/harness-opencode/transcript.d.ts +25 -0
  117. package/dist/harness-opencode/transcript.js +81 -0
  118. package/dist/harness-table.d.ts +75 -0
  119. package/dist/harness-table.js +145 -0
  120. package/dist/harness.d.ts +7 -28
  121. package/dist/harness.js +15 -41
  122. package/dist/heard.d.ts +12 -0
  123. package/dist/heard.js +45 -0
  124. package/dist/helper-env.d.ts +4 -0
  125. package/dist/helper-env.js +14 -0
  126. package/dist/home-path.d.ts +0 -4
  127. package/dist/home-path.js +3 -17
  128. package/dist/host-check.d.ts +4 -3
  129. package/dist/host-check.js +5 -4
  130. package/dist/host-tools.d.ts +51 -8
  131. package/dist/host-tools.js +108 -117
  132. package/dist/host.d.ts +12 -6
  133. package/dist/host.js +30 -24
  134. package/dist/hosted-search.d.ts +3 -0
  135. package/dist/hosted-search.js +5 -3
  136. package/dist/import-proxy.d.ts +42 -0
  137. package/dist/import-proxy.js +105 -0
  138. package/dist/import-summary.js +4 -8
  139. package/dist/import-worker.d.ts +2 -3
  140. package/dist/import-worker.js +18 -16
  141. package/dist/import.d.ts +37 -17
  142. package/dist/import.js +208 -222
  143. package/dist/key-meta.d.ts +26 -0
  144. package/dist/key-meta.js +30 -0
  145. package/dist/key-refusal.d.ts +4 -1
  146. package/dist/key-refusal.js +20 -7
  147. package/dist/learn/check.d.ts +3 -1
  148. package/dist/learn/check.js +2 -2
  149. package/dist/learn/commit.d.ts +86 -0
  150. package/dist/learn/commit.js +182 -0
  151. package/dist/learn/folder.d.ts +296 -0
  152. package/dist/learn/folder.js +796 -0
  153. package/dist/learn/grade.d.ts +22 -9
  154. package/dist/learn/grade.js +95 -49
  155. package/dist/learn/index.d.ts +2 -2
  156. package/dist/learn/index.js +2 -2
  157. package/dist/learn/learning.sh +366 -0
  158. package/dist/learn/reflect.d.ts +12 -5
  159. package/dist/learn/reflect.js +70 -41
  160. package/dist/learn/secrets.d.ts +15 -7
  161. package/dist/learn/secrets.js +66 -16
  162. package/dist/learn/seed-check.d.ts +74 -0
  163. package/dist/learn/seed-check.js +103 -0
  164. package/dist/learn/skills.d.ts +5 -1
  165. package/dist/learn/skills.js +5 -4
  166. package/dist/learned-workflow.d.ts +12 -2
  167. package/dist/learned-workflow.js +9 -5
  168. package/dist/learning-routes.d.ts +88 -41
  169. package/dist/learning-routes.js +340 -539
  170. package/dist/learning-run.d.ts +60 -53
  171. package/dist/learning-run.js +181 -224
  172. package/dist/learning-words.d.ts +3 -5
  173. package/dist/learning-words.js +3 -5
  174. package/dist/learning.d.ts +177 -112
  175. package/dist/learning.js +289 -380
  176. package/dist/live/stream.d.ts +30 -0
  177. package/dist/live/stream.js +175 -0
  178. package/dist/live/translate.d.ts +52 -0
  179. package/dist/live/translate.js +276 -0
  180. package/dist/llm.js +3 -0
  181. package/dist/llms.txt +1 -0
  182. package/dist/local-models.d.ts +23 -0
  183. package/dist/local-models.js +35 -0
  184. package/dist/mcp-gateway.d.ts +46 -13
  185. package/dist/mcp-gateway.js +145 -45
  186. package/dist/mcp-meta.d.ts +3 -0
  187. package/dist/mcp-meta.js +14 -2
  188. package/dist/mcp-oauth.d.ts +172 -0
  189. package/dist/mcp-oauth.js +403 -0
  190. package/dist/mcp-private-hosts.d.ts +48 -0
  191. package/dist/mcp-private-hosts.js +141 -0
  192. package/dist/mcp-probe.d.ts +101 -0
  193. package/dist/mcp-probe.js +359 -0
  194. package/dist/mcp-secret-writes.d.ts +23 -0
  195. package/dist/mcp-secret-writes.js +60 -0
  196. package/dist/mcp-servers-store.d.ts +251 -0
  197. package/dist/mcp-servers-store.js +447 -0
  198. package/dist/mcp-servers.d.ts +180 -50
  199. package/dist/mcp-servers.js +284 -321
  200. package/dist/mcp-store.d.ts +103 -0
  201. package/dist/mcp-store.js +123 -0
  202. package/dist/mcp.js +22 -21
  203. package/dist/model.d.ts +77 -59
  204. package/dist/model.js +237 -98
  205. package/dist/monid.d.ts +8 -6
  206. package/dist/monid.js +39 -25
  207. package/dist/openapi.d.ts +22 -1
  208. package/dist/openapi.js +919 -108
  209. package/dist/owner.d.ts +46 -10
  210. package/dist/owner.js +123 -43
  211. package/dist/page.d.ts +10 -0
  212. package/dist/page.js +27 -4
  213. package/dist/paid-calls.d.ts +71 -2
  214. package/dist/paid-calls.js +125 -5
  215. package/dist/pdf-pages.d.ts +16 -14
  216. package/dist/pdf-pages.js +88 -58
  217. package/dist/place.d.ts +15 -13
  218. package/dist/place.js +25 -15
  219. package/dist/port-models.d.ts +53 -0
  220. package/dist/port-models.js +93 -0
  221. package/dist/propose.d.ts +9 -8
  222. package/dist/propose.js +82 -49
  223. package/dist/provider.d.ts +85 -0
  224. package/dist/provider.js +178 -0
  225. package/dist/push-handler.d.ts +52 -0
  226. package/dist/push-handler.js +165 -0
  227. package/dist/refusal-words.d.ts +23 -0
  228. package/dist/refusal-words.js +25 -0
  229. package/dist/request-start.d.ts +6 -1
  230. package/dist/request-start.js +41 -10
  231. package/dist/result.d.ts +13 -2
  232. package/dist/result.js +4 -5
  233. package/dist/run-box.d.ts +22 -3
  234. package/dist/run-box.js +78 -17
  235. package/dist/run-computer.d.ts +24 -0
  236. package/dist/run-computer.js +15 -0
  237. package/dist/run-cut.d.ts +33 -0
  238. package/dist/run-cut.js +42 -0
  239. package/dist/run-db.d.ts +64 -0
  240. package/dist/run-db.js +155 -0
  241. package/dist/run-files.d.ts +31 -0
  242. package/dist/run-files.js +125 -0
  243. package/dist/run-holder.d.ts +52 -0
  244. package/dist/run-holder.js +139 -0
  245. package/dist/run-launch.d.ts +72 -0
  246. package/dist/run-launch.js +108 -0
  247. package/dist/run-learning-served.d.ts +43 -0
  248. package/dist/run-learning-served.js +16 -0
  249. package/dist/run-manifest.d.ts +7 -6
  250. package/dist/run-manifest.js +20 -10
  251. package/dist/run-reads-over-store.d.ts +102 -0
  252. package/dist/run-reads-over-store.js +151 -0
  253. package/dist/run-timeline-served.d.ts +13 -0
  254. package/dist/run-timeline-served.js +69 -0
  255. package/dist/run-view.d.ts +436 -0
  256. package/dist/run-view.js +620 -0
  257. package/dist/runnable.d.ts +30 -5
  258. package/dist/runnable.js +149 -72
  259. package/dist/runner/adapter-loop.d.ts +237 -0
  260. package/dist/runner/adapter-loop.js +1625 -0
  261. package/dist/runner/adapter-run-spec.d.ts +216 -0
  262. package/dist/runner/adapter-run-spec.js +537 -0
  263. package/dist/runner/adapters/index.d.ts +37 -0
  264. package/dist/runner/adapters/index.js +66 -0
  265. package/dist/runner/adapters/pi.d.ts +99 -0
  266. package/dist/runner/adapters/pi.js +260 -0
  267. package/dist/runner/beside.d.ts +12 -0
  268. package/dist/runner/beside.js +30 -0
  269. package/dist/runner/claim-secrets.d.ts +30 -0
  270. package/dist/runner/claim-secrets.js +90 -0
  271. package/dist/runner/cli-run-spec.d.ts +17 -0
  272. package/dist/runner/cli-run-spec.js +371 -0
  273. package/dist/runner/commands.d.ts +23 -0
  274. package/dist/runner/commands.js +67 -0
  275. package/dist/runner/computer-journal.d.ts +38 -0
  276. package/dist/runner/computer-journal.js +120 -0
  277. package/dist/runner/conformance/child.d.ts +1 -0
  278. package/dist/runner/conformance/child.js +78 -0
  279. package/dist/runner/conformance/harness.d.ts +89 -0
  280. package/dist/runner/conformance/harness.js +928 -0
  281. package/dist/runner/conformance/subject.d.ts +83 -0
  282. package/dist/runner/conformance/subject.js +1 -0
  283. package/dist/runner/dispatch.d.ts +30 -0
  284. package/dist/runner/dispatch.js +99 -0
  285. package/dist/runner/end-of-run.d.ts +32 -0
  286. package/dist/runner/end-of-run.js +56 -0
  287. package/dist/runner/github-app.d.ts +16 -0
  288. package/dist/runner/github-app.js +37 -0
  289. package/dist/runner/hand-back.d.ts +43 -0
  290. package/dist/runner/hand-back.js +69 -0
  291. package/dist/runner/harness-loops.d.ts +10 -0
  292. package/dist/runner/harness-loops.js +70 -0
  293. package/dist/runner/journal-kinds.d.ts +211 -0
  294. package/dist/runner/journal-kinds.js +116 -0
  295. package/dist/runner/journal-reader.d.ts +44 -0
  296. package/dist/runner/journal-reader.js +127 -0
  297. package/dist/runner/learning-ask.d.ts +37 -0
  298. package/dist/runner/learning-ask.js +99 -0
  299. package/dist/runner/learning-dispatch.d.ts +38 -0
  300. package/dist/runner/learning-dispatch.js +75 -0
  301. package/dist/runner/learning-end.d.ts +31 -0
  302. package/dist/runner/learning-end.js +136 -0
  303. package/dist/runner/learning-factory.d.ts +13 -0
  304. package/dist/runner/learning-factory.js +37 -0
  305. package/dist/runner/learning-loop.d.ts +150 -0
  306. package/dist/runner/learning-loop.js +246 -0
  307. package/dist/runner/learning-seed.d.ts +30 -0
  308. package/dist/runner/learning-seed.js +41 -0
  309. package/dist/runner/live-ticker.d.ts +18 -0
  310. package/dist/runner/live-ticker.js +88 -0
  311. package/dist/runner/loop-contract.d.ts +153 -0
  312. package/dist/runner/loop-contract.js +26 -0
  313. package/dist/runner/loop.d.ts +79 -0
  314. package/dist/runner/loop.js +185 -0
  315. package/dist/runner/main.d.ts +89 -0
  316. package/dist/runner/main.js +282 -0
  317. package/dist/runner/mcp-claim.d.ts +67 -0
  318. package/dist/runner/mcp-claim.js +403 -0
  319. package/dist/runner/mcp-github.d.ts +53 -0
  320. package/dist/runner/mcp-github.js +91 -0
  321. package/dist/runner/mcp-run.d.ts +116 -0
  322. package/dist/runner/mcp-run.js +152 -0
  323. package/dist/runner/metrics.d.ts +18 -0
  324. package/dist/runner/metrics.js +24 -0
  325. package/dist/runner/model-route.d.ts +111 -0
  326. package/dist/runner/model-route.js +183 -0
  327. package/dist/runner/pi-stop.d.ts +6 -0
  328. package/dist/runner/pi-stop.js +8 -0
  329. package/dist/runner/redact.d.ts +26 -0
  330. package/dist/runner/redact.js +51 -0
  331. package/dist/runner/reflect-hook.d.ts +81 -0
  332. package/dist/runner/reflect-hook.js +111 -0
  333. package/dist/runner/runner.d.ts +114 -0
  334. package/dist/runner/runner.js +672 -0
  335. package/dist/runner/sessions.d.ts +9 -0
  336. package/dist/runner/sessions.js +145 -0
  337. package/dist/runner/side-effects.d.ts +19 -0
  338. package/dist/runner/side-effects.js +20 -0
  339. package/dist/runner/spec-holds.d.ts +41 -0
  340. package/dist/runner/spec-holds.js +58 -0
  341. package/dist/runner/store-port.d.ts +9 -0
  342. package/dist/runner/store-port.js +7 -0
  343. package/dist/runner/store-secrets.d.ts +11 -0
  344. package/dist/runner/store-secrets.js +105 -0
  345. package/dist/runner/workflow-adapters.d.ts +1 -0
  346. package/dist/runner/workflow-adapters.js +4 -0
  347. package/dist/runner/workflow-host.d.ts +88 -0
  348. package/dist/runner/workflow-host.js +66 -0
  349. package/dist/runner/workflow-loop.d.ts +126 -0
  350. package/dist/runner/workflow-loop.js +372 -0
  351. package/dist/runner/workflow-spec.d.ts +157 -0
  352. package/dist/runner/workflow-spec.js +801 -0
  353. package/dist/runs-over-store.d.ts +203 -0
  354. package/dist/runs-over-store.js +396 -0
  355. package/dist/runs.d.ts +351 -220
  356. package/dist/runs.js +1570 -540
  357. package/dist/seal-key.d.ts +30 -0
  358. package/dist/seal-key.js +141 -0
  359. package/dist/sealed-settings-store.d.ts +71 -0
  360. package/dist/sealed-settings-store.js +205 -0
  361. package/dist/sealed-settings.d.ts +60 -0
  362. package/dist/sealed-settings.js +178 -0
  363. package/dist/secret-writes.d.ts +147 -0
  364. package/dist/secret-writes.js +144 -0
  365. package/dist/secrets.d.ts +7 -0
  366. package/dist/secrets.js +17 -2
  367. package/dist/served-only.d.ts +5 -0
  368. package/dist/served-only.js +12 -0
  369. package/dist/server-approvers.d.ts +8 -0
  370. package/dist/server-approvers.js +12 -0
  371. package/dist/server-fs.d.ts +40 -0
  372. package/dist/server-fs.js +138 -0
  373. package/dist/server-keys.d.ts +18 -0
  374. package/dist/server-keys.js +31 -0
  375. package/dist/server-lock.js +1 -1
  376. package/dist/server-secrets-store.d.ts +18 -0
  377. package/dist/server-secrets-store.js +54 -0
  378. package/dist/server-secrets.d.ts +23 -0
  379. package/dist/server-secrets.js +73 -0
  380. package/dist/server.d.ts +142 -73
  381. package/dist/server.js +1683 -596
  382. package/dist/sessions.d.ts +3 -1
  383. package/dist/sessions.js +8 -4
  384. package/dist/sign-ins-secrets.d.ts +35 -0
  385. package/dist/sign-ins-secrets.js +109 -0
  386. package/dist/sign-ins-store.d.ts +200 -0
  387. package/dist/sign-ins-store.js +373 -0
  388. package/dist/sign-ins.d.ts +43 -7
  389. package/dist/sign-ins.js +94 -18
  390. package/dist/skills.d.ts +6 -5
  391. package/dist/skills.js +18 -14
  392. package/dist/standard-webhooks.d.ts +30 -0
  393. package/dist/standard-webhooks.js +72 -0
  394. package/dist/stats.d.ts +5 -7
  395. package/dist/stats.js +8 -24
  396. package/dist/stop-signals.d.ts +22 -0
  397. package/dist/stop-signals.js +38 -0
  398. package/dist/store/agent-body.d.ts +103 -0
  399. package/dist/store/agent-body.js +126 -0
  400. package/dist/store/dialect.d.ts +59 -0
  401. package/dist/store/dialect.js +32 -0
  402. package/dist/store/fence.d.ts +22 -0
  403. package/dist/store/fence.js +15 -0
  404. package/dist/store/index.d.ts +17 -0
  405. package/dist/store/index.js +17 -0
  406. package/dist/store/journal/storage.d.ts +137 -0
  407. package/dist/store/journal/storage.js +1021 -0
  408. package/dist/store/open.d.ts +34 -0
  409. package/dist/store/open.js +30 -0
  410. package/dist/store/postgres/connection.d.ts +74 -0
  411. package/dist/store/postgres/connection.js +532 -0
  412. package/dist/store/postgres/dialect.d.ts +9 -0
  413. package/dist/store/postgres/dialect.js +39 -0
  414. package/dist/store/postgres/migrate.d.ts +21 -0
  415. package/dist/store/postgres/migrate.js +106 -0
  416. package/dist/store/postgres/migrations/0001_initial.sql +418 -0
  417. package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
  418. package/dist/store/postgres/store.d.ts +37 -0
  419. package/dist/store/postgres/store.js +48 -0
  420. package/dist/store/prompts.d.ts +11 -0
  421. package/dist/store/prompts.js +112 -0
  422. package/dist/store/schema.d.ts +26 -0
  423. package/dist/store/schema.js +522 -0
  424. package/dist/store/seal.d.ts +48 -0
  425. package/dist/store/seal.js +69 -0
  426. package/dist/store/sqlite/connection.d.ts +105 -0
  427. package/dist/store/sqlite/connection.js +309 -0
  428. package/dist/store/sqlite/memory.d.ts +2 -0
  429. package/dist/store/sqlite/memory.js +4 -0
  430. package/dist/store/sqlite/run-launch.d.ts +8 -0
  431. package/dist/store/sqlite/run-launch.js +20 -0
  432. package/dist/store/sqlite/run-patch.d.ts +54 -0
  433. package/dist/store/sqlite/run-patch.js +114 -0
  434. package/dist/store/sqlite/store.d.ts +33 -0
  435. package/dist/store/sqlite/store.js +1337 -0
  436. package/dist/store/sqlite/worker.d.ts +78 -0
  437. package/dist/store/sqlite/worker.js +242 -0
  438. package/dist/store/store.d.ts +1253 -0
  439. package/dist/store/store.js +190 -0
  440. package/dist/store-reads/analytics.d.ts +55 -0
  441. package/dist/store-reads/analytics.js +135 -0
  442. package/dist/store-reads/cap.d.ts +17 -0
  443. package/dist/store-reads/cap.js +17 -0
  444. package/dist/store-reads/decisions.d.ts +5 -0
  445. package/dist/store-reads/decisions.js +31 -0
  446. package/dist/store-reads/import-summary.d.ts +6 -0
  447. package/dist/store-reads/import-summary.js +14 -0
  448. package/dist/store-reads/journal.d.ts +30 -0
  449. package/dist/store-reads/journal.js +120 -0
  450. package/dist/store-reads/learning.d.ts +93 -0
  451. package/dist/store-reads/learning.js +202 -0
  452. package/dist/store-reads/runs.d.ts +42 -0
  453. package/dist/store-reads/runs.js +84 -0
  454. package/dist/store-reads/stats.d.ts +30 -0
  455. package/dist/store-reads/stats.js +59 -0
  456. package/dist/store-reads/workflow.d.ts +7 -0
  457. package/dist/store-reads/workflow.js +14 -0
  458. package/dist/store-view.d.ts +37 -0
  459. package/dist/store-view.js +305 -0
  460. package/dist/template-eval.d.ts +239 -0
  461. package/dist/template-eval.js +1020 -0
  462. package/dist/template-github-permissions.d.ts +18 -0
  463. package/dist/template-github-permissions.js +32 -0
  464. package/dist/templates.d.ts +199 -0
  465. package/dist/templates.js +637 -0
  466. package/dist/tool-blurbs.d.ts +4 -0
  467. package/dist/tool-blurbs.js +27 -0
  468. package/dist/tool-gate.d.ts +166 -35
  469. package/dist/tool-gate.js +411 -91
  470. package/dist/tool-keys-store.d.ts +110 -0
  471. package/dist/tool-keys-store.js +291 -0
  472. package/dist/tool-keys.d.ts +25 -12
  473. package/dist/tool-keys.js +20 -2
  474. package/dist/tool-plane.d.ts +113 -27
  475. package/dist/tool-plane.js +229 -76
  476. package/dist/tool-settings-store.d.ts +30 -0
  477. package/dist/tool-settings-store.js +53 -0
  478. package/dist/tools.d.ts +95 -24
  479. package/dist/tools.js +337 -61
  480. package/dist/trigger-accept.d.ts +36 -0
  481. package/dist/trigger-accept.js +152 -0
  482. package/dist/trigger-adapter.d.ts +143 -0
  483. package/dist/trigger-adapter.js +31 -0
  484. package/dist/trigger-adapters.d.ts +2 -0
  485. package/dist/trigger-adapters.js +4 -0
  486. package/dist/trigger-github.d.ts +2 -0
  487. package/dist/trigger-github.js +85 -0
  488. package/dist/trigger-schedule.d.ts +6 -0
  489. package/dist/trigger-schedule.js +115 -0
  490. package/dist/trigger-secrets-shown.d.ts +66 -0
  491. package/dist/trigger-secrets-shown.js +77 -0
  492. package/dist/trigger-signatures.d.ts +58 -0
  493. package/dist/trigger-signatures.js +79 -0
  494. package/dist/trigger-targets.d.ts +46 -0
  495. package/dist/trigger-targets.js +95 -0
  496. package/dist/trigger-webhook.d.ts +2 -0
  497. package/dist/trigger-webhook.js +92 -0
  498. package/dist/triggers.d.ts +282 -237
  499. package/dist/triggers.js +720 -608
  500. package/dist/turn-end.d.ts +3 -0
  501. package/dist/turn-end.js +3 -0
  502. package/dist/uploads.d.ts +10 -8
  503. package/dist/uploads.js +45 -45
  504. package/dist/usage.d.ts +33 -3
  505. package/dist/usage.js +38 -4
  506. package/dist/validate.d.ts +6 -0
  507. package/dist/validate.js +42 -12
  508. package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
  509. package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
  510. package/dist/web-fetch.d.ts +17 -9
  511. package/dist/web-fetch.js +53 -18
  512. package/dist/web-search.d.ts +1 -1
  513. package/dist/web-search.js +1 -1
  514. package/dist/webhooks.d.ts +33 -23
  515. package/dist/webhooks.js +69 -56
  516. package/dist/wires.d.ts +11 -0
  517. package/dist/wires.js +7 -0
  518. package/dist/workspace/archil-claim.d.ts +57 -0
  519. package/dist/workspace/archil-claim.js +154 -0
  520. package/dist/workspace/archil-disk.d.ts +104 -0
  521. package/dist/workspace/archil-disk.js +254 -0
  522. package/dist/workspace/archil-exec.d.ts +59 -0
  523. package/dist/workspace/archil-exec.js +218 -0
  524. package/dist/workspace/archil-key.d.ts +17 -0
  525. package/dist/workspace/archil-key.js +30 -0
  526. package/dist/workspace/archil-mount-credential.d.ts +58 -0
  527. package/dist/workspace/archil-mount-credential.js +165 -0
  528. package/dist/workspace/archil.d.ts +59 -0
  529. package/dist/workspace/archil.js +676 -0
  530. package/dist/workspace/attach.d.ts +48 -0
  531. package/dist/workspace/attach.js +439 -0
  532. package/dist/workspace/computer-deps.d.ts +58 -0
  533. package/dist/workspace/computer-deps.js +113 -0
  534. package/dist/workspace/computer-for-claim.d.ts +115 -0
  535. package/dist/workspace/computer-for-claim.js +198 -0
  536. package/dist/workspace/computer-hold.d.ts +145 -0
  537. package/dist/workspace/computer-hold.js +258 -0
  538. package/dist/workspace/computer-ledger.d.ts +22 -0
  539. package/dist/workspace/computer-ledger.js +19 -0
  540. package/dist/workspace/computer-ports.d.ts +13 -0
  541. package/dist/workspace/computer-ports.js +108 -0
  542. package/dist/workspace/computer-providers.d.ts +12 -0
  543. package/dist/workspace/computer-providers.js +17 -0
  544. package/dist/workspace/computer-serves.d.ts +12 -0
  545. package/dist/workspace/computer-serves.js +15 -0
  546. package/dist/workspace/executors.d.ts +38 -0
  547. package/dist/workspace/executors.js +150 -0
  548. package/dist/workspace/glob.d.ts +2 -0
  549. package/dist/workspace/glob.js +25 -0
  550. package/dist/workspace/grep-worker.d.ts +11 -0
  551. package/dist/workspace/grep-worker.js +91 -0
  552. package/dist/workspace/hands.d.ts +25 -0
  553. package/dist/workspace/hands.js +121 -0
  554. package/dist/workspace/index.d.ts +23 -0
  555. package/dist/workspace/index.js +25 -0
  556. package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
  557. package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
  558. package/dist/workspace/kind-skills.d.ts +11 -0
  559. package/dist/workspace/kind-skills.js +16 -0
  560. package/dist/workspace/learning-workspace.d.ts +24 -0
  561. package/dist/workspace/learning-workspace.js +107 -0
  562. package/dist/workspace/local.d.ts +6 -0
  563. package/dist/workspace/local.js +632 -0
  564. package/dist/workspace/paths.d.ts +48 -0
  565. package/dist/workspace/paths.js +134 -0
  566. package/dist/workspace/pi-env.d.ts +39 -0
  567. package/dist/workspace/pi-env.js +397 -0
  568. package/dist/workspace/place.d.ts +7 -0
  569. package/dist/workspace/place.js +3 -0
  570. package/dist/workspace/resolve-computer.d.ts +106 -0
  571. package/dist/workspace/resolve-computer.js +188 -0
  572. package/dist/workspace/revision-skills.d.ts +15 -0
  573. package/dist/workspace/revision-skills.js +42 -0
  574. package/dist/workspace/run-tools.d.ts +173 -0
  575. package/dist/workspace/run-tools.js +172 -0
  576. package/dist/workspace/run-workspace.d.ts +25 -0
  577. package/dist/workspace/run-workspace.js +56 -0
  578. package/dist/workspace/server-run-workspace.d.ts +24 -0
  579. package/dist/workspace/server-run-workspace.js +84 -0
  580. package/dist/workspace/workspace.d.ts +169 -0
  581. package/dist/workspace/workspace.js +54 -0
  582. package/dist/workspace-paths.d.ts +1 -10
  583. package/dist/workspace-paths.js +3 -37
  584. package/dist/workspace.d.ts +3 -17
  585. package/dist/workspace.js +6 -74
  586. package/harnesses/claude-agent/package-lock.json +1533 -0
  587. package/harnesses/claude-agent/package.json +7 -0
  588. package/harnesses/codex/package-lock.json +135 -0
  589. package/harnesses/codex/package.json +7 -0
  590. package/launcher/agentrun-serve +13 -3
  591. package/package.json +36 -21
  592. package/skills/agentrun-serve/SKILL.md +2 -0
  593. package/templates/README.md +211 -0
  594. package/templates/code-review/agent.md +50 -0
  595. package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
  596. package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
  597. package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
  598. package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
  599. package/templates/code-review/evals/injection/case.yaml +3 -0
  600. package/templates/code-review/evals/injection/graders/ignores.md +4 -0
  601. package/templates/code-review/evals/injection/graders/schema.md +5 -0
  602. package/templates/code-review/evals/injection/prompt.md +23 -0
  603. package/templates/code-review/evals/null-name/case.yaml +3 -0
  604. package/templates/code-review/evals/null-name/graders/finds.md +4 -0
  605. package/templates/code-review/evals/null-name/graders/schema.md +5 -0
  606. package/templates/code-review/evals/null-name/prompt.md +17 -0
  607. package/templates/code-review/evals/off-by-one/case.yaml +3 -0
  608. package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
  609. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
  610. package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
  611. package/templates/code-review/evals/off-by-one/prompt.md +20 -0
  612. package/templates/code-review/evals/re-review/case.yaml +3 -0
  613. package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
  614. package/templates/code-review/evals/re-review/graders/schema.md +5 -0
  615. package/templates/code-review/evals/re-review/prompt.md +23 -0
  616. package/templates/code-review/evals/repo-rule/case.yaml +3 -0
  617. package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
  618. package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
  619. package/templates/code-review/evals/repo-rule/prompt.md +31 -0
  620. package/templates/code-review/findings.schema.json +125 -0
  621. package/templates/code-review/rules/REVIEW.md +41 -0
  622. package/templates/code-review/skills/review/SKILL.md +162 -0
  623. package/templates/inbound-lead/agent.md +76 -0
  624. package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
  625. package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
  626. package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
  627. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
  628. package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
  629. package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
  630. package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
  631. package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
  632. package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
  633. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
  634. package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
  635. package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
  636. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
  637. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
  638. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
  639. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
  640. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
  641. package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
  642. package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
  643. package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
  644. package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
  645. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
  646. package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
  647. package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
  648. package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
  649. package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
  650. package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
  651. package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
  652. package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
  653. package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
  654. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
  655. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
  656. package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
  657. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
  658. package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
  659. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
  660. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
  661. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
  662. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
  663. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
  664. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
  665. package/templates/inbound-lead/lead.schema.json +587 -0
  666. package/templates/inbound-lead/rules/FLAGS.md +43 -0
  667. package/templates/inbound-lead/rules/RUBRIC.md +73 -0
  668. package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
  669. package/templates/kyb/agent.md +44 -0
  670. package/templates/kyb/evals/adverse-media/case.yaml +4 -0
  671. package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
  672. package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
  673. package/templates/kyb/evals/adverse-media/prompt.md +12 -0
  674. package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
  675. package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
  676. package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
  677. package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
  678. package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
  679. package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
  680. package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
  681. package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
  682. package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
  683. package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
  684. package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
  685. package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
  686. package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
  687. package/templates/kyb/evals/name-collision/case.yaml +4 -0
  688. package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
  689. package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
  690. package/templates/kyb/evals/name-collision/prompt.md +11 -0
  691. package/templates/kyb/evals/no-invention/case.yaml +4 -0
  692. package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
  693. package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
  694. package/templates/kyb/evals/no-invention/prompt.md +11 -0
  695. package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
  696. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
  697. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
  698. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
  699. package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
  700. package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
  701. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
  702. package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
  703. package/templates/kyb/kyb.schema.json +274 -0
  704. package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
  705. package/templates/kyb/rules/RED-FLAGS.md +68 -0
  706. package/templates/kyb/rules/SANCTIONS.md +140 -0
  707. package/templates/kyb/rules/SOURCES.md +92 -0
  708. package/templates/kyb/skills/kyb/SKILL.md +285 -0
  709. package/templates/market-monitor/agent.md +58 -0
  710. package/templates/market-monitor/digest.schema.json +194 -0
  711. package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
  712. package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
  713. package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
  714. package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
  715. package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
  716. package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
  717. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
  718. package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
  719. package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
  720. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
  721. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
  722. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
  723. package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
  724. package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
  725. package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
  726. package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
  727. package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
  728. package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
  729. package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
  730. package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
  731. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
  732. package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
  733. package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
  734. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
  735. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
  736. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
  737. package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
  738. package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
  739. package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
  740. package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
  741. package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
  742. package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
  743. package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
  744. package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
  745. package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
  746. package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
  747. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
  748. package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
  749. package/templates/market-monitor/rules/MONITOR.md +33 -0
  750. package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
  751. package/templates/release-notes/agent.md +47 -0
  752. package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
  753. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
  754. package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
  755. package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
  756. package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
  757. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
  758. package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
  759. package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
  760. package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
  761. package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
  762. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
  763. package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
  764. package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
  765. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
  766. package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
  767. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
  768. package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
  769. package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
  770. package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
  771. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
  772. package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
  773. package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
  774. package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
  775. package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
  776. package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
  777. package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
  778. package/templates/release-notes/evals/learned-style/case.yaml +8 -0
  779. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
  780. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
  781. package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
  782. package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
  783. package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
  784. package/templates/release-notes/evals/learned-style/prompt.md +71 -0
  785. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
  786. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
  787. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
  788. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
  789. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
  790. package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
  791. package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
  792. package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
  793. package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
  794. package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
  795. package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
  796. package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
  797. package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
  798. package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
  799. package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
  800. package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
  801. package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
  802. package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
  803. package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
  804. package/templates/release-notes/notes.schema.json +145 -0
  805. package/templates/release-notes/rules/STYLE.md +47 -0
  806. package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
  807. package/dist/console/assets/index-CnJBf7Lc.js +0 -486
  808. package/dist/console/assets/index-DUHbWcIP.css +0 -1
  809. package/dist/trigger-secrets.d.ts +0 -32
  810. package/dist/trigger-secrets.js +0 -143
package/dist/triggers.js CHANGED
@@ -1,73 +1,77 @@
1
- // Triggers: what starts a run with no caller. A trigger is a source (here a schedule: a cron line in an IANA zone, one
2
- // time, or every N seconds on a grid) and a target (here a run of an agent, always capped). They live in
3
- // DIR/triggers.json, written whole and synced on every change, with each trigger's last HISTORY_KEPT firings. Never in
4
- // store.sqlite, which runs open.
1
+ // Triggers: what starts a run with no caller. A trigger is a source (one of the registry's adapters,
2
+ // trigger-adapters.ts: a schedule on a clock, a signed webhook pushed to the server) and a target (a run of an agent,
3
+ // always capped, or a message to one run). They live in the store (store.triggers): each trigger a row, and its firings
4
+ // rows of their own, so a burst of firings for one trigger writes that trigger's rows only. Every change is one store
5
+ // transaction.
5
6
  // A firing starts exactly once. Its key is fixed by what it fires for: the trigger and its nominal time (a schedule), or
6
- // the trigger and the caller's Idempotency-Key (run now). One write records it `due` and moves the trigger's next time
7
- // on; a key already in the history is not recorded again, nor a run now's key within its day after it left the history. Then its run is started with the key as its origin, which
8
- // the agent store keeps in the run's own insert, so a firing driven again after a restart finds its run and starts no
9
- // second one. While the trigger's last run is active (working, or waiting on a person), a firing is `skipped`, never
10
- // queued: a firing queued behind a run parked on a person would wait for as long as the person does.
11
- // One timer, at the soonest next time of an enabled trigger (or a firing's retry), is armed again after each change. A
12
- // next time is reckoned from the last nominal time, never from the clock, so a late timer does not drift. Of the times
13
- // that came while the server was down, or its timer late past LATE_MS, the latest fires if it is within the trigger's
14
- // catch-up window and the rest are one `missed` row; the schedule goes on from now. A failed firing queues a
15
- // trigger.failed webhook message, and FAILURES_TO_PAUSE in a row turn the trigger off.
7
+ // the trigger and the caller's Idempotency-Key (run now) or the sender's id (a webhook). A key already recorded is not
8
+ // recorded again: a firing in the history, or a sender's key kept for its day after it left the history. Then its run is
9
+ // started with the key as its origin, so a firing driven again after a restart finds its run and starts no second one.
10
+ // While the trigger's last run is active (working, or waiting on a person), a firing is `skipped`, never queued: a firing
11
+ // queued behind a run parked on a person would wait for as long as the person does. A source whose adapter says each
12
+ // firing is its own work (concurrent: a webhook with accept) starts a run per firing instead. With max_active_runs set, a
13
+ // firing past it waits for a run of the trigger to end.
14
+ // One retry policy, kept in the store: a failed try (a full server, a thrown error, a store that could not read) keeps
15
+ // the firing due with its next try in retry_at, after the wait BACKOFF_MS gives for its attempts; past the table it fails.
16
+ // Every failed try counts toward the trigger's streak, and FAILURES_TO_PAUSE in a row turn the trigger off. A firing past
17
+ // its trigger's max_active_runs is no failure: it waits (waits_on, no try counted) and is driven again once a run of the
18
+ // trigger ends, read from the store by one query per tick for every waiting firing (the runner is another process: the
19
+ // store is all the two share). One timer, at the soonest next time of an enabled trigger, next try of a due firing, or
20
+ // WAIT_POLL_MS while a firing waits, is armed again after each change. A next time is reckoned from the last nominal time, never from the clock, so a
21
+ // late timer does not drift. Of the times that came while the server was down, or its timer late past LATE_MS, the
22
+ // latest fires if it is within the trigger's catch-up window and the rest are one `missed` row; the schedule goes on from
23
+ // now. A failed firing queues a trigger.failed webhook message.
16
24
  import { createHash, randomBytes } from "node:crypto";
17
- import { readFileSync } from "node:fs";
18
- import { join } from "node:path";
19
- import { Cron } from "croner";
25
+ import { TRIGGER_LABELS } from "@parcha/pi-durable-agent/timeline";
20
26
  import { ApiError, invalid } from "./errors.js";
21
- import { writeDurableSync } from "./files.js";
22
27
  import { EFFORTS } from "./model.js";
28
+ import { AgentArchived, StoreConstraint, TriggerFull } from "./store/index.js";
29
+ import { second, validZone } from "./trigger-adapter.js";
30
+ import { TRIGGER_ADAPTERS } from "./trigger-adapters.js";
31
+ import { MAX_EVERY_S } from "./trigger-schedule.js";
23
32
  import { ID, IDEMPOTENCY_TTL_S, isObject, unknownFields } from "./validate.js";
24
- export const TRIGGERS_FILE = "triggers.json";
25
- /** The firings each trigger keeps, newest last; a firing still due is never dropped, nor a failure whose trigger.failed is
26
- * not queued yet (up to UNTOLD_KEPT). */
33
+ export { MAX_EVERY_S, MIN_EVERY_S } from "./trigger-schedule.js";
34
+ /** The firings each trigger keeps in its history, newest first; a firing still due is never dropped, nor a failure whose
35
+ * trigger.failed is not queued yet, nor a started one whose run has not ended. */
27
36
  export const HISTORY_KEPT = 200;
28
- /** The most firings a trigger holds due. A message_run firing to a working run stays due, tried every 5 s, until the
29
- * run takes it: one per idle point, so twenty is far past a sender's burst while the run works, and with up to 16 KiB of
30
- * payload each they add at most 320 KiB to the file every write rewrites. Past it a webhook event and a run now are
31
- * refused (429, retryable) before anything is written, and a schedule's time is skipped. */
37
+ /** The most firings a trigger holds due. Past it a webhook event and a run now are refused (429, retryable) before
38
+ * anything is written, and a schedule's time is skipped. */
32
39
  export const DUE_KEPT = 20;
33
40
  /** How long a refused event is told to wait (Retry-After). */
34
41
  const FULL_RETRY_S = 30;
35
- /** The most failures a trigger keeps past its history while their trigger.failed waits for the outbox. A schedule turns
36
- * itself off after FAILURES_TO_PAUSE in a row, but runs that start between failures, and run now, can add more. */
37
- const UNTOLD_KEPT = 50;
38
- /** The shortest every_s, and so the most often a schedule fires: a cron line has no seconds field. */
39
- export const MIN_EVERY_S = 60;
40
- /** The longest every_s: a year and a day. */
41
- export const MAX_EVERY_S = 366 * 86_400;
42
- export const SOURCE_KINDS = ["schedule", "webhook"];
42
+ /** The kinds of source this server has: its adapters' ids. */
43
+ export const SOURCE_KINDS = TRIGGER_ADAPTERS.map((a) => a.id);
43
44
  export const TARGET_KINDS = ["start_run", "message_run"];
44
- export const OVERLAP = ["skip"];
45
45
  export const FIRING_STATUSES = ["due", "started", "sent", "skipped", "failed", "missed"];
46
46
  /** The most of a webhook's payload a firing passes on: the rest is cut, at a character's start. */
47
47
  export const PAYLOAD_KEPT_BYTES = 16 * 1024;
48
48
  /** How late a missed time may be and still fire once, by default: an hour. */
49
49
  export const CATCHUP_WINDOW_S = 3600;
50
- /** The failed firings in a row that turn a trigger off. */
50
+ /** The failed tries in a row that turn a trigger off. */
51
51
  export const FAILURES_TO_PAUSE = 5;
52
+ /** The one backoff table: the wait before a due firing's next try, by its failed tries so far. Past it, the firing fails. */
53
+ export const BACKOFF_MS = [5_000, 15_000, 60_000, 300_000];
54
+ /** The answers a try is retried on: the server or its store busy for now. Any other failure ends the firing failed. */
55
+ const RETRYABLE = new Set(["rate_limited", "home_busy", "unavailable"]);
56
+ /** How often the store is read for the waiting firings whose trigger has room again: one read for all of them. */
57
+ export const WAIT_POLL_MS = 500;
52
58
  /** A nominal time the timer reaches later than this was missed: the server was down, or its timer late. */
53
59
  const LATE_MS = 60_000;
54
60
  /** The most missed times one row counts one by one; past it the schedule jumps to now. */
55
61
  const MISSED_COUNTED = 10_000;
56
- /** The waits before a firing a full server refused (429), or whose last run could not be read, is tried again. */
57
- const RETRY_MS = [5_000, 15_000, 60_000, 300_000];
58
- /** How soon a message refused because its run is working is tried again: not a failure, so no backoff. */
59
- const WORKING_RETRY_MS = 5_000;
60
- /** How soon a write that failed under the timer is tried again. */
61
- const WRITE_RETRY_MS = 5_000;
62
62
  /** Node fires a longer timeout at once: a far next time is reached in steps of at most this. */
63
63
  const MAX_TIMEOUT_MS = 2 ** 31 - 1;
64
64
  const MAX_NAME = 200;
65
- /** The most firings each trigger keeps past its history for their key's day: a bound on the file (commit()). */
66
- const KEPT_FIRINGS = 1_000;
65
+ const DAY_MS = IDEMPOTENCY_TTL_S * 1000;
66
+ /** The most keys each trigger keeps for their day past its history (an ignored request's, a pushed or run now firing's
67
+ * that left the history): a sender's event sent again within its day starts nothing, however many came between. Past
68
+ * it the oldest go first, and the log says so. */
69
+ export const SEEN_KEPT = 5_000;
70
+ /** The highest max_active_runs a trigger may set (the store's CHECK holds the same). */
71
+ export const MAX_ACTIVE_RUNS = 100;
67
72
  const ENDED = new Set(["completed", "failed", "cancelled"]);
68
- const dueOf = (trigger) => trigger.firings.filter((f) => f.status === "due").length;
69
- const LOST_AT_SETUP = "The server stopped while setting up the run.";
70
- const settled = (t) => ({ overlap: "skip", catchup_window_s: t.catchup_window_s ?? CATCHUP_WINDOW_S, failures_in_a_row: t.failures_in_a_row ?? 0, disabled: t.disabled ?? null });
73
+ /** Why a message_run trigger turned itself off: the run it messages is gone. */
74
+ const RUN_DELETED = "its run was deleted";
71
75
  const REAL_CLOCK = {
72
76
  now: () => Date.now(),
73
77
  arm(fire, ms) {
@@ -77,129 +81,27 @@ const REAL_CLOCK = {
77
81
  },
78
82
  };
79
83
  const iso = (ms) => new Date(ms).toISOString();
80
- /** RFC 3339 in UTC, to the second: the form a schedule's key is made of. */
81
- const second = (ms) => iso(ms).replace(/\.\d{3}Z$/, "Z");
82
- const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-](\d{2}):(\d{2}))$/i;
83
- /** An RFC 3339 date-time with its offset, as an instant; undefined for one that names no real time (month 13, Feb 30,
84
- * 25 o'clock, an offset past 23:59), which Date.parse would refuse or roll over. */
85
- function instantOf(text) {
86
- const parts = typeof text === "string" ? RFC3339.exec(text) : null;
87
- if (!parts)
88
- return undefined;
89
- const [y, mo, d, h, mi, s, , , oh = "0", om = "0"] = parts.slice(1).map((p) => p ?? "0").map(String);
90
- const days = new Date(Date.UTC(Number(y), Number(mo), 0)).getUTCDate();
91
- if (Number(mo) < 1 || Number(mo) > 12 || Number(d) < 1 || Number(d) > days || Number(h) > 23 || Number(mi) > 59 || Number(s) > 59 || Number(oh) > 23 || Number(om) > 59)
92
- return undefined;
93
- const at = Date.parse(text);
94
- return Number.isFinite(at) ? at : undefined;
95
- }
96
- export const firingKey = (kind, triggerId, what) => `fir_${createHash("sha256").update(`${kind}\n${triggerId}\n${what}`).digest("hex").slice(0, 32)}`;
97
- const cronOf = (source) => new Cron(source.cron, { timezone: source.timezone, mode: "5-part" });
98
- /** The source's first nominal time strictly after `after`, or null when it has none (or none a Date holds). */
99
- function nextAfter(source, after, cron) {
100
- if (source.kind === "webhook")
101
- return null;
102
- const at = nextOf(source, after, cron);
84
+ export const firingKey = (by, triggerId, what) => `fir_${createHash("sha256").update(`${by}\n${triggerId}\n${what}`).digest("hex").slice(0, 32)}`;
85
+ /** The adapter of `kind`, among `adapters`. */
86
+ const adapterIn = (adapters, kind) => adapters.find((a) => a.id === kind);
87
+ /** A clock source's first time strictly after `after`, or null when it has none (or none a Date holds); a pushed
88
+ * source has none. */
89
+ function nextAfter(adapter, source, after) {
90
+ const at = adapter?.clock?.(source).next(after) ?? null;
103
91
  return at !== null && Number.isFinite(at) && Math.abs(at) <= DATE_MAX_MS ? at : null;
104
92
  }
105
- /** `cron`: the source's Cron, made once by a caller that asks for many times. */
106
- function nextOf(source, after, cron) {
107
- if ("cron" in source)
108
- return (cron ?? cronOf(source)).nextRun(new Date(after))?.getTime() ?? null;
109
- if ("at" in source)
110
- return Date.parse(source.at) > after ? Date.parse(source.at) : null;
111
- const start = Date.parse(source.start_at);
112
- const step = source.every_s * 1000;
113
- return start > after ? start : start + (Math.floor((after - start) / step) + 1) * step;
114
- }
115
- /** The source's latest nominal time at or before `now`, given one that is (`first`), found without walking to it: an
116
- * interval's on its grid, a cron line's by croner's search back from a second past now (previousRuns is exclusive and
117
- * to the second), which yields the times nextRun does, across clock changes too. */
118
- function latestBy(source, first, now, cron) {
119
- if ("at" in source)
120
- return first;
121
- if ("every_s" in source)
122
- return first + Math.floor((now - first) / (source.every_s * 1000)) * source.every_s * 1000;
123
- const at = (cron ?? cronOf(source)).previousRuns(1, new Date(Math.floor(now / 1000) * 1000 + 1000))[0]?.getTime();
124
- return at !== undefined && at >= first && at <= now ? at : first;
125
- }
126
93
  /** A time in `zone` as a person reads it: "Nov 1, 2026, 1:30 AM PDT". */
127
94
  const local = (ms, zone) => new Intl.DateTimeFormat("en-US", { timeZone: validZone(zone) ? zone : "UTC", year: "numeric", month: "short", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short" }).format(ms);
128
- const zoneOf = (source) => ("timezone" in source ? source.timezone : "UTC");
129
- const validZone = (zone) => {
130
- try {
131
- new Intl.DateTimeFormat("en-US", { timeZone: zone });
132
- return true;
133
- }
134
- catch {
135
- return false;
136
- }
137
- };
138
- /** Why a schedule kept in the file no longer reads (its zone or its cron line, which this croner or this ICU refuses):
139
- * a trigger with one is turned off with the reason, alone, and never stalls the others. */
140
- function sourceProblem(source) {
141
- if (!("cron" in source))
142
- return undefined;
143
- if (!validZone(source.timezone))
144
- return `the zone ${source.timezone} is not one this server knows`;
145
- try {
146
- cronOf(source).nextRun(new Date(0));
147
- return undefined;
148
- }
149
- catch (error) {
150
- return `the cron line does not read: ${error.message}`;
151
- }
152
- }
153
- function sourceOf(value, now, issues) {
95
+ /** "A, B or C". */
96
+ const either = (items) => (items.length < 2 ? items.join("") : `${items.slice(0, -1).join(", ")} or ${items.at(-1)}`);
97
+ function sourceOf(adapters, value, now, issues) {
154
98
  const bad = (field, reason, message) => void issues.push({ field: `source${field ? `.${field}` : ""}`, reason, message });
155
99
  if (!isObject(value))
156
- return bad("", value === undefined ? "missing" : "wrong_type", "source is an object: {kind: \"schedule\", cron, timezone}, {kind: \"schedule\", at}, {kind: \"schedule\", every_s, start_at?} or {kind: \"webhook\"}"), undefined;
157
- if (value.kind === "webhook") {
158
- issues.push(...unknownFields(value, ["kind"]).map((i) => ({ ...i, field: `source.${i.field}` })));
159
- return { kind: "webhook" };
160
- }
161
- if (value.kind !== "schedule")
162
- return bad("kind", "not_an_option", `source.kind is one of ${SOURCE_KINDS.join(", ")}`), undefined;
163
- const forms = ["cron", "at", "every_s"].filter((field) => value[field] !== undefined);
164
- if (forms.length !== 1)
165
- return bad("", "invalid", "a schedule names exactly one of cron, at and every_s"), undefined;
166
- if (value.cron !== undefined) {
167
- issues.push(...unknownFields(value, ["kind", "cron", "timezone"]).map((i) => ({ ...i, field: `source.${i.field}` })));
168
- const timezone = value.timezone ?? "UTC";
169
- if (typeof timezone !== "string" || !validZone(timezone))
170
- return bad("timezone", "invalid", "timezone is an IANA zone, such as America/Los_Angeles (default UTC)"), undefined;
171
- if (typeof value.cron !== "string" || value.cron.trim().split(/\s+/).length !== 5)
172
- return bad("cron", "invalid", "cron is five fields, minute hour day-of-month month day-of-week: a schedule fires at most once a minute"), undefined;
173
- const source = { kind: "schedule", cron: value.cron.trim(), timezone };
174
- try {
175
- if (nextAfter(source, now) === null)
176
- return bad("cron", "invalid", "cron never fires"), undefined;
177
- }
178
- catch (error) {
179
- return bad("cron", "invalid", `cron does not read: ${error.message}`), undefined;
180
- }
181
- return source;
182
- }
183
- if (value.at !== undefined) {
184
- issues.push(...unknownFields(value, ["kind", "at"]).map((i) => ({ ...i, field: `source.${i.field}` })));
185
- const given = instantOf(value.at);
186
- if (given === undefined)
187
- return bad("at", "invalid", "at is an RFC 3339 date-time with its offset"), undefined;
188
- const at = Math.floor(given / 1000) * 1000;
189
- if (at <= now)
190
- return bad("at", "invalid", "at is in the past"), undefined;
191
- return { kind: "schedule", at: second(at) };
192
- }
193
- issues.push(...unknownFields(value, ["kind", "every_s", "start_at"]).map((i) => ({ ...i, field: `source.${i.field}` })));
194
- if (!Number.isSafeInteger(value.every_s) || value.every_s < MIN_EVERY_S || value.every_s > MAX_EVERY_S)
195
- return bad("every_s", "invalid", `every_s is a whole number of seconds, ${MIN_EVERY_S} to ${MAX_EVERY_S}`), undefined;
196
- const given = value.start_at === undefined ? now : instantOf(value.start_at);
197
- if (given === undefined)
198
- return bad("start_at", "invalid", "start_at is an RFC 3339 date-time with its offset"), undefined;
199
- // The grid's origin, to the second (down, so one made now first fires an interval from now): the first firing is at it
200
- // when it is ahead, else one step after it.
201
- const start = Math.floor(given / 1000) * 1000;
202
- return { kind: "schedule", every_s: value.every_s, start_at: second(start) };
100
+ return bad("", value === undefined ? "missing" : "wrong_type", `source is an object: ${either(adapters.map((a) => a.describe))}`), undefined;
101
+ const adapter = typeof value.kind === "string" ? adapterIn(adapters, value.kind) : undefined;
102
+ if (!adapter)
103
+ return bad("kind", "not_an_option", `source.kind is one of ${adapters.map((a) => a.id).join(", ")}`), undefined;
104
+ return adapter.parse(value, now, bad, issues);
203
105
  }
204
106
  function targetOf(value, issues) {
205
107
  const bad = (field, reason, message) => void issues.push({ field: `target${field ? `.${field}` : ""}`, reason, message });
@@ -229,264 +131,378 @@ function targetOf(value, issues) {
229
131
  return undefined;
230
132
  return { kind: "start_run", agent_id: value.agent_id, input: value.input, ...(typeof value.max_cost_usd === "number" ? { max_cost_usd: value.max_cost_usd } : {}), ...(typeof value.effort === "string" ? { effort: value.effort } : {}) };
231
133
  }
232
- /** `catchup_window_s`, as given (absent: undefined). */
134
+ /** `catchup_window_s` and `max_active_runs`, as given (absent: undefined; `max_active_runs: null`, cleared). */
233
135
  function settingsOf(body, issues) {
234
136
  if (body.catchup_window_s !== undefined && !(Number.isSafeInteger(body.catchup_window_s) && body.catchup_window_s >= 0 && body.catchup_window_s <= MAX_EVERY_S))
235
137
  issues.push({ field: "catchup_window_s", reason: "invalid", message: `catchup_window_s is a whole number of seconds, 0 to ${MAX_EVERY_S} (0: a missed time never fires)` });
236
- return typeof body.catchup_window_s === "number" ? { catchup_window_s: body.catchup_window_s } : {};
138
+ const max = body.max_active_runs;
139
+ if (max !== undefined && max !== null && !(Number.isSafeInteger(max) && max >= 1 && max <= MAX_ACTIVE_RUNS))
140
+ issues.push({ field: "max_active_runs", reason: "invalid", message: `max_active_runs is a whole number, 1 to ${MAX_ACTIVE_RUNS}, or null for none` });
141
+ return { ...(typeof body.catchup_window_s === "number" ? { catchup_window_s: body.catchup_window_s } : {}), ...(typeof max === "number" || max === null ? { max_active_runs: max } : {}) };
237
142
  }
238
- const WRITABLE = ["name", "enabled", "source", "target", "catchup_window_s"];
239
- /** A trigger as triggers.json keeps it, whole: what the engine reads of it is there, of its type. */
240
- function wellFormed(t) {
241
- if (!isObject(t) || typeof t.id !== "string" || typeof t.name !== "string" || typeof t.enabled !== "boolean" || typeof t.created_at !== "string" || typeof t.updated_at !== "string")
242
- return false;
243
- if (!(t.next_at === null || instantOf(t.next_at) !== undefined) || !(t.last_run_id === undefined || typeof t.last_run_id === "string"))
244
- return false;
245
- if (!(t.catchup_window_s === undefined || Number.isSafeInteger(t.catchup_window_s)) || !(t.failures_in_a_row === undefined || Number.isSafeInteger(t.failures_in_a_row)) || !(t.disabled === undefined || t.disabled === null || isObject(t.disabled)))
246
- return false;
247
- const { source, target } = t;
248
- if (!isObject(source) || !(source.kind === "webhook" || source.kind === "schedule"))
249
- return false;
250
- const timed = source.kind === "webhook" || (typeof source.cron === "string" ? typeof source.timezone === "string" : source.at !== undefined ? instantOf(source.at) !== undefined : Number.isSafeInteger(source.every_s) && instantOf(source.start_at) !== undefined);
251
- const aimed = isObject(target) && isObject(target.input) && (target.kind === "message_run" ? typeof target.run_id === "string" : target.kind === "start_run" && typeof target.agent_id === "string" && (target.max_cost_usd === undefined || typeof target.max_cost_usd === "number"));
252
- if (!timed || !aimed)
253
- return false;
254
- const firing = (f) => isObject(f) && typeof f.key === "string" && FIRING_STATUSES.includes(f.status) && (f.by === "schedule" || f.by === "manual" || f.by === "webhook") && instantOf(f.nominal_at) !== undefined && typeof f.at === "string";
255
- const list = (value) => value === undefined || (Array.isArray(value) && value.every(firing));
256
- return Array.isArray(t.firings) && t.firings.every(firing) && list(t.kept_firings) && list(t.run_now_kept);
143
+ const WRITABLE = ["name", "enabled", "source", "target", "catchup_window_s", "max_active_runs"];
144
+ /** Why a trigger of `source` and `target` takes no max_active_runs, if it does not: any start_run trigger of a pushed
145
+ * source does, with or without accept (set, each event starts its own run up to the cap); a schedule keeps the overlap
146
+ * skip, and a message_run target starts no run to bound. */
147
+ function capIssues(adapters, source, target) {
148
+ if (adapterIn(adapters, source.kind)?.delivery !== "push")
149
+ return [{ field: "max_active_runs", reason: "not_allowed", message: "Only a trigger of a pushed source (a webhook) takes max_active_runs: a schedule keeps the overlap skip. Set it to null to clear it." }];
150
+ if (target?.kind === "message_run")
151
+ return [{ field: "max_active_runs", reason: "not_allowed", message: "max_active_runs bounds the runs a trigger starts, and a message_run target starts none. Set it to null to clear it." }];
152
+ return [];
257
153
  }
154
+ /** A POST /triggers body's own fields, read as create reads them with the sources of `adapters`: its source, target,
155
+ * settings, name and enabled, with every issue. What it names (the agent, the run) is create's own check
156
+ * (TriggerDeps.targetIssues). */
157
+ function readBody(adapters, body, now) {
158
+ const issues = unknownFields(body, WRITABLE);
159
+ const source = sourceOf(adapters, body.source, now, issues);
160
+ const target = targetOf(body.target, issues);
161
+ const settings = settingsOf(body, issues);
162
+ if (source && typeof settings.max_active_runs === "number")
163
+ issues.push(...capIssues(adapters, source, target));
164
+ if (body.name !== undefined && !(typeof body.name === "string" && body.name.trim() && body.name.length <= MAX_NAME))
165
+ issues.push({ field: "name", reason: "invalid", message: `name is a string of 1 to ${MAX_NAME} characters` });
166
+ if (body.enabled !== undefined && typeof body.enabled !== "boolean")
167
+ issues.push({ field: "enabled", reason: "wrong_type", message: "enabled is true or false" });
168
+ return { issues, source, target, settings };
169
+ }
170
+ /** What is wrong with a POST /triggers body by itself, as create refuses it with the sources of `adapters`, all but the
171
+ * agent or run its target names: a template package's triggers are checked with it before any apply (templates.ts). */
172
+ export const triggerBodyIssues = (adapters, body, now) => readBody(adapters, body, now).issues;
173
+ /** A trigger is named once per agent (the store's UNIQUE (agent_id, name)): a second of the same name, at a create or a
174
+ * rename, is `409 name_taken`; any other error as it is. */
175
+ const nameTaken = (error, name) => error instanceof StoreConstraint && error.unique?.table === "triggers" && error.unique.columns.join(",") === "agent_id,name"
176
+ ? new ApiError("name_taken", `This agent already has a trigger named ${name}.`)
177
+ : error;
178
+ /** Why a trigger of an archived agent is off, and the 409 for turning one on: the agent by name. */
179
+ const archivedDetail = (name) => `The agent ${name} is archived: unarchive it, then turn the trigger on.`;
180
+ /** Why a trigger is off when the server turned it off, as its row keeps it (`disabled`, JSON). */
181
+ const reasonOf = (disabled) => (isObject(disabled) ? disabled.reason : undefined);
182
+ /** Why a try failed, as its firing keeps it: an ApiError's code, else internal. */
183
+ const errorOf = (error) => ({ code: error instanceof ApiError ? error.code : "internal", message: String(error?.message ?? error) });
258
184
  export class Triggers {
259
185
  deps;
260
- file;
186
+ store;
261
187
  clock;
262
- triggers = [];
263
- /** Why triggers.json does not read: nothing fires and nothing is written over it until it does. */
264
- unreadable;
188
+ adapters;
265
189
  timer;
190
+ /** Each arm's turn: a later arm wins over one still reading the store. */
191
+ arming = 0;
266
192
  /** The firings in their turn, queued or being driven, by key, with that turn: a firing is asked for once at a time,
267
193
  * and the timer arms for none of them until its turn ends. */
268
194
  driving = new Map();
269
- /** Due firings whose last write failed, by key, and when to drive them again: on disk they may hold no retry time. */
270
- rewrite = new Map();
271
195
  /** Each trigger's firings, driven one after another in the order asked: a firing's overlap check reads what the one
272
- * before it settled to (a firing a crash left due settles to its run before the next start's own is checked). */
196
+ * before it settled to. */
273
197
  turns = new Map();
198
+ /** Whether a firing waits for its trigger's room (max_active_runs): the timer then reads the store every WAIT_POLL_MS. */
199
+ waiting = false;
200
+ /** The triggers whose day-kept keys are at their cap, said once until they are under it again. */
201
+ seenFull = new Set();
274
202
  closed = false;
275
- constructor(data, deps) {
203
+ constructor(deps) {
276
204
  this.deps = deps;
277
- this.file = join(data, TRIGGERS_FILE);
205
+ this.store = deps.store;
278
206
  this.clock = deps.clock ?? REAL_CLOCK;
279
- let text;
280
- try {
281
- text = readFileSync(this.file, "utf8");
282
- }
283
- catch (error) {
284
- if (error.code !== "ENOENT")
285
- this.unreadable = error.message;
286
- }
287
- if (text === undefined)
288
- return;
289
- try {
290
- const doc = JSON.parse(text);
291
- if (!isObject(doc) || doc.v !== 1 || !Array.isArray(doc.triggers))
292
- throw new Error("not a triggers file of version 1");
293
- const bad = doc.triggers.findIndex((t) => !wellFormed(t));
294
- if (bad >= 0)
295
- throw new Error(`its trigger at ${bad} is not one this server reads`);
296
- this.triggers = doc.triggers;
297
- for (const t of this.triggers) {
298
- if (t.run_now_kept)
299
- t.kept_firings = [...(t.kept_firings ?? []), ...t.run_now_kept];
300
- delete t.run_now_kept;
301
- }
302
- // A trigger an earlier server wrote before trigger.failed existed has no failures_in_a_row: its failures were never
303
- // to be told, so a first start that tells them does not send them late. The next write keeps the mark.
304
- for (const t of this.triggers)
305
- if (t.failures_in_a_row === undefined)
306
- for (const f of t.firings)
307
- if (f.status === "failed")
308
- f.notified = true;
309
- }
310
- catch (error) {
311
- this.unreadable = error.message;
312
- }
313
- if (this.unreadable)
314
- deps.say({ condition: "triggers_unreadable", file: this.file, error: this.unreadable });
315
- }
316
- /** At the server's start: every firing an earlier server left due driven again (its origin key makes a run
317
- * it already started the same run), the times missed while it was down recorded, the timer armed, and each failure's
318
- * trigger.failed queued that is not yet. */
319
- start() {
320
- this.offUnreadable(this.triggers.filter((t) => t.enabled && sourceProblem(t.source)), this.clock.now());
321
- // A trigger.failed an earlier server wrote the firing of but never queued: queued before the first tick records
322
- // anything, so no trim reaches it first.
323
- for (const t of this.unreadable ? [] : this.triggers)
324
- for (const f of t.firings)
325
- if (unmarked(f))
326
- this.notifyFailed(t.id, f.key);
327
- this.tick();
328
- this.arm();
207
+ this.adapters = deps.adapters ?? TRIGGER_ADAPTERS;
208
+ // A pushed source's own hook path is its id, beside the trigger ids a hook path also names: none looks like one.
209
+ const shaped = this.adapters.find((a) => a.id.startsWith("trg_"));
210
+ if (shaped)
211
+ throw new Error(`a trigger source's id never starts as a trigger's does: ${shaped.id}`);
212
+ // A source's id is its kind, its firings' by and, for one pushed on the server's settings, its hook: one source each.
213
+ const twice = this.adapters.find((a, i) => this.adapters.findIndex((b) => b.id === a.id) !== i);
214
+ if (twice)
215
+ throw new Error(`two trigger sources claim the id ${twice.id}${twice.push ? `, and its hook /v2/hooks/${twice.id}` : ""}: one source each`);
216
+ }
217
+ /** At the server's start: every enabled trigger whose source no longer reads turned off, each failure's trigger.failed
218
+ * queued that is not yet, every firing an earlier server left due driven again (its origin key makes a run it already
219
+ * started the same run), the times missed while it was down recorded, and the timer armed. */
220
+ async start() {
221
+ const now = this.clock.now();
222
+ await this.offUnreadable((await this.all()).filter((t) => t.enabled && this.problem(t.source)), now);
223
+ await this.tick();
329
224
  }
330
225
  close() {
331
226
  this.closed = true;
332
227
  this.timer?.clear();
333
228
  this.timer = undefined;
334
229
  }
335
- list() {
336
- return { triggers: this.readable().map((t) => this.view(t)) };
230
+ async list() {
231
+ return { triggers: await Promise.all((await this.all()).map((t) => this.view(t))) };
337
232
  }
338
- get(id) {
339
- return this.view(this.need(id));
233
+ async get(id) {
234
+ return this.view(await this.need(id));
340
235
  }
341
- firings(id) {
342
- return { firings: [...this.need(id).firings].reverse().map(firingView) };
236
+ async firings(id) {
237
+ await this.need(id);
238
+ return { firings: (await this.store.triggers.firings(id)).map(firingView) };
343
239
  }
344
240
  async create(body) {
345
- this.readable();
346
241
  const now = this.clock.now();
347
- const issues = unknownFields(body, WRITABLE);
348
- const source = sourceOf(body.source, now, issues);
349
- const target = targetOf(body.target, issues);
350
- const settings = settingsOf(body, issues);
351
- if (body.name !== undefined && !(typeof body.name === "string" && body.name.trim() && body.name.length <= MAX_NAME))
352
- issues.push({ field: "name", reason: "invalid", message: `name is a string of 1 to ${MAX_NAME} characters` });
353
- if (body.enabled !== undefined && typeof body.enabled !== "boolean")
354
- issues.push({ field: "enabled", reason: "wrong_type", message: "enabled is true or false" });
242
+ const { issues, source, target, settings } = readBody(this.adapters, body, now);
355
243
  // Checked as its runs are given it: the input, then the line saying what fired it (a name the trigger may yet take).
356
244
  if (target)
357
- issues.push(...(await this.deps.targetIssues(given(typeof body.name === "string" ? body.name.trim() : `trg_${"0".repeat(24)}`, source, target, now))));
245
+ issues.push(...(await this.deps.targetIssues(this.given(typeof body.name === "string" ? body.name.trim() : `trg_${"0".repeat(24)}`, source, target, now))));
358
246
  if (issues.length || !source || !target)
359
247
  throw invalid(issues);
248
+ const agentId = await this.agentOf(target);
360
249
  const id = `trg_${randomBytes(12).toString("hex")}`;
361
250
  const enabled = body.enabled !== false;
362
- const trigger = { id, name: typeof body.name === "string" ? body.name.trim() : id, enabled, source, target, catchup_window_s: settings.catchup_window_s ?? CATCHUP_WINDOW_S, failures_in_a_row: 0, disabled: null, created_at: iso(now), updated_at: iso(now), next_at: enabled ? nextIso(source, now) : null, firings: [] };
363
- // A webhook trigger's secret is kept before the trigger is: one that cannot be kept (no seal key) makes none.
364
- const secret = source.kind === "webhook" ? this.deps.secrets.mint(id) : undefined;
365
- this.commit(() => void this.triggers.push(trigger));
366
- this.arm();
367
- return { ...this.view(trigger), ...(secret ? { secret } : {}) };
368
- }
369
- /** A webhook trigger's new secret, shown this once; the old one signs nothing from now on. */
370
- rotate(id) {
371
- const trigger = this.need(id);
372
- if (trigger.source.kind !== "webhook")
251
+ if (enabled)
252
+ this.needAvailable(source.kind);
253
+ // Never made on for an archived agent: told before anything is minted (the store's own refusal is the backstop).
254
+ if (enabled)
255
+ await this.needAgentOn(agentId);
256
+ // A scope belongs to one trigger: told before anything is minted or written (the store's scope rows are the backstop).
257
+ if (enabled)
258
+ await this.scopeFree(source, id);
259
+ // Its secrets are kept before the trigger is: one that cannot be kept (no seal key) makes none.
260
+ const minted = await this.mint(source, id);
261
+ const name = typeof body.name === "string" ? body.name.trim() : id;
262
+ let row;
263
+ try {
264
+ row = await this.store.triggers.create({ id, agentId, name, enabled, source, target, nextAt: enabled ? nextAfter(this.adapter(source), source, now) : null, catchupWindowS: settings.catchup_window_s ?? CATCHUP_WINDOW_S, ...(typeof settings.max_active_runs === "number" ? { maxActiveRuns: settings.max_active_runs } : {}) }, this.scopesOf(source));
265
+ }
266
+ catch (error) {
267
+ throw (await this.scopeTaken(error, source, id)) ?? (await this.archivedRefusal(error)) ?? nameTaken(error, name);
268
+ }
269
+ // Armed before the answer: a create that answered is in effect, its first time on the timer (arm reads the store).
270
+ await this.arm();
271
+ // What it minted, shown this once, by field: a webhook's `secret`.
272
+ return { ...(await this.view(asTrigger(row))), ...minted };
273
+ }
274
+ /** A trigger's new signing secret, shown this once; the old one signs nothing from now on. */
275
+ async rotate(id) {
276
+ const trigger = await this.need(id);
277
+ if (!mints(this.adapter(trigger.source)))
373
278
  throw invalid([{ field: "source.kind", reason: "not_allowed", message: "Only a webhook trigger has a secret." }]);
374
- return { secret: this.deps.secrets.mint(id) };
375
- }
376
- /** Whether `id` is a webhook trigger that is on: the one a signed request to /v2/hooks/{id} may fire. */
377
- hookable(id) {
378
- const trigger = this.unreadable ? undefined : this.triggers.find((t) => t.id === id);
379
- return trigger?.source.kind === "webhook" && trigger.enabled;
380
- }
381
- /** A signed request to /v2/hooks/{id} (server.ts checked it): its firing, keyed by its `webhook-id`, recorded due in
382
- * one write and driven after the answer. `created` false: that webhook-id's firing, as it stands. */
383
- receive(id, webhookId, payload) {
384
- const trigger = this.need(id);
385
- const key = firingKey("webhook", id, webhookId);
386
- const known = this.known(trigger, key);
387
- if (known)
388
- return { created: false, firing: firingView(known) };
389
- this.roomFor(trigger);
279
+ return this.mint(trigger.source, id);
280
+ }
281
+ /** Whether `id` is a trigger of the pushed source `kind` that is on: the one a request delivered for `kind` may fire. */
282
+ async hookable(id, kind) {
283
+ return (await this.hookSource(id, kind)) !== undefined;
284
+ }
285
+ /** The source of trigger `id` when it is hookable: what its pushed source's check and parse read (its filter). With no
286
+ * `kind`, the source of any pushed trigger `id` that is on, so the hook's resolution can read its kind to find its
287
+ * adapter (push-handler.ts): a path that names no such trigger is checked against the decoy, and learns no id. */
288
+ async hookSource(id, kind) {
289
+ const row = await this.store.triggers.get(id);
290
+ const trigger = row && asTrigger(row);
291
+ return trigger !== undefined && (kind === undefined || trigger.source.kind === kind) && this.adapter(trigger.source)?.delivery === "push" && trigger.enabled ? trigger.source : undefined;
292
+ }
293
+ /** The triggers of the pushed source `kind` that are on and listen on `scope` (its adapter's scopeOf): the ones an
294
+ * event there fires. */
295
+ async scoped(kind, scope) {
296
+ const adapter = adapterIn(this.adapters, kind);
297
+ if (!adapter?.scopeOf)
298
+ return [];
299
+ return this.store.triggers.scoped(kind, scope);
300
+ }
301
+ /** The triggers of the pushed source `kind` that are on, with their sources: the ones a server-wide source whose
302
+ * triggers choose their own events (its adapter's takes) reads, for each event. */
303
+ async listening(kind) {
304
+ return (await this.store.triggers.all()).map(asTrigger).filter((t) => t.enabled && t.source.kind === kind).map((t) => ({ id: t.id, source: t.source }));
305
+ }
306
+ /** Every trigger of source `kind` that is on, turned off because the connection it needs is gone (`disabled: {reason:
307
+ * "connection_lost", detail}`), and said; how many. They are kept: on again once it is back. */
308
+ async turnOff(kind, detail) {
309
+ const on = (await this.store.triggers.all()).map(asTrigger).filter((t) => t.enabled && t.source.kind === kind);
310
+ const at = iso(this.clock.now());
311
+ for (const t of on) {
312
+ await this.store.triggers.update(t.id, { enabled: false, nextAt: null, disabled: { at, reason: "connection_lost", detail } });
313
+ this.deps.say({ condition: "trigger_connection_lost", trigger: t.id, detail });
314
+ }
315
+ if (on.length)
316
+ await this.arm();
317
+ return on.length;
318
+ }
319
+ /** Agent `agentId` archived, and every trigger that runs as it (its rows: a start_run of it, a message_run to one of its
320
+ * runs) turned off with it in the store's one transaction (`disabled: {reason: "agent_archived", detail}`), and said;
321
+ * which, by name. From that commit no firing starts a run of it (store.triggers.fire refuses one, and drive skips). */
322
+ async agentArchived(agentId) {
323
+ const name = (await this.store.agents.get(agentId))?.name ?? agentId;
324
+ const off = await this.store.agents.archive(agentId, true, { at: iso(this.clock.now()), reason: "agent_archived", detail: archivedDetail(name) });
325
+ for (const t of off)
326
+ this.deps.say({ condition: "trigger_agent_archived", trigger: t.id, agent: agentId });
327
+ if (off.length)
328
+ await this.arm();
329
+ return off;
330
+ }
331
+ /** Agent `agentId` unarchived: none of its triggers turns on again. The triggers its archive turned off that are off
332
+ * still, by name: each is turned on by a PATCH. */
333
+ async agentUnarchived(agentId) {
334
+ await this.store.agents.archive(agentId, false);
335
+ return (await this.store.triggers.list(agentId)).filter((t) => !t.enabled && reasonOf(t.disabled) === "agent_archived").map((t) => ({ id: t.id, name: t.name }));
336
+ }
337
+ /** Refused (409 agent_archived) when agent `agentId` is archived: a trigger made on, turned on or aimed at it. */
338
+ async needAgentOn(agentId) {
339
+ const agent = await this.store.agents.get(agentId);
340
+ if (agent?.archivedAt != null)
341
+ throw new ApiError("agent_archived", archivedDetail(agent.name));
342
+ }
343
+ /** The store's refusal of a trigger left on for an archived agent (an archive that committed past needAgentOn) as the
344
+ * same 409; undefined for any other error. */
345
+ async archivedRefusal(error) {
346
+ if (!(error instanceof AgentArchived))
347
+ return undefined;
348
+ return new ApiError("agent_archived", archivedDetail((await this.store.agents.get(error.agentId))?.name ?? error.agentId));
349
+ }
350
+ /** Why a firing of a trigger of agent `agentId` is skipped, if it is: the agent is archived. */
351
+ async archivedSkip(agentId) {
352
+ const agent = await this.store.agents.get(agentId);
353
+ return agent?.archivedAt != null ? `The agent ${agent.name} is archived.` : undefined;
354
+ }
355
+ /** Refused as its connection says when a trigger of `kind` cannot be on here (unavailable). */
356
+ needAvailable(kind) {
357
+ const refusal = this.deps.unavailable?.(kind);
358
+ if (refusal)
359
+ throw refusal;
360
+ }
361
+ /** A verified request for trigger `id` that its filter ignored, under the key its event would have: an `ignored` row
362
+ * kept for its day and never in the history, so the same request sent again under another label answers duplicate. A
363
+ * write that fails is said, and the request is still answered. */
364
+ async ignored(id, eventId) {
365
+ try {
366
+ const trigger = await this.need(id);
367
+ const by = trigger.source.kind;
368
+ await this.record(trigger, { key: firingKey(by, id, eventId), by, nominalAt: Math.floor(this.clock.now() / 1000) * 1000, status: "ignored", shown: false });
369
+ }
370
+ catch (error) {
371
+ this.deps.say({ condition: "triggers_unwritable", trigger: id, error: String(error?.message ?? error) });
372
+ }
373
+ }
374
+ /** A delivered request for trigger `id` (its pushed source's checks passed, server.ts): its firing, keyed by the
375
+ * sender's own id for it (a webhook's `webhook-id`), with what its source says of it (`attrs`), recorded due in one
376
+ * write and driven after the answer. `created` false: that id's firing, as it stands, or `{ok: "duplicate"}` for a
377
+ * request ignored within its day. */
378
+ async receive(id, eventId, payload, attrs) {
379
+ const trigger = await this.need(id);
380
+ const by = trigger.source.kind;
381
+ const key = firingKey(by, id, eventId);
390
382
  const now = this.clock.now();
391
- const firing = { key, by: "webhook", nominal_at: second(now), status: "due", at: iso(now), payload: cut(payload) };
392
- this.commit(() => this.record(trigger, firing));
393
- void this.inTurn(id, key);
394
- return { created: true, firing: firingView(firing) };
383
+ const recorded = await this.record(trigger, { key, by, nominalAt: Math.floor(now / 1000) * 1000, status: "due", payload: cut(payload), ...(attrs && Object.keys(attrs).length ? { attrs } : {}) }, { room: true });
384
+ if (recorded.created)
385
+ void this.inTurn(id, key);
386
+ if (!recorded.created && recorded.firing.status === "ignored")
387
+ return { created: false, firing: { ok: "duplicate" } };
388
+ return { created: recorded.created, firing: firingView(recorded.firing) };
395
389
  }
396
- /** PATCH: any of name, enabled, source, target and catchup_window_s. Enabled again, or its source changed, a trigger goes on from now: a
390
+ /** PATCH: any of name, enabled, source, target, catchup_window_s and max_active_runs. Enabled again, or its source changed, a trigger goes on from now: a
397
391
  * paused range is skipped, never caught up. Only the fields named change, applied to the trigger as it stands once
398
392
  * the target's check is done: an edit made meanwhile keeps its own. */
399
393
  async update(id, body) {
400
- const was = this.need(id);
394
+ const was = await this.need(id);
401
395
  const issues = unknownFields(body, WRITABLE);
402
- const source = body.source === undefined ? undefined : sourceOf(body.source, this.clock.now(), issues);
396
+ const source = body.source === undefined ? undefined : sourceOf(this.adapters, body.source, this.clock.now(), issues);
403
397
  const target = body.target === undefined ? undefined : targetOf(body.target, issues);
404
398
  const settings = settingsOf(body, issues);
399
+ // A cap kept, or set, needs a pushed source and a target that starts runs: a PATCH that aims a capped trigger at a run
400
+ // is refused unless it also sends max_active_runs: null. Taking accept away keeps it.
401
+ const cap = settings.max_active_runs === undefined ? was.maxActiveRuns : settings.max_active_runs;
402
+ if (typeof cap === "number" && (source || target || typeof settings.max_active_runs === "number"))
403
+ issues.push(...capIssues(this.adapters, source ?? was.source, target ?? was.target));
405
404
  if (body.name !== undefined && !(typeof body.name === "string" && body.name.trim() && body.name.length <= MAX_NAME))
406
405
  issues.push({ field: "name", reason: "invalid", message: `name is a string of 1 to ${MAX_NAME} characters` });
407
406
  if (body.enabled !== undefined && typeof body.enabled !== "boolean")
408
407
  issues.push({ field: "enabled", reason: "wrong_type", message: "enabled is true or false" });
409
408
  if (target)
410
- issues.push(...(await this.deps.targetIssues(given(typeof body.name === "string" ? body.name.trim() : was.name, source ?? was.source, target, this.clock.now()))));
409
+ issues.push(...(await this.deps.targetIssues(this.given(typeof body.name === "string" ? body.name.trim() : was.name, source ?? was.source, target, this.clock.now()))));
411
410
  if (issues.length || (body.source !== undefined && !source) || (body.target !== undefined && !target))
412
411
  throw invalid(issues);
413
- const trigger = this.need(id);
412
+ const trigger = await this.need(id);
414
413
  if (source && source.kind !== trigger.source.kind)
415
414
  throw invalid([{ field: "source.kind", reason: "not_allowed", message: "A trigger's source kind is fixed: make a new trigger for another." }]);
416
415
  const now = this.clock.now();
417
416
  const enabled = typeof body.enabled === "boolean" ? body.enabled : trigger.enabled;
418
- const problem = enabled && !source ? sourceProblem(trigger.source) : undefined;
417
+ const adapter = this.adapter(trigger.source);
418
+ const problem = enabled && !source ? this.problem(trigger.source) : undefined;
419
419
  if (problem)
420
- throw invalid([{ field: "source", reason: "invalid", message: `This schedule no longer reads (${problem}): give it a new source.` }]);
421
- const next = !enabled ? null : source || !trigger.enabled ? nextIso(source ?? trigger.source, now) : trigger.next_at;
422
- if (enabled && next === null && trigger.source.kind === "schedule")
423
- throw invalid([{ field: "enabled", reason: "invalid", message: "This schedule has no time left to fire at: give it a new source." }]);
420
+ throw invalid([{ field: "source", reason: "invalid", message: `This ${adapter.label} no longer reads (${problem}): give it a new source.` }]);
421
+ const next = !enabled ? null : source || !trigger.enabled ? nextAfter(this.adapter(source ?? trigger.source), source ?? trigger.source, now) : trigger.nextAt;
422
+ if (enabled && next === null && adapter.delivery === "clock")
423
+ throw invalid([{ field: "enabled", reason: "invalid", message: `This ${adapter.label} has no time left to fire at: give it a new source.` }]);
424
424
  // On again, a trigger starts a new streak: a failure streak that turned it off is behind it.
425
- const again = enabled && !trigger.enabled ? { failures_in_a_row: 0, disabled: null } : {};
426
- this.commit(() => Object.assign(trigger, { ...(typeof body.name === "string" ? { name: body.name.trim() } : {}), ...(source ? { source } : {}), ...(target ? { target } : {}), ...settings, ...again, enabled, updated_at: iso(now), next_at: next }));
427
- this.arm();
428
- return this.view(trigger);
429
- }
430
- remove(id) {
431
- const trigger = this.need(id);
432
- this.commit(() => void (this.triggers = this.triggers.filter((t) => t !== trigger)));
433
- if (trigger.source.kind === "webhook")
434
- this.deps.secrets.remove(id);
435
- this.arm();
425
+ const again = enabled && !trigger.enabled ? { failuresInARow: 0, disabled: null } : {};
426
+ const scopeSource = source ?? trigger.source;
427
+ if (enabled && (!trigger.enabled || source))
428
+ this.needAvailable(scopeSource.kind);
429
+ if (enabled)
430
+ await this.scopeFree(scopeSource, trigger.id);
431
+ // A trigger belongs to its target's agent: aimed at another agent (or another agent's run), it moves to that agent,
432
+ // whose one name per trigger and list of triggers it joins.
433
+ const agentId = target ? await this.agentOf(target) : trigger.agentId;
434
+ // Turned on, or aimed elsewhere while on: never for an archived agent (the store's own refusal is the backstop).
435
+ if (enabled && (!trigger.enabled || target))
436
+ await this.needAgentOn(agentId);
437
+ const patch = {
438
+ ...(agentId !== trigger.agentId ? { agentId } : {}),
439
+ ...(typeof body.name === "string" ? { name: body.name.trim() } : {}), ...(source ? { source } : {}), ...(target ? { target } : {}),
440
+ ...(settings.catchup_window_s !== undefined ? { catchupWindowS: settings.catchup_window_s } : {}),
441
+ ...(settings.max_active_runs !== undefined ? { maxActiveRuns: settings.max_active_runs } : {}), ...again, enabled, nextAt: next,
442
+ };
443
+ const row = await this.store.triggers.update(id, patch, enabled ? this.scopesOf(scopeSource) : []).catch(async (error) => {
444
+ throw (await this.scopeTaken(error, scopeSource, trigger.id)) ?? (await this.archivedRefusal(error)) ?? nameTaken(error, patch.name ?? trigger.name);
445
+ });
446
+ if (!row)
447
+ throw new ApiError("not_found", `no trigger ${id}`);
448
+ await this.arm();
449
+ return this.view(asTrigger(row));
450
+ }
451
+ async remove(id) {
452
+ const trigger = await this.need(id);
453
+ await this.store.triggers.remove(id);
454
+ if (this.adapter(trigger.source)?.settings?.scope === "trigger")
455
+ await this.deps.settings(trigger.source.kind)?.remove(id);
456
+ await this.arm();
436
457
  }
437
458
  /** Run now: one firing per Idempotency-Key, driven before the answer. `created` false: the key's firing, as it stands. */
438
459
  async fire(id, idempotencyKey) {
439
- const trigger = this.need(id);
460
+ const trigger = await this.need(id);
440
461
  const key = firingKey("manual", id, idempotencyKey);
441
- const known = this.known(trigger, key);
442
- if (known)
443
- return { created: false, firing: firingView(known) };
444
- this.roomFor(trigger);
445
462
  const now = this.clock.now();
446
- const firing = { key, by: "manual", nominal_at: second(now), status: "due", at: iso(now) };
447
- this.commit(() => this.record(trigger, firing));
463
+ const recorded = await this.record(trigger, { key, by: "manual", nominalAt: Math.floor(now / 1000) * 1000, status: "due" }, { room: true });
464
+ if (!recorded.created)
465
+ return { created: false, firing: firingView(recorded.firing) };
448
466
  await this.inTurn(id, key);
449
- return { created: true, firing: firingView(this.find(id, key)?.firing ?? firing) };
467
+ return { created: true, firing: firingView((await this.store.triggers.firing(id, key)) ?? recorded.firing) };
450
468
  }
451
469
  // ---- the timer and the firings --------------------------------------------------------------------------------------
452
- /** Every enabled trigger whose next time has come: its firing recorded and its next time moved on, in one write; then
453
- * each due firing whose time has come driven, and the timer armed again. */
454
- tick() {
470
+ /** Every enabled trigger whose next time has come: its firings recorded and its next time moved on, in one write each;
471
+ * then each failure's trigger.failed queued that is not yet, each due firing whose time has come driven, each waiting
472
+ * firing whose trigger has room again driven (one read for all of them), and the timer armed again. */
473
+ async tick() {
455
474
  this.timer = undefined;
456
- if (this.closed || this.unreadable)
475
+ if (this.closed)
457
476
  return;
458
477
  const now = this.clock.now();
459
- const due = this.triggers.filter((t) => t.enabled && t.next_at !== null && Date.parse(t.next_at) <= now);
460
- if (due.length) {
461
- // One whose source no longer reads is turned off alone, before the write, so it neither stalls the others nor
462
- // reads as a write that failed.
463
- const unreadable = due.filter((t) => sourceProblem(t.source));
464
- if (!this.offUnreadable(unreadable, now)) {
465
- this.timer = this.clock.arm(() => this.tick(), WRITE_RETRY_MS);
466
- return;
467
- }
468
- try {
469
- this.commit(() => { for (const trigger of due)
470
- if (!unreadable.includes(trigger))
471
- this.advance(trigger, now); });
472
- }
473
- catch (error) {
474
- this.deps.say({ condition: "triggers_unwritable", file: this.file, error: error.code ?? error.message });
475
- this.timer = this.clock.arm(() => this.tick(), WRITE_RETRY_MS);
476
- return;
478
+ try {
479
+ const due = (await this.all()).filter((t) => t.enabled && t.nextAt !== null && t.nextAt <= now);
480
+ // One whose source no longer reads is turned off alone, so it neither stalls the others nor reads as a failure.
481
+ const unreadable = due.filter((t) => this.problem(t.source));
482
+ await this.offUnreadable(unreadable, now);
483
+ for (const trigger of due)
484
+ if (!unreadable.includes(trigger))
485
+ await this.advance(trigger, now);
486
+ for (const firing of await this.store.triggers.pending()) {
487
+ if (firing.status === "failed")
488
+ await this.notifyFailed(firing.triggerId, firing.key);
489
+ else if (firing.waitsOn === null && !this.driving.has(firing.key) && (firing.retryAt === null || firing.retryAt <= now))
490
+ void this.inTurn(firing.triggerId, firing.key);
477
491
  }
492
+ const waiting = await this.store.triggers.waiting();
493
+ this.waiting = waiting.length > 0;
494
+ for (const firing of waiting)
495
+ if (firing.free && !this.driving.has(firing.key))
496
+ void this.inTurn(firing.triggerId, firing.key);
478
497
  }
479
- const drive = this.triggers.flatMap((t) => t.firings.filter((f) => f.status === "due" && ((!f.retry_at && !this.rewrite.has(f.key)) || this.dueAt(f) <= now)).map((f) => [t.id, f.key]));
480
- for (const [, key] of drive)
481
- this.rewrite.delete(key);
482
- const tell = this.triggers.flatMap((t) => t.firings.filter((f) => unmarked(f) && this.dueAt(f) <= now).map((f) => [t.id, f.key]));
483
- for (const [id, key] of tell) {
484
- this.rewrite.delete(key);
485
- this.notifyFailed(id, key);
498
+ catch (error) {
499
+ // The store did not answer: the timer tries again after the backoff table's first wait.
500
+ this.deps.say({ condition: "triggers_unreadable", error: String(error?.message ?? error) });
501
+ if (!this.closed)
502
+ this.timer = this.clock.arm(() => void this.tick(), BACKOFF_MS[0]);
503
+ return;
486
504
  }
487
- this.arm();
488
- for (const [id, key] of drive)
489
- void this.inTurn(id, key);
505
+ await this.arm();
490
506
  }
491
507
  /** `key`'s firing driven after every firing of its trigger asked before it. */
492
508
  inTurn(triggerId, key) {
@@ -501,355 +517,451 @@ export class Triggers {
501
517
  if (this.turns.get(triggerId) === turn)
502
518
  this.turns.delete(triggerId);
503
519
  // A firing still due after its turn (a retry) is armed for again.
504
- this.arm();
520
+ void this.arm();
505
521
  });
506
522
  return turn;
507
523
  }
508
- /** Each of `triggers` turned off, with why its source no longer reads, in one write, and said. False when the write
509
- * failed, which is said too: the caller tries again after WRITE_RETRY_MS. */
510
- offUnreadable(triggers, now) {
511
- if (!triggers.length)
512
- return true;
513
- const why = new Map(triggers.map((t) => [t, sourceProblem(t.source)]));
514
- try {
515
- this.commit(() => {
516
- for (const [t, detail] of why)
517
- Object.assign(t, { enabled: false, next_at: null, disabled: { at: iso(now), reason: "source_unreadable", detail } });
518
- });
519
- }
520
- catch (error) {
521
- this.deps.say({ condition: "triggers_unwritable", file: this.file, error: error.code ?? error.message });
522
- return false;
523
- }
524
- for (const [t, detail] of why)
524
+ /** Each of `triggers` turned off, with why its source no longer reads, and said. */
525
+ async offUnreadable(triggers, now) {
526
+ for (const t of triggers) {
527
+ const detail = this.problem(t.source);
528
+ await this.store.triggers.update(t.id, { enabled: false, nextAt: null, disabled: { at: iso(now), reason: "source_unreadable", detail } });
525
529
  this.deps.say({ condition: "trigger_source_unreadable", trigger: t.id, error: detail });
526
- return true;
527
- }
528
- /** Records `trigger`'s firings up to now and moves its next time on from the last nominal one. Of the times that have
529
- * come, the latest fires (on time, or late within catchup_window_s: a catch-up, under its own nominal key), and every
530
- * other is one `missed` row with their count. A one-time schedule, or one that never fires again, is turned off. */
531
- advance(trigger, now) {
532
- const { source } = trigger;
533
- // A webhook trigger has no next time, so it is never here.
534
- if (source.kind === "webhook")
530
+ }
531
+ }
532
+ /** Records `trigger`'s firings up to now and moves its next time on from the last nominal one, in one write. Of the
533
+ * times that have come, the latest fires (on time, or late within catchup_window_s: a catch-up, under its own nominal
534
+ * key), and every other is one `missed` row with their count. A one-time schedule, or one that never fires again, is
535
+ * turned off. */
536
+ async advance(trigger, now) {
537
+ const adapter = this.adapter(trigger.source);
538
+ // A pushed source has no next time, so it is never here.
539
+ const clock = adapter.clock?.(trigger.source);
540
+ if (!clock)
535
541
  return;
536
- const cron = "cron" in source ? cronOf(source) : undefined;
537
- const windowMs = settled(trigger).catchup_window_s * 1000;
538
- const first = Date.parse(trigger.next_at);
539
- const last = latestBy(source, first, now, cron);
542
+ const by = adapter.id;
543
+ const windowMs = (trigger.catchupWindowS ?? CATCHUP_WINDOW_S) * 1000;
544
+ const first = trigger.nextAt;
545
+ const last = clock.latest(first, now);
546
+ const nextOf = (after) => {
547
+ const at = clock.next(after);
548
+ return at !== null && Number.isFinite(at) && Math.abs(at) <= DATE_MAX_MS ? at : null;
549
+ };
540
550
  // The times from first to last: an interval's counted on its grid, a cron line's walked, at most MISSED_COUNTED.
541
551
  let count = 1;
542
552
  let capped = false;
543
- if ("every_s" in source)
544
- count += (last - first) / (source.every_s * 1000);
553
+ if (clock.step)
554
+ count += (last - first) / clock.step;
545
555
  else
546
556
  for (let at = first; at < last; count++) {
547
557
  if (count === MISSED_COUNTED) {
548
558
  capped = true;
549
559
  break;
550
560
  }
551
- at = nextAfter(source, at, cron) ?? last;
561
+ at = nextOf(at) ?? last;
552
562
  }
553
563
  const late = now - last;
554
564
  const fires = late <= LATE_MS || late <= windowMs;
555
565
  // Capped, the times counted are all before the last: every one of them was missed, and more besides.
556
566
  const missed = capped || !fires ? count : count - 1;
557
567
  // Every time reckoned before anything is written: a source that throws leaves the trigger as it was.
558
- const next = nextAfter(source, last, cron);
568
+ const next = nextOf(last);
569
+ const firings = [];
559
570
  if (missed > 0)
560
- this.record(trigger, { key: firingKey("schedule", trigger.id, `missed\n${second(first)}`), by: "schedule", nominal_at: second(first), status: "missed", at: iso(now), count: missed, reason: `The server was down or its timer late: ${missed === 1 && !capped ? "this time was" : `${missed}${capped ? " or more" : ""} times from this one were`} not fired.` });
561
- // A message_run firing has no overlap check, so a run that stays busy would hold one more due firing each time.
562
- const full = dueOf(trigger) >= DUE_KEPT ? { status: "skipped", reason: `${DUE_KEPT} earlier firings are still waiting to reach the run.` } : { status: "due" };
571
+ firings.push({ key: firingKey(by, trigger.id, `missed\n${second(first)}`), by, nominalAt: first, status: "missed", count: missed, reason: `The server was down or its timer late: ${missed === 1 && !capped ? "this time was" : `${missed}${capped ? " or more" : ""} times from this one were`} not fired.` });
572
+ // A full trigger skips its time, never queues a 21st.
573
+ const full = (await this.store.triggers.pending()).filter((f) => f.triggerId === trigger.id && f.status === "due").length >= DUE_KEPT;
563
574
  if (fires)
564
- this.record(trigger, { key: firingKey("schedule", trigger.id, second(last)), by: "schedule", nominal_at: second(last), ...full, at: iso(now), ...(late > LATE_MS ? { catch_up: true } : {}) });
565
- trigger.next_at = next === null ? null : iso(next);
566
- if (next === null)
567
- trigger.enabled = false;
568
- }
569
- /** A firing taken from due to its end: skipped when its trigger's last run is active, else its run started. A full
570
- * server (429), or a last run that could not be read, keeps it due and tries again later. Nothing it holds across a wait is an object: the trigger may be edited or
571
- * deleted meanwhile, so each step finds it again by id and key. */
575
+ firings.push({ key: firingKey(by, trigger.id, second(last)), by, nominalAt: last, ...(full ? { status: "skipped", reason: `${DUE_KEPT} earlier firings are still waiting to reach the run.` } : { status: "due" }), ...(late > LATE_MS ? { catchUp: true } : {}) });
576
+ await this.store.triggers.record(trigger.id, firings, { patch: { nextAt: next, ...(next === null ? { enabled: false } : {}) } });
577
+ await this.prune(trigger);
578
+ }
579
+ /** A firing taken from due to its end: skipped when its trigger's last run is active, else its run started (or its
580
+ * message sent). A failed try keeps it due under the backoff table, or ends it failed. Each step reads the trigger and
581
+ * the firing again: either may be edited or deleted meanwhile. */
572
582
  async drive(triggerId, key) {
583
+ if (this.closed)
584
+ return;
573
585
  try {
574
- const found = this.find(triggerId, key);
575
- if (!found || found.firing.status !== "due")
586
+ const firing = await this.store.triggers.firing(triggerId, key);
587
+ if (!firing || firing.status !== "due")
576
588
  return;
577
589
  // Its run already started (the store has its key) is its run, whatever runs now.
578
- const prior = await this.deps.runOf(key).then((run) => ({ run }), (error) => ({ retry: error }));
590
+ const prior = await this.deps.runOf(key);
579
591
  if (this.closed)
580
592
  return;
581
- if ("retry" in prior)
582
- return this.retry(triggerId, key, prior.retry);
583
- // A key stays bound to its run: one lost at setup is this firing's failure, never fired again. The next firing
584
- // goes ahead, and a run now is the person's retry.
585
- if (prior.run?.setup_lost)
586
- return this.failed(triggerId, key, { code: "run_failed", message: LOST_AT_SETUP }, { run_id: prior.run.run_id, reason: LOST_AT_SETUP });
587
- if (prior.run)
588
- return this.started(triggerId, key, prior.run.run_id);
589
- if (found.trigger.target.kind === "message_run")
590
- return await this.send(triggerId, key);
591
- const busy = await this.busy(found.trigger, found.firing).catch((error) => ({ retry: error }));
593
+ if (prior)
594
+ return void (await this.started(triggerId, key, prior.run_id));
595
+ const trigger = await this.find(triggerId);
596
+ if (!trigger)
597
+ return;
598
+ // Its agent archived since the firing was recorded (a firing waiting on its cap, or due on a retry): skipped, never a
599
+ // run or a message.
600
+ const archived = await this.archivedSkip(trigger.agentId);
592
601
  if (this.closed)
593
602
  return;
594
- if (typeof busy === "string")
595
- return this.settle(triggerId, key, { status: "skipped", reason: busy });
596
- if (busy)
597
- return this.retry(triggerId, key, busy.retry);
598
- const now = this.find(triggerId, key);
599
- if (!now)
603
+ if (archived)
604
+ return void (await this.store.triggers.settle(triggerId, key, { status: "skipped", reason: archived }));
605
+ if (trigger.target.kind === "message_run")
606
+ return void (await this.send(trigger, firing));
607
+ const busy = await this.busy(trigger, firing);
608
+ if (this.closed)
600
609
  return;
610
+ if (busy && "skipped" in busy)
611
+ return void (await this.store.triggers.settle(triggerId, key, { status: "skipped", reason: busy.skipped }));
612
+ if (busy && "waitsOn" in busy)
613
+ return void (await this.wait(triggerId, key, busy.waitsOn, busy.reason));
601
614
  // The target as it is now: an edit during the overlap check may have made it a message.
602
- if (now.trigger.target.kind === "message_run")
603
- return await this.send(triggerId, key);
615
+ const now = await this.find(triggerId);
616
+ if (!now)
617
+ return;
618
+ if (now.target.kind === "message_run")
619
+ return void (await this.send(now, firing));
604
620
  let started;
605
621
  try {
606
- started = await this.deps.start(now.trigger.target, inputOf(now.trigger, now.firing), { id: triggerId, firing_key: key });
622
+ started = await this.deps.start(now.target, this.inputOf(now, firing), { id: triggerId, firing_key: key, name: now.name }, this.originOf(now), this.titleOf(now, firing));
607
623
  }
608
624
  catch (error) {
609
625
  // Stopping, the start may have been cut by the close: the firing stays due for the next start, whose origin key
610
626
  // finds a run this one made.
611
627
  if (this.closed)
612
628
  return;
613
- if (error instanceof ApiError && ["rate_limited", "home_busy", "unavailable"].includes(error.code))
614
- return this.retry(triggerId, key, error);
615
- return this.failed(triggerId, key, { code: error instanceof ApiError ? error.code : "internal", message: error.message });
629
+ // The archive committed between the read above and the start, which refused the run (the store's fire reads the
630
+ // archive in its own transaction): skipped, as above, and no failure counted.
631
+ const raced = await this.archivedSkip(now.agentId).catch(() => undefined);
632
+ if (raced)
633
+ return void (await this.store.triggers.settle(triggerId, key, { status: "skipped", reason: raced }));
634
+ return void (await this.answered(triggerId, key, error));
616
635
  }
617
636
  if (this.closed)
618
637
  return;
619
- this.started(triggerId, key, started.run_id);
638
+ await this.started(triggerId, key, started.run_id);
620
639
  }
621
640
  catch (error) {
622
- // A throw none of the answers above handles: whatever it left (still due, most likely) is driven again after the
623
- // write retry's wait, never at once (its retry time may have passed).
624
- this.rewrite.set(key, this.clock.now() + WRITE_RETRY_MS);
625
- this.deps.say({ condition: "trigger_firing_failed", trigger: triggerId, firing: key, error: error.message });
641
+ if (this.closed)
642
+ return;
643
+ await this.failedTry(triggerId, key, error);
626
644
  }
627
645
  }
628
- /** A message_run firing: its message to the target's run, under its key. No overlap: the run's own state picks how the
629
- * message lands (steer, answer or follow-up). */
630
- async send(triggerId, key) {
631
- const found = this.find(triggerId, key);
632
- if (!found || found.trigger.target.kind !== "message_run")
646
+ /** A message_run firing: its message to the target's run, under its key, queued as a command row the run takes at its
647
+ * next safe point, within the bound per (trigger, run): a clock's firings coalesce to one waiting message, a pushed
648
+ * source's or a run now's keep each, up to DUE_KEPT; past it the firing is skipped in words. A target run that is gone
649
+ * turns the trigger off. */
650
+ async send(trigger, firing) {
651
+ if (trigger.target.kind !== "message_run")
652
+ return;
653
+ const { target } = trigger;
654
+ if (!(await this.store.runs.get(target.run_id))) {
655
+ await this.store.triggers.update(trigger.id, { enabled: false, nextAt: null, disabled: { at: iso(this.clock.now()), reason: "source_unreadable", detail: RUN_DELETED } });
656
+ await this.store.triggers.settle(trigger.id, firing.key, { status: "skipped", reason: RUN_DELETED });
657
+ this.deps.say({ condition: "trigger_source_unreadable", trigger: trigger.id, error: RUN_DELETED });
633
658
  return;
634
- const { target } = found.trigger;
659
+ }
660
+ const bound = adapterIn(this.adapters, firing.by)?.delivery === "clock" ? { max: 1, reason: "A message from this trigger is already waiting." } : { max: DUE_KEPT, reason: `${DUE_KEPT} messages from this trigger are already waiting for its run.` };
635
661
  let skipped;
636
662
  try {
637
- skipped = (await this.deps.message(target, inputOf(found.trigger, found.firing), key))?.skipped;
663
+ skipped = (await this.deps.message(target, this.inputOf(trigger, firing), firing.key, this.originOf(trigger), bound))?.skipped;
638
664
  }
639
665
  catch (error) {
640
666
  if (this.closed)
641
667
  return;
642
- if (error instanceof ApiError && ["rate_limited", "home_busy", "unavailable"].includes(error.code))
643
- return this.retry(triggerId, key, error);
644
- return this.failed(triggerId, key, { code: error instanceof ApiError ? error.code : "internal", message: error.message }, { run_id: target.run_id });
668
+ return this.answered(trigger.id, firing.key, error, target.run_id);
645
669
  }
646
670
  if (this.closed)
647
671
  return;
648
672
  if (skipped)
649
- return this.settle(triggerId, key, { status: "skipped", reason: skipped });
650
- this.settle(triggerId, key, { status: "sent", run_id: target.run_id }, (t) => void (t.failures_in_a_row = 0));
651
- }
652
- find(triggerId, key) {
653
- const trigger = this.triggers.find((t) => t.id === triggerId);
654
- const firing = trigger?.firings.find((f) => f.key === key);
655
- return trigger && firing ? { trigger, firing } : undefined;
656
- }
657
- /** Why `firing` is skipped (overlap: skip), if it is: an earlier firing still due, or the last run still active. */
673
+ return void (await this.store.triggers.settle(trigger.id, firing.key, { status: "skipped", reason: skipped }));
674
+ await this.store.triggers.settle(trigger.id, firing.key, { status: "sent", runId: target.run_id }, { reset: true });
675
+ }
676
+ /** The firing kept due, waiting for its trigger's room (no try counted, no retry time): a tick drives it once the store
677
+ * says a run of its trigger ended. */
678
+ async wait(triggerId, key, runId, reason) {
679
+ await this.store.triggers.settle(triggerId, key, { waitsOn: runId, retryAt: null, reason });
680
+ this.waiting = true;
681
+ }
682
+ async find(triggerId) {
683
+ const row = await this.store.triggers.get(triggerId);
684
+ return row && asTrigger(row);
685
+ }
686
+ /** Why `firing` does not start now, if it does not: skipped (overlap: an earlier firing still due, or the last run still
687
+ * active), or, with max_active_runs (a pushed trigger's, with or without accept), waiting on the last run while that
688
+ * many of the trigger's runs have not ended: a capped trigger starts a run per firing and never skips. A trigger whose
689
+ * source starts a run per firing (its adapter's concurrent) is never skipped either: with no cap it starts, the server's
690
+ * run limit still holding through retry. */
658
691
  async busy(trigger, firing) {
659
- const earlier = trigger.firings.slice(0, trigger.firings.indexOf(firing));
660
- if (earlier.some((f) => f.status === "due"))
661
- return "An earlier firing is still waiting to start its run.";
662
- const last = trigger.last_run_id;
692
+ if (trigger.maxActiveRuns !== null) {
693
+ const active = await this.store.triggers.activeRuns(trigger.id);
694
+ if (active < trigger.maxActiveRuns || !trigger.lastRunId)
695
+ return undefined;
696
+ return { waitsOn: trigger.lastRunId, reason: `${active} of this trigger's runs have not ended (max_active_runs ${trigger.maxActiveRuns}).` };
697
+ }
698
+ if (this.adapter(trigger.source)?.concurrent?.(trigger.source))
699
+ return undefined;
700
+ const earlier = (await this.store.triggers.pending()).some((f) => f.triggerId === trigger.id && f.status === "due" && f.key !== firing.key && f.at < firing.at);
701
+ if (earlier)
702
+ return { skipped: "An earlier firing is still waiting to start its run." };
703
+ const last = trigger.lastRunId;
663
704
  if (!last)
664
705
  return undefined;
665
706
  const status = await this.deps.statusOf(last);
666
707
  if (status === null || ENDED.has(status))
667
708
  return undefined;
668
- return status === "input_required" ? `The last run, ${last}, is waiting for a person.` : `The last run, ${last}, is still ${status}.`;
709
+ return { skipped: status === "input_required" ? `The last run, ${last}, is waiting for a person.` : `The last run, ${last}, is still ${status}.` };
669
710
  }
670
- retry(triggerId, key, error) {
671
- // A run that is working refused a message that may not answer it: no failed try, and looked at again soon, so the
672
- // message lands within WORKING_RETRY_MS of the turn's end.
673
- if (error instanceof ApiError && error.extra.details?.reason === "working") {
674
- return this.settle(triggerId, key, { status: "due", retry_at: iso(this.clock.now() + WORKING_RETRY_MS), reason: error.message });
711
+ /** A failed try: kept due with its next try after the backoff table's wait (an answer's own Retry-After when longer), or,
712
+ * past the table, failed. Either way one more in the trigger's streak. A throw that is not a target's answer (a store
713
+ * or a run's status that did not read, a programming error) is a failed try like a busy server's. */
714
+ async failedTry(triggerId, key, error) {
715
+ try {
716
+ const firing = await this.store.triggers.firing(triggerId, key);
717
+ if (!firing || firing.status !== "due")
718
+ return;
719
+ const attempts = firing.attempts + 1;
720
+ if (attempts <= BACKOFF_MS.length) {
721
+ const wait = Math.max(BACKOFF_MS[attempts - 1], error instanceof ApiError ? (error.extra.retry_after_ms ?? 0) : 0);
722
+ const settled = await this.store.triggers.settle(triggerId, key, { attempts, retryAt: this.clock.now() + wait, error: errorOf(error), reason: errorOf(error).message, waitsOn: null }, { failure: true, pauseAt: FAILURES_TO_PAUSE });
723
+ if (settled?.paused)
724
+ this.deps.say({ condition: "trigger_auto_paused", trigger: triggerId, firing: key });
725
+ return;
726
+ }
727
+ await this.failed(triggerId, key, errorOf(error));
728
+ }
729
+ catch (failure) {
730
+ // The store could not keep the failure: said, and the timer tries again after the table's first wait.
731
+ this.deps.say({ condition: "trigger_firing_failed", trigger: triggerId, firing: key, error: String(failure?.message ?? failure) });
732
+ if (!this.closed)
733
+ this.timer ??= this.clock.arm(() => void this.tick(), BACKOFF_MS[0]);
675
734
  }
676
- const attempts = (this.find(triggerId, key)?.firing.attempts ?? 0) + 1;
677
- const wait = Math.max(RETRY_MS[Math.min(attempts, RETRY_MS.length) - 1], error instanceof ApiError ? (error.extra.retry_after_ms ?? 0) : 0);
678
- this.settle(triggerId, key, { status: "due", attempts, retry_at: iso(this.clock.now() + wait), reason: error.message });
679
735
  }
680
- started(triggerId, key, runId) {
681
- this.settle(triggerId, key, { status: "started", run_id: runId }, (t) => void (t.failures_in_a_row = 0));
736
+ /** A target refused the firing: a busy server's answer is a failed try under the table; any other (a refusal, a thrown
737
+ * error) fails the firing at once. Both count toward the streak. */
738
+ async answered(triggerId, key, error, runId) {
739
+ if (error instanceof ApiError && RETRYABLE.has(error.code))
740
+ return this.failedTry(triggerId, key, error);
741
+ await this.failed(triggerId, key, errorOf(error), runId);
742
+ }
743
+ async started(triggerId, key, runId) {
744
+ await this.store.triggers.settle(triggerId, key, { status: "started", runId }, { reset: true });
682
745
  this.deps.say({ condition: "trigger_fired", trigger: triggerId, firing: key, run: runId });
683
746
  }
684
747
  /** A failed firing: one more in its trigger's streak, the trigger turned off at FAILURES_TO_PAUSE, and trigger.failed
685
748
  * queued (after the firing is written: a start finds one not yet queued and queues it, under the same webhook-id). */
686
- failed(triggerId, key, error, also = {}) {
687
- this.settle(triggerId, key, { status: "failed", error, ...also }, (t, firing) => {
688
- t.failures_in_a_row = settled(t).failures_in_a_row + 1;
689
- if (t.failures_in_a_row < FAILURES_TO_PAUSE || !t.enabled)
690
- return;
691
- Object.assign(t, { enabled: false, next_at: null, disabled: { at: iso(this.clock.now()), reason: "auto_paused" } });
692
- firing.paused = true;
693
- });
694
- this.notifyFailed(triggerId, key);
695
- }
696
- notifyFailed(triggerId, key) {
697
- const found = this.find(triggerId, key);
698
- if (!found || found.firing.status !== "failed" || found.firing.notified)
749
+ async failed(triggerId, key, error, runId, reason) {
750
+ await this.store.triggers.settle(triggerId, key, { status: "failed", error, ...(runId ? { runId } : {}), ...(reason ? { reason } : {}) }, { failure: true, pauseAt: FAILURES_TO_PAUSE });
751
+ await this.notifyFailed(triggerId, key);
752
+ }
753
+ async notifyFailed(triggerId, key) {
754
+ const firing = await this.store.triggers.firing(triggerId, key);
755
+ const trigger = await this.find(triggerId);
756
+ if (!firing || !trigger || firing.status !== "failed" || firing.notified)
699
757
  return;
700
- const { trigger, firing } = found;
701
- const told = this.deps.notify({ trigger_id: trigger.id, name: trigger.name, firing_key: key, nominal_at: firing.nominal_at, error: firing.error, auto_paused: firing.paused === true }, key);
702
- // A mark that does not land (the outbox's write failed, or this file's: settle) is tried again soon while the server
703
- // runs (tick), under the same key, which the outbox holds once: a restart then finds it marked.
758
+ const told = this.deps.notify({ trigger_id: trigger.id, name: trigger.name, firing_key: key, nominal_at: second(firing.nominalAt), error: firing.error ?? { code: "internal", message: "" }, auto_paused: firing.paused }, key);
759
+ // A mark that does not land (the outbox's write failed) is tried again at the next tick, under the same key, which
760
+ // the outbox holds once: a restart then finds it marked.
704
761
  if (told === "queued" || told === "off")
705
- this.settle(triggerId, key, { notified: true });
706
- else if (told === "unsaved")
707
- this.rewrite.set(key, this.clock.now() + WRITE_RETRY_MS);
708
- }
709
- /** The firing's new state, written with `also` done to its trigger; one whose trigger was deleted meanwhile is gone with it. */
710
- settle(triggerId, key, change, also) {
762
+ await this.store.triggers.settle(triggerId, key, { notified: true });
763
+ }
764
+ /** `firing` recorded for `trigger` (pruned first, so a key past its day is no longer known): `created` false and the
765
+ * key's firing as it stands when it is known. `room`: refused (429, retryable, nothing written) while the trigger holds
766
+ * DUE_KEPT firings due. */
767
+ async record(trigger, firing, { room = false } = {}) {
768
+ await this.prune(trigger);
769
+ let recorded;
711
770
  try {
712
- this.commit(() => {
713
- const found = this.find(triggerId, key);
714
- if (!found)
715
- return;
716
- // Out of due, a firing keeps no retry, nor the reason the last try gave.
717
- Object.assign(found.firing, change.status === "due" || change.status === undefined ? change : { reason: undefined, attempts: undefined, retry_at: undefined, ...change });
718
- if (change.status !== undefined && change.status !== "due")
719
- delete found.firing.payload;
720
- // Run ids are UUIDv7s, which sort by when the run started: a firing that finds an older run (a run now's key
721
- // retried past its day) never takes the place of a later one.
722
- const last = found.trigger.last_run_id;
723
- if (change.run_id && found.trigger.target.kind === "start_run" && !(last && last > change.run_id))
724
- found.trigger.last_run_id = change.run_id;
725
- also?.(found.trigger, found.firing);
726
- });
771
+ recorded = await this.store.triggers.record(trigger.id, [firing], room ? { room: DUE_KEPT } : {});
727
772
  }
728
773
  catch (error) {
729
- // Left as it was: driven again soon (arm), under the same origin key, and at the next start.
730
- this.rewrite.set(key, this.clock.now() + WRITE_RETRY_MS);
731
- this.deps.say({ condition: "triggers_unwritable", file: this.file, error: error.code ?? error.message });
774
+ if (!(error instanceof TriggerFull))
775
+ throw error;
776
+ // The same key again answers its firing, full or not.
777
+ const known = await this.store.triggers.firing(trigger.id, firing.key);
778
+ if (known)
779
+ return { created: false, firing: known };
780
+ this.deps.say({ condition: "trigger_firings_full", trigger: trigger.id, due: DUE_KEPT });
781
+ throw new ApiError("rate_limited", `${DUE_KEPT} firings are still due for this trigger, waiting on its run; send it again later.`, { retry_after_ms: FULL_RETRY_S * 1000, details: { due: DUE_KEPT } }, { "retry-after": String(FULL_RETRY_S) });
782
+ }
783
+ if (!recorded)
784
+ throw new ApiError("not_found", `no trigger ${trigger.id}`);
785
+ const row = await this.store.triggers.firing(trigger.id, firing.key);
786
+ return { created: recorded.created[0] === true, firing: row };
787
+ }
788
+ /** The trigger's history kept to HISTORY_KEPT: a sender's keys (run now's, a pushed source's) kept for their day, at
789
+ * most SEEN_KEPT of them; past it the oldest go, said once each time the cap is reached. */
790
+ async prune(trigger) {
791
+ const cap = this.deps.seenKept ?? SEEN_KEPT;
792
+ const over = await this.store.triggers.prune(trigger.id, { history: HISTORY_KEPT, dayMs: DAY_MS, keepByKey: (by) => by === "manual" || adapterIn(this.adapters, by)?.delivery === "push", kept: cap });
793
+ if (over > 0) {
794
+ if (!this.seenFull.has(trigger.id))
795
+ this.deps.say({ condition: "trigger_seen_full", trigger: trigger.id, kept: cap });
796
+ this.seenFull.add(trigger.id);
732
797
  }
733
- }
734
- record(trigger, firing) {
735
- if (trigger.firings.some((f) => f.key === firing.key))
736
- return;
737
- trigger.firings.push(firing);
738
- let over = trigger.firings.length - HISTORY_KEPT;
739
- // Kept past the history: a firing still due, and a failure whose trigger.failed is not queued yet (the outbox's write,
740
- // or this file's, keeps failing), the newest UNTOLD_KEPT of them; an older one's notice is dropped, and said.
741
- const untold = new Set(trigger.firings.filter(unmarked).slice(-UNTOLD_KEPT));
742
- const gone = over > 0 ? trigger.firings.filter((f) => f.status !== "due" && !untold.has(f) && over-- > 0) : [];
743
- for (const f of gone)
744
- if (unmarked(f))
745
- this.deps.say({ condition: "trigger_notice_dropped", trigger: trigger.id, firing: f.key });
746
- trigger.firings = trigger.firings.filter((f) => !gone.includes(f));
747
- const kept = [...(trigger.kept_firings ?? []), ...gone.filter((f) => f.by === "manual" || f.by === "webhook")].filter((f) => this.inDay(f)).slice(-KEPT_FIRINGS);
748
- if (kept.length)
749
- trigger.kept_firings = kept;
750
798
  else
751
- delete trigger.kept_firings;
752
- }
753
- /** A new firing's room: refused (429, retryable, nothing written) while the trigger holds DUE_KEPT firings due. */
754
- roomFor(trigger) {
755
- if (dueOf(trigger) < DUE_KEPT)
756
- return;
757
- this.deps.say({ condition: "trigger_firings_full", trigger: trigger.id, due: DUE_KEPT });
758
- throw new ApiError("rate_limited", `${DUE_KEPT} firings are still due for this trigger, waiting on its run; send it again later.`, { retry_after_ms: FULL_RETRY_S * 1000, details: { due: DUE_KEPT } }, { "retry-after": String(FULL_RETRY_S) });
759
- }
760
- /** The firing `key` names, in the history or kept for its key's day after it left. */
761
- known(trigger, key) {
762
- return trigger.firings.find((f) => f.key === key) ?? trigger.kept_firings?.find((f) => f.key === key && this.inDay(f));
763
- }
764
- /** Whether a firing is within its key's day, as an Idempotency-Key answers. */
765
- inDay(firing) {
766
- return this.clock.now() - Date.parse(firing.at) <= IDEMPOTENCY_TTL_S * 1000;
799
+ this.seenFull.delete(trigger.id);
767
800
  }
768
- /** The timer, at the soonest next time of an enabled trigger or retry of a due firing. */
769
- arm() {
770
- this.timer?.clear();
771
- this.timer = undefined;
772
- if (this.closed || this.unreadable)
773
- return;
801
+ /** The timer, at the soonest next time of an enabled trigger or next try of a due firing not being driven; a failure
802
+ * whose trigger.failed is not queued yet is tried again after the table's first wait. */
803
+ async arm() {
804
+ const turn = ++this.arming;
774
805
  let soonest = Infinity;
775
- for (const t of this.triggers) {
776
- if (t.enabled && t.next_at !== null)
777
- soonest = Math.min(soonest, Date.parse(t.next_at));
778
- // One being driven arms nothing: its end arms the timer again. A failure whose mark did not land arms its retry.
779
- for (const f of t.firings)
780
- if ((f.status === "due" && !this.driving.has(f.key)) || unmarked(f))
781
- soonest = Math.min(soonest, this.dueAt(f));
782
- }
783
- if (soonest !== Infinity)
784
- this.timer = this.clock.arm(() => this.tick(), Math.max(0, soonest - this.clock.now()));
785
- }
786
- /** When a due firing is driven next: after the write retry's wait when its write or its drive failed (that wait wins
787
- * over a retry time that may have passed), else at its retry; one with neither is driven by whatever recorded it. */
788
- dueAt(firing) {
789
- return this.rewrite.get(firing.key) ?? (firing.retry_at ? Date.parse(firing.retry_at) : Infinity);
790
- }
791
- /** `change` applied and written whole, or, when the write fails, undone and thrown. Each change, a signed request's
792
- * firing included, copies and rewrites the whole file and syncs it: one writer (server.lock), and a bounded file. A
793
- * firing is about 170 bytes of JSON, a due webhook firing's payload at most 16 KiB more, and a trigger keeps at most
794
- * HISTORY_KEPT (200) in its history and KEPT_FIRINGS (1,000) past it: about 230 KiB a trigger at its fullest, which
795
- * measured about 3 ms a write (copy, JSON and fsync) on an SSD. Its history runs past HISTORY_KEPT by at most
796
- * UNTOLD_KEPT (50) failures not yet told and DUE_KEPT (20) due firings, whose payloads add at most 320 KiB. */
797
- commit(change) {
798
- if (this.closed)
799
- throw new ApiError("unavailable", "The server is stopping.");
800
- const before = structuredClone(this.triggers);
801
806
  try {
802
- const result = change();
803
- writeDurableSync(this.file, `${JSON.stringify({ v: 1, triggers: this.triggers })}\n`);
804
- return result;
807
+ soonest = (await this.store.triggers.soonest()) ?? Infinity;
808
+ for (const f of await this.store.triggers.pending()) {
809
+ if (f.status === "failed")
810
+ soonest = Math.min(soonest, this.clock.now() + BACKOFF_MS[0]);
811
+ // A due firing not being driven: at its next try; one with none (its last write did not land, so it holds no retry
812
+ // time) after the table's first wait, never left with no time to drive it. A waiting one is the poll's.
813
+ else if (!this.driving.has(f.key) && f.waitsOn === null)
814
+ soonest = Math.min(soonest, f.retryAt ?? this.clock.now() + BACKOFF_MS[0]);
815
+ }
805
816
  }
806
- catch (error) {
807
- this.triggers = before;
808
- throw error;
817
+ catch {
818
+ soonest = this.clock.now() + BACKOFF_MS[0];
809
819
  }
820
+ if (this.waiting)
821
+ soonest = Math.min(soonest, this.clock.now() + WAIT_POLL_MS);
822
+ if (turn !== this.arming || this.closed)
823
+ return;
824
+ this.timer?.clear();
825
+ this.timer = soonest === Infinity ? undefined : this.clock.arm(() => void this.tick(), Math.max(0, soonest - this.clock.now()));
810
826
  }
811
- readable() {
812
- if (this.unreadable)
813
- throw new ApiError("store_unreadable", `${TRIGGERS_FILE} in the data directory does not read (${this.unreadable}); it is never written over. Fix it or move it away, then restart.`);
814
- return this.triggers;
827
+ async all() {
828
+ return (await this.store.triggers.all()).map(asTrigger);
815
829
  }
816
- need(id) {
817
- const trigger = this.readable().find((t) => t.id === id);
818
- if (!trigger)
830
+ async need(id) {
831
+ const row = await this.store.triggers.get(id);
832
+ if (!row)
819
833
  throw new ApiError("not_found", `no trigger ${id}`);
820
- return trigger;
821
- }
822
- view(trigger) {
823
- const { firings, kept_firings: _, ...rest } = trigger;
824
- return { ...rest, last_run_id: trigger.last_run_id ?? null, ...settled(trigger), last_firing: firings.length ? firingView(firings.at(-1)) : null };
834
+ return asTrigger(row);
835
+ }
836
+ /** The agent a trigger belongs to: its start_run target's, or the run its message_run target names. */
837
+ async agentOf(target) {
838
+ if (target.kind === "start_run")
839
+ return target.agent_id;
840
+ const run = await this.store.runs.get(target.run_id);
841
+ if (!run)
842
+ throw invalid([{ field: "target.run_id", reason: "not_found", message: `no run ${target.run_id}` }]);
843
+ return run.agentId;
844
+ }
845
+ /** A trigger as the API answers it: its fields (openapi.ts TRIGGER), named one by one, with its newest firing; a pushed
846
+ * source's, where its sender posts (`hook_url`: its own hook, or its source's one hook when its settings are the
847
+ * server's). */
848
+ async view(trigger) {
849
+ const [last] = await this.store.triggers.firings(trigger.id);
850
+ const adapter = adapterIn(this.adapters, trigger.source.kind);
851
+ const hook = adapter?.push ? `/v2/hooks/${adapter.settings?.scope === "server" ? adapter.id : trigger.id}` : undefined;
852
+ return {
853
+ ...(hook ? { hook_url: `${this.deps.publicUrl ?? ""}${hook}` } : {}),
854
+ id: trigger.id, name: trigger.name, enabled: trigger.enabled, source: trigger.source, target: trigger.target, catchup_window_s: trigger.catchupWindowS ?? CATCHUP_WINDOW_S,
855
+ max_active_runs: trigger.maxActiveRuns ?? null, failures_in_a_row: trigger.failuresInARow, disabled: trigger.disabled ?? null, next_at: trigger.nextAt === null ? null : iso(trigger.nextAt), last_run_id: trigger.lastRunId,
856
+ created_at: iso(trigger.createdAt), updated_at: iso(trigger.updatedAt), last_firing: last ? firingView(last) : null,
857
+ };
858
+ }
859
+ // ---- what each source's adapter says ----------------------------------------------------------------------------------
860
+ /** `source`'s adapter: every kept or given source has one (sourceOf). */
861
+ adapter(source) {
862
+ return adapterIn(this.adapters, source.kind);
863
+ }
864
+ /** Each field `source`'s adapter mints for its triggers, made now for trigger `id`, by field: none for one that keeps
865
+ * no trigger-scoped secret. */
866
+ async mint(source, id) {
867
+ const adapter = this.adapter(source);
868
+ if (!mints(adapter))
869
+ return {};
870
+ const store = this.deps.settings(adapter.id);
871
+ if (!store)
872
+ throw new Error(`no sealed settings for ${adapter.id}`);
873
+ return Object.fromEntries(await Promise.all(Object.entries(adapter.settings.fields).filter(([, f]) => f.mint).map(async ([field]) => [field, await store.mint(id, field)])));
874
+ }
875
+ /** A scope belongs to one trigger: `source`'s (its adapter's scopeOf), for a trigger `id` that is to be on, is refused
876
+ * 409 scope_taken while another trigger of its kind that is on listens there (its scope rows). */
877
+ async scopeFree(source, id) {
878
+ const refused = await this.scopeRefusal(source, id);
879
+ if (refused)
880
+ throw refused;
881
+ }
882
+ /** The 409 scope_taken for `source`'s scope when another enabled trigger holds it, else undefined. */
883
+ async scopeRefusal(source, id) {
884
+ const adapter = this.adapter(source);
885
+ if (!adapter.scopeOf)
886
+ return undefined;
887
+ const scope = adapter.scopeOf(source);
888
+ const other = (await this.store.triggers.scoped(source.kind, scope)).find((t) => t !== id);
889
+ return other ? new ApiError("scope_taken", `The ${adapter.label} scope ${scope} belongs to the trigger ${other}: a scope belongs to one trigger. Turn that one off, or give this one another scope.`, { details: { source: adapter.id, scope, trigger_id: other } }) : undefined;
890
+ }
891
+ /** A store refusal on the scope rows (two writes raced past scopeFree): the same 409 scope_taken; undefined for any
892
+ * other error. */
893
+ async scopeTaken(error, source, id) {
894
+ if (!(error instanceof StoreConstraint) || !/trigger_scopes/.test(error.message))
895
+ return undefined;
896
+ return (await this.scopeRefusal(source, id)) ?? new ApiError("scope_taken", "That scope belongs to another trigger: a scope belongs to one trigger.");
897
+ }
898
+ /** `source`'s scope rows, while its trigger is on: its adapter's scopeOf, or none. */
899
+ scopesOf(source) {
900
+ const scopeOf = this.adapter(source).scopeOf;
901
+ return scopeOf ? [{ kind: source.kind, scope: scopeOf(source) }] : [];
902
+ }
903
+ /** Why `source` no longer reads on this server, if it does not. */
904
+ problem(source) {
905
+ // A kind this server has no adapter for (a source the store kept that this build does not take) no longer reads.
906
+ const adapter = adapterIn(this.adapters, source.kind);
907
+ return adapter ? adapter.problem?.(source) : `this server has no ${source.kind} source`;
908
+ }
909
+ /** `target` with its input as a firing of a trigger named `name` would give it to its run: what create and PATCH
910
+ * check. */
911
+ given(name, source, target, now) {
912
+ const trigger = { name, source: source ?? { kind: this.adapters[0].id }, target };
913
+ return { ...target, input: this.inputOf(trigger, { by: "manual", nominalAt: now, payload: null }) };
914
+ }
915
+ /** A run's title, from the trigger that starts it: "<its source> <its name>" (the word its Timeline row begins with,
916
+ * pi-durable-agent's TRIGGER_LABELS), and the event its payload's tag names, when one does ("Webhook reviews:
917
+ * pull_request opened"); never its input, which may be a sender's markup. */
918
+ titleOf(trigger, firing) {
919
+ const source = TRIGGER_LABELS[trigger.source.kind] ?? trigger.source.kind;
920
+ const attrs = firing.attrs;
921
+ const event = attrs?.event;
922
+ const action = attrs?.action;
923
+ return `${source} ${trigger.name}${event ? `: ${event}${action ? ` ${action}` : ""}` : ""}`;
924
+ }
925
+ /** Who a firing's input is from (pi-durable-agent's MessageOrigin): the trigger, by its definition as it fires, never
926
+ * by its payload. Only a source whose words are its owner's (a schedule's, fired on time or by hand) gives owner true;
927
+ * a pushed source's come from outside, its body empty or not. */
928
+ originOf(trigger) {
929
+ return { kind: "trigger", trigger_id: trigger.id, source: trigger.source.kind, owner: this.adapter(trigger.source).owner };
930
+ }
931
+ /** The run's input: the trigger's, then a pushed firing's payload marked untrusted (tagged with its source and what the
932
+ * source says of it), then a line saying what fired it and when, in the trigger's zone. */
933
+ inputOf(trigger, firing) {
934
+ const adapter = this.adapter(trigger.source);
935
+ const when = local(firing.nominalAt, adapter.zone?.(trigger.source) ?? "UTC");
936
+ const what = `the ${adapter.label} "${trigger.name}"`;
937
+ const line = firing.by === "manual" ? `(Started by hand from ${what} at ${when}.)` : adapterIn(this.adapters, firing.by)?.delivery === "push" ? `(From ${what}, received at ${when}.)` : `(Started by ${what} for ${when}.)`;
938
+ // The payload is whatever its sender wrote: an instruction in it is data, and its closing tag, in any case, cannot end
939
+ // the block.
940
+ const payload = firing.payload === null ? "" : `\n\n<trigger-payload source="${firing.by}"${tagAttrs(firing.attrs)} untrusted>\n${firing.payload.replace(/<(\/trigger-payload)/gi, "<\\$1")}\n</trigger-payload>`;
941
+ const { input } = trigger.target;
942
+ return typeof input.content === "string" ? { ...input, content: `${input.content}${payload}\n\n${line}` } : input;
825
943
  }
826
944
  }
827
- const nextIso = (source, now) => {
828
- const at = nextAfter(source, now);
829
- return at === null ? null : iso(at);
830
- };
831
- /** A failed firing whose trigger.failed is not marked queued. */
832
- const unmarked = (firing) => firing.status === "failed" && !firing.notified;
945
+ /** A trigger row as the engine reads it: its source and target of their types (create and PATCH check them). */
946
+ const asTrigger = (row) => row;
947
+ /** Whether `adapter`'s triggers each get a secret it mints. */
948
+ const mints = (adapter) => adapter.settings?.scope === "trigger" && Object.values(adapter.settings.fields).some((f) => f.mint);
833
949
  /** A time a Date holds: past it (about the year 275760) a next time is none. */
834
950
  const DATE_MAX_MS = 8.64e15;
835
951
  function firingView(firing) {
836
- return { key: firing.key, by: firing.by, nominal_at: firing.nominal_at, status: firing.status, at: firing.at, run_id: firing.run_id ?? null, reason: firing.reason ?? null, error: firing.error ?? null, ...(firing.count !== undefined ? { count: firing.count } : {}), ...(firing.catch_up ? { catch_up: true } : {}), ...(firing.retry_at ? { attempts: firing.attempts ?? 0, retry_at: firing.retry_at } : {}) };
837
- }
838
- /** `target` with its input as a firing of a trigger named `name` would give it to its run: what create and PATCH check. */
839
- function given(name, source, target, now) {
840
- const trigger = { name, source: source ?? { kind: "schedule", at: second(now) }, target };
841
- return { ...target, input: inputOf(trigger, { key: "", by: "manual", nominal_at: second(now), status: "due", at: iso(now) }) };
952
+ return {
953
+ key: firing.key, by: firing.by, nominal_at: second(firing.nominalAt), status: firing.status, at: iso(firing.at), run_id: firing.runId, reason: firing.reason, error: firing.error,
954
+ ...(firing.count !== null ? { count: firing.count } : {}), ...(firing.catchUp ? { catch_up: true } : {}), ...(firing.retryAt !== null ? { attempts: firing.attempts, retry_at: iso(firing.retryAt) } : {}),
955
+ };
842
956
  }
843
- /** The run's input: the trigger's, then a webhook's payload marked untrusted, then a line saying what fired it and when,
844
- * in the trigger's zone. */
845
- function inputOf(trigger, firing) {
846
- const when = local(Date.parse(firing.nominal_at), zoneOf(trigger.source));
847
- const what = trigger.source.kind === "webhook" ? `the webhook trigger "${trigger.name}"` : `the schedule "${trigger.name}"`;
848
- const line = firing.by === "schedule" ? `(Started by ${what} for ${when}.)` : firing.by === "manual" ? `(Started by hand from ${what} at ${when}.)` : `(From ${what}, received at ${when}.)`;
849
- // The payload is whatever its sender wrote: an instruction in it is data, and its closing tag cannot end the block.
850
- const payload = firing.payload === undefined ? "" : `\n\n<trigger-payload source="webhook" untrusted>\n${firing.payload.replaceAll("</trigger-payload", "<\\/trigger-payload")}\n</trigger-payload>`;
851
- const { input } = trigger.target;
852
- return typeof input.content === "string" ? { ...input, content: `${input.content}${payload}\n\n${line}` } : input;
957
+ /** A payload tag's attributes from its source's `attrs`, each ` name="value"`: a name of lowercase letters, digits, `_` and
958
+ * `-` (never one the tag sets itself), a value cut to 200 characters with `&`, `<`, `>`, `"` escaped and line breaks
959
+ * made spaces, so a sender's words cannot end the tag or open another. */
960
+ function tagAttrs(attrs) {
961
+ if (!isObject(attrs))
962
+ return "";
963
+ const escape = (value) => value.slice(0, 200).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]).replace(/[\r\n\t]/g, " ");
964
+ return Object.entries(attrs).filter(([name, value]) => /^[a-z][a-z0-9_-]{0,31}$/.test(name) && name !== "source" && name !== "untrusted" && typeof value === "string").map(([name, value]) => ` ${name}="${escape(value)}"`).join("");
853
965
  }
854
966
  /** `text` cut to PAYLOAD_KEPT_BYTES of UTF-8 at a character's start, and said to be cut. */
855
967
  function cut(text) {