@parcha/agentrun-serve 0.1.0-beta.38 → 0.1.0-beta.39

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 (410) hide show
  1. package/CHANGELOG.md +418 -0
  2. package/README.md +325 -124
  3. package/dist/adapters.d.ts +4 -1
  4. package/dist/adapters.js +4 -2
  5. package/dist/agent-rows.d.ts +0 -2
  6. package/dist/agents-store.d.ts +5 -5
  7. package/dist/agents-store.js +14 -14
  8. package/dist/bash-read-only.js +2 -1
  9. package/dist/cap-short.d.ts +12 -0
  10. package/dist/cap-short.js +60 -0
  11. package/dist/cap.d.ts +3 -10
  12. package/dist/cap.js +2 -5
  13. package/dist/catalog.d.ts +0 -5
  14. package/dist/catalog.js +1 -5
  15. package/dist/chatgpt-plan.d.ts +163 -0
  16. package/dist/chatgpt-plan.js +549 -0
  17. package/dist/cli.js +26 -6
  18. package/dist/composio-preset.d.ts +8 -0
  19. package/dist/composio-preset.js +8 -7
  20. package/dist/composio-triggers.d.ts +113 -0
  21. package/dist/composio-triggers.js +411 -0
  22. package/dist/computer-calls.js +2 -2
  23. package/dist/computer-commands.d.ts +2 -0
  24. package/dist/computer-commands.js +7 -3
  25. package/dist/computer-live.d.ts +7 -2
  26. package/dist/computer-live.js +9 -5
  27. package/dist/computer-routes.d.ts +2 -2
  28. package/dist/computer-routes.js +2 -2
  29. package/dist/computer-setting.d.ts +3 -3
  30. package/dist/computer-setting.js +5 -5
  31. package/dist/computer-view.d.ts +15 -0
  32. package/dist/computer-view.js +16 -2
  33. package/dist/computer-viewer.js +14 -1
  34. package/dist/computers.d.ts +5 -2
  35. package/dist/computers.js +9 -5
  36. package/dist/console/assets/index-BNhZs-jp.css +1 -0
  37. package/dist/console/assets/index-BQv5aOGB.js +700 -0
  38. package/dist/console/index.html +2 -2
  39. package/dist/console-links.js +3 -3
  40. package/dist/decision-cap.d.ts +2 -5
  41. package/dist/decision-cap.js +3 -6
  42. package/dist/decision-rows.js +11 -11
  43. package/dist/email/account.d.ts +84 -0
  44. package/dist/email/account.js +159 -0
  45. package/dist/email/answer.d.ts +10 -0
  46. package/dist/email/answer.js +182 -0
  47. package/dist/email/email-faux.d.ts +95 -0
  48. package/dist/email/email-faux.js +849 -0
  49. package/dist/email/labels.d.ts +1 -0
  50. package/dist/email/labels.js +84 -0
  51. package/dist/email/mail.d.ts +186 -0
  52. package/dist/email/mail.js +380 -0
  53. package/dist/email/names.d.ts +20 -0
  54. package/dist/email/names.js +40 -0
  55. package/dist/email/routes.d.ts +9 -0
  56. package/dist/email/routes.js +50 -0
  57. package/dist/email/tools.d.ts +20 -0
  58. package/dist/email/tools.js +517 -0
  59. package/dist/environment.d.ts +17 -2
  60. package/dist/environment.js +36 -8
  61. package/dist/errors.d.ts +6 -0
  62. package/dist/errors.js +12 -0
  63. package/dist/eval-mailbox.d.ts +103 -0
  64. package/dist/eval-mailbox.js +236 -0
  65. package/dist/graph-view.d.ts +9 -2
  66. package/dist/graph-view.js +6 -2
  67. package/dist/harness-install.d.ts +28 -2
  68. package/dist/harness-install.js +147 -59
  69. package/dist/harness-opencode/adapter.js +2 -26
  70. package/dist/harness-opencode/facts.js +5 -2
  71. package/dist/harness-opencode/host/policy.d.ts +2 -0
  72. package/dist/harness-opencode/host/policy.js +10 -5
  73. package/dist/harness-opencode/index.d.ts +1 -1
  74. package/dist/harness-opencode/index.js +1 -1
  75. package/dist/harness-opencode/versions.d.ts +6 -0
  76. package/dist/harness-opencode/versions.js +6 -0
  77. package/dist/harness-table.js +8 -5
  78. package/dist/harness.d.ts +12 -0
  79. package/dist/harness.js +15 -3
  80. package/dist/hosted-search.d.ts +3 -1
  81. package/dist/hosted-search.js +51 -11
  82. package/dist/import-sources.d.ts +1 -1
  83. package/dist/import-sources.js +3 -3
  84. package/dist/import.d.ts +21 -0
  85. package/dist/import.js +186 -1
  86. package/dist/key-check.d.ts +0 -2
  87. package/dist/key-check.js +3 -4
  88. package/dist/key-refusal.d.ts +8 -2
  89. package/dist/key-refusal.js +16 -13
  90. package/dist/learn/check.d.ts +18 -3
  91. package/dist/learn/check.js +328 -3
  92. package/dist/learn/compile.d.ts +9 -2
  93. package/dist/learn/compile.js +52 -16
  94. package/dist/learn/grade.d.ts +4 -0
  95. package/dist/learn/grade.js +4 -1
  96. package/dist/learn/promote.d.ts +106 -51
  97. package/dist/learn/promote.js +82 -189
  98. package/dist/learn/refit.d.ts +21 -12
  99. package/dist/learn/refit.js +51 -23
  100. package/dist/learn/replay-calls.js +1 -1
  101. package/dist/learn/skills.d.ts +2 -7
  102. package/dist/learn/skills.js +28 -14
  103. package/dist/learned-nodes.d.ts +15 -7
  104. package/dist/learned-nodes.js +29 -5
  105. package/dist/learned-workflow.d.ts +41 -31
  106. package/dist/learned-workflow.js +122 -63
  107. package/dist/learning-batch.js +3 -3
  108. package/dist/learning-cost.d.ts +26 -8
  109. package/dist/learning-cost.js +17 -7
  110. package/dist/learning-routes.d.ts +2 -4
  111. package/dist/learning-routes.js +20 -3
  112. package/dist/learning-words.d.ts +1 -1
  113. package/dist/learning-words.js +4 -1
  114. package/dist/learning.d.ts +5 -5
  115. package/dist/link-check.d.ts +27 -0
  116. package/dist/link-check.js +164 -0
  117. package/dist/local-models.d.ts +33 -2
  118. package/dist/local-models.js +43 -5
  119. package/dist/mcp-pin-first.js +6 -0
  120. package/dist/mcp-secret-writes.js +3 -0
  121. package/dist/mcp-servers-store.d.ts +25 -16
  122. package/dist/mcp-servers-store.js +23 -3
  123. package/dist/model-form.d.ts +11 -0
  124. package/dist/model-form.js +17 -1
  125. package/dist/model.d.ts +26 -6
  126. package/dist/model.js +126 -18
  127. package/dist/monid.d.ts +26 -31
  128. package/dist/monid.js +84 -79
  129. package/dist/native/binding.d.ts +13 -0
  130. package/dist/native/binding.js +57 -0
  131. package/dist/native/cli.d.ts +2 -0
  132. package/dist/native/cli.js +48 -0
  133. package/dist/native/connection.d.ts +8 -0
  134. package/dist/native/connection.js +94 -0
  135. package/dist/native/context.d.ts +6 -0
  136. package/dist/native/context.js +22 -0
  137. package/dist/native/discovery.d.ts +27 -0
  138. package/dist/native/discovery.js +404 -0
  139. package/dist/native/environment.d.ts +4 -0
  140. package/dist/native/environment.js +18 -0
  141. package/dist/native/history.d.ts +20 -0
  142. package/dist/native/history.js +147 -0
  143. package/dist/native/instructions.d.ts +21 -0
  144. package/dist/native/instructions.js +173 -0
  145. package/dist/native/remote-worker-bridge.d.ts +3 -0
  146. package/dist/native/remote-worker-bridge.js +278 -0
  147. package/dist/native/remote.d.ts +187 -0
  148. package/dist/native/remote.js +492 -0
  149. package/dist/native/runtime.d.ts +17 -0
  150. package/dist/native/runtime.js +316 -0
  151. package/dist/native/runtimes.d.ts +66 -0
  152. package/dist/native/runtimes.js +41 -0
  153. package/dist/native/schema.d.ts +46 -0
  154. package/dist/native/schema.js +41 -0
  155. package/dist/native/types.d.ts +87 -0
  156. package/dist/native/types.js +1 -0
  157. package/dist/observation/http.d.ts +4 -0
  158. package/dist/observation/http.js +140 -0
  159. package/dist/observation/observer.d.ts +301 -0
  160. package/dist/observation/observer.js +919 -0
  161. package/dist/observation/schema.d.ts +52 -0
  162. package/dist/observation/schema.js +154 -0
  163. package/dist/openapi.d.ts +1 -0
  164. package/dist/openapi.js +394 -85
  165. package/dist/paid-calls.d.ts +8 -3
  166. package/dist/paid-calls.js +6 -2
  167. package/dist/place-offers.d.ts +4 -8
  168. package/dist/place-offers.js +4 -9
  169. package/dist/port-models.d.ts +7 -2
  170. package/dist/port-models.js +5 -2
  171. package/dist/print.d.ts +4 -2
  172. package/dist/print.js +4 -3
  173. package/dist/propose.d.ts +1 -2
  174. package/dist/propose.js +10 -1
  175. package/dist/provider.d.ts +5 -1
  176. package/dist/provider.js +8 -0
  177. package/dist/push-handler.d.ts +3 -2
  178. package/dist/push-handler.js +20 -6
  179. package/dist/refusal-words.d.ts +11 -0
  180. package/dist/refusal-words.js +13 -2
  181. package/dist/run-launch.d.ts +10 -1
  182. package/dist/run-launch.js +11 -4
  183. package/dist/run-learning-served.d.ts +75 -2
  184. package/dist/run-manifest.d.ts +3 -0
  185. package/dist/run-manifest.js +13 -1
  186. package/dist/run-reads-over-store.d.ts +3 -3
  187. package/dist/run-reads-over-store.js +13 -10
  188. package/dist/run-timeline-served.d.ts +3 -2
  189. package/dist/run-timeline-served.js +8 -9
  190. package/dist/run-view.d.ts +42 -35
  191. package/dist/run-view.js +79 -44
  192. package/dist/runnable.d.ts +13 -5
  193. package/dist/runnable.js +69 -60
  194. package/dist/runner/adapter-loop.d.ts +42 -11
  195. package/dist/runner/adapter-loop.js +651 -247
  196. package/dist/runner/adapter-run-spec.d.ts +37 -12
  197. package/dist/runner/adapter-run-spec.js +139 -106
  198. package/dist/runner/adapters/pi.d.ts +24 -0
  199. package/dist/runner/adapters/pi.js +59 -9
  200. package/dist/runner/beside.d.ts +3 -1
  201. package/dist/runner/beside.js +24 -8
  202. package/dist/runner/claim-secrets.d.ts +3 -1
  203. package/dist/runner/claim-secrets.js +28 -4
  204. package/dist/runner/cli-run-spec.d.ts +30 -0
  205. package/dist/runner/cli-run-spec.js +94 -50
  206. package/dist/runner/computer-channel.d.ts +5 -2
  207. package/dist/runner/computer-channel.js +3 -2
  208. package/dist/runner/computer-journal.d.ts +6 -0
  209. package/dist/runner/computer-journal.js +8 -10
  210. package/dist/runner/conformance/harness.js +6 -3
  211. package/dist/runner/end-of-run.d.ts +2 -0
  212. package/dist/runner/end-of-run.js +3 -1
  213. package/dist/runner/feedback-round.d.ts +40 -13
  214. package/dist/runner/feedback-round.js +64 -16
  215. package/dist/runner/harness-loops.js +17 -0
  216. package/dist/runner/journal-kinds.d.ts +37 -13
  217. package/dist/runner/journal-kinds.js +9 -5
  218. package/dist/runner/learning-dispatch.d.ts +3 -2
  219. package/dist/runner/learning-dispatch.js +6 -6
  220. package/dist/runner/learning-end.d.ts +4 -0
  221. package/dist/runner/learning-end.js +64 -36
  222. package/dist/runner/learning-factory.d.ts +3 -0
  223. package/dist/runner/learning-factory.js +8 -2
  224. package/dist/runner/learning-loop.d.ts +2 -0
  225. package/dist/runner/learning-loop.js +19 -4
  226. package/dist/runner/loop.d.ts +18 -0
  227. package/dist/runner/loop.js +34 -0
  228. package/dist/runner/main.d.ts +6 -1
  229. package/dist/runner/main.js +26 -4
  230. package/dist/runner/mcp-run.d.ts +4 -1
  231. package/dist/runner/mcp-run.js +11 -5
  232. package/dist/runner/meta-tools.d.ts +10 -3
  233. package/dist/runner/meta-tools.js +112 -36
  234. package/dist/runner/metrics.d.ts +80 -21
  235. package/dist/runner/metrics.js +114 -39
  236. package/dist/runner/model-route.d.ts +12 -3
  237. package/dist/runner/model-route.js +139 -18
  238. package/dist/runner/monid-run.d.ts +8 -6
  239. package/dist/runner/monid-run.js +117 -43
  240. package/dist/runner/native-loop.d.ts +11 -0
  241. package/dist/runner/native-loop.js +438 -0
  242. package/dist/runner/promotion.d.ts +74 -8
  243. package/dist/runner/promotion.js +365 -124
  244. package/dist/runner/redact.js +3 -0
  245. package/dist/runner/reflect-hook.js +9 -0
  246. package/dist/runner/runner.d.ts +7 -1
  247. package/dist/runner/runner.js +8 -4
  248. package/dist/runner/sdk-loop.d.ts +7 -0
  249. package/dist/runner/sdk-loop.js +470 -0
  250. package/dist/runner/spec-holds.d.ts +16 -2
  251. package/dist/runner/spec-holds.js +42 -14
  252. package/dist/runner/store-secrets.js +17 -2
  253. package/dist/runner/workflow-first.d.ts +30 -20
  254. package/dist/runner/workflow-first.js +22 -32
  255. package/dist/runner/workflow-loop.d.ts +1 -1
  256. package/dist/runner/workflow-loop.js +18 -12
  257. package/dist/runner/workflow-spec.d.ts +4 -1
  258. package/dist/runner/workflow-spec.js +56 -45
  259. package/dist/runs-over-store.d.ts +30 -2
  260. package/dist/runs-over-store.js +46 -14
  261. package/dist/sdk/runs.d.ts +115 -0
  262. package/dist/sdk/runs.js +422 -0
  263. package/dist/sdk/schema.d.ts +175 -0
  264. package/dist/sdk/schema.js +138 -0
  265. package/dist/sdk/workflows.d.ts +22 -0
  266. package/dist/sdk/workflows.js +39 -0
  267. package/dist/secrets.d.ts +2 -0
  268. package/dist/secrets.js +19 -1
  269. package/dist/server.d.ts +48 -32
  270. package/dist/server.js +554 -130
  271. package/dist/skill-route.d.ts +3 -0
  272. package/dist/skill-route.js +16 -0
  273. package/dist/skills/agentrun-serve/SKILL.md +368 -0
  274. package/dist/stats.d.ts +10 -10
  275. package/dist/store/agent-body.d.ts +12 -8
  276. package/dist/store/agent-body.js +9 -4
  277. package/dist/store/index.d.ts +1 -1
  278. package/dist/store/native-command-owner.d.ts +10 -0
  279. package/dist/store/native-command-owner.js +47 -0
  280. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  281. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  282. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  283. package/dist/store/postgres/store.js +3 -0
  284. package/dist/store/schema.d.ts +7 -0
  285. package/dist/store/schema.js +20 -1
  286. package/dist/store/sqlite/run-patch.d.ts +8 -1
  287. package/dist/store/sqlite/run-patch.js +14 -3
  288. package/dist/store/sqlite/store.js +133 -18
  289. package/dist/store/store.d.ts +52 -7
  290. package/dist/store-reads/analytics.d.ts +7 -7
  291. package/dist/store-reads/analytics.js +23 -5
  292. package/dist/store-reads/cap.js +8 -6
  293. package/dist/store-reads/journal.d.ts +5 -0
  294. package/dist/store-reads/journal.js +85 -41
  295. package/dist/store-reads/learning.d.ts +85 -5
  296. package/dist/store-reads/learning.js +45 -17
  297. package/dist/store-reads/runs.d.ts +5 -0
  298. package/dist/store-reads/runs.js +3 -2
  299. package/dist/store-view.js +75 -21
  300. package/dist/template-eval.d.ts +73 -11
  301. package/dist/template-eval.js +535 -75
  302. package/dist/templates.d.ts +70 -20
  303. package/dist/templates.js +191 -34
  304. package/dist/text-urls.d.ts +38 -0
  305. package/dist/text-urls.js +170 -0
  306. package/dist/timeline/index.d.ts +3 -2
  307. package/dist/timeline/index.js +3 -2
  308. package/dist/timeline/labels.d.ts +5 -2
  309. package/dist/timeline/labels.js +29 -6
  310. package/dist/timeline/origin.d.ts +1 -1
  311. package/dist/timeline/origin.js +2 -2
  312. package/dist/timeline/render-text.js +1 -1
  313. package/dist/timeline/timeline.d.ts +66 -4
  314. package/dist/timeline/timeline.js +160 -30
  315. package/dist/timeline/util.d.ts +5 -0
  316. package/dist/timeline/util.js +44 -8
  317. package/dist/timeline/web-calls.d.ts +17 -0
  318. package/dist/timeline/web-calls.js +106 -0
  319. package/dist/tool-gate.d.ts +42 -42
  320. package/dist/tool-gate.js +97 -91
  321. package/dist/tool-list.d.ts +4 -1
  322. package/dist/tool-list.js +8 -1
  323. package/dist/tool-names.d.ts +18 -13
  324. package/dist/tool-names.js +19 -17
  325. package/dist/tool-plane.d.ts +17 -13
  326. package/dist/tool-plane.js +12 -5
  327. package/dist/tools.d.ts +44 -16
  328. package/dist/tools.js +28 -28
  329. package/dist/trigger-adapter.d.ts +85 -5
  330. package/dist/trigger-adapter.js +6 -0
  331. package/dist/trigger-adapters.js +3 -1
  332. package/dist/trigger-composio.d.ts +10 -0
  333. package/dist/trigger-composio.js +122 -0
  334. package/dist/trigger-email.d.ts +4 -0
  335. package/dist/trigger-email.js +228 -0
  336. package/dist/trigger-signatures.d.ts +6 -10
  337. package/dist/trigger-signatures.js +16 -16
  338. package/dist/trigger-targets.d.ts +1 -1
  339. package/dist/trigger-targets.js +4 -3
  340. package/dist/trigger-webhook.js +6 -4
  341. package/dist/triggers.d.ts +94 -9
  342. package/dist/triggers.js +263 -62
  343. package/dist/uploads.d.ts +9 -0
  344. package/dist/uploads.js +27 -0
  345. package/dist/validate.js +1 -7
  346. package/dist/web-fake.d.ts +56 -0
  347. package/dist/web-fake.js +102 -0
  348. package/dist/web-fetch-direct.d.ts +3 -0
  349. package/dist/web-fetch-direct.js +4 -1
  350. package/dist/web-fetch.d.ts +5 -1
  351. package/dist/web-fetch.js +8 -31
  352. package/dist/web-search.d.ts +51 -2
  353. package/dist/web-search.js +116 -18
  354. package/dist/webhooks.d.ts +2 -1
  355. package/dist/webhooks.js +5 -1
  356. package/dist/workflow/node-runner.js +10 -2
  357. package/dist/workspace/archil-claim.d.ts +3 -0
  358. package/dist/workspace/archil-claim.js +9 -2
  359. package/dist/workspace/computer-deps.d.ts +22 -9
  360. package/dist/workspace/computer-deps.js +78 -37
  361. package/dist/workspace/computer-for-claim.d.ts +54 -4
  362. package/dist/workspace/computer-for-claim.js +179 -39
  363. package/dist/workspace/computer-janitor.d.ts +10 -3
  364. package/dist/workspace/computer-janitor.js +96 -29
  365. package/dist/workspace/computer-kept.d.ts +82 -0
  366. package/dist/workspace/computer-kept.js +147 -0
  367. package/dist/workspace/computer-mcp.js +4 -3
  368. package/dist/workspace/computer-ports.d.ts +23 -3
  369. package/dist/workspace/computer-ports.js +115 -5
  370. package/dist/workspace/index.d.ts +1 -2
  371. package/dist/workspace/index.js +1 -2
  372. package/dist/workspace/kind-skills/desktop/SKILL.md +25 -18
  373. package/dist/workspace/kind-skills/phone/SKILL.md +28 -17
  374. package/dist/workspace/resolve-computer.d.ts +15 -3
  375. package/dist/workspace/resolve-computer.js +10 -7
  376. package/dist/workspace/revision-skills.d.ts +6 -2
  377. package/dist/workspace/revision-skills.js +12 -5
  378. package/dist/workspace/run-end-computers.d.ts +30 -0
  379. package/dist/workspace/run-end-computers.js +137 -0
  380. package/dist/workspace/run-tools.d.ts +28 -29
  381. package/dist/workspace/run-tools.js +29 -30
  382. package/dist/wrap-up.d.ts +19 -5
  383. package/dist/wrap-up.js +31 -4
  384. package/package.json +13 -9
  385. package/skills/agentrun-serve/SKILL.md +248 -10
  386. package/templates/README.md +117 -23
  387. package/templates/TOOLS.md +168 -0
  388. package/templates/code-review/agent.md +18 -4
  389. package/templates/code-review/evals/mentions-defused/case.yaml +1 -1
  390. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  391. package/templates/code-review/evals/other-repo/case.yaml +1 -1
  392. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  393. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  394. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  395. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  396. package/templates/code-review/skills/review/DEEP.md +2 -2
  397. package/templates/code-review/skills/review/REVIEWER.md +2 -2
  398. package/templates/code-review/skills/review/SKILL.md +7 -3
  399. package/templates/release-notes/evals/draft-not-publish/case.yaml +1 -1
  400. package/templates/release-notes/evals/issue-write-refused/case.yaml +1 -1
  401. package/templates/release-notes/evals/late-arrival/case.yaml +1 -1
  402. package/templates/release-notes/evals/other-repo/case.yaml +1 -1
  403. package/dist/console/assets/index-CjqQirbo.css +0 -1
  404. package/dist/console/assets/index-b6-XY5A9.js +0 -576
  405. package/dist/host-calls.d.ts +0 -20
  406. package/dist/host-calls.js +0 -12
  407. package/dist/runner/adapters/pi-computer.d.ts +0 -9
  408. package/dist/runner/adapters/pi-computer.js +0 -51
  409. package/dist/workspace/computer-script.d.ts +0 -53
  410. package/dist/workspace/computer-script.js +0 -172
