@tangle-network/agent-eval 1.0.22 → 1.0.24

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 (233) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-DU5InUT9.d.ts → agent-profile-DC_v4p1f.d.ts} +3 -3
  4. package/dist/{agent-profile-DU5InUT9.d.ts.map → agent-profile-DC_v4p1f.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +14 -14
  6. package/dist/analyst/index.js +9 -9
  7. package/dist/{analyze-runs-jLTRKuoK.js → analyze-runs-BCSHzqna.js} +2 -2
  8. package/dist/{analyze-runs-jLTRKuoK.js.map → analyze-runs-BCSHzqna.js.map} +1 -1
  9. package/dist/{analyze-runs-DYYe18Gw.d.ts → analyze-runs-DGr7mpC3.d.ts} +5 -5
  10. package/dist/{analyze-runs-DYYe18Gw.d.ts.map → analyze-runs-DGr7mpC3.d.ts.map} +1 -1
  11. package/dist/app-grade/index.d.ts +4 -4
  12. package/dist/app-grade/index.js +3 -3
  13. package/dist/{benchmark-command-DkUpd9Q6.js → benchmark-command-DRAHkn4D.js} +8 -9
  14. package/dist/{benchmark-command-DkUpd9Q6.js.map → benchmark-command-DRAHkn4D.js.map} +1 -1
  15. package/dist/benchmarks/index.d.ts +5 -5
  16. package/dist/benchmarks/index.js +3 -3
  17. package/dist/campaign/index.d.ts +7 -7
  18. package/dist/campaign/index.js +8 -8
  19. package/dist/{campaign-C2mmydmx.js → campaign-C9QC27C2.js} +12 -12
  20. package/dist/{campaign-C2mmydmx.js.map → campaign-C9QC27C2.js.map} +1 -1
  21. package/dist/{campaign-evidence-NtH29ctt.js → campaign-evidence-CVNKiK0q.js} +2 -2
  22. package/dist/{campaign-evidence-NtH29ctt.js.map → campaign-evidence-CVNKiK0q.js.map} +1 -1
  23. package/dist/{chat-client-Zz97O3NB.js → chat-client-9XLgWrQ7.js} +5 -3
  24. package/dist/chat-client-9XLgWrQ7.js.map +1 -0
  25. package/dist/{chat-json-call-Dgi7-RH-.js → chat-json-call-CaNO3k0A.js} +2 -2
  26. package/dist/{chat-json-call-Dgi7-RH-.js.map → chat-json-call-CaNO3k0A.js.map} +1 -1
  27. package/dist/cli.js +8 -8
  28. package/dist/{cluster-Cd0MRbr9.d.ts → cluster-CkzP4h3T.d.ts} +4 -2
  29. package/dist/{cluster-Cd0MRbr9.d.ts.map → cluster-CkzP4h3T.d.ts.map} +1 -1
  30. package/dist/{completion-verifier-DFyYFezn.js → completion-verifier-BYLOcQt7.js} +5 -4
  31. package/dist/completion-verifier-BYLOcQt7.js.map +1 -0
  32. package/dist/{completion-verifier-BEpsr3N4.d.ts → completion-verifier-CJVDPv2T.d.ts} +3 -2
  33. package/dist/{completion-verifier-BEpsr3N4.d.ts.map → completion-verifier-CJVDPv2T.d.ts.map} +1 -1
  34. package/dist/contract/index.d.ts +11 -11
  35. package/dist/contract/index.js +11 -13
  36. package/dist/contract/index.js.map +1 -1
  37. package/dist/{cost-ledger-DfhStGcZ.js → cost-ledger-1CwUnVOd.js} +145 -3
  38. package/dist/cost-ledger-1CwUnVOd.js.map +1 -0
  39. package/dist/{decision-point-Di2LATNH.js → decision-point-CQOczIIH.js} +2 -2
  40. package/dist/{decision-point-Di2LATNH.js.map → decision-point-CQOczIIH.js.map} +1 -1
  41. package/dist/{default-registry-aPvwtzEM.d.ts → default-registry-C_Akmpui.d.ts} +7 -7
  42. package/dist/{default-registry-aPvwtzEM.d.ts.map → default-registry-C_Akmpui.d.ts.map} +1 -1
  43. package/dist/{default-registry-CdFbxPnr.js → default-registry-D-xd7KxV.js} +5 -5
  44. package/dist/{default-registry-CdFbxPnr.js.map → default-registry-D-xd7KxV.js.map} +1 -1
  45. package/dist/{define-agent-eval-BROmIwn1.js → define-agent-eval-BLVewqJm.js} +8 -8
  46. package/dist/{define-agent-eval-BROmIwn1.js.map → define-agent-eval-BLVewqJm.js.map} +1 -1
  47. package/dist/{define-agent-eval-DGWBgCid.d.ts → define-agent-eval-nNPC7cD5.d.ts} +7 -7
  48. package/dist/{define-agent-eval-DGWBgCid.d.ts.map → define-agent-eval-nNPC7cD5.d.ts.map} +1 -1
  49. package/dist/diagnosis/index.d.ts +2 -2
  50. package/dist/diagnosis/index.js +1 -1
  51. package/dist/{dspy-rlm-engine-cWyn8G1a.js → dspy-rlm-engine-BS_jxE0P.js} +4 -4
  52. package/dist/{dspy-rlm-engine-cWyn8G1a.js.map → dspy-rlm-engine-BS_jxE0P.js.map} +1 -1
  53. package/dist/{engine-BF8naBn7.d.ts → engine-B0gr15-l.d.ts} +2 -2
  54. package/dist/{engine-BF8naBn7.d.ts.map → engine-B0gr15-l.d.ts.map} +1 -1
  55. package/dist/{eval-campaign-Dq8DEKmy.js → eval-campaign-DpkToY_w.js} +2 -2
  56. package/dist/eval-campaign-DpkToY_w.js.map +1 -0
  57. package/dist/{evaluation-bU_bhlv-.js → evaluation-C_GJvEEG.js} +2 -2
  58. package/dist/{evaluation-bU_bhlv-.js.map → evaluation-C_GJvEEG.js.map} +1 -1
  59. package/dist/{evaluation-CFKj_IlJ.d.ts → evaluation-mk3u_ZJC.d.ts} +4 -4
  60. package/dist/{evaluation-CFKj_IlJ.d.ts.map → evaluation-mk3u_ZJC.d.ts.map} +1 -1
  61. package/dist/evaluation.d.ts +1 -1
  62. package/dist/evaluation.js +1 -1
  63. package/dist/{exact-types-VAFjtOQN.d.ts → exact-types-Blq7YvsK.d.ts} +2 -2
  64. package/dist/{exact-types-VAFjtOQN.d.ts.map → exact-types-Blq7YvsK.d.ts.map} +1 -1
  65. package/dist/experiment/index.d.ts +3 -3
  66. package/dist/experiment/index.js +2 -2
  67. package/dist/{external-optimizer-process-2ImGH_LR.js → external-optimizer-process-m9xln7zN.js} +2 -2
  68. package/dist/{external-optimizer-process-2ImGH_LR.js.map → external-optimizer-process-m9xln7zN.js.map} +1 -1
  69. package/dist/{external-optimizer-subprocess-_C_2yriN.js → external-optimizer-subprocess-GO6s84Ov.js} +3 -3
  70. package/dist/{external-optimizer-subprocess-_C_2yriN.js.map → external-optimizer-subprocess-GO6s84Ov.js.map} +1 -1
  71. package/dist/{feedback-trajectory-DTj8eVTR.d.ts → feedback-trajectory-D3oISeGl.d.ts} +3 -3
  72. package/dist/{feedback-trajectory-DTj8eVTR.d.ts.map → feedback-trajectory-D3oISeGl.d.ts.map} +1 -1
  73. package/dist/{findings-store-BSuaV3dN.js → findings-store-CTy71Lnr.js} +5 -5
  74. package/dist/{findings-store-BSuaV3dN.js.map → findings-store-CTy71Lnr.js.map} +1 -1
  75. package/dist/fuzz.js +1 -1
  76. package/dist/hosted/index.js +1 -1
  77. package/dist/{index-DNXFzSpc.d.ts → index-BN6htPVi.d.ts} +2 -2
  78. package/dist/{index-DNXFzSpc.d.ts.map → index-BN6htPVi.d.ts.map} +1 -1
  79. package/dist/{index-BlTbxHlY.d.ts → index-BdFlQP54.d.ts} +4 -4
  80. package/dist/{index-BlTbxHlY.d.ts.map → index-BdFlQP54.d.ts.map} +1 -1
  81. package/dist/{index-QLDWZTxI.d.ts → index-CxuK3sxA.d.ts} +9 -9
  82. package/dist/{index-QLDWZTxI.d.ts.map → index-CxuK3sxA.d.ts.map} +1 -1
  83. package/dist/{index-YS58LHlx.d.ts → index-Dodw93oW.d.ts} +25 -181
  84. package/dist/index-Dodw93oW.d.ts.map +1 -0
  85. package/dist/{index-DX87wzX3.d.ts → index-IE8O0HNr.d.ts} +9 -9
  86. package/dist/{index-DX87wzX3.d.ts.map → index-IE8O0HNr.d.ts.map} +1 -1
  87. package/dist/{index-B62BaRzH.d.ts → index-KAYaJtMA.d.ts} +4 -4
  88. package/dist/{index-B62BaRzH.d.ts.map → index-KAYaJtMA.d.ts.map} +1 -1
  89. package/dist/{index-Bp3w4fWc.d.ts → index-cp5gkylN.d.ts} +12 -12
  90. package/dist/{index-Bp3w4fWc.d.ts.map → index-cp5gkylN.d.ts.map} +1 -1
  91. package/dist/index.d.ts +30 -30
  92. package/dist/index.js +72 -30
  93. package/dist/index.js.map +1 -1
  94. package/dist/{integrity-CrmnGB2T.d.ts → integrity-zeWMeTQt.d.ts} +2 -2
  95. package/dist/{integrity-CrmnGB2T.d.ts.map → integrity-zeWMeTQt.d.ts.map} +1 -1
  96. package/dist/{judge-gate-CrN0PaAL.js → judge-gate-DsoI5tx7.js} +2 -2
  97. package/dist/{judge-gate-CrN0PaAL.js.map → judge-gate-DsoI5tx7.js.map} +1 -1
  98. package/dist/{kind-factory-CV0FNCMM.js → kind-factory-CJXaE1oF.js} +2 -2
  99. package/dist/{kind-factory-CV0FNCMM.js.map → kind-factory-CJXaE1oF.js.map} +1 -1
  100. package/dist/{llm-client-DMMSg-Ro.js → llm-client-Bj-TooRS.js} +11 -11
  101. package/dist/{llm-client-DMMSg-Ro.js.map → llm-client-Bj-TooRS.js.map} +1 -1
  102. package/dist/{llm-judge-C813vmpc.js → llm-judge-DzAT7Wka.js} +11 -11
  103. package/dist/{llm-judge-C813vmpc.js.map → llm-judge-DzAT7Wka.js.map} +1 -1
  104. package/dist/{matrix-C-GxIgeJ.d.ts → matrix-Diw3yJCG.d.ts} +3 -4
  105. package/dist/matrix-Diw3yJCG.d.ts.map +1 -0
  106. package/dist/meta-eval/index.d.ts +3 -3
  107. package/dist/meta-eval/index.js +2 -2
  108. package/dist/{mint-yF51iBgY.js → mint-Ck92efNo.js} +2 -2
  109. package/dist/{mint-yF51iBgY.js.map → mint-Ck92efNo.js.map} +1 -1
  110. package/dist/multishot/golden/index.d.ts +1 -1
  111. package/dist/multishot/index.d.ts +3 -2
  112. package/dist/multishot/index.d.ts.map +1 -1
  113. package/dist/multishot/index.js +3 -3
  114. package/dist/multishot/index.js.map +1 -1
  115. package/dist/openapi.json +1 -1
  116. package/dist/{paired-promotion-decision-DJU3fZxH.d.ts → paired-promotion-decision-COeOgNHG.d.ts} +2 -2
  117. package/dist/{paired-promotion-decision-DJU3fZxH.d.ts.map → paired-promotion-decision-COeOgNHG.d.ts.map} +1 -1
  118. package/dist/paired-promotion-power-D03cUj9E.js +289 -0
  119. package/dist/paired-promotion-power-D03cUj9E.js.map +1 -0
  120. package/dist/{pareto-fJZg8pXm.js → pareto-UzjB3ZBk.js} +5 -288
  121. package/dist/pareto-UzjB3ZBk.js.map +1 -0
  122. package/dist/{prime-protocol-D1NkJRuD.d.ts → prime-protocol-bRbh6dqd.d.ts} +2 -2
  123. package/dist/{prime-protocol-D1NkJRuD.d.ts.map → prime-protocol-bRbh6dqd.d.ts.map} +1 -1
  124. package/dist/{promotion-gate-Da0xV4sa.d.ts → promotion-gate-XglbDCNo.d.ts} +3 -3
  125. package/dist/{promotion-gate-Da0xV4sa.d.ts.map → promotion-gate-XglbDCNo.d.ts.map} +1 -1
  126. package/dist/{proposal-findings-DWs94yT8.js → proposal-findings-CS6LoGGp.js} +2 -2
  127. package/dist/{proposal-findings-DWs94yT8.js.map → proposal-findings-CS6LoGGp.js.map} +1 -1
  128. package/dist/{registry-BAcEbzKm.d.ts → registry-Pfeqsr5k.d.ts} +4 -4
  129. package/dist/{registry-BAcEbzKm.d.ts.map → registry-Pfeqsr5k.d.ts.map} +1 -1
  130. package/dist/{release-confidence-DGtuPDxJ.js → release-confidence-B4Xxdpmn.js} +2 -2
  131. package/dist/{release-confidence-DGtuPDxJ.js.map → release-confidence-B4Xxdpmn.js.map} +1 -1
  132. package/dist/reporting.d.ts +5 -5
  133. package/dist/reporting.js +2 -2
  134. package/dist/{researcher-CSlc84Bp.d.ts → researcher-DlyjP5uq.d.ts} +6 -6
  135. package/dist/{researcher-CSlc84Bp.d.ts.map → researcher-DlyjP5uq.d.ts.map} +1 -1
  136. package/dist/{reward-ST4PXNXF.d.ts → reward-ap_R9mCH.d.ts} +2 -2
  137. package/dist/{reward-ST4PXNXF.d.ts.map → reward-ap_R9mCH.d.ts.map} +1 -1
  138. package/dist/{reward-hacking-C9hPVT0Q.d.ts → reward-hacking-CIdVwVe4.d.ts} +2 -2
  139. package/dist/{reward-hacking-C9hPVT0Q.d.ts.map → reward-hacking-CIdVwVe4.d.ts.map} +1 -1
  140. package/dist/rl.d.ts +11 -11
  141. package/dist/rl.js +5 -5
  142. package/dist/rl.js.map +1 -1
  143. package/dist/rollout/index.d.ts +3 -3
  144. package/dist/rollout/index.js +2 -2
  145. package/dist/{rollout-DKa54qer.js → rollout-Dh5q6CPA.js} +3 -3
  146. package/dist/{rollout-DKa54qer.js.map → rollout-Dh5q6CPA.js.map} +1 -1
  147. package/dist/{rubric-predictive-validity-B3RzbwOx.d.ts → rubric-predictive-validity-Bbi88Aut.d.ts} +2 -2
  148. package/dist/{rubric-predictive-validity-B3RzbwOx.d.ts.map → rubric-predictive-validity-Bbi88Aut.d.ts.map} +1 -1
  149. package/dist/{run-record-CFbnkE1K.js → run-record-DTTx9Ktr.js} +2 -2
  150. package/dist/{run-record-CFbnkE1K.js.map → run-record-DTTx9Ktr.js.map} +1 -1
  151. package/dist/{run-record-CpLS4Uid.js → run-record-DmX_ESC5.js} +7 -5
  152. package/dist/run-record-DmX_ESC5.js.map +1 -0
  153. package/dist/{run-record-D2BFMPGl.d.ts → run-record-pBlhZizT.d.ts} +8 -8
  154. package/dist/{run-record-D2BFMPGl.d.ts.map → run-record-pBlhZizT.d.ts.map} +1 -1
  155. package/dist/search/index.d.ts +2 -2
  156. package/dist/search/index.d.ts.map +1 -1
  157. package/dist/search/index.js +2 -2
  158. package/dist/{search-kernel-CQGLbmgn.d.ts → search-kernel-6P1dRpJ4.d.ts} +4 -4
  159. package/dist/{search-kernel-CQGLbmgn.d.ts.map → search-kernel-6P1dRpJ4.d.ts.map} +1 -1
  160. package/dist/{search-ledger-Dk-yk5Li.js → search-ledger-9liYyZf5.js} +2 -2
  161. package/dist/{search-ledger-Dk-yk5Li.js.map → search-ledger-9liYyZf5.js.map} +1 -1
  162. package/dist/{search-shipper-Dm-_Dtvy.js → search-shipper-B6tMNx1I.js} +2 -2
  163. package/dist/{search-shipper-Dm-_Dtvy.js.map → search-shipper-B6tMNx1I.js.map} +1 -1
  164. package/dist/{search-summary-sPWiYtSl.js → search-summary-CISbbxyr.js} +2 -2
  165. package/dist/{search-summary-sPWiYtSl.js.map → search-summary-CISbbxyr.js.map} +1 -1
  166. package/dist/{sequential-CAksw6EU.js → sequential-Ko7T-zvu.js} +65 -28
  167. package/dist/sequential-Ko7T-zvu.js.map +1 -0
  168. package/dist/sequential-OeSwJ2uG.d.ts +246 -0
  169. package/dist/sequential-OeSwJ2uG.d.ts.map +1 -0
  170. package/dist/{server-DFVwfoZq.js → server-BorE0Y3O.js} +16 -5
  171. package/dist/server-BorE0Y3O.js.map +1 -0
  172. package/dist/{skillopt-optimization-method-QO1nU8Kz.js → skillopt-optimization-method-BtX7xXDd.js} +7 -7
  173. package/dist/{skillopt-optimization-method-QO1nU8Kz.js.map → skillopt-optimization-method-BtX7xXDd.js.map} +1 -1
  174. package/dist/{statistical-heldout-CvOwNqt9.d.ts → statistical-heldout-vjrs8iyO.d.ts} +6 -6
  175. package/dist/{statistical-heldout-CvOwNqt9.d.ts.map → statistical-heldout-vjrs8iyO.d.ts.map} +1 -1
  176. package/dist/statistics.d.ts +2 -2
  177. package/dist/{store-otlp-C-jyj3WX.js → store-otlp-CmgKDr0O.js} +2 -2
  178. package/dist/{store-otlp-C-jyj3WX.js.map → store-otlp-CmgKDr0O.js.map} +1 -1
  179. package/dist/{store-tool-spans-B3z_Qb5u.d.ts → store-tool-spans-BemsQEhd.d.ts} +6 -6
  180. package/dist/{store-tool-spans-B3z_Qb5u.d.ts.map → store-tool-spans-BemsQEhd.d.ts.map} +1 -1
  181. package/dist/{store-tool-spans-DalWlKY8.js → store-tool-spans-CW24axM0.js} +3 -3
  182. package/dist/{store-tool-spans-DalWlKY8.js.map → store-tool-spans-CW24axM0.js.map} +1 -1
  183. package/dist/{summary-report-DyZquTaH.d.ts → summary-report-vdhE20Zf.d.ts} +4 -4
  184. package/dist/{summary-report-DyZquTaH.d.ts.map → summary-report-vdhE20Zf.d.ts.map} +1 -1
  185. package/dist/supervisor-run/index.d.ts +1 -1
  186. package/dist/{systemone-DVk-Crtu.d.ts → systemone-DFUN9DL1.d.ts} +7 -7
  187. package/dist/{systemone-DVk-Crtu.d.ts.map → systemone-DFUN9DL1.d.ts.map} +1 -1
  188. package/dist/{systemone-review-CToBl1oa.d.ts → systemone-review-4CKmHvr5.d.ts} +2 -2
  189. package/dist/{systemone-review-CToBl1oa.d.ts.map → systemone-review-4CKmHvr5.d.ts.map} +1 -1
  190. package/dist/systemone.d.ts +3 -3
  191. package/dist/systemone.js +2 -2
  192. package/dist/{tool-groups-R5RO9OHn.d.ts → tool-groups-Dpl3picW.d.ts} +3 -3
  193. package/dist/tool-groups-Dpl3picW.d.ts.map +1 -0
  194. package/dist/{trace-questions-BY6taxnl.d.ts → trace-questions-oT2fZWJ8.d.ts} +3 -3
  195. package/dist/{trace-questions-BY6taxnl.d.ts.map → trace-questions-oT2fZWJ8.d.ts.map} +1 -1
  196. package/dist/trace-repair/index.d.ts +2 -2
  197. package/dist/traces.d.ts +6 -6
  198. package/dist/traces.js +5 -11
  199. package/dist/traces.js.map +1 -1
  200. package/dist/{tree-C-N2kP-8.js → tree-D2cNtu9m.js} +10 -10
  201. package/dist/tree-D2cNtu9m.js.map +1 -0
  202. package/dist/{types-kBMNdo1X.d.ts → types-6GuPL-Vt.d.ts} +3 -3
  203. package/dist/{types-kBMNdo1X.d.ts.map → types-6GuPL-Vt.d.ts.map} +1 -1
  204. package/dist/{types-ip2D3-Ib.d.ts → types-C9yEqDjQ.d.ts} +6 -6
  205. package/dist/{types-ip2D3-Ib.d.ts.map → types-C9yEqDjQ.d.ts.map} +1 -1
  206. package/dist/{types-BsdcSWnf.d.ts → types-CP3rkpir.d.ts} +3 -3
  207. package/dist/{types-BsdcSWnf.d.ts.map → types-CP3rkpir.d.ts.map} +1 -1
  208. package/dist/{types-DUVhW5V1.d.ts → types-CwHU7U9J.d.ts} +2 -2
  209. package/dist/{types-DUVhW5V1.d.ts.map → types-CwHU7U9J.d.ts.map} +1 -1
  210. package/dist/wire/index.d.ts +4 -4
  211. package/dist/wire/index.d.ts.map +1 -1
  212. package/dist/wire/index.js +1 -1
  213. package/docs/adopt-stack.md +9 -0
  214. package/docs/eval-fixtures.md +2 -2
  215. package/docs/search-ledger.md +1 -0
  216. package/docs/wire-protocol.md +1 -1
  217. package/package.json +1 -1
  218. package/dist/chat-client-Zz97O3NB.js.map +0 -1
  219. package/dist/completion-verifier-DFyYFezn.js.map +0 -1
  220. package/dist/cost-ledger-DfhStGcZ.js.map +0 -1
  221. package/dist/eval-campaign-Dq8DEKmy.js.map +0 -1
  222. package/dist/index-YS58LHlx.d.ts.map +0 -1
  223. package/dist/matrix-C-GxIgeJ.d.ts.map +0 -1
  224. package/dist/metrics-zALlR17s.js +0 -146
  225. package/dist/metrics-zALlR17s.js.map +0 -1
  226. package/dist/pareto-fJZg8pXm.js.map +0 -1
  227. package/dist/run-record-CpLS4Uid.js.map +0 -1
  228. package/dist/sequential-B9p6uoV8.d.ts +0 -168
  229. package/dist/sequential-B9p6uoV8.d.ts.map +0 -1
  230. package/dist/sequential-CAksw6EU.js.map +0 -1
  231. package/dist/server-DFVwfoZq.js.map +0 -1
  232. package/dist/tool-groups-R5RO9OHn.d.ts.map +0 -1
  233. package/dist/tree-C-N2kP-8.js.map +0 -1
@@ -1,6 +1,148 @@
1
1
  import { s as ValidationError } from "./errors-DeEEV9Vx.js";
2
- import { a as resolveModelPricing, n as estimateCost } from "./metrics-zALlR17s.js";
3
2
  import { z } from "zod";
3
+ // src/metrics.ts
4
+ /** Per-1K token pricing for exact model ids. */
5
+ const MODEL_PRICING = {
6
+ "gpt-4o": {
7
+ input: .0025,
8
+ output: .01
9
+ },
10
+ "gpt-4o-mini": {
11
+ input: 15e-5,
12
+ output: 6e-4
13
+ },
14
+ "gpt-4-turbo": {
15
+ input: .01,
16
+ output: .03
17
+ },
18
+ "claude-sonnet-4-20250514": {
19
+ input: .003,
20
+ output: .015
21
+ },
22
+ "claude-opus-4-20250514": {
23
+ input: .015,
24
+ output: .075
25
+ },
26
+ "claude-3-haiku-20240307": {
27
+ input: 25e-5,
28
+ output: .00125
29
+ },
30
+ "glm-5.3": {
31
+ input: .00168,
32
+ output: .00528
33
+ },
34
+ "gpt-6-luna": {
35
+ input: 1e-4,
36
+ output: 5e-4
37
+ },
38
+ "gpt-5-mini": {
39
+ input: 25e-5,
40
+ output: .002
41
+ }
42
+ };
43
+ /** Family-level pricing fallbacks (per-1K), matched against a normalized id
44
+ * after exact lookup misses. Ordered — first match wins. Covers the model
45
+ * ids actually used through the Tangle router + cli-bridge harnesses, none
46
+ * of which appear in the exact table above — without this they priced to a
47
+ * silent $0, blanking every cost/Pareto axis downstream. */
48
+ const FAMILY_PRICING = [
49
+ [/^stealth\//, {
50
+ input: 0,
51
+ output: 0
52
+ }],
53
+ [/claude.*opus/, {
54
+ input: .015,
55
+ output: .075
56
+ }],
57
+ [/claude.*haiku/, {
58
+ input: 8e-4,
59
+ output: .004
60
+ }],
61
+ [/claude.*sonnet|claude-code|claude-sonnet/, {
62
+ input: .003,
63
+ output: .015
64
+ }],
65
+ [/gpt-4o-mini/, {
66
+ input: 15e-5,
67
+ output: 6e-4
68
+ }],
69
+ [/gpt-5|gpt-4\.1|o[134]\b/, {
70
+ input: .00125,
71
+ output: .01
72
+ }],
73
+ [/gpt-4o|gpt-4/, {
74
+ input: .0025,
75
+ output: .01
76
+ }],
77
+ [/deepseek/, {
78
+ input: 3e-4,
79
+ output: .0011
80
+ }],
81
+ [/glm|zhipu|zai/, {
82
+ input: 6e-4,
83
+ output: .0022
84
+ }],
85
+ [/kimi|moonshot/, {
86
+ input: 6e-4,
87
+ output: .0025
88
+ }],
89
+ [/qwen/, {
90
+ input: 4e-4,
91
+ output: .0012
92
+ }],
93
+ [/gemini.*flash/, {
94
+ input: 1e-4,
95
+ output: 4e-4
96
+ }],
97
+ [/gemini/, {
98
+ input: .00125,
99
+ output: .005
100
+ }],
101
+ [/llama/, {
102
+ input: 2e-4,
103
+ output: 6e-4
104
+ }]
105
+ ];
106
+ /** Normalize a model id for pricing: drop `@snapshot` and trailing
107
+ * `-YYYY-MM-DD` dated-snapshot suffixes, lowercase, and return the complete
108
+ * id plus its final served-model segment for exact-row lookup. */
109
+ function normalizedModelIds(model) {
110
+ const id = (model.split("@")[0] ?? model).trim().toLowerCase().replace(/-(?:19|20)\d{2}-\d{2}-\d{2}$/, "");
111
+ const finalSegment = id.slice(id.lastIndexOf("/") + 1);
112
+ return finalSegment === id ? [id] : [id, finalSegment];
113
+ }
114
+ /** Resolve pricing for a model id: exact table, then family fallback.
115
+ * Returns null when the id matches nothing (caller decides — never a
116
+ * silent-zero masquerading as a real $0 cost). */
117
+ function resolveModelPricing(model) {
118
+ if (MODEL_PRICING[model]) return MODEL_PRICING[model];
119
+ const ids = normalizedModelIds(model);
120
+ for (const id of ids) if (MODEL_PRICING[id]) return MODEL_PRICING[id];
121
+ for (const [pattern, price] of FAMILY_PRICING) if (ids.some((id) => pattern.test(id))) return price;
122
+ return null;
123
+ }
124
+ /** True when `model` has known pricing: distinguishes a real $0 from unpriced. */
125
+ function isModelPriced(model) {
126
+ return resolveModelPricing(model) !== null;
127
+ }
128
+ const warnedUnpricedModels = /* @__PURE__ */ new Set();
129
+ /** Estimate token count from string length (chars / 4 approximation) */
130
+ function estimateTokens(text) {
131
+ return Math.ceil(text.length / 4);
132
+ }
133
+ /** Calculate cost in USD from token counts and model. Unknown models warn once
134
+ * (not a silent zero) and return 0; cost-sensitive callers gate on {@link isModelPriced}. */
135
+ function estimateCost(inputTokens, outputTokens, model) {
136
+ const pricing = resolveModelPricing(model);
137
+ if (!pricing) {
138
+ if (!warnedUnpricedModels.has(model)) {
139
+ warnedUnpricedModels.add(model);
140
+ console.warn(`estimateCost: no pricing for "${model}" — returning 0; add it to MODEL_PRICING`);
141
+ }
142
+ return 0;
143
+ }
144
+ return inputTokens / 1e3 * pricing.input + outputTokens / 1e3 * pricing.output;
145
+ }
4
146
  // src/cost-ledger/validation.ts
