@parcha/agentrun-serve 0.1.0-beta.34 → 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 (450) hide show
  1. package/CHANGELOG.md +263 -0
  2. package/README.md +339 -179
  3. package/dist/adapters.d.ts +15 -2
  4. package/dist/adapters.js +34 -2
  5. package/dist/agent-rows.d.ts +3 -1
  6. package/dist/agents-store.d.ts +2 -0
  7. package/dist/agents-store.js +25 -5
  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 +90 -8
  13. package/dist/archil-settings.js +150 -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/bash-read-only.d.ts +13 -0
  19. package/dist/bash-read-only.js +77 -0
  20. package/dist/box-image.d.ts +1 -97
  21. package/dist/box-image.js +4 -284
  22. package/dist/box-paths.d.ts +2 -7
  23. package/dist/box-paths.js +7 -13
  24. package/dist/box-settings.d.ts +0 -11
  25. package/dist/box-settings.js +4 -29
  26. package/dist/browser-commands.js +1 -1
  27. package/dist/browser-computer.d.ts +47 -3
  28. package/dist/browser-computer.js +286 -18
  29. package/dist/browser-cost.d.ts +2 -2
  30. package/dist/browser-cost.js +6 -4
  31. package/dist/browser-person.d.ts +19 -2
  32. package/dist/browser-person.js +55 -6
  33. package/dist/browser-wait-ended.d.ts +23 -0
  34. package/dist/browser-wait-ended.js +42 -0
  35. package/dist/cap.d.ts +19 -44
  36. package/dist/cap.js +31 -77
  37. package/dist/cli.js +36 -27
  38. package/dist/computer-keys.d.ts +20 -10
  39. package/dist/computer-keys.js +36 -57
  40. package/dist/computer-routes.d.ts +1 -4
  41. package/dist/computer-routes.js +3 -5
  42. package/dist/computer-setting.d.ts +8 -5
  43. package/dist/computer-setting.js +91 -26
  44. package/dist/computer-view.d.ts +11 -2
  45. package/dist/computer-view.js +2 -1
  46. package/dist/computers.d.ts +54 -8
  47. package/dist/computers.js +101 -22
  48. package/dist/console/assets/index-BI4Byidu.js +550 -0
  49. package/dist/console/assets/index-C19gUF2n.css +1 -0
  50. package/dist/console/index.html +2 -2
  51. package/dist/content-filter.d.ts +7 -0
  52. package/dist/content-filter.js +23 -0
  53. package/dist/decision-cap.d.ts +7 -29
  54. package/dist/decision-cap.js +3 -94
  55. package/dist/docker-daemon.d.ts +2 -2
  56. package/dist/docker-daemon.js +2 -2
  57. package/dist/errors.d.ts +1 -0
  58. package/dist/errors.js +8 -5
  59. package/dist/explain.js +3 -1
  60. package/dist/faux-computers.js +4 -0
  61. package/dist/files.d.ts +1 -9
  62. package/dist/files.js +1 -9
  63. package/dist/github-connection.js +25 -7
  64. package/dist/github-faux.d.ts +26 -0
  65. package/dist/github-faux.js +76 -0
  66. package/dist/github.d.ts +28 -4
  67. package/dist/github.js +46 -10
  68. package/dist/gpu-words.d.ts +14 -0
  69. package/dist/gpu-words.js +21 -0
  70. package/dist/graph-served.d.ts +5 -3
  71. package/dist/graph-served.js +14 -6
  72. package/dist/graph-view.d.ts +2 -0
  73. package/dist/graph-view.js +29 -2
  74. package/dist/handed-values.d.ts +1 -1
  75. package/dist/handed-values.js +1 -1
  76. package/dist/harness-install.d.ts +60 -3
  77. package/dist/harness-install.js +322 -34
  78. package/dist/harness-opencode/harness.js +0 -1
  79. package/dist/harness-opencode/host/policy.js +2 -2
  80. package/dist/harness.js +1 -1
  81. package/dist/host-tools.d.ts +8 -9
  82. package/dist/host-tools.js +7 -7
  83. package/dist/index.d.ts +2 -3
  84. package/dist/index.js +2 -2
  85. package/dist/key-refusal.d.ts +1 -1
  86. package/dist/key-refusal.js +2 -2
  87. package/dist/learn/check.d.ts +10 -2
  88. package/dist/learn/check.js +126 -8
  89. package/dist/learn/commit.d.ts +40 -6
  90. package/dist/learn/commit.js +164 -20
  91. package/dist/learn/folder.d.ts +11 -3
  92. package/dist/learn/folder.js +40 -16
  93. package/dist/learn/grade.d.ts +22 -2
  94. package/dist/learn/grade.js +127 -19
  95. package/dist/learn/index.d.ts +2 -2
  96. package/dist/learn/index.js +2 -2
  97. package/dist/learn/learning.sh +11 -13
  98. package/dist/learn/notes.d.ts +17 -3
  99. package/dist/learn/notes.js +19 -6
  100. package/dist/learn/reflect.d.ts +5 -2
  101. package/dist/learn/reflect.js +48 -32
  102. package/dist/learn/skills.d.ts +52 -5
  103. package/dist/learn/skills.js +104 -21
  104. package/dist/learned-nodes.d.ts +18 -0
  105. package/dist/learned-nodes.js +8 -0
  106. package/dist/learned-workflow.d.ts +27 -13
  107. package/dist/learned-workflow.js +110 -38
  108. package/dist/learning-cost.d.ts +79 -0
  109. package/dist/learning-cost.js +69 -0
  110. package/dist/learning-routes.d.ts +48 -2
  111. package/dist/learning-routes.js +99 -28
  112. package/dist/learning-run.d.ts +7 -5
  113. package/dist/learning-run.js +9 -6
  114. package/dist/learning-words.d.ts +3 -0
  115. package/dist/learning-words.js +6 -2
  116. package/dist/learning.d.ts +13 -28
  117. package/dist/learning.js +4 -18
  118. package/dist/llm.d.ts +4 -1
  119. package/dist/llm.js +4 -2
  120. package/dist/mcp-gateway.d.ts +6 -0
  121. package/dist/mcp-gateway.js +11 -1
  122. package/dist/mcp-probe.d.ts +8 -1
  123. package/dist/mcp-probe.js +62 -20
  124. package/dist/mcp-secret-writes.js +4 -0
  125. package/dist/mcp-servers-store.d.ts +12 -12
  126. package/dist/mcp-servers-store.js +8 -3
  127. package/dist/model.d.ts +8 -5
  128. package/dist/model.js +14 -6
  129. package/dist/openapi.d.ts +2 -0
  130. package/dist/openapi.js +236 -55
  131. package/dist/owner.d.ts +0 -1
  132. package/dist/owner.js +0 -2
  133. package/dist/pause.d.ts +2 -19
  134. package/dist/pause.js +5 -74
  135. package/dist/place-offers.d.ts +97 -0
  136. package/dist/place-offers.js +206 -0
  137. package/dist/place.d.ts +9 -13
  138. package/dist/place.js +22 -32
  139. package/dist/port-models.d.ts +12 -4
  140. package/dist/port-models.js +31 -9
  141. package/dist/print.d.ts +1 -8
  142. package/dist/print.js +1 -14
  143. package/dist/propose.d.ts +3 -0
  144. package/dist/propose.js +25 -19
  145. package/dist/run-cut.d.ts +5 -0
  146. package/dist/run-cut.js +19 -0
  147. package/dist/run-db.js +3 -3
  148. package/dist/run-launch.d.ts +18 -3
  149. package/dist/run-launch.js +11 -5
  150. package/dist/run-learning-served.d.ts +12 -1
  151. package/dist/run-manifest.d.ts +2 -2
  152. package/dist/run-manifest.js +2 -2
  153. package/dist/run-reads-over-store.d.ts +4 -2
  154. package/dist/run-reads-over-store.js +10 -8
  155. package/dist/run-secrets.js +3 -3
  156. package/dist/run-timeline-served.js +60 -38
  157. package/dist/run-view.d.ts +35 -16
  158. package/dist/run-view.js +64 -35
  159. package/dist/runnable.d.ts +6 -3
  160. package/dist/runnable.js +20 -4
  161. package/dist/runner/adapter-loop.d.ts +46 -5
  162. package/dist/runner/adapter-loop.js +381 -56
  163. package/dist/runner/adapter-run-spec.d.ts +46 -4
  164. package/dist/runner/adapter-run-spec.js +200 -45
  165. package/dist/runner/adapters/pi.d.ts +39 -3
  166. package/dist/runner/adapters/pi.js +124 -29
  167. package/dist/runner/beside.d.ts +8 -0
  168. package/dist/runner/beside.js +24 -2
  169. package/dist/runner/claim-secrets.d.ts +6 -0
  170. package/dist/runner/claim-secrets.js +15 -1
  171. package/dist/runner/cli-run-spec.d.ts +10 -0
  172. package/dist/runner/cli-run-spec.js +207 -64
  173. package/dist/runner/commands.d.ts +5 -1
  174. package/dist/runner/commands.js +3 -3
  175. package/dist/runner/conformance/harness.d.ts +1 -1
  176. package/dist/runner/conformance/harness.js +13 -10
  177. package/dist/runner/github-app.d.ts +7 -2
  178. package/dist/runner/github-app.js +46 -15
  179. package/dist/runner/harness-loops.d.ts +6 -1
  180. package/dist/runner/harness-loops.js +24 -1
  181. package/dist/runner/journal-kinds.d.ts +53 -7
  182. package/dist/runner/journal-kinds.js +29 -1
  183. package/dist/runner/learning-end.d.ts +15 -0
  184. package/dist/runner/learning-end.js +113 -20
  185. package/dist/runner/learning-factory.js +6 -2
  186. package/dist/runner/learning-loop.d.ts +75 -1
  187. package/dist/runner/learning-loop.js +215 -22
  188. package/dist/runner/learning-seed.d.ts +8 -0
  189. package/dist/runner/learning-seed.js +7 -1
  190. package/dist/runner/loop-contract.d.ts +12 -0
  191. package/dist/runner/loop-contract.js +6 -0
  192. package/dist/runner/loop.d.ts +5 -1
  193. package/dist/runner/loop.js +20 -0
  194. package/dist/runner/main.d.ts +9 -4
  195. package/dist/runner/main.js +38 -13
  196. package/dist/runner/mcp-claim.d.ts +7 -0
  197. package/dist/runner/mcp-claim.js +35 -2
  198. package/dist/runner/mcp-github.d.ts +15 -4
  199. package/dist/runner/mcp-github.js +55 -11
  200. package/dist/runner/mcp-run.d.ts +2 -0
  201. package/dist/runner/mcp-run.js +2 -0
  202. package/dist/runner/metrics.d.ts +18 -1
  203. package/dist/runner/metrics.js +81 -1
  204. package/dist/runner/model-route.d.ts +6 -0
  205. package/dist/runner/model-route.js +5 -2
  206. package/dist/runner/pr-checkout.d.ts +59 -0
  207. package/dist/runner/pr-checkout.js +176 -0
  208. package/dist/runner/reflect-hook.d.ts +1 -0
  209. package/dist/runner/reflect-hook.js +3 -3
  210. package/dist/runner/runner.js +136 -19
  211. package/dist/runner/spec-holds.d.ts +13 -3
  212. package/dist/runner/spec-holds.js +13 -10
  213. package/dist/runner/store-port.d.ts +4 -1
  214. package/dist/runner/store-secrets.js +17 -1
  215. package/dist/runner/subagent.d.ts +44 -0
  216. package/dist/runner/subagent.js +188 -0
  217. package/dist/runner/workflow-host.d.ts +25 -4
  218. package/dist/runner/workflow-host.js +26 -4
  219. package/dist/runner/workflow-loop.d.ts +9 -3
  220. package/dist/runner/workflow-loop.js +17 -10
  221. package/dist/runner/workflow-spec.d.ts +28 -13
  222. package/dist/runner/workflow-spec.js +247 -102
  223. package/dist/runs-over-store.d.ts +18 -7
  224. package/dist/runs-over-store.js +149 -31
  225. package/dist/seal-key.d.ts +0 -2
  226. package/dist/seal-key.js +0 -2
  227. package/dist/sealing.js +1 -2
  228. package/dist/secret-cut.d.ts +1 -1
  229. package/dist/secret-cut.js +1 -1
  230. package/dist/server-lock.js +4 -5
  231. package/dist/server.d.ts +49 -63
  232. package/dist/server.js +429 -230
  233. package/dist/stop-signals.d.ts +4 -2
  234. package/dist/stop-signals.js +5 -3
  235. package/dist/store/agent-body.d.ts +14 -3
  236. package/dist/store/agent-body.js +22 -8
  237. package/dist/store/deadline.d.ts +18 -0
  238. package/dist/store/deadline.js +49 -0
  239. package/dist/store/index.d.ts +3 -3
  240. package/dist/store/index.js +2 -2
  241. package/dist/store/journal/storage.js +2 -1
  242. package/dist/store/postgres/connection.d.ts +4 -0
  243. package/dist/store/postgres/connection.js +64 -13
  244. package/dist/store/postgres/migrations/0004_runs_outcome_stop_or_cancel.sql +11 -0
  245. package/dist/store/schema.d.ts +2 -1
  246. package/dist/store/schema.js +11 -8
  247. package/dist/store/seal.d.ts +13 -0
  248. package/dist/store/seal.js +19 -0
  249. package/dist/store/sqlite/connection.d.ts +5 -0
  250. package/dist/store/sqlite/connection.js +88 -82
  251. package/dist/store/sqlite/run-patch.d.ts +18 -2
  252. package/dist/store/sqlite/run-patch.js +31 -2
  253. package/dist/store/sqlite/store.js +65 -11
  254. package/dist/store/store.d.ts +62 -12
  255. package/dist/store/store.js +22 -1
  256. package/dist/store-reads/analytics.js +3 -2
  257. package/dist/store-reads/cap.d.ts +1 -3
  258. package/dist/store-reads/cap.js +8 -6
  259. package/dist/store-reads/decisions.d.ts +2 -2
  260. package/dist/store-reads/decisions.js +3 -6
  261. package/dist/store-reads/journal.js +83 -15
  262. package/dist/store-reads/learning.d.ts +73 -3
  263. package/dist/store-reads/learning.js +232 -9
  264. package/dist/store-reads/runs.d.ts +6 -4
  265. package/dist/store-reads/runs.js +17 -10
  266. package/dist/store-reads/stats.js +5 -1
  267. package/dist/store-view.d.ts +15 -1
  268. package/dist/store-view.js +88 -29
  269. package/dist/template-eval.js +2 -1
  270. package/dist/templates.d.ts +73 -4
  271. package/dist/templates.js +113 -23
  272. package/dist/timeline/timeline.d.ts +11 -1
  273. package/dist/timeline/timeline.js +19 -4
  274. package/dist/tool-blurbs.js +1 -0
  275. package/dist/tool-budget.d.ts +26 -0
  276. package/dist/tool-budget.js +56 -0
  277. package/dist/tool-gate.d.ts +13 -3
  278. package/dist/tool-gate.js +15 -7
  279. package/dist/tool-plane.d.ts +42 -29
  280. package/dist/tool-plane.js +64 -27
  281. package/dist/tools.d.ts +53 -39
  282. package/dist/tools.js +174 -79
  283. package/dist/trigger-signatures.d.ts +1 -0
  284. package/dist/trigger-signatures.js +3 -1
  285. package/dist/triggers.d.ts +3 -3
  286. package/dist/triggers.js +2 -2
  287. package/dist/turn-end.d.ts +0 -3
  288. package/dist/turn-end.js +0 -3
  289. package/dist/uploads.d.ts +28 -5
  290. package/dist/uploads.js +82 -9
  291. package/dist/usage-lines.d.ts +1 -1
  292. package/dist/usage.d.ts +1 -47
  293. package/dist/usage.js +3 -82
  294. package/dist/validate.d.ts +8 -0
  295. package/dist/validate.js +40 -3
  296. package/dist/webhooks.d.ts +2 -1
  297. package/dist/webhooks.js +5 -2
  298. package/dist/workflow/decision-recovery.d.ts +23 -0
  299. package/dist/workflow/decision-recovery.js +80 -0
  300. package/dist/workflow/decisions.d.ts +134 -0
  301. package/dist/workflow/decisions.js +46 -0
  302. package/dist/workflow/host-session.d.ts +5 -0
  303. package/dist/workflow/host-session.js +85 -0
  304. package/dist/workflow/host-tools.d.ts +3 -0
  305. package/dist/workflow/host-tools.js +3 -0
  306. package/dist/workflow/node-runner.d.ts +112 -0
  307. package/dist/workflow/node-runner.js +270 -0
  308. package/dist/workflow/node.d.ts +88 -0
  309. package/dist/workflow/node.js +99 -0
  310. package/dist/workflow/operator-error.d.ts +4 -0
  311. package/dist/workflow/operator-error.js +4 -0
  312. package/dist/workflow/pi-versions.d.ts +9 -0
  313. package/dist/workflow/pi-versions.js +8 -0
  314. package/dist/workflow/readers.d.ts +36 -0
  315. package/dist/workflow/readers.js +145 -0
  316. package/dist/workflow/record-file.d.ts +10 -0
  317. package/dist/workflow/record-file.js +56 -0
  318. package/dist/workflow/record-tool.d.ts +76 -0
  319. package/dist/workflow/record-tool.js +126 -0
  320. package/dist/workflow/record.d.ts +151 -0
  321. package/dist/workflow/record.js +401 -0
  322. package/dist/workflow/run-error.d.ts +16 -0
  323. package/dist/workflow/run-error.js +26 -0
  324. package/dist/workflow/runner.d.ts +6 -0
  325. package/dist/workflow/runner.js +240 -0
  326. package/dist/workflow/store.d.ts +23 -0
  327. package/dist/workflow/store.js +242 -0
  328. package/dist/workflow/task.d.ts +133 -0
  329. package/dist/workflow/task.js +411 -0
  330. package/dist/workflow/thinking.d.ts +3 -0
  331. package/dist/workflow/thinking.js +7 -0
  332. package/dist/workflow/tool-context.d.ts +21 -0
  333. package/dist/workflow/tool-context.js +13 -0
  334. package/dist/workflow/types.d.ts +126 -0
  335. package/dist/workflow/types.js +1 -0
  336. package/dist/workflow/wal.d.ts +11 -0
  337. package/dist/workflow/wal.js +106 -0
  338. package/dist/workflow-run.d.ts +1 -1
  339. package/dist/workspace/agent-computer.d.ts +137 -0
  340. package/dist/workspace/agent-computer.js +292 -0
  341. package/dist/workspace/archil-claim.d.ts +13 -2
  342. package/dist/workspace/archil-claim.js +22 -13
  343. package/dist/workspace/archil-disk.d.ts +10 -1
  344. package/dist/workspace/archil-disk.js +4 -0
  345. package/dist/workspace/archil-disks.d.ts +49 -0
  346. package/dist/workspace/archil-disks.js +185 -0
  347. package/dist/workspace/archil-exec.d.ts +12 -2
  348. package/dist/workspace/archil-exec.js +18 -3
  349. package/dist/workspace/archil-mount-credential.d.ts +20 -4
  350. package/dist/workspace/archil-mount-credential.js +13 -4
  351. package/dist/workspace/archil.d.ts +2 -2
  352. package/dist/workspace/archil.js +25 -5
  353. package/dist/workspace/attach.js +2 -0
  354. package/dist/workspace/computer-deps.d.ts +18 -11
  355. package/dist/workspace/computer-deps.js +64 -40
  356. package/dist/workspace/computer-for-claim.d.ts +47 -9
  357. package/dist/workspace/computer-for-claim.js +236 -24
  358. package/dist/workspace/computer-janitor.d.ts +3 -2
  359. package/dist/workspace/computer-janitor.js +43 -9
  360. package/dist/workspace/computer-ledger.d.ts +3 -8
  361. package/dist/workspace/computer-ledger.js +7 -3
  362. package/dist/workspace/computer-providers.d.ts +5 -3
  363. package/dist/workspace/computer-providers.js +11 -9
  364. package/dist/workspace/hands.d.ts +5 -2
  365. package/dist/workspace/hands.js +4 -3
  366. package/dist/workspace/index.d.ts +5 -4
  367. package/dist/workspace/index.js +2 -1
  368. package/dist/workspace/local.d.ts +3 -0
  369. package/dist/workspace/local.js +9 -0
  370. package/dist/workspace/paths.js +3 -2
  371. package/dist/workspace/pi-env.d.ts +4 -0
  372. package/dist/workspace/pi-env.js +3 -2
  373. package/dist/workspace/resolve-computer.d.ts +48 -12
  374. package/dist/workspace/resolve-computer.js +88 -19
  375. package/dist/workspace/run-disk.d.ts +34 -0
  376. package/dist/workspace/run-disk.js +91 -0
  377. package/dist/workspace/run-tools.d.ts +6 -4
  378. package/dist/workspace/run-tools.js +17 -9
  379. package/dist/workspace/server-run-workspace.d.ts +3 -2
  380. package/dist/workspace/server-run-workspace.js +17 -4
  381. package/dist/workspace/workspace.d.ts +5 -0
  382. package/dist/workspace.d.ts +0 -3
  383. package/dist/workspace.js +2 -15
  384. package/package.json +11 -16
  385. package/skills/agentrun-serve/SKILL.md +1 -1
  386. package/templates/README.md +11 -8
  387. package/templates/code-review/agent.md +27 -11
  388. package/templates/code-review/evals/clean-refactor/graders/coverage.md +4 -0
  389. package/templates/code-review/evals/clean-refactor/graders/risk.md +5 -0
  390. package/templates/code-review/evals/injection/graders/ignores.md +1 -1
  391. package/templates/code-review/evals/mentions-defused/case.yaml +15 -0
  392. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +254 -0
  393. package/templates/code-review/evals/mentions-defused/graders/no-pings.md +16 -0
  394. package/templates/code-review/evals/mentions-defused/graders/posted-a-review.md +5 -0
  395. package/templates/code-review/evals/mentions-defused/graders/schema.md +5 -0
  396. package/templates/code-review/evals/mentions-defused/prompt.md +10 -0
  397. package/templates/code-review/evals/never-flag/case.yaml +3 -0
  398. package/templates/code-review/evals/never-flag/graders/only-p0.md +4 -0
  399. package/templates/code-review/evals/never-flag/graders/schema.md +5 -0
  400. package/templates/code-review/evals/never-flag/prompt.md +30 -0
  401. package/templates/code-review/evals/null-name/graders/finds.md +1 -1
  402. package/templates/code-review/evals/off-by-one/graders/finds.md +1 -1
  403. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +6 -5
  404. package/templates/code-review/evals/re-review/graders/resolves.md +1 -1
  405. package/templates/code-review/evals/re-review/prompt.md +1 -1
  406. package/templates/code-review/evals/re-review-open/case.yaml +3 -0
  407. package/templates/code-review/evals/re-review-open/graders/schema.md +5 -0
  408. package/templates/code-review/evals/re-review-open/graders/stays-open.md +4 -0
  409. package/templates/code-review/evals/re-review-open/prompt.md +27 -0
  410. package/templates/code-review/evals/repo-rule/graders/cites.md +1 -1
  411. package/templates/code-review/evals/two-defects/case.yaml +3 -0
  412. package/templates/code-review/evals/two-defects/graders/both.md +4 -0
  413. package/templates/code-review/evals/two-defects/graders/schema.md +5 -0
  414. package/templates/code-review/evals/two-defects/prompt.md +25 -0
  415. package/templates/code-review/findings.schema.json +131 -27
  416. package/templates/code-review/rules/CODEREVIEW.md +76 -0
  417. package/templates/code-review/skills/review/DEEP.md +130 -0
  418. package/templates/code-review/skills/review/REVIEWER.md +116 -0
  419. package/templates/code-review/skills/review/SKILL.md +104 -154
  420. package/templates/kyb/evals/clean-public-company/graders/no-opensanctions.md +5 -0
  421. package/templates/kyb/evals/opensanctions-on/case.yaml +5 -0
  422. package/templates/kyb/evals/opensanctions-on/graders/licence-and-evidence.md +18 -0
  423. package/templates/kyb/evals/opensanctions-on/graders/schema.md +5 -0
  424. package/templates/kyb/evals/opensanctions-on/prompt.md +11 -0
  425. package/templates/release-notes/agent.md +11 -0
  426. package/dist/box/record.d.ts +0 -6
  427. package/dist/box/record.js +0 -41
  428. package/dist/box/sweep.d.ts +0 -53
  429. package/dist/box/sweep.js +0 -193
  430. package/dist/box-egress-vm.d.ts +0 -118
  431. package/dist/box-egress-vm.js +0 -354
  432. package/dist/box-egress.d.ts +0 -105
  433. package/dist/box-egress.js +0 -256
  434. package/dist/box-relay-vm.d.ts +0 -84
  435. package/dist/box-relay-vm.js +0 -437
  436. package/dist/box-relay.d.ts +0 -36
  437. package/dist/box-relay.js +0 -207
  438. package/dist/boxes.d.ts +0 -109
  439. package/dist/boxes.js +0 -249
  440. package/dist/budget.d.ts +0 -76
  441. package/dist/budget.js +0 -204
  442. package/dist/console/assets/index-RPHGlXmM.js +0 -540
  443. package/dist/console/assets/index-opTN5Naq.css +0 -1
  444. package/dist/daytona-api.d.ts +0 -10
  445. package/dist/daytona-api.js +0 -20
  446. package/dist/egress-proxy.d.ts +0 -45
  447. package/dist/egress-proxy.js +0 -416
  448. package/dist/egress-table.d.ts +0 -24
  449. package/dist/egress-table.js +0 -165
  450. package/templates/code-review/rules/REVIEW.md +0 -41
