@tangle-network/agent-eval 0.144.0 → 0.144.1
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 +12 -0
- package/dist/analyst/index.d.ts +82 -17
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +4 -4
- package/dist/{benchmark-command-4c7N_rlw.js → benchmark-command-95Zqd1e8.js} +331 -110
- package/dist/benchmark-command-95Zqd1e8.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-CRT4ScEA.js} +4 -4
- package/dist/{benchmarks-05UGZ8sZ.js.map → benchmarks-CRT4ScEA.js.map} +1 -1
- package/dist/campaign/index.d.ts +4 -4
- package/dist/campaign/index.js +4 -4
- package/dist/{campaign-BKOtvRAB.js → campaign-CefP3fPS.js} +4 -4
- package/dist/{campaign-BKOtvRAB.js.map → campaign-CefP3fPS.js.map} +1 -1
- package/dist/cli.js +2 -2
- package/dist/contract/index.d.ts +1 -1
- package/dist/contract/index.js +3 -3
- 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/{dspy-rlm-engine-CBFwlyaY.js → dspy-rlm-engine-BR7TtB0o.js} +61 -105
- package/dist/dspy-rlm-engine-BR7TtB0o.js.map +1 -0
- package/dist/{eval-campaign-YdkpWWoT.js → eval-campaign-lI7wB9DH.js} +2 -2
- package/dist/{eval-campaign-YdkpWWoT.js.map → eval-campaign-lI7wB9DH.js.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/{index-DgbFl4cv.d.ts → index-BrpxwELi.d.ts} +2 -2
- package/dist/{index-DgbFl4cv.d.ts.map → index-BrpxwELi.d.ts.map} +1 -1
- package/dist/{index-DtMpBKVF.d.ts → index-DRI1DU5z.d.ts} +3 -3
- package/dist/{index-DtMpBKVF.d.ts.map → index-DRI1DU5z.d.ts.map} +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.js +9 -9
- package/dist/{llm-client-B3WXSH5Y.js → llm-client-D3EoChAU.js} +7 -7
- package/dist/llm-client-D3EoChAU.js.map +1 -0
- package/dist/openapi.json +1 -1
- package/dist/rl.js +1 -1
- package/dist/{semantic-concept-judge-DJQtFr95.js → semantic-concept-judge-l8Lb3Kqz.js} +2 -2
- package/dist/{semantic-concept-judge-DJQtFr95.js.map → semantic-concept-judge-l8Lb3Kqz.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-B-cFnnNn.js} +718 -186
- package/dist/single-run-lock-B-cFnnNn.js.map +1 -0
- package/dist/{skill-usage-BiVEU0QY.d.ts → skill-usage-3vUWdZ9n.d.ts} +23 -4
- package/dist/skill-usage-3vUWdZ9n.d.ts.map +1 -0
- package/dist/{skillopt-optimization-method-Ds8J1_K8.js → skillopt-optimization-method-DA5mJmFE.js} +15 -204
- package/dist/skillopt-optimization-method-DA5mJmFE.js.map +1 -0
- package/dist/{skillopt-optimization-method-B7o01OdX.d.ts → skillopt-optimization-method-DNniakI5.d.ts} +6 -2
- package/dist/{skillopt-optimization-method-B7o01OdX.d.ts.map → skillopt-optimization-method-DNniakI5.d.ts.map} +1 -1
- package/dist/types-BjMFz88h.d.ts.map +1 -1
- package/dist/wire/index.js +1 -1
- package/docs/trace-analysis.md +43 -32
- package/package.json +1 -1
- package/dist/benchmark-command-4c7N_rlw.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/llm-client-B3WXSH5Y.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,QAAQ,QAAQ;GAChB,SAAS,QAAQ;EACnB;EACA,kBAAkB,IAAI,UAAU;EAChC,WAAW,OAAO,iBAAiB,SAAS,cAAc,EAAE,MAAM,KAAK,CAAC;EAExE,IAAI;EACJ,UAAU,cAAc,SAAS,UAAU,WAAW,MAAM,CAAC,CAAC,cAAc;GAC1E,WAAW,OAAO,oBAAoB,SAAS,YAAY;GAC3D,kBAAkB,OAAO,UAAU;GACnC,eAAe,OAAO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,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":"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,2BACd,SACA,UAA4B,CAAC,GACF;CAC3B,IAAI,QAAQ,cAAc,KAAA,GAAW,OAAO,KAAA;CAC5C,IAAI,CAAC,OAAO,UAAU,QAAQ,SAAS,KAAK,QAAQ,aAAa,GAC/D,MAAM,IAAI,WAAW,kEAAkE;CAEzF,IACE,QAAQ,SAAS,MACd,YACC,MAAM,QAAQ,QAAQ,OAAO,KAAK,QAAQ,QAAQ,MAAM,SAAS,KAAK,SAAS,WAAW,CAC9F,GAEA;CAGF,MAAM,WAAW,uBAAuB,QAAQ,eAAe;CAC/D,MAAM,kBAAkB,QAAQ,wBAAwB;CAGxD,MAAM,e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AAG;EACxD;CACF;AACF;;;;;;AAOA,IAAa,YAAb,MAAuB;CACrB;CACA;CAEA,YAAY,OAAyB,CAAC,GAAG;EACvC,KAAK,OAAO;EACZ,KAAK,kBAAkB,uBAAuB,KAAK,eAAe;CACpE;CAEA,KAAK,KAAqB,KAAgD;EACxE,MAAM,UAAU;GAAE,GAAG,KAAK;GAAM,GAAG;EAAI;EACvC,OAAO,IAAI,aAAa,kBAAkB,KAAK,OAAO,IAAI,QAAQ,KAAK,OAAO;CAChF;CAEA,SACE,KACA,KAC8C;EAC9C,OAAO,YAAe,KAAK;GAAE,GAAG,KAAK;GAAM,GAAG;EAAI,CAAC;CACrD;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"single-run-lock-t1si1ob7.js","names":["MAX_TIMER_DELAY_MS"],"sources":["../src/campaign/external-optimizer-contracts.ts","../src/verdict-cache.ts","../src/campaign/external-optimizer-http.ts","../src/campaign/external-optimizer-model-proxy.ts","../src/campaign/external-optimizer-resources.ts","../src/campaign/external-optimizer-subprocess.ts","../src/campaign/search-ledger-errors.ts","../src/campaign/search-ledger-file.ts","../src/campaign/storage.ts","../src/campaign/single-run-lock.ts"],"sourcesContent":["import type { CustomTokenPricing } from '../cost-ledger'\nimport { costForTokenPricing } from '../cost-ledger'\n\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\n\nexport interface ExternalOptimizerRunnerCommand {\n command?: string\n args?: readonly string[]\n env?: NodeJS.ProcessEnv\n}\n\nexport type ExternalOptimizerResumeMode = 'never' | 'if-compatible' | 'required'\n\nexport type ExternalTextCandidate = string | Record<string, string>\n\nexport interface ExternalTextEvaluationRequest {\n candidate: ExternalTextCandidate\n exampleId: string\n}\n\nexport interface ExternalOptimizerCallback {\n url: string\n token: string\n evaluations: () => number\n close: () => Promise<void>\n}\n\n/** One exact model request admitted by the loopback proxy. */\nexport interface ExternalOptimizerModelCallRequest {\n readonly path: '/v1/chat/completions' | '/v1/responses'\n readonly model: string\n readonly body: Readonly<Record<string, unknown>>\n readonly signal: AbortSignal\n}\n\n/** Runtime-owned result for one admitted optimizer-model call. */\nexport type ExternalOptimizerModelCallResult =\n | {\n readonly succeeded: true\n /** OpenAI-compatible response forwarded unchanged to the optimizer process. */\n readonly response: Response\n /** Canonical measured usage/cost input retained by Agent Eval's cost ledger. */\n readonly receipt: import('../cost-ledger').CostReceiptInput\n /** Opaque, finite JSON proof of the exact execution retained in provenance. */\n readonly execution: unknown\n }\n | {\n readonly succeeded: false\n /** Public failure text safe to retain and return to the child process. */\n readonly error: string\n /** Usage/cost state for the failed Runtime call. Unknown values stay unknown. */\n readonly receipt: import('../cost-ledger').CostReceiptInput\n /** Opaque, finite JSON proof of the failed exact execution. */\n readonly execution: unknown\n }\n\n/**\n * Execution-neutral model-call seam for an external optimizer.\n *\n * The package that owns execution implements this with its exact execution\n * path. For Discovery that owner is Runtime and the identity is an\n * AgentProfile. The loopback proxy owns request validation, limits, response\n * bounds, and cost-ledger recording. Once invoked, the callback must resolve\n * with one success/failure result. Rejecting loses the execution record and\n * therefore fails the optimizer attempt.\n */\nexport type ExternalOptimizerModelCall = (\n request: ExternalOptimizerModelCallRequest,\n) => Promise<ExternalOptimizerModelCallResult>\n\n/** One opaque Runtime execution record retained for one admitted model call. */\nexport type ExternalOptimizerModelExecutionObservation =\n | {\n readonly sequence: number\n readonly callRef: string\n readonly path: ExternalOptimizerModelCallRequest['path']\n readonly model: string\n readonly succeeded: true\n readonly responseStatus: number\n readonly execution: unknown\n }\n | {\n readonly sequence: number\n readonly callRef: string\n readonly path: ExternalOptimizerModelCallRequest['path']\n readonly model: string\n readonly succeeded: false\n readonly error: string\n readonly execution: unknown\n }\n\nexport type ExternalOptimizerEvaluationRefusalReason =\n | 'invalid-request'\n | 'evaluation-limit'\n | 'evaluation-failed'\n\n/**\n * Durable callback-side record of every candidate submitted for scoring,\n * scored task, and callback refusal. Optimizer-internal proposals that never\n * reach this callback are outside this record's scope.\n */\nexport type ExternalOptimizerEvaluationObservation =\n | {\n readonly kind: 'proposal'\n readonly sequence: number\n readonly candidate: ExternalTextCandidate\n readonly candidateHash: string\n }\n | {\n readonly kind: 'evaluation'\n readonly sequence: number\n readonly candidate: ExternalTextCandidate\n readonly candidateHash: string\n readonly exampleId: string\n /** One-based accepted evaluation number for this optimizer attempt. */\n readonly evaluationNumber: number\n readonly response: unknown\n }\n | {\n readonly kind: 'refusal'\n readonly sequence: number\n readonly reason: ExternalOptimizerEvaluationRefusalReason\n readonly candidate?: ExternalTextCandidate\n readonly candidateHash?: string\n readonly exampleId?: string\n }\n\nexport interface ExternalOptimizerModelBudget {\n /** Optional optimizer-model spend ceiling, independent of task-evaluation spend. */\n maxCostUsd?: number\n /** Maximum calls into the execution owner; owner-internal retries are reported there. */\n maxRequests: number\n /** Reject a request body above this byte count. */\n maxRequestBytes: number\n /** Reject a provider response above this byte count. */\n maxResponseBytes: number\n /** Reject a request asking the provider for more output tokens. */\n maxOutputTokensPerRequest: number\n /**\n * Reasoning tokens a single response may bill beyond its completion limit.\n *\n * A reasoning model bounds only the completion by `max_tokens` and bills\n * thinking on top, so a reservation sized to the completion alone is always\n * too small and the ledger refuses the real charge. Callers that route a\n * reasoning model declare its thinking budget here; the reservation covers\n * it and a response exceeding it still fails loudly. Default: 0.\n */\n maxReasoningTokensPerRequest?: number\n /**\n * Optional rates used to estimate cost when the provider omits a valid\n * `usage.cost`. Omit when billed USD is unknown; catalog estimates are not\n * enforcement evidence.\n */\n pricing?: CustomTokenPricing\n /** Per-provider-request deadline. Default: 300,000 ms. */\n requestTimeoutMs?: number\n}\n\nexport interface ExternalOptimizerModelProxy {\n /** OpenAI-compatible base URL supplied to the optimizer process. */\n baseUrl: string\n /** Ephemeral credential supplied only to the local proxy. */\n apiKey: string\n /** Execution-owner calls admitted during this proxy process, including failures. */\n requestAttempts: () => number\n /** Successful 2xx responses recorded during this proxy process. */\n successfulCompletions: () => number\n /** Fail if an invoked caller-owned model path omitted its execution record. */\n assertExecutionComplete: () => void\n close: () => Promise<void>\n}\n\nexport function isCandidateText(value: unknown, maxChars: number): value is string {\n return typeof value === 'string' && value.trim().length > 0 && value.length <= maxChars\n}\n\nexport function isExternalTextCandidate(value: unknown): value is ExternalTextCandidate {\n if (typeof value === 'string') return value.trim().length > 0\n if (!isRecord(value)) return false\n const entries = Object.entries(value)\n return (\n entries.length > 0 &&\n entries.every(\n ([name, content]) =>\n name.trim().length > 0 && name.trim() === name && typeof content === 'string',\n )\n )\n}\n\nexport function assertJsonValue(value: unknown, label: string, seen = new Set<object>()): void {\n if (value === null || typeof value === 'string' || typeof value === 'boolean') return\n if (typeof value === 'number' && Number.isFinite(value)) return\n if (Array.isArray(value)) {\n if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`)\n seen.add(value)\n for (const item of value) assertJsonValue(item, label, seen)\n seen.delete(value)\n return\n }\n if (typeof value === 'object') {\n if (seen.has(value)) throw new Error(`${label} must be JSON-serializable`)\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must be JSON-serializable`)\n }\n seen.add(value)\n for (const item of Object.values(value)) assertJsonValue(item, label, seen)\n seen.delete(value)\n return\n }\n throw new Error(`${label} must be JSON-serializable`)\n}\n\nexport function assertNoCredentialValues(\n value: unknown,\n path: string,\n credentialLocation = 'runner.env',\n): void {\n if (Array.isArray(value)) {\n for (const [index, item] of value.entries()) {\n assertNoCredentialValues(item, `${path}[${index}]`, credentialLocation)\n }\n return\n }\n if (!isRecord(value)) return\n for (const [key, item] of Object.entries(value)) {\n if (isCredentialKey(key)) {\n throw new Error(`${path}.${key} must be supplied through ${credentialLocation}`)\n }\n assertNoCredentialValues(item, `${path}.${key}`, credentialLocation)\n }\n}\n\nexport function removeCredentialEnvironment(\n environment: Readonly<Record<string, string | undefined>>,\n): Record<string, string> {\n const sanitized: Record<string, string> = {}\n for (const [key, value] of Object.entries(environment)) {\n if (value !== undefined && !isCredentialKey(key)) sanitized[key] = value\n }\n return sanitized\n}\n\nexport function assertExternalOptimizerModelBudget(\n value: ExternalOptimizerModelBudget,\n label: string,\n): void {\n if (!value || typeof value !== 'object') {\n throw new Error(`${label} is required`)\n }\n for (const [field, entry] of [\n ['maxRequests', value.maxRequests],\n ['maxRequestBytes', value.maxRequestBytes],\n ['maxResponseBytes', value.maxResponseBytes],\n ['maxOutputTokensPerRequest', value.maxOutputTokensPerRequest],\n ] as const) {\n if (!Number.isSafeInteger(entry) || entry <= 0) {\n throw new Error(`${label}.${field} must be a positive safe integer`)\n }\n }\n if (\n value.maxReasoningTokensPerRequest !== undefined &&\n (!Number.isSafeInteger(value.maxReasoningTokensPerRequest) ||\n value.maxReasoningTokensPerRequest < 0)\n ) {\n throw new Error(`${label}.maxReasoningTokensPerRequest must be a non-negative safe integer`)\n }\n if (\n value.maxCostUsd !== undefined &&\n (!Number.isFinite(value.maxCostUsd) || value.maxCostUsd <= 0)\n ) {\n throw new Error(`${label}.maxCostUsd must be positive and finite when supplied`)\n }\n if (\n value.requestTimeoutMs !== undefined &&\n (!Number.isSafeInteger(value.requestTimeoutMs) ||\n value.requestTimeoutMs <= 0 ||\n value.requestTimeoutMs > MAX_TIMER_DELAY_MS)\n ) {\n throw new Error(`${label}.requestTimeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n if (value.pricing !== undefined) {\n costForTokenPricing(value.pricing, { inputTokens: 1, outputTokens: 1 })\n }\n if (value.maxCostUsd !== undefined && value.pricing === undefined) {\n throw new Error(`${label}.pricing is required when maxCostUsd is supplied`)\n }\n}\n\nexport function safePathComponent(value: string): string {\n return value.replace(/[^a-zA-Z0-9._-]/g, '_')\n}\n\nfunction isCredentialKey(key: string): boolean {\n const normalized = key\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/-/g, '_')\n .toLowerCase()\n const segments = normalized.split('_')\n return segments.some((segment) =>\n [\n 'auth',\n 'authorization',\n 'cookie',\n 'credential',\n 'credentials',\n 'key',\n 'password',\n 'secret',\n 'session',\n 'token',\n ].includes(segment),\n )\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","/**\n * Content-addressed judge-verdict caching.\n *\n * LAW: cache JUDGE VERDICTS only — judging the same artifact with the same\n * judge+rubric is pure. NEVER cache agent rollouts. (A router that cached\n * identical fanout prompts silently destroyed best-of-N diversity; rollout\n * caching reintroduces that failure class. Judging has no diversity to\n * destroy — same artifact + same rubric ⇒ same verdict is the desired\n * property, not a bug.)\n *\n * The cache key is a sha-256 over the canonical JSON of everything that can\n * change a verdict: the artifact content, the scenario id, the judge name,\n * the full dimension list (key + description — the description IS the rubric\n * text shown to the judge), and a caller-supplied `judgeVersion`.\n * `judgeVersion` is REQUIRED: a judge whose prompt/model/ensemble changes\n * without a version bump would otherwise silently serve stale verdicts.\n *\n * Strict canonicalization (`canonicalJson`) throws on undefined / function /\n * symbol / non-finite numbers — an artifact that cannot be unambiguously\n * serialized cannot be content-addressed, and coercing it would let two\n * different artifacts collide on one key.\n */\n\nimport { createHash } from 'node:crypto'\nimport { appendFileSync, existsSync, readFileSync } from 'node:fs'\nimport type { JudgeConfig, JudgeScore, Scenario } from './campaign/types'\n\n// ── canonical JSON + content hash ─────────────────────────────────────────\n\nfunction canonicalizeAt(value: unknown, path: string): string {\n if (value === null) return 'null'\n switch (typeof value) {\n case 'boolean':\n return value ? 'true' : 'false'\n case 'number':\n if (!Number.isFinite(value)) {\n throw new Error(\n `canonicalJson: non-finite number (${value}) at ${path} — ambiguity is an error, not a coercion`,\n )\n }\n return JSON.stringify(value)\n case 'string':\n return JSON.stringify(value)\n case 'undefined':\n case 'function':\n case 'symbol':\n throw new Error(\n `canonicalJson: ${typeof value} at ${path} — ambiguity is an error, not a coercion`,\n )\n case 'bigint':\n throw new Error(`canonicalJson: bigint at ${path} — not representable in JSON`)\n case 'object':\n break\n }\n const obj = value as Record<string, unknown>\n // Honor toJSON (Date → ISO string) before structural checks — without it a\n // Date would canonicalize to '{}' and every timestamp would collide.\n if (typeof obj.toJSON === 'function') {\n return canonicalizeAt((obj as { toJSON(): unknown }).toJSON(), path)\n }\n if (Array.isArray(obj)) {\n return `[${obj.map((item, i) => canonicalizeAt(item, `${path}[${i}]`)).join(',')}]`\n }\n if (obj instanceof Map || obj instanceof Set) {\n throw new Error(\n `canonicalJson: ${obj instanceof Map ? 'Map' : 'Set'} at ${path} — would serialize as '{}'; convert to a plain object/array first`,\n )\n }\n const keys = Object.keys(obj).sort()\n const parts = keys.map((k) => `${JSON.stringify(k)}:${canonicalizeAt(obj[k], `${path}.${k}`)}`)\n return `{${parts.join(',')}}`\n}\n\n/**\n * Stable JSON stringify: object keys sorted recursively, so two semantically\n * equal values produce byte-identical output regardless of key insertion\n * order. Throws on undefined / function / symbol / NaN / ±Infinity / bigint /\n * Map / Set — anything JSON.stringify would coerce or drop silently.\n *\n * Distinct from `pre-registration.ts`'s `canonicalize`/`hashJson`, which are\n * permissive (coercion allowed) and async (web-crypto). Use THIS pair when a\n * hash collision or silent coercion would corrupt a cache key or attestation.\n */\nexport function canonicalJson(value: unknown): string {\n return canonicalizeAt(value, '$')\n}\n\n/** Hex sha-256 over `canonicalJson(value)`. The content address used by the\n * verdict cache and report attestation. */\nexport function contentHash(value: unknown): string {\n return createHash('sha256').update(canonicalJson(value)).digest('hex')\n}\n\n// ── store contract ─────────────────────────────────────────────────────────\n\n/** Pluggable verdict store. Sync or async on both legs — `cachedJudge`\n * awaits the results either way. */\nexport interface VerdictCacheStore {\n get(key: string): Promise<JudgeScore | undefined> | JudgeScore | undefined\n set(key: string, score: JudgeScore): Promise<void> | void\n}\n\n/** Process-local Map-backed store. */\nexport function inMemoryVerdictCache(): VerdictCacheStore {\n const entries = new Map<string, JudgeScore>()\n return {\n get: (key) => entries.get(key),\n set: (key, score) => {\n entries.set(key, score)\n },\n }\n}\n\ninterface VerdictCacheLine {\n key: string\n score: JudgeScore\n}\n\nfunction parseCacheLine(line: string, path: string, lineNo: number): VerdictCacheLine {\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n throw new Error(\n `fileVerdictCache: corrupt JSONL at ${path}:${lineNo} — ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n const rec = parsed as Partial<VerdictCacheLine>\n if (\n typeof rec !== 'object' ||\n rec === null ||\n typeof rec.key !== 'string' ||\n typeof rec.score !== 'object' ||\n rec.score === null ||\n typeof rec.score.composite !== 'number' ||\n typeof rec.score.dimensions !== 'object'\n ) {\n throw new Error(\n `fileVerdictCache: invalid record shape at ${path}:${lineNo} — expected {key, score:{dimensions, composite, notes}}`,\n )\n }\n return rec as VerdictCacheLine\n}\n\n/**\n * JSONL-file-backed store: the full file is loaded into an in-memory index at\n * construction; every `set` appends one line synchronously (durable before\n * the verdict is returned). A corrupt or malformed line throws at load with\n * file:line — a skipped line would silently re-judge (cost) or, worse, mask\n * a half-written file that needs operator attention.\n */\nexport function fileVerdictCache(path: string): VerdictCacheStore {\n const entries = new Map<string, JudgeScore>()\n if (existsSync(path)) {\n const lines = readFileSync(path, 'utf8').split('\\n')\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]\n if (line === undefined || line.trim() === '') continue\n const rec = parseCacheLine(line, path, i + 1)\n entries.set(rec.key, rec.score)\n }\n }\n return {\n get: (key) => entries.get(key),\n set: (key, score) => {\n appendFileSync(path, `${JSON.stringify({ key, score })}\\n`, 'utf8')\n entries.set(key, score)\n },\n }\n}\n\n// ── cached judge wrapper ───────────────────────────────────────────────────\n\nexport interface VerdictCacheStats {\n hits: number\n misses: number\n}\n\nexport interface CachedJudgeOptions {\n /** REQUIRED — part of the cache key. Bump on any change to the judge's\n * prompt, model, ensemble, or scoring logic; silent judge upgrades must\n * never serve stale verdicts. */\n judgeVersion: string\n}\n\n/** The wrapped judge: same `JudgeConfig` seam, plus hit/miss observability. */\nexport type CachedJudge<TArtifact, TScenario extends Scenario = Scenario> = JudgeConfig<\n TArtifact,\n TScenario\n> & {\n stats(): VerdictCacheStats\n}\n\n/**\n * Wrap a `JudgeConfig` so repeat judgments of the same artifact are served\n * from the store instead of re-invoking `score()`. The wrapper is generic\n * over the judge's own type parameters and preserves `appliesTo` — it is a\n * drop-in replacement anywhere a `JudgeConfig` is accepted.\n *\n * A judge that throws is NOT cached: the error propagates and the next\n * attempt re-judges (caching a failure would pin a transient outage forever).\n */\nexport function cachedJudge<TArtifact, TScenario extends Scenario = Scenario>(\n judge: JudgeConfig<TArtifact, TScenario>,\n store: VerdictCacheStore,\n options: CachedJudgeOptions,\n): CachedJudge<TArtifact, TScenario> {\n if (typeof options.judgeVersion !== 'string' || options.judgeVersion.trim() === '') {\n throw new Error('cachedJudge: judgeVersion is required and must be a non-empty string')\n }\n const stats: VerdictCacheStats = { hits: 0, misses: 0 }\n const wrapped: CachedJudge<TArtifact, TScenario> = {\n name: judge.name,\n dimensions: judge.dimensions,\n judgeVersion: options.judgeVersion,\n async score(input) {\n const key = contentHash({\n artifact: canonicalJson(input.artifact),\n scenarioId: input.scenario.id,\n judgeName: judge.name,\n dimensions: judge.dimensions,\n judgeVersion: options.judgeVersion,\n })\n const cached = await store.get(key)\n if (cached !== undefined) {\n stats.hits += 1\n return cached\n }\n const score = await judge.score(input)\n await store.set(key, score)\n stats.misses += 1\n return score\n },\n stats: () => ({ ...stats }),\n }\n if (judge.appliesTo) wrapped.appliesTo = judge.appliesTo\n return wrapped\n}\n","import type { Server, ServerResponse } from 'node:http'\n\nexport function listenLocal(server: Server): Promise<number> {\n return new Promise((resolvePromise, reject) => {\n server.once('error', reject)\n server.listen(0, '127.0.0.1', () => {\n server.off('error', reject)\n const address = server.address()\n if (!address || typeof address === 'string') {\n reject(new Error('external optimizer callback did not bind a TCP port'))\n return\n }\n resolvePromise(address.port)\n })\n })\n}\n\nexport function closeServer(server: Server): Promise<void> {\n return new Promise((resolvePromise, reject) => {\n server.close((error) => (error ? reject(error) : resolvePromise()))\n })\n}\n\nexport function sendJson(response: ServerResponse, status: number, body: unknown): void {\n response.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })\n response.end(JSON.stringify(body))\n}\n","import { randomBytes } from 'node:crypto'\nimport { createServer, type IncomingMessage, type ServerResponse } from 'node:http'\nimport type {\n CostChannel,\n CostLedgerHandle,\n CostReceiptInput,\n CustomTokenPricing,\n} from '../cost-ledger'\nimport { costForTokenPricing } from '../cost-ledger'\nimport { canonicalJson } from '../verdict-cache'\nimport {\n assertExternalOptimizerModelBudget,\n assertJsonValue,\n type ExternalOptimizerModelBudget,\n type ExternalOptimizerModelCall,\n type ExternalOptimizerModelExecutionObservation,\n type ExternalOptimizerModelProxy,\n isRecord,\n} from './external-optimizer-contracts'\nimport { closeServer, listenLocal, sendJson } from './external-optimizer-http'\n\nconst MODEL_PROXY_PATHS = new Set(['/v1/chat/completions', '/v1/responses'])\n\ntype UnsequencedExecutionObservation = ExternalOptimizerModelExecutionObservation extends infer T\n ? T extends ExternalOptimizerModelExecutionObservation\n ? Omit<T, 'sequence'>\n : never\n : never\n\ninterface ProviderProxyResponse {\n status: number\n contentType: string\n body: Uint8Array\n receipt: CostReceiptInput\n usageComplete: boolean\n /** A Runtime-owned call failed after returning complete execution evidence. */\n modelCallFailed?: string\n /** Set when the response violated the output or reasoning limit; forces a 502. */\n usageRejected?: string\n}\n\ntype ExternalOptimizerModelProxyArgs = {\n call: ExternalOptimizerModelCall\n callRef: string\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n budget: ExternalOptimizerModelBudget\n costLedger: CostLedgerHandle\n phase: string\n actor: string\n /** Cost-ledger channel. Defaults to `optimizer`. */\n channel?: CostChannel\n tags?: Record<string, string>\n initialUsage?: {\n requests: number\n /** Known billed subtotal. Omit when prior billed USD is unknown. */\n costUsd?: number\n }\n signal?: AbortSignal\n}\n\n/**\n * Put an OpenAI-compatible optimizer behind the shared cost ledger.\n *\n * The child process receives only a loopback URL and an ephemeral token. The\n * package that owns execution receives a validated immutable request through\n * `call`; Eval receives no provider credential. Every request reserves its\n * conservative byte-count input bound plus the declared output cap before the\n * owner is invoked exactly once.\n */\nexport async function startExternalOptimizerModelProxy(\n args: ExternalOptimizerModelProxyArgs,\n): Promise<ExternalOptimizerModelProxy> {\n assertModelProxyConfig(args)\n args.signal?.throwIfAborted()\n const token = randomLocalToken()\n let requestCount = 0\n let successfulCompletionCount = 0\n let modelCallInvocations = 0\n let executionRecordCount = 0\n let executionSequence = 0\n let totalRequestCount = args.initialUsage?.requests ?? 0\n let committedForBudget = args.initialUsage?.costUsd ?? 0\n let reservedForBudget = 0\n let accepting = true\n let closePromise: Promise<void> | undefined\n const activeControllers = new Set<AbortController>()\n const activeHandlers = new Set<Promise<void>>()\n\n const server = createServer((request, response) => {\n if (!accepting) {\n sendJsonIfOpen(response, 503, { error: 'external optimizer model proxy is closing' })\n return\n }\n\n const controller = new AbortController()\n const abortRequest = (): void => {\n request.destroy()\n response.destroy()\n }\n activeControllers.add(controller)\n controller.signal.addEventListener('abort', abortRequest, { once: true })\n\n let handler!: Promise<void>\n handler = handleModelProxyRequest({\n request,\n response,\n controller,\n token,\n args,\n nextReservation: (maximumCostUsd) => {\n if (totalRequestCount >= args.budget.maxRequests) {\n return { accepted: false as const, reason: 'optimizer model request limit reached' }\n }\n if (\n args.budget.maxCostUsd !== undefined &&\n maximumCostUsd !== undefined &&\n committedForBudget + reservedForBudget + maximumCostUsd >\n args.budget.maxCostUsd + Number.EPSILON\n ) {\n return { accepted: false as const, reason: 'optimizer model cost limit reached' }\n }\n requestCount += 1\n totalRequestCount += 1\n reservedForBudget += maximumCostUsd ?? 0\n return { accepted: true as const }\n },\n settleReservation: (maximumCostUsd, chargedCostUsd) => {\n reservedForBudget = Math.max(0, reservedForBudget - (maximumCostUsd ?? 0))\n committedForBudget += chargedCostUsd ?? 0\n },\n recordSuccessfulCompletion: () => {\n successfulCompletionCount += 1\n },\n recordExecutionReceipt: (observation) => {\n try {\n args.recordExecution({ ...observation, sequence: executionSequence + 1 })\n } catch (error) {\n throw new ModelExecutionPersistenceError(\n `optimizer model execution evidence was not persisted: ${toErrorMessage(error)}`,\n )\n }\n executionSequence += 1\n executionRecordCount += 1\n },\n recordModelCallInvocation: () => {\n modelCallInvocations += 1\n },\n }).finally(() => {\n controller.signal.removeEventListener('abort', abortRequest)\n activeControllers.delete(controller)\n activeHandlers.delete(handler)\n })\n activeHandlers.add(handler)\n void handler.catch(() => undefined)\n })\n const port = await listenLocal(server)\n const close = (): Promise<void> => {\n closePromise ??= closeModelProxy()\n return closePromise\n }\n const onAbort = (): void => {\n void close().catch(() => undefined)\n }\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n const assertExecutionComplete = (): void => {\n if (executionRecordCount !== modelCallInvocations) {\n throw new Error(\n `external optimizer model callback returned ${executionRecordCount} execution records for ${modelCallInvocations} invoked calls`,\n )\n }\n }\n return {\n baseUrl: `http://127.0.0.1:${port}/v1`,\n apiKey: token,\n requestAttempts: () => requestCount,\n successfulCompletions: () => successfulCompletionCount,\n assertExecutionComplete,\n close,\n }\n\n async function closeModelProxy(): Promise<void> {\n args.signal?.removeEventListener('abort', onAbort)\n accepting = false\n const closingServer = closeServer(server)\n server.closeIdleConnections?.()\n for (const controller of activeControllers) controller.abort()\n const [serverResult] = await Promise.allSettled([\n closingServer,\n waitForActiveHandlers(activeHandlers),\n ])\n if (activeControllers.size !== 0 || activeHandlers.size !== 0) {\n throw new Error('external optimizer model proxy closed with active request work')\n }\n let executionError: unknown\n try {\n assertExecutionComplete()\n } catch (error) {\n executionError = error\n }\n if (serverResult?.status === 'rejected' && executionError !== undefined) {\n throw new AggregateError(\n [serverResult.reason, executionError],\n 'external optimizer model proxy close and execution evidence both failed',\n )\n }\n if (serverResult?.status === 'rejected') throw serverResult.reason\n if (executionError !== undefined) throw executionError\n }\n}\n\nasync function handleModelProxyRequest(args: {\n request: IncomingMessage\n response: ServerResponse\n controller: AbortController\n token: string\n args: {\n call: ExternalOptimizerModelCall\n callRef: string\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n budget: ExternalOptimizerModelBudget\n costLedger: CostLedgerHandle\n phase: string\n actor: string\n channel?: CostChannel\n tags?: Record<string, string>\n }\n nextReservation: (maximumCostUsd: number | undefined) =>\n | { accepted: true }\n | {\n accepted: false\n reason: 'optimizer model request limit reached' | 'optimizer model cost limit reached'\n }\n settleReservation: (\n maximumCostUsd: number | undefined,\n chargedCostUsd: number | undefined,\n ) => void\n recordSuccessfulCompletion: () => void\n recordExecutionReceipt: (observation: UnsequencedExecutionObservation) => void\n recordModelCallInvocation: () => void\n}): Promise<void> {\n const { controller, request, response } = args\n try {\n const path = request.url ? new URL(request.url, 'http://127.0.0.1').pathname : ''\n if (request.method !== 'POST' || !MODEL_PROXY_PATHS.has(path)) {\n sendJsonIfOpen(response, 404, { error: 'not found' })\n return\n }\n if (request.headers.authorization !== `Bearer ${args.token}`) {\n sendJsonIfOpen(response, 401, { error: 'unauthorized' })\n return\n }\n\n const body = await readBody(request, args.args.budget.maxRequestBytes)\n const parsed = parseModelProxyRequest(body, args.args.model, args.args.budget)\n const maximumUsage = conservativeMaximumUsage(\n body.byteLength,\n parsed.maxOutputTokens + (args.args.budget.maxReasoningTokensPerRequest ?? 0),\n args.args.budget.pricing,\n )\n const maximumCostUsd = args.args.budget.pricing\n ? costForTokenPricing(args.args.budget.pricing, maximumUsage)\n : undefined\n const reservation = args.nextReservation(maximumCostUsd)\n if (!reservation.accepted) {\n sendJsonIfOpen(response, 429, { error: reservation.reason })\n return\n }\n\n const timeout = setTimeout(\n () => controller.abort(),\n args.args.budget.requestTimeoutMs ?? 300_000,\n )\n let chargedForBudget = maximumCostUsd\n try {\n const paid = await args.args.costLedger.runPaidCall<ProviderProxyResponse>({\n channel: args.args.channel ?? 'optimizer',\n phase: args.args.phase,\n actor: args.args.actor,\n ...(args.args.tags ? { tags: args.args.tags } : {}),\n model: args.args.model,\n ...(args.args.budget.pricing\n ? {\n maximumCharge: {\n customTokenPricing: args.args.budget.pricing,\n ...maximumUsage,\n },\n }\n : {}),\n execute: async () =>\n forwardModelProxyRequest({\n call: args.args.call,\n callRef: args.args.callRef,\n recordExecutionReceipt: args.recordExecutionReceipt,\n recordModelCallInvocation: args.recordModelCallInvocation,\n path,\n requestBody: parsed.body,\n model: args.args.model,\n maxOutputTokens: parsed.maxOutputTokens,\n ...(args.args.budget.maxReasoningTokensPerRequest === undefined\n ? {}\n : { maxReasoningTokens: args.args.budget.maxReasoningTokensPerRequest }),\n maxResponseBytes: args.args.budget.maxResponseBytes,\n signal: controller.signal,\n }),\n receipt: (result) => result.receipt,\n receiptFromError: () => ({\n model: args.args.model,\n inputTokens: 0,\n outputTokens: 0,\n costUnknown: true,\n usageUnknown: true,\n }),\n })\n if (!paid.succeeded) {\n chargedForBudget = paid.receipt\n ? paid.receipt.usageUnknown || paid.receipt.costUnknown\n ? maximumCostUsd\n : paid.receipt.costUsd\n : undefined\n sendJsonIfOpen(\n response,\n isAbortError(paid.error)\n ? 504\n : paid.error instanceof ProviderResponseTooLargeError ||\n paid.error instanceof MissingModelExecutionError ||\n paid.error instanceof ModelExecutionPersistenceError ||\n paid.error instanceof OwnerModelContractError\n ? 502\n : 429,\n { error: paid.error.message },\n )\n return\n }\n if (paid.value.modelCallFailed) {\n sendJsonIfOpen(response, 502, { error: paid.value.modelCallFailed })\n return\n }\n chargedForBudget = paid.value.usageComplete ? paid.receipt.costUsd : maximumCostUsd\n // A response that violated the output or reasoning limit is rejected. A\n // response the provider merely under-reported is forwarded with its cost\n // charged at the reservation maximum, so the analysis keeps its usable\n // completion and the ledger holds an honest upper-bound charge.\n if (paid.value.usageRejected) {\n sendJsonIfOpen(response, 502, { error: paid.value.usageRejected })\n return\n }\n if (paid.value.status >= 200 && paid.value.status < 300) {\n args.recordSuccessfulCompletion()\n }\n if (response.destroyed || response.writableEnded) return\n response.writeHead(paid.value.status, {\n 'content-type': paid.value.contentType,\n 'content-length': String(paid.value.body.byteLength),\n })\n response.end(paid.value.body)\n } finally {\n clearTimeout(timeout)\n args.settleReservation(maximumCostUsd, chargedForBudget)\n }\n } catch (error) {\n const status =\n error instanceof RequestBodyTooLargeError\n ? 413\n : error instanceof Error && isAbortError(error)\n ? 503\n : 400\n sendJsonIfOpen(response, status, { error: toErrorMessage(error) })\n }\n}\n\nasync function waitForActiveHandlers(activeHandlers: Set<Promise<void>>): Promise<void> {\n while (activeHandlers.size > 0) {\n await Promise.allSettled([...activeHandlers])\n }\n}\n\nfunction sendJsonIfOpen(response: ServerResponse, status: number, body: unknown): void {\n if (response.destroyed || response.writableEnded) return\n sendJson(response, status, body)\n}\n\nasync function forwardModelProxyRequest(args: {\n call: ExternalOptimizerModelCall\n callRef: string\n recordExecutionReceipt: (observation: UnsequencedExecutionObservation) => void\n recordModelCallInvocation: () => void\n path: string\n requestBody: Readonly<Record<string, unknown>>\n model: string\n maxOutputTokens: number\n /** Enforced only when the caller declared a thinking budget. */\n maxReasoningTokens?: number\n maxResponseBytes: number\n signal: AbortSignal\n}): Promise<ProviderProxyResponse> {\n args.recordModelCallInvocation()\n let called: Awaited<ReturnType<ExternalOptimizerModelCall>>\n try {\n called = await args.call({\n path: args.path as '/v1/chat/completions' | '/v1/responses',\n model: args.model,\n body: freezeJsonSnapshot(args.requestBody, 'optimizer model call body') as Readonly<\n Record<string, unknown>\n >,\n signal: args.signal,\n })\n } catch (error) {\n throw new MissingModelExecutionError(\n `optimizer model callback rejected without execution evidence: ${toErrorMessage(error)}`,\n )\n }\n if (!called || typeof called !== 'object' || typeof called.succeeded !== 'boolean') {\n throw new MissingModelExecutionError(\n 'optimizer model callback returned no typed success/failure outcome',\n )\n }\n let execution: unknown\n try {\n execution = freezeJsonSnapshot(called.execution, 'optimizer model callback execution evidence')\n } catch (error) {\n throw new MissingModelExecutionError(\n `optimizer model callback returned invalid execution evidence: ${toErrorMessage(error)}`,\n )\n }\n if (called.succeeded) {\n if (!(called.response instanceof Response)) {\n throw new MissingModelExecutionError(\n 'optimizer model callback success did not return a Response',\n )\n }\n args.recordExecutionReceipt({\n callRef: args.callRef,\n path: args.path as '/v1/chat/completions' | '/v1/responses',\n model: args.model,\n succeeded: true,\n responseStatus: called.response.status,\n execution,\n })\n } else {\n if (typeof called.error !== 'string' || !called.error.trim()) {\n throw new MissingModelExecutionError(\n 'optimizer model callback failure did not return a public error',\n )\n }\n args.recordExecutionReceipt({\n callRef: args.callRef,\n path: args.path as '/v1/chat/completions' | '/v1/responses',\n model: args.model,\n succeeded: false,\n error: called.error,\n execution,\n })\n const failedReceipt = snapshotModelReceipt(called.receipt, args.model)\n return {\n status: 502,\n contentType: 'application/json',\n body: new TextEncoder().encode(JSON.stringify({ error: called.error })),\n receipt: failedReceipt,\n usageComplete: failedReceipt.usageUnknown !== true,\n modelCallFailed: called.error,\n }\n }\n const response = called.response\n const authoritativeReceipt = snapshotModelReceipt(called.receipt, args.model)\n const body = await readProviderResponseBody(response, args.maxResponseBytes)\n const usage = parseProviderUsage(body)\n const successful = response.status >= 200 && response.status < 300\n // `outputTokens` carries reasoning tokens as a subset, and a reasoning model\n // bounds only the completion by the requested limit. Charging the whole\n // output against that limit rejects every ordinary response such a model\n // returns, so the guard measures the completion it actually governs.\n const completionTokens =\n usage === undefined ? 0 : usage.outputTokens - (usage.reasoningTokens ?? 0)\n const reasoningTokens = usage?.reasoningTokens ?? 0\n // A response that exceeds the requested output or the declared reasoning\n // budget violated the contract and is rejected. A response whose usage the\n // provider merely omitted is forwarded with its cost flagged: the completion\n // is still usable, and refusing it would fail a case over a reporting gap.\n const usageRejected =\n successful && usage !== undefined && completionTokens > args.maxOutputTokens\n ? `optimizer model provider reported ${completionTokens} completion tokens, exceeding requested limit ${args.maxOutputTokens}`\n : successful &&\n args.maxReasoningTokens !== undefined &&\n reasoningTokens > args.maxReasoningTokens\n ? `optimizer model provider reported ${reasoningTokens} reasoning tokens, exceeding the declared budget ${args.maxReasoningTokens}`\n : undefined\n if (usage !== undefined) {\n assertResponseUsageMatchesReceipt(usage, authoritativeReceipt)\n }\n return {\n status: response.status,\n contentType: response.headers.get('content-type') ?? 'application/json',\n body,\n receipt: authoritativeReceipt,\n usageComplete: authoritativeReceipt.usageUnknown !== true,\n ...(usageRejected ? { usageRejected } : {}),\n }\n}\n\nfunction snapshotModelReceipt(value: CostReceiptInput, expectedModel: string): CostReceiptInput {\n let snapshot: CostReceiptInput\n try {\n assertJsonValue(value, 'optimizer model callback receipt')\n snapshot = JSON.parse(canonicalJson(value)) as CostReceiptInput\n } catch (error) {\n throw new OwnerModelContractError(\n `optimizer model callback returned an invalid receipt: ${toErrorMessage(error)}`,\n )\n }\n if (snapshot.model !== expectedModel) {\n throw new OwnerModelContractError(\n `optimizer model callback receipt used '${snapshot.model}' instead of '${expectedModel}'`,\n )\n }\n return snapshot\n}\n\nfunction freezeJsonSnapshot(value: unknown, label: string): unknown {\n assertJsonValue(value, label)\n return deepFreezeJson(JSON.parse(canonicalJson(value)))\n}\n\nfunction deepFreezeJson(value: unknown): unknown {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) deepFreezeJson(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction assertResponseUsageMatchesReceipt(\n usage: NonNullable<ReturnType<typeof parseProviderUsage>>,\n receipt: CostReceiptInput,\n): void {\n for (const field of [\n 'inputTokens',\n 'outputTokens',\n 'cachedTokens',\n 'cacheWriteTokens',\n 'reasoningTokens',\n ] as const) {\n if ((usage[field] ?? 0) !== (receipt[field] ?? 0)) {\n throw new OwnerModelContractError(\n `optimizer model response usage disagrees with Runtime receipt at ${field}`,\n )\n }\n }\n if (usage.actualCostUsd !== undefined && usage.actualCostUsd !== receipt.actualCostUsd) {\n throw new OwnerModelContractError(\n 'optimizer model response cost disagrees with Runtime receipt',\n )\n }\n}\n\nfunction parseModelProxyRequest(\n body: Uint8Array,\n expectedModel: string,\n budget: ExternalOptimizerModelBudget,\n): { maxOutputTokens: number; body: Readonly<Record<string, unknown>> } {\n let value: unknown\n try {\n value = JSON.parse(Buffer.from(body).toString('utf8'))\n } catch {\n throw new Error('optimizer model request must be valid JSON')\n }\n if (!isRecord(value)) throw new Error('optimizer model request must be a JSON object')\n if (value.model !== expectedModel) {\n throw new Error(`optimizer model request must use configured model '${expectedModel}'`)\n }\n if (value.stream !== undefined && value.stream !== false) {\n throw new Error('streaming optimizer model requests are not supported')\n }\n for (const field of ['n', 'best_of', 'candidate_count', 'num_candidates'] as const) {\n if (value[field] !== undefined && value[field] !== 1) {\n throw new Error(`optimizer model request ${field} must be 1 when supplied`)\n }\n }\n const suppliedMaximums = [\n value.max_output_tokens,\n value.max_completion_tokens,\n value.max_tokens,\n ].filter((maximum) => maximum !== undefined)\n if (\n suppliedMaximums.length === 0 ||\n suppliedMaximums.some((maximum) => !Number.isSafeInteger(maximum) || (maximum as number) <= 0)\n ) {\n throw new Error('optimizer model request requires a positive output-token limit')\n }\n const maxOutputTokens = Math.max(...(suppliedMaximums as number[]))\n if (maxOutputTokens > budget.maxOutputTokensPerRequest) {\n throw new Error('optimizer model request exceeds maxOutputTokensPerRequest')\n }\n return { maxOutputTokens, body: value }\n}\n\nfunction parseProviderUsage(\n body: Uint8Array,\n):\n | Omit<CostReceiptInput, 'model' | 'customTokenPricing' | 'costUnknown' | 'usageUnknown'>\n | undefined {\n let value: unknown\n try {\n value = JSON.parse(Buffer.from(body).toString('utf8'))\n } catch {\n return undefined\n }\n if (!isRecord(value) || !isRecord(value.usage)) return undefined\n const usage = value.usage\n const totalInputTokens = usage.input_tokens ?? usage.prompt_tokens\n const outputTokens = usage.output_tokens ?? usage.completion_tokens\n if (\n !Number.isSafeInteger(totalInputTokens) ||\n (totalInputTokens as number) < 0 ||\n !Number.isSafeInteger(outputTokens) ||\n (outputTokens as number) < 0\n ) {\n return undefined\n }\n const inputDetails = isRecord(usage.input_tokens_details)\n ? usage.input_tokens_details\n : isRecord(usage.prompt_tokens_details)\n ? usage.prompt_tokens_details\n : {}\n const outputDetails = isRecord(usage.output_tokens_details)\n ? usage.output_tokens_details\n : isRecord(usage.completion_tokens_details)\n ? usage.completion_tokens_details\n : {}\n const nestedCachedTokens = optionalTokenCount(inputDetails, [\n 'cached_tokens',\n 'cache_read_tokens',\n ])\n const separateCachedTokens = optionalTokenCount(usage, ['cache_read_input_tokens'])\n const nestedCacheWriteTokens = optionalTokenCount(inputDetails, [\n 'cache_write_tokens',\n 'cache_creation_tokens',\n ])\n const separateCacheWriteTokens = optionalTokenCount(usage, ['cache_creation_input_tokens'])\n const nestedReasoningTokens = optionalTokenCount(outputDetails, ['reasoning_tokens'])\n const separateReasoningTokens = optionalTokenCount(usage, ['reasoning_tokens'])\n const actualCostUsd =\n typeof usage.cost === 'number' && Number.isFinite(usage.cost) && usage.cost >= 0\n ? usage.cost\n : undefined\n if (\n nestedCachedTokens === INVALID_TOKEN_COUNT ||\n separateCachedTokens === INVALID_TOKEN_COUNT ||\n nestedCacheWriteTokens === INVALID_TOKEN_COUNT ||\n separateCacheWriteTokens === INVALID_TOKEN_COUNT ||\n nestedReasoningTokens === INVALID_TOKEN_COUNT ||\n separateReasoningTokens === INVALID_TOKEN_COUNT\n ) {\n return undefined\n }\n const cached = selectProviderTokenClass(nestedCachedTokens, separateCachedTokens)\n const cacheWrite = selectProviderTokenClass(nestedCacheWriteTokens, separateCacheWriteTokens)\n const reasoning = selectProviderTokenClass(nestedReasoningTokens, separateReasoningTokens)\n if (cached === undefined || cacheWrite === undefined || reasoning === undefined) return undefined\n const classifiedInputTokens =\n (cached.includedInTotal ? cached.count : 0) +\n (cacheWrite.includedInTotal ? cacheWrite.count : 0)\n if (\n classifiedInputTokens > (totalInputTokens as number) ||\n reasoning.count > (outputTokens as number)\n ) {\n return undefined\n }\n return {\n inputTokens: (totalInputTokens as number) - classifiedInputTokens,\n outputTokens: outputTokens as number,\n ...(cached.supplied ? { cachedTokens: cached.count } : {}),\n ...(cacheWrite.supplied ? { cacheWriteTokens: cacheWrite.count } : {}),\n ...(reasoning.supplied ? { reasoningTokens: reasoning.count } : {}),\n ...(actualCostUsd === undefined ? {} : { actualCostUsd }),\n }\n}\n\n/**\n * OpenAI reports a cache class inside the input total; Anthropic reports it\n * beside the input total. When both equivalent forms are present they must\n * agree, and the nested normalized form wins.\n */\nfunction selectProviderTokenClass(\n nested: number | undefined,\n separate: number | undefined,\n): { count: number; supplied: boolean; includedInTotal: boolean } | undefined {\n if (nested !== undefined && separate !== undefined && nested > 0 && separate > 0) {\n if (nested !== separate) return undefined\n return { count: nested, supplied: true, includedInTotal: true }\n }\n if (nested !== undefined && nested > 0) {\n return { count: nested, supplied: true, includedInTotal: true }\n }\n if (separate !== undefined && separate > 0) {\n return { count: separate, supplied: true, includedInTotal: false }\n }\n return {\n count: 0,\n supplied: nested !== undefined || separate !== undefined,\n includedInTotal: nested !== undefined,\n }\n}\n\nconst INVALID_TOKEN_COUNT = Symbol('invalid-token-count')\n\nfunction optionalTokenCount(\n details: Record<string, unknown>,\n fields: readonly string[],\n): number | undefined | typeof INVALID_TOKEN_COUNT {\n let found: number | undefined\n for (const field of fields) {\n const value = details[field]\n if (value === undefined || value === null) continue\n if (!Number.isSafeInteger(value) || (value as number) < 0) return INVALID_TOKEN_COUNT\n if (found !== undefined && found !== value) return INVALID_TOKEN_COUNT\n found = value as number\n }\n return found\n}\n\nfunction conservativeMaximumUsage(\n inputTokenUpperBound: number,\n outputTokenUpperBound: number,\n pricing?: CustomTokenPricing,\n): Pick<CostReceiptInput, 'inputTokens' | 'outputTokens' | 'cachedTokens' | 'cacheWriteTokens'> {\n if (pricing === undefined) {\n return { inputTokens: inputTokenUpperBound, outputTokens: outputTokenUpperBound }\n }\n const inputRates = [\n pricing.inputUsdPerMillion,\n pricing.cachedInputUsdPerMillion ?? pricing.inputUsdPerMillion,\n pricing.cacheWriteUsdPerMillion ?? pricing.inputUsdPerMillion,\n ]\n const mostExpensiveInputClass = inputRates.indexOf(Math.max(...inputRates))\n return {\n inputTokens: mostExpensiveInputClass === 0 ? inputTokenUpperBound : 0,\n ...(mostExpensiveInputClass === 1 ? { cachedTokens: inputTokenUpperBound } : {}),\n ...(mostExpensiveInputClass === 2 ? { cacheWriteTokens: inputTokenUpperBound } : {}),\n outputTokens: outputTokenUpperBound,\n }\n}\n\nasync function readProviderResponseBody(response: Response, maxBytes: number): Promise<Uint8Array> {\n const declaredLength = response.headers.get('content-length')\n if (declaredLength !== null) {\n const parsedLength = Number(declaredLength)\n if (Number.isFinite(parsedLength) && parsedLength > maxBytes) {\n throw new ProviderResponseTooLargeError()\n }\n }\n if (!response.body) return new Uint8Array()\n\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let totalBytes = 0\n try {\n while (true) {\n const next = await reader.read()\n if (next.done) break\n totalBytes += next.value.byteLength\n if (totalBytes > maxBytes) {\n await reader.cancel()\n throw new ProviderResponseTooLargeError()\n }\n chunks.push(next.value)\n }\n } finally {\n reader.releaseLock()\n }\n\n const body = new Uint8Array(totalBytes)\n let offset = 0\n for (const chunk of chunks) {\n body.set(chunk, offset)\n offset += chunk.byteLength\n }\n return body\n}\n\nfunction assertModelProxyConfig(args: {\n call: ExternalOptimizerModelCall\n callRef: string\n recordExecution: (observation: ExternalOptimizerModelExecutionObservation) => void\n model: string\n budget: ExternalOptimizerModelBudget\n phase: string\n actor: string\n tags?: Record<string, string>\n initialUsage?: {\n requests: number\n costUsd?: number\n }\n}): void {\n for (const [label, value] of [\n ['model', args.model],\n ['phase', args.phase],\n ['actor', args.actor],\n ] as const) {\n if (typeof value !== 'string' || !value.trim() || value.trim() !== value) {\n throw new Error(`external optimizer model proxy: ${label} must be trimmed and non-empty`)\n }\n }\n if (typeof args.call !== 'function') {\n throw new Error('external optimizer model proxy: call must be a function')\n }\n if (\n typeof args.callRef !== 'string' ||\n !args.callRef.trim() ||\n args.callRef.trim() !== args.callRef\n ) {\n throw new Error('external optimizer model proxy: callRef must be trimmed and non-empty')\n }\n if (typeof args.recordExecution !== 'function') {\n throw new Error('external optimizer model proxy: recordExecution must be a function')\n }\n assertExternalOptimizerModelBudget(args.budget, 'external optimizer model proxy: budget')\n if (args.tags !== undefined) {\n for (const [key, value] of Object.entries(args.tags)) {\n if (!key.trim() || key.trim() !== key || !value.trim() || value.trim() !== value) {\n throw new Error('external optimizer model proxy: tags must be trimmed and non-empty')\n }\n }\n }\n if (args.initialUsage !== undefined) {\n if (\n !Number.isSafeInteger(args.initialUsage.requests) ||\n args.initialUsage.requests < 0 ||\n (args.initialUsage.costUsd !== undefined &&\n (!Number.isFinite(args.initialUsage.costUsd) || args.initialUsage.costUsd < 0))\n ) {\n throw new Error(\n 'external optimizer model proxy: initialUsage must contain non-negative requests and cost',\n )\n }\n if (\n args.initialUsage.requests > args.budget.maxRequests ||\n (args.budget.maxCostUsd !== undefined &&\n args.initialUsage.costUsd !== undefined &&\n args.initialUsage.costUsd > args.budget.maxCostUsd + Number.EPSILON)\n ) {\n throw new Error('external optimizer model proxy: initialUsage exceeds the configured budget')\n }\n }\n}\n\nclass RequestBodyTooLargeError extends Error {}\n\nclass ProviderResponseTooLargeError extends Error {\n constructor() {\n super('optimizer model response exceeds maxResponseBytes')\n }\n}\n\nclass MissingModelExecutionError extends Error {}\nclass ModelExecutionPersistenceError extends Error {}\nclass OwnerModelContractError extends Error {}\n\nfunction readBody(request: IncomingMessage, maximumBytes: number): Promise<Uint8Array> {\n return new Promise((resolvePromise, reject) => {\n let size = 0\n let tooLarge = false\n const chunks: Buffer[] = []\n request.on('data', (chunk: Buffer) => {\n if (tooLarge) return\n size += chunk.byteLength\n if (size > maximumBytes) {\n tooLarge = true\n chunks.length = 0\n return\n }\n chunks.push(chunk)\n })\n request.on('error', reject)\n request.on('end', () => {\n if (tooLarge) {\n reject(new RequestBodyTooLargeError('optimizer model request body too large'))\n return\n }\n resolvePromise(new Uint8Array(Buffer.concat(chunks)))\n })\n })\n}\n\nfunction randomLocalToken(): string {\n return randomBytes(32).toString('hex')\n}\n\nfunction isAbortError(error: Error): boolean {\n return error.name === 'AbortError' || error.message.toLowerCase().includes('abort')\n}\n\nfunction toErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import type {\n ExternalOptimizerCallback,\n ExternalOptimizerModelProxy,\n} from './external-optimizer-contracts'\n\nexport async function runWithCleanup<T>(args: {\n label: string\n run: () => Promise<T>\n cleanup: () => Promise<void>\n}): Promise<T> {\n let value: T | undefined\n let operationError: Error | undefined\n try {\n value = await args.run()\n } catch (cause) {\n operationError = toError(cause)\n }\n\n let cleanupError: Error | undefined\n try {\n await args.cleanup()\n } catch (cause) {\n cleanupError = toError(cause)\n }\n\n if (operationError && cleanupError) {\n throw new AggregateError(\n [operationError, cleanupError],\n `${operationError.message}; ${args.label} cleanup failed: ${cleanupError.message}`,\n )\n }\n if (operationError) throw operationError\n if (cleanupError) {\n throw new Error(`${args.label} cleanup failed: ${cleanupError.message}`, {\n cause: cleanupError,\n })\n }\n return value as T\n}\n\nexport async function closeExternalOptimizerResources(args: {\n label: string\n callback: ExternalOptimizerCallback\n modelProxy?: ExternalOptimizerModelProxy\n}): Promise<void> {\n const results = await Promise.allSettled([\n ...(args.modelProxy ? [args.modelProxy.close()] : []),\n args.callback.close(),\n ])\n const errors = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []))\n if (errors.length > 0) {\n throw new AggregateError(errors, `${args.label}: failed to close optimizer resources`)\n }\n}\n\nfunction toError(cause: unknown): Error {\n return cause instanceof Error ? cause : new Error(String(cause))\n}\n","import { type ChildProcess, spawn } from 'node:child_process'\nimport { lstat, mkdtemp, open, rm, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join, resolve } from 'node:path'\nimport { type ExternalOptimizerRunnerCommand, isRecord } from './external-optimizer-contracts'\nimport { runWithCleanup } from './external-optimizer-resources'\n\nconst MAX_PROCESS_OUTPUT_CHARS = 64_000\nconst MAX_PROCESS_INPUT_BYTES = 64 * 1024 * 1024\nconst MAX_PROCESS_RESULT_BYTES = 4 * 1024 * 1024\nconst PROCESS_TERMINATION_GRACE_MS = 5_000\nconst PROCESS_TERMINATION_POLL_MS = 25\nconst PROCESS_KILL_WAIT_MS = 1_000\nconst MAX_TIMER_DELAY_MS = 2_147_483_647\nconst PROCESS_OUTPUT_HEAD_CHARS = MAX_PROCESS_OUTPUT_CHARS / 2\nconst PROCESS_OUTPUT_TAIL_CHARS = MAX_PROCESS_OUTPUT_CHARS - PROCESS_OUTPUT_HEAD_CHARS\n\ninterface ProcessOutputCapture {\n full: string | undefined\n head: string\n tail: string\n totalChars: number\n}\n\nexport async function runExternalOptimizerProcess<TOutput>(args: {\n label: string\n tempPrefix: string\n module: string\n input: unknown\n runner?: ExternalOptimizerRunnerCommand\n timeoutMs: number\n signal?: AbortSignal\n}): Promise<TOutput> {\n if (\n !Number.isSafeInteger(args.timeoutMs) ||\n args.timeoutMs <= 0 ||\n args.timeoutMs > MAX_TIMER_DELAY_MS\n ) {\n throw new Error(`${args.label} timeoutMs must be between 1 and ${MAX_TIMER_DELAY_MS}`)\n }\n if (process.platform === 'win32') {\n throw new Error(\n `${args.label} requires POSIX process-group cleanup; run the optimizer through WSL or Linux`,\n )\n }\n throwIfAborted(args.signal, args.label)\n const dir = await mkdtemp(join(tmpdir(), args.tempPrefix))\n const inputPath = join(dir, 'input.json')\n const outputPath = join(dir, 'output.json')\n return runWithCleanup({\n label: `${args.label} temporary directory`,\n run: async () => {\n const serializedInput = JSON.stringify(args.input)\n if (serializedInput === undefined) {\n throw new Error(`${args.label} input must be JSON-serializable`)\n }\n const inputJson = `${serializedInput}\\n`\n const inputBytes = Buffer.byteLength(inputJson)\n if (inputBytes > MAX_PROCESS_INPUT_BYTES) {\n throw new Error(\n `${args.label} input exceeds ${MAX_PROCESS_INPUT_BYTES} bytes (${inputBytes})`,\n )\n }\n await writeFile(inputPath, inputJson)\n const command = resolveRunnerCommand(args.runner?.command ?? 'python')\n const commandArgs = [\n ...(args.runner?.args ?? ['-m', args.module]),\n '--input',\n inputPath,\n '--output',\n outputPath,\n ]\n await runProcess({\n label: args.label,\n command,\n args: commandArgs,\n cwd: dir,\n env: args.runner?.env,\n timeoutMs: args.timeoutMs,\n signal: args.signal,\n })\n throwIfAborted(args.signal, args.label)\n const raw = JSON.parse(\n await readBoundedTextFile(outputPath, MAX_PROCESS_RESULT_BYTES, `${args.label} output`),\n ) as unknown\n throwIfAborted(args.signal, args.label)\n if (!isRecord(raw)) throw new Error(`${args.label} output must be a JSON object`)\n return raw as TOutput\n },\n cleanup: () => rm(dir, { recursive: true, force: true }),\n })\n}\n\nfunction resolveRunnerCommand(command: string): string {\n if (isAbsolute(command) || (!command.includes('/') && !command.includes('\\\\'))) return command\n return resolve(command)\n}\n\nasync function readBoundedTextFile(path: string, maxBytes: number, label: string): Promise<string> {\n const entry = await lstat(path)\n if (!entry.isFile()) throw new Error(`${label} must be a regular file`)\n const file = await open(path, 'r')\n try {\n const buffer = Buffer.allocUnsafe(maxBytes + 1)\n let bytesRead = 0\n while (bytesRead < buffer.byteLength) {\n const chunk = await file.read(buffer, bytesRead, buffer.byteLength - bytesRead, bytesRead)\n if (chunk.bytesRead === 0) break\n bytesRead += chunk.bytesRead\n }\n if (bytesRead > maxBytes) {\n throw new Error(`${label} exceeds ${maxBytes} bytes`)\n }\n return buffer.subarray(0, bytesRead).toString('utf8')\n } finally {\n await file.close()\n }\n}\n\nfunction runProcess(args: {\n label: string\n command: string\n args: string[]\n cwd: string | undefined\n env: NodeJS.ProcessEnv | undefined\n timeoutMs: number\n signal: AbortSignal | undefined\n}): Promise<void> {\n throwIfAborted(args.signal, args.label)\n return new Promise((resolvePromise, reject) => {\n const child = spawn(args.command, args.args, {\n cwd: args.cwd,\n env: { ...safeProcessEnvironment(), ...args.env },\n stdio: ['ignore', 'pipe', 'pipe'],\n detached: process.platform !== 'win32',\n windowsHide: true,\n })\n const stdout = createProcessOutputCapture()\n const stderr = createProcessOutputCapture()\n let settled = false\n let timeout: NodeJS.Timeout | undefined\n const onAbort = () => finish(abortReason(args.signal!, args.label))\n const finish = (error?: Error) => {\n if (settled) return\n settled = true\n if (timeout) clearTimeout(timeout)\n args.signal?.removeEventListener('abort', onAbort)\n void terminateProcessTree(child).then(\n () => {\n if (error) reject(error)\n else resolvePromise()\n },\n (cleanupError: unknown) => {\n if (error) {\n const cleanup =\n cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError))\n reject(\n new AggregateError(\n [error, cleanup],\n `${error.message}; ${args.label} process cleanup failed: ${cleanup.message}`,\n ),\n )\n return\n }\n reject(\n new Error(\n `${args.label} process cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`,\n ),\n )\n },\n )\n }\n timeout = setTimeout(() => {\n finish(new Error(`${args.label} exceeded ${args.timeoutMs}ms`))\n }, args.timeoutMs)\n args.signal?.addEventListener('abort', onAbort, { once: true })\n if (args.signal?.aborted) onAbort()\n child.stdout.on('data', (chunk: Buffer) => {\n appendProcessOutput(stdout, chunk)\n })\n child.stderr.on('data', (chunk: Buffer) => {\n appendProcessOutput(stderr, chunk)\n })\n child.on('error', (error) => {\n finish(new Error(`${args.label} could not start: ${error.message}`))\n })\n child.on('close', (code) => {\n if (code === 0) {\n finish()\n return\n }\n finish(\n new Error(\n `${args.label} exited ${String(code)}. stderr=${summarizeProcessOutput(stderr)} stdout=${summarizeProcessOutput(stdout)}`,\n ),\n )\n })\n })\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined, label: string): void {\n if (signal?.aborted) throw abortReason(signal, label)\n}\n\nfunction abortReason(signal: AbortSignal, label: string): Error {\n return signal.reason instanceof Error\n ? signal.reason\n : new Error(`${label} aborted`, { cause: signal.reason })\n}\n\nfunction safeProcessEnvironment(): NodeJS.ProcessEnv {\n const allowed = [\n 'PATH',\n 'HOME',\n 'USER',\n 'LOGNAME',\n 'SHELL',\n 'TMPDIR',\n 'TMP',\n 'TEMP',\n 'LANG',\n 'LANGUAGE',\n 'LC_ALL',\n 'VIRTUAL_ENV',\n 'PYTHONPATH',\n 'SYSTEMROOT',\n 'COMSPEC',\n 'PATHEXT',\n 'WINDIR',\n ] as const\n return Object.fromEntries(\n allowed.flatMap((name) => {\n const value = process.env[name]\n return value === undefined ? [] : [[name, value]]\n }),\n )\n}\n\nasync function terminateProcessTree(child: ChildProcess): Promise<void> {\n const pid = child.pid\n if (!pid) return\n if (process.platform === 'win32') {\n throw new Error('native Windows process-tree cleanup is unsupported')\n }\n\n if (!signalProcessGroup(pid, 'SIGTERM')) return\n if (await waitForProcessGroupExit(pid, PROCESS_TERMINATION_GRACE_MS)) return\n if (!signalProcessGroup(pid, 'SIGKILL')) return\n if (await waitForProcessGroupExit(pid, PROCESS_KILL_WAIT_MS)) return\n throw new Error(`process group ${pid} remained alive after SIGKILL`)\n}\n\nfunction signalProcessGroup(pid: number, signal: NodeJS.Signals): boolean {\n try {\n process.kill(-pid, signal)\n return true\n } catch (error) {\n if (isMissingProcessError(error)) return false\n throw error\n }\n}\n\nasync function waitForProcessGroupExit(pid: number, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + timeoutMs\n while (processGroupExists(pid)) {\n const remainingMs = deadline - Date.now()\n if (remainingMs <= 0) return false\n await new Promise((resolve) =>\n setTimeout(resolve, Math.min(PROCESS_TERMINATION_POLL_MS, remainingMs)),\n )\n }\n return true\n}\n\nfunction processGroupExists(pid: number): boolean {\n try {\n process.kill(-pid, 0)\n return true\n } catch (error) {\n if (isMissingProcessError(error)) return false\n throw error\n }\n}\n\nfunction isMissingProcessError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code?: unknown }).code === 'ESRCH'\n )\n}\n\nfunction createProcessOutputCapture(): ProcessOutputCapture {\n return { full: '', head: '', tail: '', totalChars: 0 }\n}\n\nfunction appendProcessOutput(capture: ProcessOutputCapture, chunk: Buffer): void {\n const text = chunk.toString()\n capture.totalChars += text.length\n if (capture.full !== undefined) {\n const combined = `${capture.full}${text}`\n if (combined.length <= MAX_PROCESS_OUTPUT_CHARS) {\n capture.full = combined\n return\n }\n capture.head = combined.slice(0, PROCESS_OUTPUT_HEAD_CHARS)\n capture.tail = combined.slice(-PROCESS_OUTPUT_TAIL_CHARS)\n capture.full = undefined\n return\n }\n capture.tail = `${capture.tail}${text}`.slice(-PROCESS_OUTPUT_TAIL_CHARS)\n}\n\nfunction summarizeProcessOutput(capture: ProcessOutputCapture, max = 4_000): string {\n const raw =\n capture.full ??\n `${capture.head}\\n...[${capture.totalChars - capture.head.length - capture.tail.length} chars omitted]...\\n${capture.tail}`\n const compact = raw.trim().replace(/\\s+/g, ' ')\n if (compact.length <= max) return compact\n const headChars = Math.floor(max / 3)\n const tailChars = max - headChars\n return `${compact.slice(0, headChars)}...[${compact.length - max} chars omitted]...${compact.slice(-tailChars)}`\n}\n","import { ValidationError } from '../errors'\n\n/** Base error for invalid search-ledger input or operations. */\nexport class SearchLedgerError extends ValidationError {}\n\n/** Error raised when durable search-ledger data fails an integrity check. */\nexport class SearchLedgerIntegrityError extends SearchLedgerError {}\n\n/** Error raised when an event identifier is reused with different content. */\nexport class SearchLedgerConflictError extends SearchLedgerError {}\n","/** Campaign binding of the generic journal file layer to search-ledger errors. */\n\nimport {\n appendLedgerLine,\n type FileLockResult,\n type LedgerFileContext,\n tryWithLedgerFileLock,\n withLedgerFileLock,\n} from '../ledger-core'\nimport { SearchLedgerIntegrityError } from './search-ledger-errors'\n\nexport const SEARCH_LEDGER_FILE_CONTEXT: LedgerFileContext = {\n subject: 'search ledger',\n integrityError: (message, options) => new SearchLedgerIntegrityError(message, options),\n}\n\nexport function appendSearchLedgerLine(path: string, line: string): void {\n appendLedgerLine(path, line, SEARCH_LEDGER_FILE_CONTEXT)\n}\n\nexport function withSearchLedgerFileLock<T>(ledgerPath: string, run: () => T): T {\n return withLedgerFileLock(ledgerPath, SEARCH_LEDGER_FILE_CONTEXT, run)\n}\n\nexport type { FileLockResult }\n\nexport function tryWithSearchLedgerFileLock<T>(\n ledgerPath: string,\n run: () => T,\n): FileLockResult<T> {\n return tryWithLedgerFileLock(ledgerPath, SEARCH_LEDGER_FILE_CONTEXT, run)\n}\n","import { createRequire } from 'node:module'\nimport { join } from 'node:path'\nimport { CostLedger } from '../cost-ledger'\nimport { appendSearchLedgerLine, tryWithSearchLedgerFileLock } from './search-ledger-file'\n\n/**\n * `CampaignStorage` — the filesystem seam `runCampaign` writes through\n * (run/cell dirs, the resumability cache, per-cell artifacts, trace spans).\n *\n * The default (`fsCampaignStorage`) is the Node filesystem — identical\n * behavior to the inline `node:fs` calls it replaces, so existing CLI\n * consumers are unaffected. `inMemoryCampaignStorage` keeps everything in a\n * `Map`, so the substrate runs in environments WITHOUT a filesystem\n * (Cloudflare Workers, Deno Deploy, other edge runtimes) — the campaign\n * still produces its `CampaignResult` (cells + aggregates) in memory;\n * artifacts/traces simply aren't persisted to disk.\n *\n * Paths are opaque keys to the in-memory adapter — it does not parse them,\n * so the same `join(...)`-built paths work unchanged across both adapters.\n */\nexport interface CampaignStorage {\n /** Ensure a directory exists (recursive). No-op for in-memory. */\n ensureDir(dir: string): void\n /** Does this path exist (as a written file or an ensured dir)? */\n exists(path: string): boolean\n /** Read a UTF-8 file; `undefined` when missing or unreadable. */\n read(path: string): string | undefined\n /** Write a file (string or bytes). Parent dir is assumed ensured. */\n write(path: string, content: string | Uint8Array): void\n /** Append only when the current UTF-8 byte length matches `expectedBytes`.\n * Returns the new length, or undefined when another writer won. */\n append(path: string, content: string, expectedBytes: number): number | undefined\n}\n\n/** Node-filesystem storage — the default. Lazily requires `node:fs` so the\n * module imports cleanly in non-Node runtimes (where the caller passes\n * `inMemoryCampaignStorage` instead and never constructs this).\n *\n * `createRequire(import.meta.url)` is the ESM-native lazy require — a bare\n * `require` is a ReferenceError under `\"type\": \"module\"`, which is exactly\n * the shape this package publishes. */\nexport function fsCampaignStorage(): CampaignStorage {\n const nodeRequire = createRequire(import.meta.url)\n const { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } = nodeRequire(\n 'node:fs',\n ) as typeof import('node:fs')\n return {\n ensureDir(dir) {\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n },\n exists(path) {\n return existsSync(path)\n },\n read(path) {\n try {\n return readFileSync(path, 'utf8')\n } catch {\n return undefined\n }\n },\n write(path, content) {\n writeFileSync(path, content as Uint8Array)\n },\n append(path, content, expectedBytes) {\n const result = tryWithSearchLedgerFileLock(path, () => {\n let actualBytes = 0\n try {\n actualBytes = statSync(path).size\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n if (actualBytes !== expectedBytes) return undefined\n appendSearchLedgerLine(path, content)\n return expectedBytes + Buffer.byteLength(content)\n })\n return result.acquired ? result.value : undefined\n },\n }\n}\n\n/** In-memory storage for filesystem-less runtimes. Artifacts + trace spans\n * live in a `Map` for the duration of the run; the `CampaignResult` is\n * fully populated, but nothing is persisted to disk. */\nexport function inMemoryCampaignStorage(): CampaignStorage {\n const files = new Map<string, string | Uint8Array>()\n const dirs = new Set<string>()\n return {\n ensureDir(dir) {\n dirs.add(dir)\n },\n exists(path) {\n return files.has(path) || dirs.has(path)\n },\n read(path) {\n const value = files.get(path)\n if (value === undefined) return undefined\n return typeof value === 'string' ? value : new TextDecoder().decode(value)\n },\n write(path, content) {\n files.set(path, content)\n },\n append(path, content, expectedBytes) {\n const current = files.get(path)\n const currentText =\n current === undefined\n ? ''\n : typeof current === 'string'\n ? current\n : new TextDecoder().decode(current)\n const currentBytes = new TextEncoder().encode(currentText).byteLength\n if (currentBytes !== expectedBytes) return undefined\n files.set(path, `${currentText}${content}`)\n return currentBytes + new TextEncoder().encode(content).byteLength\n },\n }\n}\n\n/** Open the durable spend account stored beside a logical run. */\nexport function createRunCostLedger(input: {\n storage: CampaignStorage\n runDir: string\n costCeilingUsd?: number\n /** Set false for read-only inspection that must not create the run directory. */\n ensureRunDir?: boolean\n}): CostLedger {\n const path = join(input.runDir, 'cost-ledger.jsonl')\n if (input.ensureRunDir ?? true) input.storage.ensureDir(input.runDir)\n return new CostLedger({\n costCeilingUsd: input.costCeilingUsd,\n persistence: {\n read: () => {\n const stored = input.storage.read(path)\n if (stored === undefined && input.storage.exists(path)) {\n throw new Error(`CostLedger: cannot read existing event log '${path}'`)\n }\n const events = stored ?? ''\n return {\n revision: String(new TextEncoder().encode(events).byteLength),\n events,\n }\n },\n append: (expectedRevision, event) => {\n const expectedBytes = Number(expectedRevision)\n if (!Number.isSafeInteger(expectedBytes) || expectedBytes < 0) {\n throw new Error(`CostLedger: invalid storage revision '${expectedRevision}'`)\n }\n const next = input.storage.append(path, event, expectedBytes)\n return next === undefined ? undefined : String(next)\n },\n },\n })\n}\n","/**\n * Single-run lock for evaluations that share one mutable environment.\n *\n * Two concurrent runs against a shared stateful gym silently corrupt each\n * other: each resets/mutates environment state mid-cell of the other, and\n * every score from both becomes garbage that LOOKS like worker variance\n * (agent-lab R357 burned hours on flip-flopping scores before tracing them\n * to exactly this). The fix is a pid lockfile: refuse to start while a live\n * holder exists, reclaim stale locks whose pid is gone, release only if the\n * lock is still ours.\n *\n * `alsoCheck` exists because independent runners can guard the same shared\n * resource with differently named lockfiles; a runner must respect all of\n * them even though it writes only its own.\n */\n\nimport {\n type AtomicFileLockUnavailable,\n probeAtomicFileLock,\n tryAcquireAtomicFileLock,\n} from '../ledger-core/atomic-file-lock'\n\nexport interface SingleRunLockOptions {\n /** Lockfile this runner writes (and checks). */\n readonly lockPath: string\n /** Other runners' lockfiles guarding the same resource; checked, never written. */\n readonly alsoCheck?: readonly string[]\n /** Install a process 'exit' hook that releases the lock. Default true. */\n readonly releaseOnExit?: boolean\n /** Owner pid recorded in the lockfile metadata. Default process.pid. */\n readonly pid?: number\n}\n\nexport interface SingleRunLock {\n /** Remove the lockfile if this process still owns it. Idempotent. */\n release(): void\n}\n\nfunction assertAvailable(path: string): void {\n const unavailable = probeAtomicFileLock({ lockPath: path })\n if (unavailable) throw unavailableError(path, unavailable)\n}\n\nfunction unavailableError(path: string, unavailable: AtomicFileLockUnavailable): Error {\n if (unavailable.reason === 'recovery') {\n return new Error(\n `single-run lock recovery is already in progress (${path}); refusing a concurrent run`,\n )\n }\n return new Error(\n `single-run lock held by live pid ${unavailable.holder.pid} (${path}); refusing a concurrent run on the shared resource`,\n )\n}\n\n/**\n * Acquire the lock or throw naming the live holder. A stale lock (holder pid\n * no longer running) is reclaimed by one contender. An interrupted reclaim\n * leaves a marker that fails closed instead of admitting overlapping runs.\n */\nexport function acquireSingleRunLock(opts: SingleRunLockOptions): SingleRunLock {\n const pid = opts.pid ?? process.pid\n if (!Number.isSafeInteger(pid) || pid <= 0)\n throw new Error('single-run lock pid must be a positive integer')\n for (const path of opts.alsoCheck ?? []) assertAvailable(path)\n const acquisition = tryAcquireAtomicFileLock({\n lockPath: opts.lockPath,\n pid,\n })\n if (!acquisition.acquired) throw unavailableError(opts.lockPath, acquisition)\n const releaseOnExit = opts.releaseOnExit ?? true\n let released = false\n const release = (): void => {\n if (released) return\n released = true\n if (releaseOnExit) process.off('exit', release)\n try {\n acquisition.lock.release()\n } catch {\n // release is best-effort; a leftover stale lock is reclaimed on next acquire\n }\n }\n try {\n for (const path of opts.alsoCheck ?? []) assertAvailable(path)\n } catch (error) {\n release()\n throw error\n }\n if (releaseOnExit) process.on('exit', release)\n return { release }\n}\n"],"mappings":";;;;;;;;;;;;AAGA,MAAMA,uBAAqB;AAyK3B,SAAgB,gBAAgB,OAAgB,UAAmC;CACjF,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,SAAS,KAAK,MAAM,UAAU;AACjF;AAEA,SAAgB,wBAAwB,OAAgD;CACtF,IAAI,OAAO,UAAU,UAAU,OAAO,MAAM,KAAK,CAAC,CAAC,SAAS;CAC5D,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,UAAU,OAAO,QAAQ,KAAK;CACpC,OACE,QAAQ,SAAS,KACjB,QAAQ,OACL,CAAC,MAAM,aACN,KAAK,KAAK,CAAC,CAAC,SAAS,KAAK,KAAK,KAAK,MAAM,QAAQ,OAAO,YAAY,QACzE;AAEJ;AAEA,SAAgB,gB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F;;;;;;AAOA,SAAgB,qBAAqB,MAA2C;CAC9E,MAAM,MAAM,KAAK,OAAO,QAAQ;CAChC,IAAI,CAAC,OAAO,cAAc,GAAG,KAAK,OAAO,GACvC,MAAM,IAAI,MAAM,gDAAgD;CAClE,KAAK,MAAM,QAAQ,KAAK,aAAa,CAAC,GAAG,gBAAgB,IAAI;CAC7D,MAAM,cAAc,yBAAyB;EAC3C,UAAU,KAAK;EACf;CACF,CAAC;CACD,IAAI,CAAC,YAAY,UAAU,MAAM,iBAAiB,KAAK,UAAU,WAAW;CAC5E,MAAM,gBAAgB,KAAK,iBAAiB;CAC5C,IAAI,WAAW;CACf,MAAM,gBAAsB;EAC1B,IAAI,UAAU;EACd,WAAW;EACX,IAAI,eAAe,QAAQ,IAAI,QAAQ,OAAO;EAC9C,IAAI;GACF,YAAY,KAAK,QAAQ;EAC3B,QAAQ,CAER;CACF;CACA,IAAI;EACF,KAAK,MAAM,QAAQ,KAAK,aAAa,CAAC,GAAG,gBAAgB,IAAI;CAC/D,SAAS,OAAO;EACd,QAAQ;EACR,MAAM;CACR;CACA,IAAI,eAAe,QAAQ,GAAG,QAAQ,OAAO;CAC7C,OAAO,EAAE,QAAQ;AACnB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"skill-usage-BiVEU0QY.d.ts","names":[],"sources":["../src/run-score.ts","../src/run-critic.ts","../src/semantic-concept-judge.ts","../src/analyst/define.ts","../src/analyst/dspy-rlm-engine.ts","../src/analyst/finding-subject.ts","../src/analyst/findings-store.ts","../src/analyst/kinds/control-integrity.ts","../src/analyst/kinds/failure-mode.ts","../src/analyst/kinds/improvement.ts","../src/analyst/kinds/knowledge-gap.ts","../src/analyst/kinds/knowledge-poisoning.ts","../src/analyst/kinds/index.ts","../src/analyst/kinds/skill-usage.ts"],"mappings":";;;;;;;;;;;;;;UAAiB;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;E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