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

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 (381) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +266 -201
  3. package/dist/adapters.d.ts +0 -4
  4. package/dist/adapters.js +11 -15
  5. package/dist/agent-rows.d.ts +98 -0
  6. package/dist/agent-rows.js +1 -0
  7. package/dist/agents-store.d.ts +6 -2
  8. package/dist/agents-store.js +60 -25
  9. package/dist/agents.d.ts +9 -125
  10. package/dist/agents.js +15 -305
  11. package/dist/answer-json.d.ts +23 -0
  12. package/dist/answer-json.js +58 -0
  13. package/dist/api-only.d.ts +1 -1
  14. package/dist/api-only.js +2 -2
  15. package/dist/bash-read-only.d.ts +22 -0
  16. package/dist/bash-read-only.js +701 -0
  17. package/dist/box-settings.d.ts +3 -23
  18. package/dist/box-settings.js +7 -51
  19. package/dist/boxes.d.ts +17 -0
  20. package/dist/boxes.js +27 -20
  21. package/dist/browser-commands.d.ts +5 -2
  22. package/dist/browser-commands.js +4 -4
  23. package/dist/browser-computer.d.ts +5 -0
  24. package/dist/browser-computer.js +21 -0
  25. package/dist/browser-cost.d.ts +9 -6
  26. package/dist/browser-cost.js +92 -50
  27. package/dist/browser-live.d.ts +7 -20
  28. package/dist/browser-live.js +15 -93
  29. package/dist/browser-person.d.ts +18 -51
  30. package/dist/browser-person.js +94 -277
  31. package/dist/cap.d.ts +8 -5
  32. package/dist/cap.js +12 -5
  33. package/dist/cli.js +39 -13
  34. package/dist/closed-pipes.d.ts +2 -0
  35. package/dist/closed-pipes.js +13 -0
  36. package/dist/computer-commands.d.ts +2 -0
  37. package/dist/computer-commands.js +2 -0
  38. package/dist/computer-keys.js +5 -2
  39. package/dist/computer-setting.d.ts +20 -4
  40. package/dist/computer-setting.js +25 -5
  41. package/dist/computers.d.ts +30 -2
  42. package/dist/computers.js +70 -11
  43. package/dist/confine.d.ts +120 -0
  44. package/dist/confine.js +436 -0
  45. package/dist/console/assets/index-RPHGlXmM.js +540 -0
  46. package/dist/console/assets/index-opTN5Naq.css +1 -0
  47. package/dist/console/index.html +2 -2
  48. package/dist/decision-rows.d.ts +1 -1
  49. package/dist/decision-rows.js +1 -1
  50. package/dist/docker-daemon.d.ts +31 -0
  51. package/dist/docker-daemon.js +56 -0
  52. package/dist/effort-guidance.js +4 -3
  53. package/dist/environment.d.ts +0 -3
  54. package/dist/environment.js +3 -5
  55. package/dist/errors.d.ts +0 -2
  56. package/dist/errors.js +6 -9
  57. package/dist/filed-answer.d.ts +32 -0
  58. package/dist/filed-answer.js +160 -0
  59. package/dist/files.d.ts +1 -3
  60. package/dist/files.js +2 -4
  61. package/dist/github-connection.d.ts +1 -1
  62. package/dist/graph-view.d.ts +3 -5
  63. package/dist/graph-view.js +4 -14
  64. package/dist/handed-values.d.ts +9 -0
  65. package/dist/handed-values.js +26 -0
  66. package/dist/harness-install.d.ts +1 -7
  67. package/dist/harness-install.js +1 -18
  68. package/dist/harness-opencode/adapter.d.ts +7 -0
  69. package/dist/harness-opencode/adapter.js +23 -6
  70. package/dist/harness-opencode/index.d.ts +1 -1
  71. package/dist/harness-opencode/index.js +1 -1
  72. package/dist/harness-opencode/verify.d.ts +17 -0
  73. package/dist/harness-opencode/verify.js +30 -10
  74. package/dist/harness-table.js +6 -1
  75. package/dist/heard.js +1 -1
  76. package/dist/held-fd.d.ts +5 -0
  77. package/dist/held-fd.js +14 -0
  78. package/dist/host-calls.d.ts +20 -0
  79. package/dist/host-calls.js +12 -0
  80. package/dist/host-tools.d.ts +4 -21
  81. package/dist/host-tools.js +4 -61
  82. package/dist/host.d.ts +2 -4
  83. package/dist/host.js +2 -7
  84. package/dist/import-summary.d.ts +1 -5
  85. package/dist/import-summary.js +0 -21
  86. package/dist/import.d.ts +6 -6
  87. package/dist/import.js +14 -15
  88. package/dist/key-refusal.d.ts +5 -1
  89. package/dist/key-refusal.js +19 -4
  90. package/dist/learn/check.d.ts +6 -2
  91. package/dist/learn/check.js +83 -29
  92. package/dist/learn/folder.d.ts +5 -1
  93. package/dist/learn/folder.js +10 -3
  94. package/dist/learn/grade.d.ts +14 -0
  95. package/dist/learn/grade.js +68 -12
  96. package/dist/learn/index.d.ts +4 -4
  97. package/dist/learn/index.js +4 -4
  98. package/dist/learn/reflect.d.ts +31 -2
  99. package/dist/learn/reflect.js +79 -4
  100. package/dist/learn/relevance.d.ts +24 -0
  101. package/dist/learn/relevance.js +91 -0
  102. package/dist/learn/secrets.d.ts +7 -1
  103. package/dist/learn/secrets.js +86 -19
  104. package/dist/learn/skills.d.ts +112 -14
  105. package/dist/learn/skills.js +556 -52
  106. package/dist/learned-workflow.d.ts +32 -1
  107. package/dist/learned-workflow.js +100 -9
  108. package/dist/learning-routes.d.ts +8 -4
  109. package/dist/learning-routes.js +23 -9
  110. package/dist/learning-run.d.ts +9 -26
  111. package/dist/learning-run.js +22 -32
  112. package/dist/learning-words.d.ts +12 -5
  113. package/dist/learning-words.js +18 -9
  114. package/dist/learning.d.ts +93 -77
  115. package/dist/learning.js +176 -304
  116. package/dist/live/stream.js +1 -1
  117. package/dist/live/translate.js +12 -2
  118. package/dist/local-models.d.ts +11 -5
  119. package/dist/local-models.js +13 -8
  120. package/dist/mcp-gateway.d.ts +11 -49
  121. package/dist/mcp-gateway.js +44 -135
  122. package/dist/mcp-oauth.d.ts +10 -14
  123. package/dist/mcp-oauth.js +14 -32
  124. package/dist/mcp-probe.d.ts +0 -7
  125. package/dist/mcp-probe.js +4 -10
  126. package/dist/mcp-servers-store.d.ts +6 -6
  127. package/dist/mcp-servers-store.js +12 -14
  128. package/dist/mcp-store.js +3 -4
  129. package/dist/mcp.js +4 -3
  130. package/dist/model.d.ts +6 -7
  131. package/dist/model.js +43 -27
  132. package/dist/monid.d.ts +0 -2
  133. package/dist/monid.js +3 -6
  134. package/dist/openapi.d.ts +8 -1
  135. package/dist/openapi.js +121 -47
  136. package/dist/page.d.ts +1 -3
  137. package/dist/page.js +6 -18
  138. package/dist/paid-calls.d.ts +21 -27
  139. package/dist/paid-calls.js +25 -60
  140. package/dist/propose.js +83 -39
  141. package/dist/push-handler.d.ts +1 -1
  142. package/dist/reflect-range.d.ts +25 -0
  143. package/dist/reflect-range.js +30 -0
  144. package/dist/refusal-words.d.ts +5 -1
  145. package/dist/refusal-words.js +5 -1
  146. package/dist/rows.d.ts +1 -1
  147. package/dist/run-cut.d.ts +0 -6
  148. package/dist/run-cut.js +0 -6
  149. package/dist/run-db.d.ts +2 -11
  150. package/dist/run-db.js +2 -37
  151. package/dist/run-launch.d.ts +19 -2
  152. package/dist/run-launch.js +13 -5
  153. package/dist/run-learning-served.d.ts +10 -4
  154. package/dist/run-learning-served.js +23 -13
  155. package/dist/run-reads-over-store.d.ts +1 -1
  156. package/dist/run-reads-over-store.js +15 -6
  157. package/dist/run-secrets.d.ts +1 -1
  158. package/dist/run-timeline-served.d.ts +5 -1
  159. package/dist/run-timeline-served.js +15 -4
  160. package/dist/run-view.d.ts +7 -8
  161. package/dist/run-view.js +26 -7
  162. package/dist/runnable.d.ts +18 -10
  163. package/dist/runnable.js +21 -10
  164. package/dist/runner/adapter-loop.d.ts +6 -1
  165. package/dist/runner/adapter-loop.js +423 -53
  166. package/dist/runner/adapter-run-spec.d.ts +21 -8
  167. package/dist/runner/adapter-run-spec.js +90 -32
  168. package/dist/runner/adapters/index.js +11 -1
  169. package/dist/runner/adapters/pi.d.ts +12 -2
  170. package/dist/runner/adapters/pi.js +16 -5
  171. package/dist/runner/beside.d.ts +30 -3
  172. package/dist/runner/beside.js +36 -5
  173. package/dist/runner/claim-secrets.d.ts +10 -1
  174. package/dist/runner/claim-secrets.js +48 -14
  175. package/dist/runner/cli-run-spec.d.ts +2 -0
  176. package/dist/runner/cli-run-spec.js +45 -16
  177. package/dist/runner/commands.js +1 -1
  178. package/dist/runner/computer-journal.d.ts +15 -2
  179. package/dist/runner/computer-journal.js +41 -5
  180. package/dist/runner/conformance/harness.js +118 -8
  181. package/dist/runner/conformance/subject.d.ts +4 -1
  182. package/dist/runner/dispatch.d.ts +8 -1
  183. package/dist/runner/dispatch.js +81 -7
  184. package/dist/runner/end-of-run.d.ts +8 -2
  185. package/dist/runner/end-of-run.js +10 -4
  186. package/dist/runner/github-app.js +1 -1
  187. package/dist/runner/harness-loops.d.ts +9 -1
  188. package/dist/runner/harness-loops.js +15 -2
  189. package/dist/runner/journal-kinds.d.ts +24 -6
  190. package/dist/runner/journal-kinds.js +20 -5
  191. package/dist/runner/journal-reader.d.ts +1 -1
  192. package/dist/runner/journal-reader.js +2 -2
  193. package/dist/runner/learning-ask.d.ts +4 -0
  194. package/dist/runner/learning-ask.js +15 -1
  195. package/dist/runner/learning-end.d.ts +18 -3
  196. package/dist/runner/learning-end.js +113 -11
  197. package/dist/runner/learning-loop.d.ts +5 -0
  198. package/dist/runner/learning-loop.js +26 -6
  199. package/dist/runner/main.d.ts +56 -9
  200. package/dist/runner/main.js +127 -18
  201. package/dist/runner/mcp-claim.js +1 -2
  202. package/dist/runner/mcp-run.d.ts +2 -0
  203. package/dist/runner/mcp-run.js +15 -5
  204. package/dist/runner/memory-claim.d.ts +9 -0
  205. package/dist/runner/memory-claim.js +25 -0
  206. package/dist/runner/metrics.d.ts +33 -1
  207. package/dist/runner/metrics.js +85 -1
  208. package/dist/runner/model-route.d.ts +13 -0
  209. package/dist/runner/model-route.js +133 -9
  210. package/dist/runner/reflect-hook.d.ts +12 -1
  211. package/dist/runner/reflect-hook.js +33 -3
  212. package/dist/runner/runner.d.ts +20 -0
  213. package/dist/runner/runner.js +56 -10
  214. package/dist/runner/store-port.d.ts +1 -1
  215. package/dist/runner/store-secrets.d.ts +3 -3
  216. package/dist/runner/store-secrets.js +8 -12
  217. package/dist/runner/text-tools.d.ts +44 -0
  218. package/dist/runner/text-tools.js +237 -0
  219. package/dist/runner/workflow-loop.d.ts +6 -0
  220. package/dist/runner/workflow-loop.js +6 -4
  221. package/dist/runner/workflow-spec.d.ts +18 -0
  222. package/dist/runner/workflow-spec.js +63 -17
  223. package/dist/runs-over-store.d.ts +7 -2
  224. package/dist/runs-over-store.js +60 -14
  225. package/dist/seal-key.js +5 -43
  226. package/dist/sealed-settings-store.d.ts +19 -4
  227. package/dist/sealed-settings-store.js +9 -9
  228. package/dist/sealing.d.ts +4 -0
  229. package/dist/sealing.js +20 -0
  230. package/dist/secret-cut.d.ts +1 -1
  231. package/dist/secret-cut.js +1 -1
  232. package/dist/secret-name.d.ts +9 -0
  233. package/dist/secret-name.js +15 -0
  234. package/dist/secret-writes.d.ts +0 -1
  235. package/dist/secret-writes.js +0 -1
  236. package/dist/server-fs.d.ts +4 -0
  237. package/dist/server-fs.js +8 -2
  238. package/dist/server-lock.d.ts +0 -24
  239. package/dist/server-lock.js +1 -80
  240. package/dist/server-secrets-store.d.ts +4 -4
  241. package/dist/server-secrets-store.js +9 -31
  242. package/dist/server-secrets.d.ts +4 -9
  243. package/dist/server-secrets.js +12 -36
  244. package/dist/server.d.ts +16 -38
  245. package/dist/server.js +145 -106
  246. package/dist/sign-ins-store.d.ts +34 -36
  247. package/dist/sign-ins-store.js +27 -38
  248. package/dist/sign-ins.d.ts +2 -119
  249. package/dist/sign-ins.js +5 -311
  250. package/dist/standard-webhooks.d.ts +1 -1
  251. package/dist/standard-webhooks.js +1 -1
  252. package/dist/stats.d.ts +3 -2
  253. package/dist/stats.js +1 -1
  254. package/dist/store/agent-body.d.ts +8 -2
  255. package/dist/store/agent-body.js +16 -4
  256. package/dist/store/index.d.ts +2 -2
  257. package/dist/store/index.js +2 -2
  258. package/dist/store/open.d.ts +6 -3
  259. package/dist/store/open.js +2 -2
  260. package/dist/store/postgres/connection.d.ts +18 -2
  261. package/dist/store/postgres/connection.js +156 -32
  262. package/dist/store/postgres/migrate.d.ts +4 -0
  263. package/dist/store/postgres/migrate.js +9 -2
  264. package/dist/store/postgres/migrations/0003_commands_one_answer.check.sql +19 -0
  265. package/dist/store/postgres/migrations/0003_commands_one_answer.sql +13 -0
  266. package/dist/store/postgres/store.d.ts +9 -2
  267. package/dist/store/postgres/store.js +9 -0
  268. package/dist/store/schema.js +1 -1
  269. package/dist/store/seal.js +2 -2
  270. package/dist/store/sqlite/connection.js +49 -5
  271. package/dist/store/sqlite/run-patch.d.ts +3 -0
  272. package/dist/store/sqlite/run-patch.js +3 -0
  273. package/dist/store/sqlite/store.js +41 -12
  274. package/dist/store/store.d.ts +35 -6
  275. package/dist/store/store.js +12 -2
  276. package/dist/store-reads/cap.d.ts +1 -1
  277. package/dist/store-reads/cap.js +22 -4
  278. package/dist/store-reads/journal.d.ts +9 -6
  279. package/dist/store-reads/journal.js +93 -17
  280. package/dist/store-reads/learning.d.ts +26 -8
  281. package/dist/store-reads/learning.js +12 -4
  282. package/dist/store-reads/workflow.d.ts +1 -1
  283. package/dist/store-reads/workflow.js +1 -1
  284. package/dist/store-view.d.ts +5 -1
  285. package/dist/store-view.js +53 -18
  286. package/dist/template-eval.d.ts +60 -4
  287. package/dist/template-eval.js +120 -54
  288. package/dist/templates.d.ts +24 -10
  289. package/dist/templates.js +69 -38
  290. package/dist/timeline/group.d.ts +33 -0
  291. package/dist/timeline/group.js +77 -0
  292. package/dist/timeline/index.d.ts +7 -0
  293. package/dist/timeline/index.js +7 -0
  294. package/dist/timeline/labels.d.ts +79 -0
  295. package/dist/timeline/labels.js +150 -0
  296. package/dist/timeline/origin.d.ts +56 -0
  297. package/dist/timeline/origin.js +92 -0
  298. package/dist/timeline/render-text.d.ts +11 -0
  299. package/dist/timeline/render-text.js +62 -0
  300. package/dist/timeline/timeline.d.ts +274 -0
  301. package/dist/timeline/timeline.js +1308 -0
  302. package/dist/timeline/util.d.ts +17 -0
  303. package/dist/timeline/util.js +49 -0
  304. package/dist/tool-gate.d.ts +41 -216
  305. package/dist/tool-gate.js +79 -540
  306. package/dist/tool-keys-store.d.ts +11 -12
  307. package/dist/tool-keys-store.js +24 -31
  308. package/dist/tool-keys.d.ts +5 -101
  309. package/dist/tool-keys.js +8 -267
  310. package/dist/tool-plane.d.ts +14 -42
  311. package/dist/tool-plane.js +23 -81
  312. package/dist/tool-settings-store.d.ts +1 -2
  313. package/dist/tool-settings-store.js +5 -8
  314. package/dist/tools.d.ts +30 -18
  315. package/dist/tools.js +97 -107
  316. package/dist/trigger-adapter.d.ts +2 -2
  317. package/dist/trigger-targets.d.ts +13 -1
  318. package/dist/trigger-targets.js +31 -1
  319. package/dist/triggers.d.ts +2 -2
  320. package/dist/triggers.js +3 -3
  321. package/dist/turn-end.d.ts +1 -1
  322. package/dist/turn-end.js +1 -1
  323. package/dist/turns.d.ts +0 -6
  324. package/dist/turns.js +0 -19
  325. package/dist/uploads.js +1 -1
  326. package/dist/usage.d.ts +0 -2
  327. package/dist/usage.js +0 -2
  328. package/dist/validate.d.ts +2 -0
  329. package/dist/validate.js +23 -14
  330. package/dist/webhooks.d.ts +102 -76
  331. package/dist/webhooks.js +266 -233
  332. package/dist/workflow-run.d.ts +114 -0
  333. package/dist/workflow-run.js +144 -0
  334. package/dist/workspace/beneath.d.ts +19 -0
  335. package/dist/workspace/beneath.js +106 -0
  336. package/dist/workspace/computer-deps.d.ts +24 -6
  337. package/dist/workspace/computer-deps.js +108 -20
  338. package/dist/workspace/computer-for-claim.d.ts +12 -11
  339. package/dist/workspace/computer-for-claim.js +76 -15
  340. package/dist/workspace/computer-hold.d.ts +6 -1
  341. package/dist/workspace/computer-hold.js +6 -1
  342. package/dist/workspace/computer-janitor.d.ts +47 -0
  343. package/dist/workspace/computer-janitor.js +182 -0
  344. package/dist/workspace/grep-worker.d.ts +5 -0
  345. package/dist/workspace/grep-worker.js +9 -6
  346. package/dist/workspace/index.d.ts +3 -2
  347. package/dist/workspace/index.js +3 -3
  348. package/dist/workspace/local.d.ts +11 -2
  349. package/dist/workspace/local.js +161 -43
  350. package/dist/workspace/resolve-computer.d.ts +50 -10
  351. package/dist/workspace/resolve-computer.js +46 -11
  352. package/dist/workspace/run-tools.d.ts +13 -31
  353. package/dist/workspace/run-tools.js +10 -27
  354. package/dist/workspace-paths.d.ts +0 -17
  355. package/dist/workspace-paths.js +1 -41
  356. package/dist/workspace.d.ts +0 -14
  357. package/dist/workspace.js +3 -96
  358. package/package.json +13 -13
  359. package/templates/README.md +9 -3
  360. package/templates/market-monitor/agent.md +2 -2
  361. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  362. package/dist/bound-files.d.ts +0 -4
  363. package/dist/bound-files.js +0 -164
  364. package/dist/coding-tools.d.ts +0 -47
  365. package/dist/coding-tools.js +0 -189
  366. package/dist/computer-adb.d.ts +0 -12
  367. package/dist/computer-adb.js +0 -14
  368. package/dist/console/assets/index-Dn0ngwG9.js +0 -535
  369. package/dist/console/assets/index-DvW6Aled.css +0 -1
  370. package/dist/grade.d.ts +0 -63
  371. package/dist/grade.js +0 -150
  372. package/dist/mcp-servers.d.ts +0 -269
  373. package/dist/mcp-servers.js +0 -456
  374. package/dist/packs.d.ts +0 -71
  375. package/dist/packs.js +0 -180
  376. package/dist/sealed-settings.d.ts +0 -60
  377. package/dist/sealed-settings.js +0 -171
  378. package/dist/sessions.d.ts +0 -6
  379. package/dist/sessions.js +0 -109
  380. package/dist/workspace/computer-serves.d.ts +0 -12
  381. package/dist/workspace/computer-serves.js +0 -15