@@ -8,7 +8,7 @@
8
8
  // passes its decisions. `effort` is the level the run ran at and `model`, on a harness other than pi, the model its
9
9
  // revision named — both as storedMetrics added them, resolved by the caller from the run's launch and harness.
10
10
  import { runMetricsWithDecisions, timelineOf } from "../timeline/index.js";
11
- import { answeredUnpriced, RUNNER_RECORDS, sessionSpendOf } from "@parcha/agentrun-kernel";
11
+ import { costOfParts, rebooked, RUNNER_RECORDS, sessionSpendOf, turnCostOf } from "@parcha/agentrun-kernel";
12
12
  import { DECISION_SESSION, TOOL_SESSION } from "@parcha/agentrun-kernel/kernel/cap";
13
13
  import { KINDS, WORKFLOW_SESSION } from "./journal-kinds.js";
14
14
  import { anthropicModelId } from "../provider.js";
@@ -55,10 +55,16 @@ export function bookedSpend(entries, which) {
55
55
  models[name] = (models[name] ?? 0) + 1;
56
56
  };
57
57
  let known = 0;
58
+ let bounded = 0;
58
59
  let unpriced = 0;
59
60
  let requests = 0;
60
61
  let unmetered = 0;
62
+ let free = 0;
63
+ let atMost = 0;
61
64
  const tokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
