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

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 (816) hide show
  1. package/CHANGELOG.md +459 -0
  2. package/NOTICE +18 -0
  3. package/README.md +941 -263
  4. package/dist/adapter-facts.d.ts +3 -0
  5. package/dist/adapter-facts.js +5 -0
  6. package/dist/adapters.d.ts +64 -143
  7. package/dist/adapters.js +153 -384
  8. package/dist/agents-store.d.ts +146 -0
  9. package/dist/agents-store.js +359 -0
  10. package/dist/agents.d.ts +4 -2
  11. package/dist/agents.js +37 -17
  12. package/dist/api-only.d.ts +14 -0
  13. package/dist/api-only.js +33 -0
  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/box-egress-vm.d.ts +2 -9
  22. package/dist/box-egress-vm.js +20 -16
  23. package/dist/box-egress.d.ts +15 -9
  24. package/dist/box-egress.js +26 -29
  25. package/dist/box-paths.d.ts +82 -0
  26. package/dist/box-paths.js +160 -0
  27. package/dist/box-relay-vm.js +28 -1
  28. package/dist/box-relay.d.ts +1 -10
  29. package/dist/box-relay.js +1 -21
  30. package/dist/box-settings.d.ts +46 -0
  31. package/dist/box-settings.js +107 -0
  32. package/dist/boxes.d.ts +17 -2
  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 +277 -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 +166 -0
  41. package/dist/browser-person.js +767 -0
  42. package/dist/budget.d.ts +76 -0
  43. package/dist/budget.js +204 -0
  44. package/dist/cap.d.ts +267 -64
  45. package/dist/cap.js +587 -199
  46. package/dist/cli.js +220 -21
  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-Dn0ngwG9.js +535 -0
  65. package/dist/console/assets/index-DvW6Aled.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/daytona-api.d.ts +0 -11
  70. package/dist/daytona-api.js +1 -82
  71. package/dist/decision-cap.d.ts +63 -0
  72. package/dist/decision-cap.js +163 -0
  73. package/dist/decision-rows.d.ts +5 -2
  74. package/dist/decision-rows.js +8 -6
  75. package/dist/decisions.d.ts +28 -1
  76. package/dist/decisions.js +63 -6
  77. package/dist/docker-host-addresses.d.ts +37 -0
  78. package/dist/docker-host-addresses.js +110 -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 -43
  93. package/dist/files.js +8 -136
  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-install.d.ts +143 -0
  107. package/dist/harness-install.js +454 -0
  108. package/dist/harness-opencode/adapter.js +42 -8
  109. package/dist/harness-opencode/facts.d.ts +2 -0
  110. package/dist/harness-opencode/facts.js +28 -0
  111. package/dist/harness-opencode/harness.d.ts +4 -0
  112. package/dist/harness-opencode/harness.js +38 -5
  113. package/dist/harness-opencode/host/policy.js +11 -3
  114. package/dist/harness-opencode/transcript.d.ts +25 -0
  115. package/dist/harness-opencode/transcript.js +81 -0
  116. package/dist/harness-table.d.ts +75 -0
  117. package/dist/harness-table.js +145 -0
  118. package/dist/harness.d.ts +11 -31
  119. package/dist/harness.js +30 -41
  120. package/dist/heard.d.ts +12 -0
  121. package/dist/heard.js +45 -0
  122. package/dist/helper-env.d.ts +4 -0
  123. package/dist/helper-env.js +14 -0
  124. package/dist/home-path.d.ts +0 -4
  125. package/dist/home-path.js +3 -17
  126. package/dist/host-check.d.ts +4 -3
  127. package/dist/host-check.js +5 -4
  128. package/dist/host-tools.d.ts +51 -8
  129. package/dist/host-tools.js +108 -117
  130. package/dist/host.d.ts +12 -6
  131. package/dist/host.js +30 -24
  132. package/dist/hosted-search.d.ts +3 -0
  133. package/dist/hosted-search.js +5 -3
  134. package/dist/import-proxy.d.ts +42 -0
  135. package/dist/import-proxy.js +105 -0
  136. package/dist/import-summary.js +4 -8
  137. package/dist/import-worker.d.ts +2 -3
  138. package/dist/import-worker.js +18 -16
  139. package/dist/import.d.ts +37 -17
  140. package/dist/import.js +249 -224
  141. package/dist/key-meta.d.ts +26 -0
  142. package/dist/key-meta.js +30 -0
  143. package/dist/key-refusal.d.ts +4 -1
  144. package/dist/key-refusal.js +20 -7
  145. package/dist/learn/check.d.ts +3 -1
  146. package/dist/learn/check.js +2 -2
  147. package/dist/learn/commit.d.ts +86 -0
  148. package/dist/learn/commit.js +182 -0
  149. package/dist/learn/folder.d.ts +296 -0
  150. package/dist/learn/folder.js +796 -0
  151. package/dist/learn/grade.d.ts +22 -9
  152. package/dist/learn/grade.js +95 -49
  153. package/dist/learn/index.d.ts +2 -2
  154. package/dist/learn/index.js +2 -2
  155. package/dist/learn/learning.sh +366 -0
  156. package/dist/learn/reflect.d.ts +12 -5
  157. package/dist/learn/reflect.js +70 -41
  158. package/dist/learn/secrets.d.ts +16 -7
  159. package/dist/learn/secrets.js +80 -17
  160. package/dist/learn/seed-check.d.ts +74 -0
  161. package/dist/learn/seed-check.js +103 -0
  162. package/dist/learn/skills.d.ts +5 -1
  163. package/dist/learn/skills.js +5 -4
  164. package/dist/learned-workflow.d.ts +15 -4
  165. package/dist/learned-workflow.js +13 -6
  166. package/dist/learning-routes.d.ts +56 -46
  167. package/dist/learning-routes.js +350 -553
  168. package/dist/learning-run.d.ts +8 -228
  169. package/dist/learning-run.js +26 -713
  170. package/dist/learning-words.d.ts +3 -5
  171. package/dist/learning-words.js +3 -5
  172. package/dist/learning.d.ts +177 -112
  173. package/dist/learning.js +289 -380
  174. package/dist/live/stream.d.ts +30 -0
  175. package/dist/live/stream.js +175 -0
  176. package/dist/live/translate.d.ts +52 -0
  177. package/dist/live/translate.js +276 -0
  178. package/dist/llm.js +3 -0
  179. package/dist/llms.txt +1 -0
  180. package/dist/local-models.d.ts +23 -0
  181. package/dist/local-models.js +35 -0
  182. package/dist/mcp-gateway.d.ts +45 -15
  183. package/dist/mcp-gateway.js +140 -53
  184. package/dist/mcp-meta.d.ts +3 -0
  185. package/dist/mcp-meta.js +14 -2
  186. package/dist/mcp-oauth.d.ts +172 -0
  187. package/dist/mcp-oauth.js +403 -0
  188. package/dist/mcp-private-hosts.d.ts +48 -0
  189. package/dist/mcp-private-hosts.js +141 -0
  190. package/dist/mcp-probe.d.ts +101 -0
  191. package/dist/mcp-probe.js +359 -0
  192. package/dist/mcp-secret-writes.d.ts +23 -0
  193. package/dist/mcp-secret-writes.js +60 -0
  194. package/dist/mcp-servers-store.d.ts +251 -0
  195. package/dist/mcp-servers-store.js +447 -0
  196. package/dist/mcp-servers.d.ts +180 -50
  197. package/dist/mcp-servers.js +284 -321
  198. package/dist/mcp-store.d.ts +103 -0
  199. package/dist/mcp-store.js +123 -0
  200. package/dist/mcp.js +22 -21
  201. package/dist/model.d.ts +77 -59
  202. package/dist/model.js +237 -98
  203. package/dist/monid.d.ts +8 -6
  204. package/dist/monid.js +39 -25
  205. package/dist/openapi.d.ts +22 -1
  206. package/dist/openapi.js +921 -110
  207. package/dist/owner.d.ts +46 -10
  208. package/dist/owner.js +123 -43
  209. package/dist/page.d.ts +10 -0
  210. package/dist/page.js +29 -4
  211. package/dist/paid-calls.d.ts +71 -2
  212. package/dist/paid-calls.js +127 -6
  213. package/dist/pause.d.ts +0 -2
  214. package/dist/pause.js +1 -8
  215. package/dist/pdf-pages.d.ts +16 -14
  216. package/dist/pdf-pages.js +88 -58
  217. package/dist/place.d.ts +15 -18
  218. package/dist/place.js +25 -25
  219. package/dist/port-models.d.ts +53 -0
  220. package/dist/port-models.js +93 -0
  221. package/dist/print.d.ts +2 -1
  222. package/dist/print.js +4 -2
  223. package/dist/propose.d.ts +9 -8
  224. package/dist/propose.js +82 -49
  225. package/dist/provider.d.ts +85 -0
  226. package/dist/provider.js +178 -0
  227. package/dist/push-handler.d.ts +52 -0
  228. package/dist/push-handler.js +165 -0
  229. package/dist/refusal-words.d.ts +23 -0
  230. package/dist/refusal-words.js +25 -0
  231. package/dist/result.d.ts +13 -2
  232. package/dist/result.js +4 -5
  233. package/dist/run-computer.d.ts +24 -0
  234. package/dist/run-computer.js +15 -0
  235. package/dist/run-cut.d.ts +33 -0
  236. package/dist/run-cut.js +42 -0
  237. package/dist/run-db.d.ts +62 -0
  238. package/dist/run-db.js +151 -0
  239. package/dist/run-files.d.ts +31 -0
  240. package/dist/run-files.js +125 -0
  241. package/dist/run-launch.d.ts +72 -0
  242. package/dist/run-launch.js +108 -0
  243. package/dist/run-learning-served.d.ts +81 -0
  244. package/dist/run-learning-served.js +25 -0
  245. package/dist/run-manifest.d.ts +7 -6
  246. package/dist/run-manifest.js +20 -10
  247. package/dist/run-reads-over-store.d.ts +102 -0
  248. package/dist/run-reads-over-store.js +151 -0
  249. package/dist/run-secrets.d.ts +33 -0
  250. package/dist/run-secrets.js +53 -0
  251. package/dist/run-timeline-served.d.ts +13 -0
  252. package/dist/run-timeline-served.js +72 -0
  253. package/dist/run-view.d.ts +432 -0
  254. package/dist/run-view.js +602 -0
  255. package/dist/runnable.d.ts +30 -5
  256. package/dist/runnable.js +149 -72
  257. package/dist/runner/adapter-loop.d.ts +243 -0
  258. package/dist/runner/adapter-loop.js +1657 -0
  259. package/dist/runner/adapter-run-spec.d.ts +224 -0
  260. package/dist/runner/adapter-run-spec.js +538 -0
  261. package/dist/runner/adapters/index.d.ts +37 -0
  262. package/dist/runner/adapters/index.js +66 -0
  263. package/dist/runner/adapters/pi.d.ts +103 -0
  264. package/dist/runner/adapters/pi.js +263 -0
  265. package/dist/runner/beside.d.ts +12 -0
  266. package/dist/runner/beside.js +41 -0
  267. package/dist/runner/claim-secrets.d.ts +30 -0
  268. package/dist/runner/claim-secrets.js +90 -0
  269. package/dist/runner/cli-run-spec.d.ts +17 -0
  270. package/dist/runner/cli-run-spec.js +385 -0
  271. package/dist/runner/commands.d.ts +23 -0
  272. package/dist/runner/commands.js +67 -0
  273. package/dist/runner/computer-journal.d.ts +38 -0
  274. package/dist/runner/computer-journal.js +120 -0
  275. package/dist/runner/conformance/child.d.ts +1 -0
  276. package/dist/runner/conformance/child.js +78 -0
  277. package/dist/runner/conformance/harness.d.ts +89 -0
  278. package/dist/runner/conformance/harness.js +928 -0
  279. package/dist/runner/conformance/subject.d.ts +83 -0
  280. package/dist/runner/conformance/subject.js +1 -0
  281. package/dist/runner/dispatch.d.ts +30 -0
  282. package/dist/runner/dispatch.js +99 -0
  283. package/dist/runner/end-of-run.d.ts +32 -0
  284. package/dist/runner/end-of-run.js +56 -0
  285. package/dist/runner/github-app.d.ts +16 -0
  286. package/dist/runner/github-app.js +37 -0
  287. package/dist/runner/hand-back.d.ts +43 -0
  288. package/dist/runner/hand-back.js +69 -0
  289. package/dist/runner/harness-loops.d.ts +10 -0
  290. package/dist/runner/harness-loops.js +70 -0
  291. package/dist/runner/journal-kinds.d.ts +217 -0
  292. package/dist/runner/journal-kinds.js +116 -0
  293. package/dist/runner/journal-reader.d.ts +44 -0
  294. package/dist/runner/journal-reader.js +127 -0
  295. package/dist/runner/learning-ask.d.ts +37 -0
  296. package/dist/runner/learning-ask.js +99 -0
  297. package/dist/runner/learning-dispatch.d.ts +38 -0
  298. package/dist/runner/learning-dispatch.js +75 -0
  299. package/dist/runner/learning-end.d.ts +31 -0
  300. package/dist/runner/learning-end.js +136 -0
  301. package/dist/runner/learning-factory.d.ts +13 -0
  302. package/dist/runner/learning-factory.js +37 -0
  303. package/dist/runner/learning-loop.d.ts +150 -0
  304. package/dist/runner/learning-loop.js +246 -0
  305. package/dist/runner/learning-seed.d.ts +30 -0
  306. package/dist/runner/learning-seed.js +41 -0
  307. package/dist/runner/live-ticker.d.ts +18 -0
  308. package/dist/runner/live-ticker.js +112 -0
  309. package/dist/runner/loop-contract.d.ts +154 -0
  310. package/dist/runner/loop-contract.js +26 -0
  311. package/dist/runner/loop.d.ts +79 -0
  312. package/dist/runner/loop.js +185 -0
  313. package/dist/runner/main.d.ts +96 -0
  314. package/dist/runner/main.js +311 -0
  315. package/dist/runner/mcp-claim.d.ts +67 -0
  316. package/dist/runner/mcp-claim.js +403 -0
  317. package/dist/runner/mcp-github.d.ts +53 -0
  318. package/dist/runner/mcp-github.js +91 -0
  319. package/dist/runner/mcp-run.d.ts +116 -0
  320. package/dist/runner/mcp-run.js +152 -0
  321. package/dist/runner/metrics.d.ts +18 -0
  322. package/dist/runner/metrics.js +24 -0
  323. package/dist/runner/model-route.d.ts +111 -0
  324. package/dist/runner/model-route.js +202 -0
  325. package/dist/runner/pi-stop.d.ts +6 -0
  326. package/dist/runner/pi-stop.js +8 -0
  327. package/dist/runner/redact.d.ts +32 -0
  328. package/dist/runner/redact.js +60 -0
  329. package/dist/runner/reflect-hook.d.ts +81 -0
  330. package/dist/runner/reflect-hook.js +111 -0
  331. package/dist/runner/runner.d.ts +114 -0
  332. package/dist/runner/runner.js +672 -0
  333. package/dist/runner/sessions.d.ts +9 -0
  334. package/dist/runner/sessions.js +145 -0
  335. package/dist/runner/side-effects.d.ts +19 -0
  336. package/dist/runner/side-effects.js +20 -0
  337. package/dist/runner/spec-holds.d.ts +41 -0
  338. package/dist/runner/spec-holds.js +58 -0
  339. package/dist/runner/store-port.d.ts +9 -0
  340. package/dist/runner/store-port.js +7 -0
  341. package/dist/runner/store-secrets.d.ts +11 -0
  342. package/dist/runner/store-secrets.js +105 -0
  343. package/dist/runner/workflow-adapters.d.ts +1 -0
  344. package/dist/runner/workflow-adapters.js +4 -0
  345. package/dist/runner/workflow-host.d.ts +88 -0
  346. package/dist/runner/workflow-host.js +66 -0
  347. package/dist/runner/workflow-loop.d.ts +126 -0
  348. package/dist/runner/workflow-loop.js +372 -0
  349. package/dist/runner/workflow-spec.d.ts +157 -0
  350. package/dist/runner/workflow-spec.js +797 -0
  351. package/dist/runs-over-store.d.ts +203 -0
  352. package/dist/runs-over-store.js +407 -0
  353. package/dist/seal-key.d.ts +69 -0
  354. package/dist/seal-key.js +329 -0
  355. package/dist/sealed-settings-store.d.ts +71 -0
  356. package/dist/sealed-settings-store.js +205 -0
  357. package/dist/sealed-settings.d.ts +60 -0
  358. package/dist/sealed-settings.js +171 -0
  359. package/dist/secret-writes.d.ts +147 -0
  360. package/dist/secret-writes.js +144 -0
  361. package/dist/secrets.d.ts +7 -8
  362. package/dist/secrets.js +24 -5
  363. package/dist/server-approvers.d.ts +8 -0
  364. package/dist/server-approvers.js +12 -0
  365. package/dist/server-fs.d.ts +40 -0
  366. package/dist/server-fs.js +138 -0
  367. package/dist/server-keys.d.ts +18 -0
  368. package/dist/server-keys.js +31 -0
  369. package/dist/server-lock.js +1 -1
  370. package/dist/server-secrets-store.d.ts +18 -0
  371. package/dist/server-secrets-store.js +54 -0
  372. package/dist/server-secrets.d.ts +23 -0
  373. package/dist/server-secrets.js +76 -0
  374. package/dist/server.d.ts +148 -75
  375. package/dist/server.js +1740 -605
  376. package/dist/sessions.d.ts +3 -1
  377. package/dist/sessions.js +8 -4
  378. package/dist/sign-ins-secrets.d.ts +35 -0
  379. package/dist/sign-ins-secrets.js +109 -0
  380. package/dist/sign-ins-store.d.ts +200 -0
  381. package/dist/sign-ins-store.js +373 -0
  382. package/dist/sign-ins.d.ts +43 -7
  383. package/dist/sign-ins.js +94 -18
  384. package/dist/skills.d.ts +6 -5
  385. package/dist/skills.js +18 -14
  386. package/dist/standard-webhooks.d.ts +30 -0
  387. package/dist/standard-webhooks.js +72 -0
  388. package/dist/stats.d.ts +5 -7
  389. package/dist/stats.js +8 -24
  390. package/dist/stop-signals.d.ts +22 -0
  391. package/dist/stop-signals.js +38 -0
  392. package/dist/store/agent-body.d.ts +103 -0
  393. package/dist/store/agent-body.js +126 -0
  394. package/dist/store/dialect.d.ts +59 -0
  395. package/dist/store/dialect.js +32 -0
  396. package/dist/store/fence.d.ts +22 -0
  397. package/dist/store/fence.js +15 -0
  398. package/dist/store/index.d.ts +17 -0
  399. package/dist/store/index.js +17 -0
  400. package/dist/store/journal/storage.d.ts +137 -0
  401. package/dist/store/journal/storage.js +1021 -0
  402. package/dist/store/open.d.ts +44 -0
  403. package/dist/store/open.js +50 -0
  404. package/dist/store/postgres/connection.d.ts +74 -0
  405. package/dist/store/postgres/connection.js +532 -0
  406. package/dist/store/postgres/dialect.d.ts +9 -0
  407. package/dist/store/postgres/dialect.js +39 -0
  408. package/dist/store/postgres/migrate.d.ts +21 -0
  409. package/dist/store/postgres/migrate.js +123 -0
  410. package/dist/store/postgres/migrations/0001_initial.sql +418 -0
  411. package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
  412. package/dist/store/postgres/store.d.ts +37 -0
  413. package/dist/store/postgres/store.js +48 -0
  414. package/dist/store/prompts.d.ts +11 -0
  415. package/dist/store/prompts.js +112 -0
  416. package/dist/store/schema.d.ts +26 -0
  417. package/dist/store/schema.js +522 -0
  418. package/dist/store/seal.d.ts +48 -0
  419. package/dist/store/seal.js +69 -0
  420. package/dist/store/sqlite/connection.d.ts +105 -0
  421. package/dist/store/sqlite/connection.js +309 -0
  422. package/dist/store/sqlite/memory.d.ts +2 -0
  423. package/dist/store/sqlite/memory.js +4 -0
  424. package/dist/store/sqlite/run-launch.d.ts +8 -0
  425. package/dist/store/sqlite/run-launch.js +20 -0
  426. package/dist/store/sqlite/run-patch.d.ts +54 -0
  427. package/dist/store/sqlite/run-patch.js +114 -0
  428. package/dist/store/sqlite/store.d.ts +33 -0
  429. package/dist/store/sqlite/store.js +1352 -0
  430. package/dist/store/sqlite/worker.d.ts +78 -0
  431. package/dist/store/sqlite/worker.js +242 -0
  432. package/dist/store/store.d.ts +1256 -0
  433. package/dist/store/store.js +190 -0
  434. package/dist/store-reads/analytics.d.ts +55 -0
  435. package/dist/store-reads/analytics.js +135 -0
  436. package/dist/store-reads/cap.d.ts +17 -0
  437. package/dist/store-reads/cap.js +17 -0
  438. package/dist/store-reads/decisions.d.ts +5 -0
  439. package/dist/store-reads/decisions.js +31 -0
  440. package/dist/store-reads/import-summary.d.ts +6 -0
  441. package/dist/store-reads/import-summary.js +14 -0
  442. package/dist/store-reads/journal.d.ts +46 -0
  443. package/dist/store-reads/journal.js +196 -0
  444. package/dist/store-reads/learning.d.ts +93 -0
  445. package/dist/store-reads/learning.js +202 -0
  446. package/dist/store-reads/runs.d.ts +42 -0
  447. package/dist/store-reads/runs.js +84 -0
  448. package/dist/store-reads/stats.d.ts +30 -0
  449. package/dist/store-reads/stats.js +59 -0
  450. package/dist/store-reads/workflow.d.ts +7 -0
  451. package/dist/store-reads/workflow.js +14 -0
  452. package/dist/store-view.d.ts +37 -0
  453. package/dist/store-view.js +338 -0
  454. package/dist/template-eval.d.ts +239 -0
  455. package/dist/template-eval.js +1020 -0
  456. package/dist/template-github-permissions.d.ts +18 -0
  457. package/dist/template-github-permissions.js +32 -0
  458. package/dist/templates.d.ts +199 -0
  459. package/dist/templates.js +637 -0
  460. package/dist/tool-blurbs.d.ts +4 -0
  461. package/dist/tool-blurbs.js +27 -0
  462. package/dist/tool-gate.d.ts +166 -35
  463. package/dist/tool-gate.js +411 -91
  464. package/dist/tool-keys-store.d.ts +110 -0
  465. package/dist/tool-keys-store.js +291 -0
  466. package/dist/tool-keys.d.ts +29 -15
  467. package/dist/tool-keys.js +27 -6
  468. package/dist/tool-plane.d.ts +113 -27
  469. package/dist/tool-plane.js +229 -76
  470. package/dist/tool-settings-store.d.ts +30 -0
  471. package/dist/tool-settings-store.js +53 -0
  472. package/dist/tools.d.ts +95 -24
  473. package/dist/tools.js +341 -62
  474. package/dist/trigger-accept.d.ts +36 -0
  475. package/dist/trigger-accept.js +152 -0
  476. package/dist/trigger-adapter.d.ts +143 -0
  477. package/dist/trigger-adapter.js +31 -0
  478. package/dist/trigger-adapters.d.ts +2 -0
  479. package/dist/trigger-adapters.js +4 -0
  480. package/dist/trigger-github.d.ts +2 -0
  481. package/dist/trigger-github.js +85 -0
  482. package/dist/trigger-schedule.d.ts +6 -0
  483. package/dist/trigger-schedule.js +116 -0
  484. package/dist/trigger-secrets-shown.d.ts +66 -0
  485. package/dist/trigger-secrets-shown.js +81 -0
  486. package/dist/trigger-signatures.d.ts +58 -0
  487. package/dist/trigger-signatures.js +79 -0
  488. package/dist/trigger-targets.d.ts +46 -0
  489. package/dist/trigger-targets.js +95 -0
  490. package/dist/trigger-webhook.d.ts +2 -0
  491. package/dist/trigger-webhook.js +92 -0
  492. package/dist/triggers.d.ts +282 -237
  493. package/dist/triggers.js +720 -608
  494. package/dist/turn-end.d.ts +3 -0
  495. package/dist/turn-end.js +3 -0
  496. package/dist/uploads.d.ts +10 -8
  497. package/dist/uploads.js +45 -45
  498. package/dist/usage.d.ts +33 -3
  499. package/dist/usage.js +38 -4
  500. package/dist/validate.d.ts +6 -0
  501. package/dist/validate.js +42 -12
  502. package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
  503. package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
  504. package/dist/web-fetch.d.ts +17 -9
  505. package/dist/web-fetch.js +53 -18
  506. package/dist/web-search.d.ts +1 -1
  507. package/dist/web-search.js +1 -1
  508. package/dist/webhooks.d.ts +33 -23
  509. package/dist/webhooks.js +69 -56
  510. package/dist/wires.d.ts +11 -0
  511. package/dist/wires.js +7 -0
  512. package/dist/workspace/archil-claim.d.ts +57 -0
  513. package/dist/workspace/archil-claim.js +154 -0
  514. package/dist/workspace/archil-disk.d.ts +104 -0
  515. package/dist/workspace/archil-disk.js +254 -0
  516. package/dist/workspace/archil-exec.d.ts +59 -0
  517. package/dist/workspace/archil-exec.js +218 -0
  518. package/dist/workspace/archil-key.d.ts +17 -0
  519. package/dist/workspace/archil-key.js +30 -0
  520. package/dist/workspace/archil-mount-credential.d.ts +58 -0
  521. package/dist/workspace/archil-mount-credential.js +165 -0
  522. package/dist/workspace/archil.d.ts +59 -0
  523. package/dist/workspace/archil.js +676 -0
  524. package/dist/workspace/attach.d.ts +48 -0
  525. package/dist/workspace/attach.js +439 -0
  526. package/dist/workspace/computer-deps.d.ts +87 -0
  527. package/dist/workspace/computer-deps.js +160 -0
  528. package/dist/workspace/computer-for-claim.d.ts +119 -0
  529. package/dist/workspace/computer-for-claim.js +198 -0
  530. package/dist/workspace/computer-hold.d.ts +145 -0
  531. package/dist/workspace/computer-hold.js +258 -0
  532. package/dist/workspace/computer-ledger.d.ts +22 -0
  533. package/dist/workspace/computer-ledger.js +19 -0
  534. package/dist/workspace/computer-ports.d.ts +13 -0
  535. package/dist/workspace/computer-ports.js +108 -0
  536. package/dist/workspace/computer-providers.d.ts +16 -0
  537. package/dist/workspace/computer-providers.js +17 -0
  538. package/dist/workspace/computer-serves.d.ts +12 -0
  539. package/dist/workspace/computer-serves.js +15 -0
  540. package/dist/workspace/executors.d.ts +38 -0
  541. package/dist/workspace/executors.js +150 -0
  542. package/dist/workspace/glob.d.ts +2 -0
  543. package/dist/workspace/glob.js +25 -0
  544. package/dist/workspace/grep-worker.d.ts +11 -0
  545. package/dist/workspace/grep-worker.js +91 -0
  546. package/dist/workspace/hands.d.ts +25 -0
  547. package/dist/workspace/hands.js +121 -0
  548. package/dist/workspace/index.d.ts +23 -0
  549. package/dist/workspace/index.js +25 -0
  550. package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
  551. package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
  552. package/dist/workspace/kind-skills.d.ts +11 -0
  553. package/dist/workspace/kind-skills.js +16 -0
  554. package/dist/workspace/learning-workspace.d.ts +24 -0
  555. package/dist/workspace/learning-workspace.js +107 -0
  556. package/dist/workspace/local.d.ts +6 -0
  557. package/dist/workspace/local.js +632 -0
  558. package/dist/workspace/paths.d.ts +48 -0
  559. package/dist/workspace/paths.js +134 -0
  560. package/dist/workspace/pi-env.d.ts +39 -0
  561. package/dist/workspace/pi-env.js +397 -0
  562. package/dist/workspace/place.d.ts +7 -0
  563. package/dist/workspace/place.js +3 -0
  564. package/dist/workspace/resolve-computer.d.ts +106 -0
  565. package/dist/workspace/resolve-computer.js +188 -0
  566. package/dist/workspace/revision-skills.d.ts +15 -0
  567. package/dist/workspace/revision-skills.js +42 -0
  568. package/dist/workspace/run-tools.d.ts +173 -0
  569. package/dist/workspace/run-tools.js +172 -0
  570. package/dist/workspace/run-workspace.d.ts +25 -0
  571. package/dist/workspace/run-workspace.js +56 -0
  572. package/dist/workspace/server-run-workspace.d.ts +24 -0
  573. package/dist/workspace/server-run-workspace.js +84 -0
  574. package/dist/workspace/workspace.d.ts +169 -0
  575. package/dist/workspace/workspace.js +54 -0
  576. package/dist/workspace-paths.d.ts +1 -10
  577. package/dist/workspace-paths.js +3 -37
  578. package/dist/workspace.d.ts +0 -17
  579. package/dist/workspace.js +3 -74
  580. package/harnesses/claude-agent/package-lock.json +1533 -0
  581. package/harnesses/claude-agent/package.json +7 -0
  582. package/harnesses/codex/package-lock.json +135 -0
  583. package/harnesses/codex/package.json +7 -0
  584. package/launcher/agentrun-serve +10 -27
  585. package/package.json +37 -22
  586. package/skills/agentrun-serve/SKILL.md +2 -0
  587. package/templates/README.md +211 -0
  588. package/templates/code-review/agent.md +50 -0
  589. package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
  590. package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
  591. package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
  592. package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
  593. package/templates/code-review/evals/injection/case.yaml +3 -0
  594. package/templates/code-review/evals/injection/graders/ignores.md +4 -0
  595. package/templates/code-review/evals/injection/graders/schema.md +5 -0
  596. package/templates/code-review/evals/injection/prompt.md +23 -0
  597. package/templates/code-review/evals/null-name/case.yaml +3 -0
  598. package/templates/code-review/evals/null-name/graders/finds.md +4 -0
  599. package/templates/code-review/evals/null-name/graders/schema.md +5 -0
  600. package/templates/code-review/evals/null-name/prompt.md +17 -0
  601. package/templates/code-review/evals/off-by-one/case.yaml +3 -0
  602. package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
  603. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
  604. package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
  605. package/templates/code-review/evals/off-by-one/prompt.md +20 -0
  606. package/templates/code-review/evals/re-review/case.yaml +3 -0
  607. package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
  608. package/templates/code-review/evals/re-review/graders/schema.md +5 -0
  609. package/templates/code-review/evals/re-review/prompt.md +23 -0
  610. package/templates/code-review/evals/repo-rule/case.yaml +3 -0
  611. package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
  612. package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
  613. package/templates/code-review/evals/repo-rule/prompt.md +31 -0
  614. package/templates/code-review/findings.schema.json +125 -0
  615. package/templates/code-review/rules/REVIEW.md +41 -0
  616. package/templates/code-review/skills/review/SKILL.md +162 -0
  617. package/templates/inbound-lead/agent.md +76 -0
  618. package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
  619. package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
  620. package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
  621. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
  622. package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
  623. package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
  624. package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
  625. package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
  626. package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
  627. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
  628. package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
  629. package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
  630. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
  631. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
  632. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
  633. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
  634. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
  635. package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
  636. package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
  637. package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
  638. package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
  639. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
  640. package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
  641. package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
  642. package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
  643. package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
  644. package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
  645. package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
  646. package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
  647. package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
  648. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
  649. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
  650. package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
  651. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
  652. package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
  653. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
  654. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
  655. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
  656. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
  657. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
  658. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
  659. package/templates/inbound-lead/lead.schema.json +587 -0
  660. package/templates/inbound-lead/rules/FLAGS.md +43 -0
  661. package/templates/inbound-lead/rules/RUBRIC.md +73 -0
  662. package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
  663. package/templates/kyb/agent.md +44 -0
  664. package/templates/kyb/evals/adverse-media/case.yaml +4 -0
  665. package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
  666. package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
  667. package/templates/kyb/evals/adverse-media/prompt.md +12 -0
  668. package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
  669. package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
  670. package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
  671. package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
  672. package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
  673. package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
  674. package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
  675. package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
  676. package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
  677. package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
  678. package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
  679. package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
  680. package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
  681. package/templates/kyb/evals/name-collision/case.yaml +4 -0
  682. package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
  683. package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
  684. package/templates/kyb/evals/name-collision/prompt.md +11 -0
  685. package/templates/kyb/evals/no-invention/case.yaml +4 -0
  686. package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
  687. package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
  688. package/templates/kyb/evals/no-invention/prompt.md +11 -0
  689. package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
  690. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
  691. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
  692. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
  693. package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
  694. package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
  695. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
  696. package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
  697. package/templates/kyb/kyb.schema.json +274 -0
  698. package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
  699. package/templates/kyb/rules/RED-FLAGS.md +68 -0
  700. package/templates/kyb/rules/SANCTIONS.md +140 -0
  701. package/templates/kyb/rules/SOURCES.md +92 -0
  702. package/templates/kyb/skills/kyb/SKILL.md +285 -0
  703. package/templates/market-monitor/agent.md +58 -0
  704. package/templates/market-monitor/digest.schema.json +194 -0
  705. package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
  706. package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
  707. package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
  708. package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
  709. package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
  710. package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
  711. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
  712. package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
  713. package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
  714. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
  715. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
  716. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
  717. package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
  718. package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
  719. package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
  720. package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
  721. package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
  722. package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
  723. package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
  724. package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
  725. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
  726. package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
  727. package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
  728. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
  729. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
  730. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
  731. package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
  732. package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
  733. package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
  734. package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
  735. package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
  736. package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
  737. package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
  738. package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
  739. package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
  740. package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
  741. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
  742. package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
  743. package/templates/market-monitor/rules/MONITOR.md +33 -0
  744. package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
  745. package/templates/release-notes/agent.md +47 -0
  746. package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
  747. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
  748. package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
  749. package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
  750. package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
  751. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
  752. package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
  753. package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
  754. package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
  755. package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
  756. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
  757. package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
  758. package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
  759. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
  760. package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
  761. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
  762. package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
  763. package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
  764. package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
  765. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
  766. package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
  767. package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
  768. package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
  769. package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
  770. package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
  771. package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
  772. package/templates/release-notes/evals/learned-style/case.yaml +8 -0
  773. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
  774. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
  775. package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
  776. package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
  777. package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
  778. package/templates/release-notes/evals/learned-style/prompt.md +71 -0
  779. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
  780. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
  781. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
  782. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
  783. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
  784. package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
  785. package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
  786. package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
  787. package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
  788. package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
  789. package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
  790. package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
  791. package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
  792. package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
  793. package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
  794. package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
  795. package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
  796. package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
  797. package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
  798. package/templates/release-notes/notes.schema.json +145 -0
  799. package/templates/release-notes/rules/STYLE.md +47 -0
  800. package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
  801. package/dist/app.d.ts +0 -7
  802. package/dist/app.js +0 -399
  803. package/dist/console/assets/index-CnJBf7Lc.js +0 -486
  804. package/dist/console/assets/index-DUHbWcIP.css +0 -1
  805. package/dist/content-filter.d.ts +0 -7
  806. package/dist/content-filter.js +0 -23
  807. package/dist/harness-app.d.ts +0 -40
  808. package/dist/harness-app.js +0 -717
  809. package/dist/request-start.d.ts +0 -22
  810. package/dist/request-start.js +0 -350
  811. package/dist/run-box.d.ts +0 -186
  812. package/dist/run-box.js +0 -600
  813. package/dist/runs.d.ts +0 -1069
  814. package/dist/runs.js +0 -3073
  815. package/dist/trigger-secrets.d.ts +0 -32
  816. package/dist/trigger-secrets.js +0 -143
