@tangle-network/agent-eval 0.129.0 → 0.130.1

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 (428) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +2 -0
  3. package/dist/active-curriculum-C4mk67HP.js +214 -0
  4. package/dist/active-curriculum-C4mk67HP.js.map +1 -0
  5. package/dist/adversarial-smnADNFS.d.ts +21 -0
  6. package/dist/adversarial-smnADNFS.d.ts.map +1 -0
  7. package/dist/analyst/index.d.ts +81 -2872
  8. package/dist/analyst/index.d.ts.map +1 -0
  9. package/dist/analyst/index.js +319 -360
  10. package/dist/analyst/index.js.map +1 -1
  11. package/dist/analyst-BkTS3C58.d.ts +89 -0
  12. package/dist/analyst-BkTS3C58.d.ts.map +1 -0
  13. package/dist/analyst-LsnNpSkm.js +152 -0
  14. package/dist/analyst-LsnNpSkm.js.map +1 -0
  15. package/dist/analyze-runs-C1CavBMk.js +1067 -0
  16. package/dist/analyze-runs-C1CavBMk.js.map +1 -0
  17. package/dist/analyze-runs-FsgYCinh.d.ts +72 -0
  18. package/dist/analyze-runs-FsgYCinh.d.ts.map +1 -0
  19. package/dist/attribute-vocabulary-DLJ6303h.d.ts +54 -0
  20. package/dist/attribute-vocabulary-DLJ6303h.d.ts.map +1 -0
  21. package/dist/authenticity/index.d.ts +81 -79
  22. package/dist/authenticity/index.d.ts.map +1 -0
  23. package/dist/authenticity/index.js +209 -193
  24. package/dist/authenticity/index.js.map +1 -1
  25. package/dist/baseline-HsBvw_dk.js +550 -0
  26. package/dist/baseline-HsBvw_dk.js.map +1 -0
  27. package/dist/baseline-hG3K85h4.d.ts +125 -0
  28. package/dist/baseline-hG3K85h4.d.ts.map +1 -0
  29. package/dist/belief-state/index.d.ts +448 -1188
  30. package/dist/belief-state/index.d.ts.map +1 -0
  31. package/dist/belief-state/index.js +1617 -1709
  32. package/dist/belief-state/index.js.map +1 -1
  33. package/dist/benchmarks/index.d.ts +2 -891
  34. package/dist/benchmarks/index.js +2 -60
  35. package/dist/benchmarks-BJgDGkAD.js +754 -0
  36. package/dist/benchmarks-BJgDGkAD.js.map +1 -0
  37. package/dist/builder-eval/index.d.ts +150 -662
  38. package/dist/builder-eval/index.d.ts.map +1 -0
  39. package/dist/builder-eval/index.js +356 -345
  40. package/dist/builder-eval/index.js.map +1 -1
  41. package/dist/calibration-CNWWA6K8.js +94 -0
  42. package/dist/calibration-CNWWA6K8.js.map +1 -0
  43. package/dist/campaign/index.d.ts +5 -6381
  44. package/dist/campaign/index.js +3 -213
  45. package/dist/campaign-aKJt6emI.js +3886 -0
  46. package/dist/campaign-aKJt6emI.js.map +1 -0
  47. package/dist/cli.d.ts +1 -1
  48. package/dist/cli.js +164 -175
  49. package/dist/cli.js.map +1 -1
  50. package/dist/client-C97NMzqi.d.ts +581 -0
  51. package/dist/client-C97NMzqi.d.ts.map +1 -0
  52. package/dist/client-CYzbdJOZ.js +637 -0
  53. package/dist/client-CYzbdJOZ.js.map +1 -0
  54. package/dist/code-agent-session-BjkMTQ7H.js +1390 -0
  55. package/dist/code-agent-session-BjkMTQ7H.js.map +1 -0
  56. package/dist/code-agent-session-DqqgOJaz.d.ts +143 -0
  57. package/dist/code-agent-session-DqqgOJaz.d.ts.map +1 -0
  58. package/dist/concurrency-DIxRZF_J.js +85 -0
  59. package/dist/concurrency-DIxRZF_J.js.map +1 -0
  60. package/dist/contract/index.d.ts +645 -5565
  61. package/dist/contract/index.d.ts.map +1 -0
  62. package/dist/contract/index.js +1730 -1938
  63. package/dist/contract/index.js.map +1 -1
  64. package/dist/control.d.ts +3 -1030
  65. package/dist/control.js +2 -33
  66. package/dist/cost-ledger-DIgQUFZZ.js +801 -0
  67. package/dist/cost-ledger-DIgQUFZZ.js.map +1 -0
  68. package/dist/cost-ledger-Dye6jCgg.d.ts +236 -0
  69. package/dist/cost-ledger-Dye6jCgg.d.ts.map +1 -0
  70. package/dist/dataset-BvtnC8Dc.d.ts +115 -0
  71. package/dist/dataset-BvtnC8Dc.d.ts.map +1 -0
  72. package/dist/default-registry-C-vFCSEc.js +2579 -0
  73. package/dist/default-registry-C-vFCSEc.js.map +1 -0
  74. package/dist/default-registry-CNPo-Vsb.d.ts +540 -0
  75. package/dist/default-registry-CNPo-Vsb.d.ts.map +1 -0
  76. package/dist/emitter-CPBAhxum.js +266 -0
  77. package/dist/emitter-CPBAhxum.js.map +1 -0
  78. package/dist/emitter-DGQGoLyj.d.ts +113 -0
  79. package/dist/emitter-DGQGoLyj.d.ts.map +1 -0
  80. package/dist/errors-8YnH8WlF.js +64 -0
  81. package/dist/errors-8YnH8WlF.js.map +1 -0
  82. package/dist/errors-CEk209JS.d.ts +76 -0
  83. package/dist/errors-CEk209JS.d.ts.map +1 -0
  84. package/dist/eval-campaign-DEm6c8ru.js +349 -0
  85. package/dist/eval-campaign-DEm6c8ru.js.map +1 -0
  86. package/dist/execution-tracks-CpgFPpS5.js +93 -0
  87. package/dist/execution-tracks-CpgFPpS5.js.map +1 -0
  88. package/dist/exporters-q9iL-2Jf.js +148 -0
  89. package/dist/exporters-q9iL-2Jf.js.map +1 -0
  90. package/dist/extract-usage-BrQ8mCLX.js +155 -0
  91. package/dist/extract-usage-BrQ8mCLX.js.map +1 -0
  92. package/dist/failure-cluster-CqcvCcdR.d.ts +59 -0
  93. package/dist/failure-cluster-CqcvCcdR.d.ts.map +1 -0
  94. package/dist/feedback-trajectory-CVaeREXV.d.ts +340 -0
  95. package/dist/feedback-trajectory-CVaeREXV.d.ts.map +1 -0
  96. package/dist/fuzz.d.ts +320 -646
  97. package/dist/fuzz.d.ts.map +1 -0
  98. package/dist/fuzz.js +670 -618
  99. package/dist/fuzz.js.map +1 -1
  100. package/dist/hf-dataset-DBJXXoY1.js +763 -0
  101. package/dist/hf-dataset-DBJXXoY1.js.map +1 -0
  102. package/dist/hosted/index.d.ts +11 -831
  103. package/dist/hosted/index.d.ts.map +1 -0
  104. package/dist/hosted/index.js +2 -37
  105. package/dist/index-2JJSA6-r2.d.ts +926 -0
  106. package/dist/index-2JJSA6-r2.d.ts.map +1 -0
  107. package/dist/index-6N0aYmpW.d.ts +217 -0
  108. package/dist/index-6N0aYmpW.d.ts.map +1 -0
  109. package/dist/index-BAvgST_9.d.ts +131 -0
  110. package/dist/index-BAvgST_9.d.ts.map +1 -0
  111. package/dist/index-BvnJuTGD.d.ts +68 -0
  112. package/dist/index-BvnJuTGD.d.ts.map +1 -0
  113. package/dist/index-C61Wi7yg.d.ts +547 -0
  114. package/dist/index-C61Wi7yg.d.ts.map +1 -0
  115. package/dist/index-CD_WZ_Xr.d.ts +2250 -0
  116. package/dist/index-CD_WZ_Xr.d.ts.map +1 -0
  117. package/dist/index-DSC51roc.d.ts +102 -0
  118. package/dist/index-DSC51roc.d.ts.map +1 -0
  119. package/dist/index-Em67JBjs.d.ts +335 -0
  120. package/dist/index-Em67JBjs.d.ts.map +1 -0
  121. package/dist/index.d.ts +3755 -15555
  122. package/dist/index.d.ts.map +1 -0
  123. package/dist/index.js +11182 -11216
  124. package/dist/index.js.map +1 -1
  125. package/dist/integrity-BzRbCHzi.js +424 -0
  126. package/dist/integrity-BzRbCHzi.js.map +1 -0
  127. package/dist/integrity-rmVhXWA7.d.ts +61 -0
  128. package/dist/integrity-rmVhXWA7.d.ts.map +1 -0
  129. package/dist/judge-calibration-DFtEMlde.d.ts +146 -0
  130. package/dist/judge-calibration-DFtEMlde.d.ts.map +1 -0
  131. package/dist/ledger-core/index.d.ts +2 -0
  132. package/dist/ledger-core/index.js +2 -0
  133. package/dist/ledger-core-DtZz1RG0.js +388 -0
  134. package/dist/ledger-core-DtZz1RG0.js.map +1 -0
  135. package/dist/llm-client--GR4JbZE.js +687 -0
  136. package/dist/llm-client--GR4JbZE.js.map +1 -0
  137. package/dist/llm-client-B_nIBlYo.d.ts +290 -0
  138. package/dist/llm-client-B_nIBlYo.d.ts.map +1 -0
  139. package/dist/matrix/index.d.ts +3 -155
  140. package/dist/matrix/index.js +2 -8
  141. package/dist/matrix-BzQnu2S6.js +270 -0
  142. package/dist/matrix-BzQnu2S6.js.map +1 -0
  143. package/dist/meta-eval/index.d.ts +4 -1027
  144. package/dist/meta-eval/index.js +393 -390
  145. package/dist/meta-eval/index.js.map +1 -1
  146. package/dist/metrics-C9YY1OcL.js +239 -0
  147. package/dist/metrics-C9YY1OcL.js.map +1 -0
  148. package/dist/mint-yN2M2eh0.js +201 -0
  149. package/dist/mint-yN2M2eh0.js.map +1 -0
  150. package/dist/multi-layer-verifier-BHY1gWAc.d.ts +138 -0
  151. package/dist/multi-layer-verifier-BHY1gWAc.d.ts.map +1 -0
  152. package/dist/multishot/index.d.ts +273 -480
  153. package/dist/multishot/index.d.ts.map +1 -0
  154. package/dist/multishot/index.js +595 -548
  155. package/dist/multishot/index.js.map +1 -1
  156. package/dist/off-policy-DvgzvtIx.js +220 -0
  157. package/dist/off-policy-DvgzvtIx.js.map +1 -0
  158. package/dist/off-policy-mskQw8Mb.d.ts +153 -0
  159. package/dist/off-policy-mskQw8Mb.d.ts.map +1 -0
  160. package/dist/openapi.json +1 -1
  161. package/dist/opencode-sqlite-BGrHeDu3.js +318 -0
  162. package/dist/opencode-sqlite-BGrHeDu3.js.map +1 -0
  163. package/dist/outcome-store-BYHIuO0e.d.ts +65 -0
  164. package/dist/outcome-store-BYHIuO0e.d.ts.map +1 -0
  165. package/dist/outcome-store-ChBKlTd_.js +75 -0
  166. package/dist/outcome-store-ChBKlTd_.js.map +1 -0
  167. package/dist/paired-arms-D9D0wXj2.js +260 -0
  168. package/dist/paired-arms-D9D0wXj2.js.map +1 -0
  169. package/dist/pipelines/index.d.ts +95 -532
  170. package/dist/pipelines/index.d.ts.map +1 -0
  171. package/dist/pipelines/index.js +497 -478
  172. package/dist/pipelines/index.js.map +1 -1
  173. package/dist/pre-registration-DakwTRXk.js +96 -0
  174. package/dist/pre-registration-DakwTRXk.js.map +1 -0
  175. package/dist/propose-review-control-LhIWGzHl.js +1458 -0
  176. package/dist/propose-review-control-LhIWGzHl.js.map +1 -0
  177. package/dist/query-CJ_DX8vl.d.ts +28 -0
  178. package/dist/query-CJ_DX8vl.d.ts.map +1 -0
  179. package/dist/query-Di7eEQ79.js +83 -0
  180. package/dist/query-Di7eEQ79.js.map +1 -0
  181. package/dist/raw-provider-sink-BQd7mzyT.js +201 -0
  182. package/dist/raw-provider-sink-BQd7mzyT.js.map +1 -0
  183. package/dist/raw-provider-sink-BU29Sh8h.d.ts +134 -0
  184. package/dist/raw-provider-sink-BU29Sh8h.d.ts.map +1 -0
  185. package/dist/redact-7Aq1ukl-.js +107 -0
  186. package/dist/redact-7Aq1ukl-.js.map +1 -0
  187. package/dist/release-report-Cz9NKH39.js +603 -0
  188. package/dist/release-report-Cz9NKH39.js.map +1 -0
  189. package/dist/release-report-mvB2G4_J.d.ts +244 -0
  190. package/dist/release-report-mvB2G4_J.d.ts.map +1 -0
  191. package/dist/replay-GnyotH0J.js +1741 -0
  192. package/dist/replay-GnyotH0J.js.map +1 -0
  193. package/dist/replay-OoidtG1E.d.ts +749 -0
  194. package/dist/replay-OoidtG1E.d.ts.map +1 -0
  195. package/dist/reporting.d.ts +6 -1312
  196. package/dist/reporting.js +6 -51
  197. package/dist/researcher-CwTdwXG1.d.ts +314 -0
  198. package/dist/researcher-CwTdwXG1.d.ts.map +1 -0
  199. package/dist/reward-hacking-eAnOsynk.d.ts +224 -0
  200. package/dist/reward-hacking-eAnOsynk.d.ts.map +1 -0
  201. package/dist/reward-hacking-qipEpKvY.js +596 -0
  202. package/dist/reward-hacking-qipEpKvY.js.map +1 -0
  203. package/dist/reward-nw2xZGZG.js +137 -0
  204. package/dist/reward-nw2xZGZG.js.map +1 -0
  205. package/dist/rl.d.ts +760 -4010
  206. package/dist/rl.d.ts.map +1 -0
  207. package/dist/rl.js +2325 -1958
  208. package/dist/rl.js.map +1 -1
  209. package/dist/rolldown-runtime-8H4AJuhK.js +14 -0
  210. package/dist/rollout/index.d.ts +3 -2087
  211. package/dist/rollout/index.js +8 -168
  212. package/dist/rollout-BOYjemfR.js +624 -0
  213. package/dist/rollout-BOYjemfR.js.map +1 -0
  214. package/dist/rubric-predictive-validity-B3xmbmS1.js +141 -0
  215. package/dist/rubric-predictive-validity-B3xmbmS1.js.map +1 -0
  216. package/dist/rubric-predictive-validity-Ku_clp_1.d.ts +74 -0
  217. package/dist/rubric-predictive-validity-Ku_clp_1.d.ts.map +1 -0
  218. package/dist/run-evidence-ClRX_8A9.d.ts +225 -0
  219. package/dist/run-evidence-ClRX_8A9.d.ts.map +1 -0
  220. package/dist/run-record-BuoE80Dq.js +467 -0
  221. package/dist/{chunk-56TAVBOK.js.map → run-record-BuoE80Dq.js.map} +1 -1
  222. package/dist/run-record-CnZu_gjl.d.ts +357 -0
  223. package/dist/run-record-CnZu_gjl.d.ts.map +1 -0
  224. package/dist/run-score-iEEAWiBY.js +41 -0
  225. package/dist/run-score-iEEAWiBY.js.map +1 -0
  226. package/dist/runtime-trajectory-1gyaTOoC.js +93 -0
  227. package/dist/runtime-trajectory-1gyaTOoC.js.map +1 -0
  228. package/dist/runtime-trajectory-BvSZcCHD.d.ts +50 -0
  229. package/dist/runtime-trajectory-BvSZcCHD.d.ts.map +1 -0
  230. package/dist/schema-BtVldJ3T.d.ts +206 -0
  231. package/dist/schema-BtVldJ3T.d.ts.map +1 -0
  232. package/dist/schema-C6DW4ZHR.js +821 -0
  233. package/dist/schema-C6DW4ZHR.js.map +1 -0
  234. package/dist/schema-CRhEY1SO.js +69 -0
  235. package/dist/schema-CRhEY1SO.js.map +1 -0
  236. package/dist/schema-Cef2cFmb.d.ts +408 -0
  237. package/dist/schema-Cef2cFmb.d.ts.map +1 -0
  238. package/dist/semantic-concept-judge-B6cWNJ2K.js +725 -0
  239. package/dist/semantic-concept-judge-B6cWNJ2K.js.map +1 -0
  240. package/dist/sequential-Br0mAPHA.js +148 -0
  241. package/dist/sequential-Br0mAPHA.js.map +1 -0
  242. package/dist/sequential-CYwq6Ff_.d.ts +141 -0
  243. package/dist/sequential-CYwq6Ff_.d.ts.map +1 -0
  244. package/dist/series-convergence-CjO2QdRW.js +43 -0
  245. package/dist/series-convergence-CjO2QdRW.js.map +1 -0
  246. package/dist/series-convergence-ofsqPWhs.d.ts +35 -0
  247. package/dist/series-convergence-ofsqPWhs.d.ts.map +1 -0
  248. package/dist/server-m5D9cvnG.js +1040 -0
  249. package/dist/server-m5D9cvnG.js.map +1 -0
  250. package/dist/skill-usage-C_pXm7lP.d.ts +534 -0
  251. package/dist/skill-usage-C_pXm7lP.d.ts.map +1 -0
  252. package/dist/skillopt-optimization-method-CUmHkGbI.js +7718 -0
  253. package/dist/skillopt-optimization-method-CUmHkGbI.js.map +1 -0
  254. package/dist/skillopt-optimization-method-CWKVTnks.d.ts +1740 -0
  255. package/dist/skillopt-optimization-method-CWKVTnks.d.ts.map +1 -0
  256. package/dist/statistics-Cmj6nynr.d.ts +514 -0
  257. package/dist/statistics-Cmj6nynr.d.ts.map +1 -0
  258. package/dist/statistics-CnnxdpOg.js +1437 -0
  259. package/dist/statistics-CnnxdpOg.js.map +1 -0
  260. package/dist/store-CT9YIIve.d.ts +117 -0
  261. package/dist/store-CT9YIIve.d.ts.map +1 -0
  262. package/dist/store-CxJry_cs.d.ts +229 -0
  263. package/dist/store-CxJry_cs.d.ts.map +1 -0
  264. package/dist/storyboard/index.d.ts +84 -203
  265. package/dist/storyboard/index.d.ts.map +1 -0
  266. package/dist/storyboard/index.js +609 -542
  267. package/dist/storyboard/index.js.map +1 -1
  268. package/dist/summary-report-BNs5nmXI.js +862 -0
  269. package/dist/summary-report-BNs5nmXI.js.map +1 -0
  270. package/dist/summary-report-Cj9gdw4i.d.ts +407 -0
  271. package/dist/summary-report-Cj9gdw4i.d.ts.map +1 -0
  272. package/dist/supervisor-run/index.d.ts +2 -959
  273. package/dist/supervisor-run/index.js +2 -65
  274. package/dist/supervisor-run-_lnTLM3z.js +1679 -0
  275. package/dist/supervisor-run-_lnTLM3z.js.map +1 -0
  276. package/dist/task-failure-attributes-CQZlB3et.js +311 -0
  277. package/dist/task-failure-attributes-CQZlB3et.js.map +1 -0
  278. package/dist/test-graded-scenario-BsqWLmPt.js +318 -0
  279. package/dist/test-graded-scenario-BsqWLmPt.js.map +1 -0
  280. package/dist/test-graded-scenario-D1TaI2va.d.ts +141 -0
  281. package/dist/test-graded-scenario-D1TaI2va.d.ts.map +1 -0
  282. package/dist/tools-BmuN627J.js +1085 -0
  283. package/dist/tools-BmuN627J.js.map +1 -0
  284. package/dist/trace-attributes.d.ts +2 -52
  285. package/dist/trace-attributes.js +131 -61
  286. package/dist/trace-attributes.js.map +1 -1
  287. package/dist/traces.d.ts +12 -2365
  288. package/dist/traces.js +12 -252
  289. package/dist/trajectory-D_7rLrvE.js +56 -0
  290. package/dist/trajectory-D_7rLrvE.js.map +1 -0
  291. package/dist/types-DGsxbAEd.d.ts +387 -0
  292. package/dist/types-DGsxbAEd.d.ts.map +1 -0
  293. package/dist/types-k9tZGKUg.d.ts +640 -0
  294. package/dist/types-k9tZGKUg.d.ts.map +1 -0
  295. package/dist/verdict-Dps8_okt.d.ts +37 -0
  296. package/dist/verdict-Dps8_okt.d.ts.map +1 -0
  297. package/dist/wire/index.d.ts +702 -1173
  298. package/dist/wire/index.d.ts.map +1 -0
  299. package/dist/wire/index.js +2 -81
  300. package/docs/campaign-proposers.md +1 -0
  301. package/package.json +17 -9
  302. package/dist/benchmarks/index.js.map +0 -1
  303. package/dist/campaign/index.js.map +0 -1
  304. package/dist/chunk-2QU3YOPR.js +0 -7374
  305. package/dist/chunk-2QU3YOPR.js.map +0 -1
  306. package/dist/chunk-3OCR4R5I.js +0 -728
  307. package/dist/chunk-3OCR4R5I.js.map +0 -1
  308. package/dist/chunk-3RF76KTD.js +0 -84
  309. package/dist/chunk-3RF76KTD.js.map +0 -1
  310. package/dist/chunk-56TAVBOK.js +0 -698
  311. package/dist/chunk-5DTSBUL2.js +0 -159
  312. package/dist/chunk-5DTSBUL2.js.map +0 -1
  313. package/dist/chunk-7FO3TNPI.js +0 -232
  314. package/dist/chunk-7FO3TNPI.js.map +0 -1
  315. package/dist/chunk-7ZZMD7UK.js +0 -386
  316. package/dist/chunk-7ZZMD7UK.js.map +0 -1
  317. package/dist/chunk-BOD4O7OF.js +0 -40
  318. package/dist/chunk-BOD4O7OF.js.map +0 -1
  319. package/dist/chunk-BSO5JDQH.js +0 -2335
  320. package/dist/chunk-BSO5JDQH.js.map +0 -1
  321. package/dist/chunk-C6LXANRU.js +0 -1550
  322. package/dist/chunk-C6LXANRU.js.map +0 -1
  323. package/dist/chunk-DODXQREJ.js +0 -752
  324. package/dist/chunk-DODXQREJ.js.map +0 -1
  325. package/dist/chunk-DRYIUNWY.js +0 -622
  326. package/dist/chunk-DRYIUNWY.js.map +0 -1
  327. package/dist/chunk-E7QXT7SX.js +0 -183
  328. package/dist/chunk-E7QXT7SX.js.map +0 -1
  329. package/dist/chunk-EG66UGL4.js +0 -341
  330. package/dist/chunk-EG66UGL4.js.map +0 -1
  331. package/dist/chunk-FXTVJPYD.js +0 -576
  332. package/dist/chunk-FXTVJPYD.js.map +0 -1
  333. package/dist/chunk-G7MGMCZD.js +0 -153
  334. package/dist/chunk-G7MGMCZD.js.map +0 -1
  335. package/dist/chunk-GGE4NNQT.js +0 -65
  336. package/dist/chunk-GGE4NNQT.js.map +0 -1
  337. package/dist/chunk-H23X7XKK.js +0 -181
  338. package/dist/chunk-H23X7XKK.js.map +0 -1
  339. package/dist/chunk-HHWE3POT.js +0 -94
  340. package/dist/chunk-HHWE3POT.js.map +0 -1
  341. package/dist/chunk-HPWUNB47.js +0 -289
  342. package/dist/chunk-HPWUNB47.js.map +0 -1
  343. package/dist/chunk-IYCLP2N2.js +0 -766
  344. package/dist/chunk-IYCLP2N2.js.map +0 -1
  345. package/dist/chunk-JHCHEVET.js +0 -274
  346. package/dist/chunk-JHCHEVET.js.map +0 -1
  347. package/dist/chunk-JQSF5DQT.js +0 -701
  348. package/dist/chunk-JQSF5DQT.js.map +0 -1
  349. package/dist/chunk-K4DBDHLK.js +0 -158
  350. package/dist/chunk-K4DBDHLK.js.map +0 -1
  351. package/dist/chunk-K6N6XJJX.js +0 -306
  352. package/dist/chunk-K6N6XJJX.js.map +0 -1
  353. package/dist/chunk-M4YBQKIJ.js +0 -1040
  354. package/dist/chunk-M4YBQKIJ.js.map +0 -1
  355. package/dist/chunk-MA6HLL3S.js +0 -65
  356. package/dist/chunk-MA6HLL3S.js.map +0 -1
  357. package/dist/chunk-MAZ26DC7.js +0 -99
  358. package/dist/chunk-MAZ26DC7.js.map +0 -1
  359. package/dist/chunk-NPCTHQIO.js +0 -91
  360. package/dist/chunk-NPCTHQIO.js.map +0 -1
  361. package/dist/chunk-NY44NC4A.js +0 -1056
  362. package/dist/chunk-NY44NC4A.js.map +0 -1
  363. package/dist/chunk-OIUOT4QD.js +0 -44
  364. package/dist/chunk-OIUOT4QD.js.map +0 -1
  365. package/dist/chunk-ONWEPEDO.js +0 -57
  366. package/dist/chunk-ONWEPEDO.js.map +0 -1
  367. package/dist/chunk-OWN5NPMC.js +0 -152
  368. package/dist/chunk-OWN5NPMC.js.map +0 -1
  369. package/dist/chunk-P6FYH6K4.js +0 -1161
  370. package/dist/chunk-P6FYH6K4.js.map +0 -1
  371. package/dist/chunk-PC4UYEBM.js +0 -166
  372. package/dist/chunk-PC4UYEBM.js.map +0 -1
  373. package/dist/chunk-PC5DOSM7.js +0 -579
  374. package/dist/chunk-PC5DOSM7.js.map +0 -1
  375. package/dist/chunk-PXE2VKMX.js +0 -140
  376. package/dist/chunk-PXE2VKMX.js.map +0 -1
  377. package/dist/chunk-PZ5AY32C.js +0 -10
  378. package/dist/chunk-PZ5AY32C.js.map +0 -1
  379. package/dist/chunk-QB6BDBP2.js +0 -4464
  380. package/dist/chunk-QB6BDBP2.js.map +0 -1
  381. package/dist/chunk-RXHCETDZ.js +0 -536
  382. package/dist/chunk-RXHCETDZ.js.map +0 -1
  383. package/dist/chunk-RZTMDUO7.js +0 -49
  384. package/dist/chunk-RZTMDUO7.js.map +0 -1
  385. package/dist/chunk-SFLLL76A.js +0 -669
  386. package/dist/chunk-SFLLL76A.js.map +0 -1
  387. package/dist/chunk-SZLVEKMJ.js +0 -1446
  388. package/dist/chunk-SZLVEKMJ.js.map +0 -1
  389. package/dist/chunk-T4SQEITX.js +0 -95
  390. package/dist/chunk-T4SQEITX.js.map +0 -1
  391. package/dist/chunk-T6RLYGAD.js +0 -158
  392. package/dist/chunk-T6RLYGAD.js.map +0 -1
  393. package/dist/chunk-TJVT4QFF.js +0 -911
  394. package/dist/chunk-TJVT4QFF.js.map +0 -1
  395. package/dist/chunk-TQ7LNKZ3.js +0 -136
  396. package/dist/chunk-TQ7LNKZ3.js.map +0 -1
  397. package/dist/chunk-U4L7JRPZ.js +0 -1706
  398. package/dist/chunk-U4L7JRPZ.js.map +0 -1
  399. package/dist/chunk-U4PHLT2N.js +0 -419
  400. package/dist/chunk-U4PHLT2N.js.map +0 -1
  401. package/dist/chunk-VCZ5FQYW.js +0 -928
  402. package/dist/chunk-VCZ5FQYW.js.map +0 -1
  403. package/dist/chunk-VI2UW6B6.js +0 -162
  404. package/dist/chunk-VI2UW6B6.js.map +0 -1
  405. package/dist/chunk-VQMK5FMP.js +0 -247
  406. package/dist/chunk-VQMK5FMP.js.map +0 -1
  407. package/dist/chunk-WGXIEX7P.js +0 -116
  408. package/dist/chunk-WGXIEX7P.js.map +0 -1
  409. package/dist/chunk-WVATSFCP.js +0 -1553
  410. package/dist/chunk-WVATSFCP.js.map +0 -1
  411. package/dist/chunk-X4YIBDER.js +0 -1662
  412. package/dist/chunk-X4YIBDER.js.map +0 -1
  413. package/dist/chunk-YQN4ICPP.js +0 -355
  414. package/dist/chunk-YQN4ICPP.js.map +0 -1
  415. package/dist/chunk-ZET2UAYW.js +0 -89
  416. package/dist/chunk-ZET2UAYW.js.map +0 -1
  417. package/dist/chunk-ZHTZ4EYI.js +0 -1212
  418. package/dist/chunk-ZHTZ4EYI.js.map +0 -1
  419. package/dist/control.js.map +0 -1
  420. package/dist/hosted/index.js.map +0 -1
  421. package/dist/matrix/index.js.map +0 -1
  422. package/dist/reporting.js.map +0 -1
  423. package/dist/rollout/index.js.map +0 -1
  424. package/dist/run-campaign-OJJ7CZF4.js +0 -18
  425. package/dist/run-campaign-OJJ7CZF4.js.map +0 -1
  426. package/dist/supervisor-run/index.js.map +0 -1
  427. package/dist/traces.js.map +0 -1
  428. package/dist/wire/index.js.map +0 -1
