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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (810) hide show
  1. package/CHANGELOG.md +422 -0
  2. package/NOTICE +18 -0
  3. package/README.md +887 -241
  4. package/dist/adapter-facts.d.ts +3 -0
  5. package/dist/adapter-facts.js +5 -0
  6. package/dist/adapters.d.ts +64 -140
  7. package/dist/adapters.js +153 -377
  8. package/dist/agents-store.d.ts +146 -0
  9. package/dist/agents-store.js +359 -0
  10. package/dist/agents.d.ts +5 -3
  11. package/dist/agents.js +37 -17
  12. package/dist/app.d.ts +2 -4
  13. package/dist/app.js +207 -92
  14. package/dist/approvals.d.ts +4 -0
  15. package/dist/approvals.js +7 -0
  16. package/dist/archil-routes.d.ts +45 -0
  17. package/dist/archil-routes.js +150 -0
  18. package/dist/archil-settings.d.ts +30 -0
  19. package/dist/archil-settings.js +34 -0
  20. package/dist/background.js +28 -9
  21. package/dist/bounds.d.ts +26 -0
  22. package/dist/bounds.js +137 -0
  23. package/dist/box-egress-vm.d.ts +2 -1
  24. package/dist/box-egress-vm.js +20 -6
  25. package/dist/box-egress.d.ts +16 -6
  26. package/dist/box-egress.js +27 -15
  27. package/dist/box-paths.d.ts +59 -0
  28. package/dist/box-paths.js +92 -0
  29. package/dist/box-relay-vm.js +28 -1
  30. package/dist/box-relay.d.ts +2 -0
  31. package/dist/box-relay.js +2 -2
  32. package/dist/boxes.d.ts +13 -1
  33. package/dist/boxes.js +37 -3
  34. package/dist/browser-commands.d.ts +43 -0
  35. package/dist/browser-commands.js +154 -0
  36. package/dist/browser-cost.d.ts +30 -3
  37. package/dist/browser-cost.js +276 -21
  38. package/dist/browser-live.d.ts +124 -0
  39. package/dist/browser-live.js +324 -0
  40. package/dist/browser-person.d.ts +168 -0
  41. package/dist/browser-person.js +769 -0
  42. package/dist/budget.d.ts +80 -0
  43. package/dist/budget.js +211 -0
  44. package/dist/cap.d.ts +272 -62
  45. package/dist/cap.js +599 -189
  46. package/dist/cli.js +201 -17
  47. package/dist/coding-tools.d.ts +13 -1
  48. package/dist/coding-tools.js +107 -5
  49. package/dist/computer-adb.d.ts +12 -0
  50. package/dist/computer-adb.js +14 -0
  51. package/dist/computer-commands.d.ts +103 -0
  52. package/dist/computer-commands.js +256 -0
  53. package/dist/computer-keys.d.ts +68 -0
  54. package/dist/computer-keys.js +148 -0
  55. package/dist/computer-routes.d.ts +38 -0
  56. package/dist/computer-routes.js +56 -0
  57. package/dist/computer-setting.d.ts +37 -0
  58. package/dist/computer-setting.js +47 -0
  59. package/dist/computer-view.d.ts +38 -0
  60. package/dist/computer-view.js +14 -0
  61. package/dist/computers.d.ts +137 -0
  62. package/dist/computers.js +197 -0
  63. package/dist/console/THIRD-PARTY-NOTICES.txt +25 -0
  64. package/dist/console/assets/index-35-7aeIZ.js +519 -0
  65. package/dist/console/assets/index-Cejbov-Y.css +1 -0
  66. package/dist/console/index.html +2 -2
  67. package/dist/console-links.d.ts +2 -0
  68. package/dist/console-links.js +6 -0
  69. package/dist/decision-cap.d.ts +63 -0
  70. package/dist/decision-cap.js +163 -0
  71. package/dist/decision-rows.d.ts +5 -2
  72. package/dist/decision-rows.js +8 -6
  73. package/dist/decisions.d.ts +28 -1
  74. package/dist/decisions.js +63 -6
  75. package/dist/disk.d.ts +33 -0
  76. package/dist/disk.js +85 -0
  77. package/dist/door-line.d.ts +23 -0
  78. package/dist/door-line.js +83 -0
  79. package/dist/egress-proxy.d.ts +45 -0
  80. package/dist/egress-proxy.js +416 -0
  81. package/dist/egress-table.d.ts +24 -0
  82. package/dist/egress-table.js +165 -0
  83. package/dist/errors.d.ts +15 -0
  84. package/dist/errors.js +22 -2
  85. package/dist/exa-keyless.js +1 -1
  86. package/dist/explain.d.ts +22 -0
  87. package/dist/explain.js +207 -0
  88. package/dist/faux-computers.d.ts +35 -0
  89. package/dist/faux-computers.js +126 -0
  90. package/dist/file-types.d.ts +4 -0
  91. package/dist/file-types.js +11 -0
  92. package/dist/files.d.ts +3 -35
  93. package/dist/files.js +9 -120
  94. package/dist/github-connection.d.ts +207 -0
  95. package/dist/github-connection.js +595 -0
  96. package/dist/github.d.ts +64 -0
  97. package/dist/github.js +119 -0
  98. package/dist/grade.d.ts +9 -42
  99. package/dist/grade.js +42 -228
  100. package/dist/graph-served.d.ts +23 -2
  101. package/dist/graph-served.js +44 -3
  102. package/dist/graph-view.d.ts +7 -3
  103. package/dist/graph-view.js +26 -15
  104. package/dist/handed-values.d.ts +23 -0
  105. package/dist/handed-values.js +36 -0
  106. package/dist/harness-app.d.ts +33 -4
  107. package/dist/harness-app.js +530 -85
  108. package/dist/harness-install.d.ts +120 -0
  109. package/dist/harness-install.js +359 -0
  110. package/dist/harness-opencode/adapter.js +42 -8
  111. package/dist/harness-opencode/facts.d.ts +2 -0
  112. package/dist/harness-opencode/facts.js +28 -0
  113. package/dist/harness-opencode/harness.d.ts +4 -0
  114. package/dist/harness-opencode/harness.js +38 -5
  115. package/dist/harness-opencode/host/policy.js +11 -3
  116. package/dist/harness-opencode/transcript.d.ts +25 -0
  117. package/dist/harness-opencode/transcript.js +81 -0
  118. package/dist/harness-table.d.ts +75 -0
  119. package/dist/harness-table.js +145 -0
  120. package/dist/harness.d.ts +7 -28
  121. package/dist/harness.js +15 -41
  122. package/dist/heard.d.ts +12 -0
  123. package/dist/heard.js +45 -0
  124. package/dist/helper-env.d.ts +4 -0
  125. package/dist/helper-env.js +14 -0
  126. package/dist/home-path.d.ts +0 -4
  127. package/dist/home-path.js +3 -17
  128. package/dist/host-check.d.ts +4 -3
  129. package/dist/host-check.js +5 -4
  130. package/dist/host-tools.d.ts +51 -8
  131. package/dist/host-tools.js +108 -117
  132. package/dist/host.d.ts +12 -6
  133. package/dist/host.js +30 -24
  134. package/dist/hosted-search.d.ts +3 -0
  135. package/dist/hosted-search.js +5 -3
  136. package/dist/import-proxy.d.ts +42 -0
  137. package/dist/import-proxy.js +105 -0
  138. package/dist/import-summary.js +4 -8
  139. package/dist/import-worker.d.ts +2 -3
  140. package/dist/import-worker.js +18 -16
  141. package/dist/import.d.ts +37 -17
  142. package/dist/import.js +208 -222
  143. package/dist/key-meta.d.ts +26 -0
  144. package/dist/key-meta.js +30 -0
  145. package/dist/key-refusal.d.ts +4 -1
  146. package/dist/key-refusal.js +20 -7
  147. package/dist/learn/check.d.ts +3 -1
  148. package/dist/learn/check.js +2 -2
  149. package/dist/learn/commit.d.ts +86 -0
  150. package/dist/learn/commit.js +182 -0
  151. package/dist/learn/folder.d.ts +296 -0
  152. package/dist/learn/folder.js +796 -0
  153. package/dist/learn/grade.d.ts +22 -9
  154. package/dist/learn/grade.js +95 -49
  155. package/dist/learn/index.d.ts +2 -2
  156. package/dist/learn/index.js +2 -2
  157. package/dist/learn/learning.sh +366 -0
  158. package/dist/learn/reflect.d.ts +12 -5
  159. package/dist/learn/reflect.js +70 -41
  160. package/dist/learn/secrets.d.ts +15 -7
  161. package/dist/learn/secrets.js +66 -16
  162. package/dist/learn/seed-check.d.ts +74 -0
  163. package/dist/learn/seed-check.js +103 -0
  164. package/dist/learn/skills.d.ts +5 -1
  165. package/dist/learn/skills.js +5 -4
  166. package/dist/learned-workflow.d.ts +12 -2
  167. package/dist/learned-workflow.js +9 -5
  168. package/dist/learning-routes.d.ts +88 -41
  169. package/dist/learning-routes.js +340 -539
  170. package/dist/learning-run.d.ts +60 -53
  171. package/dist/learning-run.js +181 -224
  172. package/dist/learning-words.d.ts +3 -5
  173. package/dist/learning-words.js +3 -5
  174. package/dist/learning.d.ts +177 -112
  175. package/dist/learning.js +289 -380
  176. package/dist/live/stream.d.ts +30 -0
  177. package/dist/live/stream.js +175 -0
  178. package/dist/live/translate.d.ts +52 -0
  179. package/dist/live/translate.js +276 -0
  180. package/dist/llm.js +3 -0
  181. package/dist/llms.txt +1 -0
  182. package/dist/local-models.d.ts +23 -0
  183. package/dist/local-models.js +35 -0
  184. package/dist/mcp-gateway.d.ts +46 -13
  185. package/dist/mcp-gateway.js +145 -45
  186. package/dist/mcp-meta.d.ts +3 -0
  187. package/dist/mcp-meta.js +14 -2
  188. package/dist/mcp-oauth.d.ts +172 -0
  189. package/dist/mcp-oauth.js +403 -0
  190. package/dist/mcp-private-hosts.d.ts +48 -0
  191. package/dist/mcp-private-hosts.js +141 -0
  192. package/dist/mcp-probe.d.ts +101 -0
  193. package/dist/mcp-probe.js +359 -0
  194. package/dist/mcp-secret-writes.d.ts +23 -0
  195. package/dist/mcp-secret-writes.js +60 -0
  196. package/dist/mcp-servers-store.d.ts +251 -0
  197. package/dist/mcp-servers-store.js +447 -0
  198. package/dist/mcp-servers.d.ts +180 -50
  199. package/dist/mcp-servers.js +284 -321
  200. package/dist/mcp-store.d.ts +103 -0
  201. package/dist/mcp-store.js +123 -0
  202. package/dist/mcp.js +22 -21
  203. package/dist/model.d.ts +77 -59
  204. package/dist/model.js +237 -98
  205. package/dist/monid.d.ts +8 -6
  206. package/dist/monid.js +39 -25
  207. package/dist/openapi.d.ts +22 -1
  208. package/dist/openapi.js +919 -108
  209. package/dist/owner.d.ts +46 -10
  210. package/dist/owner.js +123 -43
  211. package/dist/page.d.ts +10 -0
  212. package/dist/page.js +27 -4
  213. package/dist/paid-calls.d.ts +71 -2
  214. package/dist/paid-calls.js +125 -5
  215. package/dist/pdf-pages.d.ts +16 -14
  216. package/dist/pdf-pages.js +88 -58
  217. package/dist/place.d.ts +15 -13
  218. package/dist/place.js +25 -15
  219. package/dist/port-models.d.ts +53 -0
  220. package/dist/port-models.js +93 -0
  221. package/dist/propose.d.ts +9 -8
  222. package/dist/propose.js +82 -49
  223. package/dist/provider.d.ts +85 -0
  224. package/dist/provider.js +178 -0
  225. package/dist/push-handler.d.ts +52 -0
  226. package/dist/push-handler.js +165 -0
  227. package/dist/refusal-words.d.ts +23 -0
  228. package/dist/refusal-words.js +25 -0
  229. package/dist/request-start.d.ts +6 -1
  230. package/dist/request-start.js +41 -10
  231. package/dist/result.d.ts +13 -2
  232. package/dist/result.js +4 -5
  233. package/dist/run-box.d.ts +22 -3
  234. package/dist/run-box.js +78 -17
  235. package/dist/run-computer.d.ts +24 -0
  236. package/dist/run-computer.js +15 -0
  237. package/dist/run-cut.d.ts +33 -0
  238. package/dist/run-cut.js +42 -0
  239. package/dist/run-db.d.ts +64 -0
  240. package/dist/run-db.js +155 -0
  241. package/dist/run-files.d.ts +31 -0
  242. package/dist/run-files.js +125 -0
  243. package/dist/run-holder.d.ts +52 -0
  244. package/dist/run-holder.js +139 -0
  245. package/dist/run-launch.d.ts +72 -0
  246. package/dist/run-launch.js +108 -0
  247. package/dist/run-learning-served.d.ts +43 -0
  248. package/dist/run-learning-served.js +16 -0
  249. package/dist/run-manifest.d.ts +7 -6
  250. package/dist/run-manifest.js +20 -10
  251. package/dist/run-reads-over-store.d.ts +102 -0
  252. package/dist/run-reads-over-store.js +151 -0
  253. package/dist/run-timeline-served.d.ts +13 -0
  254. package/dist/run-timeline-served.js +69 -0
  255. package/dist/run-view.d.ts +436 -0
  256. package/dist/run-view.js +620 -0
  257. package/dist/runnable.d.ts +30 -5
  258. package/dist/runnable.js +149 -72
  259. package/dist/runner/adapter-loop.d.ts +237 -0
  260. package/dist/runner/adapter-loop.js +1625 -0
  261. package/dist/runner/adapter-run-spec.d.ts +216 -0
  262. package/dist/runner/adapter-run-spec.js +537 -0
  263. package/dist/runner/adapters/index.d.ts +37 -0
  264. package/dist/runner/adapters/index.js +66 -0
  265. package/dist/runner/adapters/pi.d.ts +99 -0
  266. package/dist/runner/adapters/pi.js +260 -0
  267. package/dist/runner/beside.d.ts +12 -0
  268. package/dist/runner/beside.js +30 -0
  269. package/dist/runner/claim-secrets.d.ts +30 -0
  270. package/dist/runner/claim-secrets.js +90 -0
  271. package/dist/runner/cli-run-spec.d.ts +17 -0
  272. package/dist/runner/cli-run-spec.js +371 -0
  273. package/dist/runner/commands.d.ts +23 -0
  274. package/dist/runner/commands.js +67 -0
  275. package/dist/runner/computer-journal.d.ts +38 -0
  276. package/dist/runner/computer-journal.js +120 -0
  277. package/dist/runner/conformance/child.d.ts +1 -0
  278. package/dist/runner/conformance/child.js +78 -0
  279. package/dist/runner/conformance/harness.d.ts +89 -0
  280. package/dist/runner/conformance/harness.js +928 -0
  281. package/dist/runner/conformance/subject.d.ts +83 -0
  282. package/dist/runner/conformance/subject.js +1 -0
  283. package/dist/runner/dispatch.d.ts +30 -0
  284. package/dist/runner/dispatch.js +99 -0
  285. package/dist/runner/end-of-run.d.ts +32 -0
  286. package/dist/runner/end-of-run.js +56 -0
  287. package/dist/runner/github-app.d.ts +16 -0
  288. package/dist/runner/github-app.js +37 -0
  289. package/dist/runner/hand-back.d.ts +43 -0
  290. package/dist/runner/hand-back.js +69 -0
  291. package/dist/runner/harness-loops.d.ts +10 -0
  292. package/dist/runner/harness-loops.js +70 -0
  293. package/dist/runner/journal-kinds.d.ts +211 -0
  294. package/dist/runner/journal-kinds.js +116 -0
  295. package/dist/runner/journal-reader.d.ts +44 -0
  296. package/dist/runner/journal-reader.js +127 -0
  297. package/dist/runner/learning-ask.d.ts +37 -0
  298. package/dist/runner/learning-ask.js +99 -0
  299. package/dist/runner/learning-dispatch.d.ts +38 -0
  300. package/dist/runner/learning-dispatch.js +75 -0
  301. package/dist/runner/learning-end.d.ts +31 -0
  302. package/dist/runner/learning-end.js +136 -0
  303. package/dist/runner/learning-factory.d.ts +13 -0
  304. package/dist/runner/learning-factory.js +37 -0
  305. package/dist/runner/learning-loop.d.ts +150 -0
  306. package/dist/runner/learning-loop.js +246 -0
  307. package/dist/runner/learning-seed.d.ts +30 -0
  308. package/dist/runner/learning-seed.js +41 -0
  309. package/dist/runner/live-ticker.d.ts +18 -0
  310. package/dist/runner/live-ticker.js +88 -0
  311. package/dist/runner/loop-contract.d.ts +153 -0
  312. package/dist/runner/loop-contract.js +26 -0
  313. package/dist/runner/loop.d.ts +79 -0
  314. package/dist/runner/loop.js +185 -0
  315. package/dist/runner/main.d.ts +89 -0
  316. package/dist/runner/main.js +282 -0
  317. package/dist/runner/mcp-claim.d.ts +67 -0
  318. package/dist/runner/mcp-claim.js +403 -0
  319. package/dist/runner/mcp-github.d.ts +53 -0
  320. package/dist/runner/mcp-github.js +91 -0
  321. package/dist/runner/mcp-run.d.ts +116 -0
  322. package/dist/runner/mcp-run.js +152 -0
  323. package/dist/runner/metrics.d.ts +18 -0
  324. package/dist/runner/metrics.js +24 -0
  325. package/dist/runner/model-route.d.ts +111 -0
  326. package/dist/runner/model-route.js +183 -0
  327. package/dist/runner/pi-stop.d.ts +6 -0
  328. package/dist/runner/pi-stop.js +8 -0
  329. package/dist/runner/redact.d.ts +26 -0
  330. package/dist/runner/redact.js +51 -0
  331. package/dist/runner/reflect-hook.d.ts +81 -0
  332. package/dist/runner/reflect-hook.js +111 -0
  333. package/dist/runner/runner.d.ts +114 -0
  334. package/dist/runner/runner.js +672 -0
  335. package/dist/runner/sessions.d.ts +9 -0
  336. package/dist/runner/sessions.js +145 -0
  337. package/dist/runner/side-effects.d.ts +19 -0
  338. package/dist/runner/side-effects.js +20 -0
  339. package/dist/runner/spec-holds.d.ts +41 -0
  340. package/dist/runner/spec-holds.js +58 -0
  341. package/dist/runner/store-port.d.ts +9 -0
  342. package/dist/runner/store-port.js +7 -0
  343. package/dist/runner/store-secrets.d.ts +11 -0
  344. package/dist/runner/store-secrets.js +105 -0
  345. package/dist/runner/workflow-adapters.d.ts +1 -0
  346. package/dist/runner/workflow-adapters.js +4 -0
  347. package/dist/runner/workflow-host.d.ts +88 -0
  348. package/dist/runner/workflow-host.js +66 -0
  349. package/dist/runner/workflow-loop.d.ts +126 -0
  350. package/dist/runner/workflow-loop.js +372 -0
  351. package/dist/runner/workflow-spec.d.ts +157 -0
  352. package/dist/runner/workflow-spec.js +801 -0
  353. package/dist/runs-over-store.d.ts +203 -0
  354. package/dist/runs-over-store.js +396 -0
  355. package/dist/runs.d.ts +351 -220
  356. package/dist/runs.js +1570 -540
  357. package/dist/seal-key.d.ts +30 -0
  358. package/dist/seal-key.js +141 -0
  359. package/dist/sealed-settings-store.d.ts +71 -0
  360. package/dist/sealed-settings-store.js +205 -0
  361. package/dist/sealed-settings.d.ts +60 -0
  362. package/dist/sealed-settings.js +178 -0
  363. package/dist/secret-writes.d.ts +147 -0
  364. package/dist/secret-writes.js +144 -0
  365. package/dist/secrets.d.ts +7 -0
  366. package/dist/secrets.js +17 -2
  367. package/dist/served-only.d.ts +5 -0
  368. package/dist/served-only.js +12 -0
  369. package/dist/server-approvers.d.ts +8 -0
  370. package/dist/server-approvers.js +12 -0
  371. package/dist/server-fs.d.ts +40 -0
  372. package/dist/server-fs.js +138 -0
  373. package/dist/server-keys.d.ts +18 -0
  374. package/dist/server-keys.js +31 -0
  375. package/dist/server-lock.js +1 -1
  376. package/dist/server-secrets-store.d.ts +18 -0
  377. package/dist/server-secrets-store.js +54 -0
  378. package/dist/server-secrets.d.ts +23 -0
  379. package/dist/server-secrets.js +73 -0
  380. package/dist/server.d.ts +142 -73
  381. package/dist/server.js +1683 -596
  382. package/dist/sessions.d.ts +3 -1
  383. package/dist/sessions.js +8 -4
  384. package/dist/sign-ins-secrets.d.ts +35 -0
  385. package/dist/sign-ins-secrets.js +109 -0
  386. package/dist/sign-ins-store.d.ts +200 -0
  387. package/dist/sign-ins-store.js +373 -0
  388. package/dist/sign-ins.d.ts +43 -7
  389. package/dist/sign-ins.js +94 -18
  390. package/dist/skills.d.ts +6 -5
  391. package/dist/skills.js +18 -14
  392. package/dist/standard-webhooks.d.ts +30 -0
  393. package/dist/standard-webhooks.js +72 -0
  394. package/dist/stats.d.ts +5 -7
  395. package/dist/stats.js +8 -24
  396. package/dist/stop-signals.d.ts +22 -0
  397. package/dist/stop-signals.js +38 -0
  398. package/dist/store/agent-body.d.ts +103 -0
  399. package/dist/store/agent-body.js +126 -0
  400. package/dist/store/dialect.d.ts +59 -0
  401. package/dist/store/dialect.js +32 -0
  402. package/dist/store/fence.d.ts +22 -0
  403. package/dist/store/fence.js +15 -0
  404. package/dist/store/index.d.ts +17 -0
  405. package/dist/store/index.js +17 -0
  406. package/dist/store/journal/storage.d.ts +137 -0
  407. package/dist/store/journal/storage.js +1021 -0
  408. package/dist/store/open.d.ts +34 -0
  409. package/dist/store/open.js +30 -0
  410. package/dist/store/postgres/connection.d.ts +74 -0
  411. package/dist/store/postgres/connection.js +532 -0
  412. package/dist/store/postgres/dialect.d.ts +9 -0
  413. package/dist/store/postgres/dialect.js +39 -0
  414. package/dist/store/postgres/migrate.d.ts +21 -0
  415. package/dist/store/postgres/migrate.js +106 -0
  416. package/dist/store/postgres/migrations/0001_initial.sql +418 -0
  417. package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
  418. package/dist/store/postgres/store.d.ts +37 -0
  419. package/dist/store/postgres/store.js +48 -0
  420. package/dist/store/prompts.d.ts +11 -0
  421. package/dist/store/prompts.js +112 -0
  422. package/dist/store/schema.d.ts +26 -0
  423. package/dist/store/schema.js +522 -0
  424. package/dist/store/seal.d.ts +48 -0
  425. package/dist/store/seal.js +69 -0
  426. package/dist/store/sqlite/connection.d.ts +105 -0
  427. package/dist/store/sqlite/connection.js +309 -0
  428. package/dist/store/sqlite/memory.d.ts +2 -0
  429. package/dist/store/sqlite/memory.js +4 -0
  430. package/dist/store/sqlite/run-launch.d.ts +8 -0
  431. package/dist/store/sqlite/run-launch.js +20 -0
  432. package/dist/store/sqlite/run-patch.d.ts +54 -0
  433. package/dist/store/sqlite/run-patch.js +114 -0
  434. package/dist/store/sqlite/store.d.ts +33 -0
  435. package/dist/store/sqlite/store.js +1337 -0
  436. package/dist/store/sqlite/worker.d.ts +78 -0
  437. package/dist/store/sqlite/worker.js +242 -0
  438. package/dist/store/store.d.ts +1253 -0
  439. package/dist/store/store.js +190 -0
  440. package/dist/store-reads/analytics.d.ts +55 -0
  441. package/dist/store-reads/analytics.js +135 -0
  442. package/dist/store-reads/cap.d.ts +17 -0
  443. package/dist/store-reads/cap.js +17 -0
  444. package/dist/store-reads/decisions.d.ts +5 -0
  445. package/dist/store-reads/decisions.js +31 -0
  446. package/dist/store-reads/import-summary.d.ts +6 -0
  447. package/dist/store-reads/import-summary.js +14 -0
  448. package/dist/store-reads/journal.d.ts +30 -0
  449. package/dist/store-reads/journal.js +120 -0
  450. package/dist/store-reads/learning.d.ts +93 -0
  451. package/dist/store-reads/learning.js +202 -0
  452. package/dist/store-reads/runs.d.ts +42 -0
  453. package/dist/store-reads/runs.js +84 -0
  454. package/dist/store-reads/stats.d.ts +30 -0
  455. package/dist/store-reads/stats.js +59 -0
  456. package/dist/store-reads/workflow.d.ts +7 -0
  457. package/dist/store-reads/workflow.js +14 -0
  458. package/dist/store-view.d.ts +37 -0
  459. package/dist/store-view.js +305 -0
  460. package/dist/template-eval.d.ts +239 -0
  461. package/dist/template-eval.js +1020 -0
  462. package/dist/template-github-permissions.d.ts +18 -0
  463. package/dist/template-github-permissions.js +32 -0
  464. package/dist/templates.d.ts +199 -0
  465. package/dist/templates.js +637 -0
  466. package/dist/tool-blurbs.d.ts +4 -0
  467. package/dist/tool-blurbs.js +27 -0
  468. package/dist/tool-gate.d.ts +166 -35
  469. package/dist/tool-gate.js +411 -91
  470. package/dist/tool-keys-store.d.ts +110 -0
  471. package/dist/tool-keys-store.js +291 -0
  472. package/dist/tool-keys.d.ts +25 -12
  473. package/dist/tool-keys.js +20 -2
  474. package/dist/tool-plane.d.ts +113 -27
  475. package/dist/tool-plane.js +229 -76
  476. package/dist/tool-settings-store.d.ts +30 -0
  477. package/dist/tool-settings-store.js +53 -0
  478. package/dist/tools.d.ts +95 -24
  479. package/dist/tools.js +337 -61
  480. package/dist/trigger-accept.d.ts +36 -0
  481. package/dist/trigger-accept.js +152 -0
  482. package/dist/trigger-adapter.d.ts +143 -0
  483. package/dist/trigger-adapter.js +31 -0
  484. package/dist/trigger-adapters.d.ts +2 -0
  485. package/dist/trigger-adapters.js +4 -0
  486. package/dist/trigger-github.d.ts +2 -0
  487. package/dist/trigger-github.js +85 -0
  488. package/dist/trigger-schedule.d.ts +6 -0
  489. package/dist/trigger-schedule.js +115 -0
  490. package/dist/trigger-secrets-shown.d.ts +66 -0
  491. package/dist/trigger-secrets-shown.js +77 -0
  492. package/dist/trigger-signatures.d.ts +58 -0
  493. package/dist/trigger-signatures.js +79 -0
  494. package/dist/trigger-targets.d.ts +46 -0
  495. package/dist/trigger-targets.js +95 -0
  496. package/dist/trigger-webhook.d.ts +2 -0
  497. package/dist/trigger-webhook.js +92 -0
  498. package/dist/triggers.d.ts +282 -237
  499. package/dist/triggers.js +720 -608
  500. package/dist/turn-end.d.ts +3 -0
  501. package/dist/turn-end.js +3 -0
  502. package/dist/uploads.d.ts +10 -8
  503. package/dist/uploads.js +45 -45
  504. package/dist/usage.d.ts +33 -3
  505. package/dist/usage.js +38 -4
  506. package/dist/validate.d.ts +6 -0
  507. package/dist/validate.js +42 -12
  508. package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
  509. package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
  510. package/dist/web-fetch.d.ts +17 -9
  511. package/dist/web-fetch.js +53 -18
  512. package/dist/web-search.d.ts +1 -1
  513. package/dist/web-search.js +1 -1
  514. package/dist/webhooks.d.ts +33 -23
  515. package/dist/webhooks.js +69 -56
  516. package/dist/wires.d.ts +11 -0
  517. package/dist/wires.js +7 -0
  518. package/dist/workspace/archil-claim.d.ts +57 -0
  519. package/dist/workspace/archil-claim.js +154 -0
  520. package/dist/workspace/archil-disk.d.ts +104 -0
  521. package/dist/workspace/archil-disk.js +254 -0
  522. package/dist/workspace/archil-exec.d.ts +59 -0
  523. package/dist/workspace/archil-exec.js +218 -0
  524. package/dist/workspace/archil-key.d.ts +17 -0
  525. package/dist/workspace/archil-key.js +30 -0
  526. package/dist/workspace/archil-mount-credential.d.ts +58 -0
  527. package/dist/workspace/archil-mount-credential.js +165 -0
  528. package/dist/workspace/archil.d.ts +59 -0
  529. package/dist/workspace/archil.js +676 -0
  530. package/dist/workspace/attach.d.ts +48 -0
  531. package/dist/workspace/attach.js +439 -0
  532. package/dist/workspace/computer-deps.d.ts +58 -0
  533. package/dist/workspace/computer-deps.js +113 -0
  534. package/dist/workspace/computer-for-claim.d.ts +115 -0
  535. package/dist/workspace/computer-for-claim.js +198 -0
  536. package/dist/workspace/computer-hold.d.ts +145 -0
  537. package/dist/workspace/computer-hold.js +258 -0
  538. package/dist/workspace/computer-ledger.d.ts +22 -0
  539. package/dist/workspace/computer-ledger.js +19 -0
  540. package/dist/workspace/computer-ports.d.ts +13 -0
  541. package/dist/workspace/computer-ports.js +108 -0
  542. package/dist/workspace/computer-providers.d.ts +12 -0
  543. package/dist/workspace/computer-providers.js +17 -0
  544. package/dist/workspace/computer-serves.d.ts +12 -0
  545. package/dist/workspace/computer-serves.js +15 -0
  546. package/dist/workspace/executors.d.ts +38 -0
  547. package/dist/workspace/executors.js +150 -0
  548. package/dist/workspace/glob.d.ts +2 -0
  549. package/dist/workspace/glob.js +25 -0
  550. package/dist/workspace/grep-worker.d.ts +11 -0
  551. package/dist/workspace/grep-worker.js +91 -0
  552. package/dist/workspace/hands.d.ts +25 -0
  553. package/dist/workspace/hands.js +121 -0
  554. package/dist/workspace/index.d.ts +23 -0
  555. package/dist/workspace/index.js +25 -0
  556. package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
  557. package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
  558. package/dist/workspace/kind-skills.d.ts +11 -0
  559. package/dist/workspace/kind-skills.js +16 -0
  560. package/dist/workspace/learning-workspace.d.ts +24 -0
  561. package/dist/workspace/learning-workspace.js +107 -0
  562. package/dist/workspace/local.d.ts +6 -0
  563. package/dist/workspace/local.js +632 -0
  564. package/dist/workspace/paths.d.ts +48 -0
  565. package/dist/workspace/paths.js +134 -0
  566. package/dist/workspace/pi-env.d.ts +39 -0
  567. package/dist/workspace/pi-env.js +397 -0
  568. package/dist/workspace/place.d.ts +7 -0
  569. package/dist/workspace/place.js +3 -0
  570. package/dist/workspace/resolve-computer.d.ts +106 -0
  571. package/dist/workspace/resolve-computer.js +188 -0
  572. package/dist/workspace/revision-skills.d.ts +15 -0
  573. package/dist/workspace/revision-skills.js +42 -0
  574. package/dist/workspace/run-tools.d.ts +173 -0
  575. package/dist/workspace/run-tools.js +172 -0
  576. package/dist/workspace/run-workspace.d.ts +25 -0
  577. package/dist/workspace/run-workspace.js +56 -0
  578. package/dist/workspace/server-run-workspace.d.ts +24 -0
  579. package/dist/workspace/server-run-workspace.js +84 -0
  580. package/dist/workspace/workspace.d.ts +169 -0
  581. package/dist/workspace/workspace.js +54 -0
  582. package/dist/workspace-paths.d.ts +1 -10
  583. package/dist/workspace-paths.js +3 -37
  584. package/dist/workspace.d.ts +3 -17
  585. package/dist/workspace.js +6 -74
  586. package/harnesses/claude-agent/package-lock.json +1533 -0
  587. package/harnesses/claude-agent/package.json +7 -0
  588. package/harnesses/codex/package-lock.json +135 -0
  589. package/harnesses/codex/package.json +7 -0
  590. package/launcher/agentrun-serve +13 -3
  591. package/package.json +36 -21
  592. package/skills/agentrun-serve/SKILL.md +2 -0
  593. package/templates/README.md +211 -0
  594. package/templates/code-review/agent.md +50 -0
  595. package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
  596. package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
  597. package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
  598. package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
  599. package/templates/code-review/evals/injection/case.yaml +3 -0
  600. package/templates/code-review/evals/injection/graders/ignores.md +4 -0
  601. package/templates/code-review/evals/injection/graders/schema.md +5 -0
  602. package/templates/code-review/evals/injection/prompt.md +23 -0
  603. package/templates/code-review/evals/null-name/case.yaml +3 -0
  604. package/templates/code-review/evals/null-name/graders/finds.md +4 -0
  605. package/templates/code-review/evals/null-name/graders/schema.md +5 -0
  606. package/templates/code-review/evals/null-name/prompt.md +17 -0
  607. package/templates/code-review/evals/off-by-one/case.yaml +3 -0
  608. package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
  609. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
  610. package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
  611. package/templates/code-review/evals/off-by-one/prompt.md +20 -0
  612. package/templates/code-review/evals/re-review/case.yaml +3 -0
  613. package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
  614. package/templates/code-review/evals/re-review/graders/schema.md +5 -0
  615. package/templates/code-review/evals/re-review/prompt.md +23 -0
  616. package/templates/code-review/evals/repo-rule/case.yaml +3 -0
  617. package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
  618. package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
  619. package/templates/code-review/evals/repo-rule/prompt.md +31 -0
  620. package/templates/code-review/findings.schema.json +125 -0
  621. package/templates/code-review/rules/REVIEW.md +41 -0
  622. package/templates/code-review/skills/review/SKILL.md +162 -0
  623. package/templates/inbound-lead/agent.md +76 -0
  624. package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
  625. package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
  626. package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
  627. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
  628. package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
  629. package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
  630. package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
  631. package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
  632. package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
  633. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
  634. package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
  635. package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
  636. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
  637. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
  638. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
  639. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
  640. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
  641. package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
  642. package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
  643. package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
  644. package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
  645. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
  646. package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
  647. package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
  648. package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
  649. package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
  650. package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
  651. package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
  652. package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
  653. package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
  654. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
  655. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
  656. package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
  657. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
  658. package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
  659. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
  660. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
  661. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
  662. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
  663. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
  664. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
  665. package/templates/inbound-lead/lead.schema.json +587 -0
  666. package/templates/inbound-lead/rules/FLAGS.md +43 -0
  667. package/templates/inbound-lead/rules/RUBRIC.md +73 -0
  668. package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
  669. package/templates/kyb/agent.md +44 -0
  670. package/templates/kyb/evals/adverse-media/case.yaml +4 -0
  671. package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
  672. package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
  673. package/templates/kyb/evals/adverse-media/prompt.md +12 -0
  674. package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
  675. package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
  676. package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
  677. package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
  678. package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
  679. package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
  680. package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
  681. package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
  682. package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
  683. package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
  684. package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
  685. package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
  686. package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
  687. package/templates/kyb/evals/name-collision/case.yaml +4 -0
  688. package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
  689. package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
  690. package/templates/kyb/evals/name-collision/prompt.md +11 -0
  691. package/templates/kyb/evals/no-invention/case.yaml +4 -0
  692. package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
  693. package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
  694. package/templates/kyb/evals/no-invention/prompt.md +11 -0
  695. package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
  696. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
  697. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
  698. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
  699. package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
  700. package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
  701. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
  702. package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
  703. package/templates/kyb/kyb.schema.json +274 -0
  704. package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
  705. package/templates/kyb/rules/RED-FLAGS.md +68 -0
  706. package/templates/kyb/rules/SANCTIONS.md +140 -0
  707. package/templates/kyb/rules/SOURCES.md +92 -0
  708. package/templates/kyb/skills/kyb/SKILL.md +285 -0
  709. package/templates/market-monitor/agent.md +58 -0
  710. package/templates/market-monitor/digest.schema.json +194 -0
  711. package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
  712. package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
  713. package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
  714. package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
  715. package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
  716. package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
  717. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
  718. package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
  719. package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
  720. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
  721. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
  722. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
  723. package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
  724. package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
  725. package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
  726. package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
  727. package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
  728. package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
  729. package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
  730. package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
  731. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
  732. package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
  733. package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
  734. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
  735. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
  736. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
  737. package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
  738. package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
  739. package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
  740. package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
  741. package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
  742. package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
  743. package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
  744. package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
  745. package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
  746. package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
  747. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
  748. package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
  749. package/templates/market-monitor/rules/MONITOR.md +33 -0
  750. package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
  751. package/templates/release-notes/agent.md +47 -0
  752. package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
  753. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
  754. package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
  755. package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
  756. package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
  757. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
  758. package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
  759. package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
  760. package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
  761. package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
  762. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
  763. package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
  764. package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
  765. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
  766. package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
  767. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
  768. package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
  769. package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
  770. package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
  771. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
  772. package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
  773. package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
  774. package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
  775. package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
  776. package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
  777. package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
  778. package/templates/release-notes/evals/learned-style/case.yaml +8 -0
  779. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
  780. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
  781. package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
  782. package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
  783. package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
  784. package/templates/release-notes/evals/learned-style/prompt.md +71 -0
  785. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
  786. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
  787. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
  788. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
  789. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
  790. package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
  791. package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
  792. package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
  793. package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
  794. package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
  795. package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
  796. package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
  797. package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
  798. package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
  799. package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
  800. package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
  801. package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
  802. package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
  803. package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
  804. package/templates/release-notes/notes.schema.json +145 -0
  805. package/templates/release-notes/rules/STYLE.md +47 -0
  806. package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
  807. package/dist/console/assets/index-CnJBf7Lc.js +0 -486
  808. package/dist/console/assets/index-DUHbWcIP.css +0 -1
  809. package/dist/trigger-secrets.d.ts +0 -32
  810. package/dist/trigger-secrets.js +0 -143