5
147
  /** Validate cost and usage primitives without admitting work or consulting pricing. */
6
148
  function toError(value) {
@@ -978,6 +1120,6 @@ function paidFailure(callId, error, receipt) {
978
1120
  ...receipt ? { receipt: cloneReceipt(receipt) } : {}
979
1121
  };
980
1122
  }
981
- export { CostLedgerPersistenceError as a, costForTokenPricing as c, CostCeilingReachedError as i, costForUsage as l, CostAccountingIncompleteError as n, CostReceiptCaptureError as o, CostCallConflictError as r, CostReservationExceededError as s, CostLedger as t };
1123
+ export { CostLedgerPersistenceError as a, costForTokenPricing as c, estimateCost as d, estimateTokens as f, CostCeilingReachedError as i, costForUsage as l, resolveModelPricing as m, CostAccountingIncompleteError as n, CostReceiptCaptureError as o, isModelPriced as p, CostCallConflictError as r, CostReservationExceededError as s, CostLedger as t, MODEL_PRICING as u };
982
1124
 
983
- //# sourceMappingURL=cost-ledger-DfhStGcZ.js.map
1125
+ //# sourceMappingURL=cost-ledger-1CwUnVOd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cost-ledger-1CwUnVOd.js","names":[],"sources":["../src/metrics.ts","../src/cost-ledger/validation.ts","../src/cost-ledger/pricing.ts","../src/cost-ledger/receipts.ts","../src/cost-ledger/errors.ts","../src/cost-ledger/journal.ts","../src/cost-ledger/summary.ts","../src/cost-ledger.ts"],"sourcesContent":["interface TokenPrice {\n input: number\n output: number\n}\n\n/** Per-1K token pricing for exact model ids. */\nexport const MODEL_PRICING: Record<string, TokenPrice> = {\n 'gpt-4o': { input: 0.0025, output: 0.01 },\n 'gpt-4o-mini': { input: 0.00015, output: 0.0006 },\n 'gpt-4-turbo': { input: 0.01, output: 0.03 },\n 'claude-sonnet-4-20250514': { input: 0.003, output: 0.015 },\n 'claude-opus-4-20250514': { input: 0.015, output: 0.075 },\n 'claude-3-haiku-20240307': { input: 0.00025, output: 0.00125 },\n // Router response-header rates observed for the exact served model on\n // 2026-08-15. Keep this exact row ahead of the deliberately coarse family\n // fallback so glm-5.3 campaign costs are not understated by ~2.5x.\n 'glm-5.3': { input: 0.00168, output: 0.00528 },\n // Tangle Router's published rate (`GET /v1/models`) on 2026-10-09:\n // $0.10 / $0.50 per Mtok. Exact, because the coarse gpt-5 family row would\n // overstate it 12x on input and 20x on output.\n 'gpt-6-luna': { input: 0.0001, output: 0.0005 },\n // Router receipts for the served id `gpt-5-mini-2025-08-07` solve exactly\n // to $0.25 / $2 per Mtok; the gpt-5 family row is 5x too high.\n 'gpt-5-mini': { input: 0.00025, output: 0.002 },\n}\n\n/** Family-level pricing fallbacks (per-1K), matched against a normalized id\n * after exact lookup misses. Ordered — first match wins. Covers the model\n * ids actually used through the Tangle router + cli-bridge harnesses, none\n * of which appear in the exact table above — without this they priced to a\n * silent $0, blanking every cost/Pareto axis downstream. */\nconst FAMILY_PRICING: Array<[RegExp, TokenPrice]> = [\n // OpenRouter stealth previews (`stealth/union-alpha`, …) bill $0 during\n // their preview window. A real zero row lets the budget ledger admit them;\n // an unpriced id is refused before the first call.\n [/^stealth\\//, { input: 0, output: 0 }],\n [/claude.*opus/, { input: 0.015, output: 0.075 }],\n [/claude.*haiku/, { input: 0.0008, output: 0.004 }],\n [/claude.*sonnet|claude-code|claude-sonnet/, { input: 0.003, output: 0.015 }],\n [/gpt-4o-mini/, { input: 0.00015, output: 0.0006 }],\n [/gpt-5|gpt-4\\.1|o[134]\\b/, { input: 0.00125, output: 0.01 }],\n [/gpt-4o|gpt-4/, { input: 0.0025, output: 0.01 }],\n [/deepseek/, { input: 0.0003, output: 0.0011 }],\n [/glm|zhipu|zai/, { input: 0.0006, output: 0.0022 }],\n [/kimi|moonshot/, { input: 0.0006, output: 0.0025 }],\n [/qwen/, { input: 0.0004, output: 0.0012 }],\n [/gemini.*flash/, { input: 0.0001, output: 0.0004 }],\n [/gemini/, { input: 0.00125, output: 0.005 }],\n [/llama/, { input: 0.0002, output: 0.0006 }],\n]\n\n/** Normalize a model id for pricing: drop `@snapshot` and trailing\n * `-YYYY-MM-DD` dated-snapshot suffixes, lowercase, and return the complete\n * id plus its final served-model segment for exact-row lookup. */\nfunction normalizedModelIds(model: string): string[] {\n const stripped = (model.split('@')[0] ?? model).trim().toLowerCase()\n const id = stripped.replace(/-(?:19|20)\\d{2}-\\d{2}-\\d{2}$/, '')\n const finalSegment = id.slice(id.lastIndexOf('/') + 1)\n return finalSegment === id ? [id] : [id, finalSegment]\n}\n\n/** Resolve pricing for a model id: exact table, then family fallback.\n * Returns null when the id matches nothing (caller decides — never a\n * silent-zero masquerading as a real $0 cost). */\nexport function resolveModelPricing(model: string): TokenPrice | null {\n if (MODEL_PRICING[model]) return MODEL_PRICING[model]\n const ids = normalizedModelIds(model)\n for (const id of ids) {\n if (MODEL_PRICING[id]) return MODEL_PRICING[id]\n }\n for (const [pattern, price] of FAMILY_PRICING) {\n if (ids.some((id) => pattern.test(id))) return price\n }\n return null\n}\n\n/** True when `model` has known pricing: distinguishes a real $0 from unpriced. */\nexport function isModelPriced(model: string): boolean {\n return resolveModelPricing(model) !== null\n}\n\nconst warnedUnpricedModels = new Set<string>()\n\n/** Estimate token count from string length (chars / 4 approximation) */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4)\n}\n\n/** Calculate cost in USD from token counts and model. Unknown models warn once\n * (not a silent zero) and return 0; cost-sensitive callers gate on {@link isModelPriced}. */\nexport function estimateCost(inputTokens: number, outputTokens: number, model: string): number {\n const pricing = resolveModelPricing(model)\n if (!pricing) {\n if (!warnedUnpricedModels.has(model)) {\n warnedUnpricedModels.add(model)\n console.warn(`estimateCost: no pricing for \"${model}\" — returning 0; add it to MODEL_PRICING`)\n }\n return 0\n }\n return (inputTokens / 1000) * pricing.input + (outputTokens / 1000) * pricing.output\n}\n","/** Validate cost and usage primitives without admitting work or consulting pricing. */\nimport { z } from 'zod'\nimport { ValidationError } from '../errors'\nimport type { CostUsage } from './contract'\n\nexport function toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value))\n}\n\nexport function validationMessage(cause: unknown): string {\n return cause instanceof z.ZodError ? z.prettifyError(cause) : toError(cause).message\n}\n\nexport function assertUsage(usage: CostUsage): void {\n assertTokenCount(usage.inputTokens, 'inputTokens')\n assertTokenCount(usage.outputTokens, 'outputTokens')\n if (usage.reasoningTokens !== undefined) {\n assertTokenCount(usage.reasoningTokens, 'reasoningTokens')\n if (usage.reasoningTokens > usage.outputTokens) {\n throw new ValidationError('CostLedger: reasoningTokens must not exceed outputTokens')\n }\n }\n if (usage.cachedTokens !== undefined) assertTokenCount(usage.cachedTokens, 'cachedTokens')\n if (usage.cacheWriteTokens !== undefined) {\n assertTokenCount(usage.cacheWriteTokens, 'cacheWriteTokens')\n }\n}\n\nexport function assertTokenCount(value: unknown, name: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative integer, got ${String(value)}`,\n )\n }\n}\n\nexport function assertNonNegative(value: unknown, name: string): asserts value is number {\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative finite number, got ${String(value)}`,\n )\n }\n}\n\nexport function assertTimeout(value: unknown, name: string): asserts value is number {\n if (\n typeof value !== 'number' ||\n !Number.isSafeInteger(value) ||\n value < 0 ||\n value > 2_147_483_647\n ) {\n throw new ValidationError(\n `CostLedger: ${name} must be a non-negative safe integer no greater than 2147483647, got ${String(value)}`,\n )\n }\n}\n\nexport function assertString(value: unknown, name: string): asserts value is string {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new ValidationError(`CostLedger: ${name} must be a non-empty string`)\n }\n}\n","/** Model-price lookup and caller-supplied token pricing, including receipt snapshots. */\nimport { estimateCost, resolveModelPricing } from '../metrics'\nimport type { CostReceipt, CostUsage, CustomTokenPricing } from './contract'\nimport { assertNonNegative, assertTokenCount, assertUsage } from './validation'\n\n\n\nexport interface CostResult {\n costUsd: number\n costUnknown: boolean\n}\n\nexport function costForUsage(model: string, usage: CostUsage): CostResult {\n assertUsage(usage)\n if (!resolveModelPricing(model)) return { costUsd: 0, costUnknown: true }\n return {\n costUsd: estimateCost(\n usage.inputTokens + (usage.cachedTokens ?? 0) + (usage.cacheWriteTokens ?? 0),\n usage.outputTokens,\n model,\n ),\n costUnknown: false,\n }\n}\n\n/** Price token counts with caller-supplied per-million rates. */\nexport function costForTokenPricing(\n pricing: CustomTokenPricing,\n usage: Pick<CostUsage, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'>,\n): number {\n assertTokenCount(usage.inputTokens, 'usage.inputTokens')\n assertTokenCount(usage.outputTokens, 'usage.outputTokens')\n if (usage.cachedTokens !== undefined) {\n assertTokenCount(usage.cachedTokens, 'usage.cachedTokens')\n }\n if (usage.cacheWriteTokens !== undefined) {\n assertTokenCount(usage.cacheWriteTokens, 'usage.cacheWriteTokens')\n }\n assertNonNegative(pricing.inputUsdPerMillion, 'pricing.inputUsdPerMillion')\n if (pricing.cachedInputUsdPerMillion !== undefined) {\n assertNonNegative(pricing.cachedInputUsdPerMillion, 'pricing.cachedInputUsdPerMillion')\n }\n if (pricing.cacheWriteUsdPerMillion !== undefined) {\n assertNonNegative(pricing.cacheWriteUsdPerMillion, 'pricing.cacheWriteUsdPerMillion')\n }\n assertNonNegative(pricing.outputUsdPerMillion, 'pricing.outputUsdPerMillion')\n const cachedInputRate = pricing.cachedInputUsdPerMillion ?? pricing.inputUsdPerMillion\n const cacheWriteRate = pricing.cacheWriteUsdPerMillion ?? pricing.inputUsdPerMillion\n return (\n (usage.inputTokens / 1_000_000) * pricing.inputUsdPerMillion +\n ((usage.cachedTokens ?? 0) / 1_000_000) * cachedInputRate +\n ((usage.cacheWriteTokens ?? 0) / 1_000_000) * cacheWriteRate +\n (usage.outputTokens / 1_000_000) * pricing.outputUsdPerMillion\n )\n}\n\nexport function costFromPricing(\n usage: CostUsage,\n pricing: NonNullable<CostReceipt['pricing']>,\n): number {\n const cachedInputRate = pricing.cachedInputUsdPerThousand ?? pricing.inputUsdPerThousand\n const cacheWriteRate = pricing.cacheWriteUsdPerThousand ?? pricing.inputUsdPerThousand\n return (\n (usage.inputTokens / 1000) * pricing.inputUsdPerThousand +\n ((usage.cachedTokens ?? 0) / 1000) * cachedInputRate +\n ((usage.cacheWriteTokens ?? 0) / 1000) * cacheWriteRate +\n (usage.outputTokens / 1000) * pricing.outputUsdPerThousand\n )\n}\n\nexport function pricingSnapshot(pricing: CustomTokenPricing): NonNullable<CostReceipt['pricing']> {\n costForTokenPricing(pricing, { inputTokens: 0, outputTokens: 0 })\n return {\n inputUsdPerThousand: pricing.inputUsdPerMillion / 1000,\n ...(pricing.cachedInputUsdPerMillion === undefined\n ? {}\n : { cachedInputUsdPerThousand: pricing.cachedInputUsdPerMillion / 1000 }),\n ...(pricing.cacheWriteUsdPerMillion === undefined\n ? {}\n : { cacheWriteUsdPerThousand: pricing.cacheWriteUsdPerMillion / 1000 }),\n outputUsdPerThousand: pricing.outputUsdPerMillion / 1000,\n }\n}\n","/** Create, validate, filter, and detach the receipts stored by a cost ledger. */\nimport { z } from 'zod'\nimport { ValidationError } from '../errors'\nimport { resolveModelPricing } from '../metrics'\nimport type {\n CostCallBase,\n CostLedgerFilter,\n CostLedgerRecord,\n CostReceipt,\n CostReceiptInput,\n CostUsage,\n PendingCostCall,\n RunPaidCallInput,\n} from './contract'\nimport { costForUsage, costFromPricing, pricingSnapshot } from './pricing'\nimport { assertNonNegative, assertString, assertUsage, validationMessage } from './validation'\n\nconst NonEmptyString = z.string().refine((value) => value.trim().length > 0, 'must be non-empty')\nexport const TokenCount = z.number().int().nonnegative().finite()\nexport const NonNegative = z.number().nonnegative().finite()\nconst Tags = z.record(NonEmptyString, z.string())\nconst CostPricingSchema = z.strictObject({\n inputUsdPerThousand: NonNegative,\n cachedInputUsdPerThousand: NonNegative.optional(),\n cacheWriteUsdPerThousand: NonNegative.optional(),\n outputUsdPerThousand: NonNegative,\n})\nconst CostCallBaseShape = {\n callId: NonEmptyString,\n channel: NonEmptyString,\n phase: NonEmptyString,\n actor: NonEmptyString,\n model: NonEmptyString,\n maximumCostUsd: NonNegative.optional(),\n tags: Tags.optional(),\n timestamp: NonNegative,\n}\nexport const PendingCostCallSchema = z.strictObject({\n status: z.literal('pending'),\n ...CostCallBaseShape,\n})\nconst CostProvenanceSchema = z.discriminatedUnion('kind', [\n z.strictObject({ kind: z.literal('observed'), usd: NonNegative }),\n z.strictObject({ kind: z.literal('estimated'), usd: NonNegative }),\n z.strictObject({ kind: z.literal('uncaptured'), usd: z.null() }),\n])\nconst CostBreakdownSchema = z.strictObject({\n router: CostProvenanceSchema,\n sandbox: CostProvenanceSchema,\n seatCredits: z.discriminatedUnion('kind', [\n z.strictObject({ kind: z.literal('estimated'), credits: NonNegative }),\n z.strictObject({ kind: z.literal('uncaptured'), credits: z.null(), reason: NonEmptyString }),\n ]),\n sources: z.array(\n z.strictObject({\n url: z.string().url(),\n readAt: z.string().datetime(),\n sha256: z.string().regex(/^[a-f0-9]{64}$/u),\n rates: z.record(NonEmptyString, NonNegative),\n }),\n ),\n})\nconst CostReceiptBaseShape = {\n costBreakdown: CostBreakdownSchema.optional(),\n status: z.literal('settled'),\n ...CostCallBaseShape,\n inputTokens: TokenCount,\n outputTokens: TokenCount,\n cachedTokens: TokenCount.optional(),\n costUsd: NonNegative,\n costUnknown: z.boolean(),\n usageUnknown: z.boolean().default(false),\n pricing: CostPricingSchema.optional(),\n actualCostUsd: NonNegative.optional(),\n estimatedCostUsd: NonNegative.optional(),\n error: NonEmptyString.optional(),\n}\nexport const CostReceiptSchema = z\n .strictObject({\n ...CostReceiptBaseShape,\n reasoningTokens: TokenCount.optional(),\n cacheWriteTokens: TokenCount.optional(),\n })\n .superRefine((receipt, ctx) => validateCostReceipt(receipt, ctx))\n\nfunction validateCostReceipt(\n receipt: CostUsage & {\n costUsd: number\n costUnknown: boolean\n usageUnknown: boolean\n costBreakdown?: CostReceipt['costBreakdown']\n pricing?: NonNullable<CostReceipt['pricing']>\n actualCostUsd?: number\n estimatedCostUsd?: number\n },\n ctx: z.RefinementCtx,\n): void {\n const split = receipt.costBreakdown\n if (split) {\n if (\n split.router.kind === 'estimated' ||\n (split.router.kind === 'observed' &&\n (receipt.actualCostUsd === undefined ||\n !costAmountsMatch(split.router.usd, receipt.actualCostUsd)))\n ) {\n ctx.addIssue({\n code: 'custom',\n message: 'Router breakdown must match the observed USD receipt or remain uncaptured',\n })\n }\n if (split.sandbox.kind === 'observed') {\n ctx.addIssue({\n code: 'custom',\n message: 'Sandbox breakdown is an estimate, not observed billing',\n })\n }\n }\n\n if (receipt.reasoningTokens !== undefined && receipt.reasoningTokens > receipt.outputTokens) {\n ctx.addIssue({ code: 'custom', message: 'reasoningTokens must not exceed outputTokens' })\n }\n\n if (receipt.actualCostUsd !== undefined && receipt.estimatedCostUsd !== undefined) {\n ctx.addIssue({\n code: 'custom',\n message: 'actual and external estimated costs cannot both be present',\n })\n }\n\n if (receipt.actualCostUsd !== undefined) {\n if (receipt.costUnknown || receipt.costUsd !== receipt.actualCostUsd) {\n ctx.addIssue({ code: 'custom', message: 'actual cost must be known and equal costUsd' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'actual cost must not include estimated pricing' })\n }\n return\n }\n\n if (receipt.estimatedCostUsd !== undefined) {\n if (receipt.costUnknown || receipt.costUsd !== receipt.estimatedCostUsd) {\n ctx.addIssue({ code: 'custom', message: 'external estimate must be known and equal costUsd' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'external estimate must not include token pricing' })\n }\n return\n }\n\n if (receipt.costUnknown) {\n if (receipt.costUsd !== 0) {\n ctx.addIssue({ code: 'custom', message: 'unknown cost must have costUsd 0' })\n }\n if (receipt.pricing !== undefined) {\n ctx.addIssue({ code: 'custom', message: 'unknown cost must not include estimated pricing' })\n }\n return\n }\n\n if (receipt.usageUnknown) {\n ctx.addIssue({ code: 'custom', message: 'known estimated cost requires known usage' })\n }\n if (!receipt.pricing) {\n ctx.addIssue({ code: 'custom', message: 'known estimated cost requires a pricing snapshot' })\n return\n }\n\n const expected = costFromPricing(receipt, receipt.pricing)\n if (!costAmountsMatch(receipt.costUsd, expected)) {\n ctx.addIssue({\n code: 'custom',\n message: `estimated cost ${receipt.costUsd} does not match pricing snapshot ${expected}`,\n })\n }\n}\n\nfunction costAmountsMatch(left: number, right: number): boolean {\n const scale = Math.max(1, Math.abs(left), Math.abs(right))\n return Math.abs(left - right) <= Number.EPSILON * scale * 8\n}\n\nexport function buildReceipt(\n pending: PendingCostCall,\n observed: CostReceiptInput,\n failed = false,\n error?: string,\n): CostReceipt {\n assertUsage(observed)\n assertString(observed.model, 'receipt.model')\n const suppliedAmounts = [\n observed.actualCostUsd,\n observed.estimatedCostUsd,\n observed.customTokenPricing,\n ].filter((value) => value !== undefined)\n if (suppliedAmounts.length > 1) {\n throw new ValidationError(\n 'CostLedger: a receipt can have only one of actualCostUsd, estimatedCostUsd, or customTokenPricing',\n )\n }\n const customPricingSnapshot =\n observed.customTokenPricing === undefined\n ? undefined\n : pricingSnapshot(observed.customTokenPricing)\n const estimated = customPricingSnapshot\n ? {\n costUsd: costFromPricing(observed, customPricingSnapshot),\n costUnknown: false,\n }\n : costForUsage(observed.model, observed)\n const hasActual = observed.actualCostUsd !== undefined\n const hasExternalEstimate = observed.estimatedCostUsd !== undefined\n if (hasActual && observed.costUnknown === true) {\n throw new ValidationError(\n 'CostLedger: a receipt cannot have both actualCostUsd and costUnknown=true',\n )\n }\n if (hasActual) assertNonNegative(observed.actualCostUsd!, 'actualCostUsd')\n if (hasExternalEstimate) assertNonNegative(observed.estimatedCostUsd!, 'estimatedCostUsd')\n if (hasExternalEstimate && observed.costUnknown === true) {\n throw new ValidationError(\n 'CostLedger: a receipt cannot have both estimatedCostUsd and costUnknown=true',\n )\n }\n const usageUnknown = observed.usageUnknown === true\n const costUnknown =\n observed.costUnknown === true ||\n (!hasActual && !hasExternalEstimate && (usageUnknown || estimated.costUnknown))\n const resolvedModelPricing =\n !customPricingSnapshot && !hasActual && !hasExternalEstimate && !costUnknown\n ? resolveModelPricing(observed.model)\n : null\n const receiptPricing =\n !hasActual && !hasExternalEstimate && !costUnknown\n ? (customPricingSnapshot ??\n (resolvedModelPricing\n ? {\n inputUsdPerThousand: resolvedModelPricing.input,\n outputUsdPerThousand: resolvedModelPricing.output,\n }\n : undefined))\n : undefined\n return parseReceipt(\n {\n ...(observed.costBreakdown ? { costBreakdown: observed.costBreakdown } : {}),\n status: 'settled',\n callId: pending.callId,\n channel: pending.channel,\n phase: pending.phase,\n actor: pending.actor,\n model: observed.model,\n inputTokens: observed.inputTokens,\n outputTokens: observed.outputTokens,\n ...(observed.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: observed.reasoningTokens }),\n ...(observed.cachedTokens === undefined ? {} : { cachedTokens: observed.cachedTokens }),\n ...(observed.cacheWriteTokens === undefined\n ? {}\n : { cacheWriteTokens: observed.cacheWriteTokens }),\n costUsd: costUnknown\n ? 0\n : hasActual\n ? observed.actualCostUsd!\n : hasExternalEstimate\n ? observed.estimatedCostUsd!\n : estimated.costUsd,\n costUnknown,\n usageUnknown,\n ...(receiptPricing ? { pricing: receiptPricing } : {}),\n ...(hasActual ? { actualCostUsd: observed.actualCostUsd } : {}),\n ...(hasExternalEstimate ? { estimatedCostUsd: observed.estimatedCostUsd } : {}),\n ...(pending.maximumCostUsd === undefined ? {} : { maximumCostUsd: pending.maximumCostUsd }),\n ...(failed ? { error: error ?? 'paid-call-failed' } : {}),\n ...(pending.tags ? { tags: { ...pending.tags } } : {}),\n timestamp: pending.timestamp,\n },\n 'provider receipt',\n )\n}\n\nfunction parseReceipt(value: unknown, path: string): CostReceipt {\n try {\n return CostReceiptSchema.parse(value) as CostReceipt\n } catch (cause) {\n throw new ValidationError(`CostLedger: invalid ${path}: ${validationMessage(cause)}`, { cause })\n }\n}\n\nexport function parseImportedReceipt(value: unknown, path: string): CostReceipt {\n if (typeof value !== 'object' || value === null) return parseReceipt(value, path)\n const candidate = { ...value } as Record<string, unknown>\n if (\n candidate.status === 'settled' &&\n candidate.actualCostUsd === undefined &&\n candidate.estimatedCostUsd === undefined &&\n candidate.costUnknown === false &&\n candidate.pricing === undefined &&\n typeof candidate.model === 'string'\n ) {\n const pricing = resolveModelPricing(candidate.model)\n if (pricing) {\n candidate.pricing = {\n inputUsdPerThousand: pricing.input,\n outputUsdPerThousand: pricing.output,\n }\n }\n }\n return parseReceipt(candidate, path)\n}\n\nexport function validateAttribution(\n input: Pick<RunPaidCallInput<unknown>, 'channel' | 'phase' | 'actor' | 'model' | 'tags'>,\n): void {\n assertString(input.channel, 'channel')\n assertString(input.phase, 'phase')\n assertString(input.actor, 'actor')\n if (input.model !== undefined) assertString(input.model, 'model')\n if (input.tags !== undefined) {\n const parsed = Tags.safeParse(input.tags)\n if (!parsed.success)\n throw new ValidationError(`CostLedger: invalid tags: ${parsed.error.message}`)\n }\n}\n\nexport function matches(record: CostCallBase, filter: CostLedgerFilter | undefined): boolean {\n if (!filter) return true\n if (filter.channel !== undefined && record.channel !== filter.channel) return false\n if (filter.phase !== undefined && record.phase !== filter.phase) return false\n return Object.entries(filter.tags ?? {}).every(([key, value]) => record.tags?.[key] === value)\n}\n\nexport function cloneRecord(record: CostLedgerRecord): CostLedgerRecord {\n if (record.status === 'settled') return cloneReceipt(record)\n return clonePendingCall(record)\n}\n\nexport function clonePendingCall(record: PendingCostCall): PendingCostCall {\n const { tags, ...rest } = record\n return { ...rest, ...(tags ? { tags: { ...tags } } : {}) }\n}\n\nexport function cloneReceipt(receipt: CostReceipt): CostReceipt {\n const { pricing, tags, costBreakdown, ...rest } = receipt\n return {\n ...rest,\n ...(costBreakdown ? { costBreakdown: structuredClone(costBreakdown) } : {}),\n ...(tags ? { tags: { ...tags } } : {}),\n ...(pricing ? { pricing: { ...pricing } } : {}),\n }\n}\n","/** Typed cost-accounting failures retain detached receipt evidence. */\nimport { ValidationError } from '../errors'\nimport type { CostReceipt } from './contract'\nimport { cloneReceipt } from './receipts'\nimport { toError } from './validation'\n\nexport class CostCeilingReachedError extends ValidationError {\n constructor(\n ceilingUsd: number,\n committedUsd: number,\n requestedUsd: number,\n phase: string,\n actor: string,\n ) {\n super(\n `CostLedger: reserving ${requestedUsd} for '${actor}' during '${phase}' would exceed ceiling ${ceilingUsd} with ${committedUsd} already committed`,\n )\n }\n}\n\nexport class CostAccountingIncompleteError extends ValidationError {}\n\nexport class CostReservationExceededError extends ValidationError {\n constructor(actor: string, actualUsd: number, maximumUsd: number) {\n super(\n `CostLedger: '${actor}' charged ${actualUsd}, exceeding its enforced maximum ${maximumUsd}`,\n )\n }\n}\n\nexport class CostCallConflictError extends ValidationError {\n readonly callId?: string\n readonly receipt?: CostReceipt\n\n constructor(\n message: string,\n options: { callId?: string; receipt?: CostReceipt; cause?: unknown } = {},\n ) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause })\n this.callId = options.callId\n this.receipt = options.receipt ? cloneReceipt(options.receipt) : undefined\n }\n}\n\nexport class CostLedgerPersistenceError extends ValidationError {\n readonly callId?: string\n readonly receipt?: CostReceipt\n\n constructor(cause: unknown, callId?: string, receipt?: CostReceipt) {\n super(\n `CostLedger: failed to persist${callId ? ` call '${callId}'` : ''}: ${toError(cause).message}`,\n { cause },\n )\n this.callId = callId\n this.receipt = receipt ? cloneReceipt(receipt) : undefined\n }\n}\n\nexport class CostReceiptCaptureError extends ValidationError {\n readonly callId: string\n readonly receipt?: CostReceipt\n readonly receiptError: Error\n\n constructor(callId: string, cause: unknown, receiptError: unknown, receipt?: CostReceipt) {\n super(`CostLedger: could not capture the provider receipt for call '${callId}'`, { cause })\n this.callId = callId\n this.receipt = receipt ? cloneReceipt(receipt) : undefined\n this.receiptError = toError(receiptError)\n }\n}\n","/** Parse the append-only journal and enforce immutable pending-to-settled transitions. */\nimport { z } from 'zod'\nimport { ValidationError } from '../errors'\nimport type { CostCallBase, CostLedgerRecord, CostReceipt, PendingCostCall } from './contract'\nimport { CostCallConflictError } from './errors'\nimport {\n CostReceiptSchema,\n cloneRecord,\n NonNegative,\n PendingCostCallSchema,\n TokenCount,\n} from './receipts'\nimport { validationMessage } from './validation'\n\ninterface PendingCostCallEvent {\n version: 1\n record: PendingCostCall\n}\n\ninterface SettledCostCallEvent {\n version: 2\n record: CostReceipt\n}\n\ninterface CompletedTasksEvent {\n version: 1\n completedTasks: number\n}\n\ninterface CostLimitEvent {\n version: 1\n costCeilingUsd: number\n}\n\nexport type CostCallEvent = PendingCostCallEvent | SettledCostCallEvent\nexport type CostLedgerEvent = CostCallEvent | CompletedTasksEvent | CostLimitEvent\n\nconst CostLedgerEventSchema = z.union([\n z.strictObject({\n version: z.literal(1),\n record: PendingCostCallSchema,\n }),\n z.strictObject({\n version: z.literal(2),\n record: CostReceiptSchema,\n }),\n z.strictObject({\n version: z.literal(1),\n completedTasks: TokenCount,\n }),\n z.strictObject({\n version: z.literal(1),\n costCeilingUsd: NonNegative,\n }),\n])\n\nexport function parseEvents(serialized: string): {\n records: CostLedgerRecord[]\n completedTasks: number\n costCeilingUsd?: number\n} {\n const records = new Map<string, CostLedgerRecord>()\n let completedTasks = 0\n let costCeilingUsd: number | undefined\n let lineNumber = 0\n try {\n for (const line of completeJournalPrefix(serialized).split('\\n')) {\n if (!line.trim()) continue\n lineNumber += 1\n const event = CostLedgerEventSchema.parse(JSON.parse(line)) as CostLedgerEvent\n if ('record' in event) {\n const record = event.record\n validateTransition(records, record)\n records.set(record.callId, cloneRecord(record))\n } else if ('completedTasks' in event) {\n completedTasks += event.completedTasks\n if (!Number.isSafeInteger(completedTasks)) {\n throw new ValidationError('CostLedger: completed task count exceeds safe integer range')\n }\n } else {\n if (costCeilingUsd !== undefined) {\n throw new ValidationError('CostLedger: duplicate persisted cost ceiling')\n }\n costCeilingUsd = event.costCeilingUsd\n }\n }\n return {\n records: [...records.values()],\n completedTasks,\n ...(costCeilingUsd === undefined ? {} : { costCeilingUsd }),\n }\n } catch (cause) {\n throw new ValidationError(\n `CostLedger: invalid persisted event ${lineNumber || 1}: ${validationMessage(cause)}`,\n { cause },\n )\n }\n}\n\nfunction completeJournalPrefix(serialized: string): string {\n if (!serialized || serialized.endsWith('\\n')) return serialized\n const finalNewline = serialized.lastIndexOf('\\n')\n const tail = serialized.slice(finalNewline + 1)\n try {\n JSON.parse(tail)\n } catch {\n return finalNewline < 0 ? '' : serialized.slice(0, finalNewline + 1)\n }\n throw new ValidationError(\n 'CostLedger: complete final persisted event is missing its newline terminator',\n )\n}\n\nexport function validateTransition(\n records: ReadonlyMap<string, CostLedgerRecord>,\n record: CostLedgerRecord,\n): void {\n const current = records.get(record.callId)\n if (!current) return\n if (record.status === 'pending' || current.status === 'settled') {\n throw new CostCallConflictError(`CostLedger: duplicate callId '${record.callId}'`)\n }\n if (!sameAttribution(current, record)) {\n throw new ValidationError(`CostLedger: receipt attribution changed for call '${record.callId}'`)\n }\n}\n\nfunction sameAttribution(before: CostCallBase, after: CostCallBase): boolean {\n return (\n before.channel === after.channel &&\n before.phase === after.phase &&\n before.actor === after.actor &&\n before.maximumCostUsd === after.maximumCostUsd &&\n before.timestamp === after.timestamp &&\n sameTags(before.tags, after.tags)\n )\n}\n\nfunction sameTags(\n left: Readonly<Record<string, string>> | undefined,\n right: Readonly<Record<string, string>> | undefined,\n): boolean {\n const leftEntries = Object.entries(left ?? {}).sort(([a], [b]) => a.localeCompare(b))\n const rightEntries = Object.entries(right ?? {}).sort(([a], [b]) => a.localeCompare(b))\n return JSON.stringify(leftEntries) === JSON.stringify(rightEntries)\n}\n","/** Derive attribution rollups and accounting completeness from one snapshot of ledger records. */\nimport type {\n ChannelRollup,\n CostBreakdown,\n CostChannel,\n CostLedgerRecord,\n CostLedgerSummary,\n CostProvenance,\n CostReceipt,\n PendingCostCall,\n} from './contract'\n\nexport function summarizeCostLedger(\n records: readonly CostLedgerRecord[],\n activeCallIds: ReadonlySet<string>,\n lateCallIds: ReadonlySet<string>,\n): CostLedgerSummary {\n const pending = records.filter((record): record is PendingCostCall => record.status === 'pending')\n const receipts = records.filter((record): record is CostReceipt => record.status === 'settled')\n const byChannel = new Map<string, ChannelRollup>()\n const unpriced = new Set<string>()\n const incompleteReasons: string[] = pending.map(\n (record) => `call '${record.callId}' for '${record.actor}' is pending`,\n )\n let inputTokens = 0\n let outputTokens = 0\n let reasoningTokens = 0\n let cachedTokens = 0\n let cacheWriteTokens = 0\n let totalCostUsd = 0\n\n for (const receipt of receipts) {\n inputTokens += receipt.inputTokens\n outputTokens += receipt.outputTokens\n reasoningTokens += receipt.reasoningTokens ?? 0\n cachedTokens += receipt.cachedTokens ?? 0\n cacheWriteTokens += receipt.cacheWriteTokens ?? 0\n totalCostUsd += receipt.costUsd\n if (receipt.costUnknown) {\n unpriced.add(receipt.model)\n incompleteReasons.push(\n receipt.error ?? `cost unknown for '${receipt.actor}' using '${receipt.model}'`,\n )\n }\n if (receipt.usageUnknown) {\n incompleteReasons.push(`token usage unknown for '${receipt.actor}' using '${receipt.model}'`)\n }\n if (receipt.maximumCostUsd !== undefined && receipt.costUsd > receipt.maximumCostUsd) {\n incompleteReasons.push(\n `'${receipt.actor}' charged ${receipt.costUsd}, exceeding its enforced maximum ${receipt.maximumCostUsd}`,\n )\n }\n const rollup = byChannel.get(receipt.channel) ?? emptyRollup(receipt.channel)\n rollup.calls += 1\n rollup.inputTokens += receipt.inputTokens\n rollup.outputTokens += receipt.outputTokens\n rollup.reasoningTokens = (rollup.reasoningTokens ?? 0) + (receipt.reasoningTokens ?? 0)\n rollup.cachedTokens += receipt.cachedTokens ?? 0\n rollup.cacheWriteTokens = (rollup.cacheWriteTokens ?? 0) + (receipt.cacheWriteTokens ?? 0)\n rollup.costUsd += receipt.costUsd\n if (receipt.costUnknown) rollup.unpricedCalls += 1\n if (receipt.usageUnknown) rollup.unknownUsageCalls += 1\n byChannel.set(receipt.channel, rollup)\n }\n\n return {\n ...(receipts.some((r) => r.costBreakdown)\n ? { costBreakdown: summarizeBreakdown(records) }\n : {}),\n totalCalls: receipts.length,\n pendingCalls: pending.length,\n unresolvedCalls: pending.filter(\n (record) => !activeCallIds.has(record.callId) || lateCallIds.has(record.callId),\n ).length,\n reservedCostUsd: pending.reduce((sum, record) => sum + (record.maximumCostUsd ?? 0), 0),\n inputTokens,\n outputTokens,\n reasoningTokens,\n cachedTokens,\n cacheWriteTokens,\n totalCostUsd,\n costProvenance:\n pending.length > 0 || receipts.some((receipt) => receipt.costUnknown)\n ? { kind: 'uncaptured', usd: null }\n : receipts.every((receipt) => receipt.actualCostUsd !== undefined)\n ? { kind: 'observed', usd: totalCostUsd }\n : { kind: 'estimated', usd: totalCostUsd },\n byChannel: [...byChannel.values()].sort((a, b) => a.channel.localeCompare(b.channel)),\n unpricedModels: [...unpriced].sort(),\n fullyPriced: unpriced.size === 0,\n usageComplete: pending.length === 0 && receipts.every((receipt) => !receipt.usageUnknown),\n accountingComplete: incompleteReasons.length === 0,\n incompleteReasons: [...new Set(incompleteReasons)],\n }\n}\n\nfunction emptyRollup(channel: CostChannel): ChannelRollup {\n return {\n channel,\n calls: 0,\n inputTokens: 0,\n outputTokens: 0,\n reasoningTokens: 0,\n cachedTokens: 0,\n cacheWriteTokens: 0,\n costUsd: 0,\n unpricedCalls: 0,\n unknownUsageCalls: 0,\n }\n}\n\nfunction summarizeBreakdown(records: readonly CostLedgerRecord[]): CostBreakdown {\n const details = records.map((r) => (r.status === 'settled' ? r.costBreakdown : undefined))\n const money = (key: 'router' | 'sandbox'): CostProvenance => {\n if (details.some((d) => !d || d[key].kind === 'uncaptured'))\n return { kind: 'uncaptured', usd: null }\n const values = details.map((d) => d![key])\n return {\n kind: values.every((v) => v.kind === 'observed') ? 'observed' : 'estimated',\n usd: values.reduce((sum, v) => sum + (v.usd ?? 0), 0),\n }\n }\n return {\n router: money('router'),\n sandbox: money('sandbox'),\n seatCredits: details.some((d) => !d || d.seatCredits.kind === 'uncaptured')\n ? {\n kind: 'uncaptured',\n credits: null,\n reason: 'One or more calls lack captured standard model credits',\n }\n : {\n kind: 'estimated',\n credits: details.reduce((sum, d) => sum + (d!.seatCredits.credits ?? 0), 0),\n },\n sources: structuredClone(details.flatMap((d) => d?.sources ?? [])),\n }\n}\n","/** Run-wide paid-call admission and durable call state. */\n\nimport type {\n CostLedgerFilter,\n CostLedgerOptions,\n CostLedgerPersistence,\n CostLedgerRecord,\n CostLedgerSummary,\n CostLedgerWaitOptions,\n CostReceipt,\n CostReceiptInput,\n MaximumCharge,\n PaidCallResult,\n PendingCostCall,\n PendingCostCallView,\n RunPaidCallInput,\n} from './cost-ledger/contract'\nimport {\n CostAccountingIncompleteError,\n CostCallConflictError,\n CostCeilingReachedError,\n CostLedgerPersistenceError,\n CostReceiptCaptureError,\n CostReservationExceededError,\n} from './cost-ledger/errors'\nimport type { CostCallEvent, CostLedgerEvent } from './cost-ledger/journal'\nimport { parseEvents, validateTransition } from './cost-ledger/journal'\nimport { costForTokenPricing, costForUsage } from './cost-ledger/pricing'\nimport {\n buildReceipt,\n clonePendingCall,\n cloneReceipt,\n cloneRecord,\n matches,\n parseImportedReceipt,\n validateAttribution,\n} from './cost-ledger/receipts'\nimport { summarizeCostLedger } from './cost-ledger/summary'\nimport { assertNonNegative, assertString, assertTimeout, toError } from './cost-ledger/validation'\nimport { ValidationError } from './errors'\n\nexport type {\n ChannelRollup,\n CostBreakdown,\n CostChannel,\n CostLedgerFilter,\n CostLedgerHandle,\n CostLedgerOptions,\n CostLedgerPersistence,\n CostLedgerRecord,\n CostLedgerSummary,\n CostLedgerWaitOptions,\n CostProvenance,\n CostReceipt,\n CostReceiptInput,\n CostUsage,\n CustomTokenPricing,\n MaximumCharge,\n PaidCallResult,\n PendingCostCall,\n PendingCostCallView,\n RunPaidCallInput,\n} from './cost-ledger/contract'\nexport {\n CostAccountingIncompleteError,\n CostCallConflictError,\n CostCeilingReachedError,\n CostLedgerPersistenceError,\n CostReceiptCaptureError,\n CostReservationExceededError,\n} from './cost-ledger/errors'\nexport type { CostResult } from './cost-ledger/pricing'\nexport { costForTokenPricing, costForUsage } from './cost-ledger/pricing'\n\n/** Run-wide paid-call admission, durable call state, receipts, and summaries. */\nexport class CostLedger {\n private readonly records = new Map<string, CostLedgerRecord>()\n private readonly activeCallIds = new Set<string>()\n private readonly lateCallIds = new Set<string>()\n private readonly idleWaiters = new Set<() => void>()\n private completedTasks = 0\n private revision = 'memory'\n private costLimitPersisted = false\n readonly costCeilingUsd?: number\n private readonly persistence?: CostLedgerPersistence\n\n constructor(input?: number | CostLedgerOptions) {\n const options = typeof input === 'number' ? { costCeilingUsd: input } : (input ?? {})\n this.persistence = options.persistence\n if (options.costCeilingUsd !== undefined) {\n assertNonNegative(options.costCeilingUsd, 'costCeilingUsd')\n }\n\n let persistedCostCeilingUsd: number | undefined\n if (this.persistence) {\n let stored: ReturnType<CostLedgerPersistence['read']>\n try {\n stored = this.persistence.read()\n } catch (cause) {\n throw new CostLedgerPersistenceError(cause)\n }\n assertString(stored.revision, 'persistence revision')\n this.revision = stored.revision\n const restored = parseEvents(stored.events)\n for (const record of restored.records) this.records.set(record.callId, record)\n this.completedTasks = restored.completedTasks\n persistedCostCeilingUsd = restored.costCeilingUsd\n }\n\n if (\n options.costCeilingUsd !== undefined &&\n persistedCostCeilingUsd !== undefined &&\n options.costCeilingUsd !== persistedCostCeilingUsd\n ) {\n throw new ValidationError(\n `CostLedger: requested cost ceiling ${options.costCeilingUsd} does not match persisted ceiling ${persistedCostCeilingUsd}`,\n )\n }\n this.costCeilingUsd = persistedCostCeilingUsd ?? options.costCeilingUsd\n this.costLimitPersisted =\n !this.persistence ||\n this.costCeilingUsd === undefined ||\n persistedCostCeilingUsd !== undefined\n\n if (\n this.costCeilingUsd !== undefined &&\n [...this.records.values()].some(\n (record) => record.status === 'pending' && record.maximumCostUsd === undefined,\n )\n ) {\n throw new ValidationError('CostLedger: capped event log contains an unbounded pending call')\n }\n\n if (options.receipts?.length) {\n const imported = options.receipts.map((receipt, index) =>\n parseImportedReceipt(receipt, `imported receipt ${index + 1}`),\n )\n this.ensureCostLimitPersisted()\n for (const receipt of imported) this.appendRecord(receipt)\n }\n }\n\n async runPaidCall<T>(input: RunPaidCallInput<T>): Promise<PaidCallResult<T>> {\n let callId: string | undefined\n let pending: PendingCostCall | undefined\n try {\n callId = resolveCallId(input.callId)\n validateAttribution(input)\n if (input.signal?.aborted) {\n return { succeeded: false, callId, error: abortError(input.signal) }\n }\n this.ensureCostLimitPersisted(callId)\n\n const maximumCostUsd = this.resolveMaximum(input.maximumCharge)\n const existing = this.records.get(callId)\n if (existing) {\n return {\n succeeded: false,\n callId,\n error: new CostCallConflictError(\n existing.status === 'pending'\n ? `CostLedger: callId '${callId}' is unresolved and must be reconciled before retry`\n : `CostLedger: callId '${callId}' already exists`,\n { callId },\n ),\n }\n }\n\n if (!pending) {\n while (true) {\n if (this.records.has(callId)) {\n return {\n succeeded: false,\n callId,\n error: new CostCallConflictError(`CostLedger: callId '${callId}' already exists`),\n }\n }\n const admission = this.admissionState()\n if (admission.unresolvedCalls > 0) {\n return {\n succeeded: false,\n callId,\n error: new CostAccountingIncompleteError(\n `CostLedger: ${admission.unresolvedCalls} unresolved call(s) must be reconciled before new paid work`,\n ),\n }\n }\n if (this.costCeilingUsd === undefined) break\n if (admission.budgetBreached) {\n return {\n succeeded: false,\n callId,\n error: new CostAccountingIncompleteError(\n `CostLedger: a settled call exceeded its enforced maximum; refusing paid call '${input.actor}' during '${input.phase}'`,\n ),\n }\n }\n // A settled call whose cost the provider left unknown is charged its\n // reserved maximum here, so the ceiling is enforced against a real\n // upper bound and one under-reported response cannot let later calls\n // silently exceed the budget — while still permitting them.\n const { committedCostUsd } = admission\n if (committedCostUsd + maximumCostUsd! > this.costCeilingUsd) {\n return {\n succeeded: false,\n callId,\n error: new CostCeilingReachedError(\n this.costCeilingUsd,\n committedCostUsd,\n maximumCostUsd!,\n input.phase,\n input.actor,\n ),\n }\n }\n if (\n committedCostUsd + admission.reservedCostUsd + maximumCostUsd! <=\n this.costCeilingUsd\n ) {\n break\n }\n await this.waitForReservationRelease(input.signal)\n }\n\n pending = {\n status: 'pending',\n callId,\n channel: input.channel,\n phase: input.phase,\n actor: input.actor,\n model: pendingModel(input),\n ...(maximumCostUsd === undefined ? {} : { maximumCostUsd }),\n ...(input.tags ? { tags: { ...input.tags } } : {}),\n timestamp: Date.now(),\n }\n this.appendRecord(pending)\n this.activeCallIds.add(callId)\n }\n } catch (error) {\n return { succeeded: false, ...(callId ? { callId } : {}), error: toError(error) }\n }\n\n try {\n return await this.execute(input, pending)\n } catch (error) {\n return { succeeded: false, callId: pending.callId, error: toError(error) }\n } finally {\n if (!this.lateCallIds.has(pending.callId)) this.releaseActiveCall(pending.callId)\n }\n }\n\n /** Wait until every call started by this ledger has produced a durable outcome. */\n async waitForIdle(options: CostLedgerWaitOptions = {}): Promise<boolean> {\n const hasActiveMatch = (): boolean =>\n [...this.activeCallIds].some((callId) => {\n const record = this.records.get(callId)\n return record !== undefined && matches(record, options.filter)\n })\n if (!hasActiveMatch()) return true\n const timeoutMs = options.timeoutMs ?? 5_000\n assertTimeout(timeoutMs, 'waitForIdle.timeoutMs')\n return new Promise<boolean>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n const finish = (settled: boolean): void => {\n this.idleWaiters.delete(onIdle)\n if (timer !== undefined) clearTimeout(timer)\n resolve(settled)\n }\n const onIdle = (): void => {\n if (!hasActiveMatch()) finish(true)\n }\n this.idleWaiters.add(onIdle)\n timer = setTimeout(() => finish(false), timeoutMs)\n onIdle()\n })\n }\n\n /** Settle a call left pending by a crashed process after reconciling with the provider. */\n reconcile(\n callId: string,\n observed: CostReceiptInput,\n options: { failed?: boolean; error?: string } = {},\n ): CostReceipt {\n const pending = this.records.get(callId)\n if (pending?.status !== 'pending') {\n throw new CostCallConflictError(`CostLedger: no pending call '${callId}'`)\n }\n if (this.activeCallIds.has(callId)) {\n throw new CostCallConflictError(`CostLedger: call '${callId}' is still active`)\n }\n this.ensureCostLimitPersisted(callId)\n return this.commitReceipt(\n pending,\n observed,\n options.failed === true || options.error !== undefined,\n options.error,\n )\n }\n\n list(filter?: CostLedgerFilter): CostReceipt[] {\n return [...this.records.values()]\n .filter((record): record is CostReceipt => record.status === 'settled')\n .filter((receipt) => matches(receipt, filter))\n .map(cloneReceipt)\n }\n\n /** Read pending calls without exposing mutable ledger state. */\n listPending(filter?: CostLedgerFilter): PendingCostCallView[] {\n return [...this.records.values()]\n .filter((record): record is PendingCostCall => record.status === 'pending')\n .filter((record) => matches(record, filter))\n .map((record) => ({\n ...clonePendingCall(record),\n state: this.lateCallIds.has(record.callId)\n ? 'late'\n : this.activeCallIds.has(record.callId)\n ? 'active'\n : 'interrupted',\n }))\n }\n\n summary(filter?: CostLedgerFilter): CostLedgerSummary {\n const records = [...this.records.values()].filter((record) => matches(record, filter))\n return summarizeCostLedger(records, this.activeCallIds, this.lateCallIds)\n }\n markCompleted(count = 1): void {\n if (!Number.isInteger(count) || count < 0) {\n throw new ValidationError(\n `CostLedger.markCompleted: count must be a non-negative integer, got ${count}`,\n )\n }\n if (count === 0) return\n this.ensureCostLimitPersisted()\n this.appendEvent({ version: 1, completedTasks: count })\n this.completedTasks += count\n }\n\n costPerCompletedTask(): number | null {\n return this.completedTasks === 0 ? null : this.summary().totalCostUsd / this.completedTasks\n }\n\n private async execute<T>(\n input: RunPaidCallInput<T>,\n pending: PendingCostCall,\n ): Promise<PaidCallResult<T>> {\n const signal = input.signal ?? new AbortController().signal\n if (signal.aborted) {\n return this.commitOutcome(pending, abortError(signal), {\n model: pending.model,\n inputTokens: 0,\n outputTokens: 0,\n actualCostUsd: 0,\n })\n }\n\n const operation = Promise.resolve().then(() => input.execute(signal, pending.callId))\n const settled = await settle(operation, signal)\n if (settled.kind === 'aborted') {\n this.lateCallIds.add(pending.callId)\n this.captureLateOutcome(input, pending, operation)\n return paidFailure(pending.callId, abortError(signal))\n }\n if (settled.kind === 'error') {\n let observed: CostReceiptInput | undefined\n try {\n observed = input.receiptFromError?.(settled.error)\n } catch (receiptError) {\n return this.captureFailure(pending, settled.error, receiptError)\n }\n return this.commitOutcome(pending, settled.error, observed ?? unknownReceipt(pending.model))\n }\n\n try {\n const receipt = this.commitReceipt(pending, input.receipt(settled.value))\n if (receipt.maximumCostUsd !== undefined && receipt.costUsd > receipt.maximumCostUsd) {\n return paidFailure(\n pending.callId,\n new CostReservationExceededError(pending.actor, receipt.costUsd, receipt.maximumCostUsd),\n receipt,\n )\n }\n return { succeeded: true, callId: pending.callId, value: settled.value, receipt }\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return paidFailure(pending.callId, receiptError)\n }\n return this.captureFailure(pending, receiptError, receiptError)\n }\n }\n\n private captureLateOutcome<T>(\n input: RunPaidCallInput<T>,\n pending: PendingCostCall,\n operation: Promise<T>,\n ): void {\n void operation\n .then(\n (value) => {\n if (this.records.get(pending.callId)?.status !== 'pending') return\n try {\n this.commitReceipt(pending, input.receipt(value))\n } catch {\n // A failed durable settlement leaves the reservation pending and blocks new paid work.\n }\n },\n (cause) => {\n if (this.records.get(pending.callId)?.status !== 'pending') return\n const error = toError(cause)\n try {\n const observed = input.receiptFromError?.(error)\n this.commitReceipt(pending, observed ?? unknownReceipt(pending.model), true)\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return\n }\n this.captureFailure(pending, error, receiptError)\n }\n },\n )\n .finally(() => {\n this.lateCallIds.delete(pending.callId)\n this.releaseActiveCall(pending.callId)\n })\n }\n\n private releaseActiveCall(callId: string): void {\n this.activeCallIds.delete(callId)\n for (const resolve of [...this.idleWaiters]) resolve()\n }\n\n private async waitForReservationRelease(signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) throw abortError(signal)\n await new Promise<void>((resolve, reject) => {\n let finished = false\n const finish = (error?: Error): void => {\n if (finished) return\n finished = true\n this.idleWaiters.delete(onRelease)\n signal?.removeEventListener('abort', onAbort)\n if (error) reject(error)\n else resolve()\n }\n const onRelease = (): void => finish()\n const onAbort = (): void => finish(abortError(signal!))\n this.idleWaiters.add(onRelease)\n signal?.addEventListener('abort', onAbort, { once: true })\n if (this.activeCallIds.size === 0) onRelease()\n })\n }\n\n private commitOutcome<T>(\n pending: PendingCostCall,\n error: Error,\n observed: CostReceiptInput,\n ): PaidCallResult<T> {\n try {\n const receipt = this.commitReceipt(pending, observed, true)\n return paidFailure(pending.callId, error, receipt)\n } catch (receiptError) {\n if (\n receiptError instanceof CostLedgerPersistenceError ||\n receiptError instanceof CostCallConflictError\n ) {\n return paidFailure(pending.callId, receiptError)\n }\n return this.captureFailure(pending, error, receiptError)\n }\n }\n\n private captureFailure<T>(\n pending: PendingCostCall,\n cause: unknown,\n receiptError: unknown,\n ): PaidCallResult<T> {\n try {\n const receipt = this.commitReceipt(pending, unknownReceipt(pending.model), true)\n return paidFailure(\n pending.callId,\n new CostReceiptCaptureError(pending.callId, cause, receiptError, receipt),\n receipt,\n )\n } catch (error) {\n const typed = error instanceof Error ? error : toError(error)\n return paidFailure(pending.callId, typed)\n }\n }\n\n private commitReceipt(\n pending: PendingCostCall,\n observed: CostReceiptInput,\n failed = false,\n error?: string,\n ): CostReceipt {\n const receipt = buildReceipt(pending, observed, failed, error)\n if (this.records.get(pending.callId)?.status !== 'pending') {\n throw new CostCallConflictError(`CostLedger: call '${pending.callId}' is not pending`)\n }\n this.appendRecord(receipt)\n return cloneReceipt(receipt)\n }\n\n private resolveMaximum(maximum: MaximumCharge | undefined): number | undefined {\n if (!maximum) {\n if (this.costCeilingUsd !== undefined) {\n throw new CostAccountingIncompleteError(\n 'CostLedger: capped paid calls require a hard maximumCharge before execution',\n )\n }\n return undefined\n }\n if ('externallyEnforcedMaximumUsd' in maximum) {\n assertNonNegative(\n maximum.externallyEnforcedMaximumUsd,\n 'maximumCharge.externallyEnforcedMaximumUsd',\n )\n return maximum.externallyEnforcedMaximumUsd\n }\n if ('customTokenPricing' in maximum) {\n return costForTokenPricing(maximum.customTokenPricing, maximum)\n }\n const priced = costForUsage(maximum.model, maximum)\n if (priced.costUnknown) {\n if (this.costCeilingUsd !== undefined) {\n throw new CostAccountingIncompleteError(\n `CostLedger: cannot reserve unpriced model '${maximum.model}' in a capped run`,\n )\n }\n return undefined\n }\n return priced.costUsd\n }\n\n /** Compute admission totals in record order without building reporting rollups. */\n private admissionState() {\n let unresolvedCalls = 0\n let reservedCostUsd = 0\n let committedCostUsd = 0\n let budgetBreached = false\n for (const record of this.records.values()) {\n if (record.status === 'pending') {\n if (!this.activeCallIds.has(record.callId) || this.lateCallIds.has(record.callId)) {\n unresolvedCalls += 1\n }\n reservedCostUsd += record.maximumCostUsd ?? 0\n } else {\n if (record.maximumCostUsd !== undefined && record.costUsd > record.maximumCostUsd) {\n budgetBreached = true\n }\n // Unknown settled costs consume their reserved maximum for admission.\n committedCostUsd += record.costUnknown\n ? (record.maximumCostUsd ?? record.costUsd)\n : record.costUsd\n }\n }\n return { unresolvedCalls, reservedCostUsd, committedCostUsd, budgetBreached }\n }\n\n private appendRecord(record: CostLedgerRecord): void {\n const callId = record.callId\n const receipt = record.status === 'settled' ? record : undefined\n validateTransition(this.records, record)\n const event: CostCallEvent =\n record.status === 'settled'\n ? { version: 2, record: cloneReceipt(record) }\n : { version: 1, record: clonePendingCall(record) }\n this.appendEvent(event, callId, receipt)\n this.records.set(callId, cloneRecord(record))\n }\n\n private ensureCostLimitPersisted(callId?: string): void {\n if (this.costLimitPersisted || this.costCeilingUsd === undefined) return\n this.appendEvent({ version: 1, costCeilingUsd: this.costCeilingUsd }, callId)\n this.costLimitPersisted = true\n }\n\n private appendEvent(event: CostLedgerEvent, callId?: string, receipt?: CostReceipt): void {\n try {\n if (this.persistence) {\n const nextRevision = this.persistence.append(this.revision, `${JSON.stringify(event)}\\n`)\n if (nextRevision === undefined) {\n throw new CostCallConflictError(\n `CostLedger: persisted revision changed while writing call '${callId}'`,\n { callId, receipt },\n )\n }\n assertString(nextRevision, 'persistence revision')\n this.revision = nextRevision\n }\n } catch (cause) {\n if (cause instanceof CostCallConflictError) throw cause\n throw new CostLedgerPersistenceError(cause, callId, receipt)\n }\n }\n}\n\ntype Settled<T> =\n | { kind: 'value'; value: T }\n | { kind: 'error'; error: Error }\n | { kind: 'aborted' }\n\nasync function settle<T>(promise: Promise<T>, signal: AbortSignal): Promise<Settled<T>> {\n return await new Promise((resolve) => {\n let done = false\n const finish = (value: Settled<T>): void => {\n if (done) return\n done = true\n signal.removeEventListener('abort', onAbort)\n resolve(value)\n }\n const onAbort = () => finish({ kind: 'aborted' })\n signal.addEventListener('abort', onAbort, { once: true })\n if (signal.aborted) onAbort()\n promise.then(\n (value) => finish({ kind: 'value', value }),\n (error) => finish({ kind: 'error', error: toError(error) }),\n )\n })\n}\n\nfunction pendingModel(input: RunPaidCallInput<unknown>): string {\n if (input.model) return input.model\n if (input.maximumCharge && 'model' in input.maximumCharge) return input.maximumCharge.model\n return 'unknown'\n}\n\nfunction unknownReceipt(model: string): CostReceiptInput {\n return { model, inputTokens: 0, outputTokens: 0, costUnknown: true, usageUnknown: true }\n}\n\nfunction resolveCallId(input: string | undefined): string {\n if (input !== undefined) {\n assertString(input, 'callId')\n return input\n }\n if (typeof globalThis.crypto?.randomUUID !== 'function') {\n throw new ValidationError('CostLedger: crypto.randomUUID is required when callId is omitted')\n }\n return globalThis.crypto.randomUUID()\n}\n\nfunction abortError(signal: AbortSignal): Error {\n const reason = (signal as { reason?: unknown }).reason\n if (reason instanceof Error) return reason\n const error = new Error('CostLedger: paid call aborted')\n error.name = 'AbortError'\n return error\n}\n\nfunction paidFailure<T>(callId: string, error: Error, receipt?: CostReceipt): PaidCallResult<T> {\n return {\n succeeded: false,\n callId,\n error,\n ...(receipt ? { receipt: cloneReceipt(receipt) } : {}),\n }\n}\n"],"mappings":";;;;AAMA,MAAa,gBAA4C;CACvD,UAAU;EAAE,OAAO;EAAQ,QAAQ;CAAK;CACxC,eAAe;EAAE,OAAO;EAAS,QAAQ;CAAO;CAChD,eAA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AAM,cAAc;CAAK;AACzF;AAEA,SAAS,cAAc,OAAmC;CACxD,IAAI,UAAU,KAAA,GAAW;EACvB,aAAa,OAAO,QAAQ;EAC5B,OAAO;CACT;CACA,IAAI,OAAO,WAAW,QAAQ,eAAe,YAC3C,MAAM,IAAI,gBAAgB,kEAAkE;CAE9F,OAAO,WAAW,OAAO,WAAW;AACtC;AAEA,SAAS,WAAW,QAA4B;CAC9C,MAAM,SAAU,OAAgC;CAChD,IAAI,kBAAkB,OAAO,OAAO;CACpC,MAAM,wBAAQ,IAAI,MAAM,+BAA+B;CACvD,MAAM,OAAO;CACb,OAAO;AACT;AAEA,SAAS,YAAe,QAAgB,OAAc,SAA0C;CAC9F,OAAO;EACL,WAAW;EACX;EACA;EACA,GAAI,UAAU,EAAE,SAAS,aAAa,OAAO,EAAE,IAAI,CAAC;CACtD;AACF"}
@@ -6,7 +6,7 @@ import { t as deepFreezeCanonicalJson } from "./deep-freeze-CK8-2W7p.js";
6
6
  import { i as makeFinding } from "./types-CL1_N7AZ.js";
