@tangle-network/agent-eval 2.0.11 → 2.0.13

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 (164) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/adapters/http.d.ts +2 -2
  3. package/dist/{agent-profile-_JzxgLDM.d.ts → agent-profile-8S2LfCvs.d.ts} +4 -4
  4. package/dist/{agent-profile-_JzxgLDM.d.ts.map → agent-profile-8S2LfCvs.d.ts.map} +1 -1
  5. package/dist/analyst/index.d.ts +324 -74
  6. package/dist/analyst/index.d.ts.map +1 -1
  7. package/dist/analyst/index.js +11 -161
  8. package/dist/analyst/index.js.map +1 -1
  9. package/dist/app-grade/index.d.ts +2 -2
  10. package/dist/app-grade/index.js +3 -3
  11. package/dist/{benchmark-command-CGQXNFj7.js → benchmark-command-C7ObyGm9.js} +945 -13
  12. package/dist/benchmark-command-C7ObyGm9.js.map +1 -0
  13. package/dist/benchmarks/index.d.ts +4 -4
  14. package/dist/benchmarks/index.js +3 -3
  15. package/dist/campaign/index.d.ts +6 -6
  16. package/dist/campaign/index.js +10 -10
  17. package/dist/{campaign-eus7YRs2.js → campaign-CaO2k8Jb.js} +11 -11
  18. package/dist/{campaign-eus7YRs2.js.map → campaign-CaO2k8Jb.js.map} +1 -1
  19. package/dist/{campaign-evidence-KM5GTsHG.js → campaign-evidence-71uzJMVY.js} +2 -2
  20. package/dist/{campaign-evidence-KM5GTsHG.js.map → campaign-evidence-71uzJMVY.js.map} +1 -1
  21. package/dist/{campaign-evidence-BOcX4w0r.d.ts → campaign-evidence-DcTgo4ze.d.ts} +2 -2
  22. package/dist/{campaign-evidence-BOcX4w0r.d.ts.map → campaign-evidence-DcTgo4ze.d.ts.map} +1 -1
  23. package/dist/{chat-client-Oyot5tyo.js → chat-client-TkNgQDLj.js} +2 -2
  24. package/dist/{chat-client-Oyot5tyo.js.map → chat-client-TkNgQDLj.js.map} +1 -1
  25. package/dist/{chat-json-call-DTmv2uNY.js → chat-json-call-gu3deRID.js} +2 -2
  26. package/dist/{chat-json-call-DTmv2uNY.js.map → chat-json-call-gu3deRID.js.map} +1 -1
  27. package/dist/cli.js +1371 -11
  28. package/dist/cli.js.map +1 -1
  29. package/dist/{client-DUMIaMob.d.ts → client-3sR4_h5q.d.ts} +2 -2
  30. package/dist/{client-DUMIaMob.d.ts.map → client-3sR4_h5q.d.ts.map} +1 -1
  31. package/dist/code-agent-jsonl-aPWZG3vr.js +104 -0
  32. package/dist/code-agent-jsonl-aPWZG3vr.js.map +1 -0
  33. package/dist/{completion-verifier-CCPG2Yc0.js → completion-verifier-BvPqg9Gp.js} +4 -4
  34. package/dist/{completion-verifier-CCPG2Yc0.js.map → completion-verifier-BvPqg9Gp.js.map} +1 -1
  35. package/dist/contract/index.d.ts +9 -9
  36. package/dist/contract/index.js +16 -112
  37. package/dist/contract/index.js.map +1 -1
  38. package/dist/{cost-ledger-C5CCidPm.js → cost-ledger-ni6f77QJ.js} +106 -50
  39. package/dist/cost-ledger-ni6f77QJ.js.map +1 -0
  40. package/dist/{decision-point-CfqtnGop.js → decision-point-CjC56Enj.js} +2 -2
  41. package/dist/{decision-point-CfqtnGop.js.map → decision-point-CjC56Enj.js.map} +1 -1
  42. package/dist/{default-registry-Rs5uzlfJ.js → default-registry-C5iSuS8e.js} +5 -5
  43. package/dist/{default-registry-Rs5uzlfJ.js.map → default-registry-C5iSuS8e.js.map} +1 -1
  44. package/dist/{default-registry-X8McMoUV.d.ts → default-registry-CVklg2e-.d.ts} +2 -2
  45. package/dist/{default-registry-X8McMoUV.d.ts.map → default-registry-CVklg2e-.d.ts.map} +1 -1
  46. package/dist/{define-agent-eval-D8ntOXqV.js → define-agent-eval-BLHr0_IP.js} +4 -4
  47. package/dist/{define-agent-eval-D8ntOXqV.js.map → define-agent-eval-BLHr0_IP.js.map} +1 -1
  48. package/dist/{define-agent-eval-DH5-xi-F.d.ts → define-agent-eval-DZ7wWMHC.d.ts} +5 -5
  49. package/dist/{define-agent-eval-DH5-xi-F.d.ts.map → define-agent-eval-DZ7wWMHC.d.ts.map} +1 -1
  50. package/dist/{dspy-rlm-engine-ChE1PUM5.js → dspy-rlm-engine-CR5MSL2k.js} +6 -5
  51. package/dist/{dspy-rlm-engine-ChE1PUM5.js.map → dspy-rlm-engine-CR5MSL2k.js.map} +1 -1
  52. package/dist/{evaluation-CjZH6gW0.d.ts → evaluation-D50Dzyce.d.ts} +2 -2
  53. package/dist/{evaluation-CjZH6gW0.d.ts.map → evaluation-D50Dzyce.d.ts.map} +1 -1
  54. package/dist/{evaluation-BAisv8ZR.js → evaluation-DqfNMaKr.js} +2 -2
  55. package/dist/{evaluation-BAisv8ZR.js.map → evaluation-DqfNMaKr.js.map} +1 -1
  56. package/dist/evaluation.d.ts +1 -1
  57. package/dist/evaluation.js +1 -1
  58. package/dist/experiment/index.d.ts +2 -2
  59. package/dist/experiment/index.js +1 -1
  60. package/dist/{external-optimizer-contracts-BFV8lnhl.js → external-optimizer-contracts-vrye9kti.js} +2 -2
  61. package/dist/{external-optimizer-contracts-BFV8lnhl.js.map → external-optimizer-contracts-vrye9kti.js.map} +1 -1
  62. package/dist/{external-optimizer-process-B6emPodQ.js → external-optimizer-process-DkOMkeHW.js} +3 -3
  63. package/dist/{external-optimizer-process-B6emPodQ.js.map → external-optimizer-process-DkOMkeHW.js.map} +1 -1
  64. package/dist/{external-optimizer-subprocess-_O06eDVA.js → external-optimizer-subprocess-CFIiwHSE.js} +3 -3
  65. package/dist/{external-optimizer-subprocess-_O06eDVA.js.map → external-optimizer-subprocess-CFIiwHSE.js.map} +1 -1
  66. package/dist/{finding-scope-B_As3F_v.js → finding-scope-BVQVcjz7.js} +2 -2
  67. package/dist/{finding-scope-B_As3F_v.js.map → finding-scope-BVQVcjz7.js.map} +1 -1
  68. package/dist/{findings-store-CvYUzQBR.js → findings-store-Drnjid7m.js} +5 -5
  69. package/dist/{findings-store-CvYUzQBR.js.map → findings-store-Drnjid7m.js.map} +1 -1
  70. package/dist/fuzz.js +1 -1
  71. package/dist/hosted/index.d.ts +2 -2
  72. package/dist/hosted/index.js +1 -1
  73. package/dist/{index-BmWw8zN6.d.ts → index-Bam453Y5.d.ts} +8 -8
  74. package/dist/{index-BmWw8zN6.d.ts.map → index-Bam453Y5.d.ts.map} +1 -1
  75. package/dist/{index-Cn9gB5Ca.d.ts → index-CYrvUGQl.d.ts} +206 -30
  76. package/dist/index-CYrvUGQl.d.ts.map +1 -0
  77. package/dist/{index-aRalB_Ma.d.ts → index-CxciVDt0.d.ts} +2 -2
  78. package/dist/{index-aRalB_Ma.d.ts.map → index-CxciVDt0.d.ts.map} +1 -1
  79. package/dist/{index-CCOaNmh2.d.ts → index-D1ghgNRI.d.ts} +3 -3
  80. package/dist/{index-CCOaNmh2.d.ts.map → index-D1ghgNRI.d.ts.map} +1 -1
  81. package/dist/index.d.ts +14 -14
  82. package/dist/index.js +471 -22
  83. package/dist/index.js.map +1 -1
  84. package/dist/{judge-gate-CpD3wmcf.js → judge-gate-WgYqQ9LA.js} +2 -2
  85. package/dist/{judge-gate-CpD3wmcf.js.map → judge-gate-WgYqQ9LA.js.map} +1 -1
  86. package/dist/{kind-factory-B-xCxG7p.js → kind-factory-C8MJpMTV.js} +2 -2
  87. package/dist/{kind-factory-B-xCxG7p.js.map → kind-factory-C8MJpMTV.js.map} +1 -1
  88. package/dist/{llm-client-Dk8lBnMh.js → llm-client-D4B1qR_1.js} +2 -2
  89. package/dist/{llm-client-Dk8lBnMh.js.map → llm-client-D4B1qR_1.js.map} +1 -1
  90. package/dist/{llm-judge-DYmEdo3M.js → llm-judge-ChGnwj4s.js} +4 -4
  91. package/dist/{llm-judge-DYmEdo3M.js.map → llm-judge-ChGnwj4s.js.map} +1 -1
  92. package/dist/{matrix-BDl7hoBr.d.ts → matrix-CAeyP9m-.d.ts} +2 -2
  93. package/dist/{matrix-BDl7hoBr.d.ts.map → matrix-CAeyP9m-.d.ts.map} +1 -1
  94. package/dist/meta-eval/index.js +2 -2
  95. package/dist/metrics-C6pXdupw.js +9 -0
  96. package/dist/metrics-C6pXdupw.js.map +1 -0
  97. package/dist/multishot/golden/index.d.ts +1 -1
  98. package/dist/multishot/index.d.ts +6 -6
  99. package/dist/multishot/index.js +8 -7
  100. package/dist/multishot/index.js.map +1 -1
  101. package/dist/openapi.json +1 -1
  102. package/dist/{optimization-method-4JlbMxd2.js → optimization-method-D2uCSc2j.js} +9 -9
  103. package/dist/{optimization-method-4JlbMxd2.js.map → optimization-method-D2uCSc2j.js.map} +1 -1
  104. package/dist/{proposal-findings-CfRFCFXS.js → proposal-findings-BCd4KjLy.js} +2 -2
  105. package/dist/{proposal-findings-CfRFCFXS.js.map → proposal-findings-BCd4KjLy.js.map} +1 -1
  106. package/dist/rl.d.ts +1 -1
  107. package/dist/rollout/index.d.ts +2 -2
  108. package/dist/rollout/index.js +1 -1
  109. package/dist/{rollout--rSr43Pd.js → rollout-CbHMVoDr.js} +2 -2
  110. package/dist/{rollout--rSr43Pd.js.map → rollout-CbHMVoDr.js.map} +1 -1
  111. package/dist/{run-improvement-loop-BeHu5D9Z.d.ts → run-improvement-loop-C9z817z_.d.ts} +7 -7
  112. package/dist/{run-improvement-loop-BeHu5D9Z.d.ts.map → run-improvement-loop-C9z817z_.d.ts.map} +1 -1
  113. package/dist/search/index.d.ts +3 -3
  114. package/dist/search/index.js +2 -2
  115. package/dist/{search-kernel-mZc79S6N.js → search-kernel-B1TEQ9pa.js} +2 -2
  116. package/dist/{search-kernel-mZc79S6N.js.map → search-kernel-B1TEQ9pa.js.map} +1 -1
  117. package/dist/{search-kernel-CJZ-ZSV1.d.ts → search-kernel-CZmj8gJW.d.ts} +3 -3
  118. package/dist/{search-kernel-CJZ-ZSV1.d.ts.map → search-kernel-CZmj8gJW.d.ts.map} +1 -1
  119. package/dist/{search-ledger-C7t68cmy.js → search-ledger-EjLGVZ4X.js} +25 -5
  120. package/dist/search-ledger-EjLGVZ4X.js.map +1 -0
  121. package/dist/{search-ledger-types-BhZE848w.d.ts → search-ledger-types-D4FsvPP9.d.ts} +8 -2
  122. package/dist/search-ledger-types-D4FsvPP9.d.ts.map +1 -0
  123. package/dist/{search-shipper-CmDW9dU6.js → search-shipper-DtSnRfOJ.js} +2 -2
  124. package/dist/{search-shipper-CmDW9dU6.js.map → search-shipper-DtSnRfOJ.js.map} +1 -1
  125. package/dist/{search-summary-CCgP2qXz.js → search-summary-C5fewoUi.js} +2 -2
  126. package/dist/{search-summary-CCgP2qXz.js.map → search-summary-C5fewoUi.js.map} +1 -1
  127. package/dist/{self-improve-C_Bcdmv8.js → self-improve-CQM7hIL_.js} +5 -5
  128. package/dist/{self-improve-C_Bcdmv8.js.map → self-improve-CQM7hIL_.js.map} +1 -1
  129. package/dist/{self-improve-B1fsNejr.d.ts → self-improve-Eo-EAWL8.d.ts} +7 -7
  130. package/dist/{self-improve-B1fsNejr.d.ts.map → self-improve-Eo-EAWL8.d.ts.map} +1 -1
  131. package/dist/{server-aZFmRucn.js → server-B-7vXS9T.js} +4 -4
  132. package/dist/{server-aZFmRucn.js.map → server-B-7vXS9T.js.map} +1 -1
  133. package/dist/{skillopt-optimization-method-DHk1K757.js → skillopt-optimization-method-DQ4urRij.js} +9 -9
  134. package/dist/{skillopt-optimization-method-DHk1K757.js.map → skillopt-optimization-method-DQ4urRij.js.map} +1 -1
  135. package/dist/{store-otlp-CdeW7NWq.js → store-otlp-DL30pdXE.js} +2 -2
  136. package/dist/{store-otlp-CdeW7NWq.js.map → store-otlp-DL30pdXE.js.map} +1 -1
  137. package/dist/{store-tool-spans-M3WxeRrG.d.ts → store-tool-spans-BD5Z304_.d.ts} +2 -2
  138. package/dist/{store-tool-spans-M3WxeRrG.d.ts.map → store-tool-spans-BD5Z304_.d.ts.map} +1 -1
  139. package/dist/{store-tool-spans-CVX-jfkk.js → store-tool-spans-DRdpbrnb.js} +3 -3
  140. package/dist/{store-tool-spans-CVX-jfkk.js.map → store-tool-spans-DRdpbrnb.js.map} +1 -1
  141. package/dist/{systemone-4PadCE4C.d.ts → systemone-D7FQ7n00.d.ts} +3 -3
  142. package/dist/{systemone-4PadCE4C.d.ts.map → systemone-D7FQ7n00.d.ts.map} +1 -1
  143. package/dist/systemone.d.ts +2 -2
  144. package/dist/systemone.js +2 -2
  145. package/dist/traces.d.ts +1 -1
  146. package/dist/traces.js +3 -3
  147. package/dist/{tree-CiIe-f3f.js → tree-CljLPWVm.js} +3 -3
  148. package/dist/{tree-CiIe-f3f.js.map → tree-CljLPWVm.js.map} +1 -1
  149. package/dist/{types-D5XtEH9Q.d.ts → types-BtWzceBY.d.ts} +17 -2
  150. package/dist/types-BtWzceBY.d.ts.map +1 -0
  151. package/dist/{types-Bte3EsFQ.d.ts → types-XxFZ2IAT.d.ts} +2 -2
  152. package/dist/{types-Bte3EsFQ.d.ts.map → types-XxFZ2IAT.d.ts.map} +1 -1
  153. package/dist/wire/index.js +1 -1
  154. package/docs/feature-guide.md +2 -0
  155. package/docs/public-api.md +16 -10
  156. package/docs/search-ledger.md +1 -1
  157. package/docs/skill-eval.md +110 -0
  158. package/package.json +4 -2
  159. package/dist/benchmark-command-CGQXNFj7.js.map +0 -1
  160. package/dist/cost-ledger-C5CCidPm.js.map +0 -1
  161. package/dist/index-Cn9gB5Ca.d.ts.map +0 -1
  162. package/dist/search-ledger-C7t68cmy.js.map +0 -1
  163. package/dist/search-ledger-types-BhZE848w.d.ts.map +0 -1
  164. package/dist/types-D5XtEH9Q.d.ts.map +0 -1
@@ -1,5 +1,5 @@
1
1
  import { r as assertServedModel } from "./served-model-BXmeKm7D.js";
2
- import { c as costForTokenPricing } from "./cost-ledger-C5CCidPm.js";
2
+ import { l as costForTokenPricing } from "./cost-ledger-ni6f77QJ.js";
3
3
  import { a as LlmCallError, o as LlmResponseError, r as parseJsonResult } from "./json-DtvZNAU9.js";
4
4
  import { a as providerFromBaseUrl, i as defaultProviderRedactor } from "./raw-provider-sink-RbaEv2vB.js";
5
5
  import { t as newRecordId } from "./record-id-CWZXFh58.js";
@@ -641,4 +641,4 @@ var LlmClient = class {
641
641
  };
642
642
  export { maximumChargeForLlmRequest as a, combineAbortSignals as c, costReceiptFromLlmError as i, callLlmJson as n, backoffMs as o, costReceiptFromLlm as r, isTransientLlmError as s, LlmClient as t };
643
643
 