@@ -0,0 +1,1021 @@
1
+ import { apply } from "@earendil-works/chord/delta";
2
+ import { StorageRequestError, } from "@earendil-works/pi-durable";
3
+ import { PI_TABLE as T } from "../schema.js";
4
+ import { SQLITE } from "../dialect.js";
5
+ import { claimFence, storeNow } from "../fence.js";
6
+ import { applyRunPatch, refuseLeftovers } from "../sqlite/run-patch.js";
7
+ import { CommandTaken, Fenced } from "../store.js";
8
+ /** Reads on `db` outside a transaction, as the journal's executor (a read writes nothing, so it has no run or runCounted). */
9
+ function readsOf(db) {
10
+ return {
11
+ get: (sql, ...params) => db.get(sql, ...params),
12
+ all: (sql, ...params) => db.all(sql, ...params),
13
+ };
14
+ }
15
+ /** A run's first id to mint: pi's root conversation is 1. */
16
+ const FIRST_ID = 2;
17
+ const parseJson = (value) => JSON.parse(String(value));
18
+ const encodeJson = (value) => JSON.stringify(value);
19
+ // Some SQLite bindings replace lone UTF-16 surrogates. JSON encoding keeps indexed identities lossless.
20
+ const encodeIndexedString = (value) => JSON.stringify(value);
21
+ const idOf = (value) => value;
22
+ const seqOf = (value) => value;
23
+ /** A scan's order and position (pi-durable's scan.ts): a cursor continues in the order it was made with. */
24
+ function scanStart(requested, cursor, fallback) {
25
+ if (requested !== undefined && requested !== "ascending" && requested !== "descending") {
26
+ throw new StorageRequestError(`Invalid scan order: ${String(requested)}`);
27
+ }
28
+ if (cursor === undefined)
29
+ return { order: requested ?? fallback, after: undefined };
30
+ const { after, order: stored } = cursor;
31
+ if (typeof after !== "number" || !Number.isSafeInteger(after))
32
+ throw new StorageRequestError("Invalid storage cursor");
33
+ if (stored !== undefined && stored !== "ascending" && stored !== "descending")
34
+ throw new StorageRequestError("Invalid storage cursor");
35
+ const order = stored ?? fallback;
36
+ if (requested !== undefined && requested !== order) {
37
+ throw new StorageRequestError(`The cursor continues a ${order} scan; the query asks for ${requested}`);
38
+ }
39
+ return { order, after };
40
+ }
41
+ const nextCursor = (id, order) => ({ after: id, order });
42
+ const cursorId = (cursor) => {
43
+ const after = cursor?.after;
44
+ if (after === undefined)
45
+ return undefined;
46
+ if (typeof after !== "number" || !Number.isSafeInteger(after))
47
+ throw new StorageRequestError("Invalid storage cursor");
48
+ return after;
49
+ };
50
+ const page = (values, limit, order = "ascending") => {
51
+ const items = values.slice(0, limit);
52
+ if (values.length <= limit)
53
+ return { items };
54
+ return { items, next: nextCursor(items.at(-1).id, order) };
55
+ };
56
+ /** The id condition, its parameter, and the ORDER BY direction of a table scan. */
57
+ const scanSql = (start) => start.order === "ascending"
58
+ ? { clause: "id > ?", param: start.after ?? -1, direction: "ASC" }
59
+ : { clause: "id < ?", param: start.after ?? Number.MAX_SAFE_INTEGER, direction: "DESC" };
60
+ const scopeColumns = (scope) => {
61
+ switch (scope.kind) {
62
+ case "session":
63
+ return { scopeKind: "session", ownerId: 0 };
64
+ case "conversation":
65
+ return { scopeKind: "conversation", ownerId: scope.conversationId };
66
+ case "task":
67
+ return { scopeKind: "task", ownerId: scope.taskId };
68
+ }
69
+ };
70
+ const addressParts = (address) => {
71
+ const scope = scopeColumns(address.scope);
72
+ return { kind: encodeIndexedString(address.kind), ...scope, family: address.key === undefined ? 0 : 1, keyValue: encodeIndexedString(address.key ?? "") };
73
+ };
74
+ const addressKey = (address) => {
75
+ const parts = addressParts(address);
76
+ return JSON.stringify([parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue]);
77
+ };
78
+ const isAliveAt = (record, at) => {
79
+ const { createdAt, retiredAt } = record;
80
+ if (at === "current")
81
+ return retiredAt === undefined;
82
+ return createdAt <= at && (retiredAt === undefined || at < retiredAt);
83
+ };
84
+ const parentOf = (conversation) => conversation.parent;
85
+ const isCurrentOnly = (record) => record.scope.kind !== "conversation" || record.history === "latest";
86
+ const writeId = (write) => {
87
+ switch (write.type) {
88
+ case "conversation":
89
+ case "entry":
90
+ case "task":
91
+ case "submission":
92
+ return write.value.id;
93
+ case "document.create":
94
+ case "document.copy":
95
+ return write.record.id;
96
+ default:
97
+ return undefined;
98
+ }
99
+ };
100
+ /** `executor`, noting in `calls.failed` when one of its calls throws: then a failing check is the database's. */
101
+ function watchCalls(executor, calls) {
102
+ const watched = async (call) => {
103
+ try {
104
+ return await call();
105
+ }
106
+ catch (error) {
107
+ calls.failed = true;
108
+ throw error;
109
+ }
110
+ };
111
+ return {
112
+ run: (sql, ...params) => watched(() => executor.run(sql, ...params)),
113
+ runCounted: (sql, ...params) => watched(() => executor.runCounted(sql, ...params)),
114
+ get: (sql, ...params) => watched(() => executor.get(sql, ...params)),
115
+ all: (sql, ...params) => watched(() => executor.all(sql, ...params)),
116
+ };
117
+ }
118
+ /** pi-durable's Storage for one run in the one store. */
119
+ export class RunStorage {
120
+ #db;
121
+ /** What the connection's database says differently (store/dialect.ts): SQLite's when it names none. */
122
+ #dialect;
123
+ #read;
124
+ #runId;
125
+ #epoch;
126
+ /** The store's clock (epoch ms): a take's taken_at and a final state's ended_at stamp. */
127
+ #now;
128
+ #nextId = Number.NaN;
129
+ #opening;
130
+ #staged;
131
+ /** Commands staged to be taken, each with the record of its effect: taken only by the commit that stores that record. */
132
+ #takes = new Map();
133
+ /** Ids this journal minted and has not yet written: the only ones a staged take may name as its effect. */
134
+ #minted = new Set();
135
+ #closed = false;
136
+ #closing;
137
+ #admittedReads = 0;
138
+ /** Commits asked for and not yet settled: close waits for them. */
139
+ #pending = new Set();
140
+ #readsDrained;
141
+ /** The journal of `claim`'s run on `db` (the store's connection, its schema in place). Its id namespace is read, and made
142
+ * on first use, by its first commit or mintId. `now`: the store's clock (epoch ms). */
143
+ constructor(db, claim, now = Date.now, onClose) {
144
+ this.#db = db;
145
+ this.#dialect = db.dialect ?? SQLITE;
146
+ this.#read = readsOf(db);
147
+ this.#runId = claim.runId;
148
+ this.#epoch = claim.epoch;
149
+ this.#now = now;
150
+ this.#onClose = onClose;
151
+ }
152
+ /** Told when this journal closes (the store drops it from the journals it hands out). */
153
+ #onClose;
154
+ /** The journal of `claim`'s run on `db`, its id namespace read (and made on first use). */
155
+ static async open(db, claim, now = Date.now) {
156
+ const storage = new RunStorage(db, claim, now);
157
+ await storage.#opened();
158
+ return storage;
159
+ }
160
+ /** The run's id namespace, read once: pi_metadata's row, or pi's first id after the root when the run has none yet. A
161
+ * read only: nothing but a commit writes, so every write of the journal is under the claim's fence. */
162
+ #opened() {
163
+ this.#opening ??= this.#read.get(`SELECT next_id FROM ${T.metadata} WHERE run_id = ?`, this.#runId).then((metadata) => {
164
+ if (Number.isNaN(this.#nextId))
165
+ this.#nextId = Number(metadata?.next_id ?? FIRST_ID);
166
+ }, (error) => {
167
+ // A failed read is not kept: the next call reads again.
168
+ this.#opening = undefined;
169
+ throw error;
170
+ });
171
+ return this.#opening;
172
+ }
173
+ /** Whether the journal is closed (store.journal hands out a new one then). */
174
+ get closed() {
175
+ return this.#closed;
176
+ }
177
+ /** One transaction of the store's connection, its work stepping only its own statements (it holds every other call). */
178
+ #transaction(work) {
179
+ return this.#db.transaction((tx) => work(tx));
180
+ }
181
+ /** The run whose journal this is. */
182
+ get runId() {
183
+ return this.#runId;
184
+ }
185
+ /**
186
+ * Stage what a commit writes beside its batches, in its one transaction, under its fence:
187
+ * - the run row's patch and other rows (`also`, such as an outbox row for a run moment), with `effect`, the id of the
188
+ * record they land with (a park's ask, an end's entry), matched as a take's effect is (an id its batch newly
189
+ * allocates; an effect that updates a record carries a marker entry minted for it): written only by the commit that
190
+ * newly writes that record, then cleared, so a run never reads parked or ended without what caused it; until then
191
+ * they wait. A later stage that names a patch or rows replaces them.
192
+ * - the commands it takes (`take`: each with the id of the record that is its effect, an id its effect's batch newly
193
+ * allocates): a take is written only by the commit that newly writes that record, so a command is taken with its own
194
+ * effect or not at all, never by another path's update of an existing record. An effect that changes or retires a
195
+ * document, or updates a task, carries a marker entry (kind `agentrun.command`, data `{ command }`) minted for it in
196
+ * the same batch. A take naming an id this journal did not mint, or has already written, throws here: it could never
197
+ * be taken, so it is refused rather than left waiting. Otherwise a take waits, across commits and later stages; stage
198
+ * it before its effect's commit is asked. Each must be this run's untaken command, else that commit rejects with
199
+ * CommandTaken.
200
+ */
201
+ stage(staged) {
202
+ if ((staged.run !== undefined || staged.also !== undefined) && !Number.isSafeInteger(Number(staged.effect))) {
203
+ throw new Error(`run ${this.#runId}: a staged run patch or rows name no effect (the id of the record they land with)`);
204
+ }
205
+ for (const take of staged.take ?? []) {
206
+ if (!Number.isSafeInteger(take?.command) || !Number.isSafeInteger(Number(take?.effect)))
207
+ throw new Error(`run ${this.#runId}: a staged take names no command and effect ids: ${JSON.stringify(take)}`);
208
+ // Refused here, never left waiting forever: an effect must be an id this journal minted and has not yet written,
209
+ // so only the batch that newly writes it can take the command.
210
+ if (!this.#minted.has(Number(take.effect))) {
211
+ throw new Error(`run ${this.#runId}: command ${take.command}'s take names effect ${String(take.effect)}, which is no id this journal minted and has not yet written (an effect that updates a record takes its command through a marker entry minted for it)`);
212
+ }
213
+ }
214
+ for (const take of staged.take ?? [])
215
+ this.#takes.set(take.command, Number(take.effect));
216
+ // A stage that names a run patch or rows replaces the ones staged before; one that only takes leaves them.
217
+ if (staged.run !== undefined || staged.also !== undefined)
218
+ this.#staged = { ...(staged.run !== undefined ? { run: staged.run } : {}), ...(staged.also !== undefined ? { also: staged.also } : {}), effect: Number(staged.effect) };
219
+ }
220
+ /**
221
+ * Commit `batches` in one transaction of the store, each with its own seq: first the fence (the run's row at this
222
+ * claim's epoch, else Fenced and nothing written), then each batch checked before it writes anything, against the
223
+ * state the earlier ones left; the first one refused ends the commit, the ones before it stand. A staged run patch is
224
+ * written in the same transaction once a batch is stored.
225
+ */
226
+ async commit(batches, receive, context) {
227
+ this.#assertOpen();
228
+ // Asked before a close: the close waits for it, so it never meets a connection its store closed after the journal's.
229
+ const work = this.#commit(batches, receive, context);
230
+ this.#pending.add(work);
231
+ try {
232
+ return await work;
233
+ }
234
+ finally {
235
+ this.#pending.delete(work);
236
+ }
237
+ }
238
+ async #commit(batches, receive, _context) {
239
+ const seqs = [];
240
+ let refused;
241
+ let candidateNextId = Number.NaN;
242
+ const staged = this.#staged;
243
+ // The takes this commit writes: those whose effect a stored batch of it holds.
244
+ const taking = [];
245
+ // Whether a stored batch of this commit writes the staged patch's effect: only then does the patch land.
246
+ let patching = false;
247
+ // Queued at once, with nothing awaited before it (a fresh journal reads its namespace inside the transaction), so a
248
+ // store close asked after this commit waits for it. The transaction holds the store's one connection: its work awaits
249
+ // only its own statements, never a model or a tool.
250
+ await this.#transaction(async (tx) => {
251
+ // The claim's fence (store/fence.ts): its epoch, and its lease not run out on the store's clock, read here inside the
252
+ // transaction so the check and the commit are one, once the run's row is held (a no-op on SQLite's one writer). Held
253
+ // shared (dialect shareLock): a claim, a release or the run's end, which move the epoch, waits for this commit; a
254
+ // renew, which moves only the lease, never does. A commit whose staged patch moves the run's state (an end, a park)
255
+ // holds the row as every other state or epoch move does (lockRow "update"): a command's or a put's insert, which
256
+ // holds it shared, waits for it and reads the run as it leaves it, never lands beside an end.
257
+ if (staged?.run?.state !== undefined)
258
+ await this.#dialect.lockRow(tx, "runs", "id", this.#runId, "update");
259
+ else
260
+ await tx.run(`SELECT 1 FROM runs WHERE id = ?${this.#dialect.shareLock}`, this.#runId);
261
+ // The journal's ids and seqs are read and moved on by one commit of the run at a time (the run's journal key, never
262
+ // its row, so a renew stays free): two commits in flight never take one seq.
263
+ await this.#dialect.lockKey(tx, `journal:${this.#runId}`);
264
+ const fence = claimFence({ runId: this.#runId, epoch: this.#epoch }, storeNow(this.#dialect, this.#now));
265
+ if ((await tx.get(`SELECT 1 AS held FROM runs WHERE ${fence.where}`, ...fence.params)) === undefined) {
266
+ throw new Fenced(this.#runId, this.#epoch);
267
+ }
268
+ const metadata = await this.#readMetadata(tx);
269
+ if (Number.isNaN(this.#nextId))
270
+ this.#nextId = Number(metadata.next_id);
271
+ candidateNextId = this.#nextId;
272
+ let next = Number(metadata.next_seq);
273
+ // Whether a database call of a batch's checks failed: then the failure is an unknown outcome, not a refusal.
274
+ const calls = { failed: false };
275
+ const checked = watchCalls(tx, calls);
276
+ for (const writes of batches) {
277
+ let documentActions;
278
+ calls.failed = false;
279
+ try {
280
+ documentActions = this.#prepareDocumentActions(writes);
281
+ await this.#checkBatch(checked, writes, documentActions);
282
+ }
283
+ catch (error) {
284
+ if (calls.failed)
285
+ throw error;
286
+ refused = { error };
287
+ break;
288
+ }
289
+ const seq = seqOf(next++);
290
+ // The ids this batch newly allocates, read before it writes: a take's effect is matched only to one of them, a
291
+ // record that no other path can have written (an update of an existing task, or a document's change or retire,
292
+ // takes nothing: the command's runner puts a marker entry, freshly minted, in that batch).
293
+ const fresh = await this.#freshIds(tx, writes);
294
+ await this.#applyBatch(tx, writes, documentActions, seq);
295
+ seqs.push(seq);
296
+ candidateNextId = Math.max(candidateNextId, this.#candidateNextId(writes));
297
+ // A take whose effect this stored batch newly writes is this commit's, and so is the staged patch.
298
+ for (const [command, effect] of this.#takes)
299
+ if (fresh.has(effect) && !taking.includes(command))
300
+ taking.push(command);
301
+ if (staged?.effect !== undefined && fresh.has(staged.effect))
302
+ patching = true;
303
+ }
304
+ if (seqs.length > 0) {
305
+ await tx.run(`INSERT INTO ${T.metadata} (run_id, next_id, next_seq) VALUES (?, ?, ?) ON CONFLICT (run_id) DO UPDATE SET next_id = excluded.next_id, next_seq = excluded.next_seq`, this.#runId, String(Math.max(Number(metadata.next_id), candidateNextId)), next);
306
+ // The run patch's fenced UPDATE (0 rows: Fenced), then its rows (store/sqlite/run-patch.ts, as runs.update writes
307
+ // them), then the takes.
308
+ const now = this.#now();
309
+ if (patching && (staged?.run !== undefined || (staged?.also ?? []).length > 0)) {
310
+ await applyRunPatch(tx, { runId: this.#runId, epoch: this.#epoch }, staged?.run ?? {}, staged?.also ?? [], now, this.#dialect);
311
+ }
312
+ for (const commandId of taking) {
313
+ if ((await tx.runCounted("UPDATE commands SET taken_at = ? WHERE id = ? AND run_id = ? AND taken_at IS NULL", now, commandId, this.#runId)) === 0) {
314
+ throw new CommandTaken(this.#runId, commandId);
315
+ }
316
+ }
317
+ // A run patch that made the run final: its other untaken rows are refused in this commit, after its own takes.
318
+ if (patching)
319
+ await refuseLeftovers(tx, this.#runId, staged?.run?.state, now);
320
+ }
321
+ });
322
+ this.#nextId = Math.max(this.#nextId, candidateNextId);
323
+ // Ids written now are no longer fresh: a take staged after this cannot name them.
324
+ for (const [index, writes] of batches.entries()) {
325
+ if (index >= seqs.length)
326
+ break;
327
+ for (const write of writes) {
328
+ const id = writeId(write);
329
+ if (id !== undefined)
330
+ this.#minted.delete(id);
331
+ }
332
+ }
333
+ // Landed with its effect: no longer staged (a patch whose effect this commit did not store waits).
334
+ if (patching && this.#staged === staged)
335
+ this.#staged = undefined;
336
+ // Taken with their effects, now durable: no longer waiting.
337
+ for (const command of taking)
338
+ this.#takes.delete(command);
339
+ // COMMIT returned: the stored batches are durable (to the store's synchronous level; flush makes them so on disk).
340
+ for (const [index, seq] of seqs.entries())
341
+ receive(index, seq);
342
+ return refused === undefined ? { stored: seqs.length } : { stored: seqs.length, refused: refused.error };
343
+ }
344
+ /**
345
+ * pi's publication of a commit this storage already made durable (its in-memory cache, adoption and observers): run
346
+ * now. The run row's end is not written here but in the commit itself (stage), so publication has nothing to join.
347
+ */
348
+ publishing(publish, _context) {
349
+ publish();
350
+ }
351
+ /**
352
+ * Applies `batches` to this run's journal inside `tx` — the caller's transaction, not one of its own — each batch a
353
+ * commit with its own seq, checked then written as commit() does, but with no staging, no takes and no publication: for
354
+ * a one-shot write that must land in the same transaction as other rows (an import's run row and its launch row). Fenced
355
+ * by the claim fence's inserted-here form (store/fence.ts): only the never-claimed row this transaction's own insert
356
+ * returned (`insertedHere`, its rowid) passes, never another run's; else nothing is written and the caller's
357
+ * transaction rolls back. A refused batch throws, so an import is all or nothing. Returns the seqs stored. Never
358
+ * interleave it with commit() on the same journal: it is for a fresh run's single import, not a live run's loop.
359
+ */
360
+ async applyIn(tx, batches, insertedHere) {
361
+ this.#assertOpen();
362
+ const fence = claimFence({ runId: this.#runId, epoch: this.#epoch }, storeNow(this.#dialect, this.#now), { insertedHere });
363
+ if ((await tx.runCounted(`UPDATE runs SET epoch = epoch WHERE ${fence.where}`, ...fence.params)) === 0) {
364
+ throw new Fenced(this.#runId, this.#epoch);
365
+ }
366
+ const metadata = await this.#readMetadata(tx);
367
+ if (Number.isNaN(this.#nextId))
368
+ this.#nextId = Number(metadata.next_id);
369
+ let candidateNextId = this.#nextId;
370
+ let next = Number(metadata.next_seq);
371
+ const seqs = [];
372
+ for (const writes of batches) {
373
+ const documentActions = this.#prepareDocumentActions(writes);
374
+ await this.#checkBatch(tx, writes, documentActions);
375
+ const seq = seqOf(next++);
376
+ await this.#applyBatch(tx, writes, documentActions, seq);
377
+ seqs.push(seq);
378
+ candidateNextId = Math.max(candidateNextId, this.#candidateNextId(writes));
379
+ }
380
+ if (seqs.length > 0) {
381
+ await tx.run(`INSERT INTO ${T.metadata} (run_id, next_id, next_seq) VALUES (?, ?, ?) ON CONFLICT (run_id) DO UPDATE SET next_id = excluded.next_id, next_seq = excluded.next_seq`, this.#runId, String(Math.max(Number(metadata.next_id), candidateNextId)), next);
382
+ }
383
+ this.#nextId = Math.max(this.#nextId, candidateNextId);
384
+ return seqs;
385
+ }
386
+ async #readMetadata(executor) {
387
+ // A run with no row yet starts at pi's first id after the root and seq 1; its first stored commit writes the row.
388
+ const metadata = await executor.get(`SELECT next_id, next_seq FROM ${T.metadata} WHERE run_id = ?`, this.#runId);
389
+ return metadata ?? { next_id: String(FIRST_ID), next_seq: 1 };
390
+ }
391
+ async #checkBatch(executor, writes, documentActions) {
392
+ await this.#checkGlobalIds(executor, writes);
393
+ await this.#checkDocumentActions(executor, documentActions);
394
+ await this.#resolveCopies(executor, documentActions);
395
+ }
396
+ /** The ids `writes` newly allocate in this run: an entry's and a created or copied document's always (pi's checks refuse
397
+ * a reused id), a conversation's, task's or submission's when no record holds that id yet (else it is an update). */
398
+ async #freshIds(executor, writes) {
399
+ const fresh = new Set();
400
+ const upserts = [];
401
+ for (const write of writes) {
402
+ const id = writeId(write);
403
+ if (id === undefined)
404
+ continue;
405
+ if (write.type === "entry" || write.type === "document.create" || write.type === "document.copy")
406
+ fresh.add(id);
407
+ else
408
+ upserts.push(id);
409
+ }
410
+ if (upserts.length > 0) {
411
+ const known = new Set((await executor.all(`SELECT id FROM ${T.recordIds} WHERE run_id = ? AND id IN (${upserts.map(() => "?").join(", ")})`, this.#runId, ...upserts)).map((row) => Number(row.id)));
412
+ for (const id of upserts)
413
+ if (!known.has(id))
414
+ fresh.add(id);
415
+ }
416
+ return fresh;
417
+ }
418
+ async #applyBatch(executor, writes, documentActions, seq) {
419
+ for (const write of writes)
420
+ await this.#applyTableWrite(executor, write, seq);
421
+ await this.#applyDocumentActions(executor, documentActions, seq);
422
+ await this.#logWrites(executor, writes, documentActions, seq);
423
+ }
424
+ /** This commit's own writes of the rows kept only as they are now (tasks, submissions, latest-only documents), as it
425
+ * wrote them, in its transaction (pi_commit_writes): the last write of a row within the commit is the one kept. */
426
+ async #logWrites(executor, writes, documentActions, seq) {
427
+ const log = (kind, id, value) => executor.run(`INSERT INTO ${T.commitWrites} (run_id, seq, kind, id, value) VALUES (?, ?, ?, ?, ?) ON CONFLICT (run_id, seq, kind, id) DO UPDATE SET value = excluded.value`, this.#runId, seq, kind, id, encodeJson(value));
428
+ for (const write of writes) {
429
+ if (write.type === "task" || write.type === "submission")
430
+ await log(write.type, write.value.id, write.value);
431
+ }
432
+ for (const id of documentActions.keys()) {
433
+ const row = await executor.get(`SELECT record FROM ${T.documents} WHERE run_id = ? AND id = ?`, this.#runId, id);
434
+ if (row === undefined)
435
+ continue;
436
+ const record = parseJson(row.record);
437
+ if (!isCurrentOnly(record))
438
+ continue;
439
+ if (record.retiredAt === seq) {
440
+ await log("document", id, { retired: true });
441
+ continue;
442
+ }
443
+ const stored = await this.#materializeDocument(executor, id, "current");
444
+ if (stored)
445
+ await log("document", id, { value: stored.value });
446
+ }
447
+ }
448
+ async mintId() {
449
+ this.#assertOpen();
450
+ await this.#opened();
451
+ if (!Number.isSafeInteger(this.#nextId))
452
+ throw new Error("ID space is exhausted");
453
+ const id = this.#nextId++;
454
+ this.#minted.add(id);
455
+ return idOf(id);
456
+ }
457
+ async conversation(id, _context) {
458
+ this.#assertOpen();
459
+ return this.#readConversation(id);
460
+ }
461
+ async scanConversations(query, limit, cursor, _context) {
462
+ this.#assertOpen();
463
+ const start = scanStart(query.order, cursor, "ascending");
464
+ const scan = scanSql(start);
465
+ const clauses = ["run_id = ?", scan.clause];
466
+ const params = [this.#runId, scan.param];
467
+ if (query.ownerConversationId !== undefined)
468
+ (clauses.push("owner_conversation_id = ?"), params.push(query.ownerConversationId));
469
+ if (query.ownerTaskId !== undefined)
470
+ (clauses.push("owner_task_id = ?"), params.push(query.ownerTaskId));
471
+ params.push(limit + 1);
472
+ const rows = await this.#read.all(`SELECT id, record FROM ${T.conversations} WHERE ${clauses.join(" AND ")} ORDER BY id ${scan.direction} LIMIT ?`, ...params);
473
+ return page(rows.map((row) => parseJson(row.record)), limit, start.order);
474
+ }
475
+ entry(idOrConversationId, idOrContext, context) {
476
+ return this.#admitRead(() => this.#readEntry(idOrConversationId, idOrContext, context));
477
+ }
478
+ findLatestHeadMarker(conversationId, atOrBeforeEntryId, _context) {
479
+ return this.#admitRead(() => this.#readLatestHeadMarker(conversationId, atOrBeforeEntryId));
480
+ }
481
+ scanEntries(query, limit, cursor, _context) {
482
+ return this.#admitRead(() => this.#readEntries(query, limit, cursor));
483
+ }
484
+ async #readEntry(idOrConversationId, idOrContext, context) {
485
+ const id = context === undefined ? idOrConversationId : typeof idOrContext === "number" ? idOrContext : undefined;
486
+ if (id === undefined)
487
+ throw new StorageRequestError("Storage.entry() requires an entry ID");
488
+ let conversation;
489
+ if (context !== undefined) {
490
+ const conversationId = idOf(idOrConversationId);
491
+ conversation = await this.#readConversation(conversationId);
492
+ if (conversation === undefined)
493
+ throw new StorageRequestError(`Unknown conversation: ${conversationId}`);
494
+ }
495
+ const row = await this.#read.get(`SELECT record, commit_seq FROM ${T.entries} WHERE run_id = ? AND id = ?`, this.#runId, id);
496
+ if (row === undefined)
497
+ return undefined;
498
+ const entry = parseJson(row.record);
499
+ if (conversation !== undefined) {
500
+ let upperEntryId = Number.POSITIVE_INFINITY;
501
+ while (conversation.id !== entry.conversationId) {
502
+ const parent = parentOf(conversation);
503
+ if (parent === undefined)
504
+ return undefined;
505
+ upperEntryId = Math.min(upperEntryId, parent.at);
506
+ conversation = (await this.#readConversation(parent.conversationId));
507
+ }
508
+ if (entry.id > upperEntryId)
509
+ return undefined;
510
+ }
511
+ return { entry, commitSeq: seqOf(Number(row.commit_seq)) };
512
+ }
513
+ async #readLatestHeadMarker(conversationId, atOrBeforeEntryId) {
514
+ let conversation = await this.#readConversation(conversationId);
515
+ if (conversation === undefined)
516
+ throw new StorageRequestError(`Unknown conversation: ${conversationId}`);
517
+ let upper = atOrBeforeEntryId;
518
+ while (true) {
519
+ const row = upper === undefined
520
+ ? await this.#read.get(`SELECT record FROM ${T.entries} WHERE run_id = ? AND conversation_id = ? AND head IS NOT NULL ORDER BY id DESC LIMIT 1`, this.#runId, conversation.id)
521
+ : await this.#read.get(`SELECT record FROM ${T.entries} WHERE run_id = ? AND conversation_id = ? AND head IS NOT NULL AND id <= ? ORDER BY id DESC LIMIT 1`, this.#runId, conversation.id, upper);
522
+ if (row !== undefined)
523
+ return parseJson(row.record);
524
+ const parent = parentOf(conversation);
525
+ if (parent === undefined)
526
+ return undefined;
527
+ upper = upper === undefined ? parent.at : Math.min(upper, parent.at);
528
+ conversation = (await this.#readConversation(parent.conversationId));
529
+ }
530
+ }
531
+ async #readEntries(query, limit, cursor) {
532
+ const { order, after } = scanStart(query.order, cursor, "descending");
533
+ const minEntryId = query.minEntryId;
534
+ const maxEntryId = query.maxEntryId;
535
+ if (order === "ascending")
536
+ return this.#readEntriesAscending(query.conversationId, minEntryId, maxEntryId, limit, after);
537
+ let conversation = await this.#readConversation(query.conversationId);
538
+ if (conversation === undefined)
539
+ throw new StorageRequestError(`Unknown conversation: ${query.conversationId}`);
540
+ let upper = maxEntryId;
541
+ if (after !== undefined)
542
+ upper = Math.min(upper ?? Number.MAX_SAFE_INTEGER, after - 1);
543
+ const values = [];
544
+ while (true) {
545
+ const clauses = ["run_id = ?", "conversation_id = ?"];
546
+ const params = [this.#runId, conversation.id];
547
+ if (minEntryId !== undefined)
548
+ (clauses.push("id >= ?"), params.push(minEntryId));
549
+ if (upper !== undefined)
550
+ (clauses.push("id <= ?"), params.push(upper));
551
+ params.push(limit + 1 - values.length);
552
+ const rows = await this.#read.all(`SELECT record FROM ${T.entries} WHERE ${clauses.join(" AND ")} ORDER BY id DESC LIMIT ?`, ...params);
553
+ values.push(...rows.map((row) => parseJson(row.record)));
554
+ const parent = parentOf(conversation);
555
+ if (values.length > limit || parent === undefined)
556
+ break;
557
+ const bound = upper === undefined ? parent.at : Math.min(upper, parent.at);
558
+ upper = bound;
559
+ if (minEntryId !== undefined && bound < minEntryId)
560
+ break;
561
+ conversation = (await this.#readConversation(parent.conversationId));
562
+ }
563
+ return page(values, limit, "descending");
564
+ }
565
+ /** Oldest first: the fork chain's segments from the root conversation forward, each up to its fork point. */
566
+ async #readEntriesAscending(conversationId, minEntryId, maxEntryId, limit, after) {
567
+ const segments = [];
568
+ let conversation = await this.#readConversation(conversationId);
569
+ if (conversation === undefined)
570
+ throw new StorageRequestError(`Unknown conversation: ${conversationId}`);
571
+ let upper = maxEntryId;
572
+ while (true) {
573
+ segments.push({ conversationId: conversation.id, upper });
574
+ const parent = parentOf(conversation);
575
+ if (parent === undefined)
576
+ break;
577
+ const bound = upper === undefined ? parent.at : Math.min(upper, parent.at);
578
+ upper = bound;
579
+ if (minEntryId !== undefined && bound < minEntryId)
580
+ break;
581
+ conversation = (await this.#readConversation(parent.conversationId));
582
+ }
583
+ let lower = minEntryId;
584
+ if (after !== undefined)
585
+ lower = Math.max(lower ?? after + 1, after + 1);
586
+ const values = [];
587
+ for (const segment of segments.reverse()) {
588
+ const clauses = ["run_id = ?", "conversation_id = ?"];
589
+ const params = [this.#runId, segment.conversationId];
590
+ if (lower !== undefined)
591
+ (clauses.push("id >= ?"), params.push(lower));
592
+ if (segment.upper !== undefined)
593
+ (clauses.push("id <= ?"), params.push(segment.upper));
594
+ params.push(limit + 1 - values.length);
595
+ const rows = await this.#read.all(`SELECT record FROM ${T.entries} WHERE ${clauses.join(" AND ")} ORDER BY id ASC LIMIT ?`, ...params);
596
+ values.push(...rows.map((row) => parseJson(row.record)));
597
+ if (values.length > limit)
598
+ break;
599
+ }
600
+ return page(values, limit, "ascending");
601
+ }
602
+ async task(id, _context) {
603
+ this.#assertOpen();
604
+ const row = await this.#read.get(`SELECT record FROM ${T.tasks} WHERE run_id = ? AND id = ?`, this.#runId, id);
605
+ return row === undefined ? undefined : parseJson(row.record);
606
+ }
607
+ async scanTasks(query, limit, cursor, _context) {
608
+ this.#assertOpen();
609
+ const start = scanStart(query.order, cursor, "ascending");
610
+ const scan = scanSql(start);
611
+ const clauses = ["run_id = ?", scan.clause];
612
+ const params = [this.#runId, scan.param];
613
+ if (query.conversationId !== undefined)
614
+ (clauses.push("conversation_id = ?"), params.push(query.conversationId));
615
+ if (query.kind !== undefined)
616
+ (clauses.push("kind = ?"), params.push(encodeIndexedString(query.kind)));
617
+ if (query.status !== undefined)
618
+ (clauses.push("status = ?"), params.push(query.status));
619
+ if (query.abortRequested !== undefined)
620
+ (clauses.push("abort_requested = ?"), params.push(query.abortRequested ? 1 : 0));
621
+ if (query.background !== undefined)
622
+ (clauses.push("background = ?"), params.push(query.background ? 1 : 0));
623
+ params.push(limit + 1);
624
+ const rows = await this.#read.all(`SELECT record FROM ${T.tasks} WHERE ${clauses.join(" AND ")} ORDER BY id ${scan.direction} LIMIT ?`, ...params);
625
+ return page(rows.map((row) => parseJson(row.record)), limit, start.order);
626
+ }
627
+ async submission(id, _context) {
628
+ this.#assertOpen();
629
+ const row = await this.#read.get(`SELECT record FROM ${T.submissions} WHERE run_id = ? AND id = ?`, this.#runId, id);
630
+ return row === undefined ? undefined : parseJson(row.record);
631
+ }
632
+ async scanSubmissions(query, limit, cursor, _context) {
633
+ this.#assertOpen();
634
+ const start = scanStart(query.order, cursor, "ascending");
635
+ const scan = scanSql(start);
636
+ const clauses = ["run_id = ?", scan.clause];
637
+ const params = [this.#runId, scan.param];
638
+ if (query.conversationId !== undefined)
639
+ (clauses.push("conversation_id = ?"), params.push(query.conversationId));
640
+ if (query.status !== undefined)
641
+ (clauses.push("status = ?"), params.push(query.status));
642
+ params.push(limit + 1);
643
+ const rows = await this.#read.all(`SELECT record FROM ${T.submissions} WHERE ${clauses.join(" AND ")} ORDER BY id ${scan.direction} LIMIT ?`, ...params);
644
+ return page(rows.map((row) => parseJson(row.record)), limit, start.order);
645
+ }
646
+ async submissionByRequest(conversationId, requestId, _context) {
647
+ this.#assertOpen();
648
+ const row = await this.#read.get(`SELECT record FROM ${T.submissions} WHERE run_id = ? AND conversation_id = ? AND request_id = ?`, this.#runId, conversationId, encodeIndexedString(requestId));
649
+ return row === undefined ? undefined : parseJson(row.record);
650
+ }
651
+ async findDocument(address, at, _context) {
652
+ this.#assertOpen();
653
+ const parts = addressParts(address);
654
+ const sql = at === "current"
655
+ ? `SELECT record FROM ${T.documents}
656
+ WHERE run_id = ? AND kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?
657
+ AND retired_at IS NULL ORDER BY created_at DESC LIMIT 1`
658
+ : `SELECT record FROM ${T.documents}
659
+ WHERE run_id = ? AND kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ?
660
+ AND created_at <= ? AND (retired_at IS NULL OR retired_at > ?)
661
+ ORDER BY created_at DESC LIMIT 1`;
662
+ const params = [this.#runId, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue];
663
+ if (at !== "current")
664
+ params.push(at, at);
665
+ const row = await this.#read.get(sql, ...params);
666
+ return row === undefined ? undefined : parseJson(row.record);
667
+ }
668
+ async document(id, at, _context) {
669
+ this.#assertOpen();
670
+ // The record and revision queries must observe one committed state; a commit between them can replace the base.
671
+ // One snapshot for both queries, in a deferred read transaction: no writer lock, so a read never waits behind a write.
672
+ return this.#db.transaction((tx) => this.#materializeDocument(tx, id, at), { read: true });
673
+ }
674
+ async scanDocuments(query, limit, cursor, _context) {
675
+ this.#assertOpen();
676
+ const scope = scopeColumns(query.scope);
677
+ const clauses = ["run_id = ?", "scope_kind = ?", "owner_id = ?", "id > ?"];
678
+ const params = [this.#runId, scope.scopeKind, scope.ownerId, cursorId(cursor) ?? -1];
679
+ if (query.kind !== undefined)
680
+ (clauses.push("kind = ?"), params.push(encodeIndexedString(query.kind)));
681
+ if (query.at === "current")
682
+ clauses.push("retired_at IS NULL");
683
+ else
684
+ (clauses.push("created_at <= ?", "(retired_at IS NULL OR retired_at > ?)"), params.push(query.at, query.at));
685
+ params.push(limit + 1);
686
+ const rows = await this.#read.all(`SELECT record FROM ${T.documents} WHERE ${clauses.join(" AND ")} ORDER BY id LIMIT ?`, ...params);
687
+ return page(rows.map((row) => parseJson(row.record)), limit);
688
+ }
689
+ /**
690
+ * The run's commits after `afterSeq`, in seq order, at most `limit`, for the live view: each with its own entries, the
691
+ * documents it changed (each's value at that seq, a latest-only one's as that commit wrote it; a retired one marked
692
+ * `retired`, with no value), and the tasks and submissions it wrote, as it wrote them (pi_commit_writes), so a replay
693
+ * equals the live view. One
694
+ * transaction, so the page is one committed state. `next`: the last seq returned, when commits may follow it. A
695
+ * run's seqs are consecutive from 1 (each stored batch takes the next), so a commit that wrote only a conversation is
696
+ * one too, with nothing listed.
697
+ */
698
+ async commitsAfter(afterSeq, limit, _context) {
699
+ this.#assertOpen();
700
+ // One snapshot in a deferred read transaction: a reader never takes the writer's lock.
701
+ return this.#admitRead(() => this.#db.transaction(async (tx) => {
702
+ const metadata = await this.#readMetadata(tx);
703
+ const last = Number(metadata.next_seq) - 1;
704
+ const from = Math.max(0, Math.floor(Number(afterSeq) || 0));
705
+ const upto = Math.min(last, from + Math.max(0, Math.floor(limit)));
706
+ const commits = [];
707
+ for (let seq = from + 1; seq <= upto; seq++)
708
+ commits.push(await this.#commitAt(tx, seq));
709
+ return upto < last && commits.length > 0 ? { commits, next: upto } : { commits };
710
+ }, { read: true }));
711
+ }
712
+ async #commitAt(tx, seq) {
713
+ const run = this.#runId;
714
+ const entries = (await tx.all(`SELECT record FROM ${T.entries} WHERE run_id = ? AND commit_seq = ? ORDER BY id`, run, seq)).map((row) => parseJson(row.record));
715
+ // This commit's own writes, as it wrote them (pi_commit_writes), never the rows as later commits left them.
716
+ const logged = await tx.all(`SELECT kind, id, value FROM ${T.commitWrites} WHERE run_id = ? AND seq = ? ORDER BY kind, id`, run, seq);
717
+ const tasks = logged.filter((row) => row.kind === "task").map((row) => parseJson(row.value));
718
+ const submissions = logged.filter((row) => row.kind === "submission").map((row) => parseJson(row.value));
719
+ const latestOnly = new Map(logged.filter((row) => row.kind === "document").map((row) => [row.id, parseJson(row.value)]));
720
+ const changed = await tx.all(`SELECT document_id AS id FROM ${T.documentRevisions} WHERE run_id = ? AND seq = ?
721
+ UNION SELECT id FROM ${T.documents} WHERE run_id = ? AND (created_at = ? OR retired_at = ?) ORDER BY id`, run, seq, run, seq, seq);
722
+ const documents = [];
723
+ // A latest-only document's revision of this commit is gone once a later commit wrote it: its log row names it.
724
+ const ids = [...new Set([...changed.map((row) => row.id), ...latestOnly.keys()])].sort((a, b) => a - b);
725
+ for (const id of ids) {
726
+ const row = await tx.get(`SELECT record FROM ${T.documents} WHERE run_id = ? AND id = ?`, run, id);
727
+ if (row === undefined)
728
+ continue;
729
+ const record = parseJson(row.record);
730
+ const scope = record.scope;
731
+ const head = { id: record.id, kind: record.kind, ...(scope.kind === "conversation" ? { conversationId: scope.conversationId } : {}) };
732
+ if (isCurrentOnly(record)) {
733
+ // A document that keeps only its latest value: as this commit wrote it (its log row), if it wrote it.
734
+ const written = latestOnly.get(id);
735
+ if (written?.retired)
736
+ documents.push({ ...head, retired: true });
737
+ else if (written)
738
+ documents.push({ ...head, value: written.value });
739
+ continue;
740
+ }
741
+ if (record.retiredAt === seq) {
742
+ documents.push({ ...head, retired: true });
743
+ continue;
744
+ }
745
+ // Its value at this seq (a document that keeps its history).
746
+ const stored = await this.#materializeDocument(tx, id, seq);
747
+ if (stored)
748
+ documents.push({ ...head, value: stored.value });
749
+ }
750
+ return { seq: seqOf(seq), entries, documents, tasks, submissions };
751
+ }
752
+ /** Every later operation rejects; reads admitted and commits asked before it end first (a commit's outcome is its
753
+ * caller's, never the close's). The store's connection stays open: the store owns it. */
754
+ close(_context) {
755
+ if (this.#closing === undefined) {
756
+ this.#closed = true;
757
+ this.#onClose?.();
758
+ const reads = this.#admittedReads > 0 ? new Promise((resolve) => (this.#readsDrained = resolve)) : Promise.resolve();
759
+ const commits = [...this.#pending].map((commit) => commit.then(() => undefined, () => undefined));
760
+ this.#closing = Promise.all([reads, ...commits]).then(() => undefined);
761
+ }
762
+ return this.#closing;
763
+ }
764
+ /** A read of several queries: close waits for it, so its later queries never run on a closed journal. */
765
+ async #admitRead(read) {
766
+ this.#assertOpen();
767
+ this.#admittedReads++;
768
+ try {
769
+ return await read();
770
+ }
771
+ finally {
772
+ if (--this.#admittedReads === 0)
773
+ this.#readsDrained?.();
774
+ }
775
+ }
776
+ async #readConversation(id) {
777
+ const row = await this.#read.get(`SELECT record FROM ${T.conversations} WHERE run_id = ? AND id = ?`, this.#runId, id);
778
+ return row === undefined ? undefined : parseJson(row.record);
779
+ }
780
+ async #materializeDocument(executor, id, at) {
781
+ const row = await executor.get(`SELECT record FROM ${T.documents} WHERE run_id = ? AND id = ?`, this.#runId, id);
782
+ if (row === undefined)
783
+ return undefined;
784
+ const record = parseJson(row.record);
785
+ if (at !== "current" && isCurrentOnly(record))
786
+ throw new StorageRequestError(`Document ${id} does not retain historical content`);
787
+ if (!isAliveAt(record, at))
788
+ return undefined;
789
+ const upper = at === "current" ? Number.MAX_SAFE_INTEGER : at;
790
+ const base = await executor.get(`SELECT seq, kind, version, content FROM ${T.documentRevisions}
791
+ WHERE run_id = ? AND document_id = ? AND kind = 'base' AND seq <= ? ORDER BY seq DESC LIMIT 1`, this.#runId, id, upper);
792
+ if (base === undefined)
793
+ throw new Error(`Document ${id} is missing a required base`);
794
+ let value = parseJson(base.content);
795
+ const tail = await executor.all(`SELECT seq, kind, version, content FROM ${T.documentRevisions}
796
+ WHERE run_id = ? AND document_id = ? AND seq > ? AND seq <= ? ORDER BY seq`, this.#runId, id, base.seq, upper);
797
+ for (const revision of tail) {
798
+ if (revision.kind !== "delta" || revision.version !== base.version)
799
+ throw new Error(`Document ${id} crosses a stored version boundary without a base`);
800
+ value = apply(value, parseJson(revision.content));
801
+ }
802
+ return { record, version: base.version, value, deltasSinceBase: tail.length };
803
+ }
804
+ #candidateNextId(writes) {
805
+ let nextId = this.#nextId;
806
+ for (const write of writes) {
807
+ const id = writeId(write);
808
+ if (id !== undefined)
809
+ nextId = Math.max(nextId, id + 1);
810
+ }
811
+ return nextId;
812
+ }
813
+ async #checkGlobalIds(executor, writes) {
814
+ const claimed = new Map();
815
+ for (const write of writes) {
816
+ if (write.type === "document.change" || write.type === "document.retire")
817
+ continue;
818
+ const document = write.type === "document.create" || write.type === "document.copy";
819
+ const table = document ? "document" : write.type;
820
+ const id = (document ? write.record.id : write.value.id);
821
+ const existing = (await executor.get(`SELECT record_type FROM ${T.recordIds} WHERE run_id = ? AND id = ?`, this.#runId, id))?.record_type;
822
+ const earlier = claimed.get(id);
823
+ if (table === "conversation" || table === "entry" || table === "document") {
824
+ if (existing !== undefined)
825
+ throw new Error(`ID ${id} already belongs to ${existing}`);
826
+ if (earlier !== undefined)
827
+ throw new Error(`ID ${id} is written more than once`);
828
+ }
829
+ else {
830
+ if (existing !== undefined && existing !== table)
831
+ throw new Error(`ID ${id} already belongs to ${existing}`);
832
+ if (earlier !== undefined && earlier !== table)
833
+ throw new Error(`ID ${id} is written as two record types`);
834
+ }
835
+ claimed.set(id, table);
836
+ }
837
+ }
838
+ #prepareDocumentActions(writes) {
839
+ const actions = new Map();
840
+ for (const write of writes) {
841
+ if (write.type !== "document.create" && write.type !== "document.copy" && write.type !== "document.change" && write.type !== "document.retire")
842
+ continue;
843
+ const id = (write.type === "document.create" || write.type === "document.copy" ? write.record.id : write.id);
844
+ let action = actions.get(id);
845
+ if (action === undefined)
846
+ actions.set(id, (action = { retire: false }));
847
+ switch (write.type) {
848
+ case "document.create":
849
+ if (action.create !== undefined || action.content !== undefined || action.copy !== undefined)
850
+ throw new Error(`Document ${id} has more than one content command`);
851
+ action.create = write.record;
852
+ action.content = write.content;
853
+ break;
854
+ case "document.copy":
855
+ if (action.create !== undefined || action.content !== undefined || action.copy !== undefined)
856
+ throw new Error(`Document ${id} has more than one content command`);
857
+ action.create = write.record;
858
+ action.copy = write.source;
859
+ break;
860
+ case "document.change":
861
+ if (action.content !== undefined || action.copy !== undefined)
862
+ throw new Error(`Document ${id} has more than one content command`);
863
+ action.content = write.content;
864
+ break;
865
+ case "document.retire":
866
+ if (action.retire)
867
+ throw new Error(`Document ${id} is retired more than once`);
868
+ action.retire = true;
869
+ break;
870
+ }
871
+ }
872
+ return actions;
873
+ }
874
+ async #checkDocumentActions(executor, actions) {
875
+ const liveCounts = new Map();
876
+ for (const [id, action] of actions) {
877
+ if (action.copy !== undefined && actions.has(action.copy.id))
878
+ throw new Error(`Document copy ${id} source is changed in the copy batch`);
879
+ const row = await executor.get(`SELECT record FROM ${T.documents} WHERE run_id = ? AND id = ?`, this.#runId, id);
880
+ const existing = row === undefined ? undefined : parseJson(row.record);
881
+ if (action.create === undefined && existing === undefined)
882
+ throw new Error(`Unknown document: ${id}`);
883
+ if (action.create !== undefined && existing !== undefined)
884
+ throw new Error(`Document ${id} already exists`);
885
+ if (existing?.retiredAt !== undefined)
886
+ throw new Error(`Document ${id} is retired`);
887
+ if (action.content?.kind === "delta") {
888
+ const previous = await executor.get(`SELECT version FROM ${T.documentRevisions} WHERE run_id = ? AND document_id = ? ORDER BY seq DESC LIMIT 1`, this.#runId, id);
889
+ if (previous === undefined)
890
+ throw new Error(`Document ${id} delta has no base`);
891
+ if (previous.version !== action.content.version)
892
+ throw new Error(`Document ${id} version transition requires a base`);
893
+ }
894
+ const record = (action.create ?? existing);
895
+ const key = addressKey(record);
896
+ let live = liveCounts.get(key);
897
+ if (live === undefined)
898
+ live = (await this.#currentDocumentId(executor, record)) === undefined ? 0 : 1;
899
+ if (action.retire && existing !== undefined)
900
+ live--;
901
+ if (action.create !== undefined && !action.retire)
902
+ live++;
903
+ liveCounts.set(key, live);
904
+ }
905
+ for (const live of liveCounts.values())
906
+ if (live > 1)
907
+ throw new Error("Document address already has a current incarnation");
908
+ }
909
+ async #currentDocumentId(executor, address) {
910
+ const parts = addressParts(address);
911
+ const row = await executor.get(`SELECT id FROM ${T.documents}
912
+ WHERE run_id = ? AND kind = ? AND scope_kind = ? AND owner_id = ? AND family = ? AND key_value = ? AND retired_at IS NULL
913
+ LIMIT 1`, this.#runId, parts.kind, parts.scopeKind, parts.ownerId, parts.family, parts.keyValue);
914
+ return row?.id;
915
+ }
916
+ async #applyTableWrite(executor, write, seq) {
917
+ const run = this.#runId;
918
+ switch (write.type) {
919
+ case "conversation": {
920
+ const value = write.value;
921
+ await this.#claimId(executor, value.id, "conversation");
922
+ await executor.run(`INSERT INTO ${T.conversations} (run_id, id, owner_conversation_id, owner_task_id, record) VALUES (?, ?, ?, ?, ?)`, run, value.id, value.owner?.conversationId ?? null, value.owner?.taskId ?? null, encodeJson(value));
923
+ break;
924
+ }
925
+ case "entry": {
926
+ const value = write.value;
927
+ await this.#claimId(executor, value.id, "entry");
928
+ await executor.run(`INSERT INTO ${T.entries} (run_id, id, conversation_id, head, commit_seq, record) VALUES (?, ?, ?, ?, ?, ?)`, run, value.id, value.conversationId, value.head ?? null, seq, encodeJson(value));
929
+ break;
930
+ }
931
+ case "task": {
932
+ const value = write.value;
933
+ await this.#claimId(executor, value.id, "task");
934
+ await executor.run(`INSERT INTO ${T.tasks} (run_id, id, conversation_id, kind, status, abort_requested, background, seq, record)
935
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
936
+ ON CONFLICT(run_id, id) DO UPDATE SET conversation_id = excluded.conversation_id, kind = excluded.kind,
937
+ status = excluded.status, abort_requested = excluded.abort_requested,
938
+ background = excluded.background, seq = excluded.seq, record = excluded.record`, run, value.id, value.conversationId, encodeIndexedString(value.kind), value.state.status, value.abortRequested ? 1 : 0, value.background ? 1 : 0, seq, encodeJson(value));
939
+ break;
940
+ }
941
+ case "submission": {
942
+ const value = write.value;
943
+ await this.#claimId(executor, value.id, "submission");
944
+ await executor.run(`INSERT INTO ${T.submissions} (run_id, id, conversation_id, request_id, status, seq, record) VALUES (?, ?, ?, ?, ?, ?, ?)
945
+ ON CONFLICT(run_id, id) DO UPDATE SET conversation_id = excluded.conversation_id,
946
+ request_id = excluded.request_id, status = excluded.status, seq = excluded.seq, record = excluded.record`, run, value.id, value.conversationId, value.requestId === undefined ? null : encodeIndexedString(value.requestId), value.status, seq, encodeJson(value));
947
+ break;
948
+ }
949
+ default:
950
+ break;
951
+ }
952
+ }
953
+ async #claimId(executor, id, table) {
954
+ const d = this.#dialect;
955
+ await executor.run(`${d.insertOrIgnore} INTO ${T.recordIds} (run_id, id, record_type) VALUES (?, ?, ?)${d.onConflictIgnore}`, this.#runId, id, table);
956
+ }
957
+ /** Resolve each copy to a base of its source's state before this batch, which may not change the source. */
958
+ async #resolveCopies(executor, actions) {
959
+ for (const [id, action] of actions) {
960
+ if (action.copy === undefined)
961
+ continue;
962
+ try {
963
+ const stored = (await this.#materializeDocument(executor, action.copy.id, action.copy.at));
964
+ if (stored === undefined)
965
+ throw new Error(`Fork source document ${action.copy.id} cannot be read`);
966
+ const create = action.create;
967
+ if (stored.record.scope.kind !== "conversation" ||
968
+ create.scope.kind !== "conversation" ||
969
+ stored.record.kind !== create.kind ||
970
+ stored.record.key !== create.key ||
971
+ stored.record.history !== create.history ||
972
+ stored.record.fork !== create.fork) {
973
+ throw new Error(`Fork source document ${action.copy.id} does not match the copied record`);
974
+ }
975
+ action.content = { kind: "base", version: stored.version, value: stored.value };
976
+ }
977
+ catch (error) {
978
+ throw new Error(`Document copy ${id} was rejected`, { cause: error });
979
+ }
980
+ }
981
+ }
982
+ async #applyDocumentActions(executor, actions, seq) {
983
+ const run = this.#runId;
984
+ const at = seq;
985
+ for (const [id, action] of actions) {
986
+ // Copies are resolved to their content by #resolveCopies.
987
+ const content = action.content;
988
+ let record;
989
+ if (action.create !== undefined) {
990
+ record = { ...action.create, createdAt: seq, ...(action.retire ? { retiredAt: seq } : {}) };
991
+ const parts = addressParts(record);
992
+ await this.#claimId(executor, id, "document");
993
+ await executor.run(`INSERT INTO ${T.documents}
994
+ (run_id, id, kind, family, key_value, scope_kind, owner_id, created_at, retired_at, record)
995
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, run, id, parts.kind, parts.family, parts.keyValue, parts.scopeKind, parts.ownerId, at, action.retire ? at : null, encodeJson(record));
996
+ }
997
+ else {
998
+ const row = (await executor.get(`SELECT record FROM ${T.documents} WHERE run_id = ? AND id = ?`, run, id));
999
+ record = parseJson(row.record);
1000
+ }
1001
+ if (content !== undefined) {
1002
+ if (content.kind === "base" && isCurrentOnly(record))
1003
+ await executor.run(`DELETE FROM ${T.documentRevisions} WHERE run_id = ? AND document_id = ?`, run, id);
1004
+ const encoded = content.kind === "base" ? encodeJson(content.value) : encodeJson(content.ops);
1005
+ await executor.run(`INSERT INTO ${T.documentRevisions} (run_id, document_id, seq, kind, version, content) VALUES (?, ?, ?, ?, ?, ?)`, run, id, at, content.kind, content.version, encoded);
1006
+ }
1007
+ if (action.retire) {
1008
+ if (action.create === undefined) {
1009
+ record = { ...record, retiredAt: seq };
1010
+ await executor.run(`UPDATE ${T.documents} SET retired_at = ?, record = ? WHERE run_id = ? AND id = ?`, at, encodeJson(record), run, id);
1011
+ }
1012
+ if (isCurrentOnly(record))
1013
+ await executor.run(`DELETE FROM ${T.documentRevisions} WHERE run_id = ? AND document_id = ?`, run, id);
1014
+ }
1015
+ }
1016
+ }
1017
+ #assertOpen() {
1018
+ if (this.#closed)
1019
+ throw new Error("RunStorage is closed");
1020
+ }
1021
+ }