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

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 (410) hide show
  1. package/CHANGELOG.md +418 -0
  2. package/README.md +325 -124
  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-BNhZs-jp.css +1 -0
  37. package/dist/console/assets/index-BQv5aOGB.js +700 -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 +84 -0
  44. package/dist/email/account.js +159 -0
  45. package/dist/email/answer.d.ts +10 -0
  46. package/dist/email/answer.js +182 -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 +380 -0
  53. package/dist/email/names.d.ts +20 -0
  54. package/dist/email/names.js +40 -0
  55. package/dist/email/routes.d.ts +9 -0
  56. package/dist/email/routes.js +50 -0
  57. package/dist/email/tools.d.ts +20 -0
  58. package/dist/email/tools.js +517 -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 +9 -2
  93. package/dist/learn/compile.js +52 -16
  94. package/dist/learn/grade.d.ts +4 -0
  95. package/dist/learn/grade.js +4 -1
  96. package/dist/learn/promote.d.ts +106 -51
  97. package/dist/learn/promote.js +82 -189
  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 +26 -8
  109. package/dist/learning-cost.js +17 -7
  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 +33 -2
  118. package/dist/local-models.js +43 -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 +1 -0
  164. package/dist/openapi.js +394 -85
  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 +7 -2
  170. package/dist/port-models.js +5 -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 +11 -0
  180. package/dist/refusal-words.js +13 -2
  181. package/dist/run-launch.d.ts +10 -1
  182. package/dist/run-launch.js +11 -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 +42 -35
  191. package/dist/run-view.js +79 -44
  192. package/dist/runnable.d.ts +13 -5
  193. package/dist/runnable.js +69 -60
  194. package/dist/runner/adapter-loop.d.ts +42 -11
  195. package/dist/runner/adapter-loop.js +651 -247
  196. package/dist/runner/adapter-run-spec.d.ts +37 -12
  197. package/dist/runner/adapter-run-spec.js +139 -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 +94 -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 +37 -13
  217. package/dist/runner/journal-kinds.js +9 -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 +12 -3
  237. package/dist/runner/model-route.js +139 -18
  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 +74 -8
  243. package/dist/runner/promotion.js +365 -124
  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 +554 -130
  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/index.d.ts +1 -1
  278. package/dist/store/native-command-owner.d.ts +10 -0
  279. package/dist/store/native-command-owner.js +47 -0
  280. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  281. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  282. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  283. package/dist/store/postgres/store.js +3 -0
  284. package/dist/store/schema.d.ts +7 -0
  285. package/dist/store/schema.js +20 -1
  286. package/dist/store/sqlite/run-patch.d.ts +8 -1
  287. package/dist/store/sqlite/run-patch.js +14 -3
  288. package/dist/store/sqlite/store.js +133 -18
  289. package/dist/store/store.d.ts +52 -7
  290. package/dist/store-reads/analytics.d.ts +7 -7
  291. package/dist/store-reads/analytics.js +23 -5
  292. package/dist/store-reads/cap.js +8 -6
  293. package/dist/store-reads/journal.d.ts +5 -0
  294. package/dist/store-reads/journal.js +85 -41
  295. package/dist/store-reads/learning.d.ts +85 -5
  296. package/dist/store-reads/learning.js +45 -17
  297. package/dist/store-reads/runs.d.ts +5 -0
  298. package/dist/store-reads/runs.js +3 -2
  299. package/dist/store-view.js +75 -21
  300. package/dist/template-eval.d.ts +73 -11
  301. package/dist/template-eval.js +535 -75
  302. package/dist/templates.d.ts +70 -20
  303. package/dist/templates.js +191 -34
  304. package/dist/text-urls.d.ts +38 -0
  305. package/dist/text-urls.js +170 -0
  306. package/dist/timeline/index.d.ts +3 -2
  307. package/dist/timeline/index.js +3 -2
  308. package/dist/timeline/labels.d.ts +5 -2
  309. package/dist/timeline/labels.js +29 -6
  310. package/dist/timeline/origin.d.ts +1 -1
  311. package/dist/timeline/origin.js +2 -2
  312. package/dist/timeline/render-text.js +1 -1
  313. package/dist/timeline/timeline.d.ts +66 -4
  314. package/dist/timeline/timeline.js +160 -30
  315. package/dist/timeline/util.d.ts +5 -0
  316. package/dist/timeline/util.js +44 -8
  317. package/dist/timeline/web-calls.d.ts +17 -0
  318. package/dist/timeline/web-calls.js +106 -0
  319. package/dist/tool-gate.d.ts +42 -42
  320. package/dist/tool-gate.js +97 -91
  321. package/dist/tool-list.d.ts +4 -1
  322. package/dist/tool-list.js +8 -1
  323. package/dist/tool-names.d.ts +18 -13
  324. package/dist/tool-names.js +19 -17
  325. package/dist/tool-plane.d.ts +17 -13
  326. package/dist/tool-plane.js +12 -5
  327. package/dist/tools.d.ts +44 -16
  328. package/dist/tools.js +28 -28
  329. package/dist/trigger-adapter.d.ts +85 -5
  330. package/dist/trigger-adapter.js +6 -0
  331. package/dist/trigger-adapters.js +3 -1
  332. package/dist/trigger-composio.d.ts +10 -0
  333. package/dist/trigger-composio.js +122 -0
  334. package/dist/trigger-email.d.ts +4 -0
  335. package/dist/trigger-email.js +228 -0
  336. package/dist/trigger-signatures.d.ts +6 -10
  337. package/dist/trigger-signatures.js +16 -16
  338. package/dist/trigger-targets.d.ts +1 -1
  339. package/dist/trigger-targets.js +4 -3
  340. package/dist/trigger-webhook.js +6 -4
  341. package/dist/triggers.d.ts +94 -9
  342. package/dist/triggers.js +263 -62
  343. package/dist/uploads.d.ts +9 -0
  344. package/dist/uploads.js +27 -0
  345. package/dist/validate.js +1 -7
  346. package/dist/web-fake.d.ts +56 -0
  347. package/dist/web-fake.js +102 -0
  348. package/dist/web-fetch-direct.d.ts +3 -0
  349. package/dist/web-fetch-direct.js +4 -1
  350. package/dist/web-fetch.d.ts +5 -1
  351. package/dist/web-fetch.js +8 -31
  352. package/dist/web-search.d.ts +51 -2
  353. package/dist/web-search.js +116 -18
  354. package/dist/webhooks.d.ts +2 -1
  355. package/dist/webhooks.js +5 -1
  356. package/dist/workflow/node-runner.js +10 -2
  357. package/dist/workspace/archil-claim.d.ts +3 -0
  358. package/dist/workspace/archil-claim.js +9 -2
  359. package/dist/workspace/computer-deps.d.ts +22 -9
  360. package/dist/workspace/computer-deps.js +78 -37
  361. package/dist/workspace/computer-for-claim.d.ts +54 -4
  362. package/dist/workspace/computer-for-claim.js +179 -39
  363. package/dist/workspace/computer-janitor.d.ts +10 -3
  364. package/dist/workspace/computer-janitor.js +96 -29
  365. package/dist/workspace/computer-kept.d.ts +82 -0
  366. package/dist/workspace/computer-kept.js +147 -0
  367. package/dist/workspace/computer-mcp.js +4 -3
  368. package/dist/workspace/computer-ports.d.ts +23 -3
  369. package/dist/workspace/computer-ports.js +115 -5
  370. package/dist/workspace/index.d.ts +1 -2
  371. package/dist/workspace/index.js +1 -2
  372. package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
  373. package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
  374. package/dist/workspace/resolve-computer.d.ts +15 -3
  375. package/dist/workspace/resolve-computer.js +10 -7
  376. package/dist/workspace/revision-skills.d.ts +6 -2
  377. package/dist/workspace/revision-skills.js +12 -5
  378. package/dist/workspace/run-end-computers.d.ts +30 -0
  379. package/dist/workspace/run-end-computers.js +137 -0
  380. package/dist/workspace/run-tools.d.ts +28 -29
  381. package/dist/workspace/run-tools.js +29 -30
  382. package/dist/wrap-up.d.ts +19 -5
  383. package/dist/wrap-up.js +31 -4
  384. package/package.json +13 -9
  385. package/skills/agentrun-serve/SKILL.md +248 -10
  386. package/templates/README.md +117 -23
  387. package/templates/TOOLS.md +168 -0
  388. package/templates/code-review/agent.md +18 -4
  389. package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
  390. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  391. package/templates/code-review/evals/other-repo/case.yaml +1 -1
  392. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  393. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  394. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  395. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  396. package/templates/code-review/skills/review/DEEP.md +2 -2
  397. package/templates/code-review/skills/review/REVIEWER.md +2 -2
  398. package/templates/code-review/skills/review/SKILL.md +7 -3
  399. package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
  400. package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
  401. package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
  402. package/templates/release-notes/evals/other-repo/case.yaml +1 -1
  403. package/dist/console/assets/index-CjqQirbo.css +0 -1
  404. package/dist/console/assets/index-b6-XY5A9.js +0 -576
  405. package/dist/host-calls.d.ts +0 -20
  406. package/dist/host-calls.js +0 -12
  407. package/dist/runner/adapters/pi-computer.d.ts +0 -9
  408. package/dist/runner/adapters/pi-computer.js +0 -51
  409. package/dist/workspace/computer-script.d.ts +0 -53
  410. package/dist/workspace/computer-script.js +0 -172
