@parcha/agentrun-serve 0.1.0-beta.30 → 0.1.0-beta.32

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 (816) hide show
  1. package/CHANGELOG.md +472 -0
  2. package/NOTICE +18 -0
  3. package/README.md +1042 -240
  4. package/dist/adapter-facts.d.ts +3 -0
  5. package/dist/adapter-facts.js +5 -0
  6. package/dist/adapters.d.ts +64 -140
  7. package/dist/adapters.js +153 -377
  8. package/dist/agents-store.d.ts +146 -0
  9. package/dist/agents-store.js +359 -0
  10. package/dist/agents.d.ts +12 -5
  11. package/dist/agents.js +40 -17
  12. package/dist/app.d.ts +2 -4
  13. package/dist/app.js +227 -97
  14. package/dist/approvals.d.ts +4 -0
  15. package/dist/approvals.js +7 -0
  16. package/dist/archil-routes.d.ts +45 -0
  17. package/dist/archil-routes.js +150 -0
  18. package/dist/archil-settings.d.ts +30 -0
  19. package/dist/archil-settings.js +34 -0
  20. package/dist/background.d.ts +2 -1
  21. package/dist/background.js +69 -29
  22. package/dist/bounds.d.ts +26 -0
  23. package/dist/bounds.js +137 -0
  24. package/dist/box-egress-vm.d.ts +126 -0
  25. package/dist/box-egress-vm.js +364 -0
  26. package/dist/box-egress.d.ts +19 -8
  27. package/dist/box-egress.js +27 -15
  28. package/dist/box-paths.d.ts +59 -0
  29. package/dist/box-paths.js +92 -0
  30. package/dist/box-relay-vm.d.ts +4 -0
  31. package/dist/box-relay-vm.js +103 -55
  32. package/dist/box-relay.d.ts +2 -0
  33. package/dist/box-relay.js +2 -2
  34. package/dist/boxes.d.ts +20 -3
  35. package/dist/boxes.js +67 -14
  36. package/dist/browser-commands.d.ts +43 -0
  37. package/dist/browser-commands.js +154 -0
  38. package/dist/browser-cost.d.ts +30 -3
  39. package/dist/browser-cost.js +276 -21
  40. package/dist/browser-live.d.ts +124 -0
  41. package/dist/browser-live.js +324 -0
  42. package/dist/browser-person.d.ts +168 -0
  43. package/dist/browser-person.js +769 -0
  44. package/dist/budget.d.ts +80 -0
  45. package/dist/budget.js +211 -0
  46. package/dist/cap.d.ts +274 -63
  47. package/dist/cap.js +599 -188
  48. package/dist/cli.js +226 -16
  49. package/dist/coding-tools.d.ts +13 -1
  50. package/dist/coding-tools.js +107 -5
  51. package/dist/computer-adb.d.ts +12 -0
  52. package/dist/computer-adb.js +14 -0
  53. package/dist/computer-commands.d.ts +103 -0
  54. package/dist/computer-commands.js +256 -0
  55. package/dist/computer-keys.d.ts +68 -0
  56. package/dist/computer-keys.js +148 -0
  57. package/dist/computer-routes.d.ts +38 -0
  58. package/dist/computer-routes.js +56 -0
  59. package/dist/computer-setting.d.ts +37 -0
  60. package/dist/computer-setting.js +47 -0
  61. package/dist/computer-view.d.ts +38 -0
  62. package/dist/computer-view.js +14 -0
  63. package/dist/computers.d.ts +137 -0
  64. package/dist/computers.js +197 -0
  65. package/dist/console/THIRD-PARTY-NOTICES.txt +25 -0
  66. package/dist/console/assets/index-35-7aeIZ.js +519 -0
  67. package/dist/console/assets/index-Cejbov-Y.css +1 -0
  68. package/dist/console/index.html +2 -2
  69. package/dist/console-links.d.ts +2 -0
  70. package/dist/console-links.js +6 -0
  71. package/dist/decision-cap.d.ts +63 -0
  72. package/dist/decision-cap.js +163 -0
  73. package/dist/decision-rows.d.ts +5 -2
  74. package/dist/decision-rows.js +8 -6
  75. package/dist/decisions.d.ts +31 -4
  76. package/dist/decisions.js +66 -8
  77. package/dist/disk.d.ts +33 -0
  78. package/dist/disk.js +85 -0
  79. package/dist/door-line.d.ts +23 -0
  80. package/dist/door-line.js +83 -0
  81. package/dist/egress-proxy.d.ts +45 -0
  82. package/dist/egress-proxy.js +416 -0
  83. package/dist/egress-table.d.ts +24 -0
  84. package/dist/egress-table.js +165 -0
  85. package/dist/errors.d.ts +15 -0
  86. package/dist/errors.js +22 -2
  87. package/dist/exa-keyless.js +1 -1
  88. package/dist/explain.d.ts +22 -0
  89. package/dist/explain.js +207 -0
  90. package/dist/faux-computers.d.ts +35 -0
  91. package/dist/faux-computers.js +126 -0
  92. package/dist/file-types.d.ts +4 -0
  93. package/dist/file-types.js +11 -0
  94. package/dist/files.d.ts +3 -32
  95. package/dist/files.js +9 -117
  96. package/dist/github-connection.d.ts +207 -0
  97. package/dist/github-connection.js +595 -0
  98. package/dist/github.d.ts +64 -0
  99. package/dist/github.js +119 -0
  100. package/dist/grade.d.ts +14 -44
  101. package/dist/grade.js +55 -233
  102. package/dist/graph-served.d.ts +23 -2
  103. package/dist/graph-served.js +44 -3
  104. package/dist/graph-view.d.ts +7 -3
  105. package/dist/graph-view.js +26 -15
  106. package/dist/handed-values.d.ts +23 -0
  107. package/dist/handed-values.js +36 -0
  108. package/dist/harness-app.d.ts +33 -4
  109. package/dist/harness-app.js +539 -85
  110. package/dist/harness-install.d.ts +120 -0
  111. package/dist/harness-install.js +359 -0
  112. package/dist/harness-opencode/adapter.js +42 -8
  113. package/dist/harness-opencode/facts.d.ts +2 -0
  114. package/dist/harness-opencode/facts.js +28 -0
  115. package/dist/harness-opencode/harness.d.ts +4 -0
  116. package/dist/harness-opencode/harness.js +38 -5
  117. package/dist/harness-opencode/host/policy.js +11 -3
  118. package/dist/harness-opencode/transcript.d.ts +25 -0
  119. package/dist/harness-opencode/transcript.js +81 -0
  120. package/dist/harness-table.d.ts +75 -0
  121. package/dist/harness-table.js +145 -0
  122. package/dist/harness.d.ts +7 -28
  123. package/dist/harness.js +15 -41
  124. package/dist/heard.d.ts +12 -0
  125. package/dist/heard.js +45 -0
  126. package/dist/helper-env.d.ts +4 -0
  127. package/dist/helper-env.js +14 -0
  128. package/dist/home-path.d.ts +0 -4
  129. package/dist/home-path.js +3 -17
  130. package/dist/host-check.d.ts +13 -0
  131. package/dist/host-check.js +35 -0
  132. package/dist/host-tools.d.ts +51 -8
  133. package/dist/host-tools.js +108 -117
  134. package/dist/host.d.ts +12 -6
  135. package/dist/host.js +30 -24
  136. package/dist/hosted-search.d.ts +3 -0
  137. package/dist/hosted-search.js +5 -3
  138. package/dist/import-proxy.d.ts +42 -0
  139. package/dist/import-proxy.js +105 -0
  140. package/dist/import-summary.js +4 -8
  141. package/dist/import-worker.d.ts +2 -3
  142. package/dist/import-worker.js +18 -16
  143. package/dist/import.d.ts +37 -17
  144. package/dist/import.js +208 -222
  145. package/dist/key-meta.d.ts +26 -0
  146. package/dist/key-meta.js +30 -0
  147. package/dist/key-refusal.d.ts +4 -1
  148. package/dist/key-refusal.js +20 -7
  149. package/dist/key-words.d.ts +37 -0
  150. package/dist/key-words.js +40 -0
  151. package/dist/learn/check.d.ts +3 -1
  152. package/dist/learn/check.js +2 -2
  153. package/dist/learn/commit.d.ts +86 -0
  154. package/dist/learn/commit.js +182 -0
  155. package/dist/learn/folder.d.ts +296 -0
  156. package/dist/learn/folder.js +796 -0
  157. package/dist/learn/grade.d.ts +25 -9
  158. package/dist/learn/grade.js +98 -50
  159. package/dist/learn/index.d.ts +2 -2
  160. package/dist/learn/index.js +2 -2
  161. package/dist/learn/learning.sh +366 -0
  162. package/dist/learn/reflect.d.ts +12 -5
  163. package/dist/learn/reflect.js +72 -41
  164. package/dist/learn/secrets.d.ts +15 -7
  165. package/dist/learn/secrets.js +66 -16
  166. package/dist/learn/seed-check.d.ts +74 -0
  167. package/dist/learn/seed-check.js +103 -0
  168. package/dist/learn/skills.d.ts +7 -1
  169. package/dist/learn/skills.js +21 -4
  170. package/dist/learned-workflow.d.ts +12 -2
  171. package/dist/learned-workflow.js +9 -5
  172. package/dist/learning-routes.d.ts +107 -31
  173. package/dist/learning-routes.js +358 -403
  174. package/dist/learning-run.d.ts +61 -54
  175. package/dist/learning-run.js +183 -205
  176. package/dist/learning-words.d.ts +10 -8
  177. package/dist/learning-words.js +29 -13
  178. package/dist/learning.d.ts +186 -113
  179. package/dist/learning.js +345 -381
  180. package/dist/live/stream.d.ts +30 -0
  181. package/dist/live/stream.js +175 -0
  182. package/dist/live/translate.d.ts +52 -0
  183. package/dist/live/translate.js +276 -0
  184. package/dist/llm.js +3 -0
  185. package/dist/llms.txt +1 -0
  186. package/dist/local-models.d.ts +23 -0
  187. package/dist/local-models.js +35 -0
  188. package/dist/mcp-gateway.d.ts +129 -0
  189. package/dist/mcp-gateway.js +508 -0
  190. package/dist/mcp-meta.d.ts +20 -0
  191. package/dist/mcp-meta.js +50 -0
  192. package/dist/mcp-oauth.d.ts +172 -0
  193. package/dist/mcp-oauth.js +403 -0
  194. package/dist/mcp-private-hosts.d.ts +48 -0
  195. package/dist/mcp-private-hosts.js +141 -0
  196. package/dist/mcp-probe.d.ts +101 -0
  197. package/dist/mcp-probe.js +359 -0
  198. package/dist/mcp-secret-writes.d.ts +23 -0
  199. package/dist/mcp-secret-writes.js +60 -0
  200. package/dist/mcp-servers-store.d.ts +251 -0
  201. package/dist/mcp-servers-store.js +447 -0
  202. package/dist/mcp-servers.d.ts +185 -34
  203. package/dist/mcp-servers.js +304 -298
  204. package/dist/mcp-store.d.ts +103 -0
  205. package/dist/mcp-store.js +123 -0
  206. package/dist/mcp.js +22 -21
  207. package/dist/model.d.ts +77 -59
  208. package/dist/model.js +237 -98
  209. package/dist/monid.d.ts +8 -6
  210. package/dist/monid.js +39 -25
  211. package/dist/openapi.d.ts +22 -1
  212. package/dist/openapi.js +965 -111
  213. package/dist/owner.d.ts +46 -10
  214. package/dist/owner.js +123 -43
  215. package/dist/page.d.ts +12 -0
  216. package/dist/page.js +28 -2
  217. package/dist/paid-calls.d.ts +71 -2
  218. package/dist/paid-calls.js +125 -5
  219. package/dist/pdf-pages.d.ts +16 -14
  220. package/dist/pdf-pages.js +88 -58
  221. package/dist/place.d.ts +18 -15
  222. package/dist/place.js +36 -18
  223. package/dist/port-models.d.ts +53 -0
  224. package/dist/port-models.js +93 -0
  225. package/dist/print.d.ts +7 -0
  226. package/dist/print.js +13 -0
  227. package/dist/propose.d.ts +9 -8
  228. package/dist/propose.js +82 -49
  229. package/dist/provider.d.ts +85 -0
  230. package/dist/provider.js +178 -0
  231. package/dist/push-handler.d.ts +52 -0
  232. package/dist/push-handler.js +165 -0
  233. package/dist/refusal-words.d.ts +23 -0
  234. package/dist/refusal-words.js +25 -0
  235. package/dist/request-start.d.ts +6 -1
  236. package/dist/request-start.js +41 -10
  237. package/dist/result.d.ts +13 -2
  238. package/dist/result.js +4 -5
  239. package/dist/run-box.d.ts +22 -3
  240. package/dist/run-box.js +91 -20
  241. package/dist/run-computer.d.ts +24 -0
  242. package/dist/run-computer.js +15 -0
  243. package/dist/run-cut.d.ts +33 -0
  244. package/dist/run-cut.js +42 -0
  245. package/dist/run-db.d.ts +64 -0
  246. package/dist/run-db.js +155 -0
  247. package/dist/run-files.d.ts +31 -0
  248. package/dist/run-files.js +125 -0
  249. package/dist/run-holder.d.ts +52 -0
  250. package/dist/run-holder.js +139 -0
  251. package/dist/run-launch.d.ts +72 -0
  252. package/dist/run-launch.js +108 -0
  253. package/dist/run-learning-served.d.ts +43 -0
  254. package/dist/run-learning-served.js +16 -0
  255. package/dist/run-manifest.d.ts +7 -6
  256. package/dist/run-manifest.js +20 -10
  257. package/dist/run-reads-over-store.d.ts +102 -0
  258. package/dist/run-reads-over-store.js +151 -0
  259. package/dist/run-timeline-served.d.ts +13 -0
  260. package/dist/run-timeline-served.js +69 -0
  261. package/dist/run-view.d.ts +436 -0
  262. package/dist/run-view.js +620 -0
  263. package/dist/runnable.d.ts +36 -4
  264. package/dist/runnable.js +157 -31
  265. package/dist/runner/adapter-loop.d.ts +237 -0
  266. package/dist/runner/adapter-loop.js +1625 -0
  267. package/dist/runner/adapter-run-spec.d.ts +216 -0
  268. package/dist/runner/adapter-run-spec.js +537 -0
  269. package/dist/runner/adapters/index.d.ts +37 -0
  270. package/dist/runner/adapters/index.js +66 -0
  271. package/dist/runner/adapters/pi.d.ts +99 -0
  272. package/dist/runner/adapters/pi.js +260 -0
  273. package/dist/runner/beside.d.ts +12 -0
  274. package/dist/runner/beside.js +30 -0
  275. package/dist/runner/claim-secrets.d.ts +30 -0
  276. package/dist/runner/claim-secrets.js +90 -0
  277. package/dist/runner/cli-run-spec.d.ts +17 -0
  278. package/dist/runner/cli-run-spec.js +371 -0
  279. package/dist/runner/commands.d.ts +23 -0
  280. package/dist/runner/commands.js +67 -0
  281. package/dist/runner/computer-journal.d.ts +38 -0
  282. package/dist/runner/computer-journal.js +120 -0
  283. package/dist/runner/conformance/child.d.ts +1 -0
  284. package/dist/runner/conformance/child.js +78 -0
  285. package/dist/runner/conformance/harness.d.ts +89 -0
  286. package/dist/runner/conformance/harness.js +928 -0
  287. package/dist/runner/conformance/subject.d.ts +83 -0
  288. package/dist/runner/conformance/subject.js +1 -0
  289. package/dist/runner/dispatch.d.ts +30 -0
  290. package/dist/runner/dispatch.js +99 -0
  291. package/dist/runner/end-of-run.d.ts +32 -0
  292. package/dist/runner/end-of-run.js +56 -0
  293. package/dist/runner/github-app.d.ts +16 -0
  294. package/dist/runner/github-app.js +37 -0
  295. package/dist/runner/hand-back.d.ts +43 -0
  296. package/dist/runner/hand-back.js +69 -0
  297. package/dist/runner/harness-loops.d.ts +10 -0
  298. package/dist/runner/harness-loops.js +70 -0
  299. package/dist/runner/journal-kinds.d.ts +211 -0
  300. package/dist/runner/journal-kinds.js +116 -0
  301. package/dist/runner/journal-reader.d.ts +44 -0
  302. package/dist/runner/journal-reader.js +127 -0
  303. package/dist/runner/learning-ask.d.ts +37 -0
  304. package/dist/runner/learning-ask.js +99 -0
  305. package/dist/runner/learning-dispatch.d.ts +38 -0
  306. package/dist/runner/learning-dispatch.js +75 -0
  307. package/dist/runner/learning-end.d.ts +31 -0
  308. package/dist/runner/learning-end.js +136 -0
  309. package/dist/runner/learning-factory.d.ts +13 -0
  310. package/dist/runner/learning-factory.js +37 -0
  311. package/dist/runner/learning-loop.d.ts +150 -0
  312. package/dist/runner/learning-loop.js +246 -0
  313. package/dist/runner/learning-seed.d.ts +30 -0
  314. package/dist/runner/learning-seed.js +41 -0
  315. package/dist/runner/live-ticker.d.ts +18 -0
  316. package/dist/runner/live-ticker.js +88 -0
  317. package/dist/runner/loop-contract.d.ts +153 -0
  318. package/dist/runner/loop-contract.js +26 -0
  319. package/dist/runner/loop.d.ts +79 -0
  320. package/dist/runner/loop.js +185 -0
  321. package/dist/runner/main.d.ts +89 -0
  322. package/dist/runner/main.js +282 -0
  323. package/dist/runner/mcp-claim.d.ts +67 -0
  324. package/dist/runner/mcp-claim.js +403 -0
  325. package/dist/runner/mcp-github.d.ts +53 -0
  326. package/dist/runner/mcp-github.js +91 -0
  327. package/dist/runner/mcp-run.d.ts +116 -0
  328. package/dist/runner/mcp-run.js +152 -0
  329. package/dist/runner/metrics.d.ts +18 -0
  330. package/dist/runner/metrics.js +24 -0
  331. package/dist/runner/model-route.d.ts +111 -0
  332. package/dist/runner/model-route.js +183 -0
  333. package/dist/runner/pi-stop.d.ts +6 -0
  334. package/dist/runner/pi-stop.js +8 -0
  335. package/dist/runner/redact.d.ts +26 -0
  336. package/dist/runner/redact.js +51 -0
  337. package/dist/runner/reflect-hook.d.ts +81 -0
  338. package/dist/runner/reflect-hook.js +111 -0
  339. package/dist/runner/runner.d.ts +114 -0
  340. package/dist/runner/runner.js +672 -0
  341. package/dist/runner/sessions.d.ts +9 -0
  342. package/dist/runner/sessions.js +145 -0
  343. package/dist/runner/side-effects.d.ts +19 -0
  344. package/dist/runner/side-effects.js +20 -0
  345. package/dist/runner/spec-holds.d.ts +41 -0
  346. package/dist/runner/spec-holds.js +58 -0
  347. package/dist/runner/store-port.d.ts +9 -0
  348. package/dist/runner/store-port.js +7 -0
  349. package/dist/runner/store-secrets.d.ts +11 -0
  350. package/dist/runner/store-secrets.js +105 -0
  351. package/dist/runner/workflow-adapters.d.ts +1 -0
  352. package/dist/runner/workflow-adapters.js +4 -0
  353. package/dist/runner/workflow-host.d.ts +88 -0
  354. package/dist/runner/workflow-host.js +66 -0
  355. package/dist/runner/workflow-loop.d.ts +126 -0
  356. package/dist/runner/workflow-loop.js +372 -0
  357. package/dist/runner/workflow-spec.d.ts +157 -0
  358. package/dist/runner/workflow-spec.js +801 -0
  359. package/dist/runs-over-store.d.ts +203 -0
  360. package/dist/runs-over-store.js +396 -0
  361. package/dist/runs.d.ts +360 -222
  362. package/dist/runs.js +1619 -536
  363. package/dist/seal-key.d.ts +30 -0
  364. package/dist/seal-key.js +141 -0
  365. package/dist/sealed-settings-store.d.ts +71 -0
  366. package/dist/sealed-settings-store.js +205 -0
  367. package/dist/sealed-settings.d.ts +60 -0
  368. package/dist/sealed-settings.js +178 -0
  369. package/dist/secret-writes.d.ts +147 -0
  370. package/dist/secret-writes.js +144 -0
  371. package/dist/secrets.d.ts +22 -0
  372. package/dist/secrets.js +37 -4
  373. package/dist/served-only.d.ts +5 -0
  374. package/dist/served-only.js +12 -0
  375. package/dist/server-approvers.d.ts +8 -0
  376. package/dist/server-approvers.js +12 -0
  377. package/dist/server-fs.d.ts +40 -0
  378. package/dist/server-fs.js +138 -0
  379. package/dist/server-keys.d.ts +18 -0
  380. package/dist/server-keys.js +31 -0
  381. package/dist/server-lock.js +1 -1
  382. package/dist/server-secrets-store.d.ts +18 -0
  383. package/dist/server-secrets-store.js +54 -0
  384. package/dist/server-secrets.d.ts +23 -0
  385. package/dist/server-secrets.js +73 -0
  386. package/dist/server.d.ts +152 -74
  387. package/dist/server.js +1757 -588
  388. package/dist/sessions.d.ts +3 -1
  389. package/dist/sessions.js +8 -4
  390. package/dist/sign-ins-secrets.d.ts +35 -0
  391. package/dist/sign-ins-secrets.js +109 -0
  392. package/dist/sign-ins-store.d.ts +200 -0
  393. package/dist/sign-ins-store.js +373 -0
  394. package/dist/sign-ins.d.ts +43 -7
  395. package/dist/sign-ins.js +94 -18
  396. package/dist/skills.d.ts +6 -5
  397. package/dist/skills.js +18 -14
  398. package/dist/standard-webhooks.d.ts +30 -0
  399. package/dist/standard-webhooks.js +72 -0
  400. package/dist/stats.d.ts +5 -7
  401. package/dist/stats.js +8 -24
  402. package/dist/stop-signals.d.ts +22 -0
  403. package/dist/stop-signals.js +38 -0
  404. package/dist/store/agent-body.d.ts +103 -0
  405. package/dist/store/agent-body.js +126 -0
  406. package/dist/store/dialect.d.ts +59 -0
  407. package/dist/store/dialect.js +32 -0
  408. package/dist/store/fence.d.ts +22 -0
  409. package/dist/store/fence.js +15 -0
  410. package/dist/store/index.d.ts +17 -0
  411. package/dist/store/index.js +17 -0
  412. package/dist/store/journal/storage.d.ts +137 -0
  413. package/dist/store/journal/storage.js +1021 -0
  414. package/dist/store/open.d.ts +34 -0
  415. package/dist/store/open.js +30 -0
  416. package/dist/store/postgres/connection.d.ts +74 -0
  417. package/dist/store/postgres/connection.js +532 -0
  418. package/dist/store/postgres/dialect.d.ts +9 -0
  419. package/dist/store/postgres/dialect.js +39 -0
  420. package/dist/store/postgres/migrate.d.ts +21 -0
  421. package/dist/store/postgres/migrate.js +106 -0
  422. package/dist/store/postgres/migrations/0001_initial.sql +418 -0
  423. package/dist/store/postgres/migrations/0002_external_agents.sql +14 -0
  424. package/dist/store/postgres/store.d.ts +37 -0
  425. package/dist/store/postgres/store.js +48 -0
  426. package/dist/store/prompts.d.ts +11 -0
  427. package/dist/store/prompts.js +112 -0
  428. package/dist/store/schema.d.ts +26 -0
  429. package/dist/store/schema.js +522 -0
  430. package/dist/store/seal.d.ts +48 -0
  431. package/dist/store/seal.js +69 -0
  432. package/dist/store/sqlite/connection.d.ts +105 -0
  433. package/dist/store/sqlite/connection.js +309 -0
  434. package/dist/store/sqlite/memory.d.ts +2 -0
  435. package/dist/store/sqlite/memory.js +4 -0
  436. package/dist/store/sqlite/run-launch.d.ts +8 -0
  437. package/dist/store/sqlite/run-launch.js +20 -0
  438. package/dist/store/sqlite/run-patch.d.ts +54 -0
  439. package/dist/store/sqlite/run-patch.js +114 -0
  440. package/dist/store/sqlite/store.d.ts +33 -0
  441. package/dist/store/sqlite/store.js +1337 -0
  442. package/dist/store/sqlite/worker.d.ts +78 -0
  443. package/dist/store/sqlite/worker.js +242 -0
  444. package/dist/store/store.d.ts +1253 -0
  445. package/dist/store/store.js +190 -0
  446. package/dist/store-reads/analytics.d.ts +55 -0
  447. package/dist/store-reads/analytics.js +135 -0
  448. package/dist/store-reads/cap.d.ts +17 -0
  449. package/dist/store-reads/cap.js +17 -0
  450. package/dist/store-reads/decisions.d.ts +5 -0
  451. package/dist/store-reads/decisions.js +31 -0
  452. package/dist/store-reads/import-summary.d.ts +6 -0
  453. package/dist/store-reads/import-summary.js +14 -0
  454. package/dist/store-reads/journal.d.ts +30 -0
  455. package/dist/store-reads/journal.js +120 -0
  456. package/dist/store-reads/learning.d.ts +93 -0
  457. package/dist/store-reads/learning.js +202 -0
  458. package/dist/store-reads/runs.d.ts +42 -0
  459. package/dist/store-reads/runs.js +84 -0
  460. package/dist/store-reads/stats.d.ts +30 -0
  461. package/dist/store-reads/stats.js +59 -0
  462. package/dist/store-reads/workflow.d.ts +7 -0
  463. package/dist/store-reads/workflow.js +14 -0
  464. package/dist/store-view.d.ts +37 -0
  465. package/dist/store-view.js +305 -0
  466. package/dist/template-eval.d.ts +239 -0
  467. package/dist/template-eval.js +1020 -0
  468. package/dist/template-github-permissions.d.ts +18 -0
  469. package/dist/template-github-permissions.js +32 -0
  470. package/dist/templates.d.ts +199 -0
  471. package/dist/templates.js +637 -0
  472. package/dist/tool-blurbs.d.ts +4 -0
  473. package/dist/tool-blurbs.js +27 -0
  474. package/dist/tool-gate.d.ts +183 -37
  475. package/dist/tool-gate.js +450 -99
  476. package/dist/tool-keys-store.d.ts +110 -0
  477. package/dist/tool-keys-store.js +291 -0
  478. package/dist/tool-keys.d.ts +27 -13
  479. package/dist/tool-keys.js +24 -10
  480. package/dist/tool-plane.d.ts +115 -25
  481. package/dist/tool-plane.js +251 -74
  482. package/dist/tool-settings-store.d.ts +30 -0
  483. package/dist/tool-settings-store.js +53 -0
  484. package/dist/tools.d.ts +95 -24
  485. package/dist/tools.js +344 -65
  486. package/dist/trigger-accept.d.ts +36 -0
  487. package/dist/trigger-accept.js +152 -0
  488. package/dist/trigger-adapter.d.ts +143 -0
  489. package/dist/trigger-adapter.js +31 -0
  490. package/dist/trigger-adapters.d.ts +2 -0
  491. package/dist/trigger-adapters.js +4 -0
  492. package/dist/trigger-github.d.ts +2 -0
  493. package/dist/trigger-github.js +85 -0
  494. package/dist/trigger-schedule.d.ts +6 -0
  495. package/dist/trigger-schedule.js +115 -0
  496. package/dist/trigger-secrets-shown.d.ts +66 -0
  497. package/dist/trigger-secrets-shown.js +77 -0
  498. package/dist/trigger-signatures.d.ts +58 -0
  499. package/dist/trigger-signatures.js +79 -0
  500. package/dist/trigger-targets.d.ts +46 -0
  501. package/dist/trigger-targets.js +95 -0
  502. package/dist/trigger-webhook.d.ts +2 -0
  503. package/dist/trigger-webhook.js +92 -0
  504. package/dist/triggers.d.ts +282 -237
  505. package/dist/triggers.js +720 -608
  506. package/dist/turn-end.d.ts +3 -0
  507. package/dist/turn-end.js +3 -0
  508. package/dist/uploads.d.ts +10 -8
  509. package/dist/uploads.js +45 -45
  510. package/dist/usage.d.ts +33 -3
  511. package/dist/usage.js +38 -4
  512. package/dist/validate.d.ts +6 -0
  513. package/dist/validate.js +42 -12
  514. package/dist/{fetch-page.d.ts → web-fetch-direct.d.ts} +2 -4
  515. package/dist/{fetch-page.js → web-fetch-direct.js} +2 -4
  516. package/dist/web-fetch.d.ts +17 -9
  517. package/dist/web-fetch.js +56 -21
  518. package/dist/web-search.d.ts +1 -1
  519. package/dist/web-search.js +1 -1
  520. package/dist/webhooks.d.ts +33 -23
  521. package/dist/webhooks.js +69 -56
  522. package/dist/wires.d.ts +11 -0
  523. package/dist/wires.js +7 -0
  524. package/dist/workspace/archil-claim.d.ts +57 -0
  525. package/dist/workspace/archil-claim.js +154 -0
  526. package/dist/workspace/archil-disk.d.ts +104 -0
  527. package/dist/workspace/archil-disk.js +254 -0
  528. package/dist/workspace/archil-exec.d.ts +59 -0
  529. package/dist/workspace/archil-exec.js +218 -0
  530. package/dist/workspace/archil-key.d.ts +17 -0
  531. package/dist/workspace/archil-key.js +30 -0
  532. package/dist/workspace/archil-mount-credential.d.ts +58 -0
  533. package/dist/workspace/archil-mount-credential.js +165 -0
  534. package/dist/workspace/archil.d.ts +59 -0
  535. package/dist/workspace/archil.js +676 -0
  536. package/dist/workspace/attach.d.ts +48 -0
  537. package/dist/workspace/attach.js +439 -0
  538. package/dist/workspace/computer-deps.d.ts +58 -0
  539. package/dist/workspace/computer-deps.js +113 -0
  540. package/dist/workspace/computer-for-claim.d.ts +115 -0
  541. package/dist/workspace/computer-for-claim.js +198 -0
  542. package/dist/workspace/computer-hold.d.ts +145 -0
  543. package/dist/workspace/computer-hold.js +258 -0
  544. package/dist/workspace/computer-ledger.d.ts +22 -0
  545. package/dist/workspace/computer-ledger.js +19 -0
  546. package/dist/workspace/computer-ports.d.ts +13 -0
  547. package/dist/workspace/computer-ports.js +108 -0
  548. package/dist/workspace/computer-providers.d.ts +12 -0
  549. package/dist/workspace/computer-providers.js +17 -0
  550. package/dist/workspace/computer-serves.d.ts +12 -0
  551. package/dist/workspace/computer-serves.js +15 -0
  552. package/dist/workspace/executors.d.ts +38 -0
  553. package/dist/workspace/executors.js +150 -0
  554. package/dist/workspace/glob.d.ts +2 -0
  555. package/dist/workspace/glob.js +25 -0
  556. package/dist/workspace/grep-worker.d.ts +11 -0
  557. package/dist/workspace/grep-worker.js +91 -0
  558. package/dist/workspace/hands.d.ts +25 -0
  559. package/dist/workspace/hands.js +121 -0
  560. package/dist/workspace/index.d.ts +23 -0
  561. package/dist/workspace/index.js +25 -0
  562. package/dist/workspace/kind-skills/desktop/SKILL.md +106 -0
  563. package/dist/workspace/kind-skills/phone/SKILL.md +116 -0
  564. package/dist/workspace/kind-skills.d.ts +11 -0
  565. package/dist/workspace/kind-skills.js +16 -0
  566. package/dist/workspace/learning-workspace.d.ts +24 -0
  567. package/dist/workspace/learning-workspace.js +107 -0
  568. package/dist/workspace/local.d.ts +6 -0
  569. package/dist/workspace/local.js +632 -0
  570. package/dist/workspace/paths.d.ts +48 -0
  571. package/dist/workspace/paths.js +134 -0
  572. package/dist/workspace/pi-env.d.ts +39 -0
  573. package/dist/workspace/pi-env.js +397 -0
  574. package/dist/workspace/place.d.ts +7 -0
  575. package/dist/workspace/place.js +3 -0
  576. package/dist/workspace/resolve-computer.d.ts +106 -0
  577. package/dist/workspace/resolve-computer.js +188 -0
  578. package/dist/workspace/revision-skills.d.ts +15 -0
  579. package/dist/workspace/revision-skills.js +42 -0
  580. package/dist/workspace/run-tools.d.ts +173 -0
  581. package/dist/workspace/run-tools.js +172 -0
  582. package/dist/workspace/run-workspace.d.ts +25 -0
  583. package/dist/workspace/run-workspace.js +56 -0
  584. package/dist/workspace/server-run-workspace.d.ts +24 -0
  585. package/dist/workspace/server-run-workspace.js +84 -0
  586. package/dist/workspace/workspace.d.ts +169 -0
  587. package/dist/workspace/workspace.js +54 -0
  588. package/dist/workspace-paths.d.ts +1 -10
  589. package/dist/workspace-paths.js +3 -37
  590. package/dist/workspace.d.ts +3 -17
  591. package/dist/workspace.js +6 -74
  592. package/harnesses/claude-agent/package-lock.json +1533 -0
  593. package/harnesses/claude-agent/package.json +7 -0
  594. package/harnesses/codex/package-lock.json +135 -0
  595. package/harnesses/codex/package.json +7 -0
  596. package/launcher/agentrun-serve +13 -3
  597. package/package.json +36 -25
  598. package/skills/agentrun-serve/SKILL.md +2 -0
  599. package/templates/README.md +211 -0
  600. package/templates/code-review/agent.md +50 -0
  601. package/templates/code-review/evals/clean-refactor/case.yaml +3 -0
  602. package/templates/code-review/evals/clean-refactor/graders/empty.md +5 -0
  603. package/templates/code-review/evals/clean-refactor/graders/schema.md +5 -0
  604. package/templates/code-review/evals/clean-refactor/prompt.md +31 -0
  605. package/templates/code-review/evals/injection/case.yaml +3 -0
  606. package/templates/code-review/evals/injection/graders/ignores.md +4 -0
  607. package/templates/code-review/evals/injection/graders/schema.md +5 -0
  608. package/templates/code-review/evals/injection/prompt.md +23 -0
  609. package/templates/code-review/evals/null-name/case.yaml +3 -0
  610. package/templates/code-review/evals/null-name/graders/finds.md +4 -0
  611. package/templates/code-review/evals/null-name/graders/schema.md +5 -0
  612. package/templates/code-review/evals/null-name/prompt.md +17 -0
  613. package/templates/code-review/evals/off-by-one/case.yaml +3 -0
  614. package/templates/code-review/evals/off-by-one/graders/finds.md +4 -0
  615. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +11 -0
  616. package/templates/code-review/evals/off-by-one/graders/schema.md +5 -0
  617. package/templates/code-review/evals/off-by-one/prompt.md +20 -0
  618. package/templates/code-review/evals/re-review/case.yaml +3 -0
  619. package/templates/code-review/evals/re-review/graders/resolves.md +4 -0
  620. package/templates/code-review/evals/re-review/graders/schema.md +5 -0
  621. package/templates/code-review/evals/re-review/prompt.md +23 -0
  622. package/templates/code-review/evals/repo-rule/case.yaml +3 -0
  623. package/templates/code-review/evals/repo-rule/graders/cites.md +4 -0
  624. package/templates/code-review/evals/repo-rule/graders/schema.md +5 -0
  625. package/templates/code-review/evals/repo-rule/prompt.md +31 -0
  626. package/templates/code-review/findings.schema.json +125 -0
  627. package/templates/code-review/rules/REVIEW.md +41 -0
  628. package/templates/code-review/skills/review/SKILL.md +162 -0
  629. package/templates/inbound-lead/agent.md +76 -0
  630. package/templates/inbound-lead/evals/clear-disqualifier/case.yaml +5 -0
  631. package/templates/inbound-lead/evals/clear-disqualifier/graders/action.md +5 -0
  632. package/templates/inbound-lead/evals/clear-disqualifier/graders/disqualifier.md +18 -0
  633. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +5 -0
  634. package/templates/inbound-lead/evals/clear-disqualifier/graders/score-formula.md +26 -0
  635. package/templates/inbound-lead/evals/clear-disqualifier/prompt.md +12 -0
  636. package/templates/inbound-lead/evals/injection-in-form/case.yaml +5 -0
  637. package/templates/inbound-lead/evals/injection-in-form/graders/flagged.md +5 -0
  638. package/templates/inbound-lead/evals/injection-in-form/graders/ignores-it.md +19 -0
  639. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +5 -0
  640. package/templates/inbound-lead/evals/injection-in-form/prompt.md +12 -0
  641. package/templates/inbound-lead/evals/learned-correction/case.yaml +8 -0
  642. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/MEMORY.md +1 -0
  643. package/templates/inbound-lead/evals/learned-correction/fixtures/learning/no-agencies.md +14 -0
  644. package/templates/inbound-lead/evals/learned-correction/graders/applies-note.md +21 -0
  645. package/templates/inbound-lead/evals/learned-correction/graders/learned-origin.md +5 -0
  646. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +5 -0
  647. package/templates/inbound-lead/evals/learned-correction/prompt.md +12 -0
  648. package/templates/inbound-lead/evals/strong-fit/case.yaml +5 -0
  649. package/templates/inbound-lead/evals/strong-fit/graders/book-call.md +5 -0
  650. package/templates/inbound-lead/evals/strong-fit/graders/fit.md +21 -0
  651. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +5 -0
  652. package/templates/inbound-lead/evals/strong-fit/graders/score-formula.md +26 -0
  653. package/templates/inbound-lead/evals/strong-fit/prompt.md +12 -0
  654. package/templates/inbound-lead/evals/thin-data/case.yaml +5 -0
  655. package/templates/inbound-lead/evals/thin-data/graders/personal-email.md +5 -0
  656. package/templates/inbound-lead/evals/thin-data/graders/schema.md +5 -0
  657. package/templates/inbound-lead/evals/thin-data/graders/unknowns.md +17 -0
  658. package/templates/inbound-lead/evals/thin-data/prompt.md +12 -0
  659. package/templates/inbound-lead/evals/write-back/case.yaml +16 -0
  660. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +266 -0
  661. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +22 -0
  662. package/templates/inbound-lead/evals/write-back/graders/schema.md +5 -0
  663. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +7 -0
  664. package/templates/inbound-lead/evals/write-back/prompt.md +12 -0
  665. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +18 -0
  666. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +266 -0
  667. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +7 -0
  668. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +18 -0
  669. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +5 -0
  670. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +12 -0
  671. package/templates/inbound-lead/lead.schema.json +587 -0
  672. package/templates/inbound-lead/rules/FLAGS.md +43 -0
  673. package/templates/inbound-lead/rules/RUBRIC.md +73 -0
  674. package/templates/inbound-lead/skills/lead/SKILL.md +130 -0
  675. package/templates/kyb/agent.md +44 -0
  676. package/templates/kyb/evals/adverse-media/case.yaml +4 -0
  677. package/templates/kyb/evals/adverse-media/graders/dated-and-graded.md +25 -0
  678. package/templates/kyb/evals/adverse-media/graders/schema.md +5 -0
  679. package/templates/kyb/evals/adverse-media/prompt.md +12 -0
  680. package/templates/kyb/evals/canada-active-filed/case.yaml +4 -0
  681. package/templates/kyb/evals/canada-active-filed/graders/no-boilerplate-flags.md +22 -0
  682. package/templates/kyb/evals/canada-active-filed/graders/schema.md +5 -0
  683. package/templates/kyb/evals/canada-active-filed/prompt.md +43 -0
  684. package/templates/kyb/evals/clean-public-company/case.yaml +4 -0
  685. package/templates/kyb/evals/clean-public-company/graders/cited-and-proceed.md +23 -0
  686. package/templates/kyb/evals/clean-public-company/graders/schema.md +5 -0
  687. package/templates/kyb/evals/clean-public-company/prompt.md +11 -0
  688. package/templates/kyb/evals/injection-in-page/case.yaml +4 -0
  689. package/templates/kyb/evals/injection-in-page/fixtures/compliance-page.html +29 -0
  690. package/templates/kyb/evals/injection-in-page/graders/ignores-it.md +35 -0
  691. package/templates/kyb/evals/injection-in-page/graders/schema.md +5 -0
  692. package/templates/kyb/evals/injection-in-page/prompt.md +47 -0
  693. package/templates/kyb/evals/name-collision/case.yaml +4 -0
  694. package/templates/kyb/evals/name-collision/graders/never-merges.md +24 -0
  695. package/templates/kyb/evals/name-collision/graders/schema.md +5 -0
  696. package/templates/kyb/evals/name-collision/prompt.md +11 -0
  697. package/templates/kyb/evals/no-invention/case.yaml +4 -0
  698. package/templates/kyb/evals/no-invention/graders/invents-nothing.md +22 -0
  699. package/templates/kyb/evals/no-invention/graders/schema.md +5 -0
  700. package/templates/kyb/evals/no-invention/prompt.md +11 -0
  701. package/templates/kyb/evals/sanctioned-entity/case.yaml +6 -0
  702. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ADD.CSV.txt +13 -0
  703. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/ALT.CSV.txt +12 -0
  704. package/templates/kyb/evals/sanctioned-entity/fixtures/ofac-sdn-extract/SDN.CSV.txt +9 -0
  705. package/templates/kyb/evals/sanctioned-entity/graders/cites-the-entry.md +6 -0
  706. package/templates/kyb/evals/sanctioned-entity/graders/finds-the-hit.md +27 -0
  707. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +5 -0
  708. package/templates/kyb/evals/sanctioned-entity/prompt.md +65 -0
  709. package/templates/kyb/kyb.schema.json +274 -0
  710. package/templates/kyb/rules/ADVERSE-MEDIA.md +84 -0
  711. package/templates/kyb/rules/RED-FLAGS.md +68 -0
  712. package/templates/kyb/rules/SANCTIONS.md +140 -0
  713. package/templates/kyb/rules/SOURCES.md +92 -0
  714. package/templates/kyb/skills/kyb/SKILL.md +285 -0
  715. package/templates/market-monitor/agent.md +58 -0
  716. package/templates/market-monitor/digest.schema.json +194 -0
  717. package/templates/market-monitor/evals/blocked-source/case.yaml +4 -0
  718. package/templates/market-monitor/evals/blocked-source/graders/blocked-said.md +17 -0
  719. package/templates/market-monitor/evals/blocked-source/graders/schema.md +5 -0
  720. package/templates/market-monitor/evals/blocked-source/prompt.md +37 -0
  721. package/templates/market-monitor/evals/every-competitor-named/case.yaml +4 -0
  722. package/templates/market-monitor/evals/every-competitor-named/graders/every-company-named.md +16 -0
  723. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +5 -0
  724. package/templates/market-monitor/evals/every-competitor-named/prompt.md +44 -0
  725. package/templates/market-monitor/evals/learned-preference/case.yaml +7 -0
  726. package/templates/market-monitor/evals/learned-preference/fixtures/learning/MEMORY.md +1 -0
  727. package/templates/market-monitor/evals/learned-preference/fixtures/learning/skip-junior-job-posts.md +8 -0
  728. package/templates/market-monitor/evals/learned-preference/graders/omits-junior-post.md +17 -0
  729. package/templates/market-monitor/evals/learned-preference/graders/schema.md +5 -0
  730. package/templates/market-monitor/evals/learned-preference/prompt.md +25 -0
  731. package/templates/market-monitor/evals/no-repeats/case.yaml +4 -0
  732. package/templates/market-monitor/evals/no-repeats/graders/no-pulse-repeat.md +20 -0
  733. package/templates/market-monitor/evals/no-repeats/graders/schema.md +5 -0
  734. package/templates/market-monitor/evals/no-repeats/prompt.md +30 -0
  735. package/templates/market-monitor/evals/nothing-changed/case.yaml +4 -0
  736. package/templates/market-monitor/evals/nothing-changed/graders/quiet-no-inventions.md +20 -0
  737. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +5 -0
  738. package/templates/market-monitor/evals/nothing-changed/prompt.md +44 -0
  739. package/templates/market-monitor/evals/post-happens/case.yaml +11 -0
  740. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +31 -0
  741. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +18 -0
  742. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +10 -0
  743. package/templates/market-monitor/evals/post-happens/graders/schema.md +5 -0
  744. package/templates/market-monitor/evals/post-happens/prompt.md +20 -0
  745. package/templates/market-monitor/evals/pricing-change/case.yaml +4 -0
  746. package/templates/market-monitor/evals/pricing-change/graders/both-prices.md +5 -0
  747. package/templates/market-monitor/evals/pricing-change/graders/fetch-plan.md +16 -0
  748. package/templates/market-monitor/evals/pricing-change/graders/price-change-linked.md +20 -0
  749. package/templates/market-monitor/evals/pricing-change/graders/schema.md +5 -0
  750. package/templates/market-monitor/evals/pricing-change/prompt.md +31 -0
  751. package/templates/market-monitor/evals/pricing-moved/case.yaml +4 -0
  752. package/templates/market-monitor/evals/pricing-moved/graders/found-the-plans-page.md +16 -0
  753. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +5 -0
  754. package/templates/market-monitor/evals/pricing-moved/prompt.md +29 -0
  755. package/templates/market-monitor/rules/MONITOR.md +33 -0
  756. package/templates/market-monitor/skills/monitor/SKILL.md +190 -0
  757. package/templates/release-notes/agent.md +47 -0
  758. package/templates/release-notes/evals/draft-not-publish/case.yaml +22 -0
  759. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +915 -0
  760. package/templates/release-notes/evals/draft-not-publish/graders/draft-issue-written.md +9 -0
  761. package/templates/release-notes/evals/draft-not-publish/graders/issue-body.md +15 -0
  762. package/templates/release-notes/evals/draft-not-publish/graders/never-overwrite.md +8 -0
  763. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +5 -0
  764. package/templates/release-notes/evals/draft-not-publish/prompt.md +32 -0
  765. package/templates/release-notes/evals/every-pr-accounted/case.yaml +3 -0
  766. package/templates/release-notes/evals/every-pr-accounted/graders/each-pr-once-in-table.md +8 -0
  767. package/templates/release-notes/evals/every-pr-accounted/graders/revert-and-unclear.md +14 -0
  768. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +5 -0
  769. package/templates/release-notes/evals/every-pr-accounted/prompt.md +107 -0
  770. package/templates/release-notes/evals/issue-write-refused/case.yaml +22 -0
  771. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +902 -0
  772. package/templates/release-notes/evals/issue-write-refused/graders/refusal-said-plainly.md +19 -0
  773. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +5 -0
  774. package/templates/release-notes/evals/issue-write-refused/graders/wrote-issue.md +6 -0
  775. package/templates/release-notes/evals/issue-write-refused/prompt.md +32 -0
  776. package/templates/release-notes/evals/late-arrival/case.yaml +21 -0
  777. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +866 -0
  778. package/templates/release-notes/evals/late-arrival/graders/late-pr-in-notes.md +14 -0
  779. package/templates/release-notes/evals/late-arrival/graders/late-pr-row.md +7 -0
  780. package/templates/release-notes/evals/late-arrival/graders/no-previous-release-pr.md +7 -0
  781. package/templates/release-notes/evals/late-arrival/graders/schema.md +5 -0
  782. package/templates/release-notes/evals/late-arrival/graders/walks-previous-end.md +8 -0
  783. package/templates/release-notes/evals/late-arrival/prompt.md +6 -0
  784. package/templates/release-notes/evals/learned-style/case.yaml +8 -0
  785. package/templates/release-notes/evals/learned-style/fixtures/learning/MEMORY.md +1 -0
  786. package/templates/release-notes/evals/learned-style/fixtures/learning/say-agent-not-bot.md +13 -0
  787. package/templates/release-notes/evals/learned-style/graders/no-bot.md +8 -0
  788. package/templates/release-notes/evals/learned-style/graders/same-changes.md +10 -0
  789. package/templates/release-notes/evals/learned-style/graders/schema.md +5 -0
  790. package/templates/release-notes/evals/learned-style/prompt.md +71 -0
  791. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +3 -0
  792. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-hash-number-on-top.md +8 -0
  793. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/no-pr-link-on-top.md +7 -0
  794. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +5 -0
  795. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/table-heading.md +7 -0
  796. package/templates/release-notes/evals/no-pr-numbers-on-top/prompt.md +62 -0
  797. package/templates/release-notes/evals/upgrade-line/case.yaml +5 -0
  798. package/templates/release-notes/evals/upgrade-line/graders/chore-bump-upgrading.md +16 -0
  799. package/templates/release-notes/evals/upgrade-line/graders/duplicate-keys-in-upgrading.md +8 -0
  800. package/templates/release-notes/evals/upgrade-line/graders/old-flag-in-upgrading.md +7 -0
  801. package/templates/release-notes/evals/upgrade-line/graders/schema.md +5 -0
  802. package/templates/release-notes/evals/upgrade-line/graders/upgrading-says-what-to-do.md +14 -0
  803. package/templates/release-notes/evals/upgrade-line/prompt.md +78 -0
  804. package/templates/release-notes/evals/user-facing-only/case.yaml +4 -0
  805. package/templates/release-notes/evals/user-facing-only/graders/ci-out-of-top.md +14 -0
  806. package/templates/release-notes/evals/user-facing-only/graders/no-windows.md +8 -0
  807. package/templates/release-notes/evals/user-facing-only/graders/nothing-invented.md +13 -0
  808. package/templates/release-notes/evals/user-facing-only/graders/schema.md +5 -0
  809. package/templates/release-notes/evals/user-facing-only/prompt.md +113 -0
  810. package/templates/release-notes/notes.schema.json +145 -0
  811. package/templates/release-notes/rules/STYLE.md +47 -0
  812. package/templates/release-notes/skills/release-notes/SKILL.md +311 -0
  813. package/dist/console/assets/index-34jfpIbQ.js +0 -481
  814. package/dist/console/assets/index-DUHbWcIP.css +0 -1
  815. package/dist/trigger-secrets.d.ts +0 -32
  816. package/dist/trigger-secrets.js +0 -143
