@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
@@ -37,28 +37,33 @@ export type RevisionComputer = {
37
37
  type: string;
38
38
  count: number;
39
39
  };
40
+ persistent?: boolean;
40
41
  };
41
42
  /** A revision's tool settings as its body keeps them: a map of a tool's key to its settings ({provider?, permission?,
42
43
  * pin?}), checked and made canonical by the caller (agents-store.ts, through tool-plane's settingsIssues +
43
44
  * canonicalToolSettings, the one copy). The store body holds it as it is given; this validator never reimplements it. */
44
45
  export type ToolSettings = Record<string, unknown>;
46
+ /** The model of each tier an agentic revision names (its definition's `model_tiers`: fast, strong), each "provider/model-id". */
47
+ export type ModelTiers = Partial<Record<"fast" | "strong", string>>;
45
48
  export type AgenticBody = {
46
49
  instructions: string;
47
50
  skills: Record<string, string>;
48
51
  tools: string[];
49
52
  model?: string;
53
+ modelTiers?: ModelTiers;
50
54
  thinking?: string;
51
55
  prompts?: Record<string, PromptVariant>;
52
56
  harness?: string;
53
57
  place?: RevisionPlace;
54
58
  computer?: RevisionComputer;
55
- learning?: boolean;
59
+ learning?: boolean | "notes";
56
60
  toolSettings?: ToolSettings;
57
61
  maxCostUsd?: number;
58
62
  capMode?: string;
59
63
  approvals?: "ask" | "never";
60
64
  outputSchema?: Record<string, unknown>;
61
65
  maxToolCalls?: number;
66
+ checkout?: "pull_request";
62
67
  };