@@ -0,0 +1,6 @@
1
+ -- Version 14: whether a run's stored cost is the most it can have cost (runs.cost_upper_bound, as store/schema.ts keeps it
2
+ -- on SQLite): 1 when it counts a request cut with no answer at what its cap held for it, written in the end's commit with
3
+ -- cost_usd; 0 otherwise, an unknown cost's included. A run ended before reads 0. Applied once, after 0013, inside the
4
+ -- transaction migrate.ts opens. Never edit this file once applied: a change is a new file.
5
+ ALTER TABLE runs ADD COLUMN IF NOT EXISTS cost_upper_bound BIGINT NOT NULL DEFAULT 0 CHECK (cost_upper_bound IN (0, 1));
6
+ UPDATE store_meta SET schema_version = 14 WHERE singleton = 1;
@@ -2,6 +2,7 @@
2
2
  // (connection.ts) in the store's own schema (default "agentrun"). The server sets the schema up (migrate.ts) and holds the
3
3
  // owner lock, one server per schema; runners are many, set nothing up, and refuse a schema version they do not know.
4
4
  import { SchemaVersionUnknown } from "../store.js";
5
+ import { backfillNativeCommandOwners } from '../native-command-owner.js';
5
6
  import { storeOver } from "../sqlite/store.js";
