@parcha/agentrun-serve 0.1.0-beta.57 → 0.1.0-beta.59

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 (404) hide show
  1. package/CHANGELOG.md +376 -0
  2. package/README.md +393 -118
  3. package/dist/acp-package.d.ts +5 -1
  4. package/dist/acp-package.js +19 -2
  5. package/dist/adapters.d.ts +23 -2
  6. package/dist/adapters.js +106 -33
  7. package/dist/agents-store.js +1 -1
  8. package/dist/answer-text.d.ts +3 -0
  9. package/dist/answer-text.js +22 -0
  10. package/dist/api-only.d.ts +2 -4
  11. package/dist/api-only.js +2 -4
  12. package/dist/attach-conformance.js +5 -4
  13. package/dist/box-paths.d.ts +7 -5
  14. package/dist/box-paths.js +12 -8
  15. package/dist/browser-computer.d.ts +3 -8
  16. package/dist/browser-computer.js +12 -35
  17. package/dist/browser-cost.js +94 -20
  18. package/dist/capacity.d.ts +1 -1
  19. package/dist/capacity.js +3 -3
  20. package/dist/chatgpt-plan.d.ts +5 -0
  21. package/dist/chatgpt-plan.js +25 -11
  22. package/dist/claude-login-token.d.ts +121 -0
  23. package/dist/claude-login-token.js +797 -0
  24. package/dist/claude-login.d.ts +119 -34
  25. package/dist/claude-login.js +551 -79
  26. package/dist/claude-sign-in.d.ts +3 -0
  27. package/dist/claude-sign-in.js +10 -1
  28. package/dist/cli.js +325 -328
  29. package/dist/composio-made.d.ts +1 -6
  30. package/dist/composio-made.js +1 -6
  31. package/dist/composio-owners.d.ts +26 -0
  32. package/dist/composio-owners.js +36 -0
  33. package/dist/composio-preset.d.ts +56 -23
  34. package/dist/composio-preset.js +173 -77
  35. package/dist/composio-triggers.d.ts +4 -4
  36. package/dist/composio-triggers.js +6 -7
  37. package/dist/compute-cost.js +11 -2
  38. package/dist/computer-attach.d.ts +40 -19
  39. package/dist/computer-attach.js +326 -62
  40. package/dist/computer-held-routes.d.ts +1 -1
  41. package/dist/computer-held-routes.js +9 -4
  42. package/dist/computer-keys.d.ts +11 -1
  43. package/dist/computer-keys.js +26 -1
  44. package/dist/computer-record.js +3 -1
  45. package/dist/computer-view.d.ts +5 -3
  46. package/dist/computer-view.js +10 -6
  47. package/dist/computer-viewer.js +36 -7
  48. package/dist/computers.d.ts +12 -11
  49. package/dist/computers.js +11 -8
  50. package/dist/console/THIRD-PARTY-NOTICES.txt +50 -0
  51. package/dist/console/assets/backend-BztxEAvb.js +166 -0
  52. package/dist/console/assets/index-LwNL4L9q.js +619 -0
  53. package/dist/console/assets/share-L84tlUDW.js +6 -0
  54. package/dist/console/assets/styles-CaRKlHke.js +291 -0
  55. package/dist/console/assets/styles-DQo8rzY-.css +1 -0
  56. package/dist/console/index.html +4 -3
  57. package/dist/console/share.html +17 -0
  58. package/dist/decisions.d.ts +17 -7
  59. package/dist/decisions.js +41 -15
  60. package/dist/dial-relay.d.ts +25 -4
  61. package/dist/dial-relay.js +139 -5
  62. package/dist/docker-daemon.js +4 -5
  63. package/dist/docker-host-addresses.js +29 -11
  64. package/dist/email/account.d.ts +6 -0
  65. package/dist/email/account.js +6 -0
  66. package/dist/email/authentication.d.ts +21 -0
  67. package/dist/email/authentication.js +106 -0
  68. package/dist/email/email-faux.d.ts +11 -2
  69. package/dist/email/email-faux.js +21 -5
  70. package/dist/email/mail.d.ts +25 -0
  71. package/dist/email/mail.js +58 -2
  72. package/dist/email/names.js +2 -2
  73. package/dist/email/tools.d.ts +9 -4
  74. package/dist/email/tools.js +95 -13
  75. package/dist/env-switch.d.ts +13 -5
  76. package/dist/env-switch.js +24 -6
  77. package/dist/errors.d.ts +1 -0
  78. package/dist/errors.js +2 -0
  79. package/dist/fal-price.d.ts +12 -4
  80. package/dist/fal-price.js +110 -26
  81. package/dist/faux-computers.js +1 -1
  82. package/dist/filed-answer.d.ts +2 -2
  83. package/dist/filed-answer.js +2 -2
  84. package/dist/graph-served.d.ts +10 -5
  85. package/dist/graph-served.js +40 -10
  86. package/dist/handed-values.js +1 -2
  87. package/dist/harness-check.d.ts +2 -1
  88. package/dist/harness-check.js +45 -12
  89. package/dist/harness-keys.js +9 -6
  90. package/dist/harness-opencode/facts.js +2 -0
  91. package/dist/harness-recipe-entry.d.ts +9 -3
  92. package/dist/harness-recipe-entry.js +18 -9
  93. package/dist/harness-recipe.d.ts +21 -0
  94. package/dist/harness-recipe.js +25 -3
  95. package/dist/harness-table.d.ts +8 -0
  96. package/dist/harness-table.js +17 -6
  97. package/dist/helper-env.d.ts +4 -1
  98. package/dist/helper-env.js +4 -1
  99. package/dist/host-check.d.ts +2 -3
  100. package/dist/host-check.js +13 -7
  101. package/dist/hosted-search.js +1 -1
  102. package/dist/import.d.ts +11 -8
  103. package/dist/import.js +437 -186
  104. package/dist/key-refusal.d.ts +9 -2
  105. package/dist/key-refusal.js +86 -32
  106. package/dist/learn/audit.d.ts +8 -5
  107. package/dist/learn/audit.js +15 -7
  108. package/dist/learn/compile.d.ts +5 -2
  109. package/dist/learn/compile.js +45 -21
  110. package/dist/learn/field-check.d.ts +111 -0
  111. package/dist/learn/field-check.js +174 -0
  112. package/dist/learn/ledger.d.ts +173 -0
  113. package/dist/learn/ledger.js +225 -0
  114. package/dist/learn/promote.d.ts +82 -39
  115. package/dist/learn/promote.js +61 -66
  116. package/dist/learn/secrets.d.ts +4 -0
  117. package/dist/learn/secrets.js +12 -0
  118. package/dist/learned-nodes.d.ts +8 -5
  119. package/dist/learned-nodes.js +8 -5
  120. package/dist/learned-workflow.d.ts +2 -1
  121. package/dist/learned-workflow.js +13 -10
  122. package/dist/learning-cost.d.ts +40 -21
  123. package/dist/learning-cost.js +30 -21
  124. package/dist/learning-setting.d.ts +6 -0
  125. package/dist/learning-setting.js +11 -1
  126. package/dist/listen-first.d.ts +5 -4
  127. package/dist/listen-first.js +4 -5
  128. package/dist/live-reach.d.ts +9 -0
  129. package/dist/live-reach.js +9 -0
  130. package/dist/mcp-api-only-origins.d.ts +23 -3
  131. package/dist/mcp-api-only-origins.js +57 -17
  132. package/dist/mcp-gateway.d.ts +16 -2
  133. package/dist/mcp-gateway.js +41 -3
  134. package/dist/mcp-oauth.d.ts +1 -1
  135. package/dist/mcp-oauth.js +3 -2
  136. package/dist/mcp-probe.d.ts +3 -0
  137. package/dist/mcp-probe.js +3 -0
  138. package/dist/mcp-secret-writes.d.ts +24 -2
  139. package/dist/mcp-secret-writes.js +30 -2
  140. package/dist/mcp-servers-store.d.ts +52 -14
  141. package/dist/mcp-servers-store.js +165 -61
  142. package/dist/mcp-sources.d.ts +1 -2
  143. package/dist/mcp-sources.js +1 -2
  144. package/dist/mcp-store.d.ts +5 -5
  145. package/dist/mcp-store.js +3 -3
  146. package/dist/mcp.js +1 -1
  147. package/dist/micro.d.ts +2 -0
  148. package/dist/micro.js +2 -0
  149. package/dist/model-gateway.d.ts +1 -1
  150. package/dist/model-gateway.js +20 -36
  151. package/dist/model.d.ts +5 -4
  152. package/dist/model.js +7 -6
  153. package/dist/monid.d.ts +14 -1
  154. package/dist/monid.js +103 -26
  155. package/dist/ollama-provider.d.ts +23 -9
  156. package/dist/ollama-provider.js +49 -20
  157. package/dist/openapi.js +234 -61
  158. package/dist/otel/genai.d.ts +83 -7
  159. package/dist/otel/genai.js +69 -9
  160. package/dist/otel/tracer.d.ts +42 -13
  161. package/dist/otel/tracer.js +241 -56
  162. package/dist/page.d.ts +7 -1
  163. package/dist/page.js +76 -22
  164. package/dist/paid-calls.d.ts +6 -4
  165. package/dist/paid-calls.js +15 -7
  166. package/dist/place-offers.d.ts +59 -34
  167. package/dist/place-offers.js +100 -58
  168. package/dist/place.d.ts +13 -14
  169. package/dist/place.js +56 -41
  170. package/dist/print.js +1 -1
  171. package/dist/provider.d.ts +5 -4
  172. package/dist/provider.js +26 -13
  173. package/dist/redact/match.d.ts +27 -9
  174. package/dist/redact/match.js +266 -57
  175. package/dist/run-census.d.ts +1 -1
  176. package/dist/run-census.js +4 -5
  177. package/dist/run-cut.js +4 -5
  178. package/dist/run-export-store.d.ts +15 -0
  179. package/dist/run-export-store.js +30 -0
  180. package/dist/run-export.d.ts +139 -0
  181. package/dist/run-export.js +379 -0
  182. package/dist/run-file-cut.d.ts +5 -0
  183. package/dist/run-file-cut.js +13 -0
  184. package/dist/run-launch.js +16 -3
  185. package/dist/run-learning-served.d.ts +2 -2
  186. package/dist/run-model-key.d.ts +15 -6
  187. package/dist/run-model-key.js +30 -31
  188. package/dist/run-reads-over-store.js +4 -4
  189. package/dist/run-secrets.js +3 -5
  190. package/dist/run-timeline-served.js +3 -1
  191. package/dist/run-view.d.ts +1 -2
  192. package/dist/run-view.js +2 -1
  193. package/dist/runnable.js +2 -2
  194. package/dist/runner/adapter-loop.d.ts +35 -18
  195. package/dist/runner/adapter-loop.js +97 -63
  196. package/dist/runner/adapter-run-spec.d.ts +34 -14
  197. package/dist/runner/adapter-run-spec.js +120 -75
  198. package/dist/runner/adapters/pi.js +4 -2
  199. package/dist/runner/audit.d.ts +8 -5
  200. package/dist/runner/audit.js +37 -17
  201. package/dist/runner/beside.d.ts +9 -2
  202. package/dist/runner/beside.js +29 -13
  203. package/dist/runner/claim-secrets.d.ts +27 -18
  204. package/dist/runner/claim-secrets.js +61 -47
  205. package/dist/runner/cli-run-spec.d.ts +18 -0
  206. package/dist/runner/cli-run-spec.js +93 -46
  207. package/dist/runner/compare-end.d.ts +2 -1
  208. package/dist/runner/compare-end.js +25 -10
  209. package/dist/runner/conformance/harness.js +2 -3
  210. package/dist/runner/conformance/subject.d.ts +4 -1
  211. package/dist/runner/harness-loops.js +3 -3
  212. package/dist/runner/held.d.ts +19 -4
  213. package/dist/runner/journal-kinds.d.ts +4 -1
  214. package/dist/runner/journal-kinds.js +22 -4
  215. package/dist/runner/learned-first.js +20 -4
  216. package/dist/runner/learning-end.d.ts +2 -8
  217. package/dist/runner/learning-end.js +11 -19
  218. package/dist/runner/live-ticker.js +7 -5
  219. package/dist/runner/loop-contract.d.ts +0 -2
  220. package/dist/runner/loop.d.ts +7 -0
  221. package/dist/runner/loop.js +1 -0
  222. package/dist/runner/main.d.ts +11 -6
  223. package/dist/runner/main.js +24 -18
  224. package/dist/runner/mcp-claim.js +24 -7
  225. package/dist/runner/mcp-run.d.ts +3 -6
  226. package/dist/runner/mcp-run.js +3 -4
  227. package/dist/runner/meta-tools.js +3 -2
  228. package/dist/runner/metrics.d.ts +7 -0
  229. package/dist/runner/metrics.js +19 -0
  230. package/dist/runner/model-route.d.ts +10 -7
  231. package/dist/runner/model-route.js +79 -15
  232. package/dist/runner/native-loop.js +10 -8
  233. package/dist/runner/presence.d.ts +11 -4
  234. package/dist/runner/presence.js +11 -6
  235. package/dist/runner/promotion.d.ts +25 -13
  236. package/dist/runner/promotion.js +125 -50
  237. package/dist/runner/redact.d.ts +3 -1
  238. package/dist/runner/redact.js +5 -3
  239. package/dist/runner/reflect-hook.js +1 -1
  240. package/dist/runner/responses-fetch.d.ts +36 -0
  241. package/dist/runner/responses-fetch.js +511 -0
  242. package/dist/runner/run-child-host.d.ts +38 -12
  243. package/dist/runner/run-child-host.js +231 -83
  244. package/dist/runner/run-child.js +11 -4
  245. package/dist/runner/runner-check.js +5 -1
  246. package/dist/runner/runner.d.ts +5 -3
  247. package/dist/runner/runner.js +14 -10
  248. package/dist/runner/save-slots.js +2 -1
  249. package/dist/runner/sdk-loop.js +8 -8
  250. package/dist/runner/spec-holds.d.ts +8 -1
  251. package/dist/runner/spec-holds.js +9 -4
  252. package/dist/runner/subagent.d.ts +11 -0
  253. package/dist/runner/subagent.js +17 -3
  254. package/dist/runner/workflow-calls.d.ts +9 -0
  255. package/dist/runner/workflow-calls.js +150 -0
  256. package/dist/runner/workflow-first.d.ts +138 -37
  257. package/dist/runner/workflow-first.js +230 -99
  258. package/dist/runner/workflow-spec.js +2 -2
  259. package/dist/runs-over-store.js +8 -7
  260. package/dist/save-once.d.ts +14 -0
  261. package/dist/save-once.js +31 -0
  262. package/dist/scrub-command.d.ts +34 -31
  263. package/dist/scrub-command.js +116 -147
  264. package/dist/sdk/runs.d.ts +6 -0
  265. package/dist/sdk/runs.js +89 -10
  266. package/dist/seal-key.js +4 -4
  267. package/dist/secret-cut.d.ts +3 -0
  268. package/dist/secret-cut.js +7 -1
  269. package/dist/secret-rules.d.ts +8 -1
  270. package/dist/secret-rules.js +482 -53
  271. package/dist/secrets.d.ts +51 -9
  272. package/dist/secrets.js +311 -21
  273. package/dist/server-keys.d.ts +4 -3
  274. package/dist/server-keys.js +4 -3
  275. package/dist/server-secrets-store.js +2 -4
  276. package/dist/server.d.ts +33 -10
  277. package/dist/server.js +454 -136
  278. package/dist/share-context.d.ts +22 -0
  279. package/dist/share-context.js +76 -0
  280. package/dist/shell-lex.d.ts +105 -0
  281. package/dist/shell-lex.js +646 -0
  282. package/dist/sign-ins-store.d.ts +5 -7
  283. package/dist/sign-ins-store.js +12 -16
  284. package/dist/sign-ins.d.ts +7 -11
  285. package/dist/sign-ins.js +40 -41
  286. package/dist/skills/agentrun-serve/SKILL.md +5 -2
  287. package/dist/slots.d.ts +9 -0
  288. package/dist/slots.js +45 -0
  289. package/dist/start-switches.d.ts +6 -5
  290. package/dist/start-switches.js +8 -4
  291. package/dist/stats.d.ts +5 -1
  292. package/dist/stats.js +1 -1
  293. package/dist/store/agent-body.js +2 -2
  294. package/dist/store/dialect.d.ts +4 -0
  295. package/dist/store/dialect.js +1 -0
  296. package/dist/store/index.d.ts +2 -2
  297. package/dist/store/index.js +1 -1
  298. package/dist/store/mcp-record-keys.d.ts +10 -0
  299. package/dist/store/mcp-record-keys.js +13 -0
  300. package/dist/store/postgres/dialect.js +2 -0
  301. package/dist/store/postgres/migrations/0028_learning_ledger.sql +44 -0
  302. package/dist/store/postgres/migrations/0029_run_launch_census_settle.sql +28 -0
  303. package/dist/store/postgres/migrations/0030_learning_ledger_epoch.sql +40 -0
  304. package/dist/store/postgres/migrations/0031_learning_ledger_calls.sql +12 -0
  305. package/dist/store/postgres/store.js +4 -0
  306. package/dist/store/schema.d.ts +44 -4
  307. package/dist/store/schema.js +111 -11
  308. package/dist/store/seal.d.ts +4 -1
  309. package/dist/store/sqlite/run-launch.d.ts +3 -10
  310. package/dist/store/sqlite/run-launch.js +12 -23
  311. package/dist/store/sqlite/run-patch.d.ts +19 -2
  312. package/dist/store/sqlite/run-patch.js +67 -2
  313. package/dist/store/sqlite/store.d.ts +3 -0
  314. package/dist/store/sqlite/store.js +177 -32
  315. package/dist/store/store-schema.js +3 -4
  316. package/dist/store/store.d.ts +74 -25
  317. package/dist/store/store.js +14 -11
  318. package/dist/store-reads/analytics.d.ts +2 -1
  319. package/dist/store-reads/analytics.js +7 -5
  320. package/dist/store-reads/learning.d.ts +102 -136
  321. package/dist/store-reads/learning.js +251 -302
  322. package/dist/store-reads/stats.d.ts +2 -2
  323. package/dist/store-reads/stats.js +13 -7
  324. package/dist/store-view.js +10 -7
  325. package/dist/suggestions.d.ts +1 -1
  326. package/dist/suggestions.js +29 -13
  327. package/dist/template-eval.d.ts +91 -9
  328. package/dist/template-eval.js +448 -105
  329. package/dist/template-import.d.ts +0 -10
  330. package/dist/template-import.js +5 -10
  331. package/dist/timeline/labels.d.ts +1 -1
  332. package/dist/timeline/labels.js +4 -3
  333. package/dist/timeline/timeline.d.ts +23 -11
  334. package/dist/timeline/timeline.js +115 -31
  335. package/dist/timeline/web-calls.d.ts +14 -14
  336. package/dist/timeline/web-calls.js +18 -30
  337. package/dist/tool-gate.d.ts +13 -1
  338. package/dist/tool-gate.js +43 -3
  339. package/dist/tool-keys-store.js +2 -4
  340. package/dist/tool-keys.d.ts +11 -0
  341. package/dist/tool-keys.js +16 -0
  342. package/dist/tool-plane.d.ts +50 -11
  343. package/dist/tool-plane.js +94 -30
  344. package/dist/tools.d.ts +5 -1
  345. package/dist/tools.js +7 -7
  346. package/dist/trigger-email.js +12 -6
  347. package/dist/triggers.d.ts +15 -34
  348. package/dist/triggers.js +119 -126
  349. package/dist/validate.d.ts +8 -1
  350. package/dist/validate.js +163 -23
  351. package/dist/web-fake.d.ts +2 -1
  352. package/dist/web-fake.js +8 -6
  353. package/dist/web-fetch.d.ts +8 -6
  354. package/dist/web-fetch.js +13 -11
  355. package/dist/web-holds.d.ts +32 -0
  356. package/dist/web-holds.js +86 -0
  357. package/dist/web-run.d.ts +32 -5
  358. package/dist/web-run.js +75 -28
  359. package/dist/web-save.d.ts +4 -9
  360. package/dist/web-save.js +27 -55
  361. package/dist/web-search.js +14 -25
  362. package/dist/wires.d.ts +4 -3
  363. package/dist/wires.js +5 -4
  364. package/dist/workspace/archil-claim.d.ts +12 -5
  365. package/dist/workspace/archil-claim.js +45 -5
  366. package/dist/workspace/attach.js +52 -19
  367. package/dist/workspace/attached-computers.d.ts +38 -11
  368. package/dist/workspace/attached-computers.js +81 -16
  369. package/dist/workspace/computer-deps.d.ts +29 -7
  370. package/dist/workspace/computer-deps.js +36 -18
  371. package/dist/workspace/computer-for-claim.d.ts +21 -4
  372. package/dist/workspace/computer-for-claim.js +166 -57
  373. package/dist/workspace/computer-intervals.d.ts +2 -0
  374. package/dist/workspace/computer-intervals.js +1 -1
  375. package/dist/workspace/computer-janitor.d.ts +48 -14
  376. package/dist/workspace/computer-janitor.js +153 -44
  377. package/dist/workspace/computer-kept.d.ts +158 -32
  378. package/dist/workspace/computer-kept.js +288 -63
  379. package/dist/workspace/computer-providers.d.ts +8 -3
  380. package/dist/workspace/computer-providers.js +12 -5
  381. package/dist/workspace/index.d.ts +1 -1
  382. package/dist/workspace/index.js +1 -1
  383. package/dist/workspace/local.js +41 -1
  384. package/dist/workspace/mount-revoke-left.d.ts +31 -0
  385. package/dist/workspace/mount-revoke-left.js +72 -0
  386. package/dist/workspace/paired-route.d.ts +91 -0
  387. package/dist/workspace/paired-route.js +152 -0
  388. package/dist/workspace/resolve-computer.d.ts +5 -2
  389. package/dist/workspace/resolve-computer.js +9 -3
  390. package/dist/workspace/run-end-computers.d.ts +11 -5
  391. package/dist/workspace/run-end-computers.js +153 -28
  392. package/dist/workspace/run-tools.d.ts +22 -3
  393. package/dist/workspace/run-tools.js +17 -5
  394. package/dist/workspace/run-workspace.d.ts +14 -1
  395. package/dist/workspace/run-workspace.js +34 -1
  396. package/dist/workspace/workspace.d.ts +6 -0
  397. package/dist/wrapped.d.ts +8 -2
  398. package/dist/wrapped.js +21 -6
  399. package/package.json +12 -13
  400. package/skills/agentrun-serve/SKILL.md +5 -2
  401. package/templates/README.md +25 -9
  402. package/dist/console/assets/backend-DVhHzJX2.js +0 -166
  403. package/dist/console/assets/index-Bwn1oTem.css +0 -1
  404. package/dist/console/assets/index-okP-y8PK.js +0 -747
