@parcha/agentrun-serve 0.1.0-beta.38 → 0.1.0-beta.40

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 (423) hide show
  1. package/CHANGELOG.md +455 -0
  2. package/README.md +376 -125
  3. package/dist/adapters.d.ts +4 -1
  4. package/dist/adapters.js +4 -2
  5. package/dist/agent-rows.d.ts +0 -2
  6. package/dist/agents-store.d.ts +5 -5
  7. package/dist/agents-store.js +14 -14
  8. package/dist/bash-read-only.js +2 -1
  9. package/dist/cap-short.d.ts +12 -0
  10. package/dist/cap-short.js +60 -0
  11. package/dist/cap.d.ts +3 -10
  12. package/dist/cap.js +2 -5
  13. package/dist/catalog.d.ts +0 -5
  14. package/dist/catalog.js +1 -5
  15. package/dist/chatgpt-plan.d.ts +163 -0
  16. package/dist/chatgpt-plan.js +549 -0
  17. package/dist/cli.js +26 -6
  18. package/dist/composio-preset.d.ts +8 -0
  19. package/dist/composio-preset.js +8 -7
  20. package/dist/composio-triggers.d.ts +113 -0
  21. package/dist/composio-triggers.js +411 -0
  22. package/dist/computer-calls.js +2 -2
  23. package/dist/computer-commands.d.ts +2 -0
  24. package/dist/computer-commands.js +7 -3
  25. package/dist/computer-live.d.ts +7 -2
  26. package/dist/computer-live.js +9 -5
  27. package/dist/computer-routes.d.ts +2 -2
  28. package/dist/computer-routes.js +2 -2
  29. package/dist/computer-setting.d.ts +3 -3
  30. package/dist/computer-setting.js +5 -5
  31. package/dist/computer-view.d.ts +15 -0
  32. package/dist/computer-view.js +16 -2
  33. package/dist/computer-viewer.js +14 -1
  34. package/dist/computers.d.ts +5 -2
  35. package/dist/computers.js +9 -5
  36. package/dist/console/assets/index-B8Zn1Iqn.css +1 -0
  37. package/dist/console/assets/index-Jbxjcmdp.js +705 -0
  38. package/dist/console/index.html +2 -2
  39. package/dist/console-links.js +3 -3
  40. package/dist/decision-cap.d.ts +2 -5
  41. package/dist/decision-cap.js +3 -6
  42. package/dist/decision-rows.js +11 -11
  43. package/dist/email/account.d.ts +83 -0
  44. package/dist/email/account.js +159 -0
  45. package/dist/email/answer.d.ts +15 -0
  46. package/dist/email/answer.js +217 -0
  47. package/dist/email/email-faux.d.ts +95 -0
  48. package/dist/email/email-faux.js +849 -0
  49. package/dist/email/labels.d.ts +1 -0
  50. package/dist/email/labels.js +84 -0
  51. package/dist/email/mail.d.ts +186 -0
  52. package/dist/email/mail.js +373 -0
  53. package/dist/email/names.d.ts +50 -0
  54. package/dist/email/names.js +74 -0
  55. package/dist/email/routes.d.ts +10 -0
  56. package/dist/email/routes.js +50 -0
  57. package/dist/email/tools.d.ts +27 -0
  58. package/dist/email/tools.js +562 -0
  59. package/dist/environment.d.ts +17 -2
  60. package/dist/environment.js +36 -8
  61. package/dist/errors.d.ts +6 -0
  62. package/dist/errors.js +12 -0
  63. package/dist/eval-mailbox.d.ts +103 -0
  64. package/dist/eval-mailbox.js +236 -0
  65. package/dist/graph-view.d.ts +9 -2
  66. package/dist/graph-view.js +6 -2
  67. package/dist/harness-install.d.ts +28 -2
  68. package/dist/harness-install.js +147 -59
  69. package/dist/harness-opencode/adapter.js +2 -26
  70. package/dist/harness-opencode/facts.js +5 -2
  71. package/dist/harness-opencode/host/policy.d.ts +2 -0
  72. package/dist/harness-opencode/host/policy.js +10 -5
  73. package/dist/harness-opencode/index.d.ts +1 -1
  74. package/dist/harness-opencode/index.js +1 -1
  75. package/dist/harness-opencode/versions.d.ts +6 -0
  76. package/dist/harness-opencode/versions.js +6 -0
  77. package/dist/harness-table.js +8 -5
  78. package/dist/harness.d.ts +12 -0
  79. package/dist/harness.js +15 -3
  80. package/dist/hosted-search.d.ts +3 -1
  81. package/dist/hosted-search.js +51 -11
  82. package/dist/import-sources.d.ts +1 -1
  83. package/dist/import-sources.js +3 -3
  84. package/dist/import.d.ts +21 -0
  85. package/dist/import.js +186 -1
  86. package/dist/key-check.d.ts +0 -2
  87. package/dist/key-check.js +3 -4
  88. package/dist/key-refusal.d.ts +8 -2
  89. package/dist/key-refusal.js +16 -13
  90. package/dist/learn/check.d.ts +18 -3
  91. package/dist/learn/check.js +328 -3
  92. package/dist/learn/compile.d.ts +12 -4
  93. package/dist/learn/compile.js +57 -20
  94. package/dist/learn/grade.d.ts +4 -0
  95. package/dist/learn/grade.js +4 -1
  96. package/dist/learn/promote.d.ts +130 -64
  97. package/dist/learn/promote.js +113 -202
  98. package/dist/learn/refit.d.ts +21 -12
  99. package/dist/learn/refit.js +51 -23
  100. package/dist/learn/replay-calls.js +1 -1
  101. package/dist/learn/skills.d.ts +2 -7
  102. package/dist/learn/skills.js +28 -14
  103. package/dist/learned-nodes.d.ts +15 -7
  104. package/dist/learned-nodes.js +29 -5
  105. package/dist/learned-workflow.d.ts +41 -31
  106. package/dist/learned-workflow.js +122 -63
  107. package/dist/learning-batch.js +3 -3
  108. package/dist/learning-cost.d.ts +35 -8
  109. package/dist/learning-cost.js +27 -9
  110. package/dist/learning-routes.d.ts +2 -4
  111. package/dist/learning-routes.js +20 -3
  112. package/dist/learning-words.d.ts +1 -1
  113. package/dist/learning-words.js +4 -1
  114. package/dist/learning.d.ts +5 -5
  115. package/dist/link-check.d.ts +27 -0
  116. package/dist/link-check.js +164 -0
  117. package/dist/local-models.d.ts +39 -2
  118. package/dist/local-models.js +49 -5
  119. package/dist/mcp-pin-first.js +6 -0
  120. package/dist/mcp-secret-writes.js +3 -0
  121. package/dist/mcp-servers-store.d.ts +25 -16
  122. package/dist/mcp-servers-store.js +23 -3
  123. package/dist/model-form.d.ts +11 -0
  124. package/dist/model-form.js +17 -1
  125. package/dist/model.d.ts +26 -6
  126. package/dist/model.js +126 -18
  127. package/dist/monid.d.ts +26 -31
  128. package/dist/monid.js +84 -79
  129. package/dist/native/binding.d.ts +13 -0
  130. package/dist/native/binding.js +57 -0
  131. package/dist/native/cli.d.ts +2 -0
  132. package/dist/native/cli.js +48 -0
  133. package/dist/native/connection.d.ts +8 -0
  134. package/dist/native/connection.js +94 -0
  135. package/dist/native/context.d.ts +6 -0
  136. package/dist/native/context.js +22 -0
  137. package/dist/native/discovery.d.ts +27 -0
  138. package/dist/native/discovery.js +404 -0
  139. package/dist/native/environment.d.ts +4 -0
  140. package/dist/native/environment.js +18 -0
  141. package/dist/native/history.d.ts +20 -0
  142. package/dist/native/history.js +147 -0
  143. package/dist/native/instructions.d.ts +21 -0
  144. package/dist/native/instructions.js +173 -0
  145. package/dist/native/remote-worker-bridge.d.ts +3 -0
  146. package/dist/native/remote-worker-bridge.js +278 -0
  147. package/dist/native/remote.d.ts +187 -0
  148. package/dist/native/remote.js +492 -0
  149. package/dist/native/runtime.d.ts +17 -0
  150. package/dist/native/runtime.js +316 -0
  151. package/dist/native/runtimes.d.ts +66 -0
  152. package/dist/native/runtimes.js +41 -0
  153. package/dist/native/schema.d.ts +46 -0
  154. package/dist/native/schema.js +41 -0
  155. package/dist/native/types.d.ts +87 -0
  156. package/dist/native/types.js +1 -0
  157. package/dist/observation/http.d.ts +4 -0
  158. package/dist/observation/http.js +140 -0
  159. package/dist/observation/observer.d.ts +301 -0
  160. package/dist/observation/observer.js +919 -0
  161. package/dist/observation/schema.d.ts +52 -0
  162. package/dist/observation/schema.js +154 -0
  163. package/dist/openapi.d.ts +2 -1
  164. package/dist/openapi.js +404 -93
  165. package/dist/paid-calls.d.ts +8 -3
  166. package/dist/paid-calls.js +6 -2
  167. package/dist/place-offers.d.ts +4 -8
  168. package/dist/place-offers.js +4 -9
  169. package/dist/port-models.d.ts +10 -2
  170. package/dist/port-models.js +6 -2
  171. package/dist/print.d.ts +4 -2
  172. package/dist/print.js +4 -3
  173. package/dist/propose.d.ts +1 -2
  174. package/dist/propose.js +10 -1
  175. package/dist/provider.d.ts +5 -1
  176. package/dist/provider.js +8 -0
  177. package/dist/push-handler.d.ts +3 -2
  178. package/dist/push-handler.js +20 -6
  179. package/dist/refusal-words.d.ts +14 -0
  180. package/dist/refusal-words.js +16 -2
  181. package/dist/run-launch.d.ts +12 -1
  182. package/dist/run-launch.js +13 -4
  183. package/dist/run-learning-served.d.ts +75 -2
  184. package/dist/run-manifest.d.ts +3 -0
  185. package/dist/run-manifest.js +13 -1
  186. package/dist/run-reads-over-store.d.ts +3 -3
  187. package/dist/run-reads-over-store.js +13 -10
  188. package/dist/run-timeline-served.d.ts +3 -2
  189. package/dist/run-timeline-served.js +8 -9
  190. package/dist/run-view.d.ts +44 -38
  191. package/dist/run-view.js +93 -56
  192. package/dist/runnable.d.ts +13 -5
  193. package/dist/runnable.js +69 -60
  194. package/dist/runner/adapter-loop.d.ts +48 -13
  195. package/dist/runner/adapter-loop.js +691 -254
  196. package/dist/runner/adapter-run-spec.d.ts +38 -12
  197. package/dist/runner/adapter-run-spec.js +175 -106
  198. package/dist/runner/adapters/pi.d.ts +24 -0
  199. package/dist/runner/adapters/pi.js +59 -9
  200. package/dist/runner/beside.d.ts +3 -1
  201. package/dist/runner/beside.js +24 -8
  202. package/dist/runner/claim-secrets.d.ts +3 -1
  203. package/dist/runner/claim-secrets.js +28 -4
  204. package/dist/runner/cli-run-spec.d.ts +30 -0
  205. package/dist/runner/cli-run-spec.js +95 -50
  206. package/dist/runner/computer-channel.d.ts +5 -2
  207. package/dist/runner/computer-channel.js +3 -2
  208. package/dist/runner/computer-journal.d.ts +6 -0
  209. package/dist/runner/computer-journal.js +8 -10
  210. package/dist/runner/conformance/harness.js +6 -3
  211. package/dist/runner/end-of-run.d.ts +2 -0
  212. package/dist/runner/end-of-run.js +3 -1
  213. package/dist/runner/feedback-round.d.ts +40 -13
  214. package/dist/runner/feedback-round.js +64 -16
  215. package/dist/runner/harness-loops.js +17 -0
  216. package/dist/runner/journal-kinds.d.ts +59 -13
  217. package/dist/runner/journal-kinds.js +48 -5
  218. package/dist/runner/learning-dispatch.d.ts +3 -2
  219. package/dist/runner/learning-dispatch.js +6 -6
  220. package/dist/runner/learning-end.d.ts +4 -0
  221. package/dist/runner/learning-end.js +64 -36
  222. package/dist/runner/learning-factory.d.ts +3 -0
  223. package/dist/runner/learning-factory.js +8 -2
  224. package/dist/runner/learning-loop.d.ts +2 -0
  225. package/dist/runner/learning-loop.js +19 -4
  226. package/dist/runner/loop.d.ts +18 -0
  227. package/dist/runner/loop.js +34 -0
  228. package/dist/runner/main.d.ts +6 -1
  229. package/dist/runner/main.js +26 -4
  230. package/dist/runner/mcp-run.d.ts +4 -1
  231. package/dist/runner/mcp-run.js +11 -5
  232. package/dist/runner/meta-tools.d.ts +10 -3
  233. package/dist/runner/meta-tools.js +112 -36
  234. package/dist/runner/metrics.d.ts +80 -21
  235. package/dist/runner/metrics.js +114 -39
  236. package/dist/runner/model-route.d.ts +14 -3
  237. package/dist/runner/model-route.js +155 -19
  238. package/dist/runner/monid-run.d.ts +8 -6
  239. package/dist/runner/monid-run.js +117 -43
  240. package/dist/runner/native-loop.d.ts +11 -0
  241. package/dist/runner/native-loop.js +438 -0
  242. package/dist/runner/promotion.d.ts +76 -10
  243. package/dist/runner/promotion.js +476 -154
  244. package/dist/runner/redact.js +3 -0
  245. package/dist/runner/reflect-hook.js +9 -0
  246. package/dist/runner/runner.d.ts +7 -1
  247. package/dist/runner/runner.js +8 -4
  248. package/dist/runner/sdk-loop.d.ts +7 -0
  249. package/dist/runner/sdk-loop.js +470 -0
  250. package/dist/runner/spec-holds.d.ts +16 -2
  251. package/dist/runner/spec-holds.js +42 -14
  252. package/dist/runner/store-secrets.js +17 -2
  253. package/dist/runner/workflow-first.d.ts +30 -20
  254. package/dist/runner/workflow-first.js +22 -32
  255. package/dist/runner/workflow-loop.d.ts +1 -1
  256. package/dist/runner/workflow-loop.js +18 -12
  257. package/dist/runner/workflow-spec.d.ts +4 -1
  258. package/dist/runner/workflow-spec.js +56 -45
  259. package/dist/runs-over-store.d.ts +30 -2
  260. package/dist/runs-over-store.js +46 -14
  261. package/dist/sdk/runs.d.ts +115 -0
  262. package/dist/sdk/runs.js +422 -0
  263. package/dist/sdk/schema.d.ts +175 -0
  264. package/dist/sdk/schema.js +138 -0
  265. package/dist/sdk/workflows.d.ts +22 -0
  266. package/dist/sdk/workflows.js +39 -0
  267. package/dist/secrets.d.ts +2 -0
  268. package/dist/secrets.js +19 -1
  269. package/dist/server.d.ts +48 -32
  270. package/dist/server.js +568 -137
  271. package/dist/skill-route.d.ts +3 -0
  272. package/dist/skill-route.js +16 -0
  273. package/dist/skills/agentrun-serve/SKILL.md +368 -0
  274. package/dist/stats.d.ts +10 -10
  275. package/dist/store/agent-body.d.ts +12 -8
  276. package/dist/store/agent-body.js +9 -4
  277. package/dist/store/dialect.d.ts +3 -0
  278. package/dist/store/dialect.js +1 -0
  279. package/dist/store/index.d.ts +1 -1
  280. package/dist/store/native-command-owner.d.ts +10 -0
  281. package/dist/store/native-command-owner.js +47 -0
  282. package/dist/store/postgres/connection.d.ts +11 -5
  283. package/dist/store/postgres/connection.js +44 -17
  284. package/dist/store/postgres/dialect.js +5 -0
  285. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  286. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  287. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  288. package/dist/store/postgres/store.d.ts +7 -3
  289. package/dist/store/postgres/store.js +4 -0
  290. package/dist/store/schema.d.ts +7 -0
  291. package/dist/store/schema.js +20 -1
  292. package/dist/store/sqlite/connection.js +72 -8
  293. package/dist/store/sqlite/run-launch.d.ts +11 -0
  294. package/dist/store/sqlite/run-launch.js +8 -0
  295. package/dist/store/sqlite/run-patch.d.ts +8 -1
  296. package/dist/store/sqlite/run-patch.js +14 -3
  297. package/dist/store/sqlite/store.js +170 -34
  298. package/dist/store/sqlite/worker.d.ts +2 -0
  299. package/dist/store/sqlite/worker.js +13 -10
  300. package/dist/store/store.d.ts +67 -7
  301. package/dist/store-reads/analytics.d.ts +7 -7
  302. package/dist/store-reads/analytics.js +23 -5
  303. package/dist/store-reads/cap.js +8 -6
  304. package/dist/store-reads/journal.d.ts +5 -0
  305. package/dist/store-reads/journal.js +85 -41
  306. package/dist/store-reads/learning.d.ts +115 -18
  307. package/dist/store-reads/learning.js +170 -68
  308. package/dist/store-reads/runs.d.ts +5 -0
  309. package/dist/store-reads/runs.js +3 -2
  310. package/dist/store-view.js +75 -21
  311. package/dist/template-eval.d.ts +73 -11
  312. package/dist/template-eval.js +535 -75
  313. package/dist/templates.d.ts +84 -21
  314. package/dist/templates.js +254 -47
  315. package/dist/text-urls.d.ts +38 -0
  316. package/dist/text-urls.js +170 -0
  317. package/dist/timeline/index.d.ts +3 -2
  318. package/dist/timeline/index.js +3 -2
  319. package/dist/timeline/labels.d.ts +5 -2
  320. package/dist/timeline/labels.js +29 -6
  321. package/dist/timeline/origin.d.ts +1 -1
  322. package/dist/timeline/origin.js +2 -2
  323. package/dist/timeline/render-text.js +1 -1
  324. package/dist/timeline/timeline.d.ts +66 -4
  325. package/dist/timeline/timeline.js +160 -30
  326. package/dist/timeline/util.d.ts +5 -0
  327. package/dist/timeline/util.js +44 -8
  328. package/dist/timeline/web-calls.d.ts +17 -0
  329. package/dist/timeline/web-calls.js +106 -0
  330. package/dist/tool-gate.d.ts +46 -44
  331. package/dist/tool-gate.js +101 -92
  332. package/dist/tool-list.d.ts +4 -1
  333. package/dist/tool-list.js +8 -1
  334. package/dist/tool-names.d.ts +18 -13
  335. package/dist/tool-names.js +19 -17
  336. package/dist/tool-plane.d.ts +17 -13
  337. package/dist/tool-plane.js +12 -5
  338. package/dist/tools.d.ts +57 -16
  339. package/dist/tools.js +33 -28
  340. package/dist/trigger-adapter.d.ts +56 -5
  341. package/dist/trigger-adapter.js +6 -0
  342. package/dist/trigger-adapters.js +3 -1
  343. package/dist/trigger-composio.d.ts +10 -0
  344. package/dist/trigger-composio.js +122 -0
  345. package/dist/trigger-email.d.ts +4 -0
  346. package/dist/trigger-email.js +181 -0
  347. package/dist/trigger-signatures.d.ts +6 -10
  348. package/dist/trigger-signatures.js +16 -16
  349. package/dist/trigger-targets.d.ts +1 -1
  350. package/dist/trigger-targets.js +4 -3
  351. package/dist/trigger-webhook.js +6 -4
  352. package/dist/triggers.d.ts +105 -8
  353. package/dist/triggers.js +286 -62
  354. package/dist/uploads.d.ts +9 -0
  355. package/dist/uploads.js +27 -0
  356. package/dist/validate.js +1 -7
  357. package/dist/web-fake.d.ts +56 -0
  358. package/dist/web-fake.js +102 -0
  359. package/dist/web-fetch-direct.d.ts +3 -0
  360. package/dist/web-fetch-direct.js +4 -1
  361. package/dist/web-fetch.d.ts +5 -1
  362. package/dist/web-fetch.js +8 -31
  363. package/dist/web-search.d.ts +51 -2
  364. package/dist/web-search.js +116 -18
  365. package/dist/webhooks.d.ts +2 -1
  366. package/dist/webhooks.js +5 -1
  367. package/dist/workflow/decision-recovery.js +5 -2
  368. package/dist/workflow/decisions.d.ts +7 -0
  369. package/dist/workflow/node-runner.js +10 -2
  370. package/dist/workspace/archil-claim.d.ts +3 -0
  371. package/dist/workspace/archil-claim.js +9 -2
  372. package/dist/workspace/computer-deps.d.ts +22 -9
  373. package/dist/workspace/computer-deps.js +78 -37
  374. package/dist/workspace/computer-for-claim.d.ts +54 -4
  375. package/dist/workspace/computer-for-claim.js +179 -39
  376. package/dist/workspace/computer-janitor.d.ts +10 -3
  377. package/dist/workspace/computer-janitor.js +96 -29
  378. package/dist/workspace/computer-kept.d.ts +82 -0
  379. package/dist/workspace/computer-kept.js +147 -0
  380. package/dist/workspace/computer-mcp.js +4 -3
  381. package/dist/workspace/computer-ports.d.ts +23 -3
  382. package/dist/workspace/computer-ports.js +115 -5
  383. package/dist/workspace/index.d.ts +1 -2
  384. package/dist/workspace/index.js +1 -2
  385. package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
  386. package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
  387. package/dist/workspace/resolve-computer.d.ts +15 -3
  388. package/dist/workspace/resolve-computer.js +10 -7
  389. package/dist/workspace/revision-skills.d.ts +6 -2
  390. package/dist/workspace/revision-skills.js +12 -5
  391. package/dist/workspace/run-end-computers.d.ts +30 -0
  392. package/dist/workspace/run-end-computers.js +137 -0
  393. package/dist/workspace/run-tools.d.ts +28 -29
  394. package/dist/workspace/run-tools.js +29 -30
  395. package/dist/wrap-up.d.ts +19 -5
  396. package/dist/wrap-up.js +31 -4
  397. package/package.json +13 -9
  398. package/skills/agentrun-serve/SKILL.md +248 -10
  399. package/templates/README.md +117 -23
  400. package/templates/TOOLS.md +168 -0
  401. package/templates/code-review/agent.md +18 -4
  402. package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
  403. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  404. package/templates/code-review/evals/other-repo/case.yaml +1 -1
  405. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  406. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  407. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  408. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  409. package/templates/code-review/skills/review/DEEP.md +2 -2
  410. package/templates/code-review/skills/review/REVIEWER.md +2 -2
  411. package/templates/code-review/skills/review/SKILL.md +7 -3
  412. package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
  413. package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
  414. package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
  415. package/templates/release-notes/evals/other-repo/case.yaml +1 -1
  416. package/dist/console/assets/index-CjqQirbo.css +0 -1
  417. package/dist/console/assets/index-b6-XY5A9.js +0 -576
  418. package/dist/host-calls.d.ts +0 -20
  419. package/dist/host-calls.js +0 -12
  420. package/dist/runner/adapters/pi-computer.d.ts +0 -9
  421. package/dist/runner/adapters/pi-computer.js +0 -51
  422. package/dist/workspace/computer-script.d.ts +0 -53
  423. package/dist/workspace/computer-script.js +0 -172