@@ -100,6 +100,71 @@ function int8(text) {
100
100
  return value;
101
101
  }
102
102
  const types = { getTypeParser: (oid, format) => (oid === 20 ? int8 : pg.types.getTypeParser(oid, format)) };
103
+ /** How long a server waits for the owner lock another server holds before it gives up (StoreOwned), in ms, at its open
104
+ * and to take its own back after its lock's connection is lost: a deploy's new server waits out the old one's drain
105
+ * (a runner's 35 s graceful stop, the server's own) instead of exiting, and a lost lock is never a 503 forever. */
106
+ export const OWNER_WAIT_MS = 120_000;
107
+ /** How often a waiting server asks for the owner lock again (ms). */
108
+ const OWNER_POLL_MS = 250;
109
+ /** How long after its lock's connection ends a server first asks for it back (ms): a server already waiting for the
110
+ * schema (a deploy's new one) takes it first, and this one then exits. */
111
+ const OWNER_RETAKE_DELAY_MS = 1_000;
112
+ /** The owner session's own keepalives on the database's end: a dead server's session, and its lock, end in about 60 s,
113
+ * later than this end finds the connection dead (Node's keepalive: 10 s, then 10 probes 1 s apart), so the database
114
+ * never lets the lock go while this server still believes it holds it. */
115
+ const OWNER_SESSION = "-c tcp_keepalives_idle=30 -c tcp_keepalives_interval=10 -c tcp_keepalives_count=3";
116
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
117
+ /** How long one ask for the owner lock may wait for the database's answer once connected (ms): a connection that stays
118
+ * open but never answers is destroyed past it, so a wait or a take-back always reaches its own end. */
119
+ const OWNER_ASK_MS = 5_000;
120
+ /** Destroys `client`'s socket and lets it go: for a connection that never answered, whose own end would wait on it. */
121
+ function destroyed(client) {
122
+ client.connection?.stream?.destroy();
123
+ return client.end().catch(() => undefined);
124
+ }
125
+ /** Ends backend `pid` (this server's own lost owner session) from a connection of its own, bounded as an ask is. */
126
+ async function endSession(url, pid, connectMs) {
127
+ const client = new pg.Client({ connectionString: url, types, application_name: "agentrun-store", connectionTimeoutMillis: connectMs });
128
+ client.on("error", () => undefined);
129
+ try {
130
+ await client.connect();
131
+ await answered(client.query("SELECT pg_terminate_backend($1)", [pid]), OWNER_ASK_MS, "the end of the lost owner session");
132
+ await client.end().catch(() => undefined);
133
+ }
134
+ catch {
135
+ await destroyed(client);
136
+ }
137
+ }
138
+ /** Asks for `schema`'s owner lock once, on a connection of its own: kept open, holding the lock, when taken. Bounded: its
139
+ * connect by `connectMs`, each of its statements by OWNER_ASK_MS (Unanswered past it, the connection destroyed). */
140
+ async function tryOwner(url, schema, connectMs, where) {
141
+ const client = new pg.Client({ connectionString: url, types, options: OWNER_SESSION, application_name: `agentrun-store-owner:${schema}`, connectionTimeoutMillis: connectMs, keepAlive: true, keepAliveInitialDelayMillis: KEEPALIVE_IDLE_S * 1_000 });
142
+ // A lost owner connection lets the lock go: its error is never left unhandled (the store watches its end).
143
+ client.on("error", () => undefined);
144
+ try {
145
+ await client.connect();
146
+ }
147
+ catch (error) {
148
+ await client.end().catch(() => undefined);
149
+ throw connectTimedOut(error) ? connectDeadline(where, connectMs) : typed(error);
150
+ }
151
+ try {
152
+ const asked = (await answered(client.query("SELECT pg_try_advisory_lock(hashtext($1), hashtext('owner')) AS held, pg_backend_pid() AS pid, (SELECT backend_start::text FROM pg_stat_activity WHERE pid = pg_backend_pid()) AS started", [schema]), OWNER_ASK_MS, "the owner lock's ask")).rows[0];
153
+ if (asked.held === true)
154
+ return { taken: { client, pid: Number(asked.pid), startedAt: String(asked.started) } };
155
+ // Who holds it: the advisory lock (hashtext(schema), hashtext('owner')) in this database (advisory locks are per
156
+ // database; pg_locks shows the whole cluster's), its two keys as pg_locks shows them.
157
+ const holder = (await answered(client.query(`SELECT l.pid, a.backend_start::text AS started FROM pg_locks l LEFT JOIN pg_stat_activity a ON a.pid = l.pid
158
+ WHERE l.locktype = 'advisory' AND l.granted AND l.objsubid = 2 AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database())
159
+ AND l.classid::bigint = (hashtext($1)::bigint & 4294967295) AND l.objid::bigint = (hashtext('owner')::bigint & 4294967295)`, [schema]), OWNER_ASK_MS, "the owner lock's holder")).rows[0];
160
+ await client.end().catch(() => undefined);
161
+ return { heldBy: holder ? { pid: Number(holder.pid), startedAt: holder.started ?? null } : undefined };
162
+ }
163
+ catch (error) {
164
+ await destroyed(client);
165
+ throw error instanceof Unanswered ? error : typed(error);
166
+ }
167
+ }
103
168
  /** `?` parameters numbered $1, $2 … (outside quoted text and identifiers), kept per statement text. */
