@tangle-network/agent-eval 0.172.1 → 0.173.0

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 (219) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +17 -2
  3. package/dist/adapters/http.d.ts +2 -2
  4. package/dist/analyst/index.d.ts +13 -13
  5. package/dist/analyst/index.js +7 -6
  6. package/dist/analyst/index.js.map +1 -1
  7. package/dist/{attestation-CJBGmMVh.d.ts → attestation-c1QvaBdX.d.ts} +2 -2
  8. package/dist/{attestation-CJBGmMVh.d.ts.map → attestation-c1QvaBdX.d.ts.map} +1 -1
  9. package/dist/{backend-integrity-e79K3UPD.d.ts → backend-integrity-CeuTgqsd.d.ts} +3 -4
  10. package/dist/backend-integrity-CeuTgqsd.d.ts.map +1 -0
  11. package/dist/{benchmark-h-h4bfqj.d.ts → benchmark-BjLGkfnN.d.ts} +3 -3
  12. package/dist/{benchmark-h-h4bfqj.d.ts.map → benchmark-BjLGkfnN.d.ts.map} +1 -1
  13. package/dist/{benchmark-command--qeZUHbu.js → benchmark-command-9S20PRel.js} +9 -9
  14. package/dist/{benchmark-command--qeZUHbu.js.map → benchmark-command-9S20PRel.js.map} +1 -1
  15. package/dist/benchmarks/index.d.ts +5 -5
  16. package/dist/benchmarks/index.js +3 -3
  17. package/dist/{bounded-process-VIi0KSL2.js → bounded-process-BBZob7vl.js} +30 -7
  18. package/dist/bounded-process-BBZob7vl.js.map +1 -0
  19. package/dist/builder-eval/index.d.ts +3 -3
  20. package/dist/builder-eval/index.js +2 -2
  21. package/dist/campaign/index.d.ts +9 -9
  22. package/dist/campaign/index.js +6 -6
  23. package/dist/{campaign-Dp35pBbS.js → campaign-pxS0wmo4.js} +8 -8
  24. package/dist/{campaign-Dp35pBbS.js.map → campaign-pxS0wmo4.js.map} +1 -1
  25. package/dist/chat-client-Db4bqYfA.js +115 -0
  26. package/dist/chat-client-Db4bqYfA.js.map +1 -0
  27. package/dist/{chat-json-call-5Jxna-aV.js → chat-json-call-C26igCih.js} +16 -6
  28. package/dist/chat-json-call-C26igCih.js.map +1 -0
  29. package/dist/cli.js +31 -17
  30. package/dist/cli.js.map +1 -1
  31. package/dist/{client-BvwNkIRN.js → client-BlLY6o2w.js} +2 -2
  32. package/dist/{client-BvwNkIRN.js.map → client-BlLY6o2w.js.map} +1 -1
  33. package/dist/{client-Df7wdslk.d.ts → client-DlqdbM7n.d.ts} +4 -4
  34. package/dist/{client-Df7wdslk.d.ts.map → client-DlqdbM7n.d.ts.map} +1 -1
  35. package/dist/contract/index.d.ts +13 -13
  36. package/dist/contract/index.js +202 -10
  37. package/dist/contract/index.js.map +1 -1
  38. package/dist/{counterfactual-Bee5_BIn.d.ts → counterfactual-CLgrwhkY.d.ts} +4 -4
  39. package/dist/{counterfactual-Bee5_BIn.d.ts.map → counterfactual-CLgrwhkY.d.ts.map} +1 -1
  40. package/dist/{chat-client-DI79OPye.js → default-registry-B0bKikCb.js} +3 -39
  41. package/dist/default-registry-B0bKikCb.js.map +1 -0
  42. package/dist/{default-registry-XxedTLwu.d.ts → default-registry-BKwc8bN5.d.ts} +6 -6
  43. package/dist/{default-registry-XxedTLwu.d.ts.map → default-registry-BKwc8bN5.d.ts.map} +1 -1
  44. package/dist/{define-agent-eval-0wW7gFhr.d.ts → define-agent-eval-CY6qdlGV.d.ts} +6 -6
  45. package/dist/{define-agent-eval-0wW7gFhr.d.ts.map → define-agent-eval-CY6qdlGV.d.ts.map} +1 -1
  46. package/dist/{define-agent-eval-jS8xj_Q_.js → define-agent-eval-D_i_s69h.js} +7 -7
  47. package/dist/{define-agent-eval-jS8xj_Q_.js.map → define-agent-eval-D_i_s69h.js.map} +1 -1
  48. package/dist/{dspy-rlm-engine-CS3qcCEk.js → dspy-rlm-engine-D5byiHn9.js} +5 -6
  49. package/dist/dspy-rlm-engine-D5byiHn9.js.map +1 -0
  50. package/dist/{emitter-Bvnu0VzL.d.ts → emitter-Cs0egaFd.d.ts} +3 -3
  51. package/dist/{emitter-Bvnu0VzL.d.ts.map → emitter-Cs0egaFd.d.ts.map} +1 -1
  52. package/dist/{engine-BfRay1qD.d.ts → engine-DhFir3Ys.d.ts} +23 -8
  53. package/dist/{engine-BfRay1qD.d.ts.map → engine-DhFir3Ys.d.ts.map} +1 -1
  54. package/dist/{eval-campaign-JDTeE6Pl.js → eval-campaign-BeAjdhzC.js} +2 -2
  55. package/dist/{eval-campaign-JDTeE6Pl.js.map → eval-campaign-BeAjdhzC.js.map} +1 -1
  56. package/dist/{exact-types-BEecmnWm.d.ts → exact-types-BKOEILRP.d.ts} +2 -2
  57. package/dist/{exact-types-BEecmnWm.d.ts.map → exact-types-BKOEILRP.d.ts.map} +1 -1
  58. package/dist/experiment/index.d.ts +4 -4
  59. package/dist/{external-optimizer-contracts-szBJ_1vh.d.ts → external-optimizer-contracts-CQCpyrIL.d.ts} +2 -2
  60. package/dist/{external-optimizer-contracts-szBJ_1vh.d.ts.map → external-optimizer-contracts-CQCpyrIL.d.ts.map} +1 -1
  61. package/dist/{external-optimizer-process-CQxylYeG.js → external-optimizer-process-Cq_Pg15r.js} +2 -2
  62. package/dist/{external-optimizer-process-CQxylYeG.js.map → external-optimizer-process-Cq_Pg15r.js.map} +1 -1
  63. package/dist/{external-optimizer-subprocess-Cex8Da2i.js → external-optimizer-subprocess-DgNebftP.js} +2 -2
  64. package/dist/{external-optimizer-subprocess-Cex8Da2i.js.map → external-optimizer-subprocess-DgNebftP.js.map} +1 -1
  65. package/dist/failure-cluster-OldNRoAt.d.ts +154 -0
  66. package/dist/failure-cluster-OldNRoAt.d.ts.map +1 -0
  67. package/dist/{feedback-trajectory-DIqpCyF0.d.ts → feedback-trajectory-CMnv_uYs.d.ts} +6 -6
  68. package/dist/{feedback-trajectory-DIqpCyF0.d.ts.map → feedback-trajectory-CMnv_uYs.d.ts.map} +1 -1
  69. package/dist/{heldout-gate-JgNRDZwZ.d.ts → heldout-gate-Df5hsqmm.d.ts} +7 -7
  70. package/dist/{heldout-gate-JgNRDZwZ.d.ts.map → heldout-gate-Df5hsqmm.d.ts.map} +1 -1
  71. package/dist/hosted/index.d.ts +2 -2
  72. package/dist/hosted/index.js +1 -1
  73. package/dist/{index-DnglhM0A.d.ts → index-BQqOjerE.d.ts} +94 -13
  74. package/dist/index-BQqOjerE.d.ts.map +1 -0
  75. package/dist/{index-_vPrVMRX.d.ts → index-CFDffsKz.d.ts} +11 -11
  76. package/dist/{index-_vPrVMRX.d.ts.map → index-CFDffsKz.d.ts.map} +1 -1
  77. package/dist/{index-DDAPhUJJ.d.ts → index-D0Db5X-4.d.ts} +45 -9
  78. package/dist/index-D0Db5X-4.d.ts.map +1 -0
  79. package/dist/{index-DMoxLG8P.d.ts → index-e7LXeRVa.d.ts} +3 -3
  80. package/dist/{index-DMoxLG8P.d.ts.map → index-e7LXeRVa.d.ts.map} +1 -1
  81. package/dist/index.d.ts +130 -42
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +64 -41
  84. package/dist/index.js.map +1 -1
  85. package/dist/{insight-report-08F022xN.d.ts → insight-report-DETqPc_A.d.ts} +4 -4
  86. package/dist/{insight-report-08F022xN.d.ts.map → insight-report-DETqPc_A.d.ts.map} +1 -1
  87. package/dist/{integrity-B_EDELom.d.ts → integrity-BKTcA-HP.d.ts} +3 -3
  88. package/dist/{integrity-B_EDELom.d.ts.map → integrity-BKTcA-HP.d.ts.map} +1 -1
  89. package/dist/{kind-factory-DMeEoMQZ.js → kind-factory-gP6lDySe.js} +164 -149
  90. package/dist/kind-factory-gP6lDySe.js.map +1 -0
  91. package/dist/{llm-client-BFMRpmqb.js → llm-client-CxQtdtd6.js} +12 -5
  92. package/dist/llm-client-CxQtdtd6.js.map +1 -0
  93. package/dist/{llm-judge-aQHIk5_-.js → llm-judge-B2YxbAJb.js} +81 -7
  94. package/dist/{llm-judge-aQHIk5_-.js.map → llm-judge-B2YxbAJb.js.map} +1 -1
  95. package/dist/{matrix-Ch8JO1pG.d.ts → matrix-DGu8KhSs.d.ts} +2 -2
  96. package/dist/{matrix-Ch8JO1pG.d.ts.map → matrix-DGu8KhSs.d.ts.map} +1 -1
  97. package/dist/meta-eval/index.d.ts +100 -5
  98. package/dist/meta-eval/index.d.ts.map +1 -1
  99. package/dist/meta-eval/index.js +200 -2
  100. package/dist/meta-eval/index.js.map +1 -1
  101. package/dist/{mint-DjfDUMHr.js → mint-vWOdD8Ae.js} +2 -2
  102. package/dist/{mint-DjfDUMHr.js.map → mint-vWOdD8Ae.js.map} +1 -1
  103. package/dist/multishot/golden/index.d.ts +1 -1
  104. package/dist/multishot/index.d.ts +2 -2
  105. package/dist/openapi.json +1 -1
  106. package/dist/pipelines/index.d.ts +5 -5
  107. package/dist/pipelines/index.js +3 -3
  108. package/dist/{pre-registration-DHz6P_6f.d.ts → pre-registration-BoI4ucR3.d.ts} +2 -2
  109. package/dist/{pre-registration-DHz6P_6f.d.ts.map → pre-registration-BoI4ucR3.d.ts.map} +1 -1
  110. package/dist/{produced-state-CxmbFxFd.js → produced-state-7VYDwtkk.js} +3 -3
  111. package/dist/{produced-state-CxmbFxFd.js.map → produced-state-7VYDwtkk.js.map} +1 -1
  112. package/dist/{promotion-policy-BBBcz5_3.d.ts → promotion-policy-CvMda3kU.d.ts} +2 -2
  113. package/dist/{promotion-policy-BBBcz5_3.d.ts.map → promotion-policy-CvMda3kU.d.ts.map} +1 -1
  114. package/dist/{provenance-Dp-vvyrU.d.ts → provenance-CRY67X50.d.ts} +39 -165
  115. package/dist/provenance-CRY67X50.d.ts.map +1 -0
  116. package/dist/{query-BPGMVlbM.js → query-D1nLIKt7.js} +2 -2
  117. package/dist/{query-BPGMVlbM.js.map → query-D1nLIKt7.js.map} +1 -1
  118. package/dist/{query-Na5gEIGd.d.ts → query-D6W6MaGx.d.ts} +3 -3
  119. package/dist/{query-Na5gEIGd.d.ts.map → query-D6W6MaGx.d.ts.map} +1 -1
  120. package/dist/{registry-xEb_xfns.d.ts → registry-7pOUBrtX.d.ts} +4 -4
  121. package/dist/{registry-xEb_xfns.d.ts.map → registry-7pOUBrtX.d.ts.map} +1 -1
  122. package/dist/{release-confidence-D6lQw_o7.d.ts → release-confidence-BAcNYOf1.d.ts} +4 -4
  123. package/dist/{release-confidence-D6lQw_o7.d.ts.map → release-confidence-BAcNYOf1.d.ts.map} +1 -1
  124. package/dist/{release-confidence-CzUHc4z4.js → release-confidence-BsGEg_xg.js} +3 -3
  125. package/dist/{release-confidence-CzUHc4z4.js.map → release-confidence-BsGEg_xg.js.map} +1 -1
  126. package/dist/reporting.d.ts +3 -3
  127. package/dist/reporting.js +1 -1
  128. package/dist/{researcher-CMUTQXD7.d.ts → researcher-jsW1X94L.d.ts} +7 -8
  129. package/dist/researcher-jsW1X94L.d.ts.map +1 -0
  130. package/dist/{reward-hacking-SkxYgT0x.js → reward-hacking-CKW4teig.js} +2 -2
  131. package/dist/{reward-hacking-SkxYgT0x.js.map → reward-hacking-CKW4teig.js.map} +1 -1
  132. package/dist/{reward-hacking-CgPRUesA.d.ts → reward-hacking-ZXEi9VCq.d.ts} +2 -2
  133. package/dist/{reward-hacking-CgPRUesA.d.ts.map → reward-hacking-ZXEi9VCq.d.ts.map} +1 -1
  134. package/dist/rl.d.ts +7 -7
  135. package/dist/rl.js +4 -4
  136. package/dist/rollout/index.d.ts +1 -1
  137. package/dist/rollout/index.js +2 -2
  138. package/dist/{rollout-Crypdx8s.js → rollout-C-znbbYg.js} +2 -2
  139. package/dist/{rollout-Crypdx8s.js.map → rollout-C-znbbYg.js.map} +1 -1
  140. package/dist/{rubric-predictive-validity-DluJLCKQ.d.ts → rubric-predictive-validity-Dl1dvKCv.d.ts} +2 -2
  141. package/dist/{rubric-predictive-validity-DluJLCKQ.d.ts.map → rubric-predictive-validity-Dl1dvKCv.d.ts.map} +1 -1
  142. package/dist/{run-record-DQjRcYwA.d.ts → run-record-DTv1MdjK.d.ts} +2 -2
  143. package/dist/{run-record-DQjRcYwA.d.ts.map → run-record-DTv1MdjK.d.ts.map} +1 -1
  144. package/dist/{run-record-DLORoL7t.js → run-record-ZIsR9Fif.js} +2 -2
  145. package/dist/{run-record-DLORoL7t.js.map → run-record-ZIsR9Fif.js.map} +1 -1
  146. package/dist/{schema-DID1Cqct.d.ts → schema-CR5cpjQ3.d.ts} +57 -2
  147. package/dist/{schema-DID1Cqct.d.ts.map → schema-CR5cpjQ3.d.ts.map} +1 -1
  148. package/dist/{schema-CdIX2aHu.js → schema-CSf6qWgZ.js} +35 -1
  149. package/dist/{schema-CdIX2aHu.js.map → schema-CSf6qWgZ.js.map} +1 -1
  150. package/dist/semantic-concept-judge-Ct3QU7t5.js +780 -0
  151. package/dist/semantic-concept-judge-Ct3QU7t5.js.map +1 -0
  152. package/dist/{series-convergence-D9WgpXGi.d.ts → series-convergence-DeG33RpC.d.ts} +2 -2
  153. package/dist/{series-convergence-D9WgpXGi.d.ts.map → series-convergence-DeG33RpC.d.ts.map} +1 -1
  154. package/dist/{server-CCEnywOR.js → server-BR6onwZB.js} +2 -2
  155. package/dist/{server-CCEnywOR.js.map → server-BR6onwZB.js.map} +1 -1
  156. package/dist/{skillopt-optimization-method-LHi02MzH.js → skillopt-optimization-method-BzdphODy.js} +6 -6
  157. package/dist/{skillopt-optimization-method-LHi02MzH.js.map → skillopt-optimization-method-BzdphODy.js.map} +1 -1
  158. package/dist/{statistical-heldout-Yldkntvy.d.ts → statistical-heldout-DTyB_6-1.d.ts} +3 -3
  159. package/dist/{statistical-heldout-Yldkntvy.d.ts.map → statistical-heldout-DTyB_6-1.d.ts.map} +1 -1
  160. package/dist/{store-Cq9oOrI1.d.ts → store-BErPvYBr.d.ts} +2 -2
  161. package/dist/{store-Cq9oOrI1.d.ts.map → store-BErPvYBr.d.ts.map} +1 -1
  162. package/dist/{store-otlp-CHjBvWQY.js → store-otlp-Dow0pk_5.js} +2 -2
  163. package/dist/{store-otlp-CHjBvWQY.js.map → store-otlp-Dow0pk_5.js.map} +1 -1
  164. package/dist/{store-tool-spans-BvdUbeOB.d.ts → store-tool-spans-CCZNsihA.d.ts} +8 -8
  165. package/dist/{store-tool-spans-BvdUbeOB.d.ts.map → store-tool-spans-CCZNsihA.d.ts.map} +1 -1
  166. package/dist/{store-tool-spans-B9o6tU8f.js → store-tool-spans-CeNj_m2L.js} +3 -3
  167. package/dist/{store-tool-spans-B9o6tU8f.js.map → store-tool-spans-CeNj_m2L.js.map} +1 -1
  168. package/dist/storyboard/index.d.ts +1 -1
  169. package/dist/{summary-report-DRstQNBX.d.ts → summary-report-gMrbYawB.d.ts} +3 -3
  170. package/dist/{summary-report-DRstQNBX.d.ts.map → summary-report-gMrbYawB.d.ts.map} +1 -1
  171. package/dist/{task-failure-attributes-CBGtLS_H.js → task-failure-attributes-CZjZeBsY.js} +3 -3
  172. package/dist/{task-failure-attributes-CBGtLS_H.js.map → task-failure-attributes-CZjZeBsY.js.map} +1 -1
  173. package/dist/{tool-groups-DjwlMBvW.d.ts → tool-groups-Cp4Xdzrp.d.ts} +3 -3
  174. package/dist/tool-groups-Cp4Xdzrp.d.ts.map +1 -0
  175. package/dist/{tool-waste-CwGHzBzX.js → tool-waste-B9tdWV6g.js} +253 -6
  176. package/dist/tool-waste-B9tdWV6g.js.map +1 -0
  177. package/dist/{tool-waste-BrmLKxMw.d.ts → tool-waste-D23I0zWm.d.ts} +4 -4
  178. package/dist/{tool-waste-BrmLKxMw.d.ts.map → tool-waste-D23I0zWm.d.ts.map} +1 -1
  179. package/dist/trace-repair/index.d.ts +2 -2
  180. package/dist/traces.d.ts +10 -10
  181. package/dist/traces.js +7 -7
  182. package/dist/{trajectory-r1bQqvBQ.d.ts → trajectory-D7qrNvaN.d.ts} +3 -3
  183. package/dist/{trajectory-r1bQqvBQ.d.ts.map → trajectory-D7qrNvaN.d.ts.map} +1 -1
  184. package/dist/trajectory-replay/index.d.ts +3 -3
  185. package/dist/{types-CCZ34qmV.d.ts → types-BDV4PiMR.d.ts} +3 -3
  186. package/dist/{types-CCZ34qmV.d.ts.map → types-BDV4PiMR.d.ts.map} +1 -1
  187. package/dist/{types-nokrtr7M.d.ts → types-Ba5UQyVD.d.ts} +4 -4
  188. package/dist/{types-nokrtr7M.d.ts.map → types-Ba5UQyVD.d.ts.map} +1 -1
  189. package/dist/{types-DMoNFDWi.d.ts → types-DN2WdT5S.d.ts} +3 -3
  190. package/dist/{types-DMoNFDWi.d.ts.map → types-DN2WdT5S.d.ts.map} +1 -1
  191. package/dist/types-gvRsyJLh.d.ts +831 -0
  192. package/dist/types-gvRsyJLh.d.ts.map +1 -0
  193. package/dist/wire/index.d.ts +3 -3
  194. package/dist/wire/index.js +1 -1
  195. package/docs/plants.md +69 -1
  196. package/docs/public-api.md +6 -4
  197. package/docs/trace-analysis.md +55 -8
  198. package/package.json +1 -1
  199. package/dist/backend-integrity-e79K3UPD.d.ts.map +0 -1
  200. package/dist/bounded-process-VIi0KSL2.js.map +0 -1
  201. package/dist/chat-client-DI79OPye.js.map +0 -1
  202. package/dist/chat-json-call-5Jxna-aV.js.map +0 -1
  203. package/dist/dspy-rlm-engine-CS3qcCEk.js.map +0 -1
  204. package/dist/failure-cluster-6YSvsKlp.d.ts +0 -58
  205. package/dist/failure-cluster-6YSvsKlp.d.ts.map +0 -1
  206. package/dist/index-DDAPhUJJ.d.ts.map +0 -1
  207. package/dist/index-DnglhM0A.d.ts.map +0 -1
  208. package/dist/kind-factory-DMeEoMQZ.js.map +0 -1
  209. package/dist/llm-client-BFMRpmqb.js.map +0 -1
  210. package/dist/provenance-Dp-vvyrU.d.ts.map +0 -1
  211. package/dist/raw-provider-sink-BU29Sh8h.d.ts +0 -134
  212. package/dist/raw-provider-sink-BU29Sh8h.d.ts.map +0 -1
  213. package/dist/researcher-CMUTQXD7.d.ts.map +0 -1
  214. package/dist/semantic-concept-judge-I36eejJx.js +0 -382
  215. package/dist/semantic-concept-judge-I36eejJx.js.map +0 -1
  216. package/dist/tool-groups-DjwlMBvW.d.ts.map +0 -1
  217. package/dist/tool-waste-CwGHzBzX.js.map +0 -1
  218. package/dist/types-Bfk0uxRj.d.ts +0 -443
  219. package/dist/types-Bfk0uxRj.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"client-BvwNkIRN.js","names":[],"sources":["../src/hosted/types.ts","../src/hosted/schemas.ts","../src/hosted/client.ts"],"sourcesContent":["/**\n * # Hosted-tier wire format — the schema that EVERY orchestrator (ours,\n * a partner's self-hosted one, a future open implementation) must accept.\n *\n * This package implements exactly one wire version. Servers reject every\n * other version instead of translating old payloads.\n *\n * The wire format is two event streams in one transport:\n *\n * 1. **Eval-run events** (`POST /v1/ingest/eval-runs`). Posted when a\n * campaign / improvement-loop completes (or per-generation if\n * streaming). Carries the structured result + per-cell scores +\n * surface diffs the orchestrator stores for the dashboard.\n *\n * 2. **Trace spans** (`POST /v1/ingest/traces`). Standard OTLP-shaped\n * spans with a few additional attributes so the orchestrator can\n * pivot from eval-run → underlying execution. Compatible with any\n * OTel collector.\n *\n * Both endpoints are authenticated with a bearer token + a tenant id\n * header. Tenants isolate everything downstream of ingest; no tenant\n * ever sees another tenant's data.\n */\n\nimport type { GateDecision, MutableSurface } from '../campaign/types'\nimport type { InsightReport } from '../contract/insight-report'\nimport type { RunTerminalOutcome } from '../run-record'\n\n// re-export so wire-format consumers can import the optional payload type\n// from `@tangle-network/agent-eval/hosted` without reaching into /contract.\nexport type { InsightReport } from '../contract/insight-report'\n\nexport const HOSTED_WIRE_VERSION = '2026-07-24.v1' as const\nexport type HostedWireVersion = typeof HOSTED_WIRE_VERSION\n\n// ── Transport headers ───────────────────────────────────────────────\n\n/** Every ingest request carries these. */\nexport interface HostedIngestHeaders {\n /** Bearer token. The orchestrator validates against the tenant key. */\n authorization: `Bearer ${string}`\n /** Stable tenant id (the orchestrator-side primary key for the tenant). */\n 'x-tangle-tenant-id': string\n /** Wire-version pin so the server can reject incompatible payloads. */\n 'x-tangle-wire-version': HostedWireVersion\n /** Stable request key generated once and reused across retries. */\n 'idempotency-key': string\n}\n\n// ── Eval-run event ──────────────────────────────────────────────────\n\n/** Lifecycle stages of an eval-run as the substrate reports them. */\nexport type EvalRunStatus =\n | 'started'\n | 'baseline-complete'\n | 'generation-complete'\n | 'gate-decided'\n | 'finished'\n | 'errored'\n\nexport interface EvalRunCellScore {\n /** Stable scenario id from the consumer's scenario set. */\n scenarioId: string\n /** Repetition index when reps > 1; 0 for the default. */\n rep: number\n /** Composite score across successful judges, or null when unscored. */\n compositeMean: number | null\n /** Per-judge and per-dimension scores; failed or missing judges are absent. */\n dimensions: Record<string, Record<string, number>>\n /** Root execution result, kept separate from task quality. */\n terminalOutcome: RunTerminalOutcome\n /** Canonical execution-error count, or null when the producer did not measure it. */\n executionErrorCount: number | null\n /** Per-cell dispatch or judge error. Missing on success. */\n errorMessage?: string\n}\n\nexport interface EvalRunGenerationSnapshot {\n /** Generation index. 0 is baseline. */\n index: number\n /** Candidate surface fingerprint (stable hash) — pivot key into the\n * trace stream to fetch the underlying execution. */\n surfaceHash: string\n /** The candidate surface itself. May be omitted to avoid PII when the\n * consumer prefers not to ship verbatim prompts. */\n surface?: MutableSurface\n /** Per-cell scores for this generation. */\n cells: EvalRunCellScore[]\n /** Mean across scored cells, or null when no cell has a task-quality label. */\n compositeMean: number | null\n /** Total $ spent across this generation. */\n costUsd: number\n /** Wall-clock duration of this generation. */\n durationMs: number\n}\n\n/**\n * The top-level eval-run event. One ingest call per logical eval-run;\n * generations stream in incrementally via repeated calls with the same\n * `runId`. The orchestrator deduplicates by `(runId, generation.index)`.\n */\nexport interface EvalRunEvent {\n /** Stable run id (the substrate's `runId`). UUID or substrate-generated. */\n runId: string\n /** Where this run was happening — derived from `RunCampaignOptions.runDir`. */\n runDir: string\n /** ISO-8601 timestamp the substrate recorded the event. */\n timestamp: string\n /** Lifecycle stage this event represents. */\n status: EvalRunStatus\n /** Free-form consumer tags (env, branch, model id, etc.). Searchable. */\n labels: Record<string, string>\n /** Baseline campaign snapshot. Present when status >= baseline-complete. */\n baseline?: EvalRunGenerationSnapshot\n /** Per-generation snapshots. Streams in; orchestrator appends. */\n generations: EvalRunGenerationSnapshot[]\n /** Final gate decision. Present when status >= gate-decided. */\n gateDecision?: GateDecision\n /** Held-out lift = winner-on-holdout - baseline-on-holdout. */\n holdoutLift?: number\n /** Total $ spent across baseline + every generation. */\n totalCostUsd: number\n /** Total wall-clock duration. */\n totalDurationMs: number\n /** Error message if status === 'errored'. */\n errorMessage?: string\n /** Rigor packet emitted alongside the run — distributional summary,\n * paired-bootstrap lift CI, judge stats, inter-rater agreement,\n * contamination check, failure clusters (when an analyst is wired),\n * outcome correlation (when downstream signal is supplied), and the\n * recommendations the dashboard surfaces verbatim. */\n insightReport?: InsightReport\n}\n\n// ── Trace span event ────────────────────────────────────────────────\n\n/**\n * Canonical unsigned 64-bit integer encoded as a base-10 string.\n * JSON numbers cannot represent OTLP nanosecond timestamps exactly.\n */\nexport type UnixNanoTimestamp = string\n\n/**\n * OTel-shape span with a few additional attributes for eval-run pivoting.\n * Compatible with any OTLP collector — `name`, `traceId`, `spanId`,\n * `startTimeUnixNano`, `endTimeUnixNano`, `attributes` are stock OTel.\n */\nexport interface TraceSpanEvent {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n startTimeUnixNano: UnixNanoTimestamp\n endTimeUnixNano: UnixNanoTimestamp\n attributes: Record<string, string | number | boolean>\n events?: Array<{\n timeUnixNano: UnixNanoTimestamp\n name: string\n attributes?: Record<string, string | number | boolean>\n }>\n status?: { code: 'OK' | 'ERROR' | 'UNSET'; message?: string }\n /** Pivot back into the eval-run stream. */\n 'tangle.runId'?: string\n /** Pivot to the specific generation. */\n 'tangle.generation'?: number\n /** Pivot to the specific cell. */\n 'tangle.cellId'?: string\n /** Pivot to the specific scenario. */\n 'tangle.scenarioId'?: string\n}\n\n// ── Ingest request bodies ───────────────────────────────────────────\n\nexport interface IngestEvalRunsRequest {\n wireVersion: HostedWireVersion\n events: EvalRunEvent[]\n}\n\nexport interface IngestTracesRequest {\n wireVersion: HostedWireVersion\n spans: TraceSpanEvent[]\n}\n\nexport interface IngestResponse {\n /** Accepted events / spans count. */\n accepted: number\n /** Rejected events with reasons (validation failures, dup idempotency key, etc.). */\n rejected: Array<{ index: number; reason: string }>\n}\n","import { z } from 'zod'\nimport type { MutableSurface } from '../campaign/types'\nimport type { InsightReport } from '../contract/insight-report'\nimport { FAILURE_CLASSES, type FailureClass } from '../trace/schema'\nimport type {\n EvalRunCellScore,\n EvalRunEvent,\n EvalRunGenerationSnapshot,\n IngestEvalRunsRequest,\n IngestResponse,\n IngestTracesRequest,\n TraceSpanEvent,\n UnixNanoTimestamp,\n} from './types'\nimport { HOSTED_WIRE_VERSION } from './types'\n\nconst finiteNumber = z.number().finite()\nconst nonNegativeNumber = finiteNumber.nonnegative()\nconst nonNegativeInteger = z.number().int().nonnegative()\nconst nonEmptyString = z\n .string()\n .min(1)\n .refine((value) => value.trim().length > 0, 'must not be blank')\nconst attributeValue = z.union([z.string(), finiteNumber, z.boolean()])\nconst attributes = z.record(z.string(), attributeValue)\nconst FailureClassSchema = z.custom<FailureClass>(\n (value) => typeof value === 'string' && FAILURE_CLASSES.includes(value as FailureClass),\n `expected one of ${FAILURE_CLASSES.join(', ')}`,\n)\nconst UINT64_MAX = 18_446_744_073_709_551_615n\n\nexport const UnixNanoTimestampSchema: z.ZodType<UnixNanoTimestamp> = z\n .string()\n .regex(/^(0|[1-9][0-9]*)$/, 'expected an unsigned base-10 integer string')\n .refine((value) => BigInt(value) <= UINT64_MAX, 'must fit in an unsigned 64-bit integer')\n\nconst GainDistributionBinSchema = z\n .object({\n lo: finiteNumber,\n hi: finiteNumber,\n count: nonNegativeInteger,\n })\n .strict()\n\nconst ScalarDistributionSchema = z\n .object({\n n: nonNegativeInteger,\n mean: finiteNumber.nullable(),\n p50: finiteNumber.nullable(),\n p95: finiteNumber.nullable(),\n stddev: nonNegativeNumber.nullable(),\n min: finiteNumber.nullable(),\n max: finiteNumber.nullable(),\n histogram: z.array(GainDistributionBinSchema),\n tailRuns: z\n .array(\n z\n .object({\n runId: nonEmptyString,\n score: finiteNumber,\n })\n .strict(),\n )\n .optional(),\n })\n .strict()\n .superRefine((distribution, ctx) => {\n const values = [\n distribution.mean,\n distribution.p50,\n distribution.p95,\n distribution.stddev,\n distribution.min,\n distribution.max,\n ]\n if (distribution.n === 0 && values.some((value) => value !== null)) {\n ctx.addIssue({\n code: 'custom',\n message: 'distribution values must be null when n is 0',\n })\n }\n if (distribution.n > 0 && values.some((value) => value === null)) {\n ctx.addIssue({\n code: 'custom',\n message: 'distribution values must be numbers when n is greater than 0',\n })\n }\n if (\n distribution.min !== null &&\n distribution.max !== null &&\n distribution.min > distribution.max\n ) {\n ctx.addIssue({ code: 'custom', path: ['min'], message: 'min must not exceed max' })\n }\n })\n\nconst TokenUsageInsightSchema = z\n .object({\n input: ScalarDistributionSchema,\n output: ScalarDistributionSchema,\n reasoning: ScalarDistributionSchema,\n cached: ScalarDistributionSchema,\n cacheWrite: ScalarDistributionSchema,\n totals: z\n .object({\n input: nonNegativeNumber,\n output: nonNegativeNumber,\n reasoning: nonNegativeNumber,\n cached: nonNegativeNumber,\n cacheWrite: nonNegativeNumber,\n })\n .strict(),\n })\n .strict()\n\nconst ExecutionErrorOutcomeCellSchema = z\n .object({\n withErrors: nonNegativeInteger,\n withoutErrors: nonNegativeInteger,\n unreported: nonNegativeInteger,\n })\n .strict()\n\nconst ExecutionInsightSchema = z\n .object({\n durationMs: ScalarDistributionSchema,\n queueMs: ScalarDistributionSchema,\n tokenUsage: TokenUsageInsightSchema,\n aggregateUsage: z\n .object({\n runs: nonNegativeInteger,\n tokenUsage: TokenUsageInsightSchema,\n costUsd: ScalarDistributionSchema,\n totalCostUsd: nonNegativeNumber,\n })\n .strict(),\n models: z.array(\n z\n .object({\n model: nonEmptyString,\n runs: nonNegativeInteger,\n })\n .strict(),\n ),\n modelCalls: z\n .object({\n runs: nonNegativeInteger,\n events: nonNegativeInteger,\n reportingRuns: nonNegativeInteger,\n })\n .strict(),\n executionErrors: z\n .object({\n runs: nonNegativeInteger,\n fraction: finiteNumber.min(0).max(1).nullable(),\n events: nonNegativeInteger,\n reportingRuns: nonNegativeInteger,\n errorSpanEvents: nonNegativeInteger,\n errorSpanReportingRuns: nonNegativeInteger,\n byTerminalOutcome: z\n .object({\n succeeded: ExecutionErrorOutcomeCellSchema,\n failed: ExecutionErrorOutcomeCellSchema,\n cancelled: ExecutionErrorOutcomeCellSchema,\n incomplete: ExecutionErrorOutcomeCellSchema,\n unknown: ExecutionErrorOutcomeCellSchema,\n })\n .strict(),\n })\n .strict(),\n terminalOutcomes: z\n .object({\n succeeded: nonNegativeInteger,\n failed: nonNegativeInteger,\n cancelled: nonNegativeInteger,\n incomplete: nonNegativeInteger,\n unknown: nonNegativeInteger,\n })\n .strict(),\n })\n .strict()\n\nconst CostProvenanceSummarySchema = z\n .object({\n observed: z\n .object({\n n: nonNegativeInteger,\n totalUsd: nonNegativeNumber,\n })\n .strict(),\n estimated: z\n .object({\n n: nonNegativeInteger,\n totalUsd: nonNegativeNumber,\n })\n .strict(),\n uncaptured: z.object({ n: nonNegativeInteger }).strict(),\n knownFraction: finiteNumber.min(0).max(1),\n })\n .strict()\n\nconst ParetoFigureSpecSchema = z\n .object({\n kind: z.literal('pareto-cost-quality'),\n split: z.enum(['search', 'holdout']),\n points: z.array(\n z\n .object({\n candidateId: nonEmptyString,\n cost: nonNegativeNumber,\n quality: finiteNumber,\n n: nonNegativeInteger,\n onFrontier: z.boolean(),\n gate: z.enum(['promote', 'reject']).optional(),\n })\n .strict(),\n ),\n axes: z.object({ x: z.literal('costUsd'), y: z.literal('score') }).strict(),\n })\n .strict()\n\nconst ContinuousAgreementSchema = z\n .object({\n weightedKappa: finiteNumber,\n icc: finiteNumber,\n pearson: finiteNumber,\n spearman: finiteNumber,\n ci: z\n .object({\n icc: z.tuple([finiteNumber, finiteNumber]),\n weightedKappa: z.tuple([finiteNumber, finiteNumber]),\n })\n .strict(),\n n: nonNegativeInteger,\n raters: nonNegativeInteger,\n })\n .strict()\n\nconst JudgeInsightSchema = z\n .object({\n n: nonNegativeInteger,\n meanScore: finiteNumber,\n calibration: ContinuousAgreementSchema.optional(),\n positionalBias: finiteNumber.optional(),\n selfPreference: finiteNumber.optional(),\n verbosityBias: finiteNumber.optional(),\n })\n .strict()\n\nconst InterRaterInsightSchema = z\n .object({\n raters: nonNegativeInteger,\n jointlyRated: nonNegativeInteger,\n kappa: finiteNumber,\n icc: finiteNumber,\n pearson: finiteNumber,\n spearman: finiteNumber,\n perPair: z.record(z.string(), finiteNumber),\n disagreementCases: z.array(\n z\n .object({\n runId: nonEmptyString,\n ratings: z.array(\n z\n .object({\n rater: nonEmptyString,\n score: finiteNumber,\n })\n .strict(),\n ),\n range: nonNegativeNumber,\n })\n .strict(),\n ),\n })\n .strict()\n\nconst LiftInsightSchema = z\n .object({\n baselineMean: finiteNumber,\n candidateMean: finiteNumber,\n delta: finiteNumber,\n ci95: z.tuple([finiteNumber, finiteNumber]),\n pValue: finiteNumber.min(0).max(1).nullable(),\n n: nonNegativeInteger,\n minimumRequired: z.number().int().positive(),\n decisionEligible: z.boolean(),\n unpairedBaseline: nonNegativeInteger,\n unpairedCandidate: nonNegativeInteger,\n cohensD: finiteNumber.nullable(),\n mde: nonNegativeNumber,\n requiredN: nonNegativeInteger.nullable(),\n })\n .strict()\n\nconst FailureClusterInsightSchema = z\n .object({\n clusters: z.array(\n z\n .object({\n id: nonEmptyString,\n name: nonEmptyString,\n share: finiteNumber.min(0).max(1),\n exemplars: z.array(nonEmptyString).max(5),\n suggestedFix: nonEmptyString.optional(),\n })\n .strict(),\n ),\n totalFailures: nonNegativeInteger,\n })\n .strict()\n\nconst ContaminationInsightSchema = z\n .object({\n leaks: nonNegativeInteger,\n holdoutAuditPassed: z.boolean(),\n details: z\n .array(\n z\n .object({\n runId: nonEmptyString,\n canary: nonEmptyString,\n matched: nonEmptyString,\n })\n .strict(),\n )\n .optional(),\n })\n .strict()\n\nconst OutcomeCorrelationInsightSchema = z\n .object({\n metric: nonEmptyString,\n n: nonNegativeInteger,\n pearson: finiteNumber,\n spearman: finiteNumber,\n rewardModel: z\n .object({\n intercept: finiteNumber,\n slope: finiteNumber,\n r2: finiteNumber,\n })\n .strict()\n .optional(),\n })\n .strict()\n\nconst ReleaseSummarySchema = z\n .object({\n status: z.enum(['pass', 'warn', 'fail']),\n axes: z.array(\n z\n .object({\n name: z.enum(['quality-lift', 'contamination', 'composite-distribution']),\n status: z.enum(['pass', 'warn', 'fail', 'not_evaluated']),\n detail: nonEmptyString,\n })\n .strict(),\n ),\n issues: z.array(z.string()),\n })\n .strict()\n\nconst MetricDeltaBaseSchema = z\n .object({\n current: finiteNumber,\n baseline: finiteNumber,\n delta: finiteNumber,\n baselineN: nonNegativeInteger,\n currentN: nonNegativeInteger,\n })\n .strict()\n\nconst MetricDeltaSchema = z.discriminatedUnion('status', [\n MetricDeltaBaseSchema.extend({\n status: z.literal('ok'),\n ci95: z.tuple([finiteNumber, finiteNumber]),\n pValue: finiteNumber.min(0).max(1),\n cohensD: finiteNumber,\n significant: z.boolean(),\n }),\n MetricDeltaBaseSchema.extend({\n status: z.enum(['insufficient-sample', 'zero-variance']),\n ci95: z.null(),\n pValue: z.null(),\n cohensD: z.null(),\n significant: z.literal(false),\n }),\n])\n\nconst PriorPeriodComparisonSchema = z\n .object({\n baselineN: nonNegativeInteger,\n currentN: nonNegativeInteger,\n windowLabel: nonEmptyString.optional(),\n metrics: z.record(z.string(), MetricDeltaSchema),\n regressedMetrics: z.array(nonEmptyString),\n improvedMetrics: z.array(nonEmptyString),\n inconclusiveMetrics: z.array(nonEmptyString),\n })\n .strict()\n\nconst RecommendationSchema = z\n .object({\n priority: z.enum(['critical', 'high', 'medium', 'low']),\n kind: z.enum(['ship', 'hold', 'investigate', 'fix', 'recalibrate', 'expand-corpus']),\n title: nonEmptyString,\n detail: nonEmptyString,\n evidencePath: nonEmptyString.optional(),\n })\n .strict()\n\nexport const InsightReportSchema: z.ZodType<InsightReport> = z\n .object({\n n: nonNegativeInteger,\n execution: ExecutionInsightSchema,\n composite: ScalarDistributionSchema,\n perDimension: z.record(z.string(), ScalarDistributionSchema),\n costQuality: z\n .object({\n cost: ScalarDistributionSchema,\n pareto: ParetoFigureSpecSchema,\n provenance: CostProvenanceSummarySchema.optional(),\n degraded: z\n .object({\n cost: nonEmptyString.optional(),\n pareto: nonEmptyString.optional(),\n })\n .strict()\n .optional(),\n })\n .strict(),\n judges: z.record(z.string(), JudgeInsightSchema),\n interRater: InterRaterInsightSchema.optional(),\n lift: LiftInsightSchema.optional(),\n failureClusters: FailureClusterInsightSchema.optional(),\n contamination: ContaminationInsightSchema.optional(),\n outcomeCorrelation: OutcomeCorrelationInsightSchema.optional(),\n release: ReleaseSummarySchema,\n priorPeriodComparison: PriorPeriodComparisonSchema.optional(),\n failureClasses: z\n .array(\n z\n .object({\n failureClass: FailureClassSchema,\n count: nonNegativeInteger,\n share: finiteNumber.min(0).max(1),\n })\n .strict(),\n )\n .optional(),\n recommendations: z.array(RecommendationSchema),\n })\n .strict()\n\nconst sha256Digest = z.custom<`sha256:${string}`>(\n (value) => typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value),\n 'expected sha256:<64 lowercase hex characters>',\n)\n\nconst MutableSurfaceSchema: z.ZodType<MutableSurface> = z.union([\n z.string(),\n z\n .object({\n kind: z.literal('components'),\n components: z.record(z.string(), z.string()),\n })\n .strict(),\n z\n .object({\n kind: z.literal('code'),\n worktreeRef: nonEmptyString,\n baseRef: nonEmptyString,\n baseCommit: nonEmptyString,\n baseTree: nonEmptyString,\n candidateCommit: nonEmptyString,\n candidateTree: nonEmptyString,\n patch: z\n .object({\n format: z.literal('git-diff-binary'),\n sha256: sha256Digest,\n byteLength: nonNegativeInteger,\n })\n .strict(),\n summary: z.string().optional(),\n })\n .strict(),\n])\n\nconst RunTerminalOutcomeSchema = z.enum([\n 'succeeded',\n 'failed',\n 'cancelled',\n 'incomplete',\n 'unknown',\n])\n\nconst EvalRunCellScoreSchema: z.ZodType<EvalRunCellScore> = z\n .object({\n scenarioId: nonEmptyString,\n rep: nonNegativeInteger,\n compositeMean: finiteNumber.nullable(),\n dimensions: z.record(z.string(), z.record(z.string(), finiteNumber)),\n terminalOutcome: RunTerminalOutcomeSchema,\n executionErrorCount: nonNegativeInteger.nullable(),\n errorMessage: z.string().optional(),\n })\n .strict()\n\nconst EvalRunGenerationSnapshotSchema: z.ZodType<EvalRunGenerationSnapshot> = z\n .object({\n index: nonNegativeInteger,\n surfaceHash: nonEmptyString,\n surface: MutableSurfaceSchema.optional(),\n cells: z.array(EvalRunCellScoreSchema),\n compositeMean: finiteNumber.nullable(),\n costUsd: nonNegativeNumber,\n durationMs: nonNegativeNumber,\n })\n .strict()\n\nconst EvalRunStatusSchema = z.enum([\n 'started',\n 'baseline-complete',\n 'generation-complete',\n 'gate-decided',\n 'finished',\n 'errored',\n])\n\nconst GateDecisionSchema = z.enum([\n 'ship',\n 'hold',\n 'need_more_work',\n 'model_ceiling',\n 'arch_ceiling',\n])\n\nexport const EvalRunEventSchema: z.ZodType<EvalRunEvent> = z\n .object({\n runId: nonEmptyString,\n runDir: nonEmptyString,\n timestamp: z.string().datetime({ offset: true }),\n status: EvalRunStatusSchema,\n labels: z.record(z.string(), z.string()),\n baseline: EvalRunGenerationSnapshotSchema.optional(),\n generations: z.array(EvalRunGenerationSnapshotSchema),\n gateDecision: GateDecisionSchema.optional(),\n holdoutLift: finiteNumber.optional(),\n totalCostUsd: nonNegativeNumber,\n totalDurationMs: nonNegativeNumber,\n errorMessage: z.string().optional(),\n insightReport: InsightReportSchema.optional(),\n })\n .strict()\n .superRefine((event, ctx) => {\n if (event.baseline && event.baseline.index !== 0) {\n ctx.addIssue({\n code: 'custom',\n path: ['baseline', 'index'],\n message: 'baseline index must be 0',\n })\n }\n\n const seen = new Set<number>()\n for (let i = 0; i < event.generations.length; i++) {\n const index = event.generations[i]!.index\n if (seen.has(index)) {\n ctx.addIssue({\n code: 'custom',\n path: ['generations', i, 'index'],\n message: `duplicate generation index ${index}`,\n })\n }\n seen.add(index)\n }\n\n if (event.status === 'errored' && !event.errorMessage?.trim()) {\n ctx.addIssue({\n code: 'custom',\n path: ['errorMessage'],\n message: 'errorMessage is required when status is errored',\n })\n }\n })\n\nconst TraceSpanEventEntrySchema = z\n .object({\n timeUnixNano: UnixNanoTimestampSchema,\n name: nonEmptyString,\n attributes: attributes.optional(),\n })\n .strict()\n\nexport const TraceSpanEventSchema: z.ZodType<TraceSpanEvent> = z\n .object({\n traceId: nonEmptyString,\n spanId: nonEmptyString,\n parentSpanId: nonEmptyString.optional(),\n name: nonEmptyString,\n startTimeUnixNano: UnixNanoTimestampSchema,\n endTimeUnixNano: UnixNanoTimestampSchema,\n attributes,\n events: z.array(TraceSpanEventEntrySchema).optional(),\n status: z\n .object({\n code: z.enum(['OK', 'ERROR', 'UNSET']),\n message: z.string().optional(),\n })\n .strict()\n .optional(),\n 'tangle.runId': nonEmptyString.optional(),\n 'tangle.generation': nonNegativeInteger.optional(),\n 'tangle.cellId': nonEmptyString.optional(),\n 'tangle.scenarioId': nonEmptyString.optional(),\n })\n .strict()\n .refine((span) => BigInt(span.endTimeUnixNano) >= BigInt(span.startTimeUnixNano), {\n path: ['endTimeUnixNano'],\n message: 'endTimeUnixNano must be greater than or equal to startTimeUnixNano',\n })\n\nexport const IngestEvalRunsEnvelopeSchema = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n events: z.array(z.unknown()),\n })\n .strict()\n\nexport const IngestTracesEnvelopeSchema = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n spans: z.array(z.unknown()),\n })\n .strict()\n\nexport const IngestEvalRunsRequestSchema: z.ZodType<IngestEvalRunsRequest> = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n events: z.array(EvalRunEventSchema),\n })\n .strict()\n\nexport const IngestTracesRequestSchema: z.ZodType<IngestTracesRequest> = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n spans: z.array(TraceSpanEventSchema),\n })\n .strict()\n\nexport const IngestResponseSchema: z.ZodType<IngestResponse> = z\n .object({\n accepted: nonNegativeInteger,\n rejected: z.array(\n z\n .object({\n index: nonNegativeInteger,\n reason: nonEmptyString,\n })\n .strict(),\n ),\n })\n .strict()\n","/**\n * # Hosted-tier ingest client.\n *\n * Ships eval-run events + trace spans to any orchestrator (ours, a\n * partner's self-hosted one, or a future open implementation) that\n * speaks the wire format in `./types.ts`.\n *\n * Three modes:\n * - **Ours:** point at `https://orchestrator.tangle.tools` (the host root —\n * the client appends the versioned `/v1/ingest/...` path itself; a trailing\n * `/v1` on the endpoint is tolerated and normalized away). We handle ingest\n * + storage + dashboard.\n * - **Self-hosted:** point at whatever URL runs the reference receiver\n * from `examples/hosted-ingest-server/`.\n * - **Off (default):** when `hostedTenant` is unset, nothing is sent.\n * Everything stays local.\n */\n\nimport {\n IngestEvalRunsRequestSchema,\n IngestResponseSchema,\n IngestTracesRequestSchema,\n} from './schemas'\nimport {\n type EvalRunEvent,\n HOSTED_WIRE_VERSION,\n type HostedWireVersion,\n type IngestEvalRunsRequest,\n type IngestResponse,\n type IngestTracesRequest,\n type TraceSpanEvent,\n} from './types'\n\nexport interface HostedTenant {\n /** Orchestrator endpoint base URL (no trailing slash). Required. */\n endpoint: string\n /** Bearer token issued by the orchestrator. Required. */\n apiKey: string\n /** Tenant id — the orchestrator's primary key for this consumer. Required. */\n tenantId: string\n /** Optional `fetch` override (auth wrappers, custom agent, test mocks). */\n fetchImpl?: typeof fetch\n /** Per-call timeout in ms. Default 30s. */\n timeoutMs?: number\n /** Retries on 5xx / network errors. Default 2. */\n retries?: number\n}\n\nexport interface HostedClient {\n ingestEvalRun(event: EvalRunEvent, idempotencyKey?: string): Promise<IngestResponse>\n ingestEvalRuns(events: EvalRunEvent[], idempotencyKey?: string): Promise<IngestResponse>\n ingestTraces(spans: TraceSpanEvent[], idempotencyKey?: string): Promise<IngestResponse>\n readonly tenant: HostedTenant\n readonly wireVersion: HostedWireVersion\n}\n\ninterface RequestOptions {\n idempotencyKey?: string\n signal?: AbortSignal\n}\n\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction normalizeHostedBase(endpoint: string): string {\n return endpoint.trim().replace(/\\/+$/, '').replace(/\\/v1$/, '')\n}\n\nfunction resolveIdempotencyKey(key: string | undefined): string {\n const resolved = key ?? globalThis.crypto.randomUUID()\n if (resolved.trim().length === 0) throw new Error('idempotency key must not be blank')\n if (resolved.length > MAX_IDEMPOTENCY_KEY_LENGTH) {\n throw new Error(`idempotency key must be at most ${MAX_IDEMPOTENCY_KEY_LENGTH} characters`)\n }\n return resolved\n}\n\nfunction responseValidationReason(error: {\n issues: Array<{ path: PropertyKey[]; message: string }>\n}) {\n return error.issues\n .map(\n (issue) =>\n `${issue.path.length > 0 ? issue.path.map(String).join('.') : 'value'}: ${issue.message}`,\n )\n .join('; ')\n}\n\nasync function post<TReq>(\n tenant: HostedTenant,\n path: string,\n body: TReq,\n opts: RequestOptions = {},\n): Promise<IngestResponse> {\n const timeoutMs = tenant.timeoutMs ?? 30_000\n const maxRetries = tenant.retries ?? 2\n const f: typeof fetch = tenant.fetchImpl ?? ((...args) => fetch(...args))\n const base = normalizeHostedBase(tenant.endpoint)\n const url = `${base}${path}`\n const idempotencyKey = resolveIdempotencyKey(opts.idempotencyKey)\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n authorization: `Bearer ${tenant.apiKey}`,\n 'x-tangle-tenant-id': tenant.tenantId,\n 'x-tangle-wire-version': HOSTED_WIRE_VERSION,\n 'idempotency-key': idempotencyKey,\n }\n\n let lastError: unknown\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const ourTimeout = AbortSignal.timeout(timeoutMs)\n const combinedSignal = opts.signal ? AbortSignal.any([opts.signal, ourTimeout]) : ourTimeout\n let res: Response\n try {\n res = await f(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: combinedSignal,\n })\n } catch (err) {\n if (opts.signal?.aborted) throw err\n lastError = err\n if (attempt === maxRetries) throw err\n await sleep(2 ** attempt * 200 + Math.random() * 200)\n continue\n }\n\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n const error = new Error(`hosted ingest ${url} failed (${res.status}): ${text.slice(0, 500)}`)\n const retryable = res.status >= 500 || res.status === 408 || res.status === 429\n if (!retryable || attempt === maxRetries) throw error\n lastError = error\n await sleep(2 ** attempt * 200 + Math.random() * 200)\n continue\n }\n\n let rawResponse: unknown\n try {\n rawResponse = await res.json()\n } catch (error) {\n throw new Error(`hosted ingest ${url} returned invalid JSON`, { cause: error })\n }\n const parsed = IngestResponseSchema.safeParse(rawResponse)\n if (!parsed.success) {\n throw new Error(\n `hosted ingest ${url} returned an invalid response: ${responseValidationReason(parsed.error)}`,\n )\n }\n return parsed.data\n }\n throw lastError ?? new Error('hosted ingest exhausted retries')\n}\n\nexport function createHostedClient(tenant: HostedTenant): HostedClient {\n if (normalizeHostedBase(tenant.endpoint).length === 0) throw new Error('endpoint is required')\n if (tenant.apiKey.trim().length === 0) throw new Error('apiKey is required')\n if (tenant.tenantId.trim().length === 0) throw new Error('tenantId is required')\n if (\n tenant.timeoutMs !== undefined &&\n (!Number.isFinite(tenant.timeoutMs) || tenant.timeoutMs <= 0)\n ) {\n throw new Error('timeoutMs must be greater than 0')\n }\n if (tenant.retries !== undefined && (!Number.isInteger(tenant.retries) || tenant.retries < 0)) {\n throw new Error('retries must be a non-negative integer')\n }\n\n return {\n tenant,\n wireVersion: HOSTED_WIRE_VERSION,\n\n async ingestEvalRun(event, idempotencyKey) {\n return this.ingestEvalRuns([event], idempotencyKey)\n },\n\n async ingestEvalRuns(events, idempotencyKey) {\n const body: IngestEvalRunsRequest = IngestEvalRunsRequestSchema.parse({\n wireVersion: HOSTED_WIRE_VERSION,\n events,\n })\n return post<IngestEvalRunsRequest>(tenant, '/v1/ingest/eval-runs', body, {\n idempotencyKey,\n })\n },\n\n async ingestTraces(spans, idempotencyKey) {\n const body: IngestTracesRequest = IngestTracesRequestSchema.parse({\n wireVersion: HOSTED_WIRE_VERSION,\n spans,\n })\n return post<IngestTracesRequest>(tenant, '/v1/ingest/traces', body, {\n idempotencyKey,\n })\n },\n }\n}\n\n/**\n * Build a `HostedClient` from environment, or `undefined` when ingest is not\n * configured — the canonical, fail-soft wiring every product uses so eval-run +\n * trace provenance lands in the Intelligence dashboard with ONE call:\n *\n * const hosted = hostedClientFromEnv()\n * // ...run the loop...\n * await emitLoopProvenance({ ..., hostedClient: hosted }) // no-op if undefined\n *\n * Returns `undefined` (NOT an error) when any of endpoint / apiKey / tenantId is\n * missing — so a product wires the ship call unconditionally and it stays a\n * no-op until the env is set. Env precedence:\n * - endpoint: `TANGLE_INGEST_URL` → `TANGLE_ORCHESTRATOR_URL`\n * - apiKey: `TANGLE_INGEST_API_KEY` → `TANGLE_API_KEY`\n * - tenantId: `TANGLE_TENANT_ID`\n * A trailing slash on the endpoint is stripped. Pass `overrides` to supply any\n * field directly (e.g. a fixed `tenantId` per product) — overrides win over env.\n */\n/**\n * Build a {@link HostedTenant} config from env — the input `selfImprove`'s\n * `hostedTenant` and `emitLoopProvenance` take. Same env precedence + overrides\n * as {@link hostedClientFromEnv}; returns `undefined` (not an error) when any of\n * endpoint / apiKey / tenantId is missing, so a product wires\n * `hostedTenant: hostedTenantFromEnv({ tenantId: 'my-agent' })` unconditionally\n * and it stays off until the env is set.\n */\nexport function hostedTenantFromEnv(\n overrides: Partial<HostedTenant> & { env?: Record<string, string | undefined> } = {},\n): HostedTenant | undefined {\n const env = overrides.env ?? process.env\n const endpoint = (\n overrides.endpoint ??\n env.TANGLE_INGEST_URL ??\n env.TANGLE_ORCHESTRATOR_URL\n )?.trim()\n const apiKey = (overrides.apiKey ?? env.TANGLE_INGEST_API_KEY ?? env.TANGLE_API_KEY)?.trim()\n const tenantId = (overrides.tenantId ?? env.TANGLE_TENANT_ID)?.trim()\n if (!endpoint || !apiKey || !tenantId) return undefined\n const tenant: HostedTenant = { endpoint: endpoint.replace(/\\/+$/, ''), apiKey, tenantId }\n if (overrides.fetchImpl) tenant.fetchImpl = overrides.fetchImpl\n if (overrides.timeoutMs !== undefined) tenant.timeoutMs = overrides.timeoutMs\n if (overrides.retries !== undefined) tenant.retries = overrides.retries\n return tenant\n}\n\nexport function hostedClientFromEnv(\n overrides: Partial<HostedTenant> & { env?: Record<string, string | undefined> } = {},\n): HostedClient | undefined {\n const tenant = hostedTenantFromEnv(overrides)\n return tenant ? createHostedClient(tenant) : undefined\n}\n"],"mappings":";;;AAgCA,MAAa,sBAAsB;;;AChBnC,MAAM,eAAe,EAAE,OAAO,CAAC,CAAC,OAAO;AACvC,MAAM,oBAAoB,aAAa,YAAY;AACnD,MAAM,qBAAqB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,YAAY;AACxD,MAAM,iBAAiB,EACpB,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,QAAQ,UAAU,MAAM,KAAK,CAAC,CAAC,SAAS,GAAG,mBAAmB;AACjE,MAAM,iBAAiB,EAAE,MAAM;CAAC,EAAE,OAAO;CAAG;CAAc,EAAE,QAAQ;AAAC,CAAC;AACtE,MAAM,aAAa,EAAE,OAAO,EAAE,OAAO,GAAG,cAAc;AACtD,MAAM,qBAAqB,EAAE,QAC1B,UAAU,OAAO,UAAU,YAAY,gBAAgB,SAAS,KAAqB,GACtF,mBAAmB,gBAAgB,KAAK,IAAI,GAC9C;AACA,MAAM,aAAa;AAEnB,MAAa,0BAAwD,EAClE,OAAO,CAAC,CACR,MAAM,qBAAqB,6CAA6C,CAAC,CACzE,QAAQ,UAAU,OAAO,KAAK,KAAK,YAAY,wCAAwC;AAE1F,MAAM,4BAA4B,EAC/B,OAAO;CACN,IAAI;CACJ,IAAI;CACJ,OAAO;AACT,CAAC,CAAC,CACD,OAAO;AAEV,MAAM,2BAA2B,EAC9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CAAC;EACH;EAEA,MAAM,aAAa,OAAO,gBAAgB;GAKxC,OAAO,KAA0B,QAAQ,qBAJP,0BAA0B,MAAM;IAChE,aAAa;IACb;GACF,CACiE,GAAG,EAClE,eACF,CAAC;EACH;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,oBACd,YAAkF,CAAC,GACzD;CAC1B,MAAM,MAAM,UAAU,OAAO,QAAQ;CACrC,MAAM,YACJ,UAAU,YACV,IAAI,qBACJ,IAAI,wBAAA,EACH,KAAK;CACR,MAAM,UAAU,UAAU,UAAU,IAAI,yBAAyB,IAAI,eAAA,EAAiB,KAAK;CAC3F,MAAM,YAAY,UAAU,YAAY,IAAI,iBAAA,EAAmB,KAAK;CACpE,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,UAAU,OAAO,KAAA;CAC9C,MAAM,SAAuB;EAAE,UAAU,SAAS,QAAQ,QAAQ,EAAE;EAAG;EAAQ;CAAS;CACxF,IAAI,UAAU,WAAW,OAAO,YAAY,UAAU;CACtD,IAAI,UAAU,cAAc,KAAA,GAAW,OAAO,YAAY,UAAU;CACpE,IAAI,UAAU,YAAY,KAAA,GAAW,OAAO,UAAU,UAAU;CAChE,OAAO;AACT;AAEA,SAAgB,oBACd,YAAkF,CAAC,GACzD;CAC1B,MAAM,SAAS,oBAAoB,SAAS;CAC5C,OAAO,SAAS,mBAAmB,MAAM,IAAI,KAAA;AAC/C"}
