@tangle-network/agent-eval 0.140.1 → 0.141.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/dist/analyst/index.d.ts +74 -6
  3. package/dist/analyst/index.d.ts.map +1 -1
  4. package/dist/analyst/index.js +6 -6
  5. package/dist/{benchmark-command-Bo_hkhQf.js → benchmark-command-D8xXNVVh.js} +2239 -1820
  6. package/dist/benchmark-command-D8xXNVVh.js.map +1 -0
  7. package/dist/benchmarks/index.js +1 -1
  8. package/dist/{benchmarks-HwoBE32G.js → benchmarks-Ce8GdJbc.js} +4 -4
  9. package/dist/{benchmarks-HwoBE32G.js.map → benchmarks-Ce8GdJbc.js.map} +1 -1
  10. package/dist/campaign/index.js +3 -3
  11. package/dist/{campaign-BzjYNYVZ.js → campaign-COFTVy3Q.js} +3 -3
  12. package/dist/{campaign-BzjYNYVZ.js.map → campaign-COFTVy3Q.js.map} +1 -1
  13. package/dist/cli.js +1 -1
  14. package/dist/contract/index.d.ts.map +1 -1
  15. package/dist/contract/index.js +56 -13
  16. package/dist/contract/index.js.map +1 -1
  17. package/dist/{default-registry-BOiBXNFh.js → default-registry-BupFSXSN.js} +108 -20
  18. package/dist/default-registry-BupFSXSN.js.map +1 -0
  19. package/dist/default-registry-Ci7wAAR8.d.ts.map +1 -1
  20. package/dist/{dspy-rlm-engine-Bkak4nzo.js → dspy-rlm-engine-Bw8Zz9CX.js} +7 -4
  21. package/dist/{dspy-rlm-engine-Bkak4nzo.js.map → dspy-rlm-engine-Bw8Zz9CX.js.map} +1 -1
  22. package/dist/{extract-usage-C5vMw-0R.js → extract-usage-7l1Xq5ti.js} +2 -2
  23. package/dist/{extract-usage-C5vMw-0R.js.map → extract-usage-7l1Xq5ti.js.map} +1 -1
  24. package/dist/index.d.ts +68 -31
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +122 -46
  27. package/dist/index.js.map +1 -1
  28. package/dist/{kind-factory-DB7nIs35.js → kind-factory-Bvwe3pup.js} +11 -1
  29. package/dist/kind-factory-Bvwe3pup.js.map +1 -0
  30. package/dist/multishot/index.d.ts +29 -6
  31. package/dist/multishot/index.d.ts.map +1 -1
  32. package/dist/multishot/index.js +53 -3
  33. package/dist/multishot/index.js.map +1 -1
  34. package/dist/openapi.json +1 -1
  35. package/dist/replay-BqTgoioO.d.ts.map +1 -1
  36. package/dist/{replay-k2MsOmv5.js → replay-DjUfTrHD.js} +40 -48
  37. package/dist/replay-DjUfTrHD.js.map +1 -0
  38. package/dist/{single-run-lock-CiQThJxB.js → single-run-lock-BcvPQY57.js} +65 -15
  39. package/dist/single-run-lock-BcvPQY57.js.map +1 -0
  40. package/dist/{skill-usage-CVVnoIx-.d.ts → skill-usage-CNZTk_LT.d.ts} +8 -4
  41. package/dist/{skill-usage-CVVnoIx-.d.ts.map → skill-usage-CNZTk_LT.d.ts.map} +1 -1
  42. package/dist/{skillopt-optimization-method-CSBQ8Qma.js → skillopt-optimization-method-DV6c4ooy.js} +2 -2
  43. package/dist/{skillopt-optimization-method-CSBQ8Qma.js.map → skillopt-optimization-method-DV6c4ooy.js.map} +1 -1
  44. package/dist/{store-otlp-vRByAR6h.js → store-otlp-D4I90_vR.js} +2 -2
  45. package/dist/{store-otlp-vRByAR6h.js.map → store-otlp-D4I90_vR.js.map} +1 -1
  46. package/dist/traces.js +4 -4
  47. package/docs/adapters-observability.md +35 -21
  48. package/docs/concepts.md +1 -0
  49. package/docs/distributed-driver.md +7 -3
  50. package/docs/feature-guide.md +1 -0
  51. package/docs/insight-report.md +1 -1
  52. package/docs/trace-analysis.md +11 -0
  53. package/docs/wire-protocol.md +70 -2
  54. package/package.json +5 -3
  55. package/dist/benchmark-command-Bo_hkhQf.js.map +0 -1
  56. package/dist/default-registry-BOiBXNFh.js.map +0 -1
  57. package/dist/kind-factory-DB7nIs35.js.map +0 -1
  58. package/dist/replay-k2MsOmv5.js.map +0 -1
  59. package/dist/single-run-lock-CiQThJxB.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"replay-k2MsOmv5.js","names":["toAttributes","padSpanId","msToNs","padTraceId","padSpanId"],"sources":["../src/trace-analyst/prompts.ts","../src/trace-analyst/analyst.ts","../src/trace-analyst/hook.ts","../src/trace-analyst/insights.ts","../src/trace/otlp-flat.ts","../src/trace-analyst/otlp-flatten.ts","../src/trace-analyst/otlp-to-run-records.ts","../src/trace-analyst/store-tool-spans.ts","../src/trace/capture-fetch.ts","../src/trace/otel.ts","../src/trace/otel-bridge.ts","../src/trace/otel-export.ts","../src/trace/store-to-otlp.ts","../src/replay.ts"],"sourcesContent":["/** General policy for recursive, evidence-backed trace analysis. */\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION = `Answer the question by inspecting the OTLP trace dataset with the available tools.\n\n1. Call getDatasetOverview first. Use its real trace ids and dataset size to plan the investigation.\n2. Narrow with queryTraces and countTraces before scanning large payloads.\n3. For a small trace, use viewTrace. For a large trace, use searchTrace and then viewSpans or searchSpan.\n4. Never invent a trace id, span id, tool result, error, frequency, or final outcome.\n5. When a search reports has_more, refine the query before drawing a conclusion.\n6. Use llm_query only over evidence already loaded. A recursive query cannot inspect traces itself.\n7. Cite exact evidence URIs returned by the tools. Include a short exact excerpt when it supports the claim.\n8. Return no finding when the available evidence cannot support one.\n\nThe prose answer must directly answer the question and state important uncertainty.\nThe findings array contains only actionable or decision-relevant claims supported by inspected evidence.`\n\nexport const TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION = 'trace-analyst-research-v1-2026-07-30'\n","import { randomUUID } from 'node:crypto'\nimport type {\n TraceAnalysisEngine,\n TraceAnalysisEngineResult,\n TraceAnalystLimits,\n} from '../analyst/engine'\nimport { runTraceAnalyst } from '../analyst/kind-factory'\nimport type { TraceToolGroupName } from '../analyst/tool-groups'\nimport type { AnalystFinding, AnalystUsageReceipt } from '../analyst/types'\nimport type { CostLedgerHandle } from '../cost-ledger'\nimport { TRACE_ANALYST_ACTOR_DESCRIPTION, TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION } from './prompts'\nimport type { TraceAnalysisStore } from './store'\nimport { OtlpFileTraceStore } from './store-otlp'\n\nexport interface AnalyzeTracesInput {\n question: string\n id?: string\n description?: string\n area?: string\n}\n\nexport type AnalyzeTracesResult = TraceAnalysisEngineResult\n\nexport interface AnalyzeTracesOptions {\n /** OTLP JSONL path or a caller-owned store. */\n source: string | TraceAnalysisStore\n /** Recursive research engine. */\n engine: TraceAnalysisEngine\n /** Override the general trace-research policy. */\n instructions?: string\n /** Smallest tool set that can answer the question. Default: all. */\n toolGroup?: TraceToolGroupName\n limits?: Partial<TraceAnalystLimits>\n runId?: string\n budgetUsd?: number\n costLedger?: CostLedgerHandle\n costPhase?: string\n priorFindings?: readonly AnalystFinding[]\n upstreamFindings?: readonly AnalystFinding[]\n recordUsage?: (receipt: AnalystUsageReceipt) => void\n tags?: Record<string, string>\n log?: (message: string, fields?: Record<string, unknown>) => void\n signal?: AbortSignal\n}\n\n/**\n * Answer one question by recursively inspecting a trace store.\n *\n * The returned answer, cited findings, engine steps, call counts, and runtime\n * identity are one audit record. A direct one-shot model call is not used.\n */\nexport async function analyzeTraces(\n input: AnalyzeTracesInput,\n options: AnalyzeTracesOptions,\n): Promise<AnalyzeTracesResult> {\n if (typeof input.question !== 'string' || !input.question.trim()) {\n throw new TypeError('analyzeTraces: input.question must be a non-empty string')\n }\n const id = input.id?.trim() || 'trace-analysis'\n const store =\n typeof options.source === 'string'\n ? new OtlpFileTraceStore({ path: options.source })\n : options.source\n if (store instanceof OtlpFileTraceStore) {\n await store.ensureIndexed(options.signal ? { signal: options.signal } : undefined)\n }\n\n return runTraceAnalyst({\n definition: {\n id,\n description:\n input.description?.trim() ||\n 'Answers a caller-defined question by recursively inspecting trace evidence.',\n area: input.area?.trim() || 'trace-analysis',\n version: TRACE_ANALYST_ACTOR_DESCRIPTION_VERSION,\n question: input.question,\n instructions: options.instructions ?? TRACE_ANALYST_ACTOR_DESCRIPTION,\n toolGroup: options.toolGroup ?? 'all',\n limits: options.limits,\n },\n engine: options.engine,\n store,\n context: {\n runId: options.runId ?? id,\n correlationId: randomUUID(),\n budgetUsd: options.budgetUsd,\n costLedger: options.costLedger,\n costPhase: options.costPhase ?? 'trace-analysis',\n priorFindings: options.priorFindings,\n upstreamFindings: options.upstreamFindings,\n recordUsage: options.recordUsage,\n tags: options.tags,\n log: options.log,\n signal: options.signal,\n },\n })\n}\n","/**\n * Trace-analyst auto-execution hook.\n *\n * Wires `analyzeTraces` into a `TraceEmitter`'s `onRunComplete` so a\n * direct matrix run produces an analysis artifact without an out-of-band\n * step. Designed for the case where the consumer reports \"the analyst\n * never ran\" — the cause is almost always orchestration, not the analyst.\n *\n * Usage:\n *\n * const emitter = new TraceEmitter(store, {\n * onRunComplete: [traceAnalystOnRunComplete({ analyze: opts, save })],\n * })\n *\n * Hooks are best-effort by default — they never crash the underlying run.\n * The caller decides whether to gate the run on the analysis result via\n * the `gateOn` callback.\n */\n\nimport type { RunCompleteHook, RunCompleteHookContext } from '../trace/emitter'\nimport { type AnalyzeTracesOptions, type AnalyzeTracesResult, analyzeTraces } from './analyst'\n\nexport interface TraceAnalystHookOptions {\n /**\n * Options forwarded to `analyzeTraces`. The hook supplies the question\n * if you don't pass one — defaulting to a launch-grade prompt that asks\n * for failure modes, surprising findings, and a recommendation.\n */\n analyze: Omit<AnalyzeTracesOptions, 'source'> & { source?: AnalyzeTracesOptions['source'] }\n /**\n * Override the question. The default is intentionally generic:\n * \"Summarise what happened in this run, surface any failure modes,\n * surprising findings, or evidence the verdict is wrong.\"\n */\n question?: string\n /**\n * Persist the result. The hook calls this with the analysis output and\n * the run context. Common implementations write to a TraceAnalysisStore\n * or append to a per-run JSONL.\n */\n save?: (result: AnalyzeTracesResult, ctx: RunCompleteHookContext) => Promise<void>\n /**\n * Predicate gating execution per run. Default: every completed run.\n * Use to skip aborted runs, debug runs, or runs without LLM activity.\n */\n shouldRun?: (ctx: RunCompleteHookContext) => boolean\n /**\n * Optional gate: if set and returns false, the hook records the failure\n * as a log event on the run instead of staying quiet. The caller can\n * then trigger downstream alerts off `analyst_gate_failed` log events.\n */\n gateOn?: (result: AnalyzeTracesResult, ctx: RunCompleteHookContext) => boolean\n}\n\nconst DEFAULT_QUESTION =\n \"Summarise what happened in this run. Surface any failure modes, surprising findings, or evidence that the run's verdict is wrong.\"\n\nexport function traceAnalystOnRunComplete(opts: TraceAnalystHookOptions): RunCompleteHook {\n return async (ctx: RunCompleteHookContext) => {\n if (opts.shouldRun && !opts.shouldRun(ctx)) return\n const source = opts.analyze.source\n if (source === undefined) {\n // The analyst needs a source. If the caller didn't supply one we don't\n // run — but we do leave a breadcrumb so the absence is visible.\n await ctx.store.appendEvent({\n eventId: `analyst-skip-${ctx.runId}`,\n runId: ctx.runId,\n kind: 'log',\n timestamp: Date.now(),\n payload: { source: 'trace_analyst_hook', reason: 'no source configured' },\n })\n return\n }\n const result = await analyzeTraces({ question: opts.question ?? DEFAULT_QUESTION }, {\n ...opts.analyze,\n source,\n } as AnalyzeTracesOptions)\n if (opts.save) await opts.save(result, ctx)\n if (opts.gateOn && !opts.gateOn(result, ctx)) {\n await ctx.store.appendEvent({\n eventId: `analyst-gate-${ctx.runId}`,\n runId: ctx.runId,\n kind: 'log',\n timestamp: Date.now(),\n payload: {\n source: 'trace_analyst_hook',\n reason: 'analyst_gate_failed',\n findings: result.findings,\n },\n })\n }\n }\n}\n","export interface TraceInsightTask {\n id: string\n name: string\n prompt?: string\n difficulty?: string\n tags?: string[]\n outcome?: string\n score?: number\n gaps?: string[]\n}\n\nexport interface TraceInsightSuite {\n name: string\n collectionId?: string\n tasks: TraceInsightTask[]\n}\n\nexport interface TraceInsightFinding {\n kind: string\n severity?: string\n taskIds: string[]\n evidence?: string\n proposedFixClass?: string\n}\n\nexport interface TraceInsightQuestion {\n id: string\n question: string\n why: string\n}\n\nexport interface TraceInsightPanelRole {\n id: string\n name: string\n responsibility: string\n}\n\nexport interface TraceInsightPromptInput {\n suite: TraceInsightSuite\n findings?: TraceInsightFinding[]\n agent?: Record<string, unknown>\n totals?: Record<string, unknown>\n maxRepresentativeTraces?: number\n}\n\nexport interface TraceInsightContext {\n suite: TraceInsightSuite\n scope: string\n keywords: string[]\n questions: TraceInsightQuestion[]\n panel: TraceInsightPanelRole[]\n findings: TraceInsightFinding[]\n agent: Record<string, unknown> | null\n totals: Record<string, unknown> | null\n}\n\nexport interface TraceInsightQualityGate {\n id: string\n label: string\n passed: boolean\n severity: 'critical' | 'high' | 'medium' | 'low'\n detail: string\n}\n\nexport interface TraceInsightReadiness {\n score: number\n grade: 'external-ready' | 'internal-review' | 'raw-analysis'\n gates: TraceInsightQualityGate[]\n}\n\nconst DOMAIN_STOP_WORDS = new Set([\n 'and',\n 'advanced',\n 'app',\n 'build',\n 'create',\n 'easy',\n 'expert',\n 'extreme',\n 'for',\n 'from',\n 'hard',\n 'implementation',\n 'integrate',\n 'medium',\n 'project',\n 'task',\n 'the',\n 'this',\n 'with',\n 'workflow',\n])\n\nexport function tokenizeDomainWords(value: string): string[] {\n return [...value.matchAll(/[A-Za-z][A-Za-z0-9.+#-]{2,}/g)]\n .map((match) => match[0].toLowerCase())\n .filter((word) => !DOMAIN_STOP_WORDS.has(word))\n}\n\nexport function inferDomainKeywords(suite: TraceInsightSuite): string[] {\n const suiteWords = new Set(tokenizeDomainWords(`${suite.name} ${suite.collectionId ?? ''}`))\n const source = [\n suite.name,\n suite.collectionId ?? '',\n ...suite.tasks.flatMap((task) => [\n task.id,\n task.name,\n task.prompt ?? '',\n task.difficulty ?? '',\n ...(task.tags ?? []),\n ...(task.gaps ?? []),\n ]),\n ].join(' ')\n const counts = new Map<string, number>()\n for (const word of tokenizeDomainWords(source)) counts.set(word, (counts.get(word) ?? 0) + 1)\n return [...counts.entries()]\n .filter(([word, count]) => count >= 2 || suiteWords.has(word))\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([word]) => word)\n .slice(0, 18)\n}\n\nexport function domainEvidencePattern(keywords: string[]): RegExp {\n const escaped = keywords\n .filter((keyword) => keyword.length >= 3)\n .map((keyword) => keyword.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n return escaped.length > 0\n ? new RegExp(`(?<![A-Za-z0-9])(?:${escaped.join('|')})(?![A-Za-z0-9])`, 'i')\n : /(?<![A-Za-z0-9])(?:sdk|api|css|dns|xml|provider|client|service|integration|webhook|transaction|auth|oauth|graphql|rest)(?![A-Za-z0-9])/i\n}\n\nexport function describeTraceInsightScope(suite: TraceInsightSuite): string {\n const taskLabel =\n suite.tasks.length === 1\n ? '1 implementation task'\n : `${suite.tasks.length} implementation tasks`\n const tags = new Map<string, number>()\n for (const task of suite.tasks) {\n for (const tag of task.tags ?? []) tags.set(tag, (tags.get(tag) ?? 0) + 1)\n }\n const topTags = [...tags.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .slice(0, 8)\n .map(([tag]) => tag)\n if (topTags.length > 0) return `${taskLabel} across ${topTags.join(', ')}.`\n const difficulties = [\n ...new Set(\n suite.tasks.map((task) => task.difficulty).filter((value): value is string => Boolean(value)),\n ),\n ].join(', ')\n return `${taskLabel} across ${difficulties || 'the selected benchmark scope'}.`\n}\n\nexport function planTraceInsightQuestions(input: TraceInsightPromptInput): TraceInsightQuestion[] {\n const hasFailures = input.suite.tasks.some((task) => task.outcome && task.outcome !== 'satisfied')\n const hasMultipleShots = input.suite.tasks.some((task) =>\n (task.gaps ?? []).some((gap) => /shot|review|retry|continue/i.test(gap)),\n )\n const questions: TraceInsightQuestion[] = [\n {\n id: 'execution-path',\n question: 'What did the worker actually do before the first meaningful implementation edit?',\n why: 'Separates grounded execution from polished but shallow output.',\n },\n {\n id: 'research-grounding',\n question:\n 'Did the worker inspect docs, source, examples, or package references before committing to an implementation path?',\n why: 'Identifies whether failures came from weak retrieval, weak examples, or premature coding.',\n },\n {\n id: 'domain-proof',\n question:\n 'Which tasks produced executable domain proof versus UI copy, placeholders, or inferred behavior?',\n why: 'Keeps product-quality claims tied to concrete evidence.',\n },\n {\n id: 'root-cause',\n question:\n 'For each major failure cluster, is the likely root cause prompt/scaffold, docs/examples, SDK/API ergonomics, evaluator, runtime, or model behavior?',\n why: 'Turns trace observations into actionable ownership.',\n },\n {\n id: 'evidence-quality',\n question:\n 'Which external-facing claims are directly supported by trace ids, span ids, verifier findings, reviewer notes, or generated code?',\n why: 'Prevents unsupported customer-report conclusions.',\n },\n ]\n if (hasMultipleShots) {\n questions.push({\n id: 'reviewer-lift',\n question: 'Where did reviewer feedback improve score, stall, or regress across shots?',\n why: 'Shows whether the driver loop is learning or merely repeating work.',\n })\n }\n if (hasFailures) {\n questions.push({\n id: 'optimization-targets',\n question:\n 'Which prompt, evaluator, scaffold, or workflow changes should feed the next GEPA/autoresearch optimization run?',\n why: 'Connects benchmark evidence to the optimization loop.',\n })\n }\n return questions\n}\n\nexport function buildTraceInsightContext(input: TraceInsightPromptInput): TraceInsightContext {\n return {\n suite: input.suite,\n scope: describeTraceInsightScope(input.suite),\n keywords: inferDomainKeywords(input.suite),\n questions: planTraceInsightQuestions(input),\n panel: defaultTraceInsightPanel(),\n findings: input.findings ?? [],\n agent: input.agent ?? null,\n totals: input.totals ?? null,\n }\n}\n\nexport function scoreTraceInsightReadiness(context: TraceInsightContext): TraceInsightReadiness {\n const failedTasks = context.suite.tasks.filter(\n (task) => task.outcome && task.outcome !== 'satisfied',\n )\n const findingTaskIds = new Set(context.findings.flatMap((finding) => finding.taskIds))\n const failedTasksWithFindings = failedTasks.filter((task) => findingTaskIds.has(task.id))\n const tasksWithGaps = context.suite.tasks.filter((task) => (task.gaps ?? []).length > 0)\n const gates: TraceInsightQualityGate[] = [\n {\n id: 'domain-context',\n label: 'Domain context inferred',\n passed: context.keywords.length > 0,\n severity: 'high',\n detail:\n context.keywords.length > 0\n ? `${context.keywords.length} domain terms inferred: ${context.keywords.slice(0, 8).join(', ')}`\n : 'No domain terms were inferred from suite, tasks, prompts, tags, or gaps.',\n },\n {\n id: 'panel-coverage',\n label: 'Analyst panel planned',\n passed: context.panel.length >= 4 && context.questions.length >= 5,\n severity: 'high',\n detail: `${context.panel.length} panel roles and ${context.questions.length} investigation questions planned.`,\n },\n {\n id: 'failure-coverage',\n label: 'Failures mapped to findings',\n passed:\n failedTasks.length === 0 || failedTasksWithFindings.length / failedTasks.length >= 0.5,\n severity: 'critical',\n detail:\n failedTasks.length === 0\n ? 'No failed tasks in suite.'\n : `${failedTasksWithFindings.length}/${failedTasks.length} failed tasks appear in finding clusters.`,\n },\n {\n id: 'gap-evidence',\n label: 'Task gaps captured',\n passed: failedTasks.length === 0 || tasksWithGaps.length / failedTasks.length >= 0.5,\n severity: 'medium',\n detail: `${tasksWithGaps.length} tasks include explicit evaluator or analyst gaps.`,\n },\n ]\n const penalty = gates.reduce((sum, gate) => {\n if (gate.passed) return sum\n if (gate.severity === 'critical') return sum + 35\n if (gate.severity === 'high') return sum + 20\n if (gate.severity === 'medium') return sum + 10\n return sum + 5\n }, 0)\n const score = Math.max(0, Math.min(1, 1 - penalty / 100))\n return {\n score,\n grade: score >= 0.9 ? 'external-ready' : score >= 0.7 ? 'internal-review' : 'raw-analysis',\n gates,\n }\n}\n\nexport function defaultTraceInsightPanel(): TraceInsightPanelRole[] {\n return [\n {\n id: 'trace-forensics',\n name: 'Trace Forensics',\n responsibility:\n 'Reconstruct what the worker did in order, including research, edits, reviewer interventions, verifier feedback, and stop reason.',\n },\n {\n id: 'root-cause',\n name: 'Root Cause',\n responsibility:\n 'Map failures to prompt/scaffold, docs/examples, SDK/API/product ergonomics, evaluator, runtime, or model behavior.',\n },\n {\n id: 'optimization',\n name: 'Optimization',\n responsibility:\n 'Identify prompt, reviewer, evaluator, scaffold, and GEPA/autoresearch changes that should be tested next.',\n },\n {\n id: 'external-evidence',\n name: 'External Evidence',\n responsibility:\n 'Separate customer-safe claims from internal harness findings and reject conclusions without task, trace, span, code, reviewer, or verifier evidence.',\n },\n ]\n}\n\nexport function buildTraceInsightPrompt(input: TraceInsightPromptInput): string {\n const context = buildTraceInsightContext(input)\n const maxRepresentativeTraces = input.maxRepresentativeTraces ?? 6\n return `Analyze this benchmark run and produce evidence-backed trace intelligence.\n\nAudience:\n- internal AI/product leadership\n- possible customer-facing report for ${input.suite.name}\n\nInvestigation plan:\n${context.questions.map((item, index) => `${index + 1}. ${item.question} (${item.why})`).join('\\n')}\n\nAnalyst panel:\n${context.panel.map((role) => `- ${role.name}: ${role.responsibility}`).join('\\n')}\n\nIf the task branches are independent, use subagents for the panel roles above and aggregate their findings. Do not run a panel role unless its answer will change the final report.\n\nRequired output:\n1. Executive verdict: what this run proves and does not prove.\n2. The investigation questions you answered and the evidence used.\n3. Failure taxonomy: agent prompting, evaluator/harness, docs/examples, SDK/API/product integration, infra.\n4. Evidence-backed examples with trace ids/task ids and concrete verifier findings.\n5. Highest-ROI fixes for the benchmark harness, prompt/GEPA optimization, and customer-facing product/docs surface.\n6. What is safe for an external report versus what must stay internal.\n7. One rerun plan that would validate lift after optimization.\n\nBudget:\n- Inspect the dataset overview, the failure summary, and at most ${maxRepresentativeTraces} representative traces.\n- Prefer traces named in the failure summary over broad exploration.\n- Do not do exhaustive trace sweeps.\n- Return the final report as soon as the taxonomy and examples are supported.\n\nRun summary:\n${JSON.stringify(\n {\n suite: input.suite.name,\n scope: context.scope,\n inferredKeywords: context.keywords,\n agent: context.agent,\n totals: context.totals,\n findings: context.findings.map((finding) => ({\n kind: finding.kind,\n severity: finding.severity,\n taskCount: finding.taskIds.length,\n proposedFixClass: finding.proposedFixClass,\n })),\n failures: input.suite.tasks\n .filter((task) => task.outcome && task.outcome !== 'satisfied')\n .map((task) => ({\n task: task.id,\n difficulty: task.difficulty,\n outcome: task.outcome,\n score: task.score,\n gaps: task.gaps ?? [],\n })),\n },\n null,\n 2,\n)}\n\nUse the trace tools. Do not invent facts. Cite task ids. Separate customer-facing claims from internal harness/model findings.`\n}\n","/** Canonical flattened OTLP span shape shared by trace producers and readers. */\n\nimport type { SpanStatus } from './schema'\n\nexport type OtlpStatusCode = 'STATUS_CODE_OK' | 'STATUS_CODE_ERROR' | 'STATUS_CODE_UNSET'\n\nexport interface OtlpFlatLine {\n trace_id: string\n span_id: string\n parent_span_id: string | null\n name: string\n kind: string\n start_time: string\n end_time: string\n status: {\n code: OtlpStatusCode\n message?: string\n }\n resource: { attributes: Record<string, unknown> }\n attributes: Record<string, unknown>\n events?: Array<{ name: string; timeUnixNano?: string; attributes?: Record<string, unknown> }>\n}\n\nexport interface CreateOtlpFlatLineInput {\n traceId: string\n spanId: string\n parentSpanId: string | null\n name: string\n kind: string\n startTime: string\n endTime: string\n statusCode: OtlpStatusCode\n statusMessage?: string\n resource: OtlpFlatLine['resource']\n attributes: Record<string, unknown>\n events?: OtlpFlatLine['events']\n}\n\nexport function createOtlpFlatLine(input: CreateOtlpFlatLineInput): OtlpFlatLine {\n return {\n trace_id: input.traceId,\n span_id: input.spanId,\n parent_span_id: input.parentSpanId,\n name: input.name,\n kind: input.kind,\n start_time: input.startTime,\n end_time: input.endTime,\n status: {\n code: input.statusCode,\n ...(input.statusMessage !== undefined ? { message: input.statusMessage } : {}),\n },\n resource: input.resource,\n attributes: input.attributes,\n ...(input.events && input.events.length > 0 ? { events: input.events } : {}),\n }\n}\n\n/** Map the canonical trace status while letting each caller choose its legacy default. */\nexport function spanStatusToOtlp(\n status: SpanStatus | undefined,\n error: string | undefined,\n defaultCode: OtlpStatusCode,\n): OtlpStatusCode {\n if (status === 'error' || error) return 'STATUS_CODE_ERROR'\n if (status === 'ok') return 'STATUS_CODE_OK'\n return defaultCode\n}\n\n/** Convert epoch milliseconds, returning `undefined` for invalid or out-of-range values. */\nexport function epochMillisToIso(value: number): string | undefined {\n if (!Number.isFinite(value)) return undefined\n try {\n return new Date(value).toISOString()\n } catch {\n return undefined\n }\n}\n","/**\n * `flattenOtlpExportToNdjson` — flatten an `OtlpExport` (the shape\n * `exportRunAsOtlp` produces) into the per-line JSON the analyst's\n * `OtlpFileTraceStore` index reads. Replaces three per-consumer OTLP\n * flatteners with one canonical projection.\n *\n * Pure function, no I/O — the caller does `.map(JSON.stringify).join('\\n')`\n * and writes the file (consumers want control over rotation + naming).\n */\n\nimport type { OtlpExport, OtlpSpan } from '../trace/otel'\nimport {\n LLM_INPUT_TOKENS,\n LLM_MODEL_NAME,\n LLM_OUTPUT_TOKENS,\n OPENINFERENCE_SPAN_KIND,\n TOOL_NAME,\n} from '../trace/otlp-attributes'\nimport { createOtlpFlatLine, type OtlpFlatLine } from '../trace/otlp-flat'\n\nexport type { OtlpFlatLine } from '../trace/otlp-flat'\n\nexport interface FlattenOtlpOptions {\n /** `'openinference'` (default) maps source per-span attributes into the\n * canonical OpenInference vocabulary the analyst readers consume. `'none'`\n * passes attributes through untouched. */\n attributeVocabulary?: 'openinference' | 'none'\n /** Override the numeric-kind → otlp-string mapping. */\n kindMap?: Partial<Record<number, string>>\n}\n\nconst DEFAULT_KIND_MAP: Record<number, string> = {\n 0: 'SPAN_KIND_UNSPECIFIED',\n 1: 'SPAN_KIND_INTERNAL',\n 2: 'SPAN_KIND_SERVER',\n 3: 'SPAN_KIND_CLIENT',\n 4: 'SPAN_KIND_PRODUCER',\n 5: 'SPAN_KIND_CONSUMER',\n}\n\nconst STATUS_MAP: Record<number, OtlpFlatLine['status']['code']> = {\n 0: 'STATUS_CODE_UNSET',\n 1: 'STATUS_CODE_OK',\n 2: 'STATUS_CODE_ERROR',\n}\n\n/** Unwrap an OTLP attribute-value union to a scalar. */\nfunction attrValue(v: OtlpSpan['attributes'][number]['value']): string | number | boolean {\n if (v.stringValue !== undefined) return v.stringValue\n if (v.intValue !== undefined) return Number(v.intValue)\n if (v.doubleValue !== undefined) return v.doubleValue\n if (v.boolValue !== undefined) return v.boolValue\n return ''\n}\n\nfunction attrsToRecord(attrs: OtlpSpan['attributes']): Record<string, string | number | boolean> {\n const out: Record<string, string | number | boolean> = {}\n for (const a of attrs) out[a.key] = attrValue(a.value)\n return out\n}\n\nfunction nanoToIso(nano: string): string {\n const ms = Number(nano) / 1_000_000\n return Number.isFinite(ms) ? new Date(ms).toISOString() : new Date(0).toISOString()\n}\n\n/** Mirror selected attributes into the OpenInference vocabulary in place. */\nfunction applyOpenInference(attrs: Record<string, string | number | boolean>): void {\n if ('llm.model' in attrs && !(LLM_MODEL_NAME in attrs)) {\n attrs[LLM_MODEL_NAME] = attrs['llm.model']!\n }\n if ('llm.input_tokens' in attrs && !(LLM_INPUT_TOKENS in attrs)) {\n attrs[LLM_INPUT_TOKENS] = attrs['llm.input_tokens']!\n }\n if ('inference.llm.input_tokens' in attrs && !(LLM_INPUT_TOKENS in attrs)) {\n attrs[LLM_INPUT_TOKENS] = attrs['inference.llm.input_tokens']!\n }\n if ('llm.output_tokens' in attrs && !(LLM_OUTPUT_TOKENS in attrs)) {\n attrs[LLM_OUTPUT_TOKENS] = attrs['llm.output_tokens']!\n }\n if ('inference.llm.output_tokens' in attrs && !(LLM_OUTPUT_TOKENS in attrs)) {\n attrs[LLM_OUTPUT_TOKENS] = attrs['inference.llm.output_tokens']!\n }\n if (TOOL_NAME in attrs && !('inference.tool.name' in attrs)) {\n attrs['inference.tool.name'] = attrs[TOOL_NAME]!\n }\n if ('span.kind' in attrs && !(OPENINFERENCE_SPAN_KIND in attrs)) {\n attrs[OPENINFERENCE_SPAN_KIND] = String(attrs['span.kind']).toUpperCase()\n }\n}\n\nexport function flattenOtlpExportToNdjson(\n otlpExport: OtlpExport,\n opts: FlattenOtlpOptions = {},\n): OtlpFlatLine[] {\n const vocab = opts.attributeVocabulary ?? 'openinference'\n const kindMap = { ...DEFAULT_KIND_MAP, ...opts.kindMap }\n const lines: OtlpFlatLine[] = []\n\n for (const rs of otlpExport.resourceSpans ?? []) {\n const resource = { attributes: attrsToRecord(rs.resource?.attributes ?? []) }\n for (const scope of rs.scopeSpans ?? []) {\n for (const span of scope.spans ?? []) {\n const attributes = attrsToRecord(span.attributes ?? [])\n if (vocab === 'openinference') applyOpenInference(attributes)\n const line = createOtlpFlatLine({\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId ?? null,\n name: span.name,\n kind: kindMap[span.kind] ?? 'SPAN_KIND_UNSPECIFIED',\n startTime: nanoToIso(span.startTimeUnixNano),\n endTime: nanoToIso(span.endTimeUnixNano),\n statusCode: STATUS_MAP[span.status?.code ?? 0] ?? 'STATUS_CODE_UNSET',\n statusMessage: span.status?.message,\n resource,\n attributes,\n events: span.events?.map((e) => ({\n name: e.name,\n timeUnixNano: e.timeUnixNano,\n ...(e.attributes ? { attributes: attrsToRecord(e.attributes) } : {}),\n })),\n })\n lines.push(line)\n }\n }\n }\n\n return lines\n}\n","/**\n * `otlpToRunRecords` — fold an OTLP traces.jsonl (one OTLP span per line;\n * the form AppWorld / HALO emit via their OpenInference OTLP exporter, the\n * same shape `flattenOtlpExportToNdjson` produces) into validated\n * `RunRecord[]` — one record per `trace_id` by default, or per caller-defined\n * logical run when one task is fragmented across multiple OTLP traces.\n *\n * This is the offline ingestion primitive the AppWorld proposer bench and the\n * hosted Intelligence product both stand on: traces in, paper-grade rows\n * out, ready for `compareOptimizationMethods` / `analyzeRuns` / the promotion gate.\n *\n * Aggregation per trace:\n * - tokenUsage: reconcile input, output, cache-read, and cache-write across\n * nested model-call wrappers without double-counting parent aggregates.\n * - costUsd: reconcile complete observed model-call cost when present; else priced via\n * `opts.priceUsdPerToken` from the aggregated tokens; else `null` with a\n * loud `raw.cost_unpriced = 1` marker.\n * - task failure class and detail: read from process-root\n * `tangle.task.failure_*` attributes; malformed or conflicting values throw.\n * - terminalFailureReason: the failed root's normalized status message,\n * when one unambiguous root supplies terminal failure evidence.\n * - terminalOutcome: reduced from root-span status only. Child tool errors\n * remain visible in `error_span_count` and `execution_error_count` without\n * changing the run outcome. Root, guardrail, evaluator, propagated, and\n * unknown errors retain separate counters.\n * - model: the dominant LLM model in the trace (snapshot-padded to satisfy\n * `validateRunRecord` when the trace's model is a bare alias).\n * - outcome score: `opts.scoreForTrace` (AppWorld `world.evaluate()` →\n * TGC/SGC) when supplied. Traces without an external task-quality signal\n * remain unlabeled; execution errors never become a task score.\n * - prompt / completion: carried into `raw` as token-count signals and,\n * when the first/last LLM span exposes `input.value` / `output.value`,\n * the verbatim text is preserved on the optional `promptText` /\n * `completionText` of the returned `OtlpTraceRunRecord`.\n *\n * Fail-loud: an OTLP file with zero valid spans throws. A trace with no\n * spans is impossible (a trace exists only because a span referenced it).\n * `validateRunRecord` runs on every row — a malformed projection throws\n * rather than silently producing a half-record.\n */\n\nimport {\n type RunCostProvenance,\n type RunRecord,\n type RunSplitTag,\n type RunTerminalOutcome,\n type RunTokenUsage,\n validateRunRecord,\n} from '../run-record'\nimport { summarizeTraceErrors, type TraceErrorRole } from '../trace/error-classification'\nimport {\n type MeasurementCoverage,\n recordAggregateMeasurements,\n summarizeExecutionMeasurements,\n} from '../trace/execution-measurements'\nimport {\n classifyOtlpSpanRole,\n isOtlpModelCall,\n LLM_MODEL_ATTR_KEYS,\n} from '../trace/otlp-attributes'\nimport { readTaskFailureLabels } from '../trace/task-failure-attributes'\nimport {\n compareSpanTime,\n firstStringAttr,\n type ProjectedOtlpSpan,\n projectOtlpFlatLine,\n spanEpochMillis,\n} from './otlp-span'\n\nexport interface OtlpToRunRecordsOptions {\n /** Logical experiment grouping for every produced record. */\n experimentId: string\n /** Candidate (variant) id — the surface these traces exercised. The\n * bench passes the proposer label here so `compareOptimizationMethods` can pair rows. */\n candidateId: string\n /** Split assignment for every produced record. Default `'holdout'` —\n * ingested traces are evidence, not the optimizer's training pool. */\n splitTag?: RunSplitTag\n /** Git SHA the traces were produced from. Default `'unknown'`. */\n commitSha?: string\n /** sha256 of the effective prompt surface. Default `'unknown'`. */\n promptHash?: string\n /** sha256 of the effective config. Default `'unknown'`. */\n configHash?: string\n /** RNG seed recorded on every row. Default 0. */\n seed?: number\n /**\n * Fallback model snapshot when the trace exposes no LLM model attribute\n * OR exposes a bare alias `validateRunRecord` would reject. The trace's\n * own model wins when it already carries a snapshot. Default\n * `'unknown@otlp'` (opaque-snapshot form the validator accepts).\n */\n fallbackModel?: string\n /**\n * USD per total token (input+output) used to price a trace when no\n * per-span cost attribute is present. When unset, an unpriced trace\n * records `costUsd: null` and `raw.cost_unpriced = 1`.\n */\n priceUsdPerToken?: number\n /**\n * Map each OTLP `trace_id` to the logical run it belongs to. Use this when a\n * provider emits several traces for one task attempt. All mapped traces are\n * aggregated into one record; duplicate span ids remain isolated by their\n * source trace. The callback must return a non-empty id for every trace.\n *\n * When omitted, every `trace_id` remains an independent run.\n */\n logicalRunIdForTrace?: (traceId: string) => string\n /**\n * Score for a produced run's outcome (AppWorld `world.evaluate()` →\n * TGC/SGC, or\n * any [0,1] task-success signal). Keyed by the logical run id when\n * `logicalRunIdForTrace` is supplied, otherwise by `trace_id`. When the map\n * has no entry or the function returns undefined, the record remains\n * unlabeled.\n */\n scoreForTrace?: (runId: string, span: TraceAggregate) => number | undefined\n /**\n * Per-record judge metadata when an external judge produced the score.\n * Keyed by the logical run id when supplied, otherwise by `trace_id`.\n */\n judgeMetadataForTrace?: (runId: string) => RunRecord['judgeMetadata'] | undefined\n}\n\n/** A `RunRecord` plus the verbatim prompt/completion text when the trace's\n * LLM spans exposed it. The text is NOT on the validated `RunRecord`\n * (`outcome.raw` is numeric-only) but consumers ingesting full traces want\n * it — so it rides alongside. */\nexport interface OtlpTraceRunRecord {\n record: RunRecord\n /** Verbatim first-LLM-span `input.value`, when present. */\n promptText?: string\n /** Verbatim last-LLM-span `output.value`, when present. */\n completionText?: string\n}\n\n/** Per-trace rollup the score callback can inspect. */\nexport interface TraceAggregate {\n traceId: string\n /** Number of source OTLP traces folded into this run. */\n sourceTraceCount: number\n /** Source OTLP trace ids folded into this run, sorted for deterministic audit output. */\n sourceTraceIds: readonly string[]\n spanCount: number\n llmSpanCount: number\n toolSpanCount: number\n agentSpanCount: number\n errorSpanCount: number\n executionErrorCount: number\n processErrorCount: number\n guardrailErrorCount: number\n judgeErrorCount: number\n propagatedErrorCount: number\n unclassifiedErrorCount: number\n tokenUsage: RunTokenUsage\n /** First error span's normalized status message, if any. */\n firstErrorMessage?: string\n model: string\n startTime: string\n endTime: string\n wallMs: number\n /** Root-span terminal result. Child span errors do not change this value. */\n terminalOutcome: RunTerminalOutcome\n}\n\ninterface AggregatedTrace extends TraceAggregate {\n callSpanIds: string[]\n costMeasurement: MeasurementCoverage\n aggregateMeasurement?: ReturnType<typeof summarizeExecutionMeasurements>['aggregate']\n terminalFailureMessage?: string\n}\n\n/**\n * Parse + aggregate an OTLP traces.jsonl string into validated\n * `RunRecord[]` (one per trace). Use {@link otlpToTraceRunRecords} when you\n * also want the verbatim prompt/completion text alongside each record.\n */\nexport function otlpToRunRecords(otlpJsonl: string, opts: OtlpToRunRecordsOptions): RunRecord[] {\n return otlpToTraceRunRecords(otlpJsonl, opts).map((r) => r.record)\n}\n\n/**\n * Aggregate already-parsed OTLP flat rows without serializing them back to\n * JSONL. This is the in-memory counterpart to {@link otlpToRunRecords}; both\n * paths share projection, reconciliation, validation, and ordering.\n */\nexport function otlpRowsToRunRecords(\n rows: Iterable<object>,\n opts: OtlpToRunRecordsOptions,\n): RunRecord[] {\n return otlpRowsToTraceRunRecords(rows, opts).map((row) => row.record)\n}\n\n/** As {@link otlpToRunRecords} but returns the prompt/completion text too. */\nexport function otlpToTraceRunRecords(\n otlpJsonl: string,\n opts: OtlpToRunRecordsOptions,\n): OtlpTraceRunRecord[] {\n return traceRunRecordsFromSpans(\n groupSpansByLogicalRun(groupJsonlSpansByTrace(otlpJsonl), opts.logicalRunIdForTrace),\n opts,\n )\n}\n\n/** Parsed-row counterpart to {@link otlpToTraceRunRecords}. */\nexport function otlpRowsToTraceRunRecords(\n rows: Iterable<object>,\n opts: OtlpToRunRecordsOptions,\n): OtlpTraceRunRecord[] {\n return traceRunRecordsFromSpans(\n groupSpansByLogicalRun(groupRowsByTrace(rows), opts.logicalRunIdForTrace),\n opts,\n )\n}\n\nfunction traceRunRecordsFromSpans(\n byTrace: Map<string, ProjectedOtlpSpan[]>,\n opts: OtlpToRunRecordsOptions,\n): OtlpTraceRunRecord[] {\n const splitTag = opts.splitTag ?? 'holdout'\n const commitSha = opts.commitSha ?? 'unknown'\n const promptHash = opts.promptHash ?? 'unknown'\n const configHash = opts.configHash ?? 'unknown'\n const seed = opts.seed ?? 0\n const fallbackModel = opts.fallbackModel ?? 'unknown@otlp'\n\n if (byTrace.size === 0) {\n throw new Error(\n 'otlpToRunRecords: OTLP input produced zero valid spans — every row was empty, malformed, or missing trace_id/span_id',\n )\n }\n\n // Stable trace order (insertion order of first appearance is preserved by\n // Map; sort by trace_id for determinism across producers).\n const traceIds = [...byTrace.keys()].sort()\n const out: OtlpTraceRunRecord[] = []\n\n for (const traceId of traceIds) {\n const spans = byTrace.get(traceId)!\n const agg = aggregateTrace(traceId, spans, fallbackModel)\n\n const score = resolveScore(opts, traceId, agg)\n const { costUsd, costProvenance } = resolveCost(opts, agg)\n\n const raw: Record<string, number> = {\n source_trace_count: agg.sourceTraceCount,\n span_count: agg.spanCount,\n llm_span_count: agg.llmSpanCount,\n tool_span_count: agg.toolSpanCount,\n agent_span_count: agg.agentSpanCount,\n error_span_count: agg.errorSpanCount,\n execution_error_count: agg.executionErrorCount,\n process_error_count: agg.processErrorCount,\n guardrail_error_count: agg.guardrailErrorCount,\n judge_error_count: agg.judgeErrorCount,\n propagated_error_count: agg.propagatedErrorCount,\n unclassified_error_count: agg.unclassifiedErrorCount,\n prompt_tokens: agg.tokenUsage.input,\n completion_tokens: agg.tokenUsage.output,\n }\n if (agg.tokenUsage.reasoning !== undefined) raw.reasoning_tokens = agg.tokenUsage.reasoning\n if (agg.tokenUsage.cached !== undefined) raw.cached_tokens = agg.tokenUsage.cached\n if (agg.tokenUsage.cacheWrite !== undefined) {\n raw.cache_write_tokens = agg.tokenUsage.cacheWrite\n }\n if (agg.costMeasurement.value !== undefined && !agg.costMeasurement.complete) {\n raw.partial_observed_cost_usd = agg.costMeasurement.value\n }\n recordAggregateMeasurements(raw, agg.aggregateMeasurement)\n if (costProvenance.kind === 'uncaptured') raw.cost_unpriced = 1\n\n const outcome: RunRecord['outcome'] = { raw }\n if (score !== undefined) {\n if (splitTag === 'holdout') outcome.holdoutScore = score\n else outcome.searchScore = score\n }\n\n const { promptText, completionText } = extractPromptCompletion(spans, agg.callSpanIds)\n const judgeMetadata = opts.judgeMetadataForTrace?.(traceId)\n const taskFailure = readTaskFailureLabels(\n spans.filter((span) => span.parent_span_id === null && isTerminalRootCandidate(span)),\n `otlpToRunRecords: run '${traceId}'`,\n )\n\n const record = validateRunRecord({\n runId: `otlp:${opts.experimentId}:${opts.candidateId}:${traceId}`,\n experimentId: opts.experimentId,\n candidateId: opts.candidateId,\n seed,\n model: ensureSnapshot(agg.model, fallbackModel),\n promptHash,\n configHash,\n commitSha,\n wallMs: agg.wallMs,\n costUsd,\n costProvenance,\n tokenUsage: agg.tokenUsage,\n terminalOutcome: agg.terminalOutcome,\n ...(agg.terminalFailureMessage ? { terminalFailureReason: agg.terminalFailureMessage } : {}),\n ...(judgeMetadata ? { judgeMetadata } : {}),\n outcome,\n ...taskFailure,\n splitTag,\n scenarioId: traceId,\n })\n\n out.push({\n record,\n ...(promptText !== undefined ? { promptText } : {}),\n ...(completionText !== undefined ? { completionText } : {}),\n })\n }\n\n return out\n}\n\n// ── Internals ──────────────────────────────────────────────────────────\n\nfunction* yieldJsonlRows(otlpJsonl: string): Iterable<Record<string, unknown>> {\n for (const line of otlpJsonl.split('\\n')) {\n const trimmed = line.trim()\n if (trimmed.length === 0) continue\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch {\n // Tolerate a stray malformed line — mirrors the store's index, which\n // skips unparseable lines rather than nuking a whole dataset. A file\n // that is ENTIRELY malformed still throws (zero valid spans).\n continue\n }\n if (parsed && typeof parsed === 'object') yield parsed as Record<string, unknown>\n }\n}\n\nfunction groupJsonlSpansByTrace(otlpJsonl: string): Map<string, ProjectedOtlpSpan[]> {\n return groupRowsByTrace(yieldJsonlRows(otlpJsonl))\n}\n\nfunction groupRowsByTrace(rows: Iterable<object>): Map<string, ProjectedOtlpSpan[]> {\n const byTrace = new Map<string, ProjectedOtlpSpan[]>()\n for (const row of rows) {\n if (!row || typeof row !== 'object') continue\n const span = projectOtlpFlatLine(row as Record<string, unknown>)\n if (!span) continue\n const arr = byTrace.get(span.trace_id)\n if (arr) arr.push(span)\n else byTrace.set(span.trace_id, [span])\n }\n return byTrace\n}\n\nfunction groupSpansByLogicalRun(\n byTrace: Map<string, ProjectedOtlpSpan[]>,\n logicalRunIdForTrace: OtlpToRunRecordsOptions['logicalRunIdForTrace'],\n): Map<string, ProjectedOtlpSpan[]> {\n if (!logicalRunIdForTrace) return byTrace\n\n const byRun = new Map<string, ProjectedOtlpSpan[]>()\n for (const [traceId, spans] of byTrace) {\n const suppliedRunId = logicalRunIdForTrace(traceId)\n if (typeof suppliedRunId !== 'string' || suppliedRunId.trim().length === 0) {\n throw new Error(\n `otlpToRunRecords: logicalRunIdForTrace('${traceId}') returned an empty run id`,\n )\n }\n const runId = suppliedRunId.trim()\n const target = byRun.get(runId) ?? []\n for (const span of spans) {\n target.push({\n ...span,\n span_id: qualifySpanId(traceId, span.span_id),\n parent_span_id: span.parent_span_id ? qualifySpanId(traceId, span.parent_span_id) : null,\n })\n }\n byRun.set(runId, target)\n }\n return byRun\n}\n\nfunction qualifySpanId(traceId: string, spanId: string): string {\n const prefix = `${traceId}:`\n return spanId.startsWith(prefix) ? spanId : `${prefix}${spanId}`\n}\n\nfunction aggregateTrace(\n traceId: string,\n spans: ProjectedOtlpSpan[],\n fallbackModel: string,\n): AggregatedTrace {\n // Span order within a trace is by start time (epoch-aware across ISO/epoch\n // dialects), then a stable tiebreak.\n const ordered = [...spans].sort(\n (a, b) => compareSpanTime(a.start_time, b.start_time) || a.span_id.localeCompare(b.span_id),\n )\n\n const measurements = summarizeExecutionMeasurements(\n ordered.map((span) => ({\n id: span.span_id,\n ...(span.parent_span_id ? { parentId: span.parent_span_id } : {}),\n attributes: span.attributes,\n modelCall: isOtlpModelCall({\n kind: span.kind,\n name: span.name,\n attributes: span.attributes,\n }),\n aggregate: span.kind !== 'LLM' && span.kind !== 'UNKNOWN',\n })),\n )\n let toolSpanCount = 0\n let agentSpanCount = 0\n let firstErrorMessage: string | undefined\n const modelVotes = new Map<string, number>()\n let earliest = ordered[0]?.start_time ?? ''\n let latest = ordered[0]?.end_time ?? ''\n\n for (const s of ordered) {\n if (s.start_time && (!earliest || compareSpanTime(s.start_time, earliest) < 0))\n earliest = s.start_time\n if (s.end_time && (!latest || compareSpanTime(s.end_time, latest) > 0)) latest = s.end_time\n\n if (s.kind === 'TOOL') {\n toolSpanCount += 1\n } else if (s.kind === 'AGENT') {\n agentSpanCount += 1\n }\n\n if (s.status === 'ERROR') {\n if (firstErrorMessage === undefined) {\n firstErrorMessage = (s.status_message ?? `${s.name} — STATUS_CODE_ERROR`).slice(0, 500)\n }\n }\n }\n\n const callSpanIds = new Set(measurements.callSpanIds)\n for (const span of ordered) {\n if (!callSpanIds.has(span.span_id)) continue\n const model = firstStringAttr(span.attributes, LLM_MODEL_ATTR_KEYS) ?? span.model_name\n if (model) modelVotes.set(model, (modelVotes.get(model) ?? 0) + 1)\n }\n\n // Dominant model across LLM spans; falls back to any model attribute on a\n // non-LLM span, then the supplied fallback snapshot.\n const model = topVote(modelVotes) ?? firstModelAttr(ordered) ?? fallbackModel\n\n let wallMs = 0\n // epoch-aware: Date.parse returns NaN for a bare epoch-millis string, which\n // silently zeroed wallMs for traces emitted with epoch timestamps.\n const a = spanEpochMillis(earliest)\n const b = spanEpochMillis(latest)\n if (a !== null && b !== null) wallMs = Math.max(0, b - a)\n\n const sourceTraceIds = [...new Set(spans.map((span) => span.trace_id))].sort()\n\n const terminal = terminalEvidenceFromRoots(ordered)\n const errorSummary = summarizeTraceErrors(\n ordered.map((span) => ({\n id: span.span_id,\n ...(span.parent_span_id ? { parentId: span.parent_span_id } : {}),\n role: errorRoleForProjectedSpan(span),\n error: span.status === 'ERROR',\n processRoot: span.parent_span_id === null && isTerminalRootCandidate(span),\n })),\n )\n return {\n traceId,\n sourceTraceCount: sourceTraceIds.length,\n sourceTraceIds,\n spanCount: spans.length,\n llmSpanCount: measurements.modelCallCount,\n toolSpanCount,\n agentSpanCount,\n errorSpanCount: errorSummary.total,\n executionErrorCount: errorSummary.execution,\n processErrorCount: errorSummary.process,\n guardrailErrorCount: errorSummary.guardrail,\n judgeErrorCount: errorSummary.evaluation,\n propagatedErrorCount: errorSummary.propagated,\n unclassifiedErrorCount: errorSummary.unclassified,\n tokenUsage: measurements.tokenUsage,\n firstErrorMessage,\n model,\n startTime: earliest,\n endTime: latest,\n wallMs,\n terminalOutcome: terminal.outcome,\n ...(terminal.failureMessage ? { terminalFailureMessage: terminal.failureMessage } : {}),\n callSpanIds: measurements.callSpanIds,\n costMeasurement: measurements.cost,\n ...(measurements.aggregate ? { aggregateMeasurement: measurements.aggregate } : {}),\n }\n}\n\nfunction terminalEvidenceFromRoots(spans: ProjectedOtlpSpan[]): {\n outcome: RunTerminalOutcome\n failureMessage?: string\n} {\n const roots = spans.filter(\n (span) => span.parent_span_id === null && isTerminalRootCandidate(span),\n )\n if (roots.length !== 1) return { outcome: 'unknown' }\n const root = roots[0]!\n if (root.status === 'ERROR') {\n return {\n outcome: 'failed',\n failureMessage: (root.status_message ?? `${root.name} — STATUS_CODE_ERROR`).slice(0, 500),\n }\n }\n if (root.status === 'OK') return { outcome: 'succeeded' }\n return { outcome: 'unknown' }\n}\n\nfunction isTerminalRootCandidate(span: ProjectedOtlpSpan): boolean {\n const role = errorRoleForProjectedSpan(span)\n return role !== 'LLM' && role !== 'TOOL' && role !== 'EVALUATOR' && role !== 'GUARDRAIL'\n}\n\nfunction errorRoleForProjectedSpan(span: ProjectedOtlpSpan): TraceErrorRole {\n return classifyOtlpSpanRole({\n kind: span.kind,\n name: span.name,\n attributes: span.attributes,\n })\n}\n\nfunction resolveScore(\n opts: OtlpToRunRecordsOptions,\n traceId: string,\n agg: TraceAggregate,\n): number | undefined {\n const supplied = opts.scoreForTrace?.(traceId, agg)\n if (supplied !== undefined) {\n if (!Number.isFinite(supplied)) {\n throw new Error(\n `otlpToRunRecords: scoreForTrace('${traceId}') returned non-finite ${supplied}`,\n )\n }\n return supplied\n }\n return undefined\n}\n\nfunction resolveCost(\n opts: OtlpToRunRecordsOptions,\n agg: AggregatedTrace,\n): { costUsd: number | null; costProvenance: RunCostProvenance } {\n const observedCost = agg.costMeasurement\n if (observedCost.complete && observedCost.value !== undefined) {\n return {\n costUsd: observedCost.value,\n costProvenance: { kind: 'observed', usd: observedCost.value },\n }\n }\n if (agg.aggregateMeasurement?.costUsd !== undefined) {\n return {\n costUsd: agg.aggregateMeasurement.costUsd,\n costProvenance: { kind: 'observed', usd: agg.aggregateMeasurement.costUsd },\n }\n }\n\n if (opts.priceUsdPerToken !== undefined) {\n const totalTokens = agg.tokenUsage.input + agg.tokenUsage.output\n const costUsd = totalTokens * opts.priceUsdPerToken\n return { costUsd, costProvenance: { kind: 'estimated', usd: costUsd } }\n }\n\n return { costUsd: null, costProvenance: { kind: 'uncaptured', usd: null } }\n}\n\nfunction extractPromptCompletion(\n spans: ProjectedOtlpSpan[],\n callSpanIds: string[],\n): {\n promptText?: string\n completionText?: string\n} {\n const callIds = new Set(callSpanIds)\n const measuredCalls = spans.filter((span) => callIds.has(span.span_id))\n const llm = (\n measuredCalls.length > 0 ? measuredCalls : spans.filter((s) => s.kind === 'LLM')\n ).sort(\n (a, b) => compareSpanTime(a.start_time, b.start_time) || a.span_id.localeCompare(b.span_id),\n )\n if (llm.length === 0) return {}\n const promptText =\n firstStringAttr(llm[0]!.attributes, ['input.value', 'llm.input_messages', 'gen_ai.prompt']) ??\n undefined\n const last = llm[llm.length - 1]!\n const completionText =\n firstStringAttr(last.attributes, [\n 'output.value',\n 'llm.output_messages',\n 'gen_ai.completion',\n ]) ?? undefined\n return {\n ...(promptText !== undefined ? { promptText } : {}),\n ...(completionText !== undefined ? { completionText } : {}),\n }\n}\n\nfunction topVote(votes: Map<string, number>): string | null {\n let best: string | null = null\n let bestN = 0\n for (const [k, n] of votes) {\n // Strict > keeps the higher count; lexicographic tie-break makes the winner\n // independent of Map insertion order (reproducible across producers).\n if (n > bestN || (n === bestN && best !== null && k < best)) {\n best = k\n bestN = n\n }\n }\n return best\n}\n\nfunction firstModelAttr(spans: ProjectedOtlpSpan[]): string | null {\n for (const s of spans) {\n const m = firstStringAttr(s.attributes, LLM_MODEL_ATTR_KEYS) ?? s.model_name\n if (m) return m\n }\n return null\n}\n\n/**\n * `validateRunRecord` rejects bare model aliases (`gpt-4o`) that remap\n * silently. AppWorld/HALO traces frequently carry such bare ids (or a null\n * model). When the model already encodes a snapshot we keep it; otherwise we\n * append the fallback snapshot token so the row is admissible without lying\n * about the model — the bare base name is preserved verbatim before `@`.\n */\nfunction ensureSnapshot(model: string, fallbackModel: string): string {\n if (modelHasSnapshot(model)) return model\n const fallbackTag = fallbackModel.includes('@')\n ? fallbackModel.slice(fallbackModel.indexOf('@'))\n : '@otlp'\n return `${model}${fallbackTag}`\n}\n\nfunction modelHasSnapshot(model: string): boolean {\n if (model.includes('@')) return true\n if (/-\\d{8}$/.test(model)) return true\n if (/-\\d{4}-\\d{2}-\\d{2}$/.test(model)) return true\n if (/:date-/.test(model)) return true\n return false\n}\n","import { CaptureIntegrityError } from '../errors'\nimport { applyToolSpanOtlpAttributes, OPENINFERENCE_SPAN_KIND } from '../trace/otlp-attributes'\nimport { createOtlpFlatLine, epochMillisToIso, spanStatusToOtlp } from '../trace/otlp-flat'\nimport type { ToolSpan } from '../trace/schema'\nimport type { TraceAnalysisStore } from './store'\nimport { createOtlpBufferTraceStore, type ToolSpansToTraceAnalysisStoreOptions } from './store-otlp'\n\n/** Missing tool spans cannot distinguish a tool-free run from broken capture. */\nexport class ToolTraceMissingError extends CaptureIntegrityError {\n constructor() {\n super('toolSpansToTraceAnalysisStore: no tool spans supplied; trace evidence is missing')\n }\n}\n\n/**\n * Snapshot canonical tool spans into the read interface used by trace analysts.\n * One run becomes one trace while arguments, results, errors, and timing remain searchable.\n */\nexport function toolSpansToTraceAnalysisStore(\n spans: readonly ToolSpan[] | null | undefined,\n options: ToolSpansToTraceAnalysisStoreOptions = {},\n): TraceAnalysisStore {\n if (!spans || spans.length === 0) throw new ToolTraceMissingError()\n\n const seen = new Set<string>()\n const lines = spans.map((span, index) => {\n assertToolSpanIdentity(span, index)\n const identity = `${span.runId}\\u0000${span.spanId}`\n if (seen.has(identity)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: duplicate span '${span.spanId}' in run '${span.runId}'`,\n )\n }\n seen.add(identity)\n\n const attributes = { ...(span.attributes ?? {}) }\n applyToolSpanOtlpAttributes(attributes, span)\n attributes[OPENINFERENCE_SPAN_KIND] = 'TOOL'\n\n const endedAt = span.endedAt ?? span.startedAt + (span.latencyMs ?? 0)\n const line = createOtlpFlatLine({\n traceId: span.runId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId ?? null,\n name: span.name,\n kind: 'SPAN_KIND_INTERNAL',\n startTime: toolSpanTimeIso(span.startedAt, span.spanId, 'startedAt'),\n endTime: toolSpanTimeIso(endedAt, span.spanId, 'endedAt'),\n statusCode: spanStatusToOtlp(span.status, span.error, 'STATUS_CODE_UNSET'),\n statusMessage: span.error,\n resource: { attributes: {} },\n attributes,\n })\n try {\n return JSON.stringify(line)\n } catch (cause) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' in run '${span.runId}' is not JSON-serializable`,\n { cause },\n )\n }\n })\n\n return createOtlpBufferTraceStore(Buffer.from(`${lines.join('\\n')}\\n`, 'utf8'), options)\n}\n\nfunction assertToolSpanIdentity(span: ToolSpan, index: number): void {\n if (span.kind !== 'tool') {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span at index ${index} has kind '${String(span.kind)}', not 'tool'`,\n )\n }\n if (!span.runId || !span.spanId || !span.name || !span.toolName) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span at index ${index} is missing runId, spanId, name, or toolName`,\n )\n }\n if (!Number.isFinite(span.startedAt)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid startedAt`,\n )\n }\n if (span.endedAt !== undefined && !Number.isFinite(span.endedAt)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid endedAt`,\n )\n }\n if (span.endedAt !== undefined && span.endedAt < span.startedAt) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' ends before it starts`,\n )\n }\n if (span.latencyMs !== undefined && (!Number.isFinite(span.latencyMs) || span.latencyMs < 0)) {\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${span.spanId}' has invalid latencyMs`,\n )\n }\n}\n\nfunction toolSpanTimeIso(value: number, spanId: string, field: string): string {\n const iso = epochMillisToIso(value)\n if (iso) return iso\n throw new CaptureIntegrityError(\n `toolSpansToTraceAnalysisStore: span '${spanId}' has invalid ${field}`,\n )\n}\n","/**\n * Wrap a provider `fetch` and record request, response, and error events.\n *\n * The returned value is a plain `typeof fetch`. Capture is best-effort by\n * default; set `failClosed` when telemetry loss must stop the provider call.\n */\n\nimport {\n type ExtractedUsage,\n extractUsage,\n extractUsageFromSse,\n type SseUsageMode,\n} from './extract-usage'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderDirection,\n type RawProviderEvent,\n type RawProviderSink,\n} from './raw-provider-sink'\n\nexport interface CaptureFetchContext {\n /** Logical run id stamped on every captured event. Required — without it\n * the raw events can't be paired with their parent `Run`. */\n runId: string\n /** Optional logical span id (enables span-level sink filtering). */\n spanId?: string\n /** Resolved base URL (normalised, no trailing slash). Used for the event's\n * `baseUrl` and for endpoint-path extraction. */\n baseUrl: string\n /** Model id the caller intends to invoke. Stamped on every event. */\n model: string\n /** Provider override. When omitted, `providerFromBaseUrl(baseUrl)`. */\n provider?: string\n}\n\nexport interface CaptureFetchOptions {\n /** Override the capture-time redactor. Default `defaultProviderRedactor`. */\n redactor?: ProviderRedactor\n /** Cap on captured response-body bytes; beyond it the body is truncated and\n * `body_truncated` is added to `redactedFields`. Default 2 MiB. */\n responseBodyByteCap?: number\n /** When true, a sink-write failure propagates to the caller. Default false\n * — capture is best-effort so a sink failure never kills the LLM call. */\n failClosed?: boolean\n /**\n * Invoked with the token usage parsed off each successful response (JSON or\n * SSE), keyed by the captured context. Lets a caller fold usage → cost without\n * re-cloning the response themselves. Not called when the response carries no\n * usage. Best-effort: a throw here is swallowed (it never kills the LLM call)\n * unless `failClosed` is set.\n */\n onUsage?: (usage: ExtractedUsage, ctx: CaptureFetchContext) => void\n /** How repeated SSE usage events should be reconciled. Default `cumulative`. */\n sseUsageMode?: SseUsageMode\n}\n\nconst DEFAULT_BODY_CAP = 2 * 1024 * 1024\n\nfunction headersToRecord(headers: Headers | undefined): Record<string, string> | undefined {\n if (!headers) return undefined\n const out: Record<string, string> = {}\n headers.forEach((value, key) => {\n out[key.toLowerCase()] = value\n })\n return Object.keys(out).length > 0 ? out : undefined\n}\n\nfunction parseMaybeJson(text: string): unknown {\n if (text.length === 0) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\n/** Best-effort request-body read across the `fetch` input forms. */\nasync function readRequestBody(\n input: RequestInfo | URL,\n init: RequestInit | undefined,\n): Promise<unknown> {\n if (typeof init?.body === 'string') return parseMaybeJson(init.body)\n if (init?.body != null) return undefined // streams / FormData / Blob — not captured\n if (input instanceof Request) {\n try {\n return parseMaybeJson(await input.clone().text())\n } catch {\n return undefined\n }\n }\n return undefined\n}\n\nfunction endpointFromUrl(url: string, baseUrl: string): string {\n const normalisedBase = baseUrl.replace(/\\/+$/, '')\n if (url.startsWith(normalisedBase)) return url.slice(normalisedBase.length) || '/'\n try {\n return new URL(url).pathname\n } catch {\n return url\n }\n}\n\nexport function captureFetchToRawSink(\n fetch: typeof globalThis.fetch,\n sink: RawProviderSink,\n ctx: CaptureFetchContext,\n opts: CaptureFetchOptions = {},\n): typeof globalThis.fetch {\n const provider = ctx.provider ?? providerFromBaseUrl(ctx.baseUrl)\n const redactor = opts.redactor ?? defaultProviderRedactor\n const bodyCap = opts.responseBodyByteCap ?? DEFAULT_BODY_CAP\n let warned = false\n\n const baseEvent = (direction: RawProviderDirection, endpoint: string): RawProviderEvent => ({\n eventId: crypto.randomUUID(),\n runId: ctx.runId,\n spanId: ctx.spanId,\n provider,\n model: ctx.model,\n endpoint,\n baseUrl: ctx.baseUrl,\n attemptIndex: 0, // retries are re-invocations one layer up; documented in 0.x\n direction,\n timestamp: Date.now(),\n redactedFields: [],\n })\n\n const record = async (event: RawProviderEvent): Promise<void> => {\n try {\n await sink.record(redactor(event))\n } catch (err) {\n if (opts.failClosed) throw err\n if (!warned) {\n warned = true\n console.warn(\n `captureFetchToRawSink: sink.record failed (capture is best-effort) — ${\n err instanceof Error ? err.message : String(err)\n }`,\n )\n }\n }\n }\n\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const url =\n typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase()\n const endpoint = endpointFromUrl(url, ctx.baseUrl)\n\n const reqHeaders = new Headers(\n init?.headers ?? (input instanceof Request ? input.headers : undefined),\n )\n await record({\n ...baseEvent('request', endpoint),\n requestHeaders: { ...headersToRecord(reqHeaders), 'x-http-method': method },\n requestBody: await readRequestBody(input, init),\n })\n\n const start = Date.now()\n let response: Response\n try {\n response = await fetch(input, init)\n } catch (err) {\n await record({\n ...baseEvent('error', endpoint),\n durationMs: Date.now() - start,\n errorMessage: err instanceof Error ? err.message : String(err),\n })\n throw err\n }\n\n // Read the body off a clone so the caller still consumes the original.\n let responseBody: unknown\n let rawText: string | undefined\n const redactedFields: string[] = []\n try {\n rawText = await response.clone().text()\n if (rawText.length > bodyCap) {\n responseBody = rawText.slice(0, bodyCap)\n redactedFields.push('body_truncated')\n } else {\n responseBody = parseMaybeJson(rawText)\n }\n } catch {\n responseBody = undefined\n }\n\n if (opts.onUsage && rawText !== undefined) {\n // Reuse the body already read for capture; no extra clone. JSON first,\n // then SSE accumulation. A throw in the consumer's callback is swallowed\n // (best-effort) unless failClosed is set — the LLM call must not die here.\n try {\n const parsedForUsage = parseMaybeJson(rawText)\n const usage =\n extractUsage(parsedForUsage) ??\n (typeof parsedForUsage === 'string'\n ? extractUsageFromSse(rawText, { mode: opts.sseUsageMode })\n : null)\n if (usage) opts.onUsage(usage, ctx)\n } catch (err) {\n if (opts.failClosed) throw err\n }\n }\n\n await record({\n ...baseEvent('response', endpoint),\n durationMs: Date.now() - start,\n statusCode: response.status,\n responseHeaders: headersToRecord(response.headers),\n responseBody,\n redactedFields,\n })\n\n return response\n }\n}\n","/**\n * OpenTelemetry JSON export — maps TraceSchema v1 to OTLP/JSON so\n * traces render natively in Jaeger / Honeycomb / Langfuse / Grafana.\n *\n * Wire format only. We do NOT depend on the @opentelemetry SDK — that\n * would drag in polyfills incompatible with Workers/Edge. Consumers\n * push the JSON to their collector of choice via HTTP.\n *\n * Reference: OTLP 1.3.2 (ResourceSpans / ScopeSpans / Span).\n */\n\nimport {\n applyLlmSpanOtlpAttributes,\n applyToolSpanOtlpAttributes,\n OPENINFERENCE_SPAN_KIND,\n traceSpanKindToOpenInferenceKind,\n} from './otlp-attributes'\nimport type { Run, Span, TraceEvent } from './schema'\nimport type { TraceStore } from './store'\n\nexport const OTEL_AGENT_EVAL_SCOPE = { name: '@tangle-network/agent-eval', version: '0.3.0' }\n\nexport interface OtlpSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes: Array<{\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n }>\n events?: Array<{ timeUnixNano: string; name: string; attributes?: OtlpSpan['attributes'] }>\n status?: { code: number; message?: string }\n}\n\nexport interface OtlpResourceSpans {\n resource: { attributes: OtlpSpan['attributes'] }\n scopeSpans: Array<{ scope: typeof OTEL_AGENT_EVAL_SCOPE; spans: OtlpSpan[] }>\n}\n\nexport interface OtlpExport {\n resourceSpans: OtlpResourceSpans[]\n}\n\n/** Export a single run's spans + events in OTLP/JSON. */\nexport async function exportRunAsOtlp(\n store: TraceStore,\n runId: string,\n resourceAttrs: Record<string, string | number | boolean> = {},\n): Promise<OtlpExport> {\n const run = await store.getRun(runId)\n if (!run) throw new Error(`run ${runId} not found`)\n const spans = await store.spans({ runId })\n const events = await store.events({ runId })\n const eventsBySpan = new Map<string, TraceEvent[]>()\n for (const e of events) {\n if (!e.spanId) continue\n const arr = eventsBySpan.get(e.spanId) ?? []\n arr.push(e)\n eventsBySpan.set(e.spanId, arr)\n }\n const traceId = runToTraceId(run)\n const otlpSpans: OtlpSpan[] = spans.map((s) =>\n spanToOtlp(s, traceId, eventsBySpan.get(s.spanId) ?? []),\n )\n return {\n resourceSpans: [\n {\n resource: {\n attributes: toAttributes({\n 'service.name': 'agent-eval',\n 'run.id': run.runId,\n 'run.scenario_id': run.scenarioId,\n 'run.variant_id': run.variantId ?? '',\n 'run.dataset_version': run.datasetVersion ?? '',\n 'run.code_sha': run.codeSha ?? '',\n 'run.model_fingerprint': run.modelFingerprint ?? '',\n ...resourceAttrs,\n }),\n },\n scopeSpans: [{ scope: OTEL_AGENT_EVAL_SCOPE, spans: otlpSpans }],\n },\n ],\n }\n}\n\nfunction spanToOtlp(span: Span, traceId: string, events: TraceEvent[]): OtlpSpan {\n const endedAt = span.endedAt ?? span.startedAt\n return {\n traceId,\n spanId: padSpanId(span.spanId),\n parentSpanId: span.parentSpanId ? padSpanId(span.parentSpanId) : undefined,\n name: span.name,\n kind: 1, // SPAN_KIND_INTERNAL\n startTimeUnixNano: msToNs(span.startedAt),\n endTimeUnixNano: msToNs(endedAt),\n attributes: toAttributes(flattenSpanAttributes(span)),\n events: events.map((e) => ({\n timeUnixNano: msToNs(e.timestamp),\n name: e.kind,\n attributes: toAttributes(flattenPayload(e.payload)),\n })),\n status: span.status === 'error' ? { code: 2, message: span.error } : { code: 1 },\n }\n}\n\nfunction flattenSpanAttributes(span: Span): Record<string, string | number | boolean> {\n const base: Record<string, string | number | boolean> = {}\n if (span.attributes) {\n for (const [k, v] of Object.entries(span.attributes)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') base[k] = v\n }\n }\n base[OPENINFERENCE_SPAN_KIND] = traceSpanKindToOpenInferenceKind(span.kind)\n if (span.kind === 'llm') {\n applyLlmSpanOtlpAttributes(base, span)\n } else if (span.kind === 'tool') {\n applyToolSpanOtlpAttributes(base, span)\n } else if (span.kind === 'retrieval') {\n base['retrieval.query'] = span.query\n base['retrieval.hits'] = span.hits.length\n } else if (span.kind === 'judge') {\n base['judge.id'] = span.judgeId\n base['judge.dimension'] = span.dimension\n base['judge.score'] = span.score\n base['judge.target_span_id'] = span.targetSpanId\n } else if (span.kind === 'sandbox') {\n if (span.image) base['sandbox.image'] = span.image\n if (span.exitCode !== undefined) base['sandbox.exit_code'] = span.exitCode\n if (span.testsPassed !== undefined) base['sandbox.tests_passed'] = span.testsPassed\n if (span.testsTotal !== undefined) base['sandbox.tests_total'] = span.testsTotal\n }\n return base\n}\n\nfunction flattenPayload(\n payload: Record<string, unknown>,\n): Record<string, string | number | boolean> {\n const out: Record<string, string | number | boolean> = {}\n for (const [k, v] of Object.entries(payload)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') out[k] = v\n else out[k] = JSON.stringify(v)\n }\n return out\n}\n\nfunction toAttributes(record: Record<string, string | number | boolean>): OtlpSpan['attributes'] {\n return Object.entries(record).map(([key, value]) => ({\n key,\n value:\n typeof value === 'number'\n ? Number.isInteger(value)\n ? { intValue: value.toString() }\n : { doubleValue: value }\n : typeof value === 'boolean'\n ? { boolValue: value }\n : { stringValue: value },\n }))\n}\n\nfunction msToNs(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n\nfunction padSpanId(id: string): string {\n // OTLP wants 16-hex spanIds. UUIDs are 32-hex; strip dashes and take first 16.\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 16).padEnd(16, '0')\n}\n\nfunction runToTraceId(run: Run): string {\n // OTLP wants 32-hex traceIds. Use runId directly when it's 32-hex already,\n // else SHA-ish truncate.\n const cleaned = run.runId.replace(/-/g, '')\n return cleaned.slice(0, 32).padEnd(32, '0')\n}\n","/**\n * OTEL bridge — connects TraceEmitter span lifecycle to the OtelExporter.\n *\n * When an OtelExporter is active, every span that closes through the\n * TraceEmitter is also pushed to the exporter for real-time streaming to\n * the user's OTEL collector.\n *\n * The bridge is opt-in: attach via `otelRunCompleteHook(exporter)` as a\n * RunCompleteHook, or wrap the store with `createOtelTracingStore` for\n * real-time per-span export.\n */\n\nimport type { RunCompleteHook } from './emitter'\nimport type { ExportableSpan, OtelExporter } from './otel-export'\nimport type { LlmSpan, Span, ToolSpan } from './schema'\nimport type { TraceStore } from './store'\n\n/**\n * Create a RunCompleteHook that exports all spans from the completed run\n * to the OTEL exporter, then flushes.\n */\nexport function otelRunCompleteHook(exporter: OtelExporter): RunCompleteHook {\n return async (ctx) => {\n const spans = await ctx.store.spans({ runId: ctx.runId })\n for (const span of spans) {\n if (span.endedAt) {\n exporter.exportSpan(storeSpanToExportable(span, ctx.runId))\n }\n }\n await exporter.flush()\n }\n}\n\n/**\n * Create an auto-exporting TraceStore wrapper that intercepts updateSpan\n * calls. When a span gets an endedAt, it's exported immediately. This\n * gives real-time streaming instead of batch-at-end.\n *\n * This is the preferred integration path: wrap the store before\n * constructing the TraceEmitter.\n */\nexport function createOtelTracingStore(\n inner: TraceStore,\n exporter: OtelExporter,\n traceId: string,\n): TraceStore {\n return {\n async appendRun(run) {\n return inner.appendRun(run)\n },\n async updateRun(runId, patch) {\n return inner.updateRun(runId, patch)\n },\n async appendSpan(span) {\n if (span.endedAt) {\n exporter.exportSpan(storeSpanToExportable(span, traceId))\n }\n return inner.appendSpan(span)\n },\n async updateSpan(spanId, patch) {\n await inner.updateSpan(spanId, patch)\n if (patch.endedAt) {\n const spans = await inner.spans({ runId: traceId })\n const found = spans.find((s) => s.spanId === spanId)\n if (found) {\n exporter.exportSpan(storeSpanToExportable(found, traceId))\n }\n }\n },\n async appendEvent(event) {\n return inner.appendEvent(event)\n },\n async appendBudgetEntry(entry) {\n return inner.appendBudgetEntry(entry)\n },\n async appendArtifact(artifact) {\n return inner.appendArtifact(artifact)\n },\n getRun: inner.getRun.bind(inner),\n listRuns: inner.listRuns.bind(inner),\n spans: inner.spans.bind(inner),\n events: inner.events.bind(inner),\n budget: inner.budget.bind(inner),\n artifacts: inner.artifacts.bind(inner),\n }\n}\n\nfunction storeSpanToExportable(span: Span, traceId: string): ExportableSpan {\n const llm = span.kind === 'llm' ? (span as LlmSpan) : undefined\n const tool = span.kind === 'tool' ? (span as ToolSpan) : undefined\n return {\n traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n name: span.name,\n kind: span.kind,\n startedAt: span.startedAt,\n endedAt: span.endedAt,\n status: span.status,\n error: span.error,\n model: llm?.model,\n inputTokens: llm?.inputTokens,\n outputTokens: llm?.outputTokens,\n reasoningTokens: llm?.reasoningTokens,\n cachedTokens: llm?.cachedTokens,\n cacheWriteTokens: llm?.cacheWriteTokens,\n costUsd: llm?.costUsd,\n tool: tool\n ? {\n toolName: tool.toolName,\n args: tool.args,\n argsCaptured: tool.argsCaptured,\n result: tool.result,\n latencyMs: tool.latencyMs,\n }\n : undefined,\n attributes: span.attributes as Record<string, unknown> | undefined,\n }\n}\n","/**\n * OTEL span exporter — streams spans to an OTLP/HTTP collector.\n *\n * Reads OTEL_EXPORTER_OTLP_ENDPOINT + OTEL_EXPORTER_OTLP_HEADERS from env\n * when no explicit config is given. Batches spans and flushes periodically\n * or when the batch fills. No @opentelemetry SDK dependency — minimal\n * OTLP/JSON serializer (~120 LOC) using the existing otel.ts helpers.\n */\n\nimport { OTEL_AGENT_EVAL_SCOPE, type OtlpExport, type OtlpSpan } from './otel'\nimport {\n applyLlmSpanOtlpAttributes,\n applyToolSpanOtlpAttributes,\n OPENINFERENCE_SPAN_KIND,\n type ToolSpanOtlpInput,\n traceSpanKindToOpenInferenceKind,\n} from './otlp-attributes'\n\nexport interface OtelExportConfig {\n /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */\n endpoint?: string\n /** OTLP headers. Reads OTEL_EXPORTER_OTLP_HEADERS env by default. */\n headers?: Record<string, string>\n /** Batch size before flush. Default 64. */\n batchSize?: number\n /** Flush interval ms. Default 5000. */\n flushIntervalMs?: number\n /** Resource attributes stamped on every export. */\n resourceAttributes?: Record<string, string | number | boolean>\n /** Service name. Default 'agent-eval'. */\n serviceName?: string\n}\n\nexport interface OtelExporter {\n /** Called by the TraceEmitter on every span close. */\n exportSpan(span: ExportableSpan): void\n /** Force flush pending spans. */\n flush(): Promise<void>\n /** Shutdown cleanly — flushes remaining spans and stops the timer. */\n shutdown(): Promise<void>\n}\n\nexport interface ExportableSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind: string\n startedAt: number\n endedAt?: number\n status?: string\n error?: string\n model?: string\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n cachedTokens?: number\n cacheWriteTokens?: number\n costUsd?: number\n tool?: ToolSpanOtlpInput\n attributes?: Record<string, unknown>\n}\n\n/**\n * Create an OTEL exporter. Returns undefined when no endpoint is configured\n * (neither via config nor env) — callers should check before attaching.\n */\nexport function createOtelExporter(config?: OtelExportConfig): OtelExporter | undefined {\n const resolvedEndpoint =\n config?.endpoint ??\n (typeof process !== 'undefined' ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : undefined)\n if (!resolvedEndpoint) return undefined\n const endpoint: string = resolvedEndpoint\n\n const headers = config?.headers ?? parseHeadersFromEnv()\n const batchSize = config?.batchSize ?? 64\n const flushIntervalMs = config?.flushIntervalMs ?? 5000\n const serviceName = config?.serviceName ?? 'agent-eval'\n const resourceAttrs = config?.resourceAttributes ?? {}\n\n const pending: OtlpSpan[] = []\n let timer: ReturnType<typeof setInterval> | undefined\n let stopped = false\n\n const exporter: OtelExporter = {\n exportSpan(span: ExportableSpan): void {\n if (stopped) return\n pending.push(toOtlpSpan(span))\n if (pending.length >= batchSize) {\n void doFlush()\n }\n },\n\n async flush(): Promise<void> {\n await doFlush()\n },\n\n async shutdown(): Promise<void> {\n stopped = true\n if (timer !== undefined) {\n clearInterval(timer)\n timer = undefined\n }\n await doFlush()\n },\n }\n\n timer = setInterval(() => {\n if (pending.length > 0) void doFlush()\n }, flushIntervalMs)\n // Unref so the timer doesn't keep the process alive.\n if (typeof timer === 'object' && 'unref' in timer) {\n ;(timer as NodeJS.Timeout).unref()\n }\n\n async function doFlush(): Promise<void> {\n if (pending.length === 0) return\n const batch = pending.splice(0)\n const body: OtlpExport = {\n resourceSpans: [\n {\n resource: {\n attributes: toAttributes({\n 'service.name': serviceName,\n ...resourceAttrs,\n }),\n },\n scopeSpans: [{ scope: OTEL_AGENT_EVAL_SCOPE, spans: batch }],\n },\n ],\n }\n const url = `${endpoint.replace(/\\/+$/, '')}/v1/traces`\n try {\n await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...headers,\n },\n body: JSON.stringify(body),\n })\n } catch {\n // Best-effort — telemetry export must not crash the pipeline.\n }\n }\n\n return exporter\n}\n\nfunction parseHeadersFromEnv(): Record<string, string> {\n if (typeof process === 'undefined') return {}\n const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS\n if (!raw) return {}\n const out: Record<string, string> = {}\n for (const pair of raw.split(',')) {\n const eq = pair.indexOf('=')\n if (eq < 0) continue\n const key = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n if (key) out[key] = value\n }\n return out\n}\n\nfunction toOtlpSpan(span: ExportableSpan): OtlpSpan {\n const endedAt = span.endedAt ?? span.startedAt\n const attrs: Record<string, string | number | boolean> = {}\n if (span.attributes) {\n for (const [k, v] of Object.entries(span.attributes)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') attrs[k] = v\n }\n }\n attrs[OPENINFERENCE_SPAN_KIND] = traceSpanKindToOpenInferenceKind(span.kind)\n applyLlmSpanOtlpAttributes(attrs, span)\n if (span.tool) applyToolSpanOtlpAttributes(attrs, span.tool)\n return {\n traceId: padTraceId(span.traceId),\n spanId: padSpanId(span.spanId),\n parentSpanId: span.parentSpanId ? padSpanId(span.parentSpanId) : undefined,\n name: span.name,\n kind: 1, // SPAN_KIND_INTERNAL\n startTimeUnixNano: msToNs(span.startedAt),\n endTimeUnixNano: msToNs(endedAt),\n attributes: toAttributes(attrs),\n status: span.status === 'error' ? { code: 2, message: span.error } : { code: 1 },\n }\n}\n\nfunction toAttributes(record: Record<string, string | number | boolean>): OtlpSpan['attributes'] {\n return Object.entries(record).map(([key, value]) => ({\n key,\n value:\n typeof value === 'number'\n ? Number.isInteger(value)\n ? { intValue: value.toString() }\n : { doubleValue: value }\n : typeof value === 'boolean'\n ? { boolValue: value }\n : { stringValue: value },\n }))\n}\n\nfunction msToNs(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n\nfunction padSpanId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 16).padEnd(16, '0')\n}\n\nfunction padTraceId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 32).padEnd(32, '0')\n}\n","/**\n * Convert agent-eval's internal trace shape (`FileSystemTraceStore` → `Run`,\n * `Span`, `TraceEvent`) into the OTLP-flat JSONL the trace analyst\n * (`analyzeTraces` + `OtlpFileTraceStore`) reads.\n *\n * Eval harnesses shard a `FileSystemTraceStore` per cell (persona / variant)\n * under a run directory. The analyst consumes a single OTLP-NDJSON file keyed\n * on `trace_id` + `span_id` with `start_time`/`end_time` in ISO-8601 and\n * resource + `attributes` rolled up per-span. This module walks every shard,\n * projects each `Span` (plus events pinned to it) into the flat OTLP shape,\n * and emits one NDJSON file.\n *\n * Generic OTLP/OpenInference fields are always emitted (`service.name`,\n * `agent.name`, `run.id`/`run.status`, `openinference.span.kind`,\n * `llm.model_name`, …). Domain attributes (`legal.*`, `tax.*`, …) are injected\n * per-run via {@link TraceStoreToOtlpOptions.resourceAttributes} /\n * {@link TraceStoreToOtlpOptions.runAttributes} so consumers don't re-roll the\n * walker.\n */\n\nimport { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport {\n applyLlmSpanOtlpAttributes,\n applyToolSpanOtlpAttributes,\n OPENINFERENCE_SPAN_KIND,\n traceSpanKindToOpenInferenceKind,\n} from './otlp-attributes'\nimport { createOtlpFlatLine, epochMillisToIso, spanStatusToOtlp } from './otlp-flat'\nimport type { Run, Span, TraceEvent } from './schema'\n\n/** Marker `FileSystemTraceStore` stamps on partial-update NDJSON rows. */\ninterface MaybeUpdate {\n _update?: boolean\n}\n\nexport interface TracesToOtlpResult {\n /** Total spans emitted across every cell. */\n spanCount: number\n /** Total run-anchor spans (one per Run) appended for analyst visibility. */\n runCount: number\n /** Cells whose shards parsed cleanly. */\n cellCount: number\n /** Cells that errored mid-conversion — surfaced so a partial conversion\n * isn't silently masked. */\n cellErrorCount: number\n}\n\n/**\n * A trace source the analyst should ingest. Two layouts are supported:\n *\n * - `celled` (default): the root holds one cell subdirectory per\n * persona/variant, each a `FileSystemTraceStore` (`runs.ndjson`,\n * `spans.ndjson`, `events.ndjson`).\n * - `flat`: the root is itself a single `FileSystemTraceStore` (e.g. a\n * production-ingestion sidecar that appends one ndjson set directly under\n * the chosen directory).\n */\nexport interface TraceStoreSource {\n /** Absolute path to the trace store root. */\n root: string\n /** Layout — `celled` (default) or `flat`. */\n layout?: 'celled' | 'flat'\n /** OTLP `service.name` for this source. Overrides the options default. */\n serviceName?: string\n}\n\n/** Domain hooks. The walker is generic; consumers inject the namespaced\n * attributes that ride along on every run + span for analyst discovery. */\nexport interface TraceStoreToOtlpOptions {\n /** Default OTLP `service.name` when a source doesn't set its own.\n * Default `agent-eval`. */\n serviceName?: string\n /** Extra resource attributes per run, e.g.\n * `(run) => ({ 'legal.persona_id': run.tags?.personaId ?? '' })`. */\n resourceAttributes?: (run: Run) => Record<string, unknown>\n /** Extra attributes on the per-run anchor span, e.g. domain outcome fields. */\n runAttributes?: (run: Run) => Record<string, unknown>\n}\n\n/**\n * Read every per-cell shard under each source root and write a flat OTLP-JSONL\n * view of the corpus to `outPath`. Each cell directory is a\n * `FileSystemTraceStore` — NDJSON append-only with size-based rotation;\n * `updateRun`/`updateSpan` append `{ id, ...patch, _update: true }` rows\n * rather than rewriting, so readers must merge those patches in (done here).\n *\n * A `string` source is treated as a celled root.\n */\nexport function convertTraceStoresToOtlp(\n source: string | TraceStoreSource | readonly TraceStoreSource[],\n outPath: string,\n opts: TraceStoreToOtlpOptions = {},\n): TracesToOtlpResult {\n const sources: TraceStoreSource[] = Array.isArray(source)\n ? [...source]\n : typeof source === 'string'\n ? [{ root: source, layout: 'celled' }]\n : [source as TraceStoreSource]\n\n const defaultServiceName = opts.serviceName ?? 'agent-eval'\n const resourceAttributes = opts.resourceAttributes ?? (() => ({}))\n const runAttributes = opts.runAttributes ?? (() => ({}))\n\n const lines: string[] = []\n let spanCount = 0\n let runCount = 0\n let cellCount = 0\n let cellErrorCount = 0\n\n for (const src of sources) {\n const serviceName = src.serviceName ?? defaultServiceName\n const cellDirs: Array<{ label: string; dir: string }> =\n src.layout === 'flat'\n ? [{ label: '<root>', dir: src.root }]\n : listCells(src.root).map((name) => ({ label: name, dir: join(src.root, name) }))\n\n for (const cell of cellDirs) {\n try {\n const result = projectCell({\n cellDir: cell.dir,\n serviceName,\n resourceAttributes,\n runAttributes,\n })\n for (const line of result.lines) lines.push(line)\n spanCount += result.spanCount\n runCount += result.runCount\n cellCount += 1\n } catch (err) {\n console.warn(\n `[traces-to-otlp] cell ${cell.label} (${cell.dir}) skipped: ${err instanceof Error ? err.message : String(err)}`,\n )\n cellErrorCount += 1\n }\n }\n }\n\n writeFileSync(outPath, lines.join('\\n') + (lines.length > 0 ? '\\n' : ''))\n return { spanCount, runCount, cellCount, cellErrorCount }\n}\n\ninterface ProjectCellResult {\n lines: string[]\n runCount: number\n spanCount: number\n}\n\nfunction projectCell(args: {\n cellDir: string\n serviceName: string\n resourceAttributes: (run: Run) => Record<string, unknown>\n runAttributes: (run: Run) => Record<string, unknown>\n}): ProjectCellResult {\n const { cellDir, serviceName, resourceAttributes, runAttributes } = args\n const lines: string[] = []\n let runCount = 0\n let spanCount = 0\n\n const runs = readMergedShards<Run & MaybeUpdate>(cellDir, 'runs', 'runId')\n const spans = readMergedShards<Span & MaybeUpdate>(cellDir, 'spans', 'spanId')\n const events = readShards<TraceEvent>(cellDir, 'events')\n\n const runByRunId = new Map<string, Run>()\n for (const r of runs) runByRunId.set(r.runId, r)\n const spanBySpanId = new Map<string, Span>()\n for (const s of spans) spanBySpanId.set(s.spanId, s)\n const eventsBySpanId = new Map<string, TraceEvent[]>()\n\n // An HTTP-backed trace store can only POST `TraceEvent`s through the wire;\n // run/span lifecycle is projected into `state_mutation` events with\n // `payload.entity ∈ { run, run.update, span, span.update }`. Fold those back\n // so the analyst sees a complete Run + Span tree.\n for (const e of events) {\n if (e.kind === 'state_mutation' && e.payload && typeof e.payload === 'object') {\n const entity = (e.payload as Record<string, unknown>).entity\n if (entity === 'run') {\n const run = (e.payload as { run?: Run }).run\n if (run?.runId) runByRunId.set(run.runId, run)\n continue\n }\n if (entity === 'run.update') {\n const patch = (e.payload as { patch?: Partial<Run> }).patch\n if (patch && e.runId) {\n const prior = runByRunId.get(e.runId)\n if (prior) runByRunId.set(e.runId, { ...prior, ...patch })\n }\n continue\n }\n if (entity === 'span') {\n const span = (e.payload as { span?: Span }).span\n if (span?.spanId) spanBySpanId.set(span.spanId, span)\n continue\n }\n if (entity === 'span.update') {\n const spanId = (e.payload as { spanId?: string }).spanId\n const patch = (e.payload as { patch?: Partial<Span> }).patch\n if (spanId && patch) {\n const prior = spanBySpanId.get(spanId)\n if (prior) spanBySpanId.set(spanId, { ...prior, ...patch } as Span)\n }\n continue\n }\n }\n if (!e.spanId) continue\n const arr = eventsBySpanId.get(e.spanId) ?? []\n arr.push(e)\n eventsBySpanId.set(e.spanId, arr)\n }\n\n for (const run of runByRunId.values()) {\n const traceId = padTraceId(run.runId)\n const agentName = run.variantId ?? run.scenarioId\n const sharedResource = {\n attributes: {\n 'service.name': serviceName,\n 'agent.name': agentName,\n 'run.id': run.runId,\n 'run.status': run.status,\n ...resourceAttributes(run),\n },\n }\n\n const runSpanId = padSpanId(`run-${run.runId}`)\n const runStart = msToIso(run.startedAt)\n const runEnd = msToIso(run.endedAt ?? run.startedAt)\n const runStatus =\n run.outcome?.failureClass && run.outcome.failureClass !== 'success'\n ? 'STATUS_CODE_ERROR'\n : 'STATUS_CODE_OK'\n const runAttrs: Record<string, unknown> = {\n [OPENINFERENCE_SPAN_KIND]: 'AGENT',\n 'agent.name': agentName,\n 'agent.workflow.name': serviceName,\n ...runAttributes(run),\n }\n lines.push(\n JSON.stringify(\n toLine({\n traceId,\n spanId: runSpanId,\n parentSpanId: '',\n name: `run.${agentName}`,\n kind: 'SPAN_KIND_INTERNAL',\n startTime: runStart,\n endTime: runEnd,\n statusCode: runStatus,\n statusMessage: run.outcome?.notes ?? '',\n resource: sharedResource,\n attributes: runAttrs,\n }),\n ),\n )\n runCount += 1\n\n for (const span of spanBySpanId.values()) {\n if (span.runId !== run.runId) continue\n const spanAttrs = spanToAttributes(span, eventsBySpanId.get(span.spanId) ?? [])\n const statusCode = spanStatusToOtlp(span.status, span.error, 'STATUS_CODE_OK')\n lines.push(\n JSON.stringify(\n toLine({\n traceId,\n spanId: padSpanId(span.spanId),\n parentSpanId: span.parentSpanId ? padSpanId(span.parentSpanId) : runSpanId,\n name: span.name,\n kind: spanKindToOtlpKind(span.kind),\n startTime: msToIso(span.startedAt),\n endTime: msToIso(span.endedAt ?? span.startedAt),\n statusCode,\n statusMessage: span.error ?? '',\n resource: sharedResource,\n attributes: spanAttrs,\n }),\n ),\n )\n spanCount += 1\n }\n }\n\n return { lines, runCount, spanCount }\n}\n\nfunction listCells(root: string): string[] {\n try {\n return readdirSync(root, { withFileTypes: true })\n .filter((d) => d.isDirectory())\n .map((d) => d.name)\n .sort()\n } catch {\n return []\n }\n}\n\n/**\n * Read every NDJSON shard for `name` under `cellDir`, ordered by mtime so\n * rotated files apply before the active one. Yields raw rows including any\n * `_update: true` patches.\n */\nfunction readShards<T>(cellDir: string, name: string): T[] {\n let entries: string[]\n try {\n entries = readdirSync(cellDir)\n } catch {\n return []\n }\n const shards = entries\n .filter((f) => (f === `${name}.ndjson` || f.startsWith(`${name}.`)) && f.endsWith('.ndjson'))\n .map((f) => ({ file: f, path: join(cellDir, f) }))\n .map((s) => {\n let mtime = 0\n try {\n mtime = statSync(s.path).mtimeMs\n } catch {\n /* skip stat errors */\n }\n return { ...s, mtime }\n })\n .sort((a, b) => a.mtime - b.mtime || a.file.localeCompare(b.file))\n\n const rows: T[] = []\n for (const shard of shards) {\n let text: string\n try {\n text = readFileSync(shard.path, 'utf-8')\n } catch {\n continue\n }\n for (const line of text.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed) continue\n try {\n rows.push(JSON.parse(trimmed) as T)\n } catch {\n /* skip partial line */\n }\n }\n }\n return rows\n}\n\n/**\n * Read NDJSON shards and merge `{ ...patch, _update: true }` rows into the\n * prior record keyed on `idKey` — mirrors the in-memory merge\n * `FileSystemTraceStore` keeps but doesn't replay on cross-process load.\n */\nfunction readMergedShards<T extends { _update?: boolean }>(\n cellDir: string,\n name: string,\n idKey: keyof T,\n): T[] {\n const rows = readShards<T>(cellDir, name)\n const byId = new Map<string, T>()\n for (const row of rows) {\n const id = row[idKey] as unknown as string\n if (!id) continue\n const prior = byId.get(id)\n if (prior && row._update) {\n byId.set(id, { ...prior, ...row, _update: undefined } as T)\n } else {\n byId.set(id, row)\n }\n }\n return [...byId.values()]\n}\n\nfunction spanToAttributes(span: Span, events: TraceEvent[]): Record<string, unknown> {\n const attrs: Record<string, unknown> = {\n [OPENINFERENCE_SPAN_KIND]: traceSpanKindToOpenInferenceKind(span.kind),\n }\n if (span.kind === 'llm') {\n applyLlmSpanOtlpAttributes(attrs, span)\n if (Array.isArray(span.messages)) {\n attrs['llm.input_messages'] = JSON.stringify(span.messages.slice(-6))\n }\n if (typeof span.output === 'string') {\n attrs['llm.output_messages'] = JSON.stringify([{ role: 'assistant', content: span.output }])\n }\n } else if (span.kind === 'tool') {\n applyToolSpanOtlpAttributes(attrs, span)\n } else if (span.kind === 'judge') {\n attrs['judge.id'] = span.judgeId\n attrs['judge.dimension'] = span.dimension\n attrs['judge.score'] = span.score\n attrs['judge.target_span_id'] = span.targetSpanId\n }\n if (span.attributes) {\n for (const [k, v] of Object.entries(span.attributes)) {\n attrs[`agent_eval.${k}`] = v\n }\n }\n if (events.length > 0) {\n attrs['agent_eval.event_count'] = events.length\n attrs['agent_eval.event_kinds'] = JSON.stringify(events.map((e) => e.kind))\n }\n return attrs\n}\n\nfunction spanKindToOtlpKind(kind: Span['kind']): string {\n switch (kind) {\n case 'llm':\n return 'SPAN_KIND_CLIENT'\n case 'retrieval':\n return 'SPAN_KIND_CLIENT'\n default:\n return 'SPAN_KIND_INTERNAL'\n }\n}\n\nconst toLine = createOtlpFlatLine\n\nfunction msToIso(ms: number): string {\n if (ms <= 0) return new Date(0).toISOString()\n return epochMillisToIso(ms) ?? new Date(0).toISOString()\n}\n\n/** OTLP wants 16-hex span ids; eval traces use UUID-ish strings. Hex-strip +\n * take 16, else deterministic FNV fold. */\nfunction padSpanId(id: string): string {\n const cleaned = id.replace(/[^a-f0-9]/gi, '').toLowerCase()\n if (cleaned.length >= 16) return cleaned.slice(0, 16)\n return foldTo16Hex(id)\n}\n\n/** OTLP wants 32-hex trace ids; fold deterministically when too short. */\nfunction padTraceId(id: string): string {\n const cleaned = id.replace(/[^a-f0-9]/gi, '').toLowerCase()\n if (cleaned.length >= 32) return cleaned.slice(0, 32)\n return foldTo32Hex(id)\n}\n\nfunction foldTo16Hex(s: string): string {\n let h1 = 0x811c9dc5\n for (const ch of s) {\n h1 ^= ch.charCodeAt(0)\n h1 = Math.imul(h1, 0x01000193) >>> 0\n }\n const part = h1.toString(16).padStart(8, '0')\n return (part + part).slice(0, 16)\n}\n\nfunction foldTo32Hex(s: string): string {\n return foldTo16Hex(s) + foldTo16Hex(`${s}::trace`).slice(0, 16)\n}\n","/**\n * Replay-from-raw-events — turn every captured campaign run into a\n * re-runnable artifact.\n *\n * `RawProviderSink` captures every provider HTTP envelope; `runEvalCampaign`\n * makes that capture the default. Together they make every past run a\n * complete fingerprint of what happened on the wire — enough to replay\n * the run without burning new LLM cost.\n *\n * Three use cases this primitive enables:\n *\n * 1. **Post-hoc judging** — apply a new judge / rubric / scoring callback\n * to last week's runs without re-calling any LLM. The cost of trying\n * a new rubric drops from \"another full sweep\" to a CPU-bound replay.\n * 2. **Determinism audits** — replay the same campaign and verify the\n * raw responses match byte-for-byte. Any drift is a non-determinism\n * bug (in the harness, the prompt builder, the sandbox, …).\n * 3. **Free judge calibration** — run two judges on identical responses\n * and measure inter-judge agreement without doubling LLM spend.\n *\n * The interface is deliberately fetch-shaped. Inject `createReplayFetch`\n * into `LlmClientOptions.fetch` and every `callLlm` transparently reads\n * from the cache instead of calling the network. No new code path through\n * the LLM client is needed; the cache hit is invisible to the runner.\n */\n\nimport { ReplayError } from './errors'\nimport { canonicalize, hashJson } from './pre-registration'\nimport type { RawProviderEvent, RawProviderSink } from './trace/raw-provider-sink'\n\nexport class ReplayCacheMissError extends ReplayError {\n constructor(\n public readonly url: string,\n public readonly requestKey: string,\n message?: string,\n ) {\n super(message ?? `replay cache miss for ${url} (key=${requestKey})`)\n }\n}\n\nexport interface ReplayCacheEntry {\n request: RawProviderEvent\n response: RawProviderEvent\n}\n\nexport interface ReplayCacheStats {\n total: number\n byProvider: Record<string, number>\n byModel: Record<string, number>\n /** Spans for which we have a request but no response (run aborted mid-call). */\n orphanRequests: number\n}\n\n/**\n * In-memory deterministic cache of (request → response) keyed on a stable\n * hash of the request body. Built from a `RawProviderSink` containing\n * paired `request` and `response` events from a previous run.\n *\n * The cache is the source of truth for replay; `createReplayFetch` is a\n * thin wrapper that reads from it.\n */\nexport class ReplayCache {\n private byKey = new Map<string, ReplayCacheEntry>()\n private orphans = 0\n private byProvider: Record<string, number> = {}\n private byModel: Record<string, number> = {}\n\n /**\n * Build a cache from a sink's events. The sink must implement `list()`.\n * Filter by `runId` / `spanId` to scope to a specific replay.\n */\n static async fromSink(\n sink: RawProviderSink,\n filter: { runId?: string; spanId?: string } = {},\n ): Promise<ReplayCache> {\n if (!sink.list) {\n throw new ReplayError('ReplayCache.fromSink: sink must implement list() to be replayable.')\n }\n const events = await sink.list(filter)\n return ReplayCache.fromEvents(events)\n }\n\n /** Build a cache from an in-memory event list. */\n static async fromEvents(events: RawProviderEvent[]): Promise<ReplayCache> {\n const cache = new ReplayCache()\n // Group by (runId, spanId, attemptIndex) so request/response/error pairs are matched.\n // A cell can have many spans; each retry attempt within a span is a separate group.\n type GroupKey = string\n const groups = new Map<GroupKey, { req?: RawProviderEvent; res?: RawProviderEvent }>()\n for (const e of events) {\n const k = `${e.runId ?? ''}::${e.spanId ?? ''}::${e.attemptIndex}`\n const g = groups.get(k) ?? {}\n if (e.direction === 'request') g.req = e\n else g.res = e\n groups.set(k, g)\n }\n for (const g of groups.values()) {\n if (!g.req) continue\n if (!g.res) {\n cache.orphans += 1\n continue\n }\n const key = await requestKey(g.req)\n cache.byKey.set(key, { request: g.req, response: g.res })\n cache.byProvider[g.req.provider] = (cache.byProvider[g.req.provider] ?? 0) + 1\n cache.byModel[g.req.model] = (cache.byModel[g.req.model] ?? 0) + 1\n }\n return cache\n }\n\n /** Number of cacheable (request, response) pairs in the cache. */\n size(): number {\n return this.byKey.size\n }\n\n stats(): ReplayCacheStats {\n return {\n total: this.byKey.size,\n byProvider: { ...this.byProvider },\n byModel: { ...this.byModel },\n orphanRequests: this.orphans,\n }\n }\n\n /** Iterate every cached `(request, response)` pair in insertion order. */\n *entries(): IterableIterator<ReplayCacheEntry> {\n for (const entry of this.byKey.values()) yield entry\n }\n\n /**\n * Look up a cached response by hashing the (model, messages, temperature,\n * maxTokens, response_format) shape. Returns `undefined` on miss; the\n * caller decides whether to throw, fall back to the network, or skip.\n */\n async lookup(requestBody: unknown): Promise<ReplayCacheEntry | undefined> {\n const key = await keyFromBody(requestBody)\n return this.byKey.get(key)\n }\n}\n\nexport interface ReplayFetchOptions {\n /**\n * Behaviour on cache miss. Default `'throw'`. `'fallback'` calls the\n * `fallbackFetch` (typically `globalThis.fetch`) so a partial replay can\n * still complete; `'fail-closed'` returns a synthetic 599 response so the\n * call site sees a non-retriable failure.\n */\n onMiss?: 'throw' | 'fallback' | 'fail-closed'\n fallbackFetch?: typeof fetch\n /** Optional callback fired once per replayed call (for telemetry / counters). */\n onHit?: (info: { url: string; provider: string; model: string }) => void\n /** Optional callback fired on cache miss before the `onMiss` policy applies. */\n onMissNotify?: (info: { url: string; requestBody: unknown }) => void\n}\n\n/**\n * Build a `fetch`-shaped function that serves cached responses out of a\n * `ReplayCache` for any URL ending in `/chat/completions`. Pass through\n * `LlmClientOptions.fetch` and `callLlm` becomes free.\n *\n * Non-`/chat/completions` URLs are passed straight to the fallback fetch\n * (default: `globalThis.fetch`). This matters because non-LLM HTTP work\n * (judge HTTP servers, sandbox callbacks) sometimes flows through the same\n * `fetch` and shouldn't be intercepted.\n */\nexport function createReplayFetch(cache: ReplayCache, opts: ReplayFetchOptions = {}): typeof fetch {\n const onMiss = opts.onMiss ?? 'throw'\n const fallback = opts.fallbackFetch ?? globalThis.fetch?.bind(globalThis)\n\n return (async (input: RequestInfo | URL, init?: RequestInit) => {\n const url =\n typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url\n if (!/\\/chat\\/completions(?:[?#].*)?$/.test(url)) {\n if (!fallback)\n throw new ReplayError(\n `replay fetch: non-completions URL ${url} but no fallbackFetch configured`,\n )\n return fallback(input as RequestInfo, init)\n }\n let bodyParsed: unknown\n if (init?.body && typeof init.body === 'string') {\n try {\n bodyParsed = JSON.parse(init.body)\n } catch {\n /* raw body, not JSON */\n }\n }\n const hit = bodyParsed === undefined ? undefined : await cache.lookup(bodyParsed)\n if (hit) {\n opts.onHit?.({ url, provider: hit.request.provider, model: hit.request.model })\n const status = hit.response.statusCode ?? 200\n const headers = new Headers(\n Object.entries(hit.response.responseHeaders ?? { 'Content-Type': 'application/json' }),\n )\n const bodyText =\n typeof hit.response.responseBody === 'string'\n ? hit.response.responseBody\n : JSON.stringify(hit.response.responseBody ?? {})\n return new Response(bodyText, { status, headers })\n }\n opts.onMissNotify?.({ url, requestBody: bodyParsed })\n if (onMiss === 'throw') {\n const key = bodyParsed === undefined ? '<unparseable>' : await keyFromBody(bodyParsed)\n throw new ReplayCacheMissError(url, key)\n }\n if (onMiss === 'fail-closed') {\n return new Response(JSON.stringify({ error: 'replay_cache_miss' }), { status: 599 })\n }\n if (!fallback)\n throw new ReplayError('replay fetch: onMiss=fallback but no fallbackFetch configured')\n return fallback(input as RequestInfo, init)\n }) as typeof fetch\n}\n\n/**\n * Convenience iterator over `(request, response)` pairs in a sink — for\n * post-hoc scoring that doesn't need a `fetch` shim. The judge or scorer\n * runs purely in-process over cached LLM outputs.\n */\nexport async function* iterateRawCalls(\n sink: RawProviderSink,\n filter: { runId?: string; spanId?: string } = {},\n): AsyncGenerator<ReplayCacheEntry> {\n if (!sink.list) {\n throw new ReplayError('iterateRawCalls: sink must implement list().')\n }\n const events = await sink.list(filter)\n const cache = await ReplayCache.fromEvents(events)\n for (const entry of cache.entries()) yield entry\n}\n\n// ── Hashing ──────────────────────────────────────────────────────────────\n\n/**\n * Canonical request key.\n *\n * `model + messages + temperature + max_tokens|max_completion_tokens +\n * response_format` are the dimensions that affect the response shape.\n * Other fields (timestamp headers, provider-specific metadata) are\n * intentionally excluded so a request hashes the same across re-runs.\n */\nasync function requestKey(event: RawProviderEvent): Promise<string> {\n return keyFromBody(event.requestBody)\n}\n\nasync function keyFromBody(body: unknown): Promise<string> {\n if (body == null || typeof body !== 'object') return hashJson({ raw: String(body) })\n const b = body as Record<string, unknown>\n const reduced = canonicalize({\n model: b.model ?? null,\n messages: b.messages ?? null,\n temperature: b.temperature ?? null,\n max_tokens: b.max_tokens ?? null,\n max_completion_tokens: b.max_completion_tokens ?? null,\n response_format: b.response_format ?? null,\n })\n return hashJson(reduced)\n}\n"],"mappings":";;;;;;;;;;;;;AAEA,MAAa,kCAAkC;;;;;;;;;;;;;AAc/C,MAAa,0CAA0C;;;;;;;;;ACmCvD,eAAsB,cACpB,OACA,SAC8B;CAC9B,IAAI,OAAO,MAAM,aAAa,YAAY,CAAC,MAAM,SAAS,KAAK,GAC7D,MAAM,IAAI,UAAU,0DAA0D;CAEhF,MAAM,KAAK,MAAM,IAAI,KAAK,KAAK;CAC/B,MAAM,QACJ,OAAO,QAAQ,WAAW,WACtB,IAAI,mBAAmB,EAAE,MAAM,QAAQ,OAAO,CAAC,IAC/C,QAAQ;CACd,IAAI,iBAAiB,oBACnB,MAAM,MAAM,cAAc,QAAQ,SAAS,EAAE,QAAQ,QAAQ,OAAO,IAAI,KAAA,CAAS;CAGnF,OAAO,gBAAgB;EACrB,YAAY;GACV;GACA,aACE,MAAM,aAAa,KAAK,KACxB;GACF,MAAM,MAAM,MAAM,KAAK,KAAK;GAC5B,SAAS;GACT,UAAU,MAAM;GAChB,cAAc,QAAQ,gBAAgB;GACtC,WAAW,QAAQ,aAAa;GAChC,QAAQ,QAAQ;EAClB;EACA,QAAQ,QAAQ;EAChB;EACA,SAAS;GACP,OAAO,QAAQ,SAAS;GACxB,eAAe,WAAW;GAC1B,WAAW,QAAQ;GACnB,YAAY,QAAQ;GACp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WAAW,OAA0C;CAClE,OAAO,YAAY,MAAM,WAAW;AACtC;AAEA,eAAe,YAAY,MAAgC;CACzD,IAAI,QAAQ,QAAQ,OAAO,SAAS,UAAU,OAAO,SAAS,EAAE,KAAK,OAAO,IAAI,EAAE,CAAC;CACnF,MAAM,IAAI;CASV,OAAO,SARS,aAAa;EAC3B,OAAO,EAAE,SAAS;EAClB,UAAU,EAAE,YAAY;EACxB,aAAa,EAAE,eAAe;EAC9B,YAAY,EAAE,cAAc;EAC5B,uBAAuB,EAAE,yBAAyB;EAClD,iBAAiB,EAAE,mBAAmB;CACxC,CACsB,CAAC;AACzB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"single-run-lock-CiQThJxB.js","names":["MAX_TIMER_DELAY_MS"],"sources":["../src/campaign/external-optimizer-contracts.ts","../src/campaign/external-optimizer-http.ts","../src/campaign/external-optimizer-model-proxy.ts","../src/campaign/external-optimizer-resources.ts","../src/campaign/external-optimizer-subprocess.ts","../src/campaign/search-ledger-errors.ts","../src/campaign/search-ledger-file.ts","../src/campaign/storage.ts","../src/campaign/single-run-lock.ts"],"sourcesContent":["import type { CustomTokenPricing } from '../cost-ledger'\nimport { costForTokenPricing } from '../cost-ledger'\n\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\n\nexport interface ExternalOptimizerRunnerCommand {\n command?: string\n args?: readonly string[]\n env?: NodeJS.ProcessEnv\n}\n\nexport type ExternalOptimizerResumeMode = 'never' | 'if-compatible' | 'required'\n\nexport type ExternalTextCandidate = string | Record<string, string>\n\nexport interface ExternalTextEvaluationRequest {\n candidate: ExternalTextCandidate\n exampleId: string\n}\n\nexport interface ExternalOptimizerCallback {\n url: string\n token: string\n evaluations: () => number\n close: () => Promise<void>\n}\n\nexport interface ExternalOptimizerModelBudget {\n /** Maximum optimizer-model spend, independent of task-evaluation spend. */\n maxCostUsd: number\n /** Network attempts, including provider retries. */\n maxRequests: number\n /** Reject a request body above this byte count. */\n maxRequestBytes: number\n /** Reject a provider response above this byte count. */\n maxResponseBytes: number\n /** Reject a request asking the provider for more output tokens. */\n maxOutputTokensPerRequest: number\n /**\n * Reasoning tokens a single response may bill beyond its completion limit.\n *\n * A reasoning model bounds only the completion by `max_tokens` and bills\n * thinking on top, so a reservation sized to the completion alone is always\n * too small and the ledger refuses the real charge. Callers that route a\n * reasoning model declare its thinking budget here; the reservation covers\n * it and a response exceeding it still fails loudly. Default: 0.\n */\n maxReasoningTokensPerRequest?: number\n /** Rates used to estimate cost when the provider omits a valid `usage.cost`. */\n pricing: CustomTokenPricing\n /** Per-provider-request deadline. Default: 300,000 ms. */\n requestTimeoutMs?: number\n}\n\nexport interface ExternalOptimizerModelProxy {\n /** OpenAI-compatible base URL supplied to the optimizer process. */\n baseUrl: string\n /** Ephemeral credential supplied only to the local proxy. */\n apiKey: string\n /** Provider requests admitted during this proxy process, including failures. */\n requestAttempts: () => number\n /** Complete successful provider responses recorded during this proxy process. */\n successfulCompletions: () => number\n close: () => Promise<void>\n}\n\nexport function isCandidateText(value: unknown, maxChars: number): value is string {\n return typeof value === 'string' && value.trim().length > 0 && value.length <= maxChars\n}\n\nexport function isExternalTextCandidate(value: unknown): value is ExternalTextCandidate {\n if (typeof value === 'string') return value.trim().length > 0\n if (!isRecord(value)) return false\n const entries = Object.entries(value)\n return (\n entries.length > 0 &&\n entries.every(\n ([name, content]) =>\n name.trim().length > 0 && name.trim() === name && typeof content === 'string',\n )\n )\n}\n\nexport function assertJsonValue(value: unknown, label: string, seen = new Set<object>()): void {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return\n if (typeof value === 'number' && Number.isFinite(value)) return\n if (Array.isArray(value)) {\n if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`)\n seen.add(value)\n for (const item of value) assertJsonValue(item, label, seen)\n seen.delete(value)\n return\n }\n if (typeof value === 'object') {\n if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`)\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must be JSON-serializable`)\n }\n seen.add(value)\n for (const item of Object.values(value)) assertJsonValue(item, label, seen)\n seen.delete(value)\n return\n }\n throw new Error(`${label} must be JSON-serializable`)\n}\n\nexport function assertNoCredentialValues(\n value: unknown,\n path: string,\n credentialLocation = 'runner.env',\n): void {\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n assertNoCredentialValues(item, `${path}[${index}]`, credentialLocation)\n }\n return\n }\n if (!isRecord(value)) return\n for (const [key, item] of Object.entries(value)) {\n if (isCredentialKey(key)) {\n throw new Error(`${path}.${key} must be supplied through ${credentialLocation}`)\n }\n assertNoCredentialValues(item, `${path}.${key}`, credentialLocation)\n }\n}\n\nexport function removeCredentialEnvironment(\n environment: Readonly<Record<string, string | undefined>>,\n): Record<string, string> {\n const sanitized: Record<string, string> = {}\n for (const [key, value] of Object.entries(environment)) {\n if (value !== undefined && !isCredentialKey(key)) sanitized[key] = value\n }\n return sanitized\n}\n\nexport function assertExternalOptimizerModelBudget(\n value: ExternalOptimizerModelBudget,\n label: string,\n): void {\n if (!value || typeof value !== 'object') {\n throw new Error(`${label} is required`)\n }\n for (const [field, entry] of [\n ['maxRequests', value.maxRequests],\n ['maxRequestBytes', value.maxRequestBytes],\n ['maxResponseBytes', value.maxResponseBytes],\n ['maxOutputTokensPerRequest', value.maxOutputTokensPerRequest],\n ] as const) {\n if (!Number.isSafeInteger(entry) || entry <= 0) {\n throw new Error(`${label}.${field} must be a positive safe integer`)\n }\n }\n if (!Number.isFinite(value.maxCostUsd) || value.maxCostUsd <= 0) {\n throw new Error(`${label}.maxCostUsd must be positive and finite`)\n }\n if (\n value.requestTimeoutMs !== undefined &&\n (!Number.isSafeInteger(value.requestTimeoutMs) ||\n value.requestTimeoutMs <= 0 ||\n value.requestTimeoutMs > MAX_TIMER_DELAY_MS)\n ) {\n throw new Error(`${label}.requestTimeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n costForTokenPricing(value.pricing, { inputTokens: 1, outputTokens: 1 })\n}\n\nexport function safePathComponent(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]/g, '_')\n}\n\nfunction isCredentialKey(key: string): boolean {\n const normalized = key\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/-/g, '_')\n .toLowerCase()\n const segments = normalized.split('_')\n return segments.some((segment) =>\n [\n 'auth',\n 'authorization',\n 'cookie',\n 'credential',\n 'credentials',\n 'key',\n 'password',\n 'secret',\n 'session',\n 'token',\n ].includes(segment),\n )\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","import type { Server, ServerResponse } from 'node:http'\n\nexport function listenLocal(server: Server): Promise<number> {\n return new Promise((resolvePromise, reject) => {\n server.once('error', reject)\n server.listen(0, '127.0.0.1', () => {\n server.off('error', reject)\n const address = server.address()\n if (!address || typeof address === 'string') {\n reject(new Error('external optimizer callback did not bind a TCP port'))\n return\n }\n resolvePromise(address.port)\n })\n })\n}\n\nexport function closeServer(server: Server): Promise<void> {\n return new Promise((resolvePromise, reject) => {\n server.close((error) => (error ? reject(error) : resolvePromise()))\n })\n}\n\nexport function sendJson(response: ServerResponse, status: number, body: unknown): void {\n response.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })\n response.end(JSON.stringify(body))\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport type {\n CostChannel,\n CostLedgerHandle,\n CostReceiptInput,\n CustomTokenPricing,\n} from '../cost-ledger'\nimport { costForTokenPricing } from '../cost-ledger'\nimport {\n assertExternalOptimizerModelBudget,\n type ExternalOptimizerModelBudget,\n type ExternalOptimizerModelProxy,\n isRecord,\n} from './external-optimizer-contracts'\nimport { closeServer, listenLocal, sendJson } from './external-optimizer-http'\n\nconst MODEL_PROXY_PATHS = new Set(['/v1/chat/completions', '/v1/responses'])\n\ninterface ProviderProxyResponse {\n status: number\n contentType: string\n body: Uint8Array\n receipt: CostReceiptInput\n usageComplete: boolean\n /** Set when the response violated the output or reasoning limit; forces a 502. */\n usageRejected?: string\n}\n\n/**\n * Put an OpenAI-compatible optimizer behind the shared cost ledger.\n *\n * The child process receives only a loopback URL and an ephemeral token.\n * Provider credentials stay in this process. Every request reserves its\n * conservative byte-count input bound plus the provider-enforced output cap\n * before it leaves the machine.\n */\nexport async function startExternalOptimizerModelProxy(args: {\n upstreamBaseUrl: string\n upstreamApiKey: string\n model: string\n budget: ExternalOptimizerModelBudget\n costLedger: CostLedgerHandle\n phase: string\n actor: string\n /** Cost-ledger channel. Defaults to `optimizer`. */\n channel?: CostChannel\n tags?: Record<string, string>\n initialUsage?: {\n requests: number\n costUsd: number\n }\n fetchImpl?: typeof fetch\n signal?: AbortSignal\n}): Promise<ExternalOptimizerModelProxy> {\n assertModelProxyConfig(args)\n args.signal?.throwIfAborted()\n const token = randomLocalToken()\n const fetchImpl = args.fetchImpl ?? fetch\n let requestCount = 0\n let successfulCompletionCount = 0\n let totalRequestCount = args.initialUsage?.requests ?? 0\n let committedForBudget = args.initialUsage?.costUsd ?? 0\n let reservedForBudget = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'external optimizer model proxy is closing' })\n return\n }\n\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleModelProxyRequest({\n request,\n response,\n controller,\n token,\n args,\n fetchImpl,\n nextReservation: (maximumCostUsd) => {\n if (totalRequestCount >= args.budget.maxRequests) {\n return { accepted: false as const, reason: 'optimizer model request limit reached' }\n }\n if (\n committedForBudget + reservedForBudget + maximumCostUsd >\n args.budget.maxCostUsd + Number.EPSILON\n ) {\n return { accepted: false as const, reason: 'optimizer model cost limit reached' }\n }\n requestCount += 1\n totalRequestCount += 1\n reservedForBudget += maximumCostUsd\n return { accepted: true as const }\n },\n settleReservation: (maximumCostUsd, chargedCostUsd) => {\n reservedForBudget = Math.max(0, reservedForBudget - maximumCostUsd)\n committedForBudget += chargedCostUsd\n },\n recordSuccessfulCompletion: () => {\n successfulCompletionCount += 1\n },\n }).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeModelProxy()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n return {\n baseUrl: `http://127.0.0.1:${port}/v1`,\n apiKey: token,\n requestAttempts: () => requestCount,\n successfulCompletions: () => successfulCompletionCount,\n close,\n }\n\n async function closeModelProxy(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('external optimizer model proxy closed with active request work')\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n }\n}\n\nasync function handleModelProxyRequest(args: {\n request: IncomingMessage\n response: ServerResponse\n controller: AbortController\n token: string\n args: {\n upstreamBaseUrl: string\n upstreamApiKey: string\n model: string\n budget: ExternalOptimizerModelBudget\n costLedger: CostLedgerHandle\n phase: string\n actor: string\n channel?: CostChannel\n tags?: Record<string, string>\n }\n fetchImpl: typeof fetch\n nextReservation: (maximumCostUsd: number) =>\n | { accepted: true }\n | {\n accepted: false\n reason: 'optimizer model request limit reached' | 'optimizer model cost limit reached'\n }\n settleReservation: (maximumCostUsd: number, chargedCostUsd: number) => void\n recordSuccessfulCompletion: () => void\n}): Promise<void> {\n const { controller, request, response } = args\n try {\n const path = request.url ? new URL(request.url, 'http://127.0.0.1').pathname : ''\n if (request.method !== 'POST' || !MODEL_PROXY_PATHS.has(path)) {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${args.token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n\n const body = await readBody(request, args.args.budget.maxRequestBytes)\n const parsed = parseModelProxyRequest(body, args.args.model, args.args.budget)\n const maximumUsage = conservativeMaximumUsage(\n body.byteLength,\n parsed.maxOutputTokens + (args.args.budget.maxReasoningTokensPerRequest ?? 0),\n args.args.budget.pricing,\n )\n const maximumCostUsd = costForTokenPricing(args.args.budget.pricing, maximumUsage)\n const reservation = args.nextReservation(maximumCostUsd)\n if (!reservation.accepted) {\n sendJsonIfOpen(response, 429, { error: reservation.reason })\n return\n }\n\n const timeout = setTimeout(\n () => controller.abort(),\n args.args.budget.requestTimeoutMs ?? 300_000,\n )\n let chargedForBudget = maximumCostUsd\n try {\n const paid = await args.args.costLedger.runPaidCall<ProviderProxyResponse>({\n channel: args.args.channel ?? 'optimizer',\n phase: args.args.phase,\n actor: args.args.actor,\n ...(args.args.tags ? { tags: args.args.tags } : {}),\n model: args.args.model,\n maximumCharge: {\n customTokenPricing: args.args.budget.pricing,\n ...maximumUsage,\n },\n execute: async () =>\n forwardModelProxyRequest({\n fetchImpl: args.fetchImpl,\n upstreamBaseUrl: args.args.upstreamBaseUrl,\n upstreamApiKey: args.args.upstreamApiKey,\n path,\n body,\n model: args.args.model,\n pricing: args.args.budget.pricing,\n maxOutputTokens: parsed.maxOutputTokens,\n ...(args.args.budget.maxReasoningTokensPerRequest === undefined\n ? {}\n : { maxReasoningTokens: args.args.budget.maxReasoningTokensPerRequest }),\n maxResponseBytes: args.args.budget.maxResponseBytes,\n signal: controller.signal,\n }),\n receipt: (result) => result.receipt,\n receiptFromError: () => ({\n model: args.args.model,\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n usageUnknown: true,\n }),\n })\n if (!paid.succeeded) {\n chargedForBudget = paid.receipt\n ? paid.receipt.usageUnknown || paid.receipt.costUnknown\n ? maximumCostUsd\n : paid.receipt.costUsd\n : 0\n sendJsonIfOpen(\n response,\n isAbortError(paid.error)\n ? 504\n : paid.error instanceof ProviderResponseTooLargeError\n ? 502\n : 429,\n { error: paid.error.message },\n )\n return\n }\n chargedForBudget = paid.value.usageComplete ? paid.receipt.costUsd : maximumCostUsd\n // A response that violated the output or reasoning limit is rejected. A\n // response the provider merely under-reported is forwarded with its cost\n // charged at the reservation maximum, so the analysis keeps its usable\n // completion and the ledger holds an honest upper-bound charge.\n if (paid.value.usageRejected) {\n sendJsonIfOpen(response, 502, { error: paid.value.usageRejected })\n return\n }\n if (paid.value.status >= 200 && paid.value.status < 300) {\n args.recordSuccessfulCompletion()\n }\n if (response.destroyed || response.writableEnded) return\n response.writeHead(paid.value.status, {\n 'content-type': paid.value.contentType,\n 'content-length': String(paid.value.body.byteLength),\n })\n response.end(paid.value.body)\n } finally {\n clearTimeout(timeout)\n args.settleReservation(maximumCostUsd, chargedForBudget)\n }\n } catch (error) {\n const status =\n error instanceof RequestBodyTooLargeError\n ? 413\n : error instanceof Error && isAbortError(error)\n ? 503\n : 400\n sendJsonIfOpen(response, status, { error: toErrorMessage(error) })\n }\n}\n\nasync function waitForActiveHandlers(activeHandlers: Set<Promise<void>>): Promise<void> {\n while (activeHandlers.size > 0) {\n await Promise.allSettled([...activeHandlers])\n }\n}\n\nfunction sendJsonIfOpen(response: ServerResponse, status: number, body: unknown): void {\n if (response.destroyed || response.writableEnded) return\n sendJson(response, status, body)\n}\n\nasync function forwardModelProxyRequest(args: {\n fetchImpl: typeof fetch\n upstreamBaseUrl: string\n upstreamApiKey: string\n path: string\n body: Uint8Array\n model: string\n pricing: CustomTokenPricing\n maxOutputTokens: number\n /** Enforced only when the caller declared a thinking budget. */\n maxReasoningTokens?: number\n maxResponseBytes: number\n signal: AbortSignal\n}): Promise<ProviderProxyResponse> {\n const upstream = modelProxyUpstreamUrl(args.upstreamBaseUrl, args.path)\n const response = await args.fetchImpl(upstream, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${args.upstreamApiKey}`,\n 'content-type': 'application/json',\n },\n body: args.body.buffer.slice(\n args.body.byteOffset,\n args.body.byteOffset + args.body.byteLength,\n ) as ArrayBuffer,\n signal: args.signal,\n redirect: 'error',\n })\n const body = await readProviderResponseBody(response, args.maxResponseBytes)\n const usage = parseProviderUsage(body)\n const successful = response.status >= 200 && response.status < 300\n const zeroUsage =\n successful &&\n usage !== undefined &&\n usage.inputTokens +\n usage.outputTokens +\n (usage.cachedTokens ?? 0) +\n (usage.cacheWriteTokens ?? 0) ===\n 0\n // `outputTokens` carries reasoning tokens as a subset, and a reasoning model\n // bounds only the completion by the requested limit. Charging the whole\n // output against that limit rejects every ordinary response such a model\n // returns, so the guard measures the completion it actually governs.\n const completionTokens =\n usage === undefined ? 0 : usage.outputTokens - (usage.reasoningTokens ?? 0)\n const reasoningTokens = usage?.reasoningTokens ?? 0\n // A response that exceeds the requested output or the declared reasoning\n // budget violated the contract and is rejected. A response whose usage the\n // provider merely omitted is forwarded with its cost flagged: the completion\n // is still usable, and refusing it would fail a case over a reporting gap.\n const usageRejected =\n successful && usage !== undefined && completionTokens > args.maxOutputTokens\n ? `optimizer model provider reported ${completionTokens} completion tokens, exceeding requested limit ${args.maxOutputTokens}`\n : successful &&\n args.maxReasoningTokens !== undefined &&\n reasoningTokens > args.maxReasoningTokens\n ? `optimizer model provider reported ${reasoningTokens} reasoning tokens, exceeding the declared budget ${args.maxReasoningTokens}`\n : undefined\n return {\n status: response.status,\n contentType: response.headers.get('content-type') ?? 'application/json',\n body,\n receipt:\n usage && !zeroUsage\n ? {\n model: args.model,\n ...usage,\n ...(usage.actualCostUsd === undefined ? { customTokenPricing: args.pricing } : {}),\n }\n : {\n model: args.model,\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n usageUnknown: true,\n },\n usageComplete: usage !== undefined && !zeroUsage,\n ...(usageRejected ? { usageRejected } : {}),\n }\n}\n\nfunction parseModelProxyRequest(\n body: Uint8Array,\n expectedModel: string,\n budget: ExternalOptimizerModelBudget,\n): { maxOutputTokens: number } {\n let value: unknown\n try {\n value = JSON.parse(Buffer.from(body).toString('utf8'))\n } catch {\n throw new Error('optimizer model request must be valid JSON')\n }\n if (!isRecord(value)) throw new Error('optimizer model request must be a JSON object')\n if (value.model !== expectedModel) {\n throw new Error(`optimizer model request must use configured model '${expectedModel}'`)\n }\n if (value.stream !== undefined && value.stream !== false) {\n throw new Error('streaming optimizer model requests are not supported')\n }\n for (const field of ['n', 'best_of', 'candidate_count', 'num_candidates'] as const) {\n if (value[field] !== undefined && value[field] !== 1) {\n throw new Error(`optimizer model request ${field} must be 1 when supplied`)\n }\n }\n const suppliedMaximums = [\n value.max_output_tokens,\n value.max_completion_tokens,\n value.max_tokens,\n ].filter((maximum) => maximum !== undefined)\n if (\n suppliedMaximums.length === 0 ||\n suppliedMaximums.some((maximum) => !Number.isSafeInteger(maximum) || (maximum as number) <= 0)\n ) {\n throw new Error('optimizer model request requires a positive output-token limit')\n }\n const maxOutputTokens = Math.max(...(suppliedMaximums as number[]))\n if (maxOutputTokens > budget.maxOutputTokensPerRequest) {\n throw new Error('optimizer model request exceeds maxOutputTokensPerRequest')\n }\n return { maxOutputTokens }\n}\n\n/**\n * Resolve the upstream URL the way an OpenAI-compatible client does.\n *\n * This proxy exposes `/v1/...` to its child for client compatibility. Whether\n * that prefix belongs upstream depends on the caller's base URL: a base that\n * already names a version segment (`/v1`, `/api/coding/paas/v4`) receives only\n * the endpoint, and a base without one receives the whole versioned path.\n * Forwarding the prefix unconditionally produced `/v4/v1/chat/completions`,\n * which providers answer with 404.\n */\nfunction modelProxyUpstreamUrl(baseUrl: string, requestPath: string): string {\n const upstream = new URL(baseUrl)\n const basePath = upstream.pathname.replace(/\\/+$/, '')\n const lastSegment = basePath.split('/').at(-1) ?? ''\n const baseNamesVersion = /^v\\d+/.test(lastSegment)\n const suffix = baseNamesVersion ? requestPath.replace(/^\\/v1(?=\\/)/, '') : requestPath\n upstream.pathname = `${basePath}${suffix}`\n return upstream.toString()\n}\n\nfunction parseProviderUsage(\n body: Uint8Array,\n):\n | Omit<CostReceiptInput, 'model' | 'customTokenPricing' | 'costUnknown' | 'usageUnknown'>\n | undefined {\n let value: unknown\n try {\n value = JSON.parse(Buffer.from(body).toString('utf8'))\n } catch {\n return undefined\n }\n if (!isRecord(value) || !isRecord(value.usage)) return undefined\n const usage = value.usage\n const totalInputTokens = usage.input_tokens ?? usage.prompt_tokens\n const outputTokens = usage.output_tokens ?? usage.completion_tokens\n if (\n !Number.isSafeInteger(totalInputTokens) ||\n (totalInputTokens as number) < 0 ||\n !Number.isSafeInteger(outputTokens) ||\n (outputTokens as number) < 0\n ) {\n return undefined\n }\n const inputDetails = isRecord(usage.input_tokens_details)\n ? usage.input_tokens_details\n : isRecord(usage.prompt_tokens_details)\n ? usage.prompt_tokens_details\n : {}\n const outputDetails = isRecord(usage.output_tokens_details)\n ? usage.output_tokens_details\n : isRecord(usage.completion_tokens_details)\n ? usage.completion_tokens_details\n : {}\n const cachedTokens = optionalTokenCount(inputDetails, [\n 'cached_tokens',\n 'cache_read_tokens',\n 'cache_read_input_tokens',\n ])\n const cacheWriteTokens = optionalTokenCount(inputDetails, [\n 'cache_write_tokens',\n 'cache_creation_tokens',\n 'cache_creation_input_tokens',\n ])\n const reasoningTokens = optionalTokenCount(outputDetails, ['reasoning_tokens'])\n const actualCostUsd =\n typeof usage.cost === 'number' && Number.isFinite(usage.cost) && usage.cost >= 0\n ? usage.cost\n : undefined\n if (\n cachedTokens === INVALID_TOKEN_COUNT ||\n cacheWriteTokens === INVALID_TOKEN_COUNT ||\n reasoningTokens === INVALID_TOKEN_COUNT\n ) {\n return undefined\n }\n const classifiedInputTokens = (cachedTokens ?? 0) + (cacheWriteTokens ?? 0)\n if (\n classifiedInputTokens > (totalInputTokens as number) ||\n (reasoningTokens ?? 0) > (outputTokens as number)\n ) {\n return undefined\n }\n return {\n inputTokens: (totalInputTokens as number) - classifiedInputTokens,\n outputTokens: outputTokens as number,\n ...(cachedTokens === undefined ? {} : { cachedTokens }),\n ...(cacheWriteTokens === undefined ? {} : { cacheWriteTokens }),\n ...(reasoningTokens === undefined ? {} : { reasoningTokens }),\n ...(actualCostUsd === undefined ? {} : { actualCostUsd }),\n }\n}\n\nconst INVALID_TOKEN_COUNT = Symbol('invalid-token-count')\n\nfunction optionalTokenCount(\n details: Record<string, unknown>,\n fields: readonly string[],\n): number | undefined | typeof INVALID_TOKEN_COUNT {\n let found: number | undefined\n for (const field of fields) {\n const value = details[field]\n if (value === undefined || value === null) continue\n if (!Number.isSafeInteger(value) || (value as number) < 0) return INVALID_TOKEN_COUNT\n if (found !== undefined && found !== value) return INVALID_TOKEN_COUNT\n found = value as number\n }\n return found\n}\n\nfunction conservativeMaximumUsage(\n inputTokenUpperBound: number,\n outputTokenUpperBound: number,\n pricing: CustomTokenPricing,\n): Pick<CostReceiptInput, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'> {\n const inputRates = [\n pricing.inputUsdPerMillion,\n pricing.cachedInputUsdPerMillion ?? pricing.inputUsdPerMillion,\n pricing.cacheWriteUsdPerMillion ?? pricing.inputUsdPerMillion,\n ]\n const mostExpensiveInputClass = inputRates.indexOf(Math.max(...inputRates))\n return {\n inputTokens: mostExpensiveInputClass === 0 ? inputTokenUpperBound : 0,\n ...(mostExpensiveInputClass === 1 ? { cachedTokens: inputTokenUpperBound } : {}),\n ...(mostExpensiveInputClass === 2 ? { cacheWriteTokens: inputTokenUpperBound } : {}),\n outputTokens: outputTokenUpperBound,\n }\n}\n\nasync function readProviderResponseBody(response: Response, maxBytes: number): Promise<Uint8Array> {\n const declaredLength = response.headers.get('content-length')\n if (declaredLength !== null) {\n const parsedLength = Number(declaredLength)\n if (Number.isFinite(parsedLength) && parsedLength > maxBytes) {\n throw new ProviderResponseTooLargeError()\n }\n }\n if (!response.body) return new Uint8Array()\n\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let totalBytes = 0\n try {\n while (true) {\n const next = await reader.read()\n if (next.done) break\n totalBytes += next.value.byteLength\n if (totalBytes > maxBytes) {\n await reader.cancel()\n throw new ProviderResponseTooLargeError()\n }\n chunks.push(next.value)\n }\n } finally {\n reader.releaseLock()\n }\n\n const body = new Uint8Array(totalBytes)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return body\n}\n\nfunction assertModelProxyConfig(args: {\n upstreamBaseUrl: string\n upstreamApiKey: string\n model: string\n budget: ExternalOptimizerModelBudget\n phase: string\n actor: string\n tags?: Record<string, string>\n initialUsage?: {\n requests: number\n costUsd: number\n }\n}): void {\n for (const [label, value] of [\n ['upstreamBaseUrl', args.upstreamBaseUrl],\n ['upstreamApiKey', args.upstreamApiKey],\n ['model', args.model],\n ['phase', args.phase],\n ['actor', args.actor],\n ] as const) {\n if (typeof value !== 'string' || !value.trim() || value.trim() !== value) {\n throw new Error(`external optimizer model proxy: ${label} must be trimmed and non-empty`)\n }\n }\n let parsed: URL\n try {\n parsed = new URL(args.upstreamBaseUrl)\n } catch {\n throw new Error('external optimizer model proxy: upstreamBaseUrl must be an HTTP(S) URL')\n }\n if (\n (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') ||\n parsed.username ||\n parsed.password ||\n parsed.search ||\n parsed.hash\n ) {\n throw new Error(\n 'external optimizer model proxy: upstreamBaseUrl must be an HTTP(S) URL without credentials, query, or fragment',\n )\n }\n assertExternalOptimizerModelBudget(args.budget, 'external optimizer model proxy: budget')\n if (args.tags !== undefined) {\n for (const [key, value] of Object.entries(args.tags)) {\n if (!key.trim() || key.trim() !== key || !value.trim() || value.trim() !== value) {\n throw new Error('external optimizer model proxy: tags must be trimmed and non-empty')\n }\n }\n }\n if (args.initialUsage !== undefined) {\n if (\n !Number.isSafeInteger(args.initialUsage.requests) ||\n args.initialUsage.requests < 0 ||\n !Number.isFinite(args.initialUsage.costUsd) ||\n args.initialUsage.costUsd < 0\n ) {\n throw new Error(\n 'external optimizer model proxy: initialUsage must contain non-negative requests and cost',\n )\n }\n if (\n args.initialUsage.requests > args.budget.maxRequests ||\n args.initialUsage.costUsd > args.budget.maxCostUsd + Number.EPSILON\n ) {\n throw new Error('external optimizer model proxy: initialUsage exceeds the configured budget')\n }\n }\n}\n\nclass RequestBodyTooLargeError extends Error {}\n\nclass ProviderResponseTooLargeError extends Error {\n constructor() {\n super('optimizer model response exceeds maxResponseBytes')\n }\n}\n\nfunction readBody(request: IncomingMessage, maximumBytes: number): Promise<Uint8Array> {\n return new Promise((resolvePromise, reject) => {\n let size = 0\n let tooLarge = false\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n if (tooLarge) return\n size += chunk.byteLength\n if (size > maximumBytes) {\n tooLarge = true\n chunks.length = 0\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n if (tooLarge) {\n reject(new RequestBodyTooLargeError('optimizer model request body too large'))\n return\n }\n resolvePromise(new Uint8Array(Buffer.concat(chunks)))\n })\n })\n}\n\nfunction randomLocalToken(): string {\n return randomBytes(32).toString('hex')\n}\n\nfunction isAbortError(error: Error): boolean {\n return error.name === 'AbortError' || error.message.toLowerCase().includes('abort')\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import type {\n ExternalOptimizerCallback,\n ExternalOptimizerModelProxy,\n} from './external-optimizer-contracts'\n\nexport async function runWithCleanup<T>(args: {\n label: string\n run: () => Promise<T>\n cleanup: () => Promise<void>\n}): Promise<T> {\n let value: T | undefined\n let operationError: Error | undefined\n try {\n value = await args.run()\n } catch (cause) {\n operationError = toError(cause)\n }\n\n let cleanupError: Error | undefined\n try {\n await args.cleanup()\n } catch (cause) {\n cleanupError = toError(cause)\n }\n\n if (operationError && cleanupError) {\n throw new AggregateError(\n [operationError, cleanupError],\n `${operationError.message}; ${args.label} cleanup failed: ${cleanupError.message}`,\n )\n }\n if (operationError) throw operationError\n if (cleanupError) {\n throw new Error(`${args.label} cleanup failed: ${cleanupError.message}`, {\n cause: cleanupError,\n })\n }\n return value as T\n}\n\nexport async function closeExternalOptimizerResources(args: {\n label: string\n callback: ExternalOptimizerCallback\n modelProxy?: ExternalOptimizerModelProxy\n}): Promise<void> {\n const results = await Promise.allSettled([\n ...(args.modelProxy ? [args.modelProxy.close()] : []),\n args.callback.close(),\n ])\n const errors = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []))\n if (errors.length > 0) {\n throw new AggregateError(errors, `${args.label}: failed to close optimizer resources`)\n }\n}\n\nfunction toError(cause: unknown): Error {\n return cause instanceof Error ? cause : new Error(String(cause))\n}\n","import { type ChildProcess, spawn } from 'node:child_process'\nimport { lstat, mkdtemp, open, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join, resolve } from 'node:path'\nimport { type ExternalOptimizerRunnerCommand, isRecord } from './external-optimizer-contracts'\nimport { runWithCleanup } from './external-optimizer-resources'\n\nconst MAX_PROCESS_OUTPUT_CHARS = 64_000\nconst MAX_PROCESS_INPUT_BYTES = 64 * 1024 * 1024\nconst MAX_PROCESS_RESULT_BYTES = 4 * 1024 * 1024\nconst PROCESS_TERMINATION_GRACE_MS = 5_000\nconst PROCESS_TERMINATION_POLL_MS = 25\nconst PROCESS_KILL_WAIT_MS = 1_000\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\nconst PROCESS_OUTPUT_HEAD_CHARS = MAX_PROCESS_OUTPUT_CHARS / 2\nconst PROCESS_OUTPUT_TAIL_CHARS = MAX_PROCESS_OUTPUT_CHARS - PROCESS_OUTPUT_HEAD_CHARS\n\ninterface ProcessOutputCapture {\n full: string | undefined\n head: string\n tail: string\n totalChars: number\n}\n\nexport async function runExternalOptimizerProcess<TOutput>(args: {\n label: string\n tempPrefix: string\n module: string\n input: unknown\n runner?: ExternalOptimizerRunnerCommand\n timeoutMs: number\n signal?: AbortSignal\n}): Promise<TOutput> {\n if (\n !Number.isSafeInteger(args.timeoutMs) ||\n args.timeoutMs <= 0 ||\n args.timeoutMs > MAX_TIMER_DELAY_MS\n ) {\n throw new Error(`${args.label} timeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n if (process.platform === 'win32') {\n throw new Error(\n `${args.label} requires POSIX process-group cleanup; run the optimizer through WSL or Linux`,\n )\n }\n throwIfAborted(args.signal, args.label)\n const dir = await mkdtemp(join(tmpdir(), args.tempPrefix))\n const inputPath = join(dir, 'input.json')\n const outputPath = join(dir, 'output.json')\n return runWithCleanup({\n label: `${args.label} temporary directory`,\n run: async () => {\n const serializedInput = JSON.stringify(args.input)\n if (serializedInput === undefined) {\n throw new Error(`${args.label} input must be JSON-serializable`)\n }\n const inputJson = `${serializedInput}\\n`\n const inputBytes = Buffer.byteLength(inputJson)\n if (inputBytes > MAX_PROCESS_INPUT_BYTES) {\n throw new Error(\n `${args.label} input exceeds ${MAX_PROCESS_INPUT_BYTES} bytes (${inputBytes})`,\n )\n }\n await writeFile(inputPath, inputJson)\n const command = resolveRunnerCommand(args.runner?.command ?? 'python')\n const commandArgs = [\n ...(args.runner?.args ?? ['-m', args.module]),\n '--input',\n inputPath,\n '--output',\n outputPath,\n ]\n await runProcess({\n label: args.label,\n command,\n args: commandArgs,\n cwd: dir,\n env: args.runner?.env,\n timeoutMs: args.timeoutMs,\n signal: args.signal,\n })\n throwIfAborted(args.signal, args.label)\n const raw = JSON.parse(\n await readBoundedTextFile(outputPath, MAX_PROCESS_RESULT_BYTES, `${args.label} output`),\n ) as unknown\n throwIfAborted(args.signal, args.label)\n if (!isRecord(raw)) throw new Error(`${args.label} output must be a JSON object`)\n return raw as TOutput\n },\n cleanup: () => rm(dir, { recursive: true, force: true }),\n })\n}\n\nfunction resolveRunnerCommand(command: string): string {\n if (isAbsolute(command) || (!command.includes('/') && !command.includes('\\\\'))) return command\n return resolve(command)\n}\n\nasync function readBoundedTextFile(path: string, maxBytes: number, label: string): Promise<string> {\n const entry = await lstat(path)\n if (!entry.isFile()) throw new Error(`${label} must be a regular file`)\n const file = await open(path, 'r')\n try {\n const buffer = Buffer.allocUnsafe(maxBytes + 1)\n let bytesRead = 0\n while (bytesRead < buffer.byteLength) {\n const chunk = await file.read(buffer, bytesRead, buffer.byteLength - bytesRead, bytesRead)\n if (chunk.bytesRead === 0) break\n bytesRead += chunk.bytesRead\n }\n if (bytesRead > maxBytes) {\n throw new Error(`${label} exceeds ${maxBytes} bytes`)\n }\n return buffer.subarray(0, bytesRead).toString('utf8')\n } finally {\n await file.close()\n }\n}\n\nfunction runProcess(args: {\n label: string\n command: string\n args: string[]\n cwd: string | undefined\n env: NodeJS.ProcessEnv | undefined\n timeoutMs: number\n signal: AbortSignal | undefined\n}): Promise<void> {\n throwIfAborted(args.signal, args.label)\n return new Promise((resolvePromise, reject) => {\n const child = spawn(args.command, args.args, {\n cwd: args.cwd,\n env: { ...safeProcessEnvironment(), ...args.env },\n stdio: ['ignore', 'pipe', 'pipe'],\n detached: process.platform !== 'win32',\n windowsHide: true,\n })\n const stdout = createProcessOutputCapture()\n const stderr = createProcessOutputCapture()\n let settled = false\n let timeout: NodeJS.Timeout | undefined\n const onAbort = () => finish(abortReason(args.signal!, args.label))\n const finish = (error?: Error) => {\n if (settled) return\n settled = true\n if (timeout) clearTimeout(timeout)\n args.signal?.removeEventListener('abort', onAbort)\n void terminateProcessTree(child).then(\n () => {\n if (error) reject(error)\n else resolvePromise()\n },\n (cleanupError: unknown) => {\n if (error) {\n const cleanup =\n cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError))\n reject(\n new AggregateError(\n [error, cleanup],\n `${error.message}; ${args.label} process cleanup failed: ${cleanup.message}`,\n ),\n )\n return\n }\n reject(\n new Error(\n `${args.label} process cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,\n ),\n )\n },\n )\n }\n timeout = setTimeout(() => {\n finish(new Error(`${args.label} exceeded ${args.timeoutMs}ms`))\n }, args.timeoutMs)\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n child.stdout.on('data', (chunk: Buffer) => {\n appendProcessOutput(stdout, chunk)\n })\n child.stderr.on('data', (chunk: Buffer) => {\n appendProcessOutput(stderr, chunk)\n })\n child.on('error', (error) => {\n finish(new Error(`${args.label} could not start: ${error.message}`))\n })\n child.on('close', (code) => {\n if (code === 0) {\n finish()\n return\n }\n finish(\n new Error(\n `${args.label} exited ${String(code)}. stderr=${summarizeProcessOutput(stderr)} stdout=${summarizeProcessOutput(stdout)}`,\n ),\n )\n })\n })\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined, label: string): void {\n if (signal?.aborted) throw abortReason(signal, label)\n}\n\nfunction abortReason(signal: AbortSignal, label: string): Error {\n return signal.reason instanceof Error\n ? signal.reason\n : new Error(`${label} aborted`, { cause: signal.reason })\n}\n\nfunction safeProcessEnvironment(): NodeJS.ProcessEnv {\n const allowed = [\n 'PATH',\n 'HOME',\n 'USER',\n 'LOGNAME',\n 'SHELL',\n 'TMPDIR',\n 'TMP',\n 'TEMP',\n 'LANG',\n 'LANGUAGE',\n 'LC_ALL',\n 'VIRTUAL_ENV',\n 'PYTHONPATH',\n 'SYSTEMROOT',\n 'COMSPEC',\n 'PATHEXT',\n 'WINDIR',\n ] as const\n return Object.fromEntries(\n allowed.flatMap((name) => {\n const value = process.env[name]\n return value === undefined ? [] : [[name, value]]\n }),\n )\n}\n\nasync function terminateProcessTree(child: ChildProcess): Promise<void> {\n const pid = child.pid\n if (!pid) return\n if (process.platform === 'win32') {\n throw new Error('native Windows process-tree cleanup is unsupported')\n }\n\n if (!signalProcessGroup(pid, 'SIGTERM')) return\n if (await waitForProcessGroupExit(pid, PROCESS_TERMINATION_GRACE_MS)) return\n if (!signalProcessGroup(pid, 'SIGKILL')) return\n if (await waitForProcessGroupExit(pid, PROCESS_KILL_WAIT_MS)) return\n throw new Error(`process group ${pid} remained alive after SIGKILL`)\n}\n\nfunction signalProcessGroup(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(-pid, signal)\n return true\n } catch (error) {\n if (isMissingProcessError(error)) return false\n throw error\n }\n}\n\nasync function waitForProcessGroupExit(pid: number, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs\n while (processGroupExists(pid)) {\n const remainingMs = deadline - Date.now()\n if (remainingMs <= 0) return false\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(PROCESS_TERMINATION_POLL_MS, remainingMs)),\n )\n }\n return true\n}\n\nfunction processGroupExists(pid: number): boolean {\n try {\n process.kill(-pid, 0)\n return true\n } catch (error) {\n if (isMissingProcessError(error)) return false\n throw error\n }\n}\n\nfunction isMissingProcessError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ESRCH'\n )\n}\n\nfunction createProcessOutputCapture(): ProcessOutputCapture {\n return { full: '', head: '', tail: '', totalChars: 0 }\n}\n\nfunction appendProcessOutput(capture: ProcessOutputCapture, chunk: Buffer): void {\n const text = chunk.toString()\n capture.totalChars += text.length\n if (capture.full !== undefined) {\n const combined = `${capture.full}${text}`\n if (combined.length <= MAX_PROCESS_OUTPUT_CHARS) {\n capture.full = combined\n return\n }\n capture.head = combined.slice(0, PROCESS_OUTPUT_HEAD_CHARS)\n capture.tail = combined.slice(-PROCESS_OUTPUT_TAIL_CHARS)\n capture.full = undefined\n return\n }\n capture.tail = `${capture.tail}${text}`.slice(-PROCESS_OUTPUT_TAIL_CHARS)\n}\n\nfunction summarizeProcessOutput(capture: ProcessOutputCapture, max = 4_000): string {\n const raw =\n capture.full ??\n `${capture.head}\\n...[${capture.totalChars - capture.head.length - capture.tail.length} chars omitted]...\\n${capture.tail}`\n const compact = raw.trim().replace(/\\s+/g, ' ')\n if (compact.length <= max) return compact\n const headChars = Math.floor(max / 3)\n const tailChars = max - headChars\n return `${compact.slice(0, headChars)}...[${compact.length - max} chars omitted]...${compact.slice(-tailChars)}`\n}\n","import { ValidationError } from '../errors'\n\n/** Base error for invalid search-ledger input or operations. */\nexport class SearchLedgerError extends ValidationError {}\n\n/** Error raised when durable search-ledger data fails an integrity check. */\nexport class SearchLedgerIntegrityError extends SearchLedgerError {}\n\n/** Error raised when an event identifier is reused with different content. */\nexport class SearchLedgerConflictError extends SearchLedgerError {}\n","/** Campaign binding of the generic journal file layer to search-ledger errors. */\n\nimport {\n appendLedgerLine,\n type FileLockResult,\n type LedgerFileContext,\n tryWithLedgerFileLock,\n withLedgerFileLock,\n} from '../ledger-core'\nimport { SearchLedgerIntegrityError } from './search-ledger-errors'\n\nexport const SEARCH_LEDGER_FILE_CONTEXT: LedgerFileContext = {\n subject: 'search ledger',\n integrityError: (message, options) => new SearchLedgerIntegrityError(message, options),\n}\n\nexport function appendSearchLedgerLine(path: string, line: string): void {\n appendLedgerLine(path, line, SEARCH_LEDGER_FILE_CONTEXT)\n}\n\nexport function withSearchLedgerFileLock<T>(ledgerPath: string, run: () => T): T {\n return withLedgerFileLock(ledgerPath, SEARCH_LEDGER_FILE_CONTEXT, run)\n}\n\nexport type { FileLockResult }\n\nexport function tryWithSearchLedgerFileLock<T>(\n ledgerPath: string,\n run: () => T,\n): FileLockResult<T> {\n return tryWithLedgerFileLock(ledgerPath, SEARCH_LEDGER_FILE_CONTEXT, run)\n}\n","import { createRequire } from 'node:module'\nimport { join } from 'node:path'\nimport { CostLedger } from '../cost-ledger'\nimport { appendSearchLedgerLine, tryWithSearchLedgerFileLock } from './search-ledger-file'\n\n/**\n * `CampaignStorage` — the filesystem seam `runCampaign` writes through\n * (run/cell dirs, the resumability cache, per-cell artifacts, trace spans).\n *\n * The default (`fsCampaignStorage`) is the Node filesystem — identical\n * behavior to the inline `node:fs` calls it replaces, so existing CLI\n * consumers are unaffected. `inMemoryCampaignStorage` keeps everything in a\n * `Map`, so the substrate runs in environments WITHOUT a filesystem\n * (Cloudflare Workers, Deno Deploy, other edge runtimes) — the campaign\n * still produces its `CampaignResult` (cells + aggregates) in memory;\n * artifacts/traces simply aren't persisted to disk.\n *\n * Paths are opaque keys to the in-memory adapter — it does not parse them,\n * so the same `join(...)`-built paths work unchanged across both adapters.\n */\nexport interface CampaignStorage {\n /** Ensure a directory exists (recursive). No-op for in-memory. */\n ensureDir(dir: string): void\n /** Does this path exist (as a written file or an ensured dir)? */\n exists(path: string): boolean\n /** Read a UTF-8 file; `undefined` when missing or unreadable. */\n read(path: string): string | undefined\n /** Write a file (string or bytes). Parent dir is assumed ensured. */\n write(path: string, content: string | Uint8Array): void\n /** Append only when the current UTF-8 byte length matches `expectedBytes`.\n * Returns the new length, or undefined when another writer won. */\n append(path: string, content: string, expectedBytes: number): number | undefined\n}\n\n/** Node-filesystem storage — the default. Lazily requires `node:fs` so the\n * module imports cleanly in non-Node runtimes (where the caller passes\n * `inMemoryCampaignStorage` instead and never constructs this).\n *\n * `createRequire(import.meta.url)` is the ESM-native lazy require — a bare\n * `require` is a ReferenceError under `\"type\": \"module\"`, which is exactly\n * the shape this package publishes. */\nexport function fsCampaignStorage(): CampaignStorage {\n const nodeRequire = createRequire(import.meta.url)\n const { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } = nodeRequire(\n 'node:fs',\n ) as typeof import('node:fs')\n return {\n ensureDir(dir) {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n },\n exists(path) {\n return existsSync(path)\n },\n read(path) {\n try {\n return readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n },\n write(path, content) {\n writeFileSync(path, content as Uint8Array)\n },\n append(path, content, expectedBytes) {\n const result = tryWithSearchLedgerFileLock(path, () => {\n let actualBytes = 0\n try {\n actualBytes = statSync(path).size\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n if (actualBytes !== expectedBytes) return undefined\n appendSearchLedgerLine(path, content)\n return expectedBytes + Buffer.byteLength(content)\n })\n return result.acquired ? result.value : undefined\n },\n }\n}\n\n/** In-memory storage for filesystem-less runtimes. Artifacts + trace spans\n * live in a `Map` for the duration of the run; the `CampaignResult` is\n * fully populated, but nothing is persisted to disk. */\nexport function inMemoryCampaignStorage(): CampaignStorage {\n const files = new Map<string, string | Uint8Array>()\n const dirs = new Set<string>()\n return {\n ensureDir(dir) {\n dirs.add(dir)\n },\n exists(path) {\n return files.has(path) || dirs.has(path)\n },\n read(path) {\n const value = files.get(path)\n if (value === undefined) return undefined\n return typeof value === 'string' ? value : new TextDecoder().decode(value)\n },\n write(path, content) {\n files.set(path, content)\n },\n append(path, content, expectedBytes) {\n const current = files.get(path)\n const currentText =\n current === undefined\n ? ''\n : typeof current === 'string'\n ? current\n : new TextDecoder().decode(current)\n const currentBytes = new TextEncoder().encode(currentText).byteLength\n if (currentBytes !== expectedBytes) return undefined\n files.set(path, `${currentText}${content}`)\n return currentBytes + new TextEncoder().encode(content).byteLength\n },\n }\n}\n\n/** Open the durable spend account stored beside a logical run. */\nexport function createRunCostLedger(input: {\n storage: CampaignStorage\n runDir: string\n costCeilingUsd?: number\n}): CostLedger {\n const path = join(input.runDir, 'cost-ledger.jsonl')\n input.storage.ensureDir(input.runDir)\n return new CostLedger({\n costCeilingUsd: input.costCeilingUsd,\n persistence: {\n read: () => {\n const stored = input.storage.read(path)\n if (stored === undefined && input.storage.exists(path)) {\n throw new Error(`CostLedger: cannot read existing event log '${path}'`)\n }\n const events = stored ?? ''\n return {\n revision: String(new TextEncoder().encode(events).byteLength),\n events,\n }\n },\n append: (expectedRevision, event) => {\n const expectedBytes = Number(expectedRevision)\n if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0) {\n throw new Error(`CostLedger: invalid storage revision '${expectedRevision}'`)\n }\n const next = input.storage.append(path, event, expectedBytes)\n return next === undefined ? undefined : String(next)\n },\n },\n })\n}\n","/**\n * Single-run lock for evaluations that share one mutable environment.\n *\n * Two concurrent runs against a shared stateful gym silently corrupt each\n * other: each resets/mutates environment state mid-cell of the other, and\n * every score from both becomes garbage that LOOKS like worker variance\n * (agent-lab R357 burned hours on flip-flopping scores before tracing them\n * to exactly this). The fix is a pid lockfile: refuse to start while a live\n * holder exists, reclaim stale locks whose pid is gone, release only if the\n * lock is still ours.\n *\n * `alsoCheck` exists because independent runners can guard the same shared\n * resource with differently named lockfiles; a runner must respect all of\n * them even though it writes only its own.\n */\n\nimport {\n type AtomicFileLockUnavailable,\n probeAtomicFileLock,\n tryAcquireAtomicFileLock,\n} from '../ledger-core/atomic-file-lock'\n\nexport interface SingleRunLockOptions {\n /** Lockfile this runner writes (and checks). */\n readonly lockPath: string\n /** Other runners' lockfiles guarding the same resource; checked, never written. */\n readonly alsoCheck?: readonly string[]\n /** Install a process 'exit' hook that releases the lock. Default true. */\n readonly releaseOnExit?: boolean\n /** Owner pid recorded in the lockfile metadata. Default process.pid. */\n readonly pid?: number\n}\n\nexport interface SingleRunLock {\n /** Remove the lockfile if this process still owns it. Idempotent. */\n release(): void\n}\n\nfunction assertAvailable(path: string): void {\n const unavailable = probeAtomicFileLock({ lockPath: path })\n if (unavailable) throw unavailableError(path, unavailable)\n}\n\nfunction unavailableError(path: string, unavailable: AtomicFileLockUnavailable): Error {\n if (unavailable.reason === 'recovery') {\n return new Error(\n `single-run lock recovery is already in progress (${path}); refusing a concurrent run`,\n )\n }\n return new Error(\n `single-run lock held by live pid ${unavailable.holder.pid} (${path}); refusing a concurrent run on the shared resource`,\n )\n}\n\n/**\n * Acquire the lock or throw naming the live holder. A stale lock (holder pid\n * no longer running) is reclaimed by one contender. An interrupted reclaim\n * leaves a marker that fails closed instead of admitting overlapping runs.\n */\nexport function acquireSingleRunLock(opts: SingleRunLockOptions): SingleRunLock {\n const pid = opts.pid ?? process.pid\n if (!Number.isSafeInteger(pid) || pid <= 0)\n throw new Error('single-run lock pid must be a positive integer')\n for (const path of opts.alsoCheck ?? []) assertAvailable(path)\n const acquisition = tryAcquireAtomicFileLock({\n lockPath: opts.lockPath,\n pid,\n })\n if (!acquisition.acquired) throw unavailableError(opts.lockPath, acquisition)\n const releaseOnExit = opts.releaseOnExit ?? true\n let released = false\n const release = (): void => {\n if (released) return\n released = true\n if (releaseOnExit) process.off('exit', release)\n try {\n acquisition.lock.release()\n } catch {\n // release is best-effort; a leftover stale lock is reclaimed on next acquire\n }\n }\n try {\n for (const path of opts.alsoCheck ?? []) assertAvailable(path)\n } catch (error) {\n release()\n throw error\n }\n if (releaseOnExit) process.on('exit', release)\n return { release }\n}\n"],"mappings":";;;;;;;;;;;AAGA,MAAMA,uBAAqB;AA+D3B,SAAgB,gBAAgB,OAAgB,UAAmC;CACjF,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS,KAAK,MAAM,UAAU;AACjF;AAEA,SAAgB,wBAAwB,OAAgD;CACtF,IAAI,OAAO,UAAU,UAAU,OAAO,MAAM,KAAK,CAAC,CAAC,SAAS;CAC5D,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,UAAU,OAAO,QAAQ,KAAK;CACpC,OACE,QAAQ,SAAS,KACjB,QAAQ,OACL,CAAC,MAAM,aACN,KAAK,KAAK,CAAC,CAAC,SAAS,KAAK,KAAK,KAAK,MAAM,QAAQ,OAAO,YAAY,QACzE;AAEJ;AAEA,SAAgB,gBAAgB,OAAgB,OAAe,uBAAO,IAAI,IAAY,GAAS;CAC7F,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW;CAC/E,IAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,GAAG;CACzD,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxB,IAAI,KAAK,IAAI,KAAK,GAAG,MAAM,IAAI,MAAM,GAAG,MAAM,2BAA2B;EACzE,KAAK,IAAI,KAAK;EACd,KAAK,MAAM,QAAQ,OAAO,gBAAgB,MAAM,OAAO,IAAI;EAC3D,KA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