65
+ // Each request is booked once, as the kernel's sessionSpendOf reads it: a second runner.turn of a turn already booked
66
+ // (two bookings of one session that each read it open, a cut written twice) counts no money and no request again.
67
+ const booked = new Set();
62
68
  for (const e of entries) {
63
69
  if (!chosen(e))
64
70
  continue;
@@ -71,17 +77,25 @@ export function bookedSpend(entries, which) {
71
77
  }
72
78
  if (e.kind !== RUNNER_RECORDS.turn)
73
79
  continue;
80
+ if (rebooked(booked, typeof e.data?.turn === "number" ? turnOf(e) : undefined))
81
+ continue;
74
82
  const d = (e.data ?? {});
75
83
  if (d.givenBack === true || d.unsent === true)
76
84
  continue;
77
85
  requests += 1;
78
86
  count(e);
79
- // An answer with no price of its own was booked at its hold for the cap (answeredUnpriced): as a cost it is unknown.
80
- const usd = answeredUnpriced(d) ? null : typeof d.bookedUsd === "number" && Number.isFinite(d.bookedUsd) ? d.bookedUsd : typeof d.usd === "number" && Number.isFinite(d.usd) ? d.usd : null;
81
- if (usd === null)
87
+ if (d.free === true)
88
+ free += 1;
89
+ // Its own cost by the kernel's one rule (turnCostOf): an answer with no price of its own is unknown, never the hold it
90
+ // was booked at for the cap; a request cut with no answer booked at its hold counts that figure, the most it can cost,
91
+ // kept apart from the requests' own figures.
92
+ const own = turnCostOf(d);
93
+ if (own.usd === null)
82
94
  unpriced += 1;
95
+ else if (own.atMost)
96
+ (bounded += own.usd), (atMost += 1);
83
97
  else
84
- known += usd;
98
+ known += own.usd;
85
99
  // The booking keeps a request's usage only when it reported some (runner.ts tokensOf): one with none is unmetered.
86
100
  if (d.usage === undefined)
87
101
  unmetered += 1;
@@ -89,13 +103,68 @@ export function bookedSpend(entries, which) {
89
103
  if (typeof d.usage?.[key] === "number")
90
104
  tokens[key] += d.usage[key];
91
105
  }
92
- return { usd: unpriced ? null : known, known, unpriced, requests, unmetered, models, tokens };
106
+ return { usd: unpriced ? null : known + bounded, known, bounded, unpriced, atMost, requests, unmetered, models, tokens, ...(requests > 0 && free === requests ? { free: true } : {}) };
107
+ }
108
+ /** A sum of charges with its float noise rounded off, nothing more (as the decisions row rounds, decision-rows.ts): a
109
+ * decision costs millionths of a dollar, so a sum rounded to the millionth would lose it. */
110
+ const floatNoiseOff = (usd) => Math.round(usd * 1e12) / 1e12;
111
+ export function costWordsOf(parts, extraUnpriced = 0) {
112
+ if (parts.some((part) => part === null))
113
+ return { usd: null };
114
+ const all = [...parts, { known: 0, bounded: 0, atMost: 0, unpriced: extraUnpriced }];
115
+ const cost = costOfParts(all);
116
+ const round = floatNoiseOff;
117
+ if (cost.usd === null)
118
+ return { usd: null, so_far_usd: round(cost.soFarUsd), unpriced: cost.unpriced };
119
+ if (!cost.atMost)
120
+ return { usd: round(cost.usd) };
121
+ // The exact part: the charges' own figures, never a hold (costOfParts' soFarUsd counts the holds once every charge is).
122
+ return { usd: round(cost.usd), so_far_usd: round(all.reduce((sum, part) => sum + part.known, 0)), unpriced: cost.atMost, upper_bound: true };
123
+ }
124
+ /** A usage row's cost (TimelineEvent.usage, or a cost block in the same words) as the kernel's parts, for a join
125
+ * (costWordsOf): an exact figure is `known`; a bound is its exact part (`so_far_usd`) known and the rest bounded over its
126
+ * `unpriced` holds, or, from a row that says no exact part, the whole bounded over one hold, never spend; an unknown cost
127
+ * is its known part and its unpriced count. Null: an unknown cost that says neither. No row (undefined): nothing spent. */
128
+ export function usageParts(usage) {
129
+ if (usage === undefined)
130
+ return { known: 0, bounded: 0, atMost: 0, unpriced: 0 };
131
+ const said = usage.so_far_usd !== undefined && usage.unpriced !== undefined;
132
+ if (usage.usd !== null && usage.upper_bound === true) {
133
+ return said ? { known: usage.so_far_usd, bounded: Math.max(0, usage.usd - usage.so_far_usd), atMost: usage.unpriced, unpriced: 0 } : { known: 0, bounded: usage.usd, atMost: 1, unpriced: 0 };
134
+ }
135
+ if (usage.usd !== null)
136
+ return { known: usage.usd, bounded: 0, atMost: 0, unpriced: 0 };
137
+ return said ? { known: usage.so_far_usd, bounded: 0, atMost: 0, unpriced: usage.unpriced } : null;
138
+ }
139
+ export function runCostOf(entries, { unbooked = false } = {}) {
140
+ const parts = [bookedSpend(entries, "model"), bookedSpend(entries, "paid"), bookedSpend(entries, "decisions")];
141
+ const cost = costOfParts([...parts, { known: 0, bounded: 0, atMost: 0, unpriced: unbooked && parts[0].requests === 0 ? 1 : 0 }]);
142
+ const round = floatNoiseOff;
143
+ // Its parts as one (CostParts, so its words are costWordsOf([cost])): `known` the requests' own figures alone, a hold
144
+ // never among them; while the cost is known, `bounded` and `atMost` its holds, else every hold counted in `unpriced`.
145
+ const known = round(parts.reduce((sum, part) => sum + part.known, 0));
146
+ const usd = cost.usd === null ? null : round(cost.usd);
147
+ return { usd, known, bounded: usd === null ? 0 : Math.max(0, round(usd - known)), unpriced: cost.unpriced, atMost: cost.atMost ?? 0, requests: parts.reduce((sum, part) => sum + part.requests, 0) };
93
148
  }
