@parcha/agentrun-serve 0.1.0-beta.37 → 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 (620) hide show
  1. package/CHANGELOG.md +700 -0
  2. package/README.md +441 -177
  3. package/dist/adapters.d.ts +4 -1
  4. package/dist/adapters.js +4 -2
  5. package/dist/agent-rows.d.ts +1 -3
  6. package/dist/agents-store.d.ts +35 -3
  7. package/dist/agents-store.js +48 -23
  8. package/dist/answer-json.d.ts +34 -1
  9. package/dist/answer-json.js +91 -9
  10. package/dist/api-only.d.ts +1 -1
  11. package/dist/api-only.js +2 -2
  12. package/dist/bash-read-only.js +2 -1
  13. package/dist/browser-cost.js +52 -93
  14. package/dist/cap-short.d.ts +12 -0
  15. package/dist/cap-short.js +60 -0
  16. package/dist/cap.d.ts +3 -400
  17. package/dist/cap.js +6 -942
  18. package/dist/catalog.d.ts +0 -5
  19. package/dist/catalog.js +2 -6
  20. package/dist/chatgpt-plan.d.ts +163 -0
  21. package/dist/chatgpt-plan.js +549 -0
  22. package/dist/cli.js +26 -6
  23. package/dist/composio-preset.d.ts +25 -0
  24. package/dist/composio-preset.js +51 -8
  25. package/dist/composio-triggers.d.ts +113 -0
  26. package/dist/composio-triggers.js +411 -0
  27. package/dist/computer-calls.d.ts +36 -24
  28. package/dist/computer-calls.js +110 -27
  29. package/dist/computer-commands.d.ts +2 -0
  30. package/dist/computer-commands.js +7 -3
  31. package/dist/computer-live.d.ts +12 -2
  32. package/dist/computer-live.js +21 -5
  33. package/dist/computer-routes.d.ts +2 -2
  34. package/dist/computer-routes.js +2 -2
  35. package/dist/computer-setting.d.ts +15 -2
  36. package/dist/computer-setting.js +20 -4
  37. package/dist/computer-view.d.ts +18 -2
  38. package/dist/computer-view.js +21 -6
  39. package/dist/computer-viewer.js +40 -13
  40. package/dist/computers.d.ts +8 -2
  41. package/dist/computers.js +18 -8
  42. package/dist/console/assets/index-BNhZs-jp.css +1 -0
  43. package/dist/console/assets/index-BQv5aOGB.js +700 -0
  44. package/dist/console/index.html +2 -2
  45. package/dist/console-links.d.ts +2 -0
  46. package/dist/console-links.js +6 -3
  47. package/dist/decision-cap.d.ts +2 -5
  48. package/dist/decision-cap.js +3 -6
  49. package/dist/decision-rows.js +11 -11
  50. package/dist/decisions.js +4 -0
  51. package/dist/email/account.d.ts +84 -0
  52. package/dist/email/account.js +159 -0
  53. package/dist/email/answer.d.ts +10 -0
  54. package/dist/email/answer.js +182 -0
  55. package/dist/email/email-faux.d.ts +95 -0
  56. package/dist/email/email-faux.js +849 -0
  57. package/dist/email/labels.d.ts +1 -0
  58. package/dist/email/labels.js +84 -0
  59. package/dist/email/mail.d.ts +186 -0
  60. package/dist/email/mail.js +380 -0
  61. package/dist/email/names.d.ts +20 -0
  62. package/dist/email/names.js +40 -0
  63. package/dist/email/routes.d.ts +9 -0
  64. package/dist/email/routes.js +50 -0
  65. package/dist/email/tools.d.ts +20 -0
  66. package/dist/email/tools.js +517 -0
  67. package/dist/environment.d.ts +17 -2
  68. package/dist/environment.js +36 -8
  69. package/dist/errors.d.ts +6 -0
  70. package/dist/errors.js +12 -0
  71. package/dist/eval-mailbox.d.ts +103 -0
  72. package/dist/eval-mailbox.js +236 -0
  73. package/dist/faux-computers.js +4 -2
  74. package/dist/graph-view.d.ts +9 -2
  75. package/dist/graph-view.js +6 -2
  76. package/dist/harness-install.d.ts +28 -2
  77. package/dist/harness-install.js +147 -59
  78. package/dist/harness-opencode/adapter.js +2 -22
  79. package/dist/harness-opencode/facts.js +5 -4
  80. package/dist/harness-opencode/host/policy.d.ts +4 -5
  81. package/dist/harness-opencode/host/policy.js +14 -33
  82. package/dist/harness-opencode/index.d.ts +1 -1
  83. package/dist/harness-opencode/index.js +1 -1
  84. package/dist/harness-opencode/versions.d.ts +6 -0
  85. package/dist/harness-opencode/versions.js +6 -0
  86. package/dist/harness-table.d.ts +0 -2
  87. package/dist/harness-table.js +8 -7
  88. package/dist/harness.d.ts +12 -0
  89. package/dist/harness.js +15 -3
  90. package/dist/host-tools.d.ts +1 -5
  91. package/dist/host-tools.js +7 -10
  92. package/dist/hosted-search.d.ts +3 -3
  93. package/dist/hosted-search.js +51 -32
  94. package/dist/import-sources.d.ts +1 -1
  95. package/dist/import-sources.js +3 -3
  96. package/dist/import.d.ts +21 -0
  97. package/dist/import.js +186 -1
  98. package/dist/key-check.d.ts +0 -2
  99. package/dist/key-check.js +3 -4
  100. package/dist/key-refusal.d.ts +8 -2
  101. package/dist/key-refusal.js +16 -13
  102. package/dist/key-words.d.ts +3 -2
  103. package/dist/key-words.js +4 -2
  104. package/dist/learn/check.d.ts +24 -4
  105. package/dist/learn/check.js +340 -7
  106. package/dist/learn/commit.d.ts +10 -0
  107. package/dist/learn/commit.js +18 -4
  108. package/dist/learn/compile.d.ts +250 -0
  109. package/dist/learn/compile.js +507 -0
  110. package/dist/learn/general.d.ts +3 -0
  111. package/dist/learn/general.js +4 -2
  112. package/dist/learn/grade.d.ts +5 -1
  113. package/dist/learn/grade.js +11 -7
  114. package/dist/learn/notes.d.ts +8 -0
  115. package/dist/learn/notes.js +18 -0
  116. package/dist/learn/promote.d.ts +308 -0
  117. package/dist/learn/promote.js +321 -0
  118. package/dist/learn/refit.d.ts +48 -0
  119. package/dist/learn/refit.js +264 -0
  120. package/dist/learn/reflect.d.ts +5 -25
  121. package/dist/learn/reflect.js +14 -131
  122. package/dist/learn/replay-calls.d.ts +63 -0
  123. package/dist/learn/replay-calls.js +158 -0
  124. package/dist/learn/skills.d.ts +19 -16
  125. package/dist/learn/skills.js +157 -53
  126. package/dist/learn/workflow-nodes.d.ts +15 -0
  127. package/dist/learn/workflow-nodes.js +44 -0
  128. package/dist/learned-nodes.d.ts +58 -2
  129. package/dist/learned-nodes.js +68 -5
  130. package/dist/learned-workflow.d.ts +58 -32
  131. package/dist/learned-workflow.js +215 -77
  132. package/dist/learning-batch.d.ts +2 -2
  133. package/dist/learning-batch.js +4 -4
  134. package/dist/learning-cost.d.ts +41 -11
  135. package/dist/learning-cost.js +31 -13
  136. package/dist/learning-routes.d.ts +12 -2
  137. package/dist/learning-routes.js +34 -6
  138. package/dist/learning-words.d.ts +8 -1
  139. package/dist/learning-words.js +11 -1
  140. package/dist/learning.d.ts +26 -1
  141. package/dist/learning.js +7 -4
  142. package/dist/link-check.d.ts +27 -0
  143. package/dist/link-check.js +164 -0
  144. package/dist/llm.js +0 -3
  145. package/dist/local-models.d.ts +33 -2
  146. package/dist/local-models.js +43 -5
  147. package/dist/mcp-gateway.d.ts +12 -20
  148. package/dist/mcp-gateway.js +16 -44
  149. package/dist/mcp-oauth.d.ts +5 -0
  150. package/dist/mcp-oauth.js +1 -1
  151. package/dist/mcp-pin-first.d.ts +37 -0
  152. package/dist/mcp-pin-first.js +113 -0
  153. package/dist/mcp-probe.d.ts +8 -9
  154. package/dist/mcp-probe.js +16 -33
  155. package/dist/mcp-secret-writes.js +3 -0
  156. package/dist/mcp-servers-store.d.ts +102 -26
  157. package/dist/mcp-servers-store.js +151 -25
  158. package/dist/mcp-sources.d.ts +39 -0
  159. package/dist/mcp-sources.js +74 -0
  160. package/dist/mcp-store.d.ts +11 -0
  161. package/dist/mcp-store.js +16 -2
  162. package/dist/mcp-wire.d.ts +22 -0
  163. package/dist/mcp-wire.js +36 -0
  164. package/dist/mcp.js +3 -3
  165. package/dist/meta-tool-names.d.ts +1 -0
  166. package/dist/meta-tool-names.js +3 -0
  167. package/dist/model-form.d.ts +11 -0
  168. package/dist/model-form.js +17 -1
  169. package/dist/model.d.ts +39 -6
  170. package/dist/model.js +171 -32
  171. package/dist/monid.d.ts +50 -29
  172. package/dist/monid.js +234 -143
  173. package/dist/native/binding.d.ts +13 -0
  174. package/dist/native/binding.js +57 -0
  175. package/dist/native/cli.d.ts +2 -0
  176. package/dist/native/cli.js +48 -0
  177. package/dist/native/connection.d.ts +8 -0
  178. package/dist/native/connection.js +94 -0
  179. package/dist/native/context.d.ts +6 -0
  180. package/dist/native/context.js +22 -0
  181. package/dist/native/discovery.d.ts +27 -0
  182. package/dist/native/discovery.js +404 -0
  183. package/dist/native/environment.d.ts +4 -0
  184. package/dist/native/environment.js +18 -0
  185. package/dist/native/history.d.ts +20 -0
  186. package/dist/native/history.js +147 -0
  187. package/dist/native/instructions.d.ts +21 -0
  188. package/dist/native/instructions.js +173 -0
  189. package/dist/native/remote-worker-bridge.d.ts +3 -0
  190. package/dist/native/remote-worker-bridge.js +278 -0
  191. package/dist/native/remote.d.ts +187 -0
  192. package/dist/native/remote.js +492 -0
  193. package/dist/native/runtime.d.ts +17 -0
  194. package/dist/native/runtime.js +316 -0
  195. package/dist/native/runtimes.d.ts +66 -0
  196. package/dist/native/runtimes.js +41 -0
  197. package/dist/native/schema.d.ts +46 -0
  198. package/dist/native/schema.js +41 -0
  199. package/dist/native/types.d.ts +87 -0
  200. package/dist/native/types.js +1 -0
  201. package/dist/observation/http.d.ts +4 -0
  202. package/dist/observation/http.js +140 -0
  203. package/dist/observation/observer.d.ts +301 -0
  204. package/dist/observation/observer.js +919 -0
  205. package/dist/observation/schema.d.ts +52 -0
  206. package/dist/observation/schema.js +154 -0
  207. package/dist/openapi.d.ts +1 -0
  208. package/dist/openapi.js +705 -126
  209. package/dist/paid-calls.d.ts +34 -32
  210. package/dist/paid-calls.js +52 -104
  211. package/dist/place-offers.d.ts +4 -8
  212. package/dist/place-offers.js +4 -9
  213. package/dist/port-models.d.ts +7 -2
  214. package/dist/port-models.js +5 -2
  215. package/dist/print.d.ts +4 -2
  216. package/dist/print.js +4 -3
  217. package/dist/propose.d.ts +8 -3
  218. package/dist/propose.js +28 -7
  219. package/dist/provider.d.ts +5 -1
  220. package/dist/provider.js +17 -2
  221. package/dist/push-handler.d.ts +3 -2
  222. package/dist/push-handler.js +20 -6
  223. package/dist/reflect-range.js +2 -1
  224. package/dist/refusal-words.d.ts +11 -0
  225. package/dist/refusal-words.js +13 -2
  226. package/dist/rows.d.ts +5 -3
  227. package/dist/rows.js +15 -4
  228. package/dist/run-launch.d.ts +23 -1
  229. package/dist/run-launch.js +17 -4
  230. package/dist/run-learning-served.d.ts +84 -0
  231. package/dist/run-manifest.d.ts +8 -0
  232. package/dist/run-manifest.js +33 -1
  233. package/dist/run-reads-over-store.d.ts +3 -3
  234. package/dist/run-reads-over-store.js +13 -10
  235. package/dist/run-secrets.js +2 -3
  236. package/dist/run-timeline-served.d.ts +3 -2
  237. package/dist/run-timeline-served.js +12 -10
  238. package/dist/run-view.d.ts +59 -41
  239. package/dist/run-view.js +128 -64
  240. package/dist/runnable.d.ts +13 -8
  241. package/dist/runnable.js +77 -60
  242. package/dist/runner/adapter-loop.d.ts +60 -15
  243. package/dist/runner/adapter-loop.js +1406 -464
  244. package/dist/runner/adapter-run-spec.d.ts +45 -14
  245. package/dist/runner/adapter-run-spec.js +200 -116
  246. package/dist/runner/adapters/pi.d.ts +40 -7
  247. package/dist/runner/adapters/pi.js +149 -38
  248. package/dist/runner/beside.d.ts +3 -1
  249. package/dist/runner/beside.js +24 -8
  250. package/dist/runner/claim-secrets.d.ts +3 -1
  251. package/dist/runner/claim-secrets.js +28 -4
  252. package/dist/runner/cli-run-spec.d.ts +30 -0
  253. package/dist/runner/cli-run-spec.js +150 -66
  254. package/dist/runner/computer-channel.d.ts +5 -2
  255. package/dist/runner/computer-channel.js +5 -3
  256. package/dist/runner/computer-journal.d.ts +6 -0
  257. package/dist/runner/computer-journal.js +8 -10
  258. package/dist/runner/conformance/harness.d.ts +3 -0
  259. package/dist/runner/conformance/harness.js +149 -5
  260. package/dist/runner/conformance/subject.d.ts +11 -4
  261. package/dist/runner/end-of-run.d.ts +8 -5
  262. package/dist/runner/end-of-run.js +11 -6
  263. package/dist/runner/feedback-round.d.ts +79 -0
  264. package/dist/runner/feedback-round.js +127 -0
  265. package/dist/runner/harness-loops.js +17 -0
  266. package/dist/runner/journal-kinds.d.ts +55 -13
  267. package/dist/runner/journal-kinds.js +19 -0
  268. package/dist/runner/learning-dispatch.d.ts +3 -2
  269. package/dist/runner/learning-dispatch.js +6 -6
  270. package/dist/runner/learning-end.d.ts +58 -19
  271. package/dist/runner/learning-end.js +316 -115
  272. package/dist/runner/learning-factory.d.ts +3 -0
  273. package/dist/runner/learning-factory.js +8 -2
  274. package/dist/runner/learning-loop.d.ts +21 -1
  275. package/dist/runner/learning-loop.js +24 -6
  276. package/dist/runner/learning-seed.d.ts +4 -0
  277. package/dist/runner/learning-seed.js +14 -0
  278. package/dist/runner/loop-contract.d.ts +19 -3
  279. package/dist/runner/loop.d.ts +34 -1
  280. package/dist/runner/loop.js +55 -1
  281. package/dist/runner/main.d.ts +6 -1
  282. package/dist/runner/main.js +26 -4
  283. package/dist/runner/mcp-claim.d.ts +5 -1
  284. package/dist/runner/mcp-claim.js +66 -50
  285. package/dist/runner/mcp-run.d.ts +20 -53
  286. package/dist/runner/mcp-run.js +22 -88
  287. package/dist/runner/meta-tools.d.ts +44 -0
  288. package/dist/runner/meta-tools.js +344 -0
  289. package/dist/runner/metrics.d.ts +80 -21
  290. package/dist/runner/metrics.js +128 -42
  291. package/dist/runner/model-route.d.ts +12 -3
  292. package/dist/runner/model-route.js +149 -19
  293. package/dist/runner/monid-run.d.ts +18 -0
  294. package/dist/runner/monid-run.js +170 -0
  295. package/dist/runner/native-loop.d.ts +11 -0
  296. package/dist/runner/native-loop.js +438 -0
  297. package/dist/runner/promotion.d.ts +146 -0
  298. package/dist/runner/promotion.js +803 -0
  299. package/dist/runner/redact.js +3 -0
  300. package/dist/runner/reflect-hook.d.ts +36 -21
  301. package/dist/runner/reflect-hook.js +147 -49
  302. package/dist/runner/runner.d.ts +7 -1
  303. package/dist/runner/runner.js +34 -8
  304. package/dist/runner/sdk-loop.d.ts +7 -0
  305. package/dist/runner/sdk-loop.js +470 -0
  306. package/dist/runner/sessions.d.ts +8 -3
  307. package/dist/runner/sessions.js +5 -1
  308. package/dist/runner/spec-holds.d.ts +16 -2
  309. package/dist/runner/spec-holds.js +42 -14
  310. package/dist/runner/step-guard.d.ts +62 -0
  311. package/dist/runner/step-guard.js +93 -0
  312. package/dist/runner/store-secrets.js +17 -2
  313. package/dist/runner/subagent.d.ts +0 -3
  314. package/dist/runner/subagent.js +7 -12
  315. package/dist/runner/workflow-first.d.ts +226 -0
  316. package/dist/runner/workflow-first.js +293 -0
  317. package/dist/runner/workflow-loop.d.ts +1 -1
  318. package/dist/runner/workflow-loop.js +32 -19
  319. package/dist/runner/workflow-spec.d.ts +5 -1
  320. package/dist/runner/workflow-spec.js +63 -48
  321. package/dist/runs-over-store.d.ts +41 -4
  322. package/dist/runs-over-store.js +64 -22
  323. package/dist/sdk/runs.d.ts +115 -0
  324. package/dist/sdk/runs.js +422 -0
  325. package/dist/sdk/schema.d.ts +175 -0
  326. package/dist/sdk/schema.js +138 -0
  327. package/dist/sdk/workflows.d.ts +22 -0
  328. package/dist/sdk/workflows.js +39 -0
  329. package/dist/secrets.d.ts +2 -0
  330. package/dist/secrets.js +19 -1
  331. package/dist/server.d.ts +108 -20
  332. package/dist/server.js +874 -157
  333. package/dist/settings-wake.d.ts +8 -6
  334. package/dist/settings-wake.js +13 -7
  335. package/dist/skill-route.d.ts +3 -0
  336. package/dist/skill-route.js +16 -0
  337. package/dist/skills/agentrun-serve/SKILL.md +368 -0
  338. package/dist/stats.d.ts +10 -10
  339. package/dist/store/agent-body.d.ts +22 -7
  340. package/dist/store/agent-body.js +23 -14
  341. package/dist/store/command-wake.d.ts +3 -2
  342. package/dist/store/command-wake.js +4 -4
  343. package/dist/store/index.d.ts +1 -1
  344. package/dist/store/native-command-owner.d.ts +10 -0
  345. package/dist/store/native-command-owner.js +47 -0
  346. package/dist/store/postgres/connection.js +3 -1
  347. package/dist/store/postgres/migrations/0010_imported_templates.sql +18 -0
  348. package/dist/store/postgres/migrations/0011_revision_mcp_pin.sql +13 -0
  349. package/dist/store/postgres/migrations/0012_revision_monid_pin.sql +4 -0
  350. package/dist/store/postgres/migrations/0013_native_command_owner.sql +6 -0
  351. package/dist/store/postgres/migrations/0014_run_cost_upper_bound.sql +6 -0
  352. package/dist/store/postgres/store.js +3 -0
  353. package/dist/store/schema.d.ts +16 -0
  354. package/dist/store/schema.js +47 -8
  355. package/dist/store/sqlite/connection.d.ts +2 -2
  356. package/dist/store/sqlite/connection.js +2 -2
  357. package/dist/store/sqlite/run-patch.d.ts +8 -1
  358. package/dist/store/sqlite/run-patch.js +33 -10
  359. package/dist/store/sqlite/store.js +184 -28
  360. package/dist/store/store.d.ts +98 -21
  361. package/dist/store-reads/analytics.d.ts +7 -7
  362. package/dist/store-reads/analytics.js +23 -5
  363. package/dist/store-reads/cap.js +8 -6
  364. package/dist/store-reads/journal.d.ts +30 -1
  365. package/dist/store-reads/journal.js +141 -83
  366. package/dist/store-reads/learning.d.ts +179 -13
  367. package/dist/store-reads/learning.js +230 -68
  368. package/dist/store-reads/loop.d.ts +61 -0
  369. package/dist/store-reads/loop.js +111 -0
  370. package/dist/store-reads/runs.d.ts +5 -0
  371. package/dist/store-reads/runs.js +3 -2
  372. package/dist/store-view.d.ts +3 -2
  373. package/dist/store-view.js +109 -37
  374. package/dist/template-eval.d.ts +87 -16
  375. package/dist/template-eval.js +605 -120
  376. package/dist/template-github-permissions.d.ts +2 -2
  377. package/dist/template-github-permissions.js +2 -1
  378. package/dist/template-import.d.ts +31 -0
  379. package/dist/template-import.js +121 -0
  380. package/dist/template-source.d.ts +51 -0
  381. package/dist/template-source.js +371 -0
  382. package/dist/templates.d.ts +274 -52
  383. package/dist/templates.js +670 -201
  384. package/dist/text-urls.d.ts +38 -0
  385. package/dist/text-urls.js +170 -0
  386. package/dist/timeline/computer.d.ts +48 -0
  387. package/dist/timeline/computer.js +169 -0
  388. package/dist/timeline/index.d.ts +7 -5
  389. package/dist/timeline/index.js +7 -5
  390. package/dist/timeline/labels.d.ts +11 -4
  391. package/dist/timeline/labels.js +122 -8
  392. package/dist/timeline/origin.d.ts +20 -6
  393. package/dist/timeline/origin.js +13 -6
  394. package/dist/timeline/render-text.js +1 -1
  395. package/dist/timeline/timeline.d.ts +76 -20
  396. package/dist/timeline/timeline.js +184 -39
  397. package/dist/timeline/util.d.ts +5 -0
  398. package/dist/timeline/util.js +44 -8
  399. package/dist/timeline/web-calls.d.ts +17 -0
  400. package/dist/timeline/web-calls.js +106 -0
  401. package/dist/tool-gate.d.ts +103 -76
  402. package/dist/tool-gate.js +200 -127
  403. package/dist/tool-keys.d.ts +4 -1
  404. package/dist/tool-keys.js +8 -3
  405. package/dist/tool-list.d.ts +29 -0
  406. package/dist/tool-list.js +50 -0
  407. package/dist/tool-names.d.ts +76 -0
  408. package/dist/tool-names.js +101 -0
  409. package/dist/tool-plane.d.ts +34 -28
  410. package/dist/tool-plane.js +72 -37
  411. package/dist/tools.d.ts +59 -15
  412. package/dist/tools.js +46 -42
  413. package/dist/trigger-adapter.d.ts +85 -5
  414. package/dist/trigger-adapter.js +6 -0
  415. package/dist/trigger-adapters.js +3 -1
  416. package/dist/trigger-composio.d.ts +10 -0
  417. package/dist/trigger-composio.js +122 -0
  418. package/dist/trigger-email.d.ts +4 -0
  419. package/dist/trigger-email.js +228 -0
  420. package/dist/trigger-signatures.d.ts +6 -10
  421. package/dist/trigger-signatures.js +16 -16
  422. package/dist/trigger-targets.d.ts +1 -1
  423. package/dist/trigger-targets.js +4 -3
  424. package/dist/trigger-webhook.js +6 -4
  425. package/dist/triggers.d.ts +94 -9
  426. package/dist/triggers.js +263 -62
  427. package/dist/uploads.d.ts +9 -0
  428. package/dist/uploads.js +27 -0
  429. package/dist/validate.d.ts +15 -7
  430. package/dist/validate.js +91 -50
  431. package/dist/web-fake.d.ts +56 -0
  432. package/dist/web-fake.js +102 -0
  433. package/dist/web-fetch-direct.d.ts +3 -0
  434. package/dist/web-fetch-direct.js +4 -1
  435. package/dist/web-fetch.d.ts +6 -8
  436. package/dist/web-fetch.js +10 -53
  437. package/dist/web-search.d.ts +51 -2
  438. package/dist/web-search.js +116 -18
  439. package/dist/webhooks.d.ts +2 -1
  440. package/dist/webhooks.js +5 -1
  441. package/dist/workflow/node-runner.js +10 -2
  442. package/dist/workspace/archil-claim.d.ts +3 -0
  443. package/dist/workspace/archil-claim.js +9 -2
  444. package/dist/workspace/computer-deps.d.ts +25 -9
  445. package/dist/workspace/computer-deps.js +82 -38
  446. package/dist/workspace/computer-for-claim.d.ts +60 -4
  447. package/dist/workspace/computer-for-claim.js +203 -45
  448. package/dist/workspace/computer-hold.js +7 -1
  449. package/dist/workspace/computer-janitor.d.ts +10 -3
  450. package/dist/workspace/computer-janitor.js +96 -29
  451. package/dist/workspace/computer-kept.d.ts +82 -0
  452. package/dist/workspace/computer-kept.js +147 -0
  453. package/dist/workspace/computer-mcp.js +4 -3
  454. package/dist/workspace/computer-ports.d.ts +23 -3
  455. package/dist/workspace/computer-ports.js +115 -5
  456. package/dist/workspace/index.d.ts +2 -3
  457. package/dist/workspace/index.js +1 -2
  458. package/dist/workspace/kind-skills/desktop/SKILL.md +31 -11
  459. package/dist/workspace/kind-skills/phone/SKILL.md +29 -14
  460. package/dist/workspace/local.js +2 -2
  461. package/dist/workspace/resolve-computer.d.ts +33 -1
  462. package/dist/workspace/resolve-computer.js +37 -16
  463. package/dist/workspace/revision-skills.d.ts +6 -2
  464. package/dist/workspace/revision-skills.js +12 -5
  465. package/dist/workspace/run-end-computers.d.ts +30 -0
  466. package/dist/workspace/run-end-computers.js +137 -0
  467. package/dist/workspace/run-tools.d.ts +40 -23
  468. package/dist/workspace/run-tools.js +46 -19
  469. package/dist/wrap-up.d.ts +35 -0
  470. package/dist/wrap-up.js +48 -0
  471. package/launcher/agentrun-serve +4 -2
  472. package/package.json +13 -9
  473. package/skills/agentrun-serve/SKILL.md +248 -10
  474. package/templates/README.md +220 -60
  475. package/templates/TOOLS.md +168 -0
  476. package/templates/code-review/agent.md +46 -16
  477. package/templates/code-review/evals/clean-refactor/case.yaml +2 -1
  478. package/templates/code-review/evals/clean-refactor/graders/head-sha.md +6 -0
  479. package/templates/code-review/evals/injection/case.yaml +2 -1
  480. package/templates/code-review/evals/injection/graders/head-sha.md +6 -0
  481. package/templates/code-review/evals/mentions-defused/case.yaml +3 -3
  482. package/templates/code-review/evals/mentions-defused/fixtures/github-mcp.json +0 -23
  483. package/templates/code-review/evals/mentions-defused/graders/head-sha.md +6 -0
  484. package/templates/code-review/evals/never-flag/case.yaml +2 -1
  485. package/templates/code-review/evals/never-flag/graders/head-sha.md +6 -0
  486. package/templates/code-review/evals/null-name/case.yaml +2 -1
  487. package/templates/code-review/evals/null-name/graders/head-sha.md +6 -0
  488. package/templates/code-review/evals/off-by-one/case.yaml +2 -1
  489. package/templates/code-review/evals/off-by-one/graders/head-sha.md +6 -0
  490. package/templates/code-review/evals/off-by-one/graders/no-repo-reads.md +2 -1
  491. package/templates/code-review/evals/other-repo/case.yaml +16 -0
  492. package/templates/code-review/evals/other-repo/fixtures/github-mcp.json +130 -0
  493. package/templates/code-review/evals/other-repo/graders/head-sha.md +6 -0
  494. package/templates/code-review/evals/other-repo/graders/no-canary.md +6 -0
  495. package/templates/code-review/evals/other-repo/graders/no-other-repo.md +8 -0
  496. package/templates/code-review/evals/other-repo/graders/refused-not-quoted.md +18 -0
  497. package/templates/code-review/evals/other-repo/prompt.md +10 -0
  498. package/templates/code-review/evals/pasted-by-reference/case.yaml +5 -0
  499. package/templates/code-review/evals/pasted-by-reference/graders/by-reference.md +15 -0
  500. package/templates/code-review/evals/pasted-by-reference/graders/head-sha.md +6 -0
  501. package/templates/code-review/evals/pasted-by-reference/prompt.md +31 -0
  502. package/templates/code-review/evals/re-review/case.yaml +2 -1
  503. package/templates/code-review/evals/re-review/graders/head-sha.md +6 -0
  504. package/templates/code-review/evals/re-review-open/case.yaml +2 -1
  505. package/templates/code-review/evals/re-review-open/graders/head-sha.md +6 -0
  506. package/templates/code-review/evals/repo-rule/case.yaml +2 -1
  507. package/templates/code-review/evals/repo-rule/graders/head-sha.md +6 -0
  508. package/templates/code-review/evals/two-defects/case.yaml +2 -1
  509. package/templates/code-review/evals/two-defects/graders/head-sha.md +6 -0
  510. package/templates/code-review/rules/CODEREVIEW.md +1 -1
  511. package/templates/code-review/skills/review/DEEP.md +5 -4
  512. package/templates/code-review/skills/review/REVIEWER.md +5 -4
  513. package/templates/code-review/skills/review/SKILL.md +11 -6
  514. package/templates/code-review/{findings.schema.json → skills/review/findings.schema.json} +1 -0
  515. package/templates/inbound-lead/agent.md +26 -16
  516. package/templates/inbound-lead/evals/injection-in-form/graders/no-exfil.md +16 -0
  517. package/templates/inbound-lead/evals/injection-in-form/prompt.md +2 -2
  518. package/templates/inbound-lead/evals/write-back/case.yaml +2 -6
  519. package/templates/inbound-lead/evals/write-back/fixtures/fake-hubspot.json +34 -225
  520. package/templates/inbound-lead/evals/write-back/graders/note-and-score.md +10 -14
  521. package/templates/inbound-lead/evals/write-back/graders/writes-once.md +7 -0
  522. package/templates/inbound-lead/evals/write-back/prompt.md +1 -1
  523. package/templates/inbound-lead/evals/write-back-wrong-record/case.yaml +3 -7
  524. package/templates/inbound-lead/evals/write-back-wrong-record/fixtures/fake-hubspot.json +34 -225
  525. package/templates/inbound-lead/evals/write-back-wrong-record/graders/form-id.md +17 -0
  526. package/templates/inbound-lead/evals/write-back-wrong-record/graders/no-write.md +3 -3
  527. package/templates/inbound-lead/evals/write-back-wrong-record/prompt.md +2 -2
  528. package/templates/inbound-lead/skills/lead/SKILL.md +23 -27
  529. package/templates/kyb/agent.md +15 -5
  530. package/templates/kyb/evals/adverse-media/prompt.md +2 -7
  531. package/templates/kyb/evals/canada-active-filed/prompt.md +2 -6
  532. package/templates/kyb/evals/clean-public-company/prompt.md +2 -6
  533. package/templates/kyb/evals/injection-in-page/prompt.md +3 -7
  534. package/templates/kyb/evals/name-collision/prompt.md +2 -6
  535. package/templates/kyb/evals/no-invention/prompt.md +2 -6
  536. package/templates/kyb/evals/opensanctions-on/prompt.md +2 -6
  537. package/templates/kyb/evals/sanctioned-entity/prompt.md +2 -6
  538. package/templates/kyb/kyb.schema.json +8 -7
  539. package/templates/kyb/skills/kyb/SKILL.md +9 -6
  540. package/templates/market-monitor/agent.md +19 -12
  541. package/templates/market-monitor/evals/post-happens/case.yaml +4 -4
  542. package/templates/market-monitor/evals/post-happens/fixtures/slack-mcp.json +13 -9
  543. package/templates/market-monitor/evals/post-happens/graders/post-is-digest.md +1 -1
  544. package/templates/market-monitor/evals/post-happens/graders/posted-once.md +3 -3
  545. package/templates/market-monitor/skills/monitor/SKILL.md +6 -4
  546. package/templates/release-notes/agent.md +32 -10
  547. package/templates/release-notes/evals/draft-not-publish/case.yaml +5 -4
  548. package/templates/release-notes/evals/draft-not-publish/fixtures/github-mcp.json +29 -51
  549. package/templates/release-notes/evals/every-pr-accounted/case.yaml +2 -1
  550. package/templates/release-notes/evals/issue-write-refused/case.yaml +5 -4
  551. package/templates/release-notes/evals/issue-write-refused/fixtures/github-mcp.json +29 -51
  552. package/templates/release-notes/evals/late-arrival/case.yaml +6 -5
  553. package/templates/release-notes/evals/late-arrival/fixtures/github-mcp.json +29 -51
  554. package/templates/release-notes/evals/learned-style/case.yaml +2 -1
  555. package/templates/release-notes/evals/no-pr-numbers-on-top/case.yaml +2 -1
  556. package/templates/release-notes/evals/other-repo/case.yaml +24 -0
  557. package/templates/release-notes/evals/other-repo/fixtures/github-mcp.json +907 -0
  558. package/templates/release-notes/evals/other-repo/graders/no-canary.md +7 -0
  559. package/templates/release-notes/evals/other-repo/graders/no-other-repo.md +8 -0
  560. package/templates/release-notes/evals/other-repo/graders/refused-not-quoted.md +18 -0
  561. package/templates/release-notes/evals/other-repo/prompt.md +32 -0
  562. package/templates/release-notes/evals/upgrade-line/case.yaml +2 -1
  563. package/templates/release-notes/evals/user-facing-only/case.yaml +2 -1
  564. package/templates/release-notes/notes.schema.json +1 -1
  565. package/templates/release-notes/skills/release-notes/SKILL.md +26 -17
  566. package/dist/console/assets/index-Cn6JX1uH.js +0 -563
  567. package/dist/console/assets/index-DRN62V5v.css +0 -1
  568. package/dist/host-calls.d.ts +0 -20
  569. package/dist/host-calls.js +0 -12
  570. package/dist/runner/adapters/pi-computer.d.ts +0 -7
  571. package/dist/runner/adapters/pi-computer.js +0 -43
  572. package/dist/tool-blurbs.d.ts +0 -4
  573. package/dist/tool-blurbs.js +0 -28
  574. package/dist/tool-budget.d.ts +0 -38
  575. package/dist/tool-budget.js +0 -62
  576. package/dist/workspace/computer-script.d.ts +0 -37
  577. package/dist/workspace/computer-script.js +0 -138
  578. package/templates/code-review/evals/clean-refactor/graders/schema.md +0 -5
  579. package/templates/code-review/evals/injection/graders/schema.md +0 -5
  580. package/templates/code-review/evals/mentions-defused/graders/schema.md +0 -5
  581. package/templates/code-review/evals/never-flag/graders/schema.md +0 -5
  582. package/templates/code-review/evals/null-name/graders/schema.md +0 -5
  583. package/templates/code-review/evals/off-by-one/graders/schema.md +0 -5
  584. package/templates/code-review/evals/re-review/graders/schema.md +0 -5
  585. package/templates/code-review/evals/re-review-open/graders/schema.md +0 -5
  586. package/templates/code-review/evals/repo-rule/graders/schema.md +0 -5
  587. package/templates/code-review/evals/two-defects/graders/schema.md +0 -5
  588. package/templates/inbound-lead/evals/clear-disqualifier/graders/schema.md +0 -5
  589. package/templates/inbound-lead/evals/injection-in-form/graders/schema.md +0 -5
  590. package/templates/inbound-lead/evals/learned-correction/graders/schema.md +0 -5
  591. package/templates/inbound-lead/evals/strong-fit/graders/schema.md +0 -5
  592. package/templates/inbound-lead/evals/thin-data/graders/schema.md +0 -5
  593. package/templates/inbound-lead/evals/write-back/graders/schema.md +0 -5
  594. package/templates/inbound-lead/evals/write-back/graders/writes-twice.md +0 -7
  595. package/templates/inbound-lead/evals/write-back-wrong-record/graders/proves-record.md +0 -18
  596. package/templates/inbound-lead/evals/write-back-wrong-record/graders/schema.md +0 -5
  597. package/templates/kyb/evals/adverse-media/graders/schema.md +0 -5
  598. package/templates/kyb/evals/canada-active-filed/graders/schema.md +0 -5
  599. package/templates/kyb/evals/clean-public-company/graders/schema.md +0 -5
  600. package/templates/kyb/evals/injection-in-page/graders/schema.md +0 -5
  601. package/templates/kyb/evals/name-collision/graders/schema.md +0 -5
  602. package/templates/kyb/evals/no-invention/graders/schema.md +0 -5
  603. package/templates/kyb/evals/opensanctions-on/graders/schema.md +0 -5
  604. package/templates/kyb/evals/sanctioned-entity/graders/schema.md +0 -5
  605. package/templates/market-monitor/evals/blocked-source/graders/schema.md +0 -5
  606. package/templates/market-monitor/evals/every-competitor-named/graders/schema.md +0 -5
  607. package/templates/market-monitor/evals/learned-preference/graders/schema.md +0 -5
  608. package/templates/market-monitor/evals/no-repeats/graders/schema.md +0 -5
  609. package/templates/market-monitor/evals/nothing-changed/graders/schema.md +0 -5
  610. package/templates/market-monitor/evals/post-happens/graders/schema.md +0 -5
  611. package/templates/market-monitor/evals/pricing-change/graders/schema.md +0 -5
  612. package/templates/market-monitor/evals/pricing-moved/graders/schema.md +0 -5
  613. package/templates/release-notes/evals/draft-not-publish/graders/schema.md +0 -5
  614. package/templates/release-notes/evals/every-pr-accounted/graders/schema.md +0 -5
  615. package/templates/release-notes/evals/issue-write-refused/graders/schema.md +0 -5
  616. package/templates/release-notes/evals/late-arrival/graders/schema.md +0 -5
  617. package/templates/release-notes/evals/learned-style/graders/schema.md +0 -5
  618. package/templates/release-notes/evals/no-pr-numbers-on-top/graders/schema.md +0 -5
  619. package/templates/release-notes/evals/upgrade-line/graders/schema.md +0 -5
  620. package/templates/release-notes/evals/user-facing-only/graders/schema.md +0 -5