@@ -12,7 +12,7 @@ import { watchCommandsAt, wakeCommands } from "../command-wake.js";
12
12
  import { claimFence, storeNow } from "../fence.js";
13
13
  import { JOURNAL_FIRST_ID, RunStorage } from "../journal/storage.js";
14
14
  import { RUNNER_RECORDS } from "@parcha/agentrun-kernel";
15
- import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, diskUpgrade, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUN_ATTEMPTS, RUNNERS, RUNNERS_ADDED, RUN_LAUNCH_CENSUS, RUN_LAUNCH_CENSUS_PENDING, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, TRIGGERS_TEMPLATE_ID } from "../schema.js";
15
+ import { COMMANDS_ONE_ANSWER, COMPUTER_INTERVALS, COMPUTER_INTERVALS_ADDED, COMPUTER_INTERVALS_RUN, DDL, diskUpgrade, HAND_BACKS, HAND_BACKS_AT, HAND_BACKS_KEPT_MS, HAND_BACKS_RUN, IMPORTED_TEMPLATES, LEARNING_LEDGER, LEARNING_LEDGER_ADDED, LEARNING_LEDGER_AGENT, LEARNING_LEDGER_BY_HAND, LEARNING_SPEND, LEARNING_SPEND_AGENT, LEARNING_SPEND_OF_RUN, ledgerUpgrade, listingUpgrade, MINTED_TOKENS, purgeUpgrade, relayUpgrade, NATIVE_COMMANDS_INDEX, PI_TABLE, PI_TABLES, REVISIONS_MCP_PIN, REVISIONS_MONID_PIN, RUN_ATTEMPTS, RUNNERS, RUNNERS_ADDED, RUN_LAUNCH_CENSUS, RUN_LAUNCH_CENSUS_ERASED, RUN_LAUNCH_CENSUS_ERASED_MADE, RUN_LAUNCH_CENSUS_SETTLE, RUNS_COST_UPPER_BOUND, RUNS_LABELS, SCHEMA_VERSION, SETTLED_LIST_STATUS, STORE_META_LEDGER_BACKFILLED, TRIGGERS_TEMPLATE_ID } from "../schema.js";
16
16
  import { ActiveRuns, AgentArchived, AgentDeleting, AgentPurged, CommandTaken, ExternalBodyConflict, Fenced, FiringMoved, RunFinal, RunPurged, RunsMadeFromLeft, SchemaVersionUnknown, STORE_WRITE_DEADLINE_MS, StoreAwaitsServer, StoreBusy, StoreConstraint, StoreFromEarlierVersion, TriggerFull, TriggersLeft, UPLOAD_PREFIX, FINAL_STATES, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, SignInHandedTo, SignInMissing, RUN_CHANGES_PAGE, KEPT_PREFIX, RUNNER_ROWS_KEPT_MS, RUNNER_STALE_MS, tombstoneMetrics, } from "../store.js";