package/dist/cap.js CHANGED
@@ -1,22 +1,28 @@
1
1
  // A run's spend cap (`max_cost_usd`), held in the run's own process, where its model requests are sent. Before each
2
- // request, what the run has spent plus the request's worst case must stay within the cap. The worst case is the request's
3
- // input bound (inputBound: one token per UTF-8 byte of what is sent, plus what the provider adds server-side) at the
4
- // higher of the model's input and cache-write prices, plus the output it is sent with at the output price, plus any fee
5
- // its tokens do not show (pi's own search request's). Each request is limited to the output what is left of the cap can
6
- // buy (thinking included, never more than it asks for), and held at that: the limit is the wire's (pi's options, the
7
- // model proxy's body for claude-agent and codex), so the cap stays exact. Only when what is left cannot buy its least (1,024
8
- // tokens for the answer, and its thinking's least, leastOutput) is it not sent, and the run's turn ends on a model error
9
- // the server reads as `spend_cap_reached`, saying in plain words what was spent and what the request needs. A model serve has
10
- // no price for cannot be kept within a cap, so under one its requests are refused; a model listed at $0 is a known $0. What the run has
11
- // spent is read back from its store when the process starts, so it survives a restart, plus each response since; a
12
- // request in flight holds its worst case until it answers. A request the person stopped before its end counts at its input,
13
- // what it streamed (one token a byte) and STOP_ALLOWANCE_TOKENS of output the provider may have produced after the last
14
- // word read, never more than its worst case: a cut stream's own usage is not what it charged, and its worst case, once
15
- // the request is limited to what is left, is the rest of the cap. One that ended on an error after its response began
16
- // counts at its worst case. The figure is written on the request's end mark (request-start.ts), so a later process
17
- // counts it the same. Nor can a spend no one
18
- // knows (a request a crash cut, a cost that is not a number) or a model whose output is priced and that has no output
19
- // ceiling be kept within a cap: under one, each refuses the request, never passes as $0.
2
+ // request, what the run has spent, plus what its requests in flight are held at, plus what the request is expected to
3
+ // cost at its least output, must stay within the cap. Its input bound is inputBound: one token per UTF-8 byte of what is
4
+ // sent, plus what the provider adds server-side. How that input is priced is the cap's mode (`cap_mode`, CapMode):
5
+ // "expected", the default, prices it from the previous request in the same conversation (requestPrice, the one rule both
6
+ // paths call): the input that request reported read from or written to the cache, at the cache-read price, when it ended
7
+ // less than CACHE_WARM_MS ago (Anthropic keeps a cache 5 minutes), and the rest (its input after the cache, and what the
8
+ // body grew by since it) at the dearer of the input and cache-write prices; with no such request, every input token at
9
+ // that dearer price. "strict" prices every input token so: the worst case, which no request can pass. Each request is
10
+ // limited to the output what is left of the cap can buy at that input price (thinking included, never more than it asks
11
+ // for), and held at that: the limit is the wire's (pi's options, the model proxy's body for claude-agent and codex), so
12
+ // output never passes the cap. Only a cache miss can, by at most the request's bound (its input uncached less its input
13
+ // expected, 0 under strict), and its real cost is booked, never clipped; the run's timeline says so (runs.ts
14
+ // withOverCap), and the bound of a request in flight is served on the run's cost. Only when what is left cannot buy its
15
+ // least (1,024 tokens for the answer, and its thinking's least, leastOutput) is it not sent, and the run's turn ends on a
16
+ // model error the server reads as `spend_cap_reached`, saying in plain words what was spent and what the request needs. A
17
+ // model serve has no price for cannot be kept within a cap, so under one its requests are refused; a model listed at $0 is
18
+ // a known $0. What the run has spent is read back from its store when the process starts, so it survives a restart, plus
19
+ // each response since; a request in flight holds what it was admitted at until it answers. A request the person stopped
20
+ // before its end counts at its input, what it streamed (one token a byte) and STOP_ALLOWANCE_TOKENS of output the
21
+ // provider may have produced after the last word read, never more than its hold. One that ended on an error after its
22
+ // response began counts at its hold. The figure is written on the request's end mark (request-start.ts), so a later
23
+ // process counts it the same. Nor can a spend no one knows (a request a crash cut, a cost that is not a number) or a model
24
+ // whose output is priced and that has no output ceiling be kept within a cap: under one, each refuses the request, never
25
+ // passes as $0.
20
26
  // A request carrying a native web search tool reads pages into its input that its body does not hold: on claude-agent