1
+ {"version":3,"file":"client-BlLY6o2w.js","names":[],"sources":["../src/hosted/types.ts","../src/hosted/schemas.ts","../src/hosted/client.ts"],"sourcesContent":["/**\n * # Hosted-tier wire format — the schema that EVERY orchestrator (ours,\n * a partner's self-hosted one, a future open implementation) must accept.\n *\n * This package implements exactly one wire version. Servers reject every\n * other version instead of translating old payloads.\n *\n * The wire format is two event streams in one transport:\n *\n * 1. **Eval-run events** (`POST /v1/ingest/eval-runs`). Posted when a\n * campaign / improvement-loop completes (or per-generation if\n * streaming). Carries the structured result + per-cell scores +\n * surface diffs the orchestrator stores for the dashboard.\n *\n * 2. **Trace spans** (`POST /v1/ingest/traces`). Standard OTLP-shaped\n * spans with a few additional attributes so the orchestrator can\n * pivot from eval-run → underlying execution. Compatible with any\n * OTel collector.\n *\n * Both endpoints are authenticated with a bearer token + a tenant id\n * header. Tenants isolate everything downstream of ingest; no tenant\n * ever sees another tenant's data.\n */\n\nimport type { GateDecision, MutableSurface } from '../campaign/types'\nimport type { InsightReport } from '../contract/insight-report'\nimport type { RunTerminalOutcome } from '../run-record'\n\n// re-export so wire-format consumers can import the optional payload type\n// from `@tangle-network/agent-eval/hosted` without reaching into /contract.\nexport type { InsightReport } from '../contract/insight-report'\n\nexport const HOSTED_WIRE_VERSION = '2026-07-24.v1' as const\nexport type HostedWireVersion = typeof HOSTED_WIRE_VERSION\n\n// ── Transport headers ───────────────────────────────────────────────\n\n/** Every ingest request carries these. */\nexport interface HostedIngestHeaders {\n /** Bearer token. The orchestrator validates against the tenant key. */\n authorization: `Bearer ${string}`\n /** Stable tenant id (the orchestrator-side primary key for the tenant). */\n 'x-tangle-tenant-id': string\n /** Wire-version pin so the server can reject incompatible payloads. */\n 'x-tangle-wire-version': HostedWireVersion\n /** Stable request key generated once and reused across retries. */\n 'idempotency-key': string\n}\n\n// ── Eval-run event ──────────────────────────────────────────────────\n\n/** Lifecycle stages of an eval-run as the substrate reports them. */\nexport type EvalRunStatus =\n | 'started'\n | 'baseline-complete'\n | 'generation-complete'\n | 'gate-decided'\n | 'finished'\n | 'errored'\n\nexport interface EvalRunCellScore {\n /** Stable scenario id from the consumer's scenario set. */\n scenarioId: string\n /** Repetition index when reps > 1; 0 for the default. */\n rep: number\n /** Composite score across successful judges, or null when unscored. */\n compositeMean: number | null\n /** Per-judge and per-dimension scores; failed or missing judges are absent. */\n dimensions: Record<string, Record<string, number>>\n /** Root execution result, kept separate from task quality. */\n terminalOutcome: RunTerminalOutcome\n /** Canonical execution-error count, or null when the producer did not measure it. */\n executionErrorCount: number | null\n /** Per-cell dispatch or judge error. Missing on success. */\n errorMessage?: string\n}\n\nexport interface EvalRunGenerationSnapshot {\n /** Generation index. 0 is baseline. */\n index: number\n /** Candidate surface fingerprint (stable hash) — pivot key into the\n * trace stream to fetch the underlying execution. */\n surfaceHash: string\n /** The candidate surface itself. May be omitted to avoid PII when the\n * consumer prefers not to ship verbatim prompts. */\n surface?: MutableSurface\n /** Per-cell scores for this generation. */\n cells: EvalRunCellScore[]\n /** Mean across scored cells, or null when no cell has a task-quality label. */\n compositeMean: number | null\n /** Total $ spent across this generation. */\n costUsd: number\n /** Wall-clock duration of this generation. */\n durationMs: number\n}\n\n/**\n * The top-level eval-run event. One ingest call per logical eval-run;\n * generations stream in incrementally via repeated calls with the same\n * `runId`. The orchestrator deduplicates by `(runId, generation.index)`.\n */\nexport interface EvalRunEvent {\n /** Stable run id (the substrate's `runId`). UUID or substrate-generated. */\n runId: string\n /** Where this run was happening — derived from `RunCampaignOptions.runDir`. */\n runDir: string\n /** ISO-8601 timestamp the substrate recorded the event. */\n timestamp: string\n /** Lifecycle stage this event represents. */\n status: EvalRunStatus\n /** Free-form consumer tags (env, branch, model id, etc.). Searchable. */\n labels: Record<string, string>\n /** Baseline campaign snapshot. Present when status >= baseline-complete. */\n baseline?: EvalRunGenerationSnapshot\n /** Per-generation snapshots. Streams in; orchestrator appends. */\n generations: EvalRunGenerationSnapshot[]\n /** Final gate decision. Present when status >= gate-decided. */\n gateDecision?: GateDecision\n /** Held-out lift = winner-on-holdout - baseline-on-holdout. */\n holdoutLift?: number\n /** Total $ spent across baseline + every generation. */\n totalCostUsd: number\n /** Total wall-clock duration. */\n totalDurationMs: number\n /** Error message if status === 'errored'. */\n errorMessage?: string\n /** Rigor packet emitted alongside the run — distributional summary,\n * paired-bootstrap lift CI, judge stats, inter-rater agreement,\n * contamination check, failure clusters (when an analyst is wired),\n * outcome correlation (when downstream signal is supplied), and the\n * recommendations the dashboard surfaces verbatim. */\n insightReport?: InsightReport\n}\n\n// ── Trace span event ────────────────────────────────────────────────\n\n/**\n * Canonical unsigned 64-bit integer encoded as a base-10 string.\n * JSON numbers cannot represent OTLP nanosecond timestamps exactly.\n */\nexport type UnixNanoTimestamp = string\n\n/**\n * OTel-shape span with a few additional attributes for eval-run pivoting.\n * Compatible with any OTLP collector — `name`, `traceId`, `spanId`,\n * `startTimeUnixNano`, `endTimeUnixNano`, `attributes` are stock OTel.\n */\nexport interface TraceSpanEvent {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n startTimeUnixNano: UnixNanoTimestamp\n endTimeUnixNano: UnixNanoTimestamp\n attributes: Record<string, string | number | boolean>\n events?: Array<{\n timeUnixNano: UnixNanoTimestamp\n name: string\n attributes?: Record<string, string | number | boolean>\n }>\n status?: { code: 'OK' | 'ERROR' | 'UNSET'; message?: string }\n /** Pivot back into the eval-run stream. */\n 'tangle.runId'?: string\n /** Pivot to the specific generation. */\n 'tangle.generation'?: number\n /** Pivot to the specific cell. */\n 'tangle.cellId'?: string\n /** Pivot to the specific scenario. */\n 'tangle.scenarioId'?: string\n}\n\n// ── Ingest request bodies ───────────────────────────────────────────\n\nexport interface IngestEvalRunsRequest {\n wireVersion: HostedWireVersion\n events: EvalRunEvent[]\n}\n\nexport interface IngestTracesRequest {\n wireVersion: HostedWireVersion\n spans: TraceSpanEvent[]\n}\n\nexport interface IngestResponse {\n /** Accepted events / spans count. */\n accepted: number\n /** Rejected events with reasons (validation failures, dup idempotency key, etc.). */\n rejected: Array<{ index: number; reason: string }>\n}\n","import { z } from 'zod'\nimport type { MutableSurface } from '../campaign/types'\nimport type { InsightReport } from '../contract/insight-report'\nimport { FAILURE_CLASSES, type FailureClass } from '../trace/schema'\nimport type {\n EvalRunCellScore,\n EvalRunEvent,\n EvalRunGenerationSnapshot,\n IngestEvalRunsRequest,\n IngestResponse,\n IngestTracesRequest,\n TraceSpanEvent,\n UnixNanoTimestamp,\n} from './types'\nimport { HOSTED_WIRE_VERSION } from './types'\n\nconst finiteNumber = z.number().finite()\nconst nonNegativeNumber = finiteNumber.nonnegative()\nconst nonNegativeInteger = z.number().int().nonnegative()\nconst nonEmptyString = z\n .string()\n .min(1)\n .refine((value) => value.trim().length > 0, 'must not be blank')\nconst attributeValue = z.union([z.string(), finiteNumber, z.boolean()])\nconst attributes = z.record(z.string(), attributeValue)\nconst FailureClassSchema = z.custom<FailureClass>(\n (value) => typeof value === 'string' && FAILURE_CLASSES.includes(value as FailureClass),\n `expected one of ${FAILURE_CLASSES.join(', ')}`,\n)\nconst UINT64_MAX = 18_446_744_073_709_551_615n\n\nexport const UnixNanoTimestampSchema: z.ZodType<UnixNanoTimestamp> = z\n .string()\n .regex(/^(0|[1-9][0-9]*)$/, 'expected an unsigned base-10 integer string')\n .refine((value) => BigInt(value) <= UINT64_MAX, 'must fit in an unsigned 64-bit integer')\n\nconst GainDistributionBinSchema = z\n .object({\n lo: finiteNumber,\n hi: finiteNumber,\n count: nonNegativeInteger,\n })\n .strict()\n\nconst ScalarDistributionSchema = z\n .object({\n n: nonNegativeInteger,\n mean: finiteNumber.nullable(),\n p50: finiteNumber.nullable(),\n p95: finiteNumber.nullable(),\n stddev: nonNegativeNumber.nullable(),\n min: finiteNumber.nullable(),\n max: finiteNumber.nullable(),\n histogram: z.array(GainDistributionBinSchema),\n tailRuns: z\n .array(\n z\n .object({\n runId: nonEmptyString,\n score: finiteNumber,\n })\n .strict(),\n )\n .optional(),\n })\n .strict()\n .superRefine((distribution, ctx) => {\n const values = [\n distribution.mean,\n distribution.p50,\n distribution.p95,\n distribution.stddev,\n distribution.min,\n distribution.max,\n ]\n if (distribution.n === 0 && values.some((value) => value !== null)) {\n ctx.addIssue({\n code: 'custom',\n message: 'distribution values must be null when n is 0',\n })\n }\n if (distribution.n > 0 && values.some((value) => value === null)) {\n ctx.addIssue({\n code: 'custom',\n message: 'distribution values must be numbers when n is greater than 0',\n })\n }\n if (\n distribution.min !== null &&\n distribution.max !== null &&\n distribution.min > distribution.max\n ) {\n ctx.addIssue({ code: 'custom', path: ['min'], message: 'min must not exceed max' })\n }\n })\n\nconst TokenUsageInsightSchema = z\n .object({\n input: ScalarDistributionSchema,\n output: ScalarDistributionSchema,\n reasoning: ScalarDistributionSchema,\n cached: ScalarDistributionSchema,\n cacheWrite: ScalarDistributionSchema,\n totals: z\n .object({\n input: nonNegativeNumber,\n output: nonNegativeNumber,\n reasoning: nonNegativeNumber,\n cached: nonNegativeNumber,\n cacheWrite: nonNegativeNumber,\n })\n .strict(),\n })\n .strict()\n\nconst ExecutionErrorOutcomeCellSchema = z\n .object({\n withErrors: nonNegativeInteger,\n withoutErrors: nonNegativeInteger,\n unreported: nonNegativeInteger,\n })\n .strict()\n\nconst ExecutionInsightSchema = z\n .object({\n durationMs: ScalarDistributionSchema,\n queueMs: ScalarDistributionSchema,\n tokenUsage: TokenUsageInsightSchema,\n aggregateUsage: z\n .object({\n runs: nonNegativeInteger,\n tokenUsage: TokenUsageInsightSchema,\n costUsd: ScalarDistributionSchema,\n totalCostUsd: nonNegativeNumber,\n })\n .strict(),\n models: z.array(\n z\n .object({\n model: nonEmptyString,\n runs: nonNegativeInteger,\n })\n .strict(),\n ),\n modelCalls: z\n .object({\n runs: nonNegativeInteger,\n events: nonNegativeInteger,\n reportingRuns: nonNegativeInteger,\n })\n .strict(),\n executionErrors: z\n .object({\n runs: nonNegativeInteger,\n fraction: finiteNumber.min(0).max(1).nullable(),\n events: nonNegativeInteger,\n reportingRuns: nonNegativeInteger,\n errorSpanEvents: nonNegativeInteger,\n errorSpanReportingRuns: nonNegativeInteger,\n byTerminalOutcome: z\n .object({\n succeeded: ExecutionErrorOutcomeCellSchema,\n failed: ExecutionErrorOutcomeCellSchema,\n cancelled: ExecutionErrorOutcomeCellSchema,\n incomplete: ExecutionErrorOutcomeCellSchema,\n unknown: ExecutionErrorOutcomeCellSchema,\n })\n .strict(),\n })\n .strict(),\n terminalOutcomes: z\n .object({\n succeeded: nonNegativeInteger,\n failed: nonNegativeInteger,\n cancelled: nonNegativeInteger,\n incomplete: nonNegativeInteger,\n unknown: nonNegativeInteger,\n })\n .strict(),\n })\n .strict()\n\nconst CostProvenanceSummarySchema = z\n .object({\n observed: z\n .object({\n n: nonNegativeInteger,\n totalUsd: nonNegativeNumber,\n })\n .strict(),\n estimated: z\n .object({\n n: nonNegativeInteger,\n totalUsd: nonNegativeNumber,\n })\n .strict(),\n uncaptured: z.object({ n: nonNegativeInteger }).strict(),\n knownFraction: finiteNumber.min(0).max(1),\n })\n .strict()\n\nconst ParetoFigureSpecSchema = z\n .object({\n kind: z.literal('pareto-cost-quality'),\n split: z.enum(['search', 'holdout']),\n points: z.array(\n z\n .object({\n candidateId: nonEmptyString,\n cost: nonNegativeNumber,\n quality: finiteNumber,\n n: nonNegativeInteger,\n onFrontier: z.boolean(),\n gate: z.enum(['promote', 'reject']).optional(),\n })\n .strict(),\n ),\n axes: z.object({ x: z.literal('costUsd'), y: z.literal('score') }).strict(),\n })\n .strict()\n\nconst ContinuousAgreementSchema = z\n .object({\n weightedKappa: finiteNumber,\n icc: finiteNumber,\n pearson: finiteNumber,\n spearman: finiteNumber,\n ci: z\n .object({\n icc: z.tuple([finiteNumber, finiteNumber]),\n weightedKappa: z.tuple([finiteNumber, finiteNumber]),\n })\n .strict(),\n n: nonNegativeInteger,\n raters: nonNegativeInteger,\n })\n .strict()\n\nconst JudgeInsightSchema = z\n .object({\n n: nonNegativeInteger,\n meanScore: finiteNumber,\n calibration: ContinuousAgreementSchema.optional(),\n positionalBias: finiteNumber.optional(),\n selfPreference: finiteNumber.optional(),\n verbosityBias: finiteNumber.optional(),\n })\n .strict()\n\nconst InterRaterInsightSchema = z\n .object({\n raters: nonNegativeInteger,\n jointlyRated: nonNegativeInteger,\n kappa: finiteNumber,\n icc: finiteNumber,\n pearson: finiteNumber,\n spearman: finiteNumber,\n perPair: z.record(z.string(), finiteNumber),\n disagreementCases: z.array(\n z\n .object({\n runId: nonEmptyString,\n ratings: z.array(\n z\n .object({\n rater: nonEmptyString,\n score: finiteNumber,\n })\n .strict(),\n ),\n range: nonNegativeNumber,\n })\n .strict(),\n ),\n })\n .strict()\n\nconst LiftInsightSchema = z\n .object({\n baselineMean: finiteNumber,\n candidateMean: finiteNumber,\n delta: finiteNumber,\n ci95: z.tuple([finiteNumber, finiteNumber]),\n pValue: finiteNumber.min(0).max(1).nullable(),\n n: nonNegativeInteger,\n minimumRequired: z.number().int().positive(),\n decisionEligible: z.boolean(),\n unpairedBaseline: nonNegativeInteger,\n unpairedCandidate: nonNegativeInteger,\n cohensD: finiteNumber.nullable(),\n mde: nonNegativeNumber,\n requiredN: nonNegativeInteger.nullable(),\n })\n .strict()\n\nconst FailureClusterInsightSchema = z\n .object({\n clusters: z.array(\n z\n .object({\n id: nonEmptyString,\n name: nonEmptyString,\n share: finiteNumber.min(0).max(1),\n exemplars: z.array(nonEmptyString).max(5),\n suggestedFix: nonEmptyString.optional(),\n })\n .strict(),\n ),\n totalFailures: nonNegativeInteger,\n })\n .strict()\n\nconst ContaminationInsightSchema = z\n .object({\n leaks: nonNegativeInteger,\n holdoutAuditPassed: z.boolean(),\n details: z\n .array(\n z\n .object({\n runId: nonEmptyString,\n canary: nonEmptyString,\n matched: nonEmptyString,\n })\n .strict(),\n )\n .optional(),\n })\n .strict()\n\nconst OutcomeCorrelationInsightSchema = z\n .object({\n metric: nonEmptyString,\n n: nonNegativeInteger,\n pearson: finiteNumber,\n spearman: finiteNumber,\n rewardModel: z\n .object({\n intercept: finiteNumber,\n slope: finiteNumber,\n r2: finiteNumber,\n })\n .strict()\n .optional(),\n })\n .strict()\n\nconst ReleaseSummarySchema = z\n .object({\n status: z.enum(['pass', 'warn', 'fail']),\n axes: z.array(\n z\n .object({\n name: z.enum(['quality-lift', 'contamination', 'composite-distribution']),\n status: z.enum(['pass', 'warn', 'fail', 'not_evaluated']),\n detail: nonEmptyString,\n })\n .strict(),\n ),\n issues: z.array(z.string()),\n })\n .strict()\n\nconst MetricDeltaBaseSchema = z\n .object({\n current: finiteNumber,\n baseline: finiteNumber,\n delta: finiteNumber,\n baselineN: nonNegativeInteger,\n currentN: nonNegativeInteger,\n })\n .strict()\n\nconst MetricDeltaSchema = z.discriminatedUnion('status', [\n MetricDeltaBaseSchema.extend({\n status: z.literal('ok'),\n ci95: z.tuple([finiteNumber, finiteNumber]),\n pValue: finiteNumber.min(0).max(1),\n cohensD: finiteNumber,\n significant: z.boolean(),\n }),\n MetricDeltaBaseSchema.extend({\n status: z.enum(['insufficient-sample', 'zero-variance']),\n ci95: z.null(),\n pValue: z.null(),\n cohensD: z.null(),\n significant: z.literal(false),\n }),\n])\n\nconst PriorPeriodComparisonSchema = z\n .object({\n baselineN: nonNegativeInteger,\n currentN: nonNegativeInteger,\n windowLabel: nonEmptyString.optional(),\n metrics: z.record(z.string(), MetricDeltaSchema),\n regressedMetrics: z.array(nonEmptyString),\n improvedMetrics: z.array(nonEmptyString),\n inconclusiveMetrics: z.array(nonEmptyString),\n })\n .strict()\n\nconst RecommendationSchema = z\n .object({\n priority: z.enum(['critical', 'high', 'medium', 'low']),\n kind: z.enum(['ship', 'hold', 'investigate', 'fix', 'recalibrate', 'expand-corpus']),\n title: nonEmptyString,\n detail: nonEmptyString,\n evidencePath: nonEmptyString.optional(),\n })\n .strict()\n\nexport const InsightReportSchema: z.ZodType<InsightReport> = z\n .object({\n n: nonNegativeInteger,\n execution: ExecutionInsightSchema,\n composite: ScalarDistributionSchema,\n perDimension: z.record(z.string(), ScalarDistributionSchema),\n costQuality: z\n .object({\n cost: ScalarDistributionSchema,\n pareto: ParetoFigureSpecSchema,\n provenance: CostProvenanceSummarySchema.optional(),\n degraded: z\n .object({\n cost: nonEmptyString.optional(),\n pareto: nonEmptyString.optional(),\n })\n .strict()\n .optional(),\n })\n .strict(),\n judges: z.record(z.string(), JudgeInsightSchema),\n interRater: InterRaterInsightSchema.optional(),\n lift: LiftInsightSchema.optional(),\n failureClusters: FailureClusterInsightSchema.optional(),\n contamination: ContaminationInsightSchema.optional(),\n outcomeCorrelation: OutcomeCorrelationInsightSchema.optional(),\n release: ReleaseSummarySchema,\n priorPeriodComparison: PriorPeriodComparisonSchema.optional(),\n failureClasses: z\n .array(\n z\n .object({\n failureClass: FailureClassSchema,\n count: nonNegativeInteger,\n share: finiteNumber.min(0).max(1),\n })\n .strict(),\n )\n .optional(),\n recommendations: z.array(RecommendationSchema),\n })\n .strict()\n\nconst sha256Digest = z.custom<`sha256:${string}`>(\n (value) => typeof value === 'string' && /^sha256:[0-9a-f]{64}$/.test(value),\n 'expected sha256:<64 lowercase hex characters>',\n)\n\nconst MutableSurfaceSchema: z.ZodType<MutableSurface> = z.union([\n z.string(),\n z\n .object({\n kind: z.literal('components'),\n components: z.record(z.string(), z.string()),\n })\n .strict(),\n z\n .object({\n kind: z.literal('code'),\n worktreeRef: nonEmptyString,\n baseRef: nonEmptyString,\n baseCommit: nonEmptyString,\n baseTree: nonEmptyString,\n candidateCommit: nonEmptyString,\n candidateTree: nonEmptyString,\n patch: z\n .object({\n format: z.literal('git-diff-binary'),\n sha256: sha256Digest,\n byteLength: nonNegativeInteger,\n })\n .strict(),\n summary: z.string().optional(),\n })\n .strict(),\n])\n\nconst RunTerminalOutcomeSchema = z.enum([\n 'succeeded',\n 'failed',\n 'cancelled',\n 'incomplete',\n 'unknown',\n])\n\nconst EvalRunCellScoreSchema: z.ZodType<EvalRunCellScore> = z\n .object({\n scenarioId: nonEmptyString,\n rep: nonNegativeInteger,\n compositeMean: finiteNumber.nullable(),\n dimensions: z.record(z.string(), z.record(z.string(), finiteNumber)),\n terminalOutcome: RunTerminalOutcomeSchema,\n executionErrorCount: nonNegativeInteger.nullable(),\n errorMessage: z.string().optional(),\n })\n .strict()\n\nconst EvalRunGenerationSnapshotSchema: z.ZodType<EvalRunGenerationSnapshot> = z\n .object({\n index: nonNegativeInteger,\n surfaceHash: nonEmptyString,\n surface: MutableSurfaceSchema.optional(),\n cells: z.array(EvalRunCellScoreSchema),\n compositeMean: finiteNumber.nullable(),\n costUsd: nonNegativeNumber,\n durationMs: nonNegativeNumber,\n })\n .strict()\n\nconst EvalRunStatusSchema = z.enum([\n 'started',\n 'baseline-complete',\n 'generation-complete',\n 'gate-decided',\n 'finished',\n 'errored',\n])\n\nconst GateDecisionSchema = z.enum([\n 'ship',\n 'hold',\n 'need_more_work',\n 'model_ceiling',\n 'arch_ceiling',\n])\n\nexport const EvalRunEventSchema: z.ZodType<EvalRunEvent> = z\n .object({\n runId: nonEmptyString,\n runDir: nonEmptyString,\n timestamp: z.string().datetime({ offset: true }),\n status: EvalRunStatusSchema,\n labels: z.record(z.string(), z.string()),\n baseline: EvalRunGenerationSnapshotSchema.optional(),\n generations: z.array(EvalRunGenerationSnapshotSchema),\n gateDecision: GateDecisionSchema.optional(),\n holdoutLift: finiteNumber.optional(),\n totalCostUsd: nonNegativeNumber,\n totalDurationMs: nonNegativeNumber,\n errorMessage: z.string().optional(),\n insightReport: InsightReportSchema.optional(),\n })\n .strict()\n .superRefine((event, ctx) => {\n if (event.baseline && event.baseline.index !== 0) {\n ctx.addIssue({\n code: 'custom',\n path: ['baseline', 'index'],\n message: 'baseline index must be 0',\n })\n }\n\n const seen = new Set<number>()\n for (let i = 0; i < event.generations.length; i++) {\n const index = event.generations[i]!.index\n if (seen.has(index)) {\n ctx.addIssue({\n code: 'custom',\n path: ['generations', i, 'index'],\n message: `duplicate generation index ${index}`,\n })\n }\n seen.add(index)\n }\n\n if (event.status === 'errored' && !event.errorMessage?.trim()) {\n ctx.addIssue({\n code: 'custom',\n path: ['errorMessage'],\n message: 'errorMessage is required when status is errored',\n })\n }\n })\n\nconst TraceSpanEventEntrySchema = z\n .object({\n timeUnixNano: UnixNanoTimestampSchema,\n name: nonEmptyString,\n attributes: attributes.optional(),\n })\n .strict()\n\nexport const TraceSpanEventSchema: z.ZodType<TraceSpanEvent> = z\n .object({\n traceId: nonEmptyString,\n spanId: nonEmptyString,\n parentSpanId: nonEmptyString.optional(),\n name: nonEmptyString,\n startTimeUnixNano: UnixNanoTimestampSchema,\n endTimeUnixNano: UnixNanoTimestampSchema,\n attributes,\n events: z.array(TraceSpanEventEntrySchema).optional(),\n status: z\n .object({\n code: z.enum(['OK', 'ERROR', 'UNSET']),\n message: z.string().optional(),\n })\n .strict()\n .optional(),\n 'tangle.runId': nonEmptyString.optional(),\n 'tangle.generation': nonNegativeInteger.optional(),\n 'tangle.cellId': nonEmptyString.optional(),\n 'tangle.scenarioId': nonEmptyString.optional(),\n })\n .strict()\n .refine((span) => BigInt(span.endTimeUnixNano) >= BigInt(span.startTimeUnixNano), {\n path: ['endTimeUnixNano'],\n message: 'endTimeUnixNano must be greater than or equal to startTimeUnixNano',\n })\n\nexport const IngestEvalRunsEnvelopeSchema = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n events: z.array(z.unknown()),\n })\n .strict()\n\nexport const IngestTracesEnvelopeSchema = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n spans: z.array(z.unknown()),\n })\n .strict()\n\nexport const IngestEvalRunsRequestSchema: z.ZodType<IngestEvalRunsRequest> = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n events: z.array(EvalRunEventSchema),\n })\n .strict()\n\nexport const IngestTracesRequestSchema: z.ZodType<IngestTracesRequest> = z\n .object({\n wireVersion: z.literal(HOSTED_WIRE_VERSION),\n spans: z.array(TraceSpanEventSchema),\n })\n .strict()\n\nexport const IngestResponseSchema: z.ZodType<IngestResponse> = z\n .object({\n accepted: nonNegativeInteger,\n rejected: z.array(\n z\n .object({\n index: nonNegativeInteger,\n reason: nonEmptyString,\n })\n .strict(),\n ),\n })\n .strict()\n","/**\n * # Hosted-tier ingest client.\n *\n * Ships eval-run events + trace spans to any orchestrator (ours, a\n * partner's self-hosted one, or a future open implementation) that\n * speaks the wire format in `./types.ts`.\n *\n * Three modes:\n * - **Ours:** point at `https://orchestrator.tangle.tools` (the host root —\n * the client appends the versioned `/v1/ingest/...` path itself; a trailing\n * `/v1` on the endpoint is tolerated and normalized away). We handle ingest\n * + storage + dashboard.\n * - **Self-hosted:** point at whatever URL runs the reference receiver\n * from `examples/hosted-ingest-server/`.\n * - **Off (default):** when `hostedTenant` is unset, nothing is sent.\n * Everything stays local.\n */\n\nimport {\n IngestEvalRunsRequestSchema,\n IngestResponseSchema,\n IngestTracesRequestSchema,\n} from './schemas'\nimport {\n type EvalRunEvent,\n HOSTED_WIRE_VERSION,\n type HostedWireVersion,\n type IngestEvalRunsRequest,\n type IngestResponse,\n type IngestTracesRequest,\n type TraceSpanEvent,\n} from './types'\n\nexport interface HostedTenant {\n /** Orchestrator endpoint base URL (no trailing slash). Required. */\n endpoint: string\n /** Bearer token issued by the orchestrator. Required. */\n apiKey: string\n /** Tenant id — the orchestrator's primary key for this consumer. Required. */\n tenantId: string\n /** Optional `fetch` override (auth wrappers, custom agent, test mocks). */\n fetchImpl?: typeof fetch\n /** Per-call timeout in ms. Default 30s. */\n timeoutMs?: number\n /** Retries on 5xx / network errors. Default 2. */\n retries?: number\n}\n\nexport interface HostedClient {\n ingestEvalRun(event: EvalRunEvent, idempotencyKey?: string): Promise<IngestResponse>\n ingestEvalRuns(events: EvalRunEvent[], idempotencyKey?: string): Promise<IngestResponse>\n ingestTraces(spans: TraceSpanEvent[], idempotencyKey?: string): Promise<IngestResponse>\n readonly tenant: HostedTenant\n readonly wireVersion: HostedWireVersion\n}\n\ninterface RequestOptions {\n idempotencyKey?: string\n signal?: AbortSignal\n}\n\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction normalizeHostedBase(endpoint: string): string {\n return endpoint.trim().replace(/\\/+$/, '').replace(/\\/v1$/, '')\n}\n\nfunction resolveIdempotencyKey(key: string | undefined): string {\n const resolved = key ?? globalThis.crypto.randomUUID()\n if (resolved.trim().length === 0) throw new Error('idempotency key must not be blank')\n if (resolved.length > MAX_IDEMPOTENCY_KEY_LENGTH) {\n throw new Error(`idempotency key must be at most ${MAX_IDEMPOTENCY_KEY_LENGTH} characters`)\n }\n return resolved\n}\n\nfunction responseValidationReason(error: {\n issues: Array<{ path: PropertyKey[]; message: string }>\n}) {\n return error.issues\n .map(\n (issue) =>\n `${issue.path.length > 0 ? issue.path.map(String).join('.') : 'value'}: ${issue.message}`,\n )\n .join('; ')\n}\n\nasync function post<TReq>(\n tenant: HostedTenant,\n path: string,\n body: TReq,\n opts: RequestOptions = {},\n): Promise<IngestResponse> {\n const timeoutMs = tenant.timeoutMs ?? 30_000\n const maxRetries = tenant.retries ?? 2\n const f: typeof fetch = tenant.fetchImpl ?? ((...args) => fetch(...args))\n const base = normalizeHostedBase(tenant.endpoint)\n const url = `${base}${path}`\n const idempotencyKey = resolveIdempotencyKey(opts.idempotencyKey)\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n authorization: `Bearer ${tenant.apiKey}`,\n 'x-tangle-tenant-id': tenant.tenantId,\n 'x-tangle-wire-version': HOSTED_WIRE_VERSION,\n 'idempotency-key': idempotencyKey,\n }\n\n let lastError: unknown\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const ourTimeout = AbortSignal.timeout(timeoutMs)\n const combinedSignal = opts.signal ? AbortSignal.any([opts.signal, ourTimeout]) : ourTimeout\n let res: Response\n try {\n res = await f(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n signal: combinedSignal,\n })\n } catch (err) {\n if (opts.signal?.aborted) throw err\n lastError = err\n if (attempt === maxRetries) throw err\n await sleep(2 ** attempt * 200 + Math.random() * 200)\n continue\n }\n\n if (!res.ok) {\n const text = await res.text().catch(() => '')\n const error = new Error(`hosted ingest ${url} failed (${res.status}): ${text.slice(0, 500)}`)\n const retryable = res.status >= 500 || res.status === 408 || res.status === 429\n if (!retryable || attempt === maxRetries) throw error\n lastError = error\n await sleep(2 ** attempt * 200 + Math.random() * 200)\n continue\n }\n\n let rawResponse: unknown\n try {\n rawResponse = await res.json()\n } catch (error) {\n throw new Error(`hosted ingest ${url} returned invalid JSON`, { cause: error })\n }\n const parsed = IngestResponseSchema.safeParse(rawResponse)\n if (!parsed.success) {\n throw new Error(\n `hosted ingest ${url} returned an invalid response: ${responseValidationReason(parsed.error)}`,\n )\n }\n return parsed.data\n }\n throw lastError ?? new Error('hosted ingest exhausted retries')\n}\n\nexport function createHostedClient(tenant: HostedTenant): HostedClient {\n if (normalizeHostedBase(tenant.endpoint).length === 0) throw new Error('endpoint is required')\n if (tenant.apiKey.trim().length === 0) throw new Error('apiKey is required')\n if (tenant.tenantId.trim().length === 0) throw new Error('tenantId is required')\n if (\n tenant.timeoutMs !== undefined &&\n (!Number.isFinite(tenant.timeoutMs) || tenant.timeoutMs <= 0)\n ) {\n throw new Error('timeoutMs must be greater than 0')\n }\n if (tenant.retries !== undefined && (!Number.isInteger(tenant.retries) || tenant.retries < 0)) {\n throw new Error('retries must be a non-negative integer')\n }\n\n return {\n tenant,\n wireVersion: HOSTED_WIRE_VERSION,\n\n async ingestEvalRun(event, idempotencyKey) {\n return this.ingestEvalRuns([event], idempotencyKey)\n },\n\n async ingestEvalRuns(events, idempotencyKey) {\n const body: IngestEvalRunsRequest = IngestEvalRunsRequestSchema.parse({\n wireVersion: HOSTED_WIRE_VERSION,\n events,\n })\n return post<IngestEvalRunsRequest>(tenant, '/v1/ingest/eval-runs', body, {\n idempotencyKey,\n })\n },\n\n async ingestTraces(spans, idempotencyKey) {\n const body: IngestTracesRequest = IngestTracesRequestSchema.parse({\n wireVersion: HOSTED_WIRE_VERSION,\n spans,\n })\n return post<IngestTracesRequest>(tenant, '/v1/ingest/traces', body, {\n idempotencyKey,\n })\n },\n }\n}\n\n/**\n * Build a `HostedClient` from environment, or `undefined` when ingest is not\n * configured — the canonical, fail-soft wiring every product uses so eval-run +\n * trace provenance lands in the Intelligence dashboard with ONE call:\n *\n * const hosted = hostedClientFromEnv()\n * // ...run the loop...\n * await emitLoopProvenance({ ..., hostedClient: hosted }) // no-op if undefined\n *\n * Returns `undefined` (NOT an error) when any of endpoint / apiKey / tenantId is\n * missing — so a product wires the ship call unconditionally and it stays a\n * no-op until the env is set. Env precedence:\n * - endpoint: `TANGLE_INGEST_URL` → `TANGLE_ORCHESTRATOR_URL`\n * - apiKey: `TANGLE_INGEST_API_KEY` → `TANGLE_API_KEY`\n * - tenantId: `TANGLE_TENANT_ID`\n * A trailing slash on the endpoint is stripped. Pass `overrides` to supply any\n * field directly (e.g. a fixed `tenantId` per product) — overrides win over env.\n */\n/**\n * Build a {@link HostedTenant} config from env — the input `selfImprove`'s\n * `hostedTenant` and `emitLoopProvenance` take. Same env precedence + overrides\n * as {@link hostedClientFromEnv}; returns `undefined` (not an error) when any of\n * endpoint / apiKey / tenantId is missing, so a product wires\n * `hostedTenant: hostedTenantFromEnv({ tenantId: 'my-agent' })` unconditionally\n * and it stays off until the env is set.\n */\nexport function hostedTenantFromEnv(\n overrides: Partial<HostedTenant> & { env?: Record<string, string | undefined> } = {},\n): HostedTenant | undefined {\n const env = overrides.env ?? process.env\n const endpoint = (\n overrides.endpoint ??\n env.TANGLE_INGEST_URL ??\n env.TANGLE_ORCHESTRATOR_URL\n )?.trim()\n const apiKey = (overrides.apiKey ?? env.TANGLE_INGEST_API_KEY ?? env.TANGLE_API_KEY)?.trim()\n const tenantId = (overrides.tenantId ?? env.TANGLE_TENANT_ID)?.trim()\n if (!endpoint || !apiKey || !tenantId) return undefined\n const tenant: HostedTenant = { endpoint: endpoint.replace(/\\/+$/, ''), apiKey, tenantId }\n if (overrides.fetchImpl) tenant.fetchImpl = overrides.fetchImpl\n if (overrides.timeoutMs !== undefined) tenant.timeoutMs = overrides.timeoutMs\n if (overrides.retries !== undefined) tenant.retries = overrides.retries\n return tenant\n}\n\nexport function hostedClientFromEnv(\n overrides: Partial<HostedTenant> & { env?: Record<string, string | undefined> } = {},\n): HostedClient | undefined {\n const tenant = hostedTenantFromEnv(overrides)\n return tenant ? createHostedClient(tenant) : undefined\n}\n"],"mappings":";;;AAgCA,MAAa,sBAAsB;;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AAY,IAAI,iBAAA,EAAmB,KAAK;CACpE,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,UAAU,OAAO,KAAA;CAC9C,MAAM,SAAuB;EAAE,UAAU,SAAS,QAAQ,QAAQ,EAAE;EAAG;EAAQ;CAAS;CACxF,IAAI,UAAU,WAAW,OAAO,YAAY,UAAU;CACtD,IAAI,UAAU,cAAc,KAAA,GAAW,OAAO,YAAY,UAAU;CACpE,IAAI,UAAU,YAAY,KAAA,GAAW,OAAO,UAAU,UAAU;CAChE,OAAO;AACT;AAEA,SAAgB,oBACd,YAAkF,CAAC,GACzD;CAC1B,MAAM,SAAS,oBAAoB,SAAS;CAC5C,OAAO,SAAS,mBAAmB,MAAM,IAAI,KAAA;AAC/C"}
@@ -1,6 +1,6 @@
1
- import { l as RunTerminalOutcome } from "./run-record-DQjRcYwA.js";
2
- import { _ as GateDecision, j as MutableSurface } from "./types-nokrtr7M.js";
3
- import { o as InsightReport } from "./insight-report-08F022xN.js";
1
+ import { l as RunTerminalOutcome } from "./run-record-DTv1MdjK.js";
2
+ import { _ as GateDecision, j as MutableSurface } from "./types-Ba5UQyVD.js";
3
+ import { o as InsightReport } from "./insight-report-DETqPc_A.js";
4
4
  //#region src/hosted/types.d.ts
