@parcha/agentrun-serve 0.1.0-beta.31 → 0.1.0-beta.33

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