6
7
  import { PgConnection, SCHEMA_NAME } from "./connection.js";
7
8
  import { migrate, migrationsIn, placeOf, versionOf } from "./migrate.js";
@@ -42,6 +43,8 @@ export async function openPostgresStore(options) {
42
43
  const found = await connection.withClient((client) => (role === "server" ? migrate(client, schema, now(), migrations) : versionOf(client, schema)));
43
44
  if (found !== known)
44
45
  throw new SchemaVersionUnknown(placeOf(schema), found, known);
46
+ if (role === "server")
47
+ await backfillNativeCommandOwners(connection);
45
48
  if (role === "runner" && options.warn) {
46
49
  const gap = now() - (await connection.clock());
47
50
  if (Math.abs(gap) > CLOCK_WARN_MS) {
@@ -5,10 +5,17 @@ export declare const SCHEMA_VERSION = 11;
5
5
  /** One unrefused answer per approval of a run: an answer the runner refused (its run could not resume) holds no place, so
6
6
  * the person can answer again. */
7
7
  export declare const ONE_ANSWER_INDEX = "commands_one_answer";
8
+ /** The connector's own command rows, without parsing another connector's events on every heartbeat. */
9
+ export declare const NATIVE_COMMANDS_INDEX = "CREATE INDEX IF NOT EXISTS settings_native_commands ON settings (connector_id, key) WHERE key >= 'native.remote.command.' AND key < 'native.remote.command/'";
8
10
  export declare const COMMANDS_ONE_ANSWER = "CREATE UNIQUE INDEX IF NOT EXISTS commands_one_answer ON commands (run_id, json_extract(body, '$.approval')) WHERE kind IN ('approve', 'deny') AND refused IS NULL";
9
11
  /** A revision's MCP pin, as its save listed the tools (JSON, null when it grants no MCP tool). In STORE_DDL, and added at a
10
12
  * server open to a store an earlier build of this version made (one that pinned each run in mcp_pins, dropped at that open). */
11
13
  export declare const REVISIONS_MCP_PIN: string;
14
+ /** A revision's monid pin (JSON, null for none): in STORE_DDL, and added at a server open as REVISIONS_MCP_PIN is. */
15
+ export declare const REVISIONS_MONID_PIN: string;
16
+ /** The bound beside a run's cost: in STORE_DDL, and added at a server open to a store an earlier build of this version made,
17
+ * as REVISIONS_MCP_PIN is (a run it ended reads 0: an exact cost or an unknown one, as it was read then). */
18
+ export declare const RUNS_COST_UPPER_BOUND = "ALTER TABLE runs ADD COLUMN cost_upper_bound INTEGER NOT NULL DEFAULT 0 CHECK (cost_upper_bound IN (0, 1))";
12
19
  /** A template package imported from GitHub (POST /v2/templates/import), by its id (`github:<owner>/<repo>[/<path>]`): its
13
20
  * source as given (ref and all), the full commit SHA read, the GitHub account that publishes it, and its files as read
14
21
  * (`files`, a JSON object of path to base64). A re-import of the id replaces the row. The server checks the files again
@@ -11,6 +11,9 @@
11
11
  // (commands.answer). An agent's MCP tools are pinned on its revision when it is saved (revisions.mcp_pin, REVISIONS_MCP_PIN),
12
12
  // in place of each run's pin at its first claim (the mcp_pins table): a server open adds the column to a store an earlier
13
13
  // build of this version made and drops the table, so a revision saved before has no pin until its first run pins it.
14
+ // Its monid endpoints are pinned beside them (revisions.monid_pin, REVISIONS_MONID_PIN), added at a server open the same way.
15
+ // A run's cost says whether it is the most the run can have cost (runs.cost_upper_bound, RUNS_COST_UPPER_BOUND), added at a
16
+ // server open the same way.
14
17
  // The template packages imported from GitHub (imported_templates) are a table of their own that nothing
15
18
  // else reads, so it needs no version: the server adds it at its open to a store an earlier build of this version made
16
19
  // (IMPORTED_TEMPLATES), as it does the one-answer index.
@@ -31,11 +34,22 @@ export const SCHEMA_VERSION = 11;
31
34
  /** One unrefused answer per approval of a run: an answer the runner refused (its run could not resume) holds no place, so
32
35
  * the person can answer again. */
33
36
  export const ONE_ANSWER_INDEX = "commands_one_answer";
37
+ /** The connector's own command rows, without parsing another connector's events on every heartbeat. */
38
+ export const NATIVE_COMMANDS_INDEX = `CREATE INDEX IF NOT EXISTS settings_native_commands ON settings (connector_id, key) WHERE key >= 'native.remote.command.' AND key < 'native.remote.command/'`;
34
39
  export const COMMANDS_ONE_ANSWER = `CREATE UNIQUE INDEX IF NOT EXISTS ${ONE_ANSWER_INDEX} ON commands (run_id, json_extract(body, '$.approval')) WHERE kind IN ('approve', 'deny') AND refused IS NULL`;
35
40
  const json = (column, nullable = false) => `${column} TEXT${nullable ? "" : " NOT NULL"} CHECK (${column} IS NULL OR json_valid(${column}))`;
36
41
  /** A revision's MCP pin, as its save listed the tools (JSON, null when it grants no MCP tool). In STORE_DDL, and added at a
37
42
  * server open to a store an earlier build of this version made (one that pinned each run in mcp_pins, dropped at that open). */
38
43
  export const REVISIONS_MCP_PIN = `ALTER TABLE revisions ADD COLUMN ${json("mcp_pin", true)}`;
44
+ /** A revision's monid pin (JSON, null for none): in STORE_DDL, and added at a server open as REVISIONS_MCP_PIN is. */
45
+ export const REVISIONS_MONID_PIN = `ALTER TABLE revisions ADD COLUMN ${json("monid_pin", true)}`;
46
+ /** Whether a run's stored cost (cost_usd) is the most it can have cost, not its cost: 1 when it counts a request cut with
47
+ * no answer at what its cap held for it (runner.ts CUT_AT_HOLD), written in the end's commit with the cost; 0 otherwise,
48
+ * an unknown cost's included. */
49
+ const COST_UPPER_BOUND = "cost_upper_bound INTEGER NOT NULL DEFAULT 0 CHECK (cost_upper_bound IN (0, 1))";
50
+ /** The bound beside a run's cost: in STORE_DDL, and added at a server open to a store an earlier build of this version made,
51
+ * as REVISIONS_MCP_PIN is (a run it ended reads 0: an exact cost or an unknown one, as it was read then). */
52
+ export const RUNS_COST_UPPER_BOUND = `ALTER TABLE runs ADD COLUMN ${COST_UPPER_BOUND}`;
39
53
  /** A template package imported from GitHub (POST /v2/templates/import), by its id (`github:<owner>/<repo>[/<path>]`): its
40
54
  * source as given (ref and all), the full commit SHA read, the GitHub account that publishes it, and its files as read
41
55
  * (`files`, a JSON object of path to base64). A re-import of the id replaces the row. The server checks the files again
@@ -79,6 +93,7 @@ export const STORE_DDL = [
79
93
  // for the v2 revisions view. `note`: the optional note a revision was committed with (the v2 note), null for none.
80
94
  // `mcp_pin`: the MCP tools the revision grants, as their servers listed them when it was saved (mcp-gateway.ts McpPin:
81
95
  // per server its URL then, the granted tools, their prices), which every run of it calls; null when it grants none.
96
+ // `monid_pin`: its monid endpoints as monid listed them when it was saved (agent-body.ts MonidPinBody); null for none.
82
97
  `CREATE TABLE IF NOT EXISTS revisions (
83
98
  id TEXT PRIMARY KEY,
84
99
  agent_id TEXT NOT NULL REFERENCES agents (id),
@@ -90,7 +105,8 @@ export const STORE_DDL = [
90
105
  note TEXT,
91
106
  external_version TEXT,
92
107
  created_at INTEGER NOT NULL,
93
- ${json("mcp_pin", true)}
108
+ ${json("mcp_pin", true)},
109
+ ${json("monid_pin", true)}
94
110
  ) STRICT`,
95
111
  `CREATE INDEX IF NOT EXISTS revisions_by_agent ON revisions (agent_id, created_at)`,
96
112
  // `external_version`: for a revision of an externally owned agent, the version it maps there (one revision per version),
@@ -109,6 +125,7 @@ export const STORE_DDL = [
109
125
  wake_at INTEGER,
110
126
  backoff_until INTEGER,
111
127
  cost_usd REAL,
128
+ ${COST_UPPER_BOUND},
112
129
  ${json("metrics", true)},
113
130
  summary TEXT,
114
131
  -- How the run ended beside its state (RunOutcome). An ended run: 'escalated' (it finished its work and waits for a
@@ -317,8 +334,10 @@ export const STORE_DDL = [
317
334
  `CREATE TABLE IF NOT EXISTS settings (
318
335
  key TEXT PRIMARY KEY,
319
336
  ${json("value")},
337
+ connector_id TEXT,
320
338
  updated_at INTEGER NOT NULL
321
339
  ) STRICT`,
340
+ NATIVE_COMMANDS_INDEX,
322
341
  `CREATE TABLE IF NOT EXISTS sealed_keys (
323
342
  name TEXT PRIMARY KEY,
324
343
  sealed BLOB NOT NULL,
@@ -36,6 +36,7 @@ export type RunRecord = {
36
36
  wake_at: number | null;
37
37
  backoff_until: number | null;
38
38
  cost_usd: number | null;
39
+ cost_upper_bound: number;
39
40
  metrics: string | null;
40
41
  summary: string | null;
41
42
  outcome: string | null;
@@ -45,7 +46,13 @@ export type RunRecord = {
45
46
  started_at: number;
46
47
  ended_at: number | null;
47
48
  };
48
- export declare const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, started_at, ended_at";
49
+ export declare const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, cost_upper_bound, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, started_at, ended_at";
50
+ /** A run's exact cost in SQL, for a query that reads runs.cost_usd itself (`alias`: its runs table's): NULL when the
51
+ * stored figure is only the most the run can have cost, as runOf reads it. Every raw read of the column goes through it. */
52
+ export declare const EXACT_COST_USD: (alias: string) => string;
53
+ /** The run row from its record. The stored cost splits here, once, for every reader: an exact cost (or null) is `costUsd`;
54
+ * a cost stored as the most the run can have cost (cost_upper_bound 1) is `costAtMostUsd` alone, and `costUsd` reads null,
55
+ * as for a cost no one knows. So a reader that sums or shows spend never reads a bound, with no check of its own. */
49
56
  export declare const runOf: (r: RunRecord) => RunRow;
50
57
  /** Applies `patch` to the claim's run, then writes `also`, through `tx` (an open transaction's handle). Fenced, with nothing
51
58
  * of it written once the caller rolls back, when the run's epoch is not the claim's or the claim's lease ran out before
@@ -18,10 +18,17 @@ export const learningLaunchOf = (runId, model, round = 1, capUsd) => ({ harness:
18
18
  /** The lock a write of a run's sign_in_handed and a sign-in's forget both take (Dialect.lockKey): the forget's check of
19
19
  * the running runs' hashes and a launch's write of them are serialized, as SQLite's one writer serializes them. */
20
20
  export const SIGN_IN_HANDED_LOCK = "sign_in_handed";
21
- export const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, started_at, ended_at";
21
+ export const RUN_COLUMNS = "id, agent_id, revision_id, state, epoch, runner, claimed_until, wake_at, backoff_until, cost_usd, cost_upper_bound, metrics, summary, outcome, archived_at, imported_from, sign_in_handed, started_at, ended_at";
22
+ /** A run's exact cost in SQL, for a query that reads runs.cost_usd itself (`alias`: its runs table's): NULL when the
23
+ * stored figure is only the most the run can have cost, as runOf reads it. Every raw read of the column goes through it. */
24
+ export const EXACT_COST_USD = (alias) => `CASE WHEN ${alias}.cost_upper_bound = 1 THEN NULL ELSE ${alias}.cost_usd END`;
25
+ const costOf = (usd, bound) => usd !== null && Number(bound) === 1 ? { costUsd: null, costAtMostUsd: usd } : { costUsd: usd, costAtMostUsd: null };
26
+ /** The run row from its record. The stored cost splits here, once, for every reader: an exact cost (or null) is `costUsd`;
27
+ * a cost stored as the most the run can have cost (cost_upper_bound 1) is `costAtMostUsd` alone, and `costUsd` reads null,
28
+ * as for a cost no one knows. So a reader that sums or shows spend never reads a bound, with no check of its own. */
22
29
  export const runOf = (r) => ({
23
30
  id: r.id, agentId: r.agent_id, revisionId: r.revision_id, state: r.state, epoch: r.epoch, runner: r.runner, claimedUntil: r.claimed_until,
24
- wakeAt: r.wake_at, backoffUntil: r.backoff_until, costUsd: r.cost_usd, metrics: r.metrics === null ? null : JSON.parse(r.metrics), summary: r.summary,
31
+ wakeAt: r.wake_at, backoffUntil: r.backoff_until, ...costOf(r.cost_usd, r.cost_upper_bound), metrics: r.metrics === null ? null : JSON.parse(r.metrics), summary: r.summary,
25
32
  outcome: r.outcome ?? null, archivedAt: r.archived_at, importedFrom: r.imported_from === null ? null : JSON.parse(r.imported_from),
26
33
  signInHanded: r.sign_in_handed === null ? null : JSON.parse(r.sign_in_handed), startedAt: r.started_at, endedAt: r.ended_at,
27
34
  });
@@ -36,8 +43,12 @@ export async function applyRunPatch(tx, claim, patch, also, now, dialect = SQLIT
36
43
  const set = (column, value) => (sets.push(`${column} = ?`), params.push(value));
37
44
  if (patch.state !== undefined)
38
45
  set("state", patch.state);
39
- if (patch.costUsd !== undefined)
46
+ // The bound beside the cost goes with it: a cost written without one is exact (or unknown), never a bound left from an
47
+ // earlier end of the run.
48
+ if (patch.costUsd !== undefined) {
40
49
  set("cost_usd", patch.costUsd);
50
+ set("cost_upper_bound", patch.costUsd !== null && patch.costUpperBound === true ? 1 : 0);
51
+ }
41
52
  if (patch.metrics !== undefined)
42
53
  set("metrics", patch.metrics === null ? null : JSON.stringify(patch.metrics));
43
54
  if (patch.summary !== undefined)
@@ -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) => {
@@ -20,7 +21,7 @@ const seqOf = (cursor) => {
20
21
  };
21
22
  import { 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 { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
24
25
  import { readLaunch, writeLaunch } from "./run-launch.js";
25
26
  import { canonical } from "../agent-body.js";
26
27
  import { aadOf, sealedAt } from "../seal.js";
@@ -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) {
@@ -386,7 +407,7 @@ class SqliteStore {
386
407
  throw new StoreConstraint(`no agent ${agentId}`);
387
408
  if (ifCurrent !== undefined && agent.current_revision !== ifCurrent)
388
409
  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));
410
+ 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
411
  await tx.run("UPDATE agents SET current_revision = ? WHERE id = ?", revision.id, agentId);
391
412
  };
392
413
  const writeScopes = async (tx, triggerId, scopes) => {
@@ -784,7 +805,7 @@ class SqliteStore {
784
805
  }
785
806
  else {
786
807
  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));
808
+ 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
809
  await tx.run("UPDATE agents SET current_revision = ?, name = ?, description = ? WHERE id = ?", revisionId, agent.name, agent.description ?? null, mapped.id);
789
810
  }
790
811
  // The run, its origin and its launch, in the same transaction as the agent and the revision.
@@ -1111,7 +1132,7 @@ class SqliteStore {
1111
1132
  },
1112
1133
  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),
1113
1134
  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
1135
+ 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
1136
  FROM learning_proposals lp
1116
1137
  JOIN runs src ON src.id = lp.run_id
1117
1138
  LEFT JOIN runs lr ON lr.id = lp.learning_run_id
@@ -1128,7 +1149,7 @@ class SqliteStore {
1128
1149
  });
1129
1150
  },