63
68
  export type WorkflowBody = {
64
69
  workflow: Record<string, unknown>;
@@ -80,18 +85,20 @@ export type RevisionBodyInput = {
80
85
  skills?: Record<string, string>;
81
86
  tools?: string[];
82
87
  model?: string;
88
+ modelTiers?: ModelTiers;
83
89
  thinking?: string;
84
90
  prompts?: Record<string, PromptVariant>;
85
91
  harness?: string;
86
92
  place?: unknown;
87
93
  computer?: unknown;
88
- learning?: boolean;
94
+ learning?: boolean | "notes";
89
95
  toolSettings?: ToolSettings;
90
96
  maxCostUsd?: number;
91
97
  capMode?: string;
92
98
  approvals?: "ask" | "never";
93
99
  outputSchema?: Record<string, unknown>;
94
100
  maxToolCalls?: number;
101
+ checkout?: "pull_request";
95
102
  } | {
96
103
  kind: "workflow";
97
104
  workflow: unknown;
@@ -1,4 +1,4 @@
1
- // The agent body validator (the P4 fold of pi-durable-agent's agent-store.ts bodyOf, with kinds.ts's canonical JSON): what
1
+ // The agent body validator (with canonical JSON): what
2
2
  // a revision's stored body may be, checked before anything is written, so a refusal makes no agent and no revision. It is
3
3
  // the one check the control plane runs over a revision's body, kept with the store (A) it writes into. The body keeps a
4
4
  // skill path to its text's SHA-256 (two revisions with the same files are one body); the texts ride beside it on the
@@ -44,20 +44,21 @@ function placeOf(place) {
44
44
  }
45
45
  /** A GPU type as a body keeps it: the vendor's own name ("T4", "A100-80GB", "RTX-PRO-6000"). */
46
46
  const GPU_TYPE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
47
- /** A computer as a body keeps it: `{kind, provider?, image?, gpu?}`, nothing else: kind and provider ids, image a name
48
- * with no spaces around it, and gpu `{type, count}`, a GPU type name and a whole count from 1. */
47
+ /** A computer as a body keeps it: `{kind, provider?, image?, gpu?, persistent?}`, nothing else: kind and provider ids,
48
+ * image a name with no spaces around it, gpu `{type, count}`, a GPU type name and a whole count from 1, and persistent a
49
+ * boolean. */
49
50
  function computerOf(computer) {
50
51
  const image = isObject(computer) ? computer.image : undefined;
51
52
  const named = (value) => typeof value === "string" && value !== "" && value === value.trim();
52
- if (!isObject(computer) || !hostId(computer.kind) || (computer.provider !== undefined && !hostId(computer.provider)) || (image !== undefined && !named(image)) || Object.keys(computer).some((key) => key !== "kind" && key !== "provider" && key !== "image" && key !== "gpu"))
53
- invalid("the computer is not {kind, provider?, image?, gpu?}, kind and provider each an id (lowercase letters, digits and dashes), image a name");
53
+ if (!isObject(computer) || !hostId(computer.kind) || (computer.provider !== undefined && !hostId(computer.provider)) || (image !== undefined && !named(image)) || (computer.persistent !== undefined && typeof computer.persistent !== "boolean") || Object.keys(computer).some((key) => key !== "kind" && key !== "provider" && key !== "image" && key !== "gpu" && key !== "persistent"))
54
+ invalid("the computer is not {kind, provider?, image?, gpu?, persistent?}, kind and provider each an id (lowercase letters, digits and dashes), image a name, persistent a boolean");
54
55
  const ok = computer;
55
56
  const gpu = ok.gpu;
56
57
  if (gpu !== undefined && (!isObject(gpu) || Object.keys(gpu).some((key) => key !== "type" && key !== "count") || typeof gpu.type !== "string" || !GPU_TYPE.test(gpu.type) || !Number.isSafeInteger(gpu.count) || gpu.count < 1)) {
57
58
  invalid("the computer's gpu is not {type, count}: a GPU type name (letters, digits, dots, underscores and dashes) and a whole count from 1");
58
59
  }
59
60
  const kept = gpu;
60
- return { kind: ok.kind, ...(ok.provider !== undefined ? { provider: ok.provider } : {}), ...(ok.image !== undefined ? { image: ok.image } : {}), ...(kept !== undefined ? { gpu: { type: kept.type, count: kept.count } } : {}) };
61
+ return { kind: ok.kind, ...(ok.provider !== undefined ? { provider: ok.provider } : {}), ...(ok.image !== undefined ? { image: ok.image } : {}), ...(kept !== undefined ? { gpu: { type: kept.type, count: kept.count } } : {}), ...(ok.persistent !== undefined ? { persistent: ok.persistent } : {}) };
61
62
  }
62
63
  /** The body of a new revision and the text of each skill it names (path to text), everything checked here, before any
63
64
  * write. The body keeps each skill path to its text's SHA-256; `skills` is the texts, for the revision's row. */
@@ -109,10 +110,14 @@ export function bodyOf(input) {
109
110
  for (const field of ["model", "thinking"])
110
111
  if (input[field] !== undefined && (typeof input[field] !== "string" || input[field] === ""))
111
112
  invalid(`the ${field} is not a non-empty string`);
112
- if (input.learning !== undefined && typeof input.learning !== "boolean")
113
- invalid("learning is not true or false");
113
+ if (input.learning !== undefined && typeof input.learning !== "boolean" && input.learning !== "notes")
114
+ invalid("learning is not true, false or \"notes\"");
114
115
  if (input.outputSchema !== undefined && !isObject(input.outputSchema))
115
116
  invalid("the outputSchema is not a JSON object");
117
+ if (input.checkout !== undefined && input.checkout !== "pull_request")
118
+ invalid("the checkout is not pull_request");
119
+ if (input.modelTiers !== undefined && !(isObject(input.modelTiers) && Object.keys(input.modelTiers).length && Object.entries(input.modelTiers).every(([tier, ref]) => (tier === "fast" || tier === "strong") && typeof ref === "string" && ref !== "")))
120
+ invalid("the modelTiers are not fast and strong to a non-empty model");
116
121
  if (input.maxToolCalls !== undefined && !(Number.isSafeInteger(input.maxToolCalls) && input.maxToolCalls > 0))
117
122
  invalid("the maxToolCalls is not a whole number above 0");
118
123
  const body = {
@@ -120,12 +125,15 @@ export function bodyOf(input) {
120
125
  skills: skillShas,
121
126
  tools: [...tools],
122
127
  ...(input.model !== undefined ? { model: input.model } : {}),
128
+ ...(input.modelTiers !== undefined ? { modelTiers: Object.fromEntries(Object.entries(input.modelTiers).sort(([a], [b]) => a.localeCompare(b))) } : {}),
123
129
  ...(input.thinking !== undefined ? { thinking: input.thinking } : {}),
124
130
  ...(input.prompts !== undefined ? { prompts: structuredClone(input.prompts) } : {}),
125
131
  ...host,
126
132
  ...(input.learning !== undefined ? { learning: input.learning } : {}),
127
133
  // The JSON Schema its final answer's structured part meets (definition.output_schema): a completed run's result.output.
128
134
  ...(input.outputSchema !== undefined ? { outputSchema: structuredClone(input.outputSchema) } : {}),
135
+ // What the server checks out in each run's folder before its first turn (runner/pr-checkout.ts).
136
+ ...(input.checkout !== undefined ? { checkout: input.checkout } : {}),
129
137
  // The tool calls each conversation of its runs may make (tool-budget.ts).
130
138
  ...(input.maxToolCalls !== undefined ? { maxToolCalls: input.maxToolCalls } : {}),
131
139
  // The agent's unattended policy (PR #2003): the runner's gate reads it from the revision body at claim (`unattended`
@@ -12,6 +12,10 @@ export const STALL_MS = 50;
12
12
  * deadline or across it, and is not counted. A wait of the transaction's own (a call awaited inside it) leaves the
13
13
  * loop free, so it counts in full and is refused on time. */
14
14
  export function runnableDeadline(ms, expire) {
15
+ // Cleared with the functions they were set with: a caller that swaps the global timers while a transaction is open
16
+ // (node:test's mocked timers, enabled mid-run) would otherwise clear nothing, and the look's interval would hold the
17
+ // process open for good.
18
+ const [after, every, cancel, stop] = [setTimeout, setInterval, clearTimeout, clearInterval];
15
19
  const start = performance.now();
16
20
  let last = start;
17
21
  let held = 0;
@@ -23,19 +27,19 @@ export function runnableDeadline(ms, expire) {
23
27
  last = now;
24
28
  return now;
25
29
  };
26
- const ticks = setInterval(look, TICK_MS);
30
+ const ticks = every(look, TICK_MS);
27
31
  let timer;
28
32
  const check = () => {
29
33
  const left = ms - (look() - start - held);
30
34
  if (left <= 0)
31
35
  return expire();
32
- timer = setTimeout(check, Math.ceil(left));
36
+ timer = after(check, Math.ceil(left));
33
37
  };
34
- timer = setTimeout(check, ms);
38
+ timer = after(check, ms);
35
39
  return {
36
40
  clear: () => {
37
- clearInterval(ticks);
38
- clearTimeout(timer);
41
+ stop(ticks);
42
+ cancel(timer);
39
43
  },
40
44
  held: () => {
41
45
  look();
@@ -1,7 +1,7 @@
1
- export { AgentArchived, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, TriggerFull } from "./store.js";
1
+ export { AgentArchived, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull } from "./store.js";
2
2
  export type { ConstraintRule, AgentRow, Agents, AlsoRow, ChannelPost, Claim, Command, ComputerLedger, ComputerLedgerRow, Firing, FiringChange, FiringRow, FiringStatus, FiringStreak, Journal, Live, LiveRow, Mcp, McpCredentialMark, McpOauth, McpOauthPendingRow, McpPinRow, McpServerRow, McpServerWrite, NewFiring, NewRevision, NewTrigger, ReleasedState, RevisionRow, RunPatch, RunRow, Runs, RunState, SealedKeyRow, SealedKeys, SealedPlane, SealedSecretRow, SealedSecrets, SettingRow, Settings, Staged, StagedTake, Store, StoreRole, TemplatePackage, Templates, TriggerDef, TriggerPatch, TriggerRow, Triggers, TriggerScope, TriggerSettingRow, TriggerSettings, ImportedFrom, ImportSource, ImportRunInput, JournalReads, RunOrigin, RunOutcome, RunLaunchInput, RunLaunchRow, Learning, LearningProposal, LiveViewerRow, LiveViewers, SignIns, SignInRow, SignInTombstoneRow, UpdatedRun, ViewerKind, } from "./store.js";
3
- export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, sealColumn, type SealedAt, sealedAt, sealMcpCredential, unsealColumn } from "./seal.js";
4
- export { AgentBodyInvalid, type AgenticBody, bodyOf, canonical, isObject, isSkillPath, type PromptVariant, type RevisionBodyInput, type RevisionComputer, type RevisionPlace, sha256, type ToolSettings, type WorkflowBody, } from "./agent-body.js";
3
+ export { aadOf, type McpCredential, type OpenedMcpCredential, openMcpCredential, openRunMcpAuth, type RunMcpAuth, sealColumn, type SealedAt, sealedAt, sealMcpCredential, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
+ export { AgentBodyInvalid, type AgenticBody, bodyOf, canonical, isObject, isSkillPath, type PromptVariant, type ModelTiers, type RevisionBodyInput, type RevisionComputer, type RevisionPlace, sha256, type ToolSettings, type WorkflowBody, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
6
6
  export { DDL, PI_DDL, PI_TABLE, PI_TABLES, SCHEMA_VERSION, STORE_DDL } from "./schema.js";
7
7
  export { RunStorage } from "./journal/storage.js";
@@ -1,6 +1,6 @@
1
1
  // The one store (design 2.1), for the cutover: nothing on main imports it until then.
2
- export { AgentArchived, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, TriggerFull } from "./store.js";
3
- export { aadOf, openMcpCredential, sealColumn, sealedAt, sealMcpCredential, unsealColumn } from "./seal.js";
2
+ export { AgentArchived, AnswerTaken, CommandTaken, endedReason, ExternalBodyConflict, FINAL_STATES, Fenced, MCP_REFRESH_CALL_MS, MCP_REFRESH_LEASE_MS, RevisionMoved, RunFinal, SchemaVersionUnknown, SignInHandedTo, SignInMissing, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreFromEarlierVersion, StoreLaunchMissing, StoreOwned, StoreWorkerLost, STORE_WRITE_DEADLINE_MS, stoppedByPerson, TriggerFull } from "./store.js";
3
+ export { aadOf, openMcpCredential, openRunMcpAuth, sealColumn, sealedAt, sealMcpCredential, sealRunMcpAuth, unsealColumn } from "./seal.js";
4
4
  export { AgentBodyInvalid, bodyOf, canonical, isObject, isSkillPath, sha256, } from "./agent-body.js";
5
5
  export { checkPrompts, OTHER_OPTION, PromptsInvalid } from "./prompts.js";
6
6
  export { DDL, PI_DDL, PI_TABLE, PI_TABLES, SCHEMA_VERSION, STORE_DDL } from "./schema.js";
@@ -315,8 +315,9 @@ export class RunStorage {
315
315
  }
316
316
  }
317
317
  // A run patch that made the run final: its other untaken rows are refused in this commit, after its own takes.
318
+ // A person's message that came while it was ending opens a completed run again instead (refuseLeftovers).
318
319
  if (patching)
319
- await refuseLeftovers(tx, this.#runId, staged?.run?.state, now);
320
+ await refuseLeftovers(tx, this.#runId, staged?.run?.state, now, this.#dialect);
320
321
  }
321
322
  });
322
323
  this.#nextId = Math.max(this.#nextId, candidateNextId);
@@ -7,7 +7,8 @@
7
7
  import pg from "pg";
8
8
  import { runnableDeadline } from "../deadline.js";
9
9
  import { cleanText } from "../dialect.js";
10
- import { Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned } from "../store.js";
10
+ import { ONE_ANSWER_INDEX } from "../schema.js";
11
+ import { AnswerTaken, Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned } from "../store.js";
11
12
  import { DEFAULT_TRANSACTION_DEADLINE_MS } from "../sqlite/connection.js";
12
13
  import { postgresDialect } from "./dialect.js";
13
14
  /** Which store this is, as two opens of the same data agree on it (StoreConnection.where): "postgres:" and the URL's host
@@ -208,14 +209,18 @@ function bound(value) {
208
209
  const returnsRows = (sql) => /^\s*(?:SELECT|WITH)\b/i.test(sql) || /\bRETURNING\b/i.test(sql);
209
210
  /** Postgres's integrity SQLSTATEs, by the rule they name. */
210
211
  const RULES = { "23514": "check", "23505": "unique", "23503": "foreign_key", "23502": "not_null" };
211
- /** A unique violation's table and columns: the table Postgres names, and the columns of the index it names (a UNIQUE's or
212
- * a primary key's is an index of the same name), read from the catalog by `columnsOf`. Any other error as it is. */
212
+ /** A unique violation's table, columns and index: the table and the index (or constraint) Postgres names, and that
213
+ * index's columns (a UNIQUE's or a primary key's is an index of the same name), read from the catalog by `columnsOf`.
214
+ * A violation of the one-answer index (an answer to an approval answered already) is AnswerTaken. Any other error as it
215
+ * is. */
213
216
  async function withUnique(error, cause, columnsOf) {
214
217
  const e = cause;
215
218
  if (!(error instanceof StoreConstraint) || error.rule !== "unique" || !e?.table || !e.constraint)
216
219
  return error;
220
+ if (e.constraint === ONE_ANSWER_INDEX)
221
+ return new AnswerTaken(error.message, e.constraint);
217
222
  const columns = await columnsOf(e.constraint).catch(() => []);
218
- return columns.length ? new StoreConstraint(error.message, { rule: "unique", unique: { table: e.table, columns } }) : error;
223
+ return new StoreConstraint(error.message, { rule: "unique", index: e.constraint, ...(columns.length ? { unique: { table: e.table, columns } } : {}) });
219
224
  }
220
225
  /** A Postgres error as the store's own: a refused row StoreConstraint, a lock or a conflict StoreBusy. */
221
226
  /** Whether `error` says the database ended the session (its idle-in-transaction timeout, SQLSTATE 25P03), or that the
@@ -0,0 +1,11 @@
1
+ -- The store's schema on Postgres, version 4: a stopped run says which stop it was in its outcome, as store/schema.ts keeps
2
+ -- it on SQLite: 'stopped' when a person stopped it (its turn is over, not the run: a message reopens it) or 'cancelled'
3
+ -- (over for good), beside an ended run's 'completed' and 'escalated'. Applied once, after 0003, inside the transaction
4
+ -- migrate.ts opens. Never edit this file once applied: a change is a new file.
5
+ --
6
+ -- runs_outcome_check is Postgres's name for 0001's column check on runs.outcome.
7
+
8
+ ALTER TABLE runs DROP CONSTRAINT runs_outcome_check;
9
+ ALTER TABLE runs ADD CONSTRAINT runs_outcome_check CHECK (outcome IS NULL OR outcome IN ('completed', 'escalated', 'stopped', 'cancelled'));
10
+
11
+ UPDATE store_meta SET schema_version = 4 WHERE singleton = 1;
@@ -1,9 +1,10 @@
1
- export declare const SCHEMA_VERSION = 5;
1
+ export declare const SCHEMA_VERSION = 6;
2
2
  /** One answer per approval of a run: a second approve or deny command naming the same approval is refused
3
3
  * (StoreConstraint), so the first answer a person gives wins from the moment it is written, before the runner takes it
4
4
  * (runs-over-store.ts approve). In STORE_DDL, and added at a server open to a store an earlier build of this version made. */
5
5
  /** One unrefused answer per approval of a run: an answer the runner refused (its run could not resume) holds no place, so
6
6
  * the person can answer again. */
7
+ export declare const ONE_ANSWER_INDEX = "commands_one_answer";
7
8
  export declare const COMMANDS_ONE_ANSWER = "CREATE UNIQUE INDEX IF NOT EXISTS commands_one_answer ON commands (run_id, json_extract(body, '$.approval')) WHERE kind IN ('approve', 'deny') AND refused IS NULL";
8
9
  export declare const STORE_DDL: readonly string[];
9
10
  /** pi-durable's journal tables (its SqliteStorage schema, version 2, the `sleeping` task status included; MIT, see NOTICE),
@@ -1,8 +1,9 @@
1
- // The store's one schema, version 5 (design 2.1). Nothing migrates into it: the rewrite replaces the old stores, and a store
1
+ // The store's one schema, version 6 (design 2.1). Nothing migrates into it: the rewrite replaces the old stores, and a store
2
2
  // an older build made is refused as a version this build does not know. The server sets it up once at its start (a
3
3
  // store_meta row holds the version); a runner refuses a version it does not know. Version 2 adds the computer ledger;
4
4
  // version 3 numbers each save of a sign-in (sign_ins.save); version 4 stamps an MCP token's end (mcp_servers.token_until);
5
- // version 5 maps an externally owned agent (agents.external_ref, revisions.external_version).
5
+ // version 5 maps an externally owned agent (agents.external_ref, revisions.external_version); version 6 tells a person's
6
+ // stop from a cancel (runs.outcome 'stopped' or 'cancelled').
6
7
  // Conventions: every time is INTEGER epoch milliseconds; JSON is TEXT checked by json_valid; money is REAL US dollars;
7
8
  // sealed columns hold ciphertext only (sealed with the server's key outside the store), so the store never sees a secret
8
9
  // in the clear. Foreign keys are on (the connection's pragma).
@@ -13,13 +14,14 @@
13
14
  // learning state, the MCP registry, pending MCP sign-ins, each run's MCP pin, and the computer ledger. PI_DDL is pi-durable's
14
15
  // journal tables, keyed by run_id (store/journal): one schema for every run's journal, so a query joins runs and their
15
16
  // journals.
16
- export const SCHEMA_VERSION = 5;
17
+ export const SCHEMA_VERSION = 6;
17
18
  /** One answer per approval of a run: a second approve or deny command naming the same approval is refused
18
19
  * (StoreConstraint), so the first answer a person gives wins from the moment it is written, before the runner takes it
19
20
  * (runs-over-store.ts approve). In STORE_DDL, and added at a server open to a store an earlier build of this version made. */
20
21
  /** One unrefused answer per approval of a run: an answer the runner refused (its run could not resume) holds no place, so
21
22
  * the person can answer again. */
22
- export const COMMANDS_ONE_ANSWER = `CREATE UNIQUE INDEX IF NOT EXISTS commands_one_answer ON commands (run_id, json_extract(body, '$.approval')) WHERE kind IN ('approve', 'deny') AND refused IS NULL`;
23
+ export const ONE_ANSWER_INDEX = "commands_one_answer";
24
+ export const COMMANDS_ONE_ANSWER = `CREATE UNIQUE INDEX IF NOT EXISTS ${ONE_ANSWER_INDEX} ON commands (run_id, json_extract(body, '$.approval')) WHERE kind IN ('approve', 'deny') AND refused IS NULL`;
23
25
  const json = (column, nullable = false) => `${column} TEXT${nullable ? "" : " NOT NULL"} CHECK (${column} IS NULL OR json_valid(${column}))`;
24
26
  export const STORE_DDL = [
25
27
  `CREATE TABLE IF NOT EXISTS store_meta (
@@ -80,10 +82,11 @@ export const STORE_DDL = [
80
82
  cost_usd REAL,
81
83
  ${json("metrics", true)},
82
84
  summary TEXT,
83
- -- How an ended run (state 'ended') ended apart from being done: 'escalated' (it finished its work and waits for a
84
- -- person, which v2 reads as completed with a review) or 'completed'; null is a plain completion. A failed or stopped
85
- -- run says so in its state and needs none. Written in the run's end commit (RunPatch.outcome).
86
- outcome TEXT CHECK (outcome IS NULL OR outcome IN ('completed', 'escalated')),
85
+ -- How the run ended beside its state (RunOutcome). An ended run: 'escalated' (it finished its work and waits for a
86
+ -- person, which v2 reads as completed with a review) or 'completed'; null is a plain completion. A stopped run:
87
+ -- 'stopped' when a person stopped it (its turn is over, not the run: a message reopens it) or 'cancelled' (over for
88
+ -- good). A failed run says so in its state and needs none. Written in the run's end commit (RunPatch.outcome).
89
+ outcome TEXT CHECK (outcome IS NULL OR outcome IN ('completed', 'escalated', 'stopped', 'cancelled')),
87
90
  -- When the run itself was archived (its agent's archive is the agent row's): hidden from the default lists, kept.
88
91
  archived_at INTEGER,
89
92
  -- The session an imported run came from ({source, session}), written by Store.importRun; null for a run started here.
@@ -13,6 +13,8 @@ export declare const sealedAt: {
13
13
  signIn: (agentId: string, provider: string) => SealedAt;
14
14
  /** A run's computer session's live viewer token (browser-live.ts): one row per run, computer kind and session tag. */
15
15
  liveViewer: (runId: string, kind: string, tag: string) => SealedAt;
16
+ /** A run's launch secrets: the MCP credentials its caller handed it for its `per_run` servers (mcp_auth). */
17
+ runLaunch: (runId: string) => SealedAt;
16
18
  };
17
19
  /** The AAD a value at `at` is sealed under. A part with the separator in it is refused: no two places share an AAD. */
18
20
  export declare function aadOf(at: SealedAt): string;
@@ -46,3 +48,14 @@ export declare function openMcpCredential(key: Buffer, row: {
46
48
  readonly url: string;
47
49
  readonly sealed: Uint8Array | null;
48
50
  }): OpenedMcpCredential;
51
+ /** The MCP credentials a run's caller handed it (`mcp_auth` at its start or with a message), by server name: each one's
52
+ * headers and the origin of the server's url when it was handed, so a server moved since never receives them. */
53
+ export type RunMcpAuth = Readonly<Record<string, {
54
+ readonly headers: Readonly<Record<string, string>>;
55
+ readonly origin: string;
56
+ }>>;
57
+ /** Seals a run's handed MCP credentials as its launch's sealed column (AAD run_launch|<run_id>|sealed). */
58
+ export declare function sealRunMcpAuth(key: Buffer, runId: string, auth: RunMcpAuth): Uint8Array;
59
+ /** A run's handed MCP credentials, opened: none when its launch holds none; undefined when the bytes do not open under
60
+ * `key` for this run (sealed for another run, or under another key). */
61
+ export declare function openRunMcpAuth(key: Buffer, runId: string, sealed: Uint8Array | null): RunMcpAuth | undefined;
@@ -25,6 +25,8 @@ export const sealedAt = {
25
25
  },
26
26
  /** A run's computer session's live viewer token (browser-live.ts): one row per run, computer kind and session tag. */
27
27
  liveViewer: (runId, kind, tag) => ({ table: "computer_viewers", row: `${runId}/${kind}:${tag}`, column: "sealed" }),
28
+ /** A run's launch secrets: the MCP credentials its caller handed it for its `per_run` servers (mcp_auth). */
29
+ runLaunch: (runId) => ({ table: "run_launch", row: runId, column: "sealed" }),
28
30
  };
29
31
  /** The AAD a value at `at` is sealed under. A part with the separator in it is refused: no two places share an AAD. */
30
32
  export function aadOf(at) {
@@ -67,3 +69,20 @@ export function openMcpCredential(key, row) {
67
69
  }
68
70
  return { credential: credential };
69
71
  }
72
+ /** Seals a run's handed MCP credentials as its launch's sealed column (AAD run_launch|<run_id>|sealed). */
73
+ export function sealRunMcpAuth(key, runId, auth) {
74
+ return sealColumn(key, sealedAt.runLaunch(runId), JSON.stringify({ mcp: auth }));
75
+ }
76
+ /** A run's handed MCP credentials, opened: none when its launch holds none; undefined when the bytes do not open under
77
+ * `key` for this run (sealed for another run, or under another key). */
78
+ export function openRunMcpAuth(key, runId, sealed) {
79
+ if (sealed === null)
80
+ return {};
81
+ try {
82
+ const opened = JSON.parse(unsealColumn(key, sealedAt.runLaunch(runId), sealed).toString("utf8"));
83
+ return opened.mcp ?? {};
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
@@ -4,6 +4,11 @@ import type { Statement, StatementResult } from "./worker.js";
4
4
  export type { Params, Statement, StatementResult } from "./worker.js";
5
5
  /** How long a transaction may stay open (it holds every other call of the process) before it is rolled back. */
6
6
  export declare const DEFAULT_TRANSACTION_DEADLINE_MS = 10000;
7
+ /** `error` with its stack naming who held the store: `opened` (its own transaction's opener, when it has one), and every
8
+ * other transaction open in this process with its age. */
9
+ export declare function holderNamed<E extends Error>(error: E, { opened }?: {
10
+ opened?: Error;
11
+ }): E;
7
12
  /** A value SQLite takes or gives back (Chord's SqliteValue). */
8
13
  export type SqliteValue = null | number | bigint | string | Uint8Array;
9
14
  /** Chord's SqliteExecutor: what a database and a transaction handle both do. */
@@ -8,20 +8,46 @@ import { Worker } from "node:worker_threads";
8
8
  import { runnableDeadline } from "../deadline.js";
9
9
  import { cleanText, SQLITE } from "../dialect.js";
10
10
  import { inMemory } from "./memory.js";
11
- import { Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned, StoreWorkerLost } from "../store.js";
11
+ import { ONE_ANSWER_INDEX } from "../schema.js";
12
+ import { AnswerTaken, Fenced, RunFinal, StoreBusy, StoreClosed, StoreConstraint, StoreDeadline, StoreOwned, StoreWorkerLost } from "../store.js";
12
13
  /** How long a transaction may stay open (it holds every other call of the process) before it is rolled back. */
13
14
  export const DEFAULT_TRANSACTION_DEADLINE_MS = 10_000;
15
+ /** The interactive transactions open in this process, on any of its connections: each with where it was opened and when
16
+ * it began. A transaction's StoreDeadline, and a begin's StoreBusy, name them in their stack (never their message, which
17
+ * an answer may carry), so a log says who held the store: the deadline's own transaction, or another of this process's
18
+ * (an in-process runner's) holding the lock a begin waited on. */
19
+ const OPEN = new Set();
20
+ /** `opened`'s frames: where a transaction was asked for, without the Error line itself. */
21
+ const framesOf = (opened) => (opened.stack ?? "").split("\n").slice(1).join("\n");
22
+ /** `error` with its stack naming who held the store: `opened` (its own transaction's opener, when it has one), and every
23
+ * other transaction open in this process with its age. */
24
+ export function holderNamed(error, { opened } = {}) {
25
+ const lines = [];
26
+ if (opened)
27
+ lines.push(` the transaction was opened at:\n${framesOf(opened)}`);
28
+ const now = Date.now();
29
+ const others = [...OPEN].filter((open) => open.opened !== opened);
30
+ if (others.length)
31
+ lines.push(` other transactions open in this process:\n${others.map((open) => ` open ${now - open.began} ms, opened at:\n${framesOf(open.opened)}`).join("\n")}`);
32
+ if (lines.length)
33
+ error.stack = `${error.stack ?? `${error.name}: ${error.message}`}\n${lines.join("\n")}`;
34
+ return error;
35
+ }
14
36
  /** A statement's text parameters as the store writes text (dialect.ts cleanText: no NUL), on both stores alike. */
15
37
  const cleaned = (params) => (params ?? []).map((value) => (typeof value === "string" ? cleanText(value) : value));
16
38
  const cleanStatement = (statement) => ({ ...statement, params: cleaned(statement.params) });
17
39
  /** SQLite's extended constraint codes, by the rule they name. */
18
40
  const RULES = { 275: "check", 2067: "unique", 1555: "unique", 787: "foreign_key", 1299: "not_null" };
19
41
  /** Which rule refused a row, from SQLite's extended code; for a duplicate, its table and columns, which SQLite reports
20
- * only in its message ("UNIQUE constraint failed: t.a, t.b"): read here, in the SQLite adapter alone. */
42
+ * only in its message ("UNIQUE constraint failed: t.a, t.b"), or the index's name for an index on an expression
43
+ * ("UNIQUE constraint failed: index 'commands_one_answer'"): read here, in the SQLite adapter alone. */
21
44
  function constraintOf(errcode, message) {
22
45
  const rule = RULES[errcode];
23
46
  if (rule !== "unique")
24
47
  return rule ? { rule } : {};
48
+ const index = /UNIQUE constraint failed: index '([^']+)'$/.exec(message)?.[1];
49
+ if (index)
50
+ return { rule, index };
25
51
  const named = /UNIQUE constraint failed: (.+)$/.exec(message)?.[1]?.split(", ").map((part) => part.split("."));
26
52
  if (!named?.length || named.some((part) => part.length !== 2) || new Set(named.map(([table]) => table)).size !== 1)
27
53
  return { rule };
@@ -33,8 +59,13 @@ function typed(error) {
33
59
  return error.miss.kind === "fenced" ? new Fenced(error.miss.runId, error.miss.epoch) : new RunFinal(error.miss.runId);
34
60
  case "busy":
35
61
  return new StoreBusy(`the store stayed locked past its busy wait: ${error.message}`);
36
- case "constraint":
37
- return new StoreConstraint(error.message, constraintOf(error.errcode, error.message));
62
+ case "constraint": {
63
+ const refused = constraintOf(error.errcode, error.message);
64
+ // A second answer to one approval (the one-answer index): the answer written first stands.
65
+ if (refused.rule === "unique" && refused.index === ONE_ANSWER_INDEX)
66
+ return new AnswerTaken(error.message, refused.index);
67
+ return new StoreConstraint(error.message, refused);
68
+ }
38
69
  case "closed":
39
70
  return new StoreClosed();
40
71
  case "owned":
@@ -215,6 +246,8 @@ export class Connection {
215
246
  transaction(callback, { full = false, read = false, deadlineMs = DEFAULT_TRANSACTION_DEADLINE_MS, fromCall = false } = {}) {
216
247
  // `fromCall`: the deadline's end, counted from now (the queue's wait inside it); else counted from the begin.
217
248
  const until = fromCall ? Date.now() + deadlineMs : undefined;
249
+ // Where it was asked for: a deadline or a busy begin names it (holderNamed).
250
+ const opened = new Error("a store transaction");
218
251
  // Set when its deadline ran out while it still waited in the queue: its turn then begins nothing.
219
252
  let gaveUp = false;
220
253
  let started = false;
@@ -222,7 +255,7 @@ export class Connection {
222
255
  const run = this.#queued(async () => {
223
256
  started = true;
224
257
  if (gaveUp || (until !== undefined && Date.now() >= until))
225
- throw new StoreDeadline(deadlineMs);
258
+ throw holderNamed(new StoreDeadline(deadlineMs), { opened });
226
259
  // Its wait for the database's lock (another process's write) bounded by what the deadline leaves: a lock still held
227
260
  // when that runs out is the deadline's end, not the connection's own busy wait.
228
261
  const busyMs = until !== undefined ? Math.max(0, until - Date.now()) : undefined;
@@ -231,55 +264,63 @@ export class Connection {
231
264
  }
232
265
  catch (error) {
233
266
  if (error instanceof StoreBusy && busyMs !== undefined && busyMs < this.#busyTimeoutMs)
234
- throw new StoreDeadline(deadlineMs);
235
- throw error;
267
+ throw holderNamed(new StoreDeadline(deadlineMs), { opened });
268
+ throw error instanceof StoreBusy ? holderNamed(error, { opened }) : error;
236
269
  }
237
- let live = true;
238
- let clear = () => { };
239
- const deadline = new Promise((_, reject) => {
240
- const expire = () => reject(new StoreDeadline(deadlineMs));
241
- // Counted from its call (a lease's), the deadline stays the wall clock's: MCP_REFRESH_LEASE_MS is reckoned from
242
- // it. Counted from its begin, it is the time this process could run (store/deadline.ts runnableDeadline): while other work held
243
- // the event loop, a statement answered meanwhile waited behind it, and that time was no statement's.
244
- if (until !== undefined) {
245
- const timer = setTimeout(expire, Math.max(0, until - Date.now()));
246
- clear = () => clearTimeout(timer);
247
- }
248
- else
249
- clear = runnableDeadline(deadlineMs, expire).clear;
250
- });
251
- let value;
270
+ const open = { opened, began: Date.now() };
271
+ OPEN.add(open);
252
272
  try {
253
- // The worker answers in order: a statement already sent finishes before the rollback a deadline sends after it.
254
- const running = callback(this.#executor(() => live));
255
- // Past the deadline the callback's own end is nobody's: its refused next statement must not surface as an
256
- // unhandled rejection.
257
- running.catch(() => undefined);
258
- value = await Promise.race([running, deadline]);
259
- }
260
- catch (error) {
273
+ let live = true;
274
+ let clear = () => { };
275
+ const deadline = new Promise((_, reject) => {
276
+ const expire = () => reject(holderNamed(new StoreDeadline(deadlineMs), { opened }));
277
+ // Counted from its call (a lease's), the deadline stays the wall clock's: MCP_REFRESH_LEASE_MS is reckoned from
278
+ // it. Counted from its begin, it is the time this process could run (store/deadline.ts runnableDeadline): while other work held
279
+ // the event loop, a statement answered meanwhile waited behind it, and that time was no statement's.
280
+ if (until !== undefined) {
281
+ const timer = setTimeout(expire, Math.max(0, until - Date.now()));
282
+ clear = () => clearTimeout(timer);
283
+ }
284
+ else
285
+ clear = runnableDeadline(deadlineMs, expire).clear;
286
+ });
287
+ let value;
288
+ try {
289
+ // The worker answers in order: a statement already sent finishes before the rollback a deadline sends after it.
290
+ const running = callback(this.#executor(() => live));
291
+ // Past the deadline the callback's own end is nobody's: its refused next statement must not surface as an
292
+ // unhandled rejection.
293
+ running.catch(() => undefined);
294
+ value = await Promise.race([running, deadline]);
295
+ }
296
+ catch (error) {
297
+ live = false;
298
+ clear();
299
+ try {
300
+ await this.#send({ op: "rollback" });
301
+ }
302
+ catch (rollback) {
303
+ // A worker lost mid-transaction failed both: its loss is the one error, as every later call's.
304
+ if (this.#lost)
305
+ throw this.#lost;
306
+ throw new AggregateError([error, rollback], "the store's transaction failed, and so did its rollback");
307
+ }
308
+ throw error;
309
+ }
261
310
  live = false;
262
311
  clear();
263
- try {
312
+ // Counted from its call, a deadline reached by now is never committed past: rolled back, nothing written.
313
+ if (until !== undefined && Date.now() >= until) {
264
314
  await this.#send({ op: "rollback" });
315
+ throw holderNamed(new StoreDeadline(deadlineMs), { opened });
265
316
  }
266
- catch (rollback) {
267
- // A worker lost mid-transaction failed both: its loss is the one error, as every later call's.
268
- if (this.#lost)
269
- throw this.#lost;
270
- throw new AggregateError([error, rollback], "the store's transaction failed, and so did its rollback");
271
- }
272
- throw error;
317
+ await this.#send({ op: "commit" });
318
+ return value;
273
319
  }
274
- live = false;
275
- clear();
276
- // Counted from its call, a deadline reached by now is never committed past: rolled back, nothing written.
277
- if (until !== undefined && Date.now() >= until) {
278
- await this.#send({ op: "rollback" });
279
- throw new StoreDeadline(deadlineMs);
320
+ finally {
321
+ // Kept until the worker has answered the commit or rollback: until then this transaction still holds the lock.
322
+ OPEN.delete(open);
280
323
  }
281
- await this.#send({ op: "commit" });
282
- return value;
283
324
  });
284
325
  if (until === undefined)
285
326
  return run;
@@ -291,7 +332,7 @@ export class Connection {
291
332
  if (started)
292
333
  return;
293
334
  gaveUp = true;
294
- reject(new StoreDeadline(deadlineMs));
335
+ reject(holderNamed(new StoreDeadline(deadlineMs), { opened }));
295
336
  }, deadlineMs);
296
337
  });
297
338
  return Promise.race([run, queuedPast]).finally(() => clearTimeout(waitTimer));
@@ -51,7 +51,23 @@ export declare const runOf: (r: RunRecord) => RunRow;
51
51
  * run in the same statement. `dialect`: the connection's (store/dialect.ts), SQLite's by default. `clock`: the deadlines'
52
52
  * clock (fence.ts storeNow) the fence and left_running_at read; `now` bound by default. */
53
53
  export declare function applyRunPatch(tx: Pick<SqliteExecutor, "run" | "get">, claim: Pick<Claim, "runId" | "epoch">, patch: RunPatch, also: readonly AlsoRow[], now: number, dialect?: Dialect, clock?: StoreNow): Promise<RunRow>;
54
+ /** 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
55
+ * with no runner (released: a runner claims it at once), its end's own fields cleared, its epoch, journal, cost and
56
+ * metrics kept. `where` holds only for an agentic run that ended completed or that a person stopped (state 'stopped',
57
+ * outcome 'stopped': its turn ended, never the run, as main's stop leaves one), not imported and not a learning run. A
58
+ * cancelled run, a failed one and a workflow run are over for good. */
59
+ export declare const REOPEN_SET = "state = 'running', runner = NULL, claimed_until = NULL, wake_at = NULL, backoff_until = NULL, ended_at = NULL, summary = NULL, outcome = NULL";
60
+ export declare const reopenableWhere: (d: Dialect) => string;
54
61
  /** After a write that made the run final has taken its own rows: every command row of the run still untaken is refused
55
62
  * with the end's reason, in that same transaction. The store takes no new row on a final run (RunFinal), so a row the
56
- * end left untaken would stay so for good, as it would if the runner died right after the end. */
57
- export declare function refuseLeftovers(tx: Pick<SqliteExecutor, "run">, runId: string, state: RunState | undefined, now: number): Promise<void>;
63
+ * end left untaken would stay so for good, as it would if the runner died right after the end.
64
+ * 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,
65
+ * or before its end: the adapter loop leaves it untaken), opens a run that ended completed again, in this same
66
+ * transaction, as main answers such a message once the end is in (runs.ts message: a completed run opens again, its
67
+ * message the next turn): the run is back to running and released (REOPEN_SET), the message waits untaken for the next
68
+ * 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
69
+ * before the end, it opens the run here; after it, the store refuses a new row (RunFinal) and runs.reopen takes it.
70
+ * 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
71
+ * message submitted before it to run; a cancel's refuses it. A run left final here has its launch secrets erased (its
72
+ * launch row's `sealed`); a run opened again keeps the ones its waiting message wrote. */
73
+ export declare function refuseLeftovers(tx: Pick<SqliteExecutor, "run" | "get">, runId: string, state: RunState | undefined, now: number, dialect?: Dialect): Promise<void>;