@tangle-network/agent-eval 0.144.0 → 0.144.3
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.
- package/CHANGELOG.md +36 -0
- package/dist/analyst/index.d.ts +88 -23
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +4 -4
- package/dist/{analyze-runs-BScZvqMV.js → analyze-runs-DWIvOAGk.js} +2 -2
- package/dist/{analyze-runs-BScZvqMV.js.map → analyze-runs-DWIvOAGk.js.map} +1 -1
- package/dist/{benchmark-DxaZfy0w.d.ts → benchmark-CP6kWfj8.d.ts} +3 -3
- package/dist/{benchmark-DxaZfy0w.d.ts.map → benchmark-CP6kWfj8.d.ts.map} +1 -1
- package/dist/{benchmark-command-4c7N_rlw.js → benchmark-command-CQPKRUr-.js} +332 -111
- package/dist/benchmark-command-CQPKRUr-.js.map +1 -0
- package/dist/benchmarks/index.d.ts +1 -1
- package/dist/benchmarks/index.js +1 -1
- package/dist/{benchmarks-05UGZ8sZ.js → benchmarks-CkG1bWFa.js} +4 -4
- package/dist/{benchmarks-05UGZ8sZ.js.map → benchmarks-CkG1bWFa.js.map} +1 -1
- package/dist/campaign/index.d.ts +6 -6
- package/dist/campaign/index.js +4 -4
- package/dist/{campaign-BKOtvRAB.js → campaign-DjGFyPxH.js} +74 -40
- package/dist/campaign-DjGFyPxH.js.map +1 -0
- package/dist/cli.js +2 -2
- package/dist/{client-Cgl6KasJ.d.ts → client-Bbht4xxl.d.ts} +4 -4
- package/dist/{client-Cgl6KasJ.d.ts.map → client-Bbht4xxl.d.ts.map} +1 -1
- package/dist/{completion-verifier-D15NHYSk.d.ts → completion-verifier-EJERfFwF.d.ts} +3 -3
- package/dist/{completion-verifier-D15NHYSk.d.ts.map → completion-verifier-EJERfFwF.d.ts.map} +1 -1
- package/dist/contract/index.d.ts +8 -8
- package/dist/contract/index.js +10 -8
- package/dist/contract/index.js.map +1 -1
- package/dist/control.d.ts +2 -2
- package/dist/control.js +1 -1
- package/dist/{default-registry-DfHJEwYh.js → default-registry-SOyHB6qG.js} +2 -2
- package/dist/{default-registry-DfHJEwYh.js.map → default-registry-SOyHB6qG.js.map} +1 -1
- package/dist/{default-registry-D3uqKbo6.d.ts → default-registry-iXfu2trt.d.ts} +5 -5
- package/dist/{default-registry-D3uqKbo6.d.ts.map → default-registry-iXfu2trt.d.ts.map} +1 -1
- package/dist/{dspy-rlm-engine-CBFwlyaY.js → dspy-rlm-engine-IRCG8kdi.js} +61 -105
- package/dist/dspy-rlm-engine-IRCG8kdi.js.map +1 -0
- package/dist/{eval-campaign-YdkpWWoT.js → eval-campaign-lZcDIwQM.js} +3 -3
- package/dist/{eval-campaign-YdkpWWoT.js.map → eval-campaign-lZcDIwQM.js.map} +1 -1
- package/dist/{exact-types-B0lJV3tu.d.ts → exact-types-BygCBR4L.d.ts} +2 -2
- package/dist/{exact-types-B0lJV3tu.d.ts.map → exact-types-BygCBR4L.d.ts.map} +1 -1
- package/dist/{external-optimizer-contracts-iK0yu4AR.d.ts → external-optimizer-contracts-CdmX2K2S.d.ts} +47 -10
- package/dist/external-optimizer-contracts-CdmX2K2S.d.ts.map +1 -0
- package/dist/{feedback-trajectory-BCHqzLh3.d.ts → feedback-trajectory-CSIkRLQX.d.ts} +3 -3
- package/dist/{feedback-trajectory-BCHqzLh3.d.ts.map → feedback-trajectory-CSIkRLQX.d.ts.map} +1 -1
- package/dist/hosted/index.d.ts +3 -3
- package/dist/{index-DgbFl4cv.d.ts → index-BuHs_OnD.d.ts} +17 -12
- package/dist/{index-DgbFl4cv.d.ts.map → index-BuHs_OnD.d.ts.map} +1 -1
- package/dist/{index-D2enbqA0.d.ts → index-CNOCxBLh.d.ts} +2 -2
- package/dist/{index-D2enbqA0.d.ts.map → index-CNOCxBLh.d.ts.map} +1 -1
- package/dist/{index-DFLVtPZ9.d.ts → index-DGIzNtRv.d.ts} +2 -2
- package/dist/{index-DFLVtPZ9.d.ts.map → index-DGIzNtRv.d.ts.map} +1 -1
- package/dist/{index-DtMpBKVF.d.ts → index-D_qTihaQ.d.ts} +5 -5
- package/dist/{index-DtMpBKVF.d.ts.map → index-D_qTihaQ.d.ts.map} +1 -1
- package/dist/index.d.ts +20 -20
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +17 -17
- package/dist/{insight-report-Bh_8ksel.d.ts → insight-report-D5m1z0_n.d.ts} +3 -3
- package/dist/{insight-report-Bh_8ksel.d.ts.map → insight-report-D5m1z0_n.d.ts.map} +1 -1
- package/dist/ledger-core/index.js +1 -1
- package/dist/{ledger-core-Dxz0Rkwa.js → ledger-core-DXZIqu17.js} +3 -3
- package/dist/ledger-core-DXZIqu17.js.map +1 -0
- package/dist/{llm-client-B3WXSH5Y.js → llm-client-D3EoChAU.js} +7 -7
- package/dist/llm-client-D3EoChAU.js.map +1 -0
- package/dist/meta-eval/index.d.ts +1 -1
- package/dist/{mint-Ctwk079K.js → mint-DD-0oQTA.js} +2 -2
- package/dist/{mint-Ctwk079K.js.map → mint-DD-0oQTA.js.map} +1 -1
- package/dist/multishot/index.d.ts +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{propose-review-control-DLXz4FCX.js → propose-review-control-BciUCZoh.js} +2 -2
- package/dist/{propose-review-control-DLXz4FCX.js.map → propose-review-control-BciUCZoh.js.map} +1 -1
- package/dist/{release-report-B_bQOHM-.d.ts → release-report-BZRWdq_t.d.ts} +3 -3
- package/dist/{release-report-B_bQOHM-.d.ts.map → release-report-BZRWdq_t.d.ts.map} +1 -1
- package/dist/{release-report-B5XPBvAU.js → release-report-Sl0xfkFv.js} +2 -2
- package/dist/{release-report-B5XPBvAU.js.map → release-report-Sl0xfkFv.js.map} +1 -1
- package/dist/{replay-DjUfTrHD.js → replay-CqOsGjzU.js} +2 -9
- package/dist/replay-CqOsGjzU.js.map +1 -0
- package/dist/{replay-BuJM6kLh.d.ts → replay-DQ-55DC_.d.ts} +4 -4
- package/dist/{replay-BuJM6kLh.d.ts.map → replay-DQ-55DC_.d.ts.map} +1 -1
- package/dist/reporting.d.ts +3 -3
- package/dist/reporting.js +1 -1
- package/dist/{researcher-C6lzl-rP.d.ts → researcher-BSiCoM1s.d.ts} +3 -3
- package/dist/{researcher-C6lzl-rP.d.ts.map → researcher-BSiCoM1s.d.ts.map} +1 -1
- package/dist/{reward-hacking-DjTi9HLb.js → reward-hacking-CyuzxKly.js} +2 -2
- package/dist/{reward-hacking-DjTi9HLb.js.map → reward-hacking-CyuzxKly.js.map} +1 -1
- package/dist/{reward-hacking-CEVVmy3h.d.ts → reward-hacking-DFgkEY4p.d.ts} +2 -2
- package/dist/{reward-hacking-CEVVmy3h.d.ts.map → reward-hacking-DFgkEY4p.d.ts.map} +1 -1
- package/dist/rl.d.ts +5 -5
- package/dist/rl.js +4 -4
- package/dist/rollout/index.d.ts +1 -1
- package/dist/rollout/index.js +2 -2
- package/dist/{rollout-8nj3mYvx.js → rollout-C2fD1cf4.js} +2 -2
- package/dist/{rollout-8nj3mYvx.js.map → rollout-C2fD1cf4.js.map} +1 -1
- package/dist/{rubric-predictive-validity-C2CthIfY.d.ts → rubric-predictive-validity-C4r4Y-q8.d.ts} +2 -2
- package/dist/{rubric-predictive-validity-C2CthIfY.d.ts.map → rubric-predictive-validity-C4r4Y-q8.d.ts.map} +1 -1
- package/dist/{run-evidence-8Ou28QSa.d.ts → run-evidence-H1vRpIdT.d.ts} +3 -3
- package/dist/{run-evidence-8Ou28QSa.d.ts.map → run-evidence-H1vRpIdT.d.ts.map} +1 -1
- package/dist/{run-record-vRgqWmJw.js → run-record-CWN8-VsV.js} +40 -14
- package/dist/{run-record-vRgqWmJw.js.map → run-record-CWN8-VsV.js.map} +1 -1
- package/dist/{run-record-Tb3TTtUn.d.ts → run-record-ooo9FWns.d.ts} +5 -9
- package/dist/{run-record-Tb3TTtUn.d.ts.map → run-record-ooo9FWns.d.ts.map} +1 -1
- package/dist/{semantic-concept-judge-DJQtFr95.js → semantic-concept-judge-Do5aM9wP.js} +3 -3
- package/dist/{semantic-concept-judge-DJQtFr95.js.map → semantic-concept-judge-Do5aM9wP.js.map} +1 -1
- package/dist/{server-Cu4M3NSO.js → server-Df00sdwz.js} +3 -3
- package/dist/{server-Cu4M3NSO.js.map → server-Df00sdwz.js.map} +1 -1
- package/dist/{single-run-lock-t1si1ob7.js → single-run-lock-D5iN0Xzb.js} +719 -187
- package/dist/single-run-lock-D5iN0Xzb.js.map +1 -0
- package/dist/{skill-usage-BiVEU0QY.d.ts → skill-usage-DtpLou9L.d.ts} +28 -9
- package/dist/skill-usage-DtpLou9L.d.ts.map +1 -0
- package/dist/{skillopt-optimization-method-Ds8J1_K8.js → skillopt-optimization-method-C4FX42dy.js} +42 -210
- package/dist/skillopt-optimization-method-C4FX42dy.js.map +1 -0
- package/dist/{skillopt-optimization-method-B7o01OdX.d.ts → skillopt-optimization-method-CvSJGdm3.d.ts} +12 -8
- package/dist/{skillopt-optimization-method-B7o01OdX.d.ts.map → skillopt-optimization-method-CvSJGdm3.d.ts.map} +1 -1
- package/dist/{summary-report-o3eJ3gxG.d.ts → summary-report-BOM6dfP7.d.ts} +2 -2
- package/dist/{summary-report-o3eJ3gxG.d.ts.map → summary-report-BOM6dfP7.d.ts.map} +1 -1
- package/dist/{tool-groups-Bqy4A3QB.d.ts → tool-groups-CMmsgTzj.d.ts} +7 -7
- package/dist/{tool-groups-Bqy4A3QB.d.ts.map → tool-groups-CMmsgTzj.d.ts.map} +1 -1
- package/dist/traces.d.ts +4 -4
- package/dist/traces.js +1 -1
- package/dist/types-BjMFz88h.d.ts.map +1 -1
- package/dist/{types-KEqL1pZc.d.ts → types-DcJxgsLy.d.ts} +8 -6
- package/dist/{types-KEqL1pZc.d.ts.map → types-DcJxgsLy.d.ts.map} +1 -1
- package/dist/{types-D3jh6F98.d.ts → types-y8jrxXWd.d.ts} +2 -2
- package/dist/{types-D3jh6F98.d.ts.map → types-y8jrxXWd.d.ts.map} +1 -1
- package/dist/wire/index.d.ts +1 -1
- package/dist/wire/index.js +1 -1
- package/docs/eval-surface-map.md +4 -0
- package/docs/trace-analysis.md +43 -32
- package/package.json +1 -1
- package/dist/benchmark-command-4c7N_rlw.js.map +0 -1
- package/dist/campaign-BKOtvRAB.js.map +0 -1
- package/dist/dspy-rlm-engine-CBFwlyaY.js.map +0 -1
- package/dist/external-optimizer-contracts-iK0yu4AR.d.ts.map +0 -1
- package/dist/ledger-core-Dxz0Rkwa.js.map +0 -1
- package/dist/llm-client-B3WXSH5Y.js.map +0 -1
- package/dist/replay-DjUfTrHD.js.map +0 -1
- package/dist/single-run-lock-t1si1ob7.js.map +0 -1
- package/dist/skill-usage-BiVEU0QY.d.ts.map +0 -1
- package/dist/skillopt-optimization-method-Ds8J1_K8.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dspy-rlm-engine-CBFwlyaY.js","names":["isRecord"],"sources":["../src/analyst/trace-tool-callback.ts","../src/analyst/dspy-rlm-engine.ts"],"sourcesContent":["import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport { closeServer, listenLocal, sendJson } from '../campaign/external-optimizer-http'\nimport type { TraceAnalysisToolDescriptor } from '../trace-analyst/tools'\n\nconst MAX_REQUEST_BYTES = 1_000_000\nconst MAX_RESPONSE_BYTES = 4_000_000\n\nexport interface TraceToolCallback {\n url: string\n token: string\n calls: () => number\n close: () => Promise<void>\n}\n\n/** Expose one bounded trace-tool set only on an authenticated loopback socket. */\nexport async function startTraceToolCallback(args: {\n tools: readonly TraceAnalysisToolDescriptor[]\n maxCalls: number\n signal?: AbortSignal\n}): Promise<TraceToolCallback> {\n if (!Number.isSafeInteger(args.maxCalls) || args.maxCalls <= 0) {\n throw new TypeError('trace tool callback maxCalls must be a positive safe integer')\n }\n args.signal?.throwIfAborted()\n const byName = new Map(args.tools.map((tool) => [tool.name, tool]))\n if (byName.size !== args.tools.length) {\n throw new Error('trace tool callback received duplicate tool names')\n }\n\n const token = randomBytes(32).toString('hex')\n let calls = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'trace tool callback is closing' })\n return\n }\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleRequest(request, response, controller.signal).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeCallback()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n\n return {\n url: `http://127.0.0.1:${port}/call`,\n token,\n calls: () => calls,\n close,\n }\n\n async function handleRequest(\n request: IncomingMessage,\n response: ServerResponse,\n signal: AbortSignal,\n ): Promise<void> {\n try {\n if (request.method !== 'POST' || request.url !== '/call') {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n if (calls >= args.maxCalls) {\n sendJsonIfOpen(response, 429, { error: 'trace tool call limit reached' })\n return\n }\n const body = await readJson(request)\n if (!isRecord(body) || typeof body.name !== 'string' || !('args' in body)) {\n sendJsonIfOpen(response, 400, { error: 'name and args are required' })\n return\n }\n const tool = byName.get(body.name)\n if (!tool) {\n sendJsonIfOpen(response, 404, { error: `unknown trace tool '${body.name}'` })\n return\n }\n calls += 1\n const result = await tool.handler(body.args, { signal })\n const encoded = JSON.stringify({ result })\n if (Buffer.byteLength(encoded) > MAX_RESPONSE_BYTES) {\n sendJsonIfOpen(response, 413, { error: 'trace tool response too large' })\n return\n }\n response.writeHead(200, {\n 'content-type': 'application/json; charset=utf-8',\n 'content-length': String(Buffer.byteLength(encoded)),\n })\n response.end(encoded)\n } catch (error) {\n sendJsonIfOpen(response, signal.aborted ? 499 : 400, {\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n async function closeCallback(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('trace tool callback closed with active requests')\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n }\n}\n\nasync function waitForActiveHandlers(activeHandlers: Set<Promise<void>>): Promise<void> {\n while (activeHandlers.size > 0) {\n await Promise.allSettled([...activeHandlers])\n }\n}\n\nfunction readJson(request: IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n let size = 0\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > MAX_REQUEST_BYTES) {\n reject(new Error('trace tool request too large'))\n request.destroy()\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n try {\n resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))\n } catch (error) {\n reject(error)\n }\n })\n })\n}\n\nfunction sendJsonIfOpen(response: ServerResponse, status: number, body: unknown): void {\n if (response.destroyed || response.writableEnded) return\n sendJson(response, status, body)\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","import {\n type ExternalOptimizerModelCall,\n type ExternalOptimizerModelExecutionObservation,\n type ExternalOptimizerModelProxy,\n type ExternalOptimizerRunnerCommand,\n removeCredentialEnvironment,\n} from '../campaign/external-optimizer-contracts'\nimport { startExternalOptimizerModelProxy } from '../campaign/external-optimizer-model-proxy'\nimport { runWithCleanup } from '../campaign/external-optimizer-resources'\nimport { runExternalOptimizerProcess } from '../campaign/external-optimizer-subprocess'\nimport type { CostReceiptInput, CustomTokenPricing } from '../cost-ledger'\nimport { resolveModelPricing } from '../metrics'\nimport type { TraceAnalysisEngine, TraceAnalysisEngineResult } from './engine'\nimport { type RawAnalystFinding, RawAnalystFindingSchema } from './finding-signature'\nimport { startTraceToolCallback } from './trace-tool-callback'\n\nconst DEFAULT_TIMEOUT_MS = 10 * 60_000\n// 4096 is below what current coding models emit for a full findings array:\n// glm-5.2 through an OpenAI-compatible gateway returns 8192 and the request is\n// rejected outright (`502 — provider reported 8192 completion tokens,\n// exceeding requested limit 4096`), so the default failed 2/2 smoke cases\n// before any analysis ran. The cap exists to bound spend, and `maxCostUsd`\n// already does that directly, so it starts above what a real completion needs.\nconst DEFAULT_MODEL_OUTPUT_TOKENS = 16_384\nconst DEFAULT_MAX_COST_USD = 1\nconst MAX_MODEL_REQUEST_BYTES = 16 * 1024 * 1024\nconst MAX_MODEL_RESPONSE_BYTES = 4 * 1024 * 1024\nconst BRIDGE_MODULE = 'agent_eval_rpc.dspy_rlm_bridge'\n/** Bumped whenever this engine's execution behavior changes. */\nconst DSPY_RLM_ENGINE_VERSION = '1.0.0'\n\nexport interface DspyRlmTraceEngineOptions {\n baseUrl: string\n apiKey: string\n model: string\n /** Exact provider rates. Required when the model is absent from the pricing table. */\n pricing?: CustomTokenPricing\n /** Maximum provider spend for one investigation. Default: 1 USD. */\n maxCostUsd?: number\n /** Controller response cap. Default: 16384. */\n maxOutputTokens?: number\n /**\n * Thinking tokens one controller turn may bill on top of its completion.\n * A reasoning model bills these beyond `maxOutputTokens`, so the cost\n * reservation must cover them. Default: four times the completion cap.\n */\n maxReasoningTokens?: number\n /**\n * How the controller's reasoning and code fields are obtained.\n *\n * `tolerant` parses marker output strictly first, then recovers the fields\n * deterministically from prose plus a fenced code block — the shape coding\n * models naturally emit — at no extra model cost. `two-step` extracts with a\n * second call per turn. `chat` accepts marker output only. Default:\n * `tolerant`.\n */\n controlAdapter?: 'chat' | 'two-step' | 'tolerant'\n /** Python command used to load agent-eval-rpc[dspy]. Default: python. */\n runner?: ExternalOptimizerRunnerCommand\n /** Whole investigation deadline. Default: 10 minutes. */\n timeoutMs?: number\n}\n\n/** Use the official DSPy RLM as a bounded recursive trace-analysis engine. */\nexport function createDspyRlmTraceEngine(options: DspyRlmTraceEngineOptions): TraceAnalysisEngine {\n assertOptions(options)\n const maxOutputTokens = options.maxOutputTokens ?? DEFAULT_MODEL_OUTPUT_TOKENS\n if (!Number.isSafeInteger(maxOutputTokens) || maxOutputTokens <= 0) {\n throw new TypeError('DSPy RLM maxOutputTokens must be a positive safe integer')\n }\n const controlAdapter = options.controlAdapter ?? 'tolerant'\n const maxReasoningTokens = options.maxReasoningTokens ?? maxOutputTokens * 4\n if (!Number.isSafeInteger(maxReasoningTokens) || maxReasoningTokens < 0) {\n throw new TypeError('DSPy RLM maxReasoningTokens must be a non-negative safe integer')\n }\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw new TypeError('DSPy RLM timeoutMs must be a positive safe integer')\n }\n const maxCostUsd = options.maxCostUsd ?? DEFAULT_MAX_COST_USD\n if (!Number.isFinite(maxCostUsd) || maxCostUsd <= 0) {\n throw new TypeError('DSPy RLM maxCostUsd must be positive and finite')\n }\n const pricing = options.pricing ?? pricingForModel(options.model)\n\n const runner = sanitizedRunner(options.runner)\n return {\n id: 'dspy-rlm',\n description: 'Official DSPy RLM with bounded trace tools and metered model calls.',\n model: options.model,\n version: DSPY_RLM_ENGINE_VERSION,\n executionConfig: {\n bridge_module: BRIDGE_MODULE,\n base_url: options.baseUrl,\n model: options.model,\n api_key_provided: true,\n pricing: { ...pricing },\n max_cost_usd: maxCostUsd,\n max_output_tokens: maxOutputTokens,\n max_reasoning_tokens: maxReasoningTokens,\n control_adapter: controlAdapter,\n timeout_ms: timeoutMs,\n max_request_bytes: MAX_MODEL_REQUEST_BYTES,\n max_response_bytes: MAX_MODEL_RESPONSE_BYTES,\n runner: runner ? 'caller-supplied' : 'default',\n runner_command: runner?.command ?? null,\n },\n async analyze(request) {\n const callback = await startTraceToolCallback({\n tools: request.tools,\n maxCalls: request.limits.maxToolCalls,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n let modelProxy: ExternalOptimizerModelProxy | undefined\n const modelExecutions: ExternalOptimizerModelExecutionObservation[] = []\n const result = await runWithCleanup({\n label: 'DSPy RLM trace-analysis resources',\n run: async () => {\n modelProxy = await startExternalOptimizerModelProxy({\n call: dspyModelCall(options, pricing),\n callRef: `dspy-rlm:${options.model}:${new URL(options.baseUrl).origin}`,\n recordExecution: (observation) => {\n modelExecutions.push(structuredClone(observation))\n },\n model: options.model,\n budget: {\n maxCostUsd,\n maxRequests: request.limits.maxIterations + request.limits.maxLlmCalls + 1,\n maxRequestBytes: MAX_MODEL_REQUEST_BYTES,\n maxResponseBytes: MAX_MODEL_RESPONSE_BYTES,\n maxOutputTokensPerRequest: maxOutputTokens,\n maxReasoningTokensPerRequest: maxReasoningTokens,\n requestTimeoutMs: timeoutMs,\n pricing,\n },\n costLedger: request.costLedger,\n channel: 'analyst',\n phase: request.costPhase,\n actor: request.analystId,\n ...(request.costTags ? { tags: request.costTags } : {}),\n ...(request.signal ? { signal: request.signal } : {}),\n })\n request.log?.('trace analyst engine started', {\n engine: 'dspy-rlm',\n model: options.model,\n tools: request.tools.map((tool) => tool.name),\n limits: request.limits,\n })\n const raw = await runExternalOptimizerProcess<unknown>({\n label: 'DSPy RLM trace analysis',\n tempPrefix: 'agent-eval-dspy-rlm-',\n module: BRIDGE_MODULE,\n input: {\n operation: 'analyze',\n question: request.question,\n instructions: request.instructions,\n modelProxy: {\n baseUrl: modelProxy.baseUrl,\n apiKey: modelProxy.apiKey,\n model: options.model,\n maxOutputTokens,\n },\n toolCallback: {\n url: callback.url,\n token: callback.token,\n },\n toolSpecs: request.tools.map(({ name, description, parameters }) => ({\n name,\n description,\n parameters,\n })),\n controlAdapter,\n limits: {\n maxIterations: request.limits.maxIterations,\n maxLlmCalls: request.limits.maxLlmCalls,\n maxOutputChars: request.limits.maxOutputChars,\n },\n },\n ...(runner ? { runner } : {}),\n timeoutMs,\n ...(request.signal ? { signal: request.signal } : {}),\n })\n const parsed = parseBridgeOutput(raw, (index, reason) => {\n request.log?.('finding rejected: bridge row failed schema validation', {\n engine: 'dspy-rlm',\n index,\n reason,\n })\n })\n const successfulCompletions = modelProxy.successfulCompletions()\n const requestAttempts = modelProxy.requestAttempts()\n if (parsed.modelCalls !== successfulCompletions) {\n throw new Error(\n `DSPy RLM reported ${parsed.modelCalls} model calls, but the provider proxy recorded ${successfulCompletions}`,\n )\n }\n modelProxy.assertExecutionComplete()\n return {\n ...parsed,\n toolCalls: callback.calls(),\n runtime: {\n ...parsed.runtime,\n modelRequestAttempts: requestAttempts,\n modelSuccessfulCompletions: successfulCompletions,\n modelExecutions,\n },\n } satisfies TraceAnalysisEngineResult\n },\n cleanup: async () => {\n const results = await Promise.allSettled([\n ...(modelProxy ? [modelProxy.close()] : []),\n callback.close(),\n ])\n const errors = results.flatMap((entry) =>\n entry.status === 'rejected' ? [entry.reason] : [],\n )\n if (errors.length > 0) {\n throw new AggregateError(errors, 'DSPy RLM resource cleanup failed')\n }\n },\n })\n request.log?.('trace analyst engine completed', {\n engine: 'dspy-rlm',\n model_calls: result.modelCalls,\n model_request_attempts: result.runtime.modelRequestAttempts,\n tool_calls: result.toolCalls,\n findings: result.findings.length,\n })\n return result\n },\n }\n}\n\nfunction parseBridgeOutput(\n value: unknown,\n onRejectedFinding: (index: number, reason: string) => void,\n): Omit<TraceAnalysisEngineResult, 'toolCalls'> {\n if (!isRecord(value)) throw new Error('DSPy RLM bridge output must be an object')\n if (typeof value.answer !== 'string' || !value.answer.trim()) {\n throw new Error('DSPy RLM bridge returned no answer')\n }\n if (!Array.isArray(value.findings)) {\n throw new Error('DSPy RLM bridge findings must be an array')\n }\n // Findings are model output: one malformed row is model noise, not a bridge\n // fault, and the rest of the paid investigation must survive it. Rejected\n // rows are logged per row and counted in runtime.rejectedFindings.\n let rejectedFindings = 0\n const findings: RawAnalystFinding[] = []\n value.findings.forEach((finding, index) => {\n const parsed = RawAnalystFindingSchema.safeParse(finding)\n if (!parsed.success) {\n rejectedFindings += 1\n onRejectedFinding(\n index,\n parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; '),\n )\n return\n }\n findings.push(parsed.data)\n })\n if (!Array.isArray(value.trajectory)) {\n throw new Error('DSPy RLM bridge trajectory must be an array')\n }\n if (!Number.isSafeInteger(value.modelCalls) || (value.modelCalls as number) <= 0) {\n throw new Error('DSPy RLM bridge modelCalls must be a positive safe integer')\n }\n if (!isRecord(value.runtime)) {\n throw new Error('DSPy RLM bridge runtime must be an object')\n }\n return {\n answer: value.answer,\n findings,\n trajectory: value.trajectory,\n modelCalls: value.modelCalls as number,\n runtime: { ...value.runtime, rejectedFindings },\n }\n}\n\nfunction assertOptions(options: DspyRlmTraceEngineOptions): void {\n for (const [name, value] of [\n ['baseUrl', options.baseUrl],\n ['apiKey', options.apiKey],\n ['model', options.model],\n ] as const) {\n if (typeof value !== 'string' || !value.trim()) {\n throw new TypeError(`DSPy RLM ${name} must be a non-empty string`)\n }\n }\n let baseUrl: URL\n try {\n baseUrl = new URL(options.baseUrl)\n } catch {\n throw new TypeError('DSPy RLM baseUrl must be an HTTP(S) URL')\n }\n if (\n (baseUrl.protocol !== 'http:' && baseUrl.protocol !== 'https:') ||\n baseUrl.username ||\n baseUrl.password ||\n baseUrl.search ||\n baseUrl.hash\n ) {\n throw new TypeError(\n 'DSPy RLM baseUrl must be an HTTP(S) URL without credentials, query, or fragment',\n )\n }\n}\n\nfunction dspyModelCall(\n options: DspyRlmTraceEngineOptions,\n pricing: CustomTokenPricing,\n): ExternalOptimizerModelCall {\n return async (request) => {\n const started = performance.now()\n const baseUrl = options.baseUrl.replace(/\\/+$/, '')\n const path = /\\/v\\d+$/.test(baseUrl) ? request.path.replace(/^\\/v1/, '') : request.path\n try {\n const response = await fetch(`${baseUrl}${path}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${options.apiKey}`,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(request.body),\n signal: request.signal,\n redirect: 'error',\n })\n return {\n succeeded: true,\n response,\n receipt: await dspyResponseReceipt(response.clone(), request.model, pricing),\n execution: {\n kind: 'agent-eval/dspy-rlm-model-call',\n model: request.model,\n path: request.path,\n status: response.status,\n durationMs: performance.now() - started,\n },\n }\n } catch (error) {\n return {\n succeeded: false,\n error: error instanceof Error ? error.message : String(error),\n receipt: unknownDspyReceipt(request.model),\n execution: {\n kind: 'agent-eval/dspy-rlm-model-call',\n model: request.model,\n path: request.path,\n error: error instanceof Error ? error.name : 'Error',\n durationMs: performance.now() - started,\n },\n }\n }\n }\n}\n\nasync function dspyResponseReceipt(\n response: Response,\n model: string,\n pricing: CustomTokenPricing,\n): Promise<CostReceiptInput> {\n let value: unknown\n try {\n value = await response.json()\n } catch {\n return unknownDspyReceipt(model)\n }\n if (!isRecord(value) || !isRecord(value.usage)) return unknownDspyReceipt(model)\n const inputTokens = value.usage.prompt_tokens ?? value.usage.input_tokens\n const outputTokens = value.usage.completion_tokens ?? value.usage.output_tokens\n if (\n !Number.isSafeInteger(inputTokens) ||\n (inputTokens as number) < 0 ||\n !Number.isSafeInteger(outputTokens) ||\n (outputTokens as number) < 0\n ) {\n return unknownDspyReceipt(model)\n }\n const actualCostUsd = value.usage.cost\n return {\n model,\n inputTokens: inputTokens as number,\n outputTokens: outputTokens as number,\n ...(typeof actualCostUsd === 'number' && Number.isFinite(actualCostUsd) && actualCostUsd >= 0\n ? { actualCostUsd }\n : { customTokenPricing: pricing }),\n }\n}\n\nfunction unknownDspyReceipt(model: string): CostReceiptInput {\n return {\n model,\n inputTokens: 0,\n outputTokens: 0,\n usageUnknown: true,\n costUnknown: true,\n }\n}\n\nfunction pricingForModel(model: string): CustomTokenPricing {\n const pricing = resolveModelPricing(model)\n if (!pricing) {\n throw new Error(\n `no pricing is configured for '${model}'; provide DspyRlmTraceEngineOptions.pricing`,\n )\n }\n return {\n inputUsdPerMillion: pricing.input * 1_000,\n outputUsdPerMillion: pricing.output * 1_000,\n }\n}\n\nfunction sanitizedRunner(\n runner: ExternalOptimizerRunnerCommand | undefined,\n): ExternalOptimizerRunnerCommand | undefined {\n if (!runner) return undefined\n return {\n ...(runner.command ? { command: runner.command } : {}),\n ...(runner.args ? { args: runner.args } : {}),\n ...(runner.env ? { env: removeCredentialEnvironment(runner.env) } : {}),\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n"],"mappings":";;;;;;AAKA,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;;AAU3B,eAAsB,uBAAuB,MAId;CAC7B,IAAI,CAAC,OAAO,cAAc,KAAK,QAAQ,KAAK,KAAK,YAAY,GAC3D,MAAM,IAAI,UAAU,8DAA8D;CAEpF,KAAK,QAAQ,eAAe;CAC5B,MAAM,SAAS,IAAI,IAAI,KAAK,MAAM,KAAK,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC,CAAC;CAClE,IAAI,OAAO,SAAS,KAAK,MAAM,QAC7B,MAAM,IAAI,MAAM,mDAAmD;CAGrE,MAAM,QAAQ,YAAY,EAAE,CAAC,CAAC,SAAS,KAAK;CAC5C,IAAI,QAAQ;CACZ,IAAI,YAAY;CAChB,IAAI;CACJ,MAAM,oCAAoB,IAAI,IAAqB;CACnD,MAAM,iCAAiB,IAAI,IAAmB;CAC9C,MAAM,SAAS,cAAc,SAAS,aAAa;EACjD,IAAI,CAAC,WAAW;GACd,eAAe,UAAU,KAAK,EAAE,OAAO,iCAAiC,CAAC;GACzE;EACF;EACA,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,qBAA2B;GAC/B,QAA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CAAC,SACH,MAAM,IAAI,MACR,iCAAiC,MAAM,6CACzC;CAEF,OAAO;EACL,oBAAoB,QAAQ,QAAQ;EACpC,qBAAqB,QAAQ,SAAS;CACxC;AACF;AAEA,SAAS,gBACP,QAC4C;CAC5C,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,OAAO;EACL,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;EACpD,GAAI,OAAO,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;EAC3C,GAAI,OAAO,MAAM,EAAE,KAAK,4BAA4B,OAAO,GAAG,EAAE,IAAI,CAAC;CACvE;AACF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"external-optimizer-contracts-iK0yu4AR.d.ts","names":[],"sources":["../src/campaign/external-optimizer-contracts.ts"],"mappings":";;UAKiB;EACf;EACA;EACA,MAAM,OAAO;;KAGH;KAEA,iCAAiC;UAE5B;EACf,WAAW;EACX;;;UAWe;WACN;WACA;WACA,MAAM,SAAS;WACf,QAAQ;;;KAIP;WAEG;;WAEA,UAAU;;WAEV,SAFU;;WAIV;;WAGA;;WAEA;;WAEA,SATkC;;WAWlC;;;;;;;;;;;;KAaH,8BACV,SAAS,sCACN,QAAQ;;KAGD;WAEG;WACA;WACA,MAAM;WACN;WACA;WACA;WACA;;WAGA;WACA;WACA,MAAM;WACN;WACA;WACA;WACA;;KAGH;;;;;;KAUA;WAEG;WACA;WACA,WAAW;WACX;;WAGA;WACA;WACA,WAAW;WACX;WACA;;WAEA;WACA;;WAGA;WACA;WACA,QAAQ;WACR,YAAY;WACZ;WACA;;UAGE;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;;;;EAUA;;;;;;EAMA,UAAU;;EAEV"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ledger-core-Dxz0Rkwa.js","names":[],"sources":["../src/concurrency.ts","../src/ledger-core/atomic-file-lock.ts","../src/ledger-core/journal-file.ts","../src/ledger-core/trusted-head.ts","../src/ledger-core/journal.ts"],"sourcesContent":["/**\n * concurrency — small primitives the evolution loop needs.\n *\n * `Mutex` is a zero-dep async lock with FIFO fairness. The evolution loop\n * uses it to serialise checkout/build/commit sequences inside a single\n * pool slot, and to gate concurrent JSONL writers (see\n * `lockedJsonlReferenceReplayStore`).\n *\n * Deliberately minimal — no priority queue, no timeouts. If you need\n * those, swap to `async-mutex` at the call site.\n */\n\nexport class Mutex {\n private locked = false\n private readonly waiters: Array<() => void> = []\n\n async acquire(): Promise<() => void> {\n if (!this.locked) {\n this.locked = true\n return () => this.release()\n }\n return new Promise<() => void>((resolve) => {\n this.waiters.push(() => {\n resolve(() => this.release())\n })\n })\n }\n\n private release(): void {\n const next = this.waiters.shift()\n if (next) {\n next()\n } else {\n this.locked = false\n }\n }\n\n async runExclusive<T>(fn: () => Promise<T> | T): Promise<T> {\n const release = await this.acquire()\n try {\n return await fn()\n } finally {\n release()\n }\n }\n\n /** True iff someone holds the lock right now. Diagnostics only. */\n get isLocked(): boolean {\n return this.locked\n }\n\n /** Pending waiter count. Diagnostics only. */\n get pending(): number {\n return this.waiters.length\n }\n}\n\nexport interface MapConcurrentRangeOptions<R> {\n count: number\n maxConcurrency: number\n label: string\n signal?: AbortSignal\n map(index: number, signal: AbortSignal): Promise<R>\n}\n\n/** Map an integer range with bounded work, cancellation, and first-error cleanup. */\nexport async function mapConcurrentRange<R>(options: MapConcurrentRangeOptions<R>): Promise<R[]> {\n if (!Number.isSafeInteger(options.count) || options.count < 0) {\n throw new Error(`${options.label} count must be a non-negative integer`)\n }\n if (!Number.isSafeInteger(options.maxConcurrency) || options.maxConcurrency < 1) {\n throw new Error(`${options.label} maxConcurrency must be a positive integer`)\n }\n\n const controller = new AbortController()\n const abortFromCaller = () => controller.abort(options.signal?.reason)\n if (options.signal?.aborted) abortFromCaller()\n else options.signal?.addEventListener('abort', abortFromCaller, { once: true })\n\n const results = new Array<R>(options.count)\n let nextIndex = 0\n let failed = false\n let firstFailure: unknown\n const workers = Array.from(\n { length: Math.min(options.maxConcurrency, options.count) },\n async () => {\n while (!controller.signal.aborted) {\n const index = nextIndex\n nextIndex += 1\n if (index >= options.count) return\n try {\n results[index] = await options.map(index, controller.signal)\n } catch (error) {\n if (!failed) {\n failed = true\n firstFailure = error\n controller.abort(error)\n }\n return\n }\n }\n },\n )\n\n try {\n await Promise.all(workers)\n if (options.signal?.aborted) throw abortError(options.signal, options.label)\n if (failed) throw firstFailure\n if (controller.signal.aborted) throw abortError(controller.signal, options.label)\n return results\n } finally {\n options.signal?.removeEventListener('abort', abortFromCaller)\n }\n}\n\n/**\n * Map independent work with a fixed worker count while preserving input order.\n * After the first rejection, no new items start; already-running work is allowed\n * to settle before the returned promise rejects. Partial results are discarded.\n */\nexport async function mapConcurrent<T, R>(\n items: readonly T[],\n concurrency: number,\n map: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n return mapConcurrentRange({\n count: items.length,\n maxConcurrency: concurrency,\n label: 'mapConcurrent',\n map(index) {\n return map(items[index]!, index)\n },\n })\n}\n\nfunction abortError(signal: AbortSignal, label: string): Error {\n return signal.reason instanceof Error ? signal.reason : new Error(`${label} aborted`)\n}\n","/** Crash-safe filesystem lock shared by campaign persistence and run exclusion. */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n constants,\n existsSync,\n fsyncSync,\n linkSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { hostname } from 'node:os'\n\nexport interface AtomicFileLockOwner {\n readonly pid: number\n readonly host: string\n readonly nonce: string\n}\n\nexport interface AtomicFileLock {\n readonly owner: AtomicFileLockOwner\n release(): void\n}\n\nexport type AtomicFileLockUnavailable =\n | { readonly acquired: false; readonly reason: 'held'; readonly holder: AtomicFileLockOwner }\n | { readonly acquired: false; readonly reason: 'recovery' }\n\nexport type AtomicFileLockAcquisition =\n | { readonly acquired: true; readonly lock: AtomicFileLock }\n | AtomicFileLockUnavailable\n\nexport interface AtomicFileLockOptions {\n readonly lockPath: string\n readonly pid?: number\n}\n\nexport class AtomicFileLockError extends Error {\n override readonly name = 'AtomicFileLockError'\n}\n\ntype OwnerState =\n | { readonly state: 'missing' }\n | { readonly state: 'stale'; readonly owner: AtomicFileLockOwner }\n | { readonly state: 'held'; readonly owner: AtomicFileLockOwner }\n\n/** Report whether another lock path prevents acquisition without modifying it. */\nexport function probeAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockUnavailable | null {\n if (existsSync(recoveryPath(options.lockPath))) return { acquired: false, reason: 'recovery' }\n const state = ownerState(options.lockPath)\n if (state.state === 'held') {\n return { acquired: false, reason: 'held', holder: state.owner }\n }\n return null\n}\n\n/**\n * Try to acquire a complete, uniquely-owned lock inode.\n *\n * A hard link publishes fully-written owner metadata atomically. Stale-owner\n * removal is serialized so one reclaimer cannot delete a new owner's lock.\n */\nexport function tryAcquireAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockAcquisition {\n const pid = options.pid ?? process.pid\n if (!Number.isSafeInteger(pid) || pid <= 0) {\n throw new AtomicFileLockError('atomic file lock pid must be a positive integer')\n }\n const owner: AtomicFileLockOwner = { pid, host: hostname(), nonce: randomUUID() }\n for (let attempt = 0; attempt < 8; attempt += 1) {\n if (existsSync(recoveryPath(options.lockPath))) {\n const recovery = tryAcquireRecoveryLease(options.lockPath, owner, attempt)\n if (!recovery) return { acquired: false, reason: 'recovery' }\n try {\n return recoverLock(options.lockPath, owner, attempt)\n } finally {\n recovery.release()\n }\n }\n if (tryLinkOwner(options.lockPath, owner, `acquire.${attempt}`)) {\n return acquired(options.lockPath, owner)\n }\n\n const holder = ownerState(options.lockPath)\n if (holder.state === 'missing') continue\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n\n const recovery = tryAcquireRecoveryLease(options.lockPath, owner, attempt)\n if (!recovery) return { acquired: false, reason: 'recovery' }\n try {\n return recoverLock(options.lockPath, owner, attempt)\n } finally {\n recovery.release()\n }\n }\n\n throw new AtomicFileLockError(`could not acquire atomic file lock ${options.lockPath}`)\n}\n\ninterface RecoveryLease {\n release(): void\n}\n\nfunction tryAcquireRecoveryLease(\n lockPath: string,\n owner: AtomicFileLockOwner,\n attempt: number,\n): RecoveryLease | null {\n let leasePath = recoveryPath(lockPath)\n const staleOwners: Array<{ path: string; owner: AtomicFileLockOwner }> = []\n\n for (let depth = 0; depth < 64; depth += 1) {\n const state = ownerState(leasePath)\n if (state.state === 'missing') {\n if (!tryLinkOwner(leasePath, owner, `reclaim.${attempt}.${depth}`)) continue\n return {\n release: () => {\n for (const stale of staleOwners) releaseOwnedPath(stale.path, stale.owner)\n releaseOwnedPath(leasePath, owner)\n },\n }\n }\n if (state.state === 'held') return null\n staleOwners.push({ path: leasePath, owner: state.owner })\n leasePath = `${leasePath}.next.${state.owner.nonce}`\n }\n\n throw new AtomicFileLockError(`atomic file lock recovery chain is too deep (${lockPath})`)\n}\n\nfunction recoverLock(\n lockPath: string,\n owner: AtomicFileLockOwner,\n attempt: number,\n): AtomicFileLockAcquisition {\n const current = ownerState(lockPath)\n if (current.state === 'held') {\n return { acquired: false, reason: 'held', holder: current.owner }\n }\n if (current.state === 'stale') {\n const tombstone = `${lockPath}.stale.${owner.nonce}.${attempt}`\n try {\n renameSync(lockPath, tombstone)\n unlinkSync(tombstone)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n }\n if (tryLinkOwner(lockPath, owner, `recovered.${attempt}`)) {\n return acquired(lockPath, owner)\n }\n const holder = ownerState(lockPath)\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n return { acquired: false, reason: 'recovery' }\n}\n\nfunction acquired(lockPath: string, owner: AtomicFileLockOwner): AtomicFileLockAcquisition {\n return {\n acquired: true,\n lock: {\n owner,\n release: () => releaseOwnedPath(lockPath, owner),\n },\n }\n}\n\nfunction tryLinkOwner(lockPath: string, owner: AtomicFileLockOwner, suffix: string): boolean {\n const ownerPath = `${lockPath}.${owner.pid}.${owner.nonce}.${suffix}.owner`\n const descriptor = openSync(\n ownerPath,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o600,\n )\n try {\n writeFileSync(descriptor, `${canonicalOwner(owner)}\\n`, 'utf8')\n fsyncSync(descriptor)\n } catch (error) {\n closeSync(descriptor)\n unlinkIfExists(ownerPath)\n throw error\n }\n closeSync(descriptor)\n\n try {\n linkSync(ownerPath, lockPath)\n return true\n } catch (error) {\n if (!isAlreadyExists(error)) throw error\n return false\n } finally {\n unlinkIfExists(ownerPath)\n }\n}\n\nfunction ownerState(lockPath: string): OwnerState {\n const owner = readOwner(lockPath)\n if (!owner) return { state: 'missing' }\n if (owner.host !== hostname()) return { state: 'held', owner }\n try {\n process.kill(owner.pid, 0)\n return { state: 'held', owner }\n } catch (error) {\n if (isNoSuchProcess(error)) return { state: 'stale', owner }\n return { state: 'held', owner }\n }\n}\n\nfunction readOwner(lockPath: string): AtomicFileLockOwner | undefined {\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8').trim()\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n\n let value: unknown\n try {\n value = JSON.parse(contents)\n } catch (error) {\n throw invalidOwner(lockPath, error)\n }\n if (!isOwner(value)) throw invalidOwner(lockPath)\n return value\n}\n\nfunction isOwner(value: unknown): value is AtomicFileLockOwner {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return (\n Object.keys(record).length === 3 &&\n Number.isSafeInteger(record.pid) &&\n Number(record.pid) > 0 &&\n typeof record.host === 'string' &&\n record.host.trim().length > 0 &&\n typeof record.nonce === 'string' &&\n record.nonce.trim().length > 0\n )\n}\n\nfunction invalidOwner(lockPath: string, cause?: unknown): AtomicFileLockError {\n const error = new AtomicFileLockError(\n `atomic file lock has an invalid owner (${lockPath}); refusing unsafe recovery`,\n )\n if (cause !== undefined) Object.defineProperty(error, 'cause', { value: cause })\n return error\n}\n\nfunction releaseOwnedPath(lockPath: string, owner: AtomicFileLockOwner): void {\n const current = readOwner(lockPath)\n if (!current) return\n if (canonicalOwner(current) !== canonicalOwner(owner)) {\n throw new AtomicFileLockError(`atomic file lock owner changed before release (${lockPath})`)\n }\n try {\n unlinkSync(lockPath)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n\nfunction canonicalOwner(owner: AtomicFileLockOwner): string {\n return JSON.stringify({ host: owner.host, nonce: owner.nonce, pid: owner.pid })\n}\n\nfunction recoveryPath(lockPath: string): string {\n return `${lockPath}.reclaim`\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'EEXIST'\n}\n\nfunction isMissing(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ENOENT'\n}\n\nfunction isNoSuchProcess(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ESRCH'\n}\n\nfunction unlinkIfExists(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n","/** Filesystem durability and cross-process exclusion for append-only journal files. */\n\nimport {\n closeSync,\n constants,\n fstatSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readSync,\n renameSync,\n rmSync,\n writeSync,\n} from 'node:fs'\nimport { dirname } from 'node:path'\nimport { AtomicFileLockError, tryAcquireAtomicFileLock } from './atomic-file-lock'\n\n/** How a journal binding reports file-layer faults in its own error taxonomy. */\nexport interface LedgerFileContext {\n /** Noun used in error messages, e.g. 'search ledger'. */\n subject: string\n integrityError(message: string, options?: { cause?: unknown }): Error\n}\n\n/** Append one already-serialized line; the write is fsynced (file and directory)\n * before returning so an acknowledged append survives a crash. */\nexport function appendLedgerLine(path: string, line: string, context: LedgerFileContext): void {\n mkdirSync(dirname(path), { recursive: true })\n recoverTornFinalWrite(path, context)\n const fd = openSync(path, constants.O_CREAT | constants.O_WRONLY | constants.O_APPEND, 0o600)\n try {\n writeAll(fd, Buffer.from(line, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n fsyncDirectory(dirname(path))\n}\n\nfunction recoverTornFinalWrite(path: string, context: LedgerFileContext): void {\n let fd: number\n try {\n fd = openSync(path, constants.O_RDWR)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw context.integrityError(`${context.subject} ${path} could not be opened for recovery`, {\n cause: error,\n })\n }\n\n try {\n const size = fstatSync(fd).size\n if (size === 0 || readByte(fd, size - 1) === 0x0a) return\n const tailStart = findFinalLineStart(fd, size)\n const replacement = Buffer.alloc(size - tailStart, 0x20)\n replacement[replacement.length - 1] = 0x0a\n writeAllAt(fd, replacement, tailStart, context)\n fsyncSync(fd)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} ${path} has an unrecoverable final journal write`,\n { cause: error },\n )\n } finally {\n closeSync(fd)\n }\n}\n\n/** Replace a small sidecar file whole: write a temporary sibling, fsync it,\n * then rename over the target. A reader therefore sees the previous contents\n * or the new ones, never a partial file. */\nexport function writeLedgerFileAtomically(\n path: string,\n contents: string,\n context: LedgerFileContext,\n): void {\n const directory = dirname(path)\n mkdirSync(directory, { recursive: true })\n const temporaryPath = `${path}.tmp`\n const fd = openSync(\n temporaryPath,\n constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC,\n 0o600,\n )\n try {\n writeAll(fd, Buffer.from(contents, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n renameSync(temporaryPath, path)\n fsyncDirectory(directory)\n}\n\n/** Remove whatever occupies a sidecar path and fsync its directory, so the\n * removal is as durable as the write that created it. False when the path was\n * already empty. Recursive because a sidecar path holding a directory is one of\n * the states this has to be able to clear, not one it can refuse. */\nexport function removeLedgerFile(path: string, context: LedgerFileContext): boolean {\n try {\n rmSync(path, { recursive: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw context.integrityError(`${context.subject} ${path} could not be removed`, {\n cause: error,\n })\n }\n fsyncDirectory(dirname(path))\n return true\n}\n\nexport function withLedgerFileLock<T>(path: string, context: LedgerFileContext, run: () => T): T {\n const result = tryWithLedgerFileLock(path, context, run)\n if (!result.acquired) {\n throw context.integrityError(`${context.subject} lock is held (${path})`)\n }\n return result.value\n}\n\nexport type FileLockResult<T> = { acquired: true; value: T } | { acquired: false }\n\nexport function tryWithLedgerFileLock<T>(\n path: string,\n context: LedgerFileContext,\n run: () => T,\n): FileLockResult<T> {\n mkdirSync(dirname(path), { recursive: true })\n const lockPath = `${path}.lock`\n try {\n const acquisition = tryAcquireAtomicFileLock({ lockPath })\n if (!acquisition.acquired) return { acquired: false }\n try {\n return { acquired: true, value: run() }\n } finally {\n acquisition.lock.release()\n }\n } catch (error) {\n if (error instanceof AtomicFileLockError) {\n throw context.integrityError(error.message, { cause: error })\n }\n throw error\n }\n}\n\nfunction writeAll(fd: number, bytes: Buffer, context: LedgerFileContext): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset)\n if (written <= 0) throw context.integrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction writeAllAt(fd: number, bytes: Buffer, position: number, context: LedgerFileContext): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset, position + offset)\n if (written <= 0) throw context.integrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction findFinalLineStart(fd: number, size: number): number {\n const chunk = Buffer.alloc(Math.min(4_096, size))\n let cursor = size\n while (cursor > 0) {\n const length = Math.min(chunk.byteLength, cursor)\n cursor -= length\n const read = readSync(fd, chunk, 0, length, cursor)\n for (let index = read - 1; index >= 0; index -= 1) {\n if (chunk[index] === 0x0a) return cursor + index + 1\n }\n }\n return 0\n}\n\nfunction readByte(fd: number, position: number): number {\n const byte = Buffer.allocUnsafe(1)\n const read = readSync(fd, byte, 0, 1, position)\n return read === 1 ? byte[0]! : -1\n}\n\nfunction fsyncDirectory(path: string): void {\n const fd = openSync(path, constants.O_RDONLY)\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n","/**\n * Trusted head — the pin that makes deletion detectable.\n *\n * ## What the chain binds\n *\n * Every entry hashes the journal header, its sequence, the previous entry's\n * hash, and its event, so editing, reordering, or removing an entry in the\n * middle of a journal invalidates every hash after it. What a hash chain\n * cannot bind is its own length. Dropping entries off the END leaves a shorter\n * journal that is internally perfect, and rebuilding a journal from sequence 0\n * with recomputed hashes produces a different, equally perfect chain. For an\n * audit log of candidate registrations and promotion decisions that is the\n * difference between a record of a search that happened and a record of one\n * that did not.\n *\n * ## What the pin binds\n *\n * `<journal>.head` holds `{sequence, entryHash}` for one entry a writer\n * actually appended, in a file separate from the journal it attests. Each\n * entry hash commits to the entire prefix before it, so checking that the\n * entry at exactly `sequence` still carries `entryHash` proves two things at\n * once: the journal is at least `sequence + 1` entries long, and those entries\n * are byte-for-byte the ones the writer saw. A journal that merely grew past\n * the pin still verifies; a truncated, rolled-back, or wholesale-rewritten one\n * cannot.\n *\n * ## What the pin does NOT defend against\n *\n * The pin is a second file, not a signature. A writer with access to BOTH the\n * journal and its pin can rewrite both consistently, and the result verifies.\n * Pinning raises the cost of undetected tampering from one file to two and\n * nothing more; defending against a writer who holds both requires an anchor\n * outside this store entirely — a signed head, or a digest published to an\n * append-only service the tamperer does not control.\n *\n * Deleting the pin file downgrades a pinned journal to an unpinned one, which\n * cannot be distinguished from a journal written before pinning existed. That\n * is what `requireTrustedHead` is for: a journal opened under it refuses to\n * read at all once a non-empty journal has no pin.\n *\n * ## Abandoning a pin\n *\n * A pin outlives the journal it attests: deleting or rebuilding the journal\n * leaves a pin naming history the file no longer carries, and every read is\n * refused because that is precisely the deletion the pin exists to catch. The\n * refusal names the pin file, and `clearTrustedHeadFile` is the explicit way to\n * discard it — the same downgrade a writer with filesystem access could already\n * perform with `rm`, made reachable through the API so it is a decision in the\n * code rather than an undocumented manual step. It returns the guarantee it\n * gave up and writes no record of its own; a caller that needs the discard on\n * the record has to write one.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { canonicalString, LEDGER_HASH_PATTERN, type LedgerHash } from './canonical'\nimport { type LedgerFileContext, removeLedgerFile, writeLedgerFileAtomically } from './journal-file'\n\n/** A `(sequence, entryHash)` pair a writer pinned outside the journal. */\nexport interface LedgerTrustedHead {\n sequence: number\n entryHash: LedgerHash\n}\n\n/** Minimum entry shape the anchor check needs. */\nexport interface LedgerAnchoredEntry {\n sequence: number\n entryHash: LedgerHash\n}\n\n/** Sibling pin file for a journal — deliberately NOT the journal, so rewriting\n * the log is not enough to rewrite the trust recorded about it. */\nexport function trustedHeadPathFor(journalPath: string): string {\n return `${journalPath}.head`\n}\n\nconst TRUSTED_HEAD_RECOVERY =\n ' Restore the file, or discard the pin it held with clearTrustedHead().'\n\n/** The pin, or null when this journal has never been pinned. A pin that exists\n * but does not parse is corruption or tamper of the trust record itself and\n * fails loudly: reporting it as \"no pin\" would silently downgrade what the\n * journal can prove. */\nexport function readTrustedHeadFile(\n path: string,\n context: LedgerFileContext,\n): LedgerTrustedHead | null {\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw context.integrityError(\n `${context.subject} trusted head ${path} could not be read.${TRUSTED_HEAD_RECOVERY}`,\n { cause: error },\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} is not valid JSON.${TRUSTED_HEAD_RECOVERY}`,\n { cause: error },\n )\n }\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} is not an object.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n const record = raw as Record<string, unknown>\n const keys = Object.keys(record).sort()\n if (keys.length !== 2 || keys[0] !== 'entryHash' || keys[1] !== 'sequence') {\n throw context.integrityError(\n `${context.subject} trusted head ${path} has keys [${keys.join(', ')}], expected [entryHash, sequence].${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n const { sequence, entryHash } = record\n if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 0) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} sequence is not a non-negative integer.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n if (typeof entryHash !== 'string' || !LEDGER_HASH_PATTERN.test(entryHash)) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} entryHash is not a sha256 digest.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n return { sequence, entryHash: entryHash as LedgerHash }\n}\n\n/** Publish a pin by write-then-rename, so a crash leaves either the previous\n * pin or the new one and never a torn file that would lock a journal out of\n * its own trust record.\n *\n * Not re-exported from the package's public surface. It takes no lock, checks no\n * chain, and enforces no monotonicity, so a public form would be the one call\n * able to move a pin BACKWARD onto a journal it never read — which is the\n * truncation the pin exists to refuse. `FileLedgerJournal.pinTrustedHead` is\n * the public writer: locked, chain-verified, forward-only. */\nexport function writeTrustedHeadFile(\n path: string,\n head: LedgerTrustedHead,\n context: LedgerFileContext,\n): void {\n try {\n writeLedgerFileAtomically(path, `${canonicalString(head)}\\n`, context)\n } catch (error) {\n throw context.integrityError(`${context.subject} trusted head ${path} could not be written`, {\n cause: error,\n })\n }\n}\n\n/** Outcome of discarding a pin: the guarantee that was given up. `unreadable`\n * carries why the discarded pin could not be named — corruption, a permission\n * fault, a wrong file type — so a caller recording the decision never has to\n * treat \"no pin was there\" and \"the pin could not be read\" as one state.\n * `cleanupError` reports a stale atomic-write sibling that remains after the\n * actual pin was cleared. */\nexport type LedgerTrustedHeadRemoval =\n | { removed: true; head: LedgerTrustedHead; cleanupError?: string }\n | { removed: true; head: null; unreadable: string; cleanupError?: string }\n | { removed: false; cleanupError?: string }\n\n/** Discard a journal's pin, reporting what was discarded. The journal file is\n * untouched and reads as unpinned afterwards, so the next pinning append opens\n * a new pin at the entry it writes. This gives up the deletion guarantee for\n * every entry the pin covered; it is the recovery for a pin whose journal was\n * deliberately deleted or rebuilt, and the only way past a pin file that can no\n * longer be read at all. */\nexport function clearTrustedHeadFile(\n path: string,\n context: LedgerFileContext,\n): LedgerTrustedHeadRemoval {\n let head: LedgerTrustedHead | null = null\n let unreadable = ''\n try {\n head = readTrustedHeadFile(path, context)\n } catch (error) {\n // A pin nobody can read is precisely what clearing has to get past, so the\n // fault is reported on a removal that still happens rather than raised —\n // but it is reported, never flattened into \"there was no pin\".\n unreadable = error instanceof Error ? error.message : String(error)\n }\n const removed = removeLedgerFile(path, context)\n let cleanupError: string | undefined\n try {\n // Cleanup cannot block the requested trust-state change. Report a stale\n // atomic-write sibling so the caller can repair it before the next write.\n removeLedgerFile(`${path}.tmp`, context)\n } catch (error) {\n cleanupError = error instanceof Error ? error.message : String(error)\n }\n const cleanup = cleanupError === undefined ? {} : { cleanupError }\n if (!removed) return { removed: false, ...cleanup }\n if (head === null) return { removed: true, head: null, unreadable, ...cleanup }\n return { removed: true, head, ...cleanup }\n}\n\n/** How a journal is named when a trusted-head check refuses it. */\nexport interface LedgerTrustedHeadSubject {\n /** The journal in error messages, e.g. `search ledger /runs/a/ledger.jsonl`. */\n subject: string\n /** The sibling pin file, named in every refusal so the operator can see which\n * of the two files carries the claim being enforced. */\n trustedHeadPath: string\n}\n\n/** The entry at exactly `head.sequence` must still carry `head.entryHash`.\n * Entries must already have passed chain verification, which is what makes\n * index and sequence interchangeable here. */\nexport function verifyEntriesAgainstTrustedHead(\n entries: readonly LedgerAnchoredEntry[],\n head: LedgerTrustedHead,\n context: LedgerFileContext,\n naming: LedgerTrustedHeadSubject,\n): void {\n // A caller passing the bare subject string an untyped build would accept\n // destructures into two undefineds, which would corrupt the text of a\n // security refusal rather than fail. Refuse instead.\n if (typeof naming !== 'object' || naming === null) {\n throw new TypeError(\n 'verifyEntriesAgainstTrustedHead expects { subject, trustedHeadPath } as its fourth argument',\n )\n }\n const { subject, trustedHeadPath } = naming\n const pinned = entries[head.sequence]\n if (pinned === undefined) {\n throw context.integrityError(\n `${subject} trusted head ${trustedHeadPath} pins sequence ${head.sequence} (${head.entryHash}) but the journal has ${entries.length} entries — pinned history is missing (truncation, rollback, or rewrite). Restore the journal, or abandon the pinned history on purpose with clearTrustedHead().`,\n )\n }\n if (pinned.sequence !== head.sequence) {\n throw context.integrityError(\n `${subject} entry at index ${head.sequence} carries sequence ${pinned.sequence}; the chain was not verified before the trusted head ${trustedHeadPath}`,\n )\n }\n if (pinned.entryHash !== head.entryHash) {\n throw context.integrityError(\n `${subject} entry at pinned sequence ${head.sequence} carries ${pinned.entryHash} but the trusted head ${trustedHeadPath} recorded ${head.entryHash} — the journal was rewritten. Restore the journal, or abandon the pinned history on purpose with clearTrustedHead().`,\n )\n }\n}\n","/**\n * Generic durable append-only journal with a SHA-256 hash chain.\n *\n * The file format is canonical JSONL: every row is the canonical JSON encoding\n * (RFC 8785, object keys sorted recursively) of one entry, and every entry\n * hashes the previous entry's hash so the log is tamper-evident. Appends are\n * serialized in-process per path and across processes via a lock file, fsynced\n * before acknowledgement, and idempotent by `eventId`. A malformed,\n * non-canonical, truncated, reordered, or conflicting log fails loudly; a bad\n * row is never skipped.\n *\n * A hash chain binds each entry to its predecessor, which cannot prove that no\n * entry was removed from the end: a valid shorter prefix is still a valid\n * chain. `pinHead` records the appended entry in a sibling `<journal>.head`\n * file and every read re-verifies the journal against a pin that is present,\n * so truncation and wholesale rewrite are refused. `trusted-head.ts` carries\n * the full threat model, including what a pin does not defend against.\n *\n * Domain vocabulary lives entirely in the consumer's codec: entry schema\n * validation, the constant header fields stamped into every entry, the error\n * taxonomy, and the state machine replayed over verified entries.\n */\n\nimport { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { Mutex } from '../concurrency'\nimport { canonicalString, hashCanonical, type LedgerHash } from './canonical'\nimport { appendLedgerLine, type LedgerFileContext, withLedgerFileLock } from './journal-file'\nimport {\n clearTrustedHeadFile,\n type LedgerTrustedHead,\n type LedgerTrustedHeadRemoval,\n readTrustedHeadFile,\n trustedHeadPathFor,\n verifyEntriesAgainstTrustedHead,\n writeTrustedHeadFile,\n} from './trusted-head'\n\n/** Minimum shape of a journal event: the idempotency key. */\nexport interface LedgerEventBase {\n eventId: string\n}\n\n/** Chain envelope every entry carries in addition to the journal's constant\n * header fields. `entryHash` covers the header, sequence, previous hash, and\n * event, so any rewrite of history invalidates every later entry. */\nexport interface LedgerChainFields<Event extends LedgerEventBase> {\n sequence: number\n previousHash: LedgerHash | null\n event: Event\n entryHash: LedgerHash\n}\n\nexport type LedgerEntryOf<Header extends object, Event extends LedgerEventBase> = Header &\n LedgerChainFields<Event>\n\nexport interface LedgerLineContext {\n path: string\n line: number\n}\n\n/** Domain state machine replayed over chain-verified entries in order.\n * `apply` throws (via the codec's error taxonomy) on an invalid transition;\n * `finish` builds the consumer's projection once every entry was applied. */\nexport interface LedgerProjector<Entry, Projection> {\n apply(entry: Entry, index: number): void\n finish(entries: Entry[]): Projection\n}\n\nexport interface LedgerJournalCodec<\n Header extends object,\n Event extends LedgerEventBase,\n Projection,\n> extends LedgerFileContext {\n /** Constant fields stamped into every entry and covered by its hash. */\n header: Header\n conflictError(message: string): Error\n /** Validate one parsed JSON row into a typed entry. Must reject malformed\n * rows and non-canonical event encodings with the binding's own errors;\n * the journal itself verifies the stored bytes and the hash chain. */\n parseEntry(raw: unknown, context: LedgerLineContext): LedgerEntryOf<Header, Event>\n /** Reject an entry whose constant header fields do not match this journal. */\n checkEntryHeader(entry: LedgerEntryOf<Header, Event>, index: number): void\n createProjector(): LedgerProjector<LedgerEntryOf<Header, Event>, Projection>\n}\n\nexport interface LedgerReplayResult<Entry, Projection> {\n entries: Entry[]\n projection: Projection\n}\n\nexport interface LedgerAppendResult<Entry, Projection> {\n entry: Entry\n /** False when the exact event was already durably present. */\n appended: boolean\n projection: Projection\n}\n\nexport interface LedgerAppendOptions {\n /** Record the appended entry as this journal's trusted head, so a later read\n * can prove nothing was deleted from the end.\n *\n * On the idempotent path — the event is already durable — the pin moves up to\n * that entry only when the entry is ahead of it, along a chain this call has\n * just verified. So a pin write that failed after its row was fsynced is\n * repaired by the retry that idempotency already asks the caller for, and the\n * pin still only ever moves forward over history it has checked.\n *\n * A strict journal whose first pin write failed still refuses the retry\n * because it cannot distinguish that failure from a deleted pin. Recover it\n * explicitly with `pinTrustedHead()`; silently adopting the current file\n * would defeat `requireTrustedHead`. */\n pinHead?: boolean\n}\n\nexport interface FileLedgerJournalOptions {\n /** Refuse to read a non-empty journal that has no trusted head.\n *\n * Off by default because journals written before pinning have no pin and\n * must keep opening. Turn it on for a journal this process pins: without it,\n * deleting the sibling pin file silently downgrades the journal back to a\n * chain that cannot detect deletion. */\n requireTrustedHead?: boolean\n}\n\n// One async mutex per resolved journal path so concurrent appends from a single\n// process queue up instead of failing on the held cross-process lock file.\nconst journalMutexes = new Map<string, Mutex>()\n\nfunction mutexFor(path: string): Mutex {\n const existing = journalMutexes.get(path)\n if (existing) return existing\n const mutex = new Mutex()\n journalMutexes.set(path, mutex)\n return mutex\n}\n\n/** Durable filesystem journal. Construction performs no I/O; `append` and\n * `replay` validate the complete existing file under the locks. */\nexport class FileLedgerJournal<Header extends object, Event extends LedgerEventBase, Projection> {\n readonly path: string\n /** Sibling file holding this journal's trusted head. */\n readonly trustedHeadPath: string\n private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly mutex: Mutex\n private readonly requireTrustedHead: boolean\n\n constructor(\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n options: FileLedgerJournalOptions = {},\n ) {\n this.path = resolve(path)\n this.trustedHeadPath = trustedHeadPathFor(this.path)\n this.codec = codec\n this.mutex = mutexFor(this.path)\n this.requireTrustedHead = options.requireTrustedHead === true\n }\n\n async replay(): Promise<LedgerReplayResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => this.replayLocked()),\n )\n }\n\n async append(\n event: Event,\n options: LedgerAppendOptions = {},\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n const before = this.replayLocked()\n const existing = before.entries.find((entry) => entry.event.eventId === event.eventId)\n if (existing) {\n if (canonicalString(existing.event) !== canonicalString(event)) {\n throw this.codec.conflictError(\n `eventId ${event.eventId} already exists with different content`,\n )\n }\n if (options.pinHead === true) this.pinAcknowledged(existing, before.entries)\n return { entry: existing, appended: false, projection: before.projection }\n }\n\n const material = {\n ...this.codec.header,\n sequence: before.entries.length,\n previousHash: before.entries.at(-1)?.entryHash ?? null,\n event,\n }\n const entry = { ...material, entryHash: hashCanonical(material) }\n\n // Apply the state transition before spending an append: an entry the\n // projector rejects must never reach the durable file.\n const projection = this.project([...before.entries, entry])\n appendLedgerLine(this.path, `${canonicalString(entry)}\\n`, this.codec)\n if (options.pinHead === true) {\n // Journal first, pin second: a crash or a failed pin write between\n // them leaves the pin one entry behind, which still verifies and is\n // repaired by the next pinning append, including the idempotent\n // retry of this same event. The reverse order would leave a pin\n // naming an entry the journal does not carry, locking the journal\n // out of its own history.\n writeTrustedHeadFile(\n this.trustedHeadPath,\n { sequence: entry.sequence, entryHash: entry.entryHash },\n this.codec,\n )\n }\n return { entry, appended: true, projection }\n }),\n )\n }\n\n /** The pinned head, or null when this journal has never been pinned. */\n async trustedHead(): Promise<LedgerTrustedHead | null> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () =>\n readTrustedHeadFile(this.trustedHeadPath, this.codec),\n ),\n )\n }\n\n /** Pin the current verified head. The chain and any existing pin are checked\n * first, so the pin only ever moves forward along a journal that still\n * carries the history it already recorded. */\n async pinTrustedHead(): Promise<LedgerTrustedHead> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n const entries = this.readEntries()\n this.project(entries)\n // `requireTrustedHead` is deliberately not applied here: pinning is how\n // a journal that lacks a pin acquires one.\n this.verifyTrustedHead(entries, false)\n const last = entries.at(-1)\n if (last === undefined) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} is empty; there is no head to pin`,\n )\n }\n const head: LedgerTrustedHead = { sequence: last.sequence, entryHash: last.entryHash }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n return head\n }),\n )\n }\n\n /** Discard this journal's pin, reporting what was discarded. The journal file\n * is untouched and reads as unpinned afterwards, so the next pinning append\n * opens a new pin at the entry it writes. It is the way out of a pin whose\n * journal was deliberately deleted or rebuilt — every read of such a path is\n * refused, correctly, because a pin naming history the file no longer carries\n * is indistinguishable from a deletion. Clearing removes the deletion\n * guarantee for every entry the pin covered. */\n async clearTrustedHead(): Promise<LedgerTrustedHeadRemoval> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () =>\n clearTrustedHeadFile(this.trustedHeadPath, this.codec),\n ),\n )\n }\n\n /** Move the pin up to an entry this caller just acknowledged on the\n * idempotent path, when a pin write that failed after its row was already\n * fsynced left the pin behind. The move is safe because it is forward-only\n * along a chain `replayLocked` has just verified: every entry up to this one\n * is bound to it by hash, so the pin can only ever come to name more history\n * than it did, never different history.\n *\n * With no pin at all this only pins the journal's current head. An entry in\n * the middle would publish a pin that reads as protection while leaving every\n * later entry silently truncatable, which is a worse state to hand an auditor\n * than the honest absence of a pin; `pinTrustedHead()` is the way to pin an\n * unpinned journal on purpose. */\n private pinAcknowledged(\n entry: LedgerEntryOf<Header, Event>,\n entries: LedgerEntryOf<Header, Event>[],\n ): void {\n const pinned = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n if (pinned === null) {\n if (entry.sequence !== entries.length - 1) return\n } else if (pinned.sequence >= entry.sequence) {\n return\n }\n writeTrustedHeadFile(\n this.trustedHeadPath,\n { sequence: entry.sequence, entryHash: entry.entryHash },\n this.codec,\n )\n }\n\n private replayLocked(): LedgerReplayResult<LedgerEntryOf<Header, Event>, Projection> {\n const entries = this.readEntries()\n const projection = this.project(entries)\n // The anchor is meaningful only over a chain that already verified, so it\n // is checked last — and on every read path, so a violated pin is refused\n // before an append can extend the journal over it.\n this.verifyTrustedHead(entries, this.requireTrustedHead)\n return { entries, projection }\n }\n\n private verifyTrustedHead(entries: LedgerEntryOf<Header, Event>[], requirePin: boolean): void {\n const pinned = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n if (pinned === null) {\n if (requirePin && entries.length > 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has ${entries.length} entries but no trusted head at ${this.trustedHeadPath} — without its pin the journal cannot prove nothing was deleted. Restore the pin file, or adopt the current head with pinTrustedHead().`,\n )\n }\n return\n }\n verifyEntriesAgainstTrustedHead(entries, pinned, this.codec, {\n subject: `${this.codec.subject} ${this.path}`,\n trustedHeadPath: this.trustedHeadPath,\n })\n }\n\n private readEntries(): LedgerEntryOf<Header, Event>[] {\n if (!existsSync(this.path)) return []\n const text = readFileSync(this.path, 'utf8')\n if (text.length === 0) return []\n if (!text.endsWith('\\n')) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a truncated final record (missing newline)`,\n )\n }\n\n const lines = text.slice(0, -1).split('\\n')\n const entries: LedgerEntryOf<Header, Event>[] = []\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index]!\n if (line.length === 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a blank row at line ${index + 1}`,\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(line)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has invalid JSON at line ${index + 1}`,\n { cause: error },\n )\n }\n const entry = this.codec.parseEntry(raw, { path: this.path, line: index + 1 })\n let canonical: string\n try {\n canonical = canonicalString(entry)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a row with no canonical JSON form at line ${index + 1}`,\n { cause: error },\n )\n }\n if (line !== canonical) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has non-canonical bytes at line ${index + 1}`,\n )\n }\n entries.push(entry)\n }\n return entries\n }\n\n private project(entries: LedgerEntryOf<Header, Event>[]): Projection {\n const projector = this.codec.createProjector()\n const eventIds = new Set<string>()\n let expectedPrevious: LedgerHash | null = null\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index]!\n this.codec.checkEntryHeader(entry, index)\n if (entry.sequence !== index) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`,\n )\n }\n if (entry.previousHash !== expectedPrevious) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} does not extend the previous hash`,\n )\n }\n const { entryHash: _entryHash, ...material } = entry\n const expectedHash = hashCanonical(material)\n if (entry.entryHash !== expectedHash) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`,\n )\n }\n expectedPrevious = entry.entryHash\n if (eventIds.has(entry.event.eventId)) {\n throw this.codec.integrityError(\n `duplicate eventId ${entry.event.eventId} in durable ledger`,\n )\n }\n eventIds.add(entry.event.eventId)\n projector.apply(entry, index)\n }\n return projector.finish(entries)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAYA,IAAa,QAAb,MAAmB;CACjB,SAAiB;CACjB,UAA8C,CAAC;CAE/C,MAAM,UAA+B;EACnC,IAAI,CAAC,KAAK,QAAQ;GAChB,KAAK,SAAS;GACd,aAAa,KAAK,QAAQ;EAC5B;EACA,OAAO,IAAI,SAAqB,YAAY;GAC1C,KAAK,QAAQ,WAAW;IACtB,cAAc,KAAK,QAAQ,CAAC;GAC9B,CAAC;EACH,CAAC;CACH;CAEA,UAAwB;EACtB,MAAM,OAAO,KAAK,QAAQ,MAAM;EAChC,IAAI,MACF,KAAK;OAEL,KAAK,SAAS;CAElB;CAEA,MAAM,aAAgB,IAAsC;EAC1D,MAA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AO;GAChC,UAAU,MAAM,OAAO,KAAK;EAC9B;EACA,OAAO,UAAU,OAAO,OAAO;CACjC;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"llm-client-B3WXSH5Y.js","names":[],"sources":["../src/llm-client.ts"],"sourcesContent":["/**\n * LLM client with graceful degrade.\n *\n * OpenAI-compatible `/v1/chat/completions` client with:\n * - Exponential-backoff retry on 429 + 5xx gateway errors (502/503/504).\n * - Retry on transient network errors (fetch failed, AbortError, ECONNRESET).\n * - One retry at temperature 1 when a model explicitly requires it.\n * - Graceful json_schema → json_object degrade on 400 with schema-reject body.\n * - Fenced-JSON stripping (```json ... ```) for models that wrap structured output.\n * - Configurable base URL + api key / bearer, works with LiteLLM proxies, OpenAI\n * directly, cli-bridge subscriptions, and any router that speaks the spec.\n *\n * Usage:\n * const { value, result } = await callLlmJson<MyType>(\n * { model: 'gpt-4o', messages: [...], jsonSchema: { name: 'x', schema: {...} } },\n * { baseUrl: 'https://router.tangle.tools/v1', apiKey: process.env.KEY },\n * )\n *\n * `createChatClient` wraps this implementation for provider-neutral package\n * entry points. Direct callers can use `callLlm` or `callLlmJson`.\n */\n\nimport {\n type CostReceiptInput,\n type CustomTokenPricing,\n costForTokenPricing,\n type MaximumCharge,\n} from './cost-ledger'\nimport { AgentEvalError, CaptureIntegrityError } from './errors'\nimport {\n defaultProviderRedactor,\n type ProviderRedactor,\n providerFromBaseUrl,\n type RawProviderEvent,\n type RawProviderSink,\n} from './trace/raw-provider-sink'\n\n// ─── Types ──────────────────────────────────────────────────────────────\n\nexport interface LlmMessage {\n role: 'system' | 'user' | 'assistant'\n /**\n * Either a plain text content string OR a multimodal content array\n * (text + image_url parts) for vision-capable models.\n */\n content:\n | string\n | Array<\n | { type: 'text'; text: string }\n | { type: 'image_url'; image_url: { url: string; detail?: 'auto' | 'low' | 'high' } }\n >\n}\n\nexport type LlmThinkingMode = 'enabled' | 'disabled'\n\nexport interface LlmCallRequest {\n model: string\n messages: LlmMessage[]\n /** Optional JSON-mode response format (response_format: json_object). */\n jsonMode?: boolean\n /** Optional structured output via JSON Schema. Falls back to json_object on 400. */\n jsonSchema?: { name: string; schema: Record<string, unknown> }\n temperature?: number\n maxTokens?: number\n /** OpenAI-compatible reasoning mode. Omitted when the provider default should apply. */\n thinking?: LlmThinkingMode\n /** Per-call timeout, default 300s. */\n timeoutMs?: number\n}\n\n/** Conservative priced bound for the exact text request sent to a provider.\n * Returns undefined when output or multimodal input is not bounded, causing a\n * capped CostLedger to reject the call before execution. Pass\n * `customTokenPricing` when package pricing does not cover the model or endpoint. */\nexport function maximumChargeForLlmRequest(\n request: Pick<LlmCallRequest, 'model' | 'messages' | 'jsonSchema' | 'maxTokens' | 'thinking'>,\n options: LlmClientOptions = {},\n): MaximumCharge | undefined {\n if (request.maxTokens === undefined) return undefined\n if (!Number.isInteger(request.maxTokens) || request.maxTokens <= 0) {\n throw new RangeError(`maximumChargeForLlmRequest: maxTokens must be a positive integer`)\n }\n if (\n request.messages.some(\n (message) =>\n Array.isArray(message.content) && message.content.some((part) => part.type === 'image_url'),\n )\n ) {\n return undefined\n }\n\n const attempts = resolveMaximumAttempts(options.maximumAttempts)\n const forceJsonObject = options.jsonSchemaTransport === 'json-object'\n // A byte-level tokenizer cannot emit more input tokens than request bytes.\n // Pricing the complete body also covers role/schema framing omitted from content-only estimates.\n const requestBytes = new TextEncoder().encode(\n JSON.stringify(buildBody(request, forceJsonObject, options.thinking)),\n ).byteLength\n // A rejected response schema can trigger one JSON-mode batch with the same output limit.\n const batches = request.jsonSchema && !forceJsonObject ? 2 : 1\n const usage = {\n inputTokens: requestBytes * attempts * batches,\n outputTokens: request.maxTokens * attempts * batches,\n }\n return options.customTokenPricing\n ? { customTokenPricing: options.customTokenPricing, ...usage }\n : { model: request.model, ...usage }\n}\n\nexport interface LlmUsage {\n promptTokens: number\n completionTokens: number\n totalTokens: number\n /** False when the provider omitted or malformed prompt/completion usage. */\n captured?: boolean\n /** Reasoning-token subset of completionTokens, when reported. */\n reasoningTokens?: number\n /** Proxies populate this when prompt caching is on. */\n cachedPromptTokens?: number\n}\n\nexport interface LlmCallResult {\n /** The text content of the first choice. Empty string if none. */\n content: string\n usage: LlmUsage\n /**\n * Cost in USD. Uses the provider's reported cost when present, otherwise\n * caller-supplied token pricing. `null` when neither is available.\n */\n costUsd: number | null\n /** Model name actually used (echoed from response). */\n model: string\n /** Wall-clock duration of the HTTP call (last attempt, if retried). */\n durationMs: number\n /**\n * `finish_reason` echoed from the first choice (`stop`, `length`,\n * `content_filter`, `tool_calls`, ...). `null` when the provider omits it.\n * Exposed so a free-form `callLlm` caller CAN detect a truncated answer\n * (`length`) instead of treating a cut-off completion as complete. Note:\n * `callLlm` does not itself reject on it — acting on this signal is the\n * caller's responsibility (in-repo free-form drivers do not yet enforce it).\n */\n finishReason?: string | null\n /**\n * True when `content.trim()` is empty. An empty completion is a silent zero\n * for free-form `callLlm` callers; this flag is the signal a caller can\n * inspect to fail loud rather than proceed on an empty string. `callLlm`\n * surfaces it but does not throw on it.\n */\n contentEmpty?: boolean\n /** Raw response body. */\n raw: Record<string, unknown>\n}\n\nexport type LlmCallMetadata = Pick<LlmCallResult, 'usage' | 'costUsd' | 'model' | 'durationMs'>\n\n/** Convert a provider result into the canonical paid-call receipt input. */\nexport function costReceiptFromLlm(\n result: LlmCallResult,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput {\n const cachedTokens = result.usage.cachedPromptTokens ?? 0\n const inputTokens = Math.max(0, result.usage.promptTokens - cachedTokens)\n const configuredCostUsd =\n result.costUsd === null && customTokenPricing && result.usage.captured !== false\n ? costForTokenPricing(customTokenPricing, {\n inputTokens,\n ...(cachedTokens > 0 ? { cachedTokens } : {}),\n outputTokens: result.usage.completionTokens,\n })\n : undefined\n return {\n model: result.model,\n inputTokens,\n outputTokens: result.usage.completionTokens,\n reasoningTokens: result.usage.reasoningTokens,\n cachedTokens: cachedTokens > 0 ? cachedTokens : undefined,\n actualCostUsd: result.costUsd ?? configuredCostUsd,\n usageUnknown: result.usage.captured === false,\n }\n}\n\n/** Structured-response failures retain their completed provider receipt. */\nexport function costReceiptFromLlmError(\n error: Error,\n customTokenPricing?: CustomTokenPricing,\n): CostReceiptInput | undefined {\n return error instanceof LlmResponseError\n ? costReceiptFromLlm(error.result, customTokenPricing)\n : undefined\n}\n\nexport class LlmCallError extends AgentEvalError {\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: string,\n public readonly model: string,\n ) {\n super('judge', message)\n }\n}\n\n/** A provider response completed and incurred measurable usage, but its content\n * could not satisfy the caller's response contract. The response envelope is\n * retained so accounting can commit the receipt before the error propagates. */\nexport class LlmResponseError extends AgentEvalError {\n constructor(\n message: string,\n public readonly result: LlmCallResult,\n options?: { cause?: unknown },\n ) {\n super('judge', message, options)\n }\n}\n\nexport interface LlmClientOptions {\n /** Base URL (without trailing slash). Must end at the `/v1` prefix. */\n baseUrl?: string\n /** Bearer token — either `apiKey` or `bearer` populates `Authorization: Bearer ...`. */\n apiKey?: string\n bearer?: string\n /** Override for the `Authorization` header (e.g. `X-Auth: ...`). Takes precedence over apiKey/bearer. */\n authHeader?: { name: string; value: string }\n /** Stable provider idempotency key, reused across retries of this logical call. */\n idempotencyKey?: string\n /** Default timeout in ms. Per-call can override. */\n defaultTimeoutMs?: number\n /**\n * Caller-supplied abort signal — e.g. a campaign-wide cancel. Linked to\n * each attempt's per-attempt timeout controller, so aborting it cancels\n * the in-flight fetch. A caller abort is FATAL: it is not retried even\n * though an AbortError otherwise matches the transient patterns.\n */\n signal?: AbortSignal\n /**\n * Cross-attempt wall-clock budget in ms, measured from the first attempt.\n * Before launching each attempt the loop checks the remaining budget and\n * stops retrying once it is exhausted, rather than waiting the full\n * per-attempt timeout on every retry. Bounds total time independent of\n * total attempts × `timeoutMs`.\n */\n deadlineMs?: number\n /** Total provider attempts. Default 3. */\n maximumAttempts?: number\n /** Token rates used when the provider omits cost or package pricing does not cover the model. */\n customTokenPricing?: CustomTokenPricing\n /**\n * Transport for requests that declare `jsonSchema`. `native` sends\n * `response_format: json_schema`; `json-object` sends the broadly supported\n * JSON mode and relies on the caller to include the schema in model-visible\n * instructions. Default: `native`.\n */\n jsonSchemaTransport?: 'native' | 'json-object'\n /**\n * JSON payload parsing policy. `extract` accepts fenced or prose-prefixed JSON.\n * `exact` requires the complete response content to be one JSON value.\n * Default: `extract`.\n */\n jsonPayloadMode?: 'extract' | 'exact'\n /** Default provider reasoning mode. A per-call request value takes precedence. */\n thinking?: LlmThinkingMode\n /** Fetch implementation — defaults to global `fetch`. Override for custom transport (e.g. tests). */\n fetch?: typeof fetch\n /**\n * Optional raw HTTP capture sink. When provided, every request, response,\n * and error (across all retry attempts) is recorded to the sink, with auth\n * headers and credential-shaped body fields redacted by default. This is\n * the layer-1 forensics primitive: structured `LlmSpan`s record intent,\n * raw events record what actually crossed the wire.\n */\n rawSink?: RawProviderSink\n /**\n * Logical provider id attached to raw events. When omitted, derived from\n * `baseUrl` via `providerFromBaseUrl`.\n */\n provider?: string\n /** Trace context attached to raw events; populated by emitter-aware callers. */\n traceContext?: { runId?: string; spanId?: string }\n /** Override the redaction strategy for this call. Defaults to `defaultProviderRedactor`. */\n redactor?: ProviderRedactor\n}\n\n// ─── Internals ──────────────────────────────────────────────────────────\n\nconst DEFAULT_BASE_URL = 'https://router.tangle.tools/v1'\n// Flagship / reasoning models routinely take several minutes on large prompts (a\n// reflection over many failures, a long tool transcript). A tight cap aborts a\n// legitimately-slow but healthy call — and because every retry attempt re-uses\n// the same window, such a model aborts on ALL attempts and the loop throws. The\n// default is generous enough to let those complete, bounded enough that a truly\n// hung call still fails over after retries, and tunable per deployment via\n// TANGLE_LLM_TIMEOUT_MS. Per-call `req.timeoutMs` / `opts.defaultTimeoutMs`\n// still win for callers that know their model's latency.\nconst DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 300_000\nconst DEFAULT_MAXIMUM_ATTEMPTS =\n process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === undefined\n ? 3\n : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS)\n\nfunction resolveMaximumAttempts(configured: number | undefined): number {\n const attempts = configured ?? DEFAULT_MAXIMUM_ATTEMPTS\n if (!Number.isInteger(attempts) || attempts <= 0) {\n throw new RangeError('LLM maximum attempts must be a positive integer')\n }\n return attempts\n}\n\nfunction providerTokenCount(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined\n}\n\nconst RETRYABLE_STATUS = new Set([429, 502, 503, 504])\n\n/**\n * Transient transport/network error signatures, matched against an error's\n * name, message, and `code`. Covers fetch/undici network failures, aborts\n * and timeouts, and — critically — HTTP/2 transport faults a keep-alive\n * connection raises mid-response: `terminated`, `NGHTTP2_INTERNAL_ERROR`,\n * `UND_ERR_*`, `other side closed`. Those last ones carry no clean HTTP\n * status; unrecognised, they escape the retry loop and surface as an\n * uncaught rejection.\n */\nconst TRANSIENT_ERROR_PATTERNS: readonly RegExp[] = [\n /AbortError/i,\n /TimeoutError/i,\n /this operation was aborted/i,\n /fetch failed/i,\n /ECONNRESET/i,\n /ETIMEDOUT/i,\n /EAI_AGAIN/i,\n /socket hang up/i,\n /stream.*ended.*unexpectedly/i,\n /terminated/i,\n /other side closed/i,\n /NGHTTP2/i,\n /UND_ERR/i,\n]\n\n/**\n * True when an error is a transient transport/network fault worth retrying,\n * as opposed to a deterministic failure (4xx schema reject, JSON parse) that\n * a retry cannot fix. Inspects `LlmCallError.status`, then the error's\n * name/message/code, then recurses into `error.cause` — undici nests the\n * real socket fault one or more levels under `.cause`.\n *\n * This is the retry classifier for the package: `callLlm` and\n * `withJudgeRetry` both route through it, so connection failures are treated\n * consistently across transports.\n */\nexport function isTransientLlmError(err: unknown): boolean {\n return classifyTransient(err, 0)\n}\n\nfunction classifyTransient(err: unknown, depth: number): boolean {\n if (err instanceof LlmCallError) return RETRYABLE_STATUS.has(err.status)\n if (!(err instanceof Error)) return false\n // Foreign transport errors can carry a numeric HTTP status without being an\n // LlmCallError. A retryable status is decisive.\n const status = (err as { status?: unknown }).status\n if (typeof status === 'number' && RETRYABLE_STATUS.has(status)) return true\n const code = (err as { code?: unknown }).code\n const haystack = `${err.name}\\n${err.message}\\n${typeof code === 'string' ? code : ''}`\n if (TRANSIENT_ERROR_PATTERNS.some((p) => p.test(haystack))) return true\n const cause = (err as { cause?: unknown }).cause\n if (depth < 4 && cause instanceof Error && cause !== err) {\n return classifyTransient(cause, depth + 1)\n }\n return false\n}\n\nfunction parseRetryAfter(headers: Headers): number | null {\n const h = headers.get('retry-after')\n if (!h) return null\n const asNumber = Number(h)\n if (Number.isFinite(asNumber) && asNumber > 0) return asNumber * 1000\n const asDate = Date.parse(h)\n if (Number.isFinite(asDate)) return Math.max(0, asDate - Date.now())\n return null\n}\n\n/** Exponential backoff: 500ms, 1s, 2s, 4s, ... capped at 16s. Attempt is 0-indexed. */\nexport function backoffMs(attempt: number): number {\n return Math.min(500 * 2 ** attempt, 16_000)\n}\n\nfunction buildHeaders(opts: LlmClientOptions): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n }\n if (opts.authHeader) {\n headers[opts.authHeader.name] = opts.authHeader.value\n } else if (opts.bearer || opts.apiKey) {\n headers.Authorization = `Bearer ${opts.bearer ?? opts.apiKey}`\n }\n if (opts.idempotencyKey) headers['Idempotency-Key'] = opts.idempotencyKey\n return headers\n}\n\nfunction isSchemaRejection(status: number, body: string): boolean {\n if (status !== 400) return false\n const lower = body.toLowerCase()\n return (\n lower.includes('response_format') ||\n lower.includes('json_schema') ||\n lower.includes('is unavailable') ||\n lower.includes('not supported')\n )\n}\n\nfunction isTemperatureOneRejection(status: number, body: string): boolean {\n if (status !== 400 || !/temperature/i.test(body)) return false\n return (\n /temperature[^.\\n]{0,120}\\b(?:only|must|should|required|requires?)\\b[^.\\n]{0,40}\\b1(?:\\.0+)?\\b/i.test(\n body,\n ) || /\\bonly\\s+1(?:\\.0+)?\\s+is\\s+allowed\\b[^.\\n]{0,120}\\btemperature\\b/i.test(body)\n )\n}\n\nfunction buildBody(\n req: LlmCallRequest,\n forceJsonObject: boolean,\n defaultThinking?: LlmThinkingMode,\n): Record<string, unknown> {\n const body: Record<string, unknown> = {\n model: req.model,\n messages: req.messages,\n temperature: req.temperature ?? 0,\n }\n if (req.maxTokens != null) {\n if (usesMaxCompletionTokens(req.model)) body.max_completion_tokens = req.maxTokens\n else body.max_tokens = req.maxTokens\n }\n const thinking = req.thinking ?? defaultThinking\n if (thinking !== undefined) {\n body.thinking = { type: thinking }\n }\n\n if (req.jsonSchema && !forceJsonObject) {\n body.response_format = {\n type: 'json_schema',\n json_schema: { name: req.jsonSchema.name, schema: req.jsonSchema.schema, strict: true },\n }\n } else if (req.jsonMode || req.jsonSchema) {\n body.response_format = { type: 'json_object' }\n }\n\n return body\n}\n\nfunction usesMaxCompletionTokens(model: string): boolean {\n return /^gpt-5(?:[.-]|$)/i.test(model)\n}\n\nasync function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Combine the per-attempt timeout signal with an optional caller signal into\n * one signal the fetch listens on. Prefers the native `AbortSignal.any`; falls\n * back to manual wiring on runtimes that predate it. The caller signal is also\n * propagated to the timeout controller so aborting it cancels the in-flight\n * fetch immediately.\n */\nfunction linkSignals(timeoutController: AbortController, caller?: AbortSignal): AbortSignal {\n if (!caller) return timeoutController.signal\n if (typeof (AbortSignal as { any?: unknown }).any === 'function') {\n return AbortSignal.any([timeoutController.signal, caller])\n }\n if (caller.aborted) {\n timeoutController.abort()\n } else {\n caller.addEventListener('abort', () => timeoutController.abort(), { once: true })\n }\n return timeoutController.signal\n}\n\n/** True once the cross-attempt wall-clock budget (if any) is exhausted. */\nfunction deadlineExceeded(start: number, deadlineMs: number | undefined): boolean {\n return deadlineMs != null && Date.now() - start >= deadlineMs\n}\n\n// ─── Public API ─────────────────────────────────────────────────────────\n\n/**\n * Strip a ```json / ``` code fence if the model emitted one.\n * Idempotent for naked JSON. Some models (claude-code via router, certain\n * deepseek models) wrap output even under json_object.\n */\nexport function stripFencedJson(raw: string): string {\n const trimmed = raw.trim()\n const m = trimmed.match(/^```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```\\s*$/)\n return m ? m[1]!.trim() : trimmed\n}\n\nexport function extractJsonPayload(raw: string): string {\n const stripped = stripFencedJson(raw)\n try {\n JSON.parse(stripped)\n return stripped\n } catch {\n // A response that declares a JSON root must parse as that complete root.\n // Scanning onward could turn a truncated object into one of its valid nested\n // arrays or objects and silently change the response schema.\n if (stripped.startsWith('{') || stripped.startsWith('[')) return stripped\n }\n\n // Only prose-leading responses may contain a recoverable JSON payload.\n const starts = [...stripped.matchAll(/[[{]/g)]\n .map((match) => match.index)\n .filter((index) => index != null)\n for (const start of starts) {\n const candidate = extractBalancedJson(stripped, start)\n if (!candidate) continue\n try {\n JSON.parse(candidate)\n return candidate\n } catch {\n // Keep scanning; earlier braces may belong to prose.\n }\n }\n\n return stripped\n}\n\nfunction extractBalancedJson(input: string, start: number): string | null {\n const opener = input[start]\n const closer = opener === '{' ? '}' : opener === '[' ? ']' : null\n if (!closer) return null\n\n const stack: string[] = [closer]\n let isInString = false\n let isEscaped = false\n\n for (let i = start + 1; i < input.length; i++) {\n const char = input[i]!\n if (isEscaped) {\n isEscaped = false\n continue\n }\n if (char === '\\\\') {\n isEscaped = isInString\n continue\n }\n if (char === '\"') {\n isInString = !isInString\n continue\n }\n if (isInString) continue\n\n if (char === '{') stack.push('}')\n else if (char === '[') stack.push(']')\n else if (char === stack[stack.length - 1]) {\n stack.pop()\n if (stack.length === 0) return input.slice(start, i + 1)\n }\n }\n\n return null\n}\n\n/**\n * Low-level call. Returns raw content + usage + cost. Retries on transient\n * failures; does NOT degrade schema here — callers that want graceful\n * degrade use `callLlmJson`.\n */\nexport async function callLlm(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n const url = `${baseUrl}/chat/completions`\n const endpoint = '/chat/completions'\n const timeoutMs = req.timeoutMs ?? opts.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS\n const maximumAttempts = resolveMaximumAttempts(opts.maximumAttempts)\n const fetchFn = opts.fetch ?? globalThis.fetch\n const headers = buildHeaders(opts)\n const provider = opts.provider ?? providerFromBaseUrl(baseUrl)\n const sink = opts.rawSink\n const redactor = opts.redactor ?? defaultProviderRedactor\n const traceContext = opts.traceContext\n const callerSignal = opts.signal\n const deadlineMs = opts.deadlineMs\n const deadlineStart = Date.now()\n if (opts.customTokenPricing) {\n costForTokenPricing(opts.customTokenPricing, { inputTokens: 0, outputTokens: 0 })\n }\n\n let lastErr: unknown\n let effectiveRequest = req\n for (let attempt = 0; attempt < maximumAttempts; attempt++) {\n // A caller cancel is fatal — never retried. Checking before each attempt\n // means an already-aborted signal short-circuits without firing fetch.\n if (callerSignal?.aborted) {\n throw new DOMException('callLlm aborted by caller signal', 'AbortError')\n }\n // Stop retrying once the cross-attempt budget is spent rather than burning\n // a full per-attempt timeout on each remaining retry.\n if (attempt > 0 && deadlineExceeded(deadlineStart, deadlineMs)) {\n throw lastErr instanceof Error ? lastErr : new Error(String(lastErr))\n }\n const controller = new AbortController()\n const attemptSignal = linkSignals(controller, callerSignal)\n const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs)\n const started = Date.now()\n const requestBody = buildBody(\n effectiveRequest,\n opts.jsonSchemaTransport === 'json-object',\n opts.thinking,\n )\n let attemptErrorRecorded = false\n if (sink) {\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'request',\n timestamp: started,\n requestHeaders: headers,\n requestBody,\n redactedFields: [],\n })\n }\n\n try {\n const res = await fetchFn(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(requestBody),\n signal: attemptSignal,\n })\n clearTimeout(timeoutHandle)\n const responseHeaders = sink ? headersToObject(res.headers) : undefined\n\n if (!res.ok) {\n const body = await res.text()\n if (sink) {\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: body,\n errorMessage: `HTTP ${res.status}`,\n redactedFields: [],\n })\n attemptErrorRecorded = true\n }\n const err = new LlmCallError(\n `LLM call failed with HTTP ${res.status}`,\n res.status,\n body,\n req.model,\n )\n if (\n isTemperatureOneRejection(res.status, body) &&\n effectiveRequest.temperature !== 1 &&\n attempt < maximumAttempts - 1 &&\n !deadlineExceeded(deadlineStart, deadlineMs)\n ) {\n lastErr = err\n effectiveRequest = { ...effectiveRequest, temperature: 1 }\n continue\n }\n if (\n RETRYABLE_STATUS.has(res.status) &&\n attempt < maximumAttempts - 1 &&\n !deadlineExceeded(deadlineStart, deadlineMs)\n ) {\n lastErr = err\n const retryAfter = parseRetryAfter(res.headers)\n await sleep(retryAfter ?? backoffMs(attempt))\n continue\n }\n throw err\n }\n\n const text = await res.text()\n let json: Record<string, unknown>\n try {\n json = JSON.parse(text) as Record<string, unknown>\n } catch (parseErr) {\n if (sink) {\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: text,\n errorMessage: `non-JSON response: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,\n redactedFields: [],\n })\n attemptErrorRecorded = true\n }\n throw parseErr\n }\n if (sink) {\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'response',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n statusCode: res.status,\n responseHeaders,\n responseBody: json,\n redactedFields: [],\n })\n }\n const choice = (\n json.choices as\n | Array<{ message?: { content?: string }; finish_reason?: string | null }>\n | undefined\n )?.[0]\n const usageRaw =\n json.usage && typeof json.usage === 'object' && !Array.isArray(json.usage)\n ? (json.usage as Record<string, unknown>)\n : undefined\n const promptTokens = providerTokenCount(usageRaw?.prompt_tokens)\n const completionTokens = providerTokenCount(usageRaw?.completion_tokens)\n const totalTokens = providerTokenCount(usageRaw?.total_tokens)\n const completionDetails =\n usageRaw?.completion_tokens_details &&\n typeof usageRaw.completion_tokens_details === 'object' &&\n !Array.isArray(usageRaw.completion_tokens_details)\n ? (usageRaw.completion_tokens_details as Record<string, unknown>)\n : undefined\n const reasoningRaw = completionDetails?.reasoning_tokens\n const reasoningTokens =\n reasoningRaw === undefined ? undefined : providerTokenCount(reasoningRaw)\n const cachedRaw =\n usageRaw?.prompt_tokens_details &&\n typeof usageRaw.prompt_tokens_details === 'object' &&\n !Array.isArray(usageRaw.prompt_tokens_details)\n ? (usageRaw.prompt_tokens_details as Record<string, unknown>).cached_tokens\n : undefined\n const cachedPromptTokens = cachedRaw === undefined ? undefined : providerTokenCount(cachedRaw)\n const usageCaptured =\n promptTokens !== undefined &&\n completionTokens !== undefined &&\n (reasoningRaw === undefined ||\n (reasoningTokens !== undefined && reasoningTokens <= completionTokens)) &&\n (cachedRaw === undefined ||\n (cachedPromptTokens !== undefined && cachedPromptTokens <= promptTokens)) &&\n (totalTokens === undefined || totalTokens === promptTokens + completionTokens)\n const costFromProxy = (json._response_cost ?? json.cost_usd) as number | undefined\n const content = choice?.message?.content ?? ''\n\n const configuredCost =\n typeof costFromProxy !== 'number' && usageCaptured && opts.customTokenPricing\n ? costForTokenPricing(opts.customTokenPricing, {\n inputTokens: promptTokens! - (cachedPromptTokens ?? 0),\n ...(cachedPromptTokens ? { cachedTokens: cachedPromptTokens } : {}),\n outputTokens: completionTokens!,\n })\n : undefined\n\n return {\n content,\n finishReason: choice?.finish_reason ?? null,\n contentEmpty: content.trim().length === 0,\n usage: {\n promptTokens: promptTokens ?? 0,\n completionTokens: completionTokens ?? 0,\n totalTokens: totalTokens ?? (promptTokens ?? 0) + (completionTokens ?? 0),\n captured: usageCaptured,\n reasoningTokens,\n cachedPromptTokens,\n },\n costUsd: typeof costFromProxy === 'number' ? costFromProxy : (configuredCost ?? null),\n model: (json.model as string) ?? req.model,\n durationMs: Date.now() - started,\n raw: json,\n }\n } catch (err) {\n clearTimeout(timeoutHandle)\n lastErr = err\n // A caller cancel is fatal even though an AbortError matches the\n // transient patterns — a cancelled call must surface immediately, not\n // be retried against the same dead intent.\n if (callerSignal?.aborted) {\n if (sink && !attemptErrorRecorded) {\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n redactedFields: [],\n })\n }\n throw err\n }\n if (sink && !attemptErrorRecorded) {\n // Record only if neither the !res.ok branch nor the JSON.parse catch\n // already produced an error event for this attempt. Covers network\n // failures, timeouts, and aborts.\n await recordRaw(sink, redactor, {\n eventId: cryptoEventId(),\n runId: traceContext?.runId,\n spanId: traceContext?.spanId,\n provider,\n model: req.model,\n endpoint,\n baseUrl,\n attemptIndex: attempt,\n direction: 'error',\n timestamp: Date.now(),\n durationMs: Date.now() - started,\n errorMessage: err instanceof Error ? err.message : String(err),\n redactedFields: [],\n })\n }\n if (\n attempt < maximumAttempts - 1 &&\n isTransientLlmError(err) &&\n !deadlineExceeded(deadlineStart, deadlineMs)\n ) {\n await sleep(backoffMs(attempt))\n continue\n }\n throw err\n }\n }\n throw lastErr instanceof Error ? lastErr : new Error(String(lastErr))\n}\n\nasync function recordRaw(\n sink: RawProviderSink,\n redactor: ProviderRedactor,\n event: RawProviderEvent,\n): Promise<void> {\n // Errors from sinks must not crash the LLM call. Forensic capture is\n // best-effort; the structured trace is the system of record.\n try {\n await sink.record(redactor(event))\n } catch {\n // Intentionally swallowed.\n }\n}\n\nfunction headersToObject(h: Headers): Record<string, string> {\n const out: Record<string, string> = {}\n h.forEach((value, key) => {\n out[key] = value\n })\n return out\n}\n\nfunction cryptoEventId(): string {\n if (typeof globalThis.crypto?.randomUUID === 'function') return globalThis.crypto.randomUUID()\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`\n}\n\n/**\n * Structured-output call. Returns parsed JSON plus the raw result envelope.\n * Degrades `jsonSchema` → `jsonMode` on a 400 that names the schema param —\n * critical for deepseek-v3/v4, kimi-k2.6, and other models that don't accept\n * the `response_format.json_schema` shape but DO accept `json_object`.\n */\nexport async function callLlmJson<T = unknown>(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<{ value: T; result: LlmCallResult }> {\n const result = await callLlmStructured(req, opts)\n const value = parseJsonResult<T>(result, opts.jsonPayloadMode ?? 'extract')\n return { value, result }\n}\n\n/** Shared schema-to-JSON-mode fallback that preserves the raw result. */\nasync function callLlmStructured(\n req: LlmCallRequest,\n opts: LlmClientOptions = {},\n): Promise<LlmCallResult> {\n try {\n return await callLlm({ ...req, jsonMode: req.jsonMode ?? !req.jsonSchema }, opts)\n } catch (err) {\n if (\n opts.jsonSchemaTransport !== 'json-object' &&\n err instanceof LlmCallError &&\n isSchemaRejection(err.status, err.body) &&\n req.jsonSchema\n ) {\n const degradedReq: LlmCallRequest = { ...req, jsonMode: true, jsonSchema: undefined }\n return await callLlm(degradedReq, opts)\n }\n throw err\n }\n}\n\nfunction parseJsonResult<T>(\n result: LlmCallResult,\n jsonPayloadMode: NonNullable<LlmClientOptions['jsonPayloadMode']>,\n): T {\n try {\n if (result.finishReason === 'length') {\n throw new Error(\n `LLM returned truncated JSON content (model=${result.model}, finishReason=length)`,\n )\n }\n return parseJsonSafely<T>(result.content, result.model, jsonPayloadMode)\n } catch (error) {\n if (error instanceof LlmResponseError) throw error\n const cause = error instanceof Error ? error : new Error(String(error))\n throw new LlmResponseError(cause.message, result, { cause })\n }\n}\n\nfunction parseJsonSafely<T>(\n content: string,\n model: string,\n jsonPayloadMode: NonNullable<LlmClientOptions['jsonPayloadMode']>,\n): T {\n const payload = jsonPayloadMode === 'exact' ? content : extractJsonPayload(content)\n try {\n return JSON.parse(payload) as T\n } catch {\n throw new Error(`LLM returned non-JSON content (model=${model})`)\n }\n}\n\n// ─── Route assertion ────────────────────────────────────────────────────\n\nexport type LlmRouteAssertionReason =\n | 'no_explicit_base_url'\n | 'base_url_blocked'\n | 'base_url_not_allowed'\n | 'no_auth'\n | 'wrong_provider'\n\nexport class LlmRouteAssertionError extends CaptureIntegrityError {\n constructor(\n message: string,\n public readonly reason: LlmRouteAssertionReason,\n public readonly baseUrl: string,\n ) {\n super(message)\n }\n}\n\nexport interface LlmRouteRequirements {\n /**\n * Throw if `opts.baseUrl` is undefined, i.e. the call would fall back to\n * `DEFAULT_BASE_URL`. Set this for evaluation runs where silently using\n * the public/free-tier router is a defect — the launch reviewer needs to\n * know exactly which provider answered.\n */\n requireExplicitBaseUrl?: boolean\n /**\n * Allowlist of acceptable base URLs. Strings match by prefix\n * (case-insensitive); RegExps test against the full base URL.\n */\n allowedBaseUrls?: Array<string | RegExp>\n /** Blocklist that takes precedence over `allowedBaseUrls`. */\n blockedBaseUrls?: Array<string | RegExp>\n /** Throw if no auth header / api key is configured. */\n requireAuth?: boolean\n /**\n * Logical provider id the configured `baseUrl` is expected to match (via\n * `providerFromBaseUrl`). Mainly useful when paired with `requireExplicitBaseUrl`.\n */\n expectedProvider?: string\n}\n\n/**\n * Fail-loud assertion that the configured LLM client points at the route\n * the caller intends. Designed for the matrix-runner preflight: invoke\n * once before any LLM call to catch misconfiguration before a sweep burns\n * dollars on the wrong provider.\n *\n * Throws `LlmRouteAssertionError`. Pure — no I/O — so it's safe to call\n * from constructors and CI gates.\n */\nexport function assertLlmRoute(opts: LlmClientOptions, req: LlmRouteRequirements = {}): void {\n const baseUrlExplicit = opts.baseUrl !== undefined\n const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n\n if (req.requireExplicitBaseUrl && !baseUrlExplicit) {\n throw new LlmRouteAssertionError(\n `assertLlmRoute: requireExplicitBaseUrl set but opts.baseUrl is undefined; would fall back to ${DEFAULT_BASE_URL}.`,\n 'no_explicit_base_url',\n baseUrl,\n )\n }\n\n if (req.blockedBaseUrls?.some((p) => matchUrl(baseUrl, p))) {\n throw new LlmRouteAssertionError(\n `assertLlmRoute: baseUrl ${baseUrl} matches a blocked pattern.`,\n 'base_url_blocked',\n baseUrl,\n )\n }\n\n if (req.allowedBaseUrls && req.allowedBaseUrls.length > 0) {\n const ok = req.allowedBaseUrls.some((p) => matchUrl(baseUrl, p))\n if (!ok) {\n throw new LlmRouteAssertionError(\n `assertLlmRoute: baseUrl ${baseUrl} is not in the allowed list (${req.allowedBaseUrls.map(describePattern).join(', ')}).`,\n 'base_url_not_allowed',\n baseUrl,\n )\n }\n }\n\n if (req.requireAuth && !opts.apiKey && !opts.bearer && !opts.authHeader) {\n throw new LlmRouteAssertionError(\n `assertLlmRoute: requireAuth set but no apiKey, bearer, or authHeader was supplied.`,\n 'no_auth',\n baseUrl,\n )\n }\n\n if (req.expectedProvider) {\n const actual = opts.provider ?? providerFromBaseUrl(baseUrl)\n if (actual !== req.expectedProvider) {\n throw new LlmRouteAssertionError(\n `assertLlmRoute: expected provider ${req.expectedProvider} but baseUrl ${baseUrl} resolves to ${actual}.`,\n 'wrong_provider',\n baseUrl,\n )\n }\n }\n}\n\nfunction matchUrl(url: string, pattern: string | RegExp): boolean {\n if (pattern instanceof RegExp) return pattern.test(url)\n return url.toLowerCase().startsWith(pattern.toLowerCase())\n}\n\nfunction describePattern(p: string | RegExp): string {\n return p instanceof RegExp ? p.source : p\n}\n\n/**\n * Probe whether a model is reachable. Returns latency + null error on\n * success; `ok=false` + error message on any failure (HTTP, timeout,\n * network, parse). Designed for sweep preflights — fail loud at the\n * boundary before burning a 30-leaf run on a misconfigured router.\n *\n * Sends a tiny `ping` message with `maxTokens=64`. Reasoning models\n * (glm-5.1, deepseek-v4) can burn the entire budget on internal reasoning\n * for short prompts, so don't tighten this further. We don't validate\n * content; HTTP 200 means reachable.\n */\nexport async function probeLlm(\n model: string,\n opts: LlmClientOptions & { timeoutMs?: number } = {},\n): Promise<{ ok: boolean; latencyMs: number; error: string | null }> {\n const start = Date.now()\n try {\n await callLlm(\n {\n model,\n messages: [{ role: 'user', content: 'ping' }],\n maxTokens: 64,\n timeoutMs: opts.timeoutMs ?? 30_000,\n },\n opts,\n )\n return { ok: true, latencyMs: Date.now() - start, error: null }\n } catch (err) {\n return {\n ok: false,\n latencyMs: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\n/**\n * Stateful client — construct once with defaults, call many times.\n * Thin wrapper around the free functions; exists for callers that want\n * to inject a single configured instance into multiple primitives.\n */\nexport class LlmClient {\n readonly maximumAttempts: number\n private readonly opts: LlmClientOptions\n\n constructor(opts: LlmClientOptions = {}) {\n this.opts = opts\n this.maximumAttempts = resolveMaximumAttempts(opts.maximumAttempts)\n }\n\n call(req: LlmCallRequest, per?: LlmClientOptions): Promise<LlmCallResult> {\n const options = { ...this.opts, ...per }\n return req.jsonSchema ? callLlmStructured(req, options) : callLlm(req, options)\n }\n\n callJson<T = unknown>(\n req: LlmCallRequest,\n per?: LlmClientOptions,\n ): Promise<{ value: T; result: LlmCallResult }> {\n return callLlmJson<T>(req, { ...this.opts, ...per })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0EA,SAAgB,2BAC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