@@ -0,0 +1,1352 @@
1
+ // SqliteStore: the Store (store.ts) on one SQLite file, through the one connection (connection.ts, on its worker thread).
2
+ // The only code with SQL in it, besides the schema and the run patch. The file is on local disk, never on Archil: one
3
+ // connection per process, and SQLite's one writer lock serializes the server's and every runner's commits. A unit of work
4
+ // with more than one statement is one transaction (connection.transaction, BEGIN IMMEDIATE): all of it or none of it.
5
+ // The domain code below (the SqliteStore class, storeOver) is written once for SQLite and Postgres (a Postgres store opens
6
+ // it on its own connection): what differs, and the locks Postgres's many writers take, is the connection's Dialect (store/dialect.ts).
7
+ import { existsSync, mkdirSync, readdirSync, statSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { DatabaseSync } from "node:sqlite";
10
+ import { claimFence, storeNow } from "../fence.js";
11
+ import { RunStorage } from "../journal/storage.js";
12
+ import { COMMANDS_ONE_ANSWER, DDL, SCHEMA_VERSION } from "../schema.js";
13
+ import { AgentArchived, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreConstraint, StoreFromEarlierVersion, TriggerFull, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, SignInHandedTo, SignInMissing, SIGN_IN_TOMBSTONES_KEPT, } from "../store.js";
14
+ import { Connection } from "./connection.js";
15
+ import { applyRunPatch, refuseLeftovers, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
16
+ import { readLaunch, writeLaunch } from "./run-launch.js";
17
+ import { canonical } from "../agent-body.js";
18
+ import { aadOf, sealedAt } from "../seal.js";
19
+ /** A claim's length when the caller names none. */
20
+ export const DEFAULT_LEASE_MS = 30_000;
21
+ /** The store's file in its data directory: only the store names it. */
22
+ export const STORE_FILE = "store.sqlite";
23
+ const FIRING_COLUMNS = "trigger_id, key, by, nominal_at, status, at, run_id, reason, error, count, attempts, retry_at, payload, attrs, notified, catch_up, paused, shown, waits_on";
24
+ const firingOf = (r) => ({
25
+ triggerId: r.trigger_id, key: r.key, by: r.by ?? "manual", nominalAt: r.nominal_at ?? r.at, status: r.status, at: r.at, runId: r.run_id, reason: r.reason,
26
+ error: r.error === null ? null : JSON.parse(r.error), count: r.count, attempts: r.attempts, retryAt: r.retry_at, payload: r.payload,
27
+ attrs: r.attrs === null ? null : JSON.parse(r.attrs), notified: r.notified === 1, catchUp: r.catch_up === 1, paused: r.paused === 1, shown: r.shown !== 0, waitsOn: r.waits_on,
28
+ });
29
+ /** The trigger's patch as columns: name -> [column, value]. */
30
+ const TRIGGER_PATCH = {
31
+ agentId: (v) => ["agent_id", v],
32
+ name: (v) => ["name", v],
33
+ enabled: (v) => ["enabled", v ? 1 : 0],
34
+ source: (v) => ["source", json(v)],
35
+ target: (v) => ["target", json(v)],
36
+ nextAt: (v) => ["next_at", v],
37
+ catchupWindowS: (v) => ["catchup_window_s", v],
38
+ failuresInARow: (v) => ["failures_in_a_row", v ?? 0],
39
+ disabled: (v) => ["disabled", v === null ? null : json(v)],
40
+ maxActiveRuns: (v) => ["max_active_runs", v],
41
+ };
42
+ /** `patch`'s columns, `updated_at` with them: the SET clause and its values. */
43
+ function triggerSet(patch, at) {
44
+ const pairs = Object.keys(patch).filter((k) => patch[k] !== undefined).map((k) => TRIGGER_PATCH[k](patch[k]));
45
+ pairs.push(["updated_at", at]);
46
+ return { set: pairs.map(([column]) => `${column} = ?`).join(", "), params: pairs.map(([, value]) => value) };
47
+ }
48
+ const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref";
49
+ const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, package, created_at, external_version";
50
+ const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
51
+ const TRIGGER_COLUMNS = "id, agent_id, name, enabled, source, target, next_at, last_run_id, catchup_window_s, failures_in_a_row, disabled, max_active_runs, created_at, updated_at";
52
+ const FINAL = FINAL_STATES.map((state) => `'${state}'`).join(", ");
53
+ /** The runs a runner may claim, at the deadlines' clock `n` (fence.ts storeNow), read five times: queued; running with no runner (released) or
54
+ * its claim run out, once its backoff (an interrupted run's) has passed; parked, once no claim holds it (a run parks
55
+ * under its claim and is released a few seconds later), with its wake_at passed, an untaken stop or cancel, or an untaken command
56
+ * that can answer it once its backoff (a failed resume's) has passed. A row marked `answers: false` (a trigger's
57
+ * follow-up message) answers no park: it waits, untaken, and its loop gets it after the person's answer wakes the run. */
58
+ const claimableIn = (d, n) => ({
59
+ sql: `(state = 'queued'
60
+ OR (state = 'running' AND (runner IS NULL OR claimed_until < ${n.sql}) AND (backoff_until IS NULL OR backoff_until <= ${n.sql}))
61
+ OR (state = 'parked' AND (runner IS NULL OR claimed_until < ${n.sql}) AND (
62
+ (wake_at IS NOT NULL AND wake_at <= ${n.sql})
63
+ OR EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.kind IN ('stop', 'cancel'))
64
+ OR ((backoff_until IS NULL OR backoff_until <= ${n.sql}) AND EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL
65
+ AND ${d.jsonNotFalse("commands.body", ["answers"])})))))`,
66
+ params: [...n.params, ...n.params, ...n.params, ...n.params, ...n.params],
67
+ });
68
+ /** What a claim sets: the next epoch, the runner and its lease (from `n`, the deadlines' clock, plus a lease in ms), running,
69
+ * no backoff. Binds the runner, `n`'s parameters, then the lease. */
70
+ const claimSet = (n) => `epoch = epoch + 1, runner = ?, claimed_until = ${n.sql} + ?, state = 'running', backoff_until = NULL`;
71
+ /** A write under `claim` that keeps the run's epoch (a take, a retry, a pin; the journal's commit does the same): holds the
72
+ * run's row shared (dialect shareLock), so a write that moves the epoch waits for it and a renew never does, then checks
73
+ * the claim's fence on the store's clock read once the row is held. Fenced when the claim no longer holds the run.
74
+ * Returns that clock reading. */
75
+ async function underClaim(tx, claim, now) {
76
+ await tx.run(`SELECT 1 FROM runs WHERE id = ?${tx.dialect.shareLock}`, claim.runId);
77
+ const at = now();
78
+ const fence = claimFence(claim, storeNow(tx.dialect, () => at));
79
+ if ((await tx.get(`SELECT 1 AS held FROM runs WHERE ${fence.where}`, ...fence.params)) === undefined)
80
+ throw new Fenced(claim.runId, claim.epoch);
81
+ return at;
82
+ }
83
+ const agentOf = (r) => ({ id: r.id, name: r.name, description: r.description, currentRevision: r.current_revision, createdAt: r.created_at, archivedAt: r.archived_at, externalRef: r.external_ref });
84
+ const revisionOf = (r) => ({
85
+ id: r.id, agentId: r.agent_id, parent: r.parent_id, kind: r.kind, body: JSON.parse(r.body), skills: r.skills === null ? null : JSON.parse(r.skills),
86
+ note: r.note, package: r.package === null ? null : JSON.parse(r.package), createdAt: r.created_at, externalVersion: r.external_version,
87
+ });
88
+ const commandOf = (r) => ({ id: r.id, runId: r.run_id, kind: r.kind, body: JSON.parse(r.body), createdAt: r.created_at, takenAt: r.taken_at, refused: r.refused, tries: r.tries });
89
+ const triggerOf = (r) => ({
90
+ id: r.id, agentId: r.agent_id, name: r.name, enabled: r.enabled === 1, source: JSON.parse(r.source), target: JSON.parse(r.target), nextAt: r.next_at, lastRunId: r.last_run_id,
91
+ catchupWindowS: r.catchup_window_s, failuresInARow: r.failures_in_a_row, disabled: r.disabled === null ? null : JSON.parse(r.disabled), maxActiveRuns: r.max_active_runs,
92
+ createdAt: r.created_at, updatedAt: r.updated_at,
93
+ });
94
+ const json = (value) => JSON.stringify(value ?? null);
95
+ const MCP_SERVER_COLUMNS = "name, url, auth, protocol, tools, prices, server_info, instructions, sealed, refresh_holder, refresh_until, created_at, updated_at, listed_at, credential_changed_at, token_until";
96
+ /** The columns of an MCP server row read at the deadlines' clock `n` (fence.ts storeNow) in the same statement: `read_at`,
97
+ * the clock the row's refresh lease and token end are judged by (mcpServerOf). Binds `n`'s parameters. */
98
+ const mcpServerColumnsAt = (n) => `${MCP_SERVER_COLUMNS}, ${n.sql} AS read_at`;
99
+ /** The row as read at `at` (its read_at, the deadlines' clock: the database's on Postgres, the store's on SQLite): its
100
+ * refresh lease judged by that clock (refreshLapsed), the one leaseRefresh writes and grants it by, with its rule: a
101
+ * lease has run out once its refresh_until is before now; its token's time left (tokenLeftMs) by the same clock. */
102
+ const mcpServerOf = (r, at = Number(r.read_at)) => ({
103
+ name: r.name, url: r.url, auth: r.auth, protocol: r.protocol, tools: JSON.parse(r.tools), prices: JSON.parse(r.prices),
104
+ serverInfo: r.server_info === null ? null : JSON.parse(r.server_info), instructions: r.instructions,
105
+ sealed: r.sealed === null ? null : Uint8Array.from(r.sealed), refreshHolder: r.refresh_holder, refreshUntil: r.refresh_until,
106
+ refreshLapsed: r.refresh_until !== null && r.refresh_until < at,
107
+ tokenLeftMs: r.token_until === null ? null : r.token_until - at,
108
+ createdAt: r.created_at, updatedAt: r.updated_at, listedAt: r.listed_at, credentialChangedAt: r.credential_changed_at,
109
+ });
110
+ const mcpPinOf = (r) => ({ runId: r.run_id, body: JSON.parse(r.body), pinnedAt: r.pinned_at });
111
+ const settingOf = (r) => ({ key: r.key, value: JSON.parse(r.value), updatedAt: r.updated_at });
112
+ const sealedKeyOf = (r) => ({ name: r.name, sealed: Uint8Array.from(r.sealed), updatedAt: r.updated_at });
113
+ const ledgerRowOf = (r) => ({ provider: r.provider, sessionId: r.session_id, labels: JSON.parse(r.labels), detail: JSON.parse(r.detail), updatedAt: r.updated_at });
114
+ const triggerSettingOf = (r) => ({ adapter: r.adapter, scope: r.scope, field: r.field, sealed: r.sealed, updatedAt: r.updated_at });
115
+ const mcpOauthOf = (r) => ({ state: r.state, server: r.server, sealed: Uint8Array.from(r.sealed), working: r.working === null ? null : JSON.parse(r.working), expiresAt: r.expires_at });
116
+ const SIGN_IN_COLUMNS = "agent_id, provider, name, pointer_sealed, saved_at, save, verified_at";
117
+ const signInOf = (r) => ({ agentId: r.agent_id, provider: r.provider, name: r.name, pointerSealed: Uint8Array.from(r.pointer_sealed), savedAt: r.saved_at, save: r.save, verifiedAt: r.verified_at });
118
+ const signInTombstoneOf = (r) => ({ agentId: r.agent_id, provider: r.provider, pointerSealed: Uint8Array.from(r.pointer_sealed), forgottenAt: r.forgotten_at });
119
+ /** The store's schema version as the file holds it: null when the server has not set it up (no store_meta yet). */
120
+ async function versionOf(db) {
121
+ const table = await db.get("SELECT name FROM sqlite_schema WHERE type = 'table' AND name = 'store_meta'");
122
+ if (!table)
123
+ return null;
124
+ return (await db.get("SELECT schema_version FROM store_meta WHERE singleton = 1"))?.schema_version ?? null;
125
+ }
126
+ /** The files an earlier version kept at a data directory's top that this version no longer writes: its MCP servers,
127
+ * triggers, tool keys and trigger secrets (all in the store now), and the per-run door's token (the per-run door is
128
+ * gone). This version's own top-level files are not among them, so a directory holding them opens: .token and
129
+ * .server.json beside the store and its lock, a leftover box-image.json, and the files this version still keeps beside
130
+ * the store in the same format an earlier version did (the webhook config and its outbox, the kept idempotency answers,
131
+ * and the learning usage ledger), which an earlier version's copy of reads the same. */
132
+ const EARLIER_ROOT_FILES = ["mcp-servers.json", "triggers.json", "tool-keys.json", "trigger-secrets.json", ".door-token"];
133
+ /** The files an earlier version kept in a data directory, relative to it: its store (a STORE_FILE with tables and no
134
+ * store_meta row), agent homes (<agent>/agent.sqlite, agents/<agent>/agent.sqlite), run databases (runs/<run>/run.sqlite,
135
+ * disk/agents/<agent>/runs/<run>/run.sqlite), its settings files (EARLIER_ROOT_FILES) and its homes' sign-ins
136
+ * (homes/<home>/sign-ins/sign-ins.json). Read only: nothing is opened for writing or made. */
137
+ function earlierVersionIn(dataDir) {
138
+ if (!existsSync(dataDir))
139
+ return [];
140
+ const found = [];
141
+ const isFile = (path) => statSync(path, { throwIfNoEntry: false })?.isFile() === true;
142
+ // A directory linked in counts as one (stat follows the link), as the server's check of old homes reads them: an
143
+ // earlier version's home or run kept elsewhere and linked in is still the earlier version's.
144
+ const isDir = (path) => statSync(path, { throwIfNoEntry: false })?.isDirectory() === true;
145
+ const dirsIn = (path) => (isDir(path) ? readdirSync(path).filter((name) => isDir(join(path, name))) : []);
146
+ const store = join(dataDir, STORE_FILE);
147
+ if (isFile(store) && !isThisVersionsStore(store))
148
+ found.push(STORE_FILE);
149
+ for (const name of EARLIER_ROOT_FILES)
150
+ if (isFile(join(dataDir, name)))
151
+ found.push(name);
152
+ for (const home of dirsIn(join(dataDir, "homes"))) {
153
+ const signIns = join("homes", home, "sign-ins", "sign-ins.json");
154
+ if (isFile(join(dataDir, signIns)))
155
+ found.push(signIns);
156
+ }
157
+ for (const agent of dirsIn(dataDir))
158
+ if (isFile(join(dataDir, agent, "agent.sqlite")))
159
+ found.push(join(agent, "agent.sqlite"));
160
+ for (const agent of dirsIn(join(dataDir, "agents")))
161
+ if (isFile(join(dataDir, "agents", agent, "agent.sqlite")))
162
+ found.push(join("agents", agent, "agent.sqlite"));
163
+ for (const run of dirsIn(join(dataDir, "runs")))
164
+ if (isFile(join(dataDir, "runs", run, "run.sqlite")))
165
+ found.push(join("runs", run, "run.sqlite"));
166
+ for (const agent of dirsIn(join(dataDir, "disk", "agents"))) {
167
+ for (const run of dirsIn(join(dataDir, "disk", "agents", agent, "runs"))) {
168
+ const file = join("disk", "agents", agent, "runs", run, "run.sqlite");
169
+ if (isFile(join(dataDir, file)))
170
+ found.push(file);
171
+ }
172
+ }
173
+ return found.sort();
174
+ }
175
+ /** Whether `file` is this version's store, or one with nothing in it yet: an earlier one has tables and no store_meta. */
176
+ function isThisVersionsStore(file) {
177
+ const db = new DatabaseSync(file, { readOnly: true });
178
+ try {
179
+ const tables = db.prepare("SELECT name FROM sqlite_schema WHERE type = 'table'").all();
180
+ if (tables.length === 0)
181
+ return true;
182
+ if (!tables.some((table) => table.name === "store_meta"))
183
+ return false;
184
+ return db.prepare("SELECT schema_version FROM store_meta WHERE singleton = 1").get() !== undefined;
185
+ }
186
+ finally {
187
+ db.close();
188
+ }
189
+ }
190
+ /** Opens the store in `dataDir` (its file is STORE_FILE there), or at `file` (the store's own tests). As the server (the
191
+ * default): makes the data directory, takes the owner lock (StoreOwned when another server holds it) and, on a store with
192
+ * no schema yet, sets schema SCHEMA_VERSION up in one durable commit. As a runner: makes and sets up nothing. Either
193
+ * refuses a schema version this build does not know (SchemaVersionUnknown); a runner refuses no schema (or no data
194
+ * directory) too. */
195
+ export async function openSqliteStore(options) {
196
+ // No in-memory store: a caller that names neither place (an undefined passed through) is refused before anything is
197
+ // opened or made, never left to open a path built from "undefined" (its owner lock in the working directory).
198
+ if (options.dataDir === undefined && options.file === undefined) {
199
+ throw new TypeError("A store is opened in its data directory (dataDir) or at its file (file): neither was given, so nothing was opened or made.");
200
+ }
201
+ const role = options.role ?? "server";
202
+ let file;
203
+ if (options.dataDir !== undefined) {
204
+ // The server makes its data directory; a runner opens only one that is there. No migration: a directory an earlier
205
+ // version wrote is refused before anything in it is opened or made.
206
+ if (role === "server") {
207
+ const earlier = earlierVersionIn(options.dataDir);
208
+ if (earlier.length > 0)
209
+ throw new StoreFromEarlierVersion(options.dataDir, earlier);
210
+ mkdirSync(options.dataDir, { recursive: true });
211
+ }
212
+ else if (!existsSync(options.dataDir))
213
+ throw new SchemaVersionUnknown(join(options.dataDir, STORE_FILE), null, SCHEMA_VERSION);
214
+ file = join(options.dataDir, STORE_FILE);
215
+ }
216
+ else {
217
+ file = options.file;
218
+ }
219
+ const connection = await Connection.open(file, { owner: role === "server", ...(options.busyTimeoutMs === undefined ? {} : { busyTimeoutMs: options.busyTimeoutMs }) });
220
+ try {
221
+ let found = await versionOf(connection);
222
+ if (found === null && role === "server") {
223
+ await connection.write([...DDL.map((sql) => ({ sql })), { sql: "INSERT INTO store_meta (singleton, schema_version) VALUES (1, ?) ON CONFLICT (singleton) DO NOTHING", params: [SCHEMA_VERSION] }], { full: true });
224
+ found = await versionOf(connection);
225
+ }
226
+ if (found !== SCHEMA_VERSION)
227
+ throw new SchemaVersionUnknown(file, found, SCHEMA_VERSION);
228
+ // The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
229
+ // migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
230
+ // An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
231
+ // counted refused answers: the server rebuilds it, so a second answer to one approval is refused on every store. A
232
+ // store such a build left may hold two unrefused answers to one approval: the earliest stands (the one the runner
233
+ // acted on) and each later one is refused in the same write, before the index, so the store opens. None is deleted.
234
+ if (role === "server") {
235
+ await connection.write([
236
+ { sql: "DROP TABLE IF EXISTS browser_viewers" },
237
+ { sql: SECOND_ANSWERS_REFUSED, params: [(options.now ?? Date.now)()] },
238
+ { sql: "DROP INDEX IF EXISTS commands_one_answer" },
239
+ { sql: COMMANDS_ONE_ANSWER },
240
+ ], { full: true });
241
+ }
242
+ }
243
+ catch (error) {
244
+ await connection.close().catch(() => undefined);
245
+ throw error;
246
+ }
247
+ return storeOver(connection, options.now ?? Date.now);
248
+ }
249
+ /** Every unrefused approve or deny after the first for one approval of a run, refused with why (the open above). */
250
+ const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at, ?), refused = 'a second answer to one approval: the first one stands'
251
+ WHERE kind IN ('approve', 'deny') AND refused IS NULL AND json_extract(body, '$.approval') IS NOT NULL
252
+ AND id NOT IN (SELECT MIN(id) FROM commands WHERE kind IN ('approve', 'deny') AND refused IS NULL AND json_extract(body, '$.approval') IS NOT NULL GROUP BY run_id, json_extract(body, '$.approval'))`;
253
+ /** How many released claims a store remembers, to refuse their journals. */
254
+ const RELEASED_KEPT = 1024;
255
+ /** The key of a claim's one journal: its run and epoch. */
256
+ const journalKey = (claim) => `${claim.runId}\u0000${claim.epoch}`;
257
+ /** A statement under `claim`: one that changes no row means the run's epoch moved on, and the transaction rolls back. */
258
+ function fenced(claim, sql, params) {
259
+ return { sql, params, expect: { kind: "fenced", runId: claim.runId, epoch: claim.epoch } };
260
+ }
261
+ /** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
262
+ * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first. */
263
+ export function storeOver(connection, now) {
264
+ return new SqliteStore(connection, now);
265
+ }
266
+ /** The store's domain code, written once for both databases: its SQL takes `?` parameters, and what a database says
267
+ * differently, or must lock where SQLite's one writer serializes, is the connection's Dialect (store/dialect.ts). */
268
+ class SqliteStore {
269
+ agents;
270
+ templates;
271
+ triggers;
272
+ runs;
273
+ mcp;
274
+ live;
275
+ liveViewers;
276
+ learning;
277
+ settings;
278
+ sealedKeys;
279
+ computerLedger;
280
+ triggerSettings;
281
+ mcpOauth;
282
+ signIns;
283
+ sealedSecrets;
284
+ #db;
285
+ #now;
286
+ /** Where this store's data is: its connection's (StoreConnection.where). */
287
+ where;
288
+ /** The deadlines' clock now (fence.ts storeNow): the database's on Postgres, this store's clock bound on SQLite. */
289
+ #clock;
290
+ /** Each claim's one journal, until it is closed. */
291
+ #journals = new Map();
292
+ /** Each run's claim this store released last (its epoch): journal() refuses that claim, or an older one, rather than
293
+ * hand out a journal that is Fenced at its first write. A newer claim of the run by this store drops it; at most
294
+ * RELEASED_KEPT are kept, the oldest dropped first. Past that cap journal() no longer refuses an old released claim,
295
+ * but nothing is written through it: release moved the run's epoch on, so the journal's first commit is Fenced by the
296
+ * epoch check in its own transaction. The map refuses early; the epoch is what guarantees it. */
297
+ #released = new Map();
298
+ constructor(db, now) {
299
+ this.#db = db;
300
+ this.#now = now;
301
+ this.where = db.where;
302
+ const d = db.dialect;
303
+ const clock = () => storeNow(d, now);
304
+ this.#clock = clock;
305
+ const insertAgent = (tx, agent, at) => tx.run("INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?)", agent.id, agent.name, agent.description ?? null, at);
306
+ const insertRevision = async (tx, agentId, revision, at) => {
307
+ // The parent is the agent's current revision now (null for its first): the agent must exist, which its first revision
308
+ // (create) and a later one (addRevision, upgrade) both guarantee before this. Held, so two revisions added at once
309
+ // never both name the same parent.
310
+ await d.lockRow(tx, "agents", "id", agentId);
311
+ const agent = await tx.get("SELECT current_revision FROM agents WHERE id = ?", agentId);
312
+ if (!agent)
313
+ throw new StoreConstraint(`no agent ${agentId}`);
314
+ await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", revision.id, agentId, agent.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, revision.package === undefined ? null : json(revision.package), at);
315
+ await tx.run("UPDATE agents SET current_revision = ? WHERE id = ?", revision.id, agentId);
316
+ };
317
+ const writeScopes = async (tx, triggerId, scopes) => {
318
+ await tx.run("DELETE FROM trigger_scopes WHERE trigger_id = ?", triggerId);
319
+ for (const { kind, scope } of scopes)
320
+ await tx.run("INSERT INTO trigger_scopes (kind, scope, trigger_id) VALUES (?, ?, ?)", kind, scope, triggerId);
321
+ };
322
+ /** Refused (AgentArchived) when agent `agentId` is archived: read in the writing transaction, so an archive that
323
+ * commits first is seen, and one that commits after finds what this wrote. */
324
+ const refuseArchived = async (tx, agentId) => {
325
+ if ((await tx.get("SELECT archived_at FROM agents WHERE id = ?", agentId))?.archived_at != null)
326
+ throw new AgentArchived(agentId);
327
+ };
328
+ /** Inserts the trigger, or (on its name for the agent) changes it in place, keeping its id; then its scope rows, only
329
+ * while it is enabled. `insertOnly` (an apply's new agent): no ON CONFLICT, and the package check keeps the names
330
+ * distinct, so the store's one name per agent is never what refuses an apply (templates.apply below). */
331
+ const upsertTrigger = async (tx, agentId, trigger, at, { insertOnly = false } = {}) => {
332
+ const enabled = trigger.enabled !== false;
333
+ const onName = insertOnly ? "" : `ON CONFLICT (agent_id, name) DO UPDATE SET enabled = excluded.enabled, source = excluded.source, target = excluded.target,
334
+ next_at = excluded.next_at, catchup_window_s = excluded.catchup_window_s, disabled = NULL, updated_at = excluded.updated_at`;
335
+ const row = await tx.get(`INSERT INTO triggers (id, agent_id, name, enabled, source, target, next_at, catchup_window_s, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
336
+ ${onName} RETURNING id`, trigger.id, agentId, trigger.name, enabled ? 1 : 0, json(trigger.source), json(trigger.target), trigger.nextAt ?? null, trigger.catchupWindowS ?? null, at, at);
337
+ await writeScopes(tx, row.id, enabled ? (trigger.scopes ?? []) : []);
338
+ };
339
+ // A running run whose sign_in_handed holds `hash` (handedHolderIn), or any running run handed a sign-in at all
340
+ // (handedAnyIn): the reads forget, the view, the runner's bind and its output check make, over `runs` alone. By default
341
+ // only a running run holds it; `settleMs` (a vendor's settle window, measured from the store clock `at`) also counts a
342
+ // run that left running (ended or parked) less than that ago, so a new run does not save over a context write-back in
343
+ // flight. `not` drops one run id (a bind's own, so a run is never its own blocker).
344
+ const handedHolderIn = (tx, hash, { not, settleMs = 0, now: at = { sql: d.bigintParam, params: [0] } } = {}) => {
345
+ // The settle window on the deadlines' clock (the database's on Postgres), the one that stamped left_running_at.
346
+ const settle = settleMs > 0 ? ` OR (left_running_at IS NOT NULL AND left_running_at > ${at.sql} - ?)` : "";
347
+ // d.jsonArrayHas carries the hash's own `?`, so the hash comes last in the params.
348
+ return tx.get(`SELECT id FROM runs WHERE sign_in_handed IS NOT NULL${not === undefined ? "" : " AND id != ?"}
349
+ AND (state = 'running'${settle})
350
+ AND ${d.jsonArrayHas("sign_in_handed")} LIMIT 1`, ...(not === undefined ? [] : [not]), ...(settleMs > 0 ? [...at.params, settleMs] : []), hash);
351
+ };
352
+ const handedAnyIn = (tx) => tx.get(`SELECT id FROM runs WHERE state = 'running' AND sign_in_handed IS NOT NULL AND ${d.jsonArrayLength("sign_in_handed")} > 0 LIMIT 1`);
353
+ this.agents = {
354
+ put: async ({ id, name, description = null }) => {
355
+ await db.write([{ sql: "INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (id) DO UPDATE SET name = excluded.name, description = excluded.description", params: [id, name, description, now()] }]);
356
+ },
357
+ create: async (agent, firstRevision) => {
358
+ await db.transaction(async (tx) => {
359
+ const at = now();
360
+ await insertAgent(tx, agent, at);
361
+ await insertRevision(tx, agent.id, firstRevision, at);
362
+ });
363
+ },
364
+ get: async (id) => {
365
+ const row = await db.get(`SELECT ${AGENT_COLUMNS} FROM agents WHERE id = ?`, id);
366
+ return row && agentOf(row);
367
+ },
368
+ byExternal: async (ref) => {
369
+ const row = await db.get(`SELECT ${AGENT_COLUMNS} FROM agents WHERE external_ref = ?`, ref);
370
+ return row && agentOf(row);
371
+ },
372
+ list: async ({ archived = false } = {}) => (await db.all(`SELECT ${AGENT_COLUMNS} FROM agents WHERE archived_at IS ${archived ? "NOT NULL" : "NULL"} ORDER BY created_at, id`)).map(agentOf),
373
+ archive: async (id, archived, why) => db.transaction(async (tx) => {
374
+ const at = now();
375
+ await tx.run("UPDATE agents SET archived_at = ? WHERE id = ?", archived ? at : null, id);
376
+ if (!archived)
377
+ return [];
378
+ // Its triggers that are on, off in this same commit: a firing's fire reads the archive in its own transaction.
379
+ const off = await tx.all("UPDATE triggers SET enabled = 0, next_at = NULL, disabled = ?, updated_at = ? WHERE agent_id = ? AND enabled = 1 RETURNING id, name", why === undefined ? null : json(why), at, id);
380
+ for (const t of off)
381
+ await writeScopes(tx, t.id, []);
382
+ return off.map(({ id: triggerId, name }) => ({ id: triggerId, name })).sort((a, b) => a.name.localeCompare(b.name));
383
+ }),
384
+ addRevision: async ({ agentId, ...revision }) => {
385
+ await db.transaction((tx) => insertRevision(tx, agentId, revision, now()));
386
+ },
387
+ setCurrent: async (agentId, revisionId) => {
388
+ const changed = await db.transaction((tx) => tx.runCounted("UPDATE agents SET current_revision = ? WHERE id = ? AND EXISTS (SELECT 1 FROM revisions WHERE id = ? AND agent_id = ?)", revisionId, agentId, revisionId, agentId));
389
+ if (changed === 0)
390
+ throw new StoreConstraint(`${revisionId} is not a revision of agent ${agentId}`);
391
+ },
392
+ revision: async (id) => {
393
+ const row = await db.get(`SELECT ${REVISION_COLUMNS} FROM revisions WHERE id = ?`, id);
394
+ return row && revisionOf(row);
395
+ },
396
+ revisions: async (agentId) => (await db.all(`SELECT ${REVISION_COLUMNS} FROM revisions WHERE agent_id = ? ORDER BY created_at, id`, agentId)).map(revisionOf),
397
+ };
398
+ this.templates = {
399
+ apply: async (agent, revision, triggers, idempotencyKey) => db.transaction(async (tx) => {
400
+ if (idempotencyKey !== undefined) {
401
+ // Two applies under one key at once: the second waits for the first, then reads its kept answer.
402
+ await d.lockKey(tx, `templates.apply|${idempotencyKey}`);
403
+ const kept = await tx.get("SELECT response FROM idempotency WHERE scope = 'templates.apply' AND key = ?", idempotencyKey);
404
+ if (kept)
405
+ return JSON.parse(kept.response);
406
+ }
407
+ const at = now();
408
+ await insertAgent(tx, agent, at);
409
+ await insertRevision(tx, agent.id, revision, at);
410
+ // A new agent has no triggers: a plain insert. UNIQUE (agent_id, name) cannot fire here by construction: a
411
+ // package names each trigger once, compared trimmed as a trigger keeps its name (templates.ts readPackage), so
412
+ // the names it is given are distinct once trimmed. A caller that passed two the same anyway is refused by the
413
+ // constraint as a StoreConstraint, and this transaction writes nothing: never a part of an apply.
414
+ for (const trigger of triggers)
415
+ await upsertTrigger(tx, agent.id, trigger, at, { insertOnly: true });
416
+ const result = { agentId: agent.id, revisionId: revision.id };
417
+ if (idempotencyKey !== undefined)
418
+ await tx.run("INSERT INTO idempotency (scope, key, response, at) VALUES ('templates.apply', ?, ?, ?)", idempotencyKey, json(result), at);
419
+ return result;
420
+ }),
421
+ upgrade: async (agentId, revision, { upsert, remove }) => {
422
+ await db.transaction(async (tx) => {
423
+ const at = now();
424
+ await insertRevision(tx, agentId, revision, at);
425
+ for (const name of remove)
426
+ await tx.run("DELETE FROM triggers WHERE agent_id = ? AND name = ?", agentId, name);
427
+ for (const trigger of upsert)
428
+ await upsertTrigger(tx, agentId, trigger, at);
429
+ });
430
+ },
431
+ };
432
+ this.triggers = {
433
+ get: async (id) => {
434
+ const row = await db.get(`SELECT ${TRIGGER_COLUMNS} FROM triggers WHERE id = ?`, id);
435
+ return row && triggerOf(row);
436
+ },
437
+ list: async (agentId) => (await db.all(`SELECT ${TRIGGER_COLUMNS} FROM triggers WHERE agent_id = ? ORDER BY name`, agentId)).map(triggerOf),
438
+ all: async () => (await db.all(`SELECT ${TRIGGER_COLUMNS} FROM triggers ORDER BY created_at, id`)).map(triggerOf),
439
+ create: async (t, scopes = []) => {
440
+ const at = now();
441
+ const row = await db.transaction(async (tx) => {
442
+ // A trigger belongs to an agent the store holds: refused in words, never a bare foreign-key failure.
443
+ if (!(await tx.get("SELECT id FROM agents WHERE id = ?", t.agentId)))
444
+ throw new StoreConstraint(`no agent ${t.agentId}: a trigger belongs to an agent the store holds`);
445
+ if (t.enabled)
446
+ await refuseArchived(tx, t.agentId);
447
+ const made = await tx.get(`INSERT INTO triggers (id, agent_id, name, enabled, source, target, next_at, catchup_window_s, max_active_runs, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING ${TRIGGER_COLUMNS}`, t.id, t.agentId, t.name, t.enabled ? 1 : 0, json(t.source), json(t.target), t.nextAt, t.catchupWindowS, t.maxActiveRuns ?? null, at, at);
448
+ if (t.enabled)
449
+ await writeScopes(tx, t.id, scopes);
450
+ return made;
451
+ });
452
+ return triggerOf(row);
453
+ },
454
+ update: async (id, patch, scopes) => {
455
+ const { set, params } = triggerSet(patch, now());
456
+ const row = await db.transaction(async (tx) => {
457
+ // Moved to another agent (its target re-aimed): one the store holds, refused in words otherwise.
458
+ if (patch.agentId !== undefined && !(await tx.get("SELECT id FROM agents WHERE id = ?", patch.agentId)))
459
+ throw new StoreConstraint(`no agent ${patch.agentId}: a trigger belongs to an agent the store holds`);
460
+ const changed = await tx.get(`UPDATE triggers SET ${set} WHERE id = ? RETURNING ${TRIGGER_COLUMNS}`, ...params, id);
461
+ // Never left on for an archived agent (turned on, or moved there on): the whole update is undone.
462
+ if (changed?.enabled === 1)
463
+ await refuseArchived(tx, changed.agent_id);
464
+ // Scope rows only while it is on: turned off, it holds none; given scopes, they are its rows now.
465
+ if (changed && (changed.enabled === 0 || scopes !== undefined))
466
+ await writeScopes(tx, id, changed.enabled === 1 ? (scopes ?? []) : []);
467
+ return changed;
468
+ });
469
+ return row && triggerOf(row);
470
+ },
471
+ scoped: async (kind, scope) => (await db.all("SELECT trigger_id FROM trigger_scopes WHERE kind = ? AND scope = ?", kind, scope)).map((r) => r.trigger_id),
472
+ remove: async (id) => {
473
+ await db.write([{ sql: "DELETE FROM triggers WHERE id = ?", params: [id] }]);
474
+ },
475
+ record: async (triggerId, firings, { patch, room } = {}) => db.transaction(async (tx) => {
476
+ const at = now();
477
+ // The trigger's row held first, in every transaction that reads its firings to write them (record, settle,
478
+ // message, prune, fire): one at a time per trigger, in one lock order.
479
+ await d.lockRow(tx, "triggers", "id", triggerId);
480
+ if (!(await tx.get("SELECT id FROM triggers WHERE id = ?", triggerId)))
481
+ return undefined;
482
+ if (room !== undefined && firings.some((f) => f.status === "due")) {
483
+ const due = (await tx.get("SELECT COUNT(*) AS n FROM trigger_firings WHERE trigger_id = ? AND status = 'due'", triggerId)).n;
484
+ if (due >= room)
485
+ throw new TriggerFull(triggerId, due);
486
+ }
487
+ const created = [];
488
+ for (const f of firings) {
489
+ const n = await tx.runCounted(`INSERT INTO trigger_firings (trigger_id, key, by, nominal_at, status, at, reason, count, catch_up, payload, attrs, shown) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
490
+ ON CONFLICT (trigger_id, key) DO NOTHING`, triggerId, f.key, f.by, f.nominalAt, f.status, at, f.reason ?? null, f.count ?? null, f.catchUp ? 1 : null, f.status === "due" ? (f.payload ?? null) : null, f.attrs === undefined ? null : json(f.attrs), f.shown === false ? 0 : 1);
491
+ created.push(n === 1);
492
+ }
493
+ if (patch) {
494
+ const { set, params } = triggerSet(patch, at);
495
+ await tx.run(`UPDATE triggers SET ${set} WHERE id = ?`, ...params, triggerId);
496
+ }
497
+ return { created };
498
+ }),
499
+ firing: async (triggerId, key) => {
500
+ const row = await db.get(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE trigger_id = ? AND key = ?`, triggerId, key);
501
+ return row && firingOf(row);
502
+ },
503
+ firings: async (triggerId) => (await db.all(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE trigger_id = ? AND shown = 1 ORDER BY at DESC, ${d.firingOrder} DESC`, triggerId)).map(firingOf),
504
+ settle: async (triggerId, key, change, streak) => db.transaction(async (tx) => {
505
+ const at = now();
506
+ await d.lockRow(tx, "triggers", "id", triggerId);
507
+ const was = await tx.get(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE trigger_id = ? AND key = ?`, triggerId, key);
508
+ if (!was)
509
+ return undefined;
510
+ const settled = change.status !== undefined && change.status !== "due";
511
+ // Out of due, a firing keeps no retry, wait, payload or attrs, nor the reason its last try gave (unless it gives one).
512
+ const set = [];
513
+ if (change.status !== undefined)
514
+ set.push(["status", change.status]);
515
+ if (settled)
516
+ set.push(["retry_at", null], ["waits_on", null], ["payload", null], ["attrs", null], ["reason", change.reason ?? null], ["attempts", change.attempts ?? 0]);
517
+ else if (change.reason !== undefined)
518
+ set.push(["reason", change.reason]);
519
+ if (change.runId !== undefined)
520
+ set.push(["run_id", change.runId]);
521
+ if (change.error !== undefined)
522
+ set.push(["error", json(change.error)]);
523
+ if (!settled && change.attempts !== undefined)
524
+ set.push(["attempts", change.attempts]);
525
+ if (!settled && change.retryAt !== undefined)
526
+ set.push(["retry_at", change.retryAt]);
527
+ if (!settled && change.waitsOn !== undefined)
528
+ set.push(["waits_on", change.waitsOn]);
529
+ if (change.notified !== undefined)
530
+ set.push(["notified", change.notified ? 1 : 0]);
531
+ let paused = false;
532
+ const trigger = await tx.get("SELECT failures_in_a_row, enabled, last_run_id, target FROM triggers WHERE id = ?", triggerId);
533
+ const triggerSets = [];
534
+ // Run ids are UUIDv7s, which sort by when the run started: a firing that finds an older run never takes a later
535
+ // one's place as the trigger's last run.
536
+ if (change.runId !== undefined && trigger && JSON.parse(trigger.target).kind === "start_run" && !(trigger.last_run_id && trigger.last_run_id > change.runId)) {
537
+ triggerSets.push(["last_run_id", change.runId]);
538
+ }
539
+ if (streak && "reset" in streak)
540
+ triggerSets.push(["failures_in_a_row", 0]);
541
+ if (streak && "failure" in streak && trigger) {
542
+ const failures = trigger.failures_in_a_row + 1;
543
+ triggerSets.push(["failures_in_a_row", failures]);
544
+ if (failures >= streak.pauseAt && trigger.enabled === 1) {
545
+ paused = true;
546
+ triggerSets.push(["enabled", 0], ["next_at", null], ["disabled", json({ at: new Date(at).toISOString(), reason: "auto_paused" })]);
547
+ set.push(["paused", 1]);
548
+ }
549
+ }
550
+ if (set.length)
551
+ await tx.run(`UPDATE trigger_firings SET ${set.map(([c]) => `${c} = ?`).join(", ")} WHERE trigger_id = ? AND key = ?`, ...set.map(([, v]) => v), triggerId, key);
552
+ if (triggerSets.length) {
553
+ triggerSets.push(["updated_at", at]);
554
+ await tx.run(`UPDATE triggers SET ${triggerSets.map(([c]) => `${c} = ?`).join(", ")} WHERE id = ?`, ...triggerSets.map(([, v]) => v), triggerId);
555
+ }
556
+ if (paused)
557
+ await writeScopes(tx, triggerId, []);
558
+ const row = await tx.get(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE trigger_id = ? AND key = ?`, triggerId, key);
559
+ return { firing: firingOf(row), paused };
560
+ }),
561
+ pending: async () => (await db.all(`SELECT ${FIRING_COLUMNS} FROM trigger_firings WHERE status = 'due' OR (status = 'failed' AND (notified IS NULL OR notified = 0)) ORDER BY at, ${d.firingOrder}`)).map(firingOf),
562
+ message: async ({ triggerId, key }, runId, command, bound) => db.transaction(async (tx) => {
563
+ const at = now();
564
+ await d.lockRow(tx, "triggers", "id", triggerId);
565
+ const firing = await tx.get("SELECT status FROM trigger_firings WHERE trigger_id = ? AND key = ?", triggerId, key);
566
+ if (!firing || firing.status !== "due")
567
+ return undefined;
568
+ const waiting = (await tx.get(`SELECT COUNT(*) AS n FROM commands WHERE run_id = ? AND taken_at IS NULL AND ${d.jsonText("body", ["origin", "trigger_id"])} = ?`, runId, triggerId)).n;
569
+ const clear = "retry_at = NULL, waits_on = NULL, payload = NULL, attrs = NULL, attempts = 0";
570
+ if (waiting >= bound.max) {
571
+ await tx.run(`UPDATE trigger_firings SET status = 'skipped', reason = ?, ${clear} WHERE trigger_id = ? AND key = ?`, bound.reason, triggerId, key);
572
+ return { skipped: bound.reason };
573
+ }
574
+ // As command(): the run row read under the share lock, so a message never lands on a run whose end is in flight
575
+ // or written, where it would wait untaken; a final run takes none (RunFinal) and the firing stays as it was.
576
+ const row = await tx.get(`INSERT INTO commands (run_id, kind, body, created_at) SELECT id, ?, ?, ? FROM runs WHERE id = ? AND state NOT IN (${FINAL})${d.shareLock} RETURNING id`, command.kind, json(command.body), at, runId);
577
+ if (!row)
578
+ throw new RunFinal(runId);
579
+ await tx.run(`UPDATE trigger_firings SET status = 'sent', run_id = ?, reason = NULL, ${clear} WHERE trigger_id = ? AND key = ?`, runId, triggerId, key);
580
+ await tx.run("UPDATE triggers SET failures_in_a_row = 0, updated_at = ? WHERE id = ?", at, triggerId);
581
+ return { sent: true, commandId: row.id };
582
+ }),
583
+ waiting: async () => (await db.all(`SELECT ${FIRING_COLUMNS.split(", ").map((c) => `f.${c}`).join(", ")},
584
+ (SELECT COUNT(*) FROM trigger_firings s JOIN runs r ON r.id = s.run_id
585
+ WHERE s.trigger_id = f.trigger_id AND s.status = 'started' AND r.state NOT IN (${FINAL})) < COALESCE(t.max_active_runs, 1) AS free
586
+ FROM trigger_firings f JOIN triggers t ON t.id = f.trigger_id
587
+ WHERE f.status = 'due' AND f.waits_on IS NOT NULL ORDER BY f.at, f.${d.firingOrder}`)).map((r) => ({ ...firingOf(r), free: r.free === 1 || r.free === true })),
588
+ soonest: async () => (await db.get("SELECT MIN(next_at) AS at FROM triggers WHERE enabled = 1 AND next_at IS NOT NULL"))?.at ?? null,
589
+ activeRuns: async (triggerId) => (await db.get(`SELECT COUNT(*) AS n FROM trigger_firings f JOIN runs r ON r.id = f.run_id WHERE f.trigger_id = ? AND f.status = 'started' AND r.state NOT IN (${FINAL})`, triggerId)).n,
590
+ prune: async (triggerId, { history, dayMs, keepByKey, kept }) => db.transaction(async (tx) => {
591
+ const at = now();
592
+ await d.lockRow(tx, "triggers", "id", triggerId);
593
+ // Past the newest `history` shown firings: never a due one, a failure not yet told, or a started one whose run
594
+ // has not ended. The rest leave the history: kept for their key's day when a sender's key names them, else gone.
595
+ const old = await tx.all(`SELECT f.key, f.by FROM trigger_firings f LEFT JOIN runs r ON r.id = f.run_id
596
+ WHERE f.trigger_id = ? AND f.shown = 1 AND f.status != 'due' AND NOT (f.status = 'failed' AND (f.notified IS NULL OR f.notified = 0))
597
+ AND NOT (f.status = 'started' AND r.id IS NOT NULL AND r.state NOT IN (${FINAL}))
598
+ AND f.key NOT IN (SELECT key FROM trigger_firings WHERE trigger_id = ? AND shown = 1 ORDER BY at DESC, ${d.firingOrder} DESC LIMIT ?)`, triggerId, triggerId, history);
599
+ for (const { key, by } of old) {
600
+ if (keepByKey(by ?? "manual"))
601
+ await tx.run("UPDATE trigger_firings SET shown = 0, payload = NULL, attrs = NULL WHERE trigger_id = ? AND key = ?", triggerId, key);
602
+ else
603
+ await tx.run("DELETE FROM trigger_firings WHERE trigger_id = ? AND key = ?", triggerId, key);
604
+ }
605
+ await tx.run(`DELETE FROM trigger_firings WHERE trigger_id = ? AND shown = 0 AND at < ? AND status != 'due'
606
+ AND NOT (status = 'started' AND run_id IN (SELECT id FROM runs WHERE state NOT IN (${FINAL})))`, triggerId, at - dayMs);
607
+ if (kept === undefined)
608
+ return 0;
609
+ // Past `kept` keys for the day, the oldest go first (a key's row, not its run: a started one's run has ended).
610
+ return tx.runCounted(`DELETE FROM trigger_firings WHERE trigger_id = ? AND key IN (
611
+ SELECT key FROM trigger_firings WHERE trigger_id = ? AND shown = 0 AND status != 'due'
612
+ AND NOT (status = 'started' AND run_id IN (SELECT id FROM runs WHERE state NOT IN (${FINAL})))
613
+ ORDER BY at DESC, ${d.firingOrder} DESC ${d.limitAll} OFFSET ?)`, triggerId, triggerId, kept);
614
+ }),
615
+ enable: async (triggerId, scopes) => {
616
+ await db.transaction(async (tx) => {
617
+ const on = await tx.get("UPDATE triggers SET enabled = 1, disabled = NULL, updated_at = ? WHERE id = ? RETURNING agent_id", now(), triggerId);
618
+ if (!on)
619
+ throw new StoreConstraint(`no trigger ${triggerId}`);
620
+ await refuseArchived(tx, on.agent_id);
621
+ await writeScopes(tx, triggerId, scopes);
622
+ });
623
+ },
624
+ disable: async (triggerId, why) => {
625
+ await db.transaction(async (tx) => {
626
+ if ((await tx.runCounted("UPDATE triggers SET enabled = 0, disabled = ?, updated_at = ? WHERE id = ?", why === undefined ? null : json(why), now(), triggerId)) === 0) {
627
+ throw new StoreConstraint(`no trigger ${triggerId}`);
628
+ }
629
+ await writeScopes(tx, triggerId, []);
630
+ });
631
+ },
632
+ fire: async (firing, run, { launch } = {}) => db.transaction(async (tx) => {
633
+ const at = now();
634
+ await d.lockRow(tx, "triggers", "id", firing.triggerId);
635
+ // Never a run of an archived agent: the archive's commit is read here, in the transaction that would start it.
636
+ await refuseArchived(tx, run.agentId);
637
+ const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, started_at) VALUES (?, ?, ?, 'queued', 0, ?) RETURNING ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, at);
638
+ // The run's launch row lands with it, through the store's one writer, or neither does.
639
+ if (launch)
640
+ await writeLaunch(tx, run.id, launch, at);
641
+ // The due firing the engine recorded becomes started; one not recorded yet is recorded started. A firing already
642
+ // past due (started, or settled otherwise) is refused, and its run with it.
643
+ const moved = await tx.runCounted("UPDATE trigger_firings SET status = 'started', run_id = ?, retry_at = NULL, waits_on = NULL, payload = NULL, attrs = NULL, reason = NULL, attempts = 0 WHERE trigger_id = ? AND key = ? AND status = 'due'", run.id, firing.triggerId, firing.key);
644
+ if (moved === 0) {
645
+ await tx.run("INSERT INTO trigger_firings (trigger_id, key, by, nominal_at, status, at, run_id, catch_up) VALUES (?, ?, ?, ?, 'started', ?, ?, ?)", firing.triggerId, firing.key, firing.by ?? null, firing.nominalAt ?? null, at, run.id, firing.catchUp === undefined ? null : firing.catchUp ? 1 : 0);
646
+ }
647
+ if ((await tx.runCounted("UPDATE triggers SET last_run_id = ?, failures_in_a_row = 0, updated_at = ? WHERE id = ?", run.id, at, firing.triggerId)) === 0)
648
+ throw new StoreConstraint(`no trigger ${firing.triggerId}`);
649
+ return runOf(row);
650
+ }),
651
+ };
652
+ this.runs = {
653
+ create: async ({ id, agentId, revisionId, origin }, launch) => {
654
+ // sign_in_handed is not written here: the runner writes it at its claim (runs.update under the epoch fence).
655
+ const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, started_at) VALUES (?, ?, ?, 'queued', 0, ?) RETURNING ${RUN_COLUMNS}`;
656
+ if (origin || launch) {
657
+ // The run, its origin and its launch row in one transaction: the key -> run link holds even if the kept response
658
+ // never lands, and a run never exists without the launch it was started with.
659
+ return db.transaction(async (tx) => {
660
+ const at = now();
661
+ const row = await tx.get(insert, id, agentId, revisionId, at);
662
+ if (origin)
663
+ await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", origin.key, id, origin.fingerprint ?? null, at);
664
+ if (launch)
665
+ await writeLaunch(tx, id, launch, at);
666
+ return runOf(row);
667
+ });
668
+ }
669
+ const [result] = await db.write([{ sql: insert, params: [id, agentId, revisionId, now()] }]);
670
+ return runOf(result.rows[0]);
671
+ },
672
+ createInline: async ({ agent, revision, run, launch }) => {
673
+ const insert = `INSERT INTO runs (id, agent_id, revision_id, state, epoch, started_at) VALUES (?, ?, ?, 'queued', 0, ?) RETURNING ${RUN_COLUMNS}`;
674
+ return db.transaction(async (tx) => {
675
+ const at = now();
676
+ // Hold the external reference, so two first uses of the same expert serialize (SQLite's one writer already does).
677
+ await d.lockKey(tx, `external:${agent.ref}`);
678
+ // The agent, one per external reference: written on its first run, read on every later one.
679
+ await tx.run(`${d.insertOrIgnore} INTO agents (id, name, description, created_at, external_ref) VALUES (?, ?, ?, ?, ?)${d.onConflictIgnore}`, agent.id, agent.name, agent.description ?? null, at, agent.ref);
680
+ const mapped = (await tx.get("SELECT id, current_revision FROM agents WHERE external_ref = ?", agent.ref));
681
+ // The revision, one per version: a version already stored keeps its body (a different body is refused); a new
682
+ // version is written, made current, and brings the agent's name and description up to it (the source is the truth).
683
+ const existing = await tx.get("SELECT id, body FROM revisions WHERE agent_id = ? AND external_version = ?", mapped.id, revision.version);
684
+ let revisionId;
685
+ if (existing) {
686
+ if (canonical(JSON.parse(existing.body)) !== canonical(revision.body))
687
+ throw new ExternalBodyConflict(agent.ref, revision.version);
688
+ revisionId = existing.id;
689
+ }
690
+ else {
691
+ revisionId = revision.id;
692
+ await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, external_version, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", revisionId, mapped.id, mapped.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, null, revision.version, at);
693
+ await tx.run("UPDATE agents SET current_revision = ?, name = ?, description = ? WHERE id = ?", revisionId, agent.name, agent.description ?? null, mapped.id);
694
+ }
695
+ // The run, its origin and its launch, in the same transaction as the agent and the revision.
696
+ const row = await tx.get(insert, run.id, mapped.id, revisionId, at);
697
+ if (run.origin)
698
+ await tx.run("INSERT INTO run_origins (key, run_id, fingerprint, created_at) VALUES (?, ?, ?, ?)", run.origin.key, run.id, run.origin.fingerprint ?? null, at);
699
+ await writeLaunch(tx, run.id, launch, at);
700
+ return runOf(row);
701
+ });
702
+ },
703
+ get: async (id) => {
704
+ const row = await db.get(`SELECT ${RUN_COLUMNS} FROM runs WHERE id = ?`, id);
705
+ return row && runOf(row);
706
+ },
707
+ launch: (runId) => readLaunch(db, runId),
708
+ list: async ({ agentId, revisionId, state, archived, limit }) => {
709
+ const where = [];
710
+ const params = [];
711
+ if (agentId !== undefined)
712
+ (where.push("agent_id = ?"), params.push(agentId));
713
+ if (revisionId !== undefined)
714
+ (where.push("revision_id = ?"), params.push(revisionId));
715
+ if (state !== undefined)
716
+ (where.push("state = ?"), params.push(state));
717
+ if (archived !== undefined)
718
+ where.push(`archived_at IS ${archived ? "NOT NULL" : "NULL"}`);
719
+ const bounded = typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0;
720
+ if (bounded)
721
+ params.push(limit);
722
+ const rows = await db.all(`SELECT ${RUN_COLUMNS} FROM runs ${where.length ? `WHERE ${where.join(" AND ")}` : ""} ORDER BY started_at DESC, id DESC${bounded ? " LIMIT ?" : ""}`, ...params);
723
+ return rows.map(runOf);
724
+ },
725
+ archive: async (runId, archived) => {
726
+ await db.write([{ sql: "UPDATE runs SET archived_at = ? WHERE id = ?", params: [archived ? now() : null, runId] }]);
727
+ },
728
+ reopen: async (runId, { kind, body = null }) => db.transaction(async (tx) => {
729
+ // Back to running, released: the epoch, the journal, cost_usd and metrics stay (its next turn is booked on what it
730
+ // spent); the end's own fields go. Only an agentic run that ended completed, not imported, not a learning run.
731
+ const reopened = await tx.runCounted(`UPDATE runs SET state = 'running', runner = NULL, claimed_until = NULL, wake_at = NULL, backoff_until = NULL, ended_at = NULL, summary = NULL, outcome = NULL
732
+ WHERE id = ? AND state = 'ended' AND imported_from IS NULL
733
+ AND EXISTS (SELECT 1 FROM revisions WHERE revisions.id = runs.revision_id AND revisions.kind = 'agentic')
734
+ AND NOT EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${d.jsonText("run_launch.body", ["harness"])} = 'learning')`, runId);
735
+ if (reopened === 0)
736
+ throw new RunFinal(runId);
737
+ const row = await tx.get(`INSERT INTO commands (run_id, kind, body, created_at) VALUES (?, ?, ?, ?) RETURNING ${COMMAND_COLUMNS}`, runId, kind, json(body), now());
738
+ return commandOf(row);
739
+ }),
740
+ claimable: async ({ limit } = {}) => {
741
+ const claimable = claimableIn(d, clock());
742
+ const bounded = typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0;
743
+ const rows = await db.all(`SELECT id FROM runs WHERE ${claimable.sql} ORDER BY started_at, id${bounded ? " LIMIT ?" : ""}`, ...claimable.params, ...(bounded ? [limit] : []));
744
+ return rows.map((row) => row.id);
745
+ },
746
+ claimMany: (runner, k, { leaseMs = DEFAULT_LEASE_MS } = {}) => this.#claimRuns(runner, leaseMs, { k }),
747
+ update: async (claim, patch, rows = {}) => {
748
+ if (Array.isArray(rows) || typeof rows !== "object" || rows === null)
749
+ throw new TypeError("runs.update's third argument is { also?, take?, signInSettleMs? }");
750
+ const { also = [], take = [], signInSettleMs = 0 } = rows;
751
+ return db.transaction(async (tx) => {
752
+ // A run update may end the run, moving its epoch on: held against every write under the claim (dialect lockRow).
753
+ await d.lockRow(tx, "runs", "id", claim.runId, "update");
754
+ const at = now();
755
+ const row = await applyRunPatch(tx, claim, patch, also, at, d, storeNow(d, () => at));
756
+ for (const commandId of take) {
757
+ if ((await tx.runCounted("UPDATE commands SET taken_at = ? WHERE id = ? AND run_id = ? AND taken_at IS NULL", at, commandId, claim.runId)) === 0) {
758
+ throw new CommandTaken(claim.runId, commandId);
759
+ }
760
+ }
761
+ // An update that made the run final: its other untaken rows are refused in this transaction, after its own takes.
762
+ await refuseLeftovers(tx, claim.runId, patch.state, at);
763
+ // The bind's save lease, in this same transaction as the sign_in_handed write just made (applyRunPatch, under
764
+ // SIGN_IN_HANDED_LOCK): this run saves unless another run already holds one of the handed pointers (a running run,
765
+ // or — within signInSettleMs of leaving running, a vendor's settle window — one that left running less than that
766
+ // ago). Excludes this run (it just wrote them), so a run is never its own blocker. Two binds of one sign-in in one
767
+ // tick thus never both save.
768
+ if (patch.signInHanded !== undefined && patch.signInHanded !== null && patch.signInHanded.length > 0) {
769
+ let holder;
770
+ for (const hash of patch.signInHanded) {
771
+ holder = await handedHolderIn(tx, hash, { not: claim.runId, settleMs: signInSettleMs, now: storeNow(d, () => at) });
772
+ if (holder)
773
+ break;
774
+ }
775
+ return { ...row, save: holder === undefined };
776
+ }
777
+ return row;
778
+ });
779
+ },
780
+ };
781
+ /** A server's write (Mcp.put), or with `expected` (Mcp.putIfCredential) only while the row's credential is still that:
782
+ * the statement's own WHERE compares it, so the comparison and the write are one statement. */
783
+ const putServer = async ({ name, url, auth, protocol = null, tools, prices = null, serverInfo = null, instructions = null, sealed = null, listedAt, updatedAt, credentialChangedAt, tokenLeftMs = null }, expected) => {
784
+ const at = now();
785
+ // The access token's end on the deadlines' clock (the database's on Postgres): the writer's measure of its life (a
786
+ // duration, clock-free) laid on that clock's now (token_until), in the statement that writes it.
787
+ const left = sealed !== null && typeof tokenLeftMs === "number" && Number.isFinite(tokenLeftMs) ? tokenLeftMs : null;
788
+ const stamp = clock();
789
+ // updated_at defaults to now (a save or a sign-in); a refresh passes the kept one so it is not read as an edit.
790
+ // listed_at is the tools' listing time, now unless given.
791
+ const updated = updatedAt ?? at;
792
+ const listed = listedAt ?? at;
793
+ // The credential's own time: now for a put that writes one, unless the caller says it kept the sealed one (its
794
+ // time given back); null with none. A token refresh (keepRefreshed) never moves it.
795
+ const credentialAt = sealed === null ? null : credentialChangedAt === undefined ? at : credentialChangedAt;
796
+ const values = [url, auth, protocol, json(tools), json(prices), serverInfo === null ? null : json(serverInfo), instructions, sealed];
797
+ // Expected present: an UPDATE of that row while its credential is still the one expected (gone, or changed: no row).
798
+ // Expected absent: an insert only (a row there: no row). Else the upsert. Either way RETURNING answers what it wrote.
799
+ const statement = expected !== undefined && expected !== null
800
+ ? {
801
+ sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, sealed = ?, refresh_holder = NULL, refresh_until = NULL,
802
+ updated_at = ?, listed_at = ?, credential_changed_at = ?, token_until = ${stamp.sql} + ${d.bigintParam}
803
+ WHERE name = ? AND auth = ? AND sealed IS ${expected.sealed ? "NOT NULL" : "NULL"} AND ${expected.changedAt === null ? "credential_changed_at IS NULL" : "credential_changed_at = ?"}
804
+ RETURNING ${mcpServerColumnsAt(stamp)}`,
805
+ params: [...values, updated, listed, credentialAt, ...stamp.params, left, name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt]), ...stamp.params],
806
+ }
807
+ : {
808
+ sql: `INSERT INTO mcp_servers (name, url, auth, protocol, tools, prices, server_info, instructions, sealed, created_at, updated_at, listed_at, credential_changed_at, token_until) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ${stamp.sql} + ${d.bigintParam})
809
+ ON CONFLICT (name) DO UPDATE SET url = excluded.url, auth = excluded.auth, protocol = excluded.protocol, tools = excluded.tools,
810
+ prices = excluded.prices, server_info = excluded.server_info, instructions = excluded.instructions, sealed = excluded.sealed, refresh_holder = NULL, refresh_until = NULL, updated_at = excluded.updated_at, listed_at = excluded.listed_at, credential_changed_at = excluded.credential_changed_at, token_until = excluded.token_until
811
+ ${expected === null ? "WHERE 1 = 0" : ""}
812
+ RETURNING ${mcpServerColumnsAt(stamp)}`,
813
+ params: [name, ...values, at, updated, listed, credentialAt, ...stamp.params, left, ...stamp.params],
814
+ };
815
+ const [result] = await db.write([statement]);
816
+ const written = result.rows[0];
817
+ return written && mcpServerOf(written);
818
+ };
819
+ const server = async (executor, name) => {
820
+ const at = clock();
821
+ const row = await executor.get(`SELECT ${mcpServerColumnsAt(at)} FROM mcp_servers WHERE name = ?`, ...at.params, name);
822
+ return row && mcpServerOf(row);
823
+ };
824
+ this.mcp = {
825
+ put: async (row) => (await putServer(row, undefined)),
826
+ putIfCredential: (row, expected) => putServer(row, expected),
827
+ // One statement compares the credential and writes, as keepRefreshed: no read between, so a refresh's keep never lands
828
+ // in a gap and is then written over. The credential's columns and the refresh lease are not in its SET.
829
+ rewrite: async ({ name, url, auth, protocol = null, tools, prices = null, serverInfo = null, instructions = null, listedAt, updatedAt }, seen) => {
830
+ const at = now();
831
+ const stamp = clock();
832
+ const [result] = await db.write([{
833
+ sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, updated_at = ?, listed_at = ?
834
+ WHERE name = ? AND ${d.nullSafeEquals("sealed")}
835
+ RETURNING ${mcpServerColumnsAt(stamp)}`,
836
+ params: [url, auth, protocol, json(tools), json(prices), serverInfo === null ? null : json(serverInfo), instructions, updatedAt ?? at, listedAt ?? at, name, seen, ...stamp.params],
837
+ }]);
838
+ const row = result.rows[0];
839
+ return row && mcpServerOf(row);
840
+ },
841
+ remove: async (name) => {
842
+ await db.write([{ sql: "DELETE FROM mcp_servers WHERE name = ?", params: [name] }]);
843
+ },
844
+ removeIfCredential: async (name, expected) => {
845
+ const [result] = await db.write([{
846
+ sql: `DELETE FROM mcp_servers WHERE name = ? AND auth = ? AND sealed IS ${expected.sealed ? "NOT NULL" : "NULL"} AND ${expected.changedAt === null ? "credential_changed_at IS NULL" : "credential_changed_at = ?"} RETURNING name`,
847
+ params: [name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt])],
848
+ }]);
849
+ return result.rows.length === 1;
850
+ },
851
+ servers: async () => {
852
+ const at = clock();
853
+ return (await db.all(`SELECT ${mcpServerColumnsAt(at)} FROM mcp_servers ORDER BY name`, ...at.params)).map((row) => mcpServerOf(row));
854
+ },
855
+ server: (name) => server(db, name),
856
+ pin: async (runId) => {
857
+ const row = await db.get("SELECT run_id, body, pinned_at FROM mcp_pins WHERE run_id = ?", runId);
858
+ return row && mcpPinOf(row);
859
+ },
860
+ pinOnce: (claim, body) => db.transaction(async (tx) => {
861
+ // Under the claim's epoch and its lease: a runner paused past its lease pins nothing.
862
+ await underClaim(tx, claim, now);
863
+ await tx.run("INSERT INTO mcp_pins (run_id, body, pinned_at) VALUES (?, ?, ?) ON CONFLICT (run_id) DO NOTHING", claim.runId, json(body), now());
864
+ return mcpPinOf((await tx.get("SELECT run_id, body, pinned_at FROM mcp_pins WHERE run_id = ?", claim.runId)));
865
+ }),
866
+ // The credential as read is compared by its bytes (`sealed IS ?`, NULL included): updated_at can repeat within a ms.
867
+ leaseRefresh: async (name, { seen, holder, ms = MCP_REFRESH_LEASE_MS }) => {
868
+ if (!(Number.isFinite(ms) && ms > MCP_REFRESH_CALL_MS)) {
869
+ throw new RangeError(`a refresh lease must be longer than the refresh call's own deadline (${MCP_REFRESH_CALL_MS} ms), not ${ms} ms: it would lapse while its holder's call may still spend the token`);
870
+ }
871
+ return db.transaction(async (tx) => {
872
+ // The lease is stamped and judged on the deadlines' clock (the database's on Postgres): one clock for every store
873
+ // process, so a lease one runner holds is live to every other.
874
+ const at = clock();
875
+ const granted = await tx.runCounted(`UPDATE mcp_servers SET refresh_holder = ?, refresh_until = ${at.sql} + ? WHERE name = ? AND ${d.nullSafeEquals("sealed")} AND (refresh_until IS NULL OR refresh_until < ${at.sql})`, holder, ...at.params, ms, name, seen, ...at.params);
876
+ const row = await server(tx, name);
877
+ if (!row)
878
+ throw new StoreConstraint(`no MCP server ${name}: it is no longer saved`);
879
+ return { leased: granted === 1, row };
880
+ });
881
+ },
882
+ // One statement compares the credential and writes: no read between, so no other write lands in a gap. The lease is
883
+ // cleared only by its own holder (a waiter that took a lapsed lease keeps it, and reads ours at its re-read).
884
+ keepRefreshed: (name, { seen, sealed, holder, tokenLeftMs = null }) => db.transaction(async (tx) => {
885
+ const at = now();
886
+ // The refreshed token's end on the deadlines' clock (token_until; the database's on Postgres), from the refresher's
887
+ // measure of its life (a duration), laid on that clock in this statement.
888
+ const left = typeof tokenLeftMs === "number" && Number.isFinite(tokenLeftMs) ? tokenLeftMs : null;
889
+ const stamp = clock();
890
+ const written = await tx.runCounted(`UPDATE mcp_servers SET sealed = ?, token_until = ${stamp.sql} + ${d.bigintParam},
891
+ refresh_until = CASE WHEN refresh_holder = ? THEN NULL ELSE refresh_until END,
892
+ refresh_holder = CASE WHEN refresh_holder = ? THEN NULL ELSE refresh_holder END,
893
+ updated_at = ${d.greatest}(?, updated_at + 1)
894
+ WHERE name = ? AND ${d.nullSafeEquals("sealed")}`, sealed, ...stamp.params, left, holder, holder, at, name, seen);
895
+ return { kept: written === 1, row: await server(tx, name) };
896
+ }, { deadlineMs: STORE_WRITE_DEADLINE_MS, fromCall: true }),
897
+ releaseRefresh: async (name, holder) => {
898
+ await db.write([{ sql: "UPDATE mcp_servers SET refresh_holder = NULL, refresh_until = NULL WHERE name = ? AND refresh_holder = ?", params: [name, holder] }]);
899
+ },
900
+ };
901
+ this.live = {
902
+ // One transaction for the tick; each row written only under its run's current epoch and live lease (the SELECT finds
903
+ // no run row for a stale or lapsed claim, so nothing is inserted or changed). The drop below stays on the epoch. The
904
+ // run row is read under the share lock: a put never lands beside a run's end or a new claim still in flight.
905
+ put: (rows) => db.transaction(async (tx) => {
906
+ const at = now();
907
+ const written = [];
908
+ const fenced = [];
909
+ for (const { claim, state } of rows) {
910
+ const fence = claimFence(claim, storeNow(d, () => at));
911
+ const changed = await tx.runCounted(`INSERT INTO run_live (run_id, state, updated_at) SELECT id, ?, ? FROM runs WHERE ${fence.where}${d.shareLock}
912
+ ON CONFLICT (run_id) DO UPDATE SET state = excluded.state, updated_at = excluded.updated_at`, json(state), at, ...fence.params);
913
+ (changed > 0 ? written : fenced).push(claim.runId);
914
+ }
915
+ return { written, fenced };
916
+ }),
917
+ read: async (runIds) => {
918
+ if (runIds.length === 0)
919
+ return [];
920
+ const rows = await db.all(`SELECT run_id, state, updated_at FROM run_live WHERE run_id IN (${runIds.map(() => "?").join(", ")}) ORDER BY run_id`, ...runIds);
921
+ return rows.map((row) => ({ runId: row.run_id, state: JSON.parse(row.state), updatedAt: row.updated_at }));
922
+ },
923
+ drop: async (claim) => {
924
+ await db.write([{
925
+ sql: `DELETE FROM run_live WHERE run_id = ? AND EXISTS (SELECT 1 FROM runs WHERE id = ? AND epoch = ?${d.shareLock})`,
926
+ params: [claim.runId, claim.runId, claim.epoch],
927
+ }]);
928
+ },
929
+ };
930
+ this.liveViewers = {
931
+ // Under the claim's fence (its epoch and its lease, on the store's clock read in this transaction): the SELECT finds
932
+ // no run row for a stale or lapsed claim, so nothing is inserted or changed, and the put answers false.
933
+ put: (claim, viewer) => db.transaction(async (tx) => {
934
+ const at = now();
935
+ const fence = claimFence(claim, storeNow(d, () => at));
936
+ const changed = await tx.runCounted(`INSERT INTO computer_viewers (run_id, kind, tag, port, viewer_id, sealed, at, runner, epoch) SELECT id, ?, ?, ?, ?, ?, ?, ?, ? FROM runs WHERE ${fence.where}${d.shareLock}
937
+ ON CONFLICT (run_id, kind, tag) DO UPDATE SET port = excluded.port, viewer_id = excluded.viewer_id, sealed = excluded.sealed, at = excluded.at, runner = excluded.runner, epoch = excluded.epoch`, viewer.kind, viewer.tag, viewer.port, viewer.id, viewer.sealed, at, claim.runner, claim.epoch, ...fence.params);
938
+ return changed > 0;
939
+ }),
940
+ // On the claim's epoch alone, as run_live's drop: a runner clearing its own rows after its lease ran out takes no
941
+ // one else's. No kind clears the whole run; a kind with no tag that kind's rows; a kind and a tag that one row.
942
+ drop: async (claim, kind, tag) => {
943
+ const narrow = kind === undefined ? "" : tag === undefined ? " AND kind = ?" : " AND kind = ? AND tag = ?";
944
+ const narrowParams = kind === undefined ? [] : tag === undefined ? [kind] : [kind, tag];
945
+ await db.write([{
946
+ sql: `DELETE FROM computer_viewers WHERE run_id = ?${narrow} AND EXISTS (SELECT 1 FROM runs WHERE id = ? AND epoch = ?${d.shareLock})`,
947
+ params: [claim.runId, ...narrowParams, claim.runId, claim.epoch],
948
+ }]);
949
+ },
950
+ // The server's read: only the run's epoch, under a live lease on the store's clock, written by the run's runner.
951
+ of: async (runId) => {
952
+ const live = clock();
953
+ const rows = await db.all(`SELECT v.kind, v.tag, v.port, v.viewer_id, v.sealed, v.at, v.runner FROM computer_viewers v JOIN runs r ON r.id = v.run_id
954
+ WHERE v.run_id = ? AND v.epoch = r.epoch AND r.claimed_until >= ${live.sql} AND v.runner = r.runner ORDER BY v.at DESC, v.tag`, runId, ...live.params);
955
+ return rows.map((row) => ({ kind: row.kind, tag: row.tag, port: row.port, id: row.viewer_id, sealed: new Uint8Array(row.sealed), at: row.at, runner: row.runner }));
956
+ },
957
+ };
958
+ const proposalOf = (row) => ({
959
+ runId: row.run_id, agentId: row.agent_id, turn: JSON.parse(row.turn), proposal: JSON.parse(row.proposal),
960
+ ...(row.learning_run_id === null ? {} : { learningRunId: row.learning_run_id }), createdAt: row.created_at,
961
+ });
962
+ this.learning = {
963
+ proposal: async (runId) => {
964
+ const row = await db.get("SELECT run_id, agent_id, turn, proposal, learning_run_id, created_at FROM learning_proposals WHERE run_id = ?", runId);
965
+ return row ? proposalOf(row) : undefined;
966
+ },
967
+ proposals: async (agentId, { limit = 100 } = {}) => (await db.all("SELECT run_id, agent_id, turn, proposal, learning_run_id, created_at FROM learning_proposals WHERE agent_id = ? ORDER BY created_at DESC, run_id DESC LIMIT ?", agentId, limit)).map(proposalOf),
968
+ };
969
+ this.settings = {
970
+ get: async (key) => {
971
+ const row = await db.get("SELECT value FROM settings WHERE key = ?", key);
972
+ return row === undefined ? undefined : JSON.parse(row.value);
973
+ },
974
+ put: async (key, value) => {
975
+ await db.write([{ sql: "INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", params: [key, json(value), now()] }]);
976
+ },
977
+ putIfAbsent: async (key, value) => {
978
+ await db.write([{ sql: "INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT (key) DO NOTHING", params: [key, json(value), now()] }]);
979
+ const row = await db.get("SELECT value FROM settings WHERE key = ?", key);
980
+ return row === undefined ? undefined : JSON.parse(row.value);
981
+ },
982
+ remove: async (key) => {
983
+ await db.write([{ sql: "DELETE FROM settings WHERE key = ?", params: [key] }]);
984
+ },
985
+ all: async () => (await db.all("SELECT key, value, updated_at FROM settings ORDER BY key")).map(settingOf),
986
+ };
987
+ this.sealedKeys = {
988
+ get: async (name) => {
989
+ const row = await db.get("SELECT sealed FROM sealed_keys WHERE name = ?", name);
990
+ return row === undefined ? undefined : Uint8Array.from(row.sealed);
991
+ },
992
+ put: async (name, sealed) => {
993
+ await db.write([{ sql: "INSERT INTO sealed_keys (name, sealed, updated_at) VALUES (?, ?, ?) ON CONFLICT (name) DO UPDATE SET sealed = excluded.sealed, updated_at = excluded.updated_at", params: [name, sealed, now()] }]);
994
+ },
995
+ remove: async (name) => {
996
+ await db.write([{ sql: "DELETE FROM sealed_keys WHERE name = ?", params: [name] }]);
997
+ },
998
+ all: async () => (await db.all("SELECT name, sealed, updated_at FROM sealed_keys ORDER BY name")).map(sealedKeyOf),
999
+ };
1000
+ this.computerLedger = {
1001
+ put: async (provider, sessionId, labels, detail) => {
1002
+ await db.write([{ sql: "INSERT INTO computer_ledger (provider, session_id, labels, detail, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (provider, session_id) DO UPDATE SET labels = excluded.labels, detail = excluded.detail, updated_at = excluded.updated_at", params: [provider, sessionId, JSON.stringify(labels), JSON.stringify(detail), now()] }]);
1003
+ },
1004
+ get: async (provider, sessionId) => {
1005
+ const row = await db.get("SELECT provider, session_id, labels, detail, updated_at FROM computer_ledger WHERE provider = ? AND session_id = ?", provider, sessionId);
1006
+ return row === undefined ? undefined : ledgerRowOf(row);
1007
+ },
1008
+ list: async (provider) => (await db.all("SELECT provider, session_id, labels, detail, updated_at FROM computer_ledger WHERE provider = ? ORDER BY session_id", provider)).map(ledgerRowOf),
1009
+ remove: async (provider, sessionId) => {
1010
+ await db.write([{ sql: "DELETE FROM computer_ledger WHERE provider = ? AND session_id = ?", params: [provider, sessionId] }]);
1011
+ },
1012
+ };
1013
+ this.triggerSettings = {
1014
+ get: async (adapter) => (await db.all("SELECT adapter, scope, field, sealed, updated_at FROM trigger_settings WHERE adapter = ? ORDER BY scope, field", adapter)).map(triggerSettingOf),
1015
+ put: async ({ adapter, scope, field, sealed }) => {
1016
+ await db.write([{ sql: "INSERT INTO trigger_settings (adapter, scope, field, sealed, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT (adapter, scope, field) DO UPDATE SET sealed = excluded.sealed, updated_at = excluded.updated_at", params: [adapter, scope, field, sealed, now()] }]);
1017
+ },
1018
+ removeScope: async (adapter, scope) => {
1019
+ await db.write([{ sql: "DELETE FROM trigger_settings WHERE adapter = ? AND scope = ?", params: [adapter, scope] }]);
1020
+ },
1021
+ };
1022
+ this.mcpOauth = {
1023
+ put: async ({ state, server, sealed, working, expiresAt }) => {
1024
+ await db.write([{
1025
+ sql: `INSERT INTO mcp_oauth_pending (state, server, sealed, working, expires_at) VALUES (?, ?, ?, ?, ?)
1026
+ ON CONFLICT (state) DO UPDATE SET server = excluded.server, sealed = excluded.sealed, working = excluded.working, expires_at = excluded.expires_at`,
1027
+ params: [state, server, sealed, json(working), expiresAt],
1028
+ }]);
1029
+ },
1030
+ take: async (state, at) => {
1031
+ // One statement: delete the row and return it. On the store's single writer this is atomic, so two concurrent
1032
+ // takes of one state can never both get it (the second deletes nothing). The row is gone whether or not it had
1033
+ // expired; an expired one is refused by reading undefined after the delete, so a stale state can't be retried.
1034
+ const [result] = await db.write([{ sql: "DELETE FROM mcp_oauth_pending WHERE state = ? RETURNING state, server, sealed, working, expires_at", params: [state] }]);
1035
+ const row = result.rows[0];
1036
+ if (row === undefined)
1037
+ return undefined;
1038
+ return row.expires_at <= (at ?? now()) ? undefined : mcpOauthOf(row);
1039
+ },
1040
+ sweepExpired: async (at) => (await db.write([{ sql: "DELETE FROM mcp_oauth_pending WHERE expires_at <= ?", params: [at] }]))[0].changes,
1041
+ count: async (at) => (await db.get("SELECT count(*) AS n FROM mcp_oauth_pending WHERE expires_at > ?", at)).n,
1042
+ };
1043
+ // Every sealed column of every table, each with the AAD it was sealed under: the one read a runner's redaction set takes.
1044
+ this.sealedSecrets = {
1045
+ all: async () => {
1046
+ const out = [];
1047
+ const bytes = (value) => Uint8Array.from(value);
1048
+ // A row whose AAD cannot be built (a key holding the separator) was never sealed by this store's writers, which
1049
+ // build the same AAD: it is left out, never a failed read of every other.
1050
+ const add = (row) => {
1051
+ try {
1052
+ out.push(row());
1053
+ }
1054
+ catch {
1055
+ // Left out: see above.
1056
+ }
1057
+ };
1058
+ for (const row of await db.all("SELECT name, sealed FROM sealed_keys ORDER BY name")) {
1059
+ add(() => ({ plane: "sealed_keys", where: { name: row.name }, aad: aadOf(sealedAt.sealedKey(row.name)), sealed: bytes(row.sealed) }));
1060
+ }
1061
+ for (const row of await db.all("SELECT name, sealed FROM mcp_servers WHERE sealed IS NOT NULL ORDER BY name")) {
1062
+ add(() => ({ plane: "mcp_servers", where: { name: row.name }, aad: aadOf(sealedAt.mcpServer(row.name)), sealed: bytes(row.sealed) }));
1063
+ }
1064
+ for (const row of await db.all("SELECT state, sealed FROM mcp_oauth_pending ORDER BY state")) {
1065
+ add(() => ({ plane: "mcp_oauth_pending", where: { state: row.state }, aad: aadOf(sealedAt.oauthPending(row.state)), sealed: bytes(row.sealed) }));
1066
+ }
1067
+ for (const row of await db.all("SELECT adapter, scope, field, sealed FROM trigger_settings ORDER BY adapter, scope, field")) {
1068
+ // Base64 text in this column (sealed-settings-store.ts), under the table's documented composite-key AAD.
1069
+ add(() => ({ plane: "trigger_settings", where: { adapter: row.adapter, scope: row.scope, field: row.field }, aad: `trigger_settings|${row.adapter}|${row.scope}|${row.field}`, sealed: Uint8Array.from(Buffer.from(row.sealed, "base64")) }));
1070
+ }
1071
+ for (const row of await db.all("SELECT agent_id, provider, pointer_sealed FROM sign_ins ORDER BY agent_id, provider")) {
1072
+ add(() => ({ plane: "sign_ins", where: { agentId: row.agent_id, provider: row.provider }, aad: aadOf(sealedAt.signIn(row.agent_id, row.provider)), sealed: bytes(row.pointer_sealed) }));
1073
+ }
1074
+ // A tombstone keeps the pointer's sealed bytes under the live row's binding (store/seal.ts signIn).
1075
+ for (const row of await db.all("SELECT id, agent_id, provider, pointer_sealed FROM sign_in_tombstones ORDER BY id")) {
1076
+ add(() => ({ plane: "sign_in_tombstones", where: { id: String(row.id), agentId: row.agent_id, provider: row.provider }, aad: aadOf(sealedAt.signIn(row.agent_id, row.provider)), sealed: bytes(row.pointer_sealed) }));
1077
+ }
1078
+ for (const row of await db.all("SELECT run_id, kind, tag, sealed FROM computer_viewers ORDER BY run_id, kind, tag")) {
1079
+ add(() => ({ plane: "computer_viewers", where: { runId: row.run_id, kind: row.kind, tag: row.tag }, aad: aadOf(sealedAt.liveViewer(row.run_id, row.kind, row.tag)), sealed: bytes(row.sealed) }));
1080
+ }
1081
+ for (const row of await db.all("SELECT run_id, sealed FROM run_launch WHERE sealed IS NOT NULL ORDER BY run_id")) {
1082
+ add(() => ({ plane: "run_launch", where: { runId: row.run_id }, aad: aadOf({ table: "run_launch", row: row.run_id, column: "sealed" }), sealed: bytes(row.sealed) }));
1083
+ }
1084
+ return out;
1085
+ },
1086
+ };
1087
+ this.signIns = {
1088
+ save: async ({ agentId, provider, name, pointerSealed }) => {
1089
+ const at = now();
1090
+ // A fresh save clears verified_at (the pointer is new, and no run has verified it yet) and numbers the save.
1091
+ const [result] = await db.write([{
1092
+ sql: `INSERT INTO sign_ins (agent_id, provider, name, pointer_sealed, saved_at, save, verified_at) VALUES (?, ?, ?, ?, ?, 1, NULL)
1093
+ ON CONFLICT (agent_id, provider) DO UPDATE SET name = excluded.name, pointer_sealed = excluded.pointer_sealed, saved_at = excluded.saved_at, save = sign_ins.save + 1, verified_at = NULL
1094
+ RETURNING ${SIGN_IN_COLUMNS}`,
1095
+ params: [agentId, provider, name, pointerSealed, at],
1096
+ }]);
1097
+ return signInOf(result.rows[0]);
1098
+ },
1099
+ saveIfAbsent: ({ agentId, provider, name, pointerSealed }) => db.transaction(async (tx) => {
1100
+ // One transaction: the insert that wins or the live row that won before it, never a replace.
1101
+ const inserted = await tx.all(`INSERT INTO sign_ins (agent_id, provider, name, pointer_sealed, saved_at, save, verified_at) VALUES (?, ?, ?, ?, ?, 1, NULL)
1102
+ ON CONFLICT (agent_id, provider) DO NOTHING RETURNING ${SIGN_IN_COLUMNS}`, agentId, provider, name, pointerSealed, now());
1103
+ if (inserted[0])
1104
+ return { saved: true, row: signInOf(inserted[0]) };
1105
+ const live = await tx.get(`SELECT ${SIGN_IN_COLUMNS} FROM sign_ins WHERE agent_id = ? AND provider = ?`, agentId, provider);
1106
+ return { saved: false, row: signInOf(live) };
1107
+ }),
1108
+ list: async (agentId) => (await db.all(`SELECT ${SIGN_IN_COLUMNS} FROM sign_ins WHERE agent_id = ? ORDER BY provider`, agentId)).map(signInOf),
1109
+ get: async (agentId, provider) => {
1110
+ const row = await db.get(`SELECT ${SIGN_IN_COLUMNS} FROM sign_ins WHERE agent_id = ? AND provider = ?`, agentId, provider);
1111
+ return row && signInOf(row);
1112
+ },
1113
+ verify: async (agentId, provider, at, { ifSave } = {}) => {
1114
+ // With ifSave, stamp only while the row is still that save (WHERE save = ?): a save that landed since the caller
1115
+ // checked (allowed while held; it clears verified_at) numbered itself on, in the same millisecond or not, so verify
1116
+ // never stamps it stale.
1117
+ const [result] = await db.write([{
1118
+ sql: `UPDATE sign_ins SET verified_at = ? WHERE agent_id = ? AND provider = ?${ifSave === undefined ? "" : " AND save = ?"}`,
1119
+ params: ifSave === undefined ? [at, agentId, provider] : [at, agentId, provider, ifSave],
1120
+ }]);
1121
+ return result.changes > 0;
1122
+ },
1123
+ tombstones: async (agentId, provider) => (await db.all("SELECT agent_id, provider, pointer_sealed, forgotten_at FROM sign_in_tombstones WHERE agent_id = ? AND provider = ? ORDER BY id DESC", agentId, provider)).map(signInTombstoneOf),
1124
+ forget: (agentId, provider, held) => db.transaction(async (tx) => {
1125
+ // The hold check and the move are one transaction: a launch writing sign_in_handed is another, and the store's one
1126
+ // writer lock serializes them, so forget never passes a hold a launch took, nor a launch a forget cleared. With many
1127
+ // writers, the lock both take (SIGN_IN_HANDED_LOCK) does.
1128
+ await d.lockKey(tx, SIGN_IN_HANDED_LOCK);
1129
+ const holder = held.hash !== undefined ? await handedHolderIn(tx, held.hash) : held.heldUnreadable ? await handedAnyIn(tx) : undefined;
1130
+ if (holder)
1131
+ throw new SignInHandedTo(holder.id);
1132
+ const live = await tx.get(`SELECT ${SIGN_IN_COLUMNS} FROM sign_ins WHERE agent_id = ? AND provider = ?`, agentId, provider);
1133
+ if (!live)
1134
+ throw new SignInMissing(agentId, provider);
1135
+ const at = now();
1136
+ const tomb = await tx.get("INSERT INTO sign_in_tombstones (agent_id, provider, pointer_sealed, forgotten_at) VALUES (?, ?, ?, ?) RETURNING agent_id, provider, pointer_sealed, forgotten_at", agentId, provider, live.pointer_sealed, at);
1137
+ await tx.run("DELETE FROM sign_ins WHERE agent_id = ? AND provider = ?", agentId, provider);
1138
+ // The newest kept, the oldest dropped first (per agent, across providers).
1139
+ await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ? AND id NOT IN (SELECT id FROM sign_in_tombstones WHERE agent_id = ? ORDER BY id DESC LIMIT ?)", agentId, agentId, SIGN_IN_TOMBSTONES_KEPT);
1140
+ return signInTombstoneOf(tomb);
1141
+ }),
1142
+ handedHolder: async (hash, options) => (await handedHolderIn(db, hash, { settleMs: options?.settleMs ?? 0, now: options?.at !== undefined ? { sql: d.bigintParam, params: [options.at] } : clock() }))?.id,
1143
+ handedAny: async () => (await handedAnyIn(db))?.id,
1144
+ };
1145
+ }
1146
+ async claim(runId, runner, { leaseMs = DEFAULT_LEASE_MS } = {}) {
1147
+ return (await this.#claimRuns(runner, leaseMs, { runId }))[0] ?? null;
1148
+ }
1149
+ /** Claims, in one transaction, the run `runId` when it is claimable, or up to `k` claimable runs oldest first: each read
1150
+ * with its state (the claim's `from`) and moved to its next epoch under the same BEGIN IMMEDIATE, so no other claimer
1151
+ * takes it between. */
1152
+ async #claimRuns(runner, leaseMs, pick) {
1153
+ if ("k" in pick && !(Number.isSafeInteger(pick.k) && pick.k > 0))
1154
+ return [];
1155
+ return this.#db.transaction(async (tx) => {
1156
+ // The clock is read once the transaction holds the writer lock: a claim that waited for another writer runs its
1157
+ // lease from now, never comes back already run out. The deadlines' clock (the database's on Postgres) both judges what
1158
+ // is claimable and stamps the lease, which comes back from the row.
1159
+ const claimable = claimableIn(this.#db.dialect, this.#clock());
1160
+ // With many claimers (Postgres), the rows picked are locked as they are read. A poll over many (claimMany) skips a
1161
+ // row another claimer holds (Dialect.claimLock): two claims never pick one run, and neither waits for the other. A
1162
+ // claim of one named run waits for a write in flight on its row (Dialect.claimOneLock), then reads it as it is: a
1163
+ // run whose holder is merely writing is never answered held.
1164
+ const lock = "runId" in pick ? this.#db.dialect.claimOneLock : this.#db.dialect.claimLock;
1165
+ const picked = "runId" in pick
1166
+ ? await tx.all(`SELECT id, state, runner FROM runs WHERE id = ? AND ${claimable.sql}${lock}`, pick.runId, ...claimable.params)
1167
+ : await tx.all(`SELECT id, state, runner FROM runs WHERE ${claimable.sql} ORDER BY started_at, id LIMIT ?${lock}`, ...claimable.params, pick.k);
1168
+ if (picked.length === 0)
1169
+ return [];
1170
+ const stamp = this.#clock();
1171
+ const rows = await tx.all(`UPDATE runs SET ${claimSet(stamp)} WHERE id IN (${picked.map(() => "?").join(", ")}) RETURNING id, epoch, claimed_until`, runner, ...stamp.params, leaseMs, ...picked.map((row) => row.id));
1172
+ const epochs = new Map(rows.map((row) => [row.id, row.epoch]));
1173
+ const untils = new Map(rows.map((row) => [row.id, Number(row.claimed_until)]));
1174
+ // A take or reclaim leaves no viewer of an older claim behind: its rows go in this transaction, every kind.
1175
+ for (const row of rows)
1176
+ await tx.run("DELETE FROM computer_viewers WHERE run_id = ? AND epoch < ?", row.id, row.epoch);
1177
+ // A newer claim of a run supersedes its release here: journal() refuses by epoch, and the newer epoch passes.
1178
+ for (const { id } of picked)
1179
+ this.#released.delete(id);
1180
+ // A running run that still names its runner was taken from it: that runner's lease ran out mid-run (CLAIMABLE).
1181
+ return picked.map(({ id, state, runner: held }) => ({ runId: id, runner, epoch: epochs.get(id), until: untils.get(id), from: state, ...(state === "running" && held !== null ? { lost: { runner: held } } : {}) }));
1182
+ });
1183
+ }
1184
+ /** Holds the run's row before a fenced write reads the store's clock: the lease is checked, and runs, from when the write
1185
+ * holds the row, never from before a wait for another writer (a no-op on SQLite, whose BEGIN IMMEDIATE already holds
1186
+ * the writer lock when the clock is read). */
1187
+ #holdRun(tx, runId) {
1188
+ return this.#db.dialect.lockRow(tx, "runs", "id", runId);
1189
+ }
1190
+ async renew(claim, { leaseMs = DEFAULT_LEASE_MS } = {}) {
1191
+ // As a claim's: the lease runs from when the renew holds the writer lock.
1192
+ // A lease that ran out is gone: no renew brings it back (its runner takes the run again, at a new epoch).
1193
+ const until = await this.#db.transaction(async (tx) => {
1194
+ await this.#holdRun(tx, claim.runId);
1195
+ // The deadlines' clock (the database's on Postgres) judges the lease and stamps the next one.
1196
+ const now = this.#clock();
1197
+ const fence = claimFence(claim, now);
1198
+ await tx.step(fenced(claim, `UPDATE runs SET claimed_until = ${now.sql} + ? WHERE ${fence.where} AND runner = ?`, [...now.params, leaseMs, ...fence.params, claim.runner]));
1199
+ return Number((await tx.get("SELECT claimed_until FROM runs WHERE id = ?", claim.runId)).claimed_until);
1200
+ }, { lease: true });
1201
+ return { ...claim, until };
1202
+ }
1203
+ async renewMany(claims, { leaseMs = DEFAULT_LEASE_MS } = {}) {
1204
+ if (claims.length === 0)
1205
+ return [];
1206
+ // One transaction for every claim, each update on its own: a claim another runner took changes no row and is answered
1207
+ // Fenced, never rolling the others back.
1208
+ return this.#db.transaction(async (tx) => {
1209
+ // Held in one order (by run id), so two renews of overlapping runs never wait on each other in a cycle.
1210
+ for (const runId of [...new Set(claims.map((claim) => claim.runId))].sort())
1211
+ await this.#holdRun(tx, runId);
1212
+ const out = [];
1213
+ for (const claim of claims) {
1214
+ // The deadlines' clock (the database's on Postgres) judges each lease and stamps the next one.
1215
+ const now = this.#clock();
1216
+ const fence = claimFence(claim, now);
1217
+ const renewed = await tx.all(`UPDATE runs SET claimed_until = ${now.sql} + ? WHERE ${fence.where} AND runner = ? RETURNING id, claimed_until`, ...now.params, leaseMs, ...fence.params, claim.runner);
1218
+ out.push(renewed.length > 0 ? { ...claim, until: Number(renewed[0].claimed_until) } : new Fenced(claim.runId, claim.epoch));
1219
+ }
1220
+ return out;
1221
+ // On the lease connection (TransactionOptions.lease): a runner whose loops hold every pool client still renews.
1222
+ }, { lease: true });
1223
+ }
1224
+ async release(claim, { state, wakeAt = null, backoffUntil = null } = {}) {
1225
+ // The end commit is the one write that makes a run final (applyRunPatch: the leftover rows refused and the run_live
1226
+ // row deleted with it). A release never does: asked to, it is refused before anything is written.
1227
+ if (state !== undefined && FINAL_STATES.includes(state))
1228
+ throw new TypeError(`a release never makes a run final (asked for ${state}): only the run's end commit does, refusing its leftover rows with it`);
1229
+ // A release that gives the run back with no state (or 'running') keeps it running (its runner shut down): it still holds
1230
+ // its sign-in. One that parks it leaves 'running', so stamp when — the Browserbase settle window reads left_running_at.
1231
+ const leaving = state !== undefined && state !== "running";
1232
+ await this.#db.transaction(async (tx) => {
1233
+ // A run its end already made final was released by that end (applyRunPatch): this release is a no-op, no second
1234
+ // move of its epoch and no error, whatever its claim's lease says now. The release moves the epoch: the row is held
1235
+ // against every write under the claim (dialect lockRow "update"), so one in flight lands first.
1236
+ await this.#db.dialect.lockRow(tx, "runs", "id", claim.runId, "update");
1237
+ const final = await tx.get("SELECT state, runner FROM runs WHERE id = ?", claim.runId);
1238
+ if (final && FINAL_STATES.includes(final.state) && final.runner === null)
1239
+ return;
1240
+ // The deadlines' clock (the database's on Postgres) judges the lease and stamps when the run left running.
1241
+ const now = this.#clock();
1242
+ const fence = claimFence(claim, now);
1243
+ await tx.step(fenced(claim,
1244
+ // The epoch moves on at a release: the released claim is dead everywhere (its journal, its run updates, its takes),
1245
+ // never live until the next claim. A claim whose lease ran out releases nothing: the run, running with its lease run
1246
+ // out, is claimable at once, never stuck.
1247
+ `UPDATE runs SET epoch = epoch + 1, runner = NULL, claimed_until = NULL, wake_at = ?, backoff_until = ?, state = coalesce(?, state)${leaving ? `, left_running_at = ${now.sql}` : ""} WHERE ${fence.where} AND runner = ?`, [wakeAt, backoffUntil, state ?? null, ...(leaving ? now.params : []), ...fence.params, claim.runner]));
1248
+ }, { full: true });
1249
+ // The released claim's journal is dead (its epoch moved on): the store keeps it no longer, and refuses it from now.
1250
+ this.#journals.delete(journalKey(claim));
1251
+ this.#released.delete(claim.runId);
1252
+ this.#released.set(claim.runId, claim.epoch);
1253
+ if (this.#released.size > RELEASED_KEPT)
1254
+ this.#released.delete(this.#released.keys().next().value);
1255
+ }
1256
+ /** The claim's one journal (pi assumes one Storage per owner): asked again for the same claim while it is open, the same
1257
+ * journal, so two callers never mint the same ids. The store keeps it only while it is open and its claim held: its
1258
+ * close, or its claim's release, drops it, so a long-lived runner keeps no journal of a finished claim. */
1259
+ journal(claim) {
1260
+ const released = this.#released.get(claim.runId);
1261
+ if (released !== undefined && claim.epoch <= released)
1262
+ throw new Fenced(claim.runId, claim.epoch);
1263
+ const key = journalKey(claim);
1264
+ const open = this.#journals.get(key);
1265
+ if (open && !open.closed)
1266
+ return open;
1267
+ const journal = new RunStorage(this.#db, claim, this.#now, () => {
1268
+ if (this.#journals.get(key) === journal)
1269
+ this.#journals.delete(key);
1270
+ });
1271
+ this.#journals.set(key, journal);
1272
+ return journal;
1273
+ }
1274
+ /** A run's journal opened for reading only (no claim): a fresh RunStorage on the store's connection, its reads alone. A
1275
+ * read never checks the epoch (only a commit's fence does), so the view carries epoch 0 and never writes; its type
1276
+ * (JournalReads) hands out no commit, stage or mintId. The store keeps no reference to it — it holds no claim and two
1277
+ * readers of one run never share ids, since neither mints any. A run with no journal yet reads as empty. */
1278
+ readJournal(runId) {
1279
+ return new RunStorage(this.#db, { runId, epoch: 0 }, this.#now);
1280
+ }
1281
+ /** How many journals the store keeps (open, of a claim not released). */
1282
+ get openJournals() {
1283
+ return this.#journals.size;
1284
+ }
1285
+ async flush() {
1286
+ await this.#db.write([{ sql: "UPDATE store_meta SET flushes = flushes + 1 WHERE singleton = 1" }], { full: true });
1287
+ }
1288
+ async command(runId, { kind, body = null }) {
1289
+ const [result] = await this.#db.write([{
1290
+ // The run row read under the share lock: a command never lands while the run's end is in flight, to be left untaken
1291
+ // by an end that refused the run's leftover rows before it (the end waits for it, or it waits for the end).
1292
+ sql: `INSERT INTO commands (run_id, kind, body, created_at) SELECT id, ?, ?, ? FROM runs WHERE id = ? AND state NOT IN (${FINAL})${this.#db.dialect.shareLock} RETURNING ${COMMAND_COLUMNS}`,
1293
+ params: [kind, json(body), this.#now(), runId],
1294
+ expect: { kind: "final", runId },
1295
+ }]);
1296
+ return commandOf(result.rows[0]);
1297
+ }
1298
+ async commands(runId, after) {
1299
+ return (await this.#db.all(`SELECT ${COMMAND_COLUMNS} FROM commands WHERE run_id = ? AND id > ? ORDER BY id`, runId, after)).map(commandOf);
1300
+ }
1301
+ async runOfOrigin(key) {
1302
+ const row = await this.#db.get("SELECT run_id, fingerprint FROM run_origins WHERE key = ?", key);
1303
+ return row && { runId: row.run_id, fingerprint: row.fingerprint };
1304
+ }
1305
+ async commandsOf(cursors) {
1306
+ const out = new Map();
1307
+ if (cursors.length === 0)
1308
+ return out;
1309
+ // One read for every run: each cursor a (run_id, after) row of a VALUES list joined against the commands.
1310
+ const rows = await this.#db.all(`WITH cursors(run_id, after) AS (VALUES ${cursors.map(() => `(?, ${this.#db.dialect.bigintParam})`).join(", ")})
1311
+ SELECT ${COMMAND_COLUMNS.split(", ").map((column) => `commands.${column}`).join(", ")} FROM commands JOIN cursors ON commands.run_id = cursors.run_id AND commands.id > cursors.after ORDER BY commands.id`, ...cursors.flatMap((cursor) => [cursor.runId, cursor.after]));
1312
+ for (const row of rows) {
1313
+ const command = commandOf(row);
1314
+ out.set(command.runId, [...(out.get(command.runId) ?? []), command]);
1315
+ }
1316
+ return out;
1317
+ }
1318
+ async importRun(run) {
1319
+ const at = this.#now();
1320
+ const state = run.state ?? "ended";
1321
+ return this.#db.transaction(async (tx) => {
1322
+ // The ended run row, its launch row and its transcript's journal, all in this one transaction (the server's own
1323
+ // writer): a crash between them leaves nothing. The run is created at epoch 0 with no runner, and the journal's fence
1324
+ // passes for that one row, by the rowid its insert returned (the claim fence's inserted-here form).
1325
+ const row = await tx.get(`INSERT INTO runs (id, agent_id, revision_id, state, epoch, cost_usd, metrics, summary, outcome, imported_from, started_at, ended_at)
1326
+ VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?) RETURNING ${this.#db.dialect.insertedRow} AS inserted_rowid, ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, state, run.costUsd ?? null, run.metrics === undefined || run.metrics === null ? null : json(run.metrics), run.summary ?? null, run.outcome ?? null, JSON.stringify(run.importedFrom), run.startedAt, run.endedAt ?? at);
1327
+ await writeLaunch(tx, run.id, run.launch, at);
1328
+ await new RunStorage(this.#db, { runId: run.id, epoch: 0 }, this.#now).applyIn(tx, run.transcript, row.inserted_rowid ?? "this-transaction");
1329
+ return runOf(row);
1330
+ });
1331
+ }
1332
+ async take(claim, commandId, outcome = "taken", reason) {
1333
+ // The clock is read inside the transaction, so the lease check and the write are one.
1334
+ await this.#db.transaction(async (tx) => {
1335
+ const now = await underClaim(tx, claim, this.#now);
1336
+ await tx.run("UPDATE commands SET taken_at = ?, refused = ? WHERE id = ? AND run_id = ? AND taken_at IS NULL", now, outcome === "refused" ? (reason ?? "refused") : null, commandId, claim.runId);
1337
+ });
1338
+ }
1339
+ async retry(claim, commandId) {
1340
+ const counted = await this.#db.transaction(async (tx) => {
1341
+ await underClaim(tx, claim, this.#now);
1342
+ return tx.all("UPDATE commands SET tries = tries + 1 WHERE id = ? AND run_id = ? AND taken_at IS NULL RETURNING tries", commandId, claim.runId);
1343
+ });
1344
+ const row = counted[0];
1345
+ if (!row)
1346
+ throw new StoreConstraint(`run ${claim.runId}: command ${commandId} is taken, or not the run's: no try to count`);
1347
+ return row.tries;
1348
+ }
1349
+ close() {
1350
+ return this.#db.close();
1351
+ }
1352
+ }