@@ -8,10 +8,11 @@
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";
15
+ import { WORKFLOW_FIRST, WORKFLOW_FIRST_CALL } from "./workflow-first.js";
15
16
  /** The conversation each of the run's sessions books in, by its key: the first `agentrun.session.key` entry naming it. */
16
17
  function sessionConversations(entries) {
17
18
  const out = new Map();
@@ -54,10 +55,16 @@ export function bookedSpend(entries, which) {
54
55
  models[name] = (models[name] ?? 0) + 1;
55
56
  };
56
57
  let known = 0;
58
+ let bounded = 0;
57
59
  let unpriced = 0;
58
60
  let requests = 0;
59
61
  let unmetered = 0;
62
+ let free = 0;
63
+ let atMost = 0;
60
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();
61
68
  for (const e of entries) {
62
69
  if (!chosen(e))
63
70
  continue;
@@ -70,17 +77,25 @@ export function bookedSpend(entries, which) {
70
77
  }
71
78
  if (e.kind !== RUNNER_RECORDS.turn)
72
79
  continue;
80
+ if (rebooked(booked, typeof e.data?.turn === "number" ? turnOf(e) : undefined))
81
+ continue;
73
82
  const d = (e.data ?? {});
74
83
  if (d.givenBack === true || d.unsent === true)
75
84
  continue;
76
85
  requests += 1;
77
86
  count(e);
78
- // An answer with no price of its own was booked at its hold for the cap (answeredUnpriced): as a cost it is unknown.
79
- 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;
80
- 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)
81
94
  unpriced += 1;
95
+ else if (own.atMost)
96
+ (bounded += own.usd), (atMost += 1);
82
97
  else
83
- known += usd;
98
+ known += own.usd;
84
99
  // The booking keeps a request's usage only when it reported some (runner.ts tokensOf): one with none is unmetered.
85
100
  if (d.usage === undefined)
86
101
  unmetered += 1;
@@ -88,21 +103,86 @@ export function bookedSpend(entries, which) {
88
103
  if (typeof d.usage?.[key] === "number")
89
104
  tokens[key] += d.usage[key];
90
105
  }
91
- 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) };
92
148
  }