@@ -0,0 +1,240 @@
1
+ import { Compile } from "typebox/compile";
2
+ import { submitParameters } from "@parcha/agentrun-dsl";
3
+ import { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager, ModelRuntime, } from "@earendil-works/pi-coding-agent";
4
+ import { SUBMIT_TOOL } from "./host-tools.js";
5
+ import { PiRunError } from "./run-error.js";
6
+ import { nodeThinking } from "./thinking.js";
7
+ export { PiRunError } from "./run-error.js";
8
+ /** Why a review rejected a candidate, as the model reads it: its message, or, for none (no message, or a blank one),
9
+ * that it gave no reason. Always a string, so a rejection never lets the candidate through (the kernel's runner reads
10
+ * a review the same way). */
11
+ const reviewRejection = (message) => {
12
+ const said = message === undefined || message === null ? "" : String(message);
13
+ return said.trim() ? said : "the review rejected it without saying why";
14
+ };
15
+ function positive(value, name) {
16
+ if (!Number.isSafeInteger(value) || value < 1)
17
+ throw new Error(`${name} must be a positive integer`);
18
+ return value;
19
+ }
20
+ export function createPiRunner(options) {
21
+ if (!options.model || (!options.modelRuntime && !options.sessionFactory))
22
+ throw new Error("Pi requires an explicit model and modelRuntime, or a host-owned sessionFactory");
23
+ if (!options.sessionFactory && !(options.modelRuntime instanceof ModelRuntime))
24
+ throw new Error("modelRuntime must be a ModelRuntime instance from the supported Pi SDK");
25
+ const maxTurns = options.maxTurns === null ? null : positive(options.maxTurns ?? 8, "maxTurns");
26
+ const maxSubmissions = options.maxSubmissions === null ? null : positive(options.maxSubmissions ?? 5, "maxSubmissions");
27
+ const timeoutMs = options.timeoutMs === null ? null : positive(options.timeoutMs ?? 120_000, "timeoutMs");
28
+ const names = new Set();
29
+ for (const tool of options.tools ?? []) {
30
+ if (tool.name === SUBMIT_TOOL || names.has(tool.name))
31
+ throw new Error(`Reserved or duplicate Pi tool: ${tool.name}`);
32
+ names.add(tool.name);
33
+ }
34
+ return async (request) => {
35
+ const signals = [options.signal, request.signal].filter((s) => Boolean(s));
36
+ if (signals.some(s => s.aborted))
37
+ throw new PiRunError("aborted", 0, 0);
38
+ const requested = request.tools ?? [...names];
39
+ for (const name of requested)
40
+ if (!names.has(name))
41
+ throw new Error(`Pi tool was not explicitly registered: ${name}`);
42
+ // Every Pi node starts a fresh session, so there is no caller transcript to fork.
43
+ if (request.context === "fork")
44
+ throw new Error(`Pi node "${request.label}" asks for context: "fork", but the Pi runner starts every node in a fresh session and has no caller transcript to fork. Declare context: "fresh", or run it on a host that supports fork.`);
45
+ // A node's max_turns applies within this runner's limit, which caps it; without one the node gets the limit.
46
+ if (request.maxTurns !== undefined) {
47
+ positive(request.maxTurns, "maxTurns");
48
+ if (maxTurns !== null && request.maxTurns > maxTurns)
49
+ throw new Error(`Pi node "${request.label}" asks max_turns ${request.maxTurns}, above this host's cap of ${maxTurns} turns`);
50
+ }
51
+ const limit = request.maxTurns ?? maxTurns;
52
+ const validator = Compile(request.schema);
53
+ const parameters = submitParameters(request.schema);
54
+ const envelopeValidator = Compile(parameters);
55
+ let session;
56
+ let turns = 0, submissions = 0;
57
+ let lastTool;
58
+ let accepted = false;
59
+ let submission;
60
+ const pendingSubmissions = new Map();
61
+ let stopped;
62
+ let fatal;
63
+ let rejectStopped;
64
+ const interrupted = new Promise((_resolve, reject) => { rejectStopped = reject; });
65
+ void interrupted.catch(() => { });
66
+ const bounded = (work) => Promise.race([work, interrupted]);
67
+ const clean = (target) => {
68
+ void target.abort().catch(() => { });
69
+ target.dispose();
70
+ };
71
+ const failure = (reason) => new PiRunError(reason, turns, submissions, { maxTurns: limit, ...(lastTool === undefined ? {} : { lastTool }) });
72
+ const stop = (reason) => {
73
+ stopped ??= reason;
74
+ if (fatal)
75
+ rejectStopped(fatal);
76
+ else if (stopped)
77
+ rejectStopped(failure(stopped));
78
+ void session?.abort().catch(() => { });
79
+ };
80
+ const onAbort = () => stop("aborted");
81
+ signals.forEach(s => s.addEventListener("abort", onAbort, { once: true }));
82
+ const timer = timeoutMs === null ? undefined : setTimeout(() => stop("timeout"), timeoutMs);
83
+ let unsubscribe;
84
+ const result = (text, ok) => ({ content: [{ type: "text", text }], details: { accepted: ok } });
85
+ const submit = {
86
+ name: SUBMIT_TOOL, label: "Submit result", description: "Deliver a result matching the required JSON Schema. Rejection feedback must be corrected in this session.",
87
+ parameters,
88
+ executionMode: "sequential",
89
+ async execute(id, args) {
90
+ if (accepted)
91
+ return result("Already accepted; end your turn.", true);
92
+ if (stopped || fatal)
93
+ return result("This session has stopped.", false);
94
+ const pending = pendingSubmissions.get(id);
95
+ const original = pending && !pending.executed && Object.hasOwn(pending, "args") ? pending.args : args;
96
+ if (pending && !pending.executed)
97
+ pending.executed = true;
98
+ else
99
+ submissions++;
100
+ try {
101
+ const candidate = original?.value;
102
+ let message;
103
+ if (!envelopeValidator.Check(original))
104
+ message = JSON.stringify([...envelopeValidator.Errors(original)]);
105
+ else if (!validator.Check(candidate))
106
+ message = JSON.stringify([...validator.Errors(candidate)]);
107
+ else if (request.review) {
108
+ const verdict = await request.review(candidate);
109
+ if (!verdict.accepted)
110
+ message = reviewRejection(verdict.message);
111
+ else if (!validator.Check(candidate))
112
+ message = "The reviewed candidate no longer satisfies its output schema";
113
+ }
114
+ if (stopped)
115
+ return result("This session has stopped.", false);
116
+ if (message !== undefined) {
117
+ if (maxSubmissions !== null && submissions >= maxSubmissions)
118
+ stop("submission_limit");
119
+ return result(`Rejected: ${message}. Correct the result and call submit again.`, false);
120
+ }
121
+ submission = structuredClone(candidate);
122
+ accepted = true;
123
+ return result("Accepted. End your turn.", true);
124
+ }
125
+ catch (error) {
126
+ fatal = error;
127
+ stop();
128
+ return result("The host verifier failed; execution stopped.", false);
129
+ }
130
+ },
131
+ };
132
+ try {
133
+ const cwd = options.cwd ?? process.cwd();
134
+ const settingsManager = SettingsManager.inMemory({
135
+ enableAnalytics: false, enableInstallTelemetry: false,
136
+ retry: { enabled: false }, compaction: { enabled: false },
137
+ });
138
+ const resourceLoader = new DefaultResourceLoader({
139
+ cwd, agentDir: cwd, settingsManager,
140
+ noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
141
+ systemPrompt: [...request.system, 'Only a successful submit tool call delivers the result. Call submit with {"value": YOUR_RESULT}. The schema below describes value, not the envelope.', `Required JSON Schema: ${JSON.stringify(request.schema)}`].join("\n\n"),
142
+ appendSystemPromptOverride: () => [], agentsFilesOverride: () => ({ agentsFiles: [] }),
143
+ });
144
+ await bounded(resourceLoader.reload());
145
+ if (stopped)
146
+ throw failure(stopped);
147
+ const sessionManager = SessionManager.inMemory(cwd);
148
+ const prepared = {
149
+ cwd, model: options.model, modelRuntime: options.modelRuntime,
150
+ thinkingLevel: nodeThinking(request.thinking, options.thinkingLevel), maxTurns: limit ?? undefined, resourceLoader, settingsManager,
151
+ sessionManager,
152
+ tools: [...requested, SUBMIT_TOOL],
153
+ customTools: [...(options.tools ?? []).filter(tool => requested.includes(tool.name)).map(tool => ({
154
+ ...tool,
155
+ executionMode: "sequential",
156
+ execute: ((...args) => {
157
+ if (accepted || stopped || fatal)
158
+ throw new Error("Pi session has stopped; tool execution refused");
159
+ return tool.execute(...args);
160
+ }),
161
+ })), submit],
162
+ };
163
+ const opening = (options.sessionFactory
164
+ ? options.sessionFactory(prepared)
165
+ : createAgentSession({
166
+ ...prepared,
167
+ model: options.model,
168
+ modelRuntime: options.modelRuntime,
169
+ resourceLoader, settingsManager, sessionManager,
170
+ customTools: prepared.customTools,
171
+ })).then(opened => {
172
+ if (stopped || fatal)
173
+ clean(opened.session);
174
+ return opened;
175
+ });
176
+ ({ session } = await bounded(opening));
177
+ if (stopped)
178
+ throw failure(stopped);
179
+ unsubscribe = session.subscribe(event => {
180
+ // Native events carry correlation IDs, including SDK-rejected calls. Custom
181
+ // sessions without IDs use execute's counter so one attempt is not counted twice.
182
+ if (event.type === "tool_execution_start" && typeof event.toolName === "string")
183
+ lastTool = event.toolName.slice(0, 64);
184
+ if (event.type === "tool_execution_start" && event.toolName === SUBMIT_TOOL && event.toolCallId !== undefined && !accepted && !stopped && !fatal) {
185
+ submissions++;
186
+ pendingSubmissions.set(event.toolCallId, {
187
+ ...(Object.hasOwn(event, "args") ? { args: structuredClone(event.args) } : {}), executed: false,
188
+ });
189
+ if (maxSubmissions !== null && submissions > maxSubmissions)
190
+ stop("submission_limit");
191
+ }
192
+ if (event.type === "tool_execution_end" && event.toolName === SUBMIT_TOOL) {
193
+ if (event.toolCallId !== undefined)
194
+ pendingSubmissions.delete(event.toolCallId);
195
+ if (!accepted && !stopped && !fatal && maxSubmissions !== null && submissions >= maxSubmissions)
196
+ stop("submission_limit");
197
+ }
198
+ if (event.type === "turn_start")
199
+ turns++;
200
+ if (event.type === "turn_end" && !accepted && event.message?.role === "assistant" && (event.message.stopReason === "error" || event.message.stopReason === "aborted"))
201
+ stop(event.message.stopReason === "error" ? "model_error" : "aborted");
202
+ if (event.type === "turn_end" && (accepted || fatal || limit !== null && turns >= limit))
203
+ stop(accepted || fatal ? undefined : "turn_limit");
204
+ options.onEvent?.(event);
205
+ });
206
+ let prompt = request.user;
207
+ while (!accepted && !stopped && !fatal && (limit === null || turns < limit)) {
208
+ const before = turns;
209
+ await bounded(session.prompt(prompt, { expandPromptTemplates: false }));
210
+ if (turns === before)
211
+ turns++;
212
+ prompt = "You finished without an accepted submission. Call submit with the complete result; plain text does not deliver it.";
213
+ }
214
+ if (fatal)
215
+ throw fatal;
216
+ if (stopped)
217
+ throw failure(stopped);
218
+ if (accepted)
219
+ return submission;
220
+ // The loop ends only on one of the three above or at the turn cap, so what is left is the cap.
221
+ throw failure("turn_limit");
222
+ }
223
+ catch (error) {
224
+ if (fatal)
225
+ throw fatal;
226
+ if (stopped)
227
+ throw failure(stopped);
228
+ if (accepted)
229
+ return submission;
230
+ throw error;
231
+ }
232
+ finally {
233
+ clearTimeout(timer);
234
+ signals.forEach(s => s.removeEventListener("abort", onAbort));
235
+ unsubscribe?.();
236
+ if (session)
237
+ clean(session);
238
+ }
239
+ };
240
+ }
@@ -0,0 +1,23 @@
1
+ import type { Harness } from "@earendil-works/pi-durable";
2
+ import type { Context } from "@earendil-works/chord";
3
+ import { type RecoveryStore } from "@parcha/agentrun-dsl/recovery";
4
+ /** An effect's key in `agentrun.effects`: its journal key, then its id. The two are joined by NUL, so neither may hold
5
+ * one: two pairs could otherwise name the same document. */
6
+ export declare const effectKey: (key: string, id: string) => string;
7
+ /** What a store writes through: a Harness, or the `commit` a running task is handed. */
8
+ export type DocumentStoreHost = Pick<Harness, "commit">;
9
+ export type DocumentStoreOptions = {
10
+ /** The one owner of the journal across the invocations of a task (its id). An open by this owner takes over a journal
11
+ * an earlier invocation left open, whose later writes then fail; an open by another owner is refused while the
12
+ * journal is open. The guard is per process, by journal key: an owner is unique to its run, and two Harness files in
13
+ * one process that hold one run key under one owner count as one. Without an owner the guard is per host object,
14
+ * and a second open of a key is refused until the first is closed. */
15
+ owner?: string;
16
+ /** The context every commit runs under; default `BACKGROUND_CONTEXT`. A task passes its invocation's, so the
17
+ * invocation's cancellation ends its writes. */
18
+ context?: Context;
19
+ };
20
+ /** The recovery store for the journal `key` that `host` writes. Opening it takes ownership: a journal already open is
21
+ * refused (unless the same `owner` opens it again), a binding that differs from the one the journal was first opened
22
+ * under is refused naming the inputs that moved, and the generation advances. */
23
+ export declare function documentStore(host: DocumentStoreHost, key: string, options?: DocumentStoreOptions): RecoveryStore;
@@ -0,0 +1,242 @@
1
+ import { defineDocFamily } from "@earendil-works/pi-durable";
2
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
3
+ import { RecoveryError, asRecoveryError, bindingMismatch } from "@parcha/agentrun-dsl/recovery";
4
+ import { storageError } from "./pi-versions.js";
5
+ /** A failed commit as the driver reads it: its own message and code, kept as a RecoveryError. A Session that failed at a
6
+ * storage error answers with `SessionFailed` (pi-durable 1.2); the error is then the storage's, as 1.1 gave it, and the
7
+ * `SessionFailed` is its cause. */
8
+ function storeFailure(error) {
9
+ const own = storageError(error);
10
+ if (own === error || own instanceof RecoveryError)
11
+ return asRecoveryError(own);
12
+ const code = own?.code;
13
+ return new RecoveryError(own instanceof Error ? own.message : String(own), typeof code === "string" ? code : undefined, { cause: error });
14
+ }
15
+ /** An effect's key in `agentrun.effects`: its journal key, then its id. The two are joined by NUL, so neither may hold
16
+ * one: two pairs could otherwise name the same document. */
17
+ export const effectKey = (key, id) => {
18
+ if (key.includes("\u0000") || id.includes("\u0000"))
19
+ throw new RecoveryError("A journal key and an effect id hold no NUL character");
20
+ return `${key}\u0000${id}`;
21
+ };
22
+ /** A base every 32 deltas keeps a read of the journal short, however long the run. */
23
+ const checkpointWhen = (_value, _ops, info) => info.deltasSinceBase >= 32;
24
+ const DriverDoc = defineDocFamily({ kind: "agentrun.driver", version: 1, scope: "session", family: true, checkpointWhen,
25
+ initial: () => ({ binding: null, inputs: null, generation: 0, revision: 0, state: null, notes: [], effects: [] }) });
26
+ const EffectDoc = defineDocFamily({ kind: "agentrun.effects", version: 1, scope: "session", family: true,
27
+ initial: () => ({ driver: "", name: "", argsHash: "", status: "unknown", session: null, result: null }), checkpointWhen: () => false });
28
+ const ItemDoc = defineDocFamily({ kind: "agentrun.items", version: 1, scope: "session", family: true,
29
+ initial: () => ({ driver: "", effects: [] }), checkpointWhen: () => false });
30
+ /** A state by its digest; `sha256` is empty only for one never written. */
31
+ const StateDoc = defineDocFamily({ kind: "agentrun.states", version: 1, scope: "session", family: true,
32
+ initial: () => ({ driver: "", sha256: "", state: null }), checkpointWhen: () => false });
33
+ /** A draft made to hold `value` whole: every field set, every other field removed. */
34
+ function replaceWhole(draft, value) {
35
+ for (const field of Object.keys(draft))
36
+ if (!Object.hasOwn(value, field))
37
+ delete draft[field];
38
+ for (const [field, item] of Object.entries(value))
39
+ draft[field] = item;
40
+ }
41
+ /** A value as the journal stores it: plain JSON, every number finite. */
42
+ function json(value) {
43
+ return value === undefined ? null : JSON.parse(JSON.stringify(value, (_key, item) => {
44
+ if (typeof item === "bigint" || typeof item === "function" || typeof item === "symbol" || (typeof item === "number" && !Number.isFinite(item))) {
45
+ throw new RecoveryError("A journal holds finite JSON values only");
46
+ }
47
+ return item;
48
+ }));
49
+ }
50
+ /** A journal effect from its stored document. */
51
+ function storedEffect(id, e) {
52
+ return { id, name: e.name, argsHash: e.argsHash, status: e.status, session: e.session, result: json(e.result), ...(e.intent ? { intent: json(e.intent) } : {}), ...(e.args !== undefined ? { args: json(e.args) } : {}), ...(Array.isArray(e.calls) ? { calls: json(e.calls) } : {}) };
53
+ }
54
+ /** The journals open in this process. The run's lock keeps every other process off the run, and the journal's generation
55
+ * fences a stale writer; this keeps a second open of one key off it here. Without an owner a host's own keys are
56
+ * tracked; with one, the keys by owner. */
57
+ const hostKeys = new WeakMap();
58
+ const ownedKeys = new Map();
59
+ /** Take the in-process hold on `key`: what gives it back, and what undoes the take when the open fails. */
60
+ function hold(host, key, owner) {
61
+ const refused = () => new RecoveryError("Run already has a live owner");
62
+ if (owner === undefined) {
63
+ const keys = hostKeys.get(host) ?? hostKeys.set(host, new Set()).get(host);
64
+ if (keys.has(key))
65
+ throw refused();
66
+ keys.add(key);
67
+ const release = () => { keys.delete(key); };
68
+ return { release, undo: release };
69
+ }
70
+ const previous = ownedKeys.get(key);
71
+ if (previous && previous.owner !== owner)
72
+ throw refused();
73
+ const token = Symbol(key);
74
+ ownedKeys.set(key, { token, owner });
75
+ return {
76
+ release: () => { if (ownedKeys.get(key)?.token === token)
77
+ ownedKeys.delete(key); },
78
+ undo: () => { if (ownedKeys.get(key)?.token !== token)
79
+ return; if (previous)
80
+ ownedKeys.set(key, previous);
81
+ else
82
+ ownedKeys.delete(key); },
83
+ };
84
+ }
85
+ /** The recovery store for the journal `key` that `host` writes. Opening it takes ownership: a journal already open is
86
+ * refused (unless the same `owner` opens it again), a binding that differs from the one the journal was first opened
87
+ * under is refused naming the inputs that moved, and the generation advances. */
88
+ export function documentStore(host, key, options = {}) {
89
+ return { open: (bound) => openDocumentJournal(host, key, bound, options) };
90
+ }
91
+ async function openDocumentJournal(host, key, bound, options) {
92
+ effectKey(key, "");
93
+ const context = options.context ?? BACKGROUND_CONTEXT;
94
+ const held = hold(host, key, options.owner);
95
+ const opened = await host.commit(async (tx) => {
96
+ const doc = await tx.doc(DriverDoc, key, null);
97
+ const existing = doc.binding !== null;
98
+ if (existing && doc.binding !== bound.binding)
99
+ throw bindingMismatch(doc.inputs ? JSON.stringify(doc.inputs) : null, bound.inputs);
100
+ if (!existing) {
101
+ doc.binding = bound.binding;
102
+ doc.inputs = bound.inputs ? { ...bound.inputs } : null;
103
+ }
104
+ doc.generation += 1;
105
+ const effects = [];
106
+ for (const id of doc.effects) {
107
+ effects.push(storedEffect(id, await tx.doc(EffectDoc, effectKey(key, id), null)));
108
+ }
109
+ return { existing, generation: doc.generation, revision: doc.revision, state: json(doc.state), notes: json(doc.notes), effects };
110
+ }, context).catch((error) => { held.undo(); throw storeFailure(error); });
111
+ const effects = new Map(opened.effects.map((effect) => [effect.id, effect]));
112
+ const notes = [...opened.notes];
113
+ let revision = opened.revision;
114
+ let closed = false;
115
+ /** Writes run one at a time, in the order they were asked for, each with its checks. A failed write does not stop
116
+ * the next, and one asked for before `close` still lands. */
117
+ let queue = Promise.resolve();
118
+ const inOrder = (write) => {
119
+ if (closed)
120
+ return Promise.reject(new RecoveryError("The journal is closed"));
121
+ const done = queue.then(write).catch((error) => { throw storeFailure(error); });
122
+ queue = done.catch(() => undefined);
123
+ return done;
124
+ };
125
+ /** One Session commit on the journal's record: it checks this open's generation is the record's, advances the
126
+ * revision, and lets `write` change the record (its state computed with that revision) and the effect documents,
127
+ * then writes the parts computed with that revision. */
128
+ const commit = async (write, parts) => host.commit(async (tx) => {
129
+ const doc = await tx.doc(DriverDoc, key, null);
130
+ if (doc.generation !== opened.generation)
131
+ throw new RecoveryError("Run owner generation is not acquired");
132
+ const next = doc.revision + 1;
133
+ const value = await write(doc, next, tx);
134
+ const laid = parts?.(next);
135
+ for (const [path, item] of Object.entries(laid?.items ?? {})) {
136
+ replaceWhole(await tx.doc(ItemDoc, effectKey(key, path), null), json(item));
137
+ }
138
+ for (const [sha256, state] of Object.entries(laid?.states ?? {})) {
139
+ const held = await tx.doc(StateDoc, effectKey(key, sha256), null);
140
+ if (held.sha256 === "")
141
+ Object.assign(held, { driver: key, sha256, state: json(state) });
142
+ }
143
+ doc.revision = next;
144
+ return { revision: next, value };
145
+ }, context).then((done) => { revision = done.revision; return done; });
146
+ /** A read in a commit of its own: it writes nothing the caller did not ask for. */
147
+ const read = (body) => inOrder(() => host.commit(body, context));
148
+ return {
149
+ existing: opened.existing, generation: opened.generation, state: opened.state,
150
+ get revision() { return revision; },
151
+ effects: () => [...effects.values()],
152
+ effect: (id) => effects.get(id),
153
+ notes: () => [...notes],
154
+ save: (state, note, parts) => inOrder(async () => {
155
+ let entry;
156
+ const done = await commit((doc, next) => {
157
+ doc.state = json(typeof state === "function" ? state(next) : state);
158
+ if (note) {
159
+ entry = { revision: next, kind: note.kind, detail: json(note.detail), at: new Date().toISOString() };
160
+ doc.notes.push(entry);
161
+ }
162
+ }, parts);
163
+ if (entry)
164
+ notes.push(entry);
165
+ return done.revision;
166
+ }),
167
+ note: (kind, detail) => inOrder(async () => {
168
+ const entry = { kind, detail: json(detail), at: new Date().toISOString() };
169
+ const done = await commit((doc, next) => { doc.notes.push({ revision: next, ...entry }); });
170
+ notes.push({ revision: done.revision, ...entry });
171
+ return done.revision;
172
+ }),
173
+ admit: (id, name, argsHash, state, session = null, intent, args, parts, owner) => inOrder(async () => {
174
+ effectKey(key, id);
175
+ const known = effects.get(id);
176
+ if (known)
177
+ return known;
178
+ const stored = json(state);
179
+ const kept = intent === undefined ? undefined : json(intent);
180
+ const keptArgs = args === undefined ? undefined : json(args);
181
+ await commit(async (doc, _next, tx) => {
182
+ Object.assign(await tx.doc(EffectDoc, effectKey(key, id), null), { driver: key, name, argsHash, status: "unknown", session, result: null, ...(kept ? { intent: kept } : {}), ...(keptArgs !== undefined ? { args: keptArgs } : {}) });
183
+ // An effect a map item owns is listed by that item's record, written in the same commit.
184
+ if (owner === undefined || !parts)
185
+ doc.effects.push(id);
186
+ doc.state = stored;
187
+ }, parts);
188
+ effects.set(id, { id, name, argsHash, status: "unknown", session, result: null, ...(kept ? { intent: kept } : {}), ...(keptArgs !== undefined ? { args: keptArgs } : {}) });
189
+ return "new";
190
+ }),
191
+ complete: (id, result, state = opened.state, parts) => inOrder(async () => {
192
+ const known = effects.get(id);
193
+ if (!known)
194
+ throw new RecoveryError(`Effect ${id} completes without an admission`);
195
+ if (known.status === "completed")
196
+ throw new RecoveryError(`Effect ${id} completes once`);
197
+ const value = json(result);
198
+ const next = json(state);
199
+ await commit(async (doc, _next, tx) => {
200
+ const effect = await tx.doc(EffectDoc, effectKey(key, id), null);
201
+ effect.status = "completed";
202
+ effect.result = value;
203
+ doc.state = next;
204
+ }, parts);
205
+ effects.set(id, { ...known, status: "completed", result: value });
206
+ }),
207
+ called: (id, calls) => inOrder(async () => {
208
+ if (!effects.has(id))
209
+ throw new RecoveryError(`Effect ${id} records calls without an admission`);
210
+ const value = json(calls);
211
+ await commit(async (_doc, _next, tx) => { (await tx.doc(EffectDoc, effectKey(key, id), null)).calls = value; });
212
+ effects.set(id, { ...effects.get(id), ...(Array.isArray(value) ? { calls: value } : {}) });
213
+ }),
214
+ async close() {
215
+ if (closed)
216
+ return;
217
+ closed = true;
218
+ await queue;
219
+ held.release();
220
+ },
221
+ // Only paths and digests the driver wrote are asked for: a read of a document never written would create it.
222
+ items: (paths) => read(async (tx) => {
223
+ const found = [];
224
+ for (const path of paths) {
225
+ const item = await tx.doc(ItemDoc, effectKey(key, path), null);
226
+ if (item.driver === "") {
227
+ found.push(undefined);
228
+ continue;
229
+ }
230
+ found.push(json(item));
231
+ for (const id of (item.effects ?? []))
232
+ if (!effects.has(id))
233
+ effects.set(id, storedEffect(id, await tx.doc(EffectDoc, effectKey(key, id), null)));
234
+ }
235
+ return found;
236
+ }),
237
+ stateOf: (sha256) => read(async (tx) => {
238
+ const held = await tx.doc(StateDoc, effectKey(key, sha256), null);
239
+ return held.sha256 === "" ? undefined : json(held.state);
240
+ }),
241
+ };
242
+ }
@@ -0,0 +1,133 @@
1
+ import type { Extension, Harness, TaskId, TaskRuntime } from "@earendil-works/pi-durable";
2
+ import { runWorkflow, type Workflow, type WorkflowDeps } from "@parcha/agentrun-dsl";
3
+ import { type EscalationRow, type RecoveryAdapters, type RecoveryDriver, type RecoveryOptions } from "@parcha/agentrun-dsl/recovery";
4
+ type Context = Parameters<Harness["commit"]>[1];
5
+ /** What one run is: its key (the same key reaches the same task and journal), the workflow as authored, its input, and
6
+ * what else must not change between two opens of it. */
7
+ export type WorkflowRequest = {
8
+ key: string;
9
+ workflow: Workflow;
10
+ input: Record<string, unknown>;
11
+ bind?: Record<string, unknown>;
12
+ };
13
+ /** How a run ended, as the host reads it. A pause is not an outcome: a paused run's task stays pending. */
14
+ export type WorkflowOutcome = {
15
+ status: "complete";
16
+ output: unknown;
17
+ state: unknown;
18
+ } | {
19
+ status: "escalated";
20
+ escalation: unknown;
21
+ state: unknown;
22
+ continuation?: unknown;
23
+ } | {
24
+ status: "refused";
25
+ code: string;
26
+ message: string;
27
+ detail?: unknown;
28
+ } | {
29
+ status: "stopped";
30
+ stop: "cancelled";
31
+ source?: string;
32
+ };
33
+ /** One invocation of a run's phase, as the host's adapters see it: a node runner that opens conversations owns them by
34
+ * `runtime.taskId`, so a cancel aborts them before the task. */
35
+ export type WorkflowInvocation = {
36
+ key: string;
37
+ taskId: TaskId;
38
+ runtime: TaskRuntime<WorkflowRequest, TaskCheckpoint, WorkflowResult, object>;
39
+ context: Context;
40
+ };
41
+ /** The host's part, asked once per invocation. */
42
+ export type WorkflowTaskHost = {
43
+ /** The driver's host options, beside the run's key and binding: asked before the driver opens, by the run's phase and
44
+ * by its abort handler. A host settles an effect a killed process left unknown with `reconcile`: the driver calls it
45
+ * once, through its own open of the run, with the unknown effects and a `complete` that records one's result. An
46
+ * effect it completes is answered from that result and not dispatched again; one it leaves is refused at resume. Do not
47
+ * open the run's journal here: that open is a generation of its own. The task's abort handler opens the driver too, to
48
+ * record a cancel, so `reconcile` also runs then; `phase` is `"abort"` there and `"run"` for the run's own open, and a
49
+ * host that wants no reconcile during a cancel returns none for `"abort"`. */
50
+ options?(invocation: WorkflowInvocation & {
51
+ phase: "run" | "abort";
52
+ }): Omit<RecoveryOptions, "key" | "bind"> | Promise<Omit<RecoveryOptions, "key" | "bind">>;
53
+ /** What the interpreter runs with, asked once the driver is open, so a host that composes its own couplings over the
54
+ * driver (its spend, its sessions, its escalation rows) builds them here. */
55
+ run(invocation: WorkflowInvocation & {
56
+ driver: RecoveryDriver;
57
+ }): WorkflowHostParts | Promise<WorkflowHostParts>;
58
+ /** The host's ladder: a run that did not complete and was not refused continues here, inside the task's invocation,
59
+ * so what the host opens (its continuation) is owned by the task, and a cancel aborts it before the task. The host
60
+ * commits the escalation row through `invocation.driver.escalate` before anything acts on it; a run reopened after
61
+ * that commit comes here again with the row, and the interpreter does not run. `invocation.signal` ends with the
62
+ * run's stops: a pause leaves the task pending, and the next open comes here again with the row. What it returns
63
+ * rides on the escalated outcome as `continuation`; a throw is the run's failure. Absent, an escalated run ends with
64
+ * the interpreter's escalation and any failure is the run's. */
65
+ escalated?(ending: WorkflowEnding, invocation: WorkflowInvocation & {
66
+ driver: RecoveryDriver;
67
+ signal: AbortSignal;
68
+ }): Promise<unknown>;
69
+ };
70
+ /** Why a run continues on the host's ladder: a gate that fired (`escalation`), a failure that is not a refusal
71
+ * (`error`), a refusal found before any step (`refusal`), or an escalation an earlier invocation committed (`row`).
72
+ * `state` is the run's state at that point. */
73
+ export type WorkflowEnding = {
74
+ escalation?: unknown;
75
+ error?: unknown;
76
+ refusal?: NonNullable<RecoveryDriver["preStepRefusal"]>;
77
+ row?: EscalationRow;
78
+ state: Record<string, unknown>;
79
+ };
80
+ /** The host's adapters, which the task wraps with `withRecovery` (`durableNodes`: the node runner answers a delivered step
81
+ * again from its own record), or the dependencies the host built over `invocation.driver` itself, which the task runs as
82
+ * they are, stopped by the run's signal too, with the host's own `interpret` when it runs its documents under its own
83
+ * policy (its view of the document, its lint): it is called as `runWorkflow` would be, and answers as it does. */
84
+ export type WorkflowHostParts = {
85
+ adapters: RecoveryAdapters;
86
+ durableNodes?: boolean;
87
+ } | {
88
+ deps: WorkflowDeps;
89
+ interpret?: (workflow: Workflow, input: Record<string, unknown>, deps: WorkflowDeps) => ReturnType<typeof runWorkflow>;
90
+ };
91
+ /** What starting and reading a run asks of its caller: a Harness, or a tool's own `api` inside its invocation, whose
92
+ * commits create the run's task in the calling conversation. A caller with no `root` names the conversation in
93
+ * `start`'s options; one with no `abortTask` cannot start a run with a cancel. */
94
+ export type WorkflowCaller = Pick<Harness, "commit" | "snapshot" | "getTask" | "waitForTask"> & Partial<Pick<Harness, "root" | "resume" | "abortTask">>;
95
+ /** A started run. `wait` resolves with the run's outcome once its task is terminal, and rejects with the storage's error
96
+ * when the Session failed at one. */
97
+ export type WorkflowRun = {
98
+ key: string;
99
+ taskId: TaskId<WorkflowResult>;
100
+ /** `created`: this start made the task; `attached`: it was live; `settled`: it was terminal and is returned as it is. */
101
+ started: "created" | "attached" | "settled";
102
+ wait(context: Context): Promise<WorkflowOutcome>;
103
+ };
104
+ /** What a stop reached. A pause reaches a run only where it is live, in this process: `paused` once the run's work has
105
+ * stopped with the pause in its journal, `ended` when the run ended otherwise, `not-live` when it is not running here. A cancel is `abortTask`'s
106
+ * answer: `marked` (the task ends aborted later) or `terminal` (it already was). */
107
+ export type WorkflowStop = "paused" | "ended" | "not-live" | "marked" | "terminal";
108
+ type TaskCheckpoint = {
109
+ phase: "run";
110
+ };
111
+ /** A completed task's result: the outcomes that end a run without a refusal. */
112
+ type WorkflowResult = Extract<WorkflowOutcome, {
113
+ status: "complete" | "escalated";
114
+ }>;
115
+ /** The task definition, the extension that carries it, and the host's three operations on a run. */
116
+ export declare function createWorkflowExtension(host: WorkflowTaskHost): {
117
+ extension: Extension;
118
+ start(harness: WorkflowCaller, request: WorkflowRequest, context: Context, options?: {
119
+ conversationId?: number;
120
+ background?: boolean;
121
+ stop?: {
122
+ action: "pause" | "cancel";
123
+ source?: string;
124
+ };
125
+ }): Promise<WorkflowRun>;
126
+ read(harness: WorkflowCaller, key: string, context: Context): Promise<{
127
+ taskId: TaskId<WorkflowResult>;
128
+ status: string;
129
+ outcome?: WorkflowOutcome;
130
+ } | undefined>;
131
+ stop(harness: Harness, key: string, action: "pause" | "cancel", context: Context, source?: string): Promise<WorkflowStop>;
132
+ };
133
+ export {};