@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
@@ -0,0 +1,401 @@
1
+ // The record core: how one LLM node delivers a typed record through one `submit` call, with no pi import.
2
+ //
3
+ // A submission is repaired as a transport spelling (stringified containers and scalars, a "null" where the
4
+ // field admits null), read from a workspace file when it names one, held to the host's contracts and the
5
+ // schema, and then read a second time by the node's reviewers. Every answer that is not a delivery spends
6
+ // one delivery attempt: a rejection, the second reading's one bounce, a nudge of a yield without a record.
7
+ // The second reading is feedback, once: the first record it disagrees with goes back; the next structurally
8
+ // valid record is delivered with what the reading still disagrees with beside it. A reviewer that cannot
9
+ // answer decides nothing.
10
+ //
11
+ // `deliver` is the whole decision over a `RecordStore`, the two small states a caller keeps durably or in
12
+ // memory. `gate` and `spend` are the rules as pure functions, the ones `spec/lean` proves terminate. `deliver`
13
+ // follows `gate`. It does not hold `spend`'s bound: it decides a submission whatever the count, and a nudge that
14
+ // spends the last attempt still continues the run, so the one submission after it is decided and `attempts` can
15
+ // read one past the limit.
16
+ import { isDeepStrictEqual } from "node:util";
17
+ import { Compile } from "typebox/compile";
18
+ /** Delivery attempts a node gets: rejections, the second reading's one bounce and nudges, each once. */
19
+ export const DELIVERY_ATTEMPTS = 6;
20
+ /** The most schema violations one rejected delivery lists; the submit tool's description tells the model the number. */
21
+ export const VIOLATIONS_SHOWN = 8;
22
+ /** The second reading on one structurally valid submission: it sends the record back only while its round
23
+ * is unspent and a reviewer disagrees. A reviewer with no verdict never sends a record back. */
24
+ export function gate(bounced, readings) {
25
+ return !bounced && readings.includes("disagrees") ? "bounce" : "accept";
26
+ }
27
+ /** Whether a node's delivery has ended: it delivered, or its attempts are spent. */
28
+ export const deliveryEnded = (max, state) => state.delivered || state.attempts >= max;
29
+ /** One answer applied to the count. An ended delivery takes no further answer; every other answer counts once. */
30
+ export function spend(max, state, event) {
31
+ if (deliveryEnded(max, state))
32
+ return state;
33
+ return { attempts: state.attempts + 1, delivered: event === "delivered" };
34
+ }
35
+ // ─── the schema a record is held to ───
36
+ /** What makes a schema one no `submit` call can satisfy: a call's arguments are an object, so the schema must be a
37
+ * JSON Schema object whose root type, when it names one, admits an object. A node runner refuses such a schema
38
+ * before any conversation exists. */
39
+ export function lintRecordRoot(schema) {
40
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
41
+ return ["the record schema must be a JSON Schema object"];
42
+ const { type } = schema;
43
+ const admitsObject = type === undefined || type === "object" || (Array.isArray(type) && type.includes("object"));
44
+ return admitsObject ? [] : [`the record schema's root type must be "object", not ${JSON.stringify(type)}`];
45
+ }
46
+ const validators = new WeakMap();
47
+ /** The schema's compiled validator, or null for a schema the compiler refuses. */
48
+ function validatorOf(schema) {
49
+ if (!schema || typeof schema !== "object")
50
+ return null;
51
+ let validator = validators.get(schema);
52
+ if (validator === undefined) {
53
+ try {
54
+ validator = Compile(schema);
55
+ }
56
+ catch {
57
+ validator = null;
58
+ }
59
+ validators.set(schema, validator);
60
+ }
61
+ return validator;
62
+ }
63
+ // ─── transport repair ───
64
+ /** Where the schema expects an object or an array and the submitted value is a string that parses to one, the
65
+ * parsed value; where it expects a number, an integer, a boolean or null and admits no string, the scalar a
66
+ * string spells. Some model families serialise nested tool arguments as strings: the content is valid and
67
+ * every submit fails on its spelling. A string that parses to a container the field also admits is read as that
68
+ * container; only against a scalar does a field that admits a string keep the string. */
69
+ export function parseStringifiedContainers(value, schema, depth = 0, root) {
70
+ if (depth > 6 || !schema || typeof schema !== "object")
71
+ return value;
72
+ // A `$ref` property carries no type of its own: it is read through the root schema (its `definitions` or `$defs`),
73
+ // or the repair skips exactly the fields it exists for.
74
+ const top = root ?? schema;
75
+ const resolve = (spec) => (spec && typeof spec === "object" && typeof spec.$ref === "string" ? (deref(spec, top) ?? spec) : spec);
76
+ // Each schema once: one that refers to itself (through `$defs` or `definitions`) adds nothing the second time.
77
+ const expected = (spec, seen = new Set()) => {
78
+ const resolved = resolve(spec);
79
+ if (!resolved || typeof resolved !== "object" || seen.has(resolved))
80
+ return [];
81
+ seen.add(resolved);
82
+ const types = Array.isArray(resolved.type) ? resolved.type : resolved.type ? [resolved.type] : [];
83
+ const anyOf = Array.isArray(resolved.anyOf) ? resolved.anyOf : [];
84
+ return [...types, ...anyOf.flatMap((variant) => expected(variant, seen))];
85
+ };
86
+ const repair = (input, rawSpec) => {
87
+ const spec = resolve(rawSpec);
88
+ const wants = expected(spec);
89
+ let current = input;
90
+ if (typeof current === "string" && (wants.includes("object") || wants.includes("array"))) {
91
+ const trimmed = current.trim();
92
+ if ((trimmed.startsWith("{") && trimmed.endsWith("}")) || (trimmed.startsWith("[") && trimmed.endsWith("]"))) {
93
+ try {
94
+ const parsed = JSON.parse(trimmed);
95
+ const isObject = parsed && typeof parsed === "object" && !Array.isArray(parsed);
96
+ if ((isObject && wants.includes("object")) || (Array.isArray(parsed) && wants.includes("array")))
97
+ current = parsed;
98
+ }
99
+ catch { /* Not JSON: the string stays for the validator to report. */ }
100
+ }
101
+ }
102
+ // A scalar is coerced only when the field does not accept a string, and never when the field lists that string
103
+ // itself as a value. Integers must be exact; a decimal becomes the float64 that JSON.parse of the same literal
104
+ // yields, the only value a JSON number can hold.
105
+ if (typeof current === "string" && !wants.includes("string") && !listsValue(current, rawSpec, top)) {
106
+ const trimmed = current.trim();
107
+ if ((wants.includes("integer") || wants.includes("number")) && /^-?\d+$/.test(trimmed) && Number.isSafeInteger(Number(trimmed)))
108
+ current = Number(trimmed);
109
+ else if (wants.includes("number") && /^-?(?:0|[1-9]\d*)\.\d+$/.test(trimmed) && Number.isFinite(Number(trimmed)))
110
+ current = JSON.parse(trimmed);
111
+ else if (wants.includes("boolean") && (trimmed === "true" || trimmed === "false"))
112
+ current = trimmed === "true";
113
+ else if (wants.includes("null") && trimmed === "null")
114
+ current = null;
115
+ }
116
+ // An `anyOf`-wrapped object's nested fields live under the branch's properties, not the wrapper's.
117
+ const flattenBranches = (candidate) => [candidate, ...(Array.isArray(candidate?.anyOf) ? candidate.anyOf.flatMap(flattenBranches) : [])];
118
+ if (current && typeof current === "object" && !Array.isArray(current)) {
119
+ const objectBranch = flattenBranches(spec).map((branch) => resolve(branch)).find((branch) => branch?.properties && typeof branch.properties === "object");
120
+ if (objectBranch)
121
+ return parseStringifiedContainers(current, objectBranch, depth + 1, top);
122
+ }
123
+ if (Array.isArray(current)) {
124
+ const arrayBranch = flattenBranches(spec).map((branch) => resolve(branch)).find((branch) => branch?.items && typeof branch.items === "object");
125
+ if (arrayBranch)
126
+ return current.map((item) => repair(item, arrayBranch.items));
127
+ }
128
+ return current;
129
+ };
130
+ if (!value || typeof value !== "object" || Array.isArray(value))
131
+ return value;
132
+ const properties = schema.properties || {};
133
+ const next = { ...value };
134
+ for (const [key, spec] of Object.entries(properties))
135
+ if (key in next)
136
+ next[key] = repair(next[key], spec);
137
+ return next;
138
+ }
139
+ /** A local `$ref` (`#/definitions/<name>` or `#/$defs/<name>`) resolved against the record's root schema, so
140
+ * the null-spelling walk reads the field schemas the schema check does. One it cannot resolve reads as no schema. */
141
+ function deref(schema, root, hops = 0) {
142
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
143
+ return schema;
144
+ const ref = schema.$ref;
145
+ if (typeof ref !== "string")
146
+ return schema;
147
+ const match = ref.match(/^#\/(definitions|\$defs)\/([^/]+)$/);
148
+ const table = match && root && typeof root === "object" ? root[match[1]] : undefined;
149
+ const target = table && typeof table === "object" ? table[match[2]] : undefined;
150
+ return target && hops < 16 ? deref(target, root, hops + 1) : undefined;
151
+ }
152
+ function admitsNull(schema, root) {
153
+ schema = deref(schema, root);
154
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
155
+ return false;
156
+ const spec = schema;
157
+ if (spec.type === "null" || (Array.isArray(spec.type) && spec.type.includes("null")))
158
+ return true;
159
+ if (spec.const === null || (Array.isArray(spec.enum) && spec.enum.includes(null)))
160
+ return true;
161
+ return [spec.anyOf, spec.oneOf].some((branches) => Array.isArray(branches) && branches.some((branch) => admitsNull(branch, root)));
162
+ }
163
+ function propertiesOf(schema, root) {
164
+ schema = deref(schema, root);
165
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
166
+ return {};
167
+ const spec = schema;
168
+ const fieldMap = !("type" in spec) && !("properties" in spec) && !("anyOf" in spec) && !("oneOf" in spec) ? spec : {};
169
+ const direct = spec.properties && typeof spec.properties === "object" && !Array.isArray(spec.properties) ? spec.properties : fieldMap;
170
+ const branches = [...(Array.isArray(spec.anyOf) ? spec.anyOf : []), ...(Array.isArray(spec.oneOf) ? spec.oneOf : [])];
171
+ return Object.assign({}, ...branches.map((branch) => propertiesOf(branch, root)), direct);
172
+ }
173
+ function itemsOf(schema, root) {
174
+ schema = deref(schema, root);
175
+ if (!schema || typeof schema !== "object" || Array.isArray(schema))
176
+ return undefined;
177
+ const spec = schema;
178
+ if (spec.items)
179
+ return spec.items;
180
+ const branches = [...(Array.isArray(spec.anyOf) ? spec.anyOf : []), ...(Array.isArray(spec.oneOf) ? spec.oneOf : [])];
181
+ return branches.map((branch) => itemsOf(branch, root)).find(Boolean);
182
+ }
183
+ // The spellings a model uses when it means "no value": one set, read by the finding and by the repair, so a
184
+ // string one recognises the other heals.
185
+ const NULL_SPELLINGS = new Set(["null", "none", "n/a"]);
186
+ const spellsNull = (value) => typeof value === "string" && NULL_SPELLINGS.has(value.trim().toLowerCase());
187
+ /** Whether a field's schema lists the string itself as a value: its own `const`, or a member of its own `enum`, or the
188
+ * same in the schema its local `$ref` names, or in any branch. A schema's own listed values count beside its `$ref`,
189
+ * never in place of it. */
190
+ function listsValue(value, schema, root, hops = 0) {
191
+ if (hops > 16 || !schema || typeof schema !== "object" || Array.isArray(schema))
192
+ return false;
193
+ const spec = schema;
194
+ if (spec.const === value || (Array.isArray(spec.enum) && spec.enum.includes(value)))
195
+ return true;
196
+ const target = deref(spec, root);
197
+ if (target !== spec && listsValue(value, target, root, hops + 1))
198
+ return true;
199
+ return [spec.anyOf, spec.oneOf].some((branches) => Array.isArray(branches) && branches.some((branch) => listsValue(value, branch, root, hops + 1)));
200
+ }
201
+ /** A string that spells "no value" in a field that admits JSON null. A string the field's own enum or const lists
202
+ * exactly is one of its values, never a spelling of null. */
203
+ const spelledNull = (value, schema, root) => spellsNull(value) && admitsNull(schema, root) && !listsValue(value, schema, root);
204
+ /** The path of every string that spells "no value" in a field whose schema admits JSON null and does not list it. */
205
+ export function nullSpellings(value, schema, root = schema, at = "") {
206
+ if (spelledNull(value, schema, root))
207
+ return [at || "$"];
208
+ if (Array.isArray(value)) {
209
+ const items = itemsOf(schema, root);
210
+ return items ? value.flatMap((item, index) => nullSpellings(item, items, root, `${at}[${index}]`)) : [];
211
+ }
212
+ if (!value || typeof value !== "object")
213
+ return [];
214
+ const properties = propertiesOf(schema, root);
215
+ return Object.entries(value).flatMap(([key, child]) => Object.hasOwn(properties, key) ? nullSpellings(child, properties[key], root, at ? `${at}.${key}` : key) : []);
216
+ }
217
+ /** The record with every such string replaced by JSON null, in place. A repair the record as a whole refuses
218
+ * (it satisfied its schema before and does not after) is undone in full, so a spelling stays only where null
219
+ * is inadmissible; `undo: false` leaves that judgement to a caller that repairs more of the record and judges the
220
+ * whole. `""` is a value and stays. */
221
+ export function healNullSpellings(record, schema, options = {}) {
222
+ if (!record || typeof record !== "object" || Array.isArray(record) || Object.getPrototypeOf(record) !== Object.prototype)
223
+ return record;
224
+ if (!nullSpellings(record, schema).length)
225
+ return record;
226
+ const validator = options.undo === false ? null : validatorOf(schema);
227
+ const before = validator?.Check(record) ? structuredClone(record) : null;
228
+ const heal = (value, spec) => {
229
+ if (spelledNull(value, spec, schema))
230
+ return null;
231
+ if (Array.isArray(value)) {
232
+ const items = itemsOf(spec, schema);
233
+ if (items)
234
+ value.forEach((item, index) => { value[index] = heal(item, items); });
235
+ return value;
236
+ }
237
+ if (!value || typeof value !== "object")
238
+ return value;
239
+ const properties = propertiesOf(spec, schema);
240
+ for (const [key, child] of Object.entries(value)) {
241
+ if (Object.hasOwn(properties, key))
242
+ value[key] = heal(child, properties[key]);
243
+ }
244
+ return value;
245
+ };
246
+ heal(record, schema);
247
+ if (before && validator && !validator.Check(record)) {
248
+ const fields = record;
249
+ for (const key of Object.keys(fields))
250
+ delete fields[key];
251
+ Object.assign(fields, before);
252
+ }
253
+ return record;
254
+ }
255
+ /** A record's transport spellings repaired against its schema, without touching `args`. */
256
+ export function repairRecord(args, schema) {
257
+ if (!args || typeof args !== "object" || Array.isArray(args))
258
+ return args;
259
+ return healNullSpellings(structuredClone(parseStringifiedContainers(args, schema)), schema);
260
+ }
261
+ // ─── the file envelope ───
262
+ /** The file a submission names and nothing else: `{ <key>: "relative/path.json" }`. */
263
+ export function fileSubmission(args, key) {
264
+ if (!args || typeof args !== "object" || Array.isArray(args))
265
+ return null;
266
+ const fields = args;
267
+ return Object.keys(fields).length === 1 && typeof fields[key] === "string" ? fields[key] : null;
268
+ }
269
+ /** A submission with fields beside the file key. Fields that form a whole record on their own are that record;
270
+ * otherwise the file holds the record, and each field beside it may only restate the file's value. A schema
271
+ * that declares the file key as its own field keeps it inline. */
272
+ export function mixedFileSubmission(args, schema, key) {
273
+ if (!args || typeof args !== "object" || Array.isArray(args))
274
+ return null;
275
+ const { [key]: file, ...extras } = args;
276
+ if (typeof file !== "string" || !Object.keys(extras).length)
277
+ return null;
278
+ const properties = schema && typeof schema.properties === "object" && schema.properties ? schema.properties : {};
279
+ return Object.hasOwn(properties, key) ? null : { file, extras };
280
+ }
281
+ /** The fields beside the file key that the file's record does not hold with the same value. */
282
+ export function extrasNotInRecord(record, extras) {
283
+ const held = record && typeof record === "object" && !Array.isArray(record) ? record : {};
284
+ return Object.keys(extras).filter((key) => !Object.hasOwn(held, key) || !isDeepStrictEqual(held[key], extras[key])).sort();
285
+ }
286
+ const SCHEMA_REASON = "submission does not satisfy the schema";
287
+ const messageOf = (error) => error instanceof Error ? error.message : String(error);
288
+ /** Decide one `submit` call. `args` are the call's arguments as the model sent them, or as `repairRecord`
289
+ * already repaired them. */
290
+ export async function deliver(contract, store, args) {
291
+ const max = contract.maxAttempts ?? DELIVERY_ATTEMPTS;
292
+ const key = contract.file?.key;
293
+ const state = await store.read();
294
+ if (state.record.record != null)
295
+ return { status: "already" };
296
+ const reject = async (problems, reason = SCHEMA_REASON) => {
297
+ const attempts = await store.reject();
298
+ return { status: "rejected", attempts, spent: attempts >= max, reason, problems };
299
+ };
300
+ const validator = validatorOf(contract.schema);
301
+ let candidate = args;
302
+ const file = key === undefined ? null : fileSubmission(candidate, key);
303
+ const mixed = key === undefined ? null : mixedFileSubmission(candidate, contract.schema, key);
304
+ // Fields beside the file key that are a whole record on their own are that record, as an inline submission.
305
+ const inlineBeside = mixed ? repairRecord(mixed.extras, contract.schema) : undefined;
306
+ if (mixed && validator?.Check(inlineBeside))
307
+ candidate = inlineBeside;
308
+ else if (mixed) {
309
+ const exact = `call submit with exactly {"${key}": ${JSON.stringify(mixed.file)}} and nothing beside it`;
310
+ let record;
311
+ try {
312
+ record = await contract.file.read(mixed.file);
313
+ }
314
+ catch (error) {
315
+ if (error?.code === "ENOENT")
316
+ return reject([`${key} names a file that does not exist in the workspace; write the complete JSON there first, then ${exact}`]);
317
+ return reject([`${messageOf(error)}; then ${exact}`]);
318
+ }
319
+ const stray = extrasNotInRecord(record, mixed.extras);
320
+ if (stray.length) {
321
+ return reject([`the record is read from ${mixed.file} alone, and these fields beside ${key} are missing from that file or differ from it: ${stray.join(", ")}. Write every field into the file, then ${exact}`], "the submission mixes a file with inline fields");
322
+ }
323
+ candidate = repairRecord(record, contract.schema);
324
+ }
325
+ else if (file !== null) {
326
+ // The file's record takes the same transport repair as an inline one.
327
+ try {
328
+ candidate = repairRecord(await contract.file.read(file), contract.schema);
329
+ }
330
+ catch (error) {
331
+ if (error?.code === "ENOENT")
332
+ return reject([`${key} names a file that does not exist in the workspace; write the complete JSON there first, then resubmit`]);
333
+ return reject([messageOf(error)]);
334
+ }
335
+ }
336
+ // A "null" the repair could not heal sits where the record's other fields rule null out: the model writes the value.
337
+ const unhealed = (candidate && typeof candidate === "object" && !Array.isArray(candidate) ? nullSpellings(candidate, contract.schema) : []).map((path) => `${path}: violates "this field cannot be null in this record: the schema admits null for the field alone, but the record's other fields rule it out" — write the real value`);
338
+ const owned = [...unhealed, ...(contract.contracts ? await contract.contracts(candidate) : [])];
339
+ if (owned.length)
340
+ return reject(owned, "the record violates host-owned contracts");
341
+ if (!validator || !validator.Check(candidate)) {
342
+ return reject(validator ? [...validator.Errors(candidate)].slice(0, VIOLATIONS_SHOWN).map((error) => `${error.instancePath || error.path || "/"}: ${error.message}`) : ["the record schema does not compile"]);
343
+ }
344
+ for (const check of contract.checks ?? []) {
345
+ let refusal;
346
+ try {
347
+ refusal = await check(candidate);
348
+ }
349
+ catch (error) {
350
+ refusal = { problems: [`host validation gate threw: ${messageOf(error)}`] };
351
+ }
352
+ if (refusal?.problems.length)
353
+ return reject(refusal.problems, refusal.reason);
354
+ }
355
+ // The second reading, once.
356
+ const round = !state.gate.bounced;
357
+ const disagreements = [];
358
+ for (const reviewer of contract.reviewers ?? []) {
359
+ try {
360
+ disagreements.push(...await reviewer(candidate, { round }));
361
+ }
362
+ catch (error) {
363
+ if (contract.fatal?.(error))
364
+ throw error;
365
+ }
366
+ }
367
+ if (gate(state.gate.bounced, [disagreements.length ? "disagrees" : "agrees"]) === "bounce") {
368
+ const attempts = await store.bounce();
369
+ return { status: "bounced", attempts, spent: attempts >= max, disagreements };
370
+ }
371
+ await store.accept(candidate, disagreements);
372
+ return { status: "accepted", record: candidate, disagreements };
373
+ }
374
+ /** The `submit` tool's answer to the model for one delivery. */
375
+ export function deliveryText(delivery, maxAttempts = DELIVERY_ATTEMPTS, say = disagreementText) {
376
+ const spentLine = "The delivery attempts are spent; the run stops here.";
377
+ switch (delivery.status) {
378
+ case "already": return "Already submitted; the first valid record is authoritative.";
379
+ case "accepted": return "Submitted. You are DONE; end your turn.";
380
+ case "rejected": return `REJECTED (${delivery.attempts}/${maxAttempts}) — ${delivery.reason}: ${delivery.problems.join("; ")}.${delivery.spent ? ` ${spentLine}` : " Fix exactly those and resubmit."}`;
381
+ case "bounced": return `${delivery.disagreements.map(say).join("\n")}${delivery.spent ? `\n${spentLine}` : ""}`;
382
+ }
383
+ }
384
+ /** One disagreement as the model reads it. */
385
+ export const disagreementText = (d) => `${d.id} (${d.kind}): ${d.verdict}${d.reasons.length ? ` - ${d.reasons.join("; ")}` : ""}`;
386
+ /** Whether a delivery ends the node's run: a record was delivered, or the attempts are spent. */
387
+ export const deliveryTerminates = (delivery) => delivery.status === "already" || delivery.status === "accepted" || ((delivery.status === "rejected" || delivery.status === "bounced") && delivery.spent);
388
+ /** The delivery contract a node's task ends with: the label, the file envelope when one is offered, the
389
+ * authoritative schema and the host's own delivery instructions. The model sees the exact schema only here. */
390
+ export function submitFooter(record) {
391
+ return [
392
+ `When you are done, call the \`submit\` tool ONCE with ${record.label} as its arguments. The arguments are validated against the required schema; if validation fails you get the problems back and may fix and resubmit.`,
393
+ ...(record.reviewed ? ["A schema-valid record is then reviewed against the procedure that governs this run before it is accepted; violations come back to you, with the rule each one breaks, to fix and resubmit."] : []),
394
+ ...(record.fileKey ? [`For a large record, write the complete JSON to a fresh file inside the workspace, then call \`submit\` once with {"${record.fileKey}":"relative/path.json"}. The harness reads and validates that file directly; do not paste the record back into the tool call.`] : []),
395
+ `Required JSON Schema (authoritative): ${JSON.stringify(record.schema)}`,
396
+ record.instructions || "",
397
+ "Only a successful `submit` call counts as delivering. Do not answer in plain text.",
398
+ ].filter(Boolean).join("\n");
399
+ }
400
+ /** What a yield without a record is answered with, when the delivery has an attempt left for it. */
401
+ export const nudgeText = (label) => `You stopped without submitting. Call submit with ${label}, complete.`;
@@ -0,0 +1,16 @@
1
+ export declare class PiRunError extends Error {
2
+ readonly reason: "aborted" | "timeout" | "turn_limit" | "submission_limit" | "no_submission" | "model_error";
3
+ readonly turns: number;
4
+ readonly submissions: number;
5
+ /** The node's turn limit for this attempt, or null when it had none. */
6
+ readonly maxTurns?: number | null;
7
+ /** The name of the last tool the node called, never its arguments. */
8
+ readonly lastTool?: string;
9
+ /** A turn limit ends the step: a fresh session with the same prompt and limit would spend the same again, so a
10
+ * recovery driver gives it no second attempt. */
11
+ readonly final?: true;
12
+ constructor(reason: "aborted" | "timeout" | "turn_limit" | "submission_limit" | "no_submission" | "model_error", turns: number, submissions: number, progress?: {
13
+ maxTurns?: number | null;
14
+ lastTool?: string;
15
+ });
16
+ }
@@ -0,0 +1,26 @@
1
+ // Kept apart from runner.ts, which loads pi-coding-agent, so a reader of the error type loads none of it.
2
+ export class PiRunError extends Error {
3
+ reason;
4
+ turns;
5
+ submissions;
6
+ /** The node's turn limit for this attempt, or null when it had none. */
7
+ maxTurns;
8
+ /** The name of the last tool the node called, never its arguments. */
9
+ lastTool;
10
+ /** A turn limit ends the step: a fresh session with the same prompt and limit would spend the same again, so a
11
+ * recovery driver gives it no second attempt. */
12
+ final;
13
+ constructor(reason, turns, submissions, progress = {}) {
14
+ super(`Pi node did not deliver an accepted submission: ${reason} (${turns} turns, ${submissions} submissions)`);
15
+ this.reason = reason;
16
+ this.turns = turns;
17
+ this.submissions = submissions;
18
+ this.name = "PiRunError";
19
+ if (progress.maxTurns !== undefined)
20
+ this.maxTurns = progress.maxTurns;
21
+ if (progress.lastTool !== undefined)
22
+ this.lastTool = progress.lastTool;
23
+ if (reason === "turn_limit")
24
+ this.final = true;
25
+ }
26
+ }
@@ -0,0 +1,6 @@
1
+ import { type WorkflowDeps } from "@parcha/agentrun-dsl";
2
+ import type { PiRunnerOptions } from "./types.js";
3
+ export type { PiRunnerOptions, PiSession, PiSessionFactory } from "./types.js";
4
+ export type PiRunner = NonNullable<WorkflowDeps["runNode"]>;
5
+ export { PiRunError } from "./run-error.js";
6
+ export declare function createPiRunner(options: PiRunnerOptions): PiRunner;