5
5
  declare const HOSTED_WIRE_VERSION: '2026-07-24.v1';
6
6
  type HostedWireVersion = typeof HOSTED_WIRE_VERSION;
@@ -199,4 +199,4 @@ declare function hostedClientFromEnv(overrides?: Partial<HostedTenant> & {
199
199
  }): HostedClient | undefined;
200
200
  //#endregion
201
201
  export { UnixNanoTimestamp as _, hostedTenantFromEnv as a, EvalRunGenerationSnapshot as c, HostedIngestHeaders as d, HostedWireVersion as f, TraceSpanEvent as g, IngestTracesRequest as h, hostedClientFromEnv as i, EvalRunStatus as l, IngestResponse as m, HostedTenant as n, EvalRunCellScore as o, IngestEvalRunsRequest as p, createHostedClient as r, EvalRunEvent as s, HostedClient as t, HOSTED_WIRE_VERSION as u };
202
- //# sourceMappingURL=client-Df7wdslk.d.ts.map
202
+ //# sourceMappingURL=client-DlqdbM7n.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-Df7wdslk.d.ts","names":[],"sources":["../src/hosted/types.ts","../src/hosted/client.ts"],"mappings":";;;;cAgCa;KACD,2BAA2B;;UAKtB;;EAEf;;EAEA;;EAEA,yBAAyB;;EAEzB;;;KAMU;UAQK;;EAEf;;EAEA;;EAEA;;EAEA,YAAY,eAAe;;EAE3B,iBAAiB;;EAEjB;;EAEA;;UAGe;;EAEf;;;EAGA;;;EAGA,UAAU;;EAEV,OAAO;;EAEP;;EAEA;;EAEA;;;;;;;UAQe;;EAEf;;EAEA;;EAEA;;EAEA,QAAQ;;EAER,QAAQ;;EAER,WAAW;;EAEX,aAAa;;EAEb,eAAe;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;EAMA,gBAAgB;;;;;;KASN;;;;;;UAOK;EACf;EACA;EACA;EACA;EACA,mBAAmB;EACnB,iBAAiB;EACjB,YAAY;EACZ,SAAS;IACP,cAAc;IACd;IACA,aAAa;;EAEf;IAAW;IAAgC;;;EAE3C;;EAEA;;EAEA;;EAEA;;UAKe;EACf,aAAa;EACb,QAAQ;;UAGO;EACf,aAAa;EACb,OAAO;;UAGQ;;EAEf;;EAEA,UAAU;IAAQ;IAAe;;;;;UC1JlB;;EAEf;;EAEA;;EAEA;;EAEA,mBAAmB;;EAEnB;;EAEA;;UAGe;EACf,cAAc,OAAO,cAAc,0BAA0B,QAAQ;EACrE,eAAe,QAAQ,gBAAgB,0BAA0B,QAAQ;EACzE,aAAa,OAAO,kBAAkB,0BAA0B,QAAQ;WAC/D,QAAQ;WACR,aAAa;;iBAyGR,mBAAmB,QAAQ,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsE1C,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C;iBAiBa,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C"}
1
+ {"version":3,"file":"client-DlqdbM7n.d.ts","names":[],"sources":["../src/hosted/types.ts","../src/hosted/client.ts"],"mappings":";;;;cAgCa;KACD,2BAA2B;;UAKtB;;EAEf;;EAEA;;EAEA,yBAAyB;;EAEzB;;;KAMU;UAQK;;EAEf;;EAEA;;EAEA;;EAEA,YAAY,eAAe;;EAE3B,iBAAiB;;EAEjB;;EAEA;;UAGe;;EAEf;;;EAGA;;;EAGA,UAAU;;EAEV,OAAO;;EAEP;;EAEA;;EAEA;;;;;;;UAQe;;EAEf;;EAEA;;EAEA;;EAEA,QAAQ;;EAER,QAAQ;;EAER,WAAW;;EAEX,aAAa;;EAEb,eAAe;;EAEf;;EAEA;;EAEA;;EAEA;;;;;;EAMA,gBAAgB;;;;;;KASN;;;;;;UAOK;EACf;EACA;EACA;EACA;EACA,mBAAmB;EACnB,iBAAiB;EACjB,YAAY;EACZ,SAAS;IACP,cAAc;IACd;IACA,aAAa;;EAEf;IAAW;IAAgC;;;EAE3C;;EAEA;;EAEA;;EAEA;;UAKe;EACf,aAAa;EACb,QAAQ;;UAGO;EACf,aAAa;EACb,OAAO;;UAGQ;;EAEf;;EAEA,UAAU;IAAQ;IAAe;;;;;UC1JlB;;EAEf;;EAEA;;EAEA;;EAEA,mBAAmB;;EAEnB;;EAEA;;UAGe;EACf,cAAc,OAAO,cAAc,0BAA0B,QAAQ;EACrE,eAAe,QAAQ,gBAAgB,0BAA0B,QAAQ;EACzE,aAAa,OAAO,kBAAkB,0BAA0B,QAAQ;WAC/D,QAAQ;WACR,aAAa;;iBAyGR,mBAAmB,QAAQ,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsE1C,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C;iBAiBa,oBACd,YAAW,QAAQ;EAAkB,MAAM;IAC1C"}
@@ -1,15 +1,15 @@
1
1
  import { c as CostLedgerHandle } from "../cost-ledger-DbQdN3nO.js";