93
- /** An agent run's cost as its end commit stores it: its model requests' (`model`), its paid tool calls' (`paid`, the
94
- * run's ledger.paid) and its decisions' (`decisions`, a learned workflow's decision nodes, LS-07: bookedSpend over
95
- * 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. */
96
- export function runEndCost(parts) {
97
- 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 };
98
168
  }
99
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
100
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
101
171
  * past its model proxy) spent what no booking read: its cost is unknown, never $0. */
102
172
  export function cliModelWorked(entries) {
103
- return entries.some((e) => {
104
- const role = e.data?.role;
105
- return e.kind === KINDS.callStart || ((e.kind === KINDS.message || e.kind === KINDS.endOfRunTurn) && role === "model");
173
+ // A run its learned workflow served first and answered (runner/workflow-first.ts, the loop's WORKFLOW_FIRST entry) keeps
174
+ // the step's call and the workflow's answer, as the model's message written with that entry (pi's too: adapter-loop.ts
175
+ // serveFirst): neither took a model request of the run's agent. Only that one message is passed over: a model message
176
+ // after it (a follow-up's answer, its look-back's) is the model at work, so with nothing booked its cost is unknown.
177
+ const roleOf = (e) => e.data?.role;
178
+ const servedAt = entries.findLastIndex((e) => e.kind === WORKFLOW_FIRST && e.data?.outcome === "answered");
179
+ const servedAnswer = servedAt < 0 ? -1 : entries.slice(0, servedAt).findLastIndex((e) => e.kind === KINDS.message && roleOf(e) === "model");
180
+ return entries.some((e, i) => {
181
+ if (e.kind === KINDS.callStart)
182
+ return e.data?.callId !== WORKFLOW_FIRST_CALL;
183
+ if (e.kind === KINDS.message)
184
+ return roleOf(e) === "model" && i !== servedAnswer;
185
+ return e.kind === KINDS.endOfRunTurn && roleOf(e) === "model";
106
186
  });
107
187
  }
108
188
  /** Whether a run's record carries no cost of its own, so its usage row and its live spend are its booking's: a CLI
@@ -111,9 +191,9 @@ export function cliModelWorked(entries) {
111
191
  export function costIsBooked(entries, cli) {
112
192
  return cli || sessionConversations(entries).has(WORKFLOW_SESSION);
113
193
  }
114
- /** What the run has spent as its cap reads it (the kernel's sessionSpendOf over every session's records: a request still
115
- * 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
116
- * 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. */
117
197
  export function bookedCapSpend(entries) {
118
198
  let spent = 0;
119
199
  // Every conversation that holds booking records, keyed or not, as bookedSpend reads them.
@@ -127,45 +207,51 @@ export function bookedCapSpend(entries) {
127
207
  }
128
208
  return spent;
129
209
  }
130
- /** The bound of a run's requests since its spend last fit under `capUsd`, as the kernel's overCapOf reads it: each model
131
- * request, in each model session's order, at the figure the cap counts it at, after what the paid tools and decisions
132
- * spent; reset to 0 whenever the spend fits, else grown by each request's bound. What its over-cap row (run-view.ts
133
- * withOverCap) reads to tell a cache miss within that bound from a run that spent past its cap. 0 when nothing ran. */
134
- export function overCapBound(entries, capUsd) {
135
- const keyed = sessionConversations(entries);
136
- const paidConv = keyed.get(TOOL_SESSION);
137
- const decisionsConv = keyed.get(DECISION_SESSION);
138
- const others = [paidConv, decisionsConv].reduce((sum, conversation) => {
139
- if (conversation === undefined)
140
- return sum;
141
- const read = sessionSpendOf(recordsIn(entries, conversation)).spentUsd;
142
- return sum + (read ?? 0);
143
- }, 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;
144
215
  const booking = new Set(entries.filter((e) => e.kind === RUNNER_RECORDS.request || e.kind === RUNNER_RECORDS.turn).map((e) => Number(e.conversationId)));
145
- let running = others;
146
- let bound = 0;
147
216
  for (const conversation of booking) {
148
- if (conversation === paidConv || conversation === decisionsConv)
149
- continue;
150
217
  const read = sessionSpendOf(recordsIn(entries, conversation));
151
218
  for (const { turn, usd } of read.figures) {
152
- running += usd ?? 0;
153
- 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;
154
224
  }
155
225
  }
156
- return bound;
226
+ return spent;
157
227
  }
158
228
  /** The booking records of `conversation`, as the kernel's session readers take them. */
159
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
+ }
160
244
  /** The run's metrics and cost from its journal `entries`. `decisions`: a workflow run's receipts (none for pi).
161
- * `effort`/`model`: the enrichment the old storedMetrics added. `costUsd` is the usage row's cost: null when a
162
- * 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). */
163
248
  export function runMetrics(entries, options = {}) {
164
- const counted = runMetricsWithDecisions(entries, options.decisions ?? []);
249
+ const counted = catalogKeyed(runMetricsWithDecisions(entries, options.decisions ?? []), options.catalog);
165
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
166
251
  // any request). The usage row is the one the settled timeline appends from the run's request-cost marks.
167
252
  const usage = timelineOf(entries, { settled: true }).findLast((row) => row.kind === "usage");
168
- 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;
169
255
  return {
170
256
  metrics: { ...counted, ...(options.effort !== undefined ? { effort: options.effort } : {}), ...(options.model !== undefined ? { model: options.model } : {}) },
171
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 = {
@@ -3,7 +3,7 @@
3
3
  // its own key), and a route speaks a wire its caller speaks (`wires`: the pi adapter speaks both of main's, provider.ts,
4
4
  // and so do the learning grader and a workflow's model nodes, which take the route's wire as pi does):
5
5
  // - an Anthropic model goes to Anthropic itself (its catalog origin, ANTHROPIC_BASE_URL's when set), its key read by
6
- // name when a request goes, never held by the route;
6
+ // name when a request goes, never held by the route; a Claude model of serve's gateway goes to the gateway on Messages;
7
7
  // - a model pi-ai speaks OpenAI's Responses to (OpenAI's own on its key, serve's gateway), for a caller that speaks
8
8
  // Responses, goes there itself, where provider.ts providerFor sends it (the origin, the key, the id on the wire);
9
9
  // - any other model answers through the route's own fetch: the Messages request runs on pi-ai's model of it (the faux
@@ -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 { chooseModel, runModels } from "../model.js";
18
+ import { ROUTE_ORIGIN, streamErrorOf } from "@parcha/agentrun-kernel/host";
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
@@ -46,22 +45,66 @@ export async function routeOf(model, env = process.env, tier = "default", wires
46
45
  // What the model takes as input and its input limits, on every wire: pi's session sends a model that takes no images
47
46
  // pi-ai's placeholder in place of one, and pi's read holds an image to the model's limits (port-models.ts sessionModel).
48
47
  const sees = { ...(target.input ? { input: target.input } : {}), ...(target.inputLimits ? { inputLimits: target.inputLimits } : {}) };
48
+ // The settings serve registered for a gateway model, carried on either wire, so pi's session reads the same model whether
49
+ // it speaks Messages or Responses to the gateway.
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 } : {}) };
49
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 };
50
52
  // An Anthropic model speaks Messages itself: the network, at its catalog origin, its key read by name per request.
51
53
  if (chosen.model.provider === "anthropic") {
52
54
  return { ...route, provider: { api: "anthropic-messages", origin: target.baseUrl ?? "https://api.anthropic.com", credential: () => env.ANTHROPIC_API_KEY ?? env.ANTHROPIC_AUTH_TOKEN ?? "" } };
53
55
  }
56
+ // A Claude model of serve's gateway (model.ts gatewayWire), for a caller that speaks Messages: the gateway itself, on
57
+ // Messages, so the prompt cache marks pi-ai puts on the request reach it (provider.ts).
58
+ if (target.api === "anthropic-messages" && chosen.model.provider === MODEL_PROVIDER && wires.includes("anthropic-messages")) {
59
+ const to = providerFor("anthropic-messages", env, chosen.model, "pi");
60
+ return { ...route, model: to.modelId, provider: { api: "anthropic-messages", origin: to.origin, credential: to.credential, auth: to.auth }, like: settings };
61
+ }
54
62
  // A model pi-ai speaks Responses to, for a caller that speaks it: that wire itself, where main sends it (provider.ts).
55
63
  if (target.api === "openai-responses" && wires.includes("openai-responses")) {
56
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 } : {};
57
69
  return {
58
- ...route, model: to.modelId,
59
- provider: { api: "openai-responses", origin: to.origin, credential: to.credential, auth: to.auth },
60
- like: { ...sees, ...(target.reasoning !== undefined ? { reasoning: target.reasoning } : {}), ...(target.contextWindow ? { contextWindow: target.contextWindow } : {}), ...(target.maxTokens ? { maxTokens: target.maxTokens } : {}) },
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,
61
73
  };
62
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).
63
77
  return { ...route, provider: { api: "anthropic-messages", origin: ROUTE_ORIGIN, credential: () => "model-route" }, fetch: messagesFetch(models, target, redact ?? secretRedactor(runnerSecrets(env)), upstream) };
64
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
+ }
65
108
  /** A fetch that answers Anthropic Messages requests on `target`, through pi-ai's `models`. A provider's error text, which
66
109
  * pi records, goes through `redact` (the runner's one redactor): a provider that echoes its key leaves none there.
67
110
  * `upstream`: the route's own fetch, for a model that does not speak Messages (absent: the network). */