644
- //# sourceMappingURL=llm-client-Dk8lBnMh.js.map
644
+ //# sourceMappingURL=llm-client-D4B1qR_1.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"llm-client-Dk8lBnMh.js","names":[],"sources":["../src/abort-signal.ts","../src/llm-client/resilience.ts","../src/llm-client/wire.ts","../src/llm-client/accounting.ts","../src/llm-client/request.ts","../src/llm-client.ts"],"sourcesContent":["/** Combine active cancellation sources without wrapping a single source. */\nexport function combineAbortSignals(\n ...signals: Array<AbortSignal | undefined>\n): AbortSignal | undefined {\n const active = [\n ...new Set(signals.filter((signal): signal is AbortSignal => signal !== undefined)),\n ]\n if (active.length === 0) return undefined\n if (active.length === 1) return active[0]\n return AbortSignal.any(active)\n}\n","import type { LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\n\n// ─── Internals ──────────────────────────────────────────────────────────\n\n// Flagship / reasoning models routinely take several minutes on large prompts (a\n// reflection over many failures, a long tool transcript). A tight cap aborts a\n// legitimately-slow but healthy call — and because every retry attempt re-uses\n// the same window, such a model aborts on ALL attempts and the loop throws. The\n// default is generous enough to let those complete, bounded enough that a truly\n// hung call still fails over after retries, and tunable per deployment via\n// TANGLE_LLM_TIMEOUT_MS. Per-call `req.timeoutMs` / `opts.defaultTimeoutMs`\n// still win for callers that know their model's latency.\nexport const DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 300_000\n\nconst DEFAULT_MAXIMUM_ATTEMPTS =\n process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === undefined\n ? 6\n : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS)\n\nexport function resolveMaximumAttempts(configured: number | undefined): number {\n const attempts = configured ?? DEFAULT_MAXIMUM_ATTEMPTS\n if (!Number.isInteger(attempts) || attempts <= 0) {\n throw new RangeError('LLM maximum attempts must be a positive integer')\n }\n return attempts\n}\n\nexport function resolveMinIntervalMs(configured: number | undefined): number {\n const interval = configured ?? 0\n if (!Number.isFinite(interval) || interval < 0) {\n throw new RangeError('LLM minIntervalMs must be a finite non-negative number')\n }\n return interval\n}\n\n// Weak keys avoid retaining credentials or completed campaigns. LlmClient binds\n// its per-call option copies to the same state as its constructor options.\nexport const pacingStates = new WeakMap<LlmClientOptions, { lastStartedAt?: number }>()\n\nexport function pacingStateFor(opts: LlmClientOptions): { lastStartedAt?: number } {\n let state = pacingStates.get(opts)\n if (!state) {\n state = {}\n pacingStates.set(opts, state)\n }\n return state\n}\n\n// 522/524: Cloudflare edge timeouts (origin connect/respond) — transient\n// exactly like 504. Router deployments serve through Cloudflare, so a long\n// non-streaming call can draw these from the edge, not the origin.\nexport const RETRYABLE_STATUS = new Set([429, 502, 503, 504, 522, 524])\n\n/**\n * Transient transport/network error signatures, matched against an error's\n * name, message, and `code`. Covers fetch/undici network failures, aborts\n * and timeouts, and — critically — HTTP/2 transport faults a keep-alive\n * connection raises mid-response: `terminated`, `NGHTTP2_INTERNAL_ERROR`,\n * `UND_ERR_*`, `other side closed`. Those last ones carry no clean HTTP\n * status; unrecognised, they escape the retry loop and surface as an\n * uncaught rejection.\n */\nconst TRANSIENT_ERROR_PATTERNS: readonly RegExp[] = [\n /AbortError/i,\n /TimeoutError/i,\n /this operation was aborted/i,\n /fetch failed/i,\n /ECONNRESET/i,\n /ETIMEDOUT/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /stream.*ended.*unexpectedly/i,\n /terminated/i,\n /other side closed/i,\n /NGHTTP2/i,\n /UND_ERR/i,\n]\n\n/**\n * True when an error is a transient transport/network fault worth retrying,\n * as opposed to a deterministic failure (4xx schema reject, JSON parse) that\n * a retry cannot fix. Inspects `LlmCallError.status`, then the error's\n * name/message/code, then recurses into `error.cause` — undici nests the\n * real socket fault one or more levels under `.cause`.\n *\n * This is the retry classifier for the package: `callLlm` and\n * `withJudgeRetry` both route through it, so connection failures are treated\n * consistently across transports.\n */\nexport function isTransientLlmError(err: unknown): boolean {\n return classifyTransient(err, 0)\n}\n\nfunction classifyTransient(err: unknown, depth: number): boolean {\n if (err instanceof LlmCallError) return RETRYABLE_STATUS.has(err.status)\n if (!(err instanceof Error)) return false\n // Foreign transport errors can carry a numeric HTTP status without being an\n // LlmCallError. A retryable status is decisive.\n const status = (err as { status?: unknown }).status\n if (typeof status === 'number' && RETRYABLE_STATUS.has(status)) return true\n const code = (err as { code?: unknown }).code\n const haystack = `${err.name}\\n${err.message}\\n${typeof code === 'string' ? code : ''}`\n if (TRANSIENT_ERROR_PATTERNS.some((p) => p.test(haystack))) return true\n const cause = (err as { cause?: unknown }).cause\n if (depth < 4 && cause instanceof Error && cause !== err) {\n return classifyTransient(cause, depth + 1)\n }\n return false\n}\n\nexport function parseRetryAfter(headers: Headers): number | null {\n const h = headers.get('retry-after')?.trim()\n if (!h) return null\n const asNumber = Number(h)\n if (!Number.isNaN(asNumber)) {\n const delay = asNumber * 1000\n return Number.isFinite(delay) && delay >= 0 ? delay : null\n }\n const asDate = Date.parse(h)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return null\n}\n\n/** Exponential backoff: 500ms, 1s, 2s, 4s, ... capped at 16s. Attempt is 0-indexed. */\nexport function backoffMs(attempt: number): number {\n return Math.min(500 * 2 ** attempt, 16_000)\n}\n\n/** Backoff belongs to the caller's operation and must stop when it is cancelled. */\nexport async function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n // A timer above the signed 32-bit limit becomes a near-immediate timeout.\n // Split long server delays rather than truncating Retry-After or overflowing.\n do {\n signal?.throwIfAborted()\n const chunk = Math.min(Math.ceil(ms), 2_147_483_647)\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n reject(signal?.reason)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, chunk)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n ms -= chunk\n } while (ms > 0)\n}\n\n/** True once the cross-attempt wall-clock budget (if any) is exhausted. */\nexport function deadlineExceeded(start: number, deadlineMs: number | undefined): boolean {\n return deadlineMs != null && Date.now() - start >= deadlineMs\n}\n","import type {\n LlmCallRequest,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n} from './contract'\n\nexport function providerTokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nexport function buildHeaders(opts: LlmClientOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (opts.authHeader) {\n headers[opts.authHeader.name] = opts.authHeader.value\n } else if (opts.bearer || opts.apiKey) {\n headers.Authorization = `Bearer ${opts.bearer ?? opts.apiKey}`\n }\n if (opts.idempotencyKey) headers['Idempotency-Key'] = opts.idempotencyKey\n return headers\n}\n\nexport function isSchemaRejection(status: number, body: string): boolean {\n if (status !== 400) return false\n const lower = body.toLowerCase()\n return (\n lower.includes('response_format') ||\n lower.includes('json_schema') ||\n lower.includes('is unavailable') ||\n lower.includes('not supported')\n )\n}\n\nexport function isTemperatureOneRejection(status: number, body: string): boolean {\n if (status !== 400 || !/temperature/i.test(body)) return false\n return (\n /temperature[^.\\n]{0,120}\\b(?:only|must|should|required|requires?)\\b[^.\\n]{0,40}\\b1(?:\\.0+)?\\b/i.test(\n body,\n ) || /\\bonly\\s+1(?:\\.0+)?\\s+is\\s+allowed\\b[^.\\n]{0,120}\\btemperature\\b/i.test(body)\n )\n}\n\nexport function buildBody(\n req: LlmCallRequest,\n forceJsonObject: boolean,\n defaultThinking?: LlmThinkingMode,\n): Record<string, unknown> {\n const body: Record<string, unknown> = {\n model: req.model,\n messages: req.messages.map(encodeWireMessage),\n temperature: req.temperature ?? 0,\n }\n if (req.maxTokens != null) {\n if (usesMaxCompletionTokens(req.model)) body.max_completion_tokens = req.maxTokens\n else body.max_tokens = req.maxTokens\n }\n if (req.logprobs !== undefined) {\n body.logprobs = true\n body.top_logprobs = req.logprobs.topLogprobs\n }\n if (req.tools !== undefined) body.tools = req.tools\n if (req.toolChoice !== undefined) body.tool_choice = req.toolChoice\n const thinking = req.thinking ?? defaultThinking\n if (thinking !== undefined) {\n body.thinking = { type: thinking }\n }\n\n if (req.jsonSchema && !forceJsonObject) {\n body.response_format = {\n type: 'json_schema',\n json_schema: { name: req.jsonSchema.name, schema: req.jsonSchema.schema, strict: true },\n }\n } else if (req.jsonMode || req.jsonSchema) {\n body.response_format = { type: 'json_object' }\n }\n\n return body\n}\n\nfunction usesMaxCompletionTokens(model: string): boolean {\n return /^gpt-5(?:[.-]|$)/i.test(model)\n}\n\n/** Encode one canonical message as its OpenAI chat-completions wire shape. */\nfunction encodeWireMessage(message: LlmMessage): Record<string, unknown> {\n if (message.role === 'tool') {\n return { role: 'tool', tool_call_id: message.toolCallId, content: message.content }\n }\n if (message.toolCalls === undefined) {\n return { role: message.role, content: message.content }\n }\n return {\n role: message.role,\n content: message.content,\n tool_calls: message.toolCalls.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: call.argumentsJson },\n })),\n }\n}\n\n/**\n * Parse `choices[0].logprobs.content` into the canonical per-token shape.\n * `null` when the provider returned nothing for a request that asked: a\n * provider that ignores `logprobs` is a fact the caller must be able to read,\n * not an error. A malformed entry is a contract violation and throws.\n */\nexport function parseWireLogprobs(\n value: unknown,\n model: string,\n): ReadonlyArray<LlmTokenLogprob> | null {\n if (value === undefined || value === null) return null\n if (!Array.isArray(value)) {\n throw new Error(`LLM response logprobs.content must be an array (model=${model})`)\n }\n return value.map((entry, index) => {\n const record = entry as { token?: unknown; logprob?: unknown; top_logprobs?: unknown } | null\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.token !== 'string' ||\n typeof record.logprob !== 'number' ||\n !Number.isFinite(record.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}] is not a token with a finite logprob (model=${model})`,\n )\n }\n const top = record.top_logprobs\n if (top !== undefined && top !== null && !Array.isArray(top)) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs must be an array (model=${model})`,\n )\n }\n return {\n token: record.token,\n logprob: record.logprob,\n top: (Array.isArray(top) ? top : []).map((alternative, position) => {\n const candidate = alternative as { token?: unknown; logprob?: unknown } | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.token !== 'string' ||\n typeof candidate.logprob !== 'number' ||\n !Number.isFinite(candidate.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs[${position}] is not a token with a finite logprob (model=${model})`,\n )\n }\n return { token: candidate.token, logprob: candidate.logprob }\n }),\n }\n })\n}\n\n/** Parse provider tool_calls into the canonical shape. A malformed entry is a\n * provider-contract violation and throws rather than degrading silently. */\nexport function parseWireToolCalls(value: unknown, model: string): LlmToolCall[] | undefined {\n if (value === undefined || value === null) return undefined\n if (!Array.isArray(value)) {\n throw new Error(`LLM response tool_calls must be an array (model=${model})`)\n }\n if (value.length === 0) return undefined\n return value.map((entry, index) => {\n const record = entry as {\n id?: unknown\n type?: unknown\n function?: { name?: unknown; arguments?: unknown } | null\n } | null\n const fn = record && typeof record === 'object' ? record.function : undefined\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.id !== 'string' ||\n record.id.length === 0 ||\n (record.type !== undefined && record.type !== 'function') ||\n !fn ||\n typeof fn !== 'object' ||\n typeof fn.name !== 'string' ||\n fn.name.length === 0 ||\n typeof fn.arguments !== 'string'\n ) {\n throw new Error(\n `LLM response tool_calls[${index}] is not a function call with string arguments (model=${model})`,\n )\n }\n return { id: record.id, name: fn.name, argumentsJson: fn.arguments }\n })\n}\n","import type { CostReceiptInput, CustomTokenPricing, MaximumCharge } from '../cost-ledger'\nimport type { LlmCallRequest, LlmCallResult, LlmChargeBounds } from './contract'\nimport { LlmResponseError } from './errors'\nimport { resolveMaximumAttempts } from './resilience'\nimport { buildBody } from './wire'\n\nexport function maximumChargeForLlmRequest(\n request: Pick<\n LlmCallRequest,\n 'model' | 'messages' | 'jsonSchema' | 'tools' | 'toolChoice' | 'maxTokens' | 'thinking'\n >,\n options: LlmChargeBounds = {},\n): MaximumCharge | undefined {\n if (request.maxTokens === undefined) return undefined\n if (!Number.isInteger(request.maxTokens) || request.maxTokens <= 0) {\n throw new RangeError(`maximumChargeForLlmRequest: maxTokens must be a positive integer`)\n }\n if (\n request.messages.some(\n (message) =>\n Array.isArray(message.content) && message.content.some((part) => part.type === 'image_url'),\n )\n ) {\n return undefined\n }\n\n const attempts = resolveMaximumAttempts(options.maximumAttempts)\n const forceJsonObject = options.jsonSchemaTransport === 'json-object'\n // A byte-level tokenizer cannot emit more input tokens than request bytes.\n // Pricing the complete body also covers role/schema framing omitted from content-only estimates.\n const requestBytes = new TextEncoder().encode(\n JSON.stringify(buildBody(request, forceJsonObject, options.thinking)),\n ).byteLength\n // Schema fallback shares the same physical-attempt budget; it cannot buy a second batch.\n const usage = {\n inputTokens: requestBytes * attempts,\n outputTokens: request.maxTokens * attempts,\n }\n return options.customTokenPricing\n ? { customTokenPricing: options.customTokenPricing, ...usage }\n : { model: request.model, ...usage }\n}\n\n/** Convert a provider result into the canonical paid-call receipt input.\n * The receipt is JSON-clean: absent optional fields are omitted, never carried\n * as explicit-undefined keys. Receipts cross JSON boundaries (the external\n * optimizer's loopback proxy validates them with `assertJsonValue`), where an\n * explicit-undefined value is rejected as non-serializable. */\nexport function costReceiptFromLlm(\n result: LlmCallResult,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput {\n const cachedTokens = result.usage.cachedPromptTokens ?? 0\n const inputTokens = Math.max(0, result.usage.promptTokens - cachedTokens)\n const providerCostUsd = providerReportedCost(result.raw)\n return {\n model: result.model,\n inputTokens,\n outputTokens: result.usage.completionTokens,\n ...(result.usage.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: result.usage.reasoningTokens }),\n ...(cachedTokens > 0 ? { cachedTokens } : {}),\n ...(providerCostUsd === undefined\n ? customTokenPricing && result.usage.captured !== false\n ? { customTokenPricing }\n : result.costUsd === null\n ? {}\n : { estimatedCostUsd: result.costUsd }\n : { actualCostUsd: providerCostUsd }),\n usageUnknown: result.usage.captured === false,\n }\n}\n\nexport function providerReportedCost(raw: Record<string, unknown>): number | undefined {\n const value = raw._response_cost ?? raw.cost_usd\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\n/** Structured-response failures retain their completed provider receipt. */\nexport function costReceiptFromLlmError(\n error: Error,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput | undefined {\n return error instanceof LlmResponseError\n ? costReceiptFromLlm(error.result, customTokenPricing)\n : undefined\n}\n","import { combineAbortSignals } from '../abort-signal'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { assertServedModel as assertServedModelIdentity } from '../integrity/served-model'\nimport { newRecordId } from '../record-id'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderEvent,\n type RawProviderSink,\n} from '../trace/raw-provider-sink'\nimport { providerReportedCost } from './accounting'\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\nimport {\n backoffMs,\n DEFAULT_TIMEOUT_MS,\n deadlineExceeded,\n isTransientLlmError,\n pacingStateFor,\n parseRetryAfter,\n RETRYABLE_STATUS,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n sleep,\n} from './resilience'\nimport {\n buildBody,\n buildHeaders,\n isSchemaRejection,\n isTemperatureOneRejection,\n parseWireLogprobs,\n parseWireToolCalls,\n providerTokenCount,\n} from './wire'\n\n/**\n * Low-level call. Returns raw content + usage + cost. Retries on transient\n * failures; does NOT degrade schema here — callers that want graceful\n * degrade use `callLlmJson`.\n */\nexport async function callLlm(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts(req, opts, false)\n}\n\n/** One retry owner for raw and structured calls. Fallback changes the next\n * request, not the attempt allowance, deadline origin, or raw-event sequence. */\n/** What one call shares across its attempts: the resolved options, pacing, deadline and the request as it now stands. */\ninterface AttemptRun {\n readonly req: LlmCallRequest\n readonly opts: LlmClientOptions\n readonly allowSchemaFallback: boolean\n readonly baseUrl: string\n readonly url: string\n readonly timeoutMs: number\n readonly maximumAttempts: number\n readonly minIntervalMs: number\n readonly pacing: ReturnType<typeof pacingStateFor>\n readonly headers: ReturnType<typeof buildHeaders>\n readonly provider: string\n readonly deadlineStart: number\n readonly remainingMs: () => number\n readonly retryDelay: (ms: number) => Promise<void>\n effectiveRequest: LlmCallRequest\n lastErr: unknown\n}\n\n/** How one attempt ended without a result or a thrown error. */\ntype AttemptOutcome =\n | { kind: 'result'; result: LlmCallResult }\n | { kind: 'retry' }\n | { kind: 'exhausted' }\n\n/** Which of an attempt's raw events were already written, so the failure path records at most one error. */\ninterface AttemptState {\n dispatched: boolean\n errorRecorded: boolean\n}\n\nconst ENDPOINT = '/chat/completions'\n\nfunction startAttemptRun(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): AttemptRun {\n // No default endpoint. This client is internal to the `agent-eval` binary\n // and the loopback optimizer proxy; both name their endpoint explicitly, and\n // a fallback would let a misconfigured caller bill an unintended provider.\n if (!opts.baseUrl) throw new Error('callLlm: opts.baseUrl is required')\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n const deadlineMs = opts.deadlineMs\n const deadlineStart = Date.now()\n const remainingMs = () =>\n deadlineMs === undefined ? Infinity : Math.max(0, deadlineMs - (Date.now() - deadlineStart))\n const run: AttemptRun = {\n req,\n opts,\n allowSchemaFallback,\n baseUrl,\n url: `${baseUrl}${ENDPOINT}`,\n timeoutMs: req.timeoutMs ?? opts.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS,\n maximumAttempts: resolveMaximumAttempts(opts.maximumAttempts),\n minIntervalMs: resolveMinIntervalMs(opts.minIntervalMs),\n pacing: pacingStateFor(opts),\n headers: buildHeaders(opts),\n provider: opts.provider ?? providerFromBaseUrl(baseUrl),\n deadlineStart,\n remainingMs,\n retryDelay: (ms) => sleep(Math.min(ms, remainingMs()), opts.signal),\n effectiveRequest: req,\n lastErr: undefined,\n }\n if (opts.customTokenPricing) {\n costForTokenPricing(opts.customTokenPricing, { inputTokens: 0, outputTokens: 0 })\n }\n return run\n}\n\nfunction deadlineError(run: AttemptRun): Error | DOMException {\n return run.lastErr instanceof Error\n ? run.lastErr\n : new DOMException('callLlm deadline exceeded', 'TimeoutError')\n}\n\n/** Write one raw provider event for this attempt. Does nothing without a sink. */\nasync function recordAttemptEvent(\n run: AttemptRun,\n attempt: number,\n fields: Pick<RawProviderEvent, 'direction' | 'timestamp'> & Partial<RawProviderEvent>,\n): Promise<void> {\n const { opts } = run\n if (!opts.rawSink) return\n await recordRaw(opts.rawSink, opts.redactor ?? defaultProviderRedactor, {\n eventId: newRecordId(),\n runId: opts.traceContext?.runId,\n spanId: opts.traceContext?.spanId,\n provider: run.provider,\n model: run.req.model,\n endpoint: ENDPOINT,\n baseUrl: run.baseUrl,\n attemptIndex: attempt,\n ...fields,\n redactedFields: [],\n })\n}\n\n/**\n * Wait for this client's pacing slot, and claim it. Every wake rechecks, so concurrent waiters\n * cannot dispatch a catch-up burst; the claim is made in the same synchronous step that finds the\n * slot free, so no other waiter can slip in between the check and the claim.\n */\nasync function awaitPacingSlot(run: AttemptRun): Promise<number> {\n const { opts, pacing, minIntervalMs } = run\n while (true) {\n opts.signal?.throwIfAborted()\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const waitMs =\n pacing.lastStartedAt === undefined ? 0 : pacing.lastStartedAt + minIntervalMs - Date.now()\n if (waitMs <= 0) {\n // Queue time consumes the operation deadline, not the HTTP timeout.\n const started = Date.now()\n pacing.lastStartedAt = started\n return started\n }\n await run.retryDelay(waitMs)\n }\n}\n\n/** Answer a non-2xx response: retry with an adjusted request or after a wait, give up, or throw its error. */\nasync function handleHttpFailure(\n run: AttemptRun,\n attempt: number,\n res: Response,\n body: string,\n responseHeaders: Record<string, string> | undefined,\n started: number,\n state: AttemptState,\n): Promise<AttemptOutcome> {\n const { req, opts, maximumAttempts, deadlineStart } = run\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: body,\n errorMessage: `HTTP ${res.status}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n const err = new LlmCallError(\n `LLM call failed with HTTP ${res.status}`,\n res.status,\n body,\n req.model,\n )\n const canRetry =\n attempt < maximumAttempts - 1 && !deadlineExceeded(deadlineStart, opts.deadlineMs)\n if (\n isTemperatureOneRejection(res.status, body) &&\n run.effectiveRequest.temperature !== 1 &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, temperature: 1 }\n return { kind: 'retry' }\n }\n if (\n run.allowSchemaFallback &&\n opts.jsonSchemaTransport !== 'json-object' &&\n run.effectiveRequest.jsonSchema &&\n isSchemaRejection(res.status, body) &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, jsonMode: true, jsonSchema: undefined }\n return { kind: 'retry' }\n }\n if (RETRYABLE_STATUS.has(res.status) && canRetry) {\n run.lastErr = err\n const wait = parseRetryAfter(res.headers) ?? backoffMs(attempt)\n // A wait the deadline cannot cover ends the call with this answer. Sleeping to the\n // deadline let a timer that fired a millisecond early start one more attempt with no time\n // left, whose abort replaced the server's status (agent-eval publish run 37238259408).\n if (wait >= run.remainingMs()) {\n // A caller abort that landed while the answer was recorded still wins, as the\n // retry wait would have reported it.\n opts.signal?.throwIfAborted()\n return { kind: 'exhausted' }\n }\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n throw err\n}\n\n/** Turn a parsed completion into the call result: content, tool calls, usage with its completeness, and cost. */\nfunction parseCompletion(\n run: AttemptRun,\n json: Record<string, unknown>,\n started: number,\n): LlmCallResult {\n const { req, opts } = run\n const choice = (\n json.choices as\n | Array<{\n message?: { content?: string | null; tool_calls?: unknown }\n finish_reason?: string | null\n logprobs?: { content?: unknown } | null\n }>\n | undefined\n )?.[0]\n const toolCalls = parseWireToolCalls(choice?.message?.tool_calls, req.model)\n const usageRaw =\n json.usage && typeof json.usage === 'object' && !Array.isArray(json.usage)\n ? (json.usage as Record<string, unknown>)\n : undefined\n const promptTokens = providerTokenCount(usageRaw?.prompt_tokens)\n const completionTokens = providerTokenCount(usageRaw?.completion_tokens)\n const totalTokens = providerTokenCount(usageRaw?.total_tokens)\n const completionDetails =\n usageRaw?.completion_tokens_details &&\n typeof usageRaw.completion_tokens_details === 'object' &&\n !Array.isArray(usageRaw.completion_tokens_details)\n ? (usageRaw.completion_tokens_details as Record<string, unknown>)\n : undefined\n const reasoningRaw = completionDetails?.reasoning_tokens\n const reasoningTokens = reasoningRaw === undefined ? undefined : providerTokenCount(reasoningRaw)\n const cachedRaw =\n usageRaw?.prompt_tokens_details &&\n typeof usageRaw.prompt_tokens_details === 'object' &&\n !Array.isArray(usageRaw.prompt_tokens_details)\n ? (usageRaw.prompt_tokens_details as Record<string, unknown>).cached_tokens\n : undefined\n const cachedPromptTokens = cachedRaw === undefined ? undefined : providerTokenCount(cachedRaw)\n const usageCaptured =\n promptTokens !== undefined &&\n completionTokens !== undefined &&\n (reasoningRaw === undefined ||\n (reasoningTokens !== undefined && reasoningTokens <= completionTokens)) &&\n (cachedRaw === undefined ||\n (cachedPromptTokens !== undefined && cachedPromptTokens <= promptTokens)) &&\n (totalTokens === undefined || totalTokens === promptTokens + completionTokens)\n const costFromProxy = providerReportedCost(json)\n const content = choice?.message?.content ?? ''\n\n const configuredCost =\n typeof costFromProxy !== 'number' && usageCaptured && opts.customTokenPricing\n ? costForTokenPricing(opts.customTokenPricing, {\n inputTokens: promptTokens! - (cachedPromptTokens ?? 0),\n ...(cachedPromptTokens ? { cachedTokens: cachedPromptTokens } : {}),\n outputTokens: completionTokens!,\n })\n : undefined\n\n // The echoed id, kept separate from the attribution id: a provider that\n // omits it must read as \"unproven\", never as \"the model I asked for\".\n const servedModel = typeof json.model === 'string' && json.model.trim() !== '' ? json.model : null\n if (opts.assertServedModel) {\n assertServedModelIdentity(\n req.model,\n servedModel,\n opts.assertServedModel === true ? {} : opts.assertServedModel,\n )\n }\n\n return {\n content,\n ...(toolCalls === undefined ? {} : { toolCalls }),\n ...(req.logprobs === undefined\n ? {}\n : { logprobs: parseWireLogprobs(choice?.logprobs?.content, req.model) }),\n finishReason: choice?.finish_reason ?? null,\n contentEmpty: content.trim().length === 0,\n usage: {\n promptTokens: promptTokens ?? 0,\n completionTokens: completionTokens ?? 0,\n totalTokens: totalTokens ?? (promptTokens ?? 0) + (completionTokens ?? 0),\n captured: usageCaptured,\n reasoningTokens,\n cachedPromptTokens,\n },\n costUsd: typeof costFromProxy === 'number' ? costFromProxy : (configuredCost ?? null),\n model: servedModel ?? req.model,\n servedModel,\n durationMs: Date.now() - started,\n raw: json,\n }\n}\n\n/** Node's built-in fetch (undici) drops a request whose response headers have not arrived within this long. */\nconst NODE_FETCH_HEADER_LIMIT_MS = 300_000\n\n/**\n * Whether an attempt has to leave on node:http instead of fetch. A caller's\n * `fetch` always wins. Otherwise the question is whether the call is allowed\n * longer than Node's fetch waits for response headers: a non-streaming\n * completion sends none until the whole answer is ready, so under that fetch\n * such a call died at 300 s on every attempt, whatever `timeoutMs` said.\n */\nfunction outlastsNodeFetch(run: AttemptRun): boolean {\n if (run.opts.fetch || run.timeoutMs <= NODE_FETCH_HEADER_LIMIT_MS) return false\n // `process.versions.undici` is how Node names the fetch it ships; no other runtime's fetch has this limit.\n return typeof process === 'object' && typeof process.versions?.undici === 'string'\n}\n\n/** One attempt: pace, dispatch, read the answer. A failure either becomes a retry outcome or is thrown. */\nasync function runAttempt(run: AttemptRun, attempt: number): Promise<AttemptOutcome> {\n const { opts } = run\n const callerSignal = opts.signal\n // A caller cancel is fatal — never retried. Checking before each attempt\n // means an already-aborted signal short-circuits without firing fetch.\n if (callerSignal?.aborted) {\n throw new DOMException('callLlm aborted by caller signal', 'AbortError')\n }\n // Stop retrying once the cross-attempt budget is spent rather than burning\n // a full per-attempt timeout on each remaining retry.\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const requestBody = buildBody(\n run.effectiveRequest,\n opts.jsonSchemaTransport === 'json-object',\n opts.thinking,\n )\n const controller = new AbortController()\n const attemptSignal = combineAbortSignals(controller.signal, callerSignal)!\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined\n let started = Date.now()\n // An attempt cancelled or timed out while queued never reached the\n // provider, so it leaves no request or error event in the raw log.\n const state: AttemptState = { dispatched: false, errorRecorded: false }\n try {\n if (run.minIntervalMs > 0) {\n started = await awaitPacingSlot(run)\n } else {\n // Claim the slot before any await so a concurrent waiter cannot take it.\n run.pacing.lastStartedAt = started\n }\n state.dispatched = true\n timeoutHandle = setTimeout(() => controller.abort(), Math.min(run.timeoutMs, run.remainingMs()))\n await recordAttemptEvent(run, attempt, {\n direction: 'request',\n timestamp: started,\n requestHeaders: run.headers,\n requestBody,\n })\n attemptSignal.throwIfAborted()\n // The node:http transport loads on first use, so a bundle for a runtime\n // without node:http never has to resolve it. There the attempt's own timer\n // is the only deadline.\n const send = outlastsNodeFetch(run)\n ? (await import('./node-transport')).nodeHttpFetch\n : (opts.fetch ?? globalThis.fetch)\n const res = await send(run.url, {\n method: 'POST',\n headers: run.headers,\n body: JSON.stringify(requestBody),\n signal: attemptSignal,\n })\n const responseHeaders = opts.rawSink ? headersToObject(res.headers) : undefined\n // Headers are not completion: the same timeout/cancellation covers either response body.\n const text = await res.text()\n attemptSignal.throwIfAborted()\n clearTimeout(timeoutHandle)\n\n if (!res.ok) {\n return await handleHttpFailure(run, attempt, res, text, responseHeaders, started, state)\n }\n\n let json: Record<string, unknown>\n try {\n json = JSON.parse(text) as Record<string, unknown>\n } catch (parseErr) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: text,\n errorMessage: `non-JSON response: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n throw parseErr\n }\n await recordAttemptEvent(run, attempt, {\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: json,\n })\n return { kind: 'result', result: parseCompletion(run, json, started) }\n } catch (err) {\n clearTimeout(timeoutHandle)\n run.lastErr = err\n // Record only if neither the !res.ok branch nor the JSON.parse catch\n // already produced an error event for this attempt. Covers network\n // failures, timeouts, and aborts.\n if (state.dispatched && !state.errorRecorded) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n }\n // A caller cancel is fatal even though an AbortError matches the\n // transient patterns — a cancelled call must surface immediately, not\n // be retried against the same dead intent.\n if (callerSignal?.aborted) throw err\n const wait = backoffMs(attempt)\n if (\n attempt < run.maximumAttempts - 1 &&\n isTransientLlmError(err) &&\n !deadlineExceeded(run.deadlineStart, opts.deadlineMs) &&\n wait < run.remainingMs()\n ) {\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n callerSignal?.throwIfAborted()\n throw err\n } finally {\n clearTimeout(timeoutHandle)\n }\n}\n\nasync function callLlmAttempts(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): Promise<LlmCallResult> {\n const run = startAttemptRun(req, opts, allowSchemaFallback)\n for (let attempt = 0; attempt < run.maximumAttempts; attempt++) {\n const outcome = await runAttempt(run, attempt)\n if (outcome.kind === 'result') return outcome.result\n if (outcome.kind === 'exhausted') break\n }\n throw run.lastErr instanceof Error ? run.lastErr : new Error(String(run.lastErr))\n}\n\nasync function recordRaw(\n sink: RawProviderSink,\n redactor: ProviderRedactor,\n event: RawProviderEvent,\n): Promise<void> {\n // Errors from sinks must not crash the LLM call. Forensic capture is\n // best-effort; the structured trace is the system of record.\n try {\n await sink.record(redactor(event))\n } catch {\n // Intentionally swallowed.\n }\n}\n\nfunction headersToObject(h: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n h.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\n/** Shared schema-to-JSON-mode fallback that preserves the raw result. */\nexport async function callLlmStructured(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts({ ...req, jsonMode: req.jsonMode ?? !req.jsonSchema }, opts, true)\n}\n","/**\n * OpenAI-compatible client. The CLASS is internal; one transport now drives it\n * for public callers.\n *\n * agent-eval never goes looking for a credential — it reads no environment\n * variable to find one — and this module is still not reachable through any\n * export subpath. What reaches a consumer is `createChatClient({ transport:\n * 'openai-compatible', baseUrl, apiKey })`, the sanctioned public route, which\n * constructs this client from an endpoint and a credential the caller passed as\n * values. Anything richer than that transport's options stays in-repo.\n *\n * Three in-repo callers hold the class directly:\n * - `src/analyst/chat-client.ts`, the public transport above;\n * - the `agent-eval` binary (`src/cli-config.ts`), a deployed server whose\n * caller is a JSON-RPC client in another language and which therefore\n * configures its own endpoint from its own environment;\n * - the loopback optimizer proxy path (`src/analyst/benchmark-public-model.ts`,\n * `src/analyst/dspy-rlm-engine.ts`), which targets `http://127.0.0.1:<port>/v1`\n * with an ephemeral token and executes nothing itself.\n *\n * The canonical request/result TYPES it defines ARE public — they are the\n * contract every caller-owned transport speaks.\n *\n * OpenAI-compatible `/v1/chat/completions` client with:\n * - Exponential-backoff retry on 429 + 5xx gateway errors (502/503/504).\n * - Retry on transient network errors (fetch failed, AbortError, ECONNRESET).\n * - One retry at temperature 1 when a model explicitly requires it.\n * - Graceful json_schema → json_object degrade on 400 with schema-reject body.\n * - Fenced-JSON stripping (```json ... ```) for models that wrap structured output.\n * - Configurable base URL + api key / bearer, works with LiteLLM proxies, OpenAI\n * directly, cli-bridge subscriptions, and any router that speaks the spec.\n *\n * Usage:\n * const { value, result } = await callLlmJson<MyType>(\n * { model: 'gpt-4o', messages: [...], jsonSchema: { name: 'x', schema: {...} } },\n * { baseUrl: process.env.AGENT_EVAL_LLM_BASE_URL, apiKey: process.env.AGENT_EVAL_LLM_API_KEY },\n * )\n *\n */\n\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './llm-client/contract'\nimport { parseJsonResult } from './llm-client/json'\nimport { callLlm, callLlmStructured } from './llm-client/request'\nimport {\n pacingStateFor,\n pacingStates,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n} from './llm-client/resilience'\n\nexport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n maximumChargeForLlmRequest,\n} from './llm-client/accounting'\nexport type {\n LlmCallMetadata,\n LlmCallRequest,\n LlmCallResult,\n LlmChargeBounds,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n LlmToolChoice,\n LlmToolDefinition,\n LlmUsage,\n} from './llm-client/contract'\nexport { LlmCallError, LlmResponseError } from './llm-client/errors'\nexport { extractJsonPayload, stripFencedJson } from './llm-client/json'\nexport { callLlm } from './llm-client/request'\nexport { backoffMs, isTransientLlmError } from './llm-client/resilience'\n\n/**\n * Structured-output call. Returns parsed JSON plus the raw result envelope.\n * Degrades `jsonSchema` → `jsonMode` on a 400 that names the schema param —\n * critical for deepseek-v3/v4, kimi-k2.6, and other models that don't accept\n * the `response_format.json_schema` shape but DO accept `json_object`.\n */\nexport async function callLlmJson<T = unknown>(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<{ value: T; result: LlmCallResult }> {\n const result = await callLlmStructured(req, opts)\n const value = parseJsonResult<T>(result, opts.jsonPayloadMode ?? 'extract')\n return { value, result }\n}\n\n/**\n * Stateful client — construct once with defaults, call many times.\n * Thin wrapper around the free functions; exists for callers that want\n * to inject a single configured instance into multiple primitives.\n */\nexport class LlmClient {\n readonly maximumAttempts: number\n private readonly opts: LlmClientOptions\n\n constructor(opts: LlmClientOptions = {}) {\n this.opts = opts\n this.maximumAttempts = resolveMaximumAttempts(opts.maximumAttempts)\n resolveMinIntervalMs(opts.minIntervalMs)\n }\n\n private callOptions(per?: LlmClientOptions): LlmClientOptions {\n const options = { ...this.opts, ...per }\n pacingStates.set(options, pacingStateFor(this.opts))\n return options\n }\n\n call(req: LlmCallRequest, per?: LlmClientOptions): Promise<LlmCallResult> {\n const options = this.callOptions(per)\n return req.jsonSchema ? callLlmStructured(req, options) : callLlm(req, options)\n }\n\n callJson<T = unknown>(\n req: LlmCallRequest,\n per?: LlmClientOptions,\n ): Promise<{ value: T; result: LlmCallResult }> {\n return callLlmJson<T>(req, this.callOptions(per))\n }\n}\n"],"mappings":";;;;;;;AACA,SAAgB,oBACd,GAAG,SACsB;CACzB,MAAM,SAAS,CACb,GAAG,IAAI,IAAI,QAAQ,QAAQ,WAAkC,WAAW,KAAA,CAAS,CAAC,CACpF;CACA,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,IAAI,OAAO,WAAW,GAAG,OAAO,OAAO;CACvC,OAAO,YAAY,IAAI,MAAM;AAC/B;;ACGA,MAAa,qBAAqB,OAAO,QAAQ,IAAI,qBAAqB,KAAK;AAE/E,MAAM,2BACJ,QAAQ,IAAI,gCAAgC,KAAA,IACxC,IACA,OAAO,QAAQ,IAAI,2BAA2B;AAEpD,SAAgB,uBAAuB,YAAwC;CAC7E,MAAM,WAAW,cAAc;CAC/B,IAAI,CAAC,OAAO,UAAU,QAAQ,KAAK,YAAY,GAC7C,MAAM,IAAI,WAAW,iDAAiD;CAExE,OAAO;AACT;AAEA,SAAgB,qBAAqB,YAAwC;CAC3E,MAAM,WAAW,cAAc;CAC/B,IAAI,CAAC,OAAO,SAAS,QAAQ,KAAK,WAAW,GA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AK,OAAO,IAAI,QAAQ,KAAK,OAAO;CAChF;CAEA,SACE,KACA,KAC8C;EAC9C,OAAO,YAAe,KAAK,KAAK,YAAY,GAAG,CAAC;CAClD;AACF"}
1
+ {"version":3,"file":"llm-client-D4B1qR_1.js","names":[],"sources":["../src/abort-signal.ts","../src/llm-client/resilience.ts","../src/llm-client/wire.ts","../src/llm-client/accounting.ts","../src/llm-client/request.ts","../src/llm-client.ts"],"sourcesContent":["/** Combine active cancellation sources without wrapping a single source. */\nexport function combineAbortSignals(\n ...signals: Array<AbortSignal | undefined>\n): AbortSignal | undefined {\n const active = [\n ...new Set(signals.filter((signal): signal is AbortSignal => signal !== undefined)),\n ]\n if (active.length === 0) return undefined\n if (active.length === 1) return active[0]\n return AbortSignal.any(active)\n}\n","import type { LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\n\n// ─── Internals ──────────────────────────────────────────────────────────\n\n// Flagship / reasoning models routinely take several minutes on large prompts (a\n// reflection over many failures, a long tool transcript). A tight cap aborts a\n// legitimately-slow but healthy call — and because every retry attempt re-uses\n// the same window, such a model aborts on ALL attempts and the loop throws. The\n// default is generous enough to let those complete, bounded enough that a truly\n// hung call still fails over after retries, and tunable per deployment via\n// TANGLE_LLM_TIMEOUT_MS. Per-call `req.timeoutMs` / `opts.defaultTimeoutMs`\n// still win for callers that know their model's latency.\nexport const DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 300_000\n\nconst DEFAULT_MAXIMUM_ATTEMPTS =\n process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === undefined\n ? 6\n : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS)\n\nexport function resolveMaximumAttempts(configured: number | undefined): number {\n const attempts = configured ?? DEFAULT_MAXIMUM_ATTEMPTS\n if (!Number.isInteger(attempts) || attempts <= 0) {\n throw new RangeError('LLM maximum attempts must be a positive integer')\n }\n return attempts\n}\n\nexport function resolveMinIntervalMs(configured: number | undefined): number {\n const interval = configured ?? 0\n if (!Number.isFinite(interval) || interval < 0) {\n throw new RangeError('LLM minIntervalMs must be a finite non-negative number')\n }\n return interval\n}\n\n// Weak keys avoid retaining credentials or completed campaigns. LlmClient binds\n// its per-call option copies to the same state as its constructor options.\nexport const pacingStates = new WeakMap<LlmClientOptions, { lastStartedAt?: number }>()\n\nexport function pacingStateFor(opts: LlmClientOptions): { lastStartedAt?: number } {\n let state = pacingStates.get(opts)\n if (!state) {\n state = {}\n pacingStates.set(opts, state)\n }\n return state\n}\n\n// 522/524: Cloudflare edge timeouts (origin connect/respond) — transient\n// exactly like 504. Router deployments serve through Cloudflare, so a long\n// non-streaming call can draw these from the edge, not the origin.\nexport const RETRYABLE_STATUS = new Set([429, 502, 503, 504, 522, 524])\n\n/**\n * Transient transport/network error signatures, matched against an error's\n * name, message, and `code`. Covers fetch/undici network failures, aborts\n * and timeouts, and — critically — HTTP/2 transport faults a keep-alive\n * connection raises mid-response: `terminated`, `NGHTTP2_INTERNAL_ERROR`,\n * `UND_ERR_*`, `other side closed`. Those last ones carry no clean HTTP\n * status; unrecognised, they escape the retry loop and surface as an\n * uncaught rejection.\n */\nconst TRANSIENT_ERROR_PATTERNS: readonly RegExp[] = [\n /AbortError/i,\n /TimeoutError/i,\n /this operation was aborted/i,\n /fetch failed/i,\n /ECONNRESET/i,\n /ETIMEDOUT/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /stream.*ended.*unexpectedly/i,\n /terminated/i,\n /other side closed/i,\n /NGHTTP2/i,\n /UND_ERR/i,\n]\n\n/**\n * True when an error is a transient transport/network fault worth retrying,\n * as opposed to a deterministic failure (4xx schema reject, JSON parse) that\n * a retry cannot fix. Inspects `LlmCallError.status`, then the error's\n * name/message/code, then recurses into `error.cause` — undici nests the\n * real socket fault one or more levels under `.cause`.\n *\n * This is the retry classifier for the package: `callLlm` and\n * `withJudgeRetry` both route through it, so connection failures are treated\n * consistently across transports.\n */\nexport function isTransientLlmError(err: unknown): boolean {\n return classifyTransient(err, 0)\n}\n\nfunction classifyTransient(err: unknown, depth: number): boolean {\n if (err instanceof LlmCallError) return RETRYABLE_STATUS.has(err.status)\n if (!(err instanceof Error)) return false\n // Foreign transport errors can carry a numeric HTTP status without being an\n // LlmCallError. A retryable status is decisive.\n const status = (err as { status?: unknown }).status\n if (typeof status === 'number' && RETRYABLE_STATUS.has(status)) return true\n const code = (err as { code?: unknown }).code\n const haystack = `${err.name}\\n${err.message}\\n${typeof code === 'string' ? code : ''}`\n if (TRANSIENT_ERROR_PATTERNS.some((p) => p.test(haystack))) return true\n const cause = (err as { cause?: unknown }).cause\n if (depth < 4 && cause instanceof Error && cause !== err) {\n return classifyTransient(cause, depth + 1)\n }\n return false\n}\n\nexport function parseRetryAfter(headers: Headers): number | null {\n const h = headers.get('retry-after')?.trim()\n if (!h) return null\n const asNumber = Number(h)\n if (!Number.isNaN(asNumber)) {\n const delay = asNumber * 1000\n return Number.isFinite(delay) && delay >= 0 ? delay : null\n }\n const asDate = Date.parse(h)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return null\n}\n\n/** Exponential backoff: 500ms, 1s, 2s, 4s, ... capped at 16s. Attempt is 0-indexed. */\nexport function backoffMs(attempt: number): number {\n return Math.min(500 * 2 ** attempt, 16_000)\n}\n\n/** Backoff belongs to the caller's operation and must stop when it is cancelled. */\nexport async function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n // A timer above the signed 32-bit limit becomes a near-immediate timeout.\n // Split long server delays rather than truncating Retry-After or overflowing.\n do {\n signal?.throwIfAborted()\n const chunk = Math.min(Math.ceil(ms), 2_147_483_647)\n await new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n reject(signal?.reason)\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort)\n resolve()\n }, chunk)\n signal?.addEventListener('abort', onAbort, { once: true })\n })\n ms -= chunk\n } while (ms > 0)\n}\n\n/** True once the cross-attempt wall-clock budget (if any) is exhausted. */\nexport function deadlineExceeded(start: number, deadlineMs: number | undefined): boolean {\n return deadlineMs != null && Date.now() - start >= deadlineMs\n}\n","import type {\n LlmCallRequest,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n} from './contract'\n\nexport function providerTokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nexport function buildHeaders(opts: LlmClientOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (opts.authHeader) {\n headers[opts.authHeader.name] = opts.authHeader.value\n } else if (opts.bearer || opts.apiKey) {\n headers.Authorization = `Bearer ${opts.bearer ?? opts.apiKey}`\n }\n if (opts.idempotencyKey) headers['Idempotency-Key'] = opts.idempotencyKey\n return headers\n}\n\nexport function isSchemaRejection(status: number, body: string): boolean {\n if (status !== 400) return false\n const lower = body.toLowerCase()\n return (\n lower.includes('response_format') ||\n lower.includes('json_schema') ||\n lower.includes('is unavailable') ||\n lower.includes('not supported')\n )\n}\n\nexport function isTemperatureOneRejection(status: number, body: string): boolean {\n if (status !== 400 || !/temperature/i.test(body)) return false\n return (\n /temperature[^.\\n]{0,120}\\b(?:only|must|should|required|requires?)\\b[^.\\n]{0,40}\\b1(?:\\.0+)?\\b/i.test(\n body,\n ) || /\\bonly\\s+1(?:\\.0+)?\\s+is\\s+allowed\\b[^.\\n]{0,120}\\btemperature\\b/i.test(body)\n )\n}\n\nexport function buildBody(\n req: LlmCallRequest,\n forceJsonObject: boolean,\n defaultThinking?: LlmThinkingMode,\n): Record<string, unknown> {\n const body: Record<string, unknown> = {\n model: req.model,\n messages: req.messages.map(encodeWireMessage),\n temperature: req.temperature ?? 0,\n }\n if (req.maxTokens != null) {\n if (usesMaxCompletionTokens(req.model)) body.max_completion_tokens = req.maxTokens\n else body.max_tokens = req.maxTokens\n }\n if (req.logprobs !== undefined) {\n body.logprobs = true\n body.top_logprobs = req.logprobs.topLogprobs\n }\n if (req.tools !== undefined) body.tools = req.tools\n if (req.toolChoice !== undefined) body.tool_choice = req.toolChoice\n const thinking = req.thinking ?? defaultThinking\n if (thinking !== undefined) {\n body.thinking = { type: thinking }\n }\n\n if (req.jsonSchema && !forceJsonObject) {\n body.response_format = {\n type: 'json_schema',\n json_schema: { name: req.jsonSchema.name, schema: req.jsonSchema.schema, strict: true },\n }\n } else if (req.jsonMode || req.jsonSchema) {\n body.response_format = { type: 'json_object' }\n }\n\n return body\n}\n\nfunction usesMaxCompletionTokens(model: string): boolean {\n return /^gpt-5(?:[.-]|$)/i.test(model)\n}\n\n/** Encode one canonical message as its OpenAI chat-completions wire shape. */\nfunction encodeWireMessage(message: LlmMessage): Record<string, unknown> {\n if (message.role === 'tool') {\n return { role: 'tool', tool_call_id: message.toolCallId, content: message.content }\n }\n if (message.toolCalls === undefined) {\n return { role: message.role, content: message.content }\n }\n return {\n role: message.role,\n content: message.content,\n tool_calls: message.toolCalls.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: call.argumentsJson },\n })),\n }\n}\n\n/**\n * Parse `choices[0].logprobs.content` into the canonical per-token shape.\n * `null` when the provider returned nothing for a request that asked: a\n * provider that ignores `logprobs` is a fact the caller must be able to read,\n * not an error. A malformed entry is a contract violation and throws.\n */\nexport function parseWireLogprobs(\n value: unknown,\n model: string,\n): ReadonlyArray<LlmTokenLogprob> | null {\n if (value === undefined || value === null) return null\n if (!Array.isArray(value)) {\n throw new Error(`LLM response logprobs.content must be an array (model=${model})`)\n }\n return value.map((entry, index) => {\n const record = entry as { token?: unknown; logprob?: unknown; top_logprobs?: unknown } | null\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.token !== 'string' ||\n typeof record.logprob !== 'number' ||\n !Number.isFinite(record.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}] is not a token with a finite logprob (model=${model})`,\n )\n }\n const top = record.top_logprobs\n if (top !== undefined && top !== null && !Array.isArray(top)) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs must be an array (model=${model})`,\n )\n }\n return {\n token: record.token,\n logprob: record.logprob,\n top: (Array.isArray(top) ? top : []).map((alternative, position) => {\n const candidate = alternative as { token?: unknown; logprob?: unknown } | null\n if (\n !candidate ||\n typeof candidate !== 'object' ||\n typeof candidate.token !== 'string' ||\n typeof candidate.logprob !== 'number' ||\n !Number.isFinite(candidate.logprob)\n ) {\n throw new Error(\n `LLM response logprobs.content[${index}].top_logprobs[${position}] is not a token with a finite logprob (model=${model})`,\n )\n }\n return { token: candidate.token, logprob: candidate.logprob }\n }),\n }\n })\n}\n\n/** Parse provider tool_calls into the canonical shape. A malformed entry is a\n * provider-contract violation and throws rather than degrading silently. */\nexport function parseWireToolCalls(value: unknown, model: string): LlmToolCall[] | undefined {\n if (value === undefined || value === null) return undefined\n if (!Array.isArray(value)) {\n throw new Error(`LLM response tool_calls must be an array (model=${model})`)\n }\n if (value.length === 0) return undefined\n return value.map((entry, index) => {\n const record = entry as {\n id?: unknown\n type?: unknown\n function?: { name?: unknown; arguments?: unknown } | null\n } | null\n const fn = record && typeof record === 'object' ? record.function : undefined\n if (\n !record ||\n typeof record !== 'object' ||\n typeof record.id !== 'string' ||\n record.id.length === 0 ||\n (record.type !== undefined && record.type !== 'function') ||\n !fn ||\n typeof fn !== 'object' ||\n typeof fn.name !== 'string' ||\n fn.name.length === 0 ||\n typeof fn.arguments !== 'string'\n ) {\n throw new Error(\n `LLM response tool_calls[${index}] is not a function call with string arguments (model=${model})`,\n )\n }\n return { id: record.id, name: fn.name, argumentsJson: fn.arguments }\n })\n}\n","import type { CostReceiptInput, CustomTokenPricing, MaximumCharge } from '../cost-ledger'\nimport type { LlmCallRequest, LlmCallResult, LlmChargeBounds } from './contract'\nimport { LlmResponseError } from './errors'\nimport { resolveMaximumAttempts } from './resilience'\nimport { buildBody } from './wire'\n\nexport function maximumChargeForLlmRequest(\n request: Pick<\n LlmCallRequest,\n 'model' | 'messages' | 'jsonSchema' | 'tools' | 'toolChoice' | 'maxTokens' | 'thinking'\n >,\n options: LlmChargeBounds = {},\n): MaximumCharge | undefined {\n if (request.maxTokens === undefined) return undefined\n if (!Number.isInteger(request.maxTokens) || request.maxTokens <= 0) {\n throw new RangeError(`maximumChargeForLlmRequest: maxTokens must be a positive integer`)\n }\n if (\n request.messages.some(\n (message) =>\n Array.isArray(message.content) && message.content.some((part) => part.type === 'image_url'),\n )\n ) {\n return undefined\n }\n\n const attempts = resolveMaximumAttempts(options.maximumAttempts)\n const forceJsonObject = options.jsonSchemaTransport === 'json-object'\n // A byte-level tokenizer cannot emit more input tokens than request bytes.\n // Pricing the complete body also covers role/schema framing omitted from content-only estimates.\n const requestBytes = new TextEncoder().encode(\n JSON.stringify(buildBody(request, forceJsonObject, options.thinking)),\n ).byteLength\n // Schema fallback shares the same physical-attempt budget; it cannot buy a second batch.\n const usage = {\n inputTokens: requestBytes * attempts,\n outputTokens: request.maxTokens * attempts,\n }\n return options.customTokenPricing\n ? { customTokenPricing: options.customTokenPricing, ...usage }\n : { model: request.model, ...usage }\n}\n\n/** Convert a provider result into the canonical paid-call receipt input.\n * The receipt is JSON-clean: absent optional fields are omitted, never carried\n * as explicit-undefined keys. Receipts cross JSON boundaries (the external\n * optimizer's loopback proxy validates them with `assertJsonValue`), where an\n * explicit-undefined value is rejected as non-serializable. */\nexport function costReceiptFromLlm(\n result: LlmCallResult,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput {\n const cachedTokens = result.usage.cachedPromptTokens ?? 0\n const inputTokens = Math.max(0, result.usage.promptTokens - cachedTokens)\n const providerCostUsd = providerReportedCost(result.raw)\n return {\n model: result.model,\n inputTokens,\n outputTokens: result.usage.completionTokens,\n ...(result.usage.reasoningTokens === undefined\n ? {}\n : { reasoningTokens: result.usage.reasoningTokens }),\n ...(cachedTokens > 0 ? { cachedTokens } : {}),\n ...(providerCostUsd === undefined\n ? customTokenPricing && result.usage.captured !== false\n ? { customTokenPricing }\n : result.costUsd === null\n ? {}\n : { estimatedCostUsd: result.costUsd }\n : { actualCostUsd: providerCostUsd }),\n usageUnknown: result.usage.captured === false,\n }\n}\n\nexport function providerReportedCost(raw: Record<string, unknown>): number | undefined {\n const value = raw._response_cost ?? raw.cost_usd\n return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined\n}\n\n/** Structured-response failures retain their completed provider receipt. */\nexport function costReceiptFromLlmError(\n error: Error,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput | undefined {\n return error instanceof LlmResponseError\n ? costReceiptFromLlm(error.result, customTokenPricing)\n : undefined\n}\n","import { combineAbortSignals } from '../abort-signal'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { assertServedModel as assertServedModelIdentity } from '../integrity/served-model'\nimport { newRecordId } from '../record-id'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderEvent,\n type RawProviderSink,\n} from '../trace/raw-provider-sink'\nimport { providerReportedCost } from './accounting'\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './contract'\nimport { LlmCallError } from './errors'\nimport {\n backoffMs,\n DEFAULT_TIMEOUT_MS,\n deadlineExceeded,\n isTransientLlmError,\n pacingStateFor,\n parseRetryAfter,\n RETRYABLE_STATUS,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n sleep,\n} from './resilience'\nimport {\n buildBody,\n buildHeaders,\n isSchemaRejection,\n isTemperatureOneRejection,\n parseWireLogprobs,\n parseWireToolCalls,\n providerTokenCount,\n} from './wire'\n\n/**\n * Low-level call. Returns raw content + usage + cost. Retries on transient\n * failures; does NOT degrade schema here — callers that want graceful\n * degrade use `callLlmJson`.\n */\nexport async function callLlm(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts(req, opts, false)\n}\n\n/** One retry owner for raw and structured calls. Fallback changes the next\n * request, not the attempt allowance, deadline origin, or raw-event sequence. */\n/** What one call shares across its attempts: the resolved options, pacing, deadline and the request as it now stands. */\ninterface AttemptRun {\n readonly req: LlmCallRequest\n readonly opts: LlmClientOptions\n readonly allowSchemaFallback: boolean\n readonly baseUrl: string\n readonly url: string\n readonly timeoutMs: number\n readonly maximumAttempts: number\n readonly minIntervalMs: number\n readonly pacing: ReturnType<typeof pacingStateFor>\n readonly headers: ReturnType<typeof buildHeaders>\n readonly provider: string\n readonly deadlineStart: number\n readonly remainingMs: () => number\n readonly retryDelay: (ms: number) => Promise<void>\n effectiveRequest: LlmCallRequest\n lastErr: unknown\n}\n\n/** How one attempt ended without a result or a thrown error. */\ntype AttemptOutcome =\n | { kind: 'result'; result: LlmCallResult }\n | { kind: 'retry' }\n | { kind: 'exhausted' }\n\n/** Which of an attempt's raw events were already written, so the failure path records at most one error. */\ninterface AttemptState {\n dispatched: boolean\n errorRecorded: boolean\n}\n\nconst ENDPOINT = '/chat/completions'\n\nfunction startAttemptRun(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): AttemptRun {\n // No default endpoint. This client is internal to the `agent-eval` binary\n // and the loopback optimizer proxy; both name their endpoint explicitly, and\n // a fallback would let a misconfigured caller bill an unintended provider.\n if (!opts.baseUrl) throw new Error('callLlm: opts.baseUrl is required')\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n const deadlineMs = opts.deadlineMs\n const deadlineStart = Date.now()\n const remainingMs = () =>\n deadlineMs === undefined ? Infinity : Math.max(0, deadlineMs - (Date.now() - deadlineStart))\n const run: AttemptRun = {\n req,\n opts,\n allowSchemaFallback,\n baseUrl,\n url: `${baseUrl}${ENDPOINT}`,\n timeoutMs: req.timeoutMs ?? opts.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS,\n maximumAttempts: resolveMaximumAttempts(opts.maximumAttempts),\n minIntervalMs: resolveMinIntervalMs(opts.minIntervalMs),\n pacing: pacingStateFor(opts),\n headers: buildHeaders(opts),\n provider: opts.provider ?? providerFromBaseUrl(baseUrl),\n deadlineStart,\n remainingMs,\n retryDelay: (ms) => sleep(Math.min(ms, remainingMs()), opts.signal),\n effectiveRequest: req,\n lastErr: undefined,\n }\n if (opts.customTokenPricing) {\n costForTokenPricing(opts.customTokenPricing, { inputTokens: 0, outputTokens: 0 })\n }\n return run\n}\n\nfunction deadlineError(run: AttemptRun): Error | DOMException {\n return run.lastErr instanceof Error\n ? run.lastErr\n : new DOMException('callLlm deadline exceeded', 'TimeoutError')\n}\n\n/** Write one raw provider event for this attempt. Does nothing without a sink. */\nasync function recordAttemptEvent(\n run: AttemptRun,\n attempt: number,\n fields: Pick<RawProviderEvent, 'direction' | 'timestamp'> & Partial<RawProviderEvent>,\n): Promise<void> {\n const { opts } = run\n if (!opts.rawSink) return\n await recordRaw(opts.rawSink, opts.redactor ?? defaultProviderRedactor, {\n eventId: newRecordId(),\n runId: opts.traceContext?.runId,\n spanId: opts.traceContext?.spanId,\n provider: run.provider,\n model: run.req.model,\n endpoint: ENDPOINT,\n baseUrl: run.baseUrl,\n attemptIndex: attempt,\n ...fields,\n redactedFields: [],\n })\n}\n\n/**\n * Wait for this client's pacing slot, and claim it. Every wake rechecks, so concurrent waiters\n * cannot dispatch a catch-up burst; the claim is made in the same synchronous step that finds the\n * slot free, so no other waiter can slip in between the check and the claim.\n */\nasync function awaitPacingSlot(run: AttemptRun): Promise<number> {\n const { opts, pacing, minIntervalMs } = run\n while (true) {\n opts.signal?.throwIfAborted()\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const waitMs =\n pacing.lastStartedAt === undefined ? 0 : pacing.lastStartedAt + minIntervalMs - Date.now()\n if (waitMs <= 0) {\n // Queue time consumes the operation deadline, not the HTTP timeout.\n const started = Date.now()\n pacing.lastStartedAt = started\n return started\n }\n await run.retryDelay(waitMs)\n }\n}\n\n/** Answer a non-2xx response: retry with an adjusted request or after a wait, give up, or throw its error. */\nasync function handleHttpFailure(\n run: AttemptRun,\n attempt: number,\n res: Response,\n body: string,\n responseHeaders: Record<string, string> | undefined,\n started: number,\n state: AttemptState,\n): Promise<AttemptOutcome> {\n const { req, opts, maximumAttempts, deadlineStart } = run\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: body,\n errorMessage: `HTTP ${res.status}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n const err = new LlmCallError(\n `LLM call failed with HTTP ${res.status}`,\n res.status,\n body,\n req.model,\n )\n const canRetry =\n attempt < maximumAttempts - 1 && !deadlineExceeded(deadlineStart, opts.deadlineMs)\n if (\n isTemperatureOneRejection(res.status, body) &&\n run.effectiveRequest.temperature !== 1 &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, temperature: 1 }\n return { kind: 'retry' }\n }\n if (\n run.allowSchemaFallback &&\n opts.jsonSchemaTransport !== 'json-object' &&\n run.effectiveRequest.jsonSchema &&\n isSchemaRejection(res.status, body) &&\n canRetry\n ) {\n run.lastErr = err\n run.effectiveRequest = { ...run.effectiveRequest, jsonMode: true, jsonSchema: undefined }\n return { kind: 'retry' }\n }\n if (RETRYABLE_STATUS.has(res.status) && canRetry) {\n run.lastErr = err\n const wait = parseRetryAfter(res.headers) ?? backoffMs(attempt)\n // A wait the deadline cannot cover ends the call with this answer. Sleeping to the\n // deadline let a timer that fired a millisecond early start one more attempt with no time\n // left, whose abort replaced the server's status (agent-eval publish run 37238259408).\n if (wait >= run.remainingMs()) {\n // A caller abort that landed while the answer was recorded still wins, as the\n // retry wait would have reported it.\n opts.signal?.throwIfAborted()\n return { kind: 'exhausted' }\n }\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n throw err\n}\n\n/** Turn a parsed completion into the call result: content, tool calls, usage with its completeness, and cost. */\nfunction parseCompletion(\n run: AttemptRun,\n json: Record<string, unknown>,\n started: number,\n): LlmCallResult {\n const { req, opts } = run\n const choice = (\n json.choices as\n | Array<{\n message?: { content?: string | null; tool_calls?: unknown }\n finish_reason?: string | null\n logprobs?: { content?: unknown } | null\n }>\n | undefined\n )?.[0]\n const toolCalls = parseWireToolCalls(choice?.message?.tool_calls, req.model)\n const usageRaw =\n json.usage && typeof json.usage === 'object' && !Array.isArray(json.usage)\n ? (json.usage as Record<string, unknown>)\n : undefined\n const promptTokens = providerTokenCount(usageRaw?.prompt_tokens)\n const completionTokens = providerTokenCount(usageRaw?.completion_tokens)\n const totalTokens = providerTokenCount(usageRaw?.total_tokens)\n const completionDetails =\n usageRaw?.completion_tokens_details &&\n typeof usageRaw.completion_tokens_details === 'object' &&\n !Array.isArray(usageRaw.completion_tokens_details)\n ? (usageRaw.completion_tokens_details as Record<string, unknown>)\n : undefined\n const reasoningRaw = completionDetails?.reasoning_tokens\n const reasoningTokens = reasoningRaw === undefined ? undefined : providerTokenCount(reasoningRaw)\n const cachedRaw =\n usageRaw?.prompt_tokens_details &&\n typeof usageRaw.prompt_tokens_details === 'object' &&\n !Array.isArray(usageRaw.prompt_tokens_details)\n ? (usageRaw.prompt_tokens_details as Record<string, unknown>).cached_tokens\n : undefined\n const cachedPromptTokens = cachedRaw === undefined ? undefined : providerTokenCount(cachedRaw)\n const usageCaptured =\n promptTokens !== undefined &&\n completionTokens !== undefined &&\n (reasoningRaw === undefined ||\n (reasoningTokens !== undefined && reasoningTokens <= completionTokens)) &&\n (cachedRaw === undefined ||\n (cachedPromptTokens !== undefined && cachedPromptTokens <= promptTokens)) &&\n (totalTokens === undefined || totalTokens === promptTokens + completionTokens)\n const costFromProxy = providerReportedCost(json)\n const content = choice?.message?.content ?? ''\n\n const configuredCost =\n typeof costFromProxy !== 'number' && usageCaptured && opts.customTokenPricing\n ? costForTokenPricing(opts.customTokenPricing, {\n inputTokens: promptTokens! - (cachedPromptTokens ?? 0),\n ...(cachedPromptTokens ? { cachedTokens: cachedPromptTokens } : {}),\n outputTokens: completionTokens!,\n })\n : undefined\n\n // The echoed id, kept separate from the attribution id: a provider that\n // omits it must read as \"unproven\", never as \"the model I asked for\".\n const servedModel = typeof json.model === 'string' && json.model.trim() !== '' ? json.model : null\n if (opts.assertServedModel) {\n assertServedModelIdentity(\n req.model,\n servedModel,\n opts.assertServedModel === true ? {} : opts.assertServedModel,\n )\n }\n\n return {\n content,\n ...(toolCalls === undefined ? {} : { toolCalls }),\n ...(req.logprobs === undefined\n ? {}\n : { logprobs: parseWireLogprobs(choice?.logprobs?.content, req.model) }),\n finishReason: choice?.finish_reason ?? null,\n contentEmpty: content.trim().length === 0,\n usage: {\n promptTokens: promptTokens ?? 0,\n completionTokens: completionTokens ?? 0,\n totalTokens: totalTokens ?? (promptTokens ?? 0) + (completionTokens ?? 0),\n captured: usageCaptured,\n reasoningTokens,\n cachedPromptTokens,\n },\n costUsd: typeof costFromProxy === 'number' ? costFromProxy : (configuredCost ?? null),\n model: servedModel ?? req.model,\n servedModel,\n durationMs: Date.now() - started,\n raw: json,\n }\n}\n\n/** Node's built-in fetch (undici) drops a request whose response headers have not arrived within this long. */\nconst NODE_FETCH_HEADER_LIMIT_MS = 300_000\n\n/**\n * Whether an attempt has to leave on node:http instead of fetch. A caller's\n * `fetch` always wins. Otherwise the question is whether the call is allowed\n * longer than Node's fetch waits for response headers: a non-streaming\n * completion sends none until the whole answer is ready, so under that fetch\n * such a call died at 300 s on every attempt, whatever `timeoutMs` said.\n */\nfunction outlastsNodeFetch(run: AttemptRun): boolean {\n if (run.opts.fetch || run.timeoutMs <= NODE_FETCH_HEADER_LIMIT_MS) return false\n // `process.versions.undici` is how Node names the fetch it ships; no other runtime's fetch has this limit.\n return typeof process === 'object' && typeof process.versions?.undici === 'string'\n}\n\n/** One attempt: pace, dispatch, read the answer. A failure either becomes a retry outcome or is thrown. */\nasync function runAttempt(run: AttemptRun, attempt: number): Promise<AttemptOutcome> {\n const { opts } = run\n const callerSignal = opts.signal\n // A caller cancel is fatal — never retried. Checking before each attempt\n // means an already-aborted signal short-circuits without firing fetch.\n if (callerSignal?.aborted) {\n throw new DOMException('callLlm aborted by caller signal', 'AbortError')\n }\n // Stop retrying once the cross-attempt budget is spent rather than burning\n // a full per-attempt timeout on each remaining retry.\n if (deadlineExceeded(run.deadlineStart, opts.deadlineMs)) throw deadlineError(run)\n const requestBody = buildBody(\n run.effectiveRequest,\n opts.jsonSchemaTransport === 'json-object',\n opts.thinking,\n )\n const controller = new AbortController()\n const attemptSignal = combineAbortSignals(controller.signal, callerSignal)!\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined\n let started = Date.now()\n // An attempt cancelled or timed out while queued never reached the\n // provider, so it leaves no request or error event in the raw log.\n const state: AttemptState = { dispatched: false, errorRecorded: false }\n try {\n if (run.minIntervalMs > 0) {\n started = await awaitPacingSlot(run)\n } else {\n // Claim the slot before any await so a concurrent waiter cannot take it.\n run.pacing.lastStartedAt = started\n }\n state.dispatched = true\n timeoutHandle = setTimeout(() => controller.abort(), Math.min(run.timeoutMs, run.remainingMs()))\n await recordAttemptEvent(run, attempt, {\n direction: 'request',\n timestamp: started,\n requestHeaders: run.headers,\n requestBody,\n })\n attemptSignal.throwIfAborted()\n // The node:http transport loads on first use, so a bundle for a runtime\n // without node:http never has to resolve it. There the attempt's own timer\n // is the only deadline.\n const send = outlastsNodeFetch(run)\n ? (await import('./node-transport')).nodeHttpFetch\n : (opts.fetch ?? globalThis.fetch)\n const res = await send(run.url, {\n method: 'POST',\n headers: run.headers,\n body: JSON.stringify(requestBody),\n signal: attemptSignal,\n })\n const responseHeaders = opts.rawSink ? headersToObject(res.headers) : undefined\n // Headers are not completion: the same timeout/cancellation covers either response body.\n const text = await res.text()\n attemptSignal.throwIfAborted()\n clearTimeout(timeoutHandle)\n\n if (!res.ok) {\n return await handleHttpFailure(run, attempt, res, text, responseHeaders, started, state)\n }\n\n let json: Record<string, unknown>\n try {\n json = JSON.parse(text) as Record<string, unknown>\n } catch (parseErr) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: text,\n errorMessage: `non-JSON response: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,\n })\n if (opts.rawSink) state.errorRecorded = true\n throw parseErr\n }\n await recordAttemptEvent(run, attempt, {\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: json,\n })\n return { kind: 'result', result: parseCompletion(run, json, started) }\n } catch (err) {\n clearTimeout(timeoutHandle)\n run.lastErr = err\n // Record only if neither the !res.ok branch nor the JSON.parse catch\n // already produced an error event for this attempt. Covers network\n // failures, timeouts, and aborts.\n if (state.dispatched && !state.errorRecorded) {\n await recordAttemptEvent(run, attempt, {\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n }\n // A caller cancel is fatal even though an AbortError matches the\n // transient patterns — a cancelled call must surface immediately, not\n // be retried against the same dead intent.\n if (callerSignal?.aborted) throw err\n const wait = backoffMs(attempt)\n if (\n attempt < run.maximumAttempts - 1 &&\n isTransientLlmError(err) &&\n !deadlineExceeded(run.deadlineStart, opts.deadlineMs) &&\n wait < run.remainingMs()\n ) {\n await run.retryDelay(wait)\n return { kind: 'retry' }\n }\n callerSignal?.throwIfAborted()\n throw err\n } finally {\n clearTimeout(timeoutHandle)\n }\n}\n\nasync function callLlmAttempts(\n req: LlmCallRequest,\n opts: LlmClientOptions,\n allowSchemaFallback: boolean,\n): Promise<LlmCallResult> {\n const run = startAttemptRun(req, opts, allowSchemaFallback)\n for (let attempt = 0; attempt < run.maximumAttempts; attempt++) {\n const outcome = await runAttempt(run, attempt)\n if (outcome.kind === 'result') return outcome.result\n if (outcome.kind === 'exhausted') break\n }\n throw run.lastErr instanceof Error ? run.lastErr : new Error(String(run.lastErr))\n}\n\nasync function recordRaw(\n sink: RawProviderSink,\n redactor: ProviderRedactor,\n event: RawProviderEvent,\n): Promise<void> {\n // Errors from sinks must not crash the LLM call. Forensic capture is\n // best-effort; the structured trace is the system of record.\n try {\n await sink.record(redactor(event))\n } catch {\n // Intentionally swallowed.\n }\n}\n\nfunction headersToObject(h: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n h.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\n/** Shared schema-to-JSON-mode fallback that preserves the raw result. */\nexport async function callLlmStructured(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n return callLlmAttempts({ ...req, jsonMode: req.jsonMode ?? !req.jsonSchema }, opts, true)\n}\n","/**\n * OpenAI-compatible client. The CLASS is internal; one transport now drives it\n * for public callers.\n *\n * agent-eval never goes looking for a credential — it reads no environment\n * variable to find one — and this module is still not reachable through any\n * export subpath. What reaches a consumer is `createChatClient({ transport:\n * 'openai-compatible', baseUrl, apiKey })`, the sanctioned public route, which\n * constructs this client from an endpoint and a credential the caller passed as\n * values. Anything richer than that transport's options stays in-repo.\n *\n * Three in-repo callers hold the class directly:\n * - `src/analyst/chat-client.ts`, the public transport above;\n * - the `agent-eval` binary (`src/cli-config.ts`), a deployed server whose\n * caller is a JSON-RPC client in another language and which therefore\n * configures its own endpoint from its own environment;\n * - the loopback optimizer proxy path (`src/analyst/benchmark-public-model.ts`,\n * `src/analyst/dspy-rlm-engine.ts`), which targets `http://127.0.0.1:<port>/v1`\n * with an ephemeral token and executes nothing itself.\n *\n * The canonical request/result TYPES it defines ARE public — they are the\n * contract every caller-owned transport speaks.\n *\n * OpenAI-compatible `/v1/chat/completions` client with:\n * - Exponential-backoff retry on 429 + 5xx gateway errors (502/503/504).\n * - Retry on transient network errors (fetch failed, AbortError, ECONNRESET).\n * - One retry at temperature 1 when a model explicitly requires it.\n * - Graceful json_schema → json_object degrade on 400 with schema-reject body.\n * - Fenced-JSON stripping (```json ... ```) for models that wrap structured output.\n * - Configurable base URL + api key / bearer, works with LiteLLM proxies, OpenAI\n * directly, cli-bridge subscriptions, and any router that speaks the spec.\n *\n * Usage:\n * const { value, result } = await callLlmJson<MyType>(\n * { model: 'gpt-4o', messages: [...], jsonSchema: { name: 'x', schema: {...} } },\n * { baseUrl: process.env.AGENT_EVAL_LLM_BASE_URL, apiKey: process.env.AGENT_EVAL_LLM_API_KEY },\n * )\n *\n */\n\nimport type { LlmCallRequest, LlmCallResult, LlmClientOptions } from './llm-client/contract'\nimport { parseJsonResult } from './llm-client/json'\nimport { callLlm, callLlmStructured } from './llm-client/request'\nimport {\n pacingStateFor,\n pacingStates,\n resolveMaximumAttempts,\n resolveMinIntervalMs,\n} from './llm-client/resilience'\n\nexport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n maximumChargeForLlmRequest,\n} from './llm-client/accounting'\nexport type {\n LlmCallMetadata,\n LlmCallRequest,\n LlmCallResult,\n LlmChargeBounds,\n LlmClientOptions,\n LlmMessage,\n LlmThinkingMode,\n LlmTokenLogprob,\n LlmToolCall,\n LlmToolChoice,\n LlmToolDefinition,\n LlmUsage,\n} from './llm-client/contract'\nexport { LlmCallError, LlmResponseError } from './llm-client/errors'\nexport { extractJsonPayload, stripFencedJson } from './llm-client/json'\nexport { callLlm } from './llm-client/request'\nexport { backoffMs, isTransientLlmError } from './llm-client/resilience'\n\n/**\n * Structured-output call. Returns parsed JSON plus the raw result envelope.\n * Degrades `jsonSchema` → `jsonMode` on a 400 that names the schema param —\n * critical for deepseek-v3/v4, kimi-k2.6, and other models that don't accept\n * the `response_format.json_schema` shape but DO accept `json_object`.\n */\nexport async function callLlmJson<T = unknown>(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<{ value: T; result: LlmCallResult }> {\n const result = await callLlmStructured(req, opts)\n const value = parseJsonResult<T>(result, opts.jsonPayloadMode ?? 'extract')\n return { value, result }\n}\n\n/**\n * Stateful client — construct once with defaults, call many times.\n * Thin wrapper around the free functions; exists for callers that want\n * to inject a single configured instance into multiple primitives.\n */\nexport class LlmClient {\n readonly maximumAttempts: number\n private readonly opts: LlmClientOptions\n\n constructor(opts: LlmClientOptions = {}) {\n this.opts = opts\n this.maximumAttempts = resolveMaximumAttempts(opts.maximumAttempts)\n resolveMinIntervalMs(opts.minIntervalMs)\n }\n\n private callOptions(per?: LlmClientOptions): LlmClientOptions {\n const options = { ...this.opts, ...per }\n pacingStates.set(options, pacingStateFor(this.opts))\n return options\n }\n\n call(req: LlmCallRequest, per?: LlmClientOptions): Promise<LlmCallResult> {\n const options = this.callOptions(per)\n return req.jsonSchema ? callLlmStructured(req, options) : callLlm(req, options)\n }\n\n callJson<T = unknown>(\n req: LlmCallRequest,\n per?: LlmClientOptions,\n ): Promise<{ value: T; result: LlmCallResult }> {\n return callLlmJson<T>(req, this.callOptions(per))\n }\n}\n"],"mappings":";;;;;;;AACA,SAAgB,oBACd,GAAG,SACsB;CACzB,MAAM,SAAS,CACb,GAAG,IAAI,IAAI,QAAQ,QAAQ,WAAkC,WAAW,KAAA,CAAS,CAAC,CACpF;CACA,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,IAAI,OAAO,WAAW,GAAG,OAAO,OAAO;CACvC,OAAO,YAAY,IAAI,MAAM;AAC/B;;ACGA,MAAa,qBAAqB,OAAO,QAAQ,IAAI,qBAAqB,KAAK;AAE/E,MAAM,2BACJ,QAAQ,IAAI,gCAAgC,KAAA,IACxC,IACA,OAAO,QAAQ,IAAI,2BAA2B;AAEpD,SAAgB,uBAAuB,YAAwC;CAC7E,MAAM,WAAW,cAAc;CAC/B,IAAI,CAAC,OAAO,UAAU,QAAQ,KAAK,YAAY,GAC7C,MAAM,IAAI,WAAW,iDAAiD;CAExE,OAAO;AACT;AAEA,SAAgB,qBAAqB,YAAwC;CAC3E,MAAM,WAAW,cAAc;CAC/B,IAAI,CAAC,OAAO,SAAS,QAAQ,KAAK,WAAW,GAC3C,MAAM,IAAI,WAAW,wDAAwD;CAE/E,OAAO;AACT;AAIA,MAAa,+BAAe,IAAI,QAAsD;AAEtF,SAAgB,eAAe,MAAoD;CACjF,IAAI,QAAQ,aAAa,I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+1,9 @@
1
1
  import { h as weightedComposite } from "./paired-tests-CXcD_B80.js";
2
2
  import { n as contentHash } from "./verdict-cache-BPaYxfG8.js";
3
- import { Q as runCampaign } from "./optimization-method-4JlbMxd2.js";
4
- import { t as CostLedger } from "./cost-ledger-C5CCidPm.js";
3
+ import { Q as runCampaign } from "./optimization-method-D2uCSc2j.js";
4
+ import { t as CostLedger } from "./cost-ledger-ni6f77QJ.js";
5
5
  import { i as stripFencedJson } from "./json-DtvZNAU9.js";
6
- import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-Dk8lBnMh.js";
6
+ import { a as maximumChargeForLlmRequest, i as costReceiptFromLlmError, r as costReceiptFromLlm } from "./llm-client-D4B1qR_1.js";
7
7
  import { t as JudgeParseError } from "./judges-BLxg5p8E.js";
8
8
  import { z } from "zod";
9
9
  // src/campaign/presets/run-eval.ts
@@ -473,4 +473,4 @@ function firstString(value) {
473
473
  }
474
474
  export { clamp01 as a, aggregateRunScore as i, isTransientTransportFailure as n, runEval as o, transientDispatchFailure as r, llmJudge as t };
475
475
 
476
- //# sourceMappingURL=llm-judge-DYmEdo3M.js.map
476
+ //# sourceMappingURL=llm-judge-ChGnwj4s.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"llm-judge-DYmEdo3M.js","names":[],"sources":["../src/campaign/presets/run-eval.ts","../src/run-score.ts","../src/campaign/transient-failure.ts","../src/llm-judge.ts"],"sourcesContent":["/**\n * `runEval` — the simplest preset over `runCampaign`. No optimizer, no\n * gate, no auto-PR. Just: run scenarios through dispatch, score with\n * judges, return CampaignResult.\n *\n * The 80% case for consumers who want a scorecard, not an improvement loop.\n */\n\nimport { type RunCampaignOptions, runCampaign } from '../run-campaign'\nimport type { CampaignResult, Scenario } from '../types'\n\nexport interface RunEvalOptions<TScenario extends Scenario, TArtifact>\n extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'runDir'> {\n runDir: string\n}\n\n/**\n * Simplest evaluation preset: run scenarios through dispatch, score with judges, and return a `CampaignResult` — no optimizer, no gate, no PR.\n */\nexport async function runEval<TScenario extends Scenario, TArtifact>(\n opts: RunEvalOptions<TScenario, TArtifact>,\n): Promise<CampaignResult<TArtifact, TScenario>> {\n return runCampaign(opts)\n}\n","export interface RunScore {\n success: number\n goalProgress: number\n repoGroundedness: number\n driftPenalty: number\n toolUseQuality: number\n patchQuality: number\n testReality: number\n finalGate: number\n reviewerBlockers: number\n costUsd: number\n wallSeconds: number\n notes?: string[]\n}\n\nexport type RunScoreWeights = Omit<RunScore, 'notes'>\n\nconst DEFAULT_RUN_SCORE_WEIGHTS: RunScoreWeights = {\n success: 4,\n goalProgress: 2,\n repoGroundedness: 1.5,\n driftPenalty: -1.5,\n toolUseQuality: 1,\n patchQuality: 1.25,\n testReality: 1.5,\n finalGate: 3,\n reviewerBlockers: -2,\n costUsd: -0.2,\n wallSeconds: -0.1,\n}\n\nexport function aggregateRunScore(score: RunScore, weights: Partial<RunScoreWeights> = {}): number {\n const w = { ...DEFAULT_RUN_SCORE_WEIGHTS, ...weights }\n return (Object.keys(DEFAULT_RUN_SCORE_WEIGHTS) as Array<keyof RunScoreWeights>)\n .map(\n (key) =>\n w[key] *\n (key === 'costUsd' || key === 'wallSeconds'\n ? Math.max(0, finiteOrZero(score[key]) / (key === 'wallSeconds' ? 60 : 1))\n : clamp01(score[key])),\n )\n .reduce((sum, term) => sum + term)\n}\n\nexport function clamp01(value: number): number {\n return Math.max(0, Math.min(1, finiteOrZero(value)))\n}\n\nfunction finiteOrZero(value: number): number {\n return Number.isFinite(value) ? value : 0\n}\n","/**\n * Transient-transport-failure classification for dispatch retry policies.\n *\n * When an eval cell dies, the harness must decide: retry (the infrastructure\n * hiccuped - a 502 storm, an admission-queue rejection, a dropped stream) or\n * score it (the agent genuinely failed). Getting this wrong corrupts results\n * in both directions: scoring transport hiccups as failures buries real\n * effects under noise (agent-lab R353 found 5/30 identical repeats were 502s\n * scored as task failures), while retrying genuine failures silently drops\n * the hard cells and inflates every arm.\n *\n * A third direction was measured later and is not a knob: a provider refusal that states its own\n * release time (`quotaExhaustedUntil`). Retrying that is neither scoring nor recovering — it is\n * spending a subscription against a wall the provider already dated. It is terminal until the\n * stated instant, and an undated rate limit is untouched.\n *\n * Full-duration timeouts are the deliberate knob: on saturated shared\n * infrastructure a timeout usually means the request never got a slot\n * (retry it), but on unthrottled infrastructure it means the agent flailed\n * on the task until the clock ran out (a real score-0). Both readings were\n * needed in practice within one week, so the classifier takes it as an\n * option instead of hardcoding either.\n */\n\nimport type { CampaignCellFailureReceipt } from './run-campaign'\n\nexport interface TransientFailureOptions {\n /**\n * Treat full-duration timeouts (\"timeout after 180000ms\") as transient.\n * Enable on saturated shared infrastructure where queue starvation eats\n * the clock; leave off when the agent had the resources and simply failed.\n * Default false.\n */\n readonly retryFullDurationTimeouts?: boolean\n /** Additional caller-specific transient patterns. */\n readonly extraPatterns?: readonly RegExp[]\n /**\n * The instant a dated quota refusal is measured against. Defaults to `Date.now()`; inject it\n * to replay a past classification, which is what a retry audit needs.\n */\n readonly now?: number\n}\n\nconst BASE_TRANSIENT =\n /\\b50[234]\\b|no stream output|produced no stream|admission timed out|admission_rejected|queue_timeout|fetch failed|ECONNRESET|This operation was aborted/i\n\nconst TIMEOUT_PATTERN = /timeout after \\d+ ?ms|cli-bridge timeout/i\n\n/**\n * A provider refusal about a SPENT ALLOWANCE, which is not the same thing as a rate limit. It\n * becomes a release time only when a date follows it; the phrase alone stays retryable.\n *\n * `rate limit reached` is deliberately absent. Measured 2026-09-01: a z.ai 429 payload carries\n * `Rate limit reached for requests` and, 4,134 characters later in the same attempt log,\n * `reset at 2026-09-02 02:05:02`. That reset is minutes away and retrying it is correct. A\n * per-minute limit recovers on its own; an allowance does not.\n */\nconst QUOTA_PHRASE =\n /hit your usage limit|usage limit reached|insufficient balance|quota exceeded/gi\n\n/**\n * The clause that introduces the release time. The date may sit behind a purchase link and an\n * `or`, so the phrase and the clause are matched independently rather than as one span.\n */\nconst RELEASE_CLAUSE =\n /(?:try again|resets?|available again|retry)\\s+(?:at|on|after)\\s+([^\\n]{4,80})/i\n\n/**\n * How far past a refusal its release time may sit. Long enough for the purchase URL the codex\n * message puts between them, far shorter than one attempt record — see `quotaExhaustedUntil`.\n */\nconst RELEASE_WINDOW_CHARS = 400\n\n/**\n * The shapes a stated release is written in, in the order they are tried. THESE ARE THE\n * VALIDATION: a fragment that matches none of them is not a date, whatever `Date.parse` makes of\n * it. That matters — `Date.parse('Blursday 9999')` returns 9999-01-01, and a bare four-digit\n * number in prose would otherwise become a release nine thousand years out and stop a caller\n * forever.\n */\nconst RELEASE_SHAPES = [\n // NO UNZONED CLOCK. Measured 2026-09-01 on the z.ai seat: `Usage limit reached for 5 hour. Your\n // limit will reset at 2026-09-02 02:05:02` — a real spent allowance that states a real release,\n // in a machine payload with no zone at all. Read in the host's zone (UTC-6) that is 08:05Z; read\n // as the provider's it is 02:05Z. Nothing in the message decides between them, and a six-hour\n // error is six hours of a healthy seat withheld. A month-name or slash rendering is a CLI\n // printing in the HOST's zone, which is knowable; a bare numeric clock is not, and is refused.\n\n // 2026-09-07T02:29:00Z, 2026-09-07T02:29+02:00, or a bare 2026-09-07 (which ECMA-262 reads as\n // UTC). A numeric date-time with NO zone is deliberately absent — see NO UNZONED CLOCK below.\n /\\d{4}-\\d{2}-\\d{2}(?:[T ]\\d{1,2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?(?:Z|[+-]\\d{2}:?\\d{2}))?(?![\\d\\s:T-])/,\n // Sep 6th, 2026 8:29 PM · September 6 2026 · Sep 6, 2026\n /(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\\.?\\s+\\d{1,2}(?:st|nd|rd|th)?,?\\s+\\d{4}(?:,?\\s+\\d{1,2}:\\d{2}(?::\\d{2})?\\s*(?:[AaPp]\\.?[Mm]\\.?)?)?/,\n // 6 September 2026\n /\\d{1,2}(?:st|nd|rd|th)?\\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\\.?,?\\s+\\d{4}/,\n // 9/6/2026 8:29 PM\n /\\d{1,2}\\/\\d{1,2}\\/\\d{4}(?:,?\\s+\\d{1,2}:\\d{2}(?::\\d{2})?\\s*(?:[AaPp]\\.?[Mm]\\.?)?)?/,\n]\n\n/**\n * The instant a provider says a spent quota works again, or null when the text states none.\n *\n * MEASURED (2026-09-01, discovery lab). The codex/ChatGPT backend answered\n * `You've hit your usage limit. Visit https://chatgpt.com/codex/settings/usage to purchase more\n * credits or try again at Sep 6th, 2026 8:29 PM.` — a refusal SIX DAYS out. 25 supervised runs met\n * it. 21 of them retried it 12 times over about 31 minutes and settled with zero children, zero\n * tokens and zero claims: about 11 hours of one subscription's capacity spent on a wall that had\n * already told the caller when it would come down.\n *\n * The distinction this draws is not \"quota\" versus \"not quota\". It is \"the provider named a\n * release time\" versus \"it did not\". A bare 429, or z.ai's `您的账户已达到速率限制`, recovers on\n * its own in seconds and SHOULD be retried; those return null here and keep their existing\n * treatment. Only a stated release is terminal, and only until that instant.\n *\n * A date with no zone is read in the host's zone, because a CLI renders it in the host's zone.\n * An unparseable date returns null rather than a guess: a caller that stops dispatching must\n * never do so on a misread string.\n *\n * @param message the provider's error text\n * @returns the stated release time, or null when the text names none\n */\nfunction quotaExhaustedUntil(message: string | null | undefined): Date | null {\n if (!message) return null\n QUOTA_PHRASE.lastIndex = 0\n // THE RELEASE MUST BELONG TO THE REFUSAL. An error string can carry several provider payloads,\n // so searching the whole text for a phrase and, separately, for a date reads one payload's\n // quota against another payload's timestamp. Measured 2026-09-01: that pairing matched a z.ai\n // 429 to a date 4,134 characters away. The clause is searched only in the window FOLLOWING\n // each refusal.\n for (\n let phrase = QUOTA_PHRASE.exec(message);\n phrase !== null;\n phrase = QUOTA_PHRASE.exec(message)\n ) {\n const clause = RELEASE_CLAUSE.exec(\n message.slice(phrase.index, phrase.index + RELEASE_WINDOW_CHARS),\n )\n const stated = clause?.[1]\n if (stated === undefined) continue\n for (const shape of RELEASE_SHAPES) {\n const found = shape.exec(stated)\n if (found === null) continue\n // `Sep 6th` is not a date any parser accepts; the ordinal suffix is the only edit made.\n const until = Date.parse(found[0].replace(/\\b(\\d{1,2})(?:st|nd|rd|th)\\b/gi, '$1'))\n if (Number.isFinite(until)) return new Date(until)\n }\n }\n return null\n}\n\n/**\n * True when the error text describes an infrastructure hiccup that should be\n * retried rather than scored. Empty/undefined input is not transient.\n */\nexport function isTransientTransportFailure(\n message: string | null | undefined,\n opts: TransientFailureOptions = {},\n): boolean {\n if (!message) return false\n // A refusal that names its own release time is TERMINAL until that time, whatever else the text\n // matches. Checked first, and ahead of `extraPatterns`, because a caller's broad rate-limit\n // pattern would otherwise turn a six-day wall into a retry loop — see `quotaExhaustedUntil`.\n const until = quotaExhaustedUntil(message)\n if (until !== null && until.getTime() > (opts.now ?? Date.now())) return false\n if (BASE_TRANSIENT.test(message)) return true\n if ((opts.retryFullDurationTimeouts ?? false) && TIMEOUT_PATTERN.test(message)) return true\n for (const p of opts.extraPatterns ?? []) if (p.test(message)) return true\n return false\n}\n\n/**\n * Ready-made `cellRetry.retryable` predicate: true for a dispatch-stage\n * failure whose error message `isTransientTransportFailure` classifies as an\n * infrastructure hiccup. A judge-stage failure is never retried here — the\n * dispatch already produced an artifact, so re-dispatching would score a\n * different sample. A per-cell dispatch deadline (\"dispatch exceeded <N>ms\")\n * is not transient by default; opt in via `extraPatterns` or\n * `retryFullDurationTimeouts` when queue starvation eats the clock. A provider refusal that\n * states its own release time is never retried while that time is in the future\n * (`quotaExhaustedUntil`).\n */\nexport function transientDispatchFailure(\n opts: TransientFailureOptions = {},\n): (failure: CampaignCellFailureReceipt['failure']) => boolean {\n return (failure) =>\n failure.stage === 'dispatch' && isTransientTransportFailure(failure.error.message, opts)\n}\n","/**\n * `llmJudge` — the single-LLM-call bridge that turns a rubric prompt into a\n * canonical campaign `JudgeConfig`.\n *\n * The `JudgeConfig` contract (src/campaign/types.ts) is deliberately a\n * function, not a fixed LLM-prompt shape: real consumers judge with\n * ensembles, deterministic checks, or one LLM call. `ensembleJudge`\n * (src/judge-panel.ts) covers the multi-model case. `llmJudge` covers the\n * common single-call case the `JudgeConfig` doc-comment names:\n * one model call against `prompt`, parsed into the canonical `JudgeScore`\n * (`{ dimensions, composite, notes }`) on the campaign [0,1] scale.\n *\n * Transport is injected as a `ChatClient` (src/analyst/chat-client.ts) — the\n * substrate's transport-agnostic LLM seam — so the judge stays decoupled from\n * router-vs-sandbox-vs-cli-bridge and is unit-testable with the `mock`\n * transport. The composite is computed by `weightedComposite` (the same\n * sum-normalized weighting `ensembleJudge` uses), so a lift is attributable to\n * the dimension scores, not to a bespoke reducer.\n *\n * Fail-loud throughout: an unparseable model response throws `JudgeParseError`;\n * a response missing a declared dimension throws; an out-of-range score throws.\n * A thrown judge is recorded by the campaign engine as a failed cell, never\n * folded into a silent zero.\n */\n\nimport { z } from 'zod'\nimport type { ChatClient } from './analyst/chat-client'\nimport type { JudgeConfig, JudgeDimension, JudgeScore, Scenario } from './campaign/types'\nimport { CostLedger, type CostLedgerHandle } from './cost-ledger'\nimport { JudgeParseError } from './judges'\nimport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n type LlmCallMetadata,\n type LlmCallRequest,\n type LlmCallResult,\n type LlmTokenLogprob,\n maximumChargeForLlmRequest,\n stripFencedJson,\n} from './llm-client'\nimport { clamp01 } from './run-score'\nimport { weightedComposite } from './statistics'\nimport { contentHash } from './verdict-cache'\n\n/** A rubric dimension as a bare key or the full `{ key, description }` shape. A\n * bare string uses the key as its own description. */\nexport type LlmJudgeDimension = string | JudgeDimension\n\nexport interface LlmJudgeOptions<TArtifact, TScenario extends Scenario = Scenario> {\n /** The injected LLM transport. One `chat()` call per `score()`. Required —\n * there is no default route, so a misconfigured judge fails at construction,\n * never silently against the free-tier router. */\n chat: ChatClient\n /** Rubric dimensions the model scores. Each becomes a `[0,1]` field of the\n * returned `JudgeScore.dimensions`. Defaults to a single `quality` dimension. */\n dimensions?: LlmJudgeDimension[]\n /** Model id. Falls back to `chat.defaultModel`; one of the two MUST resolve. */\n model?: string\n /** Explicit scoring revision for opaque transport or renderer changes. */\n judgeVersion?: string\n temperature?: number\n maxTokens?: number\n /** Composite weights forwarded to `weightedComposite`: a partial map selects\n * AND weights exactly the named dimensions. Omit for a uniform mean. */\n weights?: Record<string, number>\n /**\n * How to read a score out of the model's answer.\n *\n * `'sampled'` (default) reads the number the model emitted. Discrete grades\n * tie often, and a tie carries no ranking signal.\n *\n * `'expectation'` asks the provider for the log probabilities of the score\n * token and returns the expected value over the integer grades the model\n * considered, so two answers that both sample `8` separate by how much mass\n * sat on `7` and `9`. It requires `scale: 'ten'`: an integer grade is one\n * token, and a `unit` float is not. `whenUnavailable` decides what happens\n * when the provider returns no log probabilities, or the grade did not land\n * in one token: `'fail'` throws, `'sampled'` reads the emitted number and\n * records `scoringMethod: 'sampled'` on the score.\n */\n scoring?: { method: 'sampled' } | { method: 'expectation'; whenUnavailable: 'fail' | 'sampled' }\n /** Scale the model is prompted to score on, normalized into `[0,1]`:\n * - `'unit'` (default): the model returns `[0,1]` directly.\n * - `'ten'`: the model returns `[0,10]`; divided by 10 here.\n * The prompt is annotated with the expected range either way. */\n scale?: 'unit' | 'ten'\n /** Run this judge only on matching scenarios (mirrors `JudgeConfig.appliesTo`). */\n appliesTo?: (scenario: TScenario) => boolean\n /** Render the artifact + scenario into the user message. Default:\n * pretty-printed JSON of `{ scenario, artifact }`. */\n renderUser?: (input: { artifact: TArtifact; scenario: TScenario }) => string\n /** Strict runtime contract; its JSON Schema is sent to the provider. */\n costLedger?: CostLedgerHandle\n responseSchema?: { name: string; schema: z.ZodObject }\n}\n\ninterface RawJudgeResponse {\n dimensions?: Record<string, unknown>\n scores?: Record<string, unknown>\n notes?: unknown\n rationale?: unknown\n}\n\n/**\n * Build a campaign-shaped `JudgeConfig` whose `score()` makes ONE LLM call\n * against `prompt` and reduces the model's per-dimension scores to a canonical\n * `JudgeScore` in `[0,1]`.\n *\n * The model is instructed to return JSON `{ \"dimensions\": { <key>: <number>, … },\n * \"notes\": \"…\" }`; the helper strips fenced JSON, validates every declared\n * dimension is present and in range, normalizes by `scale`, and composites via\n * `weightedComposite`.\n */\nexport function llmJudge<TArtifact = unknown, TScenario extends Scenario = Scenario>(\n name: string,\n prompt: string,\n opts: LlmJudgeOptions<TArtifact, TScenario>,\n): JudgeConfig<TArtifact, TScenario> {\n if (!name.trim()) {\n throw new Error('llmJudge: name must be non-empty')\n }\n if (!prompt.trim()) {\n throw new Error(`llmJudge '${name}': prompt must be non-empty`)\n }\n const model = opts.model ?? opts.chat.defaultModel\n if (!model) {\n throw new Error(\n `llmJudge '${name}': no model on opts and no defaultModel on the ChatClient — ` +\n 'pass opts.model or bind defaultModel at createChatClient().',\n )\n }\n\n const dimensions = normalizeDimensions(opts.dimensions, name)\n const scale = opts.scale ?? 'unit'\n const divisor = scale === 'ten' ? 10 : 1\n const scoring = opts.scoring ?? { method: 'sampled' }\n if (scoring.method === 'expectation' && scale !== 'ten') {\n throw new Error(\n `llmJudge '${name}': expectation scoring requires scale 'ten' — a [0,1] score is not one token, so no single position carries its distribution`,\n )\n }\n const renderUser =\n opts.renderUser ??\n ((input: { artifact: TArtifact; scenario: TScenario }) =>\n JSON.stringify({ scenario: input.scenario, artifact: input.artifact }, null, 2))\n\n if (opts.weights) {\n for (const key of Object.keys(opts.weights)) {\n if (!dimensions.some((d) => d.key === key)) {\n throw new Error(\n `llmJudge '${name}': weights names dimension '${key}' that is not declared in dimensions`,\n )\n }\n }\n }\n\n const systemPrompt = `${prompt}\\n\\n${renderContract(dimensions, scale)}`\n const directCostLedger = opts.costLedger ?? new CostLedger()\n let jsonSchema: { name: string; schema: Record<string, unknown> } | undefined\n if (opts.responseSchema) {\n const schema = { ...(z.toJSONSchema(opts.responseSchema.schema) as Record<string, unknown>) }\n delete schema.$schema\n jsonSchema = { name: opts.responseSchema.name, schema }\n }\n const declaredJudgeVersion = opts.judgeVersion?.trim()\n if (opts.judgeVersion !== undefined && !declaredJudgeVersion) {\n throw new Error(`llmJudge '${name}': judgeVersion must be non-empty when provided`)\n }\n const judgeVersion =\n declaredJudgeVersion ??\n contentHash({\n kind: 'llmJudge',\n prompt: systemPrompt,\n model,\n transport: opts.chat.transport,\n maximumAttempts: opts.chat.maximumAttempts ?? null,\n temperature: opts.temperature ?? 0.1,\n maxTokens: opts.maxTokens ?? 800,\n weights: opts.weights ?? null,\n scale,\n scoring,\n jsonSchema: jsonSchema ?? null,\n renderUser: opts.renderUser?.toString() ?? null,\n })\n\n return {\n name,\n dimensions,\n judgeVersion,\n appliesTo: opts.appliesTo,\n async score({\n artifact,\n scenario,\n signal,\n costLedger,\n costPhase,\n costTags,\n }): Promise<JudgeScore> {\n const request: LlmCallRequest = {\n model,\n messages: [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: renderUser({ artifact, scenario }) },\n ],\n jsonMode: true,\n jsonSchema,\n ...(scoring.method === 'expectation'\n ? { logprobs: { topLogprobs: EXPECTATION_TOP_LOGPROBS } }\n : {}),\n temperature: opts.temperature ?? 0.1,\n maxTokens: opts.maxTokens ?? 800,\n }\n const paid = await (costLedger ?? directCostLedger).runPaidCall({\n channel: 'judge',\n phase: costPhase ?? 'judge',\n actor: name,\n model,\n maximumCharge:\n opts.chat.maximumAttempts === undefined\n ? undefined\n : maximumChargeForLlmRequest(request, {\n maximumAttempts: opts.chat.maximumAttempts,\n }),\n tags: { ...costTags, scenarioId: scenario.id },\n signal,\n execute: (callSignal, callId) =>\n opts.chat.chat(request, { signal: callSignal, idempotencyKey: callId }),\n receipt: costReceiptFromLlm,\n receiptFromError: costReceiptFromLlmError,\n })\n if (!paid.succeeded) throw paid.error\n const response = paid.value\n const llmCall: LlmCallMetadata = {\n usage: response.usage,\n costUsd: response.costUsd,\n model: response.model,\n durationMs: response.durationMs,\n }\n\n const parsed = parseResponse(name, response, opts.responseSchema?.schema, llmCall)\n const rawDims = parsed.dimensions ?? parsed.scores\n if (!rawDims || typeof rawDims !== 'object') {\n throw new JudgeParseError(name, response.content, {\n cause: new Error('response has no `dimensions` object'),\n llmCall,\n })\n }\n\n const sampled: Record<string, number> = {}\n for (const { key } of dimensions) {\n const raw = (rawDims as Record<string, unknown>)[key]\n const value = Number(raw)\n if (raw === undefined || raw === null || !Number.isFinite(value)) {\n throw new JudgeParseError(name, response.content, {\n cause: new Error(\n `dimension '${key}' missing or non-numeric (got ${JSON.stringify(raw)})`,\n ),\n llmCall,\n })\n }\n sampled[key] = value\n }\n\n let scoringMethod: 'sampled' | 'expectation' = 'sampled'\n let distribution: Record<string, Array<{ score: number; probability: number }>> | undefined\n const dims: Record<string, number> = {}\n if (scoring.method === 'expectation') {\n const expectation = expectedDimensionScores({\n tokens: response.logprobs ?? null,\n sampled,\n maxScore: divisor,\n })\n if (expectation.kind === 'unavailable') {\n if (scoring.whenUnavailable === 'fail') {\n throw new Error(\n `llmJudge '${name}': expectation scoring is unavailable — ${expectation.reason}`,\n )\n }\n } else {\n scoringMethod = 'expectation'\n distribution = expectation.distribution\n for (const { key } of dimensions) dims[key] = clamp01(expectation.scores[key]! / divisor)\n }\n }\n if (scoringMethod === 'sampled') {\n for (const { key } of dimensions) dims[key] = clamp01(sampled[key]! / divisor)\n }\n\n const weights =\n opts.weights ?? Object.fromEntries(dimensions.map((d) => [d.key, 1 / dimensions.length]))\n const { composite } = weightedComposite({ dims, weights })\n\n const notes =\n firstString(parsed.notes) ??\n firstString(parsed.rationale) ??\n `${name}: composite ${composite.toFixed(3)} over ${dimensions.length} dimension(s)`\n\n return {\n dimensions: dims,\n composite,\n notes,\n llmCall,\n ...(opts.scoring ? { scoringMethod } : {}),\n ...(distribution ? { distribution } : {}),\n }\n },\n }\n}\n\n/** Alternatives requested per score token. Twenty is the documented ceiling of\n * the OpenAI-compatible `top_logprobs` field, and a grade scale has at most\n * eleven integer candidates, so the window always covers the whole scale. */\nconst EXPECTATION_TOP_LOGPROBS = 20\n\ntype ExpectationResult =\n | {\n kind: 'expectation'\n scores: Record<string, number>\n distribution: Record<string, Array<{ score: number; probability: number }>>\n }\n | { kind: 'unavailable'; reason: string }\n\n/**\n * Expected grade per dimension: locate the token that carried each dimension's\n * integer score, then average the integer grades the model considered at that\n * position, weighted by their probabilities.\n *\n * Unavailable — never silently approximated — when the provider returned no\n * log probabilities, when a dimension's grade is not in the token stream, or\n * when the grade did not land in exactly one token (a two-token `10`, a float).\n */\nfunction expectedDimensionScores(input: {\n tokens: ReadonlyArray<LlmTokenLogprob> | null\n sampled: Record<string, number>\n maxScore: number\n}): ExpectationResult {\n const { tokens, sampled, maxScore } = input\n if (tokens === null) return { kind: 'unavailable', reason: 'the provider returned no logprobs' }\n if (tokens.length === 0) {\n return { kind: 'unavailable', reason: 'the provider returned an empty logprob stream' }\n }\n const offsets: number[] = []\n let text = ''\n for (const token of tokens) {\n offsets.push(text.length)\n text += token.token\n }\n\n const scores: Record<string, number> = {}\n const distribution: Record<string, Array<{ score: number; probability: number }>> = {}\n for (const [key, value] of Object.entries(sampled)) {\n const match = new RegExp(`\"${escapeRegExp(key)}\"\\\\s*:\\\\s*`).exec(text)\n if (!match) {\n return { kind: 'unavailable', reason: `dimension '${key}' is not in the token stream` }\n }\n const scoreOffset = match.index + match[0].length\n let index = -1\n for (let position = 0; position < offsets.length; position++) {\n if (offsets[position]! <= scoreOffset) index = position\n else break\n }\n const token = tokens[index]\n if (!token) {\n return {\n kind: 'unavailable',\n reason: `dimension '${key}' has no token at its score position`,\n }\n }\n if (integerGrade(token.token, maxScore) !== value) {\n return {\n kind: 'unavailable',\n reason: `dimension '${key}' scored ${value}, which is not the whole of its token '${token.token}'`,\n }\n }\n const candidates: Array<{ score: number; probability: number }> = []\n let total = 0\n for (const alternative of token.top.length > 0 ? token.top : [token]) {\n const grade = integerGrade(alternative.token, maxScore)\n if (grade === null) continue\n const probability = Math.exp(alternative.logprob)\n if (!Number.isFinite(probability) || probability <= 0) continue\n candidates.push({ score: grade, probability })\n total += probability\n }\n if (candidates.length === 0 || total <= 0) {\n return {\n kind: 'unavailable',\n reason: `dimension '${key}' has no integer grade in its probability window`,\n }\n }\n let expectation = 0\n for (const candidate of candidates)\n expectation += (candidate.probability / total) * candidate.score\n scores[key] = expectation\n distribution[key] = candidates\n .map((candidate) => ({ score: candidate.score, probability: candidate.probability / total }))\n .sort((left, right) => left.score - right.score)\n }\n return { kind: 'expectation', scores, distribution }\n}\n\n/** The token's integer grade on the judge's scale, or null when the token is\n * not exactly one integer in range. */\nfunction integerGrade(token: string, maxScore: number): number | null {\n const trimmed = token.trim()\n if (!/^\\d+$/.test(trimmed)) return null\n const value = Number(trimmed)\n return Number.isInteger(value) && value >= 0 && value <= maxScore ? value : null\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction normalizeDimensions(\n input: LlmJudgeDimension[] | undefined,\n name: string,\n): JudgeDimension[] {\n const raw = input && input.length > 0 ? input : ['quality']\n const out: JudgeDimension[] = []\n const seen = new Set<string>()\n for (const d of raw) {\n const dim = typeof d === 'string' ? { key: d, description: d } : d\n if (!dim.key.trim()) {\n throw new Error(`llmJudge '${name}': dimension key must be non-empty`)\n }\n if (seen.has(dim.key)) {\n throw new Error(`llmJudge '${name}': duplicate dimension key '${dim.key}'`)\n }\n seen.add(dim.key)\n out.push(dim)\n }\n return out\n}\n\nfunction renderContract(dimensions: JudgeDimension[], scale: 'unit' | 'ten'): string {\n const range = scale === 'ten' ? '0 to 10' : '0.0 to 1.0'\n const lines = dimensions.map((d) => ` - \"${d.key}\": ${d.description} (score ${range})`)\n const example = `{\"dimensions\": {${dimensions\n .map((d) => `\"${d.key}\": <number>`)\n .join(', ')}}, \"notes\": \"<one-line rationale>\"}`\n return [\n 'Score the artifact on EACH of these dimensions:',\n ...lines,\n '',\n `Respond with JSON ONLY, no prose. Every dimension is a number in [${range}]:`,\n example,\n ].join('\\n')\n}\n\nfunction parseResponse(\n name: string,\n response: LlmCallResult,\n schema: z.ZodObject | undefined,\n llmCall: LlmCallMetadata,\n): RawJudgeResponse {\n const { content } = response\n const fail = (cause: unknown) => new JudgeParseError(name, content, { cause, llmCall })\n if (response.finishReason != null && response.finishReason !== 'stop') {\n throw fail(\n new Error(`response did not complete normally (finishReason=${response.finishReason})`),\n )\n }\n if (schema) {\n try {\n return schema.parse(JSON.parse(stripFencedJson(content))) as RawJudgeResponse\n } catch (cause) {\n throw fail(cause)\n }\n }\n const stripped = content.replace(/```json\\n?|\\n?```/g, '').trim()\n const objMatch = stripped.match(/\\{[\\s\\S]*\\}/)\n const payload = objMatch ? objMatch[0] : stripped\n try {\n const parsed = JSON.parse(payload) as RawJudgeResponse\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('parsed value is not an object')\n }\n return parsed\n } catch (cause) {\n throw fail(cause)\n }\n}\n\nfunction firstString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value : undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,eAAsB,QACpB,MAC+C;CAC/C,OAAO,YAAY,IAAI;AACzB;;ACNA,MAAM,4BAA6C;CACjD,SAAS;CACT,cAAc;CACd,kBAAkB;CAClB,cAAc;CACd,gBAAgB;CAChB,cAAc;CACd,aAAa;CACb,WAAW;CACX,kBAAkB;CAClB,SAAS;CACT,aAAa;AACf;AAEA,SAAgB,kBAAkB,OAAiB,UAAoC,CAAC,GAAW;CACjG,MAAM,IAAI;EAAE,GAAG;EAA2B,GAAG;CAAQ;CACrD,OAAQ,OAAO,KAAK,yBAAyB,CAAC,CAC3C,KACE,QACC,EAAE,QACD,QAAQ,aAAa,QAAQ,gBAC1B,KAAK,IAAI,GAAG,aAAa,MAAM,IAAI,KAAK,QAAQ,gBAAgB,KAAK,EAAE,IACvE,QAAQ,MAAM,IAAI,EAC1B,CAAC,CACA,QAAQ,KAAK,SAAS,MAAM,IAAI;AACrC;AAEA,SAAgB,QAA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AAa,EAAE,CACxF;CAEF,IAAI,QACF,IAAI;EACF,OAAO,OAAO,MAAM,KAAK,MAAM,gBAAgB,OAAO,CAAC,CAAC;CAC1D,SAAS,OAAO;EACd,MAAM,KAAK,KAAK;CAClB;CAEF,MAAM,WAAW,QAAQ,QAAQ,sBAAsB,EAAE,CAAC,CAAC,KAAK;CAChE,MAAM,WAAW,SAAS,MAAM,aAAa;CAC7C,MAAM,UAAU,WAAW,SAAS,KAAK;CACzC,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,OAAO;EACjC,IAAI,OAAO,WAAW,YAAY,WAAW,MAC3C,MAAM,IAAI,MAAM,+BAA+B;EAEjD,OAAO;CACT,SAAS,OAAO;EACd,MAAM,KAAK,KAAK;CAClB;AACF;AAEA,SAAS,YAAY,OAAoC;CACvD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,IAAI,QAAQ,KAAA;AAC7D"}
1
+ {"version":3,"file":"llm-judge-ChGnwj4s.js","names":[],"sources":["../src/campaign/presets/run-eval.ts","../src/run-score.ts","../src/campaign/transient-failure.ts","../src/llm-judge.ts"],"sourcesContent":["/**\n * `runEval` — the simplest preset over `runCampaign`. No optimizer, no\n * gate, no auto-PR. Just: run scenarios through dispatch, score with\n * judges, return CampaignResult.\n *\n * The 80% case for consumers who want a scorecard, not an improvement loop.\n */\n\nimport { type RunCampaignOptions, runCampaign } from '../run-campaign'\nimport type { CampaignResult, Scenario } from '../types'\n\nexport interface RunEvalOptions<TScenario extends Scenario, TArtifact>\n extends Omit<RunCampaignOptions<TScenario, TArtifact>, 'runDir'> {\n runDir: string\n}\n\n/**\n * Simplest evaluation preset: run scenarios through dispatch, score with judges, and return a `CampaignResult` — no optimizer, no gate, no PR.\n */\nexport async function runEval<TScenario extends Scenario, TArtifact>(\n opts: RunEvalOptions<TScenario, TArtifact>,\n): Promise<CampaignResult<TArtifact, TScenario>> {\n return runCampaign(opts)\n}\n","export interface RunScore {\n success: number\n goalProgress: number\n repoGroundedness: number\n driftPenalty: number\n toolUseQuality: number\n patchQuality: number\n testReality: number\n finalGate: number\n reviewerBlockers: number\n costUsd: number\n wallSeconds: number\n notes?: string[]\n}\n\nexport type RunScoreWeights = Omit<RunScore, 'notes'>\n\nconst DEFAULT_RUN_SCORE_WEIGHTS: RunScoreWeights = {\n success: 4,\n goalProgress: 2,\n repoGroundedness: 1.5,\n driftPenalty: -1.5,\n toolUseQuality: 1,\n patchQuality: 1.25,\n testReality: 1.5,\n finalGate: 3,\n reviewerBlockers: -2,\n costUsd: -0.2,\n wallSeconds: -0.1,\n}\n\nexport function aggregateRunScore(score: RunScore, weights: Partial<RunScoreWeights> = {}): number {\n const w = { ...DEFAULT_RUN_SCORE_WEIGHTS, ...weights }\n return (Object.keys(DEFAULT_RUN_SCORE_WEIGHTS) as Array<keyof RunScoreWeights>)\n .map(\n (key) =>\n w[key] *\n (key === 'costUsd' || key === 'wallSeconds'\n ? Math.max(0, finiteOrZero(score[key]) / (key === 'wallSeconds' ? 60 : 1))\n : clamp01(score[key])),\n )\n .reduce((sum, term) => sum + term)\n}\n\nexport function clamp01(value: number): number {\n return Math.max(0, Math.min(1, finiteOrZero(value)))\n}\n\nfunction finiteOrZero(value: number): number {\n return Number.isFinite(value) ? value : 0\n}\n","/**\n * Transient-transport-failure classification for dispatch retry policies.\n *\n * When an eval cell dies, the harness must decide: retry (the infrastructure\n * hiccuped - a 502 storm, an admission-queue rejection, a dropped stream) or\n * score it (the agent genuinely failed). Getting this wrong corrupts results\n * in both directions: scoring transport hiccups as failures buries real\n * effects under noise (agent-lab R353 found 5/30 identical repeats were 502s\n * scored as task failures), while retrying genuine failures silently drops\n * the hard cells and inflates every arm.\n *\n * A third direction was measured later and is not a knob: a provider refusal that states its own\n * release time (`quotaExhaustedUntil`). Retrying that is neither scoring nor recovering — it is\n * spending a subscription against a wall the provider already dated. It is terminal until the\n * stated instant, and an undated rate limit is untouched.\n *\n * Full-duration timeouts are the deliberate knob: on saturated shared\n * infrastructure a timeout usually means the request never got a slot\n * (retry it), but on unthrottled infrastructure it means the agent flailed\n * on the task until the clock ran out (a real score-0). Both readings were\n * needed in practice within one week, so the classifier takes it as an\n * option instead of hardcoding either.\n */\n\nimport type { CampaignCellFailureReceipt } from './run-campaign'\n\nexport interface TransientFailureOptions {\n /**\n * Treat full-duration timeouts (\"timeout after 180000ms\") as transient.\n * Enable on saturated shared infrastructure where queue starvation eats\n * the clock; leave off when the agent had the resources and simply failed.\n * Default false.\n */\n readonly retryFullDurationTimeouts?: boolean\n /** Additional caller-specific transient patterns. */\n readonly extraPatterns?: readonly RegExp[]\n /**\n * The instant a dated quota refusal is measured against. Defaults to `Date.now()`; inject it\n * to replay a past classification, which is what a retry audit needs.\n */\n readonly now?: number\n}\n\nconst BASE_TRANSIENT =\n /\\b50[234]\\b|no stream output|produced no stream|admission timed out|admission_rejected|queue_timeout|fetch failed|ECONNRESET|This operation was aborted/i\n\nconst TIMEOUT_PATTERN = /timeout after \\d+ ?ms|cli-bridge timeout/i\n\n/**\n * A provider refusal about a SPENT ALLOWANCE, which is not the same thing as a rate limit. It\n * becomes a release time only when a date follows it; the phrase alone stays retryable.\n *\n * `rate limit reached` is deliberately absent. Measured 2026-09-01: a z.ai 429 payload carries\n * `Rate limit reached for requests` and, 4,134 characters later in the same attempt log,\n * `reset at 2026-09-02 02:05:02`. That reset is minutes away and retrying it is correct. A\n * per-minute limit recovers on its own; an allowance does not.\n */\nconst QUOTA_PHRASE =\n /hit your usage limit|usage limit reached|insufficient balance|quota exceeded/gi\n\n/**\n * The clause that introduces the release time. The date may sit behind a purchase link and an\n * `or`, so the phrase and the clause are matched independently rather than as one span.\n */\nconst RELEASE_CLAUSE =\n /(?:try again|resets?|available again|retry)\\s+(?:at|on|after)\\s+([^\\n]{4,80})/i\n\n/**\n * How far past a refusal its release time may sit. Long enough for the purchase URL the codex\n * message puts between them, far shorter than one attempt record — see `quotaExhaustedUntil`.\n */\nconst RELEASE_WINDOW_CHARS = 400\n\n/**\n * The shapes a stated release is written in, in the order they are tried. THESE ARE THE\n * VALIDATION: a fragment that matches none of them is not a date, whatever `Date.parse` makes of\n * it. That matters — `Date.parse('Blursday 9999')` returns 9999-01-01, and a bare four-digit\n * number in prose would otherwise become a release nine thousand years out and stop a caller\n * forever.\n */\nconst RELEASE_SHAPES = [\n // NO UNZONED CLOCK. Measured 2026-09-01 on the z.ai seat: `Usage limit reached for 5 hour. Your\n // limit will reset at 2026-09-02 02:05:02` — a real spent allowance that states a real release,\n // in a machine payload with no zone at all. Read in the host's zone (UTC-6) that is 08:05Z; read\n // as the provider's it is 02:05Z. Nothing in the message decides between them, and a six-hour\n // error is six hours of a healthy seat withheld. A month-name or slash rendering is a CLI\n // printing in the HOST's zone, which is knowable; a bare numeric clock is not, and is refused.\n\n // 2026-09-07T02:29:00Z, 2026-09-07T02:29+02:00, or a bare 2026-09-07 (which ECMA-262 reads as\n // UTC). A numeric date-time with NO zone is deliberately absent — see NO UNZONED CLOCK below.\n /\\d{4}-\\d{2}-\\d{2}(?:[T ]\\d{1,2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?(?:Z|[+-]\\d{2}:?\\d{2}))?(?![\\d\\s:T-])/,\n // Sep 6th, 2026 8:29 PM · September 6 2026 · Sep 6, 2026\n /(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\\.?\\s+\\d{1,2}(?:st|nd|rd|th)?,?\\s+\\d{4}(?:,?\\s+\\d{1,2}:\\d{2}(?::\\d{2})?\\s*(?:[AaPp]\\.?[Mm]\\.?)?)?/,\n // 6 September 2026\n /\\d{1,2}(?:st|nd|rd|th)?\\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\\.?,?\\s+\\d{4}/,\n // 9/6/2026 8:29 PM\n /\\d{1,2}\\/\\d{1,2}\\/\\d{4}(?:,?\\s+\\d{1,2}:\\d{2}(?::\\d{2})?\\s*(?:[AaPp]\\.?[Mm]\\.?)?)?/,\n]\n\n/**\n * The instant a provider says a spent quota works again, or null when the text states none.\n *\n * MEASURED (2026-09-01, discovery lab). The codex/ChatGPT backend answered\n * `You've hit your usage limit. Visit https://chatgpt.com/codex/settings/usage to purchase more\n * credits or try again at Sep 6th, 2026 8:29 PM.` — a refusal SIX DAYS out. 25 supervised runs met\n * it. 21 of them retried it 12 times over about 31 minutes and settled with zero children, zero\n * tokens and zero claims: about 11 hours of one subscription's capacity spent on a wall that had\n * already told the caller when it would come down.\n *\n * The distinction this draws is not \"quota\" versus \"not quota\". It is \"the provider named a\n * release time\" versus \"it did not\". A bare 429, or z.ai's `您的账户已达到速率限制`, recovers on\n * its own in seconds and SHOULD be retried; those return null here and keep their existing\n * treatment. Only a stated release is terminal, and only until that instant.\n *\n * A date with no zone is read in the host's zone, because a CLI renders it in the host's zone.\n * An unparseable date returns null rather than a guess: a caller that stops dispatching must\n * never do so on a misread string.\n *\n * @param message the provider's error text\n * @returns the stated release time, or null when the text names none\n */\nfunction quotaExhaustedUntil(message: string | null | undefined): Date | null {\n if (!message) return null\n QUOTA_PHRASE.lastIndex = 0\n // THE RELEASE MUST BELONG TO THE REFUSAL. An error string can carry several provider payloads,\n // so searching the whole text for a phrase and, separately, for a date reads one payload's\n // quota against another payload's timestamp. Measured 2026-09-01: that pairing matched a z.ai\n // 429 to a date 4,134 characters away. The clause is searched only in the window FOLLOWING\n // each refusal.\n for (\n let phrase = QUOTA_PHRASE.exec(message);\n phrase !== null;\n phrase = QUOTA_PHRASE.exec(message)\n ) {\n const clause = RELEASE_CLAUSE.exec(\n message.slice(phrase.index, phrase.index + RELEASE_WINDOW_CHARS),\n )\n const stated = clause?.[1]\n if (stated === undefined) continue\n for (const shape of RELEASE_SHAPES) {\n const found = shape.exec(stated)\n if (found === null) continue\n // `Sep 6th` is not a date any parser accepts; the ordinal suffix is the only edit made.\n const until = Date.parse(found[0].replace(/\\b(\\d{1,2})(?:st|nd|rd|th)\\b/gi, '$1'))\n if (Number.isFinite(until)) return new Date(until)\n }\n }\n return null\n}\n\n/**\n * True when the error text describes an infrastructure hiccup that should be\n * retried rather than scored. Empty/undefined input is not transient.\n */\nexport function isTransientTransportFailure(\n message: string | null | undefined,\n opts: TransientFailureOptions = {},\n): boolean {\n if (!message) return false\n // A refusal that names its own release time is TERMINAL until that time, whatever else the text\n // matches. Checked first, and ahead of `extraPatterns`, because a caller's broad rate-limit\n // pattern would otherwise turn a six-day wall into a retry loop — see `quotaExhaustedUntil`.\n const until = quotaExhaustedUntil(message)\n if (until !== null && until.getTime() > (opts.now ?? Date.now())) return false\n if (BASE_TRANSIENT.test(message)) return true\n if ((opts.retryFullDurationTimeouts ?? false) && TIMEOUT_PATTERN.test(message)) return true\n for (const p of opts.extraPatterns ?? []) if (p.test(message)) return true\n return false\n}\n\n/**\n * Ready-made `cellRetry.retryable` predicate: true for a dispatch-stage\n * failure whose error message `isTransientTransportFailure` classifies as an\n * infrastructure hiccup. A judge-stage failure is never retried here — the\n * dispatch already produced an artifact, so re-dispatching would score a\n * different sample. A per-cell dispatch deadline (\"dispatch exceeded <N>ms\")\n * is not transient by default; opt in via `extraPatterns` or\n * `retryFullDurationTimeouts` when queue starvation eats the clock. A provider refusal that\n * states its own release time is never retried while that time is in the future\n * (`quotaExhaustedUntil`).\n */\nexport function transientDispatchFailure(\n opts: TransientFailureOptions = {},\n): (failure: CampaignCellFailureReceipt['failure']) => boolean {\n return (failure) =>\n failure.stage === 'dispatch' && isTransientTransportFailure(failure.error.message, opts)\n}\n","/**\n * `llmJudge` — the single-LLM-call bridge that turns a rubric prompt into a\n * canonical campaign `JudgeConfig`.\n *\n * The `JudgeConfig` contract (src/campaign/types.ts) is deliberately a\n * function, not a fixed LLM-prompt shape: real consumers judge with\n * ensembles, deterministic checks, or one LLM call. `ensembleJudge`\n * (src/judge-panel.ts) covers the multi-model case. `llmJudge` covers the\n * common single-call case the `JudgeConfig` doc-comment names:\n * one model call against `prompt`, parsed into the canonical `JudgeScore`\n * (`{ dimensions, composite, notes }`) on the campaign [0,1] scale.\n *\n * Transport is injected as a `ChatClient` (src/analyst/chat-client.ts) — the\n * substrate's transport-agnostic LLM seam — so the judge stays decoupled from\n * router-vs-sandbox-vs-cli-bridge and is unit-testable with the `mock`\n * transport. The composite is computed by `weightedComposite` (the same\n * sum-normalized weighting `ensembleJudge` uses), so a lift is attributable to\n * the dimension scores, not to a bespoke reducer.\n *\n * Fail-loud throughout: an unparseable model response throws `JudgeParseError`;\n * a response missing a declared dimension throws; an out-of-range score throws.\n * A thrown judge is recorded by the campaign engine as a failed cell, never\n * folded into a silent zero.\n */\n\nimport { z } from 'zod'\nimport type { ChatClient } from './analyst/chat-client'\nimport type { JudgeConfig, JudgeDimension, JudgeScore, Scenario } from './campaign/types'\nimport { CostLedger, type CostLedgerHandle } from './cost-ledger'\nimport { JudgeParseError } from './judges'\nimport {\n costReceiptFromLlm,\n costReceiptFromLlmError,\n type LlmCallMetadata,\n type LlmCallRequest,\n type LlmCallResult,\n type LlmTokenLogprob,\n maximumChargeForLlmRequest,\n stripFencedJson,\n} from './llm-client'\nimport { clamp01 } from './run-score'\nimport { weightedComposite } from './statistics'\nimport { contentHash } from './verdict-cache'\n\n/** A rubric dimension as a bare key or the full `{ key, description }` shape. A\n * bare string uses the key as its own description. */\nexport type LlmJudgeDimension = string | JudgeDimension\n\nexport interface LlmJudgeOptions<TArtifact, TScenario extends Scenario = Scenario> {\n /** The injected LLM transport. One `chat()` call per `score()`. Required —\n * there is no default route, so a misconfigured judge fails at construction,\n * never silently against the free-tier router. */\n chat: ChatClient\n /** Rubric dimensions the model scores. Each becomes a `[0,1]` field of the\n * returned `JudgeScore.dimensions`. Defaults to a single `quality` dimension. */\n dimensions?: LlmJudgeDimension[]\n /** Model id. Falls back to `chat.defaultModel`; one of the two MUST resolve. */\n model?: string\n /** Explicit scoring revision for opaque transport or renderer changes. */\n judgeVersion?: string\n temperature?: number\n maxTokens?: number\n /** Composite weights forwarded to `weightedComposite`: a partial map selects\n * AND weights exactly the named dimensions. Omit for a uniform mean. */\n weights?: Record<string, number>\n /**\n * How to read a score out of the model's answer.\n *\n * `'sampled'` (default) reads the number the model emitted. Discrete grades\n * tie often, and a tie carries no ranking signal.\n *\n * `'expectation'` asks the provider for the log probabilities of the score\n * token and returns the expected value over the integer grades the model\n * considered, so two answers that both sample `8` separate by how much mass\n * sat on `7` and `9`. It requires `scale: 'ten'`: an integer grade is one\n * token, and a `unit` float is not. `whenUnavailable` decides what happens\n * when the provider returns no log probabilities, or the grade did not land\n * in one token: `'fail'` throws, `'sampled'` reads the emitted number and\n * records `scoringMethod: 'sampled'` on the score.\n */\n scoring?: { method: 'sampled' } | { method: 'expectation'; whenUnavailable: 'fail' | 'sampled' }\n /** Scale the model is prompted to score on, normalized into `[0,1]`:\n * - `'unit'` (default): the model returns `[0,1]` directly.\n * - `'ten'`: the model returns `[0,10]`; divided by 10 here.\n * The prompt is annotated with the expected range either way. */\n scale?: 'unit' | 'ten'\n /** Run this judge only on matching scenarios (mirrors `JudgeConfig.appliesTo`). */\n appliesTo?: (scenario: TScenario) => boolean\n /** Render the artifact + scenario into the user message. Default:\n * pretty-printed JSON of `{ scenario, artifact }`. */\n renderUser?: (input: { artifact: TArtifact; scenario: TScenario }) => string\n /** Strict runtime contract; its JSON Schema is sent to the provider. */\n costLedger?: CostLedgerHandle\n responseSchema?: { name: string; schema: z.ZodObject }\n}\n\ninterface RawJudgeResponse {\n dimensions?: Record<string, unknown>\n scores?: Record<string, unknown>\n notes?: unknown\n rationale?: unknown\n}\n\n/**\n * Build a campaign-shaped `JudgeConfig` whose `score()` makes ONE LLM call\n * against `prompt` and reduces the model's per-dimension scores to a canonical\n * `JudgeScore` in `[0,1]`.\n *\n * The model is instructed to return JSON `{ \"dimensions\": { <key>: <number>, … },\n * \"notes\": \"…\" }`; the helper strips fenced JSON, validates every declared\n * dimension is present and in range, normalizes by `scale`, and composites via\n * `weightedComposite`.\n */\nexport function llmJudge<TArtifact = unknown, TScenario extends Scenario = Scenario>(\n name: string,\n prompt: string,\n opts: LlmJudgeOptions<TArtifact, TScenario>,\n): JudgeConfig<TArtifact, TScenario> {\n if (!name.trim()) {\n throw new Error('llmJudge: name must be non-empty')\n }\n if (!prompt.trim()) {\n throw new Error(`llmJudge '${name}': prompt must be non-empty`)\n }\n const model = opts.model ?? opts.chat.defaultModel\n if (!model) {\n throw new Error(\n `llmJudge '${name}': no model on opts and no defaultModel on the ChatClient — ` +\n 'pass opts.model or bind defaultModel at createChatClient().',\n )\n }\n\n const dimensions = normalizeDimensions(opts.dimensions, name)\n const scale = opts.scale ?? 'unit'\n const divisor = scale === 'ten' ? 10 : 1\n const scoring = opts.scoring ?? { method: 'sampled' }\n if (scoring.method === 'expectation' && scale !== 'ten') {\n throw new Error(\n `llmJudge '${name}': expectation scoring requires scale 'ten' — a [0,1] score is not one token, so no single position carries its distribution`,\n )\n }\n const renderUser =\n opts.renderUser ??\n ((input: { artifact: TArtifact; scenario: TScenario }) =>\n JSON.stringify({ scenario: input.scenario, artifact: input.artifact }, null, 2))\n\n if (opts.weights) {\n for (const key of Object.keys(opts.weights)) {\n if (!dimensions.some((d) => d.key === key)) {\n throw new Error(\n `llmJudge '${name}': weights names dimension '${key}' that is not declared in dimensions`,\n )\n }\n }\n }\n\n const systemPrompt = `${prompt}\\n\\n${renderContract(dimensions, scale)}`\n const directCostLedger = opts.costLedger ?? new CostLedger()\n let jsonSchema: { name: string; schema: Record<string, unknown> } | undefined\n if (opts.responseSchema) {\n const schema = { ...(z.toJSONSchema(opts.responseSchema.schema) as Record<string, unknown>) }\n delete schema.$schema\n jsonSchema = { name: opts.responseSchema.name, schema }\n }\n const declaredJudgeVersion = opts.judgeVersion?.trim()\n if (opts.judgeVersion !== undefined && !declaredJudgeVersion) {\n throw new Error(`llmJudge '${name}': judgeVersion must be non-empty when provided`)\n }\n const judgeVersion =\n declaredJudgeVersion ??\n contentHash({\n kind: 'llmJudge',\n prompt: systemPrompt,\n model,\n transport: opts.chat.transport,\n maximumAttempts: opts.chat.maximumAttempts ?? null,\n temperature: opts.temperature ?? 0.1,\n maxTokens: opts.maxTokens ?? 800,\n weights: opts.weights ?? null,\n scale,\n scoring,\n jsonSchema: jsonSchema ?? null,\n renderUser: opts.renderUser?.toString() ?? null,\n })\n\n return {\n name,\n dimensions,\n judgeVersion,\n appliesTo: opts.appliesTo,\n async score({\n artifact,\n scenario,\n signal,\n costLedger,\n costPhase,\n costTags,\n }): Promise<JudgeScore> {\n const request: LlmCallRequest = {\n model,\n messages: [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: renderUser({ artifact, scenario }) },\n ],\n jsonMode: true,\n jsonSchema,\n ...(scoring.method === 'expectation'\n ? { logprobs: { topLogprobs: EXPECTATION_TOP_LOGPROBS } }\n : {}),\n temperature: opts.temperature ?? 0.1,\n maxTokens: opts.maxTokens ?? 800,\n }\n const paid = await (costLedger ?? directCostLedger).runPaidCall({\n channel: 'judge',\n phase: costPhase ?? 'judge',\n actor: name,\n model,\n maximumCharge:\n opts.chat.maximumAttempts === undefined\n ? undefined\n : maximumChargeForLlmRequest(request, {\n maximumAttempts: opts.chat.maximumAttempts,\n }),\n tags: { ...costTags, scenarioId: scenario.id },\n signal,\n execute: (callSignal, callId) =>\n opts.chat.chat(request, { signal: callSignal, idempotencyKey: callId }),\n receipt: costReceiptFromLlm,\n receiptFromError: costReceiptFromLlmError,\n })\n if (!paid.succeeded) throw paid.error\n const response = paid.value\n const llmCall: LlmCallMetadata = {\n usage: response.usage,\n costUsd: response.costUsd,\n model: response.model,\n durationMs: response.durationMs,\n }\n\n const parsed = parseResponse(name, response, opts.responseSchema?.schema, llmCall)\n const rawDims = parsed.dimensions ?? parsed.scores\n if (!rawDims || typeof rawDims !== 'object') {\n throw new JudgeParseError(name, response.content, {\n cause: new Error('response has no `dimensions` object'),\n llmCall,\n })\n }\n\n const sampled: Record<string, number> = {}\n for (const { key } of dimensions) {\n const raw = (rawDims as Record<string, unknown>)[key]\n const value = Number(raw)\n if (raw === undefined || raw === null || !Number.isFinite(value)) {\n throw new JudgeParseError(name, response.content, {\n cause: new Error(\n `dimension '${key}' missing or non-numeric (got ${JSON.stringify(raw)})`,\n ),\n llmCall,\n })\n }\n sampled[key] = value\n }\n\n let scoringMethod: 'sampled' | 'expectation' = 'sampled'\n let distribution: Record<string, Array<{ score: number; probability: number }>> | undefined\n const dims: Record<string, number> = {}\n if (scoring.method === 'expectation') {\n const expectation = expectedDimensionScores({\n tokens: response.logprobs ?? null,\n sampled,\n maxScore: divisor,\n })\n if (expectation.kind === 'unavailable') {\n if (scoring.whenUnavailable === 'fail') {\n throw new Error(\n `llmJudge '${name}': expectation scoring is unavailable — ${expectation.reason}`,\n )\n }\n } else {\n scoringMethod = 'expectation'\n distribution = expectation.distribution\n for (const { key } of dimensions) dims[key] = clamp01(expectation.scores[key]! / divisor)\n }\n }\n if (scoringMethod === 'sampled') {\n for (const { key } of dimensions) dims[key] = clamp01(sampled[key]! / divisor)\n }\n\n const weights =\n opts.weights ?? Object.fromEntries(dimensions.map((d) => [d.key, 1 / dimensions.length]))\n const { composite } = weightedComposite({ dims, weights })\n\n const notes =\n firstString(parsed.notes) ??\n firstString(parsed.rationale) ??\n `${name}: composite ${composite.toFixed(3)} over ${dimensions.length} dimension(s)`\n\n return {\n dimensions: dims,\n composite,\n notes,\n llmCall,\n ...(opts.scoring ? { scoringMethod } : {}),\n ...(distribution ? { distribution } : {}),\n }\n },\n }\n}\n\n/** Alternatives requested per score token. Twenty is the documented ceiling of\n * the OpenAI-compatible `top_logprobs` field, and a grade scale has at most\n * eleven integer candidates, so the window always covers the whole scale. */\nconst EXPECTATION_TOP_LOGPROBS = 20\n\ntype ExpectationResult =\n | {\n kind: 'expectation'\n scores: Record<string, number>\n distribution: Record<string, Array<{ score: number; probability: number }>>\n }\n | { kind: 'unavailable'; reason: string }\n\n/**\n * Expected grade per dimension: locate the token that carried each dimension's\n * integer score, then average the integer grades the model considered at that\n * position, weighted by their probabilities.\n *\n * Unavailable — never silently approximated — when the provider returned no\n * log probabilities, when a dimension's grade is not in the token stream, or\n * when the grade did not land in exactly one token (a two-token `10`, a float).\n */\nfunction expectedDimensionScores(input: {\n tokens: ReadonlyArray<LlmTokenLogprob> | null\n sampled: Record<string, number>\n maxScore: number\n}): ExpectationResult {\n const { tokens, sampled, maxScore } = input\n if (tokens === null) return { kind: 'unavailable', reason: 'the provider returned no logprobs' }\n if (tokens.length === 0) {\n return { kind: 'unavailable', reason: 'the provider returned an empty logprob stream' }\n }\n const offsets: number[] = []\n let text = ''\n for (const token of tokens) {\n offsets.push(text.length)\n text += token.token\n }\n\n const scores: Record<string, number> = {}\n const distribution: Record<string, Array<{ score: number; probability: number }>> = {}\n for (const [key, value] of Object.entries(sampled)) {\n const match = new RegExp(`\"${escapeRegExp(key)}\"\\\\s*:\\\\s*`).exec(text)\n if (!match) {\n return { kind: 'unavailable', reason: `dimension '${key}' is not in the token stream` }\n }\n const scoreOffset = match.index + match[0].length\n let index = -1\n for (let position = 0; position < offsets.length; position++) {\n if (offsets[position]! <= scoreOffset) index = position\n else break\n }\n const token = tokens[index]\n if (!token) {\n return {\n kind: 'unavailable',\n reason: `dimension '${key}' has no token at its score position`,\n }\n }\n if (integerGrade(token.token, maxScore) !== value) {\n return {\n kind: 'unavailable',\n reason: `dimension '${key}' scored ${value}, which is not the whole of its token '${token.token}'`,\n }\n }\n const candidates: Array<{ score: number; probability: number }> = []\n let total = 0\n for (const alternative of token.top.length > 0 ? token.top : [token]) {\n const grade = integerGrade(alternative.token, maxScore)\n if (grade === null) continue\n const probability = Math.exp(alternative.logprob)\n if (!Number.isFinite(probability) || probability <= 0) continue\n candidates.push({ score: grade, probability })\n total += probability\n }\n if (candidates.length === 0 || total <= 0) {\n return {\n kind: 'unavailable',\n reason: `dimension '${key}' has no integer grade in its probability window`,\n }\n }\n let expectation = 0\n for (const candidate of candidates)\n expectation += (candidate.probability / total) * candidate.score\n scores[key] = expectation\n distribution[key] = candidates\n .map((candidate) => ({ score: candidate.score, probability: candidate.probability / total }))\n .sort((left, right) => left.score - right.score)\n }\n return { kind: 'expectation', scores, distribution }\n}\n\n/** The token's integer grade on the judge's scale, or null when the token is\n * not exactly one integer in range. */\nfunction integerGrade(token: string, maxScore: number): number | null {\n const trimmed = token.trim()\n if (!/^\\d+$/.test(trimmed)) return null\n const value = Number(trimmed)\n return Number.isInteger(value) && value >= 0 && value <= maxScore ? value : null\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction normalizeDimensions(\n input: LlmJudgeDimension[] | undefined,\n name: string,\n): JudgeDimension[] {\n const raw = input && input.length > 0 ? input : ['quality']\n const out: JudgeDimension[] = []\n const seen = new Set<string>()\n for (const d of raw) {\n const dim = typeof d === 'string' ? { key: d, description: d } : d\n if (!dim.key.trim()) {\n throw new Error(`llmJudge '${name}': dimension key must be non-empty`)\n }\n if (seen.has(dim.key)) {\n throw new Error(`llmJudge '${name}': duplicate dimension key '${dim.key}'`)\n }\n seen.add(dim.key)\n out.push(dim)\n }\n return out\n}\n\nfunction renderContract(dimensions: JudgeDimension[], scale: 'unit' | 'ten'): string {\n const range = scale === 'ten' ? '0 to 10' : '0.0 to 1.0'\n const lines = dimensions.map((d) => ` - \"${d.key}\": ${d.description} (score ${range})`)\n const example = `{\"dimensions\": {${dimensions\n .map((d) => `\"${d.key}\": <number>`)\n .join(', ')}}, \"notes\": \"<one-line rationale>\"}`\n return [\n 'Score the artifact on EACH of these dimensions:',\n ...lines,\n '',\n `Respond with JSON ONLY, no prose. Every dimension is a number in [${range}]:`,\n example,\n ].join('\\n')\n}\n\nfunction parseResponse(\n name: string,\n response: LlmCallResult,\n schema: z.ZodObject | undefined,\n llmCall: LlmCallMetadata,\n): RawJudgeResponse {\n const { content } = response\n const fail = (cause: unknown) => new JudgeParseError(name, content, { cause, llmCall })\n if (response.finishReason != null && response.finishReason !== 'stop') {\n throw fail(\n new Error(`response did not complete normally (finishReason=${response.finishReason})`),\n )\n }\n if (schema) {\n try {\n return schema.parse(JSON.parse(stripFencedJson(content))) as RawJudgeResponse\n } catch (cause) {\n throw fail(cause)\n }\n }\n const stripped = content.replace(/```json\\n?|\\n?```/g, '').trim()\n const objMatch = stripped.match(/\\{[\\s\\S]*\\}/)\n const payload = objMatch ? objMatch[0] : stripped\n try {\n const parsed = JSON.parse(payload) as RawJudgeResponse\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('parsed value is not an object')\n }\n return parsed\n } catch (cause) {\n throw fail(cause)\n }\n}\n\nfunction firstString(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value : undefined\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,eAAsB,QACpB,MAC+C;CAC/C,OAAO,YAAY,IAAI;AACzB;;ACNA,MAAM,4BAA6C;CACjD,SAAS;CACT,cAAc;CACd,kBAAkB;CAClB,cAAc;CACd,gBAAgB;CAChB,cAAc;CACd,aAAa;CACb,WAAW;CACX,kBAAkB;CAClB,SAAS;CACT,aAAa;AACf;AAEA,SAAgB,kBAAkB,OAAiB,UAAoC,CAAC,GAAW;CACjG,MAAM,IAAI;EAAE,GAAG;EAA2B,GAAG;CAAQ;CACrD,OAAQ,OAAO,KAAK,yBAAyB,CAAC,CAC3C,KACE,QACC,EAAE,QACD,QAAQ,aAAa,QAAQ,gBAC1B,KAAK,IAAI,GAAG,aAAa,MAAM,IAAI,KAAK,QAAQ,gBAAgB,KAAK,EAAE,IACvE,QAAQ,MAAM,IAAI,EAC1B,CAAC,CACA,QAAQ,KAAK,SAAS,MAAM,IAAI;AACrC;AAEA,SAAgB,QAAQ,OAAuB;CAC7C,OAAO,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,aAAa,KAAK,CAAC,CAAC;AACrD;AAEA,SAAS,aAAa,OAAuB;CAC3C,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAC1C;;ACPA,MAAM,iBACJ;AAEF,MAAM,kBAAkB;;;;;;;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AChE,MAAM,WAAW,SAAS,MAAM,aAAa;CAC7C,MAAM,UAAU,WAAW,SAAS,KAAK;CACzC,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,OAAO;EACjC,IAAI,OAAO,WAAW,YAAY,WAAW,MAC3C,MAAM,IAAI,MAAM,+BAA+B;EAEjD,OAAO;CACT,SAAS,OAAO;EACd,MAAM,KAAK,KAAK;CAClB;AACF;AAEA,SAAS,YAAY,OAAoC;CACvD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,IAAI,QAAQ,KAAA;AAC7D"}
@@ -1,5 +1,5 @@
1
1
  import { u as CostProvenance } from "./cost-ledger-CSP-OfFe.js";
2
- import { C as JudgeDimension, w as JudgeScore } from "./types-D5XtEH9Q.js";
2
+ import { C as JudgeDimension, w as JudgeScore } from "./types-BtWzceBY.js";
3
3
  import { o as MatrixResult } from "./index-DsgqP-Hg.js";
4
4
  import { AgentProfile } from "@tangle-network/agent-interface";
5
5
  interface MultishotMessage {
@@ -384,4 +384,4 @@ interface RunMultishotMatrixResult {
384
384
  }
385
385
  declare function runMultishotMatrix<TPersona extends MultishotPersona>(opts: RunMultishotMatrixOptions<TPersona>): Promise<RunMultishotMatrixResult>;
386
386
  export { MultishotTransportResponse as A, MultishotPersona as C, MultishotToolExecutor as D, MultishotToolDefinition as E, assertMultishotShotResult as M, MultishotTransport as O, MultishotMessage as S, MultishotShape as T, renderJsonFooter as _, MultishotCellOutput as a, MultishotDriverEmptyError as b, RunMultishotMatrixResult as c, MultishotShot as d, RunMultishotOptions as f, renderDimensions as g, MultishotJudgeConfig as h, ConversationJudgeInput as i, MultishotTransportToolCall as j, MultishotTransportRequest as k, computeCellComposite as l, JudgeRunResult as m, CellCompositeInput as n, MultishotJudges as o, runMultishot as p, CellCompositeScore as r, RunMultishotMatrixOptions as s, ArtifactJudgeInput as t, runMultishotMatrix as u, runJudge as v, MultishotResult as w, MultishotFatalToolError as x, MultishotArtifact as y };
387
- //# sourceMappingURL=matrix-BDl7hoBr.d.ts.map
387
+ //# sourceMappingURL=matrix-CAeyP9m-.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"matrix-BDl7hoBr.d.ts","names":[],"sources":["../src/multishot/types.ts","../src/multishot/judges.ts","../src/multishot/multishot.ts","../src/multishot/matrix.ts"],"mappings":";;;;UAIiB;EACf;EACA;EACA;EACA,YAAY;IAAQ;IAAY;IAAc,MAAM;;;UAGrC;EACf;EACA;EACA;IAAc;IAAc,MAAM;;EAClC;;UAGe;EACf,YAAY;EACZ,WAAW;EACX;EACA;;;EAGA;;;;;;;;EAQA,iBAAiB;;UAGF;EACf;EACA;IACE;IACA;IACA,YAAY;;;;;;UAOC;EACf;EACA,UAAU,MAAM;EAChB,QAAQ;EACR;EACA;;;;EAIA;EACA,SAAS;;UAGM;EACf;EACA;EACA;IAAY;IAAc;;;UAGX;EACf;IAAW;IAAyB,aAAa;;EACjD;IAAU;IAAwB;;;;EAGlC;;;;EAIA;;;;;;;;KASU,sBACV,KAAK,8BACF,QAAQ;KAED,yBACV,MAAM,yBACN;;EAEE,WAAW;EACX,SAAS;MAER;EAAU;EAAiB;;UAEf;;EAEf;;GAEC;;;;;;;;UASc,eAAe,iBAAiB;;EAE/C,eAAe,SAAS;;;EAGxB,2BAA2B,SAAS;;cAGzB,kCAAkC;WACjB;EAAA,YAAA;;cAMjB,gCAAgC;EAC/B,YAAA;;;;;;;;;;;;;;;;;;;iBAgCE,0BAA0B,yBAAyB,SAAS;UC1I3D,qBAAqB;;EAEpC;;;EAGA,WAAW;;EAEX;;EAEA,YAAY;;EAEZ;;;EAGA,cAAc,OAAO;;EAErB;;UAGe;;EAEf,OAAO;;EAEP,MAAM;;iBAGc,SAAS,QAC7B,OAAO,qBAAqB,SAC5B,OAAO,SACN,QAAQ;;;iBAsIK,iBAAiB,eAAe;;iBAKhC,iBAAiB,eAAe;UCvK/B,oBAAoB,iBAAiB;EACpD,SAAS;EACT,SAAS;;;EAGT,QAAQ,eAAe;;EAEvB,QAAQ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
+ {"version":3,"file":"matrix-CAeyP9m-.d.ts","names":[],"sources":["../src/multishot/types.ts","../src/multishot/judges.ts","../src/multishot/multishot.ts","../src/multishot/matrix.ts"],"mappings":";;;;UAIiB;EACf;EACA;EACA;EACA,YAAY;IAAQ;IAAY;IAAc,MAAM;;;UAGrC;EACf;EACA;EACA;IAAc;IAAc,MAAM;;EAClC;;UAGe;EACf,YAAY;EACZ,WAAW;EACX;EACA;;;EAGA;;;;;;;;EAQA,iBAAiB;;UAGF;EACf;EACA;IACE;IACA;IACA,YAAY;;;;;;UAOC;EACf;EACA,UAAU,MAAM;EAChB,QAAQ;EACR;EACA;;;;EAIA;EACA,SAAS;;UAGM;EACf;EACA;EACA;IAAY;IAAc;;;UAGX;EACf;IAAW;IAAyB,aAAa;;EACjD;IAAU;IAAwB;;;;EAGlC;;;;EAIA;;;;;;;;KASU,sBACV,KAAK,8BACF,QAAQ;KAED,yBACV,MAAM,yBACN;;EAEE,WAAW;EACX,SAAS;MAER;EAAU;EAAiB;;UAEf;;EAEf;;GAEC;;;;;;;;UASc,eAAe,iBAAiB;;EAE/C,eAAe,SAAS;;;EAGxB,2BAA2B,SAAS;;cAGzB,kCAAkC;WACjB;EAAA,YAAA;;cAMjB,gCAAgC;EAC/B,YAAA;;;;;;;;;;;;;;;;;;;iBAgCE,0BAA0B,yBAAyB,SAAS;UC1I3D,qBAAqB;;EAEpC;;;EAGA,WAAW;;EAEX;;EAEA,YAAY;;EAEZ;;;EAGA,cAAc,OAAO;;EAErB;;UAGe;;EAEf,OAAO;;EAEP,MAAM;;iBAGc,SAAS,QAC7B,OAAO,qBAAqB,SAC5B,OAAO,SACN,QAAQ;;;iBAsIK,iBAAiB,eAAe;;iBAKhC,iBAAiB,eAAe;UCvK/B,oBAAoB,iBAAiB;EACpD,SAAS;EACT,SAAS;;;EAGT,QAAQ,eAAe;;EAEvB,QAAQ;;EAER,gBAAgB,eAAe;;;;EAI/B,mBAAmB;EACnB;EACA;EACA;;EAEA;;EAE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ry32 } from "../random-DrzcgC7F.js";
6
6
  import { $ as selfPreference, H as clusteredAssociation, Q as positionalBias, V as associationEstimate, X as calibrateJudgeContinuous, Y as calibrateJudge, Z as continuousAgreement, b as benjaminiHochberg, et as verbosityBias, n as sampleMedian } from "../statistics-AKnVFnK-.js";
7
7
  import { s as runMetricExtractor } from "../query-Dhjkwqyx.js";
8
- import { n as callLlmJson } from "../llm-client-Dk8lBnMh.js";
8
+ import { n as callLlmJson } from "../llm-client-D4B1qR_1.js";
9
9
  import { a as reduceOutcomeMetric, i as hasVariation, n as correlationSummary, o as reduceOutcomeObservation, r as groupOutcomesByRun, s as validateObservationOptions, t as assertUniqueObservationIds } from "../outcome-observations-DEh8_V_P.js";
10
10
  import { a as rankedProbabilityScore, i as multiclassBrierScore, n as calibrationCurve, r as calibrationFromPairs, t as brierScore } from "../calibration-Dz8mQb5P.js";
11
- import { a as judgeGateDecision, c as snapshotFromJudgeAgreement, d as judgeSentinelReport, f as snapshotFromAgreement, g as withJudgeRetry, h as validateSentinelSnapshot, i as assertJudgeMayGate, l as evalHealthStamp, m as snapshotFromSentinelSet, n as JudgeGateRefusedError, o as measureJudgeAgreement, p as snapshotFromCalibration, r as addCalibrationVerdicts, s as registerCalibrationSet, t as DEFAULT_JUDGE_GATE_POLICY, u as fileSentinelStore } from "../judge-gate-CpD3wmcf.js";
11
+ import { a as judgeGateDecision, c as snapshotFromJudgeAgreement, d as judgeSentinelReport, f as snapshotFromAgreement, g as withJudgeRetry, h as validateSentinelSnapshot, i as assertJudgeMayGate, l as evalHealthStamp, m as snapshotFromSentinelSet, n as JudgeGateRefusedError, o as measureJudgeAgreement, p as snapshotFromCalibration, r as addCalibrationVerdicts, s as registerCalibrationSet, t as DEFAULT_JUDGE_GATE_POLICY, u as fileSentinelStore } from "../judge-gate-WgYqQ9LA.js";
12
12
  import { t as computeInterval } from "../interval-Bd2f4CRT.js";
13
13
  import { t as clusterBootstrapMean } from "../cluster-bootstrap-CTC8Dd30.js";
14
14
  import { t as rubricPredictiveValidity } from "../rubric-predictive-validity-BXJ92Jp_.js";
@@ -0,0 +1,9 @@
1
+ import "./cost-ledger-ni6f77QJ.js";
2
+ // src/metrics.ts
3
+ /** Estimate token count from string length (chars / 4 approximation) */
4
+ function estimateTokens(text) {
5
+ return Math.ceil(text.length / 4);
6
+ }
7
+ export { estimateTokens as t };
8
+
9
+ //# sourceMappingURL=metrics-C6pXdupw.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics-C6pXdupw.js","names":[],"sources":["../src/metrics.ts"],"sourcesContent":["export {\n estimateCost,\n isModelPriced,\n MODEL_PRICING,\n resolveModelPricing,\n type TokenPrice,\n} from './cost-ledger/pricing'\n\n/** Estimate token count from string length (chars / 4 approximation) */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4)\n}\n"],"mappings":";;;AASA,SAAgB,eAAe,MAAsB;CACnD,OAAO,KAAK,KAAK,KAAK,SAAS,CAAC;AAClC"}
@@ -1,4 +1,4 @@
1
- import { C as MultishotPersona, E as MultishotToolDefinition, c as RunMultishotMatrixResult, f as RunMultishotOptions, k as MultishotTransportRequest, s as RunMultishotMatrixOptions, w as MultishotResult } from "../../matrix-BDl7hoBr.js";
1
+ import { C as MultishotPersona, E as MultishotToolDefinition, c as RunMultishotMatrixResult, f as RunMultishotOptions, k as MultishotTransportRequest, s as RunMultishotMatrixOptions, w as MultishotResult } from "../../matrix-CAeyP9m-.js";
2
2
  interface CompareOptions {
3
3
  /** Stop after this many mismatches. A structural divergence high in the
4
4
  * tree would otherwise report every leaf below it. */