2
- import { _ as ProposalFinding, i as AnalystFinding, v as ProposalFindingOrigin, x as makeProposalFinding } from "../types-DMoNFDWi.js";
3
- import { An as runEval, B as OptimizationMethodResult, F as OptimizationMethod, Gn as CampaignStorage, I as OptimizationMethodComparison, Jn as inMemoryCampaignStorage, K as compareOptimizationMethods, L as OptimizationMethodInput, Mn as CampaignCellRetryPolicy, N as CompareOptimizationMethodsOptions, Nn as RunCampaignOptions, P as ComparisonCost, Pn as runCampaign, U as OptimizationPackageSource, W as OptimizationTokenUsage, at as transientDispatchFailure, ct as runImprovementLoop, et as LlmJudgeDimension, jn as CampaignCellFailureReceipt, kn as RunEvalOptions, nt as llmJudge, ot as RunImprovementLoopOptions, qn as fsCampaignStorage, st as RunImprovementLoopResult, tt as LlmJudgeOptions, z as OptimizationMethodProvenance } from "../provenance-Dp-vvyrU.js";
4
- import { _ as CreateChatClientOpts, p as ChatClient, x as createChatClient } from "../types-Bfk0uxRj.js";
5
- import { C as JudgeDimension, H as SurfaceProposer, M as OptimizerConfig, R as Scenario, S as JudgeConfig, V as SessionScript, _ as GateDecision, a as CampaignResult, b as GenerationRecord, c as CampaignTraceWriter, d as DispatchContext, f as DispatchFn, g as GateContribution, h as GateContext, i as CampaignCostMeter, j as MutableSurface, l as CodeSurface, m as GateCheckStatus, n as CampaignArtifactWriter, p as Gate, r as CampaignCellResult, t as CampaignAggregates, v as GateResult, w as JudgeScore, y as GenerationCandidate } from "../types-nokrtr7M.js";
6
- import { A as ReferenceEquivalenceJudgeInput, C as ExternalTextOptimizerContext, E as ExternalTextEvaluationResponse, F as runReferenceEquivalenceJudge, M as ReferenceEquivalenceJudgeResult, N as ReferenceEquivalenceScenario, O as REFERENCE_EQUIVALENCE_INPUT_LIMITS, P as createReferenceEquivalenceJudge, S as ExternalTextOptimizationMethodConfig, T as ExternalOptimizationExample, _ as GepaRunnerCommand, a as DefaultProductionRewardHackingOptions, b as OptimizerModelBudget, c as SkillOptOptimizationMethodConfig, d as skillOptOptimizationMethod, f as GepaAdaptiveEngineRun, g as GepaOptimizationRecipe, h as GepaOptimizationMethodConfig, i as DefaultProductionGateOptions, j as ReferenceEquivalenceJudgeOptions, k as REFERENCE_EQUIVALENCE_JUDGE_VERSION, l as SkillOptRunnerCommand, m as GepaEngineRun, n as heldOutGate, o as defaultProductionGate, p as GepaEngineOptions, r as DefaultProductionGateCheck, s as composeGate, t as HeldOutGateOptions, u as SkillOptTrainerConfig, v as gepaOptimizationMethod, w as ExternalTextOptimizerResult, x as externalTextOptimizationMethod, y as OpenAICompatibleOptimizerModel, z as campaignSplitDigest } from "../heldout-gate-JgNRDZwZ.js";
7
- import { a as ObjectiveSource, c as PromotionPolicy, d as paretoSignificanceGate, i as EvidenceVector, l as buildEvidenceVector, n as AxisVerdict, o as ParetoSignificanceGateOptions, r as BuildEvidenceVectorOptions, s as PromotionObjective, t as AxisEvidence, u as paretoPolicy } from "../promotion-policy-BBBcz5_3.js";
2
+ import { _ as ProposalFinding, i as AnalystFinding, v as ProposalFindingOrigin, x as makeProposalFinding } from "../types-DN2WdT5S.js";
3
+ import { S as createChatClient, _ as CreateChatClientOpts, p as ChatClient } from "../types-gvRsyJLh.js";
4
+ import { C as JudgeDimension, H as SurfaceProposer, M as OptimizerConfig, R as Scenario, S as JudgeConfig, V as SessionScript, _ as GateDecision, a as CampaignResult, b as GenerationRecord, c as CampaignTraceWriter, d as DispatchContext, f as DispatchFn, g as GateContribution, h as GateContext, i as CampaignCostMeter, j as MutableSurface, l as CodeSurface, m as GateCheckStatus, n as CampaignArtifactWriter, p as Gate, r as CampaignCellResult, t as CampaignAggregates, v as GateResult, w as JudgeScore, y as GenerationCandidate } from "../types-Ba5UQyVD.js";
5
+ import { A as ReferenceEquivalenceJudgeInput, C as ExternalTextOptimizerContext, E as ExternalTextEvaluationResponse, F as runReferenceEquivalenceJudge, M as ReferenceEquivalenceJudgeResult, N as ReferenceEquivalenceScenario, O as REFERENCE_EQUIVALENCE_INPUT_LIMITS, P as createReferenceEquivalenceJudge, S as ExternalTextOptimizationMethodConfig, T as ExternalOptimizationExample, _ as GepaRunnerCommand, a as DefaultProductionRewardHackingOptions, b as OptimizerModelBudget, c as SkillOptOptimizationMethodConfig, d as skillOptOptimizationMethod, f as GepaAdaptiveEngineRun, g as GepaOptimizationRecipe, h as GepaOptimizationMethodConfig, i as DefaultProductionGateOptions, j as ReferenceEquivalenceJudgeOptions, k as REFERENCE_EQUIVALENCE_JUDGE_VERSION, l as SkillOptRunnerCommand, m as GepaEngineRun, n as heldOutGate, o as defaultProductionGate, p as GepaEngineOptions, r as DefaultProductionGateCheck, s as composeGate, t as HeldOutGateOptions, u as SkillOptTrainerConfig, v as gepaOptimizationMethod, w as ExternalTextOptimizerResult, x as externalTextOptimizationMethod, y as OpenAICompatibleOptimizerModel, z as campaignSplitDigest } from "../heldout-gate-Df5hsqmm.js";
6
+ import { An as RunEvalOptions, B as OptimizationMethodResult, F as OptimizationMethod, Fn as runCampaign, I as OptimizationMethodComparison, Jn as fsCampaignStorage, K as compareOptimizationMethods, Kn as CampaignStorage, L as OptimizationMethodInput, Mn as CampaignCellFailureReceipt, N as CompareOptimizationMethodsOptions, Nn as CampaignCellRetryPolicy, P as ComparisonCost, Pn as RunCampaignOptions, U as OptimizationPackageSource, W as OptimizationTokenUsage, Yn as inMemoryCampaignStorage, ct as RunImprovementLoopResult, et as LlmJudgeDimension, jn as runEval, lt as runImprovementLoop, nt as llmJudge, ot as transientDispatchFailure, st as RunImprovementLoopOptions, tt as LlmJudgeOptions, z as OptimizationMethodProvenance } from "../provenance-CRY67X50.js";
7
+ import { a as ObjectiveSource, c as PromotionPolicy, d as paretoSignificanceGate, i as EvidenceVector, l as buildEvidenceVector, n as AxisVerdict, o as ParetoSignificanceGateOptions, r as BuildEvidenceVectorOptions, s as PromotionObjective, t as AxisEvidence, u as paretoPolicy } from "../promotion-policy-CvMda3kU.js";
8
8
  import { i as InMemoryOutcomeStore, n as FileSystemOutcomeStore, o as OutcomeStore, r as FileSystemOutcomeStoreOptions, t as DeploymentOutcome } from "../outcome-store-BYHIuO0e.js";