1130
1151
  spentBeside: async (runId, { beforeRound } = {}) => {
1131
- const rows = await db.all(`SELECT lr.state, lr.cost_usd, rl.body
1152
+ const rows = await db.all(`SELECT lr.state, ${EXACT_COST_USD("lr")} AS cost_usd, rl.body
1132
1153
  FROM learning_proposals lp
1133
1154
  LEFT JOIN runs lr ON lr.id = lp.learning_run_id
1134
1155
  LEFT JOIN run_launch rl ON rl.run_id = lp.learning_run_id
@@ -1157,16 +1178,52 @@ class SqliteStore {
1157
1178
  return row === undefined ? undefined : JSON.parse(row.value);
1158
1179
  },
1159
1180
  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()] }]);
1181
+ const encoded = json(value);
1182
+ 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()] }]);
1183
+ },
1184
+ putIfAbsent: async (key, value, capacity) => {
1185
+ const encoded = json(value);
1186
+ if (capacity !== undefined) {
1187
+ if (typeof capacity.prefix !== "string" || !capacity.prefix || capacity.prefix.includes("\0") || !key.startsWith(capacity.prefix) || !Number.isSafeInteger(capacity.limit) || capacity.limit < 1)
1188
+ throw new TypeError("settings capacity requires a matching nonempty prefix and a positive safe integer limit");
1189
+ return db.transaction(async (tx) => {
1190
+ // SQLite holds its writer lock already; Postgres holds this schema's prefix lock until commit. The count
1191
+ // and insertion cannot interleave with another bounded insertion, even through an independent store handle.
1192
+ await d.lockKey(tx, `settings.capacity:${capacity.prefix}`);
1193
+ const existing = await tx.get("SELECT value FROM settings WHERE key = ?", key);
1194
+ if (existing !== undefined)
1195
+ return JSON.parse(existing.value);
1196
+ // Match Settings.all's literal prefix range: use the key index and never parse values or treat _/% as LIKE.
1197
+ const points = Array.from(capacity.prefix);
1198
+ let upper;
1199
+ for (let i = points.length - 1; i >= 0; i--) {
1200
+ const cp = points[i].codePointAt(0);
1201
+ if (cp < 0x10ffff) {
1202
+ upper = points.slice(0, i).join("") + String.fromCodePoint(cp + 1);
1203
+ break;
1204
+ }
1205
+ }
1206
+ 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);
1207
+ if (Number(count?.n ?? 0) >= capacity.limit)
1208
+ return undefined;
1209
+ await tx.run("INSERT INTO settings (key, value, connector_id, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO NOTHING", key, encoded, nativeCommandOwner(key, encoded), now());
1210
+ const saved = await tx.get("SELECT value FROM settings WHERE key = ?", key);
1211
+ return saved === undefined ? undefined : JSON.parse(saved.value);
1212
+ });
1213
+ }
1214
+ 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
1215
  const row = await db.get("SELECT value FROM settings WHERE key = ?", key);