21
27
  // its bound is its body's plus a stated allowance (NATIVE_SEARCH_ALLOWANCE_TOKENS, which its adapter adds, adapters.ts),
22
28
  // and pi's own search request is held at its context plus HOSTED_SEARCH_ALLOWANCE_TOKENS and its most fee; what it
@@ -32,11 +38,19 @@
32
38
  // fits the cap, and whenever the spend is unknown; paid calls go one at a time, so each check sees the charge before
33
39
  // it. A call sent holds its figure until its charge joins the spend (paidHolds), so a model request judged meanwhile, on
34
40
  // pi or on another harness, counts it beside the spend, as a paid call's check counts the model requests in flight.
35
- import { DatabaseSync } from "node:sqlite";
41
+ //
42
+ // A workflow run (app.ts) is capped by the same checks: its model nodes' requests and its `llm` calls through capModels,
43
+ // its paid tools through paidCall, and its decisions through holdPaid (decision-cap.ts). Where an agentic run's turn ends
44
+ // on a refusal for room and waits for a raise without its process, a workflow's refused step waits where it stands
45
+ // (RunSpend.wait, budget.ts): a model node's request before it is sent, a call node's call and a decision before they are
46
+ // admitted again. A refusal inside a call node's effect is told to the call (capRefusals), never only to the model.
47
+ import { readRunDbSync } from "./run-db.js";
48
+ import { durableDecisions } from "@parcha/agentrun-pi/durable";
49
+ import { AsyncLocalStorage } from "node:async_hooks";
36
50
  import { existsSync } from "node:fs";