9
- import { a as FailureClusterInsight, c as JudgeInsight, d as Recommendation, f as ReleaseSummary, i as FailureClassTally, l as LiftInsight, m as TokenUsageInsight, n as ExecutionErrorOutcomeCell, o as InsightReport, p as ScalarDistribution, r as ExecutionInsight, s as InterRaterInsight, t as CostProvenanceSummary, u as OutcomeCorrelationInsight } from "../insight-report-08F022xN.js";
10
- import { n as HostedTenant } from "../client-Df7wdslk.js";
11
- import { a as DefinedAgentEval, c as SelfImproveOptions, d as SelfImproveRunError, f as selfImprove, i as DefineAgentEvalOptions, l as SelfImproveProgressEvent, n as AgentEvalEvaluateOptions, o as defineAgentEval, r as AgentEvalImproveOptions, s as SelfImproveBudget, t as AgentEvalAgent, u as SelfImproveResult } from "../define-agent-eval-0wW7gFhr.js";
12
- import { $ as FromRunRecordDirOptions, A as observeCodeAgentSession, At as verifyCandidateExperimentComparison, B as parseAgentTrace, C as CodeAgentSessionActionKind, Ct as evaluatePairedMeasurements, D as CodeAgentSessionObservation, Dt as sealCandidateBenchmarkTask, E as CodeAgentSessionExecutionReceipt, Et as sealCandidateBenchmarkSuite, F as AgentTraceIndex, G as EvalRunDiff, H as EvalCellScoreDelta, I as AgentTraceRange, J as diffRuns, K as diffGenerations, L as AgentTraceRecord, M as AgentTraceContributorType, N as AgentTraceConversation, O as CodeAgentSessionSource, Ot as sealCandidateExperiment, P as AgentTraceFile, Q as evalReportingSuite, R as AuthoringProvenance, S as CodeAgentSessionAction, St as SealCandidateBenchmarkSuiteOptions, T as CodeAgentSessionActionSurface, Tt as runCandidateExperiment, U as EvalDimensionDelta, V as partitionRunsByAuthoringModel, W as EvalGenerationDiff, X as EvalReportingSuiteOptions, Y as EvalReportingSuiteInput, Z as EvalReportingSuiteResult, _ as fromOpenCodeSession, _t as EvaluatePairedMeasurementsOptions, a as FromFeedbackTableOptions, at as CompareAgentProfileImprovementExperimentOptions, b as parseCodeAgentJsonlFile, bt as PairedMeasurementEvaluation, c as CodeAgentJsonlLine, ct as measuredComparisonFromAgentProfileImprovementExperiment, d as CodeAgentSessionIntakeResult, dt as sealAgentProfileImprovementSuite, et as FromRunRecordDirResult, f as CodeAgentSessionMetrics, ft as sealAgentProfileImprovementTask, g as fromKimiCodeSession, gt as CompareCandidateExperimentOptions, h as fromCodexSession, ht as CandidateExperimentRun, i as FeedbackTableRow, it as AgentProfileImprovementExperimentRun, j as AgentTraceContributor, k as CodeAgentSessionTerminalStatus, kt as verifyCandidateExperiment, l as CodeAgentSessionDiagnostic, lt as runAgentProfileImprovementExperiment, m as fromClaudeCodeSession, mt as CandidateExperimentExecutionInput, n as fromOtelSpans, nt as fromRunRecordDir, o as FromFeedbackTableResult, ot as RunAgentProfileImprovementExperimentOptions, p as ParsedCodeAgentJsonl, pt as verifyAgentProfileImprovementExperimentComparison, q as diffRunBaselineToWinner, r as FeedbackTableMeta, rt as AgentProfileImprovementExperimentExecutionInput, s as fromFeedbackTable, st as SealAgentProfileImprovementSuiteOptions, t as FromOtelSpansOptions, tt as RunRecordRejection, u as CodeAgentSessionIntakeOptions, ut as sealAgentProfileImprovementExperiment, v as fromPiSession, vt as PairedMeasurement, w as CodeAgentSessionActionStatus, wt as measuredComparisonFromCandidateExperiment, x as streamCodeAgentJsonlFile, xt as RunCandidateExperimentOptions, y as parseCodeAgentJsonl, yt as PairedMeasurementAdapter, z as PartitionByAuthoringModelResult } from "../index-DnglhM0A.js";
13
- import { n as buildDefaultAnalystRegistry, t as DefaultAnalystRegistryOptions } from "../default-registry-XxedTLwu.js";
14
- import { _ as AnalyzeRunsOptions, b as analyzeRuns, v as ExecutionReport, x as summarizeExecution, y as SummarizeExecutionOptions } from "../engine-BfRay1qD.js";
15
- export { type AgentEvalAgent, type AgentEvalEvaluateOptions, type AgentEvalImproveOptions, type AgentProfileImprovementExperimentExecutionInput, type AgentProfileImprovementExperimentRun, type AgentTraceContributor, type AgentTraceContributorType, type AgentTraceConversation, type AgentTraceFile, type AgentTraceIndex, type AgentTraceRange, type AgentTraceRecord, type AnalystFinding, type AnalyzeRunsOptions, type AuthoringProvenance, type AxisEvidence, type AxisVerdict, type BuildEvidenceVectorOptions, type CampaignAggregates, type CampaignArtifactWriter, type CampaignCellFailureReceipt, type CampaignCellResult, type CampaignCellRetryPolicy, type CampaignCostMeter, type CampaignResult, type CampaignStorage, type CampaignTraceWriter, type CandidateExperimentExecutionInput, type CandidateExperimentRun, type ChatClient, type CodeAgentJsonlLine, type CodeAgentSessionAction, type CodeAgentSessionActionKind, type CodeAgentSessionActionStatus, type CodeAgentSessionActionSurface, type CodeAgentSessionDiagnostic, type CodeAgentSessionExecutionReceipt, type CodeAgentSessionIntakeOptions, type CodeAgentSessionIntakeResult, type CodeAgentSessionMetrics, type CodeAgentSessionObservation, type CodeAgentSessionSource, type CodeAgentSessionTerminalStatus, type CodeSurface, type CompareAgentProfileImprovementExperimentOptions, type CompareCandidateExperimentOptions, type CompareOptimizationMethodsOptions, type ComparisonCost, type CostLedgerHandle, type CostProvenanceSummary, type CreateChatClientOpts, type DefaultAnalystRegistryOptions, type DefaultProductionGateCheck, type DefaultProductionGateOptions, type DefaultProductionRewardHackingOptions, type DefineAgentEvalOptions, type DefinedAgentEval, type DeploymentOutcome, type DispatchFn as Dispatch, type DispatchContext, type EvalCellScoreDelta, type EvalDimensionDelta, type EvalGenerationDiff, type EvalReportingSuiteInput, type EvalReportingSuiteOptions, type EvalReportingSuiteResult, type EvalRunDiff, type EvaluatePairedMeasurementsOptions, type EvidenceVector, type ExecutionErrorOutcomeCell, type ExecutionInsight, type ExecutionReport, type ExternalOptimizationExample, type ExternalTextEvaluationResponse, type ExternalTextOptimizationMethodConfig, type ExternalTextOptimizerContext, type ExternalTextOptimizerResult, type FailureClassTally, type FailureClusterInsight, type FeedbackTableMeta, type FeedbackTableRow, FileSystemOutcomeStore, type FileSystemOutcomeStoreOptions, type FromFeedbackTableOptions, type FromFeedbackTableResult, type FromOtelSpansOptions, type FromRunRecordDirOptions, type FromRunRecordDirResult, type Gate, type GateCheckStatus, type GateContext, type GateContribution, type GateDecision, type GateResult, type GenerationCandidate, type GenerationRecord, type GepaAdaptiveEngineRun, type GepaEngineOptions, type GepaEngineRun, type GepaOptimizationMethodConfig, type GepaOptimizationRecipe, type GepaRunnerCommand, type HeldOutGateOptions, type HostedTenant, InMemoryOutcomeStore, type InsightReport, type InterRaterInsight, type JudgeConfig, type JudgeDimension, type JudgeInsight, type JudgeScore, type LiftInsight, type LlmJudgeDimension, type LlmJudgeOptions, type MutableSurface, type ObjectiveSource, type OpenAICompatibleOptimizerModel, type OptimizationMethod, type OptimizationMethodComparison, type OptimizationMethodInput, type OptimizationMethodProvenance, type OptimizationMethodResult, type OptimizationPackageSource, type OptimizationTokenUsage, type OptimizerConfig, type OptimizerModelBudget, type OutcomeCorrelationInsight, type OutcomeStore, type PairedMeasurement, type PairedMeasurementAdapter, type PairedMeasurementEvaluation, type ParetoSignificanceGateOptions, type ParsedCodeAgentJsonl, type PartitionByAuthoringModelResult, type PromotionObjective, type PromotionPolicy, type ProposalFinding, type ProposalFindingOrigin, REFERENCE_EQUIVALENCE_INPUT_LIMITS, REFERENCE_EQUIVALENCE_JUDGE_VERSION, type Recommendation, type ReferenceEquivalenceJudgeInput, type ReferenceEquivalenceJudgeOptions, type ReferenceEquivalenceJudgeResult, type ReferenceEquivalenceScenario, type ReleaseSummary, type RunAgentProfileImprovementExperimentOptions, type RunCampaignOptions, type RunCandidateExperimentOptions, type RunEvalOptions, type RunImprovementLoopOptions, type RunImprovementLoopResult, type RunRecordRejection, type ScalarDistribution, type Scenario, type SealAgentProfileImprovementSuiteOptions, type SealCandidateBenchmarkSuiteOptions, type SelfImproveBudget, type SelfImproveOptions, type SelfImproveProgressEvent, type SelfImproveResult, SelfImproveRunError, type SessionScript, type SkillOptOptimizationMethodConfig, type SkillOptRunnerCommand, type SkillOptTrainerConfig, type SummarizeExecutionOptions, type SurfaceProposer, type TokenUsageInsight, analyzeRuns, buildDefaultAnalystRegistry, buildEvidenceVector, campaignSplitDigest, compareOptimizationMethods, composeGate, createChatClient, createReferenceEquivalenceJudge, defaultProductionGate, defineAgentEval, diffGenerations, diffRunBaselineToWinner, diffRuns, evalReportingSuite, evaluatePairedMeasurements, externalTextOptimizationMethod, fromClaudeCodeSession, fromCodexSession, fromFeedbackTable, fromKimiCodeSession, fromOpenCodeSession, fromOtelSpans, fromPiSession, fromRunRecordDir, fsCampaignStorage, gepaOptimizationMethod, heldOutGate, inMemoryCampaignStorage, llmJudge, makeProposalFinding, measuredComparisonFromAgentProfileImprovementExperiment, measuredComparisonFromCandidateExperiment, observeCodeAgentSession, paretoPolicy, paretoSignificanceGate, parseAgentTrace, parseCodeAgentJsonl, parseCodeAgentJsonlFile, partitionRunsByAuthoringModel, runAgentProfileImprovementExperiment, runCampaign, runCandidateExperiment, runEval, runImprovementLoop, runReferenceEquivalenceJudge, sealAgentProfileImprovementExperiment, sealAgentProfileImprovementSuite, sealAgentProfileImprovementTask, sealCandidateBenchmarkSuite, sealCandidateBenchmarkTask, sealCandidateExperiment, selfImprove, skillOptOptimizationMethod, streamCodeAgentJsonlFile, summarizeExecution, transientDispatchFailure, verifyAgentProfileImprovementExperimentComparison, verifyCandidateExperiment, verifyCandidateExperimentComparison };
9
+ import { a as FailureClusterInsight, c as JudgeInsight, d as Recommendation, f as ReleaseSummary, i as FailureClassTally, l as LiftInsight, m as TokenUsageInsight, n as ExecutionErrorOutcomeCell, o as InsightReport, p as ScalarDistribution, r as ExecutionInsight, s as InterRaterInsight, t as CostProvenanceSummary, u as OutcomeCorrelationInsight } from "../insight-report-DETqPc_A.js";
10
+ import { n as HostedTenant } from "../client-DlqdbM7n.js";
11
+ import { a as DefinedAgentEval, c as SelfImproveOptions, d as SelfImproveRunError, f as selfImprove, i as DefineAgentEvalOptions, l as SelfImproveProgressEvent, n as AgentEvalEvaluateOptions, o as defineAgentEval, r as AgentEvalImproveOptions, s as SelfImproveBudget, t as AgentEvalAgent, u as SelfImproveResult } from "../define-agent-eval-CY6qdlGV.js";
12
+ import { $ as diffRunBaselineToWinner, A as CodeAgentSessionActionStatus, At as measuredComparisonFromCandidateExperiment, B as AgentTraceFile, C as fromOpenCodeSession, Ct as EvaluatePairedMeasurementsOptions, D as streamCodeAgentJsonlFile, Dt as RunCandidateExperimentOptions, E as parseCodeAgentJsonlFile, Et as PairedMeasurementEvaluation, F as CodeAgentSessionTerminalStatus, Ft as verifyCandidateExperiment, G as PartitionByAuthoringModelResult, H as AgentTraceRange, I as observeCodeAgentSession, It as verifyCandidateExperimentComparison, J as EvalCellScoreDelta, K as parseAgentTrace, L as AgentTraceContributor, M as CodeAgentSessionExecutionReceipt, Mt as sealCandidateBenchmarkSuite, N as CodeAgentSessionObservation, Nt as sealCandidateBenchmarkTask, O as CodeAgentSessionAction, Ot as SealCandidateBenchmarkSuiteOptions, P as CodeAgentSessionSource, Pt as sealCandidateExperiment, Q as diffGenerations, R as AgentTraceContributorType, S as fromKimiCodeSession, St as CompareCandidateExperimentOptions, T as parseCodeAgentJsonl, Tt as PairedMeasurementAdapter, U as AgentTraceRecord, V as AgentTraceIndex, W as AuthoringProvenance, X as EvalGenerationDiff, Y as EvalDimensionDelta, Z as EvalRunDiff, _ as CodeAgentSessionIntakeResult, _t as sealAgentProfileImprovementSuite, a as FromFeedbackTableOptions, at as FromRunRecordDirOptions, b as fromClaudeCodeSession, bt as CandidateExperimentExecutionInput, c as CodeAgentStoreObservation, ct as fromRunRecordDir, d as CodeAgentStoreScope, dt as CompareAgentProfileImprovementExperimentOptions, et as diffRuns, f as CodeAgentStoreSession, ft as RunAgentProfileImprovementExperimentOptions, g as CodeAgentSessionIntakeOptions, gt as sealAgentProfileImprovementExperiment, h as CodeAgentSessionDiagnostic, ht as runAgentProfileImprovementExperiment, i as FeedbackTableRow, it as evalReportingSuite, j as CodeAgentSessionActionSurface, jt as runCandidateExperiment, k as CodeAgentSessionActionKind, kt as evaluatePairedMeasurements, l as CodeAgentStoreRejection, lt as AgentProfileImprovementExperimentExecutionInput, m as CodeAgentJsonlLine, mt as measuredComparisonFromAgentProfileImprovementExperiment, n as fromOtelSpans, nt as EvalReportingSuiteOptions, o as FromFeedbackTableResult, ot as FromRunRecordDirResult, p as observeCodeAgentStore, pt as SealAgentProfileImprovementSuiteOptions, q as partitionRunsByAuthoringModel, r as FeedbackTableMeta, rt as EvalReportingSuiteResult, s as fromFeedbackTable, st as RunRecordRejection, t as FromOtelSpansOptions, tt as EvalReportingSuiteInput, u as CodeAgentStoreRejections, ut as AgentProfileImprovementExperimentRun, v as CodeAgentSessionMetrics, vt as sealAgentProfileImprovementTask, w as fromPiSession, wt as PairedMeasurement, x as fromCodexSession, xt as CandidateExperimentRun, y as ParsedCodeAgentJsonl, yt as verifyAgentProfileImprovementExperimentComparison, z as AgentTraceConversation } from "../index-BQqOjerE.js";
13
+ import { n as buildDefaultAnalystRegistry, t as DefaultAnalystRegistryOptions } from "../default-registry-BKwc8bN5.js";
14
+ import { S as summarizeExecution, b as SummarizeExecutionOptions, v as AnalyzeRunsOptions, x as analyzeRuns, y as ExecutionReport } from "../engine-DhFir3Ys.js";
15
+ export { type AgentEvalAgent, type AgentEvalEvaluateOptions, type AgentEvalImproveOptions, type AgentProfileImprovementExperimentExecutionInput, type AgentProfileImprovementExperimentRun, type AgentTraceContributor, type AgentTraceContributorType, type AgentTraceConversation, type AgentTraceFile, type AgentTraceIndex, type AgentTraceRange, type AgentTraceRecord, type AnalystFinding, type AnalyzeRunsOptions, type AuthoringProvenance, type AxisEvidence, type AxisVerdict, type BuildEvidenceVectorOptions, type CampaignAggregates, type CampaignArtifactWriter, type CampaignCellFailureReceipt, type CampaignCellResult, type CampaignCellRetryPolicy, type CampaignCostMeter, type CampaignResult, type CampaignStorage, type CampaignTraceWriter, type CandidateExperimentExecutionInput, type CandidateExperimentRun, type ChatClient, type CodeAgentJsonlLine, type CodeAgentSessionAction, type CodeAgentSessionActionKind, type CodeAgentSessionActionStatus, type CodeAgentSessionActionSurface, type CodeAgentSessionDiagnostic, type CodeAgentSessionExecutionReceipt, type CodeAgentSessionIntakeOptions, type CodeAgentSessionIntakeResult, type CodeAgentSessionMetrics, type CodeAgentSessionObservation, type CodeAgentSessionSource, type CodeAgentSessionTerminalStatus, type CodeAgentStoreObservation, type CodeAgentStoreRejection, type CodeAgentStoreRejections, type CodeAgentStoreScope, type CodeAgentStoreSession, type CodeSurface, type CompareAgentProfileImprovementExperimentOptions, type CompareCandidateExperimentOptions, type CompareOptimizationMethodsOptions, type ComparisonCost, type CostLedgerHandle, type CostProvenanceSummary, type CreateChatClientOpts, type DefaultAnalystRegistryOptions, type DefaultProductionGateCheck, type DefaultProductionGateOptions, type DefaultProductionRewardHackingOptions, type DefineAgentEvalOptions, type DefinedAgentEval, type DeploymentOutcome, type DispatchFn as Dispatch, type DispatchContext, type EvalCellScoreDelta, type EvalDimensionDelta, type EvalGenerationDiff, type EvalReportingSuiteInput, type EvalReportingSuiteOptions, type EvalReportingSuiteResult, type EvalRunDiff, type EvaluatePairedMeasurementsOptions, type EvidenceVector, type ExecutionErrorOutcomeCell, type ExecutionInsight, type ExecutionReport, type ExternalOptimizationExample, type ExternalTextEvaluationResponse, type ExternalTextOptimizationMethodConfig, type ExternalTextOptimizerContext, type ExternalTextOptimizerResult, type FailureClassTally, type FailureClusterInsight, type FeedbackTableMeta, type FeedbackTableRow, FileSystemOutcomeStore, type FileSystemOutcomeStoreOptions, type FromFeedbackTableOptions, type FromFeedbackTableResult, type FromOtelSpansOptions, type FromRunRecordDirOptions, type FromRunRecordDirResult, type Gate, type GateCheckStatus, type GateContext, type GateContribution, type GateDecision, type GateResult, type GenerationCandidate, type GenerationRecord, type GepaAdaptiveEngineRun, type GepaEngineOptions, type GepaEngineRun, type GepaOptimizationMethodConfig, type GepaOptimizationRecipe, type GepaRunnerCommand, type HeldOutGateOptions, type HostedTenant, InMemoryOutcomeStore, type InsightReport, type InterRaterInsight, type JudgeConfig, type JudgeDimension, type JudgeInsight, type JudgeScore, type LiftInsight, type LlmJudgeDimension, type LlmJudgeOptions, type MutableSurface, type ObjectiveSource, type OpenAICompatibleOptimizerModel, type OptimizationMethod, type OptimizationMethodComparison, type OptimizationMethodInput, type OptimizationMethodProvenance, type OptimizationMethodResult, type OptimizationPackageSource, type OptimizationTokenUsage, type OptimizerConfig, type OptimizerModelBudget, type OutcomeCorrelationInsight, type OutcomeStore, type PairedMeasurement, type PairedMeasurementAdapter, type PairedMeasurementEvaluation, type ParetoSignificanceGateOptions, type ParsedCodeAgentJsonl, type PartitionByAuthoringModelResult, type PromotionObjective, type PromotionPolicy, type ProposalFinding, type ProposalFindingOrigin, REFERENCE_EQUIVALENCE_INPUT_LIMITS, REFERENCE_EQUIVALENCE_JUDGE_VERSION, type Recommendation, type ReferenceEquivalenceJudgeInput, type ReferenceEquivalenceJudgeOptions, type ReferenceEquivalenceJudgeResult, type ReferenceEquivalenceScenario, type ReleaseSummary, type RunAgentProfileImprovementExperimentOptions, type RunCampaignOptions, type RunCandidateExperimentOptions, type RunEvalOptions, type RunImprovementLoopOptions, type RunImprovementLoopResult, type RunRecordRejection, type ScalarDistribution, type Scenario, type SealAgentProfileImprovementSuiteOptions, type SealCandidateBenchmarkSuiteOptions, type SelfImproveBudget, type SelfImproveOptions, type SelfImproveProgressEvent, type SelfImproveResult, SelfImproveRunError, type SessionScript, type SkillOptOptimizationMethodConfig, type SkillOptRunnerCommand, type SkillOptTrainerConfig, type SummarizeExecutionOptions, type SurfaceProposer, type TokenUsageInsight, analyzeRuns, buildDefaultAnalystRegistry, buildEvidenceVector, campaignSplitDigest, compareOptimizationMethods, composeGate, createChatClient, createReferenceEquivalenceJudge, defaultProductionGate, defineAgentEval, diffGenerations, diffRunBaselineToWinner, diffRuns, evalReportingSuite, evaluatePairedMeasurements, externalTextOptimizationMethod, fromClaudeCodeSession, fromCodexSession, fromFeedbackTable, fromKimiCodeSession, fromOpenCodeSession, fromOtelSpans, fromPiSession, fromRunRecordDir, fsCampaignStorage, gepaOptimizationMethod, heldOutGate, inMemoryCampaignStorage, llmJudge, makeProposalFinding, measuredComparisonFromAgentProfileImprovementExperiment, measuredComparisonFromCandidateExperiment, observeCodeAgentSession, observeCodeAgentStore, paretoPolicy, paretoSignificanceGate, parseAgentTrace, parseCodeAgentJsonl, parseCodeAgentJsonlFile, partitionRunsByAuthoringModel, runAgentProfileImprovementExperiment, runCampaign, runCandidateExperiment, runEval, runImprovementLoop, runReferenceEquivalenceJudge, sealAgentProfileImprovementExperiment, sealAgentProfileImprovementSuite, sealAgentProfileImprovementTask, sealCandidateBenchmarkSuite, sealCandidateBenchmarkTask, sealCandidateExperiment, selfImprove, skillOptOptimizationMethod, streamCodeAgentJsonlFile, summarizeExecution, transientDispatchFailure, verifyAgentProfileImprovementExperimentComparison, verifyCandidateExperiment, verifyCandidateExperimentComparison };
@@ -1,27 +1,28 @@
1
1
  import { s as ValidationError } from "../errors-Dngq5h35.js";