7
7
  import { r as calibrationFromPairs } from "./calibration-Cf-wpqqO.js";
8
8
  import { parseSystemOneQuestions, parseSystemOneRequest, parseSystemOneResult, systemOneUsage } from "./systemone-protocol.js";
9
- import { n as asJudge, r as createEvaluator, t as asAnalyst } from "./evaluation-bU_bhlv-.js";
9
+ import { n as asJudge, r as createEvaluator, t as asAnalyst } from "./evaluation-C_GJvEEG.js";
10
10
  import "./systemone-review-BusEIzsg.js";
11
11
  import { randomUUID } from "node:crypto";
12
12
  import { z } from "zod";
@@ -836,4 +836,4 @@ function decisionPoint(options) {
836
836
  }
837
837
  export { normalizedSystemOneScore as a, systemOneJudge as c, systemOneChoiceMargin as d, decisionAnswerSchema as f, decisionQuestionDigest as i, assessSystemOneDomainMatch as l, validDecisionIdentity as m, DECISION_POINT_MIN_KAPPA as n, systemOneAnalyst as o, decisionCalibrationSchema as p, decisionPoint as r, systemOneEvaluator as s, DECISION_POINT_AUC_BAR as t, prepareSystemOneDomainMatch as u };
838
838
 
839
- //# sourceMappingURL=decision-point-Di2LATNH.js.map
839
+ //# sourceMappingURL=decision-point-CQOczIIH.js.map