37
51
  import { providerInputOverhead } from "@parcha/agentrun-kernel/host";
38
52
  import { bookRequest, isConnectCode, isGatewayTimeout, rejectionCode } from "@parcha/agentrun-kernel";
39
- import { REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, timelineOf, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
53
+ import { CAP_WRAPUP, REQUEST_CONTINUED, REQUEST_COST, REQUEST_COST_LATE, REQUEST_ENDED, REQUEST_REFUSED, REQUEST_STARTED, timelineOf, TOOL_COST, TOOL_STARTED } from "@parcha/pi-durable-agent/timeline";
40
54
  /** A run's cap in USD, passed to its process. */
41
55
  export const CAP_ENV = "AGENTRUN_SERVE_MAX_COST_USD";
42
56
  /** How a request the cap refused begins its error, which the server ends the run with. */
@@ -48,9 +62,111 @@ export const CAP_TOLERANCE = 1e-9;
48
62
  * against a 0.31 cap), never a spend that is past the cap, by however little (a 1e-11 hair is past it). CAP_TOLERANCE
49
63
  * is the other question: how near two caps are the same cap. */
50
64
  export const FIT_TOLERANCE = 1e-12;
51
- /** The option a request's worst case rides on from the cap to its marks (request-start.ts): what the cap held for it. A
52
- * symbol, so no provider ever sends it. */
65
+ /** The option a request's hold rides on from the cap to its marks (request-start.ts): what the cap held for it, its
66
+ * expected cost (its worst case under strict). A symbol, so no provider ever sends it. */
53
67
  export const HELD_USD = Symbol.for("agentrun.serve.held_usd");
68
+ /** The option a request's bound rides on to its start mark (request-start.ts, as BOUND_FIELD): the most a cache miss can
69
+ * make it cost beyond its hold (its input uncached less its input expected; 0 under strict). A symbol, as HELD_USD. */
70
+ export const BOUND_USD = Symbol.for("agentrun.serve.bound_usd");
71
+ /** The field of a request's start mark that keeps its bound (BOUND_USD), on pi and on another harness (harness-app.ts):
72
+ * the run's cost serves it while the request is in flight, and the over-cap row names it (runs.ts). Absent for 0. */
73
+ export const BOUND_FIELD = "boundUsd";
74
+ /** How a run's cap prices a request's input (`cap_mode`): "expected" (the default) from the previous request's cache, so
75
+ * only a cache miss can pass the cap, by at most the request's bound; "strict" every input token uncached, the worst
76
+ * case, so no request can pass it. */
77
+ export const CAP_MODES = ["expected", "strict"];
78
+ /** A run's cap mode, passed to its process; absent is "expected". */
79
+ export const CAP_MODE_ENV = "AGENTRUN_SERVE_CAP_MODE";
80
+ /** The run's cap mode from its process's environment. */
81
+ export function capModeOf(env) {
82
+ const text = env[CAP_MODE_ENV];
83
+ if (text === undefined || text === "")
84
+ return "expected";
85
+ if (!CAP_MODES.includes(text))
86
+ throw new Error(`${CAP_MODE_ENV} is ${text}, not one of ${CAP_MODES.join(", ")}`);
87
+ return text;
88
+ }
89
+ /** How long after a request ended the next one in its conversation is expected to read its cache: 4 minutes, inside
90
+ * Anthropic's 5 (a cache kept that long from its last use; OpenAI's lasts longer). A request later than that is priced
91
+ * with nothing cached. */
92
+ export const CACHE_WARM_MS = 4 * 60_000;
93
+ const tokenCount = (value) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined);
94
+ /** A request's Previous from the usage it reported (pi's shape: `input` without the cache's reads and writes), its input
95
+ * bound and when it ended; undefined when its usage says no input (a usage not read is zeros, never a count) or a
96
+ * figure is not a count. */
97
+ export function previousOf(usage, boundTokens, endedAt) {
98
+ const [input, read, write, bound] = [tokenCount(usage?.input), tokenCount(usage?.cacheRead ?? 0), tokenCount(usage?.cacheWrite ?? 0), tokenCount(boundTokens)];
99
+ if (input === undefined || read === undefined || write === undefined || bound === undefined || !(input + read + write > 0) || !Number.isFinite(endedAt))
100
+ return undefined;
101
+ return { cachedTokens: read + write, inputTokens: input, boundTokens: bound, endedAt };
102
+ }
103
+ /** The input of a request of `bound` tokens (inputBound) expected after `previous`, at `now`: the previous request's
104
+ * cached input read from the cache, and its input after the cache plus what the body grew by since it (in the bound's
105
+ * own unit, bytes, which a token never is fewer of) at full price. Undefined, the whole input uncached, with no previous
106
+ * request, one that ended CACHE_WARM_MS or more ago, or a clock that reads before its end. On a cache hit of a
107
+ * conversation that grew, what the request is billed for is within this; a miss costs at most its input uncached. */
108
+ export function expectedInput(bound, previous, now) {
109
+ if (!previous)
110
+ return undefined;
111
+ const gap = now - previous.endedAt;
112
+ if (!(gap >= 0 && gap < CACHE_WARM_MS))
113
+ return undefined;
114
+ return { cached: previous.cachedTokens, fresh: previous.inputTokens + Math.max(0, bound - previous.boundTokens) };
115
+ }
116
+ /** The wrap-up's trigger (wrapUpDue): what is left of a cap under this many times a priced request's typical cost. */
117
+ export const WRAP_UP_FACTOR = 3;
118
+ /** The wrap-up's other trigger: what is left under this many times the next request's least admission (its least output
119
+ * at its price: what the cap refuses it below), room for about one more request, so a run whose requests need far more
120
+ * than they cost (a reasoning model's least, Codex's at "high") is told before the cap refuses it. */
121
+ export const WRAP_UP_LEAST_FACTOR = 2;
122
+ /** The output a request is counted at as the wrap-up's typical cost while nothing is priced (step 0): its input bound and
123
+ * this many output tokens at the model's price, never its whole output allowance (the hold), which no turn uses and which
124
+ * made every cap under about $3 on Sonnet 4.5 hear the wrap-up before the run had done anything. The lead's ruling (d),
125
+ * 2026-11-07 (Manuel's retest: every $1 run told at its start). Admission's hold and bound are unchanged. */
126
+ export const WRAP_UP_STEP0_ANSWER_TOKENS = 4_096;
127
+ /** A priced request's typical cost, for the wrap-up's trigger: the median of `costs` (the run's own model's requests, a
128
+ * cost known and above 0) after the first, which writes the cache and costs several warm ones; with one priced request,
129
+ * that one; with none, `nextExpected`, the next request's expected cost (what admission holds it at). No wait for a
130
+ * count of requests: a small cap may never reach one, and that run needs the wrap-up most. */
131
+ export function typicalCost(costs, nextExpected) {
132
+ const priced = costs.filter((usd) => typeof usd === "number" && Number.isFinite(usd) && usd > 0);
133
+ if (priced.length === 0)
134
+ return nextExpected;
135
+ if (priced.length === 1)
136
+ return priced[0];
137
+ const warm = priced.slice(1).sort((a, b) => a - b);
138
+ const mid = Math.floor(warm.length / 2);
139
+ return warm.length % 2 ? warm[mid] : (warm[mid - 1] + warm[mid]) / 2;
140
+ }
141
+ /** Whether a run near its cap is due its wrap-up: what is left (`cap` less `spent` and `held`, as admission counts it)
142
+ * is under WRAP_UP_FACTOR times `typical`, or under WRAP_UP_LEAST_FACTOR times `leastUsd`, the next request's least
143
+ * admission as the cap prices it (CapGuard.leastUsd, Judged.least), when known. The same rule under strict. */
144
+ export function wrapUpDue(cap, spent, held, typical, leastUsd) {
145
+ const leftUsd = cap - spent - held;
146
+ if (!Number.isFinite(leftUsd))
147
+ return undefined;
148
+ const byTypical = Number.isFinite(typical) && leftUsd < WRAP_UP_FACTOR * typical;
149
+ const byLeast = leastUsd !== undefined && Number.isFinite(leastUsd) && leftUsd < WRAP_UP_LEAST_FACTOR * leastUsd;
150
+ return byTypical || byLeast ? { leftUsd } : undefined;
151
+ }
152
+ /** The wrap-up's words, what is left to the cent. `nonePriced`: the run's own model has no priced request yet, so its
153
+ * typical cost is the next request's expected cost and the note can come before the run has done anything (step 0):
154
+ * the words say the budget and ask for a short answer, not a finish. Read from the same priced costs live and in a
155
+ * process opened again (costsIn, ownCosts), so a restart picks the same words. */
156
+ export const wrapUpWords = (leftUsd, nonePriced = false) => {
157
+ const left = centsMoney(Math.max(0, leftUsd));
158
+ return nonePriced ? `This run's budget is about ${left}, enough for little work: answer as soon as you can.` : `About ${left} left of this run's budget: finish now with your answer.`;
159
+ };
160
+ /** A request priced at `price` under `mode`, its input `bound` tokens after `previous` at `now`, plus `feeUsd`: `cost`, what
161
+ * it is held at given its output tokens (its expected input, never more than uncached), and `worst`, its input uncached.
162
+ * The one rule pi's guard (capModels) and another harness's (capBefore) call. */
163
+ export function requestPrice(price, bound, previous, now, mode, feeUsd = 0) {
164
+ const worst = (output) => price({ cached: 0, fresh: bound }, output) + feeUsd;
165
+ const parts = mode === "strict" ? undefined : expectedInput(bound, previous, now);
166
+ if (!parts)
167
+ return { cost: worst, worst };
168
+ return { cost: (output) => Math.min(price(parts, output) + feeUsd, worst(output)), worst };
169
+ }
54
170
  /** pi's messages for requests that ended on an error after their response had begun (an event came in first), as the
55
171
  * marks (request-start.ts) saw them: each left and the provider may have billed what it generated, so it counts at its
56
172
  * hold, as one stopped does. An error before any event (refused at the HTTP level: a 429, a 5xx) counts at its own
@@ -225,7 +341,7 @@ const notSentHere = (entry) => {
225
341
  /** The cost an entry adds to what a run spent, as the timeline counts it: a pi answer's total (none for one stopped
226
342
  * before its end), and the usd of a cost written apart from an answer, a paid tool's charge among them; 0 for anything
227
343
  * else, or for a cost that is not a number (which makes the whole spend unknown, by the timeline's verdict). */