2
2
  import { a as hashCanonical } from "../canonical-DPyQ_rpt.js";
3
3
  import { r as pairedBootstrap } from "../paired-tests-C8iCsioC.js";
4
- import { a as summarizeExecution, i as analyzeRuns, n as SelfImproveRunError, r as selfImprove, t as defineAgentEval } from "../define-agent-eval-jS8xj_Q_.js";
5
- import { a as parseRunRecordSafe } from "../run-record-DLORoL7t.js";
6
- import { O as compareOptimizationMethods, Z as defaultProductionGate, g as runImprovementLoop, i as transientDispatchFailure, it as runCampaign, mt as campaignSplitDigest, rt as runEval, t as llmJudge } from "../llm-judge-aQHIk5_-.js";
4
+ import { a as summarizeExecution, i as analyzeRuns, n as SelfImproveRunError, r as selfImprove, t as defineAgentEval } from "../define-agent-eval-D_i_s69h.js";
5
+ import { a as parseRunRecordSafe } from "../run-record-ZIsR9Fif.js";
6
+ import { Q as defaultProductionGate, _ as runImprovementLoop, a as transientDispatchFailure, at as runCampaign, ht as campaignSplitDigest, it as runEval, k as compareOptimizationMethods, t as llmJudge } from "../llm-judge-B2YxbAJb.js";
7
7
  import { i as isModelPriced, n as estimateCost } from "../metrics-Qv-cpptD.js";