17
17
  /** The run a launch body is made from (Runs.madeFrom): the run whose input it replays (`replay.of`) or audits (`audit.of`). */
18
18
  const madeOf = (body) => {
@@ -32,9 +32,11 @@ const seqOf = (cursor) => {
32
32
  import { cleanText, settledBody } from "../dialect.js";
33
33
  import { inMemory } from "./memory.js";
34
34
  import { Connection, DEFAULT_BUSY_TIMEOUT_MS } from "./connection.js";
35
- import { applyRunPatch, EXACT_COST_USD, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
35
+ import { applyRunPatch, backfillLedger, BY_HAND_BEFORE, EXACT_COST_USD, NOT_A_LEARNING_RUN, recordLedger, refuseLeftovers, REOPEN_SET, reopenableWhere, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
36
36
  import { launchDiskOf, readableJson, readLaunch, readLearningStarts, readSeededBefore, readUsageMetadata, writeLaunch, writeLaunchSealed } from "./run-launch.js";
37
37
  import { canonical } from "../agent-body.js";
38
+ import { mcpRecordKeys } from "../mcp-record-keys.js";
39
+ import { workflowCallsIn } from "../../learning-cost.js";
38
40
  import { readProjectCheckpoints } from "./project-checkpoints.js";
39
41
  import { aadOf, sealedAt } from "../seal.js";
40
42
  /** Registry writers UPDATE/DELETE this same row, so a prepared cutover and a credential/catalog edit serialize. */
@@ -72,6 +74,10 @@ export const STORE_FILE = "store.sqlite";
72
74
  /** No audit's shadow run (learn/audit.ts SHADOW_PREFIX "audit."): the prefix compared as it is, which LIKE does not on
73
75
  * SQLite (it folds case). */
74
76
  const NOT_A_SHADOW_RUN = "substr(runs.id, 1, 6) <> 'audit.'";
77
+ /** A runs list's `model` (ListedFilter.model, `provider/model`) as SQL taking the model as its one `?`: the runs that sent at
78
+ * least one request to it, a key of the requests their metrics count per model (metrics.models), exactly (no prefix, no case
79
+ * folding). A run with no metrics yet sent none. */
80
+ const runUsedModel = (d) => d.jsonObjectHasKey("runs.metrics", ["models"]);
75
81
  /** A runner holds the run's claim at `now` (SQL), and the run is not over. */
76
82
  const heldAt = (now) => `(runs.runner IS NOT NULL AND runs.claimed_until >= ${now} AND runs.state NOT IN ('ended', 'stopped', 'failed'))`;
77
83
  /** The run's listing is behind at `now` (SQL; its parameters twice, `params`): built before the latest write that moved
@@ -154,8 +160,9 @@ const claimableIn = (d, n, claimer) => {
154
160
  };
155
161
  };
156
162
  /** The run's computer is kept at its park (its KEPT_PREFIX row) pinned to a runner other than `claimer` that is still
157
- * there under the incarnation the row names, at the deadlines' clock `n`: its runners row seen within RUNNER_STALE_MS,
158
- * claiming (refused NULL); the keep neither ending nor ended, and its `until` ahead. That runner's Docker engine or
163
+ * there (KEPT_PREFIX says what that means: its runners row seen within RUNNER_STALE_MS at the deadlines' clock `n`,
164
+ * under the incarnation the row names) and claiming (refused NULL); the keep neither ending nor ended, and its `until`
165
+ * ahead, on the same clock it was stamped on. That runner's Docker engine or
159
166
  * attach hub holds the machine, so only it can take it back (workspace/computer-kept.ts pinnedOf); once any of these
160
167
  * stops holding, any runner claims the run. Read in the claim's own statement, so no check-then-act gap. A row with no
161
168
  * runner (a computer any runner reaches: an exec vendor's, a phone; or one an earlier build kept) pins nothing. */
@@ -267,6 +274,9 @@ async function versionOf(db) {
267
274
  * (webhook.json, webhook-outbox.json) do not refuse the directory either: nothing reads them, and the webhook, now in
268
275
  * the store, is set again. */
269
276
  const EARLIER_ROOT_FILES = ["mcp-servers.json", "triggers.json", "tool-keys.json", "trigger-secrets.json", ".door-token"];
277
+ /** The store's earlier versions the server upgrades in place at its open (openSqliteStore), which a runner waits for
278
+ * (StoreAwaitsServer); store-schema reports from the same set. */
279
+ export const SQLITE_UPGRADES = new Set([11, 12, 13, 14, 15]);
270
280
  /** The columns a runner of this build needs that an earlier build of this same version may not have: the server adds each
271
281
  * at its start (openSqliteStore), and a runner on a file without one waits for that server (StoreAwaitsServer, in `why`'s
272
282
  * words; exit 3). store-schema reads the same list, so its report says "waits" where the runner would. */
@@ -281,6 +291,9 @@ export const SQLITE_RUNNER_NEEDS = [
281
291
  { table: "runners", columns: Object.keys(RUNNERS_ADDED), why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
282
292
  { table: "hand_backs", columns: ["run_id"], why: "keep each runner's version and slots, and each hand-back (runners.version, runners.slots, hand_backs)" },
283
293
  { table: "run_attempts", columns: ["run_id"], why: "keep each claim's turn and attempt (run_attempts)" },
294
+ // A run's end writes its ledger row and spend rows (run-patch.ts applyRunPatch) in its own transaction.
295
+ { table: "learning_ledger", columns: ["run_id", ...Object.keys(LEARNING_LEDGER_ADDED)], why: "write each run's learning ledger row and spend at its end (learning_ledger, learning_spend)" },
296
+ { table: "learning_spend", columns: ["run_id"], why: "write each run's learning ledger row and spend at its end (learning_ledger, learning_spend)" },
284
297
  ];
285
298
  /** What a runner of this build waits for on a file of this version (SQLITE_RUNNER_NEEDS' first missing column's `why`),
286
299
  * or undefined when it opens; `columnsOf` reads a table's columns. */
@@ -417,8 +430,10 @@ export async function openSqliteStore(options) {
417
430
  // it. Version 12 names no minting runner on a machine's token and keeps no runner's relay: the server adds them
418
431
  // (schema.ts relayUpgrade). Version 13 keeps no purge time on a run or an agent: the server adds them (schema.ts
419
432
  // purgeUpgrade). Version 14 keeps no disk on a run: the server adds it and writes each run's from its launch (schema.ts
420
- // diskUpgrade). A runner refuses 11 to 14 until that server has.
421
- const upgrading = found === 11 || found === 12 || found === 13 || found === 14;
433
+ // diskUpgrade). Version 15 keeps each ledger row's epoch: the server repairs the rows that release could leave wrong
434
+ // and drops it (the ledger's step below, then ledgerUpgrade). A runner refuses 11 to 15 until that server has, and a
435
+ // runner of 15, whose end writes the epoch, refuses 16 (SchemaVersionUnknown), or stops at its next floor read.
436
+ const upgrading = found !== null && SQLITE_UPGRADES.has(found);
422
437
  if (upgrading && role === "runner")
423
438
  throw new StoreAwaitsServer(`bring this store from version ${found} to ${SCHEMA_VERSION}`);
424
439
  if (found !== SCHEMA_VERSION && !upgrading)
@@ -455,12 +470,20 @@ export async function openSqliteStore(options) {
455
470
  await connection.write([{ sql: RUNS_LABELS }], { full: true });
456
471
  }
457
472
  // An earlier build of this version kept no census on a run's launch (schema.ts RUN_LAUNCH_CENSUS): the server adds the
458
- // column, nullable, every run ended before reading as never handed a secret, and marks each launch that holds one now
459
- // as pending (store.ts CENSUS_PENDING). A runner writes it at each end, so it waits for that server.
473
+ // column, nullable: every run ended before reads as never handed a secret, and a launch that holds one now as not yet
474
+ // counted (its end counts it). A runner writes it at each end, so it waits for that server.
460
475
  if (!(await connection.all("SELECT name FROM pragma_table_info('run_launch')")).some((column) => column.name === "census")) {
461
476
  if (role === "runner")
462
477
  throw new StoreAwaitsServer("add each run's census");
463
- await connection.write([{ sql: RUN_LAUNCH_CENSUS }, { sql: RUN_LAUNCH_CENSUS_PENDING }], { full: true });
478
+ await connection.write([{ sql: RUN_LAUNCH_CENSUS }], { full: true });
479
+ }
480
+ // A store no server of this build opened yet holds no RUN_LAUNCH_CENSUS_ERASED (an end that erases sealed bytes with
481
+ // no census, as an earlier runner's does, writes "unscanned"). The server makes it, and in the same write settles each
482
+ // "pending" 0.1.0-beta.57 left (RUN_LAUNCH_CENSUS_SETTLE), so a run live at the upgrade is counted at its end. Every
483
+ // later open reads only that the trigger is there. A runner leaves both: an end over a "pending" writes the marker,
484
+ // and its files are withheld, never read uncut.
485
+ if (role === "server" && (await connection.all(RUN_LAUNCH_CENSUS_ERASED_MADE)).length === 0) {
486
+ await connection.write([{ sql: RUN_LAUNCH_CENSUS_SETTLE }, { sql: RUN_LAUNCH_CENSUS_ERASED }], { full: true });
464
487
  }
465
488
  // An earlier build of this version kept no package mark on a trigger (schema.ts TRIGGERS_TEMPLATE_ID): the server adds
466
489
  // the column, nullable, every trigger made before reading as no package's. A runner reads each trigger through it, so
@@ -487,6 +510,15 @@ export async function openSqliteStore(options) {
487
510
  if (role === "runner" && (await connection.all("SELECT name FROM pragma_table_info('run_attempts')")).length === 0) {
488
511
  throw new StoreAwaitsServer("keep each claim's turn and attempt (run_attempts)");
489
512
  }
513
+ // A run's end writes its ledger row and spend rows (schema.ts LEARNING_LEDGER, LEARNING_SPEND) in its own transaction:
514
+ // a runner waits for the server that adds the tables (STORE_DDL at its start) and their columns (LEARNING_LEDGER_ADDED).
515
+ // The `epoch` version 15 kept on the ledger, which this build's end does not write, is the version's: a runner
516
+ // refuses 15 above.
517
+ const metaColumns = new Set((await connection.all("SELECT name FROM pragma_table_info('store_meta')")).map((column) => column.name));
518
+ const ledgerColumns = new Set((await connection.all("SELECT name FROM pragma_table_info('learning_ledger')")).map((column) => column.name));
519
+ if (role === "runner" && ((await connection.all("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name IN ('learning_ledger', 'learning_spend')")).length < 2 || Object.keys(LEARNING_LEDGER_ADDED).some((column) => !ledgerColumns.has(column)))) {
520
+ throw new StoreAwaitsServer("write each run's learning ledger row and spend at its end (learning_ledger, learning_spend)");
521
+ }
490
522
  // The per-run viewer table was renamed browser_viewers → computer_viewers (schema.ts). Its rows are ephemeral, so none
491
523
  // migrate; the server drops a stale browser_viewers an earlier build of this version left, so none lingers beside it.
492
524
  // An earlier build of this version made no one-answer index on commands (schema.ts COMMANDS_ONE_ANSWER), or one that
@@ -523,6 +555,16 @@ export async function openSqliteStore(options) {
523
555
  { sql: COMPUTER_INTERVALS_RUN },
524
556
  // Nor any claim's turn and attempt (schema.ts RUN_ATTEMPTS): a claim made before it has no row.
525
557
  { sql: RUN_ATTEMPTS },
558
+ // Nor any learning ledger (schema.ts LEARNING_LEDGER, LEARNING_SPEND; version 15's, with each row's `epoch`, is
559
+ // repaired and its epoch dropped by ledgerUpgrade below). Nor the mark that every ended run has its row
560
+ // (STORE_META_LEDGER_BACKFILLED), nor the by-hand index (LEARNING_LEDGER_BY_HAND).
561
+ ...(metaColumns.has("ledger_backfilled") ? [] : [{ sql: STORE_META_LEDGER_BACKFILLED }]),
562
+ { sql: LEARNING_LEDGER },
563
+ { sql: LEARNING_LEDGER_AGENT },
564
+ { sql: LEARNING_LEDGER_BY_HAND },
565
+ { sql: LEARNING_SPEND },
566
+ { sql: LEARNING_SPEND_AGENT },
567
+ { sql: LEARNING_SPEND_OF_RUN },
526
568
  { sql: NATIVE_COMMANDS_INDEX },
527
569
  ], { full: true });
528
570
  // A computer_intervals an earlier build of this version made has no disk or booked time (schema.ts
@@ -537,6 +579,13 @@ export async function openSqliteStore(options) {
537
579
  const runnersMissing = Object.entries(RUNNERS_ADDED).filter(([column]) => !runnersNow.has(column)).map(([, sql]) => ({ sql }));
538
580
  if (runnersMissing.length > 0)
539
581
  await connection.write(runnersMissing, { full: true });
582
+ // A learning_ledger an earlier build of this version made keeps no calls (schema.ts LEARNING_LEDGER_ADDED): added
583
+ // where missing, its rows' calls none until their run's next end. Before the open's backfill (backfillLedger below),
584
+ // whose rows recordLedger writes with their calls.
585
+ const ledgerNow = new Set((await connection.all("SELECT name FROM pragma_table_info('learning_ledger')")).map((column) => column.name));
586
+ const ledgerMissing = Object.entries(LEARNING_LEDGER_ADDED).filter(([column]) => !ledgerNow.has(column)).map(([, sql]) => ({ sql }));
587
+ if (ledgerMissing.length > 0)
588
+ await connection.write(ledgerMissing, { full: true });
540
589
  await backfillNativeCommandOwners(connection);
541
590
  if (found === 11) {
542
591
  const present = new Set((await connection.all("SELECT name FROM pragma_table_info('runs')")).map((column) => column.name));
@@ -546,12 +595,16 @@ export async function openSqliteStore(options) {
546
595
  const minted = new Set((await connection.all("SELECT name FROM pragma_table_info('minted_tokens')")).map((column) => column.name));
547
596
  await connection.write(relayUpgrade(minted).map((sql) => ({ sql })), { full: true });
548
597
  }
549
- if (upgrading) {
598
+ if (upgrading && found !== null) {
550
599
  const named = async (table) => new Set((await connection.all(`SELECT name FROM pragma_table_info('${table}')`)).map((column) => column.name));
551
- if (found !== 14)
600
+ if (found <= 13)
552
601
  await connection.write(purgeUpgrade(await named("runs"), await named("agents")).map((sql) => ({ sql })), { full: true });
553
- await connection.write(diskUpgrade(await named("runs")).map((sql) => ({ sql })), { full: true });
602
+ if (found <= 14)
603
+ await connection.write(diskUpgrade(await named("runs")).map((sql) => ({ sql })), { full: true });
604
+ await connection.write(ledgerUpgrade(await named("learning_ledger")).map((sql) => ({ sql })), { full: true });
554
605
  }
606
+ // Every run an earlier build ended gets its ledger row once, here, on the schema this build reads.
607
+ await backfillLedger(connection, options.now ?? Date.now);
555
608
  }
556
609
  }
557
610
  catch (error) {
@@ -633,6 +686,12 @@ export function storeOver(connection, now, file) {
633
686
  /** How long a purge's checkpoint waits for another connection's reader or writer before it leaves the log to the next
634
687
  * start's scrub: short, since every other request of the store's connection queues behind it. */
635
688
  const PURGE_CHECKPOINT_BUSY_MS = 20;
689
+ /** Run `runId`'s learning ledger (learn/ledger.ts), gone: its row, each spend row it booked, and an audit's spend row of
690
+ * it (its shadow's, of_run). What a run's purge (Runs.purge) and its delete (Runs.remove) both drop. */
691
+ async function dropLedger(tx, runId) {
692
+ await tx.run("DELETE FROM learning_ledger WHERE run_id = ?", runId);
693
+ await tx.run("DELETE FROM learning_spend WHERE run_id = ? OR of_run = ?", runId, runId);
694
+ }
636
695
  /** A run's content in every table that keeps it by the run's id, gone: what a run's purge (Runs.purge) and its delete
637
696
  * (Runs.remove) both drop. A table added for a run's content goes here, so neither path leaves it behind. */
638
697
  async function dropRunContent(tx, runId) {
@@ -923,6 +982,8 @@ class SqliteStore {
923
982
  if (left.length)
924
983
  throw new TriggersLeft(agentId, left.map((one) => one.id));
925
984
  await tx.run("DELETE FROM learning_proposals WHERE agent_id = ?", agentId);
985
+ await tx.run("DELETE FROM learning_ledger WHERE agent_id = ?", agentId);
986
+ await tx.run("DELETE FROM learning_spend WHERE agent_id = ?", agentId);
926
987
  await dropAgentPrivate(tx, agentId);
927
988
  // Its revisions in one statement (a revision's parent is the same agent's, checked at the statement's end), the
928
989
  // agent's pointer at its current one cleared first.
@@ -1383,7 +1444,7 @@ class SqliteStore {
1383
1444
  },
1384
1445
  // A list's page from the rows alone: filtered, ordered and cut to the page in the query, one read whatever the number
1385
1446
  // of runs, each row with its listing (schema.ts RUN_LISTING_COLUMNS) and its agent's archive time.
1386
- listed: async ({ agentId, revisionId, labels, archived, status, going, after, limit, offset = 0 }) => {
1447
+ listed: async ({ agentId, revisionId, labels, source, startedFrom, startedBefore, model, archived, status, going, after, limit, offset = 0 }) => {
1387
1448
  const n = clock();
1388
1449
  const behind = listingBehind(n.sql);
1389
1450
  // Neither a built-in learning run nor an audit's shadow run (learn/audit.ts SHADOW_PREFIX, matched as it is, case and all).
@@ -1395,6 +1456,17 @@ class SqliteStore {
1395
1456
  (where.push("runs.revision_id = ?"), params.push(revisionId));
1396
1457
  for (const [key, value] of Object.entries(labels ?? {}))
1397
1458
  (where.push(d.jsonObjectHas("runs.labels")), params.push(key, value));
1459
+ if (source === "live")
1460
+ where.push("runs.imported_from IS NULL");
1461
+ else if (source !== undefined)
1462
+ (where.push(`${d.jsonText("runs.imported_from", ["source"])} = ?`), params.push(source));
1463
+ // The window [startedFrom, startedBefore): a run started at its start is in it, one started at its end is not.
1464
+ if (startedFrom !== undefined)
1465
+ (where.push("runs.started_at >= ?"), params.push(startedFrom));
1466
+ if (startedBefore !== undefined)
1467
+ (where.push("runs.started_at < ?"), params.push(startedBefore));
1468
+ if (model !== undefined)
1469
+ (where.push(runUsedModel(d)), params.push(model));
1398
1470
  where.push(`COALESCE(runs.archived_at, agents.archived_at) IS ${archived ? "NOT NULL" : "NULL"}`, "runs.purged_at IS NULL");
1399
1471
  if (status !== undefined)
1400
1472
  (where.push("runs.list_status = ?"), params.push(status));
@@ -1450,11 +1522,14 @@ class SqliteStore {
1450
1522
  healCost: async (runId, { epoch, endedAt }, { costUsd, costUpperBound }) => {
1451
1523
  if (!Number.isFinite(costUsd) || costUsd < 0)
1452
1524
  throw new TypeError(`a healed cost is a figure of $0 or more (got ${costUsd})`);
1453
- const [result] = await db.write([{
1454
- sql: `UPDATE runs SET cost_usd = ?, cost_upper_bound = ? WHERE id = ? AND ${COST_UNKNOWN} AND epoch = ? AND ended_at = ? RETURNING id`,
1455
- params: [costUsd, costUpperBound ? 1 : 0, runId, epoch, endedAt],
1456
- }]);
1457
- return (result?.rows.length ?? 0) > 0;
1525
+ // Its ledger row is recorded again with it, in the same transaction: the job's cost it reads is the healed one.
1526
+ return db.transaction(async (tx) => {
1527
+ const row = await tx.get(`UPDATE runs SET cost_usd = ?, cost_upper_bound = ? WHERE id = ? AND ${COST_UNKNOWN} AND epoch = ? AND ended_at = ? RETURNING ${RUN_COLUMNS}`, costUsd, costUpperBound ? 1 : 0, runId, epoch, endedAt);
1528
+ if (!row)
1529
+ return false;
1530
+ await recordLedger(tx, runOf(row), now());
1531
+ return true;
1532
+ });
1458
1533
  },
1459
1534
  // The runs healCost may write that the heal's rule (store-view.ts bookedCostOf, healOf) does not refuse by its
1460
1535
  // columns alone, so the start sweep never reads one that cannot heal again at each start: left out are a person's
@@ -1537,6 +1612,9 @@ class SqliteStore {
1537
1612
  const state = JSON.parse(row.proposal)?.state;
1538
1613
  await tx.run("UPDATE learning_proposals SET turn = '{}', proposal = ? WHERE run_id = ? AND round = ?", json(typeof state === "string" ? { state } : {}), runId, row.round);
1539
1614
  }
1615
+ // Its ledger row and every spend row it booked or that audits it, as a remove takes them: what it cost stays on its
1616
+ // tombstone (cost_usd, the metrics' figures), which the readers of money (usage, stats) read; no series shows it.
1617
+ await dropLedger(tx, runId);
1540
1618
  // Its row's content, its metrics cut to their figures and names (tombstoneMetrics), with what its spend's readers
1541
1619
  // read from its journal folded in. Its outcome stays: a code (RunOutcome), never words.
1542
1620
  const metrics = tombstoneMetrics(run.metrics === null ? null : JSON.parse(run.metrics), kept);
@@ -1556,6 +1634,8 @@ class SqliteStore {
1556
1634
  throw new StoreConstraint(`run ${runId} is ${run.state}: only a final run is removed`);
1557
1635
  await dropRunContent(tx, runId);
1558
1636
  await tx.run("DELETE FROM learning_proposals WHERE run_id = ?", runId);
1637
+ // Its ledger row and every spend row it booked or that audits it, as a purge takes them.
1638
+ await dropLedger(tx, runId);
1559
1639
  // Its computers' usage, which a purge keeps (figures, no words).
1560
1640
  await tx.run("DELETE FROM computer_intervals WHERE run_id = ?", runId);
1561
1641
  await tx.run("DELETE FROM runs WHERE id = ?", runId);
@@ -1606,9 +1686,11 @@ class SqliteStore {
1606
1686
  await d.lockRow(tx, "runs", "id", id, "update");
1607
1687
  const at = now();
1608
1688
  const n = storeNow(d, () => at);
1609
- const row = await tx.get(`UPDATE runs SET state = 'failed', summary = ?, ended_at = ?, left_running_at = ${n.sql}, epoch = epoch + 1 WHERE id = ? AND state = 'queued' AND epoch = 0 AND runner IS NULL RETURNING id`, summary, at, ...n.params, id);
1689
+ const row = await tx.get(`UPDATE runs SET state = 'failed', summary = ?, ended_at = ?, left_running_at = ${n.sql}, epoch = epoch + 1 WHERE id = ? AND state = 'queued' AND epoch = 0 AND runner IS NULL RETURNING ${RUN_COLUMNS}`, summary, at, ...n.params, id);
1610
1690
  if (!row)
1611
1691
  return false;
1692
+ // Its ledger row, as an end writes one (applyRunPatch).
1693
+ await recordLedger(tx, runOf(row), at);
1612
1694
  // As an end does: its untaken commands refused, its launch's secrets erased, in this same commit.
1613
1695
  await refuseLeftovers(tx, id, "failed", at, d);
1614
1696
  return true;
@@ -1674,6 +1756,10 @@ class SqliteStore {
1674
1756
  * writes or removes the row, so an owner's save, which drops the mark in the transaction that writes its row
1675
1757
  * (dropTokensMark), never lands in between. */
1676
1758
  const recordJson = readableJson(d, "settings.value");
1759
+ /** A new row's created_at, its two `?` now and three the name's record keys (mcpRecordKeys) then now again: now, or past
1760
+ * every `of` the name's records still hold, even within its millisecond or on a clock stepped back. created_at is the
1761
+ * row's identity (the `of` its records name): a record about an earlier row of the name is never a later row's. */
1762
+ const madeAfterRecords = `${d.greatest}(${d.bigintParam}, COALESCE((SELECT MAX(${d.jsonNumber(recordJson, ["of"])}) FROM settings WHERE settings.key IN (?, ?, ?)), ${d.bigintParam} - 1) + 1)`;
1677
1763
  const tokensMarked = `EXISTS (SELECT 1 FROM settings WHERE settings.key = ? AND ${d.jsonText(recordJson, ["by"])} = 'token' AND ${d.jsonValue(recordJson, ["of"])} = CAST(mcp_servers.created_at AS TEXT))`;
1678
1764
  /** A write of the saved server `name` that the token's mark decides (McpTokensMark, McpOwnersMark): one transaction that
1679
1765
  * first holds the server's lock. SQLite's one writer holds it already; on Postgres it makes the token's statement wait
@@ -1708,7 +1794,8 @@ class SqliteStore {
1708
1794
  const left = sealed !== null && typeof tokenLeftMs === "number" && Number.isFinite(tokenLeftMs) ? tokenLeftMs : null;
1709
1795
  const stamp = clock();
1710
1796
  // updated_at defaults to now (a save or a sign-in); a refresh passes the kept one so it is not read as an edit.
1711
- // listed_at is the tools' listing time, now unless given.
1797
+ // listed_at is the tools' listing time, now unless given. A save's moves past the row's own, in the statement that
1798
+ // writes it (lastEdit), even within its millisecond: a refresh that read the row compares it, and must see the save.
1712
1799
  const updated = updatedAt ?? at;
1713
1800
  const listed = listedAt ?? at;
1714
1801
  // The credential's own time: now for a put that writes one, unless the caller says it kept the sealed one (its
@@ -1720,25 +1807,29 @@ class SqliteStore {
1720
1807
  const statement = expected !== undefined && expected !== null
1721
1808
  ? {
1722
1809
  sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, sealed = ?, refresh_holder = NULL, refresh_until = NULL,
1723
- updated_at = ?, listed_at = ?, credential_changed_at = ?, token_until = ${stamp.sql} + ${d.bigintParam}
1810
+ updated_at = ${lastEdit(updatedAt, "?")}, listed_at = ?, credential_changed_at = ?, token_until = ${stamp.sql} + ${d.bigintParam}
1724
1811
  WHERE name = ? AND auth = ? AND sealed IS ${expected.sealed ? "NOT NULL" : "NULL"} AND ${expected.changedAt === null ? "credential_changed_at IS NULL" : "credential_changed_at = ?"}${tokens ? ` AND ${tokensMarked}` : ""}
1725
1812
  RETURNING ${mcpServerColumnsAt(stamp)}`,
1726
1813
  params: [...values, updated, listed, credentialAt, ...stamp.params, left, name, expected.auth, ...(expected.changedAt === null ? [] : [expected.changedAt]), ...(tokens ? [tokens.record] : []), ...stamp.params],
1727
1814
  }
1728
1815
  : {
1729
- sql: `INSERT INTO mcp_servers (name, url, auth, protocol, tools, prices, server_info, instructions, sealed, created_at, updated_at, listed_at, credential_changed_at, token_until) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ${stamp.sql} + ${d.bigintParam})
1816
+ sql: `INSERT INTO mcp_servers (name, url, auth, protocol, tools, prices, server_info, instructions, sealed, created_at, updated_at, listed_at, credential_changed_at, token_until) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ${madeAfterRecords}, ?, ?, ?, ${stamp.sql} + ${d.bigintParam})
1730
1817
  ON CONFLICT (name) DO UPDATE SET url = excluded.url, auth = excluded.auth, protocol = excluded.protocol, tools = excluded.tools,
1731
- prices = excluded.prices, server_info = excluded.server_info, instructions = excluded.instructions, sealed = excluded.sealed, refresh_holder = NULL, refresh_until = NULL, updated_at = excluded.updated_at, listed_at = excluded.listed_at, credential_changed_at = excluded.credential_changed_at, token_until = excluded.token_until
1818
+ prices = excluded.prices, server_info = excluded.server_info, instructions = excluded.instructions, sealed = excluded.sealed, refresh_holder = NULL, refresh_until = NULL, updated_at = ${lastEdit(updatedAt, "excluded.updated_at")}, listed_at = excluded.listed_at, credential_changed_at = excluded.credential_changed_at, token_until = excluded.token_until
1732
1819
  ${expected === null ? "WHERE 1 = 0" : ""}
1733
1820
  RETURNING ${mcpServerColumnsAt(stamp)}`,
1734
- params: [name, ...values, at, updated, listed, credentialAt, ...stamp.params, left, ...stamp.params],
1821
+ params: [name, ...values, at, ...mcpRecordKeys(name), at, updated, listed, credentialAt, ...stamp.params, left, ...stamp.params],
1735
1822
  };
1736
1823
  const written = await writeMcpRow(name, statement, tokens, owns);
1737
1824
  return written && mcpServerOf(written);
1738
1825
  };
1826
+ /** A server row's updated_at as a write sets it to `value` (SQL): kept as given when the caller passes the one it read
1827
+ * (`given`, a refresh: not an edit), else past the row's own (mcp_servers.updated_at, the row before the write) by at
1828
+ * least 1 ms, so two saves in one millisecond are still two edits a compare-and-set tells apart. */
1829
+ const lastEdit = (given, value) => (given === undefined ? `${d.greatest}(${value}, mcp_servers.updated_at + 1)` : value);
1739
1830
  /** `statement`, the write of server `name`'s row, answering the row it wrote (RETURNING): alone, or, when the token's mark
1740
1831
  * decides it (`tokens`, `owns`), in one transaction under the server's lock (underMcpLock), the owner's dropping the
1741
- * mark once its row is written and only then. */
1832
+ * mark once its row is written and only then, the token's first save writing its record (`tokens.made`) there too. */
1742
1833
  const writeMcpRow = async (name, statement, tokens, owns) => {
1743
1834
  if (!tokens && !owns)
1744
1835
  return (await db.write([statement]))[0].rows[0];
@@ -1746,6 +1837,10 @@ class SqliteStore {
1746
1837
  const row = (await tx.step(statement)).rows[0];
1747
1838
  if (row && owns)
1748
1839
  await dropTokensMark(tx, owns, mcpServerOf(row).createdAt);
1840
+ if (row && tokens?.made) {
1841
+ const encoded = json(tokens.made(mcpServerOf(row)));
1842
+ await tx.run("INSERT INTO settings (key, value, connector_id, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value, connector_id = excluded.connector_id, updated_at = excluded.updated_at", tokens.record, encoded, nativeCommandOwner(tokens.record, encoded), now());
1843
+ }
1749
1844
  return row;
1750
1845
  });
1751
1846
  };
@@ -1757,16 +1852,19 @@ class SqliteStore {
1757
1852
  this.mcp = {
1758
1853
  put: async (row) => (await putServer(row, undefined)),
1759
1854
  putIfCredential: (row, expected, tokens, owns) => putServer(row, expected, tokens, owns),
1760
- // One statement compares the credential and writes, as keepRefreshed: no read between, so a refresh's keep never lands
1761
- // in a gap and is then written over. The credential's columns and the refresh lease are not in its SET.
1855
+ // One statement compares the row as read (its credential, address, auth type and last edit) and writes, as
1856
+ // keepRefreshed: no read between, so a refresh's keep never lands in a gap and is then written over, and a save with no
1857
+ // credential (the sealed column the same after it), whether it moved the row or only repriced it, is never written
1858
+ // back over: every save moves updated_at, past the row's own even within its millisecond (lastEdit). The credential's
1859
+ // columns and the refresh lease are not in its SET.
1762
1860
  rewrite: async ({ name, url, auth, protocol = null, tools, prices = null, serverInfo = null, instructions = null, listedAt, updatedAt }, seen, owns) => {
1763
1861
  const at = now();
1764
1862
  const stamp = clock();
1765
1863
  const row = await writeMcpRow(name, {
1766
- sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, updated_at = ?, listed_at = ?
1767
- WHERE name = ? AND ${d.nullSafeEquals("sealed")}
1864
+ sql: `UPDATE mcp_servers SET url = ?, auth = ?, protocol = ?, tools = ?, prices = ?, server_info = ?, instructions = ?, updated_at = ${lastEdit(updatedAt, "?")}, listed_at = ?
1865
+ WHERE name = ? AND ${d.nullSafeEquals("sealed")} AND url = ? AND auth = ? AND updated_at = ?
1768
1866
  RETURNING ${mcpServerColumnsAt(stamp)}`,
1769
- params: [url, auth, protocol, json(tools), json(prices), serverInfo === null ? null : json(serverInfo), instructions, updatedAt ?? at, listedAt ?? at, name, seen, ...stamp.params],
1867
+ params: [url, auth, protocol, json(tools), json(prices), serverInfo === null ? null : json(serverInfo), instructions, updatedAt ?? at, listedAt ?? at, name, seen.sealed, seen.url, seen.auth, seen.updatedAt, ...stamp.params],
1770
1868
  }, undefined, owns);
1771
1869
  return row && mcpServerOf(row);
1772
1870
  },
@@ -1928,6 +2026,38 @@ class SqliteStore {
1928
2026
  return kept?.state === "proposed" ? [] : [{ agentId: row.agent_id, at: row.created_at, costUsd: 0 }];
1929
2027
  });
1930
2028
  },
2029
+ ledger: async (agentId, runIds) => {
2030
+ if (runIds !== undefined && runIds.length === 0)
2031
+ return { rows: [], spend: [] };
2032
+ const list = runIds === undefined ? "" : runIds.map(() => "?").join(", ");
2033
+ const rowsOf = runIds === undefined ? { sql: "", params: [] } : { sql: ` AND run_id IN (${list})`, params: [...runIds] };
2034
+ const spendOf = runIds === undefined ? { sql: "", params: [] } : { sql: ` AND (run_id IN (${list}) OR of_run IN (${list}))`, params: [...runIds, ...runIds] };
2035
+ const text = "CAST(NULL AS TEXT)", whole = "CAST(NULL AS BIGINT)", usd = "CAST(NULL AS DOUBLE PRECISION)";
2036
+ const parts = await db.all(`SELECT 'row' AS part, run_id, agent_id, started_at, path, workflow, digest, not_served, job_usd, look_back_usd, cost, workflow_calls, ${text} AS kind, ${whole} AS round, ${text} AS of_run, ${usd} AS usd
2037
+ FROM learning_ledger WHERE agent_id = ?${rowsOf.sql}
2038
+ UNION ALL
2039
+ SELECT 'spend' AS part, run_id, agent_id, ${whole}, ${text}, workflow, digest, ${text}, ${usd}, ${usd}, ${text}, ${text}, kind, round, of_run, usd
2040
+ FROM learning_spend WHERE agent_id = ?${spendOf.sql}`, agentId, ...rowsOf.params, agentId, ...spendOf.params);
2041
+ const usdOf = (value) => (value === null ? null : Number(value));
2042
+ const rows = parts.filter((one) => one.part === "row").map((row) => ({
2043
+ runId: row.run_id, agentId: row.agent_id, startedAt: Number(row.started_at), path: row.path, workflow: row.workflow, digest: row.digest,
2044
+ notServed: row.not_served, jobUsd: usdOf(row.job_usd), lookBackUsd: usdOf(row.look_back_usd), cost: row.cost,
2045
+ // Its calls as its end wrote them (record), each checked again as read.
2046
+ workflowCalls: workflowCallsIn({ workflow_calls: JSON.parse(row.workflow_calls ?? "[]") }),
2047
+ }));
2048
+ const spend = parts.filter((one) => one.part === "spend").map((row) => ({
2049
+ runId: row.run_id, round: Number(row.round), agentId: row.agent_id, kind: row.kind, ofRun: row.of_run, workflow: row.workflow, digest: row.digest, usd: usdOf(row.usd),
2050
+ }));
2051
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
2052
+ return {
2053
+ rows: rows.sort((a, b) => a.startedAt - b.startedAt || byText(a.runId, b.runId)),
2054
+ spend: spend.sort((a, b) => byText(a.runId, b.runId) || byText(a.kind, b.kind) || a.round - b.round),
2055
+ };
2056
+ },
2057
+ byHandBefore: async (agentId, before, limit) => {
2058
+ const rows = await db.all(BY_HAND_BEFORE, agentId, before.startedAt, before.id, limit);
2059
+ return rows.map((row) => ({ id: row.run_id, startedAt: Number(row.started_at), jobUsd: Number(row.job_usd) }));
2060
+ },
1931
2061
  };
1932
2062
  this.settings = {
1933
2063
  get: async (key) => {
@@ -1938,7 +2068,7 @@ class SqliteStore {
1938
2068
  const encoded = json(value);
1939
2069
  await db.write([{ sql: "INSERT INTO settings (key, value, connector_id, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value, connector_id = excluded.connector_id, updated_at = excluded.updated_at", params: [key, encoded, nativeCommandOwner(key, encoded), now()] }]);
1940
2070
  },
1941
- putIfAbsent: async (key, value, capacity) => {
2071
+ putIfAbsent: async (key, value, capacity, claim) => {
1942
2072
  const encoded = json(value);
1943
2073
  if (capacity !== undefined) {
1944
2074
  if (typeof capacity.prefix !== "string" || !capacity.prefix || capacity.prefix.includes("\0") || !key.startsWith(capacity.prefix) || !Number.isSafeInteger(capacity.limit) || capacity.limit < 1)
@@ -1947,6 +2077,9 @@ class SqliteStore {
1947
2077
  // SQLite holds its writer lock already; Postgres holds this schema's prefix lock until commit. The count
1948
2078
  // and insertion cannot interleave with another bounded insertion, even through an independent store handle.
1949
2079
  await d.lockKey(tx, `settings.capacity:${capacity.prefix}`);
2080
+ // Settings precede the run's claim lock, as in replaceIf.
2081
+ if (claim)
2082
+ await underClaim(tx, claim, now);
1950
2083
  const existing = await tx.get("SELECT value FROM settings WHERE key = ?", key);
1951
2084
  if (existing !== undefined)
1952
2085
  return JSON.parse(existing.value);
@@ -1968,6 +2101,14 @@ class SqliteStore {
1968
2101
  return saved === undefined ? undefined : JSON.parse(saved.value);
1969
2102
  });
1970
2103
  }
2104
+ // Under a claim: the claim's fence and the insert in one transaction, so a claim that lost the run writes nothing.
2105
+ if (claim)
2106
+ return db.transaction(async (tx) => {
2107
+ const at = await underClaim(tx, claim, now);
2108
+ await tx.run("INSERT INTO settings (key, value, connector_id, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO NOTHING", key, encoded, nativeCommandOwner(key, encoded), at);
2109
+ const saved = await tx.get("SELECT value FROM settings WHERE key = ?", key);
2110
+ return saved === undefined ? undefined : JSON.parse(saved.value);
2111
+ });
1971
2112
  await db.write([{ sql: "INSERT INTO settings (key, value, connector_id, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT (key) DO NOTHING", params: [key, encoded, nativeCommandOwner(key, encoded), now()] }]);
1972
2113
  const row = await db.get("SELECT value FROM settings WHERE key = ?", key);
1973
2114
  return row === undefined ? undefined : JSON.parse(row.value);
@@ -2797,7 +2938,11 @@ class SqliteStore {
2797
2938
  VALUES (?, ?, ?, ?, 0, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING ${this.#db.dialect.insertedRow} AS inserted_rowid, ${RUN_COLUMNS}`, run.id, run.agentId, run.revisionId, state, run.costUsd ?? null, run.metrics === undefined || run.metrics === null ? null : json(run.metrics), run.summary ?? null, run.outcome ?? null, JSON.stringify(run.importedFrom), launchDiskOf(run.launch), run.startedAt, run.endedAt ?? at);
2798
2939
  await writeLaunch(tx, run.id, run.launch, at);
2799
2940
  await new RunStorage(this.#db, { runId: run.id, epoch: 0 }, this.#now).applyIn(tx, run.transcript, row.inserted_rowid ?? "this-transaction");
2800
- return runOf(row);
2941
+ // Its ledger row, as an end writes one (applyRunPatch), in this same commit.
2942
+ const imported = runOf(row);
2943
+ if (FINAL_STATES.includes(imported.state))
2944
+ await recordLedger(tx, imported, at);
2945
+ return imported;
2801
2946
  });
2802
2947
  }
2803
2948
  async take(claim, commandId, outcome = "taken", reason) {
@@ -21,9 +21,7 @@ import { migrationsIn, runnerFloorOf, runnerOn } from "./postgres/migrate.js";
21
21
  import { STORE_CONNECT_TIMEOUT_MS } from "./postgres/connection.js";
22
22
  import { storePlace, storeTarget } from "./open.js";
23
23
  import { SCHEMA_VERSION } from "./schema.js";
24
- import { earlierVersionIn, runnerWaitsFor, STORE_FILE } from "./sqlite/store.js";
25
- /** The SQLite store's versions the server upgrades in place (sqlite/store.ts openSqliteStore). */
26
- const SQLITE_UPGRADES = new Set([11, 12, 13, 14]);
24
+ import { earlierVersionIn, runnerWaitsFor, SQLITE_UPGRADES, STORE_FILE } from "./sqlite/store.js";
27
25
  /** What a build that knows `build` does with a store at `state`, on `kind`. `earlier`: the data directory holds an earlier
28
26
  * version's files (SQLite only), which this build's server refuses to start beside (StoreFromEarlierVersion). `awaits`:
29
27
  * on SQLite at this build's version, a column this build's runner needs that the file lacks (SQLITE_RUNNER_NEEDS), which
@@ -34,7 +32,8 @@ export function storeSchemaReport(target, state, build, earlier = false, awaits
34
32
  ? "refuses"
35
33
  : version === null ? "sets up" : version === build ? "opens" : version > build ? "refuses" : target.kind === "postgres" || SQLITE_UPGRADES.has(version) ? "migrates" : "refuses";
36
34
  // A SQLite runner opens only its own version: its floor is the version (sqlite/store.ts schemaState).
37
- // On SQLite a runner waits only for a version its server upgrades in place (11-14), and refuses any other earlier one.
35
+ // On SQLite a runner waits only for a version its server upgrades in place (SQLITE_UPGRADES), and refuses any other
36
+ // earlier one.
38
37
  const runner = target.kind === "sqlite" && version !== null && version < build && !SQLITE_UPGRADES.has(version)
39
38
  ? "refused"
40
39
  : awaits && version === build ? "waits" : runnerOn(target.kind === "sqlite" ? { version, runnerFloor: version } : state, build);