1165
1216
  return row === undefined ? undefined : JSON.parse(row.value);
1166
1217
  },
1167
1218
  // `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)] }]);
1219
+ replaceIf: async (key, was, value, claim) => {
1220
+ const encoded = json(value);
1221
+ if (claim)
1222
+ return db.transaction(async (tx) => {
1223
+ const at = await underClaim(tx, claim, now);
1224
+ 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;
1225
+ });
1226
+ 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
1227
  return result.changes === 1;
1171
1228
  },
1172
1229
  removeIf: async (key, was) => {
@@ -1176,7 +1233,38 @@ class SqliteStore {
1176
1233
  remove: async (key) => {
1177
1234
  await db.write([{ sql: "DELETE FROM settings WHERE key = ?", params: [key] }]);
1178
1235
  },
1179
- all: async () => (await db.all("SELECT key, value, updated_at FROM settings ORDER BY key")).map(settingOf),
1236
+ all: async (filter) => {
1237
+ const clauses = [], params = [];
1238
+ if (filter?.connectorId !== undefined && !validConnectorId(filter.connectorId))
1239
+ return [];
1240
+ if (filter) {
1241
+ // Both stores order keys by bytes (Postgres settings.key is COLLATE C). This range also enables namespace indexes.
1242
+ const points = Array.from(filter.prefix);
1243
+ let upper;
1244
+ for (let i = points.length - 1; i >= 0; i--) {
1245
+ const cp = points[i].codePointAt(0);
1246
+ if (cp < 0x10ffff) {
1247
+ upper = points.slice(0, i).join("") + String.fromCodePoint(cp + 1);
1248
+ break;
1249
+ }
1250
+ }
1251
+ clauses.push("key >= ?");
1252
+ params.push(filter.prefix);
1253
+ if (upper !== undefined) {
1254
+ clauses.push("key < ?");
1255
+ params.push(upper);
1256
+ }
1257
+ clauses.push("substr(key, 1, length(?)) = ?");
1258
+ params.push(filter.prefix, filter.prefix);
1259
+ }
1260
+ const selection = `SELECT key, value, updated_at FROM settings${clauses.length ? ` WHERE ${clauses.join(" AND ")}` : ""}`;
1261
+ // Disjoint indexed branches: an OR lets SQLite choose a namespace scan over every connector's payload.
1262
+ // Null metadata is a legacy write racing setup; strict JS verification below never widens its owner.
1263
+ const query = filter?.connectorId === undefined ? `${selection} ORDER BY key` : `${selection} AND connector_id = ? UNION ALL ${selection} AND connector_id IS NULL ORDER BY key`;
1264
+ const values = filter?.connectorId === undefined ? params : [...params, filter.connectorId, ...params];
1265
+ const rows = await db.all(query, ...values);
1266
+ return rows.filter(row => filter?.connectorId === undefined || nativeCommandOwner(row.key, row.value) === filter.connectorId).map(settingOf);
1267
+ },
1180
1268
  };
1181
1269
  this.sealedKeys = {
1182
1270
  get: async (name) => {
@@ -1186,9 +1274,20 @@ class SqliteStore {
1186
1274
  put: async (name, sealed) => {
1187
1275
  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
1276
  },
1277
+ replaceIf: async (name, was, sealed) => {
1278
+ const [result] = await db.write([{ sql: "UPDATE sealed_keys SET sealed = ?, updated_at = ? WHERE name = ? AND sealed = ?", params: [sealed, now(), name, was] }]);
1279
+ return result.changes === 1;
1280
+ },
1189
1281
  remove: async (name) => {
1190
1282
  await db.write([{ sql: "DELETE FROM sealed_keys WHERE name = ?", params: [name] }]);
1191
1283
  },
1284
+ removeIf: async (name, was) => {
1285
+ const [result] = await db.write([{ sql: "DELETE FROM sealed_keys WHERE name = ? AND sealed = ?", params: [name, was] }]);
1286
+ return result.changes === 1;
1287
+ },
1288
+ // The deadlines' clock (fence.ts storeNow): read from the database where the dialect names its clock (Postgres),
1289
+ // else the store's own.
1290
+ clock: async () => (d.nowSql ? Number((await db.get(`SELECT ${d.nowSql} AS now`)).now) : now()),
1192
1291
  all: async () => (await db.all("SELECT name, sealed, updated_at FROM sealed_keys ORDER BY name")).map(sealedKeyOf),
1193
1292
  };
1194
1293
  this.computerLedger = {
@@ -1660,6 +1759,22 @@ class SqliteStore {
1660
1759
  const at = this.#now();
1661
1760
  const state = run.state ?? "ended";
1662
1761
  return this.#db.transaction(async (tx) => {
1762
+ for (const guard of [...(run.settingsGuards ?? [])].sort((a, b) => a.key.localeCompare(b.key))) {
1763
+ // A no-op update takes the row's write lock on both SQLite and Postgres until the import commits. A source
1764
+ // revoke/disconnect either commits first and refuses this write, or waits for this already-started import.
1765
+ const setting = await tx.get("UPDATE settings SET value = value WHERE key = ? RETURNING value", guard.key);
1766
+ const value = setting === undefined ? undefined : JSON.parse(setting.value);
1767
+ if (!value || Object.entries(guard.fields).some(([field, expected]) => JSON.stringify(value[field]) !== JSON.stringify(expected))) {
1768
+ throw new StoreConstraint("The source import grant changed before the history write committed.");
1769
+ }
1770
+ }
1771
+ if (run.requireActiveAgent) {
1772
+ // Archive updates this same row. It either commits first and refuses this import, or waits for this
1773
+ // already-admitted history transaction; a read outside the transaction cannot establish that order.
1774
+ const agent = await tx.get("UPDATE agents SET archived_at = archived_at WHERE id = ? AND archived_at IS NULL RETURNING id", run.agentId);
1775
+ if (!agent)
1776
+ throw new StoreConstraint("The agent was archived before the history write committed.");
1777
+ }
1663
1778
  // The ended run row, its launch row and its transcript's journal, all in this one transaction (the server's own
1664
1779
  // writer): a crash between them leaves nothing. The run is created at epoch 0 with no runner, and the journal's fence
1665
1780
  // passes for that one row, by the rowid its insert returned (the claim fence's inserted-here form).
@@ -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. */
@@ -765,6 +789,7 @@ export interface Runs {
765
789
  skills?: unknown;
766
790
  note?: string;
767
791
  mcpPin?: unknown;
792
+ monidPin?: MonidPinBody;
768
793
  };
769
794
  run: {
770
795
  id: string;
@@ -1051,19 +1076,28 @@ export interface Settings {
1051
1076
  get(key: string): Promise<unknown | undefined>;
1052
1077
  /** Saves `value` (JSON) under `key`, inserted or replaced in place. */
1053
1078
  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>;
1079
+ /** Saves `value` under `key` only when the key has no row yet; the value saved after (this one, or the one there before).
1080
+ * With `capacity`, count and insert share a namespace lock and transaction across store handles. Every raw key under
1081
+ * the exact prefix counts, without decoding values. An existing key wins even at capacity; undefined means a new key
1082
+ * was refused. The nonempty prefix must contain the key, and limit must be a positive safe integer. */
1083
+ putIfAbsent(key: string, value: unknown, capacity?: {
1084
+ readonly prefix: string;
1085
+ readonly limit: number;
1086
+ }): Promise<unknown>;
1057
1087
  /** Saves `value` under `key` only while its row still holds `was` (as get read it), in one statement: a compare-and-set,
1058
1088
  * 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>;
1089
+ * when the row changed since or is gone. With `claim`, holds the run's shared row lock and checks its epoch/lease in
1090
+ * the same transaction as the setting update; a stale claim throws Fenced without changing the setting. */
1091
+ replaceIf(key: string, was: unknown, value: unknown, claim?: Claim): Promise<boolean>;
1061
1092
  /** The key's row goes only while it still holds `was`, in one statement: true when it went. */
1062
1093
  removeIf(key: string, was: unknown): Promise<boolean>;
1063
1094
  /** The key's row goes; a key with no row is left as it is. */
1064
1095
  remove(key: string): Promise<void>;
1065
- /** Every setting, by key. */
1066
- all(): Promise<SettingRow[]>;
1096
+ /** Settings by key, optionally selecting a namespace and native connector owner before values are read. */
1097
+ all(filter?: {
1098
+ readonly prefix: string;
1099
+ readonly connectorId?: string;
1100
+ }): Promise<SettingRow[]>;
1067
1101
  }
1068
1102
  /** A sealed key as a row (store schema `sealed_keys`): its name and the bytes the server sealed (store/seal.ts, AAD
1069
1103
  * sealed_keys|<name>|sealed), which the store never opens. */
@@ -1093,8 +1127,19 @@ export interface SealedKeys {
1093
1127
  get(name: string): Promise<Uint8Array | undefined>;
1094
1128
  /** Saves `sealed` under `name`, inserted or replaced in place. */
1095
1129
  put(name: string, sealed: Uint8Array): Promise<void>;
1130
+ /** Saves `sealed` under `name` only while its row still holds `was` (the bytes as get read them), in one statement: a
1131
+ * compare-and-set, so of two writers that read one row only one replaces it. Each seal is fresh bytes, so a row any
1132
+ * writer saved since reads as changed. True when it was replaced; false, writing nothing, when it changed or is gone. */
1133
+ replaceIf(name: string, was: Uint8Array, sealed: Uint8Array): Promise<boolean>;
1096
1134
  /** The key's row goes. */
1097
1135
  remove(name: string): Promise<void>;
1136
+ /** The key's row goes only while it still holds `was` (the bytes as get read them), in one statement: true when it
1137
+ * went; false, removing nothing, when it changed since or is gone. */
1138
+ removeIf(name: string, was: Uint8Array): Promise<boolean>;
1139
+ /** The deadlines' clock now, in ms: the database's on Postgres, the store's own on SQLite (fence.ts storeNow). A lease
1140
+ * kept inside a sealed key's bytes (the ChatGPT sign-in's renewal) is stamped and judged by it, so every process
1141
+ * sharing the store judges it by one clock, whatever its own says. */
1142
+ clock(): Promise<number>;
1098
1143
  /** Every saved key, by name (its bytes never opened here). */
1099
1144
  all(): Promise<SealedKeyRow[]>;
1100
1145
  }
@@ -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;