94
- /** An agent run's cost as its end commit stores it: its model requests' (`model`), its paid tool calls' (`paid`, the
95
- * run's ledger.paid) and its decisions' (`decisions`, a learned workflow's decision nodes, LS-07: bookedSpend over
96
- * their own session's records, so one that reported no cost is unknown, never the cap's hold for it), summed; null (unknown) when any of them is. Never a known figure that leaves an unknown part out. */
97
- export function runEndCost(parts) {
98
- return parts.model === null || parts.paid === null || parts.decisions === null ? null : parts.model + parts.paid + parts.decisions;
149
+ export const endCostOf = (cost) => ({ costUsd: cost.usd, costUpperBound: cost.usd !== null && cost.atMost > 0 });
150
+ /** The run's model requests billed to a ChatGPT plan (runner.turn `billing` "plan", booked at no price, chatgpt-plan.ts):
151
+ * how many and their tokens (input, output and cache, as each booking reported them). Each is $0 to the run by the
152
+ * kernel's one rule (turnCostOf), however it ended: the plan pays for it, so no reader counts it unpriced. */
153
+ export function planSpend(entries) {
154
+ let requests = 0;
155
+ let tokens = 0;
156
+ for (const e of entries) {
157
+ if (e.kind !== RUNNER_RECORDS.turn)
158
+ continue;
159
+ const d = (e.data ?? {});
160
+ if (d.billing !== "plan" || d.givenBack === true || d.unsent === true)
161
+ continue;
162
+ requests += 1;
163
+ for (const key of ["input", "output", "cacheRead", "cacheWrite"])
164
+ if (typeof d.usage?.[key] === "number")
165
+ tokens += d.usage[key];
166
+ }
167
+ return { requests, tokens };
99
168
  }
100
169
  /** Whether a CLI harness's record (`entries`, its root's) shows the model at work: a model message, a tool call it made, or
101
170
  * its end-of-run turn's answer. Each took a model request, so a run that shows one and booked none (its requests went
@@ -122,9 +191,9 @@ export function cliModelWorked(entries) {
122
191
  export function costIsBooked(entries, cli) {
123
192
  return cli || sessionConversations(entries).has(WORKFLOW_SESSION);
124
193
  }
125
- /** What the run has spent as its cap reads it (the kernel's sessionSpendOf over every session's records: a request still
126
- * out at its hold and bound), for a run whose cost is its booking: the runs list's figure while it runs. Null when one
127
- * session's is unknown, never 0 for it. */
194
+ /** What the run has spent and holds as its cap reads it (the kernel's sessionSpendOf over every session's records: a
195
+ * request still out at its hold and bound), for a run whose cost is its booking: the figure a gate holds it to (the
196
+ * runs list says bookedListSpend). Null when one session's is unknown, never 0 for it. */
128
197
  export function bookedCapSpend(entries) {
129
198
  let spent = 0;
130
199
  // Every conversation that holds booking records, keyed or not, as bookedSpend reads them.
@@ -138,45 +207,51 @@ export function bookedCapSpend(entries) {
138
207
  }
139
208
  return spent;
140
209
  }
141
- /** The bound of a run's requests since its spend last fit under `capUsd`, as the kernel's overCapOf reads it: each model
142
- * request, in each model session's order, at the figure the cap counts it at, after what the paid tools and decisions
143
- * spent; reset to 0 whenever the spend fits, else grown by each request's bound. What its over-cap row (run-view.ts
144
- * withOverCap) reads to tell a cache miss within that bound from a run that spent past its cap. 0 when nothing ran. */
145
- export function overCapBound(entries, capUsd) {
146
- const keyed = sessionConversations(entries);
147
- const paidConv = keyed.get(TOOL_SESSION);
148
- const decisionsConv = keyed.get(DECISION_SESSION);
149
- const others = [paidConv, decisionsConv].reduce((sum, conversation) => {
150
- if (conversation === undefined)
151
- return sum;
152
- const read = sessionSpendOf(recordsIn(entries, conversation)).spentUsd;
153
- return sum + (read ?? 0);
154
- }, 0);
210
+ /** What a run whose cost is its booking has spent, as the runs list says it while the run goes on: every booked request at
211
+ * what it was booked at, never the hold of a request still out (a hold is no spend: the request settles at what it cost,
212
+ * which the cap's own reading, bookedCapSpend, holds it to meanwhile). Null when a booked request's figure is unknown. */
213
+ export function bookedListSpend(entries) {
214
+ let spent = 0;
155
215
  const booking = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn).map((e) => Number(e.conversationId)));
156
- let running = others;
157
- let bound = 0;
158
216
  for (const conversation of booking) {
159
- if (conversation === paidConv || conversation === decisionsConv)
160
- continue;
161
217
  const read = sessionSpendOf(recordsIn(entries, conversation));
162
218
  for (const { turn, usd } of read.figures) {
163
- running += usd ?? 0;
164
- bound = running <= capUsd ? 0 : bound + (read.bounds.get(turn) ?? 0);
219
+ if (!read.answered.has(turn))
220
+ continue;
221
+ if (usd === null)
222
+ return null;
223
+ spent += usd;
165
224
  }
166
225
  }
167
- return bound;
226
+ return spent;
168
227
  }