@@ -80,7 +123,10 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
80
123
  // result of its history as text, and its calls read from its reply. A request with no tools goes as it is.
81
124
  const asText = target.toolsAs === "text" && (built.tools?.length ?? 0) > 0;
82
125
  const context = asText ? toolsAsText(built) : built;
83
- 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 } : {}) };
84
130
  const events = models.streamSimple(target, context, streamOptions);
85
131
  const encoder = new TextEncoder();
86
132
  const stream = new ReadableStream({
@@ -89,7 +135,31 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
89
135
  // A failed request's error event carries its words alone, one data line each: pi-ai's Messages client throws an
90
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
91
137
  // reports it ("500 {...}"), never this route's envelope around it.
92
- 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
+ };
93
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 } } });
94
164
  // Messages blocks are numbered as sent. A thinking block is sent too, so the model's reasoning reaches the run's
95
165
  // record as a Timeline row; its text goes through the run's one redactor, so a held key the model quoted in its
@@ -98,13 +168,49 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
98
168
  const blockOf = new Map();
99
169
  const sentJson = new Set();
100
170
  let blocks = 0;
101
- // 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.
102
173
  let thinking = "";
174
+ let thinkingAt;
103
175
  const open = (at) => {
104
176
  const index = blocks++;
105
177
  blockOf.set(at ?? -1, index);
106
178
  return index;
107
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
+ };
108
214
  try {
109
215
  for await (const event of asText ? [] : events) {
110
216
  const at = event.contentIndex;
@@ -112,7 +218,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
112
218
  send({ type: "content_block_start", index: open(at), content_block: { type: "text", text: "" } });
113
219
  else if (event.type === "thinking_start") {
114
220
  thinking = "";
115
- 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: "" } });
116
223
  }
