@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
@@ -0,0 +1,47 @@
1
+ export const NATIVE_COMMAND_PREFIX = 'native.remote.command.';
2
+ export const NATIVE_COMMAND_UPPER = 'native.remote.command/';
3
+ export const validConnectorId = (value) => typeof value === 'string' && value.length > 0 && value.length <= 160 && !/[\x00-\x1f]/.test(value) && /^[\w.-]+$/.test(value);
4
+ export function nativeCommandOwner(key, encoded) {
5
+ if (!key.startsWith(NATIVE_COMMAND_PREFIX))
6
+ return null;
7
+ try {
8
+ const value = JSON.parse(encoded);
9
+ const owner = value !== null && typeof value === 'object' && !Array.isArray(value) ? value.connector_id : undefined;
10
+ return validConnectorId(owner) ? owner : null;
11
+ }
12
+ catch {
13
+ return null;
14
+ }
15
+ }
16
+ const change = (row) => ({ sql: 'UPDATE settings SET connector_id = ? WHERE key = ? AND value = ? AND connector_id IS NULL', params: [nativeCommandOwner(row.key, row.value), row.key, row.value] });
17
+ /** A server's additive setup, in bounded pages. Never changes a value, timestamp, lease or receipt. A new writer derives
18
+ * its owner atomically; a concurrent legacy update is reread after its raw-value CAS fails, never labelled from stale data.
19
+ * Older native commands keep immutable owners; supported writers update metadata with their value.
20
+ * Null-owner legacy rows remain readable by the filtered reader until a later server can index them. */
21
+ export async function backfillNativeCommandOwners(connection) {
22
+ let after = '';
23
+ for (;;) {
24
+ const page = await connection.all('SELECT key,value,connector_id FROM settings WHERE key >= ? AND key < ? AND key > ? AND connector_id IS NULL ORDER BY key LIMIT 8', NATIVE_COMMAND_PREFIX, NATIVE_COMMAND_UPPER, after);
25
+ if (!page.length)
26
+ return;
27
+ const results = await connection.write(page.map(change));
28
+ for (let i = 0; i < page.length; i++)
29
+ if (results[i].changes === 0) {
30
+ let settled = false;
31
+ for (let attempt = 0; attempt < 10; attempt++) {
32
+ const row = await connection.get('SELECT key,value,connector_id FROM settings WHERE key = ?', page[i].key);
33
+ if (!row || row.connector_id !== null) {
34
+ settled = true;
35
+ break;
36
+ }
37
+ if ((await connection.write([change(row)]))[0].changes === 1) {
38
+ settled = true;
39
+ break;
40
+ }
41
+ }
42
+ if (!settled)
43
+ throw new Error('Native command ownership setup is busy. Stop older runners and start this build’s server again before its runners.');
44
+ }
45
+ after = page.at(-1).key;
46
+ }
47
+ }
@@ -30,12 +30,18 @@ export interface PgConnectionOptions {
30
30
  readonly poolSize?: number;
31
31
  /** Deadlines on the store's own (test) clock, bound as parameters, instead of the database's (postgresDialect). */
32
32
  readonly testClock?: boolean;
33
- /** How long getting a connection may take (STORE_CONNECT_TIMEOUT_MS by default): a new one's connect and startup, or a
34
- * wait for one of the pool's to come free. Past it the call is refused (StoreDeadline, naming the database's place,
35
- * never its URL), never left hanging on a database that does not answer. */
33
+ /** How long a new connection's connect and startup may take (STORE_CONNECT_TIMEOUT_MS by default). Past it the call is
34
+ * refused (StoreDeadline, naming the database's place, never its URL, in words that say it does not answer), never left
35
+ * hanging on a database that does not answer. */
36
36
  readonly connectTimeoutMs?: number;
37
+ /** How long a call may wait for one of the pool's connections to come free while every one is in use
38
+ * (STORE_WRITE_DEADLINE_MS by default, and never less than connectTimeoutMs): a busy pool is waited out to a write's own
39
+ * deadline, never failed at the connect timeout. Past it the call is refused (StoreDeadline, in words that say every
40
+ * connection stayed in use), nothing of it sent. */
41
+ readonly poolWaitMs?: number;
37
42
  }