@@ -1,1706 +0,0 @@
1
- import {
2
- readTaskFailureLabels,
3
- recordAggregateMeasurements,
4
- summarizeExecutionMeasurements,
5
- summarizeTraceErrors
6
- } from "./chunk-7ZZMD7UK.js";
7
- import {
8
- extractUsage,
9
- extractUsageFromSse
10
- } from "./chunk-PXE2VKMX.js";
11
- import {
12
- analyzeTraces
13
- } from "./chunk-5DTSBUL2.js";
14
- import {
15
- applyToolSpanOtlpAttributes,
16
- classifyOtlpSpanRole,
17
- compareSpanTime,
18
- firstStringAttr,
19
- isOtlpModelCall,
20
- projectOtlpFlatLine,
21
- spanEpochMillis,
22
- traceSpanKindToOpenInferenceKind
23
- } from "./chunk-P6FYH6K4.js";
24
- import {
25
- defaultProviderRedactor,
26
- providerFromBaseUrl
27
- } from "./chunk-PC4UYEBM.js";
28
- import {
29
- canonicalize,
30
- hashJson,
31
- validateRunRecord
32
- } from "./chunk-56TAVBOK.js";
33
- import {
34
- ReplayError
35
- } from "./chunk-ONWEPEDO.js";
36
- import {
37
- LLM_INPUT_TOKENS,
38
- LLM_MODEL_ATTR_KEYS,
39
- LLM_MODEL_NAME,
40
- LLM_OUTPUT_TOKENS,
41
- OPENINFERENCE_SPAN_KIND,
42
- TOOL_NAME,
43
- applyLlmSpanOtlpAttributes
44
- } from "./chunk-K4DBDHLK.js";
45
-
46
- // src/trace-analyst/hook.ts
47
- var DEFAULT_QUESTION = "Summarise what happened in this run. Surface any failure modes, surprising findings, or evidence that the run's verdict is wrong.";
48
- function traceAnalystOnRunComplete(opts) {
49
- return async (ctx) => {
50
- if (opts.shouldRun && !opts.shouldRun(ctx)) return;
51
- const source = opts.analyze.source;
52
- if (source === void 0) {
53
- await ctx.store.appendEvent({
54
- eventId: `analyst-skip-${ctx.runId}`,
55
- runId: ctx.runId,
56
- kind: "log",
57
- timestamp: Date.now(),
58
- payload: { source: "trace_analyst_hook", reason: "no source configured" }
59
- });
60
- return;
61
- }
62
- const result = await analyzeTraces({ question: opts.question ?? DEFAULT_QUESTION }, {
63
- ...opts.analyze,
64
- source
65
- });
66
- if (opts.save) await opts.save(result, ctx);
67
- if (opts.gateOn && !opts.gateOn(result, ctx)) {
68
- await ctx.store.appendEvent({
69
- eventId: `analyst-gate-${ctx.runId}`,
70
- runId: ctx.runId,
71
- kind: "log",
72
- timestamp: Date.now(),
73
- payload: {
74
- source: "trace_analyst_hook",
75
- reason: "analyst_gate_failed",
76
- findings: result.findings
77
- }
78
- });
79
- }
80
- };
81
- }
82
-
83
- // src/trace-analyst/insights.ts
84
- var DOMAIN_STOP_WORDS = /* @__PURE__ */ new Set([
85
- "and",
86
- "advanced",
87
- "app",
88
- "build",
89
- "create",
90
- "easy",
91
- "expert",
92
- "extreme",
93
- "for",
94
- "from",
95
- "hard",
96
- "implementation",
97
- "integrate",
98
- "medium",
99
- "project",
100
- "task",
101
- "the",
102
- "this",
103
- "with",
104
- "workflow"
105
- ]);
106
- function tokenizeDomainWords(value) {
107
- return [...value.matchAll(/[A-Za-z][A-Za-z0-9.+#-]{2,}/g)].map((match) => match[0].toLowerCase()).filter((word) => !DOMAIN_STOP_WORDS.has(word));
108
- }
109
- function inferDomainKeywords(suite) {
110
- const suiteWords = new Set(tokenizeDomainWords(`${suite.name} ${suite.collectionId ?? ""}`));
111
- const source = [
112
- suite.name,
113
- suite.collectionId ?? "",
114
- ...suite.tasks.flatMap((task) => [
115
- task.id,
116
- task.name,
117
- task.prompt ?? "",
118
- task.difficulty ?? "",
119
- ...task.tags ?? [],
120
- ...task.gaps ?? []
121
- ])
122
- ].join(" ");
123
- const counts = /* @__PURE__ */ new Map();
124
- for (const word of tokenizeDomainWords(source)) counts.set(word, (counts.get(word) ?? 0) + 1);
125
- return [...counts.entries()].filter(([word, count]) => count >= 2 || suiteWords.has(word)).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([word]) => word).slice(0, 18);
126
- }
127
- function domainEvidencePattern(keywords) {
128
- const escaped = keywords.filter((keyword) => keyword.length >= 3).map((keyword) => keyword.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
129
- return escaped.length > 0 ? new RegExp(`(?<![A-Za-z0-9])(?:${escaped.join("|")})(?![A-Za-z0-9])`, "i") : /(?<![A-Za-z0-9])(?:sdk|api|css|dns|xml|provider|client|service|integration|webhook|transaction|auth|oauth|graphql|rest)(?![A-Za-z0-9])/i;
130
- }
131
- function describeTraceInsightScope(suite) {
132
- const taskLabel = suite.tasks.length === 1 ? "1 implementation task" : `${suite.tasks.length} implementation tasks`;
133
- const tags = /* @__PURE__ */ new Map();
134
- for (const task of suite.tasks) {
135
- for (const tag of task.tags ?? []) tags.set(tag, (tags.get(tag) ?? 0) + 1);
136
- }
137
- const topTags = [...tags.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 8).map(([tag]) => tag);
138
- if (topTags.length > 0) return `${taskLabel} across ${topTags.join(", ")}.`;
139
- const difficulties = [
140
- ...new Set(
141
- suite.tasks.map((task) => task.difficulty).filter((value) => Boolean(value))
142
- )
143
- ].join(", ");
144
- return `${taskLabel} across ${difficulties || "the selected benchmark scope"}.`;
145
- }
146
- function planTraceInsightQuestions(input) {
147
- const hasFailures = input.suite.tasks.some((task) => task.outcome && task.outcome !== "satisfied");
148
- const hasMultipleShots = input.suite.tasks.some(
149
- (task) => (task.gaps ?? []).some((gap) => /shot|review|retry|continue/i.test(gap))
150
- );
151
- const questions = [
152
- {
153
- id: "execution-path",
154
- question: "What did the worker actually do before the first meaningful implementation edit?",
155
- why: "Separates grounded execution from polished but shallow output."
156
- },
157
- {
158
- id: "research-grounding",
159
- question: "Did the worker inspect docs, source, examples, or package references before committing to an implementation path?",
160
- why: "Identifies whether failures came from weak retrieval, weak examples, or premature coding."
161
- },
162
- {
163
- id: "domain-proof",
164
- question: "Which tasks produced executable domain proof versus UI copy, placeholders, or inferred behavior?",
165
- why: "Keeps product-quality claims tied to concrete evidence."
166
- },
167
- {
168
- id: "root-cause",
169
- question: "For each major failure cluster, is the likely root cause prompt/scaffold, docs/examples, SDK/API ergonomics, evaluator, runtime, or model behavior?",
170
- why: "Turns trace observations into actionable ownership."
171
- },
172
- {
173
- id: "evidence-quality",
174
- question: "Which external-facing claims are directly supported by trace ids, span ids, verifier findings, reviewer notes, or generated code?",
175
- why: "Prevents unsupported customer-report conclusions."
176
- }
177
- ];
178
- if (hasMultipleShots) {
179
- questions.push({
180
- id: "reviewer-lift",
181
- question: "Where did reviewer feedback improve score, stall, or regress across shots?",
182
- why: "Shows whether the driver loop is learning or merely repeating work."
183
- });
184
- }
185
- if (hasFailures) {
186
- questions.push({
187
- id: "optimization-targets",
188
- question: "Which prompt, evaluator, scaffold, or workflow changes should feed the next GEPA/autoresearch optimization run?",
189
- why: "Connects benchmark evidence to the optimization loop."
190
- });
191
- }
192
- return questions;
193
- }
194
- function buildTraceInsightContext(input) {
195
- return {
196
- suite: input.suite,
197
- scope: describeTraceInsightScope(input.suite),
198
- keywords: inferDomainKeywords(input.suite),
199
- questions: planTraceInsightQuestions(input),
200
- panel: defaultTraceInsightPanel(),
201
- findings: input.findings ?? [],
202
- agent: input.agent ?? null,
203
- totals: input.totals ?? null
204
- };
205
- }
206
- function scoreTraceInsightReadiness(context) {
207
- const failedTasks = context.suite.tasks.filter(
208
- (task) => task.outcome && task.outcome !== "satisfied"
209
- );
210
- const findingTaskIds = new Set(context.findings.flatMap((finding) => finding.taskIds));
211
- const failedTasksWithFindings = failedTasks.filter((task) => findingTaskIds.has(task.id));
212
- const tasksWithGaps = context.suite.tasks.filter((task) => (task.gaps ?? []).length > 0);
213
- const gates = [
214
- {
215
- id: "domain-context",
216
- label: "Domain context inferred",
217
- passed: context.keywords.length > 0,
218
- severity: "high",
219
- detail: context.keywords.length > 0 ? `${context.keywords.length} domain terms inferred: ${context.keywords.slice(0, 8).join(", ")}` : "No domain terms were inferred from suite, tasks, prompts, tags, or gaps."
220
- },
221
- {
222
- id: "panel-coverage",
223
- label: "Analyst panel planned",
224
- passed: context.panel.length >= 4 && context.questions.length >= 5,
225
- severity: "high",
226
- detail: `${context.panel.length} panel roles and ${context.questions.length} investigation questions planned.`
227
- },
228
- {
229
- id: "failure-coverage",
230
- label: "Failures mapped to findings",
231
- passed: failedTasks.length === 0 || failedTasksWithFindings.length / failedTasks.length >= 0.5,
232
- severity: "critical",
233
- detail: failedTasks.length === 0 ? "No failed tasks in suite." : `${failedTasksWithFindings.length}/${failedTasks.length} failed tasks appear in finding clusters.`
234
- },
235
- {
236
- id: "gap-evidence",
237
- label: "Task gaps captured",
238
- passed: failedTasks.length === 0 || tasksWithGaps.length / failedTasks.length >= 0.5,
239
- severity: "medium",
240
- detail: `${tasksWithGaps.length} tasks include explicit evaluator or analyst gaps.`
241
- }
242
- ];
243
- const penalty = gates.reduce((sum, gate) => {
244
- if (gate.passed) return sum;
245
- if (gate.severity === "critical") return sum + 35;
246
- if (gate.severity === "high") return sum + 20;
247
- if (gate.severity === "medium") return sum + 10;
248
- return sum + 5;
249
- }, 0);
250
- const score = Math.max(0, Math.min(1, 1 - penalty / 100));
251
- return {
252
- score,
253
- grade: score >= 0.9 ? "external-ready" : score >= 0.7 ? "internal-review" : "raw-analysis",
254
- gates
255
- };
256
- }
257
- function defaultTraceInsightPanel() {
258
- return [
259
- {
260
- id: "trace-forensics",
261
- name: "Trace Forensics",
262
- responsibility: "Reconstruct what the worker did in order, including research, edits, reviewer interventions, verifier feedback, and stop reason."
263
- },
264
- {
265
- id: "root-cause",
266
- name: "Root Cause",
267
- responsibility: "Map failures to prompt/scaffold, docs/examples, SDK/API/product ergonomics, evaluator, runtime, or model behavior."
268
- },
269
- {
270
- id: "optimization",
271
- name: "Optimization",
272
- responsibility: "Identify prompt, reviewer, evaluator, scaffold, and GEPA/autoresearch changes that should be tested next."
273
- },
274
- {
275
- id: "external-evidence",
276
- name: "External Evidence",
277
- responsibility: "Separate customer-safe claims from internal harness findings and reject conclusions without task, trace, span, code, reviewer, or verifier evidence."
278
- }
279
- ];
280
- }
281
- function buildTraceInsightPrompt(input) {
282
- const context = buildTraceInsightContext(input);
283
- const maxRepresentativeTraces = input.maxRepresentativeTraces ?? 6;
284
- return `Analyze this benchmark run and produce evidence-backed trace intelligence.
285
-
286
- Audience:
287
- - internal AI/product leadership
288
- - possible customer-facing report for ${input.suite.name}
289
-
290
- Investigation plan:
291
- ${context.questions.map((item, index) => `${index + 1}. ${item.question} (${item.why})`).join("\n")}
292
-
293
- Analyst panel:
294
- ${context.panel.map((role) => `- ${role.name}: ${role.responsibility}`).join("\n")}
295
-
296
- If the task branches are independent, use subagents for the panel roles above and aggregate their findings. Do not run a panel role unless its answer will change the final report.
297
-
298
- Required output:
299
- 1. Executive verdict: what this run proves and does not prove.
300
- 2. The investigation questions you answered and the evidence used.
301
- 3. Failure taxonomy: agent prompting, evaluator/harness, docs/examples, SDK/API/product integration, infra.
302
- 4. Evidence-backed examples with trace ids/task ids and concrete verifier findings.
303
- 5. Highest-ROI fixes for the benchmark harness, prompt/GEPA optimization, and customer-facing product/docs surface.
304
- 6. What is safe for an external report versus what must stay internal.
305
- 7. One rerun plan that would validate lift after optimization.
306
-
307
- Budget:
308
- - Inspect the dataset overview, the failure summary, and at most ${maxRepresentativeTraces} representative traces.
309
- - Prefer traces named in the failure summary over broad exploration.
310
- - Do not do exhaustive trace sweeps.
311
- - Return the final report as soon as the taxonomy and examples are supported.
312
-
313
- Run summary:
314
- ${JSON.stringify(
315
- {
316
- suite: input.suite.name,
317
- scope: context.scope,
318
- inferredKeywords: context.keywords,
319
- agent: context.agent,
320
- totals: context.totals,
321
- findings: context.findings.map((finding) => ({
322
- kind: finding.kind,
323
- severity: finding.severity,
324
- taskCount: finding.taskIds.length,
325
- proposedFixClass: finding.proposedFixClass
326
- })),
327
- failures: input.suite.tasks.filter((task) => task.outcome && task.outcome !== "satisfied").map((task) => ({
328
- task: task.id,
329
- difficulty: task.difficulty,
330
- outcome: task.outcome,
331
- score: task.score,
332
- gaps: task.gaps ?? []
333
- }))
334
- },
335
- null,
336
- 2
337
- )}
338
-
339
- Use the trace tools. Do not invent facts. Cite task ids. Separate customer-facing claims from internal harness/model findings.`;
340
- }
341
-
342
- // src/trace-analyst/otlp-flatten.ts
343
- var DEFAULT_KIND_MAP = {
344
- 0: "SPAN_KIND_UNSPECIFIED",
345
- 1: "SPAN_KIND_INTERNAL",
346
- 2: "SPAN_KIND_SERVER",
347
- 3: "SPAN_KIND_CLIENT",
348
- 4: "SPAN_KIND_PRODUCER",
349
- 5: "SPAN_KIND_CONSUMER"
350
- };
351
- var STATUS_MAP = {
352
- 0: "STATUS_CODE_UNSET",
353
- 1: "STATUS_CODE_OK",
354
- 2: "STATUS_CODE_ERROR"
355
- };
356
- function attrValue(v) {
357
- if (v.stringValue !== void 0) return v.stringValue;
358
- if (v.intValue !== void 0) return Number(v.intValue);
359
- if (v.doubleValue !== void 0) return v.doubleValue;
360
- if (v.boolValue !== void 0) return v.boolValue;
361
- return "";
362
- }
363
- function attrsToRecord(attrs) {
364
- const out = {};
365
- for (const a of attrs) out[a.key] = attrValue(a.value);
366
- return out;
367
- }
368
- function nanoToIso(nano) {
369
- const ms = Number(nano) / 1e6;
370
- return Number.isFinite(ms) ? new Date(ms).toISOString() : (/* @__PURE__ */ new Date(0)).toISOString();
371
- }
372
- function applyOpenInference(attrs) {
373
- if ("llm.model" in attrs && !(LLM_MODEL_NAME in attrs)) {
374
- attrs[LLM_MODEL_NAME] = attrs["llm.model"];
375
- }
376
- if ("llm.input_tokens" in attrs && !(LLM_INPUT_TOKENS in attrs)) {
377
- attrs[LLM_INPUT_TOKENS] = attrs["llm.input_tokens"];
378
- }
379
- if ("inference.llm.input_tokens" in attrs && !(LLM_INPUT_TOKENS in attrs)) {
380
- attrs[LLM_INPUT_TOKENS] = attrs["inference.llm.input_tokens"];
381
- }
382
- if ("llm.output_tokens" in attrs && !(LLM_OUTPUT_TOKENS in attrs)) {
383
- attrs[LLM_OUTPUT_TOKENS] = attrs["llm.output_tokens"];
384
- }
385
- if ("inference.llm.output_tokens" in attrs && !(LLM_OUTPUT_TOKENS in attrs)) {
386
- attrs[LLM_OUTPUT_TOKENS] = attrs["inference.llm.output_tokens"];
387
- }
388
- if (TOOL_NAME in attrs && !("inference.tool.name" in attrs)) {
389
- attrs["inference.tool.name"] = attrs[TOOL_NAME];
390
- }
391
- if ("span.kind" in attrs && !(OPENINFERENCE_SPAN_KIND in attrs)) {
392
- attrs[OPENINFERENCE_SPAN_KIND] = String(attrs["span.kind"]).toUpperCase();
393
- }
394
- }
395
- function flattenOtlpExportToNdjson(otlpExport, opts = {}) {
396
- const vocab = opts.attributeVocabulary ?? "openinference";
397
- const kindMap = { ...DEFAULT_KIND_MAP, ...opts.kindMap };
398
- const lines = [];
399
- for (const rs of otlpExport.resourceSpans ?? []) {
400
- const resource = { attributes: attrsToRecord(rs.resource?.attributes ?? []) };
401
- for (const scope of rs.scopeSpans ?? []) {
402
- for (const span of scope.spans ?? []) {
403
- const attributes = attrsToRecord(span.attributes ?? []);
404
- if (vocab === "openinference") applyOpenInference(attributes);
405
- const line = {
406
- trace_id: span.traceId,
407
- span_id: span.spanId,
408
- parent_span_id: span.parentSpanId ?? null,
409
- name: span.name,
410
- kind: kindMap[span.kind] ?? "SPAN_KIND_UNSPECIFIED",
411
- start_time: nanoToIso(span.startTimeUnixNano),
412
- end_time: nanoToIso(span.endTimeUnixNano),
413
- status: {
414
- code: STATUS_MAP[span.status?.code ?? 0] ?? "STATUS_CODE_UNSET",
415
- ...span.status?.message ? { message: span.status.message } : {}
416
- },
417
- resource,
418
- attributes
419
- };
420
- if (span.events && span.events.length > 0) {
421
- line.events = span.events.map((e) => ({
422
- name: e.name,
423
- timeUnixNano: e.timeUnixNano,
424
- ...e.attributes ? { attributes: attrsToRecord(e.attributes) } : {}
425
- }));
426
- }
427
- lines.push(line);
428
- }
429
- }
430
- }
431
- return lines;
432
- }
433
-
434
- // src/trace-analyst/otlp-to-run-records.ts
435
- function otlpToRunRecords(otlpJsonl, opts) {
436
- return otlpToTraceRunRecords(otlpJsonl, opts).map((r) => r.record);
437
- }
438
- function otlpRowsToRunRecords(rows, opts) {
439
- return otlpRowsToTraceRunRecords(rows, opts).map((row) => row.record);
440
- }
441
- function otlpToTraceRunRecords(otlpJsonl, opts) {
442
- return traceRunRecordsFromSpans(
443
- groupSpansByLogicalRun(groupJsonlSpansByTrace(otlpJsonl), opts.logicalRunIdForTrace),
444
- opts
445
- );
446
- }
447
- function otlpRowsToTraceRunRecords(rows, opts) {
448
- return traceRunRecordsFromSpans(
449
- groupSpansByLogicalRun(groupRowsByTrace(rows), opts.logicalRunIdForTrace),
450
- opts
451
- );
452
- }
453
- function traceRunRecordsFromSpans(byTrace, opts) {
454
- const splitTag = opts.splitTag ?? "holdout";
455
- const commitSha = opts.commitSha ?? "unknown";
456
- const promptHash = opts.promptHash ?? "unknown";
457
- const configHash = opts.configHash ?? "unknown";
458
- const seed = opts.seed ?? 0;
459
- const fallbackModel = opts.fallbackModel ?? "unknown@otlp";
460
- if (byTrace.size === 0) {
461
- throw new Error(
462
- "otlpToRunRecords: OTLP input produced zero valid spans \u2014 every row was empty, malformed, or missing trace_id/span_id"
463
- );
464
- }
465
- const traceIds = [...byTrace.keys()].sort();
466
- const out = [];
467
- for (const traceId of traceIds) {
468
- const spans = byTrace.get(traceId);
469
- const agg = aggregateTrace(traceId, spans, fallbackModel);
470
- const score = resolveScore(opts, traceId, agg);
471
- const { costUsd, costProvenance } = resolveCost(opts, agg);
472
- const raw = {
473
- source_trace_count: agg.sourceTraceCount,
474
- span_count: agg.spanCount,
475
- llm_span_count: agg.llmSpanCount,
476
- tool_span_count: agg.toolSpanCount,
477
- agent_span_count: agg.agentSpanCount,
478
- error_span_count: agg.errorSpanCount,
479
- execution_error_count: agg.executionErrorCount,
480
- process_error_count: agg.processErrorCount,
481
- guardrail_error_count: agg.guardrailErrorCount,
482
- judge_error_count: agg.judgeErrorCount,
483
- propagated_error_count: agg.propagatedErrorCount,
484
- unclassified_error_count: agg.unclassifiedErrorCount,
485
- prompt_tokens: agg.tokenUsage.input,
486
- completion_tokens: agg.tokenUsage.output
487
- };
488
- if (agg.tokenUsage.reasoning !== void 0) raw.reasoning_tokens = agg.tokenUsage.reasoning;
489
- if (agg.tokenUsage.cached !== void 0) raw.cached_tokens = agg.tokenUsage.cached;
490
- if (agg.tokenUsage.cacheWrite !== void 0) {
491
- raw.cache_write_tokens = agg.tokenUsage.cacheWrite;
492
- }
493
- if (agg.costMeasurement.value !== void 0 && !agg.costMeasurement.complete) {
494
- raw.partial_observed_cost_usd = agg.costMeasurement.value;
495
- }
496
- recordAggregateMeasurements(raw, agg.aggregateMeasurement);
497
- if (costProvenance.kind === "uncaptured") raw.cost_unpriced = 1;
498
- const outcome = { raw };
499
- if (score !== void 0) {
500
- if (splitTag === "holdout") outcome.holdoutScore = score;
501
- else outcome.searchScore = score;
502
- }
503
- const { promptText, completionText } = extractPromptCompletion(spans, agg.callSpanIds);
504
- const judgeMetadata = opts.judgeMetadataForTrace?.(traceId);
505
- const taskFailure = readTaskFailureLabels(
506
- spans.filter((span) => span.parent_span_id === null && isTerminalRootCandidate(span)),
507
- `otlpToRunRecords: run '${traceId}'`
508
- );
509
- const record = validateRunRecord({
510
- runId: `otlp:${opts.experimentId}:${opts.candidateId}:${traceId}`,
511
- experimentId: opts.experimentId,
512
- candidateId: opts.candidateId,
513
- seed,
514
- model: ensureSnapshot(agg.model, fallbackModel),
515
- promptHash,
516
- configHash,
517
- commitSha,
518
- wallMs: agg.wallMs,
519
- costUsd,
520
- costProvenance,
521
- tokenUsage: agg.tokenUsage,
522
- terminalOutcome: agg.terminalOutcome,
523
- ...agg.terminalFailureMessage ? { terminalFailureReason: agg.terminalFailureMessage } : {},
524
- ...judgeMetadata ? { judgeMetadata } : {},
525
- outcome,
526
- ...taskFailure,
527
- splitTag,
528
- scenarioId: traceId
529
- });
530
- out.push({
531
- record,
532
- ...promptText !== void 0 ? { promptText } : {},
533
- ...completionText !== void 0 ? { completionText } : {}
534
- });
535
- }
536
- return out;
537
- }
538
- function* yieldJsonlRows(otlpJsonl) {
539
- for (const line of otlpJsonl.split("\n")) {
540
- const trimmed = line.trim();
541
- if (trimmed.length === 0) continue;
542
- let parsed;
543
- try {
544
- parsed = JSON.parse(trimmed);
545
- } catch {
546
- continue;
547
- }
548
- if (parsed && typeof parsed === "object") yield parsed;
549
- }
550
- }
551
- function groupJsonlSpansByTrace(otlpJsonl) {
552
- return groupRowsByTrace(yieldJsonlRows(otlpJsonl));
553
- }
554
- function groupRowsByTrace(rows) {
555
- const byTrace = /* @__PURE__ */ new Map();
556
- for (const row of rows) {
557
- if (!row || typeof row !== "object") continue;
558
- const span = projectOtlpFlatLine(row);
559
- if (!span) continue;
560
- const arr = byTrace.get(span.trace_id);
561
- if (arr) arr.push(span);
562
- else byTrace.set(span.trace_id, [span]);
563
- }
564
- return byTrace;
565
- }
566
- function groupSpansByLogicalRun(byTrace, logicalRunIdForTrace) {
567
- if (!logicalRunIdForTrace) return byTrace;
568
- const byRun = /* @__PURE__ */ new Map();
569
- for (const [traceId, spans] of byTrace) {
570
- const suppliedRunId = logicalRunIdForTrace(traceId);
571
- if (typeof suppliedRunId !== "string" || suppliedRunId.trim().length === 0) {
572
- throw new Error(
573
- `otlpToRunRecords: logicalRunIdForTrace('${traceId}') returned an empty run id`
574
- );
575
- }
576
- const runId = suppliedRunId.trim();
577
- const target = byRun.get(runId) ?? [];
578
- for (const span of spans) {
579
- target.push({
580
- ...span,
581
- span_id: qualifySpanId(traceId, span.span_id),
582
- parent_span_id: span.parent_span_id ? qualifySpanId(traceId, span.parent_span_id) : null
583
- });
584
- }
585
- byRun.set(runId, target);
586
- }
587
- return byRun;
588
- }
589
- function qualifySpanId(traceId, spanId) {
590
- const prefix = `${traceId}:`;
591
- return spanId.startsWith(prefix) ? spanId : `${prefix}${spanId}`;
592
- }
593
- function aggregateTrace(traceId, spans, fallbackModel) {
594
- const ordered = [...spans].sort(
595
- (a2, b2) => compareSpanTime(a2.start_time, b2.start_time) || a2.span_id.localeCompare(b2.span_id)
596
- );
597
- const measurements = summarizeExecutionMeasurements(
598
- ordered.map((span) => ({
599
- id: span.span_id,
600
- ...span.parent_span_id ? { parentId: span.parent_span_id } : {},
601
- attributes: span.attributes,
602
- modelCall: isOtlpModelCall({
603
- kind: span.kind,
604
- name: span.name,
605
- attributes: span.attributes
606
- }),
607
- aggregate: span.kind !== "LLM" && span.kind !== "UNKNOWN"
608
- }))
609
- );
610
- let toolSpanCount = 0;
611
- let agentSpanCount = 0;
612
- let firstErrorMessage;
613
- const modelVotes = /* @__PURE__ */ new Map();
614
- let earliest = ordered[0]?.start_time ?? "";
615
- let latest = ordered[0]?.end_time ?? "";
616
- for (const s of ordered) {
617
- if (s.start_time && (!earliest || compareSpanTime(s.start_time, earliest) < 0))
618
- earliest = s.start_time;
619
- if (s.end_time && (!latest || compareSpanTime(s.end_time, latest) > 0)) latest = s.end_time;
620
- if (s.kind === "TOOL") {
621
- toolSpanCount += 1;
622
- } else if (s.kind === "AGENT") {
623
- agentSpanCount += 1;
624
- }
625
- if (s.status === "ERROR") {
626
- if (firstErrorMessage === void 0) {
627
- firstErrorMessage = (s.status_message ?? `${s.name} \u2014 STATUS_CODE_ERROR`).slice(0, 500);
628
- }
629
- }
630
- }
631
- const callSpanIds = new Set(measurements.callSpanIds);
632
- for (const span of ordered) {
633
- if (!callSpanIds.has(span.span_id)) continue;
634
- const model2 = firstStringAttr(span.attributes, LLM_MODEL_ATTR_KEYS) ?? span.model_name;
635
- if (model2) modelVotes.set(model2, (modelVotes.get(model2) ?? 0) + 1);
636
- }
637
- const model = topVote(modelVotes) ?? firstModelAttr(ordered) ?? fallbackModel;
638
- let wallMs = 0;
639
- const a = spanEpochMillis(earliest);
640
- const b = spanEpochMillis(latest);
641
- if (a !== null && b !== null) wallMs = Math.max(0, b - a);
642
- const sourceTraceIds = [...new Set(spans.map((span) => span.trace_id))].sort();
643
- const terminal = terminalEvidenceFromRoots(ordered);
644
- const errorSummary = summarizeTraceErrors(
645
- ordered.map((span) => ({
646
- id: span.span_id,
647
- ...span.parent_span_id ? { parentId: span.parent_span_id } : {},
648
- role: errorRoleForProjectedSpan(span),
649
- error: span.status === "ERROR",
650
- processRoot: span.parent_span_id === null && isTerminalRootCandidate(span)
651
- }))
652
- );
653
- return {
654
- traceId,
655
- sourceTraceCount: sourceTraceIds.length,
656
- sourceTraceIds,
657
- spanCount: spans.length,
658
- llmSpanCount: measurements.modelCallCount,
659
- toolSpanCount,
660
- agentSpanCount,
661
- errorSpanCount: errorSummary.total,
662
- executionErrorCount: errorSummary.execution,
663
- processErrorCount: errorSummary.process,
664
- guardrailErrorCount: errorSummary.guardrail,
665
- judgeErrorCount: errorSummary.evaluation,
666
- propagatedErrorCount: errorSummary.propagated,
667
- unclassifiedErrorCount: errorSummary.unclassified,
668
- tokenUsage: measurements.tokenUsage,
669
- firstErrorMessage,
670
- model,
671
- startTime: earliest,
672
- endTime: latest,
673
- wallMs,
674
- terminalOutcome: terminal.outcome,
675
- ...terminal.failureMessage ? { terminalFailureMessage: terminal.failureMessage } : {},
676
- callSpanIds: measurements.callSpanIds,
677
- costMeasurement: measurements.cost,
678
- ...measurements.aggregate ? { aggregateMeasurement: measurements.aggregate } : {}
679
- };
680
- }
681
- function terminalEvidenceFromRoots(spans) {
682
- const roots = spans.filter(
683
- (span) => span.parent_span_id === null && isTerminalRootCandidate(span)
684
- );
685
- if (roots.length !== 1) return { outcome: "unknown" };
686
- const root = roots[0];
687
- if (root.status === "ERROR") {
688
- return {
689
- outcome: "failed",
690
- failureMessage: (root.status_message ?? `${root.name} \u2014 STATUS_CODE_ERROR`).slice(0, 500)
691
- };
692
- }
693
- if (root.status === "OK") return { outcome: "succeeded" };
694
- return { outcome: "unknown" };
695
- }
696
- function isTerminalRootCandidate(span) {
697
- const role = errorRoleForProjectedSpan(span);
698
- return role !== "LLM" && role !== "TOOL" && role !== "EVALUATOR" && role !== "GUARDRAIL";
699
- }
700
- function errorRoleForProjectedSpan(span) {
701
- return classifyOtlpSpanRole({
702
- kind: span.kind,
703
- name: span.name,
704
- attributes: span.attributes
705
- });
706
- }
707
- function resolveScore(opts, traceId, agg) {
708
- const supplied = opts.scoreForTrace?.(traceId, agg);
709
- if (supplied !== void 0) {
710
- if (!Number.isFinite(supplied)) {
711
- throw new Error(
712
- `otlpToRunRecords: scoreForTrace('${traceId}') returned non-finite ${supplied}`
713
- );
714
- }
715
- return supplied;
716
- }
717
- return void 0;
718
- }
719
- function resolveCost(opts, agg) {
720
- const observedCost = agg.costMeasurement;
721
- if (observedCost.complete && observedCost.value !== void 0) {
722
- return {
723
- costUsd: observedCost.value,
724
- costProvenance: { kind: "observed", usd: observedCost.value }
725
- };
726
- }
727
- if (agg.aggregateMeasurement?.costUsd !== void 0) {
728
- return {
729
- costUsd: agg.aggregateMeasurement.costUsd,
730
- costProvenance: { kind: "observed", usd: agg.aggregateMeasurement.costUsd }
731
- };
732
- }
733
- if (opts.priceUsdPerToken !== void 0) {
734
- const totalTokens = agg.tokenUsage.input + agg.tokenUsage.output;
735
- const costUsd = totalTokens * opts.priceUsdPerToken;
736
- return { costUsd, costProvenance: { kind: "estimated", usd: costUsd } };
737
- }
738
- return { costUsd: null, costProvenance: { kind: "uncaptured", usd: null } };
739
- }
740
- function extractPromptCompletion(spans, callSpanIds) {
741
- const callIds = new Set(callSpanIds);
742
- const measuredCalls = spans.filter((span) => callIds.has(span.span_id));
743
- const llm = (measuredCalls.length > 0 ? measuredCalls : spans.filter((s) => s.kind === "LLM")).sort(
744
- (a, b) => compareSpanTime(a.start_time, b.start_time) || a.span_id.localeCompare(b.span_id)
745
- );
746
- if (llm.length === 0) return {};
747
- const promptText = firstStringAttr(llm[0].attributes, ["input.value", "llm.input_messages", "gen_ai.prompt"]) ?? void 0;
748
- const last = llm[llm.length - 1];
749
- const completionText = firstStringAttr(last.attributes, [
750
- "output.value",
751
- "llm.output_messages",
752
- "gen_ai.completion"
753
- ]) ?? void 0;
754
- return {
755
- ...promptText !== void 0 ? { promptText } : {},
756
- ...completionText !== void 0 ? { completionText } : {}
757
- };
758
- }
759
- function topVote(votes) {
760
- let best = null;
761
- let bestN = 0;
762
- for (const [k, n] of votes) {
763
- if (n > bestN || n === bestN && best !== null && k < best) {
764
- best = k;
765
- bestN = n;
766
- }
767
- }
768
- return best;
769
- }
770
- function firstModelAttr(spans) {
771
- for (const s of spans) {
772
- const m = firstStringAttr(s.attributes, LLM_MODEL_ATTR_KEYS) ?? s.model_name;
773
- if (m) return m;
774
- }
775
- return null;
776
- }
777
- function ensureSnapshot(model, fallbackModel) {
778
- if (modelHasSnapshot(model)) return model;
779
- const fallbackTag = fallbackModel.includes("@") ? fallbackModel.slice(fallbackModel.indexOf("@")) : "@otlp";
780
- return `${model}${fallbackTag}`;
781
- }
782
- function modelHasSnapshot(model) {
783
- if (model.includes("@")) return true;
784
- if (/-\d{8}$/.test(model)) return true;
785
- if (/-\d{4}-\d{2}-\d{2}$/.test(model)) return true;
786
- if (/:date-/.test(model)) return true;
787
- return false;
788
- }
789
-
790
- // src/trace/capture-fetch.ts
791
- var DEFAULT_BODY_CAP = 2 * 1024 * 1024;
792
- function headersToRecord(headers) {
793
- if (!headers) return void 0;
794
- const out = {};
795
- headers.forEach((value, key) => {
796
- out[key.toLowerCase()] = value;
797
- });
798
- return Object.keys(out).length > 0 ? out : void 0;
799
- }
800
- function parseMaybeJson(text) {
801
- if (text.length === 0) return void 0;
802
- try {
803
- return JSON.parse(text);
804
- } catch {
805
- return text;
806
- }
807
- }
808
- async function readRequestBody(input, init) {
809
- if (typeof init?.body === "string") return parseMaybeJson(init.body);
810
- if (init?.body != null) return void 0;
811
- if (input instanceof Request) {
812
- try {
813
- return parseMaybeJson(await input.clone().text());
814
- } catch {
815
- return void 0;
816
- }
817
- }
818
- return void 0;
819
- }
820
- function endpointFromUrl(url, baseUrl) {
821
- const normalisedBase = baseUrl.replace(/\/+$/, "");
822
- if (url.startsWith(normalisedBase)) return url.slice(normalisedBase.length) || "/";
823
- try {
824
- return new URL(url).pathname;
825
- } catch {
826
- return url;
827
- }
828
- }
829
- function captureFetchToRawSink(fetch2, sink, ctx, opts = {}) {
830
- const provider = ctx.provider ?? providerFromBaseUrl(ctx.baseUrl);
831
- const redactor = opts.redactor ?? defaultProviderRedactor;
832
- const bodyCap = opts.responseBodyByteCap ?? DEFAULT_BODY_CAP;
833
- let warned = false;
834
- const baseEvent = (direction, endpoint) => ({
835
- eventId: crypto.randomUUID(),
836
- runId: ctx.runId,
837
- spanId: ctx.spanId,
838
- provider,
839
- model: ctx.model,
840
- endpoint,
841
- baseUrl: ctx.baseUrl,
842
- attemptIndex: 0,
843
- // retries are re-invocations one layer up; documented in 0.x
844
- direction,
845
- timestamp: Date.now(),
846
- redactedFields: []
847
- });
848
- const record = async (event) => {
849
- try {
850
- await sink.record(redactor(event));
851
- } catch (err) {
852
- if (opts.failClosed) throw err;
853
- if (!warned) {
854
- warned = true;
855
- console.warn(
856
- `captureFetchToRawSink: sink.record failed (capture is best-effort) \u2014 ${err instanceof Error ? err.message : String(err)}`
857
- );
858
- }
859
- }
860
- };
861
- return async (input, init) => {
862
- const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
863
- const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
864
- const endpoint = endpointFromUrl(url, ctx.baseUrl);
865
- const reqHeaders = new Headers(
866
- init?.headers ?? (input instanceof Request ? input.headers : void 0)
867
- );
868
- await record({
869
- ...baseEvent("request", endpoint),
870
- requestHeaders: { ...headersToRecord(reqHeaders), "x-http-method": method },
871
- requestBody: await readRequestBody(input, init)
872
- });
873
- const start = Date.now();
874
- let response;
875
- try {
876
- response = await fetch2(input, init);
877
- } catch (err) {
878
- await record({
879
- ...baseEvent("error", endpoint),
880
- durationMs: Date.now() - start,
881
- errorMessage: err instanceof Error ? err.message : String(err)
882
- });
883
- throw err;
884
- }
885
- let responseBody;
886
- let rawText;
887
- const redactedFields = [];
888
- try {
889
- rawText = await response.clone().text();
890
- if (rawText.length > bodyCap) {
891
- responseBody = rawText.slice(0, bodyCap);
892
- redactedFields.push("body_truncated");
893
- } else {
894
- responseBody = parseMaybeJson(rawText);
895
- }
896
- } catch {
897
- responseBody = void 0;
898
- }
899
- if (opts.onUsage && rawText !== void 0) {
900
- try {
901
- const parsedForUsage = parseMaybeJson(rawText);
902
- const usage = extractUsage(parsedForUsage) ?? (typeof parsedForUsage === "string" ? extractUsageFromSse(rawText, { mode: opts.sseUsageMode }) : null);
903
- if (usage) opts.onUsage(usage, ctx);
904
- } catch (err) {
905
- if (opts.failClosed) throw err;
906
- }
907
- }
908
- await record({
909
- ...baseEvent("response", endpoint),
910
- durationMs: Date.now() - start,
911
- statusCode: response.status,
912
- responseHeaders: headersToRecord(response.headers),
913
- responseBody,
914
- redactedFields
915
- });
916
- return response;
917
- };
918
- }
919
-
920
- // src/trace/otel.ts
921
- var OTEL_AGENT_EVAL_SCOPE = { name: "@tangle-network/agent-eval", version: "0.3.0" };
922
- async function exportRunAsOtlp(store, runId, resourceAttrs = {}) {
923
- const run = await store.getRun(runId);
924
- if (!run) throw new Error(`run ${runId} not found`);
925
- const spans = await store.spans({ runId });
926
- const events = await store.events({ runId });
927
- const eventsBySpan = /* @__PURE__ */ new Map();
928
- for (const e of events) {
929
- if (!e.spanId) continue;
930
- const arr = eventsBySpan.get(e.spanId) ?? [];
931
- arr.push(e);
932
- eventsBySpan.set(e.spanId, arr);
933
- }
934
- const traceId = runToTraceId(run);
935
- const otlpSpans = spans.map(
936
- (s) => spanToOtlp(s, traceId, eventsBySpan.get(s.spanId) ?? [])
937
- );
938
- return {
939
- resourceSpans: [
940
- {
941
- resource: {
942
- attributes: toAttributes({
943
- "service.name": "agent-eval",
944
- "run.id": run.runId,
945
- "run.scenario_id": run.scenarioId,
946
- "run.variant_id": run.variantId ?? "",
947
- "run.dataset_version": run.datasetVersion ?? "",
948
- "run.code_sha": run.codeSha ?? "",
949
- "run.model_fingerprint": run.modelFingerprint ?? "",
950
- ...resourceAttrs
951
- })
952
- },
953
- scopeSpans: [{ scope: OTEL_AGENT_EVAL_SCOPE, spans: otlpSpans }]
954
- }
955
- ]
956
- };
957
- }
958
- function spanToOtlp(span, traceId, events) {
959
- const endedAt = span.endedAt ?? span.startedAt;
960
- return {
961
- traceId,
962
- spanId: padSpanId(span.spanId),
963
- parentSpanId: span.parentSpanId ? padSpanId(span.parentSpanId) : void 0,
964
- name: span.name,
965
- kind: 1,
966
- // SPAN_KIND_INTERNAL
967
- startTimeUnixNano: msToNs(span.startedAt),
968
- endTimeUnixNano: msToNs(endedAt),
969
- attributes: toAttributes(flattenSpanAttributes(span)),
970
- events: events.map((e) => ({
971
- timeUnixNano: msToNs(e.timestamp),
972
- name: e.kind,
973
- attributes: toAttributes(flattenPayload(e.payload))
974
- })),
975
- status: span.status === "error" ? { code: 2, message: span.error } : { code: 1 }
976
- };
977
- }
978
- function flattenSpanAttributes(span) {
979
- const base = {};
980
- if (span.attributes) {
981
- for (const [k, v] of Object.entries(span.attributes)) {
982
- if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") base[k] = v;
983
- }
984
- }
985
- base[OPENINFERENCE_SPAN_KIND] = traceSpanKindToOpenInferenceKind(span.kind);
986
- if (span.kind === "llm") {
987
- applyLlmSpanOtlpAttributes(base, span);
988
- } else if (span.kind === "tool") {
989
- applyToolSpanOtlpAttributes(base, span);
990
- } else if (span.kind === "retrieval") {
991
- base["retrieval.query"] = span.query;
992
- base["retrieval.hits"] = span.hits.length;
993
- } else if (span.kind === "judge") {
994
- base["judge.id"] = span.judgeId;
995
- base["judge.dimension"] = span.dimension;
996
- base["judge.score"] = span.score;
997
- base["judge.target_span_id"] = span.targetSpanId;
998
- } else if (span.kind === "sandbox") {
999
- if (span.image) base["sandbox.image"] = span.image;
1000
- if (span.exitCode !== void 0) base["sandbox.exit_code"] = span.exitCode;
1001
- if (span.testsPassed !== void 0) base["sandbox.tests_passed"] = span.testsPassed;
1002
- if (span.testsTotal !== void 0) base["sandbox.tests_total"] = span.testsTotal;
1003
- }
1004
- return base;
1005
- }
1006
- function flattenPayload(payload) {
1007
- const out = {};
1008
- for (const [k, v] of Object.entries(payload)) {
1009
- if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") out[k] = v;
1010
- else out[k] = JSON.stringify(v);
1011
- }
1012
- return out;
1013
- }
1014
- function toAttributes(record) {
1015
- return Object.entries(record).map(([key, value]) => ({
1016
- key,
1017
- value: typeof value === "number" ? Number.isInteger(value) ? { intValue: value.toString() } : { doubleValue: value } : typeof value === "boolean" ? { boolValue: value } : { stringValue: value }
1018
- }));
1019
- }
1020
- function msToNs(ms) {
1021
- return (BigInt(Math.floor(ms)) * 1000000n).toString();
1022
- }
1023
- function padSpanId(id) {
1024
- const cleaned = id.replace(/-/g, "");
1025
- return cleaned.slice(0, 16).padEnd(16, "0");
1026
- }
1027
- function runToTraceId(run) {
1028
- const cleaned = run.runId.replace(/-/g, "");
1029
- return cleaned.slice(0, 32).padEnd(32, "0");
1030
- }
1031
-
1032
- // src/trace/otel-bridge.ts
1033
- function otelRunCompleteHook(exporter) {
1034
- return async (ctx) => {
1035
- const spans = await ctx.store.spans({ runId: ctx.runId });
1036
- for (const span of spans) {
1037
- if (span.endedAt) {
1038
- exporter.exportSpan(storeSpanToExportable(span, ctx.runId));
1039
- }
1040
- }
1041
- await exporter.flush();
1042
- };
1043
- }
1044
- function createOtelTracingStore(inner, exporter, traceId) {
1045
- return {
1046
- async appendRun(run) {
1047
- return inner.appendRun(run);
1048
- },
1049
- async updateRun(runId, patch) {
1050
- return inner.updateRun(runId, patch);
1051
- },
1052
- async appendSpan(span) {
1053
- if (span.endedAt) {
1054
- exporter.exportSpan(storeSpanToExportable(span, traceId));
1055
- }
1056
- return inner.appendSpan(span);
1057
- },
1058
- async updateSpan(spanId, patch) {
1059
- await inner.updateSpan(spanId, patch);
1060
- if (patch.endedAt) {
1061
- const spans = await inner.spans({ runId: traceId });
1062
- const found = spans.find((s) => s.spanId === spanId);
1063
- if (found) {
1064
- exporter.exportSpan(storeSpanToExportable(found, traceId));
1065
- }
1066
- }
1067
- },
1068
- async appendEvent(event) {
1069
- return inner.appendEvent(event);
1070
- },
1071
- async appendBudgetEntry(entry) {
1072
- return inner.appendBudgetEntry(entry);
1073
- },
1074
- async appendArtifact(artifact) {
1075
- return inner.appendArtifact(artifact);
1076
- },
1077
- getRun: inner.getRun.bind(inner),
1078
- listRuns: inner.listRuns.bind(inner),
1079
- spans: inner.spans.bind(inner),
1080
- events: inner.events.bind(inner),
1081
- budget: inner.budget.bind(inner),
1082
- artifacts: inner.artifacts.bind(inner)
1083
- };
1084
- }
1085
- function storeSpanToExportable(span, traceId) {
1086
- const llm = span.kind === "llm" ? span : void 0;
1087
- const tool = span.kind === "tool" ? span : void 0;
1088
- return {
1089
- traceId,
1090
- spanId: span.spanId,
1091
- parentSpanId: span.parentSpanId,
1092
- name: span.name,
1093
- kind: span.kind,
1094
- startedAt: span.startedAt,
1095
- endedAt: span.endedAt,
1096
- status: span.status,
1097
- error: span.error,
1098
- model: llm?.model,
1099
- inputTokens: llm?.inputTokens,
1100
- outputTokens: llm?.outputTokens,
1101
- reasoningTokens: llm?.reasoningTokens,
1102
- cachedTokens: llm?.cachedTokens,
1103
- cacheWriteTokens: llm?.cacheWriteTokens,
1104
- costUsd: llm?.costUsd,
1105
- tool: tool ? {
1106
- toolName: tool.toolName,
1107
- args: tool.args,
1108
- argsCaptured: tool.argsCaptured,
1109
- result: tool.result,
1110
- latencyMs: tool.latencyMs
1111
- } : void 0,
1112
- attributes: span.attributes
1113
- };
1114
- }
1115
-
1116
- // src/trace/otel-export.ts
1117
- function createOtelExporter(config) {
1118
- const resolvedEndpoint = config?.endpoint ?? (typeof process !== "undefined" ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : void 0);
1119
- if (!resolvedEndpoint) return void 0;
1120
- const endpoint = resolvedEndpoint;
1121
- const headers = config?.headers ?? parseHeadersFromEnv();
1122
- const batchSize = config?.batchSize ?? 64;
1123
- const flushIntervalMs = config?.flushIntervalMs ?? 5e3;
1124
- const serviceName = config?.serviceName ?? "agent-eval";
1125
- const resourceAttrs = config?.resourceAttributes ?? {};
1126
- const pending = [];
1127
- let timer;
1128
- let stopped = false;
1129
- const exporter = {
1130
- exportSpan(span) {
1131
- if (stopped) return;
1132
- pending.push(toOtlpSpan(span));
1133
- if (pending.length >= batchSize) {
1134
- void doFlush();
1135
- }
1136
- },
1137
- async flush() {
1138
- await doFlush();
1139
- },
1140
- async shutdown() {
1141
- stopped = true;
1142
- if (timer !== void 0) {
1143
- clearInterval(timer);
1144
- timer = void 0;
1145
- }
1146
- await doFlush();
1147
- }
1148
- };
1149
- timer = setInterval(() => {
1150
- if (pending.length > 0) void doFlush();
1151
- }, flushIntervalMs);
1152
- if (typeof timer === "object" && "unref" in timer) {
1153
- ;
1154
- timer.unref();
1155
- }
1156
- async function doFlush() {
1157
- if (pending.length === 0) return;
1158
- const batch = pending.splice(0);
1159
- const body = {
1160
- resourceSpans: [
1161
- {
1162
- resource: {
1163
- attributes: toAttributes2({
1164
- "service.name": serviceName,
1165
- ...resourceAttrs
1166
- })
1167
- },
1168
- scopeSpans: [{ scope: OTEL_AGENT_EVAL_SCOPE, spans: batch }]
1169
- }
1170
- ]
1171
- };
1172
- const url = `${endpoint.replace(/\/+$/, "")}/v1/traces`;
1173
- try {
1174
- await fetch(url, {
1175
- method: "POST",
1176
- headers: {
1177
- "content-type": "application/json",
1178
- ...headers
1179
- },
1180
- body: JSON.stringify(body)
1181
- });
1182
- } catch {
1183
- }
1184
- }
1185
- return exporter;
1186
- }
1187
- function parseHeadersFromEnv() {
1188
- if (typeof process === "undefined") return {};
1189
- const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS;
1190
- if (!raw) return {};
1191
- const out = {};
1192
- for (const pair of raw.split(",")) {
1193
- const eq = pair.indexOf("=");
1194
- if (eq < 0) continue;
1195
- const key = pair.slice(0, eq).trim();
1196
- const value = pair.slice(eq + 1).trim();
1197
- if (key) out[key] = value;
1198
- }
1199
- return out;
1200
- }
1201
- function toOtlpSpan(span) {
1202
- const endedAt = span.endedAt ?? span.startedAt;
1203
- const attrs = {};
1204
- if (span.attributes) {
1205
- for (const [k, v] of Object.entries(span.attributes)) {
1206
- if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") attrs[k] = v;
1207
- }
1208
- }
1209
- attrs[OPENINFERENCE_SPAN_KIND] = traceSpanKindToOpenInferenceKind(span.kind);
1210
- applyLlmSpanOtlpAttributes(attrs, span);
1211
- if (span.tool) applyToolSpanOtlpAttributes(attrs, span.tool);
1212
- return {
1213
- traceId: padTraceId(span.traceId),
1214
- spanId: padSpanId2(span.spanId),
1215
- parentSpanId: span.parentSpanId ? padSpanId2(span.parentSpanId) : void 0,
1216
- name: span.name,
1217
- kind: 1,
1218
- // SPAN_KIND_INTERNAL
1219
- startTimeUnixNano: msToNs2(span.startedAt),
1220
- endTimeUnixNano: msToNs2(endedAt),
1221
- attributes: toAttributes2(attrs),
1222
- status: span.status === "error" ? { code: 2, message: span.error } : { code: 1 }
1223
- };
1224
- }
1225
- function toAttributes2(record) {
1226
- return Object.entries(record).map(([key, value]) => ({
1227
- key,
1228
- value: typeof value === "number" ? Number.isInteger(value) ? { intValue: value.toString() } : { doubleValue: value } : typeof value === "boolean" ? { boolValue: value } : { stringValue: value }
1229
- }));
1230
- }
1231
- function msToNs2(ms) {
1232
- return (BigInt(Math.floor(ms)) * 1000000n).toString();
1233
- }
1234
- function padSpanId2(id) {
1235
- const cleaned = id.replace(/-/g, "");
1236
- return cleaned.slice(0, 16).padEnd(16, "0");
1237
- }
1238
- function padTraceId(id) {
1239
- const cleaned = id.replace(/-/g, "");
1240
- return cleaned.slice(0, 32).padEnd(32, "0");
1241
- }
1242
-
1243
- // src/trace/store-to-otlp.ts
1244
- import { readdirSync, readFileSync, statSync, writeFileSync } from "fs";
1245
- import { join } from "path";
1246
- function convertTraceStoresToOtlp(source, outPath, opts = {}) {
1247
- const sources = Array.isArray(source) ? [...source] : typeof source === "string" ? [{ root: source, layout: "celled" }] : [source];
1248
- const defaultServiceName = opts.serviceName ?? "agent-eval";
1249
- const resourceAttributes = opts.resourceAttributes ?? (() => ({}));
1250
- const runAttributes = opts.runAttributes ?? (() => ({}));
1251
- const lines = [];
1252
- let spanCount = 0;
1253
- let runCount = 0;
1254
- let cellCount = 0;
1255
- let cellErrorCount = 0;
1256
- for (const src of sources) {
1257
- const serviceName = src.serviceName ?? defaultServiceName;
1258
- const cellDirs = src.layout === "flat" ? [{ label: "<root>", dir: src.root }] : listCells(src.root).map((name) => ({ label: name, dir: join(src.root, name) }));
1259
- for (const cell of cellDirs) {
1260
- try {
1261
- const result = projectCell({
1262
- cellDir: cell.dir,
1263
- serviceName,
1264
- resourceAttributes,
1265
- runAttributes
1266
- });
1267
- for (const line of result.lines) lines.push(line);
1268
- spanCount += result.spanCount;
1269
- runCount += result.runCount;
1270
- cellCount += 1;
1271
- } catch (err) {
1272
- console.warn(
1273
- `[traces-to-otlp] cell ${cell.label} (${cell.dir}) skipped: ${err instanceof Error ? err.message : String(err)}`
1274
- );
1275
- cellErrorCount += 1;
1276
- }
1277
- }
1278
- }
1279
- writeFileSync(outPath, lines.join("\n") + (lines.length > 0 ? "\n" : ""));
1280
- return { spanCount, runCount, cellCount, cellErrorCount };
1281
- }
1282
- function projectCell(args) {
1283
- const { cellDir, serviceName, resourceAttributes, runAttributes } = args;
1284
- const lines = [];
1285
- let runCount = 0;
1286
- let spanCount = 0;
1287
- const runs = readMergedShards(cellDir, "runs", "runId");
1288
- const spans = readMergedShards(cellDir, "spans", "spanId");
1289
- const events = readShards(cellDir, "events");
1290
- const runByRunId = /* @__PURE__ */ new Map();
1291
- for (const r of runs) runByRunId.set(r.runId, r);
1292
- const spanBySpanId = /* @__PURE__ */ new Map();
1293
- for (const s of spans) spanBySpanId.set(s.spanId, s);
1294
- const eventsBySpanId = /* @__PURE__ */ new Map();
1295
- for (const e of events) {
1296
- if (e.kind === "state_mutation" && e.payload && typeof e.payload === "object") {
1297
- const entity = e.payload.entity;
1298
- if (entity === "run") {
1299
- const run = e.payload.run;
1300
- if (run?.runId) runByRunId.set(run.runId, run);
1301
- continue;
1302
- }
1303
- if (entity === "run.update") {
1304
- const patch = e.payload.patch;
1305
- if (patch && e.runId) {
1306
- const prior = runByRunId.get(e.runId);
1307
- if (prior) runByRunId.set(e.runId, { ...prior, ...patch });
1308
- }
1309
- continue;
1310
- }
1311
- if (entity === "span") {
1312
- const span = e.payload.span;
1313
- if (span?.spanId) spanBySpanId.set(span.spanId, span);
1314
- continue;
1315
- }
1316
- if (entity === "span.update") {
1317
- const spanId = e.payload.spanId;
1318
- const patch = e.payload.patch;
1319
- if (spanId && patch) {
1320
- const prior = spanBySpanId.get(spanId);
1321
- if (prior) spanBySpanId.set(spanId, { ...prior, ...patch });
1322
- }
1323
- continue;
1324
- }
1325
- }
1326
- if (!e.spanId) continue;
1327
- const arr = eventsBySpanId.get(e.spanId) ?? [];
1328
- arr.push(e);
1329
- eventsBySpanId.set(e.spanId, arr);
1330
- }
1331
- for (const run of runByRunId.values()) {
1332
- const traceId = padTraceId2(run.runId);
1333
- const agentName = run.variantId ?? run.scenarioId;
1334
- const sharedResource = {
1335
- attributes: {
1336
- "service.name": serviceName,
1337
- "agent.name": agentName,
1338
- "run.id": run.runId,
1339
- "run.status": run.status,
1340
- ...resourceAttributes(run)
1341
- }
1342
- };
1343
- const runSpanId = padSpanId3(`run-${run.runId}`);
1344
- const runStart = msToIso(run.startedAt);
1345
- const runEnd = msToIso(run.endedAt ?? run.startedAt);
1346
- const runStatus = run.outcome?.failureClass && run.outcome.failureClass !== "success" ? "STATUS_CODE_ERROR" : "STATUS_CODE_OK";
1347
- const runAttrs = {
1348
- [OPENINFERENCE_SPAN_KIND]: "AGENT",
1349
- "agent.name": agentName,
1350
- "agent.workflow.name": serviceName,
1351
- ...runAttributes(run)
1352
- };
1353
- lines.push(
1354
- JSON.stringify(
1355
- toLine({
1356
- traceId,
1357
- spanId: runSpanId,
1358
- parentSpanId: "",
1359
- name: `run.${agentName}`,
1360
- kind: "SPAN_KIND_INTERNAL",
1361
- startTime: runStart,
1362
- endTime: runEnd,
1363
- statusCode: runStatus,
1364
- statusMessage: run.outcome?.notes ?? "",
1365
- resource: sharedResource,
1366
- attributes: runAttrs
1367
- })
1368
- )
1369
- );
1370
- runCount += 1;
1371
- for (const span of spanBySpanId.values()) {
1372
- if (span.runId !== run.runId) continue;
1373
- const spanAttrs = spanToAttributes(span, eventsBySpanId.get(span.spanId) ?? []);
1374
- const statusCode = span.status === "error" ? "STATUS_CODE_ERROR" : "STATUS_CODE_OK";
1375
- lines.push(
1376
- JSON.stringify(
1377
- toLine({
1378
- traceId,
1379
- spanId: padSpanId3(span.spanId),
1380
- parentSpanId: span.parentSpanId ? padSpanId3(span.parentSpanId) : runSpanId,
1381
- name: span.name,
1382
- kind: spanKindToOtlpKind(span.kind),
1383
- startTime: msToIso(span.startedAt),
1384
- endTime: msToIso(span.endedAt ?? span.startedAt),
1385
- statusCode,
1386
- statusMessage: span.error ?? "",
1387
- resource: sharedResource,
1388
- attributes: spanAttrs
1389
- })
1390
- )
1391
- );
1392
- spanCount += 1;
1393
- }
1394
- }
1395
- return { lines, runCount, spanCount };
1396
- }
1397
- function listCells(root) {
1398
- try {
1399
- return readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name).sort();
1400
- } catch {
1401
- return [];
1402
- }
1403
- }
1404
- function readShards(cellDir, name) {
1405
- let entries;
1406
- try {
1407
- entries = readdirSync(cellDir);
1408
- } catch {
1409
- return [];
1410
- }
1411
- const shards = entries.filter((f) => (f === `${name}.ndjson` || f.startsWith(`${name}.`)) && f.endsWith(".ndjson")).map((f) => ({ file: f, path: join(cellDir, f) })).map((s) => {
1412
- let mtime = 0;
1413
- try {
1414
- mtime = statSync(s.path).mtimeMs;
1415
- } catch {
1416
- }
1417
- return { ...s, mtime };
1418
- }).sort((a, b) => a.mtime - b.mtime || a.file.localeCompare(b.file));
1419
- const rows = [];
1420
- for (const shard of shards) {
1421
- let text;
1422
- try {
1423
- text = readFileSync(shard.path, "utf-8");
1424
- } catch {
1425
- continue;
1426
- }
1427
- for (const line of text.split("\n")) {
1428
- const trimmed = line.trim();
1429
- if (!trimmed) continue;
1430
- try {
1431
- rows.push(JSON.parse(trimmed));
1432
- } catch {
1433
- }
1434
- }
1435
- }
1436
- return rows;
1437
- }
1438
- function readMergedShards(cellDir, name, idKey) {
1439
- const rows = readShards(cellDir, name);
1440
- const byId = /* @__PURE__ */ new Map();
1441
- for (const row of rows) {
1442
- const id = row[idKey];
1443
- if (!id) continue;
1444
- const prior = byId.get(id);
1445
- if (prior && row._update) {
1446
- byId.set(id, { ...prior, ...row, _update: void 0 });
1447
- } else {
1448
- byId.set(id, row);
1449
- }
1450
- }
1451
- return [...byId.values()];
1452
- }
1453
- function spanToAttributes(span, events) {
1454
- const attrs = {
1455
- [OPENINFERENCE_SPAN_KIND]: traceSpanKindToOpenInferenceKind(span.kind)
1456
- };
1457
- if (span.kind === "llm") {
1458
- applyLlmSpanOtlpAttributes(attrs, span);
1459
- if (Array.isArray(span.messages)) {
1460
- attrs["llm.input_messages"] = JSON.stringify(span.messages.slice(-6));
1461
- }
1462
- if (typeof span.output === "string") {
1463
- attrs["llm.output_messages"] = JSON.stringify([{ role: "assistant", content: span.output }]);
1464
- }
1465
- } else if (span.kind === "tool") {
1466
- applyToolSpanOtlpAttributes(attrs, span);
1467
- } else if (span.kind === "judge") {
1468
- attrs["judge.id"] = span.judgeId;
1469
- attrs["judge.dimension"] = span.dimension;
1470
- attrs["judge.score"] = span.score;
1471
- attrs["judge.target_span_id"] = span.targetSpanId;
1472
- }
1473
- if (span.attributes) {
1474
- for (const [k, v] of Object.entries(span.attributes)) {
1475
- attrs[`agent_eval.${k}`] = v;
1476
- }
1477
- }
1478
- if (events.length > 0) {
1479
- attrs["agent_eval.event_count"] = events.length;
1480
- attrs["agent_eval.event_kinds"] = JSON.stringify(events.map((e) => e.kind));
1481
- }
1482
- return attrs;
1483
- }
1484
- function spanKindToOtlpKind(kind) {
1485
- switch (kind) {
1486
- case "llm":
1487
- return "SPAN_KIND_CLIENT";
1488
- case "retrieval":
1489
- return "SPAN_KIND_CLIENT";
1490
- default:
1491
- return "SPAN_KIND_INTERNAL";
1492
- }
1493
- }
1494
- function toLine(args) {
1495
- return {
1496
- trace_id: args.traceId,
1497
- span_id: args.spanId,
1498
- parent_span_id: args.parentSpanId,
1499
- name: args.name,
1500
- kind: args.kind,
1501
- start_time: args.startTime,
1502
- end_time: args.endTime,
1503
- status: { code: args.statusCode, message: args.statusMessage },
1504
- resource: args.resource,
1505
- attributes: args.attributes
1506
- };
1507
- }
1508
- function msToIso(ms) {
1509
- if (!Number.isFinite(ms) || ms <= 0) return (/* @__PURE__ */ new Date(0)).toISOString();
1510
- return new Date(ms).toISOString();
1511
- }
1512
- function padSpanId3(id) {
1513
- const cleaned = id.replace(/[^a-f0-9]/gi, "").toLowerCase();
1514
- if (cleaned.length >= 16) return cleaned.slice(0, 16);
1515
- return foldTo16Hex(id);
1516
- }
1517
- function padTraceId2(id) {
1518
- const cleaned = id.replace(/[^a-f0-9]/gi, "").toLowerCase();
1519
- if (cleaned.length >= 32) return cleaned.slice(0, 32);
1520
- return foldTo32Hex(id);
1521
- }
1522
- function foldTo16Hex(s) {
1523
- let h1 = 2166136261;
1524
- for (const ch of s) {
1525
- h1 ^= ch.charCodeAt(0);
1526
- h1 = Math.imul(h1, 16777619) >>> 0;
1527
- }
1528
- const part = h1.toString(16).padStart(8, "0");
1529
- return (part + part).slice(0, 16);
1530
- }
1531
- function foldTo32Hex(s) {
1532
- return foldTo16Hex(s) + foldTo16Hex(`${s}::trace`).slice(0, 16);
1533
- }
1534
-
1535
- // src/replay.ts
1536
- var ReplayCacheMissError = class extends ReplayError {
1537
- constructor(url, requestKey2, message) {
1538
- super(message ?? `replay cache miss for ${url} (key=${requestKey2})`);
1539
- this.url = url;
1540
- this.requestKey = requestKey2;
1541
- }
1542
- url;
1543
- requestKey;
1544
- };
1545
- var ReplayCache = class _ReplayCache {
1546
- byKey = /* @__PURE__ */ new Map();
1547
- orphans = 0;
1548
- byProvider = {};
1549
- byModel = {};
1550
- /**
1551
- * Build a cache from a sink's events. The sink must implement `list()`.
1552
- * Filter by `runId` / `spanId` to scope to a specific replay.
1553
- */
1554
- static async fromSink(sink, filter = {}) {
1555
- if (!sink.list) {
1556
- throw new ReplayError("ReplayCache.fromSink: sink must implement list() to be replayable.");
1557
- }
1558
- const events = await sink.list(filter);
1559
- return _ReplayCache.fromEvents(events);
1560
- }
1561
- /** Build a cache from an in-memory event list. */
1562
- static async fromEvents(events) {
1563
- const cache = new _ReplayCache();
1564
- const groups = /* @__PURE__ */ new Map();
1565
- for (const e of events) {
1566
- const k = `${e.runId ?? ""}::${e.spanId ?? ""}::${e.attemptIndex}`;
1567
- const g = groups.get(k) ?? {};
1568
- if (e.direction === "request") g.req = e;
1569
- else g.res = e;
1570
- groups.set(k, g);
1571
- }
1572
- for (const g of groups.values()) {
1573
- if (!g.req) continue;
1574
- if (!g.res) {
1575
- cache.orphans += 1;
1576
- continue;
1577
- }
1578
- const key = await requestKey(g.req);
1579
- cache.byKey.set(key, { request: g.req, response: g.res });
1580
- cache.byProvider[g.req.provider] = (cache.byProvider[g.req.provider] ?? 0) + 1;
1581
- cache.byModel[g.req.model] = (cache.byModel[g.req.model] ?? 0) + 1;
1582
- }
1583
- return cache;
1584
- }
1585
- /** Number of cacheable (request, response) pairs in the cache. */
1586
- size() {
1587
- return this.byKey.size;
1588
- }
1589
- stats() {
1590
- return {
1591
- total: this.byKey.size,
1592
- byProvider: { ...this.byProvider },
1593
- byModel: { ...this.byModel },
1594
- orphanRequests: this.orphans
1595
- };
1596
- }
1597
- /** Iterate every cached `(request, response)` pair in insertion order. */
1598
- *entries() {
1599
- for (const entry of this.byKey.values()) yield entry;
1600
- }
1601
- /**
1602
- * Look up a cached response by hashing the (model, messages, temperature,
1603
- * maxTokens, response_format) shape. Returns `undefined` on miss; the
1604
- * caller decides whether to throw, fall back to the network, or skip.
1605
- */
1606
- async lookup(requestBody) {
1607
- const key = await keyFromBody(requestBody);
1608
- return this.byKey.get(key);
1609
- }
1610
- };
1611
- function createReplayFetch(cache, opts = {}) {
1612
- const onMiss = opts.onMiss ?? "throw";
1613
- const fallback = opts.fallbackFetch ?? globalThis.fetch?.bind(globalThis);
1614
- return (async (input, init) => {
1615
- const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
1616
- if (!/\/chat\/completions(?:[?#].*)?$/.test(url)) {
1617
- if (!fallback)
1618
- throw new ReplayError(
1619
- `replay fetch: non-completions URL ${url} but no fallbackFetch configured`
1620
- );
1621
- return fallback(input, init);
1622
- }
1623
- let bodyParsed;
1624
- if (init?.body && typeof init.body === "string") {
1625
- try {
1626
- bodyParsed = JSON.parse(init.body);
1627
- } catch {
1628
- }
1629
- }
1630
- const hit = bodyParsed === void 0 ? void 0 : await cache.lookup(bodyParsed);
1631
- if (hit) {
1632
- opts.onHit?.({ url, provider: hit.request.provider, model: hit.request.model });
1633
- const status = hit.response.statusCode ?? 200;
1634
- const headers = new Headers(
1635
- Object.entries(hit.response.responseHeaders ?? { "Content-Type": "application/json" })
1636
- );
1637
- const bodyText = typeof hit.response.responseBody === "string" ? hit.response.responseBody : JSON.stringify(hit.response.responseBody ?? {});
1638
- return new Response(bodyText, { status, headers });
1639
- }
1640
- opts.onMissNotify?.({ url, requestBody: bodyParsed });
1641
- if (onMiss === "throw") {
1642
- const key = bodyParsed === void 0 ? "<unparseable>" : await keyFromBody(bodyParsed);
1643
- throw new ReplayCacheMissError(url, key);
1644
- }
1645
- if (onMiss === "fail-closed") {
1646
- return new Response(JSON.stringify({ error: "replay_cache_miss" }), { status: 599 });
1647
- }
1648
- if (!fallback)
1649
- throw new ReplayError("replay fetch: onMiss=fallback but no fallbackFetch configured");
1650
- return fallback(input, init);
1651
- });
1652
- }
1653
- async function* iterateRawCalls(sink, filter = {}) {
1654
- if (!sink.list) {
1655
- throw new ReplayError("iterateRawCalls: sink must implement list().");
1656
- }
1657
- const events = await sink.list(filter);
1658
- const cache = await ReplayCache.fromEvents(events);
1659
- for (const entry of cache.entries()) yield entry;
1660
- }
1661
- async function requestKey(event) {
1662
- return keyFromBody(event.requestBody);
1663
- }
1664
- async function keyFromBody(body) {
1665
- if (body == null || typeof body !== "object") return hashJson({ raw: String(body) });
1666
- const b = body;
1667
- const reduced = canonicalize({
1668
- model: b.model ?? null,
1669
- messages: b.messages ?? null,
1670
- temperature: b.temperature ?? null,
1671
- max_tokens: b.max_tokens ?? null,
1672
- max_completion_tokens: b.max_completion_tokens ?? null,
1673
- response_format: b.response_format ?? null
1674
- });
1675
- return hashJson(reduced);
1676
- }
1677
-
1678
- export {
1679
- traceAnalystOnRunComplete,
1680
- tokenizeDomainWords,
1681
- inferDomainKeywords,
1682
- domainEvidencePattern,
1683
- describeTraceInsightScope,
1684
- planTraceInsightQuestions,
1685
- buildTraceInsightContext,
1686
- scoreTraceInsightReadiness,
1687
- defaultTraceInsightPanel,
1688
- buildTraceInsightPrompt,
1689
- flattenOtlpExportToNdjson,
1690
- otlpToRunRecords,
1691
- otlpRowsToRunRecords,
1692
- otlpToTraceRunRecords,
1693
- otlpRowsToTraceRunRecords,
1694
- captureFetchToRawSink,
1695
- OTEL_AGENT_EVAL_SCOPE,
1696
- exportRunAsOtlp,
1697
- otelRunCompleteHook,
1698
- createOtelTracingStore,
1699
- createOtelExporter,
1700
- convertTraceStoresToOtlp,
1701
- ReplayCacheMissError,
1702
- ReplayCache,
1703
- createReplayFetch,
1704
- iterateRawCalls
1705
- };
1706
- //# sourceMappingURL=chunk-U4L7JRPZ.js.map