169
228
  /** The booking records of `conversation`, as the kernel's session readers take them. */
170
229
  const recordsIn = (entries, conversation) => entries.filter((e) => Number(e.conversationId) === conversation && e.kind !== KINDS.sessionKey).map((e) => ({ kind: e.kind, data: (e.data ?? null) }));
230
+ /** `counted` with each tool `catalog` names (an MCP tool's hashed wire name: store-reads/journal.ts hashedMcpOf) counted
231
+ * under its catalog name, `mcp:<server>/<tool>`, as the run's timeline names its calls; the analytics' top tools read
232
+ * the name a run's metrics key a tool by. Every other tool keeps the name it was called by. */
233
+ function catalogKeyed(counted, catalog) {
234
+ if (!catalog?.size)
235
+ return counted;
236
+ const tools = {};
237
+ for (const [name, each] of Object.entries(counted.tools)) {
238
+ const key = catalog.get(name) ?? name;
239
+ const had = tools[key];
240
+ tools[key] = had ? { calls: had.calls + each.calls, errors: had.errors + each.errors } : each;
241
+ }
242
+ return { ...counted, tools };
243
+ }
171
244
  /** The run's metrics and cost from its journal `entries`. `decisions`: a workflow run's receipts (none for pi).
172
- * `effort`/`model`: the enrichment the old storedMetrics added. `costUsd` is the usage row's cost: null when a
173
- * response's cost is unknown, 0 before any request (costOf). */
245
+ * `effort`/`model`: the enrichment the old storedMetrics added. `catalog`: the run's MCP tools called by a hashed wire
246
+ * name, each counted under its catalog name (catalogKeyed). `costUsd` is the usage row's cost: null when a response's
247
+ * cost is unknown, 0 before any request (costOf). */
174
248
  export function runMetrics(entries, options = {}) {
175
- const counted = runMetricsWithDecisions(entries, options.decisions ?? []);
249
+ const counted = catalogKeyed(runMetricsWithDecisions(entries, options.decisions ?? []), options.catalog);
176
250
  // The run's cost from its usage row, as serve/src/runs.ts costOf reads it: the usage row's usd (null unknown, 0 before
177
251
  // any request). The usage row is the one the settled timeline appends from the run's request-cost marks.
178
252
  const usage = timelineOf(entries, { settled: true }).findLast((row) => row.kind === "usage");
179
- const costUsd = usage ? (usage.usage?.usd ?? null) : 0;
253
+ // An exact reader: a cost that counts a hold (`upper_bound`) is the most the run can have cost, unknown here.
254
+ const costUsd = usage ? (usage.usage?.upper_bound === true ? null : (usage.usage?.usd ?? null)) : 0;
180
255
  return {
181
256
  metrics: { ...counted, ...(options.effort !== undefined ? { effort: options.effort } : {}), ...(options.model !== undefined ? { model: options.model } : {}) },
182
257
  costUsd,
@@ -1,3 +1,4 @@
1
+ import type { ThinkingLevelMap } from "../port-models.js";
1
2
  import type { Wire } from "@parcha/agentrun-kernel";
2
3
  import type { ToolsAs } from "../local-models.js";
3
4
  import { type PinnedModel, type Tier } from "../model.js";
@@ -28,12 +29,17 @@ export type RouteUsage = {
28
29
  * when its model speaks no wire of the caller's. The fields of the learning grader's route (learning-ask.ts GraderRoute),
29
30
  * and `cost` beside them. */
30
31
  export interface ModelRoute {
32
+ /** `plan`: a ChatGPT plan's route (provider.ts billing "plan"), billed to the plan: no price, its rules on the wire.
33
+ * Whether its answers state what they cost is the proxy's to read from `origin` (statesUsageCost): OpenRouter's, or
34
+ * this route's own translation of one (ROUTE_ORIGIN). */
31
35
  readonly provider: {
32
36
  readonly api: Wire;
33
37
  readonly origin: string;
34
38
  readonly credential: () => string | Promise<string>;
35
39
  readonly headers?: Readonly<Record<string, string>>;
36
40
  readonly auth?: "bearer" | "x-api-key";
41
+ readonly plan?: boolean;
42
+ readonly refused?: (credential: string) => Promise<void>;
37
43
  };
38
44
  readonly model: string;
39
45
  /** The model as the run names it (`provider/model-id`, chooseModel's): what the `llm` tool's answer says it ran on,
@@ -41,13 +47,17 @@ export interface ModelRoute {
41
47
  readonly named?: string;
42
48
  /** The catalog's entry for the model, as pi-ai's model of it takes it: on every wire, what it takes as input (whether it
43
49
  * takes images) and its input limits (an image's most size), which pi's session and its read size an image by; on a
44
- * wire that carries its reasoning (Responses), also whether it reasons, its window and its output ceiling. */
50
+ * wire that carries its reasoning (Responses), also whether it reasons, its window, its output ceiling, and the effort
51
+ * each thinking level asks for (`thinkingLevelMap`: a level mapped to null sends no effort, so pi's thinking off asks
52
+ * a model that takes no "none" for none, gpt-6.1-sol's case). */
45
53
  readonly like?: {
46
54
  readonly reasoning?: boolean;
47
55
  readonly contextWindow?: number;
48
56
  readonly maxTokens?: number;
49
57
  readonly input?: readonly string[];
50
58
  readonly inputLimits?: unknown;
59
+ readonly developerRole?: boolean;
60
+ readonly thinkingLevelMap?: ThinkingLevelMap;
51
61
  };
52
62
  /** A request's price from its usage (the proxy's booking reads it): pi-ai's calculateCost, tiers included. */
53
63
  readonly price?: (model: string, usage: RouteUsage) => number | null;
@@ -61,8 +71,6 @@ export interface ModelRoute {
61
71
  /** The model's most output tokens (its catalog ceiling): the cap's output bound, null when the catalog names none. */
62
72
  readonly outputCeiling?: number | null;
63
73
  }
64
- /** The origin a route with its own fetch names: nothing is ever sent there, its fetch answers every request. */
65
- export declare const ROUTE_ORIGIN = "https://model-route.invalid";
66
74
  type PiModel = {
67
75
  id: string;
68
76
  provider: string;
@@ -74,6 +82,7 @@ type PiModel = {
74
82
  contextWindow?: number;
75
83
  input?: readonly string[];
76
84
  inputLimits?: unknown;
85
+ thinkingLevelMap?: ThinkingLevelMap;
77
86
  toolsAs?: ToolsAs;
78
87
  };
79
88
  type PiModels = {
@@ -15,12 +15,11 @@
15
15
  // the tier, as its provider bills it), and its cost is that catalog entry, tiers included, for the cap's judgement.
16
16
  import { randomUUID } from "node:crypto";
17
17
  import { calculateCost } from "@earendil-works/pi-ai";
18
+ import { ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
18
19
  import { chooseModel, MODEL_PROVIDER, runModels } from "../model.js";
19
20
  import { providerFor } from "../provider.js";
20
21
  import { keepText, runnerSecrets, secretRedactor } from "./redact.js";
21
22
  import { callsOfText, toolsAsText } from "./text-tools.js";
22
- /** The origin a route with its own fetch names: nothing is ever sent there, its fetch answers every request. */
23
- export const ROUTE_ORIGIN = "https://model-route.invalid";
24
23
  /** The wires a caller of routeOf speaks when it names none: Anthropic's Messages alone. */
25
24
  const MESSAGES_ONLY = ["anthropic-messages"];
26
25
  /** The route of `model` ("provider/model-id"; undefined for the host's model of `tier`; a claimed run's pin, sent as
@@ -48,7 +47,7 @@ export async function routeOf(model, env = process.env, tier = "default", wires
48
47
  const sees = { ...(target.input ? { input: target.input } : {}), ...(target.inputLimits ? { inputLimits: target.inputLimits } : {}) };
49
48
  // The settings serve registered for a gateway model, carried on either wire, so pi's session reads the same model whether
50
49
  // it speaks Messages or Responses to the gateway.
51
- const settings = { ...sees, ...(target.reasoning !== undefined ? { reasoning: target.reasoning } : {}), ...(target.contextWindow ? { contextWindow: target.contextWindow } : {}), ...(target.maxTokens ? { maxTokens: target.maxTokens } : {}) };
50
+ const settings = { ...sees, ...(target.reasoning !== undefined ? { reasoning: target.reasoning } : {}), ...(target.contextWindow ? { contextWindow: target.contextWindow } : {}), ...(target.maxTokens ? { maxTokens: target.maxTokens } : {}), ...(target.thinkingLevelMap ? { thinkingLevelMap: target.thinkingLevelMap } : {}) };
52
51
  const route = { model: chosen.model.modelId, named: `${chosen.model.provider}/${chosen.model.modelId}`, price, cost: target.cost, ...(unpriced.has(chosen.model.modelId) ? { unpriced: true } : {}), outputCeiling: target.maxTokens ?? null, like: sees };
53
52
  // An Anthropic model speaks Messages itself: the network, at its catalog origin, its key read by name per request.
54
53
  if (chosen.model.provider === "anthropic") {
@@ -63,14 +62,49 @@ export async function routeOf(model, env = process.env, tier = "default", wires
63
62
  // A model pi-ai speaks Responses to, for a caller that speaks it: that wire itself, where main sends it (provider.ts).
64
63
  if (target.api === "openai-responses" && wires.includes("openai-responses")) {
65
64
  const to = providerFor("openai-responses", env, chosen.model, "pi");
65
+ // A ChatGPT plan's model: billed to the plan, at no price here (unpriced, never $0), its instructions sent as a
66
+ // developer message (the plan takes no system one).
67
+ const onPlan = to.billing === "plan";
68
+ const plan = onPlan ? { price: () => null, unpriced: true } : {};
66
69
  return {
67
- ...route, model: to.modelId,
68
- provider: { api: "openai-responses", origin: to.origin, credential: to.credential, auth: to.auth },
69
- like: settings,
70
+ ...route, model: to.modelId, ...plan,
71
+ provider: { api: "openai-responses", origin: to.origin, credential: to.credential, auth: to.auth, ...(onPlan ? { plan: true } : {}), ...(to.refused ? { refused: to.refused } : {}) },
72
+ like: onPlan ? { ...settings, developerRole: true } : settings,
70
73
  };
71
74
  }
75
+ // The translation writes an answer's cost in its usage only where pi-ai read the provider's own (OpenRouter's): the
76
+ // proxy reads it on ROUTE_ORIGIN (statesUsageCost).
72
77
  return { ...route, provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream) };
73
78
  }
79
+ /** OpenRouter's origin: every answer it gives states its cost in its usage (https://openrouter.ai/docs/use-cases/usage-accounting). */
80
+ const OPENROUTER_HOST = "openrouter.ai";
81
+ const onOpenRouter = (origin) => URL.canParse(origin) && new URL(origin).hostname === OPENROUTER_HOST;
82
+ /** Whether pi-ai sends `target`'s requests to OpenRouter (pi-ai's own test, utils/openrouter-cost.js isOpenRouterModel). */
83
+ const piOnOpenRouter = (target) => target.provider === "openrouter" || onOpenRouter(target.baseUrl ?? "");
84
+ /** How much of an answer's text the error tap keeps: its end, where a stream's error event is. */
85
+ const TAP_WINDOW = 64 * 1024;
86
+ /** `upstream` (the network when absent) with the end of each answer's body kept (`kept()`), as it streams by: what the
87
+ * provider said when pi-ai reports a failure, read for the provider's own error event by its fields (streamErrorOf),
88
+ * which pi-ai's client drops (it keeps the words alone). The body reaches pi-ai as it came. */
89
+ function tapped(upstream) {
90
+ let kept = "";
91
+ const send = upstream ?? globalThis.fetch;
92
+ const fetcher = (async (input, init) => {
93
+ const response = await send(input, init);
94
+ kept = "";
95
+ if (!response.body)
96
+ return response;
97
+ const decoder = new TextDecoder();
98
+ const keep = new TransformStream({
99
+ transform(chunk, controller) {
100
+ kept = (kept + decoder.decode(chunk, { stream: true })).slice(-TAP_WINDOW);
101
+ controller.enqueue(chunk);
102
+ },
103
+ });
104
+ return new Response(response.body.pipeThrough(keep), { status: response.status, statusText: response.statusText, headers: response.headers });
105
+ });
106
+ return { fetch: fetcher, kept: () => kept };
107
+ }
74
108
  /** A fetch that answers Anthropic Messages requests on `target`, through pi-ai's `models`. A provider's error text, which
75
109
  * pi records, goes through `redact` (the runner's one redactor): a provider that echoes its key leaves none there.
76
110
  * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). */
@@ -89,7 +123,10 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
89
123
  // result of its history as text, and its calls read from its reply. A request with no tools goes as it is.
90
124
  const asText = target.toolsAs === "text" && (built.tools?.length ?? 0) > 0;
91
125
  const context = asText ? toolsAsText(built) : built;
92
- const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(upstream ? { fetch: upstream } : {}) };
126
+ // On OpenRouter, each answer's end is kept as it streams by, for a rate limit it ends in (limitedWords).
127
+ const tap = piOnOpenRouter(target) ? tapped(upstream) : undefined;
128
+ const sendWith = tap?.fetch ?? upstream;
129
+ const streamOptions = { ...(body.max_tokens ? { maxTokens: body.max_tokens } : {}), ...(init.signal ? { signal: init.signal } : {}), ...(sendWith ? { fetch: sendWith } : {}) };
93
130
  const events = models.streamSimple(target, context, streamOptions);
94
131
  const encoder = new TextEncoder();
95
132
  const stream = new ReadableStream({
@@ -98,7 +135,31 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
98
135
  // A failed request's error event carries its words alone, one data line each: pi-ai's Messages client throws an
99
136
  // error event's data as the request's error, so the caller reads the model's own error as main's in-process pi
100
137
  // reports it ("500 {...}"), never this route's envelope around it.
101
- const sendError = (words) => controller.enqueue(encoder.encode(`event: error\n${words.split(/\r?\n/).map((line) => `data: ${line}`).join("\n")}\n\n`));
138
+ const sendWords = (words) => controller.enqueue(encoder.encode(`event: error\n${words.split(/\r?\n/).map((line) => `data: ${line}`).join("\n")}\n\n`));
139
+ // What the provider said the answer cost (pi-ai reads OpenRouter's usage.cost: totalFromProvider), in the
140
+ // message's usage as `cost`, for the proxy to book (usageCostOf). Never pi-ai's own pricing of it.
141
+ const reportedOf = (used) => {
142
+ const cost = used?.cost;
143
+ return cost?.totalFromProvider === true && typeof cost.total === "number" && Number.isFinite(cost.total) && cost.total > 0 ? cost.total : undefined;
144
+ };
145
+ // The provider's own error inside its 200 stream (the tap's kept end, read by its fields: streamErrorOf) goes as
146
+ // Messages writes one (`rate_limit_error` for a rate limit, else `api_error`), after the usage the provider reported
147
+ // before it (`used`, its stated `cost` too) as the message's, so the proxy books it by its one rule for an error in a
148
+ // stream: those tokens at list (or that cost), else refused at nothing. Its top-level `message` is the same words,
149
+ // which pi-ai's Messages client reads as the request's error. A failure with no such event (a transport error, a
150
+ // status) goes as its words alone: the proxy books that as an answer cut short, at an unknown cost. Whatever the
151
+ // model wrote that this translation held is sent before either (sendHeld), so an error with no usage after the
152
+ // model began is never read as a refusal.
153
+ const sendError = (words, used, cost) => {
154
+ const failed = tap ? streamErrorOf(tap.kept()) : undefined;
155
+ if (failed === undefined)
156
+ return sendWords(words);
157
+ const tokens = used ? { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead ?? 0, cache_creation_input_tokens: used.cacheWrite ?? 0 } : undefined;
158
+ if ((tokens && tokens.input_tokens + tokens.output_tokens + tokens.cache_read_input_tokens + tokens.cache_creation_input_tokens > 0) || cost !== undefined) {
159
+ send({ type: "message_delta", delta: { stop_reason: null, stop_sequence: null }, usage: { ...(tokens ?? { input_tokens: 0, output_tokens: 0 }), ...(cost === undefined ? {} : { cost }) } });
160
+ }
161
+ send({ type: "error", message: words, error: { type: failed.rateLimit ? "rate_limit_error" : "api_error", message: words } });
162
+ };
102
163
  send({ type: "message_start", message: { id: `msg_${Date.now().toString(36)}`, type: "message", role: "assistant", model: body.model ?? target.id, content: [], stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } } });
103
164
  // Messages blocks are numbered as sent. A thinking block is sent too, so the model's reasoning reaches the run's
104
165
  // record as a Timeline row; its text goes through the run's one redactor, so a held key the model quoted in its
@@ -107,13 +168,49 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
107
168
  const blockOf = new Map();
108
169
  const sentJson = new Set();
109
170
  let blocks = 0;
110
- // The thinking of the block being streamed, gathered so its whole text is redacted at once (its deltas are not sent).
171
+ // The thinking of the block being streamed, gathered so its whole text is redacted at once (its deltas are not sent),
172
+ // and that block's index while it is open.
111
173
  let thinking = "";
174
+ let thinkingAt;
112
175
  const open = (at) => {
113
176
  const index = blocks++;
114
177
  blockOf.set(at ?? -1, index);
115
178
  return index;
116
179
  };
180
+ // The thinking block held open, sent as it ends: its whole text through the run's one redactor, then its stop.
181
+ const endThinking = () => {
182
+ if (thinkingAt === undefined)
183
+ return;
184
+ send({ type: "content_block_delta", index: thinkingAt, delta: { type: "thinking_delta", thinking: redact(thinking) } });
185
+ send({ type: "content_block_stop", index: thinkingAt });
186
+ thinkingAt = undefined;
187
+ };
188
+ // What the model wrote that this translation held back when its request fails (a thinking block before its end; a
189
+ // text-tools reply, read whole at its end, here the failed reply's parts): sent before the error, as a provider
190
+ // that streams it would have sent it. The model ran, and the proxy must not read the error as one before anything
191
+ // was generated (a refusal at $0): what it wrote shows it did. A text-tools reply that began with no part pi-ai
192
+ // kept goes as an empty text block, which still shows the model began.
193
+ const sendHeld = (reply) => {
194
+ endThinking();
195
+ if (!reply?.began)
196
+ return;
197
+ const parts = reply.message.content ?? [];
198
+ const thought = parts.filter((each) => each.type === "thinking").map((each) => each.thinking ?? "").join("");
199
+ const text = parts.filter((each) => each.type === "text").map((each) => each.text ?? "").join("");
200
+ if (thought) {
201
+ const index = blocks++;
202
+ send({ type: "content_block_start", index, content_block: { type: "thinking", thinking: "", signature: "" } });
203
+ send({ type: "content_block_delta", index, delta: { type: "thinking_delta", thinking: redact(thought) } });
204
+ send({ type: "content_block_stop", index });
205
+ }
206
+ if (text || !thought) {
207
+ const index = blocks++;
208
+ send({ type: "content_block_start", index, content_block: { type: "text", text: "" } });
209
+ if (text)
210
+ send({ type: "content_block_delta", index, delta: { type: "text_delta", text } });
211
+ send({ type: "content_block_stop", index });
212
+ }
213
+ };
117
214
  try {
118
215
  for await (const event of asText ? [] : events) {
119
216
  const at = event.contentIndex;
@@ -121,7 +218,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
121
218
  send({ type: "content_block_start", index: open(at), content_block: { type: "text", text: "" } });
122
219
  else if (event.type === "thinking_start") {
123
220
  thinking = "";
124
- send({ type: "content_block_start", index: open(at), content_block: { type: "thinking", thinking: "", signature: "" } });
221
+ thinkingAt = open(at);
222
+ send({ type: "content_block_start", index: thinkingAt, content_block: { type: "thinking", thinking: "", signature: "" } });
125
223
  }
126
224
  else if (event.type === "thinking_delta")
127
225
  thinking += event.delta ?? "";
@@ -129,9 +227,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
129
227
  // The whole thinking at its end, through the run's one redactor, in one delta: a held key the model quoted is
130
228
  // cut before pi's session journals it even where it spans two deltas (a cut per delta could miss a key split
131
229
  // across them).
132
- const index = blockOf.get(at ?? -1);
133
- send({ type: "content_block_delta", index, delta: { type: "thinking_delta", thinking: redact(thinking) } });
134
- send({ type: "content_block_stop", index });
230
+ thinkingAt = blockOf.get(at ?? -1);
231
+ endThinking();
135
232
  }
136
233
  else if (event.type === "text_delta")
137
234
  send({ type: "content_block_delta", index: blockOf.get(at ?? -1), delta: { type: "text_delta", text: event.delta ?? "" } });
@@ -163,11 +260,13 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
163
260
  else if (event.type === "done" || event.type === "error") {
164
261
  const message = (event.type === "done" ? event.message : event.error) ?? {};
165
262
  if (event.type === "error") {
166
- sendError(redact(message.errorMessage ?? event.reason ?? "the model's request failed"));
263
+ sendHeld();
264
+ sendError(redact(message.errorMessage ?? event.reason ?? "the model's request failed"), message.usage, reportedOf(message.usage));
167
265
  break;
168
266
  }
169
267
  const used = message.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
170
- send({ type: "message_delta", delta: { stop_reason: stopReasonOf(event.reason ?? message.stopReason), stop_sequence: null }, usage: { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead, cache_creation_input_tokens: used.cacheWrite } });
268
+ const cost = reportedOf(message.usage);
269
+ send({ type: "message_delta", delta: { stop_reason: stopReasonOf(event.reason ?? message.stopReason), stop_sequence: null }, usage: { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead, cache_creation_input_tokens: used.cacheWrite, ...(cost === undefined ? {} : { cost }) } });
171
270
  send({ type: "message_stop" });
172
271
  }
173
272
  }
@@ -178,6 +277,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
178
277
  // left of it once the tries so far and the re-ask's own input, uncached, are paid.
179
278
  const tools = built.tools ?? [];
180
279
  const used = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
280
+ // The provider's cost of every try, summed while each stated one; unknown once one did not.
281
+ let reported = 0;
181
282
  const outputHeld = body.max_tokens ?? target.maxTokens;
182
283
  let heldUsd = 0;
183
284
  let spentUsd = 0;
@@ -185,12 +286,29 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
185
286
  let nextTokens = 0;
186
287
  for (let attempt = 1;; attempt++) {
187
288
  let again = false;
289
+ // Whether this try's reply began: any of its content's events (pi-ai's `start` is the request's own).
290
+ let began = false;
188
291
  for await (const event of replies) {
189
- if (event.type !== "done" && event.type !== "error")
292
+ if (event.type !== "done" && event.type !== "error") {
293
+ if (event.type !== "start")
294
+ began = true;
190
295
  continue;
296
+ }
191
297
  const message = (event.type === "done" ? event.message : event.error) ?? {};
192
298
  if (event.type === "error") {
193
- sendError(redact(message.errorMessage ?? event.reason ?? "the model's request failed"));
299
+ const wrote = began || (message.content ?? []).length > 0;
300
+ sendHeld({ began: wrote, message });
301
+ // The tries so far were paid, and this one's usage too: their sum, with their stated cost while each
302
+ // try that reported tokens stated one. A try that wrote and then failed with no usage and no cost ran at
303
+ // a cost nobody said: the sum of the tries before it would undercount the request, so none is sent
304
+ // and the request's total is unknown (the cap's hold covers every try).
305
+ const given = message.usage;
306
+ const own = reportedOf(given);
307
+ const said = given !== undefined && given.input + given.output + (given.cacheRead ?? 0) + (given.cacheWrite ?? 0) > 0;
308
+ const unsaid = wrote && !said && own === undefined;
309
+ const tokens = unsaid ? undefined : { input: used.input + (given?.input ?? 0), output: used.output + (given?.output ?? 0), cacheRead: used.cacheRead + (given?.cacheRead ?? 0), cacheWrite: used.cacheWrite + (given?.cacheWrite ?? 0) };
310
+ const cost = unsaid || reported === undefined || (said && own === undefined) ? undefined : reported + (own ?? 0);
311
+ sendError(redact(message.errorMessage ?? event.reason ?? "the model's request failed"), tokens, cost !== undefined && cost > 0 ? cost : undefined);
194
312
  break;
195
313
  }
196
314
  const given = message.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
@@ -199,6 +317,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
199
317
  used.output += part.output;
200
318
  used.cacheRead += part.cacheRead;
201
319
  used.cacheWrite += part.cacheWrite;
320
+ const cost = reportedOf(message.usage);
321
+ reported = reported === undefined || cost === undefined ? undefined : reported + cost;
202
322
  if (attempt === 1 && outputHeld !== undefined)
203
323
  heldUsd = priceOn(target, { ...part, output: outputHeld });
204
324
  spentUsd += priceOn(target, part);
@@ -236,7 +356,7 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
236
356
  send({ type: "content_block_stop", index });
237
357
  }
238
358
  const reason = read.calls.length ? "tool_use" : stopReasonOf(event.reason === "toolUse" ? "stop" : event.reason ?? message.stopReason);
239
- send({ type: "message_delta", delta: { stop_reason: reason, stop_sequence: null }, usage: { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead, cache_creation_input_tokens: used.cacheWrite } });
359
+ send({ type: "message_delta", delta: { stop_reason: reason, stop_sequence: null }, usage: { input_tokens: used.input, output_tokens: used.output, cache_read_input_tokens: used.cacheRead, cache_creation_input_tokens: used.cacheWrite, ...(reported === undefined ? {} : { cost: reported }) } });
240
360
  send({ type: "message_stop" });
241
361
  }
242
362
  if (!again)
@@ -246,6 +366,7 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
246
366
  }
247
367
  }
248
368
  catch (error) {
369
+ sendHeld();
249
370
  sendError(redact(error?.message ?? String(error)));
250
371
  }
251
372
  controller.close();
@@ -1,16 +1,18 @@
1
- import { type MonidPin } from "../monid.js";
1
+ import type { MonidPinBody } from "../store/index.js";
2
2
  import type { Workspace } from "../workspace/index.js";
3
3
  import type { ClaimMcp } from "./mcp-run.js";
4
4
  /** The run's monid endpoints, as the loop's catalog seam reads them. */
5
5
  export type ClaimMonid = Pick<ClaimMcp, "tools" | "catalogOf" | "priceOf">;
6
+ /** A template eval case's monid fake (template-eval.ts, `monid:` in its case.yaml): `unavailable`, monid unreachable. */
7
+ export type MonidFake = "unavailable";
6
8
  /** One host tool per endpoint of `pin`, on the claim's environment `env` (its key, and the tests' fake under faux), an
7
- * answer too long for the model filed in `work()`; undefined when the pin holds none. `runId` names the run in the log. */
8
- export declare function monidForClaim(pin: MonidPin | undefined, env: NodeJS.ProcessEnv, work: () => Workspace, runId?: string): ClaimMonid | undefined;
9
+ * answer too long for the model filed in `work()`; undefined when the pin holds none. `runId` names the run in the log;
10
+ * `capped`, whether the run has a spend cap now (its launch's, read at each call). `fake`: a template eval case's monid
11
+ * fake (AdapterSpecDeps.evalFakes), `unavailable`: each call goes as it does with monid unreachable, its price read
12
+ * first and failing, so it is never sent, and nothing is held or booked. */
13
+ export declare function monidForClaim(pin: MonidPinBody | undefined, env: NodeJS.ProcessEnv, work: () => Workspace, runId?: string, capped?: () => boolean, fake?: MonidFake): ClaimMonid | undefined;
9
14
  /** The claim's MCP with the run's monid endpoints beside it: the one catalog seam the loop reads (AdapterRunSpec.mcp).
10
15
  * Its credentials' hooks are MCP's alone, and so is the closure of a pinned tool's arguments (argumentsOf: the gate's
11
16
  * settings pins are on MCP tools; a monid endpoint's input is held to its pinned schema by the harness), and so is each
12
17
  * tool's effect (effectOf: Allow reads and the destructive confirm read an MCP tool's annotations; an endpoint has none). */
13
18
  export declare function withMonid(mcp: ClaimMcp | undefined, monid: ClaimMonid | undefined): ClaimMcp | undefined;
14
- /** What a subagent may be given for the grant `grant` (subagent.ts sessionNames): for a provider's wildcard, every endpoint
15
- * the revision's `pin` holds of that provider, by wire name; undefined for any other grant. */
16
- export declare function monidSessionNames(grant: string, pin: MonidPin | undefined): string[] | undefined;