@tangle-network/agent-eval 0.220.1 → 0.221.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 (192) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-D01Io2Xw.d.ts → agent-profile-Bc7ADJY4.d.ts} +2 -2
  4. package/dist/{agent-profile-D01Io2Xw.d.ts.map → agent-profile-Bc7ADJY4.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +77 -78
  6. package/dist/analyst/index.d.ts.map +1 -1
  7. package/dist/analyst/index.js +204 -25
  8. package/dist/analyst/index.js.map +1 -1
  9. package/dist/{analyze-runs-DqPJaJ4X.js → analyze-runs-CHmsykNJ.js} +4 -4
  10. package/dist/{analyze-runs-DqPJaJ4X.js.map → analyze-runs-CHmsykNJ.js.map} +1 -1
  11. package/dist/{analyze-runs-BWAHBDAw.d.ts → analyze-runs-D7In4c3z.d.ts} +2 -2
  12. package/dist/{analyze-runs-BWAHBDAw.d.ts.map → analyze-runs-D7In4c3z.d.ts.map} +1 -1
  13. package/dist/{benchmark-command-BzmMTnvC.js → benchmark-command-8XQfpUK3.js} +13 -11
  14. package/dist/benchmark-command-8XQfpUK3.js.map +1 -0
  15. package/dist/benchmarks/index.d.ts +4 -4
  16. package/dist/benchmarks/index.js +3 -3
  17. package/dist/calibration-CTwxpJ-t.js +197 -0
  18. package/dist/calibration-CTwxpJ-t.js.map +1 -0
  19. package/dist/campaign/index.d.ts +6 -6
  20. package/dist/campaign/index.js +5 -5
  21. package/dist/{campaign-BVPC6ODQ.js → campaign-Bt6rbWIU.js} +9 -8
  22. package/dist/{campaign-BVPC6ODQ.js.map → campaign-Bt6rbWIU.js.map} +1 -1
  23. package/dist/cli.js +2 -2
  24. package/dist/{completion-verifier-Cigap8CG.js → completion-verifier-YwoeujPl.js} +2 -2
  25. package/dist/{completion-verifier-Cigap8CG.js.map → completion-verifier-YwoeujPl.js.map} +1 -1
  26. package/dist/contract/index.d.ts +10 -10
  27. package/dist/contract/index.js +7 -7
  28. package/dist/decision-point-Co3u3W8k.js +831 -0
  29. package/dist/decision-point-Co3u3W8k.js.map +1 -0
  30. package/dist/default-registry-BMHqNR6_.d.ts +257 -0
  31. package/dist/default-registry-BMHqNR6_.d.ts.map +1 -0
  32. package/dist/{default-registry-BrKmT01n.js → default-registry-BbFCkqvB.js} +608 -15
  33. package/dist/default-registry-BbFCkqvB.js.map +1 -0
  34. package/dist/{define-agent-eval-C2nFhHPu.d.ts → define-agent-eval-Bsoi2GUV.d.ts} +7 -7
  35. package/dist/{define-agent-eval-C2nFhHPu.d.ts.map → define-agent-eval-Bsoi2GUV.d.ts.map} +1 -1
  36. package/dist/{define-agent-eval-UQY3VbJ2.js → define-agent-eval-CJhECJNL.js} +4 -4
  37. package/dist/{define-agent-eval-UQY3VbJ2.js.map → define-agent-eval-CJhECJNL.js.map} +1 -1
  38. package/dist/diagnosis/index.d.ts +2 -2
  39. package/dist/diagnosis/index.js +1 -1
  40. package/dist/{dspy-rlm-engine-Bn_Mt_LW.js → dspy-rlm-engine-BTy7u0jQ.js} +3 -3
  41. package/dist/{dspy-rlm-engine-Bn_Mt_LW.js.map → dspy-rlm-engine-BTy7u0jQ.js.map} +1 -1
  42. package/dist/{engine-BpGGw6cd.d.ts → engine-BF95CWzH.d.ts} +2 -2
  43. package/dist/{engine-BpGGw6cd.d.ts.map → engine-BF95CWzH.d.ts.map} +1 -1
  44. package/dist/{eval-campaign-BUMIxKTE.js → eval-campaign-DoX5vz3E.js} +2 -2
  45. package/dist/{eval-campaign-BUMIxKTE.js.map → eval-campaign-DoX5vz3E.js.map} +1 -1
  46. package/dist/{evaluation-CBdQt_kr.d.ts → evaluation-D1PGzkPR.d.ts} +3 -3
  47. package/dist/{evaluation-CBdQt_kr.d.ts.map → evaluation-D1PGzkPR.d.ts.map} +1 -1
  48. package/dist/evaluation-wdGyZ7jV.js +147 -0
  49. package/dist/evaluation-wdGyZ7jV.js.map +1 -0
  50. package/dist/evaluation.d.ts +1 -1
  51. package/dist/evaluation.js +1 -136
  52. package/dist/{exact-types-BYFmYq44.d.ts → exact-types-CVn1QxFO.d.ts} +2 -2
  53. package/dist/{exact-types-BYFmYq44.d.ts.map → exact-types-CVn1QxFO.d.ts.map} +1 -1
  54. package/dist/experiment/index.d.ts +3 -3
  55. package/dist/experiment/index.js +2 -2
  56. package/dist/{external-optimizer-process-wOLfzsCC.js → external-optimizer-process-E5yY2SYS.js} +2 -2
  57. package/dist/{external-optimizer-process-wOLfzsCC.js.map → external-optimizer-process-E5yY2SYS.js.map} +1 -1
  58. package/dist/{external-optimizer-subprocess-D670Oxf2.js → external-optimizer-subprocess-DA02c_L6.js} +12 -19
  59. package/dist/{external-optimizer-subprocess-D670Oxf2.js.map → external-optimizer-subprocess-DA02c_L6.js.map} +1 -1
  60. package/dist/{feedback-trajectory-DhB9WzYg.d.ts → feedback-trajectory-BZhVCWuz.d.ts} +3 -3
  61. package/dist/{feedback-trajectory-DhB9WzYg.d.ts.map → feedback-trajectory-BZhVCWuz.d.ts.map} +1 -1
  62. package/dist/finding-composition-8n0fFgVI.js +131 -0
  63. package/dist/finding-composition-8n0fFgVI.js.map +1 -0
  64. package/dist/{findings-store-CvNo712L.js → findings-store-DRiFdoid.js} +4 -4
  65. package/dist/{findings-store-CvNo712L.js.map → findings-store-DRiFdoid.js.map} +1 -1
  66. package/dist/{index-CVFStrQD.d.ts → index-BJZ7s-sv.d.ts} +7 -58
  67. package/dist/index-BJZ7s-sv.d.ts.map +1 -0
  68. package/dist/{index-Q6DvdcwI.d.ts → index-BvX3CFNS.d.ts} +6 -6
  69. package/dist/{index-Q6DvdcwI.d.ts.map → index-BvX3CFNS.d.ts.map} +1 -1
  70. package/dist/index-DWd1gUwR.d.ts +1086 -0
  71. package/dist/index-DWd1gUwR.d.ts.map +1 -0
  72. package/dist/{index-DAXfpVf7.d.ts → index-y7i8l6Y_.d.ts} +8 -8
  73. package/dist/{index-DAXfpVf7.d.ts.map → index-y7i8l6Y_.d.ts.map} +1 -1
  74. package/dist/index.d.ts +18 -17
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +15 -15
  77. package/dist/{integrity-C8oUeB0g.js → integrity-D-s2iHiT.js} +2 -2
  78. package/dist/{integrity-C8oUeB0g.js.map → integrity-D-s2iHiT.js.map} +1 -1
  79. package/dist/{kind-factory-BhxbtUsQ.js → kind-factory-Dl0PmNQL.js} +2 -2
  80. package/dist/{kind-factory-BhxbtUsQ.js.map → kind-factory-Dl0PmNQL.js.map} +1 -1
  81. package/dist/{llm-judge-Cc8vDJh_.js → llm-judge-3uAeRawE.js} +4 -4
  82. package/dist/{llm-judge-Cc8vDJh_.js.map → llm-judge-3uAeRawE.js.map} +1 -1
  83. package/dist/{matrix-Cf-AGxGh.d.ts → matrix-BXo3PSqM.d.ts} +2 -2
  84. package/dist/{matrix-Cf-AGxGh.d.ts.map → matrix-BXo3PSqM.d.ts.map} +1 -1
  85. package/dist/meta-eval/index.d.ts +3 -638
  86. package/dist/meta-eval/index.js +3 -193
  87. package/dist/meta-eval/index.js.map +1 -1
  88. package/dist/multishot/golden/index.d.ts +1 -1
  89. package/dist/multishot/index.d.ts +2 -2
  90. package/dist/openapi.json +1 -1
  91. package/dist/outcome-observations-FLmRpgYa.js +78 -0
  92. package/dist/outcome-observations-FLmRpgYa.js.map +1 -0
  93. package/dist/{paired-arms-Ct4LTKc1.js → paired-arms-B2ttLc0_.js} +108 -31
  94. package/dist/paired-arms-B2ttLc0_.js.map +1 -0
  95. package/dist/{power-and-mde-N5nU4_Ly.js → power-and-mde-CQX-0weG.js} +2 -2
  96. package/dist/{power-and-mde-N5nU4_Ly.js.map → power-and-mde-CQX-0weG.js.map} +1 -1
  97. package/dist/{prime-protocol-CckHBxGu.d.ts → prime-protocol-BEaqBoQE.d.ts} +2 -2
  98. package/dist/{prime-protocol-CckHBxGu.d.ts.map → prime-protocol-BEaqBoQE.d.ts.map} +1 -1
  99. package/dist/{proposal-findings-E1aSC_cU.js → proposal-findings-D0_zkQ2l.js} +2 -2
  100. package/dist/{proposal-findings-E1aSC_cU.js.map → proposal-findings-D0_zkQ2l.js.map} +1 -1
  101. package/dist/{registry-B_yG-1jh.d.ts → registry-DDKaUrmM.d.ts} +3 -3
  102. package/dist/{registry-B_yG-1jh.d.ts.map → registry-DDKaUrmM.d.ts.map} +1 -1
  103. package/dist/{render-Cs34y0iX.js → render-BhJqXoBH.js} +15 -11
  104. package/dist/render-BhJqXoBH.js.map +1 -0
  105. package/dist/reporting.d.ts +1 -1
  106. package/dist/reporting.js +3 -3
  107. package/dist/rl.d.ts +4 -5
  108. package/dist/rl.d.ts.map +1 -1
  109. package/dist/rl.js +5 -4
  110. package/dist/rl.js.map +1 -1
  111. package/dist/{rubric-predictive-validity-noY7uE03.d.ts → rubric-predictive-validity-Cd5SCtAf.d.ts} +58 -3
  112. package/dist/rubric-predictive-validity-Cd5SCtAf.d.ts.map +1 -0
  113. package/dist/{rubric-predictive-validity-D3_oI72N.js → rubric-predictive-validity-CeKW2GQN.js} +3 -77
  114. package/dist/rubric-predictive-validity-CeKW2GQN.js.map +1 -0
  115. package/dist/search/index.d.ts +2 -2
  116. package/dist/{search-kernel-Dloxd6gs.d.ts → search-kernel-C6__V0IS.d.ts} +2 -2
  117. package/dist/{search-kernel-Dloxd6gs.d.ts.map → search-kernel-C6__V0IS.d.ts.map} +1 -1
  118. package/dist/{skillopt-optimization-method-DLKqdhcR.js → skillopt-optimization-method-D21dH_Bh.js} +4 -4
  119. package/dist/{skillopt-optimization-method-DLKqdhcR.js.map → skillopt-optimization-method-D21dH_Bh.js.map} +1 -1
  120. package/dist/{statistical-heldout-3z3I-kJN.d.ts → statistical-heldout-pD1Yah-0.d.ts} +58 -8
  121. package/dist/statistical-heldout-pD1Yah-0.d.ts.map +1 -0
  122. package/dist/{store-otlp-dyWE3wAG.js → store-otlp-BVZfR168.js} +2 -2
  123. package/dist/{store-otlp-dyWE3wAG.js.map → store-otlp-BVZfR168.js.map} +1 -1
  124. package/dist/{store-tool-spans-DIUgZbzu.js → store-tool-spans-CjYiF4fF.js} +3 -3
  125. package/dist/{store-tool-spans-DIUgZbzu.js.map → store-tool-spans-CjYiF4fF.js.map} +1 -1
  126. package/dist/{store-tool-spans-DPwXHQkH.d.ts → store-tool-spans-DfnwWMFR.d.ts} +4 -4
  127. package/dist/{store-tool-spans-DPwXHQkH.d.ts.map → store-tool-spans-DfnwWMFR.d.ts.map} +1 -1
  128. package/dist/{summary-report-BsXJoYX5.js → summary-report-DHDWxe6p.js} +3 -3
  129. package/dist/{summary-report-BsXJoYX5.js.map → summary-report-DHDWxe6p.js.map} +1 -1
  130. package/dist/supervisor-run/index.d.ts +6 -5
  131. package/dist/supervisor-run/index.d.ts.map +1 -1
  132. package/dist/supervisor-run/index.js +3 -3
  133. package/dist/systemone-D3MrW63C.d.ts +400 -0
  134. package/dist/systemone-D3MrW63C.d.ts.map +1 -0
  135. package/dist/{systemone-protocol-DKoi1NdK.d.ts → systemone-protocol-Bl2EI2KQ.d.ts} +4 -2
  136. package/dist/{systemone-protocol-DKoi1NdK.d.ts.map → systemone-protocol-Bl2EI2KQ.d.ts.map} +1 -1
  137. package/dist/systemone-protocol.d.ts +2 -2
  138. package/dist/systemone-protocol.js +7 -7
  139. package/dist/systemone-protocol.js.map +1 -1
  140. package/dist/{systemone-review-CUBMuTLi.d.ts → systemone-review-C8DRiT_-.d.ts} +3 -3
  141. package/dist/{systemone-review-CUBMuTLi.d.ts.map → systemone-review-C8DRiT_-.d.ts.map} +1 -1
  142. package/dist/{systemone-review-DzdOJ8I6.js → systemone-review-DFGtIUcf.js} +2 -2
  143. package/dist/{systemone-review-DzdOJ8I6.js.map → systemone-review-DFGtIUcf.js.map} +1 -1
  144. package/dist/systemone.d.ts +5 -5
  145. package/dist/systemone.js +5 -343
  146. package/dist/{terminal-record-D4Rv-j1W.js → terminal-record-CB9BFtjS.js} +77 -29
  147. package/dist/terminal-record-CB9BFtjS.js.map +1 -0
  148. package/dist/{tool-groups-LISbBWCg.d.ts → tool-groups-DK1bu5TD.d.ts} +3 -3
  149. package/dist/tool-groups-DK1bu5TD.d.ts.map +1 -0
  150. package/dist/{trace-questions-C42fYEE4.d.ts → trace-questions-D_OKYZ6u.d.ts} +3 -3
  151. package/dist/{trace-questions-C42fYEE4.d.ts.map → trace-questions-D_OKYZ6u.d.ts.map} +1 -1
  152. package/dist/trace-repair/index.d.ts +1 -1
  153. package/dist/traces.d.ts +3 -3
  154. package/dist/traces.js +3 -3
  155. package/dist/{types-DqFMNTgK.js → types-CnWmj8NW.js} +19 -6
  156. package/dist/types-CnWmj8NW.js.map +1 -0
  157. package/dist/{types-CHfn1zg5.d.ts → types-DDKfH-N6.d.ts} +2 -2
  158. package/dist/{types-CHfn1zg5.d.ts.map → types-DDKfH-N6.d.ts.map} +1 -1
  159. package/dist/{types-8yQzNm8u.d.ts → types-DGImvHIr.d.ts} +150 -4
  160. package/dist/types-DGImvHIr.d.ts.map +1 -0
  161. package/dist/{types-D8GXK9Z5.d.ts → types-IERw_HxR.d.ts} +2 -2
  162. package/dist/{types-D8GXK9Z5.d.ts.map → types-IERw_HxR.d.ts.map} +1 -1
  163. package/dist/wire/index.d.ts +1 -1
  164. package/docs/behavioral-trace-questions.md +99 -0
  165. package/docs/experiment.md +27 -0
  166. package/docs/finding-layers.md +54 -1
  167. package/docs/rollout.md +9 -0
  168. package/docs/systemone.md +107 -0
  169. package/package.json +1 -1
  170. package/dist/benchmark-command-BzmMTnvC.js.map +0 -1
  171. package/dist/default-registry-BrKmT01n.js.map +0 -1
  172. package/dist/default-registry-Cwg_QN3d.d.ts +0 -70
  173. package/dist/default-registry-Cwg_QN3d.d.ts.map +0 -1
  174. package/dist/evaluation.js.map +0 -1
  175. package/dist/index-CVFStrQD.d.ts.map +0 -1
  176. package/dist/judge-gate-Dc_mXQsL.d.ts +0 -453
  177. package/dist/judge-gate-Dc_mXQsL.d.ts.map +0 -1
  178. package/dist/meta-eval/index.d.ts.map +0 -1
  179. package/dist/outcome-store-CNt4iZ67.d.ts +0 -58
  180. package/dist/outcome-store-CNt4iZ67.d.ts.map +0 -1
  181. package/dist/paired-arms-Ct4LTKc1.js.map +0 -1
  182. package/dist/render-Cs34y0iX.js.map +0 -1
  183. package/dist/rubric-predictive-validity-D3_oI72N.js.map +0 -1
  184. package/dist/rubric-predictive-validity-noY7uE03.d.ts.map +0 -1
  185. package/dist/statistical-heldout-3z3I-kJN.d.ts.map +0 -1
  186. package/dist/systemone-DVA7t76V.d.ts +0 -135
  187. package/dist/systemone-DVA7t76V.d.ts.map +0 -1
  188. package/dist/systemone.js.map +0 -1
  189. package/dist/terminal-record-D4Rv-j1W.js.map +0 -1
  190. package/dist/tool-groups-LISbBWCg.d.ts.map +0 -1
  191. package/dist/types-8yQzNm8u.d.ts.map +0 -1
  192. package/dist/types-DqFMNTgK.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"dspy-rlm-engine-Bn_Mt_LW.js","names":[],"sources":["../src/analyst/finding-codec.ts","../src/analyst/trace-tool-callback.ts","../src/analyst/dspy-rlm-engine.ts"],"sourcesContent":["/**\n * The raw-finding wire contract — one decoder for both sides of the process\n * boundary.\n *\n * A finding array crosses a process boundary twice: an optimizer bridge writes\n * it in Python, TypeScript reads it back. Two decoders written independently\n * accept different shapes, so Python could report a completed investigation\n * whose rows TypeScript then dropped — the paid work disappearing between two\n * \"successes\". This module is the TypeScript half; `finding_contract.json`\n * carries the same rules to the Python half, generated from the schema here.\n *\n * Decoding never invents an empty result. A value that is not an array of rows\n * fails with the exact type it was, and a malformed row is reported with its\n * index and path while its valid siblings survive.\n */\n\nimport { type RawAnalystFinding, RawAnalystFindingSchema } from './finding-signature'\nimport { parseFindingSubject } from './finding-subject'\nimport { coerceJson } from './parse-tolerant'\n\n/**\n * Version of the wire contract both languages implement. Bump when the\n * accepted row shape changes; the Python package pins the same value, and the\n * emitted contract carries it so a mismatched pair is visible.\n */\nexport const FINDING_WIRE_CONTRACT_VERSION = 1\n\n/** Why one row was refused. Stable across languages: Python reports the same codes. */\ntype FindingRejectionCode = 'not-an-object' | 'schema' | 'invalid-subject' | 'row-limit'\n\n/** A refused row, named precisely enough to repair or report. */\ninterface RejectedFindingRow {\n /** Position in the submitted array. */\n readonly index: number\n /** Dotted path to the offending field, `''` for the row itself. */\n readonly path: string\n readonly code: FindingRejectionCode\n readonly message: string\n}\n\ninterface DecodedFindingArray {\n readonly accepted: RawAnalystFinding[]\n readonly rejected: RejectedFindingRow[]\n /**\n * Set when the value was not a finding array at all — the array itself is\n * the failure, so `accepted` and `rejected` are both empty and a caller must\n * not read the result as \"no findings\".\n */\n readonly topLevelError?: string\n}\n\n/**\n * Rows past this count are refused rather than validated. A model that emits\n * thousands of rows has lost the plot, and the diagnostics for them would\n * dwarf the answer they came with.\n */\nexport const MAX_FINDING_ROWS = 500\n\n/**\n * Decode a submitted findings value into accepted rows plus per-row\n * diagnostics.\n *\n * Accepts an array of rows, or a string carrying one (a JSON array, possibly\n * fenced). Anything else — an object, a number, null, undefined — sets\n * `topLevelError` naming the type received: a caller that asked for findings\n * and got a number has a defect to report, not an empty result to record.\n */\nexport function decodeRawFindingArray(value: unknown): DecodedFindingArray {\n const rows = findingRows(value)\n if (typeof rows === 'string') return { accepted: [], rejected: [], topLevelError: rows }\n\n const accepted: RawAnalystFinding[] = []\n const rejected: RejectedFindingRow[] = []\n for (const [index, row] of rows.entries()) {\n if (index >= MAX_FINDING_ROWS) {\n rejected.push({\n index,\n path: '',\n code: 'row-limit',\n message: `findings array exceeds ${MAX_FINDING_ROWS} rows`,\n })\n continue\n }\n const decoded = decodeRow(row, index)\n if ('finding' in decoded) accepted.push(decoded.finding)\n else rejected.push(decoded.rejection)\n }\n return { accepted, rejected }\n}\n\nfunction decodeRow(\n row: unknown,\n index: number,\n): { finding: RawAnalystFinding } | { rejection: RejectedFindingRow } {\n if (row === null || typeof row !== 'object' || Array.isArray(row)) {\n return {\n rejection: {\n index,\n path: '',\n code: 'not-an-object',\n message: `finding row must be an object, received ${describe(row)}`,\n },\n }\n }\n const parsed = RawAnalystFindingSchema.safeParse(row)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n const path = (issue?.path ?? []).join('.')\n // The schema refines `subject` against the grammar; name that refusal\n // separately so a repair turn can be told which rule the row broke.\n const code: FindingRejectionCode =\n path === 'subject' && parseFindingSubject((row as { subject?: string }).subject) === null\n ? 'invalid-subject'\n : 'schema'\n return {\n rejection: { index, path, code, message: issue?.message ?? 'row does not match the schema' },\n }\n }\n return { finding: parsed.data }\n}\n\n/**\n * Narrow a submitted value to candidate rows, or return the message naming why\n * it is not a findings array at all.\n */\nfunction findingRows(value: unknown): unknown[] | string {\n if (Array.isArray(value)) return value\n if (typeof value === 'string') {\n const parsed = coerceJson(value)\n if (parsed === undefined) {\n return 'findings must be a JSON array; the string received is not JSON'\n }\n if (Array.isArray(parsed)) return parsed\n const unwrapped = findingsProperty(parsed)\n if (unwrapped !== undefined) return unwrapped\n return `findings must be a JSON array, received ${describe(parsed)}`\n }\n const unwrapped = findingsProperty(value)\n if (unwrapped !== undefined) return unwrapped\n return `findings must be an array, received ${describe(value)}`\n}\n\n/** `{ findings: [...] }` is the one wrapper models emit often enough to unwrap. */\nfunction findingsProperty(value: unknown): unknown[] | undefined {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined\n const inner = (value as Record<string, unknown>).findings\n return Array.isArray(inner) ? inner : undefined\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (Array.isArray(value)) return 'an array'\n return `a ${typeof value}`\n}\n\n\n","import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport {\n type ExternalOptimizerCallbackLimits,\n resolveExternalOptimizerCallbackLimits,\n} from '../campaign/external-optimizer-contracts'\nimport {\n closeServer,\n listenLocal,\n sendJsonIfOpen,\n waitForActiveHandlers,\n} from '../campaign/external-optimizer-http'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\n\nimport { isRecord } from '../llm-client/json'\ninterface TraceToolCallback {\n url: string\n token: string\n calls: () => number\n close: () => Promise<void>\n}\n\nexport type TraceToolCallbackLimits = ExternalOptimizerCallbackLimits\n\n/** Expose one bounded trace-tool set only on an authenticated loopback socket. */\nexport async function startTraceToolCallback(args: {\n tools: readonly TraceAnalysisToolDescriptor[]\n maxCalls: number\n /** Trace-tool request/response byte limits. Omitted fields use finite defaults. */\n limits?: Partial<TraceToolCallbackLimits>\n signal?: AbortSignal\n}): Promise<TraceToolCallback> {\n if (!Number.isSafeInteger(args.maxCalls) || args.maxCalls <= 0) {\n throw new TypeError('trace tool callback maxCalls must be a positive safe integer')\n }\n const limits = resolveExternalOptimizerCallbackLimits(args.limits, 'trace tool callback limits')\n args.signal?.throwIfAborted()\n const byName = new Map(args.tools.map((tool) => [tool.name, tool]))\n if (byName.size !== args.tools.length) {\n throw new Error('trace tool callback received duplicate tool names')\n }\n\n const token = randomBytes(32).toString('hex')\n let calls = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'trace tool callback is closing' })\n return\n }\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleRequest(request, response, controller.signal).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeCallback()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n\n return {\n url: `http://127.0.0.1:${port}/call`,\n token,\n calls: () => calls,\n close,\n }\n\n async function handleRequest(\n request: IncomingMessage,\n response: ServerResponse,\n signal: AbortSignal,\n ): Promise<void> {\n try {\n if (request.method !== 'POST' || request.url !== '/call') {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n if (calls >= args.maxCalls) {\n sendJsonIfOpen(response, 429, { error: 'trace tool call limit reached' })\n return\n }\n const body = await readJson(request, limits.maxRequestBytes)\n if (!isRecord(body) || typeof body.name !== 'string' || !('args' in body)) {\n sendJsonIfOpen(response, 400, { error: 'name and args are required' })\n return\n }\n const tool = byName.get(body.name)\n if (!tool) {\n sendJsonIfOpen(response, 404, { error: `unknown trace tool '${body.name}'` })\n return\n }\n calls += 1\n const result = await tool.handler(body.args, { signal })\n const encoded = JSON.stringify({ result })\n if (Buffer.byteLength(encoded) > limits.maxResponseBytes) {\n sendJsonIfOpen(response, 413, { error: 'trace tool response too large' })\n return\n }\n response.writeHead(200, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': String(Buffer.byteLength(encoded)),\n })\n response.end(encoded)\n } catch (error) {\n sendJsonIfOpen(response, signal.aborted ? 499 : 400, {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n async function closeCallback(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('trace tool callback closed with active requests')\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n }\n}\n\nfunction readJson(request: IncomingMessage, maxRequestBytes: number): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > maxRequestBytes) {\n reject(new Error('trace tool request too large'))\n request.destroy()\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n","import {\n assertExternalOptimizerModelBudget,\n type ExternalOptimizerModelCall,\n type ExternalOptimizerModelExecutionObservation,\n type ExternalOptimizerModelProxy,\n type ExternalOptimizerRunnerCommand,\n removeCredentialEnvironment,\n resolveExternalOptimizerCallbackLimits,\n resolveExternalOptimizerProcessLimits,\n} from '../campaign/external-optimizer-contracts'\nimport { startExternalOptimizerModelProxy } from '../campaign/external-optimizer-model-proxy'\nimport { runWithCleanup } from '../campaign/external-optimizer-resources'\nimport { runExternalOptimizerProcess } from '../campaign/external-optimizer-subprocess'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { resolveModelPricing } from '../metrics'\nimport {\n DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS,\n type TraceAnalysisEngine,\n type TraceAnalysisEngineResult,\n} from './engine'\nimport { decodeRawFindingArray } from './finding-codec'\nimport { startTraceToolCallback, type TraceToolCallbackLimits } from './trace-tool-callback'\n\nimport { isRecord } from '../llm-client/json'\nconst DEFAULT_TIMEOUT_MS = 10 * 60_000\nconst DEFAULT_MAX_COST_USD = 1\nconst DEFAULT_MAX_MODEL_REQUEST_BYTES = 16 * 1024 * 1024\nconst DEFAULT_MAX_MODEL_RESPONSE_BYTES = 4 * 1024 * 1024\nconst DEFAULT_TRACE_TOOL_TIMEOUT_MS = 60_000\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\nconst BRIDGE_MODULE = 'agent_eval_rpc.dspy_rlm_bridge'\n/** Bumped whenever this engine's execution behavior changes. */\nconst DSPY_RLM_ENGINE_VERSION = '1.0.0'\n\nexport interface DspyRlmTraceEngineOptions {\n /** Caller-owned execution path. Agent Eval never receives provider credentials. */\n call: ExternalOptimizerModelCall\n /** Stable public identity for the caller-owned path, such as an AgentProfile digest. */\n callRef: string\n /** Persist the finite execution record returned for every admitted call. */\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n /** Exact provider rates. Required when the model is absent from the pricing table. */\n pricing?: CustomTokenPricing\n /** Maximum provider spend for one investigation. Default: 1 USD. */\n maxCostUsd?: number\n /** Controller response cap. Default: {@link DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS}. */\n maxOutputTokens?: number\n /**\n * Thinking tokens one controller turn may bill on top of its completion.\n * A reasoning model bills these beyond `maxOutputTokens`, so the cost\n * reservation must cover them. Default: four times the completion cap.\n */\n maxReasoningTokens?: number\n /** Maximum caller-owned model invocations. Default derives from the analysis limits. */\n maxModelRequests?: number\n /** Maximum model request bytes. Default: 16 MiB. */\n maxModelRequestBytes?: number\n /** Maximum model response bytes. Default: 4 MiB. */\n maxModelResponseBytes?: number\n /** Deadline for one caller-owned model invocation. Default: the whole analysis deadline. */\n modelRequestTimeoutMs?: number\n /** Trace-tool loopback request/response byte limits. */\n traceToolLimits?: Partial<TraceToolCallbackLimits>\n /** Deadline for one Python-to-Node trace-tool call. Default: 60 seconds. */\n traceToolTimeoutMs?: number\n /**\n * How the controller's reasoning and code fields are obtained.\n *\n * `tolerant` parses marker output strictly first, then recovers the fields\n * deterministically from prose plus a fenced code block — the shape coding\n * models naturally emit — at no extra model cost. `two-step` extracts with a\n * second call per turn. `chat` accepts marker output only. Default:\n * `tolerant`.\n */\n controlAdapter?: 'chat' | 'two-step' | 'tolerant'\n /** Python command used to load agent-eval-rpc[dspy]. Default: python. */\n runner?: ExternalOptimizerRunnerCommand\n /** Whole investigation deadline. Default: 10 minutes. */\n timeoutMs?: number\n}\n\n/** Use the official DSPy RLM as a bounded recursive trace-analysis engine. */\nexport function createDspyRlmTraceEngine(options: DspyRlmTraceEngineOptions): TraceAnalysisEngine {\n assertOptions(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('DSPy RLM maxOutputTokens must be a positive safe integer')\n }\n const controlAdapter = options.controlAdapter ?? 'tolerant'\n const maxReasoningTokens = options.maxReasoningTokens ?? maxOutputTokens * 4\n if (!Number.isSafeInteger(maxReasoningTokens) || maxReasoningTokens < 0) {\n throw new TypeError('DSPy RLM maxReasoningTokens must be a non-negative safe integer')\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n assertTimerDelay(timeoutMs, 'timeoutMs')\n const maxCostUsd = options.maxCostUsd ?? DEFAULT_MAX_COST_USD\n if (!Number.isFinite(maxCostUsd) || maxCostUsd <= 0) {\n throw new TypeError('DSPy RLM maxCostUsd must be positive and finite')\n }\n const pricing = options.pricing ?? pricingForModel(options.model)\n const maxModelRequestBytes = options.maxModelRequestBytes ?? DEFAULT_MAX_MODEL_REQUEST_BYTES\n const maxModelResponseBytes = options.maxModelResponseBytes ?? DEFAULT_MAX_MODEL_RESPONSE_BYTES\n const modelRequestTimeoutMs = options.modelRequestTimeoutMs ?? timeoutMs\n const traceToolTimeoutMs = options.traceToolTimeoutMs ?? DEFAULT_TRACE_TOOL_TIMEOUT_MS\n assertExternalOptimizerModelBudget(\n {\n maxCostUsd,\n maxRequests: options.maxModelRequests ?? 1,\n maxRequestBytes: maxModelRequestBytes,\n maxResponseBytes: maxModelResponseBytes,\n maxOutputTokensPerRequest: maxOutputTokens,\n maxReasoningTokensPerRequest: maxReasoningTokens,\n pricing,\n requestTimeoutMs: modelRequestTimeoutMs,\n },\n 'DSPy RLM model limits',\n )\n resolveExternalOptimizerCallbackLimits(options.traceToolLimits, 'DSPy RLM trace tool limits')\n assertTimerDelay(traceToolTimeoutMs, 'traceToolTimeoutMs')\n\n const runner = sanitizedRunner(options.runner)\n const processLimits = resolveExternalOptimizerProcessLimits(runner?.limits)\n return {\n id: 'dspy-rlm',\n description: 'Official DSPy RLM with bounded trace tools and metered model calls.',\n model: options.model,\n version: DSPY_RLM_ENGINE_VERSION,\n executionConfig: {\n bridge_module: BRIDGE_MODULE,\n call_ref: options.callRef,\n model: options.model,\n pricing: { ...pricing },\n max_cost_usd: maxCostUsd,\n max_output_tokens: maxOutputTokens,\n max_reasoning_tokens: maxReasoningTokens,\n control_adapter: controlAdapter,\n timeout_ms: timeoutMs,\n max_model_requests: options.maxModelRequests ?? null,\n max_request_bytes: maxModelRequestBytes,\n max_response_bytes: maxModelResponseBytes,\n model_request_timeout_ms: modelRequestTimeoutMs,\n trace_tool_limits: options.traceToolLimits ?? null,\n trace_tool_timeout_ms: traceToolTimeoutMs,\n process_limits: processLimits,\n runner: runner ? 'caller-supplied' : 'default',\n runner_command: runner?.command ?? null,\n },\n async analyze(request) {\n const callback = await startTraceToolCallback({\n tools: request.tools,\n maxCalls: request.limits.maxToolCalls,\n ...(options.traceToolLimits ? { limits: options.traceToolLimits } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n let modelProxy: ExternalOptimizerModelProxy | undefined\n const modelExecutions: ExternalOptimizerModelExecutionObservation[] = []\n const result = await runWithCleanup({\n label: 'DSPy RLM trace-analysis resources',\n run: async () => {\n modelProxy = await startExternalOptimizerModelProxy({\n call: options.call,\n callRef: options.callRef,\n recordExecution: (observation) => {\n modelExecutions.push(structuredClone(observation))\n options.recordExecution(observation)\n },\n model: options.model,\n budget: {\n maxCostUsd,\n maxRequests: resolveMaxModelRequests(options.maxModelRequests, request.limits),\n maxRequestBytes: maxModelRequestBytes,\n maxResponseBytes: maxModelResponseBytes,\n maxOutputTokensPerRequest: maxOutputTokens,\n maxReasoningTokensPerRequest: maxReasoningTokens,\n requestTimeoutMs: modelRequestTimeoutMs,\n pricing,\n },\n costLedger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n request.log?.('trace analyst engine started', {\n engine: 'dspy-rlm',\n model: options.model,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n const raw = await runExternalOptimizerProcess<unknown>({\n label: 'DSPy RLM trace analysis',\n tempPrefix: 'agent-eval-dspy-rlm-',\n module: BRIDGE_MODULE,\n input: {\n operation: 'analyze',\n question: request.question,\n instructions: request.instructions,\n modelProxy: {\n baseUrl: modelProxy.baseUrl,\n apiKey: modelProxy.apiKey,\n model: options.model,\n maxOutputTokens,\n },\n toolCallback: {\n url: callback.url,\n token: callback.token,\n timeoutMs: traceToolTimeoutMs,\n },\n toolSpecs: request.tools.map(({ name, description, parameters }) => ({\n name,\n description,\n parameters,\n })),\n controlAdapter,\n limits: {\n maxIterations: request.limits.maxIterations,\n maxLlmCalls: request.limits.maxLlmCalls,\n maxOutputChars: request.limits.maxOutputChars,\n },\n // Omitted entirely when the caller supplied none, so a request\n // without structured inputs sends the payload it always sent.\n ...(request.taskInputs ? { taskInputs: request.taskInputs } : {}),\n },\n ...(runner ? { runner } : {}),\n additionalArgs: ['--max-input-bytes', String(processLimits.maxInputBytes)],\n timeoutMs,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n const parsed = parseBridgeOutput(raw, (index, reason) => {\n request.log?.('finding rejected: bridge row failed schema validation', {\n engine: 'dspy-rlm',\n index,\n reason,\n })\n })\n const successfulCompletions = modelProxy.successfulCompletions()\n const requestAttempts = modelProxy.requestAttempts()\n if (parsed.modelCalls !== successfulCompletions) {\n throw new Error(\n `DSPy RLM reported ${parsed.modelCalls} model calls, but the provider proxy recorded ${successfulCompletions}`,\n )\n }\n modelProxy.assertExecutionComplete()\n return {\n ...parsed,\n toolCalls: callback.calls(),\n runtime: {\n ...parsed.runtime,\n modelRequestAttempts: requestAttempts,\n modelSuccessfulCompletions: successfulCompletions,\n modelExecutions,\n },\n } satisfies TraceAnalysisEngineResult\n },\n cleanup: async () => {\n const results = await Promise.allSettled([\n ...(modelProxy ? [modelProxy.close()] : []),\n callback.close(),\n ])\n const errors = results.flatMap((entry) =>\n entry.status === 'rejected' ? [entry.reason] : [],\n )\n if (errors.length > 0) {\n throw new AggregateError(errors, 'DSPy RLM resource cleanup failed')\n }\n },\n })\n request.log?.('trace analyst engine completed', {\n engine: 'dspy-rlm',\n model_calls: result.modelCalls,\n model_request_attempts: result.runtime.modelRequestAttempts,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n },\n }\n}\n\nfunction parseBridgeOutput(\n value: unknown,\n onRejectedFinding: (index: number, reason: string) => void,\n): Omit<TraceAnalysisEngineResult, 'toolCalls'> {\n if (!isRecord(value)) throw new Error('DSPy RLM bridge output must be an object')\n if (typeof value.answer !== 'string' || !value.answer.trim()) {\n throw new Error('DSPy RLM bridge returned no answer')\n }\n // Findings are model output: one malformed row is model noise, not a bridge\n // fault, and the rest of the paid investigation must survive it. The codec\n // is the same decoder the Python side runs, so a row this bridge accepts is\n // a row the optimizer could report, and vice versa.\n const decoded = decodeRawFindingArray(value.findings)\n if (decoded.topLevelError !== undefined) {\n throw new Error(`DSPy RLM bridge findings must be an array: ${decoded.topLevelError}`)\n }\n const findings = decoded.accepted\n const rejectedFindings = decoded.rejected.length\n for (const rejection of decoded.rejected) {\n onRejectedFinding(\n rejection.index,\n `${rejection.code}${rejection.path ? ` at ${rejection.path}` : ''}: ${rejection.message}`,\n )\n }\n if (!Array.isArray(value.trajectory)) {\n throw new Error('DSPy RLM bridge trajectory must be an array')\n }\n if (!Number.isSafeInteger(value.modelCalls) || (value.modelCalls as number) <= 0) {\n throw new Error('DSPy RLM bridge modelCalls must be a positive safe integer')\n }\n if (!isRecord(value.runtime)) {\n throw new Error('DSPy RLM bridge runtime must be an object')\n }\n return {\n answer: value.answer,\n findings,\n trajectory: value.trajectory,\n modelCalls: value.modelCalls as number,\n runtime: { ...value.runtime, rejectedFindings },\n }\n}\n\nfunction assertOptions(options: DspyRlmTraceEngineOptions): void {\n for (const [name, value] of [\n ['callRef', options.callRef],\n ['model', options.model],\n ] as const) {\n if (typeof value !== 'string' || !value.trim() || value !== value.trim()) {\n throw new TypeError(`DSPy RLM ${name} must be a trimmed non-empty string`)\n }\n }\n if (typeof options.call !== 'function') {\n throw new TypeError('DSPy RLM call must be a function')\n }\n if (typeof options.recordExecution !== 'function') {\n throw new TypeError('DSPy RLM recordExecution must be a function')\n }\n if (\n options.maxModelRequests !== undefined &&\n (!Number.isSafeInteger(options.maxModelRequests) || options.maxModelRequests <= 0)\n ) {\n throw new TypeError('DSPy RLM maxModelRequests must be a positive safe integer')\n }\n}\n\nfunction resolveMaxModelRequests(\n configured: number | undefined,\n limits: { maxIterations: number; maxLlmCalls: number },\n): number {\n if (configured !== undefined) return configured\n const derived = limits.maxIterations + limits.maxLlmCalls + 1\n if (!Number.isSafeInteger(derived) || derived <= 0) {\n throw new Error('DSPy RLM analysis limits produce an invalid model request limit')\n }\n return derived\n}\n\nfunction assertTimerDelay(value: number, field: string): void {\n if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {\n throw new TypeError(`DSPy RLM ${field} must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n}\n\nfunction pricingForModel(model: string): CustomTokenPricing {\n const pricing = resolveModelPricing(model)\n if (!pricing) {\n throw new Error(\n `no pricing is configured for '${model}'; provide DspyRlmTraceEngineOptions.pricing`,\n )\n }\n return {\n inputUsdPerMillion: pricing.input * 1_000,\n outputUsdPerMillion: pricing.output * 1_000,\n }\n}\n\nfunction sanitizedRunner(\n runner: ExternalOptimizerRunnerCommand | undefined,\n): ExternalOptimizerRunnerCommand | undefined {\n if (!runner) return undefined\n return {\n ...(runner.command ? { command: runner.command } : {}),\n ...(runner.args ? { args: runner.args } : {}),\n ...(runner.env ? { env: removeCredentialEnvironment(runner.env) } : {}),\n ...(runner.limits ? { limits: { ...runner.limits } } : {}),\n }\n}\n\n"],"mappings":";;;;;;;;;;;;;;;AAmEA,SAAgB,sBAAsB,OAAqC;CACzE,MAAM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c,KAAK,KAAK,SAAS,KAAK,QAAQ,oBACxD,MAAM,IAAI,UAAU,YAAY,MAAM,yBAAyB,oBAAoB;AAEvF;AAEA,SAAS,gBAAgB,OAAmC;CAC1D,MAAM,UAAU,oBAAoB,KAAK;CACzC,IAAI,CAAC,SACH,MAAM,IAAI,MACR,iCAAiC,MAAM,6CACzC;CAEF,OAAO;EACL,oBAAoB,QAAQ,QAAQ;EACpC,qBAAqB,QAAQ,SAAS;CACxC;AACF;AAEA,SAAS,gBACP,QAC4C;CAC5C,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,OAAO;EACL,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;EACpD,GAAI,OAAO,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;EAC3C,GAAI,OAAO,MAAM,EAAE,KAAK,4BAA4B,OAAO,GAAG,EAAE,IAAI,CAAC;EACrE,GAAI,OAAO,SAAS,EAAE,QAAQ,EAAE,GAAG,OAAO,OAAO,EAAE,IAAI,CAAC;CAC1D;AACF"}
