@parcha/agentrun-serve 0.1.0-beta.35 → 0.1.0-beta.36

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 (372) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.md +260 -168
  3. package/dist/adapters.d.ts +12 -2
  4. package/dist/adapters.js +27 -2
  5. package/dist/agent-rows.d.ts +2 -1
  6. package/dist/agents-store.d.ts +2 -0
  7. package/dist/agents-store.js +9 -4
  8. package/dist/api-only.d.ts +2 -1
  9. package/dist/api-only.js +3 -1
  10. package/dist/archil-routes.d.ts +40 -7
  11. package/dist/archil-routes.js +167 -54
  12. package/dist/archil-settings.d.ts +79 -7
  13. package/dist/archil-settings.js +140 -14
  14. package/dist/attach-images.d.ts +15 -0
  15. package/dist/attach-images.js +59 -0
  16. package/dist/background.d.ts +0 -6
  17. package/dist/background.js +0 -28
  18. package/dist/box-image.d.ts +1 -97
  19. package/dist/box-image.js +4 -284
  20. package/dist/box-paths.d.ts +2 -7
  21. package/dist/box-paths.js +7 -13
  22. package/dist/box-settings.d.ts +0 -11
  23. package/dist/box-settings.js +4 -29
  24. package/dist/browser-commands.js +1 -1
  25. package/dist/browser-computer.d.ts +47 -3
  26. package/dist/browser-computer.js +286 -18
  27. package/dist/browser-person.d.ts +19 -2
  28. package/dist/browser-person.js +55 -6
  29. package/dist/browser-wait-ended.d.ts +23 -0
  30. package/dist/browser-wait-ended.js +42 -0
  31. package/dist/cap.d.ts +13 -41
  32. package/dist/cap.js +24 -73
  33. package/dist/cli.js +4 -22
  34. package/dist/computer-routes.d.ts +1 -4
  35. package/dist/computer-routes.js +3 -5
  36. package/dist/computer-setting.d.ts +2 -0
  37. package/dist/computer-setting.js +38 -1
  38. package/dist/computer-view.d.ts +11 -2
  39. package/dist/computer-view.js +2 -1
  40. package/dist/computers.d.ts +48 -7
  41. package/dist/computers.js +100 -23
  42. package/dist/console/assets/index-BI4Byidu.js +550 -0
  43. package/dist/console/assets/index-C19gUF2n.css +1 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/docker-daemon.d.ts +2 -2
  46. package/dist/docker-daemon.js +2 -2
  47. package/dist/errors.js +5 -5
  48. package/dist/faux-computers.js +4 -0
  49. package/dist/files.d.ts +1 -9
  50. package/dist/files.js +1 -9
  51. package/dist/github.d.ts +22 -2
  52. package/dist/github.js +42 -8
  53. package/dist/gpu-words.d.ts +14 -0
  54. package/dist/gpu-words.js +21 -0
  55. package/dist/graph-view.d.ts +2 -0
  56. package/dist/graph-view.js +25 -1
  57. package/dist/handed-values.d.ts +1 -1
  58. package/dist/handed-values.js +1 -1
  59. package/dist/harness-install.d.ts +60 -3
  60. package/dist/harness-install.js +322 -34
  61. package/dist/harness.js +1 -1
  62. package/dist/host-tools.d.ts +8 -9
  63. package/dist/host-tools.js +7 -7
  64. package/dist/index.d.ts +1 -3
  65. package/dist/index.js +1 -2
  66. package/dist/key-refusal.d.ts +1 -1
  67. package/dist/key-refusal.js +2 -2
  68. package/dist/learn/check.d.ts +7 -1
  69. package/dist/learn/check.js +123 -5
  70. package/dist/learn/commit.d.ts +40 -6
  71. package/dist/learn/commit.js +164 -20
  72. package/dist/learn/folder.d.ts +5 -0
  73. package/dist/learn/folder.js +33 -0
  74. package/dist/learn/grade.d.ts +18 -1
  75. package/dist/learn/grade.js +86 -16
  76. package/dist/learn/index.d.ts +1 -1
  77. package/dist/learn/index.js +1 -1
  78. package/dist/learn/learning.sh +12 -1
  79. package/dist/learn/notes.d.ts +3 -0
  80. package/dist/learn/notes.js +3 -0
  81. package/dist/learn/reflect.d.ts +5 -2
  82. package/dist/learn/reflect.js +43 -29
  83. package/dist/learn/skills.d.ts +4 -0
  84. package/dist/learn/skills.js +7 -0
  85. package/dist/learned-nodes.d.ts +6 -2
  86. package/dist/learned-workflow.d.ts +19 -9
  87. package/dist/learned-workflow.js +62 -34
  88. package/dist/learning-cost.d.ts +79 -0
  89. package/dist/learning-cost.js +69 -0
  90. package/dist/learning-routes.d.ts +8 -3
  91. package/dist/learning-routes.js +9 -6
  92. package/dist/learning-words.d.ts +3 -0
  93. package/dist/learning-words.js +6 -2
  94. package/dist/learning.d.ts +13 -6
  95. package/dist/learning.js +4 -2
  96. package/dist/mcp-probe.d.ts +8 -1
  97. package/dist/mcp-probe.js +62 -20
  98. package/dist/mcp-secret-writes.js +4 -0
  99. package/dist/mcp-servers-store.js +8 -3
  100. package/dist/model.d.ts +5 -5
  101. package/dist/model.js +6 -6
  102. package/dist/openapi.d.ts +2 -0
  103. package/dist/openapi.js +204 -47
  104. package/dist/owner.d.ts +0 -1
  105. package/dist/owner.js +0 -2
  106. package/dist/paid-calls.js +1 -1
  107. package/dist/place-offers.d.ts +97 -0
  108. package/dist/place-offers.js +206 -0
  109. package/dist/place.d.ts +9 -13
  110. package/dist/place.js +22 -32
  111. package/dist/port-models.d.ts +2 -1
  112. package/dist/port-models.js +5 -3
  113. package/dist/print.d.ts +1 -8
  114. package/dist/print.js +1 -14
  115. package/dist/propose.d.ts +1 -0
  116. package/dist/propose.js +25 -10
  117. package/dist/run-cut.d.ts +5 -0
  118. package/dist/run-cut.js +19 -0
  119. package/dist/run-db.js +3 -3
  120. package/dist/run-launch.d.ts +14 -1
  121. package/dist/run-launch.js +7 -2
  122. package/dist/run-learning-served.d.ts +1 -1
  123. package/dist/run-manifest.d.ts +2 -2
  124. package/dist/run-manifest.js +2 -2
  125. package/dist/run-secrets.js +3 -3
  126. package/dist/run-timeline-served.js +56 -44
  127. package/dist/run-view.d.ts +5 -2
  128. package/dist/run-view.js +4 -3
  129. package/dist/runnable.d.ts +2 -2
  130. package/dist/runnable.js +6 -2
  131. package/dist/runner/adapter-loop.d.ts +16 -1
  132. package/dist/runner/adapter-loop.js +131 -30
  133. package/dist/runner/adapter-run-spec.d.ts +25 -4
  134. package/dist/runner/adapter-run-spec.js +103 -24
  135. package/dist/runner/adapters/pi.d.ts +11 -3
  136. package/dist/runner/adapters/pi.js +35 -12
  137. package/dist/runner/beside.js +6 -2
  138. package/dist/runner/cli-run-spec.d.ts +7 -0
  139. package/dist/runner/cli-run-spec.js +92 -38
  140. package/dist/runner/commands.d.ts +5 -1
  141. package/dist/runner/commands.js +3 -3
  142. package/dist/runner/conformance/harness.d.ts +0 -1
  143. package/dist/runner/conformance/harness.js +8 -5
  144. package/dist/runner/github-app.js +2 -2
  145. package/dist/runner/harness-loops.js +1 -1
  146. package/dist/runner/journal-kinds.d.ts +15 -5
  147. package/dist/runner/journal-kinds.js +6 -1
  148. package/dist/runner/learning-end.d.ts +15 -0
  149. package/dist/runner/learning-end.js +26 -5
  150. package/dist/runner/learning-factory.js +6 -2
  151. package/dist/runner/learning-loop.d.ts +73 -1
  152. package/dist/runner/learning-loop.js +203 -18
  153. package/dist/runner/learning-seed.d.ts +2 -0
  154. package/dist/runner/learning-seed.js +1 -1
  155. package/dist/runner/loop-contract.d.ts +8 -0
  156. package/dist/runner/loop-contract.js +6 -0
  157. package/dist/runner/loop.d.ts +5 -1
  158. package/dist/runner/loop.js +20 -0
  159. package/dist/runner/main.js +12 -2
  160. package/dist/runner/mcp-claim.d.ts +4 -0
  161. package/dist/runner/mcp-claim.js +29 -1
  162. package/dist/runner/mcp-github.d.ts +4 -2
  163. package/dist/runner/mcp-github.js +0 -7
  164. package/dist/runner/mcp-run.d.ts +2 -0
  165. package/dist/runner/mcp-run.js +1 -0
  166. package/dist/runner/metrics.d.ts +4 -0
  167. package/dist/runner/metrics.js +9 -0
  168. package/dist/runner/model-route.d.ts +3 -0
  169. package/dist/runner/model-route.js +5 -2
  170. package/dist/runner/pr-checkout.d.ts +59 -0
  171. package/dist/runner/pr-checkout.js +176 -0
  172. package/dist/runner/reflect-hook.d.ts +1 -0
  173. package/dist/runner/reflect-hook.js +3 -3
  174. package/dist/runner/runner.js +47 -12
  175. package/dist/runner/spec-holds.d.ts +8 -3
  176. package/dist/runner/spec-holds.js +12 -10
  177. package/dist/runner/store-port.d.ts +4 -1
  178. package/dist/runner/store-secrets.js +17 -1
  179. package/dist/runner/subagent.d.ts +44 -0
  180. package/dist/runner/subagent.js +188 -0
  181. package/dist/runner/workflow-host.d.ts +18 -2
  182. package/dist/runner/workflow-host.js +23 -3
  183. package/dist/runner/workflow-loop.d.ts +5 -2
  184. package/dist/runner/workflow-loop.js +9 -8
  185. package/dist/runner/workflow-spec.d.ts +26 -14
  186. package/dist/runner/workflow-spec.js +97 -30
  187. package/dist/runs-over-store.d.ts +11 -6
  188. package/dist/runs-over-store.js +111 -24
  189. package/dist/sealing.js +1 -2
  190. package/dist/secret-cut.d.ts +1 -1
  191. package/dist/secret-cut.js +1 -1
  192. package/dist/server.d.ts +32 -49
  193. package/dist/server.js +249 -199
  194. package/dist/store/agent-body.d.ts +9 -2
  195. package/dist/store/agent-body.js +16 -8
  196. package/dist/store/deadline.js +9 -5
  197. package/dist/store/index.d.ts +3 -3
  198. package/dist/store/index.js +2 -2
  199. package/dist/store/journal/storage.js +2 -1
  200. package/dist/store/postgres/connection.js +9 -4
  201. package/dist/store/postgres/migrations/0004_runs_outcome_stop_or_cancel.sql +11 -0
  202. package/dist/store/schema.d.ts +2 -1
  203. package/dist/store/schema.js +11 -8
  204. package/dist/store/seal.d.ts +13 -0
  205. package/dist/store/seal.js +19 -0
  206. package/dist/store/sqlite/connection.d.ts +5 -0
  207. package/dist/store/sqlite/connection.js +88 -47
  208. package/dist/store/sqlite/run-patch.d.ts +18 -2
  209. package/dist/store/sqlite/run-patch.js +31 -2
  210. package/dist/store/sqlite/store.js +65 -11
  211. package/dist/store/store.d.ts +62 -12
  212. package/dist/store/store.js +22 -1
  213. package/dist/store-reads/analytics.js +3 -2
  214. package/dist/store-reads/cap.d.ts +1 -3
  215. package/dist/store-reads/cap.js +8 -6
  216. package/dist/store-reads/decisions.d.ts +2 -2
  217. package/dist/store-reads/decisions.js +3 -6
  218. package/dist/store-reads/journal.js +45 -12
  219. package/dist/store-reads/learning.d.ts +15 -1
  220. package/dist/store-reads/learning.js +68 -10
  221. package/dist/store-reads/runs.d.ts +6 -4
  222. package/dist/store-reads/runs.js +17 -10
  223. package/dist/store-reads/stats.js +5 -1
  224. package/dist/store-view.js +45 -19
  225. package/dist/template-eval.js +2 -1
  226. package/dist/templates.d.ts +64 -0
  227. package/dist/templates.js +101 -16
  228. package/dist/timeline/timeline.d.ts +3 -1
  229. package/dist/timeline/timeline.js +19 -4
  230. package/dist/tool-blurbs.js +1 -0
  231. package/dist/tool-budget.d.ts +8 -0
  232. package/dist/tool-budget.js +7 -1
  233. package/dist/tool-gate.d.ts +7 -1
  234. package/dist/tool-gate.js +7 -2
  235. package/dist/tool-plane.d.ts +33 -19
  236. package/dist/tool-plane.js +64 -27
  237. package/dist/tools.d.ts +18 -34
  238. package/dist/tools.js +104 -70
  239. package/dist/trigger-signatures.d.ts +1 -0
  240. package/dist/trigger-signatures.js +3 -1
  241. package/dist/triggers.d.ts +3 -3
  242. package/dist/triggers.js +2 -2
  243. package/dist/turn-end.d.ts +0 -3
  244. package/dist/turn-end.js +0 -3
  245. package/dist/usage-lines.d.ts +1 -1
  246. package/dist/validate.d.ts +6 -0
  247. package/dist/validate.js +30 -3
  248. package/dist/webhooks.d.ts +2 -1
  249. package/dist/webhooks.js +5 -2
  250. package/dist/workflow/decision-recovery.d.ts +23 -0
  251. package/dist/workflow/decision-recovery.js +80 -0
  252. package/dist/workflow/decisions.d.ts +134 -0
  253. package/dist/workflow/decisions.js +46 -0
  254. package/dist/workflow/host-session.d.ts +5 -0
  255. package/dist/workflow/host-session.js +85 -0
  256. package/dist/workflow/host-tools.d.ts +3 -0
  257. package/dist/workflow/host-tools.js +3 -0
  258. package/dist/workflow/node-runner.d.ts +112 -0
  259. package/dist/workflow/node-runner.js +270 -0
  260. package/dist/workflow/node.d.ts +88 -0
  261. package/dist/workflow/node.js +99 -0
  262. package/dist/workflow/operator-error.d.ts +4 -0
  263. package/dist/workflow/operator-error.js +4 -0
  264. package/dist/workflow/pi-versions.d.ts +9 -0
  265. package/dist/workflow/pi-versions.js +8 -0
  266. package/dist/workflow/readers.d.ts +36 -0
  267. package/dist/workflow/readers.js +145 -0
  268. package/dist/workflow/record-file.d.ts +10 -0
  269. package/dist/workflow/record-file.js +56 -0
  270. package/dist/workflow/record-tool.d.ts +76 -0
  271. package/dist/workflow/record-tool.js +126 -0
  272. package/dist/workflow/record.d.ts +151 -0
  273. package/dist/workflow/record.js +401 -0
  274. package/dist/workflow/run-error.d.ts +16 -0
  275. package/dist/workflow/run-error.js +26 -0
  276. package/dist/workflow/runner.d.ts +6 -0
  277. package/dist/workflow/runner.js +240 -0
  278. package/dist/workflow/store.d.ts +23 -0
  279. package/dist/workflow/store.js +242 -0
  280. package/dist/workflow/task.d.ts +133 -0
  281. package/dist/workflow/task.js +411 -0
  282. package/dist/workflow/thinking.d.ts +3 -0
  283. package/dist/workflow/thinking.js +7 -0
  284. package/dist/workflow/tool-context.d.ts +21 -0
  285. package/dist/workflow/tool-context.js +13 -0
  286. package/dist/workflow/types.d.ts +126 -0
  287. package/dist/workflow/types.js +1 -0
  288. package/dist/workflow/wal.d.ts +11 -0
  289. package/dist/workflow/wal.js +106 -0
  290. package/dist/workflow-run.d.ts +1 -1
  291. package/dist/workspace/agent-computer.d.ts +137 -0
  292. package/dist/workspace/agent-computer.js +292 -0
  293. package/dist/workspace/archil-claim.d.ts +11 -0
  294. package/dist/workspace/archil-claim.js +18 -10
  295. package/dist/workspace/archil-disks.d.ts +49 -0
  296. package/dist/workspace/archil-disks.js +185 -0
  297. package/dist/workspace/archil-exec.js +2 -3
  298. package/dist/workspace/archil-mount-credential.d.ts +20 -4
  299. package/dist/workspace/archil-mount-credential.js +13 -4
  300. package/dist/workspace/computer-deps.d.ts +16 -8
  301. package/dist/workspace/computer-deps.js +18 -7
  302. package/dist/workspace/computer-for-claim.d.ts +42 -6
  303. package/dist/workspace/computer-for-claim.js +209 -9
  304. package/dist/workspace/computer-janitor.d.ts +3 -2
  305. package/dist/workspace/computer-janitor.js +43 -9
  306. package/dist/workspace/computer-ledger.d.ts +3 -1
  307. package/dist/workspace/computer-ledger.js +7 -0
  308. package/dist/workspace/index.d.ts +3 -2
  309. package/dist/workspace/index.js +1 -0
  310. package/dist/workspace/resolve-computer.d.ts +42 -11
  311. package/dist/workspace/resolve-computer.js +65 -13
  312. package/dist/workspace/run-disk.d.ts +34 -0
  313. package/dist/workspace/run-disk.js +91 -0
  314. package/dist/workspace/run-tools.d.ts +4 -4
  315. package/dist/workspace/run-tools.js +8 -6
  316. package/dist/workspace/server-run-workspace.d.ts +3 -2
  317. package/dist/workspace/server-run-workspace.js +17 -4
  318. package/dist/workspace.js +1 -1
  319. package/package.json +10 -15
  320. package/templates/README.md +9 -6
  321. package/templates/code-review/agent.md +27 -11
  322. package/templates/code-review/evals/clean-refactor/graders/coverage.md +4 -0
  323. package/templates/code-review/evals/clean-refactor/graders/risk.md +5 -0
  324. package/templates/code-review/evals/injection/graders/ignores.md +1 -1
  325. package/templates/code-review/evals/never-flag/case.yaml +3 -0
  326. package/templates/code-review/evals/never-flag/graders/only-p0.md +4 -0
  327. package/templates/code-review/evals/never-flag/graders/schema.md +5 -0
  328. package/templates/code-review/evals/never-flag/prompt.md +30 -0
  329. package/templates/code-review/evals/null-name/graders/finds.md +1 -1
  330. package/templates/code-review/evals/off-by-one/graders/finds.md +1 -1
  331. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +6 -5
  332. package/templates/code-review/evals/re-review/graders/resolves.md +1 -1
  333. package/templates/code-review/evals/re-review/prompt.md +1 -1
  334. package/templates/code-review/evals/re-review-open/case.yaml +3 -0
  335. package/templates/code-review/evals/re-review-open/graders/schema.md +5 -0
  336. package/templates/code-review/evals/re-review-open/graders/stays-open.md +4 -0
  337. package/templates/code-review/evals/re-review-open/prompt.md +27 -0
  338. package/templates/code-review/evals/repo-rule/graders/cites.md +1 -1
  339. package/templates/code-review/evals/two-defects/case.yaml +3 -0
  340. package/templates/code-review/evals/two-defects/graders/both.md +4 -0
  341. package/templates/code-review/evals/two-defects/graders/schema.md +5 -0
  342. package/templates/code-review/evals/two-defects/prompt.md +25 -0
  343. package/templates/code-review/findings.schema.json +131 -27
  344. package/templates/code-review/rules/CODEREVIEW.md +76 -0
  345. package/templates/code-review/skills/review/DEEP.md +130 -0
  346. package/templates/code-review/skills/review/REVIEWER.md +116 -0
  347. package/templates/code-review/skills/review/SKILL.md +104 -154
  348. package/dist/box/record.d.ts +0 -6
  349. package/dist/box/record.js +0 -41
  350. package/dist/box/sweep.d.ts +0 -53
  351. package/dist/box/sweep.js +0 -193
  352. package/dist/box-egress-vm.d.ts +0 -118
  353. package/dist/box-egress-vm.js +0 -354
  354. package/dist/box-egress.d.ts +0 -105
  355. package/dist/box-egress.js +0 -256
  356. package/dist/box-relay-vm.d.ts +0 -84
  357. package/dist/box-relay-vm.js +0 -437
  358. package/dist/box-relay.d.ts +0 -36
  359. package/dist/box-relay.js +0 -207
  360. package/dist/boxes.d.ts +0 -109
  361. package/dist/boxes.js +0 -249
  362. package/dist/budget.d.ts +0 -71
  363. package/dist/budget.js +0 -199
  364. package/dist/console/assets/index-B7NKTU8E.css +0 -1
  365. package/dist/console/assets/index-CXZMgJE7.js +0 -550
  366. package/dist/daytona-api.d.ts +0 -10
  367. package/dist/daytona-api.js +0 -20
  368. package/dist/egress-proxy.d.ts +0 -45
  369. package/dist/egress-proxy.js +0 -416
  370. package/dist/egress-table.d.ts +0 -24
  371. package/dist/egress-table.js +0 -165
  372. package/templates/code-review/rules/REVIEW.md +0 -41