104
169
  const numbered = new Map();
105
170
  export function numberParams(sql) {
@@ -192,12 +257,16 @@ export class PgConnection {
192
257
  #pool;
193
258
  /** One connection kept for renewing claims (TransactionOptions.lease). */
194
259
  #leasePool;
260
+ /** The owner lock's session (a server's), replaced when it is taken back after its connection was lost. */
195
261
  #owner;
262
+ /** What taking the owner lock back needs. */
263
+ #ownerConfig;
196
264
  #busyTimeoutMs;
197
265
  /** The bound on getting a connection (PgConnectionOptions.connectTimeoutMs). */
198
266
  #connectMs;
199
267
  #closed = false;
200
- /** Set once the owner lock's connection ended or failed: every call is refused with it from then. */
268
+ /** Set while the owner lock is not held (its connection ended or failed, and it is being taken back), and for good once
269
+ * another server has the schema: every call is refused with it meanwhile. */
201
270
  #ownerLost;
202
271
  /** Calls in flight: close waits for them. */
203
272
  #inFlight = new Set();
@@ -216,27 +285,83 @@ export class PgConnection {
216
285
  }
217
286
  return columns;
218
287
  };
219
- constructor(pool, owner, schema, busyTimeoutMs, where, testClock, connectMs, leasePool) {
288
+ constructor(pool, owner, schema, busyTimeoutMs, where, testClock, connectMs, leasePool, ownerConfig) {
220
289
  this.#connectMs = connectMs;
221
290
  this.#pool = pool;
222
291
  this.#leasePool = leasePool;
223
292
  this.#owner = owner;
293
+ this.#ownerConfig = ownerConfig;
224
294
  this.schema = schema;
225
295
  this.where = where;
226
296
  this.#busyTimeoutMs = busyTimeoutMs;
227
297
  this.dialect = postgresDialect(schema, { testClock });
228
- // The owner lock lives on its own connection: when that connection ends or fails (the database went away, or killed
229
- // it), the lock is gone and another server may take the schema. From then this store refuses every call (StoreOwned),
230
- // never writing beside the server that holds the schema now.
298
+ if (owner)
299
+ this.#watch(owner);
300
+ }
301
+ /** The owner lock lives on its own connection: when that connection ends or fails (the database restarted, a failover,
302
+ * an operator killed it), the lock may be gone and another server may take the schema. From then this store refuses
303
+ * every call (StoreOwned), never writing beside a server that may hold the schema now, and takes the lock back
304
+ * (#retake). */
305
+ #watch(session) {
231
306
  const lost = () => {
232
- if (!this.#closed)
233
- this.#ownerLost ??= new StoreOwned(`the owner lock on the Postgres schema ${schema} was lost (its connection ended): this server no longer holds the store`);
307
+ if (this.#closed || this.#owner !== session || this.#ownerLost)
308
+ return;
309
+ this.#ownerLost = new StoreOwned(`the owner lock on the Postgres schema ${this.schema} was lost (its connection ended): this server is taking it back, and refuses every call until it holds it again`);
310
+ void this.#retake(session);
234
311
  };
235
- owner?.on("error", lost);
236
- owner?.on("end", lost);
312
+ session.client.on("error", lost);
313
+ session.client.on("end", lost);
314
+ }
315
+ /** Takes the owner lock back on a fresh connection, after OWNER_RETAKE_DELAY_MS (a server waiting for the schema takes
316
+ * it first). Held by this server's own lost session (the database not yet told its client is gone: a partition), that
317
+ * session is ended and the lock taken. Held by another server, or not taken within ownerWaitMs, it is lost for good:
318
+ * every call is refused from then, and onOwnerLost is told, so the process exits and its platform restarts it. */
319
+ async #retake(old) {
320
+ const config = this.#ownerConfig;
321
+ const until = Date.now() + OWNER_RETAKE_DELAY_MS + config.waitMs;
322
+ await sleep(OWNER_RETAKE_DELAY_MS);
323
+ while (!this.#closed) {
324
+ const asked = await tryOwner(config.url, this.schema, this.#connectMs, this.where).catch(() => undefined);
325
+ if (asked && "taken" in asked) {
326
+ if (this.#closed)
327
+ return void (await asked.taken.client.end().catch(() => undefined));
328
+ // While the lock was not held, a newer server may have taken the schema, migrated it and let it go: this build
329
+ // serves only the schema it opened, so a schema it does not know gives the lock up for good.
330
+ const unknown = config.check ? await answered(config.check(asked.taken.client), OWNER_ASK_MS, "the schema's check").catch((error) => `its schema could not be read (${error.message})`) : undefined;
331
+ if (unknown !== undefined) {
332
+ await asked.taken.client.end().catch(() => undefined);
333
+ return this.#lostForGood(new StoreOwned(`the owner lock on the Postgres schema ${this.schema} was taken back, but ${unknown}: this server no longer serves the store`));
334
+ }
335
+ // Closed while the schema was checked: close() ended only the old session, so this one lets the lock go here.
336
+ if (this.#closed)
337
+ return void (await asked.taken.client.end().catch(() => undefined));
338
+ this.#owner = asked.taken;
339
+ this.#watch(asked.taken);
340
+ this.#ownerLost = undefined;
341
+ return;
342
+ }
343
+ const holder = asked?.heldBy;
344
+ if (holder && holder.pid === old.pid && holder.startedAt === old.startedAt) {
345
+ // This server's own session, its client gone but its backend not: ended, so its lock comes back.
346
+ await endSession(config.url, old.pid, this.#connectMs);
347
+ }
348
+ else if (holder) {
349
+ return this.#lostForGood(new StoreOwned(`another server took the store in the Postgres schema ${this.schema} after this server's owner lock was lost: this server no longer holds it`));
350
+ }
351
+ if (Date.now() >= until) {
352
+ return this.#lostForGood(new StoreOwned(`the owner lock on the Postgres schema ${this.schema} was lost and could not be taken back within ${Math.round(config.waitMs / 1000)} s: this server no longer holds the store`));
353
+ }
354
+ await sleep(OWNER_POLL_MS);
355
+ }
356
+ }
357
+ #lostForGood(error) {
358
+ if (this.#closed)
359
+ return;
360
+ this.#ownerLost = error;
361
+ this.#ownerConfig?.onLost?.(error);
237
362
  }
238
363
  /** The pool on `url` in `schema`, and (owner) the owner lock: StoreOwned when another server holds the schema. */
239
- static async open({ url, schema, owner = false, busyTimeoutMs = 10_000, poolSize = 10, testClock = false, connectTimeoutMs = STORE_CONNECT_TIMEOUT_MS }) {
364
+ 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 }) {
240
365
  if (!SCHEMA_NAME.test(schema))
241
366
  throw new TypeError(`the store's schema is a lower-case name of letters, digits and underscores, not ${JSON.stringify(schema)}`);
242
367
  // The database's end of the keepalives (KEEPALIVE_IDLE_S): a vanished client's session, and its locks, ended in ~25 s.
@@ -249,27 +374,26 @@ export class PgConnection {
249
374
  const tcp = { keepAlive: true, keepAliveInitialDelayMillis: KEEPALIVE_IDLE_S * 1_000 };
250
375
  const config = { connectionString: url, options: session, types, max: poolSize, allowExitOnIdle: true, application_name: "agentrun-store", connectionTimeoutMillis: connectMs, ...tcp };
251
376
  let lock;
377
+ const waitMs = Math.max(0, Math.floor(ownerWaitMs));
252
378
  if (owner) {
253
- // This end's keepalives only: the database keeps the owner lock past a partition for its own default, so this server
254
- // finds its lock's connection dead (StoreOwned on every call) long before another server can take the schema.
255
- lock = new pg.Client({ connectionString: url, types, application_name: `agentrun-store-owner:${schema}`, connectionTimeoutMillis: connectMs, ...tcp });
256
- // A lost owner connection lets the lock go; the error is not left unhandled.
257
- lock.on("error", () => undefined);
258
- try {
259
- await lock.connect();
260
- }
261
- catch (error) {
262
- await lock.end().catch(() => undefined);
263
- throw connectTimedOut(error) ? connectDeadline(where, connectMs) : typed(error);
264
- }
265
- try {
266
- const held = await lock.query("SELECT pg_try_advisory_lock(hashtext($1), hashtext('owner')) AS held", [schema]);
267
- if (held.rows[0]?.held !== true)
268
- throw new StoreOwned(`another server holds the store in the Postgres schema ${schema}`);
269
- }
270
- catch (error) {
271
- await lock.end().catch(() => undefined);
272
- throw error instanceof StoreOwned ? error : typed(error);
379
+ // Another server's lock is waited for (a deploy's old server draining and stopping), asked again every
380
+ // OWNER_POLL_MS, up to waitMs; past it StoreOwned. Its keepalives: OWNER_SESSION.
381
+ const until = Date.now() + waitMs;
382
+ let told = false;
383
+ for (;;) {
384
+ const asked = await tryOwner(url, schema, connectMs, where);
385
+ if ("taken" in asked) {
386
+ lock = asked.taken;
387
+ break;
388
+ }
389
+ if (Date.now() >= until) {
390
+ throw new StoreOwned(`another server holds the store in the Postgres schema ${schema}${waitMs > 0 ? `, and still held it after ${Math.round(waitMs / 1000)} s` : ""}`);
391
+ }
392
+ if (!told) {
393
+ told = true;
394
+ onOwnerWait?.(`another server holds the store in the Postgres schema ${schema}: waiting up to ${Math.round(waitMs / 1000)} s for it to let go`);
395
+ }
396
+ await sleep(OWNER_POLL_MS);
273
397
  }
274
398
  }
275
399
  const pool = new pg.Pool(config);
@@ -287,7 +411,7 @@ export class PgConnection {
287
411
  each.on("error", () => undefined);
288
412
  each.on("connect", (fresh) => fresh.on("error", () => undefined));
289
413
  }
290
- return new PgConnection(pool, lock, schema, busyTimeoutMs, where, testClock, connectMs, leasePool);
414
+ return new PgConnection(pool, lock, schema, busyTimeoutMs, where, testClock, connectMs, leasePool, lock ? { url, waitMs, onLost: onOwnerLost, check: ownerCheck } : undefined);
291
415
  }
292
416
  /** `work`, counted in flight, refused after close. A connection it never got in time is StoreDeadline, naming the
293
417
  * database's place. */
@@ -527,6 +651,6 @@ export class PgConnection {
527
651
  await Promise.allSettled([...this.#inFlight]);
528
652
  await this.#pool.end().catch(() => undefined);
529
653
  await this.#leasePool.end().catch(() => undefined);
530
- await this.#owner?.end().catch(() => undefined);
654
+ await this.#owner?.client.end().catch(() => undefined);
531
655
  }
532
656
  }
@@ -4,6 +4,10 @@ export interface Migration {
4
4
  readonly name: string;
5
5
  readonly sql: string;
6
6
  readonly sha256: string;
7
+ /** The migration's check (NNNN_name.check.sql beside it), run just before it: a query whose rows are the reasons the
8
+ * schema cannot take the migration yet, each in a `refusal` column, in words that name what holds it back and what to do.
9
+ * Not part of the file's hash: it runs only before the migration applies. */
10
+ readonly check?: string;
7
11
  }
8
12
  /** The migrations shipped beside this module (dist/store/postgres/migrations), in version order, numbered 1, 2, 3 … with
9
13
  * no gap. */
@@ -4,7 +4,7 @@
4
4
  // that finds one changed refuses to start, naming it. A runner applies nothing; it reads the version and refuses one it does
5
5
  // not know (SchemaVersionUnknown), as on SQLite.
6
6
  import { createHash } from "node:crypto";
7
- import { readdirSync, readFileSync } from "node:fs";
7
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
8
8
  import { SchemaVersionUnknown } from "../store.js";
9
9
  import { SCHEMA_NAME } from "./connection.js";
10
10
  /** `schema` as SQL takes it here, unquoted: refused (TypeError) unless it is a store schema name (SCHEMA_NAME), before any
@@ -23,7 +23,9 @@ export function migrationsIn(dir = new URL("./migrations/", import.meta.url)) {
23
23
  .filter((match) => match !== null)
24
24
  .map((match) => {
25
25
  const sql = readFileSync(new URL(match[0], dir), "utf8");
26
- return { version: Number(match[1]), name: match[2], sql, sha256: createHash("sha256").update(sql).digest("hex") };
26
+ const checkFile = new URL(`${match[1]}_${match[2]}.check.sql`, dir);
27
+ const check = existsSync(checkFile) ? readFileSync(checkFile, "utf8") : undefined;
28
+ return { version: Number(match[1]), name: match[2], sql, sha256: createHash("sha256").update(sql).digest("hex"), ...(check === undefined ? {} : { check }) };
27
29
  })
28
30
  .sort((a, b) => a.version - b.version);
29
31
  found.forEach((migration, index) => {
@@ -110,6 +112,11 @@ export async function migrate(client, schema, at, migrations = migrationsIn()) {
110
112
  }
111
113
  }
112
114
  for (const migration of migrations.slice(top ?? 0)) {
115
+ if (migration.check !== undefined) {
116
+ const refusals = (await client.query(migration.check)).rows.map((row) => String(row.refusal));
117
+ if (refusals.length > 0)
118
+ throw new Error(`${placeOf(schema)} cannot take migration ${String(migration.version).padStart(4, "0")}_${migration.name}.sql, so nothing was applied: ${refusals.join("; ")}`);
119
+ }
113
120
  await client.query(migration.sql);
114
121
  await client.query("INSERT INTO schema_migrations (version, name, sha256, applied_at) VALUES ($1, $2, $3, $4)", [migration.version, migration.name, migration.sha256, at]);
115
122
  }
@@ -0,0 +1,19 @@
1
+ -- The check before 0003 (migrate.ts runs it first; each row refuses the migration in its words). 0003's unique index
2
+ -- takes one unrefused answer per approval of a run; a store an earlier build left after an approve and a deny raced can
3
+ -- hold two. Nothing is changed here: the words name the run, the call and its answers, and give the statement that keeps
4
+ -- the first (the one the run's runner took first) and refuses the rest, as SQLite's open does.
5
+
6
+ SELECT format(
7
+ 'run %s has %s answers to its tool call %s (commands %s), and only one may stand: keep the first and refuse the others with '
8
+ || 'UPDATE %I.commands SET refused = %L, taken_at = COALESCE(taken_at, (extract(epoch FROM now()) * 1000)::bigint) WHERE id IN (%s), '
9
+ || 'then start the server again',
10
+ run_id, count(*), body::json ->> 'approval',
11
+ string_agg(id || ' (' || kind || ')', ', ' ORDER BY id),
12
+ current_schema(), 'a second answer to one approval: the first one stands',
13
+ array_to_string((array_agg(id ORDER BY id))[2:], ', ')
14
+ ) AS refusal
15
+ FROM commands
16
+ WHERE kind IN ('approve', 'deny') AND refused IS NULL AND body::json ->> 'approval' IS NOT NULL
17
+ GROUP BY run_id, body::json ->> 'approval'
18
+ HAVING count(*) > 1
19
+ ORDER BY min(id);
@@ -0,0 +1,13 @@
1
+ -- The store's schema on Postgres, version 3: one answer per approval, as store/schema.ts COMMANDS_ONE_ANSWER keeps it on
2
+ -- SQLite. Applied once, after 0002, inside the transaction migrate.ts opens. Never edit this file once applied: a change is
3
+ -- a new file.
4
+ --
5
+ -- commands_one_answer: an approve or deny naming one approval (the body's `approval`, the tool call's id) is unique per run
6
+ -- while the runner has not refused it. The first answer written wins; a second, whether the same answer or the other one,
7
+ -- is a unique violation (StoreConstraint), which the server reads back as the first one's decision (the same again
8
+ -- changes nothing, the other is 409 already_answered). An answer the runner refused (its run could not resume) holds no
9
+ -- place, so the person may answer again.
10
+
11
+ CREATE UNIQUE INDEX commands_one_answer ON commands (run_id, (body::json ->> 'approval')) WHERE kind IN ('approve', 'deny') AND refused IS NULL;
12
+
13
+ UPDATE store_meta SET schema_version = 3 WHERE singleton = 1;
@@ -1,4 +1,4 @@
1
- import { type Store, type StoreRole } from "../store.js";
1
+ import { type Store, type StoreOwned, type StoreRole } from "../store.js";
2
2
  /** The schema a store is in when none is named. */
3
3
  export declare const DEFAULT_SCHEMA = "agentrun";
4
4
  /** How far a runner's clock may be from the database's before it says so at its start (ms). Leases are 30 s, so a gap this
@@ -27,8 +27,15 @@ export interface PostgresStoreOptions {
27
27
  * come free (STORE_CONNECT_TIMEOUT_MS, 4 s, by default). Past it the call, or the open, is refused (StoreDeadline,
28
28
  * naming the database's host, database and schema, never the URL), never left hanging. */
29
29
  readonly connectTimeoutMs?: number;
30
- /** Told, at a runner's open, when its clock is more than CLOCK_WARN_MS from the database's. */
30
+ /** 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
+ * for another server to let the schema go. */
31
32
  readonly warn?: (message: string) => void;
33
+ /** A server's: how long it waits for the owner lock another server holds, at its open and to take its own back after its
34
+ * lock's connection is lost (OWNER_WAIT_MS, 2 min, by default; 0 refuses at once with StoreOwned). */
35
+ readonly ownerWaitMs?: number;
36
+ /** A server's: told when its owner lock is lost for good (another server took the schema, or it could not be taken back
37
+ * within ownerWaitMs). Every call is refused from then: the process should exit non-zero, so its platform restarts it. */
38
+ readonly onOwnerLost?: (error: StoreOwned) => void;
32
39
  }
33
40
  /** Opens the store in `schema` on the Postgres at `url`. As the server (the default): takes the owner lock (StoreOwned when
34
41
  * another server holds the schema) and applies the pending migrations. As a runner: sets nothing up, and warns when its
@@ -28,6 +28,15 @@ export async function openPostgresStore(options) {
28
28
  ...(options.busyTimeoutMs === undefined ? {} : { busyTimeoutMs: options.busyTimeoutMs }),
29
29
  ...(options.poolSize === undefined ? {} : { poolSize: options.poolSize }),
30
30
  ...(options.connectTimeoutMs === undefined ? {} : { connectTimeoutMs: options.connectTimeoutMs }),
31
+ ...(options.ownerWaitMs === undefined ? {} : { ownerWaitMs: options.ownerWaitMs }),
32
+ ...(options.warn ? { onOwnerWait: options.warn } : {}),
33
+ ...(options.onOwnerLost ? { onOwnerLost: options.onOwnerLost } : {}),
34
+ // Taken back after a loss: the schema must still be the version this build migrated it to (a newer server may have
35
+ // taken the schema and migrated it meanwhile).
36
+ ownerCheck: async (client) => {
37
+ const found = await versionOf(client, schema);
38
+ return found === known ? undefined : `the schema is at version ${found ?? "none"} now, and this build knows ${known}`;
39
+ },
31
40
  });
32
41
  try {
33
42
  const found = await connection.withClient((client) => (role === "server" ? migrate(client, schema, now(), migrations) : versionOf(client, schema)));
@@ -278,7 +278,7 @@ export const STORE_DDL = [
278
278
  // sign_ins|<agent>:<provider>|pointer), which the store never opens. The owner sees its name ("default") and saved_at,
279
279
  // never the pointer, and no run's tools ever do. Forgetting a sign-in moves its sealed pointer, byte for byte so it
280
280
  // still opens, into a tombstone row (sign_in_tombstones), kept only so a server started later can still cut it from
281
- // what a run it was handed shows; the newest 32 per agent are kept, the oldest dropped first.
281
+ // what a run it was handed shows and from what its agent learned; every one is kept, never pruned.
282
282
  `CREATE TABLE IF NOT EXISTS sign_ins (
283
283
  agent_id TEXT NOT NULL REFERENCES agents (id),
284
284
  provider TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- // The store's one sealing rule: every sealed column is today's AES-256-GCM seal (pi-durable-agent's seal/unseal, the one
1
+ // The store's one sealing rule: every sealed column is today's AES-256-GCM seal (sealing.ts seal/unseal, the one
2
2
  // the tool keys use) under the server's seal key, bound to where it lives by its AAD, "<table>|<row key>|<column>". A value
3
3
  // copied to another row, column or table does not open. The store holds only the sealed bytes; the key stays in the
4
4
  // server's (and a runner's) environment, and the server's writer and the runner's unseal both seal and open through here.
@@ -7,7 +7,7 @@
7
7
  // credential as JSON with the server's origin inside it. Opened for a row whose url has another origin (an edit of the url
8
8
  // column by someone who can write the store but has no key), it is refused as damaged, so a credential is never sent to a
9
9
  // host it was not saved for.
10
- import { seal, unseal } from "@parcha/pi-durable-agent";
10
+ import { seal, unseal } from "../sealing.js";
11
11
  /** The sealed columns the store has. */
12
12
  export const sealedAt = {
13
13
  mcpServer: (name) => ({ table: "mcp_servers", row: name, column: "sealed" }),
@@ -10,6 +10,42 @@ import { inMemory } from "./memory.js";
10
10
  import { Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned, StoreWorkerLost } from "../store.js";
11
11
  /** How long a transaction may stay open (it holds every other call of the process) before it is rolled back. */
12
12
  export const DEFAULT_TRANSACTION_DEADLINE_MS = 10_000;
13
+ /** How often an open transaction's deadline looks at the process's event loop, and how far past its look a look may
14
+ * come before the gap counts as the process held up (runnableDeadline). */
15
+ const TICK_MS = 50;
16
+ const STALL_MS = 50;
17
+ /** Calls `expire` once `ms` of the time this process could run have passed, counted from now on the monotonic clock
18
+ * (performance.now: the host's clock set forward or back is never counted). A look every TICK_MS measures the event
19
+ * loop: a gap more than STALL_MS past its look was the process held up by other work (a harness binary hashed, a
20
+ * command run synchronously, the machine holding the process), wherever in the transaction it fell, before its
21
+ * deadline or across it, and is not counted. A wait of the transaction's own (a call awaited inside it) leaves the
22
+ * loop free, so it counts in full and is refused on time. Answers its clear. */
23
+ function runnableDeadline(ms, expire) {
24
+ const start = performance.now();
25
+ let last = start;
26
+ let held = 0;
27
+ const look = () => {
28
+ const now = performance.now();
29
+ const gap = now - last - TICK_MS;
30
+ if (gap > STALL_MS)
31
+ held += gap;
32
+ last = now;
33
+ return now;
34
+ };
35
+ const ticks = setInterval(look, TICK_MS);
36
+ let timer;
37
+ const check = () => {
38
+ const left = ms - (look() - start - held);
39
+ if (left <= 0)
40
+ return expire();
41
+ timer = setTimeout(check, Math.ceil(left));
42
+ };
43
+ timer = setTimeout(check, ms);
44
+ return () => {
45
+ clearInterval(ticks);
46
+ clearTimeout(timer);
47
+ };
48
+ }
13
49
  /** A statement's text parameters as the store writes text (dialect.ts cleanText: no NUL), on both stores alike. */
14
50
  const cleaned = (params) => (params ?? []).map((value) => (typeof value === "string" ? cleanText(value) : value));
15
51
  const cleanStatement = (statement) => ({ ...statement, params: cleaned(statement.params) });
@@ -234,10 +270,18 @@ export class Connection {
234
270
  throw error;
235
271
  }
236
272
  let live = true;
237
- let timer;
238
- const left = until !== undefined ? Math.max(0, until - Date.now()) : deadlineMs;
273
+ let clear = () => { };
239
274
  const deadline = new Promise((_, reject) => {
240
- timer = setTimeout(() => reject(new StoreDeadline(deadlineMs)), left);
275
+ const expire = () => reject(new StoreDeadline(deadlineMs));
276
+ // Counted from its call (a lease's), the deadline stays the wall clock's: MCP_REFRESH_LEASE_MS is reckoned from
277
+ // it. Counted from its begin, it is the time this process could run (runnableDeadline): while other work held
278
+ // the event loop, a statement answered meanwhile waited behind it, and that time was no statement's.
279
+ if (until !== undefined) {
280
+ const timer = setTimeout(expire, Math.max(0, until - Date.now()));
281
+ clear = () => clearTimeout(timer);
282
+ }
283
+ else
284
+ clear = runnableDeadline(deadlineMs, expire);
241
285
  });
242
286
  let value;
243
287
  try {
@@ -250,7 +294,7 @@ export class Connection {
250
294
  }
251
295
  catch (error) {
252
296
  live = false;
253
- clearTimeout(timer);
297
+ clear();
254
298
  try {
255
299
  await this.#send({ op: "rollback" });
256
300
  }
@@ -263,7 +307,7 @@ export class Connection {
263
307
  throw error;
264
308
  }
265
309
  live = false;
266
- clearTimeout(timer);
310
+ clear();
267
311
  // Counted from its call, a deadline reached by now is never committed past: rolled back, nothing written.
268
312
  if (until !== undefined && Date.now() >= until) {
269
313
  await this.#send({ op: "rollback" });
@@ -6,6 +6,9 @@ import { type StoreNow } from "../fence.js";
6
6
  * runner, no box: its only writes are the learning folder's one script). */
7
7
  /** A learning run's launch: harness "learning", its input the run that learned, and `model`, the grade model when one is
8
8
  * named (gradeModelOf; none: the agent's own grades it, as main's). No cap: main caps no grade. */
9
+ /** A WHERE condition on `runs`: the run is no built-in learning run (one a kept learning names, queued with it), which no
10
+ * list of runs names. */
11
+ export declare const NOT_A_LEARNING_RUN = "id NOT IN (SELECT learning_run_id FROM learning_proposals WHERE learning_run_id IS NOT NULL)";
9
12
  export declare const learningLaunchOf: (runId: string, model?: string) => {
10
13
  model?: string | undefined;
11
14
  harness: string;
@@ -11,6 +11,9 @@ import { writeLaunch } from "./run-launch.js";
11
11
  * runner, no box: its only writes are the learning folder's one script). */
12
12
  /** A learning run's launch: harness "learning", its input the run that learned, and `model`, the grade model when one is
13
13
  * named (gradeModelOf; none: the agent's own grades it, as main's). No cap: main caps no grade. */
14
+ /** A WHERE condition on `runs`: the run is no built-in learning run (one a kept learning names, queued with it), which no
15
+ * list of runs names. */
16
+ export const NOT_A_LEARNING_RUN = "id NOT IN (SELECT learning_run_id FROM learning_proposals WHERE learning_run_id IS NOT NULL)";
14
17
  export const learningLaunchOf = (runId, model) => ({ harness: "learning", input: { runId }, title: `Learning from ${runId}`, place: { mode: "runner" }, ...(model ? { model } : {}) });
15
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
16
19
  * the running runs' hashes and a launch's write of them are serialized, as SQLite's one writer serializes them. */
@@ -10,9 +10,9 @@ import { DatabaseSync } from "node:sqlite";
10
10
  import { claimFence, storeNow } from "../fence.js";
11
11
  import { RunStorage } from "../journal/storage.js";
12
12
  import { COMMANDS_ONE_ANSWER, DDL, SCHEMA_VERSION } from "../schema.js";
13
- import { AgentArchived, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreConstraint, StoreFromEarlierVersion, TriggerFull, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, SignInHandedTo, SignInMissing, SIGN_IN_TOMBSTONES_KEPT, } from "../store.js";
13
+ import { AgentArchived, CommandTaken, ExternalBodyConflict, Fenced, RunFinal, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreConstraint, StoreFromEarlierVersion, TriggerFull, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, } from "../store.js";
14
14
  import { Connection } from "./connection.js";
15
- import { applyRunPatch, refuseLeftovers, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
15
+ import { applyRunPatch, NOT_A_LEARNING_RUN, refuseLeftovers, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
16
16
  import { readLaunch, writeLaunch } from "./run-launch.js";
17
17
  import { canonical } from "../agent-body.js";
18
18
  import { aadOf, sealedAt } from "../seal.js";
@@ -127,8 +127,10 @@ async function versionOf(db) {
127
127
  * triggers, tool keys and trigger secrets (all in the store now), and the per-run door's token (the per-run door is
128
128
  * gone). This version's own top-level files are not among them, so a directory holding them opens: .token and
129
129
  * .server.json beside the store and its lock, a leftover box-image.json, and the files this version still keeps beside
130
- * the store in the same format an earlier version did (the webhook config and its outbox, the kept idempotency answers,
131
- * and the learning usage ledger), which an earlier version's copy of reads the same. */
130
+ * the store in the same format an earlier version did (the kept idempotency answers and the learning usage ledger),
131
+ * which an earlier version's copy of reads the same. A webhook config and outbox an earlier build kept beside the store
132
+ * (webhook.json, webhook-outbox.json) do not refuse the directory either: nothing reads them, and the webhook, now in
133
+ * the store, is set again. */
132
134
  const EARLIER_ROOT_FILES = ["mcp-servers.json", "triggers.json", "tool-keys.json", "trigger-secrets.json", ".door-token"];
133
135
  /** The files an earlier version kept in a data directory, relative to it: its store (a STORE_FILE with tables and no
134
136
  * store_meta row), agent homes (<agent>/agent.sqlite, agents/<agent>/agent.sqlite), run databases (runs/<run>/run.sqlite,
@@ -303,14 +305,17 @@ class SqliteStore {
303
305
  const clock = () => storeNow(d, now);
304
306
  this.#clock = clock;
305
307
  const insertAgent = (tx, agent, at) => tx.run("INSERT INTO agents (id, name, description, created_at) VALUES (?, ?, ?, ?)", agent.id, agent.name, agent.description ?? null, at);
306
- const insertRevision = async (tx, agentId, revision, at) => {
308
+ const insertRevision = async (tx, agentId, revision, at, ifCurrent) => {
307
309
  // The parent is the agent's current revision now (null for its first): the agent must exist, which its first revision
308
- // (create) and a later one (addRevision, upgrade) both guarantee before this. Held, so two revisions added at once
309
- // never both name the same parent.
310
+ // (create) and a later one (addRevision, upgrade) both guarantee before this. Held (a writer's row lock), so two
311
+ // revisions added at once, by this server or another on the same store, never both name the same parent, and
312
+ // `ifCurrent` is compared with what no other writer can move until this commits.
310
313
  await d.lockRow(tx, "agents", "id", agentId);
311
314
  const agent = await tx.get("SELECT current_revision FROM agents WHERE id = ?", agentId);
312
315
  if (!agent)
313
316
  throw new StoreConstraint(`no agent ${agentId}`);
317
+ if (ifCurrent !== undefined && agent.current_revision !== ifCurrent)
318
+ throw new RevisionMoved(agentId, agent.current_revision);
314
319
  await tx.run("INSERT INTO revisions (id, agent_id, parent_id, kind, body, skills, note, package, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", revision.id, agentId, agent.current_revision, revision.kind, json(revision.body), revision.skills === undefined || revision.skills === null ? null : json(revision.skills), revision.note ?? null, revision.package === undefined ? null : json(revision.package), at);
315
320
  await tx.run("UPDATE agents SET current_revision = ? WHERE id = ?", revision.id, agentId);
316
321
  };
@@ -381,8 +386,8 @@ class SqliteStore {
381
386
  await writeScopes(tx, t.id, []);
382
387
  return off.map(({ id: triggerId, name }) => ({ id: triggerId, name })).sort((a, b) => a.name.localeCompare(b.name));
383
388
  }),
384
- addRevision: async ({ agentId, ...revision }) => {
385
- await db.transaction((tx) => insertRevision(tx, agentId, revision, now()));
389
+ addRevision: async ({ agentId, ifCurrent, ...revision }) => {
390
+ await db.transaction((tx) => insertRevision(tx, agentId, revision, now(), ifCurrent));
386
391
  },
387
392
  setCurrent: async (agentId, revisionId) => {
388
393
  const changed = await db.transaction((tx) => tx.runCounted("UPDATE agents SET current_revision = ? WHERE id = ? AND EXISTS (SELECT 1 FROM revisions WHERE id = ? AND agent_id = ?)", revisionId, agentId, revisionId, agentId));
@@ -706,7 +711,9 @@ class SqliteStore {
706
711
  },
707
712
  launch: (runId) => readLaunch(db, runId),
708
713
  list: async ({ agentId, revisionId, state, archived, limit }) => {
709
- const where = [];
714
+ // A built-in learning run (a run's grade and merge, queued with its kept learning) is no run of a person's: no list,
715
+ // count, stat or notice names it.
716
+ const where = [NOT_A_LEARNING_RUN];
710
717
  const params = [];
711
718
  if (agentId !== undefined)
712
719
  (where.push("agent_id = ?"), params.push(agentId));
@@ -743,6 +750,11 @@ class SqliteStore {
743
750
  const rows = await db.all(`SELECT id FROM runs WHERE ${claimable.sql} ORDER BY started_at, id${bounded ? " LIMIT ?" : ""}`, ...claimable.params, ...(bounded ? [limit] : []));
744
751
  return rows.map((row) => row.id);
745
752
  },
753
+ heldAt: async (runId) => {
754
+ const n = clock();
755
+ const row = await db.get(`SELECT epoch FROM runs WHERE id = ? AND runner IS NOT NULL AND claimed_until >= ${n.sql}`, runId, ...n.params);
756
+ return row === undefined ? undefined : Number(row.epoch);
757
+ },
746
758
  claimMany: (runner, k, { leaseMs = DEFAULT_LEASE_MS } = {}) => this.#claimRuns(runner, leaseMs, { k }),
747
759
  update: async (claim, patch, rows = {}) => {
748
760
  if (Array.isArray(rows) || typeof rows !== "object" || rows === null)
@@ -965,6 +977,23 @@ class SqliteStore {
965
977
  return row ? proposalOf(row) : undefined;
966
978
  },
967
979
  proposals: async (agentId, { limit = 100 } = {}) => (await db.all("SELECT run_id, agent_id, turn, proposal, learning_run_id, created_at FROM learning_proposals WHERE agent_id = ? ORDER BY created_at DESC, run_id DESC LIMIT ?", agentId, limit)).map(proposalOf),
980
+ spend: async ({ from, to }) => {
981
+ 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
982
+ FROM learning_proposals lp
983
+ JOIN runs src ON src.id = lp.run_id
984
+ LEFT JOIN runs lr ON lr.id = lp.learning_run_id
985
+ WHERE src.imported_from IS NULL AND COALESCE(lr.ended_at, lp.created_at) >= ? AND COALESCE(lr.ended_at, lp.created_at) < ?
986
+ ORDER BY COALESCE(lr.ended_at, lp.created_at), lp.run_id`, from, to);
987
+ return rows.flatMap((row) => {
988
+ // A proposal: once its learning run ended, failed or was stopped, its row's cost is the grade's spend (a stop
989
+ // seen after a paid grade keeps it, learning-loop.ts).
990
+ if (row.learning_run_id !== null)
991
+ return row.run_state === "ended" || row.run_state === "failed" || row.run_state === "stopped" ? [{ agentId: row.agent_id, at: row.run_ended_at ?? row.created_at, costUsd: row.run_cost_usd }] : [];
992
+ // Kept with no learning run: dropped before it was proposed (nothing graded), unless it is still a proposal.
993
+ const kept = JSON.parse(row.proposal);
994
+ return kept?.state === "proposed" ? [] : [{ agentId: row.agent_id, at: row.created_at, costUsd: 0 }];
995
+ });
996
+ },
968
997
  };
969
998
  this.settings = {
970
999
  get: async (key) => {
@@ -1135,8 +1164,8 @@ class SqliteStore {
1135
1164
  const at = now();
1136
1165
  const tomb = await tx.get("INSERT INTO sign_in_tombstones (agent_id, provider, pointer_sealed, forgotten_at) VALUES (?, ?, ?, ?) RETURNING agent_id, provider, pointer_sealed, forgotten_at", agentId, provider, live.pointer_sealed, at);
1137
1166
  await tx.run("DELETE FROM sign_ins WHERE agent_id = ? AND provider = ?", agentId, provider);
1138
- // The newest kept, the oldest dropped first (per agent, across providers).
1139
- await tx.run("DELETE FROM sign_in_tombstones WHERE agent_id = ? AND id NOT IN (SELECT id FROM sign_in_tombstones WHERE agent_id = ? ORDER BY id DESC LIMIT ?)", agentId, agentId, SIGN_IN_TOMBSTONES_KEPT);
1167
+ // Every tombstone is kept: what the agent learned is cut of each pointer it ever held (handed-values.ts
1168
+ // agentPointers), and a dropped one would be shown again.
1140
1169
  return signInTombstoneOf(tomb);
1141
1170
  }),
1142
1171
  handedHolder: async (hash, options) => (await handedHolderIn(db, hash, { settleMs: options?.settleMs ?? 0, now: options?.at !== undefined ? { sql: d.bigintParam, params: [options.at] } : clock() }))?.id,