8
8
  import { i as CostLedger } from "../cost-ledger-B1qx30B4.js";
9
9
  import { d as mapConcurrentRange } from "../ledger-core-PIfjCbKn.js";
10
- import { C as inMemoryCampaignStorage, S as fsCampaignStorage } from "../external-optimizer-subprocess-Cex8Da2i.js";
10
+ import { C as inMemoryCampaignStorage, S as fsCampaignStorage } from "../external-optimizer-subprocess-DgNebftP.js";
11
11
  import { a as heldoutSignificance, s as decidePairedPromotion } from "../power-preflight-CFXm0Vjo.js";
12
12
  import { i as makeProposalFinding } from "../types-CiWITkGo.js";
13
- import { G as isOtlpModelCall, W as classifyOtlpSpanRole } from "../kind-factory-DMeEoMQZ.js";
14
- import { n as buildDefaultAnalystRegistry, t as createChatClient } from "../chat-client-DI79OPye.js";
13
+ import { G as classifyOtlpSpanRole, K as isOtlpModelCall } from "../kind-factory-gP6lDySe.js";
14
+ import { t as buildDefaultAnalystRegistry } from "../default-registry-B0bKikCb.js";
15
15
  import { LLM_MODEL_ATTR_KEYS, SPAN_KIND_ATTR_KEYS } from "../trace-attributes.js";