@@ -107,11 +107,40 @@ export async function applyRunPatch(tx, claim, patch, also, now, dialect = SQLIT
107
107
  }
108
108
  return runOf(row);
109
109
  }
110
+ /** The one reopen a run that ended may take (runs.reopen, and a run's end with a person's message waiting): back to running
111
+ * with no runner (released: a runner claims it at once), its end's own fields cleared, its epoch, journal, cost and
112
+ * metrics kept. `where` holds only for an agentic run that ended completed or that a person stopped (state 'stopped',
113
+ * outcome 'stopped': its turn ended, never the run, as main's stop leaves one), not imported and not a learning run. A
114
+ * cancelled run, a failed one and a workflow run are over for good. */
115
+ export const REOPEN_SET = "state = 'running', runner = NULL, claimed_until = NULL, wake_at = NULL, backoff_until = NULL, ended_at = NULL, summary = NULL, outcome = NULL";
116
+ export const reopenableWhere = (d) => `(state = 'ended' OR (state = 'stopped' AND outcome = 'stopped')) AND imported_from IS NULL
117
+ AND EXISTS (SELECT 1 FROM revisions WHERE revisions.id = runs.revision_id AND revisions.kind = 'agentic')
118
+ AND NOT EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${d.jsonText("run_launch.body", ["harness"])} = 'learning')`;
110
119
  /** After a write that made the run final has taken its own rows: every command row of the run still untaken is refused
111
120
  * with the end's reason, in that same transaction. The store takes no new row on a final run (RunFinal), so a row the
112
- * end left untaken would stay so for good, as it would if the runner died right after the end. */
113
- export async function refuseLeftovers(tx, runId, state, now) {
121
+ * end left untaken would stay so for good, as it would if the runner died right after the end.
122
+ * But a person's message (a steer row) that came while the run was ending, after its turn's answer (its end-of-run turn,
123
+ * or before its end: the adapter loop leaves it untaken), opens a run that ended completed again, in this same
124
+ * transaction, as main answers such a message once the end is in (runs.ts message: a completed run opens again, its
125
+ * message the next turn): the run is back to running and released (REOPEN_SET), the message waits untaken for the next
126
+ * claim, which runs it as a new turn, and only the run's other rows are refused. Every message so lands on one path: in
127
+ * before the end, it opens the run here; after it, the store refuses a new row (RunFinal) and runs.reopen takes it.
128
+ * A person's stop is the same (reopenableWhere): a message waiting at it is the run's next turn, as main's stop leaves a
129
+ * message submitted before it to run; a cancel's refuses it. A run left final here has its launch secrets erased (its
130
+ * launch row's `sealed`); a run opened again keeps the ones its waiting message wrote. */
131
+ export async function refuseLeftovers(tx, runId, state, now, dialect = SQLITE) {
114
132
  if (state !== "ended" && state !== "stopped" && state !== "failed")
115
133
  return;
134
+ if (state === "ended" || state === "stopped") {
135
+ const reopened = await tx.get(`UPDATE runs SET ${REOPEN_SET} WHERE id = ? AND ${reopenableWhere(dialect)}
136
+ AND EXISTS (SELECT 1 FROM commands WHERE commands.run_id = runs.id AND commands.taken_at IS NULL AND commands.kind = 'steer') RETURNING id`, runId);
137
+ if (reopened) {
138
+ await tx.run("UPDATE commands SET taken_at = ?, refused = ? WHERE run_id = ? AND taken_at IS NULL AND kind <> 'steer'", now, endedReason(state), runId);
139
+ return;
140
+ }
141
+ }
116
142
  await tx.run("UPDATE commands SET taken_at = ?, refused = ? WHERE run_id = ? AND taken_at IS NULL", now, endedReason(state), runId);
143
+ // The run is over: the secrets its launch held for its life go with this same commit. A message that opens it again
144
+ // hands its own (runs.reopen).
145
+ await tx.run("UPDATE run_launch SET sealed = NULL WHERE run_id = ? AND sealed IS NOT NULL", runId);
117
146
  }
@@ -12,7 +12,7 @@ import { RunStorage } from "../journal/storage.js";
12
12
  import { COMMANDS_ONE_ANSWER, DDL, SCHEMA_VERSION } from "../schema.js";
13
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, NOT_A_LEARNING_RUN, refuseLeftovers, RUN_COLUMNS, runOf, SIGN_IN_HANDED_LOCK } from "./run-patch.js";
15
+ import { applyRunPatch, NOT_A_LEARNING_RUN, refuseLeftovers, REOPEN_SET, reopenableWhere, 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";
@@ -260,6 +260,33 @@ const journalKey = (claim) => `${claim.runId}\u0000${claim.epoch}`;
260
260
  function fenced(claim, sql, params) {
261
261
  return { sql, params, expect: { kind: "fenced", runId: claim.runId, epoch: claim.epoch } };
262
262
  }
263
+ /** `connection` as one read-only snapshot: every read goes through `tx`, a write is refused, and a transaction opened
264
+ * inside it is the snapshot itself (Store.snapshot). */
265
+ function snapshotOf(connection, tx) {
266
+ return {
267
+ dialect: connection.dialect,
268
+ where: connection.where,
269
+ get: (sql, ...params) => tx.get(sql, ...params),
270
+ all: (sql, ...params) => tx.all(sql, ...params),
271
+ write: () => Promise.reject(new Error("a store snapshot only reads")),
272
+ // A transaction inside the snapshot reads through the same handle, and refuses what writes (SQLite's deferred BEGIN is
273
+ // not read-only, so the refusal is here, as Postgres's read-only transaction makes it).
274
+ transaction: (callback) => callback(readOnly(tx)),
275
+ close: () => Promise.resolve(),
276
+ };
277
+ }
278
+ function readOnly(tx) {
279
+ const refuse = () => Promise.reject(new Error("a store snapshot only reads"));
280
+ return {
281
+ dialect: tx.dialect,
282
+ get: (sql, ...params) => tx.get(sql, ...params),
283
+ all: (sql, ...params) => tx.all(sql, ...params),
284
+ exec: refuse,
285
+ run: refuse,
286
+ runCounted: refuse,
287
+ step: refuse,
288
+ };
289
+ }
263
290
  /** The Store over `connection`, on whichever database it is (SQLite here, Postgres in postgres/store.ts), on the store's
264
291
  * clock `now` (ms), its identity `where` (Store.where). The opener sets the schema up and checks its version first. */
265
292
  export function storeOver(connection, now) {
@@ -285,6 +312,8 @@ class SqliteStore {
285
312
  sealedSecrets;
286
313
  #db;
287
314
  #now;
315
+ /** The store this one is a snapshot of, or itself (Store.origin). */
316
+ origin;
288
317
  /** Where this store's data is: its connection's (StoreConnection.where). */
289
318
  where;
290
319
  /** The deadlines' clock now (fence.ts storeNow): the database's on Postgres, this store's clock bound on SQLite. */
@@ -297,9 +326,10 @@ class SqliteStore {
297
326
  * but nothing is written through it: release moved the run's epoch on, so the journal's first commit is Fenced by the
298
327
  * epoch check in its own transaction. The map refuses early; the epoch is what guarantees it. */
299
328
  #released = new Map();
300
- constructor(db, now) {
329
+ constructor(db, now, origin) {
301
330
  this.#db = db;
302
331
  this.#now = now;
332
+ this.origin = origin ?? this;
303
333
  this.where = db.where;
304
334
  const d = db.dialect;
305
335
  const clock = () => storeNow(d, now);
@@ -374,6 +404,7 @@ class SqliteStore {
374
404
  const row = await db.get(`SELECT ${AGENT_COLUMNS} FROM agents WHERE external_ref = ?`, ref);
375
405
  return row && agentOf(row);
376
406
  },
407
+ hasExternalVersion: async (agentId, version) => (await db.get("SELECT id FROM revisions WHERE agent_id = ? AND external_version = ?", agentId, version)) !== undefined,
377
408
  list: async ({ archived = false } = {}) => (await db.all(`SELECT ${AGENT_COLUMNS} FROM agents WHERE archived_at IS ${archived ? "NOT NULL" : "NULL"} ORDER BY created_at, id`)).map(agentOf),
378
409
  archive: async (id, archived, why) => db.transaction(async (tx) => {
379
410
  const at = now();
@@ -730,17 +761,18 @@ class SqliteStore {
730
761
  return rows.map(runOf);
731
762
  },
732
763
  archive: async (runId, archived) => {
733
- await db.write([{ sql: "UPDATE runs SET archived_at = ? WHERE id = ?", params: [archived ? now() : null, runId] }]);
764
+ // Archiving an archived run keeps its first time: a second archive is a no-op, never a new time.
765
+ await db.write([archived ? { sql: "UPDATE runs SET archived_at = COALESCE(archived_at, ?) WHERE id = ?", params: [now(), runId] } : { sql: "UPDATE runs SET archived_at = NULL WHERE id = ?", params: [runId] }]);
734
766
  },
735
- reopen: async (runId, { kind, body = null }) => db.transaction(async (tx) => {
767
+ reopen: async (runId, { kind, body = null }, { launchSealed } = {}) => db.transaction(async (tx) => {
736
768
  // Back to running, released: the epoch, the journal, cost_usd and metrics stay (its next turn is booked on what it
737
769
  // spent); the end's own fields go. Only an agentic run that ended completed, not imported, not a learning run.
738
- const reopened = await tx.runCounted(`UPDATE runs SET state = 'running', runner = NULL, claimed_until = NULL, wake_at = NULL, backoff_until = NULL, ended_at = NULL, summary = NULL, outcome = NULL
739
- WHERE id = ? AND state = 'ended' AND imported_from IS NULL
740
- AND EXISTS (SELECT 1 FROM revisions WHERE revisions.id = runs.revision_id AND revisions.kind = 'agentic')
741
- AND NOT EXISTS (SELECT 1 FROM run_launch WHERE run_launch.run_id = runs.id AND ${d.jsonText("run_launch.body", ["harness"])} = 'learning')`, runId);
770
+ const reopened = await tx.runCounted(`UPDATE runs SET ${REOPEN_SET} WHERE id = ? AND ${reopenableWhere(d)}`, runId);
742
771
  if (reopened === 0)
743
772
  throw new RunFinal(runId);
773
+ // The message's launch secrets, with it: the claim that runs its turn reads them.
774
+ if (launchSealed)
775
+ await tx.run("UPDATE run_launch SET sealed = ? WHERE run_id = ?", launchSealed, runId);
744
776
  const row = await tx.get(`INSERT INTO commands (run_id, kind, body, created_at) VALUES (?, ?, ?, ?) RETURNING ${COMMAND_COLUMNS}`, runId, kind, json(body), now());
745
777
  return commandOf(row);
746
778
  }),
@@ -771,7 +803,7 @@ class SqliteStore {
771
803
  }
772
804
  }
773
805
  // An update that made the run final: its other untaken rows are refused in this transaction, after its own takes.
774
- await refuseLeftovers(tx, claim.runId, patch.state, at);
806
+ await refuseLeftovers(tx, claim.runId, patch.state, at, d);
775
807
  // The bind's save lease, in this same transaction as the sign_in_handed write just made (applyRunPatch, under
776
808
  // SIGN_IN_HANDED_LOCK): this run saves unless another run already holds one of the handed pointers (a running run,
777
809
  // or — within signInSettleMs of leaving running, a vendor's settle window — one that left running less than that
@@ -1008,6 +1040,15 @@ class SqliteStore {
1008
1040
  const row = await db.get("SELECT value FROM settings WHERE key = ?", key);
1009
1041
  return row === undefined ? undefined : JSON.parse(row.value);
1010
1042
  },
1043
+ // `was` is compared as the JSON text put wrote: a row read and parsed gives the same text back, its keys in order.
1044
+ replaceIf: async (key, was, value) => {
1045
+ const [result] = await db.write([{ sql: "UPDATE settings SET value = ?, updated_at = ? WHERE key = ? AND value = ?", params: [json(value), now(), key, json(was)] }]);
1046
+ return result.changes === 1;
1047
+ },
1048
+ removeIf: async (key, was) => {
1049
+ const [result] = await db.write([{ sql: "DELETE FROM settings WHERE key = ? AND value = ?", params: [key, json(was)] }]);
1050
+ return result.changes === 1;
1051
+ },
1011
1052
  remove: async (key) => {
1012
1053
  await db.write([{ sql: "DELETE FROM settings WHERE key = ?", params: [key] }]);
1013
1054
  },
@@ -1038,6 +1079,14 @@ class SqliteStore {
1038
1079
  remove: async (provider, sessionId) => {
1039
1080
  await db.write([{ sql: "DELETE FROM computer_ledger WHERE provider = ? AND session_id = ?", params: [provider, sessionId] }]);
1040
1081
  },
1082
+ // The row is compared as the JSON text put wrote: a row read and parsed gives the same text back, its keys in order.
1083
+ swap: async (provider, sessionId, was, labels, detail) => {
1084
+ const [result] = await db.write([{
1085
+ sql: "UPDATE computer_ledger SET labels = ?, detail = ?, updated_at = ? WHERE provider = ? AND session_id = ? AND labels = ? AND detail = ?",
1086
+ params: [JSON.stringify(labels), JSON.stringify(detail), now(), provider, sessionId, JSON.stringify(was.labels), JSON.stringify(was.detail)],
1087
+ }]);
1088
+ return (result?.changes ?? 0) === 1;
1089
+ },
1041
1090
  };
1042
1091
  this.triggerSettings = {
1043
1092
  get: async (adapter) => (await db.all("SELECT adapter, scope, field, sealed, updated_at FROM trigger_settings WHERE adapter = ? ORDER BY scope, field", adapter)).map(triggerSettingOf),
@@ -1307,6 +1356,9 @@ class SqliteStore {
1307
1356
  readJournal(runId) {
1308
1357
  return new RunStorage(this.#db, { runId, epoch: 0 }, this.#now);
1309
1358
  }
1359
+ async snapshot(read) {
1360
+ return this.#db.transaction((tx) => read(new SqliteStore(snapshotOf(this.#db, tx), this.#now, this.origin)), { read: true });
1361
+ }
1310
1362
  /** How many journals the store keeps (open, of a claim not released). */
1311
1363
  get openJournals() {
1312
1364
  return this.#journals.size;
@@ -1314,14 +1366,16 @@ class SqliteStore {
1314
1366
  async flush() {
1315
1367
  await this.#db.write([{ sql: "UPDATE store_meta SET flushes = flushes + 1 WHERE singleton = 1" }], { full: true });
1316
1368
  }
1317
- async command(runId, { kind, body = null }) {
1369
+ async command(runId, { kind, body = null }, { launchSealed } = {}) {
1318
1370
  const [result] = await this.#db.write([{
1319
1371
  // The run row read under the share lock: a command never lands while the run's end is in flight, to be left untaken
1320
1372
  // by an end that refused the run's leftover rows before it (the end waits for it, or it waits for the end).
1321
1373
  sql: `INSERT INTO commands (run_id, kind, body, created_at) SELECT id, ?, ?, ? FROM runs WHERE id = ? AND state NOT IN (${FINAL})${this.#db.dialect.shareLock} RETURNING ${COMMAND_COLUMNS}`,
1322
1374
  params: [kind, json(body), this.#now(), runId],
1323
1375
  expect: { kind: "final", runId },
1324
- }]);
1376
+ },
1377
+ // The message's launch secrets, in the command's own write: written only when the command is (a final run refuses both).
1378
+ ...(launchSealed ? [{ sql: "UPDATE run_launch SET sealed = ? WHERE run_id = ?", params: [launchSealed, runId] }] : [])]);
1325
1379
  return commandOf(result.rows[0]);
1326
1380
  }
1327
1381
  async commands(runId, after) {
@@ -89,9 +89,16 @@ export interface RevisionRow {
89
89
  /** The version this revision maps in the agent's owning system (one revision per version), or null for one committed here. */
90
90
  readonly externalVersion: string | null;
91
91
  }
92
- /** How an ended run (state 'ended') ended apart from being done: 'escalated' (it finished its work and waits for a person,
93
- * which the v2 status reads as completed with a review) or 'completed'. A failed or stopped run says so in its state. */
94
- export type RunOutcome = "completed" | "escalated";
92
+ /** How a run ended, beside its state. An ended run (state 'ended'): 'escalated' (it finished its work and waits for a
93
+ * person, which the v2 status reads as completed with a review) or 'completed'. A stopped run (state 'stopped'): 'stopped'
94
+ * when a person stopped it (its turn ended, never the run: an agentic run reads input_required and idle, as main's
95
+ * statusOf reads a stopped run, and a person's message reopens it), 'cancelled' when it was cancelled (over for good). A
96
+ * failed run says so in its state. */
97
+ export type RunOutcome = "completed" | "escalated" | "stopped" | "cancelled";
98
+ /** Whether `run`, of a revision of `kind`, was stopped by a person and waits for them (state 'stopped', outcome 'stopped',
99
+ * an agentic run started here): its turn is over, the run is not. A workflow's stop, a cancel and an imported run's stop
100
+ * are over for good. */
101
+ export declare function stoppedByPerson(run: Pick<RunRow, "state" | "outcome" | "importedFrom">, kind: string): boolean;
95
102
  /** The harness an imported run came from. */
96
103
  export type ImportSource = "claude-code" | "codex" | "pi";
97
104
  /** Where an imported run came from: the harness that ran it, and its own session id. `file` is the server's own record of
@@ -127,7 +134,7 @@ export interface RunRow {
127
134
  readonly costUsd: number | null;
128
135
  readonly metrics: unknown;
129
136
  readonly summary: string | null;
130
- /** An ended run's outcome (RunOutcome), null for a plain completion or a run not ended this way. */
137
+ /** How the run ended beside its state (RunOutcome), null for a plain completion, a failure, or a run not ended. */
131
138
  readonly outcome: RunOutcome | null;
132
139
  /** When the run itself was archived (its agent's archive is read apart); null when it is not. */
133
140
  readonly archivedAt: number | null;
@@ -145,7 +152,7 @@ export interface RunPatch {
145
152
  readonly costUsd?: number | null;
146
153
  readonly metrics?: unknown;
147
154
  readonly summary?: string | null;
148
- /** An ended run's outcome, set in its end commit; null clears it. */
155
+ /** How the run ended (RunOutcome), set in its end commit; null clears it. */
149
156
  readonly outcome?: RunOutcome | null;
150
157
  /** The SHA-256 hashes of the sign-in pointers handed to the run, which the runner writes at its claim (under the epoch
151
158
  * fence); null clears them. While the run runs, a sign-in hashing to one of these cannot be forgotten (sign-ins-store.ts). */
@@ -161,7 +168,9 @@ export type UpdatedRun = RunRow & {
161
168
  };
162
169
  /** A run's launch, as the server writes it at start: its JSON `body` (run-launch.ts: the first input, title, place, effort,
163
170
  * cap, trigger and origin), and `sealed` ciphertext for any secret it carries (sealed with the server's key outside the
164
- * store, AAD `run_launch|<run_id>|sealed`), or none. Written once, in the same transaction as the queued run. */
171
+ * store, AAD `run_launch|<run_id>|sealed`: the MCP credentials its caller handed it, store/seal.ts sealRunMcpAuth), or
172
+ * none. The body is written once, in the same transaction as the queued run. `sealed` is the run's for its life only: a
173
+ * message may replace it (runs.command and runs.reopen, `launchSealed`), and the write that ends the run erases it. */
165
174
  export interface RunLaunchInput {
166
175
  readonly body: unknown;
167
176
  readonly sealed?: Uint8Array | null;
@@ -174,6 +183,11 @@ export interface RunLaunchRow {
174
183
  readonly sealed: Uint8Array | null;
175
184
  readonly createdAt: number;
176
185
  }
186
+ /** A message's new launch secrets (runs.command, runs.reopen): `launchSealed` replaces the run's launch `sealed` in the
187
+ * command's own transaction, so the runner that takes the command reads them, and a run already final takes neither. */
188
+ export interface LaunchSealedWrite {
189
+ readonly launchSealed?: Uint8Array;
190
+ }
177
191
  /** A run imported from another harness's session: an ended run with where it came from, its launch (built from the
178
192
  * session), its cost and metrics, and its transcript as journal batches — the whole thing written in one transaction.
179
193
  * `transcript` is the session as pi-durable write batches (a root conversation and its entries), each batch a commit. */
@@ -455,6 +469,8 @@ export interface Agents {
455
469
  /** The agent an external reference ("<source>:<kind>:<id>") maps to (Runs.createInline), or undefined before its first
456
470
  * run. */
457
471
  byExternal(ref: string): Promise<AgentRow | undefined>;
472
+ /** Whether the agent already has the revision that maps `version` of its owning system (one row looked up, no bodies read). */
473
+ hasExternalVersion(agentId: string, version: string): Promise<boolean>;
458
474
  list(options?: {
459
475
  archived?: boolean;
460
476
  }): Promise<AgentRow[]>;
@@ -643,16 +659,17 @@ export interface Runs {
643
659
  }): Promise<RunRow[]>;
644
660
  /** Archives the run (its own archive time), or unarchives it: idempotent. */
645
661
  archive(runId: string, archived: boolean): Promise<void>;
646
- /** A person's follow-up to a run that ended completed: in one transaction, the run goes back to running with no runner
662
+ /** A person's follow-up to a run that ended completed, or that a person stopped: in one transaction, the run goes back to running with no runner
647
663
  * (released, so a runner claims it at once by the claimable rule's released branch), its end's own fields cleared
648
664
  * (ended_at, summary, outcome, its waits) and everything it did kept (its epoch, its journal, its cost and metrics,
649
665
  * so its next turn is booked on top of what it spent), and `command` (the follow-up's steer) is written untaken for it.
650
- * Only an agentic run that ended completed (state 'ended'), not imported and not a learning run, reopens: a workflow,
651
- * a failed, stopped or cancelled run, any other, or none is RunFinal, and nothing is written. */
666
+ * Only an agentic run that ended completed (state 'ended') or that a person stopped (state 'stopped', outcome
667
+ * 'stopped'), not imported and not a learning run, reopens: a workflow, a failed or cancelled run, any other, or none
668
+ * is RunFinal, and nothing is written. */
652
669
  reopen(runId: string, command: {
653
670
  kind: string;
654
671
  body?: unknown;
655
- }): Promise<Command>;
672
+ }, options?: LaunchSealedWrite): Promise<Command>;
656
673
  /** The runs a runner may claim, oldest first: queued; parked with an untaken command or its wake_at passed; running with
657
674
  * no runner (released at a runner's shutdown: it stays running, a run that started keeps that fact) or its claim run
658
675
  * out. */
@@ -843,6 +860,12 @@ export interface Settings {
843
860
  /** Saves `value` under `key` only when the key has no row yet, in one statement, so of two processes that race the first
844
861
  * wins; the value saved under it after (this one, or the one there before). */
845
862
  putIfAbsent(key: string, value: unknown): Promise<unknown>;
863
+ /** Saves `value` under `key` only while its row still holds `was` (as get read it), in one statement: a compare-and-set,
864
+ * so of two writers that read one row only one replaces it. True when it was replaced; false, with nothing written,
865
+ * when the row changed since or is gone. */
866
+ replaceIf(key: string, was: unknown, value: unknown): Promise<boolean>;
867
+ /** The key's row goes only while it still holds `was`, in one statement: true when it went. */
868
+ removeIf(key: string, was: unknown): Promise<boolean>;
846
869
  /** The key's row goes; a key with no row is left as it is. */
847
870
  remove(key: string): Promise<void>;
848
871
  /** Every setting, by key. */
@@ -902,6 +925,13 @@ export interface ComputerLedger {
902
925
  list(provider: string): Promise<ComputerLedgerRow[]>;
903
926
  /** The session's row goes. */
904
927
  remove(provider: string, sessionId: string): Promise<void>;
928
+ /** Replaces the session's `labels` and `detail` only while its row still holds `was`'s, in one statement (a
929
+ * compare-and-set, so two writers that read one row never both write it): true when it was replaced; false, with
930
+ * nothing written, when the row changed since or is gone. */
931
+ swap(provider: string, sessionId: string, was: {
932
+ readonly labels: Readonly<Record<string, string>>;
933
+ readonly detail: Readonly<Record<string, unknown>>;
934
+ }, labels: Readonly<Record<string, string>>, detail: Readonly<Record<string, unknown>>): Promise<boolean>;
905
935
  }
906
936
  /** A trigger source's sealed setting as a row (store schema `trigger_settings`): its adapter, scope ("server" for the one
907
937
  * server-wide set, or a trigger's id for its own), field, and the value sealed (store/seal.ts) under AAD
@@ -1146,6 +1176,15 @@ export interface Store {
1146
1176
  /** The run's journal: pi-durable's Storage for this one run, every commit fenced by the claim (store/journal). Its commit
1147
1177
  * holds the store's one connection while it runs, so it awaits nothing but its own statements, under a deadline. */
1148
1178
  journal(claim: Claim): Journal;
1179
+ /** The store this one reads from: itself, but for the store a snapshot hands its callback, which is a new object at each
1180
+ * snapshot and gives the store it was taken of. What a reader keeps per store (a served answer's cache) is kept by this. */
1181
+ readonly origin: Store;
1182
+ /** `read` against this store as it stood at one moment: every read it makes sees one snapshot (one read-only transaction),
1183
+ * so a write that lands meanwhile, a runner's commit among them, is in all of its reads or in none. The store it is given
1184
+ * only reads. On SQLite the transaction holds this process's one connection until `read` settles, so `read` awaits the
1185
+ * store it is given and nothing else: never this store (that waits for the snapshot, which waits for it), and no
1186
+ * network or disk. Its deadline is the transaction's (StoreDeadline). */
1187
+ snapshot<T>(read: (store: Store) => Promise<T>): Promise<T>;
1149
1188
  /** A run's journal opened for reading only (JournalReads): the server's reads of a run, which hold no claim. Its reads
1150
1189
  * alone, never a commit; a read never fences, so it needs no claim. A run with no journal yet reads as empty. */
1151
1190
  readJournal(runId: string): JournalReads;
@@ -1167,7 +1206,7 @@ export interface Store {
1167
1206
  command(runId: string, command: {
1168
1207
  kind: string;
1169
1208
  body?: unknown;
1170
- }): Promise<Command>;
1209
+ }, options?: LaunchSealedWrite): Promise<Command>;
1171
1210
  /** The run's commands with an id above `after`, in id order. */
1172
1211
  commands(runId: string, after: number): Promise<Command[]>;
1173
1212
  /** Every run's commands with an id above its own cursor, in id order, in one read: a runner's poll of all it holds. A run
@@ -1252,21 +1291,32 @@ export declare class StoreLaunchMissing extends Error {
1252
1291
  export type ConstraintRule = "check" | "unique" | "foreign_key" | "not_null";
1253
1292
  /** A row the store's constraints refuse (a duplicate id or name, a revision of an unknown agent, a bad kind). When the
1254
1293
  * database said which rule refused it, `rule`; for a duplicate, `unique`: the table and the columns whose values were
1255
- * taken already (a primary key's or a UNIQUE's), so a caller tells "the name is taken" from any other refusal. */
1294
+ * taken already (a primary key's or a UNIQUE's), so a caller tells "the name is taken" from any other refusal. `index`:
1295
+ * the unique index (or constraint) the database named, when it named one: an index on an expression (one answer per
1296
+ * approval, schema.ts ONE_ANSWER_INDEX) has no plain columns to name, only its name. */
1256
1297
  export declare class StoreConstraint extends Error {
1257
1298
  readonly rule?: ConstraintRule;
1258
1299
  readonly unique?: {
1259
1300
  readonly table: string;
1260
1301
  readonly columns: readonly string[];
1261
1302
  };
1303
+ readonly index?: string;
1262
1304
  constructor(message: string, details?: {
1263
1305
  rule?: ConstraintRule;
1264
1306
  unique?: {
1265
1307
  table: string;
1266
1308
  columns: readonly string[];
1267
1309
  };
1310
+ index?: string;
1268
1311
  });
1269
1312
  }
1313
+ /** An approve or deny command refused because its approval is answered already: an unrefused answer naming it was
1314
+ * written first (the one-answer index, schema.ts ONE_ANSWER_INDEX), so this one lost. Both stores raise it from that
1315
+ * index's unique violation alone, at the command's insert; any other refusal stays a plain StoreConstraint. Its caller
1316
+ * reads the answer that won: approve's 409 already_answered, or nothing to do. */
1317
+ export declare class AnswerTaken extends StoreConstraint {
1318
+ constructor(message: string, index: string);
1319
+ }
1270
1320
  /** An agent's current revision is not the one a conditional write expected (addRevision's `ifCurrent`): another write
1271
1321
  * moved it first. `current` is the agent's current revision now. Nothing was written. */
1272
1322
  export declare class RevisionMoved extends Error {
@@ -5,6 +5,12 @@ export function endedReason(state) {
5
5
  const how = state === "ended" ? "ended" : state === "stopped" ? "was stopped" : "failed";
6
6
  return `the run ${how} before this command was taken`;
7
7
  }
8
+ /** Whether `run`, of a revision of `kind`, was stopped by a person and waits for them (state 'stopped', outcome 'stopped',
9
+ * an agentic run started here): its turn is over, the run is not. A workflow's stop, a cancel and an imported run's stop
10
+ * are over for good. */
11
+ export function stoppedByPerson(run, kind) {
12
+ return run.state === "stopped" && run.outcome === "stopped" && kind === "agentic" && run.importedFrom === null;
13
+ }
8
14
  /** A firing a trigger has no room for: `due` firings are DUE_KEPT already. Nothing was written. */
9
15
  export class TriggerFull extends Error {
10
16
  triggerId;
@@ -157,10 +163,13 @@ export class StoreLaunchMissing extends Error {
157
163
  }
158
164
  /** A row the store's constraints refuse (a duplicate id or name, a revision of an unknown agent, a bad kind). When the
159
165
  * database said which rule refused it, `rule`; for a duplicate, `unique`: the table and the columns whose values were
160
- * taken already (a primary key's or a UNIQUE's), so a caller tells "the name is taken" from any other refusal. */
166
+ * taken already (a primary key's or a UNIQUE's), so a caller tells "the name is taken" from any other refusal. `index`:
167
+ * the unique index (or constraint) the database named, when it named one: an index on an expression (one answer per
168
+ * approval, schema.ts ONE_ANSWER_INDEX) has no plain columns to name, only its name. */
161
169
  export class StoreConstraint extends Error {
162
170
  rule;
163
171
  unique;
172
+ index;
164
173
  constructor(message, details = {}) {
165
174
  super(message);
166
175
  this.name = "StoreConstraint";
@@ -168,6 +177,18 @@ export class StoreConstraint extends Error {
168
177
  this.rule = details.rule;
169
178
  if (details.unique)
170
179
  this.unique = details.unique;
180
+ if (details.index)
181
+ this.index = details.index;
182
+ }
183
+ }
184
+ /** An approve or deny command refused because its approval is answered already: an unrefused answer naming it was
185
+ * written first (the one-answer index, schema.ts ONE_ANSWER_INDEX), so this one lost. Both stores raise it from that
186
+ * index's unique violation alone, at the command's insert; any other refusal stays a plain StoreConstraint. Its caller
187
+ * reads the answer that won: approve's 409 already_answered, or nothing to do. */
188
+ export class AnswerTaken extends StoreConstraint {
189
+ constructor(message, index) {
190
+ super(message, { rule: "unique", index });
191
+ this.name = "AnswerTaken";
171
192
  }
172
193
  }
173
194
  /** An agent's current revision is not the one a conditional write expected (addRevision's `ifCurrent`): another write
@@ -31,7 +31,8 @@ export async function analytics(store, filter = {}) {
31
31
  const revision = await store.agents.revision(run.revisionId);
32
32
  harnessOf.set(run.revisionId, revision?.kind === "workflow" ? "workflow" : (revision?.body?.harness ?? DEFAULT_HARNESS));
33
33
  }
34
- const running = runReadState(run) === "running";
34
+ const read = runReadState(run, harnessOf.get(run.revisionId) === "workflow" ? "workflow" : "agentic");
35
+ const running = read === "running";
35
36
  const isPending = running && pending[run.id] !== undefined;
36
37
  const metered = !running && metricsOf(run) !== null;
37
38
  const metrics = metered ? metricsOf(run) : null;
@@ -41,7 +42,7 @@ export async function analytics(store, filter = {}) {
41
42
  costUsd: run.costUsd,
42
43
  running,
43
44
  pending: isPending,
44
- state: isPending ? pending[run.id] : runReadState(run),
45
+ state: isPending ? pending[run.id] : read,
45
46
  metered,
46
47
  metrics,
47
48
  harness: harnessOf.get(run.revisionId),
@@ -5,9 +5,7 @@ import type { Store } from "../store/store.js";
5
5
  export declare function spentOverStore(store: Store, runId: string, context: Context): Promise<number | null>;
6
6
  /** /usage's meters for a run that ended, over the one store's journal (design 2.1): cap.ts meterFiguresFrom over A's
7
7
  * entries, with the run's paid tool charges folded back from its paid-tools session (journal.ts withPaidCosts) as the
8
- * file-backed run held each on its root. The same figures meterFiguresIn reads from a settled run's own database — only
9
- * where the entries come from changes, so no money behaviour differs (the money-parity rule), as spentOverStore is to
10
- * spentIn. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
8
+ * file-backed run held each on its root. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
11
9
  export declare function metersOverStore(store: Store, runId: string, context: Context): Promise<Meters & {
12
10
  known: {
13
11
  tokens: number;
@@ -1,14 +1,18 @@
1
1
  import { meterFiguresFrom, spentFrom } from "../cap.js";
2
- import { bookedCapSpend, bookedSpend, costIsBooked } from "../runner/metrics.js";
2
+ import { bookedCapSpend, bookedSpend, cliModelWorked, costIsBooked } from "../runner/metrics.js";
3
3
  import { isCliRecord, runEntries, withPaidCosts } from "./journal.js";
4
+ /** A CLI run whose model answered or called a tool with no model request booked (metrics.ts cliModelWorked): what it
5
+ * spent no booking read, so its spend is unknown. */
6
+ const unbookedCli = (entries) => isCliRecord(entries) && bookedSpend(entries, "model").requests === 0 && cliModelWorked(entries);
4
7
  /** What a run has spent, as the cap reads it, from the one store's journal: its model requests and its paid tool calls. */
5
8
  export async function spentOverStore(store, runId, context) {
6
9
  const entries = await runEntries(store, runId, context);
7
10
  // A run whose record carries no cost of its own (a CLI harness's, a workflow's) reads what its sessions booked, the
8
11
  // figure its cap holds it to (metrics.ts bookedCapSpend), its record's answers reading $0: 0 before any request, an
9
12
  // unknown booked spend unknown (null).
13
+ // A CLI run whose model worked with no request booked (its requests went past its model proxy) reads unknown, never $0.
10
14
  if (costIsBooked(entries, isCliRecord(entries)))
11
- return bookedCapSpend(entries);
15
+ return unbookedCli(entries) ? null : bookedCapSpend(entries);
12
16
  // A pi run's paid tool calls (a browser's time, a search, a monid call) are booked on the run's one ledger, not its root:
13
17
  // folded back as the charges the file-backed root held (withPaidCosts), as metersOverStore reads them, so a live run's
14
18
  // listed spend counts them.
@@ -16,9 +20,7 @@ export async function spentOverStore(store, runId, context) {
16
20
  }
17
21
  /** /usage's meters for a run that ended, over the one store's journal (design 2.1): cap.ts meterFiguresFrom over A's
18
22
  * entries, with the run's paid tool charges folded back from its paid-tools session (journal.ts withPaidCosts) as the
19
- * file-backed run held each on its root. The same figures meterFiguresIn reads from a settled run's own database — only
20
- * where the entries come from changes, so no money behaviour differs (the money-parity rule), as spentOverStore is to
21
- * spentIn. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
23
+ * file-backed run held each on its root. A run with no journal reads as a store that was never there: every figure 0, tokens unknown. */
22
24
  export async function metersOverStore(store, runId, context) {
23
25
  const raw = await runEntries(store, runId, context);
24
26
  if (!raw.length)
@@ -30,6 +32,6 @@ export async function metersOverStore(store, runId, context) {
30
32
  return figures;
31
33
  const model = bookedSpend(raw, "model");
32
34
  if (!model.requests)
33
- return figures;
35
+ return unbookedCli(raw) ? { ...figures, tokens: null } : figures;
34
36
  return { ...figures, tokens: model.usd, known: { ...figures.known, tokens: model.known } };
35
37
  }
@@ -1,5 +1,5 @@
1
1
  import type { Context } from "@earendil-works/chord";
2
2
  import type { Store } from "../store/store.js";
3
- /** A run's decision receipts, as the old durableDecisions answered them: the single `agentrun.decisions` document's
4
- * `receipts`, or the keyed `.count` and family rows in order. The same shape, read through the one store's journal. */
3
+ /** A run's decision receipts, as durableDecisions answers them: the keyed `.count` and family rows in order, read through
4
+ * the one store's journal. */
5
5
  export declare function decisionsOverStore(store: Store, runId: string, context: Context): Promise<Array<Record<string, unknown>>>;
@@ -1,4 +1,4 @@
1
- import { decisionKey } from "@parcha/agentrun-pi/durable";
1
+ import { decisionKey } from "../workflow/decisions.js";
2
2
  /** A session-scoped document's current value, by kind and (for a family) key: findDocument, then its stored value. */
3
3
  async function sessionDocValue(reads, kind, key, context) {
4
4
  const record = await reads.findDocument({ kind, scope: { kind: "session" }, ...(key !== undefined ? { key } : {}) }, "current", context);
@@ -7,14 +7,11 @@ async function sessionDocValue(reads, kind, key, context) {
7
7
  const stored = await reads.document(record.id, "current", context);
8
8
  return stored ? stored.value : undefined;
9
9
  }
10
- /** A run's decision receipts, as the old durableDecisions answered them: the single `agentrun.decisions` document's
11
- * `receipts`, or the keyed `.count` and family rows in order. The same shape, read through the one store's journal. */
10
+ /** A run's decision receipts, as durableDecisions answers them: the keyed `.count` and family rows in order, read through
11
+ * the one store's journal. */
12
12
  export async function decisionsOverStore(store, runId, context) {
13
13
  const reads = store.readJournal(runId);
14
14
  try {
15
- const single = (await sessionDocValue(reads, "agentrun.decisions", undefined, context));
16
- if (single)
17
- return Array.isArray(single.receipts) ? single.receipts : [];
18
15
  const count = (await sessionDocValue(reads, "agentrun.decisions.count", undefined, context))?.count;
19
16
  const rows = [];
20
17
  if (typeof count === "number")