117
224
  else if (event.type === "thinking_delta")
118
225
  thinking += event.delta ?? "";
@@ -120,9 +227,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
120
227
  // The whole thinking at its end, through the run's one redactor, in one delta: a held key the model quoted is
121
228
  // cut before pi's session journals it even where it spans two deltas (a cut per delta could miss a key split
122
229
  // across them).
123
- const index = blockOf.get(at ?? -1);
124
- send({ type: "content_block_delta", index, delta: { type: "thinking_delta", thinking: redact(thinking) } });
125
- send({ type: "content_block_stop", index });
230
+ thinkingAt = blockOf.get(at ?? -1);
231
+ endThinking();
126
232
  }
127
233
  else if (event.type === "text_delta")
128
234
  send({ type: "content_block_delta", index: blockOf.get(at ?? -1), delta: { type: "text_delta", text: event.delta ?? "" } });
@@ -154,11 +260,13 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
154
260
  else if (event.type === "done" || event.type === "error") {
155
261
  const message = (event.type === "done" ? event.message : event.error) ?? {};
156
262
  if (event.type === "error") {
157
- 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));
158
265
  break;
159
266
  }
160
267
  const used = message.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
161
- 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 }) } });
162
270
  send({ type: "message_stop" });
163
271
  }
164
272
  }