16
16
  import { t as extractUsage } from "../extract-usage-BrQ8mCLX.js";
17
+ import { t as createChatClient } from "../chat-client-Db4bqYfA.js";
17
18
  import { n as InMemoryOutcomeStore, t as FileSystemOutcomeStore } from "../outcome-store-ChBKlTd_.js";
18
- import { i as summarizeTraceErrors, n as recordAggregateMeasurements, r as summarizeExecutionMeasurements, t as readTaskFailureLabels } from "../task-failure-attributes-CBGtLS_H.js";
19
- import { c as externalTextOptimizationMethod, d as REFERENCE_EQUIVALENCE_INPUT_LIMITS, f as REFERENCE_EQUIVALENCE_JUDGE_VERSION, m as runReferenceEquivalenceJudge, n as gepaOptimizationMethod, o as heldOutGate, p as createReferenceEquivalenceJudge, s as composeGate, t as skillOptOptimizationMethod } from "../skillopt-optimization-method-LHi02MzH.js";
19
+ import { i as summarizeTraceErrors, n as recordAggregateMeasurements, r as summarizeExecutionMeasurements, t as readTaskFailureLabels } from "../task-failure-attributes-CZjZeBsY.js";
20
+ import { c as externalTextOptimizationMethod, d as REFERENCE_EQUIVALENCE_INPUT_LIMITS, f as REFERENCE_EQUIVALENCE_JUDGE_VERSION, m as runReferenceEquivalenceJudge, n as gepaOptimizationMethod, o as heldOutGate, p as createReferenceEquivalenceJudge, s as composeGate, t as skillOptOptimizationMethod } from "../skillopt-optimization-method-BzdphODy.js";
20
21
  import { n as paretoPolicy, r as paretoSignificanceGate, t as buildEvidenceVector } from "../promotion-policy-LY9mVQ7W.js";
21
22
  import { createHash } from "node:crypto";
22
23
  import { agentCandidateBenchmarkSuiteSchema, agentCandidateBenchmarkTaskSchema, agentCandidateBundleSchema, agentCandidateEvaluationPolicySchema, agentCandidateExperimentSchema, agentImprovementMeasuredComparisonSchema, agentProfileImprovementExperimentSchema, agentProfileImprovementMeasuredComparisonSchema, agentProfileImprovementRunCellSchema, agentProfileImprovementRunReceiptSchema, agentProfileImprovementSuiteInputsSchema, agentProfileImprovementSuiteSchema, agentProfileImprovementTaskSchema, candidateExecutionEvidenceSchema, canonicalCandidateDigest, canonicalCandidateJson, numbersApproximatelyEqual, omitTopLevelDigest } from "@tangle-network/agent-interface";
23
24
  import { createReadStream } from "node:fs";
24
- import { dirname, join } from "node:path";
25
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
25
26
  import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
26
27
  //#region src/contract/fixed-spend.ts
27
28
  function addFixedSpend(left, right) {
@@ -3071,6 +3072,197 @@ function timestampMs(value) {
3071
3072
  }
3072
3073
  }
3073
3074
  //#endregion
3075
+ //#region src/contract/intake/code-agent-store.ts
3076
+ const SESSION_SUFFIX = ".jsonl";
3077
+ const REJECTION_SAMPLE_LIMIT = 8;
3078
+ /**
3079
+ * Read every session this run captured under `scope.root` and project them.
3080
+ *
3081
+ * A store directory that does not exist, or that holds no session the scope attributes, returns
3082
+ * `status: 'unavailable'`. That is not an error: a run whose harness store was never synced back
3083
+ * has no evidence, and saying so is the correct answer.
3084
+ */
3085
+ async function observeCodeAgentStore(scope) {
3086
+ if (!isAbsolute(scope.root)) throw new TypeError(`observeCodeAgentStore: scope.root must be an absolute path to this run's own store, received ${JSON.stringify(scope.root)}`);
3087
+ const workspaceRoot = scope.workspaceRoot === void 0 ? void 0 : resolve(scope.workspaceRoot);
3088
+ const paths = await listSessionFiles(resolve(scope.root));
3089
+ const sessions = [];
3090
+ const byReason = /* @__PURE__ */ new Map();
3091
+ const sample = [];
3092
+ const reject = (path, reason) => {
3093
+ byReason.set(reason, (byReason.get(reason) ?? 0) + 1);
3094
+ if (sample.length < REJECTION_SAMPLE_LIMIT) sample.push({
3095
+ path,
3096
+ reason
3097
+ });
3098
+ };
3099
+ for (const path of paths) {
3100
+ let entries;
3101
+ try {
3102
+ entries = (await parseCodeAgentJsonlFile(path)).entries;
3103
+ } catch {
3104
+ reject(path, "unreadable");
3105
+ continue;
3106
+ }
3107
+ if (entries.length === 0) {
3108
+ reject(path, "no-entries");
3109
+ continue;
3110
+ }
3111
+ const workspace = sessionWorkspace(entries);
3112
+ if (workspaceRoot !== void 0) {
3113
+ if (workspace === void 0) {
3114
+ reject(path, "no-workspace-recorded");
3115
+ continue;
3116
+ }
3117
+ if (!isSameOrBelow(workspaceRoot, workspace)) {
3118
+ reject(path, "outside-workspace");
3119
+ continue;
3120
+ }
3121
+ }
3122
+ const startedAtMs = sessionStartedAtMs(entries);
3123
+ if (scope.window !== void 0) {
3124
+ if (startedAtMs === void 0) {
3125
+ reject(path, "no-start-recorded");
3126
+ continue;
3127
+ }
3128
+ if (startedAtMs < scope.window.startedAtMs) {
3129
+ reject(path, "before-run");
3130
+ continue;
3131
+ }
3132
+ if (scope.window.finishedAtMs !== void 0 && startedAtMs > scope.window.finishedAtMs) {
3133
+ reject(path, "after-run");
3134
+ continue;
3135
+ }
3136
+ }
3137
+ const observation = observeCodeAgentSession({
3138
+ source: scope.source,
3139
+ entries,
3140
+ sourcePath: path
3141
+ });
3142
+ sessions.push({
3143
+ path,
3144
+ sessionId: observation.sessionId,
3145
+ ...workspace === void 0 ? {} : { workspace },
3146
+ ...startedAtMs === void 0 ? {} : { startedAtMs },
3147
+ observation
3148
+ });
3149
+ }
3150
+ const rejections = {
3151
+ total: [...byReason.values()].reduce((sum, count) => sum + count, 0),
3152
+ byReason: Object.fromEntries(byReason),
3153
+ sample
3154
+ };
3155
+ if (sessions.length === 0) return {
3156
+ status: "unavailable",
3157
+ scope,
3158
+ filesScanned: paths.length,
3159
+ reason: unavailableReason(paths.length, rejections),
3160
+ rejections
3161
+ };
3162
+ const bySurface = /* @__PURE__ */ new Map();
3163
+ let actions = 0;
3164
+ let subagentActions = 0;
3165
+ let sessionsWithSubagentActions = 0;
3166
+ for (const session of sessions) {
3167
+ let sessionSubagents = 0;
3168
+ for (const action of session.observation.actions) {
3169
+ actions += 1;
3170
+ bySurface.set(action.surface, (bySurface.get(action.surface) ?? 0) + 1);
3171
+ if (action.surface === "subagent") sessionSubagents += 1;
3172
+ }
3173
+ subagentActions += sessionSubagents;
3174
+ if (sessionSubagents > 0) sessionsWithSubagentActions += 1;
3175
+ }
3176
+ return {
3177
+ status: "observed",
3178
+ scope,
3179
+ filesScanned: paths.length,
3180
+ sessions,
3181
+ actions,
3182
+ subagentActions,
3183
+ sessionsWithSubagentActions,
3184
+ bySurface: Object.fromEntries(bySurface),
3185
+ rejections
3186
+ };
3187
+ }
3188
+ function unavailableReason(filesScanned, rejections) {
3189
+ if (filesScanned === 0) return "the run captured no session files in this store";
3190
+ return `no session in this store belongs to the run: ${filesScanned} file(s) scanned, all rejected (${Object.entries(rejections.byReason).map(([reason, count]) => `${count} ${reason}`).sort().join(", ")})`;
3191
+ }
3192
+ async function listSessionFiles(root) {
3193
+ const found = [];
3194
+ const walk = async (dir) => {
3195
+ let entries;
3196
+ try {
3197
+ entries = await readdir(dir, { withFileTypes: true });
3198
+ } catch {
3199
+ return;
3200
+ }
3201
+ for (const entry of entries) {
3202
+ const path = join(dir, entry.name);
3203
+ if (entry.isDirectory()) await walk(path);
3204
+ else if (entry.isFile() && entry.name.endsWith(SESSION_SUFFIX)) found.push(path);
3205
+ }
3206
+ };
3207
+ await walk(root);
3208
+ if (found.length === 0 && await isSessionFile(root)) found.push(root);
3209
+ return found.sort();
3210
+ }
3211
+ async function isSessionFile(path) {
3212
+ if (!path.endsWith(SESSION_SUFFIX)) return false;
3213
+ try {
3214
+ return (await stat(path)).isFile();
3215
+ } catch {
3216
+ return false;
3217
+ }
3218
+ }
3219
+ /**
3220
+ * The working directory the session RECORDED, from the first entry that states one.
3221
+ *
3222
+ * codex writes it on `session_meta.payload.cwd`; claude-code writes `cwd` on every line. Neither is
3223
+ * inferred from the file's own location: where a captured file was copied to says nothing about
3224
+ * where the agent ran.
3225
+ */
3226
+ function sessionWorkspace(entries) {
3227
+ for (const entry of entries) {
3228
+ const record = plainRecord(entry);
3229
+ if (record === void 0) continue;
3230
+ const direct = stringOf(record.cwd);
3231
+ if (direct !== void 0) return direct;
3232
+ const nested = stringOf(plainRecord(record.payload)?.cwd);
3233
+ if (nested !== void 0) return nested;
3234
+ }
3235
+ }
3236
+ /** When the session itself says it started, from the first entry carrying a parseable timestamp. */
3237
+ function sessionStartedAtMs(entries) {
3238
+ for (const entry of entries) {
3239
+ const record = plainRecord(entry);
3240
+ if (record === void 0) continue;
3241
+ const payload = plainRecord(record.payload);
3242
+ for (const candidate of [payload?.timestamp, record.timestamp]) {
3243
+ const text = stringOf(candidate);
3244
+ if (text === void 0) continue;
3245
+ const parsed = Date.parse(text);
3246
+ if (Number.isFinite(parsed)) return parsed;
3247
+ }
3248
+ const epochMs = numberOf(record.timestampMs) ?? numberOf(payload?.timestampMs);
3249
+ if (epochMs !== void 0) return epochMs;
3250
+ }
3251
+ }
3252
+ function isSameOrBelow(root, candidate) {
3253
+ const rel = relative(root, resolve(candidate));
3254
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
3255
+ }
3256
+ function plainRecord(value) {
3257
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3258
+ }
3259
+ function stringOf(value) {
3260
+ return typeof value === "string" && value.length > 0 ? value : void 0;
3261
+ }
3262
+ function numberOf(value) {
3263
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
3264
+ }
3265
+ //#endregion
3074
3266
  //#region src/contract/intake/feedback-table.ts
3075
3267
  function fromFeedbackTable(opts) {
3076
3268
  const { ratings, meta = [], scale, emitRaterScores = true } = opts;
@@ -3418,6 +3610,6 @@ function collectNumericAttrs(spans) {
3418
3610
  return raw;
3419
3611
  }
3420
3612
  //#endregion
3421
- export { FileSystemOutcomeStore, InMemoryOutcomeStore, REFERENCE_EQUIVALENCE_INPUT_LIMITS, REFERENCE_EQUIVALENCE_JUDGE_VERSION, SelfImproveRunError, analyzeRuns, buildDefaultAnalystRegistry, buildEvidenceVector, campaignSplitDigest, compareOptimizationMethods, composeGate, createChatClient, createReferenceEquivalenceJudge, defaultProductionGate, defineAgentEval, diffGenerations, diffRunBaselineToWinner, diffRuns, evalReportingSuite, evaluatePairedMeasurements, externalTextOptimizationMethod, fromClaudeCodeSession, fromCodexSession, fromFeedbackTable, fromKimiCodeSession, fromOpenCodeSession, fromOtelSpans, fromPiSession, fromRunRecordDir, fsCampaignStorage, gepaOptimizationMethod, heldOutGate, inMemoryCampaignStorage, llmJudge, makeProposalFinding, measuredComparisonFromAgentProfileImprovementExperiment, measuredComparisonFromCandidateExperiment, observeCodeAgentSession, paretoPolicy, paretoSignificanceGate, parseAgentTrace, parseCodeAgentJsonl, parseCodeAgentJsonlFile, partitionRunsByAuthoringModel, runAgentProfileImprovementExperiment, runCampaign, runCandidateExperiment, runEval, runImprovementLoop, runReferenceEquivalenceJudge, sealAgentProfileImprovementExperiment, sealAgentProfileImprovementSuite, sealAgentProfileImprovementTask, sealCandidateBenchmarkSuite, sealCandidateBenchmarkTask, sealCandidateExperiment, selfImprove, skillOptOptimizationMethod, streamCodeAgentJsonlFile, summarizeExecution, transientDispatchFailure, verifyAgentProfileImprovementExperimentComparison, verifyCandidateExperiment, verifyCandidateExperimentComparison };
3613
+ export { FileSystemOutcomeStore, InMemoryOutcomeStore, REFERENCE_EQUIVALENCE_INPUT_LIMITS, REFERENCE_EQUIVALENCE_JUDGE_VERSION, SelfImproveRunError, analyzeRuns, buildDefaultAnalystRegistry, buildEvidenceVector, campaignSplitDigest, compareOptimizationMethods, composeGate, createChatClient, createReferenceEquivalenceJudge, defaultProductionGate, defineAgentEval, diffGenerations, diffRunBaselineToWinner, diffRuns, evalReportingSuite, evaluatePairedMeasurements, externalTextOptimizationMethod, fromClaudeCodeSession, fromCodexSession, fromFeedbackTable, fromKimiCodeSession, fromOpenCodeSession, fromOtelSpans, fromPiSession, fromRunRecordDir, fsCampaignStorage, gepaOptimizationMethod, heldOutGate, inMemoryCampaignStorage, llmJudge, makeProposalFinding, measuredComparisonFromAgentProfileImprovementExperiment, measuredComparisonFromCandidateExperiment, observeCodeAgentSession, observeCodeAgentStore, paretoPolicy, paretoSignificanceGate, parseAgentTrace, parseCodeAgentJsonl, parseCodeAgentJsonlFile, partitionRunsByAuthoringModel, runAgentProfileImprovementExperiment, runCampaign, runCandidateExperiment, runEval, runImprovementLoop, runReferenceEquivalenceJudge, sealAgentProfileImprovementExperiment, sealAgentProfileImprovementSuite, sealAgentProfileImprovementTask, sealCandidateBenchmarkSuite, sealCandidateBenchmarkTask, sealCandidateExperiment, selfImprove, skillOptOptimizationMethod, streamCodeAgentJsonlFile, summarizeExecution, transientDispatchFailure, verifyAgentProfileImprovementExperimentComparison, verifyCandidateExperiment, verifyCandidateExperimentComparison };
3422
3614
 
3423
3615
  //# sourceMappingURL=index.js.map