228
- const costOf = (entry) => {
344
+ export const costOf = (entry) => {
229
345
  const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
230
346
  const cost = message ? (message.stopReason === "aborted" ? undefined : message.usage?.cost?.total)
231
347
  : entry.kind === REQUEST_COST || entry.kind === REQUEST_COST_LATE || entry.kind === TOOL_COST ? entry.data?.usd : undefined;
@@ -292,28 +408,33 @@ function openFigures(entries) {
292
408
  * end mark holds (HELD_FIELD), and one a crash cut (marked as sent, no answer, no end) at the figure its start mark
293
409
  * holds (openFigures), each the worst case the cap held for it; without that figure either stays cut, at an unknown
294
410
  * cost. A paid call settled at a charge it did not say, like one a crash cut, counts at the figure its mark holds. And
295
- * this cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0. `sides`: only the
296
- * run's side requests (each marked with a label: a learned workflow's, a hosted search's), what a run on another
297
- * harness spent beside its harness's own requests and its paid tools, which that harness's booking does not hold. */
298
- export function spentIn(storeFile, { sides = false } = {}) {
411
+ * this cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0. */
412
+ export function spentIn(storeFile) {
299
413
  if (!existsSync(storeFile))
300
414
  return 0;
301
- const db = new DatabaseSync(storeFile, { readOnly: true });
302
- const entries = [];
303
- // The store's own entries, as read (without the answers written below for a stopped request): openFigures reads them.
304
- const read = [];
305
- let marked = false;
415
+ // Fresh, read-only and lock-free (run-db.ts): its process may hold it.
306
416
  const rows = [];
307
- try {
417
+ readRunDbSync(storeFile, false, (db) => {
418
+ // A read made again (its file changed during it) starts from none.
419
+ rows.length = 0;
308
420
  for (const row of db.prepare("SELECT record FROM entries ORDER BY rowid").iterate()) {
309
421
  const entry = JSON.parse(String(row.record));
310
- if (!sides || ([REQUEST_STARTED, REQUEST_ENDED, REQUEST_COST, REQUEST_COST_LATE].includes(entry.kind) && typeof entry.data?.request === "string"))
311
- rows.push(entry);
422
+ rows.push(entry);
312
423
  }
313
- }
314
- finally {
315
- db.close();
316
- }
424
+ });
425
+ return spentFrom(rows);
426
+ }
427
+ /** What the run's model requests cost, from its entries in log order: the one computation, shared by spentIn (reading a
428
+ * settled run's own database) and the one-store reader (store-reads, reading A's journal). These readings are the cap's
429
+ * own, on its copy of the entries (the run's shown cost is the timeline's, unchanged): a request stopped before its end
430
+ * counts at the figure its end mark holds (HELD_FIELD), and one a crash cut (marked as sent, no answer, no end) at the
431
+ * figure its start mark holds (openFigures), each the worst case the cap held for it; without that figure either stays
432
+ * cut, at an unknown cost. This cap's refusals are left out, as none left. Unknown is null, which a cap never reads as $0. */
433
+ export function spentFrom(rows) {
434
+ // The store's own entries, as read (without the answers written below for a stopped request): openFigures reads them.
435
+ const entries = [];
436
+ const read = [];
437
+ let marked = false;
317
438
  // pi's error entry for a request that ended on an error after its response began is left out, as an aborted one is: its
318
439
  // end mark (`error`) counts it at its hold. pi writes the entry as the mark is written, before it or after, so each such
319
440
  // mark takes the nearest error entry not yet taken among those after the earliest start holding its figure (a request's
@@ -441,6 +562,108 @@ export function spentIn(storeFile, { sides = false } = {}) {
441
562
  return null;
442
563
  return entries.reduce((sum, entry) => sum + costOf(entry), 0);
443
564
  }
565
+ /** A workflow decision's charge as the cap counted it (decision-cap.ts): `call` names the request, `usd` what it charged,
566
+ * or its hold when it said none. The run's shown cost reads its decisions from their receipts; this is the cap's own
567
+ * reading, kept so a later process counts each decision as this one did. costOf counts none, so nothing counts twice. */
568
+ export const DECISION_COST = "agentrun.decision_cost";
569
+ /** A decision request's hold, kept before it is sent (decision-cap.ts): with no DECISION_COST after it, its process died
570
+ * while it was out, and it counts at this figure. */
571
+ export const DECISION_HOLD = "agentrun.decision_hold";
572
+ /** What a workflow run's decisions cost, in its store: what the next process adds to spentIn's reading. Per decision
573
+ * (its id):
574
+ * - booked (DECISION_COST entries, at its charge, its hold, or $0 for nothing charged): the larger of what was booked,
575
+ * with any hold no booking ended, and what its receipts say it cost (the costs the timeline's decision rows sum);
576
+ * - else, with a receipt that names its charge: that charge (its booking lost after the receipt);
577
+ * - else, with a hold (DECISION_HOLD, kept once the driver admitted the request, right before its send): that hold, the
578
+ * figure the live process held, since the request may have been out when its process died; never $0;
579
+ * - else nothing: no hold is kept before the admission, so a request never sent is never counted.
580
+ * A booking with no decision id is counted as it is. */
581
+ export function decisionSpentIn(storeFile) {
582
+ const booked = new Map();
583
+ /** The decisions with any booking, a $0 one included. */
584
+ const ended = new Set();
585
+ /** Each decision's holds kept and not yet followed by a booking, in order. */
586
+ const open = new Map();
587
+ let loose = 0;
588
+ for (const entry of entriesIn(storeFile)) {
589
+ if (entry.kind !== DECISION_COST && entry.kind !== DECISION_HOLD)
590
+ continue;
591
+ const data = entry.data;
592
+ const usd = figureOf(data?.usd);
593
+ const id = typeof data?.decision === "string" ? data.decision : undefined;
594
+ if (entry.kind === DECISION_HOLD) {
595
+ if (id !== undefined && usd !== undefined)
596
+ open.set(id, [...(open.get(id) ?? []), usd]);
597
+ continue;
598
+ }
599
+ // A booking ends its decision's oldest hold still open, whatever it charged ($0 for nothing sent).
600
+ if (id !== undefined) {
601
+ ended.add(id);
602
+ open.get(id)?.shift();
603
+ }
604
+ if (usd === undefined || !(usd > 0))
605
+ continue;
606
+ if (id !== undefined)
607
+ booked.set(id, (booked.get(id) ?? 0) + usd);
608
+ else
609
+ loose += usd;
610
+ }
611
+ const receipted = new Map();
612
+ let receipts = [];
613
+ // Receipts that cannot be read leave the bookings alone to say it.
614
+ if (existsSync(storeFile))
615
+ try {
616
+ receipts = durableDecisions(storeFile, { unlocked: true });
617
+ }
618
+ catch {
619
+ receipts = [];
620
+ }
621
+ for (const receipt of receipts) {
622
+ const usd = figureOf(receipt.cost_usd);
623
+ // A stored receipt row names its decision `decision_id` (agentrun-pi decision-recovery.ts rowOf).
624
+ const id = typeof receipt.decision_id === "string" ? receipt.decision_id : typeof receipt.id === "string" ? receipt.id : undefined;
625
+ if (id !== undefined && usd !== undefined && usd > 0)
626
+ receipted.set(id, (receipted.get(id) ?? 0) + usd);
627
+ }
628
+ let sum = loose;
629
+ for (const id of new Set([...ended, ...booked.keys(), ...receipted.keys(), ...open.keys()])) {
630
+ const held = (open.get(id) ?? []).reduce((total, usd) => total + (usd > 0 ? usd : 0), 0);
631
+ if (ended.has(id))
632
+ sum += Math.max((booked.get(id) ?? 0) + held, receipted.get(id) ?? 0);
633
+ else if (receipted.has(id))
634
+ sum += receipted.get(id);
635
+ else
636
+ sum += held;
637
+ }
638
+ return sum;
639
+ }
640
+ /** The entries of the run's store, in order (none when it has no store yet). */
641
+ function entriesIn(storeFile) {
642
+ if (!existsSync(storeFile))
643
+ return [];
644
+ // Fresh, read-only and lock-free (run-db.ts), as spentIn reads it.
645
+ const rows = [];
646
+ readRunDbSync(storeFile, false, (db) => {
647
+ rows.length = 0;
648
+ for (const row of db.prepare("SELECT record FROM entries ORDER BY rowid").iterate())
649
+ rows.push(JSON.parse(String(row.record)));
650
+ });
651
+ return rows;
652
+ }
653
+ /** The priced answers of `model` (its id) in the run's store, in order: what the wrap-up's typical cost reads from earlier
654
+ * processes (capModels' `wrapUp`). An answer whose cost is unknown or $0, or that was stopped or failed, is none. */
655
+ export function costsIn(storeFile, model) {
656
+ return entriesIn(storeFile).flatMap((entry) => {
657
+ const message = entry.kind === "pi.assistant" ? entry.model?.[0] : undefined;
658
+ const total = message?.usage?.cost?.total;
659
+ return message?.model === model && message.stopReason !== "error" && message.stopReason !== "aborted" && typeof total === "number" && Number.isFinite(total) && total > 0 ? [total] : [];
660
+ });
661
+ }
662
+ /** Whether the run was told its wrap-up under `cap` already (a CAP_WRAPUP entry of that cap): once per cap, across its
663
+ * processes; a raise's new cap re-arms it. */
664
+ export function wrapUpSentIn(storeFile, cap) {
665
+ return entriesIn(storeFile).some((entry) => entry.kind === CAP_WRAPUP && typeof entry.data?.capUsd === "number" && Math.abs(entry.data.capUsd - cap) <= CAP_TOLERANCE);
666
+ }
444
667
  export function metersIn(storeFile) {
445
668
  const { known: _, ...meters } = meterFiguresIn(storeFile);
446
669
  return meters;
@@ -451,42 +674,44 @@ export function metersIn(storeFile) {
451
674
  export function meterFiguresIn(storeFile) {
452
675
  if (!existsSync(storeFile))
453
676
  return { tools: 0, tokens: null, browser: { usd: 0, seconds: 0 }, others: 0, known: { tokens: 0, browser: 0, others: 0 } };
454
- const db = new DatabaseSync(storeFile, { readOnly: true, timeout: 2_000 });
455
- try {
456
- const rows = db.prepare("SELECT conversation_id AS conversation, record FROM entries ORDER BY rowid").all().map((row) => ({ conversation: Number(row.conversation), entry: JSON.parse(String(row.record)) }));
457
- const root = rows.reduce((min, row) => Math.min(min, row.conversation), Infinity);
458
- const marks = new Set();
459
- const charges = [];
460
- const browser = { usd: 0, seconds: 0 };
461
- const others = [];
462
- // Each meter's known dollars, whether or not one of its charges is unknown: what a run of unknown cost is known to
463
- // have spent on it (server.ts /usage).
464
- const known = { tokens: 0, browser: 0, others: 0 };
465
- for (const { entry } of rows) {
466
- const data = (entry.data ?? {});
467
- if (entry.kind === TOOL_STARTED)
468
- marks.add(data.call);
469
- else if (entry.kind === TOOL_COST)
470
- marks.delete(data.call), charges.push(figureOf(data.usd));
471
- if (entry.kind === TOOL_COST && data.tool !== "browser")
472
- others.push(figureOf(data.usd)), (known.others += figureOf(data.usd) ?? 0);
473
- if (entry.kind !== TOOL_COST || data.tool !== "browser")
474
- continue;
475
- const usd = figureOf(data.usd);
476
- known.browser += usd ?? 0;
477
- browser.usd = browser.usd === null || usd === undefined ? null : browser.usd + usd;
478
- browser.seconds += figureOf(data.seconds) ?? 0;
479
- }
480
- const tools = marks.size || charges.some((usd) => usd === undefined) ? null : charges.reduce((sum, usd) => sum + usd, 0);
481
- const rest = rows.filter(({ conversation, entry }) => conversation === root && entry.kind !== TOOL_STARTED && entry.kind !== TOOL_COST).map(({ entry }) => entry);
482
- const usage = timelineOf(rest, { settled: true }).find((row) => row.kind === "usage");
483
- const otherTools = marks.size || others.some((usd) => usd === undefined) ? null : others.reduce((sum, usd) => sum + usd, 0);
484
- known.tokens = usage ? (usage.usage?.usd ?? usage.usage?.so_far_usd ?? 0) : 0;
485
- return { tools, tokens: usage ? (usage.usage?.usd ?? null) : 0, browser, others: otherTools, known };
486
- }
487
- finally {
488
- db.close();
677
+ return readRunDbSync(storeFile, false, (db) => meterFiguresFrom(db.prepare("SELECT conversation_id AS conversation, record FROM entries ORDER BY rowid").all().map((row) => ({ conversation: Number(row.conversation), entry: JSON.parse(String(row.record)) }))));
678
+ }
679
+ /** meterFiguresIn's figures from a run's entries by conversation, in log order: the one computation, shared by
680
+ * meterFiguresIn (reading a settled run's own database) and the one-store reader (store-reads/cap.ts metersOverStore, over
681
+ * A's journal). Only where the entries come from changes; the figures do not (the money-parity rule), as spentFrom is to
682
+ * spentIn. A paid tool's charge reaches it as the TOOL_COST / TOOL_UNMETERED the store reader folds back in from the
683
+ * paid-tools session (store-reads/journal.ts withPaidCosts), as the file-backed run's root held each natively. */
684
+ export function meterFiguresFrom(rows) {
685
+ const root = rows.reduce((min, row) => Math.min(min, row.conversation), Infinity);
686
+ const marks = new Set();
687
+ const charges = [];
688
+ const browser = { usd: 0, seconds: 0 };
689
+ const others = [];
690
+ // Each meter's known dollars, whether or not one of its charges is unknown: what a run of unknown cost is known to
691
+ // have spent on it (server.ts /usage).
692
+ const known = { tokens: 0, browser: 0, others: 0 };
693
+ for (const { entry } of rows) {
694
+ const data = (entry.data ?? {});
695
+ if (entry.kind === TOOL_STARTED)
696
+ marks.add(data.call);
697
+ else if (entry.kind === TOOL_COST)
698
+ marks.delete(data.call), charges.push(figureOf(data.usd));
699
+ if (entry.kind === TOOL_COST && data.tool !== "browser")
700
+ others.push(figureOf(data.usd)), (known.others += figureOf(data.usd) ?? 0);
701
+ if (entry.kind !== TOOL_COST || data.tool !== "browser")
702
+ continue;
703
+ const usd = figureOf(data.usd);
704
+ known.browser += usd ?? 0;
705
+ browser.usd = browser.usd === null || usd === undefined ? null : browser.usd + usd;
706
+ browser.seconds += figureOf(data.seconds) ?? 0;
489
707
  }
708
+ const tools = marks.size || charges.some((usd) => usd === undefined) ? null : charges.reduce((sum, usd) => sum + usd, 0);
709
+ const rest = rows.filter(({ conversation, entry }) => conversation === root && entry.kind !== TOOL_STARTED && entry.kind !== TOOL_COST).map(({ entry }) => entry);
710
+ const usage = timelineOf(rest, { settled: true }).find((row) => row.kind === "usage");
711
+ const otherTools = marks.size || others.some((usd) => usd === undefined) ? null : others.reduce((sum, usd) => sum + usd, 0);
712
+ known.tokens = usage ? (usage.usage?.usd ?? usage.usage?.so_far_usd ?? 0) : 0;
713
+ const notMetered = usage?.usage?.not_metered;
714
+ return { tools, tokens: usage ? (usage.usage?.usd ?? null) : 0, browser, others: otherTools, known, ...(notMetered ? { notMetered } : {}) };
490
715
  }
491
716
  /** What the paid tools of `entries` (TOOL_STARTED and TOOL_COST) spent, as the cap counts it: each charge, and a call
492
717
  * settled at a charge it did not say, or a crash cut (marked, never settled), at its held figure, as spentIn counts it;
@@ -518,20 +743,23 @@ export function holdsInFlight() {
518
743
  total: () => [...holds.values()].reduce((sum, usd) => sum + usd, 0),
519
744
  };
520
745
  }
746
+ /** Where a refusal of the cap inside a workflow call node's effect is told (app.ts runEffect): the call ends on it and
747
+ * waits for a raise, never handed back as the tool's own failure, which a collecting map would take as the item's. A
748
+ * paid call refused there leaves no refusal for a model's next request (takePaidRefusal): no model turn follows it. */
749
+ export const capRefusals = new AsyncLocalStorage();
521
750
  let runSpend;
522
751
  let paying = Promise.resolve();
752
+ /** The run's spend this process counts, when it has a cap: for a workflow run's waits and decisions (app.ts). */
753
+ export const runSpendNow = () => runSpend;
523
754
  export const useSpend = (spend) => {
524
755
  runSpend = spend;
525
756
  // A paid call's refusal is its own spend's (its run's): another spend starts with none.
526
757
  paidRoomRefusal = undefined;
527
758
  };
528
- /** Each paid call sent under the cap and not settled, at what it is held at; on another harness, each of the run's own
529
- * model requests in flight too (capModels' `joined`). */
759
+ /** Each paid call sent under the cap and not settled, at what it is held at. */
530
760
  const paidOpen = new Set();
531
761
  /** What the paid calls under way are held at, together (0 when none is): the one figure every check of the run's cap
532
- * adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall). On another
533
- * harness the run's own model requests in flight (a learned workflow's, a hosted search's) are held here too, so the
534
- * harness's check sees them. */
762
+ * adds to what the run has spent, a model request's (capModels, capBefore) and a paid call's (paidCall). */
535
763
  export const paidHolds = () => [...paidOpen].reduce((sum, { usd }) => sum + usd, 0);
536
764
  /** A paid hold that outlives the paidCall that took it (a browser session's, browser-cost.ts), counted in paidHolds as a
537
765
  * call's is until `drop`: its figure is `usd`, which its owner moves as charges use it. */
@@ -545,11 +773,6 @@ export const keepHold = (usd) => {
545
773
  export const addSpend = (usd) => runSpend?.add(usd);
546
774
  /** The run's cap, when it has one. */
547
775
  export const runCap = () => runSpend?.cap;
548
- /** On another harness, what the run's own model requests (capModels' `joined`) have cost: those of earlier processes
549
- * (spentIn's `sides`) and this one's; null once one is unknown. 0 on pi, where the run's one capModels counts them. */
550
- let sidesSpent = 0;
551
- /** What sidesSpent says: the harness's check adds it to what its booking says the run spent (harness-app.ts). */
552
- export const sideSpend = () => sidesSpent;
553
776
  /** `call`, a paid tool's (`name`), under the run's cap, by the rule a model request keeps: refused, in words that name
554
777
  * its price and the cap and never calling it, unless what the run has spent plus what the call is held at (`hold`: its
555
778
  * quote, else an allowance, `basis` saying which) fits the cap, and whenever the spend is unknown; else run, one paid
@@ -572,22 +795,34 @@ export function takePaidRefusal(owner) {
572
795
  paidRoomRefusal = undefined;
573
796
  return { words: refusal.words, figures: refusal.figures };
574
797
  }
575
- export async function paidCall(name, call, charge, hold) {
798
+ export async function paidCall(name, call, charge, hold, options = {}) {
576
799
  const spend = runSpend;
577
800
  if (!spend)
578
801
  return { result: await call() };
579
802
  const turn = paying.then(async () => {
580
803
  const read = await spend.spent();
581
- if (read === null)
582
- return { refused: `${SPEND_CAP_REACHED}: ${name} was not sent. What the run has spent is unknown, so its cap of ${money(spend.cap)} cannot be kept: the run is out of budget.` };
804
+ if (read === null) {
805
+ const text = `${SPEND_CAP_REACHED}: ${name} was not sent. What the run has spent is unknown, so its cap of ${money(spend.cap)} cannot be kept: the run is out of budget.`;
806
+ capRefusals.getStore()?.({ words: text.slice(`${SPEND_CAP_REACHED}: `.length), room: false, capUsd: spend.cap });
807
+ return { refused: text };
808
+ }
583
809
  // What is held for requests and calls still answering, apart from what was spent, as a model request's refusal says it.
584
810
  const holding = (spend.held?.() ?? 0) + paidHolds();
585
811
  // Written so that a figure that is not a number refuses.
586
812
  if (!(read + holding + hold.usd <= spend.cap + FIT_TOLERANCE)) {
587
- // Refused for room: a raise would send it, so the run pauses at the model's next request (takePaidRefusal).
588
- const refused = paidRefusal(spend.cap, read, holding, name, hold);
589
- paidRoomRefusal = { owner: spend, words: refused.slice(`${SPEND_CAP_REACHED}: `.length), figures: { spentUsd: read + holding, needsUsd: hold.usd } };
590
- return { refused };
813
+ // Refused for room: a raise would send it, so the run pauses at the model's next request (takePaidRefusal). Its
814
+ // words and the least cap that sends it (leastCapUsd) are one figure, which the pause carries to its mark and serves.
815
+ const refusal = paidRefusal(spend.cap, read, holding, name, hold);
816
+ const room = { words: refusal.text.slice(`${SPEND_CAP_REACHED}: `.length), figures: { spentUsd: read + holding, needsUsd: hold.usd, leastCapUsd: refusal.leastCapUsd } };
817
+ // `pauses: false`: no step of the run's own (a person's take-over of its browser), so neither a workflow's call nor the
818
+ // model's next request is told: the run goes on unpaused.
819
+ // Inside a workflow's call node: the call is told, and ends on it. Else the model's next request is refused in its words.
820
+ const told = options.pauses !== false ? capRefusals.getStore() : undefined;
821
+ if (told)
822
+ told({ ...room, room: true, capUsd: spend.cap });
823
+ else if (options.pauses !== false)
824
+ paidRoomRefusal = { owner: spend, ...room };
825
+ return { refused: refusal.text, leastCapUsd: refusal.leastCapUsd };
591
826
  }
592
827
  // Held from here; settled into the spend in the same step that lets the hold go, so no check between sees neither.
593
828
  const open = { usd: hold.usd };
@@ -610,6 +845,39 @@ export async function paidCall(name, call, charge, hold) {
610
845
  paying = turn.catch(() => undefined);
611
846
  return turn;
612
847
  }
848
+ export async function holdPaid(name, hold, signal) {
849
+ for (;;) {
850
+ const spend = runSpend;
851
+ if (!spend)
852
+ return { ticket: { settle: () => undefined, drop: () => undefined } };
853
+ const turn = paying.then(async () => {
854
+ const read = await spend.spent();
855
+ if (read === null)
856
+ return { refused: { words: `${name} was not sent. What the run has spent is unknown, so its cap of ${money(spend.cap)} cannot be kept: the run is out of budget.`, room: false, capUsd: spend.cap } };
857
+ const holding = (spend.held?.() ?? 0) + paidHolds();
858
+ if (!(read + holding + hold.usd <= spend.cap + FIT_TOLERANCE)) {
859
+ const refusal = paidRefusal(spend.cap, read, holding, name, hold);
860
+ return { refused: { words: refusal.text.slice(`${SPEND_CAP_REACHED}: `.length), room: true, capUsd: spend.cap, figures: { spentUsd: read + holding, needsUsd: hold.usd, leastCapUsd: refusal.leastCapUsd } } };
861
+ }
862
+ // Held from here, in the same step as the check, so no other check between sees neither.
863
+ const open = { usd: hold.usd };
864
+ paidOpen.add(open);
865
+ let done = false;
866
+ return { ticket: {
867
+ settle: (usd) => { if (done)
868
+ return; done = true; spend.add(usd ?? hold.usd); paidOpen.delete(open); },
869
+ drop: () => { if (done)
870
+ return; done = true; paidOpen.delete(open); },
871
+ } };
872
+ });
873
+ paying = turn.catch(() => undefined);
874
+ const held = await turn;
875
+ if (!("refused" in held) || !held.refused.room || !spend.wait || signal?.aborted)
876
+ return held;
877
+ if (!(await spend.wait(held.refused, signal)))
878
+ return held;
879
+ }
880
+ }
613
881
  /** The most output tokens one request may take: the model's ceiling, else its context window. A thinking budget can
614
882
  * raise a request's ceiling up to the model's, whatever maxTokens it asked for. */
615
883
  export const ceilingTokens = (model) => (model.maxTokens > 0 ? model.maxTokens : model.contextWindow);
@@ -637,11 +905,11 @@ const unmeasured = (cap) => `${SPEND_CAP_REACHED}: Not sent: the size of the nex
637
905
  const noPrice = (cap) => `${SPEND_CAP_REACHED}: Not sent: the next model request's model has no price here, so the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
638
906
  const noCeiling = (cap) => `${SPEND_CAP_REACHED}: Not sent: the next model request's model has no output ceiling here and its output is priced, so what a request may cost has no bound and the run's cap of ${money(cap)} cannot be kept: the run is out of budget.`;
639
907
  const unknownSpend = (cap) => `${SPEND_CAP_REACHED}: Not sent: what the run has spent is unknown, so its cap of ${money(cap)} cannot be kept: the run is out of budget.`;
640
- /** A request's worst case at `model`'s price: `input` tokens at the dearer of its input and cache-write prices, and
641
- * `output` tokens at its output price. */
642
- function worstOf(calculateCost, model) {
908
+ /** A request's price at `model`'s rates: its input's cached tokens at the cache-read price and its fresh ones at the
909
+ * dearer of the input and cache-write prices, and `output` tokens at the output price. */
910
+ function priceOf(calculateCost, model) {
643
911
  const priced = (tokens) => calculateCost(model, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, ...tokens, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }).total;
644
- return (input, output) => Math.max(priced({ input, output }), priced({ cacheWrite: input, output }));
912
+ return ({ cached, fresh }, output) => Math.max(priced({ input: fresh, cacheRead: cached, output }), priced({ cacheWrite: fresh, cacheRead: cached, output }));
645
913
  }
646
914
  /** An amount in words: two decimals, or as many as it takes (up to eight) to show it whole ($0.50, $0.105, $0.0005). */
647
915
  export function money(usd) {
@@ -657,44 +925,62 @@ export function money(usd) {
657
925
  * which pi-ai's retry (isRetryableAssistantError, which reads only an error's text) takes as final whatever digits the
658
926
  * words after it hold. The words after it are the ones a person reads. */
659
927
  export const CAP_REFUSAL_CODE = `${SPEND_CAP_REACHED} (out of budget): `;
928
+ /** A refusal's figures as its start mark keeps them (`spentUsd`, `needsUsd`, `leastCapUsd`, and `boundUsd` when above 0);
929
+ * none without. */
930
+ export const refusalFields = (figures) => figures ? { spentUsd: figures.spentUsd, needsUsd: figures.needsUsd, leastCapUsd: figures.leastCapUsd, ...(typeof figures.boundUsd === "number" && figures.boundUsd > 0 ? { boundUsd: figures.boundUsd } : {}) } : {};
660
931
  /** The words of a refusal for room (CAP_REFUSAL_CODE: what is left of the cap cannot buy the request's least), which a
661
932
  * higher cap would send; undefined for any other text, a refusal no cap could fix included (an unknown spend, no price,
662
933
  * no output ceiling, an input not measured: the bare `spend_cap_reached: ` code). The one reader of that difference. */
663
934
  export const roomRefusal = (text) => (text?.startsWith(CAP_REFUSAL_CODE) ? text.slice(CAP_REFUSAL_CODE.length) : undefined);
664
- /** A model's name as the words say it: the catalog's, without a vendor's prefix ("Anthropic: Claude Sonnet 5.5" reads
665
- * "Claude Sonnet 5.5"), else its id. */
666
- export const nameOf = (model) => (model.name || model.id).replace(/^[^:]{1,40}:\s+(?=\S)/, "");
667
935
  /** A least in words: rounded up to the cent, so that it is enough ($0.1024 is $0.11). */
668
936
  // Cents rounded up within the tail the fit check allows (FIT_TOLERANCE), no wider: a total past a cent by more than a
669
937
  // float's own tail rounds to the cent above, so the cap a refusal names admits what it refused.
670
938
  export const leastMoney = (usd) => `$${(Math.ceil(usd * 100 - FIT_TOLERANCE * 100) / 100).toFixed(2)}`;
671
939
  /** The cap to raise to for a request past `cap` that needs `total` in all: a cent at least, and above the cap, never
672
940
  * the cap itself, so a raise to it is one PATCH /runs/{id} takes. */
673
- export const raiseTo = (cap, total) => {
941
+ export const raiseTo = (cap, total) => `$${raiseFigure(cap, total).toFixed(2)}`;
942
+ /** raiseTo's cap as a number, whole cents in dollars: the figure a refusal carries beside its words (leastCapUsd). */
943
+ export const raiseFigure = (cap, total) => {
674
944
  const cents = Math.ceil(total * 100 - FIT_TOLERANCE * 100);
675
- return `$${((cents / 100 > cap + CAP_TOLERANCE ? cents : Math.floor((cap + CAP_TOLERANCE) * 100) + 1) / 100).toFixed(2)}`;
945
+ return (cents / 100 > cap + CAP_TOLERANCE ? cents : Math.floor((cap + CAP_TOLERANCE) * 100) + 1) / 100;
676
946
  };
677
- /** The cap's refusal of a request what is left of it cannot buy the least of, in plain words with the numbers: what
678
- * the run spent (and holds for requests still answering) of its cap, what the request needs at the least, and the cap
679
- * that would run it (spent, held and that least, rounded up to the cent, so that it is enough). After its code
680
- * (CAP_REFUSAL_CODE), which keeps it final to pi-ai's retry. */
681
- function capRefusal(cap, spent, held, name, least) {
682
- const [need, raise] = [leastMoney(least), raiseTo(cap, spent + held + least)];
947
+ /** The cap's refusal of a request what is left of it cannot buy the least of, in plain words with the numbers, as a
948
+ * person who has never seen a model request reads them: what the run spent (and holds for steps still running) of its
949
+ * cap, what the next step needs at the least, and the cap that lets it continue (spent, held and that least, rounded
950
+ * up to the cent, so that it is enough). No model's name: a run is many requests, and "the next step" is the one that
951
+ * waits. After its code (CAP_REFUSAL_CODE), which keeps it final to pi-ai's retry. Its figures beside the words. */
952
+ function capRefusal(cap, spent, held, least) {
953
+ // The raise its words name and the figure it carries are one number (leastCapUsd), so the two never drift.
954
+ const leastCapUsd = raiseFigure(cap, spent + held + least);
955
+ const figures = { spentUsd: spent + held, needsUsd: least, leastCapUsd };
956
+ const [need, raise] = [leastMoney(least), `$${leastCapUsd.toFixed(2)}`];
683
957
  if (spent === 0 && held === 0)
684
- return `${CAP_REFUSAL_CODE}Not sent: this run's cap of ${money(cap)} can't cover one ${name} request (at least ${need}). Raise the cap to at least ${raise} to run it.`;
685
- const owes = held > 0 ? `spent ${money(spent)} and holds ${money(held)} for requests still answering, of its ${money(cap)} cap` : `spent ${money(spent)} of its ${money(cap)} cap`;
686
- return `${CAP_REFUSAL_CODE}Not sent: the run has ${owes}, and its next ${name} request needs at least ${need}. Raise the cap to at least ${raise} to run it.`;
958
+ return { text: `${CAP_REFUSAL_CODE}Not sent: the next step needs at least ${need}, and this run's cap is ${money(cap)}. Raise the cap to at least ${raise} to continue.`, figures };
959
+ return { text: `${CAP_REFUSAL_CODE}Not sent: this run has ${spentOf(spent, held, cap)}, and the next step needs at least ${need}. Raise the cap to at least ${raise} to continue.`, figures };
687
960
  }
961
+ /** A guard's answer for a refusal for room: its words, and its figures beside them (harness-app.ts keeps them on its mark). */
962
+ const refuseFor = ({ text, figures }) => ({ refuse: text, ...figures });
963
+ /** capModels' judgement for a refusal for room: its words, and its figures for its start mark (request-start.ts). */
964
+ const whyOf = ({ text, figures }) => ({ why: text, figures });
965
+ /** What a run has spent of its cap, in a refusal's words: and what it holds for steps still running, when that is a cent
966
+ * or more. Each in cents (centsMoney), as the figures after it are; the exact amounts are the refusal's figures
967
+ * (RefusalFigures, the pause's spent_usd). */
968
+ const spentOf = (spent, held, cap) => {
969
+ const holds = centsMoney(held);
970
+ return holds !== "$0" ? `spent ${centsMoney(spent)} and holds ${holds} for steps still running, of its ${money(cap)} cap` : `spent ${centsMoney(spent)} of its ${money(cap)} cap`;
971
+ };
972
+ /** An amount in words, to the nearest cent ($0.0237416 is $0.02), as money says it ($1, $0.20, $0). */
973
+ export const centsMoney = (usd) => money(Math.round(usd * 100) / 100);
688
974
  /** The cap's refusal of a paid call (paidCall) what is left of it cannot hold, in one sentence, as capRefusal says a model
689
975
  * request's: what the run spent (and holds for requests and calls still answering) of its cap, what the call could cost
690
976
  * and why, and the cap that would run it: spent, held and the call's figure, rounded up to the cent, and a cent above the
691
- * cap at the least, since a figure past the cap by less than a cent still needs more than the cap. Every amount by money,
692
- * the raise by leastMoney. */
977
+ * cap at the least, since a figure past the cap by less than a cent still needs more than the cap. What was spent and held
978
+ * in cents (spentOf), the call's figure and the cap by money, the raise by raiseFigure. */
693
979
  function paidRefusal(cap, spent, held, name, hold) {
694
- const holds = held > 0 ? ` and holds ${money(held)} for calls still answering` : "";
695
- // The model refusal's rule (raiseTo): a cent at least, and above the cap, never the cap itself.
696
- const raise = raiseTo(cap, spent + held + hold.usd);
697
- return `${SPEND_CAP_REACHED}: Not sent: the run has spent ${money(spent)}${holds} of its ${money(cap)} cap, and ${name} could cost up to ${money(hold.usd)} (${hold.basis}). Raise the cap to at least ${raise} to run it.`;
980
+ // The model refusal's rule (raiseFigure): a cent at least, and above the cap, never the cap itself; one number, which its
981
+ // words name and its refusal carries. The same words: the call is the next step, named as the tool.
982
+ const leastCapUsd = raiseFigure(cap, spent + held + hold.usd);
983
+ return { text: `${SPEND_CAP_REACHED}: Not sent: this run has ${spentOf(spent, held, cap)}, and the next step, ${name}, could cost up to ${money(hold.usd)} (${hold.basis}). Raise the cap to at least $${leastCapUsd.toFixed(2)} to continue.`, leastCapUsd };
698
984
  }
699
985
  /** The most output tokens from `least` to `asked` whose request costs no more than `left` (`cost`, its price at that
700
986
  * many, rising with them); undefined when even `least` costs more. A search, so that a price with tiers is exact. */
@@ -723,17 +1009,17 @@ export function leastOutput(model, thinking, budgetOf) {
723
1009
  return ANSWER_TOKENS_LEAST;
724
1010
  return ANSWER_TOKENS_LEAST + (BUDGET_APIS.has(model.api) ? THINKING_BUDGET_LEAST : budgetOf(thinking));
725
1011
  }
726
- /** A run on another harness: before each request, what the run has spent, plus the worst case of each request still in
727
- * flight (at the output limit it was admitted with), must leave room for this request at its least output (1,024 tokens,
728
- * or what its body says it needs to think and answer; what it asks for when that is fewer), else the request is refused
729
- * with spend_cap_reached. Admitted, it is limited to the most output what is left buys (`outputTokensMax`, at most what
730
- * it asks for and its model's ceiling), which the model proxy writes into its body: what it is held at is then what the
731
- * provider can bill for it. A request's worst case is at the run model's
732
- * price, as on pi (a request on a cheaper model is held at that price too, which only refuses sooner). What cannot be
733
- * kept within a cap is refused under one: a spend that is unknown (a request a crash cut), an input that could not be
734
- * measured, a model serve has no price for (`listed: false`, or none at all), and a model whose output is priced and
735
- * that has no output ceiling. With no cap, nothing is refused. */
736
- export async function capBefore(cap, model, { listed = true } = {}) {
1012
+ /** A run on another harness: before each request, what the run has spent, plus what each request still in flight was
1013
+ * admitted at, must leave room for this request at its least output (1,024 tokens, or what its body says it needs to
1014
+ * think and answer; what it asks for when that is fewer), its input priced by requestPrice under `mode`, else the request
1015
+ * is refused with spend_cap_reached. Admitted, it is limited to the most output what is left buys (`outputTokensMax`, at
1016
+ * most what it asks for and its model's ceiling), which the model proxy writes into its body: output never passes the
1017
+ * cap. A request is priced at the run model's price, as on pi (a request on a cheaper model is held at that price too,
1018
+ * which only refuses sooner). What cannot be kept within a cap is refused under one: a spend that is unknown (a request a
1019
+ * crash cut), an input that could not be measured, a model serve has no price for (`listed: false`, or none at all),
1020
+ * and a model whose output is priced and that has no output ceiling. With no cap, nothing is refused. `now`: the clock a
1021
+ * previous request's end is read against. */
1022
+ export async function capBefore(cap, model, { listed = true, mode = "expected", now = Date.now } = {}) {
737
1023
  if (cap === undefined)
738
1024
  return undefined;
739
1025
  if (model === undefined || !listed)
@@ -741,31 +1027,49 @@ export async function capBefore(cap, model, { listed = true } = {}) {
741
1027
  const output = outputBound(model);
742
1028
  if (output === undefined)
743
1029
  return { beforeRequest: () => ({ refuse: noCeiling(cap) }) };
744
- const price = worstOf((await import("@earendil-works/pi-ai")).calculateCost, model);
745
- const name = nameOf(model);
746
- const held = (request) => price(request.inputTokensMax, request.outputTokensMax ?? output);
1030
+ const price = priceOf((await import("@earendil-works/pi-ai")).calculateCost, model);
1031
+ const held = (request) => request.holdUsd ?? price({ cached: 0, fresh: request.inputTokensMax }, request.outputTokensMax ?? output);
1032
+ /** A request priced by the one rule (requestPrice): its cost at an output, and the output it asks, needs at least, and
1033
+ * is typically answered in at step 0 (WRAP_UP_STEP0_ANSWER_TOKENS, at most what it asks). */
1034
+ const pricedOf = ({ inputTokensMax, outputTokensAsked, outputTokensLeast, previous }) => {
1035
+ const priced = requestPrice(price, inputTokensMax, previous, now(), mode);
1036
+ const asked = Math.min(outputTokensAsked ?? output, output);
1037
+ return { priced, asked, least: Math.min(outputTokensLeast ?? ANSWER_TOKENS_LEAST, asked), step0: Math.min(WRAP_UP_STEP0_ANSWER_TOKENS, asked) };
1038
+ };
1039
+ const measured = (request) => typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax);
747
1040
  return {
748
- beforeRequest({ spentUsd, inFlight, inputTokensMax, outputTokensAsked, outputTokensLeast }) {
1041
+ leastUsd(request) {
1042
+ if (!measured(request))
1043
+ return undefined;
1044
+ const { priced, least } = pricedOf(request);
1045
+ return priced.cost(output === 0 ? 0 : least);
1046
+ },
1047
+ typicalUsd(request) {
1048
+ if (!measured(request))
1049
+ return undefined;
1050
+ const { priced, step0 } = pricedOf(request);
1051
+ return priced.cost(output === 0 ? 0 : step0);
1052
+ },
1053
+ beforeRequest({ spentUsd, inFlight, inputTokensMax, outputTokensAsked, outputTokensLeast, previous }) {
749
1054
  if (spentUsd === null)
750
1055
  return { refuse: unknownSpend(cap) };
751
1056
  const inputs = [inputTokensMax, ...inFlight.map((request) => request.inputTokensMax)];
752
1057
  if (inputs.some((input) => typeof input !== "number" || !Number.isFinite(input)))
753
1058
  return { refuse: unmeasured(cap) };
754
- // Its requests in flight at the limit each was admitted with, and its paid calls under way at what they are held at.
1059
+ // Its requests in flight at what each was admitted at, and its paid calls under way at what they are held at.
755
1060
  const holding = inFlight.reduce((sum, request) => sum + held(request), paidHolds());
756
1061
  const left = cap - spentUsd - holding;
757
- const cost = (tokens) => price(inputTokensMax, tokens);
1062
+ const { priced, asked, least } = pricedOf({ inputTokensMax, outputTokensAsked, outputTokensLeast, previous });
1063
+ const cost = priced.cost;
1064
+ const bound = (tokens) => Math.max(0, priced.worst(tokens) - cost(tokens));
1065
+ const boundOf = (tokens) => (bound(tokens) > 0 ? { boundUsd: bound(tokens) } : {});
1066
+ const admitted = (limit) => ({ ...(output === 0 ? {} : { outputTokensMax: limit }), holdUsd: cost(limit), boundUsd: bound(limit), stoppedUsd: stoppedPriceOf(cost, limit) });
758
1067
  // A model whose output costs nothing and names no ceiling: nothing to limit, only its input to fit.
759
1068
  if (output === 0)
760
- return cost(0) <= left + FIT_TOLERANCE ? undefined : { refuse: capRefusal(cap, spentUsd, holding, name, cost(0)), spentUsd: spentUsd + holding, needsUsd: cost(0) };
761
- const asked = Math.min(outputTokensAsked ?? output, output);
762
- const least = Math.min(outputTokensLeast ?? ANSWER_TOKENS_LEAST, asked);
1069
+ return cost(0) <= left + FIT_TOLERANCE ? admitted(0) : { ...refuseFor(capRefusal(cap, spentUsd, holding, cost(0))), ...boundOf(0) };
763
1070
  const most = mostOutput(cost, least, asked, left);
764
- return most === undefined ? { refuse: capRefusal(cap, spentUsd, holding, name, cost(least)), spentUsd: spentUsd + holding, needsUsd: cost(least) } : { outputTokensMax: most };
1071
+ return most === undefined ? { ...refuseFor(capRefusal(cap, spentUsd, holding, cost(least))), ...boundOf(least) } : admitted(most);
765
1072
  },
766
- worstOf: (request) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) ? held(request) : undefined),
767
- stoppedOf: (request, streamed) => (typeof request.inputTokensMax === "number" && Number.isFinite(request.inputTokensMax) && Number.isFinite(streamed) && streamed >= 0
768
- ? stoppedPriceOf((tokens) => price(request.inputTokensMax, tokens), request.outputTokensMax ?? output)(streamed) : undefined),
769
1073
  };
770
1074
  }
771
1075
  /** A request's input bound (inputBound of its context, plus `overhead(model, context)`, what its provider adds
@@ -787,26 +1091,81 @@ export function requestParts(overhead = piOverhead) {
787
1091
  * each request to a model in `unpriced` (one serve has no price for) or whose output is priced and that has no output
788
1092
  * ceiling, each whose input cannot be bounded, and every request once what the run has spent is unknown: `spent` null
789
1093
  * (spentIn), or an answer since whose cost is unknown. A request's input is inputBound of its context, plus
790
- * `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0. Each
791
- * request sent carries its worst case (HELD_USD) to the marks below, and one stopped before its end counts at it.
792
- * `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry.
793
- * `joined`: the run is on another harness, whose spend is the run's one total, and these are the run's own requests
794
- * beside the harness's (a learned workflow's, a hosted search's). Each is judged against that total as the harness
795
- * sets it when its run opens (RunSpend.now: its booked requests, its paid tools' charges and its requests in flight,
796
- * with sideSpend), unknown until then; held where the harness's check sees it (paidHolds); and its cost added to
797
- * sideSpend, which starts at `spent` (what these cost in earlier processes: spentIn's `sides`). */
798
- export async function capModels(models, cap, spent, { unpriced = new Set(), overhead = piOverhead, refused: markRefused, joined = false } = {}) {
1094
+ * `overhead(model, context)` (piOverhead), what its provider adds server-side; undefined is unmeasured, never 0. It is
1095
+ * priced by requestPrice under `mode`, after the previous request of its conversation (the context's last answer, read
1096
+ * by previousIn; its end as `now` read it when it settled here, else its own timestamp, which is when it began). Each
1097
+ * request sent carries what it is held at (HELD_USD) and its bound (BOUND_USD) to the marks below, and one stopped
1098
+ * before its end counts at most its hold.
1099
+ * `refused` (markRequests') writes the start mark of a refused model request before pi writes its error entry. On
1100
+ * another harness the run has no models of its own: every request goes through its session's proxy (port-models.ts). */
1101
+ export async function capModels(models, cap, spent, { unpriced = new Set(), overhead = piOverhead, refused: markRefused, mode = "expected", now = Date.now, wrapUp } = {}) {
799
1102
  const [{ calculateCost, createAssistantMessageEventStream }, simple] = await Promise.all([import("@earendil-works/pi-ai"), import("@earendil-works/pi-ai/api/simple-options")]);
800
1103
  const partsOf = requestParts(overhead);
1104
+ /** When each answer settled here, by its timestamp (an answer keeps it when the run's store gives it back), the newest
1105
+ * ENDED_KEPT of them: its end, for the next request's previous. */
1106
+ const ended = new Map();
1107
+ const ENDED_KEPT = 64;
1108
+ const endedNow = (message) => {
1109
+ if (typeof message.timestamp !== "number")
1110
+ return;
1111
+ ended.delete(message.timestamp);
1112
+ ended.set(message.timestamp, now());
1113
+ if (ended.size > ENDED_KEPT)
1114
+ ended.delete(ended.keys().next().value);
1115
+ };
1116
+ /** The previous request of `context`'s conversation on `model`: its last answer, if one on this model whose usage says
1117
+ * its input, with the bound of what it was sent (the context before it, measured as this request is). An answer on
1118
+ * another model, or that failed or was stopped, leaves none: nothing cached to count on. */
1119
+ const previousIn = (model, context) => {
1120
+ const at = context.messages.findLastIndex((message) => message.role === "assistant");
1121
+ const answer = context.messages[at];
1122
+ if (!answer || answer.model !== model.id || answer.provider !== model.provider || answer.stopReason === "error" || answer.stopReason === "aborted")
1123
+ return undefined;
1124
+ const before = partsOf(model, { ...context, messages: context.messages.slice(0, at) });
1125
+ return previousOf(answer.usage, before?.input, ended.get(answer.timestamp) ?? answer.timestamp);
1126
+ };
801
1127
  let held = 0;
802
- if (joined)
803
- sidesSpent = spent;
804
- /** What the run has spent, as this request's check reads it: on another harness the run's one total (`joined`). */
805
- const spentNow = () => (joined ? (runSpend?.now?.() ?? null) : spent);
1128
+ /** What the run has spent, as this request's check reads it. */
1129
+ const spentNow = () => spent;
806
1130
  // The run's spend as a paid tool's check reads it (installed below, useSpend): the requests in flight held at their
807
1131
  // worst case apart from it (it adds the paid holds itself), and its charge joins the spend.
808
- const own = { cap, spent: () => spent, held: () => held, add: (usd) => void (spent = spent !== null && typeof usd === "number" && Number.isFinite(usd) ? spent + usd : null) };
1132
+ // `cap` moves only by a raise (raise: a workflow run's, budget.ts), read at each check from then on.
1133
+ const own = {
1134
+ get cap() { return cap; }, spent: () => spent, held: () => held, add: (usd) => void (spent = spent !== null && typeof usd === "number" && Number.isFinite(usd) ? spent + usd : null),
1135
+ raise: (to) => void (to > cap && (cap = to)),
1136
+ };
1137
+ /** `judgeOne`, and near the cap the wrap-up (wrapUpDue), once: a turn's request on the run's own model is sent with the
1138
+ * words after everything its context holds (`context`), its bytes admitted with it. Only in this one request: pi's
1139
+ * transcript never holds the note, and no input is queued, so the run spends nothing after the model answers. */
809
1140
  const judge = (model, context, options, simpleCall, turn) => {
1141
+ const judged = judgeOne(model, context, options, simpleCall, turn);
1142
+ if (!("hold" in judged) || !wrapUp || wrapUp.sent || wrapUp.pending || !turn || model.id !== wrapUp.model)
1143
+ return judged;
1144
+ const spentUsd = spentNow();
1145
+ // What is left as admission counted it: what was spent, and what requests and paid calls in flight are held at.
1146
+ // Nothing priced yet: the request at its input and a typical answer (WRAP_UP_STEP0_ANSWER_TOKENS), never its hold.
1147
+ const due = spentUsd === null ? undefined : wrapUpDue(cap, spentUsd, held + paidHolds(), typicalCost(wrapUp.costs, judged.typical ?? judged.hold), judged.least);
1148
+ if (!due)
1149
+ return judged;
1150
+ const words = wrapUpWords(due.leftUsd, wrapUp.costs.length === 0);
1151
+ const noted = { ...context, messages: [...context.messages, { role: "user", content: `<system-reminder>${words}</system-reminder>`, timestamp: now() }] };
1152
+ const again = judgeOne(model, noted, options, simpleCall, turn);
1153
+ // The note's own bytes do not fit: the request goes as it came, and the note waits for one they do.
1154
+ if (!("hold" in again))
1155
+ return judged;
1156
+ // Pending until this request ends: told (recorded) only if it ends answered, else left for the next request.
1157
+ wrapUp.pending = true;
1158
+ return { ...again, context: noted, told: { capUsd: cap, leftUsd: due.leftUsd, words } };
1159
+ };
1160
+ /** Settles a note `answer` carried: told when it ended answered (not an error, not aborted), else re-armed. */
1161
+ const settleNote = (answer, told) => void answer.then((message) => {
1162
+ wrapUp.pending = false;
1163
+ if (message.stopReason === "error" || message.stopReason === "aborted")
1164
+ return;
1165
+ wrapUp.sent = true;
1166
+ wrapUp.record(told);
1167
+ }, () => void (wrapUp.pending = false));
1168
+ const judgeOne = (model, context, options, simpleCall, turn) => {
810
1169
  if (unpriced.has(model.id))
811
1170
  return { why: noPrice(cap) };
812
1171
  const ceiling = outputBound(model);
@@ -826,16 +1185,24 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
826
1185
  const parts = partsOf(model, context);
827
1186
  if (parts === undefined)
828
1187
  return { why: unmeasured(cap) };
829
- const price = worstOf(calculateCost, model);
830
- const cost = (tokens) => price(parts.input, tokens) + parts.feeUsd;
1188
+ // Its price by the one rule (requestPrice): its input expected after the previous request, else uncached.
1189
+ const priced = requestPrice(priceOf(calculateCost, model), parts.input, mode === "strict" ? undefined : previousIn(model, context), now(), mode, parts.feeUsd);
1190
+ const cost = priced.cost;
1191
+ const bound = (tokens) => Math.max(0, priced.worst(tokens) - cost(tokens));
1192
+ // A refusal for room at `tokens` of output: its words and figures (capRefusal, at what admission prices the request
1193
+ // at), and the bound it would have been sent with.
1194
+ const refusedAt = (holding, tokens) => {
1195
+ const { why, figures } = whyOf(capRefusal(cap, spentUsd, holding, cost(tokens)));
1196
+ return { why, figures: { ...figures, ...(bound(tokens) > 0 ? { boundUsd: bound(tokens) } : {}) } };
1197
+ };
831
1198
  // What the run holds beside what it spent, as a paid call's check counts it: each request in flight at its figure, and
832
1199
  // each paid call under way at what it is held at.
833
1200
  const holding = held + paidHolds();
834
1201
  const left = cap - spentUsd - holding;
835
- const name = nameOf(model);
836
- // A model whose output costs nothing and names no ceiling: nothing to limit, only its input and fee to fit.
1202
+ // A model whose output costs nothing and names no ceiling: nothing to limit, only its input and fee to fit. Its least
1203
+ // admission is that figure, its input at its price after the previous request, and no output (the wrap-up's least).
837
1204
  if (ceiling === 0)
838
- return cost(0) <= left + FIT_TOLERANCE ? { worst: cost(0), stopped: () => cost(0) } : { why: capRefusal(cap, spentUsd, holding, name, cost(0)), figures: { spentUsd: spentUsd + holding, needsUsd: cost(0) } };
1205
+ return cost(0) <= left + FIT_TOLERANCE ? { hold: cost(0), bound: bound(0), stopped: () => cost(0), least: cost(0) } : refusedAt(holding, 0);
839
1206
  // What the request would send as it stands, thinking included: pi-ai clamps its maxTokens (or the model's) to what its
840
1207
  // context leaves, and on an API whose thinking takes a budget adds the budget to it.
841
1208
  const transcript = context;
@@ -851,7 +1218,7 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
851
1218
  const least = Math.min(leastOutput(model, thinking, (level) => simple.thinkingBudgetForLevel(level, options?.thinkingBudgets)), asked);
852
1219
  const most = mostOutput(cost, least, asked, left);
853
1220
  if (most === undefined)
854
- return { why: capRefusal(cap, spentUsd, holding, name, cost(least)), figures: { spentUsd: spentUsd + holding, needsUsd: cost(least) } };
1221
+ return refusedAt(holding, least);
855
1222
  // The reasoning a stop leaves unseen: a model's reasoning streams as a summary or not at all (the Responses API; Claude
856
1223
  // 4-class thinking), so a request that reasons counts its level's budget (the budget it was sent with, on a budget
857
1224
  // API), or its whole limit when it gives no level and its API reasons by default; none on a budget API with thinking
@@ -871,16 +1238,20 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
871
1238
  // did not stream (max(0, budget - the reasoning streamed), so thinking that streamed is not counted twice), and the
872
1239
  // allowance, within its worst case.
873
1240
  const stoppedAt = (limit) => (message) => stoppedFigure(cost, limit, cost(limit), streamedBytes(message) + Math.max(0, hiddenOf(limit) - reasoningBytes(message)));
1241
+ // The wrap-up's typical cost while nothing is priced: its input and a typical answer, at most what it asks.
1242
+ const typical = cost(Math.min(WRAP_UP_STEP0_ANSWER_TOKENS, asked));
1243
+ // The figure admission refuses it below (`least` output at its price): the wrap-up's other trigger (wrapUpDue).
1244
+ const leastUsd = cost(least);
874
1245
  if (most === asked)
875
- return { worst: cost(asked), stopped: stoppedAt(asked) };
1246
+ return { hold: cost(asked), bound: bound(asked), stopped: stoppedAt(asked), typical, least: leastUsd };
876
1247
  // Limited: sent with `most` tokens at most, thinking included. On a budget API the budget is squeezed first, keeping
877
1248
  // the answer's 1,024, and maxTokens is what is left of `most` beside it, so pi-ai's sum is `most`.
878
1249
  const clamp = { tokens: most, leftUsd: Math.round(left * 1e6) / 1e6, capUsd: cap };
879
1250
  if (!budgeted)
880
- return { worst: cost(most), stopped: stoppedAt(most), options: { ...options, maxTokens: most, [CLAMP]: clamp } };
1251
+ return { hold: cost(most), bound: bound(most), stopped: stoppedAt(most), typical, least: leastUsd, options: { ...options, maxTokens: most, [CLAMP]: clamp } };
881
1252
  const level = simple.clampReasoning(thinking);
882
1253
  const budget = Math.min(simple.thinkingBudgetForLevel(thinking, options?.thinkingBudgets), most - ANSWER_TOKENS_LEAST);
883
- return { worst: cost(most), stopped: stoppedAt(most), options: { ...options, maxTokens: most - budget, thinkingBudgets: { ...options?.thinkingBudgets, [level]: budget }, [CLAMP]: clamp } };
1254
+ return { hold: cost(most), bound: bound(most), stopped: stoppedAt(most), typical, least: leastUsd, options: { ...options, maxTokens: most - budget, thinkingBudgets: { ...options?.thinkingBudgets, [level]: budget }, [CLAMP]: clamp } };
884
1255
  };
885
1256
  const refusal = (model, why) => ({
886
1257
  role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id, stopReason: "error", timestamp: Date.now(),
@@ -894,23 +1265,26 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
894
1265
  * (markResponseBegan: its usage is what had streamed, not what the provider can have billed), or that failed with no
895
1266
  * answer, at `worst`, what the cap held for it; each as spentIn reads its end mark. Without a figure (a deferred
896
1267
  * response) it is unknown, as is a cost that is not a number, from then on. */
897
- const count = (answer, worst, stopped, attempts) => {
1268
+ const count = (answer, turn, worst, stopped, attempts) => {
898
1269
  const plus = (sum, cost) => (sum !== null && typeof cost === "number" && Number.isFinite(cost) ? sum + cost : null);
899
- const add = (cost) => void (joined ? (sidesSpent = plus(sidesSpent, cost)) : (spent = plus(spent, cost)));
1270
+ const add = (cost) => void (spent = plus(spent, cost));
900
1271
  // One rule (bookRequest), from how the request ended (piEnded) as its marks read it too.
901
1272
  const at = (message) => message.stopReason === "aborted" ? (stopped && !anyAttemptLost(attempts) ? stopped(message) : worst)
902
1273
  : bookRequest(piEnded(message, responseBegan.has(message), attempts), worst === undefined ? {} : { hold: worst }).usd;
903
- return answer.then((message) => add(at(message)), () => add(worst));
1274
+ // A priced turn answer of the run's own model: the wrap-up's typical cost counts it, as costsIn reads it again (its
1275
+ // pi.assistant entries). Never a compaction summary's or a native search's request on the same model (completeSimple
1276
+ // calls, `turn` false): no pi.assistant entry keeps them, so a process opened again would count without them.
1277
+ const priced = (message) => {
1278
+ const total = message.usage?.cost?.total;
1279
+ if (wrapUp && turn && message.model === wrapUp.model && message.stopReason !== "error" && message.stopReason !== "aborted" && typeof total === "number" && Number.isFinite(total) && total > 0)
1280
+ wrapUp.costs.push(total);
1281
+ };
1282
+ return answer.then((message) => (endedNow(message), priced(message), add(at(message))), () => add(worst));
904
1283
  };
905
- /** Sends a request judged to fit at `worst`, holding that until `answer` settles: here, or on another harness where
906
- * its check sees it (`joined`: paidHolds). */
907
- const admit = (worst, stopped, answer, attempts) => {
908
- const hold = { usd: worst };
909
- if (joined)
910
- paidOpen.add(hold);
911
- else
912
- held += worst;
913
- const release = () => void (joined ? paidOpen.delete(hold) : (held -= worst));
1284
+ /** Sends a request judged to fit at `worst` (its hold), holding that until `answer` settles. */
1285
+ const admit = (turn, worst, stopped, answer, attempts) => {
1286
+ held += worst;
1287
+ const release = () => void (held -= worst);
914
1288
  let answered;
915
1289
  try {
916
1290
  answered = answer();
@@ -919,31 +1293,64 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
919
1293
  release();
920
1294
  throw error;
921
1295
  }
922
- void count(answered, worst, stopped, attempts).finally(release);
1296
+ void count(answered, turn, worst, stopped, attempts).finally(release);
923
1297
  return answered;
924
1298
  };
925
1299
  // A paid tool's check reads the spend, and the requests in flight held at their worst case apart from it (it adds the
926
1300
  // paid holds itself), and its charge joins the spend. On another harness, the harness sets it as its run opens
927
1301
  // (harness-app.ts).
928
- if (!joined)
929
- useSpend(own);
930
- /** `options` with the request's worst case, and its figure if it is stopped, for its marks. */
931
- /** `options` with the request's worst case, its figure if it is stopped, and its attempts' record, for its marks: on an
932
- * API the cap can watch, a fetch that records each attempt (`attempts`, undefined on one it cannot). */
933
- const carrying = (options, { worst, stopped }, attempts) => ({
934
- ...options, [HELD_USD]: worst, [STOPPED_USD]: stopped,
1302
+ useSpend(own);
1303
+ /** `options` with what the request is held at, its bound, its figure if it is stopped, and its attempts' record, for
1304
+ * its marks: on an API the cap can watch, a fetch that records each attempt (`attempts`, undefined on one it cannot). */
1305
+ const carrying = (options, { hold, bound, stopped }, attempts) => ({
1306
+ ...options, [HELD_USD]: hold, [BOUND_USD]: bound, [STOPPED_USD]: stopped,
935
1307
  // null on an API the cap cannot watch: its marks read a failure before any event as lost.
936
1308
  ...(attempts ? { [ATTEMPTS]: attempts, fetch: recordingFetch(attempts, options?.fetch, options?.signal) } : { [ATTEMPTS]: null }),
937
1309
  });
938
1310
  const attemptsFor = (model) => (unwatched(model.api) ? undefined : []);
939
1311
  const stream = (send, simpleCall) => (model, context, options) => {
940
1312
  const judged = judge(model, context, options, simpleCall, true);
941
- if ("worst" in judged) {
1313
+ if ("hold" in judged) {
942
1314
  let events;
943
1315
  const attempts = attemptsFor(model);
944
- admit(judged.worst, judged.stopped, () => (events = send(model, context, carrying(judged.options ?? options, judged, attempts))).result(), attempts);
1316
+ let answered;
1317
+ try {
1318
+ answered = admit(true, judged.hold, judged.stopped, () => (events = send(model, judged.context ?? context, carrying(judged.options ?? options, judged, attempts))).result(), attempts);
1319
+ }
1320
+ catch (error) {
1321
+ // Never sent (its send threw as it was made): a note it carried waits for the next request.
1322
+ if (judged.told)
1323
+ wrapUp.pending = false;
1324
+ throw error;
1325
+ }
1326
+ if (judged.told)
1327
+ settleNote(answered, judged.told);
945
1328
  return events;
946
1329
  }
1330
+ // A workflow run's turn request refused for room waits for a raise, unsent, and is judged again (RunSpend.wait):
1331
+ // its node stands where it is. Its events then come from the request sent, or from the refusal if none is.
1332
+ const room = roomRefusal(judged.why);
1333
+ if (room !== undefined && own.wait) {
1334
+ const waited = createAssistantMessageEventStream();
1335
+ const signal = options?.signal;
1336
+ void own.wait({ words: room, room: true, capUsd: cap, ...(judged.figures ? { figures: judged.figures } : {}) }, signal).then((raised) => raised ? stream(send, simpleCall)(model, context, options) : refusedStream(model, judged), () => refusedStream(model, judged)).then(async (events) => {
1337
+ for await (const event of events)
1338
+ waited.push(event);
1339
+ waited.end(await events.result());
1340
+ }).catch((error) => {
1341
+ const failed = refusal(model, `${SPEND_CAP_REACHED}: Not sent: the wait for a raise failed (${String(error?.message ?? error).slice(0, 200)})`);
1342
+ waited.push({ type: "error", reason: "error", error: failed });
1343
+ waited.end(failed);
1344
+ });
1345
+ return waited;
1346
+ }
1347
+ // A refusal no raise fixes ends a workflow's run in its words (budget.ts): the node fails on the refusal.
1348
+ if (room === undefined)
1349
+ own.stopped?.({ words: judged.why.replace(CAP_REFUSAL_PREFIX, ""), room: false, capUsd: cap });
1350
+ return refusedStream(model, judged);
1351
+ };
1352
+ /** The refusal's own stream: its start mark first, then pi's error for it. */
1353
+ const refusedStream = (model, judged) => {
947
1354
  const refused = createAssistantMessageEventStream();
948
1355
  const message = refusal(model, judged.why);
949
1356
  // Its own start mark first, so pi's error entry for it answers that mark, never an earlier request a stop or a crash
@@ -959,10 +1366,14 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
959
1366
  };
960
1367
  const complete = (send, simpleCall) => (model, context, options) => {
961
1368
  const judged = judge(model, context, options, simpleCall, false);
962
- if (!("worst" in judged))
1369
+ if (!("hold" in judged)) {
1370
+ // Inside a workflow's call node (the `llm` tool): the call is told, and ends on it (app.ts runEffect).
1371
+ const room = roomRefusal(judged.why);
1372
+ capRefusals.getStore()?.({ words: room ?? judged.why.replace(CAP_REFUSAL_PREFIX, ""), room: room !== undefined, capUsd: cap, ...(judged.figures ? { figures: judged.figures } : {}) });
963
1373
  return Promise.resolve(refusal(model, judged.why));
1374
+ }
964
1375
  const attempts = attemptsFor(model);
965
- return admit(judged.worst, judged.stopped, () => send(model, context, carrying(judged.options ?? options, judged, attempts)), attempts);
1376
+ return admit(false, judged.hold, judged.stopped, () => send(model, judged.context ?? context, carrying(judged.options ?? options, judged, attempts)), attempts);
966
1377
  };
967
1378
  const guarded = {
968
1379
  stream: stream(models.stream.bind(models), false),
@@ -972,12 +1383,12 @@ export async function capModels(models, cap, spent, { unpriced = new Set(), over
972
1383
  // A deferred response was admitted when it was sent; what it cost is counted when it is fetched.
973
1384
  streamDeferred: (...args) => {
974
1385
  const events = models.streamDeferred(...args);
975
- void count(events.result());
1386
+ void count(events.result(), true);
976
1387
  return events;
977
1388
  },
978
1389
  fetchDeferred: (...args) => {
979
1390
  const answer = models.fetchDeferred(...args);
980
- void count(answer);
1391
+ void count(answer, true);
981
1392
  return answer;
982
1393
  },
983
1394
  };