1
+ {"version":3,"file":"dspy-rlm-engine-BTy7u0jQ.js","names":[],"sources":["../src/analyst/finding-codec.ts","../src/analyst/trace-tool-callback.ts","../src/analyst/dspy-rlm-engine.ts"],"sourcesContent":["/**\n * The raw-finding wire contract — one decoder for both sides of the process\n * boundary.\n *\n * A finding array crosses a process boundary twice: an optimizer bridge writes\n * it in Python, TypeScript reads it back. Two decoders written independently\n * accept different shapes, so Python could report a completed investigation\n * whose rows TypeScript then dropped — the paid work disappearing between two\n * \"successes\". This module is the TypeScript half; `finding_contract.json`\n * carries the same rules to the Python half, generated from the schema here.\n *\n * Decoding never invents an empty result. A value that is not an array of rows\n * fails with the exact type it was, and a malformed row is reported with its\n * index and path while its valid siblings survive.\n */\n\nimport { type RawAnalystFinding, RawAnalystFindingSchema } from './finding-signature'\nimport { parseFindingSubject } from './finding-subject'\nimport { coerceJson } from './parse-tolerant'\n\n/**\n * Version of the wire contract both languages implement. Bump when the\n * accepted row shape changes; the Python package pins the same value, and the\n * emitted contract carries it so a mismatched pair is visible.\n */\nexport const FINDING_WIRE_CONTRACT_VERSION = 1\n\n/** Why one row was refused. Stable across languages: Python reports the same codes. */\ntype FindingRejectionCode = 'not-an-object' | 'schema' | 'invalid-subject' | 'row-limit'\n\n/** A refused row, named precisely enough to repair or report. */\ninterface RejectedFindingRow {\n /** Position in the submitted array. */\n readonly index: number\n /** Dotted path to the offending field, `''` for the row itself. */\n readonly path: string\n readonly code: FindingRejectionCode\n readonly message: string\n}\n\ninterface DecodedFindingArray {\n readonly accepted: RawAnalystFinding[]\n readonly rejected: RejectedFindingRow[]\n /**\n * Set when the value was not a finding array at all — the array itself is\n * the failure, so `accepted` and `rejected` are both empty and a caller must\n * not read the result as \"no findings\".\n */\n readonly topLevelError?: string\n}\n\n/**\n * Rows past this count are refused rather than validated. A model that emits\n * thousands of rows has lost the plot, and the diagnostics for them would\n * dwarf the answer they came with.\n */\nexport const MAX_FINDING_ROWS = 500\n\n/**\n * Decode a submitted findings value into accepted rows plus per-row\n * diagnostics.\n *\n * Accepts an array of rows, or a string carrying one (a JSON array, possibly\n * fenced). Anything else — an object, a number, null, undefined — sets\n * `topLevelError` naming the type received: a caller that asked for findings\n * and got a number has a defect to report, not an empty result to record.\n */\nexport function decodeRawFindingArray(value: unknown): DecodedFindingArray {\n const rows = findingRows(value)\n if (typeof rows === 'string') return { accepted: [], rejected: [], topLevelError: rows }\n\n const accepted: RawAnalystFinding[] = []\n const rejected: RejectedFindingRow[] = []\n for (const [index, row] of rows.entries()) {\n if (index >= MAX_FINDING_ROWS) {\n rejected.push({\n index,\n path: '',\n code: 'row-limit',\n message: `findings array exceeds ${MAX_FINDING_ROWS} rows`,\n })\n continue\n }\n const decoded = decodeRow(row, index)\n if ('finding' in decoded) accepted.push(decoded.finding)\n else rejected.push(decoded.rejection)\n }\n return { accepted, rejected }\n}\n\nfunction decodeRow(\n row: unknown,\n index: number,\n): { finding: RawAnalystFinding } | { rejection: RejectedFindingRow } {\n if (row === null || typeof row !== 'object' || Array.isArray(row)) {\n return {\n rejection: {\n index,\n path: '',\n code: 'not-an-object',\n message: `finding row must be an object, received ${describe(row)}`,\n },\n }\n }\n const parsed = RawAnalystFindingSchema.safeParse(row)\n if (!parsed.success) {\n const issue = parsed.error.issues[0]\n const path = (issue?.path ?? []).join('.')\n // The schema refines `subject` against the grammar; name that refusal\n // separately so a repair turn can be told which rule the row broke.\n const code: FindingRejectionCode =\n path === 'subject' && parseFindingSubject((row as { subject?: string }).subject) === null\n ? 'invalid-subject'\n : 'schema'\n return {\n rejection: { index, path, code, message: issue?.message ?? 'row does not match the schema' },\n }\n }\n return { finding: parsed.data }\n}\n\n/**\n * Narrow a submitted value to candidate rows, or return the message naming why\n * it is not a findings array at all.\n */\nfunction findingRows(value: unknown): unknown[] | string {\n if (Array.isArray(value)) return value\n if (typeof value === 'string') {\n const parsed = coerceJson(value)\n if (parsed === undefined) {\n return 'findings must be a JSON array; the string received is not JSON'\n }\n if (Array.isArray(parsed)) return parsed\n const unwrapped = findingsProperty(parsed)\n if (unwrapped !== undefined) return unwrapped\n return `findings must be a JSON array, received ${describe(parsed)}`\n }\n const unwrapped = findingsProperty(value)\n if (unwrapped !== undefined) return unwrapped\n return `findings must be an array, received ${describe(value)}`\n}\n\n/** `{ findings: [...] }` is the one wrapper models emit often enough to unwrap. */\nfunction findingsProperty(value: unknown): unknown[] | undefined {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined\n const inner = (value as Record<string, unknown>).findings\n return Array.isArray(inner) ? inner : undefined\n}\n\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (Array.isArray(value)) return 'an array'\n return `a ${typeof value}`\n}\n\n\n","import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport {\n type ExternalOptimizerCallbackLimits,\n resolveExternalOptimizerCallbackLimits,\n} from '../campaign/external-optimizer-contracts'\nimport {\n closeServer,\n listenLocal,\n sendJsonIfOpen,\n waitForActiveHandlers,\n} from '../campaign/external-optimizer-http'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\n\nimport { isRecord } from '../llm-client/json'\ninterface TraceToolCallback {\n url: string\n token: string\n calls: () => number\n close: () => Promise<void>\n}\n\nexport type TraceToolCallbackLimits = ExternalOptimizerCallbackLimits\n\n/** Expose one bounded trace-tool set only on an authenticated loopback socket. */\nexport async function startTraceToolCallback(args: {\n tools: readonly TraceAnalysisToolDescriptor[]\n maxCalls: number\n /** Trace-tool request/response byte limits. Omitted fields use finite defaults. */\n limits?: Partial<TraceToolCallbackLimits>\n signal?: AbortSignal\n}): Promise<TraceToolCallback> {\n if (!Number.isSafeInteger(args.maxCalls) || args.maxCalls <= 0) {\n throw new TypeError('trace tool callback maxCalls must be a positive safe integer')\n }\n const limits = resolveExternalOptimizerCallbackLimits(args.limits, 'trace tool callback limits')\n args.signal?.throwIfAborted()\n const byName = new Map(args.tools.map((tool) => [tool.name, tool]))\n if (byName.size !== args.tools.length) {\n throw new Error('trace tool callback received duplicate tool names')\n }\n\n const token = randomBytes(32).toString('hex')\n let calls = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'trace tool callback is closing' })\n return\n }\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleRequest(request, response, controller.signal).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeCallback()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n\n return {\n url: `http://127.0.0.1:${port}/call`,\n token,\n calls: () => calls,\n close,\n }\n\n async function handleRequest(\n request: IncomingMessage,\n response: ServerResponse,\n signal: AbortSignal,\n ): Promise<void> {\n try {\n if (request.method !== 'POST' || request.url !== '/call') {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n if (calls >= args.maxCalls) {\n sendJsonIfOpen(response, 429, { error: 'trace tool call limit reached' })\n return\n }\n const body = await readJson(request, limits.maxRequestBytes)\n if (!isRecord(body) || typeof body.name !== 'string' || !('args' in body)) {\n sendJsonIfOpen(response, 400, { error: 'name and args are required' })\n return\n }\n const tool = byName.get(body.name)\n if (!tool) {\n sendJsonIfOpen(response, 404, { error: `unknown trace tool '${body.name}'` })\n return\n }\n calls += 1\n const result = await tool.handler(body.args, { signal })\n const encoded = JSON.stringify({ result })\n if (Buffer.byteLength(encoded) > limits.maxResponseBytes) {\n sendJsonIfOpen(response, 413, { error: 'trace tool response too large' })\n return\n }\n response.writeHead(200, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': String(Buffer.byteLength(encoded)),\n })\n response.end(encoded)\n } catch (error) {\n sendJsonIfOpen(response, signal.aborted ? 499 : 400, {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n async function closeCallback(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('trace tool callback closed with active requests')\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n }\n}\n\nfunction readJson(request: IncomingMessage, maxRequestBytes: number): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > maxRequestBytes) {\n reject(new Error('trace tool request too large'))\n request.destroy()\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n","import {\n assertExternalOptimizerModelBudget,\n type ExternalOptimizerModelCall,\n type ExternalOptimizerModelExecutionObservation,\n type ExternalOptimizerModelProxy,\n type ExternalOptimizerRunnerCommand,\n removeCredentialEnvironment,\n resolveExternalOptimizerCallbackLimits,\n resolveExternalOptimizerProcessLimits,\n} from '../campaign/external-optimizer-contracts'\nimport { startExternalOptimizerModelProxy } from '../campaign/external-optimizer-model-proxy'\nimport { runWithCleanup } from '../campaign/external-optimizer-resources'\nimport { runExternalOptimizerProcess } from '../campaign/external-optimizer-subprocess'\nimport type { CustomTokenPricing } from '../cost-ledger'\nimport { resolveModelPricing } from '../metrics'\nimport {\n DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS,\n type TraceAnalysisEngine,\n type TraceAnalysisEngineResult,\n} from './engine'\nimport { decodeRawFindingArray } from './finding-codec'\nimport { startTraceToolCallback, type TraceToolCallbackLimits } from './trace-tool-callback'\n\nimport { isRecord } from '../llm-client/json'\nconst DEFAULT_TIMEOUT_MS = 10 * 60_000\nconst DEFAULT_MAX_COST_USD = 1\nconst DEFAULT_MAX_MODEL_REQUEST_BYTES = 16 * 1024 * 1024\nconst DEFAULT_MAX_MODEL_RESPONSE_BYTES = 4 * 1024 * 1024\nconst DEFAULT_TRACE_TOOL_TIMEOUT_MS = 60_000\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\nconst BRIDGE_MODULE = 'agent_eval_rpc.dspy_rlm_bridge'\n/** Bumped whenever this engine's execution behavior changes. */\nconst DSPY_RLM_ENGINE_VERSION = '1.0.0'\n\nexport interface DspyRlmTraceEngineOptions {\n /** Caller-owned execution path. Agent Eval never receives provider credentials. */\n call: ExternalOptimizerModelCall\n /** Stable public identity for the caller-owned path, such as an AgentProfile digest. */\n callRef: string\n /** Persist the finite execution record returned for every admitted call. */\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n /** Exact provider rates. Required when the model is absent from the pricing table. */\n pricing?: CustomTokenPricing\n /** Maximum provider spend for one investigation. Default: 1 USD. */\n maxCostUsd?: number\n /** Controller response cap. Default: {@link DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS}. */\n maxOutputTokens?: number\n /**\n * Thinking tokens one controller turn may bill on top of its completion.\n * A reasoning model bills these beyond `maxOutputTokens`, so the cost\n * reservation must cover them. Default: four times the completion cap.\n */\n maxReasoningTokens?: number\n /** Maximum caller-owned model invocations. Default derives from the analysis limits. */\n maxModelRequests?: number\n /** Maximum model request bytes. Default: 16 MiB. */\n maxModelRequestBytes?: number\n /** Maximum model response bytes. Default: 4 MiB. */\n maxModelResponseBytes?: number\n /** Deadline for one caller-owned model invocation. Default: the whole analysis deadline. */\n modelRequestTimeoutMs?: number\n /** Trace-tool loopback request/response byte limits. */\n traceToolLimits?: Partial<TraceToolCallbackLimits>\n /** Deadline for one Python-to-Node trace-tool call. Default: 60 seconds. */\n traceToolTimeoutMs?: number\n /**\n * How the controller's reasoning and code fields are obtained.\n *\n * `tolerant` parses marker output strictly first, then recovers the fields\n * deterministically from prose plus a fenced code block — the shape coding\n * models naturally emit — at no extra model cost. `two-step` extracts with a\n * second call per turn. `chat` accepts marker output only. Default:\n * `tolerant`.\n */\n controlAdapter?: 'chat' | 'two-step' | 'tolerant'\n /** Python command used to load agent-eval-rpc[dspy]. Default: python. */\n runner?: ExternalOptimizerRunnerCommand\n /** Whole investigation deadline. Default: 10 minutes. */\n timeoutMs?: number\n}\n\n/** Use the official DSPy RLM as a bounded recursive trace-analysis engine. */\nexport function createDspyRlmTraceEngine(options: DspyRlmTraceEngineOptions): TraceAnalysisEngine {\n assertOptions(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_TRACE_ANALYST_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('DSPy RLM maxOutputTokens must be a positive safe integer')\n }\n const controlAdapter = options.controlAdapter ?? 'tolerant'\n const maxReasoningTokens = options.maxReasoningTokens ?? maxOutputTokens * 4\n if (!Number.isSafeInteger(maxReasoningTokens) || maxReasoningTokens < 0) {\n throw new TypeError('DSPy RLM maxReasoningTokens must be a non-negative safe integer')\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n assertTimerDelay(timeoutMs, 'timeoutMs')\n const maxCostUsd = options.maxCostUsd ?? DEFAULT_MAX_COST_USD\n if (!Number.isFinite(maxCostUsd) || maxCostUsd <= 0) {\n throw new TypeError('DSPy RLM maxCostUsd must be positive and finite')\n }\n const pricing = options.pricing ?? pricingForModel(options.model)\n const maxModelRequestBytes = options.maxModelRequestBytes ?? DEFAULT_MAX_MODEL_REQUEST_BYTES\n const maxModelResponseBytes = options.maxModelResponseBytes ?? DEFAULT_MAX_MODEL_RESPONSE_BYTES\n const modelRequestTimeoutMs = options.modelRequestTimeoutMs ?? timeoutMs\n const traceToolTimeoutMs = options.traceToolTimeoutMs ?? DEFAULT_TRACE_TOOL_TIMEOUT_MS\n assertExternalOptimizerModelBudget(\n {\n maxCostUsd,\n maxRequests: options.maxModelRequests ?? 1,\n maxRequestBytes: maxModelRequestBytes,\n maxResponseBytes: maxModelResponseBytes,\n maxOutputTokensPerRequest: maxOutputTokens,\n maxReasoningTokensPerRequest: maxReasoningTokens,\n pricing,\n requestTimeoutMs: modelRequestTimeoutMs,\n },\n 'DSPy RLM model limits',\n )\n resolveExternalOptimizerCallbackLimits(options.traceToolLimits, 'DSPy RLM trace tool limits')\n assertTimerDelay(traceToolTimeoutMs, 'traceToolTimeoutMs')\n\n const runner = sanitizedRunner(options.runner)\n const processLimits = resolveExternalOptimizerProcessLimits(runner?.limits)\n return {\n id: 'dspy-rlm',\n description: 'Official DSPy RLM with bounded trace tools and metered model calls.',\n model: options.model,\n version: DSPY_RLM_ENGINE_VERSION,\n executionConfig: {\n bridge_module: BRIDGE_MODULE,\n call_ref: options.callRef,\n model: options.model,\n pricing: { ...pricing },\n max_cost_usd: maxCostUsd,\n max_output_tokens: maxOutputTokens,\n max_reasoning_tokens: maxReasoningTokens,\n control_adapter: controlAdapter,\n timeout_ms: timeoutMs,\n max_model_requests: options.maxModelRequests ?? null,\n max_request_bytes: maxModelRequestBytes,\n max_response_bytes: maxModelResponseBytes,\n model_request_timeout_ms: modelRequestTimeoutMs,\n trace_tool_limits: options.traceToolLimits ?? null,\n trace_tool_timeout_ms: traceToolTimeoutMs,\n process_limits: processLimits,\n runner: runner ? 'caller-supplied' : 'default',\n runner_command: runner?.command ?? null,\n },\n async analyze(request) {\n const callback = await startTraceToolCallback({\n tools: request.tools,\n maxCalls: request.limits.maxToolCalls,\n ...(options.traceToolLimits ? { limits: options.traceToolLimits } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n let modelProxy: ExternalOptimizerModelProxy | undefined\n const modelExecutions: ExternalOptimizerModelExecutionObservation[] = []\n const result = await runWithCleanup({\n label: 'DSPy RLM trace-analysis resources',\n run: async () => {\n modelProxy = await startExternalOptimizerModelProxy({\n call: options.call,\n callRef: options.callRef,\n recordExecution: (observation) => {\n modelExecutions.push(structuredClone(observation))\n options.recordExecution(observation)\n },\n model: options.model,\n budget: {\n maxCostUsd,\n maxRequests: resolveMaxModelRequests(options.maxModelRequests, request.limits),\n maxRequestBytes: maxModelRequestBytes,\n maxResponseBytes: maxModelResponseBytes,\n maxOutputTokensPerRequest: maxOutputTokens,\n maxReasoningTokensPerRequest: maxReasoningTokens,\n requestTimeoutMs: modelRequestTimeoutMs,\n pricing,\n },\n costLedger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n request.log?.('trace analyst engine started', {\n engine: 'dspy-rlm',\n model: options.model,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n const raw = await runExternalOptimizerProcess<unknown>({\n label: 'DSPy RLM trace analysis',\n tempPrefix: 'agent-eval-dspy-rlm-',\n module: BRIDGE_MODULE,\n input: {\n operation: 'analyze',\n question: request.question,\n instructions: request.instructions,\n modelProxy: {\n baseUrl: modelProxy.baseUrl,\n apiKey: modelProxy.apiKey,\n model: options.model,\n maxOutputTokens,\n },\n toolCallback: {\n url: callback.url,\n token: callback.token,\n timeoutMs: traceToolTimeoutMs,\n },\n toolSpecs: request.tools.map(({ name, description, parameters }) => ({\n name,\n description,\n parameters,\n })),\n controlAdapter,\n limits: {\n maxIterations: request.limits.maxIterations,\n maxLlmCalls: request.limits.maxLlmCalls,\n maxOutputChars: request.limits.maxOutputChars,\n },\n // Omitted entirely when the caller supplied none, so a request\n // without structured inputs sends the payload it always sent.\n ...(request.taskInputs ? { taskInputs: request.taskInputs } : {}),\n },\n ...(runner ? { runner } : {}),\n additionalArgs: ['--max-input-bytes', String(processLimits.maxInputBytes)],\n timeoutMs,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n const parsed = parseBridgeOutput(raw, (index, reason) => {\n request.log?.('finding rejected: bridge row failed schema validation', {\n engine: 'dspy-rlm',\n index,\n reason,\n })\n })\n const successfulCompletions = modelProxy.successfulCompletions()\n const requestAttempts = modelProxy.requestAttempts()\n if (parsed.modelCalls !== successfulCompletions) {\n throw new Error(\n `DSPy RLM reported ${parsed.modelCalls} model calls, but the provider proxy recorded ${successfulCompletions}`,\n )\n }\n modelProxy.assertExecutionComplete()\n return {\n ...parsed,\n toolCalls: callback.calls(),\n runtime: {\n ...parsed.runtime,\n modelRequestAttempts: requestAttempts,\n modelSuccessfulCompletions: successfulCompletions,\n modelExecutions,\n },\n } satisfies TraceAnalysisEngineResult\n },\n cleanup: async () => {\n const results = await Promise.allSettled([\n ...(modelProxy ? [modelProxy.close()] : []),\n callback.close(),\n ])\n const errors = results.flatMap((entry) =>\n entry.status === 'rejected' ? [entry.reason] : [],\n )\n if (errors.length > 0) {\n throw new AggregateError(errors, 'DSPy RLM resource cleanup failed')\n }\n },\n })\n request.log?.('trace analyst engine completed', {\n engine: 'dspy-rlm',\n model_calls: result.modelCalls,\n model_request_attempts: result.runtime.modelRequestAttempts,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n },\n }\n}\n\nfunction parseBridgeOutput(\n value: unknown,\n onRejectedFinding: (index: number, reason: string) => void,\n): Omit<TraceAnalysisEngineResult, 'toolCalls'> {\n if (!isRecord(value)) throw new Error('DSPy RLM bridge output must be an object')\n if (typeof value.answer !== 'string' || !value.answer.trim()) {\n throw new Error('DSPy RLM bridge returned no answer')\n }\n // Findings are model output: one malformed row is model noise, not a bridge\n // fault, and the rest of the paid investigation must survive it. The codec\n // is the same decoder the Python side runs, so a row this bridge accepts is\n // a row the optimizer could report, and vice versa.\n const decoded = decodeRawFindingArray(value.findings)\n if (decoded.topLevelError !== undefined) {\n throw new Error(`DSPy RLM bridge findings must be an array: ${decoded.topLevelError}`)\n }\n const findings = decoded.accepted\n const rejectedFindings = decoded.rejected.length\n for (const rejection of decoded.rejected) {\n onRejectedFinding(\n rejection.index,\n `${rejection.code}${rejection.path ? ` at ${rejection.path}` : ''}: ${rejection.message}`,\n )\n }\n if (!Array.isArray(value.trajectory)) {\n throw new Error('DSPy RLM bridge trajectory must be an array')\n }\n if (!Number.isSafeInteger(value.modelCalls) || (value.modelCalls as number) <= 0) {\n throw new Error('DSPy RLM bridge modelCalls must be a positive safe integer')\n }\n if (!isRecord(value.runtime)) {\n throw new Error('DSPy RLM bridge runtime must be an object')\n }\n return {\n answer: value.answer,\n findings,\n trajectory: value.trajectory,\n modelCalls: value.modelCalls as number,\n runtime: { ...value.runtime, rejectedFindings },\n }\n}\n\nfunction assertOptions(options: DspyRlmTraceEngineOptions): void {\n for (const [name, value] of [\n ['callRef', options.callRef],\n ['model', options.model],\n ] as const) {\n if (typeof value !== 'string' || !value.trim() || value !== value.trim()) {\n throw new TypeError(`DSPy RLM ${name} must be a trimmed non-empty string`)\n }\n }\n if (typeof options.call !== 'function') {\n throw new TypeError('DSPy RLM call must be a function')\n }\n if (typeof options.recordExecution !== 'function') {\n throw new TypeError('DSPy RLM recordExecution must be a function')\n }\n if (\n options.maxModelRequests !== undefined &&\n (!Number.isSafeInteger(options.maxModelRequests) || options.maxModelRequests <= 0)\n ) {\n throw new TypeError('DSPy RLM maxModelRequests must be a positive safe integer')\n }\n}\n\nfunction resolveMaxModelRequests(\n configured: number | undefined,\n limits: { maxIterations: number; maxLlmCalls: number },\n): number {\n if (configured !== undefined) return configured\n const derived = limits.maxIterations + limits.maxLlmCalls + 1\n if (!Number.isSafeInteger(derived) || derived <= 0) {\n throw new Error('DSPy RLM analysis limits produce an invalid model request limit')\n }\n return derived\n}\n\nfunction assertTimerDelay(value: number, field: string): void {\n if (!Number.isSafeInteger(value) || value <= 0 || value > MAX_TIMER_DELAY_MS) {\n throw new TypeError(`DSPy RLM ${field} must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n}\n\nfunction pricingForModel(model: string): CustomTokenPricing {\n const pricing = resolveModelPricing(model)\n if (!pricing) {\n throw new Error(\n `no pricing is configured for '${model}'; provide DspyRlmTraceEngineOptions.pricing`,\n )\n }\n return {\n inputUsdPerMillion: pricing.input * 1_000,\n outputUsdPerMillion: pricing.output * 1_000,\n }\n}\n\nfunction sanitizedRunner(\n runner: ExternalOptimizerRunnerCommand | undefined,\n): ExternalOptimizerRunnerCommand | undefined {\n if (!runner) return undefined\n return {\n ...(runner.command ? { command: runner.command } : {}),\n ...(runner.args ? { args: runner.args } : {}),\n ...(runner.env ? { env: removeCredentialEnvironment(runner.env) } : {}),\n ...(runner.limits ? { limits: { ...runner.limits } } : {}),\n }\n}\n\n"],"m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AAEA,SAAS,iBAAiB,OAAe,OAAqB;CAC5D,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,SAAS,KAAK,QAAQ,oBACxD,MAAM,IAAI,UAAU,YAAY,MAAM,yBAAyB,oBAAoB;AAEvF;AAEA,SAAS,gBAAgB,OAAmC;CAC1D,MAAM,UAAU,oBAAoB,KAAK;CACzC,IAAI,CAAC,SACH,MAAM,IAAI,MACR,iCAAiC,MAAM,6CACzC;CAEF,OAAO;EACL,oBAAoB,QAAQ,QAAQ;EACpC,qBAAqB,QAAQ,SAAS;CACxC;AACF;AAEA,SAAS,gBACP,QAC4C;CAC5C,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,OAAO;EACL,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;EACpD,GAAI,OAAO,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;EAC3C,GAAI,OAAO,MAAM,EAAE,KAAK,4BAA4B,OAAO,GAAG,EAAE,IAAI,CAAC;EACrE,GAAI,OAAO,SAAS,EAAE,QAAQ,EAAE,GAAG,OAAO,OAAO,EAAE,IAAI,CAAC;CAC1D;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { o as CostLedgerHandle } from "./cost-ledger-C1W3ICmP.js";
2
- import { W as TraceAnalysisStore, m as EvidenceRef, z as BoundedTraceAnalysisStoreOptions } from "./types-8yQzNm8u.js";
2
+ import { J as TraceAnalysisStore, U as BoundedTraceAnalysisStoreOptions, m as EvidenceRef } from "./types-DGImvHIr.js";
3
3
  import { z } from "zod";
4
4
  //#region src/eval-tools.d.ts
5
5
  /**
@@ -157,4 +157,4 @@ interface TraceAnalysisEngine {
157
157
  }
158
158
  //#endregion
159
159
  export { RAW_FINDING_SCHEMA_PROMPT as a, RawAnalystFindingSchema as c, BuildTraceAnalysisToolsOptions as d, TRACE_ANALYST_TOOL_NAMESPACE as f, buildTraceAnalysisToolDescriptors as h, TraceAnalystLimits as i, evidenceRefsFromRawFinding as l, UNTRUSTED_TRACE_TEXT as m, TraceAnalysisEngineRequest as n, RawAnalystEvidence as o, TraceAnalysisToolDescriptor as p, TraceAnalysisEngineResult as r, RawAnalystFinding as s, TraceAnalysisEngine as t, parseRawFinding as u };
160
- //# sourceMappingURL=engine-BpGGw6cd.d.ts.map
160
+ //# sourceMappingURL=engine-BF95CWzH.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"engine-BpGGw6cd.d.ts","names":[],"sources":["../src/eval-tools.ts","../src/trace-analyst/tools.ts","../src/analyst/finding-signature.ts","../src/analyst/engine.ts"],"mappings":";;;;;;;;;;;;;;;;;;;UAsBiB;EACf;EACA;EACA,YAAY;EACZ,UAAU,eAAe;IAAQ,SAAS;QAAkB;;;;cCZjD;;;;;;cAOA;UAGI,uCAAuC;EACtD,OAAO;;UAGQ,oCAAoC;EACnD,kBAAkB;;EAElB;;EAEA;;;iBAMc,kCACd,SAAS,iCACR;;;cC7BG,0BAAwB,EAAA;;;GAKnB,EAAA,KAAA;KAEC,qBAAqB,EAAE,aAAa;cAiBnC,yBAAuB,EAAA;;;;;;;;;;;;;;;;;GAKzB,EAAA,KAAA;KAEC,oBAAoB,EAAE,aAAa;;;;;;cAOlC;;iBAYG,2BAA2B,SAAS,oBAAoB;iBAQxD,gBACd,cACA,OAAO,aAAa,SAAS,mCAC5B;;;;UCpEc;;EAEf;;EAEA;;EAEA;;EAEA;;UA0Be;EACf;EACA;EACA;EACA,gBAAgB;;;;;;;;;;;EAWhB,aAAa,SAAS;EACtB,QAAQ;EACR,YAAY;EACZ;EACA,WAAW;EACX,SAAS;EACT,OAAO,iBAAiB,SAAS;;;UAIlB;EACf;EACA,UAAU;;EAEV;;;;;EAKA;;EAEA;EACA,SAAS;;;;;;;;;UAUM;WACN;WACA;WACA;;WAEA;;;;;;;;WAQA,iBAAiB,SAAS;EACnC,QAAQ,SAAS,6BAA6B,QAAQ"}
1
+ {"version":3,"file":"engine-BF95CWzH.d.ts","names":[],"sources":["../src/eval-tools.ts","../src/trace-analyst/tools.ts","../src/analyst/finding-signature.ts","../src/analyst/engine.ts"],"mappings":";;;;;;;;;;;;;;;;;;;UAsBiB;EACf;EACA;EACA,YAAY;EACZ,UAAU,eAAe;IAAQ,SAAS;QAAkB;;;;cCZjD;;;;;;cAOA;UAGI,uCAAuC;EACtD,OAAO;;UAGQ,oCAAoC;EACnD,kBAAkB;;EAElB;;EAEA;;;iBAMc,kCACd,SAAS,iCACR;;;cC7BG,0BAAwB,EAAA;;;GAKnB,EAAA,KAAA;KAEC,qBAAqB,EAAE,aAAa;cAiBnC,yBAAuB,EAAA;;;;;;;;;;;;;;;;;GAKzB,EAAA,KAAA;KAEC,oBAAoB,EAAE,aAAa;;;;;;cAOlC;;iBAYG,2BAA2B,SAAS,oBAAoB;iBAQxD,gBACd,cACA,OAAO,aAAa,SAAS,mCAC5B;;;;UCpEc;;EAEf;;EAEA;;EAEA;;EAEA;;UA0Be;EACf;EACA;EACA;EACA,gBAAgB;;;;;;;;;;;EAWhB,aAAa,SAAS;EACtB,QAAQ;EACR,YAAY;EACZ;EACA,WAAW;EACX,SAAS;EACT,OAAO,iBAAiB,SAAS;;;UAIlB;EACf;EACA,UAAU;;EAEV;;;;;EAKA;;EAEA;EACA,SAAS;;;;;;;;;UAUM;WACN;WACA;WACA;;WAEA;;;;;;;;WAQA,iBAAiB,SAAS;EACnC,QAAQ,SAAS,6BAA6B,QAAQ"}
@@ -1,6 +1,6 @@
1
1
  import { c as verifyAgentProfileCell, i as buildAgentProfileCell, l as hashJson } from "./agent-profile-cell-B1V1gUZs.js";
2
2
  import { c as validateRunRecord } from "./run-record-DhEJgoPz.js";
3
- import { t as researchReport } from "./summary-report-BsXJoYX5.js";
3
+ import { t as researchReport } from "./summary-report-DHDWxe6p.js";
4
4
  import { t as FileSystemRawProviderSink } from "./raw-provider-sink-75w4FWBj.js";
5
5
  import { t as TraceEmitter } from "./emitter-DbMXUIVP.js";
6
6
  import { n as assertRunCaptured, t as RunIntegrityError } from "./integrity-W4CADcFc.js";
@@ -390,4 +390,4 @@ function defaultRunId(params) {
390
390
  //#endregion
391
391
  export { runEvalCampaign as t };
392
392
 
393
- //# sourceMappingURL=eval-campaign-BUMIxKTE.js.map
393
+ //# sourceMappingURL=eval-campaign-DoX5vz3E.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"eval-campaign-BUMIxKTE.js","names":[],"sources":["../src/eval-campaign.ts"],"sourcesContent":["/**\n * EvalCampaign — opinionated matrix runner that wires the four\n * capture-integrity directives by construction.\n *\n * The canonical benchmark shape — matrix runner → for each\n * (variant, scenario, seed) → start a TraceEmitter → call LLMs → end the\n * run → analyze — has a bug class at the integration boundary: raw\n * events not captured, route silently wrong, integrity not asserted,\n * analyst never run. The directives in `SKILL.md § Capture integrity`\n * are the mitigations.\n *\n * `EvalCampaign` is the structural fix — consumers don't wire the\n * integrity surface themselves; the campaign owns it. Specifically:\n *\n * - constructs a per-run `TraceStore` and `RawProviderSink` via factories\n * - builds the run's `ChatClient` through `chatFactory`, handing it the\n * run's raw sink and trace context — a transport built any other way has\n * no raw HTTP envelope, and `assertRunCaptured` says so\n * - calls `assertRunCaptured` after every `endRun` and routes failures\n * through a configurable policy (`throw` / `mark_failed` / `log`)\n * - assembles per-run `RunRecord`s and runs `researchReport` at the end\n * so the campaign artifact is launch-decision-grade by default\n * - embeds the campaign fingerprint (a SHA-256 over the canonicalised\n * run set) and optional `preregistrationHash` in the report\n *\n * The runner contract is intentionally narrow: produce a `CampaignRunOutcome`\n * given a fully-wired `CampaignRunContext`. Everything orchestration-shaped\n * lives in the campaign. This is the inversion-of-control point — consumers\n * stop writing matrix runners and start writing scenario-runners.\n *\n * Out of scope for v1 (tracked in `docs/research-report-methodology.md`):\n *\n * - Distributed/cluster execution (concurrency is local async)\n * - Adaptive sampling / sequential interim looks\n * - Resume from partial state across crashes\n * - LLM-call retry beyond what the caller's transport already does\n */\n\nimport {\n type AgentProfileCell,\n type AgentProfileCellInput,\n buildAgentProfileCell,\n verifyAgentProfileCell,\n} from './agent-profile-cell'\nimport type { ChatClient } from './analyst/chat-client'\nimport { hashJson } from './pre-registration'\nimport type {\n JudgeScoresRecord,\n RunCostProvenance,\n RunJudgeMetadata,\n RunOutcome,\n RunRecord,\n RunSplitTag,\n RunTaskFailure,\n RunTokenUsage,\n} from './run-record'\nimport { validateRunRecord } from './run-record'\nimport { type ResearchReport, type ResearchReportOptions, researchReport } from './summary-report'\nimport type { RunCompleteHook } from './trace/emitter'\nimport { TraceEmitter } from './trace/emitter'\nimport {\n assertRunCaptured,\n RunIntegrityError,\n type RunIntegrityExpectations,\n type RunIntegrityReport,\n} from './trace/integrity'\nimport { FileSystemRawProviderSink, type RawProviderSink } from './trace/raw-provider-sink'\nimport type { TraceStore } from './trace/store'\n\n// ── Public types ─────────────────────────────────────────────────────────\n\nexport interface CampaignVariant<V> {\n id: string\n payload: V\n}\n\nexport interface CampaignScenario {\n scenarioId: string\n /** Free-form metadata propagated to runs and reports. */\n tags?: Record<string, string>\n}\n\nexport interface CampaignRunContext<V> {\n /** Stable run id. The campaign generates this; the runner does not. */\n runId: string\n /** Logical experiment id (campaignId by default; overridable per-run via opts). */\n experimentId: string\n variant: V\n variantId: string\n scenarioId: string\n scenarioTags: Record<string, string>\n seed: number\n splitTag: RunSplitTag\n /**\n * The TraceEmitter for this run, with `onRunComplete` hooks pre-wired\n * (analyst auto-execution if configured, plus integrity check). The\n * runner MUST call `emitter.startRun` before doing any work and either\n * `emitter.endRun` or `emitter.abortRun` before returning.\n */\n emitter: TraceEmitter\n store: TraceStore\n rawSink: RawProviderSink\n /**\n * The run's model transport, built by `chatFactory` with this run's\n * `rawSink` and `runId` already bound.\n */\n chat: ChatClient\n}\n\n/** What the campaign binds into the run's transport. */\nexport interface CampaignChatWiring {\n /**\n * Raw provider sink for this run. Bind it into the transport: the campaign's\n * integrity check requires every LLM span to carry a matching raw request\n * event, so a transport built without it fails `assertRunCaptured`.\n */\n rawSink: RawProviderSink\n runId: string\n}\n\ninterface CampaignRunOutcomeFields {\n /** Did the run pass? Mirrors `RunOutcome.pass` semantics. */\n pass: boolean\n /** Score for the run on its split. Maps to `searchScore` or `holdoutScore`. */\n score: number\n /** Cost in USD, or null when the runner could not capture it. */\n costUsd: number | null\n /** Source of the cost amount. */\n costProvenance: RunCostProvenance\n tokenUsage: RunTokenUsage\n /** Snapshot model id (e.g. `claude-sonnet-4-6@2025-04-15`). */\n model: string\n /** sha256 of the effective prompt sent to the model. */\n promptHash: string\n /** sha256 of the effective config (model, temperature, tools, judges, splits). */\n configHash: string\n /** Optional extra numeric metrics to land in `outcome.raw`. */\n raw?: Record<string, number>\n /** Optional judge metadata when a judge was used. */\n judgeMetadata?: RunJudgeMetadata\n /**\n * Optional per-judge / per-dim breakdown for ensemble-judged runs.\n * Propagated to `outcome.judgeScores` on the resulting `RunRecord`.\n * Single-judge or scalar-only runs leave this unset.\n */\n judgeScores?: JudgeScoresRecord\n /**\n * Agent profile cell observed by the runner. When supplied, it overrides\n * `EvalCampaignOptions.agentProfile` for this run and must match the\n * outcome's `model` and `promptHash`.\n */\n agentProfile?: AgentProfileCell | AgentProfileCellInput\n}\n\n/** Campaign result with the same task-failure invariant as `RunRecord`. */\nexport type CampaignRunOutcome = CampaignRunOutcomeFields & RunTaskFailure\n\nexport type CampaignRunner<V> = (ctx: CampaignRunContext<V>) => Promise<CampaignRunOutcome>\n\nexport type CampaignIntegrityPolicy = 'throw' | 'mark_failed' | 'log'\n\nexport interface EvalCampaignOptions<V> {\n /**\n * Stable id for the campaign. Used as the default `experimentId` on\n * every run, and folded into the campaign fingerprint.\n */\n campaignId: string\n variants: CampaignVariant<V>[]\n scenarios: CampaignScenario[]\n /** Default `[0, 1, 2]`. */\n seeds?: number[]\n /** Default `'holdout'` — the split that anchors a launch decision. */\n splitTag?: RunSplitTag\n /** Git SHA the campaign is run against. Mandatory; `RunRecord` rejects unset. */\n commitSha: string\n /**\n * Build the model transport for one run. agent-eval executes no paid model:\n * the caller owns the transport and the credential never enters this\n * package. The campaign calls this once per run and passes the run's raw\n * provider sink and `runId`, so a transport that binds them captures the\n * raw HTTP envelope `assertRunCaptured` checks for.\n */\n chatFactory: (wiring: CampaignChatWiring) => ChatClient\n /**\n * Caller-declared identity of the execution route, folded into the campaign\n * fingerprint so two campaigns run against different endpoints do not share\n * one identity. agent-eval no longer knows the endpoint; the owner of\n * execution names it.\n */\n executionRef?: string\n /**\n * Per-run TraceStore factory. Common shape: a fresh store per run keyed\n * on `runId`. Implementations that share a store across the campaign\n * are valid — the campaign only writes through `emitter`.\n */\n storeFactory: (params: CampaignFactoryParams) => TraceStore\n /**\n * Per-run RawProviderSink factory. Defaults to `FileSystemRawProviderSink`\n * rooted at `${workDir}/raw-events/${runId}` if `workDir` is supplied;\n * otherwise required. Forensic capture is non-negotiable in a campaign\n * run — pass `NoopRawProviderSink` explicitly if you want to opt out.\n */\n rawSinkFactory?: (params: CampaignFactoryParams) => RawProviderSink\n /**\n * Filesystem root for default `rawSinkFactory`. Ignored if\n * `rawSinkFactory` is supplied.\n */\n workDir?: string\n /**\n * Extra `onRunComplete` hooks the campaign appends (after its own\n * integrity-check hook). Pass `traceAnalystOnRunComplete(...)` here.\n */\n onRunComplete?: RunCompleteHook[]\n /**\n * Per-run integrity expectations. Defaults to:\n * `{ llmSpansMin: 1, requireRawCoverageOfLlmSpans: true, requireOutcome: true }`.\n * Override (e.g. `{ llmSpansMin: 0 }`) for runs that don't call LLMs.\n */\n integrity?: RunIntegrityExpectations\n /** Behaviour when integrity fails. Default `'mark_failed'`. */\n onIntegrityFailure?: CampaignIntegrityPolicy\n /**\n * Per-run runner. Receives a fully-wired context; produces an outcome\n * the campaign converts into a `RunRecord`.\n */\n runner: CampaignRunner<V>\n /**\n * If set, the campaign computes `researchReport` at the end. `comparator`\n * is a `variantId`. Other fields are forwarded verbatim.\n */\n report?: { comparator?: string } & Omit<\n ResearchReportOptions,\n 'comparator' | 'preregistrationHash' | 'generatedAt'\n >\n /**\n * Hash of a signed `HypothesisManifest` (see `pre-registration.ts`).\n * Embedded in the campaign fingerprint and the research report.\n */\n preregistrationHash?: string\n /** Local concurrency. Default `1` (sequential). */\n concurrency?: number\n /**\n * Override the time source. Tests pass a mock to make wallMs deterministic.\n */\n now?: () => number\n /** Override the runId generator. Tests pin this. */\n runId?: (params: CampaignFactoryParams) => string\n /**\n * Agent profile cell for campaign runs. Static profiles can pass an object;\n * routers or variant-specific harnesses can pass a factory. The campaign\n * stamps the built cell onto every `RunRecord` and rejects profile/model or\n * profile/prompt contradictions.\n */\n agentProfile?:\n | AgentProfileCell\n | AgentProfileCellInput\n | ((\n params: CampaignFactoryParams & {\n variant: V\n scenarioTags: Record<string, string>\n },\n ) =>\n | AgentProfileCell\n | AgentProfileCellInput\n | Promise<AgentProfileCell | AgentProfileCellInput>)\n}\n\nexport interface CampaignFactoryParams {\n campaignId: string\n runId: string\n variantId: string\n scenarioId: string\n seed: number\n}\n\nexport interface FailedRun {\n runId: string\n variantId: string\n scenarioId: string\n seed: number\n reason: string\n error?: string\n}\n\nexport interface EvalCampaignResult {\n campaignId: string\n /** SHA-256 over canonicalised `(variantIds, scenarioIds, seeds, comparator, splitTag, executionRef, preregistrationHash)`. */\n campaignFingerprint: string\n preregistrationHash: string | null\n /** Successful runs only. Failed runs land in `failedRuns`. */\n runs: RunRecord[]\n /** Integrity reports for every successful run. */\n integrityReports: RunIntegrityReport[]\n failedRuns: FailedRun[]\n /** Computed when `report` is set on options. */\n report?: ResearchReport\n startedAt: string\n endedAt: string\n}\n\n// ── Implementation ───────────────────────────────────────────────────────\n\nconst DEFAULT_INTEGRITY: RunIntegrityExpectations = {\n llmSpansMin: 1,\n requireRawCoverageOfLlmSpans: true,\n requireOutcome: true,\n}\n\ntype CampaignCell<V> = { variant: CampaignVariant<V>; scenario: CampaignScenario; seed: number }\n\ntype CampaignRunResult = { record: RunRecord; integrity: RunIntegrityReport }\n\n/** Resolved options shared by every step of one campaign. */\ninterface CampaignSettings {\n seeds: number[]\n splitTag: RunSplitTag\n concurrency: number\n integrity: RunIntegrityExpectations\n onIntegrityFailure: CampaignIntegrityPolicy\n now: () => number\n executionRef: string | null\n preregistrationHash: string | null\n rawSinkFactory: (params: CampaignFactoryParams) => RawProviderSink\n}\n\n/**\n * Mutable state of one campaign's worker pool.\n *\n * A genuine (non-CellExecutionError) error from any worker is a bug, not a\n * run-level failure. We must NOT let `Promise.all` reject mid-flight and\n * orphan the other workers' in-progress runs (emitters never finalized,\n * sinks/handles leak, partial work silently discarded). Instead: capture the\n * first genuine error, stop dispatching new cells so in-flight workers wind\n * down, finalize every still-open run, then re-throw the aggregated error.\n */\ninterface CampaignPool<V> {\n opts: EvalCampaignOptions<V>\n settings: CampaignSettings\n cells: CampaignCell<V>[]\n cursor: number\n aborting: boolean\n genuineErrors: unknown[]\n /**\n * Emitters for runs that are currently mid-flight, keyed by runId. A worker\n * registers its emitter before invoking the runner and removes it once the\n * run is finalized (via endRun/abortRun, success or failure). Anything left\n * here after the pool settles is an orphan we must abort.\n */\n openRuns: Map<string, TraceEmitter>\n runs: RunRecord[]\n integrityReports: RunIntegrityReport[]\n failedRuns: FailedRun[]\n}\n\nexport async function runEvalCampaign<V>(\n opts: EvalCampaignOptions<V>,\n): Promise<EvalCampaignResult> {\n assertCampaignPreflight(opts)\n const settings = resolveCampaignSettings(opts)\n const campaignFingerprint = await fingerprintCampaign(opts, settings)\n\n const startedAt = new Date(settings.now()).toISOString()\n const pool: CampaignPool<V> = {\n opts,\n settings,\n cells: planCampaignCells(opts, settings.seeds),\n cursor: 0,\n aborting: false,\n genuineErrors: [],\n openRuns: new Map(),\n runs: [],\n integrityReports: [],\n failedRuns: [],\n }\n await drainCampaignPool(pool)\n\n const report = await buildCampaignReport(opts, settings, pool.runs)\n const endedAt = new Date(settings.now()).toISOString()\n\n return {\n campaignId: opts.campaignId,\n campaignFingerprint,\n preregistrationHash: settings.preregistrationHash,\n runs: pool.runs,\n integrityReports: pool.integrityReports,\n failedRuns: pool.failedRuns,\n report,\n startedAt,\n endedAt,\n }\n}\n\n/** Reject structurally invalid campaigns before any work starts. */\nfunction assertCampaignPreflight<V>(opts: EvalCampaignOptions<V>): void {\n if (opts.variants.length === 0) {\n throw new Error('runEvalCampaign: variants must be non-empty.')\n }\n if (opts.scenarios.length === 0) {\n throw new Error('runEvalCampaign: scenarios must be non-empty.')\n }\n const variantIds = new Set<string>()\n for (const v of opts.variants) {\n if (variantIds.has(v.id)) {\n throw new Error(`runEvalCampaign: duplicate variant id \"${v.id}\".`)\n }\n variantIds.add(v.id)\n }\n const scenarioIds = new Set<string>()\n for (const s of opts.scenarios) {\n if (scenarioIds.has(s.scenarioId)) {\n throw new Error(`runEvalCampaign: duplicate scenarioId \"${s.scenarioId}\".`)\n }\n scenarioIds.add(s.scenarioId)\n }\n if (opts.report?.comparator && !variantIds.has(opts.report.comparator)) {\n throw new Error(\n `runEvalCampaign: report.comparator \"${opts.report.comparator}\" is not a configured variantId.`,\n )\n }\n if (!opts.commitSha) {\n throw new Error('runEvalCampaign: commitSha is required (every RunRecord needs it).')\n }\n}\n\n/** Apply defaults to the optional campaign options. */\nfunction resolveCampaignSettings<V>(opts: EvalCampaignOptions<V>): CampaignSettings {\n return {\n seeds: opts.seeds ?? [0, 1, 2],\n splitTag: opts.splitTag ?? 'holdout',\n concurrency: Math.max(1, opts.concurrency ?? 1),\n integrity: { ...DEFAULT_INTEGRITY, ...(opts.integrity ?? {}) },\n onIntegrityFailure: opts.onIntegrityFailure ?? 'mark_failed',\n now: opts.now ?? (() => Date.now()),\n executionRef: opts.executionRef ?? null,\n preregistrationHash: opts.preregistrationHash ?? null,\n rawSinkFactory: opts.rawSinkFactory ?? defaultRawSinkFactory(opts.workDir),\n }\n}\n\n/** SHA-256 over the canonicalised matrix definition. */\nfunction fingerprintCampaign<V>(\n opts: EvalCampaignOptions<V>,\n settings: CampaignSettings,\n): Promise<string> {\n return hashJson({\n campaignId: opts.campaignId,\n variants: opts.variants.map((v) => v.id).sort(),\n scenarios: opts.scenarios.map((s) => s.scenarioId).sort(),\n seeds: [...settings.seeds].sort((a, b) => a - b),\n splitTag: settings.splitTag,\n comparator: opts.report?.comparator ?? null,\n executionRef: settings.executionRef,\n preregistrationHash: settings.preregistrationHash,\n })\n}\n\n/** Expand variants x scenarios x seeds, variant-major. */\nfunction planCampaignCells<V>(opts: EvalCampaignOptions<V>, seeds: number[]): CampaignCell<V>[] {\n const cells: CampaignCell<V>[] = []\n for (const variant of opts.variants) {\n for (const scenario of opts.scenarios) {\n for (const seed of seeds) {\n cells.push({ variant, scenario, seed })\n }\n }\n }\n return cells\n}\n\n/**\n * Run the bounded-concurrency worker pool to completion, finalize any run left\n * open, and re-throw the genuine errors the workers captured.\n */\nasync function drainCampaignPool<V>(pool: CampaignPool<V>): Promise<void> {\n const workers = Array.from(\n { length: Math.min(pool.settings.concurrency, pool.cells.length) },\n () => campaignWorker(pool),\n )\n // allSettled (not all): a genuine error in one worker must not reject the\n // pool mid-flight and orphan the others. Each worker captures its own\n // genuine error into `genuineErrors` and returns; we re-throw below.\n await Promise.allSettled(workers)\n\n // Finalize any run still open after the pool wound down. With the\n // stop-dispatch flag these are the runs that were mid-flight in peer workers\n // when the first genuine error fired — abort them so their emitters finalize\n // (hooks fire, store records a terminal status) instead of leaking.\n for (const [runId, emitter] of pool.openRuns) {\n await finalizeAbort(emitter, runId, 'campaign aborted: genuine error in a sibling run')\n }\n pool.openRuns.clear()\n\n if (pool.genuineErrors.length > 0) {\n throw pool.genuineErrors.length === 1\n ? pool.genuineErrors[0]\n : new AggregateError(\n pool.genuineErrors,\n `runEvalCampaign: ${pool.genuineErrors.length} runs failed with genuine (non-run-level) errors`,\n )\n }\n}\n\n/** Pull cells off the shared cursor until none remain or the pool is aborting. */\nasync function campaignWorker<V>(pool: CampaignPool<V>): Promise<void> {\n while (!pool.aborting) {\n const i = pool.cursor++\n if (i >= pool.cells.length) return\n const cell = pool.cells[i]!\n try {\n const result = await runCampaignCell(pool, cell)\n pool.runs.push(result.record)\n pool.integrityReports.push(result.integrity)\n } catch (err) {\n if (err instanceof CellExecutionError) {\n pool.failedRuns.push(err.failed)\n if (err.integrity) pool.integrityReports.push(err.integrity)\n } else {\n // Genuine bug — not a runner failure, not an integrity failure.\n // Capture it and stop dispatching so peers wind down gracefully;\n // re-thrown after the pool settles. Do not surface here — that would\n // reject Promise.all and orphan the other workers' runs.\n pool.genuineErrors.push(err)\n pool.aborting = true\n return\n }\n }\n }\n}\n\n/** Run one matrix cell: runner, integrity check, then the validated RunRecord. */\nasync function runCampaignCell<V>(\n pool: CampaignPool<V>,\n cell: CampaignCell<V>,\n): Promise<CampaignRunResult> {\n const { opts, settings } = pool\n const runId = (opts.runId ?? defaultRunId)({\n campaignId: opts.campaignId,\n runId: '', // unused by default generator\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n seed: cell.seed,\n })\n const factoryParams: CampaignFactoryParams = {\n campaignId: opts.campaignId,\n runId,\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n seed: cell.seed,\n }\n const store = opts.storeFactory(factoryParams)\n const rawSink = settings.rawSinkFactory(factoryParams)\n\n const emitter = new TraceEmitter(store, {\n runId,\n now: opts.now,\n onRunComplete: opts.onRunComplete,\n })\n // Track this run as open so a genuine error elsewhere in the pool can\n // finalize it instead of orphaning it. Removed in the finally below.\n pool.openRuns.set(runId, emitter)\n\n const chat = opts.chatFactory({ rawSink, runId })\n\n const ctx: CampaignRunContext<V> = {\n runId,\n experimentId: opts.campaignId,\n variant: cell.variant.payload,\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n scenarioTags: cell.scenario.tags ?? {},\n seed: cell.seed,\n splitTag: settings.splitTag,\n emitter,\n store,\n rawSink,\n chat,\n }\n\n try {\n const wallStart = settings.now()\n const outcome = await invokeCampaignRunner(opts, cell, ctx)\n const wallMs = settings.now() - wallStart\n\n const integrityReport = await assertRunCaptured(store, runId, {\n ...settings.integrity,\n rawSink,\n })\n if (!integrityReport.ok) admitOrRejectIntegrity(settings, cell, runId, integrityReport)\n\n const record = buildCampaignRunRecord(opts, settings, cell, runId, outcome, wallMs)\n await stampAgentProfile(opts, cell, record, runId, outcome)\n return { record: validateRunRecord(record), integrity: integrityReport }\n } finally {\n // This run's worker has finished with it (success, run-level failure, or\n // genuine error). It is no longer the pool's job to finalize — drop it so\n // the post-settle sweep doesn't double-abort a finalized run.\n pool.openRuns.delete(runId)\n }\n}\n\n/** Invoke the runner; a throw aborts the run and becomes a run-level failure. */\nasync function invokeCampaignRunner<V>(\n opts: EvalCampaignOptions<V>,\n cell: CampaignCell<V>,\n ctx: CampaignRunContext<V>,\n): Promise<CampaignRunOutcome> {\n try {\n return await opts.runner(ctx)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n // The runner threw mid-execution. Abort the run so the emitter\n // finalizes. The only benign abortRun failure is \"the runner never\n // started the run\" (nothing to finalize). A store-write failure (disk\n // full, FS error) is a genuine diagnostic — surface it rather than\n // masking it as a plain runner failure.\n await finalizeAbort(ctx.emitter, ctx.runId, message)\n throw new CellExecutionError({\n runId: ctx.runId,\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n seed: cell.seed,\n reason: 'runner_threw',\n error: message,\n })\n }\n}\n\n/** Apply the integrity-failure policy to a report that is not ok. */\nfunction admitOrRejectIntegrity<V>(\n settings: CampaignSettings,\n cell: CampaignCell<V>,\n runId: string,\n integrityReport: RunIntegrityReport,\n): void {\n switch (settings.onIntegrityFailure) {\n case 'throw':\n throw new RunIntegrityError(integrityReport)\n case 'mark_failed':\n throw new CellExecutionError(\n {\n runId,\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n seed: cell.seed,\n reason: 'integrity_failed',\n error: integrityReport.issues.map((i) => i.code).join(', '),\n },\n integrityReport,\n )\n case 'log':\n // Caller wants the run admitted with a flagged report; fall through.\n break\n }\n}\n\n/** Assemble the RunRecord for a successful run, before profile stamping. */\nfunction buildCampaignRunRecord<V>(\n opts: EvalCampaignOptions<V>,\n settings: CampaignSettings,\n cell: CampaignCell<V>,\n runId: string,\n outcome: CampaignRunOutcome,\n wallMs: number,\n): RunRecord {\n const recordOutcome: RunOutcome = {\n raw: outcome.raw ?? {},\n }\n if (settings.splitTag === 'holdout') recordOutcome.holdoutScore = outcome.score\n else recordOutcome.searchScore = outcome.score\n if (outcome.judgeScores !== undefined) recordOutcome.judgeScores = outcome.judgeScores\n\n return {\n runId,\n experimentId: opts.campaignId,\n candidateId: cell.variant.id,\n seed: cell.seed,\n model: outcome.model,\n promptHash: outcome.promptHash,\n configHash: outcome.configHash,\n commitSha: opts.commitSha,\n wallMs,\n costUsd: outcome.costUsd,\n costProvenance: outcome.costProvenance,\n tokenUsage: outcome.tokenUsage,\n terminalOutcome: 'succeeded',\n judgeMetadata: outcome.judgeMetadata,\n outcome: recordOutcome,\n ...(outcome.failureClass ? { failureClass: outcome.failureClass } : {}),\n failureMode: outcome.failureMode,\n splitTag: settings.splitTag,\n scenarioId: cell.scenario.scenarioId,\n }\n}\n\n/** Resolve the run's agent profile (outcome first, then options) and stamp it on the record. */\nasync function stampAgentProfile<V>(\n opts: EvalCampaignOptions<V>,\n cell: CampaignCell<V>,\n record: RunRecord,\n runId: string,\n outcome: CampaignRunOutcome,\n): Promise<void> {\n const profileSource =\n outcome.agentProfile ??\n (typeof opts.agentProfile === 'function'\n ? await opts.agentProfile({\n campaignId: opts.campaignId,\n runId,\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n seed: cell.seed,\n variant: cell.variant.payload,\n scenarioTags: cell.scenario.tags ?? {},\n })\n : opts.agentProfile)\n if (profileSource !== undefined) {\n const agentProfile = await resolveAgentProfileCell(profileSource)\n assertAgentProfileMatchesRun(agentProfile, outcome.model, outcome.promptHash)\n record.agentProfile = agentProfile\n }\n}\n\n/** Build the optional research report over the successful runs. */\nasync function buildCampaignReport<V>(\n opts: EvalCampaignOptions<V>,\n settings: CampaignSettings,\n runs: RunRecord[],\n): Promise<ResearchReport | undefined> {\n if (!opts.report) return undefined\n const reportOpts: ResearchReportOptions = {\n ...opts.report,\n comparator: opts.report.comparator,\n split: settings.splitTag === 'dev' ? 'search' : settings.splitTag,\n generatedAt: new Date(settings.now()).toISOString(),\n preregistrationHash: settings.preregistrationHash ?? undefined,\n }\n return researchReport(runs, reportOpts)\n}\n\n// ── Internal ─────────────────────────────────────────────────────────────\n\nclass CellExecutionError extends Error {\n readonly failed: FailedRun\n readonly integrity?: RunIntegrityReport\n constructor(failed: FailedRun, integrity?: RunIntegrityReport) {\n super(`cell ${failed.variantId}/${failed.scenarioId}@${failed.seed} failed: ${failed.reason}`)\n this.failed = failed\n this.integrity = integrity\n }\n}\n\n/**\n * Abort a run whose owning work threw or was orphaned by a sibling's genuine\n * error, finalizing the emitter so hooks fire and the store records a terminal\n * status. Safe to call unconditionally: it only aborts runs that are still\n * `running`. Two no-op cases are intentional and benign:\n *\n * - the run was never started (absent from the store) — nothing to finalize\n * - the run is already terminal (`completed` / `failed` / `aborted`) —\n * finalizing again would overwrite the real outcome (e.g. flip a passed run\n * to `aborted` with `{ pass: false, notes: reason }`), so we leave it alone\n *\n * Any OTHER failure of the store read or the abort write (disk full, FS fault,\n * backend down) is a genuine diagnostic and propagates rather than being\n * swallowed.\n */\nasync function finalizeAbort(emitter: TraceEmitter, runId: string, reason: string): Promise<void> {\n const existing = await emitter.traceStore.getRun(runId)\n if (existing === undefined) return // run never started; nothing to abort\n if (existing.status !== 'running') return // already finalized; never overwrite a real outcome\n // The emitter never throws on a failed store write; it counts it. A failed\n // abort write is a genuine diagnostic here, so read the count and surface it.\n const droppedBefore = emitter.captureStats().dropped\n await emitter.abortRun(reason)\n const after = emitter.captureStats()\n if (after.dropped > droppedBefore) {\n throw new Error(`finalizeAbort: run ${runId} could not be finalized: ${after.lastError}`)\n }\n}\n\nfunction defaultRawSinkFactory(workDir: string | undefined) {\n return (params: CampaignFactoryParams): RawProviderSink => {\n if (!workDir) {\n throw new Error(\n 'runEvalCampaign: rawSinkFactory not supplied and workDir not set. Pass either to enable raw provider capture, or pass `new NoopRawProviderSink()` via rawSinkFactory to opt out explicitly.',\n )\n }\n return new FileSystemRawProviderSink({\n dir: `${workDir}/raw-events/${params.runId}`,\n })\n }\n}\n\nasync function resolveAgentProfileCell(\n input: AgentProfileCell | AgentProfileCellInput,\n): Promise<AgentProfileCell> {\n if (isAgentProfileCell(input)) {\n if (!(await verifyAgentProfileCell(input))) {\n throw new Error(`runEvalCampaign: agentProfile.cellId does not match its content`)\n }\n return input\n }\n return buildAgentProfileCell(input)\n}\n\nfunction isAgentProfileCell(\n input: AgentProfileCell | AgentProfileCellInput,\n): input is AgentProfileCell {\n return 'schemaVersion' in input && 'cellId' in input\n}\n\nfunction assertAgentProfileMatchesRun(\n profile: AgentProfileCell,\n model: string,\n promptHash: string,\n): void {\n if (profile.model !== undefined && profile.model !== model) {\n throw new Error(\n `runEvalCampaign: agentProfile.model \"${profile.model}\" does not match outcome.model \"${model}\"`,\n )\n }\n if (profile.promptHash !== undefined && profile.promptHash !== promptHash) {\n throw new Error(\n `runEvalCampaign: agentProfile.promptHash \"${profile.promptHash}\" does not match outcome.promptHash \"${promptHash}\"`,\n )\n }\n}\n\nfunction defaultRunId(params: CampaignFactoryParams): string {\n // Stable across re-runs: fingerprint of (campaignId, variantId, scenarioId, seed).\n // Caller can override via opts.runId for non-deterministic IDs.\n const base = `${params.campaignId}::${params.variantId}::${params.scenarioId}::${params.seed}`\n // TWO 32-bit FNV-1a accumulators with different offsets, concatenated for a\n // 64-bit-wide id. Not crypto-grade; stability and uniqueness are what this\n // needs. Frozen: the value names a persisted cell, and the second\n // accumulator's offset is part of the identity, so no single-accumulator\n // helper can replace it.\n let h1 = 0x811c9dc5\n let h2 = 0x12345678\n for (let i = 0; i < base.length; i++) {\n const c = base.charCodeAt(i)\n h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0\n h2 = Math.imul(h2 ^ c, 0x9e3779b1) >>> 0\n }\n return `run-${h1.to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AI,GAAG,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG;AAClF"}
1
+ {"version":3,"file":"eval-campaign-DoX5vz3E.js","names":[],"sources":["../src/eval-campaign.ts"],"sourcesContent":["/**\n * EvalCampaign — opinionated matrix runner that wires the four\n * capture-integrity directives by construction.\n *\n * The canonical benchmark shape — matrix runner → for each\n * (variant, scenario, seed) → start a TraceEmitter → call LLMs → end the\n * run → analyze — has a bug class at the integration boundary: raw\n * events not captured, route silently wrong, integrity not asserted,\n * analyst never run. The directives in `SKILL.md § Capture integrity`\n * are the mitigations.\n *\n * `EvalCampaign` is the structural fix — consumers don't wire the\n * integrity surface themselves; the campaign owns it. Specifically:\n *\n * - constructs a per-run `TraceStore` and `RawProviderSink` via factories\n * - builds the run's `ChatClient` through `chatFactory`, handing it the\n * run's raw sink and trace context — a transport built any other way has\n * no raw HTTP envelope, and `assertRunCaptured` says so\n * - calls `assertRunCaptured` after every `endRun` and routes failures\n * through a configurable policy (`throw` / `mark_failed` / `log`)\n * - assembles per-run `RunRecord`s and runs `researchReport` at the end\n * so the campaign artifact is launch-decision-grade by default\n * - embeds the campaign fingerprint (a SHA-256 over the canonicalised\n * run set) and optional `preregistrationHash` in the report\n *\n * The runner contract is intentionally narrow: produce a `CampaignRunOutcome`\n * given a fully-wired `CampaignRunContext`. Everything orchestration-shaped\n * lives in the campaign. This is the inversion-of-control point — consumers\n * stop writing matrix runners and start writing scenario-runners.\n *\n * Out of scope for v1 (tracked in `docs/research-report-methodology.md`):\n *\n * - Distributed/cluster execution (concurrency is local async)\n * - Adaptive sampling / sequential interim looks\n * - Resume from partial state across crashes\n * - LLM-call retry beyond what the caller's transport already does\n */\n\nimport {\n type AgentProfileCell,\n type AgentProfileCellInput,\n buildAgentProfileCell,\n verifyAgentProfileCell,\n} from './agent-profile-cell'\nimport type { ChatClient } from './analyst/chat-client'\nimport { hashJson } from './pre-registration'\nimport type {\n JudgeScoresRecord,\n RunCostProvenance,\n RunJudgeMetadata,\n RunOutcome,\n RunRecord,\n RunSplitTag,\n RunTaskFailure,\n RunTokenUsage,\n} from './run-record'\nimport { validateRunRecord } from './run-record'\nimport { type ResearchReport, type ResearchReportOptions, researchReport } from './summary-report'\nimport type { RunCompleteHook } from './trace/emitter'\nimport { TraceEmitter } from './trace/emitter'\nimport {\n assertRunCaptured,\n RunIntegrityError,\n type RunIntegrityExpectations,\n type RunIntegrityReport,\n} from './trace/integrity'\nimport { FileSystemRawProviderSink, type RawProviderSink } from './trace/raw-provider-sink'\nimport type { TraceStore } from './trace/store'\n\n// ── Public types ─────────────────────────────────────────────────────────\n\nexport interface CampaignVariant<V> {\n id: string\n payload: V\n}\n\nexport interface CampaignScenario {\n scenarioId: string\n /** Free-form metadata propagated to runs and reports. */\n tags?: Record<string, string>\n}\n\nexport interface CampaignRunContext<V> {\n /** Stable run id. The campaign generates this; the runner does not. */\n runId: string\n /** Logical experiment id (campaignId by default; overridable per-run via opts). */\n experimentId: string\n variant: V\n variantId: string\n scenarioId: string\n scenarioTags: Record<string, string>\n seed: number\n splitTag: RunSplitTag\n /**\n * The TraceEmitter for this run, with `onRunComplete` hooks pre-wired\n * (analyst auto-execution if configured, plus integrity check). The\n * runner MUST call `emitter.startRun` before doing any work and either\n * `emitter.endRun` or `emitter.abortRun` before returning.\n */\n emitter: TraceEmitter\n store: TraceStore\n rawSink: RawProviderSink\n /**\n * The run's model transport, built by `chatFactory` with this run's\n * `rawSink` and `runId` already bound.\n */\n chat: ChatClient\n}\n\n/** What the campaign binds into the run's transport. */\nexport interface CampaignChatWiring {\n /**\n * Raw provider sink for this run. Bind it into the transport: the campaign's\n * integrity check requires every LLM span to carry a matching raw request\n * event, so a transport built without it fails `assertRunCaptured`.\n */\n rawSink: RawProviderSink\n runId: string\n}\n\ninterface CampaignRunOutcomeFields {\n /** Did the run pass? Mirrors `RunOutcome.pass` semantics. */\n pass: boolean\n /** Score for the run on its split. Maps to `searchScore` or `holdoutScore`. */\n score: number\n /** Cost in USD, or null when the runner could not capture it. */\n costUsd: number | null\n /** Source of the cost amount. */\n costProvenance: RunCostProvenance\n tokenUsage: RunTokenUsage\n /** Snapshot model id (e.g. `claude-sonnet-4-6@2025-04-15`). */\n model: string\n /** sha256 of the effective prompt sent to the model. */\n promptHash: string\n /** sha256 of the effective config (model, temperature, tools, judges, splits). */\n configHash: string\n /** Optional extra numeric metrics to land in `outcome.raw`. */\n raw?: Record<string, number>\n /** Optional judge metadata when a judge was used. */\n judgeMetadata?: RunJudgeMetadata\n /**\n * Optional per-judge / per-dim breakdown for ensemble-judged runs.\n * Propagated to `outcome.judgeScores` on the resulting `RunRecord`.\n * Single-judge or scalar-only runs leave this unset.\n */\n judgeScores?: JudgeScoresRecord\n /**\n * Agent profile cell observed by the runner. When supplied, it overrides\n * `EvalCampaignOptions.agentProfile` for this run and must match the\n * outcome's `model` and `promptHash`.\n */\n agentProfile?: AgentProfileCell | AgentProfileCellInput\n}\n\n/** Campaign result with the same task-failure invariant as `RunRecord`. */\nexport type CampaignRunOutcome = CampaignRunOutcomeFields & RunTaskFailure\n\nexport type CampaignRunner<V> = (ctx: CampaignRunContext<V>) => Promise<CampaignRunOutcome>\n\nexport type CampaignIntegrityPolicy = 'throw' | 'mark_failed' | 'log'\n\nexport interface EvalCampaignOptions<V> {\n /**\n * Stable id for the campaign. Used as the default `experimentId` on\n * every run, and folded into the campaign fingerprint.\n */\n campaignId: string\n variants: CampaignVariant<V>[]\n scenarios: CampaignScenario[]\n /** Default `[0, 1, 2]`. */\n seeds?: number[]\n /** Default `'holdout'` — the split that anchors a launch decision. */\n splitTag?: RunSplitTag\n /** Git SHA the campaign is run against. Mandatory; `RunRecord` rejects unset. */\n commitSha: string\n /**\n * Build the model transport for one run. agent-eval executes no paid model:\n * the caller owns the transport and the credential never enters this\n * package. The campaign calls this once per run and passes the run's raw\n * provider sink and `runId`, so a transport that binds them captures the\n * raw HTTP envelope `assertRunCaptured` checks for.\n */\n chatFactory: (wiring: CampaignChatWiring) => ChatClient\n /**\n * Caller-declared identity of the execution route, folded into the campaign\n * fingerprint so two campaigns run against different endpoints do not share\n * one identity. agent-eval no longer knows the endpoint; the owner of\n * execution names it.\n */\n executionRef?: string\n /**\n * Per-run TraceStore factory. Common shape: a fresh store per run keyed\n * on `runId`. Implementations that share a store across the campaign\n * are valid — the campaign only writes through `emitter`.\n */\n storeFactory: (params: CampaignFactoryParams) => TraceStore\n /**\n * Per-run RawProviderSink factory. Defaults to `FileSystemRawProviderSink`\n * rooted at `${workDir}/raw-events/${runId}` if `workDir` is supplied;\n * otherwise required. Forensic capture is non-negotiable in a campaign\n * run — pass `NoopRawProviderSink` explicitly if you want to opt out.\n */\n rawSinkFactory?: (params: CampaignFactoryParams) => RawProviderSink\n /**\n * Filesystem root for default `rawSinkFactory`. Ignored if\n * `rawSinkFactory` is supplied.\n */\n workDir?: string\n /**\n * Extra `onRunComplete` hooks the campaign appends (after its own\n * integrity-check hook). Pass `traceAnalystOnRunComplete(...)` here.\n */\n onRunComplete?: RunCompleteHook[]\n /**\n * Per-run integrity expectations. Defaults to:\n * `{ llmSpansMin: 1, requireRawCoverageOfLlmSpans: true, requireOutcome: true }`.\n * Override (e.g. `{ llmSpansMin: 0 }`) for runs that don't call LLMs.\n */\n integrity?: RunIntegrityExpectations\n /** Behaviour when integrity fails. Default `'mark_failed'`. */\n onIntegrityFailure?: CampaignIntegrityPolicy\n /**\n * Per-run runner. Receives a fully-wired context; produces an outcome\n * the campaign converts into a `RunRecord`.\n */\n runner: CampaignRunner<V>\n /**\n * If set, the campaign computes `researchReport` at the end. `comparator`\n * is a `variantId`. Other fields are forwarded verbatim.\n */\n report?: { comparator?: string } & Omit<\n ResearchReportOptions,\n 'comparator' | 'preregistrationHash' | 'generatedAt'\n >\n /**\n * Hash of a signed `HypothesisManifest` (see `pre-registration.ts`).\n * Embedded in the campaign fingerprint and the research report.\n */\n preregistrationHash?: string\n /** Local concurrency. Default `1` (sequential). */\n concurrency?: number\n /**\n * Override the time source. Tests pass a mock to make wallMs deterministic.\n */\n now?: () => number\n /** Override the runId generator. Tests pin this. */\n runId?: (params: CampaignFactoryParams) => string\n /**\n * Agent profile cell for campaign runs. Static profiles can pass an object;\n * routers or variant-specific harnesses can pass a factory. The campaign\n * stamps the built cell onto every `RunRecord` and rejects profile/model or\n * profile/prompt contradictions.\n */\n agentProfile?:\n | AgentProfileCell\n | AgentProfileCellInput\n | ((\n params: CampaignFactoryParams & {\n variant: V\n scenarioTags: Record<string, string>\n },\n ) =>\n | AgentProfileCell\n | AgentProfileCellInput\n | Promise<AgentProfileCell | AgentProfileCellInput>)\n}\n\nexport interface CampaignFactoryParams {\n campaignId: string\n runId: string\n variantId: string\n scenarioId: string\n seed: number\n}\n\nexport interface FailedRun {\n runId: string\n variantId: string\n scenarioId: string\n seed: number\n reason: string\n error?: string\n}\n\nexport interface EvalCampaignResult {\n campaignId: string\n /** SHA-256 over canonicalised `(variantIds, scenarioIds, seeds, comparator, splitTag, executionRef, preregistrationHash)`. */\n campaignFingerprint: string\n preregistrationHash: string | null\n /** Successful runs only. Failed runs land in `failedRuns`. */\n runs: RunRecord[]\n /** Integrity reports for every successful run. */\n integrityReports: RunIntegrityReport[]\n failedRuns: FailedRun[]\n /** Computed when `report` is set on options. */\n report?: ResearchReport\n startedAt: string\n endedAt: string\n}\n\n// ── Implementation ───────────────────────────────────────────────────────\n\nconst DEFAULT_INTEGRITY: RunIntegrityExpectations = {\n llmSpansMin: 1,\n requireRawCoverageOfLlmSpans: true,\n requireOutcome: true,\n}\n\ntype CampaignCell<V> = { variant: CampaignVariant<V>; scenario: CampaignScenario; seed: number }\n\ntype CampaignRunResult = { record: RunRecord; integrity: RunIntegrityReport }\n\n/** Resolved options shared by every step of one campaign. */\ninterface CampaignSettings {\n seeds: number[]\n splitTag: RunSplitTag\n concurrency: number\n integrity: RunIntegrityExpectations\n onIntegrityFailure: CampaignIntegrityPolicy\n now: () => number\n executionRef: string | null\n preregistrationHash: string | null\n rawSinkFactory: (params: CampaignFactoryParams) => RawProviderSink\n}\n\n/**\n * Mutable state of one campaign's worker pool.\n *\n * A genuine (non-CellExecutionError) error from any worker is a bug, not a\n * run-level failure. We must NOT let `Promise.all` reject mid-flight and\n * orphan the other workers' in-progress runs (emitters never finalized,\n * sinks/handles leak, partial work silently discarded). Instead: capture the\n * first genuine error, stop dispatching new cells so in-flight workers wind\n * down, finalize every still-open run, then re-throw the aggregated error.\n */\ninterface CampaignPool<V> {\n opts: EvalCampaignOptions<V>\n settings: CampaignSettings\n cells: CampaignCell<V>[]\n cursor: number\n aborting: boolean\n genuineErrors: unknown[]\n /**\n * Emitters for runs that are currently mid-flight, keyed by runId. A worker\n * registers its emitter before invoking the runner and removes it once the\n * run is finalized (via endRun/abortRun, success or failure). Anything left\n * here after the pool settles is an orphan we must abort.\n */\n openRuns: Map<string, TraceEmitter>\n runs: RunRecord[]\n integrityReports: RunIntegrityReport[]\n failedRuns: FailedRun[]\n}\n\nexport async function runEvalCampaign<V>(\n opts: EvalCampaignOptions<V>,\n): Promise<EvalCampaignResult> {\n assertCampaignPreflight(opts)\n const settings = resolveCampaignSettings(opts)\n const campaignFingerprint = await fingerprintCampaign(opts, settings)\n\n const startedAt = new Date(settings.now()).toISOString()\n const pool: CampaignPool<V> = {\n opts,\n settings,\n cells: planCampaignCells(opts, settings.seeds),\n cursor: 0,\n aborting: false,\n genuineErrors: [],\n openRuns: new Map(),\n runs: [],\n integrityReports: [],\n failedRuns: [],\n }\n await drainCampaignPool(pool)\n\n const report = await buildCampaignReport(opts, settings, pool.runs)\n const endedAt = new Date(settings.now()).toISOString()\n\n return {\n campaignId: opts.campaignId,\n campaignFingerprint,\n preregistrationHash: settings.preregistrationHash,\n runs: pool.runs,\n integrityReports: pool.integrityReports,\n failedRuns: pool.failedRuns,\n report,\n startedAt,\n endedAt,\n }\n}\n\n/** Reject structurally invalid campaigns before any work starts. */\nfunction assertCampaignPreflight<V>(opts: EvalCampaignOptions<V>): void {\n if (opts.variants.length === 0) {\n throw new Error('runEvalCampaign: variants must be non-empty.')\n }\n if (opts.scenarios.length === 0) {\n throw new Error('runEvalCampaign: scenarios must be non-empty.')\n }\n const variantIds = new Set<string>()\n for (const v of opts.variants) {\n if (variantIds.has(v.id)) {\n throw new Error(`runEvalCampaign: duplicate variant id \"${v.id}\".`)\n }\n variantIds.add(v.id)\n }\n const scenarioIds = new Set<string>()\n for (const s of opts.scenarios) {\n if (scenarioIds.has(s.scenarioId)) {\n throw new Error(`runEvalCampaign: duplicate scenarioId \"${s.scenarioId}\".`)\n }\n scenarioIds.add(s.scenarioId)\n }\n if (opts.report?.comparator && !variantIds.has(opts.report.comparator)) {\n throw new Error(\n `runEvalCampaign: report.comparator \"${opts.report.comparator}\" is not a configured variantId.`,\n )\n }\n if (!opts.commitSha) {\n throw new Error('runEvalCampaign: commitSha is required (every RunRecord needs it).')\n }\n}\n\n/** Apply defaults to the optional campaign options. */\nfunction resolveCampaignSettings<V>(opts: EvalCampaignOptions<V>): CampaignSettings {\n return {\n seeds: opts.seeds ?? [0, 1, 2],\n splitTag: opts.splitTag ?? 'holdout',\n concurrency: Math.max(1, opts.concurrency ?? 1),\n integrity: { ...DEFAULT_INTEGRITY, ...(opts.integrity ?? {}) },\n onIntegrityFailure: opts.onIntegrityFailure ?? 'mark_failed',\n now: opts.now ?? (() => Date.now()),\n executionRef: opts.executionRef ?? null,\n preregistrationHash: opts.preregistrationHash ?? null,\n rawSinkFactory: opts.rawSinkFactory ?? defaultRawSinkFactory(opts.workDir),\n }\n}\n\n/** SHA-256 over the canonicalised matrix definition. */\nfunction fingerprintCampaign<V>(\n opts: EvalCampaignOptions<V>,\n settings: CampaignSettings,\n): Promise<string> {\n return hashJson({\n campaignId: opts.campaignId,\n variants: opts.variants.map((v) => v.id).sort(),\n scenarios: opts.scenarios.map((s) => s.scenarioId).sort(),\n seeds: [...settings.seeds].sort((a, b) => a - b),\n splitTag: settings.splitTag,\n comparator: opts.report?.comparator ?? null,\n executionRef: settings.executionRef,\n preregistrationHash: settings.preregistrationHash,\n })\n}\n\n/** Expand variants x scenarios x seeds, variant-major. */\nfunction planCampaignCells<V>(opts: EvalCampaignOptions<V>, seeds: number[]): CampaignCell<V>[] {\n const cells: CampaignCell<V>[] = []\n for (const variant of opts.variants) {\n for (const scenario of opts.scenarios) {\n for (const seed of seeds) {\n cells.push({ variant, scenario, seed })\n }\n }\n }\n return cells\n}\n\n/**\n * Run the bounded-concurrency worker pool to completion, finalize any run left\n * open, and re-throw the genuine errors the workers captured.\n */\nasync function drainCampaignPool<V>(pool: CampaignPool<V>): Promise<void> {\n const workers = Array.from(\n { length: Math.min(pool.settings.concurrency, pool.cells.length) },\n () => campaignWorker(pool),\n )\n // allSettled (not all): a genuine error in one worker must not reject the\n // pool mid-flight and orphan the others. Each worker captures its own\n // genuine error into `genuineErrors` and returns; we re-throw below.\n await Promise.allSettled(workers)\n\n // Finalize any run still open after the pool wound down. With the\n // stop-dispatch flag these are the runs that were mid-flight in peer workers\n // when the first genuine error fired — abort them so their emitters finalize\n // (hooks fire, store records a terminal status) instead of leaking.\n for (const [runId, emitter] of pool.openRuns) {\n await finalizeAbort(emitter, runId, 'campaign aborted: genuine error in a sibling run')\n }\n pool.openRuns.clear()\n\n if (pool.genuineErrors.length > 0) {\n throw pool.genuineErrors.length === 1\n ? pool.genuineErrors[0]\n : new AggregateError(\n pool.genuineErrors,\n `runEvalCampaign: ${pool.genuineErrors.length} runs failed with genuine (non-run-level) errors`,\n )\n }\n}\n\n/** Pull cells off the shared cursor until none remain or the pool is aborting. */\nasync function campaignWorker<V>(pool: CampaignPool<V>): Promise<void> {\n while (!pool.aborting) {\n const i = pool.cursor++\n if (i >= pool.cells.length) return\n const cell = pool.cells[i]!\n try {\n const result = await runCampaignCell(pool, cell)\n pool.runs.push(result.record)\n pool.integrityReports.push(result.integrity)\n } catch (err) {\n if (err instanceof CellExecutionError) {\n pool.failedRuns.push(err.failed)\n if (err.integrity) pool.integrityReports.push(err.integrity)\n } else {\n // Genuine bug — not a runner failure, not an integrity failure.\n // Capture it and stop dispatching so peers wind down gracefully;\n // re-thrown after the pool settles. Do not surface here — that would\n // reject Promise.all and orphan the other workers' runs.\n pool.genuineErrors.push(err)\n pool.aborting = true\n return\n }\n }\n }\n}\n\n/** Run one matrix cell: runner, integrity check, then the validated RunRecord. */\nasync function runCampaignCell<V>(\n pool: CampaignPool<V>,\n cell: CampaignCell<V>,\n): Promise<CampaignRunResult> {\n const { opts, settings } = pool\n const runId = (opts.runId ?? defaultRunId)({\n campaignId: opts.campaignId,\n runId: '', // unused by default generator\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n seed: cell.seed,\n })\n const factoryParams: CampaignFactoryParams = {\n campaignId: opts.campaignId,\n runId,\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n seed: cell.seed,\n }\n const store = opts.storeFactory(factoryParams)\n const rawSink = settings.rawSinkFactory(factoryParams)\n\n const emitter = new TraceEmitter(store, {\n runId,\n now: opts.now,\n onRunComplete: opts.onRunComplete,\n })\n // Track this run as open so a genuine error elsewhere in the pool can\n // finalize it instead of orphaning it. Removed in the finally below.\n pool.openRuns.set(runId, emitter)\n\n const chat = opts.chatFactory({ rawSink, runId })\n\n const ctx: CampaignRunContext<V> = {\n runId,\n experimentId: opts.campaignId,\n variant: cell.variant.payload,\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n scenarioTags: cell.scenario.tags ?? {},\n seed: cell.seed,\n splitTag: settings.splitTag,\n emitter,\n store,\n rawSink,\n chat,\n }\n\n try {\n const wallStart = settings.now()\n const outcome = await invokeCampaignRunner(opts, cell, ctx)\n const wallMs = settings.now() - wallStart\n\n const integrityReport = await assertRunCaptured(store, runId, {\n ...settings.integrity,\n rawSink,\n })\n if (!integrityReport.ok) admitOrRejectIntegrity(settings, cell, runId, integrityReport)\n\n const record = buildCampaignRunRecord(opts, settings, cell, runId, outcome, wallMs)\n await stampAgentProfile(opts, cell, record, runId, outcome)\n return { record: validateRunRecord(record), integrity: integrityReport }\n } finally {\n // This run's worker has finished with it (success, run-level failure, or\n // genuine error). It is no longer the pool's job to finalize — drop it so\n // the post-settle sweep doesn't double-abort a finalized run.\n pool.openRuns.delete(runId)\n }\n}\n\n/** Invoke the runner; a throw aborts the run and becomes a run-level failure. */\nasync function invokeCampaignRunner<V>(\n opts: EvalCampaignOptions<V>,\n cell: CampaignCell<V>,\n ctx: CampaignRunContext<V>,\n): Promise<CampaignRunOutcome> {\n try {\n return await opts.runner(ctx)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n // The runner threw mid-execution. Abort the run so the emitter\n // finalizes. The only benign abortRun failure is \"the runner never\n // started the run\" (nothing to finalize). A store-write failure (disk\n // full, FS error) is a genuine diagnostic — surface it rather than\n // masking it as a plain runner failure.\n await finalizeAbort(ctx.emitter, ctx.runId, message)\n throw new CellExecutionError({\n runId: ctx.runId,\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n seed: cell.seed,\n reason: 'runner_threw',\n error: message,\n })\n }\n}\n\n/** Apply the integrity-failure policy to a report that is not ok. */\nfunction admitOrRejectIntegrity<V>(\n settings: CampaignSettings,\n cell: CampaignCell<V>,\n runId: string,\n integrityReport: RunIntegrityReport,\n): void {\n switch (settings.onIntegrityFailure) {\n case 'throw':\n throw new RunIntegrityError(integrityReport)\n case 'mark_failed':\n throw new CellExecutionError(\n {\n runId,\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n seed: cell.seed,\n reason: 'integrity_failed',\n error: integrityReport.issues.map((i) => i.code).join(', '),\n },\n integrityReport,\n )\n case 'log':\n // Caller wants the run admitted with a flagged report; fall through.\n break\n }\n}\n\n/** Assemble the RunRecord for a successful run, before profile stamping. */\nfunction buildCampaignRunRecord<V>(\n opts: EvalCampaignOptions<V>,\n settings: CampaignSettings,\n cell: CampaignCell<V>,\n runId: string,\n outcome: CampaignRunOutcome,\n wallMs: number,\n): RunRecord {\n const recordOutcome: RunOutcome = {\n raw: outcome.raw ?? {},\n }\n if (settings.splitTag === 'holdout') recordOutcome.holdoutScore = outcome.score\n else recordOutcome.searchScore = outcome.score\n if (outcome.judgeScores !== undefined) recordOutcome.judgeScores = outcome.judgeScores\n\n return {\n runId,\n experimentId: opts.campaignId,\n candidateId: cell.variant.id,\n seed: cell.seed,\n model: outcome.model,\n promptHash: outcome.promptHash,\n configHash: outcome.configHash,\n commitSha: opts.commitSha,\n wallMs,\n costUsd: outcome.costUsd,\n costProvenance: outcome.costProvenance,\n tokenUsage: outcome.tokenUsage,\n terminalOutcome: 'succeeded',\n judgeMetadata: outcome.judgeMetadata,\n outcome: recordOutcome,\n ...(outcome.failureClass ? { failureClass: outcome.failureClass } : {}),\n failureMode: outcome.failureMode,\n splitTag: settings.splitTag,\n scenarioId: cell.scenario.scenarioId,\n }\n}\n\n/** Resolve the run's agent profile (outcome first, then options) and stamp it on the record. */\nasync function stampAgentProfile<V>(\n opts: EvalCampaignOptions<V>,\n cell: CampaignCell<V>,\n record: RunRecord,\n runId: string,\n outcome: CampaignRunOutcome,\n): Promise<void> {\n const profileSource =\n outcome.agentProfile ??\n (typeof opts.agentProfile === 'function'\n ? await opts.agentProfile({\n campaignId: opts.campaignId,\n runId,\n variantId: cell.variant.id,\n scenarioId: cell.scenario.scenarioId,\n seed: cell.seed,\n variant: cell.variant.payload,\n scenarioTags: cell.scenario.tags ?? {},\n })\n : opts.agentProfile)\n if (profileSource !== undefined) {\n const agentProfile = await resolveAgentProfileCell(profileSource)\n assertAgentProfileMatchesRun(agentProfile, outcome.model, outcome.promptHash)\n record.agentProfile = agentProfile\n }\n}\n\n/** Build the optional research report over the successful runs. */\nasync function buildCampaignReport<V>(\n opts: EvalCampaignOptions<V>,\n settings: CampaignSettings,\n runs: RunRecord[],\n): Promise<ResearchReport | undefined> {\n if (!opts.report) return undefined\n const reportOpts: ResearchReportOptions = {\n ...opts.report,\n comparator: opts.report.comparator,\n split: settings.splitTag === 'dev' ? 'search' : settings.splitTag,\n generatedAt: new Date(settings.now()).toISOString(),\n preregistrationHash: settings.preregistrationHash ?? undefined,\n }\n return researchReport(runs, reportOpts)\n}\n\n// ── Internal ─────────────────────────────────────────────────────────────\n\nclass CellExecutionError extends Error {\n readonly failed: FailedRun\n readonly integrity?: RunIntegrityReport\n constructor(failed: FailedRun, integrity?: RunIntegrityReport) {\n super(`cell ${failed.variantId}/${failed.scenarioId}@${failed.seed} failed: ${failed.reason}`)\n this.failed = failed\n this.integrity = integrity\n }\n}\n\n/**\n * Abort a run whose owning work threw or was orphaned by a sibling's genuine\n * error, finalizing the emitter so hooks fire and the store records a terminal\n * status. Safe to call unconditionally: it only aborts runs that are still\n * `running`. Two no-op cases are intentional and benign:\n *\n * - the run was never started (absent from the store) — nothing to finalize\n * - the run is already terminal (`completed` / `failed` / `aborted`) —\n * finalizing again would overwrite the real outcome (e.g. flip a passed run\n * to `aborted` with `{ pass: false, notes: reason }`), so we leave it alone\n *\n * Any OTHER failure of the store read or the abort write (disk full, FS fault,\n * backend down) is a genuine diagnostic and propagates rather than being\n * swallowed.\n */\nasync function finalizeAbort(emitter: TraceEmitter, runId: string, reason: string): Promise<void> {\n const existing = await emitter.traceStore.getRun(runId)\n if (existing === undefined) return // run never started; nothing to abort\n if (existing.status !== 'running') return // already finalized; never overwrite a real outcome\n // The emitter never throws on a failed store write; it counts it. A failed\n // abort write is a genuine diagnostic here, so read the count and surface it.\n const droppedBefore = emitter.captureStats().dropped\n await emitter.abortRun(reason)\n const after = emitter.captureStats()\n if (after.dropped > droppedBefore) {\n throw new Error(`finalizeAbort: run ${runId} could not be finalized: ${after.lastError}`)\n }\n}\n\nfunction defaultRawSinkFactory(workDir: string | undefined) {\n return (params: CampaignFactoryParams): RawProviderSink => {\n if (!workDir) {\n throw new Error(\n 'runEvalCampaign: rawSinkFactory not supplied and workDir not set. Pass either to enable raw provider capture, or pass `new NoopRawProviderSink()` via rawSinkFactory to opt out explicitly.',\n )\n }\n return new FileSystemRawProviderSink({\n dir: `${workDir}/raw-events/${params.runId}`,\n })\n }\n}\n\nasync function resolveAgentProfileCell(\n input: AgentProfileCell | AgentProfileCellInput,\n): Promise<AgentProfileCell> {\n if (isAgentProfileCell(input)) {\n if (!(await verifyAgentProfileCell(input))) {\n throw new Error(`runEvalCampaign: agentProfile.cellId does not match its content`)\n }\n return input\n }\n return buildAgentProfileCell(input)\n}\n\nfunction isAgentProfileCell(\n input: AgentProfileCell | AgentProfileCellInput,\n): input is AgentProfileCell {\n return 'schemaVersion' in input && 'cellId' in input\n}\n\nfunction assertAgentProfileMatchesRun(\n profile: AgentProfileCell,\n model: string,\n promptHash: string,\n): void {\n if (profile.model !== undefined && profile.model !== model) {\n throw new Error(\n `runEvalCampaign: agentProfile.model \"${profile.model}\" does not match outcome.model \"${model}\"`,\n )\n }\n if (profile.promptHash !== undefined && profile.promptHash !== promptHash) {\n throw new Error(\n `runEvalCampaign: agentProfile.promptHash \"${profile.promptHash}\" does not match outcome.promptHash \"${promptHash}\"`,\n )\n }\n}\n\nfunction defaultRunId(params: CampaignFactoryParams): string {\n // Stable across re-runs: fingerprint of (campaignId, variantId, scenarioId, seed).\n // Caller can override via opts.runId for non-deterministic IDs.\n const base = `${params.campaignId}::${params.variantId}::${params.scenarioId}::${params.seed}`\n // TWO 32-bit FNV-1a accumulators with different offsets, concatenated for a\n // 64-bit-wide id. Not crypto-grade; stability and uniqueness are what this\n // needs. Frozen: the value names a persisted cell, and the second\n // accumulator's offset is part of the identity, so no single-accumulator\n // helper can replace it.\n let h1 = 0x811c9dc5\n let h2 = 0x12345678\n for (let i = 0; i < base.length; i++) {\n const c = base.charCodeAt(i)\n h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0\n h2 = Math.imul(h2 ^ c, 0x9e3779b1) >>> 0\n }\n return `run-${h1.toString(16).padStart(8, '0')}${h2.toString(16).padStart(8, '0')}`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8SA,MAAM,oBAA8C;CAClD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as CostLedgerHandle } from "./cost-ledger-C1W3ICmP.js";
2
- import { i as AnalystFinding, n as AnalystContext, t as Analyst } from "./types-8yQzNm8u.js";
3
- import { R as Scenario, S as JudgeConfig, w as JudgeScore } from "./types-CHfn1zg5.js";
2
+ import { i as AnalystFinding, n as AnalystContext, t as Analyst } from "./types-DGImvHIr.js";
3
+ import { R as Scenario, S as JudgeConfig, w as JudgeScore } from "./types-DDKfH-N6.js";
4
4
  //#region src/evaluation.d.ts
5
5
  interface EvaluationResult<T> {
6
6
  value: T;
@@ -72,4 +72,4 @@ interface EvaluationAnalystOptions<I, O> {
72
72
  declare function asAnalyst<I, O>(options: EvaluationAnalystOptions<I, O>): Analyst<I>;
73
73
  //#endregion
74
74
  export { EvaluationResult as a, asJudge as c, EvaluationJudgeOptions as i, createEvaluator as l, EvaluationAnalystOptions as n, EvaluatorOptions as o, EvaluationContext as r, asAnalyst as s, CostedEvaluator as t };
75
- //# sourceMappingURL=evaluation-CBdQt_kr.d.ts.map
75
+ //# sourceMappingURL=evaluation-D1PGzkPR.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"evaluation-CBdQt_kr.d.ts","names":[],"sources":["../src/evaluation.ts"],"mappings":";;;;UAWiB,iBAAiB;EAChC,OAAO;EACP,SAAS;EACT;;UAGe;;;EAGf;EACA,SAAS;EACT,aAAa;EACb;EACA,UAAU;EACV;EACA,WAAW;EACX,gBAAgB;;EAEhB,aAAa,SAAS,uBAAuB;;KAGnC,gBAAgB,GAAG,MAC7B,OAAO,GACP,UAAU,sBACP,QAAQ,iBAAiB;UAEb,iBAAiB,GAAG;EACnC,UAAU,OAAO,GAAG;IAAW,QAAQ;IAAa;QAA6B,QAAQ;EACzF,UAAU,OAAO,MAAM;EACvB,oBAAoB,OAAO,UAAU;EACrC,mBAAmB,OAAO;EAC1B,aAAa;EACb,gBAAgB;;EAEhB,YAAY,OAAO,GAAG,OAAO,aAAa;;;iBAI5B,gBAAgB,GAAG,GAAG,SAAS,iBAAiB,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gBAAgB,GAAG,GAAG,SAAS,iBAAiB,GAAG,KAAK,gBAAgB,GAAG;UA6B1E,uBAAuB,GAAG,UAAU,UAAU;EAC7D;EACA;EACA,YAAY,YAAY,GAAG;EAC3B,UAAU;IAAkB,UAAU;IAAG,UAAU;KAAK;EACxD,MAAM,OAAO,GAAG;IAAS,UAAU;IAAG,UAAU;QAAQ,aAAa,QAAQ;;EAE7E,UACE,QAAQ,iBAAiB,IACzB;IAAS,UAAU;IAAG,UAAU;eACtB;EACZ,aAAa,UAAU;;;iBAIT,QAAQ,GAAG,UAAU,UAAU,GAC7C,SAAS,uBAAuB,GAAG,GAAG,KACrC,YAAY,GAAG;UA4BD,yBAAyB,GAAG;EAC3C;EACA;EACA;EACA,WAAW,QAAQ;EACnB,MAAM,QAAQ;EACd,WACE,OAAO,GACP,SAAS,mBACT,gBAAgB,mBACb,QAAQ,iBAAiB;EAC9B,MAAM,OAAO,GAAG,OAAO,GAAG,SAAS,mBAAmB,mBAAmB,QAAQ;EACjF,UAAU,QAAQ,iBAAiB,IAAI,OAAO,GAAG,SAAS,0BAA0B;;;iBAItE,UAAU,GAAG,GAAG,SAAS,yBAAyB,GAAG,KAAK,QAAQ"}
@@ -0,0 +1,147 @@
1
+ import { t as CostLedger } from "./cost-ledger-BGZB6yY2.js";
2
+ //#region src/analyst/evaluation-context.ts
3
+ /** One deadline, spending authority and usage bridge for every evaluation-backed analyst. */
4
+ function analystEvaluationContext(context, actor) {
5
+ const signals = context.signal ? [context.signal] : [];
6
+ if (context.deadlineMs !== void 0) {
7
+ const remaining = context.deadlineMs - Date.now();
8
+ if (!Number.isFinite(remaining)) throw new TypeError("Analyst deadline must be finite");
9
+ if (remaining <= 0) throw new DOMException("Analyst deadline exceeded", "TimeoutError");
10
+ signals.push(AbortSignal.timeout(Math.ceil(remaining)));
11
+ }
12
+ const signal = AbortSignal.any(signals);
13
+ signal.throwIfAborted();
14
+ return {
15
+ analystContext: {
16
+ ...context,
17
+ signal
18
+ },
19
+ evaluation: {
20
+ signal,
21
+ costLedger: context.costLedger ?? (context.budgetUsd === void 0 ? void 0 : new CostLedger({ costCeilingUsd: context.budgetUsd })),
22
+ actor,
23
+ channel: "analyst",
24
+ costPhase: context.costPhase,
25
+ costTags: {
26
+ ...context.tags,
27
+ runId: context.runId,
28
+ correlationId: context.correlationId
29
+ },
30
+ onReceipt: (receipt) => context.recordUsage?.({
31
+ calls: 1,
32
+ tokens: receipt.usageUnknown ? null : {
33
+ input: receipt.inputTokens,
34
+ output: receipt.outputTokens
35
+ },
36
+ cost: receipt.costUnknown ? {
37
+ kind: "uncaptured",
38
+ usd: null
39
+ } : {
40
+ kind: receipt.actualCostUsd === void 0 ? "estimated" : "observed",
41
+ usd: receipt.costUsd
42
+ }
43
+ })
44
+ }
45
+ };
46
+ }
47
+ //#endregion
48
+ //#region src/evaluation.ts
49
+ /** A metered function, independent of providers, question formats, and application policy. */
50
+ function createEvaluator(options) {
51
+ const defaults = { ...options };
52
+ const ledger = defaults.costLedger ?? new CostLedger();
53
+ return async (input, context = {}) => {
54
+ context.signal?.throwIfAborted();
55
+ const started = performance.now();
56
+ const paid = await (context.costLedger ?? ledger).runPaidCall({
57
+ callId: context.callId,
58
+ actor: context.actor ?? "evaluation",
59
+ channel: context.channel ?? "evaluation",
60
+ phase: context.costPhase ?? "evaluation",
61
+ tags: context.costTags,
62
+ model: typeof defaults.model === "function" ? defaults.model(input) : defaults.model,
63
+ signal: context.signal,
64
+ maximumCharge: context.maximumCharge ?? defaults.maximumCharge,
65
+ execute: (signal, idempotencyKey) => defaults.execute(input, {
66
+ signal,
67
+ idempotencyKey
68
+ }),
69
+ receipt: defaults.receipt,
70
+ receiptFromError: defaults.receiptFromError
71
+ });
72
+ if (paid.receipt) await context.onReceipt?.(paid.receipt);
73
+ if (!paid.succeeded) throw paid.error;
74
+ context.signal?.throwIfAborted();
75
+ await defaults.validate?.(paid.value, input);
76
+ context.signal?.throwIfAborted();
77
+ return {
78
+ value: paid.value,
79
+ receipt: paid.receipt,
80
+ durationMs: performance.now() - started
81
+ };
82
+ };
83
+ }
84
+ /** Return the existing contract. Mapping never performs another inference call. */
85
+ function asJudge(options) {
86
+ const config = {
87
+ ...options,
88
+ dimensions: structuredClone(options.dimensions)
89
+ };
90
+ return {
91
+ name: config.name,
92
+ judgeVersion: config.version,
93
+ dimensions: config.dimensions,
94
+ appliesTo: config.appliesTo,
95
+ async score({ artifact, scenario, signal, costLedger, costPhase, costTags }) {
96
+ signal.throwIfAborted();
97
+ const input = {
98
+ artifact,
99
+ scenario
100
+ };
101
+ const result = await config.evaluate(input, {
102
+ signal,
103
+ costLedger,
104
+ actor: config.name,
105
+ channel: "judge",
106
+ costPhase,
107
+ costTags: {
108
+ ...costTags,
109
+ scenarioId: scenario.id
110
+ }
111
+ });
112
+ await config.record?.(result, input);
113
+ signal.throwIfAborted();
114
+ const score = await config.map(result.value, input);
115
+ signal.throwIfAborted();
116
+ return score;
117
+ }
118
+ };
119
+ }
120
+ /** Registry, graph, and trace consumers keep the same Analyst interface. */
121
+ function asAnalyst(options) {
122
+ const config = {
123
+ ...options,
124
+ cost: structuredClone(options.cost)
125
+ };
126
+ return {
127
+ id: config.id,
128
+ version: config.version,
129
+ description: config.description,
130
+ inputKind: config.inputKind,
131
+ cost: config.cost,
132
+ async analyze(input, context) {
133
+ const { evaluation, analystContext } = analystEvaluationContext(context, config.id);
134
+ const signal = analystContext.signal;
135
+ const result = await config.evaluate(input, evaluation, analystContext);
136
+ await config.record?.(result, input, analystContext);
137
+ signal.throwIfAborted();
138
+ const findings = await config.map(result.value, input, analystContext);
139
+ signal.throwIfAborted();
140
+ return findings;
141
+ }
142
+ };
143
+ }
144
+ //#endregion
145
+ export { analystEvaluationContext as i, asJudge as n, createEvaluator as r, asAnalyst as t };
146
+
147
+ //# sourceMappingURL=evaluation-wdGyZ7jV.js.map