38
- /** The default bound on getting a connection to the store's Postgres (PgConnectionOptions.connectTimeoutMs), in ms. Below
43
+ /** The default bound on a new connection's connect and startup to the store's Postgres (PgConnectionOptions.connectTimeoutMs),
44
+ * in ms; a wait for a busy pool's connection to come free has its own, longer bound (PgConnectionOptions.poolWaitMs). Below
39
45
  * the runner's stop margin (runner.ts: lease 30 s, renew every 10 s, stop margin 5 s; a claim is let go when no renew has
40
46
  * landed within lease - margin = 25 s of the last one's send, so two renew ticks, at +10 s and +20 s, fall inside it): a
41
47
  * renew that cannot get a connection gives up within 4 s, inside the 5 s margin, and the next tick tries again. A renew
@@ -70,7 +76,7 @@ export declare class PgConnection implements StoreConnection {
70
76
  readonly where: string;
71
77
  private constructor();
72
78
  /** The pool on `url` in `schema`, and (owner) the owner lock: StoreOwned when another server holds the schema. */
73
- static open({ url, schema, owner, busyTimeoutMs, poolSize, testClock, connectTimeoutMs, ownerWaitMs, onOwnerWait, onOwnerLost, ownerCheck }: PgConnectionOptions): Promise<PgConnection>;
79
+ static open({ url, schema, owner, busyTimeoutMs, poolSize, testClock, connectTimeoutMs, poolWaitMs, ownerWaitMs, onOwnerWait, onOwnerLost, ownerCheck }: PgConnectionOptions): Promise<PgConnection>;
74
80
  get<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T | undefined>;
75
81
  all<T extends object>(sql: string, ...params: SqliteValue[]): Promise<T[]>;
76
82
  /** One statement on its own (autocommit), its changes counted: the shared code's run outside a transaction. */
@@ -8,7 +8,7 @@ import pg from "pg";
8
8
  import { runnableDeadline } from "../deadline.js";
9
9
  import { cleanText } from "../dialect.js";
10
10
  import { ONE_ANSWER_INDEX } from "../schema.js";
11
- import { AnswerTaken, Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned } from "../store.js";
11
+ import { AnswerTaken, Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned, STORE_WRITE_DEADLINE_MS } from "../store.js";
12
12
  import { DEFAULT_TRANSACTION_DEADLINE_MS } from "../sqlite/connection.js";
13
13
  import { postgresDialect } from "./dialect.js";
14
14
  /** Which store this is, as two opens of the same data agree on it (StoreConnection.where): "postgres:" and the URL's host
@@ -26,7 +26,8 @@ export function postgresWhere(url, schema) {
26
26
  }
27
27
  /** A schema name the store takes: a plain lower-case identifier, so it is never quoted, and never input in SQL. */
28
28
  export const SCHEMA_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
29
- /** The default bound on getting a connection to the store's Postgres (PgConnectionOptions.connectTimeoutMs), in ms. Below
29
+ /** The default bound on a new connection's connect and startup to the store's Postgres (PgConnectionOptions.connectTimeoutMs),
30
+ * in ms; a wait for a busy pool's connection to come free has its own, longer bound (PgConnectionOptions.poolWaitMs). Below
30
31
  * the runner's stop margin (runner.ts: lease 30 s, renew every 10 s, stop margin 5 s; a claim is let go when no renew has
31
32
  * landed within lease - margin = 25 s of the last one's send, so two renew ticks, at +10 s and +20 s, fall inside it): a
32
33
  * renew that cannot get a connection gives up within 4 s, inside the 5 s margin, and the next tick tries again. A renew
@@ -34,17 +35,20 @@ export const SCHEMA_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
34
35
  * renew, connect to commit, is bounded from its call (LEASE_DEADLINE_MS), so one sent at +10 s whose connection went
35
36
  * silent fails by +19 s and the +20 s tick renews on a fresh connection before +25 s. */
36
37
  export const STORE_CONNECT_TIMEOUT_MS = 4_000;