@@ -7,10 +7,11 @@
7
7
  import { existsSync, mkdirSync, readdirSync, statSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { DatabaseSync } from "node:sqlite";
10
+ import { backfillNativeCommandOwners, nativeCommandOwner, validConnectorId } from '../native-command-owner.js';
10
11
  import { watchCommandsAt, wakeCommands } from "../command-wake.js";
11
12
  import { claimFence, storeNow } from "../fence.js";
12
13
  import { RunStorage } from "../journal/storage.js";
13
- import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, REVISIONS_MCP_PIN, SCHEMA_VERSION } from "../schema.js";
14
+ import { COMMANDS_ONE_ANSWER, DDL, IMPORTED_TEMPLATES, NATIVE_COMMANDS_INDEX, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUNS_COST_UPPER_BOUND, SCHEMA_VERSION } from "../schema.js";
14
15
  import { AgentArchived, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreConstraint, StoreFromEarlierVersion, TriggerFull, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, } from "../store.js";
15
16
  /** The seq a run-change cursor names (Runs.changedSince): only a cursor this store handed back, a whole number. */
16
17
  const seqOf = (cursor) => {
@@ -18,10 +19,10 @@ const seqOf = (cursor) => {
18
19
  throw new TypeError(`${JSON.stringify(cursor)} is not a run-change cursor this store gave`);
19
20
  return Number(cursor);
20
21
  };
21
- import { settledBody } from "../dialect.js";
22
+ import { cleanText, settledBody } from "../dialect.js";
22
23
  import { Connection } from "./connection.js";
23
- import { applyRunPatch, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
24
- import { readLaunch, writeLaunch } from "./run-launch.js";
24
+ import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
25
+ import { readLaunch, readLearningStarts, writeLaunch } from "./run-launch.js";
25
26
  import { canonical } from "../agent-body.js";
26
27
  import { aadOf, sealedAt } from "../seal.js";
27
28
  /** A claim's length when the caller names none. */
@@ -54,7 +55,7 @@ function triggerSet(patch, at) {
54
55
  return { set: pairs.map(([column]) => `${column} = ?`).join(", "), params: pairs.map(([, value]) => value) };
55
56
  }
56
57
  const AGENT_COLUMNS = "id, name, description, current_revision, created_at, archived_at, external_ref";
57
- const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, package, created_at, external_version, mcp_pin";
58
+ const REVISION_COLUMNS = "id, agent_id, parent_id, kind, body, skills, note, package, created_at, external_version, mcp_pin, monid_pin";
58
59
  const COMMAND_COLUMNS = "id, run_id, kind, body, created_at, taken_at, refused, tries";
59
60
  const TRIGGER_COLUMNS = "id, agent_id, name, enabled, source, target, next_at, last_run_id, catchup_window_s, failures_in_a_row, disabled, max_active_runs, created_at, updated_at";
60
61
  const FINAL = FINAL_STATES.map((state) => `'${state}'`).join(", ");
@@ -97,7 +98,7 @@ const agentOf = (r) => ({ id: r.id, name: r.name, description: r.description, cu
97
98
  const revisionOf = (r) => ({
98
99
  id: r.id, agentId: r.agent_id, parent: r.parent_id, kind: r.kind, body: JSON.parse(r.body), skills: r.skills === null ? null : JSON.parse(r.skills),
99
100
  note: r.note, package: r.package === null ? null : JSON.parse(r.package), createdAt: r.created_at, externalVersion: r.external_version,
100
- mcpPin: r.mcp_pin === null ? null : JSON.parse(r.mcp_pin),
101
+ mcpPin: r.mcp_pin === null ? null : JSON.parse(r.mcp_pin), monidPin: r.monid_pin === null ? null : JSON.parse(r.monid_pin),
101
102
  });
102
103
  const commandOf = (r) => ({ id: r.id, runId: r.run_id, kind: r.kind, body: JSON.parse(r.body), createdAt: r.created_at, takenAt: r.taken_at, refused: r.refused, tries: r.tries });
103
104
  const triggerOf = (r) => ({
@@ -246,6 +247,23 @@ export async function openSqliteStore(options) {
246
247
  }
247
248
  if (found !== SCHEMA_VERSION)
248
249
  throw new SchemaVersionUnknown(file, found, SCHEMA_VERSION);
250
+ const columns = new Set((await connection.all("SELECT name FROM pragma_table_info('revisions')")).map((column) => column.name));
251
+ if (role === "runner" && (!columns.has("mcp_pin") || !columns.has("monid_pin")))
252
+ throw new Error("Start the AgentRun server to install MCP and Monid revision metadata before opening a runner. The runner does not upgrade this store.");
253
+ const nativeOwners = (await connection.all("PRAGMA table_info(settings)")).some(column => column.name === 'connector_id');
254
+ if (!nativeOwners) {
255
+ if (role === 'runner')
256
+ throw new Error('Native command ownership metadata is not prepared. Start this build’s server before its runners.');
257
+ await connection.write([{ sql: 'ALTER TABLE settings ADD COLUMN connector_id TEXT' }], { full: true });
258
+ }
259
+ // An earlier build of this version kept no bound beside a run's cost (schema.ts RUNS_COST_UPPER_BOUND): the server adds
260
+ // it, every run it ended reading 0, and a runner, which writes it at each end, waits for that server.
261
+ const costBound = (await connection.all("SELECT name FROM pragma_table_info('runs')")).some((column) => column.name === "cost_upper_bound");
262
+ if (!costBound) {
263
+ if (role === "runner")
264
+ throw new Error("Start the AgentRun server to add the bound beside each run's cost before opening a runner. The runner does not upgrade this store.");
265
+ await connection.write([{ sql: RUNS_COST_UPPER_BOUND }], { full: true });
266
+ }
249
267
  // The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
250
268
  // migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
251
269
  // An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
@@ -254,11 +272,12 @@ export async function openSqliteStore(options) {
254
272
  // acted on) and each later one is refused in the same write, before the index, so the store opens. None is deleted.
255
273
  // An earlier build of this version pinned each run's MCP tools at its first claim (mcp_pins) and kept no pin on a
256
274
  // revision: the server adds revisions.mcp_pin (schema.ts REVISIONS_MCP_PIN) and drops mcp_pins. A revision saved
257
- // before has no pin until its first run here pins it (Agents.pinOnce); no run's pin moves to a revision.
275
+ // before has no MCP pin until its first managed run here pins it (Agents.pinOnce); no run's pin moves to a revision.
276
+ // Monid pins are also nullable revision metadata; adding the column infers no pin from a historical body.
258
277
  if (role === "server") {
259
- const pinned = await connection.get("SELECT name FROM pragma_table_info('revisions') WHERE name = 'mcp_pin'");
260
278
  await connection.write([
261
- ...(pinned ? [] : [{ sql: REVISIONS_MCP_PIN }]),
279
+ ...(columns.has("mcp_pin") ? [] : [{ sql: REVISIONS_MCP_PIN }]),
280
+ ...(columns.has("monid_pin") ? [] : [{ sql: REVISIONS_MONID_PIN }]),
262
281
  { sql: "DROP TABLE IF EXISTS mcp_pins" },
263
282
  { sql: "DROP TABLE IF EXISTS browser_viewers" },
264
283
  { sql: SECOND_ANSWERS_REFUSED, params: [(options.now ?? Date.now)()] },
@@ -266,7 +285,9 @@ export async function openSqliteStore(options) {
266
285
  { sql: COMMANDS_ONE_ANSWER },
267
286
  // An earlier build of this version kept no imported template packages (schema.ts IMPORTED_TEMPLATES).
268
287
  { sql: IMPORTED_TEMPLATES },
288
+ { sql: NATIVE_COMMANDS_INDEX },
269
289
  ], { full: true });
290
+ await backfillNativeCommandOwners(connection);
270
291
  }
271
292
  }
272
293
  catch (error) {
@@ -281,6 +302,13 @@ const SECOND_ANSWERS_REFUSED = `UPDATE commands SET taken_at = COALESCE(taken_at
281
302
  AND id NOT IN (SELECT MIN(id) FROM commands WHERE kind IN ('approve', 'deny') AND refused IS NULL AND json_extract(body, '$.approval') IS NOT NULL GROUP BY run_id, json_extract(body, '$.approval'))`;
282
303
  /** How many released claims a store remembers, to refuse their journals. */
283
304
  const RELEASED_KEPT = 1024;
305
+ /** The most claims one statement of renewMany renews. Its WHERE joins each claim's fence with OR, and each OR is one more
306
+ * level of the expression tree, whose depth SQLite bounds at 1,000 (SQLITE_MAX_EXPR_DEPTH: 997 claims already fail). 250
307
+ * stays a quarter of that, and a runner's 300 claims are still two statements on a database a few ms away. */
308
+ const RENEW_CHUNK = 250;
309
+ /** A claim as renewMany matches it to the rows its update returned: its run, epoch and runner, each string as the store
310
+ * writes text (cleanText: a NUL as U+FFFD), so a claim and the row the database wrote for it make one key. */
311
+ const renewKey = (runId, epoch, runner) => `${cleanText(runId)}\u0000${epoch}\u0000${cleanText(runner)}`;
284
312
  /** The key of a claim's one journal: its run and epoch. */
285
313
  const journalKey = (claim) => `${claim.runId}\u0000${claim.epoch}`;
286
314
  /** A statement under `claim`: one that changes no row means the run's epoch moved on, and the transaction rolls back. */
@@ -386,7 +414,7 @@ class SqliteStore {
386
414
  throw new StoreConstraint(`no agent ${agentId}`);
387
415
  if (ifCurrent !== undefined && agent.current_revision !== ifCurrent)
388
416
  throw new RevisionMoved(agentId, agent.current_revision);
389
- await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, created_at, mcp_pin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", revision.id, agentId, agent.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, revision.package === undefined ? null : json(revision.package), at, pinText(revision.mcpPin));
417
+ await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, created_at, mcp_pin, monid_pin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", revision.id, agentId, agent.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, revision.package === undefined ? null : json(revision.package), at, pinText(revision.mcpPin), pinText(revision.monidPin));
390
418
  await tx.run("UPDATE agents SET current_revision = ? WHERE id = ?", revision.id, agentId);
391
419
  };
392
420
  const writeScopes = async (tx, triggerId, scopes) => {
@@ -784,7 +812,7 @@ class SqliteStore {
784
812
  }
785
813
  else {
786
814
  revisionId = revision.id;
787
- await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, external_version, created_at, mcp_pin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", revisionId, mapped.id, mapped.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, null, revision.version, at, pinText(revision.mcpPin));
815
+ await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, external_version, created_at, mcp_pin, monid_pin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", revisionId, mapped.id, mapped.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, null, revision.version, at, pinText(revision.mcpPin), pinText(revision.monidPin));
788
816
  await tx.run("UPDATE agents SET current_revision = ?, name = ?, description = ? WHERE id = ?", revisionId, agent.name, agent.description ?? null, mapped.id);
789
817
  }
790
818
  // The run, its origin and its launch, in the same transaction as the agent and the revision.
@@ -801,6 +829,7 @@ class SqliteStore {
801
829
  return row && runOf(row);
802
830
  },
803
831
  launch: (runId) => readLaunch(db, runId),
832
+ learningStarts: (agentId) => readLearningStarts(db, agentId, NOT_A_LEARNING_RUN),
804
833
  list: async ({ agentId, revisionId, state, archived, limit }) => {
805
834
  // A built-in learning run (a run's grade and merge, queued with its kept learning) is no run of a person's: no list,
806
835
  // count, stat or notice names it.
@@ -1110,8 +1139,13 @@ class SqliteStore {
1110
1139
  return row ? proposalOf(row) : undefined;
1111
1140
  },
1112
1141
  proposals: async (agentId, { limit = 100 } = {}) => (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY created_at DESC, run_id DESC, round DESC LIMIT ?`, agentId, limit)).map(proposalOf),
1142
+ kept: async (agentId) => {
1143
+ const proposals = (await db.all(`SELECT ${PROPOSAL_COLUMNS} FROM learning_proposals WHERE agent_id = ? ORDER BY run_id, round`, agentId)).map(proposalOf);
1144
+ const learningRuns = (await db.all(`SELECT ${RUN_COLUMNS} FROM runs WHERE id IN (SELECT learning_run_id FROM learning_proposals WHERE agent_id = ? AND learning_run_id IS NOT NULL)`, agentId)).map(runOf);
1145
+ return { proposals, learningRuns };
1146
+ },
1113
1147
  spend: async ({ from, to }) => {
1114
- const rows = await db.all(`SELECT lp.agent_id, lp.proposal, lp.created_at, lp.learning_run_id, lr.state AS run_state, lr.ended_at AS run_ended_at, lr.cost_usd AS run_cost_usd
1148
+ const rows = await db.all(`SELECT lp.agent_id, lp.proposal, lp.created_at, lp.learning_run_id, lr.state AS run_state, lr.ended_at AS run_ended_at, ${EXACT_COST_USD("lr")} AS run_cost_usd
1115
1149
  FROM learning_proposals lp
1116
1150
  JOIN runs src ON src.id = lp.run_id
1117
1151
  LEFT JOIN runs lr ON lr.id = lp.learning_run_id
@@ -1128,7 +1162,7 @@ class SqliteStore {
1128
1162
  });
1129
1163
  },
1130
1164
  spentBeside: async (runId, { beforeRound } = {}) => {
1131
- const rows = await db.all(`SELECT lr.state, lr.cost_usd, rl.body
1165
+ const rows = await db.all(`SELECT lr.state, ${EXACT_COST_USD("lr")} AS cost_usd, rl.body
1132
1166
  FROM learning_proposals lp
1133
1167
  LEFT JOIN runs lr ON lr.id = lp.learning_run_id
1134
1168
  LEFT JOIN run_launch rl ON rl.run_id = lp.learning_run_id
@@ -1157,16 +1191,52 @@ class SqliteStore {
1157
1191
  return row === undefined ? undefined : JSON.parse(row.value);
1158
1192
  },
1159
1193
  put: async (key, value) => {
1160
- await db.write([{ sql: "INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at", params: [key, json(value), now()] }]);
1161
- },
1162
- putIfAbsent: async (key, value) => {
1163
- await db.write([{ sql: "INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) ON CONFLICT (key) DO NOTHING", params: [key, json(value), now()] }]);
1194
+ const encoded = json(value);
1195
+ await db.write([{ sql: "INSERT INTO settings (key, value, connector_id, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value, connector_id = excluded.connector_id, updated_at = excluded.updated_at", params: [key, encoded, nativeCommandOwner(key, encoded), now()] }]);
1196
+ },
1197
+ putIfAbsent: async (key, value, capacity) => {
1198
+ const encoded = json(value);
1199
+ if (capacity !== undefined) {
1200
+ if (typeof capacity.prefix !== "string" || !capacity.prefix || capacity.prefix.includes("\0") || !key.startsWith(capacity.prefix) || !Number.isSafeInteger(capacity.limit) || capacity.limit < 1)
1201
+ throw new TypeError("settings capacity requires a matching nonempty prefix and a positive safe integer limit");
1202
+ return db.transaction(async (tx) => {
1203
+ // SQLite holds its writer lock already; Postgres holds this schema's prefix lock until commit. The count
1204
+ // and insertion cannot interleave with another bounded insertion, even through an independent store handle.
1205
+ await d.lockKey(tx, `settings.capacity:${capacity.prefix}`);
1206
+ const existing = await tx.get("SELECT value FROM settings WHERE key = ?", key);
1207
+ if (existing !== undefined)
1208
+ return JSON.parse(existing.value);
1209
+ // Match Settings.all's literal prefix range: use the key index and never parse values or treat _/% as LIKE.
1210
+ const points = Array.from(capacity.prefix);
1211
+ let upper;
1212
+ for (let i = points.length - 1; i >= 0; i--) {
1213
+ const cp = points[i].codePointAt(0);
1214
+ if (cp < 0x10ffff) {
1215
+ upper = points.slice(0, i).join("") + String.fromCodePoint(cp + 1);
1216
+ break;
1217
+ }
1218
+ }
1219
+ const count = await tx.get(`SELECT count(*) AS n FROM settings WHERE key >= ?${upper === undefined ? "" : " AND key < ?"} AND substr(key, 1, length(?)) = ?`, capacity.prefix, ...(upper === undefined ? [] : [upper]), capacity.prefix, capacity.prefix);
1220
+ if (Number(count?.n ?? 0) >= capacity.limit)
1221
+ return undefined;
1222
+ await tx.run("INSERT INTO settings (key, value, connector_id, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO NOTHING", key, encoded, nativeCommandOwner(key, encoded), now());
1223
+ const saved = await tx.get("SELECT value FROM settings WHERE key = ?", key);
1224
+ return saved === undefined ? undefined : JSON.parse(saved.value);
1225
+ });
1226
+ }
1227
+ await db.write([{ sql: "INSERT INTO settings (key, value, connector_id, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO NOTHING", params: [key, encoded, nativeCommandOwner(key, encoded), now()] }]);
1164
1228
  const row = await db.get("SELECT value FROM settings WHERE key = ?", key);
1165
1229
  return row === undefined ? undefined : JSON.parse(row.value);
1166
1230
  },
1167
1231
  // `was` is compared as the JSON text put wrote: a row read and parsed gives the same text back, its keys in order.
1168
- replaceIf: async (key, was, value) => {
1169
- const [result] = await db.write([{ sql: "UPDATE settings SET value = ?, updated_at = ? WHERE key = ? AND value = ?", params: [json(value), now(), key, json(was)] }]);
1232
+ replaceIf: async (key, was, value, claim) => {
1233
+ const encoded = json(value);
1234
+ if (claim)
1235
+ return db.transaction(async (tx) => {
1236
+ const at = await underClaim(tx, claim, now);
1237
+ return await tx.runCounted("UPDATE settings SET value = ?, connector_id = ?, updated_at = ? WHERE key = ? AND value = ?", encoded, nativeCommandOwner(key, encoded), at, key, json(was)) === 1;
1238
+ });
1239
+ const [result] = await db.write([{ sql: "UPDATE settings SET value = ?, connector_id = ?, updated_at = ? WHERE key = ? AND value = ?", params: [encoded, nativeCommandOwner(key, encoded), now(), key, json(was)] }]);
1170
1240
  return result.changes === 1;
1171
1241
  },
1172
1242
  removeIf: async (key, was) => {
@@ -1176,7 +1246,38 @@ class SqliteStore {
1176
1246
  remove: async (key) => {
1177
1247
  await db.write([{ sql: "DELETE FROM settings WHERE key = ?", params: [key] }]);
1178
1248
  },
1179
- all: async () => (await db.all("SELECT key, value, updated_at FROM settings ORDER BY key")).map(settingOf),
1249
+ all: async (filter) => {
1250
+ const clauses = [], params = [];
1251
+ if (filter?.connectorId !== undefined && !validConnectorId(filter.connectorId))
1252
+ return [];
1253
+ if (filter) {
1254
+ // Both stores order keys by bytes (Postgres settings.key is COLLATE C). This range also enables namespace indexes.
1255
+ const points = Array.from(filter.prefix);
1256
+ let upper;
1257
+ for (let i = points.length - 1; i >= 0; i--) {
1258
+ const cp = points[i].codePointAt(0);
1259
+ if (cp < 0x10ffff) {
1260
+ upper = points.slice(0, i).join("") + String.fromCodePoint(cp + 1);
1261
+ break;
1262
+ }
1263
+ }
1264
+ clauses.push("key >= ?");
1265
+ params.push(filter.prefix);
1266
+ if (upper !== undefined) {
1267
+ clauses.push("key < ?");
1268
+ params.push(upper);
1269
+ }
1270
+ clauses.push("substr(key, 1, length(?)) = ?");
1271
+ params.push(filter.prefix, filter.prefix);
1272
+ }
1273
+ const selection = `SELECT key, value, updated_at FROM settings${clauses.length ? ` WHERE ${clauses.join(" AND ")}` : ""}`;
1274
+ // Disjoint indexed branches: an OR lets SQLite choose a namespace scan over every connector's payload.
1275
+ // Null metadata is a legacy write racing setup; strict JS verification below never widens its owner.
1276
+ const query = filter?.connectorId === undefined ? `${selection} ORDER BY key` : `${selection} AND connector_id = ? UNION ALL ${selection} AND connector_id IS NULL ORDER BY key`;
1277
+ const values = filter?.connectorId === undefined ? params : [...params, filter.connectorId, ...params];
1278
+ const rows = await db.all(query, ...values);
1279
+ return rows.filter(row => filter?.connectorId === undefined || nativeCommandOwner(row.key, row.value) === filter.connectorId).map(settingOf);
1280
+ },
1180
1281
  };
1181
1282
  this.sealedKeys = {
1182
1283
  get: async (name) => {
@@ -1186,9 +1287,20 @@ class SqliteStore {
1186
1287
  put: async (name, sealed) => {
1187
1288
  await db.write([{ sql: "INSERT INTO sealed_keys (name, sealed, updated_at) VALUES (?, ?, ?) ON CONFLICT (name) DO UPDATE SET sealed = excluded.sealed, updated_at = excluded.updated_at", params: [name, sealed, now()] }]);
1188
1289
  },
1290
+ replaceIf: async (name, was, sealed) => {
1291
+ const [result] = await db.write([{ sql: "UPDATE sealed_keys SET sealed = ?, updated_at = ? WHERE name = ? AND sealed = ?", params: [sealed, now(), name, was] }]);
1292
+ return result.changes === 1;
1293
+ },
1189
1294
  remove: async (name) => {
1190
1295
  await db.write([{ sql: "DELETE FROM sealed_keys WHERE name = ?", params: [name] }]);
1191
1296
  },
1297
+ removeIf: async (name, was) => {
1298
+ const [result] = await db.write([{ sql: "DELETE FROM sealed_keys WHERE name = ? AND sealed = ?", params: [name, was] }]);
1299
+ return result.changes === 1;
1300
+ },
1301
+ // The deadlines' clock (fence.ts storeNow): read from the database where the dialect names its clock (Postgres),
1302
+ // else the store's own.
1303
+ clock: async () => (d.nowSql ? Number((await db.get(`SELECT ${d.nowSql} AS now`)).now) : now()),
1192
1304
  all: async () => (await db.all("SELECT name, sealed, updated_at FROM sealed_keys ORDER BY name")).map(sealedKeyOf),
1193
1305
  };
1194
1306
  this.computerLedger = {
@@ -1482,9 +1594,10 @@ class SqliteStore {
1482
1594
  const rows = await tx.all(`UPDATE runs SET ${claimSet(stamp)} WHERE id IN (${picked.map(() => "?").join(", ")}) RETURNING id, epoch, claimed_until`, runner, ...stamp.params, leaseMs, ...picked.map((row) => row.id));
1483
1595
  const epochs = new Map(rows.map((row) => [row.id, row.epoch]));
1484
1596
  const untils = new Map(rows.map((row) => [row.id, Number(row.claimed_until)]));
1485
- // A take or reclaim leaves no viewer of an older claim behind: its rows go in this transaction, every kind.
1486
- for (const row of rows)
1487
- await tx.run("DELETE FROM computer_viewers WHERE run_id = ? AND epoch < ?", row.id, row.epoch);
1597
+ // A take or reclaim leaves no viewer of an older claim behind: its rows go in this transaction, every kind, in one
1598
+ // statement for the whole batch (each run's epoch is the one just moved to), never one round trip a run.
1599
+ if (rows.length > 0)
1600
+ await tx.run(`DELETE FROM computer_viewers WHERE run_id IN (${rows.map(() => "?").join(", ")}) AND epoch < (SELECT epoch FROM runs WHERE runs.id = computer_viewers.run_id)`, ...rows.map((row) => row.id));
1488
1601
  // A newer claim of a run supersedes its release here: journal() refuses by epoch, and the newer epoch passes.
1489
1602
  for (const { id } of picked)
1490
1603
  this.#released.delete(id);
@@ -1514,21 +1627,28 @@ class SqliteStore {
1514
1627
  async renewMany(claims, { leaseMs = DEFAULT_LEASE_MS } = {}) {
1515
1628
  if (claims.length === 0)
1516
1629
  return [];
1517
- // One transaction for every claim, each update on its own: a claim another runner took changes no row and is answered
1518
- // Fenced, never rolling the others back.
1630
+ // One transaction for every claim, in a few statements whatever their count: the rows held in one, then one update
1631
+ // for each RENEW_CHUNK claims, each claim under its own fence. A runner's 300 claims are never 300 round trips with
1632
+ // their rows held, which on a database a few ms away outlast the lease's margin and lose every claim at once. A claim
1633
+ // another runner took changes no row and is answered Fenced, never rolling the others back.
1519
1634
  return this.#db.transaction(async (tx) => {
1520
- // Held in one order (by run id), so two renews of overlapping runs never wait on each other in a cycle.
1521
- for (const runId of [...new Set(claims.map((claim) => claim.runId))].sort())
1522
- await this.#holdRun(tx, runId);
1523
- const out = [];
1524
- for (const claim of claims) {
1635
+ // Every row held first, in one order (the dialect's, by run id), so two renews of overlapping runs never wait on
1636
+ // each other in a cycle, and the clock below is read once the rows are held.
1637
+ await this.#db.dialect.lockRows(tx, "runs", "id", [...new Set(claims.map((claim) => claim.runId))]);
1638
+ const renewed = new Map();
1639
+ for (let at = 0; at < claims.length; at += RENEW_CHUNK) {
1640
+ const chunk = claims.slice(at, at + RENEW_CHUNK);
1525
1641
  // The deadlines' clock (the database's on Postgres) judges each lease and stamps the next one.
1526
1642
  const now = this.#clock();
1527
- const fence = claimFence(claim, now);
1528
- const renewed = await tx.all(`UPDATE runs SET claimed_until = ${now.sql} + ? WHERE ${fence.where} AND runner = ? RETURNING id, claimed_until`, ...now.params, leaseMs, ...fence.params, claim.runner);
1529
- out.push(renewed.length > 0 ? { ...claim, until: Number(renewed[0].claimed_until) } : new Fenced(claim.runId, claim.epoch));
1643
+ const fences = chunk.map((claim) => claimFence(claim, now));
1644
+ const rows = await tx.all(`UPDATE runs SET claimed_until = ${now.sql} + ? WHERE ${fences.map((fence) => `(${fence.where} AND runner = ?)`).join(" OR ")} RETURNING id, epoch, runner, claimed_until`, ...now.params, leaseMs, ...fences.flatMap((fence, i) => [...fence.params, chunk[i].runner]));
1645
+ for (const row of rows)
1646
+ renewed.set(renewKey(row.id, Number(row.epoch), row.runner), Number(row.claimed_until));
1530
1647
  }
1531
- return out;
1648
+ return claims.map((claim) => {
1649
+ const until = renewed.get(renewKey(claim.runId, claim.epoch, claim.runner));
1650
+ return until === undefined ? new Fenced(claim.runId, claim.epoch) : { ...claim, until };
1651
+ });
1532
1652
  // On the lease connection (TransactionOptions.lease): a runner whose loops hold every pool client still renews.
1533
1653
  }, { lease: true });
1534
1654
  }
@@ -1660,6 +1780,22 @@ class SqliteStore {
1660
1780
  const at = this.#now();
1661
1781
  const state = run.state ?? "ended";
1662
1782
  return this.#db.transaction(async (tx) => {
1783
+ for (const guard of [...(run.settingsGuards ?? [])].sort((a, b) => a.key.localeCompare(b.key))) {
1784
+ // A no-op update takes the row's write lock on both SQLite and Postgres until the import commits. A source
1785
+ // revoke/disconnect either commits first and refuses this write, or waits for this already-started import.
1786
+ const setting = await tx.get("UPDATE settings SET value = value WHERE key = ? RETURNING value", guard.key);
1787
+ const value = setting === undefined ? undefined : JSON.parse(setting.value);
1788
+ if (!value || Object.entries(guard.fields).some(([field, expected]) => JSON.stringify(value[field]) !== JSON.stringify(expected))) {
1789
+ throw new StoreConstraint("The source import grant changed before the history write committed.");
1790
+ }
1791
+ }
1792
+ if (run.requireActiveAgent) {
1793
+ // Archive updates this same row. It either commits first and refuses this import, or waits for this
1794
+ // already-admitted history transaction; a read outside the transaction cannot establish that order.
1795
+ const agent = await tx.get("UPDATE agents SET archived_at = archived_at WHERE id = ? AND archived_at IS NULL RETURNING id", run.agentId);
1796
+ if (!agent)
1797
+ throw new StoreConstraint("The agent was archived before the history write committed.");
1798
+ }
1663
1799
  // The ended run row, its launch row and its transcript's journal, all in this one transaction (the server's own
1664
1800
  // writer): a crash between them leaves nothing. The run is created at epoch 0 with no runner, and the journal's fence
1665
1801
  // passes for that one row, by the rowid its insert returned (the claim fence's inserted-here form).
@@ -32,10 +32,12 @@ export type Request = {
32
32
  op: "stmt";
33
33
  statement: Statement;
34
34
  mode: Mode;
35
+ busyMs?: number;
35
36
  } | {
36
37
  op: "write";
37
38
  statements: readonly Statement[];
38
39
  full?: boolean;
40
+ busyMs?: number;
39
41
  } | {
40
42
  op: "begin";
41
43
  full?: boolean;
@@ -9,12 +9,13 @@
9
9
  // server per store file): an exclusive lock on `<file>.owner`, held until close,
10
10
  // let go by the OS when the process dies
11
11
  // exec {sql} SQL text, maybe several statements, no bindings
12
- // stmt {statement, mode} one statement: run, count (its changes), get (first row) or all. Outside a
12
+ // stmt {statement, mode, busyMs} one statement: run, count (its changes), get (first row) or all. Outside a
13
13
  // transaction, a run or count is its own BEGIN IMMEDIATE transaction
14
- // write {statements, full} one transaction: BEGIN IMMEDIATE, each statement in order, COMMIT; `full` makes it
14
+ // write {statements, full, busyMs} one transaction: BEGIN IMMEDIATE, each statement in order, COMMIT; `full` makes it
15
15
  // a FULL commit (flush). A statement's `expect` checks it changed a row; a miss
16
16
  // rolls the whole transaction back with its `miss` (fenced, or a final run)
17
- // begin {full} / commit / rollback an interactive transaction (connection.ts transaction()), its statements sent
17
+ // begin {full, busyMs} / commit / rollback
18
+ // an interactive transaction (connection.ts transaction()), its statements sent
18
19
  // as stmt, or as step (one statement, its changes and rows, its `expect` checked)
19
20
  // in between
20
21
  // close
@@ -65,8 +66,9 @@ function step(statement) {
65
66
  /** The connection's own busy wait (its open's busyTimeoutMs): what a begin given a shorter one goes back to. */
66
67
  let busyTimeout = 0;
67
68
  /** A transaction: BEGIN IMMEDIATE for a write; for `read`, a deferred one that takes no writer lock (one snapshot).
68
- * `busyMs`: the most this begin waits for the database's write lock, when the transaction's deadline leaves less than
69
- * the connection's own busy wait (Connection.transaction's `fromCall`); the connection's own is set back after it. */
69
+ * `busyMs`: the most this begin waits for the database's write lock, when less than the connection's own busy wait is
70
+ * left (a `fromCall` transaction's deadline, or a wait sent again with its held-up time given back: connection.ts
71
+ * lockWait); the connection's own is set back after it. */
70
72
  function begin(full, read = false, busyMs) {
71
73
  const conn = opened();
72
74
  if (full)
@@ -114,11 +116,12 @@ function end(commit) {
114
116
  txFull = false;
115
117
  }
116
118
  }
117
- /** `work` inside its own BEGIN IMMEDIATE transaction when none is open; inside the open one otherwise. */
118
- function written(work) {
119
+ /** `work` inside its own BEGIN IMMEDIATE transaction when none is open (its begin waiting `busyMs` at most, as begin's);
120
+ * inside the open one otherwise. */
121
+ function written(work, busyMs) {
119
122
  if (inTx)
120
123
  return work();
121
- begin(false);
124
+ begin(false, false, busyMs);
122
125
  try {
123
126
  const value = work();
124
127
  end(true);
@@ -190,10 +193,10 @@ function handle(request) {
190
193
  const prepared = opened().prepare(statement.sql);
191
194
  return mode === "all" ? prepared.all(...(statement.params ?? [])) : (prepared.get(...(statement.params ?? [])) ?? null);
192
195
  }
193
- return written(() => step(statement).changes);
196
+ return written(() => step(statement).changes, request.busyMs);
194
197
  }
195
198
  case "write": {
196
- begin(request.full === true);
199
+ begin(request.full === true, false, request.busyMs);
197
200
  try {
198
201
  const results = request.statements.map(step);
199
202
  end(true);
@@ -1,6 +1,7 @@
1
1
  import type { Context } from "@earendil-works/chord/context";
2
2
  import type { Storage, StorageWrite } from "@earendil-works/pi-durable";
3
3
  import type { JournalPage } from "./journal/storage.js";
4
+ import type { MonidPinBody } from "./agent-body.js";
4
5
  /** A run's state. queued: a row, no runner yet. running: a runner holds the claim. parked: waiting for a person (an
5
6
  * approval, a raised cap) with no claim held; a command row or its wake_at makes it claimable again. ended, stopped and
6
7
  * failed are final. A running run whose runner died is claimable once its claim runs out. */
@@ -73,6 +74,8 @@ export interface NewRevision {
73
74
  /** The MCP tools the revision grants, pinned as their servers listed them when it was saved (mcp-gateway.ts McpPin), which
74
75
  * every run of it calls; none when it grants none. */
75
76
  readonly mcpPin?: unknown;
77
+ /** Its monid endpoints, pinned as monid listed them when it was saved (agent-body.ts MonidPinBody); none for none. */
78
+ readonly monidPin?: MonidPinBody;
76
79
  }
77
80
  export interface RevisionRow {
78
81
  readonly id: string;
@@ -92,6 +95,8 @@ export interface RevisionRow {
92
95
  readonly externalVersion: string | null;
93
96
  /** Its MCP pin as its save made it (NewRevision.mcpPin), or null for a revision that grants no MCP tool. */
94
97
  readonly mcpPin: unknown;
98
+ /** Its monid pin as its save made it (NewRevision.monidPin), or null for a revision that grants no monid endpoint. */
99
+ readonly monidPin: MonidPinBody | null;
95
100
  }
96
101
  /** How a run ended, beside its state. An ended run (state 'ended'): 'escalated' (it finished its work and waits for a
97
102
  * person, which the v2 status reads as completed with a review) or 'completed'. A stopped run (state 'stopped'): 'stopped'
@@ -135,7 +140,13 @@ export interface RunRow {
135
140
  readonly wakeAt: number | null;
136
141
  /** A parked run's backoff after a failed resume: its untaken commands wait for it, a stop and its wake_at do not. */
137
142
  readonly backoffUntil: number | null;
143
+ /** What the run cost, exactly: null when that is unknown, and null when its stored cost is only the most it can have
144
+ * cost (`costAtMostUsd`). Every reader that sums, compares or shows spend reads this, so a bound never reads as spend. */
138
145
  readonly costUsd: number | null;
146
+ /** The most the run can have cost, set only when that is all its stored cost says (runs.cost_upper_bound): it counts a
147
+ * request cut with no answer at what its cap held for it (runner.ts CUT_AT_HOLD). Read only where a figure can be said
148
+ * "at most" (the run's view, the runs list); null otherwise, `costUsd` then the stored figure or null. */
149
+ readonly costAtMostUsd: number | null;
139
150
  readonly metrics: unknown;
140
151
  readonly summary: string | null;
141
152
  /** How the run ended beside its state (RunOutcome), null for a plain completion, a failure, or a run not ended. */
@@ -154,6 +165,9 @@ export interface RunRow {
154
165
  export interface RunPatch {
155
166
  readonly state?: RunState;
156
167
  readonly costUsd?: number | null;
168
+ /** Whether `costUsd` is the most the run can have cost (stored as runs.cost_upper_bound, read back as
169
+ * RunRow.costAtMostUsd): read only with `costUsd`, which always writes it (absent: false). */
170
+ readonly costUpperBound?: boolean;
157
171
  readonly metrics?: unknown;
158
172
  readonly summary?: string | null;
159
173
  /** How the run ended (RunOutcome), set in its end commit; null clears it. */
@@ -210,6 +224,16 @@ export interface ImportRunInput {
210
224
  readonly startedAt: number;
211
225
  readonly endedAt?: number;
212
226
  readonly transcript: readonly (readonly StorageWrite[])[];
227
+ /** Internal authorization fences for an outbound historical import. These settings rows are locked and their
228
+ * named fields checked in the same transaction as the terminal run and journal, so a completed revocation or
229
+ * disconnect cannot be followed by another imported run. Ordinary local imports leave this absent. */
230
+ readonly settingsGuards?: readonly {
231
+ readonly key: string;
232
+ readonly fields: Readonly<Record<string, unknown>>;
233
+ }[];
234
+ /** Remote history is admitted only while its agent remains active. Lock and check the agent in the import's
235
+ * transaction, ordering the write against archive; ordinary local imports leave this guard absent. */
236
+ readonly requireActiveAgent?: true;
213
237
  }
214
238
  /** Rows written in the same commit as a run's update (runs.update, or a journal commit's staged patch): a channel post the
215
239
  * run's moment owes (the outbox), what a channel was told. A command consumed is Staged.take, refused when not untaken. */
@@ -268,6 +292,13 @@ export interface Learning {
268
292
  proposals(agentId: string, options?: {
269
293
  limit?: number;
270
294
  }): Promise<LearningProposal[]>;
295
+ /** Everything agent `agentId`'s runs' learning kept, in two reads whatever the number of its runs: every round of every
296
+ * run's kept proposal (oldest round first within a run), and the rows of the learning runs they name (as runs.get
297
+ * reads one; a learning run named and never written has none). An agent-wide read's, never a read a run. */
298
+ kept(agentId: string): Promise<{
299
+ proposals: LearningProposal[];
300
+ learningRuns: RunRow[];
301
+ }>;
271
302
  /** What learning spent outside any run, in one read: each run (not imported) whose learning ended in [from, to) (ms),
272
303
  * its agent, when its learning ended and what its grade cost (null: unknown; 0: nothing graded). A learning dropped
273
304
  * before it was proposed ended when it was kept; a proposal ended when its learning run ended (ended or failed), whose
@@ -765,6 +796,7 @@ export interface Runs {
765
796
  skills?: unknown;
766
797
  note?: string;
767
798
  mcpPin?: unknown;
799
+ monidPin?: MonidPinBody;
768
800
  };
769
801
  run: {
770
802
  id: string;
@@ -776,6 +808,14 @@ export interface Runs {
776
808
  /** The run's launch row (the runner reads it at its claim; the server for views). StoreLaunchMissing when the run has
777
809
  * none (it was not started with one), never a default. */
778
810
  launch(runId: string): Promise<RunLaunchRow>;
811
+ /** The learning start (the launch body's `learning` member, as stored: undefined when the body names none) of every run of
812
+ * agent `agentId` (no built-in learning run's) that has a launch row, in one read: what an agent-wide read (its cost per
813
+ * run, its learning view) needs of its runs at once, never a read a run. Only that member is read: no run's input, no
814
+ * sealed bytes. A run with no launch row has no entry. */
815
+ learningStarts(agentId: string): Promise<{
816
+ runId: string;
817
+ learning: unknown;
818
+ }[]>;
779
819
  /** Newest first, at most `limit` (no limit: all). `archived` filters on the run's own archive time (true: archived,
780
820
  * false: not); its agent's archive is read apart. A built-in learning run (one a kept learning names) is never listed. */
781
821
  list(filter: {
@@ -1051,19 +1091,28 @@ export interface Settings {
1051
1091
  get(key: string): Promise<unknown | undefined>;
1052
1092
  /** Saves `value` (JSON) under `key`, inserted or replaced in place. */
1053
1093
  put(key: string, value: unknown): Promise<void>;
1054
- /** Saves `value` under `key` only when the key has no row yet, in one statement, so of two processes that race the first
1055
- * wins; the value saved under it after (this one, or the one there before). */
1056
- putIfAbsent(key: string, value: unknown): Promise<unknown>;
1094
+ /** Saves `value` under `key` only when the key has no row yet; the value saved after (this one, or the one there before).
1095
+ * With `capacity`, count and insert share a namespace lock and transaction across store handles. Every raw key under
1096
+ * the exact prefix counts, without decoding values. An existing key wins even at capacity; undefined means a new key
1097
+ * was refused. The nonempty prefix must contain the key, and limit must be a positive safe integer. */
1098
+ putIfAbsent(key: string, value: unknown, capacity?: {
1099
+ readonly prefix: string;
1100
+ readonly limit: number;
1101
+ }): Promise<unknown>;
1057
1102
  /** Saves `value` under `key` only while its row still holds `was` (as get read it), in one statement: a compare-and-set,
1058
1103
  * so of two writers that read one row only one replaces it. True when it was replaced; false, with nothing written,
1059
- * when the row changed since or is gone. */
1060
- replaceIf(key: string, was: unknown, value: unknown): Promise<boolean>;
1104
+ * when the row changed since or is gone. With `claim`, holds the run's shared row lock and checks its epoch/lease in
1105
+ * the same transaction as the setting update; a stale claim throws Fenced without changing the setting. */
1106
+ replaceIf(key: string, was: unknown, value: unknown, claim?: Claim): Promise<boolean>;
1061
1107
  /** The key's row goes only while it still holds `was`, in one statement: true when it went. */
1062
1108
  removeIf(key: string, was: unknown): Promise<boolean>;
1063
1109
  /** The key's row goes; a key with no row is left as it is. */
1064
1110
  remove(key: string): Promise<void>;
1065
- /** Every setting, by key. */
1066
- all(): Promise<SettingRow[]>;
1111
+ /** Settings by key, optionally selecting a namespace and native connector owner before values are read. */
1112
+ all(filter?: {
1113
+ readonly prefix: string;
1114
+ readonly connectorId?: string;
1115
+ }): Promise<SettingRow[]>;
1067
1116
  }
1068
1117
  /** A sealed key as a row (store schema `sealed_keys`): its name and the bytes the server sealed (store/seal.ts, AAD
1069
1118
  * sealed_keys|<name>|sealed), which the store never opens. */
@@ -1093,8 +1142,19 @@ export interface SealedKeys {
1093
1142
  get(name: string): Promise<Uint8Array | undefined>;
1094
1143
  /** Saves `sealed` under `name`, inserted or replaced in place. */
1095
1144
  put(name: string, sealed: Uint8Array): Promise<void>;
1145
+ /** Saves `sealed` under `name` only while its row still holds `was` (the bytes as get read them), in one statement: a
1146
+ * compare-and-set, so of two writers that read one row only one replaces it. Each seal is fresh bytes, so a row any
1147
+ * writer saved since reads as changed. True when it was replaced; false, writing nothing, when it changed or is gone. */
1148
+ replaceIf(name: string, was: Uint8Array, sealed: Uint8Array): Promise<boolean>;
1096
1149
  /** The key's row goes. */
1097
1150
  remove(name: string): Promise<void>;
1151
+ /** The key's row goes only while it still holds `was` (the bytes as get read them), in one statement: true when it
1152
+ * went; false, removing nothing, when it changed since or is gone. */
1153
+ removeIf(name: string, was: Uint8Array): Promise<boolean>;
1154
+ /** The deadlines' clock now, in ms: the database's on Postgres, the store's own on SQLite (fence.ts storeNow). A lease
1155
+ * kept inside a sealed key's bytes (the ChatGPT sign-in's renewal) is stamped and judged by it, so every process
1156
+ * sharing the store judges it by one clock, whatever its own says. */
1157
+ clock(): Promise<number>;
1098
1158
  /** Every saved key, by name (its bytes never opened here). */
1099
1159
  all(): Promise<SealedKeyRow[]>;
1100
1160
  }
@@ -16,18 +16,18 @@ export type AnalyticsGroup = {
16
16
  needsReview: number;
17
17
  failed: number;
18
18
  runsWithMetrics: number;
19
- tokens: number;
19
+ tokens: number | null;
20
20
  costUsd: number | null;
21
21
  unknownCostRuns: number;
22
22
  };
23
23
  export type StoreAnalytics = {
24
24
  totals: AnalyticsGroup & {
25
- input: number;
26
- cacheRead: number;
27
- cacheWrite: number;
28
- output: number;
29
- requests: number;
30
- unmetered: number;
25
+ input: number | null;
26
+ cacheRead: number | null;
27
+ cacheWrite: number | null;
28
+ output: number | null;
29
+ requests: number | null;
30
+ unmetered: number | null;
31
31
  };
32
32
  time: {
33
33
  endedRuns: number;