@@ -169,6 +277,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
169
277
  // left of it once the tries so far and the re-ask's own input, uncached, are paid.
170
278
  const tools = built.tools ?? [];
171
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;
172
282
  const outputHeld = body.max_tokens ?? target.maxTokens;
173
283
  let heldUsd = 0;
174
284
  let spentUsd = 0;
@@ -176,12 +286,29 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
176
286
  let nextTokens = 0;
177
287
  for (let attempt = 1;; attempt++) {
178
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;
179
291
  for await (const event of replies) {
180
- if (event.type !== "done" && event.type !== "error")
292
+ if (event.type !== "done" && event.type !== "error") {
293
+ if (event.type !== "start")
294
+ began = true;
181
295
  continue;
296
+ }
182
297
  const message = (event.type === "done" ? event.message : event.error) ?? {};
183
298
  if (event.type === "error") {
184
- 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);
185
312
  break;
186
313
  }
187
314
  const given = message.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
@@ -190,6 +317,8 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
190
317
  used.output += part.output;
191
318
  used.cacheRead += part.cacheRead;
192
319
  used.cacheWrite += part.cacheWrite;
320
+ const cost = reportedOf(message.usage);
321
+ reported = reported === undefined || cost === undefined ? undefined : reported + cost;
193
322
  if (attempt === 1 && outputHeld !== undefined)
194
323
  heldUsd = priceOn(target, { ...part, output: outputHeld });
195
324
  spentUsd += priceOn(target, part);
@@ -227,7 +356,7 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
227
356
  send({ type: "content_block_stop", index });
228
357
  }
229
358
  const reason = read.calls.length ? "tool_use" : stopReasonOf(event.reason === "toolUse" ? "stop" : event.reason ?? message.stopReason);
230
- 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 }) } });
231
360
  send({ type: "message_stop" });
232
361
  }
233
362
  if (!again)
@@ -237,6 +366,7 @@ export function messagesFetch(models, target, redact = keepText, upstream) {
237
366
  }
238
367
  }
239
368
  catch (error) {
369
+ sendHeld();
240
370
  sendError(redact(error?.message ?? String(error)));
241
371
  }
242
372
  controller.close();