37
- /** pg's and pg-pool's words for a connection not had in time: a connect or startup that never finished, or no pool client
38
- * free. */
39
- const CONNECT_TIMEOUT = /timeout exceeded when trying to connect|timeout expired|Connection terminated due to connection timeout/i;
40
- /** Whether `error`, or an error it was made from, is a connection not had in time. */
41
- function connectTimedOut(error) {
38
+ /** pg's and pg-pool's words for a new connection's connect or startup that never finished in time. */
39
+ const CONNECT_TIMEOUT = /timeout expired|Connection terminated due to connection timeout/i;
40
+ /** pg-pool's words for a wait in its queue that no client came free for in time (every one in use). */
41
+ const POOL_WAIT_TIMEOUT = /timeout exceeded when trying to connect/i;
42
+ /** Whether `error`, or an error it was made from, says `words`. */
43
+ function says(error, words) {
42
44
  for (let e = error, depth = 0; e && depth < 5; e = e.cause, depth++) {
43
- if (CONNECT_TIMEOUT.test(String(e.message ?? "")))
45
+ if (words.test(String(e.message ?? "")))
44
46
  return true;
45
47
  }
46
48
  return false;
47
49
  }
50
+ /** Whether `error`, or an error it was made from, is a new connection not had in time. */
51
+ const connectTimedOut = (error) => says(error, CONNECT_TIMEOUT);
48
52
  /** A COMMIT is bounded by what is left of its transaction's deadline, never less than this (a commit sent at the deadline
49
53
  * still gets an answer's time). Past it the connection is taken as silent and let go (destroyed); the commit's outcome is
50
54
  * then unknown, and the caller is told so (Unanswered). STORE_WRITE_DEADLINE_MS's users keep 2 s spare for it. */
@@ -89,9 +93,14 @@ async function answered(query, ms, what) {
89
93
  async function rollBackAndRelease(client) {
90
94
  await answered(client.query("ROLLBACK"), ROLLBACK_ANSWER_MS, "its rollback").then(() => client.release(), (error) => client.release(error));
91
95
  }
92
- /** The refusal for a connection not had within `ms` from the database at `where` (postgresWhere: no user or password). */
96
+ /** The refusal for a new connection not made within `ms` to the database at `where` (postgresWhere: no user or password). */
93
97
  function connectDeadline(where, ms) {
94
- return new StoreDeadline(ms, `no connection to the store's Postgres at ${where} within ${ms} ms: it does not answer, or every connection of this store is in use`);
98
+ return new StoreDeadline(ms, `no connection to the store's Postgres at ${where} within ${ms} ms: it does not answer`);
99
+ }
100
+ /** The refusal for a call that waited `ms` for one of the `size` connections of the store's pool on the database at
101
+ * `where`, every one of them in use all that time: the store is busier than its pool, and the database answers. */
102
+ function poolBusy(where, ms, size) {
103
+ return new StoreDeadline(ms, `no connection of the store's Postgres at ${where} came free within ${ms} ms: all ${size} of this store's connections stayed in use, so the call was never sent`);
95
104
  }
96
105
  /** int8 as a JavaScript number: every integer the store keeps (ms, ids, epochs, counts) is one, and one outside the safe
97
106
  * range is refused, as node:sqlite refuses it. */
@@ -277,8 +286,10 @@ export class PgConnection {
277
286
  /** What taking the owner lock back needs. */
278
287
  #ownerConfig;
279
288
  #busyTimeoutMs;
280
- /** The bound on getting a connection (PgConnectionOptions.connectTimeoutMs). */
289
+ /** The bound on a new connection's connect and startup (PgConnectionOptions.connectTimeoutMs). */
281
290
  #connectMs;
291
+ /** The bound on a wait for a busy pool's connection to come free (PgConnectionOptions.poolWaitMs), and the pool's size. */
292
+ #poolWait;
282
293
  #closed = false;
283
294
  /** Set while the owner lock is not held (its connection ended or failed, and it is being taken back), and for good once
284
295
  * another server has the schema: every call is refused with it meanwhile. */
@@ -300,8 +311,9 @@ export class PgConnection {
300
311
  }
301
312
  return columns;
302
313
  };
303
- constructor(pool, owner, schema, busyTimeoutMs, where, testClock, connectMs, leasePool, ownerConfig) {
314
+ constructor(pool, owner, schema, busyTimeoutMs, where, testClock, connectMs, poolWait, leasePool, ownerConfig) {
304
315
  this.#connectMs = connectMs;
316
+ this.#poolWait = poolWait;
305
317
  this.#pool = pool;
306
318
  this.#leasePool = leasePool;
307
319
  this.#owner = owner;
@@ -376,20 +388,31 @@ export class PgConnection {
376
388
  this.#ownerConfig?.onLost?.(error);
377
389
  }
378
390
  /** The pool on `url` in `schema`, and (owner) the owner lock: StoreOwned when another server holds the schema. */
379
- static async open({ url, schema, owner = false, busyTimeoutMs = 10_000, poolSize = 10, testClock = false, connectTimeoutMs = STORE_CONNECT_TIMEOUT_MS, ownerWaitMs = OWNER_WAIT_MS, onOwnerWait, onOwnerLost, ownerCheck }) {
391
+ static async open({ url, schema, owner = false, busyTimeoutMs = 10_000, poolSize = 10, testClock = false, connectTimeoutMs = STORE_CONNECT_TIMEOUT_MS, poolWaitMs = STORE_WRITE_DEADLINE_MS, ownerWaitMs = OWNER_WAIT_MS, onOwnerWait, onOwnerLost, ownerCheck }) {
380
392
  if (!SCHEMA_NAME.test(schema))
381
393
  throw new TypeError(`the store's schema is a lower-case name of letters, digits and underscores, not ${JSON.stringify(schema)}`);
382
394
  // The database's end of the keepalives (KEEPALIVE_IDLE_S): a vanished client's session, and its locks, ended in ~25 s.
383
395
  const keepalives = `-c tcp_keepalives_idle=${KEEPALIVE_IDLE_S} -c tcp_keepalives_interval=5 -c tcp_keepalives_count=3`;
384
396
  const session = `-c search_path=${schema} -c lock_timeout=${Math.max(0, Math.floor(busyTimeoutMs))} -c synchronous_commit=on ${keepalives}`;
385
397
  const connectMs = Math.max(1, Math.floor(connectTimeoutMs));
398
+ // Never below the connect's bound: pg-pool's one connectionTimeoutMillis also cuts a new client's connect, which must
399
+ // keep its own bound and its own words (StoreClient's).
400
+ const poolWait = Math.max(connectMs, Math.floor(poolWaitMs));
386
401
  const where = postgresWhere(url, schema);
387
- // connectionTimeoutMillis bounds a new connection's connect and startup, and a wait for a pool client to come free.
402
+ // Two bounds on getting a connection, each in one place. A new connection's connect and startup: connectMs, on the
403
+ // client itself (StoreClient), so a database that does not answer is refused fast. A wait in the pool's queue while
404
+ // every client is in use (a runner's loops' commits behind one another): pg-pool's connectionTimeoutMillis, poolWait,
405
+ // so a busy pool of a database that answers is waited out to a write's own deadline, never failed at connectMs.
406
+ class StoreClient extends pg.Client {
407
+ constructor(config) {
408
+ super({ ...(typeof config === "string" ? { connectionString: config } : config), connectionTimeoutMillis: connectMs });
409
+ }
410
+ }
388
411
  // keepAlive: this end's TCP keepalives, from KEEPALIVE_IDLE_S (pg's default delay, 0, is the OS's 2 h).
389
412
  const tcp = { keepAlive: true, keepAliveInitialDelayMillis: KEEPALIVE_IDLE_S * 1_000 };
390
413
  // Every connection named for its schema, as the lease's and the owner lock's are: pg_stat_activity tells which
391
414
  // store holds each one.
392
- const config = { connectionString: url, options: session, types, max: poolSize, allowExitOnIdle: true, application_name: `agentrun-store:${schema}`, connectionTimeoutMillis: connectMs, ...tcp };
415
+ const config = { connectionString: url, options: session, types, max: poolSize, allowExitOnIdle: true, application_name: `agentrun-store:${schema}`, Client: StoreClient, connectionTimeoutMillis: poolWait, ...tcp };
393
416
  let lock;
394
417
  const waitMs = Math.max(0, Math.floor(ownerWaitMs));
395
418
  if (owner) {
@@ -428,7 +451,7 @@ export class PgConnection {
428
451
  each.on("error", () => undefined);
429
452
  each.on("connect", (fresh) => fresh.on("error", () => undefined));
430
453
  }
431
- return new PgConnection(pool, lock, schema, busyTimeoutMs, where, testClock, connectMs, leasePool, lock ? { url, waitMs, onLost: onOwnerLost, check: ownerCheck } : undefined);
454
+ return new PgConnection(pool, lock, schema, busyTimeoutMs, where, testClock, connectMs, { ms: poolWait, size: poolSize }, leasePool, lock ? { url, waitMs, onLost: onOwnerLost, check: ownerCheck } : undefined);
432
455
  }
433
456
  /** `work`, counted in flight, refused after close. A connection it never got in time is StoreDeadline, naming the
434
457
  * database's place. */
@@ -438,7 +461,11 @@ export class PgConnection {
438
461
  if (this.#ownerLost)
439
462
  return Promise.reject(this.#ownerLost);
440
463
  const running = work().catch((error) => {
441
- throw connectTimedOut(error) ? connectDeadline(this.where, this.#connectMs) : error;
464
+ if (connectTimedOut(error))
465
+ throw connectDeadline(this.where, this.#connectMs);
466
+ if (says(error, POOL_WAIT_TIMEOUT))
467
+ throw poolBusy(this.where, this.#poolWait.ms, this.#poolWait.size);
468
+ throw error;
442
469
  });
443
470
  this.#inFlight.add(running);
444
471
  const done = () => void this.#inFlight.delete(running);
@@ -36,6 +36,11 @@ export function postgresDialect(schema, { testClock = false } = {}) {
36
36
  lockRow: async (tx, table, column, value, mode) => {
37
37
  await tx.run(`SELECT 1 FROM ${table} WHERE ${column} = ? FOR ${mode === "update" ? "UPDATE" : "NO KEY UPDATE"}`, value);
38
38
  },
39
+ lockRows: async (tx, table, column, values) => {
40
+ if (values.length === 0)
41
+ return;
42
+ await tx.run(`SELECT 1 FROM ${table} WHERE ${column} IN (${values.map(() => "?").join(", ")}) ORDER BY ${column} FOR NO KEY UPDATE`, ...values);
43
+ },
39
44
  lockKey: async (tx, key) => {
40
45
  await tx.run("SELECT pg_advisory_xact_lock(hashtext(?), hashtext(?))", schema, key);
41
46
  },
@@ -0,0 +1,4 @@
1
+ -- Version 12: an agent's monid pin on its revision (revisions.monid_pin, as store/schema.ts), no longer in its body.
2
+ -- Applied once, after 0011, inside the transaction migrate.ts opens. Never edit this file once applied.
3
+ ALTER TABLE revisions ADD COLUMN IF NOT EXISTS monid_pin TEXT COLLATE "C" CHECK (monid_pin IS NULL OR monid_pin::json IS NOT NULL);
4
+ UPDATE store_meta SET schema_version = 12 WHERE singleton = 1;
@@ -0,0 +1,6 @@
1
+ -- A bounded connector owner is derived from the exact command JSON by the server, preserving payload bytes (including
2
+ -- escaped NUL, which PostgreSQL JSON extraction cannot read). Existing rows are backfilled before polling is served.
3
+ ALTER TABLE settings ADD COLUMN IF NOT EXISTS connector_id TEXT COLLATE "C";
4
+ CREATE INDEX IF NOT EXISTS settings_native_commands ON settings (connector_id, key)
5
+ WHERE key >= 'native.remote.command.' AND key < 'native.remote.command/';
6
+ UPDATE store_meta SET schema_version = 13 WHERE singleton = 1;
@@ -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;
@@ -23,10 +23,14 @@ export interface PostgresStoreOptions {
23
23
  readonly busyTimeoutMs?: number;
24
24
  /** Most connections the store holds at once (10 by default). */
25
25
  readonly poolSize?: number;
26
- /** How long getting a connection may take, in ms: a new one's connect and startup, or a wait for one of the pool's to
27
- * come free (STORE_CONNECT_TIMEOUT_MS, 4 s, by default). Past it the call, or the open, is refused (StoreDeadline,
28
- * naming the database's host, database and schema, never the URL), never left hanging. */
26
+ /** How long a new connection's connect and startup may take, in ms (STORE_CONNECT_TIMEOUT_MS, 4 s, by default). Past it
27
+ * the call, or the open, is refused (StoreDeadline, naming the database's host, database and schema, never the URL:
28
+ * it does not answer), never left hanging. */
29
29
  readonly connectTimeoutMs?: number;
30
+ /** How long a call may wait for one of the pool's connections to come free while every one is in use, in ms
31
+ * (STORE_WRITE_DEADLINE_MS, 10 s, by default; never less than connectTimeoutMs). Past it the call is refused
32
+ * (StoreDeadline: every connection stayed in use), nothing of it sent. */
33
+ readonly poolWaitMs?: number;
30
34
  /** Told, at a runner's open, when its clock is more than CLOCK_WARN_MS from the database's; at a server's, when it waits
31
35
  * for another server to let the schema go. */
32
36
  readonly warn?: (message: string) => void;
@@ -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";
@@ -28,6 +29,7 @@ export async function openPostgresStore(options) {
28
29
  ...(options.busyTimeoutMs === undefined ? {} : { busyTimeoutMs: options.busyTimeoutMs }),
29
30
  ...(options.poolSize === undefined ? {} : { poolSize: options.poolSize }),
30
31
  ...(options.connectTimeoutMs === undefined ? {} : { connectTimeoutMs: options.connectTimeoutMs }),
32
+ ...(options.poolWaitMs === undefined ? {} : { poolWaitMs: options.poolWaitMs }),
31
33
  ...(options.ownerWaitMs === undefined ? {} : { ownerWaitMs: options.ownerWaitMs }),
32
34
  ...(options.warn ? { onOwnerWait: options.warn } : {}),
33
35
  ...(options.onOwnerLost ? { onOwnerLost: options.onOwnerLost } : {}),
@@ -42,6 +44,8 @@ export async function openPostgresStore(options) {
42
44
  const found = await connection.withClient((client) => (role === "server" ? migrate(client, schema, now(), migrations) : versionOf(client, schema)));
43
45
  if (found !== known)
44
46
  throw new SchemaVersionUnknown(placeOf(schema), found, known);
47
+ if (role === "server")
48
+ await backfillNativeCommandOwners(connection);
45
49
  if (role === "runner" && options.warn) {
46
50
  const gap = now() - (await connection.clock());
47
51
  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,
@@ -15,8 +15,14 @@ export const DEFAULT_TRANSACTION_DEADLINE_MS = 10_000;
15
15
  /** The interactive transactions open in this process, on any of its connections: each with where it was opened and when
16
16
  * it began. A transaction's StoreDeadline, and a begin's StoreBusy, name them in their stack (never their message, which
17
17
  * an answer may carry), so a log says who held the store: the deadline's own transaction, or another of this process's
18
- * (an in-process runner's) holding the lock a begin waited on. */
18
+ * (an in-process runner's) holding the lock a begin waited on. `where`: its database (Connection.where), so a wait for
19
+ * the write lock knows a holder of this process on the same database (lockWait). */
19
20
  const OPEN = new Set();
21
+ /** The interactive transactions of this process whose begin is with its worker, not yet answered: each on its database
22
+ * (`where`). Such a begin may hold the write lock already, its answer waiting for the event loop, and after a hold-up
23
+ * the answers of two workers come back in no set order, so a wait that ran out then can be read before that begin's
24
+ * answer adds it to OPEN (lockWait). */
25
+ const BEGINNING = new Set();
20
26
  /** `opened`'s frames: where a transaction was asked for, without the Error line itself. */
21
27
  const framesOf = (opened) => (opened.stack ?? "").split("\n").slice(1).join("\n");
22
28
  /** `error` with its stack naming who held the store: `opened` (its own transaction's opener, when it has one), and every
@@ -198,8 +204,52 @@ export class Connection {
198
204
  this.#tail = run.catch(() => undefined);
199
205
  return run;
200
206
  }
201
- #stmt(sql, params, mode) {
202
- return this.#send({ op: "stmt", statement: { sql, params: cleaned(params) }, mode });
207
+ #stmt(sql, params, mode, busyMs) {
208
+ return this.#send({ op: "stmt", statement: { sql, params: cleaned(params) }, mode, ...(busyMs !== undefined ? { busyMs } : {}) });
209
+ }
210
+ /** `send`, a request that takes the database's write lock (a transaction's begin, a write, a statement outside a
211
+ * transaction), given how long it may wait for it (`busyMs`; undefined, the connection's own busy wait). A wait that
212
+ * ran out on a transaction of this process on the same database (another of its connections: the server's and its
213
+ * in-process runner's) while this process was held up (its event loop held by other work, the machine holding it) is
214
+ * sent again, with the held-up time given back: that holder's statements wait for the same event loop, and its deadline
215
+ * counts only the time this process could run (store/deadline.ts runnableDeadline), so the wait for it counts the same
216
+ * way, and the holder, once it runs again, commits or meets its deadline. A wait on another process's write, or one
217
+ * this process could run through, ends StoreBusy as ever.
218
+ * Every wait is measured, and the holder looked for when it runs out, never when it is sent: a holder's begin posted
219
+ * in the same turn may take the lock before its answer makes it known. `self`: this request's own begin (BEGINNING),
220
+ * never its own holder. */
221
+ async #lockWait(send, self) {
222
+ let left = this.#busyTimeoutMs;
223
+ for (;;) {
224
+ const clock = runnableDeadline(left, () => { });
225
+ const sent = performance.now();
226
+ try {
227
+ return await send(left < this.#busyTimeoutMs ? left : undefined);
228
+ }
229
+ catch (error) {
230
+ if (!(error instanceof StoreBusy))
231
+ throw error;
232
+ const held = clock.held();
233
+ if (held === 0 || !this.#heldHere(self))
234
+ throw error;
235
+ left -= performance.now() - sent - held;
236
+ if (left <= 0)
237
+ throw error;
238
+ }
239
+ finally {
240
+ clock.clear();
241
+ }
242
+ }
243
+ }
244
+ /** A transaction of this process on this database is open, or its begin is with its worker (other than `self`). */
245
+ #heldHere(self) {
246
+ for (const open of OPEN)
247
+ if (open.where === this.#where)
248
+ return true;
249
+ for (const beginning of BEGINNING)
250
+ if (beginning !== self && beginning.where === this.#where)
251
+ return true;
252
+ return false;
203
253
  }
204
254
  /** The executor that sends straight to the worker: a transaction's handle, valid while `live()` says so. */
205
255
  #executor(live) {
@@ -221,10 +271,10 @@ export class Connection {
221
271
  return this.#queued(async () => void (await this.#send({ op: "exec", sql })));
222
272
  }
223
273
  run(sql, ...params) {
224
- return this.#queued(async () => void (await this.#stmt(sql, params, "run")));
274
+ return this.#queued(async () => void (await this.#lockWait((busyMs) => this.#stmt(sql, params, "run", busyMs))));
225
275
  }
226
276
  runCounted(sql, ...params) {
227
- return this.#queued(async () => (await this.#stmt(sql, params, "count")));
277
+ return this.#queued(async () => (await this.#lockWait((busyMs) => this.#stmt(sql, params, "count", busyMs))));
228
278
  }
229
279
  get(sql, ...params) {
230
280
  return this.#queued(async () => ((await this.#stmt(sql, params, "get")) ?? undefined));
@@ -235,7 +285,10 @@ export class Connection {
235
285
  /** One write transaction of fixed statements: in order; an expectation miss or an error rolls all of them back. `full`: a
236
286
  * FULL commit, durable against a lost box together with every commit before it. */
237
287
  write(statements, { full = false } = {}) {
238
- return this.#queued(async () => (await this.#send({ op: "write", statements: statements.map(cleanStatement), full })));
288
+ return this.#queued(async () => {
289
+ const cleanedStatements = statements.map(cleanStatement);
290
+ return (await this.#lockWait((busyMs) => this.#send({ op: "write", statements: cleanedStatements, full, ...(busyMs !== undefined ? { busyMs } : {}) })));
291
+ });
239
292
  }
240
293
  /** A write transaction (BEGIN IMMEDIATE) the callback steps through its handle, deciding each statement from the ones
241
294
  * before it. It commits when the callback resolves; when the callback rejects it rolls back and rejects with the same
@@ -259,15 +312,26 @@ export class Connection {
259
312
  // Its wait for the database's lock (another process's write) bounded by what the deadline leaves: a lock still held
260
313
  // when that runs out is the deadline's end, not the connection's own busy wait.
261
314
  const busyMs = until !== undefined ? Math.max(0, until - Date.now()) : undefined;
315
+ // Until its begin is answered, it may hold the lock unknown to OPEN: another wait that runs out meanwhile finds it.
316
+ const beginning = { where: this.#where };
317
+ BEGINNING.add(beginning);
262
318
  try {
263
- await this.#send({ op: "begin", full, ...(read ? { read } : {}), ...(busyMs !== undefined ? { busyMs } : {}) });
319
+ // Counted from its call, its wait is the deadline's, the wall clock's; else its wait for a holder of this process
320
+ // gives back the time this process was held up (lockWait).
321
+ if (busyMs !== undefined)
322
+ await this.#send({ op: "begin", full, ...(read ? { read } : {}), busyMs });
323
+ else
324
+ await this.#lockWait((wait) => this.#send({ op: "begin", full, ...(read ? { read } : {}), ...(wait !== undefined ? { busyMs: wait } : {}) }), beginning);
264
325
  }
265
326
  catch (error) {
266
327
  if (error instanceof StoreBusy && busyMs !== undefined && busyMs < this.#busyTimeoutMs)
267
328
  throw holderNamed(new StoreDeadline(deadlineMs), { opened });
268
329
  throw error instanceof StoreBusy ? holderNamed(error, { opened }) : error;
269
330
  }
270
- const open = { opened, began: Date.now() };
331
+ finally {
332
+ BEGINNING.delete(beginning);
333
+ }
334
+ const open = { opened, began: Date.now(), where: this.#where };
271
335
  OPEN.add(open);
272
336
  try {
273
337
  let live = true;
@@ -1,4 +1,5 @@
1
1
  import { type RunLaunchInput, type RunLaunchRow } from "../store.js";
2
+ import type { Dialect } from "../dialect.js";
2
3
  import type { SqliteExecutor } from "./connection.js";
3
4
  /** Writes a run's launch row inside `tx` (the same transaction as the queued run it belongs to): the run path and the
4
5
  * trigger path both call it, so the row lands with its run or not at all. */
@@ -6,3 +7,13 @@ export declare function writeLaunch(tx: Pick<SqliteExecutor, "run">, runId: stri
6
7
  /** The run's launch row, read by the runner at its claim (and the server for views). StoreLaunchMissing when the run has
7
8
  * none, never a default. */
8
9
  export declare function readLaunch(executor: Pick<SqliteExecutor, "get">, runId: string): Promise<RunLaunchRow>;
10
+ /** The learning start of every run of agent `agentId` that `where` (a condition on runs' columns) keeps, in one read: only
11
+ * the body's `learning` member (the notes a run was given, its seed, its # Learned section), never the rest of the body
12
+ * and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
13
+ * is the member's JSON text, null when the run's body names none. */
14
+ export declare function readLearningStarts(executor: Pick<SqliteExecutor, "all"> & {
15
+ readonly dialect: Dialect;
16
+ }, agentId: string, where: string): Promise<{
17
+ runId: string;
18
+ learning: unknown;
19
+ }[]>;
@@ -18,3 +18,11 @@ export async function readLaunch(executor, runId) {
18
18
  throw new StoreLaunchMissing(runId);
19
19
  return runLaunchOf(row);
20
20
  }
21
+ /** The learning start of every run of agent `agentId` that `where` (a condition on runs' columns) keeps, in one read: only
22
+ * the body's `learning` member (the notes a run was given, its seed, its # Learned section), never the rest of the body
23
+ * and never the sealed bytes, so an agent with thousands of runs reads kilobytes a run, not each run's input. `learning`
24
+ * is the member's JSON text, null when the run's body names none. */
25
+ export async function readLearningStarts(executor, agentId, where) {
26
+ const rows = await executor.all(`SELECT run_id, ${executor.dialect.jsonText("body", ["learning"])} AS learning FROM run_launch WHERE run_id IN (SELECT id FROM runs WHERE agent_id = ? AND ${where})`, agentId);
27
+ return rows.map((row) => ({ runId: row.run_id, learning: row.learning === null ? undefined : JSON.parse(row.learning) }));
28
+ }
@@ -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)