fascicle 0.16.4 → 0.16.5

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-B6rIIM4J.js","names":["is_record","read_string","read_number","DEFAULT_BASE_URL","consume_sse_response","SUPPORTED","SUPPORTED","to_user_content","to_assistant_message","is_record","SUPPORTED","SUPPORTED","DEFAULT_BASE_URL","SUPPORTED","SUPPORTED","SUPPORTED","SUPPORTED","SUPPORTED","SUPPORTED","node_spawn","sum_usage","assemble_result","is_plain_object"],"sources":["../src/schema/errors.ts","../src/schema/json_schema.ts","../src/engine/pricing.ts","../src/engine/retry.ts","../src/engine/providers/sse_native.ts","../src/engine/providers/anthropic_native.ts","../src/engine/providers/anthropic.ts","../src/engine/providers/openai_compatible_native.ts","../src/engine/providers/openai.ts","../src/engine/providers/google.ts","../src/engine/providers/ollama_native.ts","../src/engine/providers/ollama.ts","../src/engine/providers/lmstudio.ts","../src/engine/providers/openrouter.ts","../src/engine/providers/bedrock.ts","../src/engine/providers/claude_cli/constants.ts","../src/engine/providers/claude_cli/auth.ts","../src/engine/providers/claude_cli/argv.ts","../src/engine/providers/claude_cli/sandbox.ts","../src/engine/providers/claude_cli/spawn.ts","../src/engine/providers/claude_cli/stream_parse.ts","../src/engine/providers/claude_cli/cost.ts","../src/engine/providers/claude_cli/stream_result.ts","../src/engine/schema.ts","../src/engine/trajectory.ts","../src/engine/providers/claude_cli/adapter.ts","../src/engine/providers/registry.ts","../src/engine/merge_defaults.ts","../src/engine/streaming.ts","../src/engine/usage.ts","../src/engine/tool_call_salvage.ts","../src/engine/tool_loop.ts","../src/engine/generate.ts","../src/engine/create_engine.ts"],"sourcesContent":["/**\n * The one error this zone raises.\n *\n * It lives here rather than in core's taxonomy because core imports this zone,\n * and reaching back for an error class would close a cycle.\n */\n\nexport class schema_not_convertible_error extends Error {\n // Part of the published discriminant surface: consumers switch on `kind`\n // outside this repo, so the field has no in-repo production reader.\n // fallow-ignore-next-line unused-class-member\n readonly kind = 'schema_not_convertible_error' as const;\n readonly vendor: string;\n constructor(vendor: string, message?: string) {\n super(\n message ??\n `schema vendor '${vendor}' does not implement Standard JSON Schema, so it cannot be sent to a model as JSON Schema`,\n )\n this.name = 'schema_not_convertible_error'\n this.vendor = vendor\n }\n}\n","/**\n * JSON Schema emission for schemas that reach a model.\n *\n * Standard JSON Schema exposes two directions, `input` and `output`. A tool\n * definition describes what the model should *produce*, so Fascicle emits the\n * input direction: a field with a default is one the model may omit, and\n * saying otherwise asks it to supply a value the schema already supplies.\n *\n * The input direction alone is too loose, though. A vendor describes what it\n * will accept, and accepting unknown keys is the common default (zod's\n * `z.object` strips them, ArkType ignores them), so nothing in the emitted\n * schema stops a model inventing one. `close_objects` supplies that guard,\n * which is also what the strict and constrained-decode modes require. The AI\n * SDK composes the same two halves for every `kind: 'ai_sdk'` provider, so\n * this is what the majority of Fascicle's transports already send.\n */\n\nimport { schema_not_convertible_error } from './errors.js'\nimport { is_record } from './records.js'\nimport type { JsonSchemaOptions, ToolSchema } from './types.js'\n\nconst DEFAULT_TARGET = 'draft-2020-12'\n\n/**\n * Emit JSON Schema for `schema`, targeting draft-2020-12 unless told otherwise.\n *\n * `target` is passed explicitly on every call because the spec makes it a\n * required argument of the converter, even where a vendor tolerates its\n * omission. A vendor that implements Standard Schema but not Standard JSON\n * Schema raises `schema_not_convertible_error` naming itself, so the message\n * says which library to swap rather than just that something failed.\n */\nexport function to_json_schema(\n schema: ToolSchema,\n options: JsonSchemaOptions = {},\n): Record<string, unknown> {\n const props = schema['~standard']\n if (typeof props.jsonSchema?.input !== 'function') {\n throw new schema_not_convertible_error(props.vendor)\n }\n const json = close_objects(props.jsonSchema.input({ target: options.target ?? DEFAULT_TARGET }))\n return options.strip_meta === true ? strip_meta_keys(json) : json\n}\n\n/** Keys whose value is a bag of nested schemas, one per name. */\nconst SCHEMA_BAGS = ['properties', 'patternProperties', '$defs', 'definitions']\n\n/** Keys whose value is a nested schema, or a list of them. */\nconst SCHEMA_SLOTS = [\n 'items',\n 'additionalItems',\n 'additionalProperties',\n 'propertyNames',\n 'not',\n 'anyOf',\n 'allOf',\n 'oneOf',\n 'prefixItems',\n]\n\n/**\n * Add `additionalProperties: false` to every object node that does not already\n * constrain it, so the model is told which keys exist rather than left to\n * invent them.\n *\n * Two restraints keep this from asserting more than the vendor did. An\n * existing `additionalProperties` is never overwritten, so a deliberately open\n * schema (zod's `looseObject`, a `record`'s value schema, a server that\n * published `true`) stays open. And a node is only closed if it declares\n * `properties`: a bare `{ type: 'object' }` is how a freeform payload is\n * described, most visibly by an MCP server, and closing it would forbid every\n * key rather than constrain the listed ones. Every zod object emits\n * `properties`, `z.object({})` included, so the guard costs nothing there.\n *\n * The tree is rebuilt rather than mutated. The spec does not promise a fresh\n * object per call, and a vendor handing back a cached one would be corrupted\n * by an in-place stamp. Recursion terminates on any schema: a self-referential\n * schema emits `$ref`, which is a string, not a nested node.\n */\nfunction close_objects(node: Record<string, unknown>): Record<string, unknown> {\n const closed = close_nested(node)\n return needs_closing(closed) ? { ...closed, additionalProperties: false } : closed\n}\n\n/** Rebuild `node` with every schema it holds closed, leaving its own keys alone. */\nfunction close_nested(node: Record<string, unknown>): Record<string, unknown> {\n const closed: Record<string, unknown> = { ...node }\n for (const key of SCHEMA_BAGS) {\n const bag = closed[key]\n if (is_record(bag)) closed[key] = close_bag(bag)\n }\n for (const key of SCHEMA_SLOTS) {\n if (key in closed) closed[key] = close_value(closed[key])\n }\n return closed\n}\n\n/** Rebuild a name-to-schema bag with each of its schemas closed. */\nfunction close_bag(bag: Record<string, unknown>): Record<string, unknown> {\n const closed: Record<string, unknown> = {}\n for (const [name, value] of Object.entries(bag)) closed[name] = close_value(value)\n return closed\n}\n\n/** Recurse into a schema or a list of them, leaving anything else alone. */\nfunction close_value(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(close_value)\n return is_record(value) ? close_objects(value) : value\n}\n\n/** True for an object node listing its keys but not saying whether more are allowed. */\nfunction needs_closing(node: Record<string, unknown>): boolean {\n if ('additionalProperties' in node || !('properties' in node)) return false\n const type = node['type']\n return type === 'object' || (Array.isArray(type) && type.includes('object'))\n}\n\n/**\n * Drop the top-level `$schema` and `$id` keys.\n *\n * `claude --json-schema` rejects both, and the field constraints alone drive\n * constrained decode, so the CLI adapter asks for a stripped emission.\n */\nfunction strip_meta_keys(json: Record<string, unknown>): Record<string, unknown> {\n const { $schema: _schema, $id: _id, ...rest } = json\n return rest\n}\n","/**\n * Pricing table and cost computation.\n *\n * DEFAULT_PRICING is frozen at module load. Per-engine overrides flow through\n * engine config or register_price; the defaults are never mutated.\n *\n * Cost math formula:\n * input_usd = (input_tokens - cached - cache_write) * input_per_million / 1e6\n * cached_input_usd = cached * (cached_per_million ?? input_per_million) / 1e6\n * cache_write_usd = cache_write * (cache_write_per_million ?? input_per_million) / 1e6\n * reasoning_usd = reasoning * (reasoning_per_million ?? output_per_million) / 1e6\n * output_usd = (output_tokens - reasoning) * output_per_million / 1e6\n *\n * If reasoning_per_million is absent (the common case), reasoning tokens are\n * billed at the output rate and rolled into output_usd rather than surfacing\n * reasoning_usd separately.\n *\n * Fields on CostBreakdown are omitted (not zeroed) when the corresponding\n * usage field was 0 across the whole call. compute_cost is called per turn,\n * so it reports the fields that saw usage in THIS turn. The top-level\n * aggregation stage decides which fields to omit on the aggregated\n * CostBreakdown.\n *\n * A provider that reports its own charge (OpenRouter, the claude_cli) skips\n * the table: decompose_total_cost splits that total across the components by\n * token weight instead.\n */\n\nimport type { CostBreakdown, Pricing, PricingTable, UsageTotals } from './types.js'\n\nexport const FREE_PROVIDERS: ReadonlySet<string> = new Set(['ollama', 'lmstudio'])\n\nexport const CACHE_READ_MULTIPLIER = 0.1\n\nexport const CACHE_WRITE_MULTIPLIER = 1.25\n\nexport const DEFAULT_PRICING: PricingTable = Object.freeze({\n // Anthropic list prices, checked 2026-10-18 against\n // https://platform.claude.com/docs/en/about-claude/pricing. A cache write is\n // the 5-minute write; the 1-hour write costs more and has no field here.\n 'anthropic:claude-fable-5-1': {\n input_per_million: 10.0,\n output_per_million: 50.0,\n cached_input_per_million: 0.25,\n cache_write_per_million: 12.5,\n },\n 'anthropic:claude-fable-5': {\n input_per_million: 10.0,\n output_per_million: 50.0,\n cached_input_per_million: 1.0,\n cache_write_per_million: 12.5,\n },\n 'anthropic:claude-opus-5-5': {\n input_per_million: 4.0,\n output_per_million: 20.0,\n cached_input_per_million: 0.2,\n cache_write_per_million: 5.0,\n },\n 'anthropic:claude-opus-5': {\n input_per_million: 5.0,\n output_per_million: 25.0,\n cached_input_per_million: 0.5,\n cache_write_per_million: 6.25,\n },\n 'anthropic:claude-opus-4-8': {\n input_per_million: 5.0,\n output_per_million: 25.0,\n cached_input_per_million: 0.5,\n cache_write_per_million: 6.25,\n },\n 'anthropic:claude-opus-4-7': {\n input_per_million: 5.0,\n output_per_million: 25.0,\n cached_input_per_million: 0.5,\n cache_write_per_million: 6.25,\n },\n 'anthropic:claude-opus-4-6': {\n input_per_million: 5.0,\n output_per_million: 25.0,\n cached_input_per_million: 0.5,\n cache_write_per_million: 6.25,\n },\n 'anthropic:claude-sonnet-5-5': {\n input_per_million: 2.0,\n output_per_million: 10.0,\n cached_input_per_million: 0.1,\n cache_write_per_million: 2.5,\n },\n 'anthropic:claude-sonnet-5': {\n input_per_million: 2.0,\n output_per_million: 10.0,\n cached_input_per_million: 0.2,\n cache_write_per_million: 2.5,\n },\n 'anthropic:claude-sonnet-4-6': {\n input_per_million: 3.0,\n output_per_million: 15.0,\n cached_input_per_million: 0.3,\n cache_write_per_million: 3.75,\n },\n // The base tier, for a prompt of 100,000 tokens or fewer. A longer prompt\n // pays five times each rate, which this row under-counts.\n 'anthropic:claude-haiku-5-5': {\n input_per_million: 0.1,\n output_per_million: 0.5,\n cached_input_per_million: 0.01,\n cache_write_per_million: 0.125,\n },\n 'anthropic:claude-haiku-4-5': {\n input_per_million: 1.0,\n output_per_million: 5.0,\n cached_input_per_million: 0.1,\n cache_write_per_million: 1.25,\n },\n\n // OpenAI Standard-tier list prices, checked 2026-10-18 against\n // https://developers.openai.com/api/docs/pricing. The gpt-6 rows are the\n // short-context base tier (272K input tokens or fewer); a longer prompt\n // pays more, which these rows under-count.\n 'openai:gpt-6-astra': {\n input_per_million: 10.0,\n output_per_million: 50.0,\n cached_input_per_million: 1.0,\n cache_write_per_million: 12.5,\n },\n 'openai:gpt-6.1-sol': {\n input_per_million: 2.0,\n output_per_million: 10.0,\n cached_input_per_million: 0.1,\n cache_write_per_million: 2.5,\n },\n 'openai:gpt-6-luna': {\n input_per_million: 0.1,\n output_per_million: 0.5,\n cached_input_per_million: 0.01,\n cache_write_per_million: 0.125,\n },\n 'openai:gpt-4o': {\n input_per_million: 2.5,\n output_per_million: 10.0,\n cached_input_per_million: 1.25,\n },\n 'openai:gpt-4o-mini': {\n input_per_million: 0.15,\n output_per_million: 0.6,\n cached_input_per_million: 0.075,\n },\n\n // Gemini paid-tier list prices, checked 2026-10-18 against\n // https://ai.google.dev/gemini-api/docs/pricing (last updated 2026-10-16).\n // A cached token is the context-caching rate; the hourly storage charge has\n // no field here. Text input rates, since audio costs more on some models.\n // Gemini 4 Argon's rates hold through 2026-11-30 and double on 2026-12-01\n // (4.00 / 20.00 / 0.20), and Gemini 3.8 Flash's hold through 2026-12-31 and\n // double on 2027-01-01 (1.50 / 7.50 / 0.15).\n 'google:gemini-4-argon': {\n input_per_million: 2.0,\n output_per_million: 10.0,\n cached_input_per_million: 0.1,\n },\n 'google:gemini-3.8-flash': {\n input_per_million: 0.75,\n output_per_million: 3.75,\n cached_input_per_million: 0.075,\n },\n 'google:gemini-3.5-flash-lite': {\n input_per_million: 0.3,\n output_per_million: 2.5,\n cached_input_per_million: 0.03,\n },\n // The base tier, for a prompt of 200,000 tokens or fewer. A longer prompt\n // pays more, which this row under-counts.\n 'google:gemini-2.5-pro': {\n input_per_million: 1.25,\n output_per_million: 10.0,\n cached_input_per_million: 0.125,\n },\n 'google:gemini-2.5-flash': {\n input_per_million: 0.3,\n output_per_million: 2.5,\n cached_input_per_million: 0.03,\n },\n})\n\n/**\n * Build the `provider:model_id` key used to look up a pricing table entry.\n */\nexport function pricing_key(provider: string, model_id: string): string {\n return `${provider}:${model_id}`\n}\n\n/**\n * Round a dollar amount to 6 decimal places.\n *\n * Per-token rates produce long floating-point tails; 6 places keeps\n * sub-cent precision without leaking binary rounding noise into reports.\n */\nexport function round6(value: number): number {\n return Math.round(value * 1e6) / 1e6\n}\n\n/**\n * The breakdown for a turn whose model has no pricing entry.\n *\n * Free providers (ollama, lmstudio) still report an all-zero, estimated\n * breakdown; a priced provider missing a table entry returns undefined so the\n * caller can surface a `pricing_missing` event instead of a fake zero.\n */\nfunction missing_pricing_breakdown(provider: string): CostBreakdown | undefined {\n if (!FREE_PROVIDERS.has(provider)) return undefined\n return {\n total_usd: 0,\n input_usd: 0,\n output_usd: 0,\n currency: 'USD',\n is_estimate: true,\n }\n}\n\n/**\n * Split reasoning tokens between a surfaced `reasoning_usd` field and the\n * output total.\n *\n * With a dedicated `reasoning_per_million` rate the reasoning cost is surfaced\n * separately and left out of output; without one it rolls into output at the\n * output rate. Absent reasoning tokens leave output untouched and surface\n * nothing.\n */\nfunction apply_reasoning_cost(\n plain_output_usd_raw: number,\n reasoning: number,\n has_reasoning_rate: boolean,\n reasoning_usd_raw: number,\n): { output_usd_raw: number; surface_reasoning_usd: number | undefined } {\n if (reasoning > 0) {\n if (has_reasoning_rate) {\n return { output_usd_raw: plain_output_usd_raw, surface_reasoning_usd: round6(reasoning_usd_raw) }\n }\n return {\n output_usd_raw: plain_output_usd_raw + reasoning_usd_raw,\n surface_reasoning_usd: undefined,\n }\n }\n return { output_usd_raw: plain_output_usd_raw, surface_reasoning_usd: undefined }\n}\n\n/**\n * Compute a CostBreakdown for a single turn's usage.\n *\n * Returns undefined when pricing is absent AND the provider is not free. Free\n * providers (ollama, lmstudio) return an all-zero breakdown even with no\n * pricing entry. Callers are responsible for deduplicating pricing_missing\n * trajectory events across turns within a single generate call.\n *\n * Fields are omitted (not zeroed) when the corresponding usage is 0 for the\n * input call.\n */\nexport function compute_cost(\n usage: UsageTotals,\n pricing: Pricing | undefined,\n provider: string,\n): CostBreakdown | undefined {\n if (pricing === undefined) return missing_pricing_breakdown(provider)\n\n const cached = usage.cached_input_tokens ?? 0\n const cache_write = usage.cache_write_tokens ?? 0\n const reasoning = usage.reasoning_tokens ?? 0\n\n const fresh_input = Math.max(0, usage.input_tokens - cached - cache_write)\n const cached_rate = pricing.cached_input_per_million ?? pricing.input_per_million\n const cache_write_rate = pricing.cache_write_per_million ?? pricing.input_per_million\n const reasoning_rate = pricing.reasoning_per_million ?? pricing.output_per_million\n\n const input_usd_raw = (fresh_input * pricing.input_per_million) / 1e6\n const cached_usd_raw = (cached * cached_rate) / 1e6\n const cache_write_usd_raw = (cache_write * cache_write_rate) / 1e6\n const reasoning_usd_raw = (reasoning * reasoning_rate) / 1e6\n const plain_output_tokens = Math.max(0, usage.output_tokens - reasoning)\n const plain_output_usd_raw = (plain_output_tokens * pricing.output_per_million) / 1e6\n\n const { output_usd_raw, surface_reasoning_usd } = apply_reasoning_cost(\n plain_output_usd_raw,\n reasoning,\n pricing.reasoning_per_million !== undefined,\n reasoning_usd_raw,\n )\n\n const total_raw =\n input_usd_raw +\n cached_usd_raw +\n cache_write_usd_raw +\n (surface_reasoning_usd !== undefined ? reasoning_usd_raw : 0) +\n output_usd_raw\n\n const breakdown: CostBreakdown = {\n total_usd: round6(total_raw),\n input_usd: round6(input_usd_raw),\n output_usd: round6(output_usd_raw),\n currency: 'USD',\n is_estimate: true,\n }\n if (cached > 0) breakdown.cached_input_usd = round6(cached_usd_raw)\n if (cache_write > 0) breakdown.cache_write_usd = round6(cache_write_usd_raw)\n if (surface_reasoning_usd !== undefined) breakdown.reasoning_usd = surface_reasoning_usd\n return breakdown\n}\n\n/**\n * Split a reported total cost into an input/output cost breakdown, weighted\n * by token counts.\n *\n * Cache-read and cache-write tokens are cheaper and pricier respectively\n * than base input tokens, so they're weighted by `CACHE_READ_MULTIPLIER`\n * and `CACHE_WRITE_MULTIPLIER` before the total is distributed\n * proportionally across all weighted components. The total is what the\n * provider charged and the split is estimated, so the breakdown keeps\n * `is_estimate: true`. Returns an all-zero estimate when there's no usage or\n * no cost to distribute.\n */\nexport function decompose_total_cost(\n total_cost_usd: number,\n usage: UsageTotals,\n): CostBreakdown {\n const input = Math.max(0, usage.input_tokens)\n const output = Math.max(0, usage.output_tokens)\n const cached = Math.max(0, usage.cached_input_tokens ?? 0)\n const cache_write = Math.max(0, usage.cache_write_tokens ?? 0)\n\n const base_input = Math.max(0, input - cached - cache_write)\n\n const input_weight = base_input\n const output_weight = output\n const cached_weight = cached * CACHE_READ_MULTIPLIER\n const cache_write_weight = cache_write * CACHE_WRITE_MULTIPLIER\n\n const total_weight = input_weight + output_weight + cached_weight + cache_write_weight\n\n if (total_weight === 0 || total_cost_usd === 0) {\n return {\n total_usd: total_cost_usd,\n input_usd: 0,\n output_usd: 0,\n currency: 'USD',\n is_estimate: true,\n }\n }\n\n const input_usd = (total_cost_usd * input_weight) / total_weight\n const output_usd = (total_cost_usd * output_weight) / total_weight\n const cached_usd_raw = (total_cost_usd * cached_weight) / total_weight\n const cache_write_usd_raw = (total_cost_usd * cache_write_weight) / total_weight\n\n const breakdown: CostBreakdown = {\n total_usd: total_cost_usd,\n input_usd,\n output_usd,\n currency: 'USD',\n is_estimate: true,\n }\n if (cached > 0) breakdown.cached_input_usd = cached_usd_raw\n if (cache_write > 0) breakdown.cache_write_usd = cache_write_usd_raw\n return breakdown\n}\n","/**\n * Retry policy for provider-side failures.\n *\n * Narrow scope: retries 429 rate limits, provider 5xx errors, network\n * errors, and engine turn-timeout expiry (`turn_timeout_ms` throws a typed\n * timeout that the shared classifier treats as retryable). Composition-layer\n * retry wraps the whole generate call; this module retries a single provider\n * call between tool-loop turns.\n *\n * Once a streaming response has delivered a chunk, the caller must not retry\n * it: this helper is never wrapped around a streaming call past its first\n * chunk, and the orchestrator enforces that boundary.\n */\n\nimport type { RetryFailureKind, RetryPolicy } from './types.js'\nimport { aborted_error, provider_error, rate_limit_error } from './errors.js'\nimport { compute_backoff, wait_with_abort } from '#policy'\nimport type { BackoffPolicy } from '#policy'\n\nexport const DEFAULT_RETRY: RetryPolicy = {\n max_attempts: 3,\n initial_delay_ms: 500,\n max_delay_ms: 30_000,\n retry_on: ['rate_limit', 'provider_5xx', 'network', 'timeout'],\n}\n\ntype RetryableError =\n | { kind: 'rate_limit'; retry_after_ms?: number; status?: number; message?: string }\n | { kind: 'provider_5xx'; status?: number; body?: string; message?: string }\n | { kind: 'network'; message?: string }\n | { kind: 'timeout'; message?: string }\n\n/**\n * Parse an HTTP `Retry-After` header value into a millisecond delay.\n *\n * Accepts both forms the header allows: a plain integer or decimal number of\n * seconds, and an HTTP-date. Returns `undefined` for anything else (missing,\n * blank, or unparseable).\n */\nexport function parse_retry_after(value: string | null | undefined): number | undefined {\n if (value === null || value === undefined) return undefined\n const trimmed = value.trim()\n if (trimmed.length === 0) return undefined\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Math.max(0, Math.floor(Number(trimmed) * 1000))\n }\n const parsed = Date.parse(trimmed)\n if (Number.isNaN(parsed)) return undefined\n return Math.max(0, parsed - Date.now())\n}\n\n/**\n * Check whether `policy` allows retrying a failure of the given `kind`.\n */\nfunction is_retryable(kind: RetryFailureKind, policy: RetryPolicy): boolean {\n return policy.retry_on.includes(kind)\n}\n\n/**\n * Map an abort reason onto the error this layer rejects with, always wrapping\n * so an abort can only ever surface as `aborted_error` with the caller's\n * reason attached.\n *\n * The engine's convention, and the opposite of core's propagate-verbatim rule.\n * Two things depend on the wrap. A bare `controller.abort()` sets\n * `signal.reason` to a `DOMException`, which is an `Error` on Node, so\n * propagating would leak a non-Fascicle error out of a boundary documented as\n * throwing `aborted_error`. And the engine's other abort sites (`generate`,\n * `tool_loop`, the adapters) wrap in order to attach `step_index` and\n * `tool_call_in_flight`, which only the construction site knows; propagating\n * would discard them. Wrapping a reason that is already an `aborted_error`\n * nests one inside the other, which is the accepted cost of that contract.\n */\nfunction to_abort_error(reason: unknown): Error {\n return new aborted_error('aborted', { reason })\n}\n\n/**\n * Build the `rate_limit_error` thrown when 429 retries exhaust. Prefers the\n * failing attempt's own `Retry-After`, falling back to the most recent one a\n * prior attempt carried (`last_rate_limit_after`).\n */\nfunction build_rate_limit_error(\n retryable: Extract<RetryableError, { kind: 'rate_limit' }>,\n attempt: number,\n last_rate_limit_after: number | undefined,\n): rate_limit_error {\n const metadata: { attempts: number; retry_after_ms?: number; status?: number } = {\n attempts: attempt,\n }\n if (retryable.retry_after_ms !== undefined) metadata.retry_after_ms = retryable.retry_after_ms\n else if (last_rate_limit_after !== undefined) metadata.retry_after_ms = last_rate_limit_after\n if (retryable.status !== undefined) metadata.status = retryable.status\n return new rate_limit_error(\n retryable.message ?? `rate limited after ${attempt} attempts`,\n metadata,\n )\n}\n\n/**\n * Build the `provider_error` thrown when 5xx/network/timeout retries exhaust.\n * Timeout collapses onto the `network` cause; only 5xx carries status/body.\n */\nfunction build_provider_error(\n retryable: Exclude<RetryableError, { kind: 'rate_limit' }>,\n attempt: number,\n): provider_error {\n const cause_kind = retryable.kind === 'provider_5xx' ? 'provider_5xx' : 'network'\n const metadata: { status?: number; body?: string; cause_kind: typeof cause_kind } = {\n cause_kind,\n }\n if (retryable.kind === 'provider_5xx') {\n if (retryable.status !== undefined) metadata.status = retryable.status\n if (retryable.body !== undefined) metadata.body = retryable.body\n }\n return new provider_error(\n retryable.message ?? `${retryable.kind} after ${attempt} attempts`,\n metadata,\n )\n}\n\n/**\n * Map an exhausted retryable failure onto the error this layer rejects with:\n * `rate_limit_error` for 429s, `provider_error` for everything else.\n */\nfunction build_exhaustion_error(\n retryable: RetryableError,\n attempt: number,\n last_rate_limit_after: number | undefined,\n): Error {\n if (retryable.kind === 'rate_limit') {\n return build_rate_limit_error(retryable, attempt, last_rate_limit_after)\n }\n return build_provider_error(retryable, attempt)\n}\n\n/**\n * Compute the pre-retry backoff for `attempt`. A rate-limit `Retry-After`\n * outranks the local cap (`Math.max`), so a server instruction longer than\n * `max_delay_ms` is honored; the honored value is returned so the caller can\n * carry it onto a later failure that omits its own.\n */\nfunction next_backoff(\n retryable: RetryableError,\n backoff_policy: BackoffPolicy,\n attempt: number,\n): { delay: number; retry_after_ms?: number } {\n const delay = compute_backoff(backoff_policy, attempt - 1)\n if (retryable.kind === 'rate_limit' && retryable.retry_after_ms !== undefined) {\n return { delay: Math.max(delay, retryable.retry_after_ms), retry_after_ms: retryable.retry_after_ms }\n }\n return { delay }\n}\n\n/**\n * One failed-then-retried attempt, as reported through `on_retry`. `attempt`\n * is the 1-based count of failures so far, `delay_ms` the backoff this retry\n * will wait (a rate-limit `Retry-After` already folded in), and `status` /\n * `retry_after_ms` copy what the failure itself carried when it did.\n */\nexport type RetryAttemptInfo = {\n attempt: number\n failure_kind: RetryFailureKind\n delay_ms: number\n status?: number\n retry_after_ms?: number\n}\n\n/**\n * Assemble the `on_retry` payload from the classified failure and the backoff\n * the retry will actually wait.\n */\nfunction build_attempt_info(\n retryable: RetryableError,\n attempt: number,\n delay_ms: number,\n): RetryAttemptInfo {\n const info: RetryAttemptInfo = { attempt, failure_kind: retryable.kind, delay_ms }\n if (retryable.kind === 'rate_limit' || retryable.kind === 'provider_5xx') {\n if (retryable.status !== undefined) info.status = retryable.status\n }\n if (retryable.kind === 'rate_limit' && retryable.retry_after_ms !== undefined) {\n info.retry_after_ms = retryable.retry_after_ms\n }\n return info\n}\n\n/**\n * Retry `fn` under `policy`. `fn` must throw a RetryableError-shaped object to\n * trigger retry; any other thrown value short-circuits as a permanent failure.\n *\n * An aborted `abort` signal interrupts a pending backoff wait and throws\n * `aborted_error`. Returns the value from the last successful `fn()` call. On\n * exhaustion, throws `rate_limit_error` (for 429s) or `provider_error` (for\n * 5xx/network/timeout).\n *\n * `on_retry` fires once per retried failure, just before its backoff wait.\n * It does NOT fire for a first attempt that succeeds, a non-retryable\n * failure, or the final failure that exhausts the policy (those two throw\n * instead), so its call count is exactly the number of extra attempts made.\n */\nexport async function retry_with_policy<t>(\n fn: (attempt: number) => Promise<t>,\n policy: RetryPolicy = DEFAULT_RETRY,\n abort?: AbortSignal,\n on_retry?: (info: RetryAttemptInfo) => void,\n): Promise<t> {\n const backoff_policy: BackoffPolicy = {\n initial_delay_ms: policy.initial_delay_ms,\n max_delay_ms: policy.max_delay_ms,\n jitter: true,\n }\n const signal = abort ?? new AbortController().signal\n let attempt = 0\n let last_rate_limit_after: number | undefined\n while (true) {\n if (abort?.aborted === true) {\n throw to_abort_error(abort.reason)\n }\n try {\n return await fn(attempt)\n } catch (err: unknown) {\n const retryable = classify_retryable(err)\n if (retryable === undefined || !is_retryable(retryable.kind, policy)) throw err\n attempt += 1\n if (attempt >= policy.max_attempts) {\n throw build_exhaustion_error(retryable, attempt, last_rate_limit_after)\n }\n const backoff = next_backoff(retryable, backoff_policy, attempt)\n last_rate_limit_after = backoff.retry_after_ms ?? last_rate_limit_after\n on_retry?.(build_attempt_info(retryable, attempt, backoff.delay))\n await wait_with_abort(backoff.delay, signal, to_abort_error)\n }\n }\n}\n\n/**\n * Read `key` off `err` and return it only if the value is a string.\n */\nfunction read_string(err: object, key: string): string | undefined {\n const value: unknown = Reflect.get(err, key)\n return typeof value === 'string' ? value : undefined\n}\n\n/**\n * Read `key` off `err` and return it only if the value is a number.\n */\nfunction read_number(err: object, key: string): number | undefined {\n const value: unknown = Reflect.get(err, key)\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Assemble the `rate_limit` retryable shape, copying the optional\n * `retry_after_ms`, `status`, and `message` fields when each is present.\n */\nfunction build_retryable_rate_limit(err: object): RetryableError {\n const base: RetryableError = { kind: 'rate_limit' }\n const retry_after = read_number(err, 'retry_after_ms')\n if (retry_after !== undefined) base.retry_after_ms = retry_after\n const status = read_number(err, 'status')\n if (status !== undefined) base.status = status\n const message = read_string(err, 'message')\n if (message !== undefined) base.message = message\n return base\n}\n\n/**\n * Assemble the `provider_5xx` retryable shape, copying the optional `status`,\n * `body`, and `message` fields when each is present.\n */\nfunction build_retryable_5xx(err: object): RetryableError {\n const base: RetryableError = { kind: 'provider_5xx' }\n const status = read_number(err, 'status')\n if (status !== undefined) base.status = status\n const body = read_string(err, 'body')\n if (body !== undefined) base.body = body\n const message = read_string(err, 'message')\n if (message !== undefined) base.message = message\n return base\n}\n\n/**\n * Assemble a `network` or `timeout` retryable shape, copying the optional\n * `message` when present.\n */\nfunction build_retryable_signal(err: object, kind: 'network' | 'timeout'): RetryableError {\n const base: RetryableError = { kind }\n const message = read_string(err, 'message')\n if (message !== undefined) base.message = message\n return base\n}\n\n/**\n * Classify a thrown value into a `RetryableError`, or `undefined` if it\n * does not carry one of the recognized retryable `kind`s.\n *\n * Providers throw plain objects tagged with `kind` (set by\n * `classify_provider_error` in generate.ts); this reads that shape back out\n * field by field rather than trusting it wholesale.\n */\nfunction classify_retryable(err: unknown): RetryableError | undefined {\n if (err === null || typeof err !== 'object') return undefined\n const kind = read_string(err, 'kind')\n if (kind === 'rate_limit') return build_retryable_rate_limit(err)\n if (kind === 'provider_5xx') return build_retryable_5xx(err)\n if (kind === 'network' || kind === 'timeout') return build_retryable_signal(err, kind)\n return undefined\n}\n","/**\n * Incremental SSE decoder shared by the native (raw-HTTP) provider adapters.\n */\nimport { create_line_splitter } from './native_shared.js'\n\n/**\n * Wire-neutral framing only: push() takes decoded text as it arrives off the\n * wire (any chunk boundary, including mid-line) and returns the data payloads\n * of every event completed by that chunk; flush() drains an event left open\n * when the stream ends without a trailing blank line. Only `data:` fields\n * matter to the streams Fascicle consumes (the Messages API repeats the\n * event type inside the JSON payload and the Chat Completions stream sends\n * nothing but data frames), so `event:`/`id:`/`retry:` fields and `:`\n * comments are dropped. Multi-line data joins with '\\n' per the SSE spec.\n */\nexport function create_sse_decoder(): {\n push: (text: string) => string[]\n flush: () => string[]\n} {\n let data_lines: string[] = []\n\n const close_event = (out: string[]): void => {\n if (data_lines.length > 0) {\n out.push(data_lines.join('\\n'))\n data_lines = []\n }\n }\n\n return create_line_splitter(\n (line, out) => {\n if (line.length === 0) {\n close_event(out)\n return\n }\n if (line.startsWith(':')) return\n if (line.startsWith('data:')) {\n const value = line.slice(5)\n data_lines.push(value.startsWith(' ') ? value.slice(1) : value)\n }\n },\n close_event,\n )\n}\n","/**\n * Native Anthropic provider adapter (raw HTTP).\n *\n * Talks to the Messages API directly over global fetch with zero `ai` /\n * `@ai-sdk/*` in its module graph. It owns request/response mapping only:\n * generate.ts wraps invoke_turn in retry + classification + abort, so\n * failures are thrown in shapes the shared classify_provider_error already\n * understands (`status` + `responseHeaders` for HTTP transients,\n * `kind: 'network'` for transport failures) instead of being re-classified\n * or retried here.\n *\n * Selected via `transport: 'native'` on the anthropic provider init. The\n * adapter name stays 'anthropic' so DEFAULT_PRICING keys and UsageTotals\n * fields keep working across transports. Schema requests ride the engine's\n * prompt + parse + repair loop, so `TurnRequest.schema` is intentionally\n * unread. Streaming hand-rolls the SSE parse; the aggregator rebuilds the\n * non-stream payload shape and feeds it through the same\n * parse_messages_response, so streamed and non-streamed results are equal by\n * construction rather than by parallel code paths.\n */\n\nimport { to_json_schema } from '#schema'\nimport type {\n AssistantContentPart,\n EffortLevel,\n FinishReason,\n Message,\n ProviderInit,\n StreamChunk,\n Tool,\n TurnRequest,\n TurnResult,\n UsageTotals,\n UserContentPart,\n} from '../types.js'\nimport {\n engine_config_error,\n provider_capability_error,\n provider_error,\n} from '../errors.js'\nimport { consume_framed_stream, invoke_http_turn } from './native_shared.js'\nimport { create_sse_decoder } from './sse_native.js'\nimport type { NativeProviderAdapter, ProviderCapability } from './types.js'\n\n/**\n * Effort level to the room native adds to its max_tokens default for\n * adaptive thinking. Neither transport sends these as a budget: native\n * sends `output_config.effort`, and the ai_sdk transport hands the level to\n * the SDK's `reasoning` option.\n */\nconst ANTHROPIC_THINKING_BUDGETS: Record<EffortLevel, number> = {\n none: 0,\n low: 1024,\n medium: 5000,\n high: 20000,\n xhigh: 32000,\n max: 64000,\n}\n\nconst ANTHROPIC_VERSION = '2023-06-01'\n\n/**\n * Matches the @ai-sdk/anthropic baseURL convention (origin + /v1) so a\n * base_url configured for the ai_sdk transport keeps pointing at the same\n * place when the transport flips to native.\n */\nconst DEFAULT_BASE_URL = 'https://api.anthropic.com/v1'\n\n/**\n * The Messages API requires max_tokens on every request. Thinking spends\n * from max_tokens, so with effort set the default rides on top of that\n * effort's budget-table value rather than being swallowed by it.\n */\nconst DEFAULT_MAX_TOKENS = 4096\n\ntype AnthropicContentBlock =\n | { type: 'text'; text: string }\n | { type: 'tool_use'; id: string; name: string; input: unknown }\n | { type: 'tool_result'; tool_use_id: string; content: string }\n | { type: 'thinking'; thinking: string; signature: string }\n | { type: 'redacted_thinking'; data: string }\n\ntype ReasoningPart = Extract<AssistantContentPart, { type: 'reasoning' }>\n\nexport type AnthropicMessage = {\n role: 'user' | 'assistant'\n content: AnthropicContentBlock[]\n}\n\n/**\n * Wrap non-blank text in a single text block; blank text maps to no blocks,\n * since the API rejects empty text blocks.\n */\nfunction text_blocks(text: string): AnthropicContentBlock[] {\n return text.trim().length > 0 ? [{ type: 'text', text }] : []\n}\n\n/**\n * Map user message content to Messages-API text blocks, dropping empty text\n * (the API rejects empty blocks). Image parts throw a capability error: they\n * are not mapped on this transport.\n */\nfunction to_user_blocks(content: string | UserContentPart[]): AnthropicContentBlock[] {\n if (typeof content === 'string') return text_blocks(content)\n const blocks: AnthropicContentBlock[] = []\n for (const part of content) {\n if (part.type === 'image') {\n throw new provider_capability_error(\n 'anthropic',\n 'image_input',\n \"image parts are not mapped on the native transport; use transport: 'ai_sdk'\",\n )\n }\n blocks.push(...text_blocks(part.text))\n }\n return blocks\n}\n\n/**\n * Map a reasoning part back to the block it came from: a `signature` under\n * `anthropic` is a thinking block, its text as it was (empty included), and\n * `redactedData` is a redacted_thinking block. A part with neither (keyed for\n * another provider, or carrying no data) maps to no block, since Anthropic\n * refuses thinking it didn't sign.\n */\nfunction reasoning_blocks(part: ReasoningPart): AnthropicContentBlock[] {\n const own = part.provider_options?.['anthropic']\n const signature: unknown = own?.['signature']\n if (typeof signature === 'string') {\n return [{ type: 'thinking', thinking: part.text, signature }]\n }\n const data: unknown = own?.['redactedData']\n return typeof data === 'string' ? [{ type: 'redacted_thinking', data }] : []\n}\n\n/**\n * Map assistant message content to Messages-API blocks in part order: text\n * parts become text blocks (empties dropped), tool-call parts become tool_use\n * blocks, and Anthropic's own reasoning parts become the thinking and\n * redacted_thinking blocks they came from. Order is kept because Anthropic\n * refuses a tool-use turn whose thinking blocks moved.\n */\nfunction to_assistant_blocks(\n content: string | AssistantContentPart[],\n): AnthropicContentBlock[] {\n if (typeof content === 'string') return text_blocks(content)\n const blocks: AnthropicContentBlock[] = []\n for (const part of content) {\n if (part.type === 'text') {\n blocks.push(...text_blocks(part.text))\n } else if (part.type === 'tool_call') {\n blocks.push({ type: 'tool_use', id: part.id, name: part.name, input: part.input })\n } else {\n blocks.push(...reasoning_blocks(part))\n }\n }\n return blocks\n}\n\n/**\n * Map Fascicle Message[] to Messages-API shape: leading system messages hoist\n * to the top-level `system` string, tool messages become `tool_result` blocks\n * on a user turn, and empty text blocks are dropped (the API rejects them).\n * generate.ts already hoists leading system into TurnRequest.system, so the\n * hoist here only fires when the adapter is driven directly.\n */\nexport function to_anthropic_messages(messages: ReadonlyArray<Message>): {\n system: string | undefined\n messages: AnthropicMessage[]\n} {\n const system_parts: string[] = []\n const out: AnthropicMessage[] = []\n\n const push_blocks = (role: 'user' | 'assistant', blocks: AnthropicContentBlock[]): void => {\n if (blocks.length === 0) return\n const last = out[out.length - 1]\n // The Messages API requires alternating roles; consecutive same-role\n // entries (parallel tool results, or a tool result followed by user\n // text) merge into one message.\n if (last?.role === role) {\n last.content.push(...blocks)\n return\n }\n out.push({ role, content: blocks })\n }\n\n for (const message of messages) {\n switch (message.role) {\n case 'system': {\n if (out.length > 0) {\n throw new provider_capability_error(\n 'anthropic',\n 'mid_conversation_system_messages',\n 'the Messages API accepts system text only before the first user/assistant turn',\n )\n }\n system_parts.push(message.content)\n break\n }\n case 'user': {\n push_blocks('user', to_user_blocks(message.content))\n break\n }\n case 'assistant': {\n push_blocks('assistant', to_assistant_blocks(message.content))\n break\n }\n case 'tool': {\n push_blocks('user', [\n { type: 'tool_result', tool_use_id: message.tool_call_id, content: message.content },\n ])\n break\n }\n }\n }\n\n return {\n system: system_parts.length > 0 ? system_parts.join('\\n\\n') : undefined,\n messages: out,\n }\n}\n\n/**\n * Map Fascicle tool definitions to the Messages-API tool shape, converting\n * each input schema to JSON Schema.\n */\nexport function to_anthropic_tools(\n tools: ReadonlyArray<Tool>,\n): Array<{ name: string; description: string; input_schema: unknown }> {\n return tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: to_json_schema(tool.input_schema),\n }))\n}\n\n/**\n * Build the Messages-API request body for one turn: mapped messages and\n * tools, effort as adaptive thinking plus `output_config.effort`, the\n * required max_tokens default, and the `provider_options.anthropic` wire\n * passthrough merged last.\n */\nexport function build_messages_body(req: TurnRequest): Record<string, unknown> {\n const { system: hoisted_system, messages } = to_anthropic_messages(req.messages)\n const system_parts = [req.system, hoisted_system].filter(\n (s): s is string => typeof s === 'string' && s.length > 0,\n )\n\n const body: Record<string, unknown> = {\n model: req.model_id,\n messages,\n // The `none` row is 0, so effort `none` gets the bare default.\n max_tokens: req.max_tokens ?? ANTHROPIC_THINKING_BUDGETS[req.effort] + DEFAULT_MAX_TOKENS,\n }\n if (system_parts.length > 0) body['system'] = system_parts.join('\\n\\n')\n if (req.tools.length > 0) body['tools'] = to_anthropic_tools(req.tools)\n if (req.stream) body['stream'] = true\n if (req.effort === 'none') {\n // The API rejects temperature/top_p alongside thinking, so sampling\n // params apply only with effort `none` (parity with the @ai-sdk/anthropic\n // backend, which strips them the same way).\n if (req.temperature !== undefined) body['temperature'] = req.temperature\n if (req.top_p !== undefined) body['top_p'] = req.top_p\n } else {\n // Every model from Claude 4.6 on takes adaptive thinking, and from 4.7 on\n // refuses the `enabled` budget, so the adapter sends adaptive without\n // reading the model id; an older model's caller passes a budget through\n // provider_options.anthropic.thinking instead. The two effort scales match\n // one for one. The summary is asked for only here, since a `thinking`\n // field with effort `none` would turn thinking on for 4.6 to 4.8.\n body['thinking'] = { type: 'adaptive', display: 'summarized' }\n body['output_config'] = { effort: req.effort }\n }\n // provider_options.anthropic is raw wire-format passthrough (snake_case\n // Messages-API keys, not the ai_sdk transport's camelCase spellings),\n // shallow-merged last so an explicit user key beats every derived field:\n // the thinking and output_config the effort sets, the max_tokens default,\n // sampling params. The adapter does not reconcile interactions the API\n // rejects (for example, a passthrough temperature alongside thinking);\n // wire keys are the user asserting they know the wire.\n const passthrough = req.provider_options?.['anthropic']\n // Stryker disable next-line ConditionalExpression: spreading an undefined\n // passthrough is a no-op, so forcing the merge branch ({ ...body, ...undefined })\n // deep-equals this fast-path return; only the merge branch is observable.\n return passthrough === undefined ? body : { ...body, ...passthrough }\n}\n\n/**\n * Map the Messages-API stop_reason to the engine's FinishReason.\n */\nexport function map_anthropic_stop_reason(raw: unknown): FinishReason {\n switch (raw) {\n case 'tool_use':\n return 'tool_calls'\n case 'max_tokens':\n case 'model_context_window_exceeded':\n return 'length'\n case 'refusal':\n return 'content_filter'\n // end_turn, stop_sequence, pause_turn, and anything unrecognized all\n // mean \"the model stopped on its own\".\n default:\n return 'stop'\n }\n}\n\n/**\n * Map the Messages-API usage object to UsageTotals.\n *\n * The API reports input_tokens EXCLUSIVE of cache reads and writes, while\n * compute_cost subtracts both back out of UsageTotals.input_tokens to price\n * the fresh remainder. So the inclusive total is the sum of all three; a\n * straight copy would silently under-count input cost on cached calls.\n */\nexport function map_anthropic_usage(raw: unknown): UsageTotals {\n if (raw === null || typeof raw !== 'object') {\n return { input_tokens: 0, output_tokens: 0 }\n }\n const read = (key: string): number | undefined => {\n const value: unknown = Reflect.get(raw, key)\n return typeof value === 'number' ? value : undefined\n }\n const cache_read = read('cache_read_input_tokens')\n const cache_write = read('cache_creation_input_tokens')\n const totals: UsageTotals = {\n input_tokens: (read('input_tokens') ?? 0) + (cache_read ?? 0) + (cache_write ?? 0),\n output_tokens: read('output_tokens') ?? 0,\n }\n if (cache_read !== undefined) totals.cached_input_tokens = cache_read\n if (cache_write !== undefined) totals.cache_write_tokens = cache_write\n return totals\n}\n\n/**\n * Read the id and name a tool_use block must carry, throwing a\n * provider_error naming `where` the malformed block appeared.\n */\nfunction read_tool_use_identity(block: object, where: string): { id: string; name: string } {\n const id: unknown = Reflect.get(block, 'id')\n const name: unknown = Reflect.get(block, 'name')\n if (typeof id !== 'string' || typeof name !== 'string') {\n throw new provider_error(`anthropic native: malformed tool_use block in ${where}`)\n }\n return { id, name }\n}\n\ntype ContentAccumulators = {\n text_parts: string[]\n tool_calls: Array<{ id: string; name: string; input: unknown }>\n parts: AssistantContentPart[]\n}\n\n/**\n * Read a thinking or redacted_thinking block as a reasoning part under\n * `@ai-sdk/anthropic`'s own keys, so a transcript moves between the two\n * transports: a thinking block keeps its text (empty when the display was\n * omitted) and its `signature`, and a redacted one keeps its `data` as\n * `redactedData`. A block missing its signature or data becomes a part with\n * no data, which no adapter sends back. Any other block type is undefined.\n */\nfunction read_reasoning_block(block: object, type: unknown): ReasoningPart | undefined {\n if (type === 'thinking') {\n const thinking: unknown = Reflect.get(block, 'thinking')\n const signature: unknown = Reflect.get(block, 'signature')\n return {\n type: 'reasoning',\n text: typeof thinking === 'string' ? thinking : '',\n ...(typeof signature === 'string' ? { provider_options: { anthropic: { signature } } } : {}),\n }\n }\n if (type !== 'redacted_thinking') return undefined\n const data: unknown = Reflect.get(block, 'data')\n return {\n type: 'reasoning',\n text: '',\n ...(typeof data === 'string' ? { provider_options: { anthropic: { redactedData: data } } } : {}),\n }\n}\n\n/**\n * Fold one response `content` block into the accumulators. Text blocks append\n * their string; tool_use blocks contribute a call whose id and name are\n * validated by read_tool_use_identity; thinking and redacted_thinking blocks\n * become reasoning parts. Every kept block also lands in `parts`, in block\n * order, for TurnResult.content.\n */\nfunction push_content_block(block: unknown, acc: ContentAccumulators): void {\n if (block === null || typeof block !== 'object') return\n const type: unknown = Reflect.get(block, 'type')\n if (type === 'text') {\n const text: unknown = Reflect.get(block, 'text')\n if (typeof text === 'string') {\n acc.text_parts.push(text)\n acc.parts.push({ type: 'text', text })\n }\n return\n }\n if (type === 'tool_use') {\n const { id, name } = read_tool_use_identity(block, 'response content')\n const call = { id, name, input: Reflect.get(block, 'input') }\n acc.tool_calls.push(call)\n acc.parts.push({ type: 'tool_call', ...call })\n return\n }\n const reasoning = read_reasoning_block(block, type)\n if (reasoning !== undefined) acc.parts.push(reasoning)\n}\n\n/**\n * Walk a response payload's `content` array into the flat text and tool_call\n * lists a TurnResult carries, plus every block as a part in order. A\n * non-array `content` yields empty lists, matching a payload that carried no\n * content blocks.\n */\nfunction collect_content_blocks(content: unknown): ContentAccumulators {\n const acc: ContentAccumulators = { text_parts: [], tool_calls: [], parts: [] }\n if (Array.isArray(content)) {\n for (const block of content) push_content_block(block, acc)\n }\n return acc\n}\n\n/**\n * Parse a non-stream Messages-API response payload into a TurnResult. The\n * stream aggregator rebuilds this same payload shape and feeds it here too,\n * so both paths share one parser. A turn with a thinking block gets\n * `content`, every block in order, and any other turn stays as it was.\n */\nexport function parse_messages_response(payload: unknown): TurnResult {\n if (payload === null || typeof payload !== 'object') {\n throw new provider_error('anthropic native: response payload is not a JSON object')\n }\n const { text_parts, tool_calls, parts } = collect_content_blocks(Reflect.get(payload, 'content'))\n const result: TurnResult = {\n text: text_parts.join(''),\n tool_calls,\n finish_reason: map_anthropic_stop_reason(Reflect.get(payload, 'stop_reason')),\n usage: map_anthropic_usage(Reflect.get(payload, 'usage')),\n }\n return parts.some((part) => part.type === 'reasoning') ? { ...result, content: parts } : result\n}\n\n/**\n * Mid-stream `error` events reuse the HTTP status classification:\n * overloaded_error is the SSE analog of a 529, api_error of a 500, and\n * rate_limit_error of a 429, so classify_provider_error sees the transients\n * it already retries. Anything else is a permanent provider_error. Whether a\n * retry actually happens stays retry_turn's call: once chunks have streamed\n * it refuses, exactly as on the ai_sdk path.\n */\nfunction stream_event_error(event: object): Error {\n const error: unknown = Reflect.get(event, 'error')\n let error_type = 'unknown'\n let message = '(no message)'\n if (error !== null && typeof error === 'object') {\n const raw_type: unknown = Reflect.get(error, 'type')\n if (typeof raw_type === 'string' && raw_type.length > 0) error_type = raw_type\n const raw_message: unknown = Reflect.get(error, 'message')\n if (typeof raw_message === 'string' && raw_message.length > 0) message = raw_message\n }\n const detail = `anthropic stream error (${error_type}): ${message}`\n let status: number | undefined\n if (error_type === 'overloaded_error') status = 529\n else if (error_type === 'api_error') status = 500\n else if (error_type === 'rate_limit_error') status = 429\n if (status !== undefined) return Object.assign(new Error(detail), { status })\n return new provider_error(detail)\n}\n\n/**\n * Read the `index` field every stream event carries, identifying which\n * content block (text or tool_use) the event applies to.\n */\nfunction read_block_index(event: object): number {\n const index: unknown = Reflect.get(event, 'index')\n if (typeof index !== 'number') {\n throw new provider_error('anthropic native: stream event is missing its block index')\n }\n return index\n}\n\n/**\n * Parse one Messages-stream data line. OpenRouter's Anthropic-compatible\n * endpoint ends every stream with a chat-completions `[DONE]` line after\n * message_stop; it carries no event, so it reads as null, which the\n * aggregator drops like a JSON null. Any other data that isn't JSON is a\n * broken stream.\n */\nfunction parse_stream_event(data: string): unknown {\n if (data === '[DONE]') return null\n try {\n return JSON.parse(data)\n } catch {\n throw new provider_error('anthropic native: stream event is not valid JSON')\n }\n}\n\n/**\n * Consume parsed Messages-stream events, dispatching StreamChunks as they\n * arrive and rebuilding the non-stream response payload as it goes: text\n * deltas accumulate into synthetic text blocks, tool_use input arrives as raw\n * JSON text (input_json_delta) held per open block and parsed at\n * content_block_stop. complete() feeds the synthetic payload through\n * parse_messages_response, which is what makes the streamed TurnResult equal\n * the non-streamed one by construction. A stream that ends without\n * message_stop is truncated output, so complete() fails loud instead of\n * returning a partial turn.\n */\nfunction create_stream_aggregator(\n step_index: number,\n dispatch: (chunk: StreamChunk) => Promise<void>,\n): {\n handle: (data: string) => Promise<void>\n complete: () => TurnResult\n} {\n type SyntheticToolUse = { type: 'tool_use'; id: string; name: string; input: unknown }\n // The signature stays as the start event gave it until a signature_delta\n // replaces it, so a block that never got one parses as the same block\n // without one would in a whole response.\n type SyntheticThinking = { type: 'thinking'; thinking: string; signature: unknown }\n type SyntheticBlock =\n | { type: 'text'; text: string }\n | SyntheticToolUse\n | SyntheticThinking\n | { type: 'redacted_thinking'; data: unknown }\n // Stryker disable next-line ArrayDeclaration: a seeded initial element is dropped by\n // parse_messages_response's block guard, so a non-empty content array is unobservable.\n const content: SyntheticBlock[] = []\n const open_text = new Map<number, { type: 'text'; text: string }>()\n const open_thinking = new Map<number, SyntheticThinking>()\n const open_tools = new Map<number, { block: SyntheticToolUse; json: string }>()\n const usage: Record<string, number> = {}\n let stop_reason: string | undefined\n let stopped = false\n\n // message_delta usage (cumulative output_tokens) overlays message_start\n // usage (input + cache fields); nested non-numeric containers are skipped.\n const merge_usage = (raw: unknown): void => {\n if (raw === null || typeof raw !== 'object') return\n for (const [key, value] of Object.entries(raw)) {\n if (typeof value === 'number') usage[key] = value\n }\n }\n\n // Thinking blocks sit in `content` beside the text and tool_use blocks, in\n // block order, so each one goes back exactly where it came from.\n const start_reasoning_block = (index: number, block: object, type: unknown): void => {\n if (type === 'thinking') {\n const initial: unknown = Reflect.get(block, 'thinking')\n const synthetic: SyntheticThinking = {\n type: 'thinking',\n thinking: typeof initial === 'string' ? initial : '',\n signature: Reflect.get(block, 'signature'),\n }\n content.push(synthetic)\n open_thinking.set(index, synthetic)\n } else if (type === 'redacted_thinking') {\n content.push({ type: 'redacted_thinking', data: Reflect.get(block, 'data') })\n }\n }\n\n const on_block_start = async (event: object): Promise<void> => {\n const index = read_block_index(event)\n const block: unknown = Reflect.get(event, 'content_block')\n if (block === null || typeof block !== 'object') return\n const type: unknown = Reflect.get(block, 'type')\n if (type === 'text') {\n const initial: unknown = Reflect.get(block, 'text')\n const synthetic = {\n type: 'text' as const,\n text: typeof initial === 'string' ? initial : '',\n }\n content.push(synthetic)\n open_text.set(index, synthetic)\n return\n }\n if (type === 'tool_use') {\n const { id, name } = read_tool_use_identity(block, 'stream')\n const synthetic: SyntheticToolUse = {\n type: 'tool_use',\n id,\n name,\n input: Reflect.get(block, 'input') ?? {},\n }\n content.push(synthetic)\n open_tools.set(index, { block: synthetic, json: '' })\n await dispatch({ kind: 'tool_call_start', id, name, step_index })\n return\n }\n start_reasoning_block(index, block, type)\n }\n\n // A thinking delta streams as a reasoning chunk whether or not its block\n // opened, and grows the block when it did; a signature delta replaces the\n // block's signature, as @ai-sdk/anthropic takes the last one it sees.\n const on_thinking_delta = async (index: number, delta: object, type: unknown): Promise<void> => {\n const open = open_thinking.get(index)\n if (type === 'signature_delta') {\n const signature: unknown = Reflect.get(delta, 'signature')\n if (typeof signature === 'string' && open !== undefined) open.signature = signature\n return\n }\n const thinking: unknown = Reflect.get(delta, 'thinking')\n if (typeof thinking !== 'string') return\n if (open !== undefined) open.thinking += thinking\n await dispatch({ kind: 'reasoning', text: thinking, step_index })\n }\n\n const on_block_delta = async (event: object): Promise<void> => {\n const index = read_block_index(event)\n const delta: unknown = Reflect.get(event, 'delta')\n if (delta === null || typeof delta !== 'object') return\n const type: unknown = Reflect.get(delta, 'type')\n if (type === 'text_delta') {\n const text: unknown = Reflect.get(delta, 'text')\n const open = open_text.get(index)\n if (typeof text !== 'string' || open === undefined) return\n open.text += text\n await dispatch({ kind: 'text', text, step_index })\n return\n }\n if (type === 'thinking_delta' || type === 'signature_delta') {\n await on_thinking_delta(index, delta, type)\n return\n }\n if (type === 'input_json_delta') {\n const partial: unknown = Reflect.get(delta, 'partial_json')\n const open = open_tools.get(index)\n if (typeof partial !== 'string' || open === undefined) return\n open.json += partial\n await dispatch({\n kind: 'tool_call_input_delta',\n id: open.block.id,\n delta: partial,\n step_index,\n })\n }\n // Future delta kinds have no engine chunk; dropped.\n }\n\n const on_block_stop = async (event: object): Promise<void> => {\n const index = read_block_index(event)\n const open = open_tools.get(index)\n open_text.delete(index)\n open_thinking.delete(index)\n if (open === undefined) return\n open_tools.delete(index)\n if (open.json.length > 0) {\n try {\n open.block.input = JSON.parse(open.json)\n } catch {\n throw new provider_error(\n `anthropic native: tool_use input for ${open.block.name} is not valid JSON`,\n )\n }\n }\n await dispatch({\n kind: 'tool_call_end',\n id: open.block.id,\n input: open.block.input,\n step_index,\n })\n }\n\n return {\n async handle(data: string): Promise<void> {\n const event = parse_stream_event(data)\n if (event === null || typeof event !== 'object') return\n switch (Reflect.get(event, 'type')) {\n case 'message_start': {\n const message: unknown = Reflect.get(event, 'message')\n if (message !== null && typeof message === 'object') {\n merge_usage(Reflect.get(message, 'usage'))\n }\n break\n }\n case 'content_block_start':\n await on_block_start(event)\n break\n case 'content_block_delta':\n await on_block_delta(event)\n break\n case 'content_block_stop':\n await on_block_stop(event)\n break\n case 'message_delta': {\n const delta: unknown = Reflect.get(event, 'delta')\n if (delta !== null && typeof delta === 'object') {\n const raw: unknown = Reflect.get(delta, 'stop_reason')\n if (typeof raw === 'string') stop_reason = raw\n }\n merge_usage(Reflect.get(event, 'usage'))\n break\n }\n case 'message_stop':\n stopped = true\n await dispatch({\n kind: 'step_finish',\n step_index,\n finish_reason: map_anthropic_stop_reason(stop_reason),\n usage: map_anthropic_usage(usage),\n })\n break\n case 'error':\n throw stream_event_error(event)\n // ping and unrecognized future event types are dropped on purpose.\n default:\n break\n }\n },\n complete(): TurnResult {\n if (!stopped) {\n throw new provider_error(\n 'anthropic native: stream ended before message_stop; the result would be truncated',\n )\n }\n return parse_messages_response({ content, stop_reason, usage })\n },\n }\n}\n\n/**\n * Drain a streaming Messages response through the shared framed-stream\n * consumer: SSE framing feeding the aggregator, which dispatches chunks\n * through req.dispatch_chunk as they arrive.\n */\nasync function consume_sse_response(response: Response, req: TurnRequest): Promise<TurnResult> {\n return consume_framed_stream(response, req, 'anthropic', create_sse_decoder(), (dispatch) =>\n create_stream_aggregator(req.step_index, dispatch),\n )\n}\n\n// 'structured_output' is intentionally absent: schema requests ride the\n// prompt + parse + repair loop instead of constrained decoding. Image parts\n// are unmapped on this transport.\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n 'reasoning',\n])\n\n/**\n * Build the native Anthropic adapter: validates the required api_key,\n * normalizes base_url, and wires invoke_turn to POST /messages directly\n * (streamed or not) through the mappers above.\n */\nexport const create_anthropic_native_adapter = (\n init: ProviderInit,\n): NativeProviderAdapter => {\n const api_key = typeof init.api_key === 'string' ? init.api_key : ''\n if (api_key.length === 0) {\n throw new engine_config_error(\n 'anthropic provider requires a non-empty api_key',\n 'anthropic',\n )\n }\n const base_url = (\n typeof init.base_url === 'string' && init.base_url.length > 0\n ? init.base_url\n : DEFAULT_BASE_URL\n ).replace(/\\/+$/, '')\n\n return {\n kind: 'native',\n name: 'anthropic',\n async invoke_turn(req: TurnRequest): Promise<TurnResult> {\n return invoke_http_turn(\n req,\n 'anthropic',\n {\n url: `${base_url}/messages`,\n headers: {\n 'content-type': 'application/json',\n 'x-api-key': api_key,\n 'anthropic-version': ANTHROPIC_VERSION,\n },\n build_body: () => build_messages_body(req),\n },\n {\n stream: (response) => consume_sse_response(response, req),\n parse: parse_messages_response,\n },\n )\n },\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * Anthropic provider adapter.\n *\n * Dispatches on `transport`: the default 'ai_sdk' backend wraps\n * @ai-sdk/anthropic as an optional peer; 'native' returns the raw-HTTP\n * adapter from anthropic_native.ts. On the AI SDK, effort goes through the\n * SDK's own `reasoning` option, which @ai-sdk/anthropic maps per model:\n * adaptive thinking with `effort` from Claude 4.6 on, a budget before that.\n */\n\nimport type { ProviderInit, UsageTotals } from '../types.js'\nimport {\n default_normalize_usage,\n load_optional_peer,\n resolve_transport,\n translate_effort_to_sdk_reasoning,\n type AiSdkProviderAdapter,\n type ProviderAdapter,\n type ProviderCapability,\n type RawProviderUsage,\n} from './types.js'\nimport { create_anthropic_native_adapter } from './anthropic_native.js'\nimport { engine_config_error } from '../errors.js'\n\ntype AnthropicSdk = {\n createAnthropic: (config: {\n apiKey?: string\n baseURL?: string\n }) => (model_id: string) => unknown\n}\n\n/**\n * Normalize Anthropic usage via the shared default mapper; the AI SDK already\n * reports cache and reasoning tokens in the fields the default reads.\n */\nexport function normalize_anthropic_usage(raw: RawProviderUsage | undefined): UsageTotals {\n return default_normalize_usage(raw)\n}\n\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n 'image_input',\n 'reasoning',\n])\n\n/**\n * Build the Anthropic adapter, dispatching on `init.transport`: 'native' for\n * the raw-HTTP Messages API adapter, otherwise the AI SDK wrapper.\n */\nexport const create_anthropic_adapter = (init: ProviderInit): ProviderAdapter => {\n if (resolve_transport(init, 'anthropic') === 'native') {\n return create_anthropic_native_adapter(init)\n }\n return create_anthropic_ai_sdk_adapter(init)\n}\n\n/**\n * Build the AI SDK-backed Anthropic adapter. Requires a non-empty api_key at\n * construction; @ai-sdk/anthropic itself loads lazily on first build_model so\n * the peer is only required when a model is actually used.\n */\nconst create_anthropic_ai_sdk_adapter = (init: ProviderInit): AiSdkProviderAdapter => {\n const api_key = typeof init.api_key === 'string' ? init.api_key : ''\n if (api_key.length === 0) {\n throw new engine_config_error(\n 'anthropic provider requires a non-empty api_key',\n 'anthropic',\n )\n }\n const base_url = typeof init.base_url === 'string' ? init.base_url : undefined\n\n return {\n kind: 'ai_sdk',\n name: 'anthropic',\n async build_model(model_id: string): Promise<unknown> {\n const sdk = await load_optional_peer<AnthropicSdk>('@ai-sdk/anthropic')\n const config: { apiKey: string; baseURL?: string } = { apiKey: api_key }\n if (base_url !== undefined) config.baseURL = base_url\n const provider = sdk.createAnthropic(config)\n return provider(model_id)\n },\n translate_effort: translate_effort_to_sdk_reasoning,\n normalize_usage: normalize_anthropic_usage,\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * OpenAI-compatible native core: one `chat/completions` implementation\n * talking raw HTTP, shared by every OpenAI-compatible provider.\n *\n * Parameterized by a dialect config: base_url, auth strategy, extra headers,\n * stream-usage behavior, token-limit field name, and usage tolerance. The\n * `openai`, `openrouter`, and `lmstudio` factories each build a dialect and\n * share this core; pointing base_url at any compat server (including\n * Ollama's /v1) rides the same path.\n *\n * This module imports nothing from `ai` or `@ai-sdk/*`. The adapter owns\n * request/response mapping only: generate.ts wraps invoke_turn in retry +\n * classification + abort, so failures are thrown in shapes the shared\n * classify_provider_error already understands (`status` + `responseHeaders`\n * for HTTP transients, `kind: 'network'` for transport failures), never\n * retried here. Schema requests ride the engine's prompt + parse + repair\n * loop, so `TurnRequest.schema` is intentionally unread. Streaming hand-rolls\n * the SSE parse (`data:` lines, the literal `[DONE]` terminator, index-keyed\n * tool_call delta accumulation); the aggregator rebuilds the non-stream\n * payload shape and feeds it through the same parse_chat_completion, so\n * streamed and non-streamed results are equal by construction rather than by\n * parallel code paths.\n */\n\nimport { is_record, to_json_schema } from '#schema'\nimport type {\n AssistantContentPart,\n EffortLevel,\n FinishReason,\n Message,\n StreamChunk,\n Tool,\n TurnRequest,\n TurnResult,\n UsageTotals,\n UserContentPart,\n} from '../types.js'\nimport {\n engine_config_error,\n provider_capability_error,\n provider_error,\n} from '../errors.js'\nimport {\n consume_framed_stream,\n invoke_http_turn,\n map_messages_by_role,\n parse_tool_call_arguments,\n split_assistant_parts,\n} from './native_shared.js'\nimport { create_sse_decoder } from './sse_native.js'\nimport type { NativeProviderAdapter, ProviderCapability } from './types.js'\n\n/**\n * Per-dialect wire knobs. `name` is the provider name the adapter reports\n * and the `provider_options` key it reads, kept stable across transports so\n * pricing keys and usage fields carry over. `tolerant_usage` marks backends\n * whose usage may be absent or approximate (lmstudio, ollama-compat): the\n * mapper returns zeroed totals instead of throwing. `effort_shape` picks the\n * effort field: `'flat'` (the default) is OpenAI's `reasoning_effort`, and\n * `'nested'` is OpenRouter's `reasoning: { effort }`, kept apart from\n * `reasoning`, since a server's reasoning field doesn't decide its effort\n * field. `clamp_effort` marks a server whose flat field takes only `low`,\n * `medium`, and `high` (lmstudio), so `xhigh` and `max` send `high` there.\n * `reasoning: 'reasoning_details'` reads OpenRouter's entries from a\n * response and sends a turn's own back; a dialect without it reads no\n * reasoning at all, and another server's field would be a new value here.\n * `reports_cost` reads the charge the server puts on its usage object as\n * `usage.cost` (OpenRouter's), which the loop records in place of a pricing\n * row.\n */\nexport type OpenAICompatibleDialect = {\n readonly name: string\n readonly base_url: string\n readonly auth: { kind: 'bearer'; api_key: string } | { kind: 'none' }\n readonly extra_headers?: Readonly<Record<string, string>>\n readonly token_limit_field: 'max_tokens' | 'max_completion_tokens'\n readonly stream_include_usage: boolean\n readonly tolerant_usage: boolean\n readonly reports_cost: boolean\n readonly effort_shape?: 'flat' | 'nested'\n readonly clamp_effort?: boolean\n readonly reasoning?: 'reasoning_details'\n}\n\n/**\n * The levels a `clamp_effort` server takes on the flat field: `low | medium |\n * high` only, so `xhigh` and `max` clamp to `high`. OpenAI's own enum takes\n * every level, so the openai dialect skips this table, as the nested shape\n * does. Which levels a model honors is the server's call; the adapter does\n * not model-sniff.\n */\nconst CLAMPED_REASONING_EFFORT: Record<\n Exclude<EffortLevel, 'none'>,\n 'low' | 'medium' | 'high'\n> = {\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'high',\n max: 'high',\n}\n\ntype ChatToolCall = {\n id: string\n type: 'function'\n function: { name: string; arguments: string }\n}\n\nexport type ChatMessage =\n | { role: 'system'; content: string }\n | { role: 'user'; content: string | Array<{ type: 'text'; text: string }> }\n | {\n role: 'assistant'\n content: string | null\n tool_calls?: ChatToolCall[]\n reasoning_details?: Array<Record<string, unknown>>\n }\n | { role: 'tool'; tool_call_id: string; content: string }\n\ntype ReasoningPart = Extract<AssistantContentPart, { type: 'reasoning' }>\n\n/**\n * The field each joinable reasoning_details entry type carries its visible\n * text in. A Map rather than an object literal, since the lookup key is a\n * `type` read off the wire.\n */\nconst REASONING_TEXT_FIELD: ReadonlyMap<unknown, 'text' | 'summary'> = new Map([\n ['reasoning.text', 'text'],\n ['reasoning.summary', 'summary'],\n])\n\n/**\n * Read a reasoning_details entry's visible text: a text entry's `text`, a\n * summary's `summary`, and '' for any other entry or a missing value.\n */\nfunction reasoning_detail_text(entry: Record<string, unknown>): string {\n const field = REASONING_TEXT_FIELD.get(entry['type'])\n // Stryker disable next-line ConditionalExpression: without the guard the read\n // is entry['undefined'], a key no reasoning_details entry carries, so it\n // returns '' all the same.\n const value = field === undefined ? undefined : entry[field]\n return typeof value === 'string' ? value : ''\n}\n\n/**\n * Map user message content to this wire's shape (a string, or an array of\n * text parts). Image parts throw a capability error: they are not mapped on\n * the native transport.\n */\nfunction to_user_content(\n content: string | UserContentPart[],\n provider: string,\n): string | Array<{ type: 'text'; text: string }> {\n if (typeof content === 'string') return content\n const parts: Array<{ type: 'text'; text: string }> = []\n for (const part of content) {\n if (part.type === 'image') {\n throw new provider_capability_error(\n provider,\n 'image_input',\n \"image parts are not mapped on the native transport; use transport: 'ai_sdk'\",\n )\n }\n if (part.text.trim().length > 0) parts.push({ type: 'text', text: part.text })\n }\n return parts.length > 0 ? parts : ''\n}\n\n/**\n * Map assistant message content to Chat Completions shape: text parts join\n * into `content`, tool-call parts become `tool_calls` entries with\n * JSON-stringified arguments, and the provider's own reasoning parts give\n * their entries back as `reasoning_details`.\n */\nfunction to_assistant_message(\n content: string | AssistantContentPart[],\n provider: string,\n): ChatMessage {\n if (typeof content === 'string') return { role: 'assistant', content }\n const { texts, tool_parts, reasoning } = split_assistant_parts(content, provider)\n const tool_calls: ChatToolCall[] = tool_parts.map((part) => ({\n id: part.id,\n type: 'function',\n function: { name: part.name, arguments: JSON.stringify(part.input) },\n }))\n const text = texts.join('')\n // A tool-call turn with no prose sends content: null, the shape the API\n // itself produces; an all-text turn keeps its (possibly empty) string.\n const message: ChatMessage = {\n role: 'assistant',\n content: text.length > 0 || tool_calls.length === 0 ? text : null,\n }\n if (tool_calls.length > 0) message.tool_calls = tool_calls\n // Every entry goes back once, in order, unchanged: OpenRouter checks the\n // whole sequence, and the plain `reasoning` string is never sent, since\n // thinking text without its signature is what Anthropic refuses.\n const reasoning_details = reasoning.flatMap((part) => own_reasoning_detail(part, provider))\n if (reasoning_details.length > 0) message.reasoning_details = reasoning_details\n return message\n}\n\n/**\n * The reasoning_details entry a reasoning part keeps for `provider`, as a\n * one-element list, or an empty one when the part carries no entry (a part\n * another transport keyed for this provider, say).\n */\nfunction own_reasoning_detail(\n part: ReasoningPart,\n provider: string,\n): Array<Record<string, unknown>> {\n // Stryker disable next-line OptionalChaining: split_assistant_parts keeps a\n // reasoning part only when provider_options[provider] is set, so neither link\n // can be nullish here.\n const detail: unknown = part.provider_options?.[provider]?.['detail']\n return is_record(detail) ? [detail] : []\n}\n\n/**\n * Map Fascicle Message[] to Chat Completions shape. Unlike the Messages API\n * there is no top-level system field or role-alternation constraint: system\n * messages map in place at any position, and tool results are first-class\n * `tool` role messages keyed by tool_call_id.\n */\nexport function to_chat_messages(\n messages: ReadonlyArray<Message>,\n provider: string,\n): ChatMessage[] {\n return map_messages_by_role<ChatMessage>(messages, {\n system: (content) => ({ role: 'system', content }),\n user: (content) => ({ role: 'user', content: to_user_content(content, provider) }),\n assistant: (content) => to_assistant_message(content, provider),\n tool: (message) => ({\n role: 'tool',\n tool_call_id: message.tool_call_id,\n content: message.content,\n }),\n })\n}\n\n/**\n * Map Fascicle Tool[] to the Chat Completions function-tool shape,\n * converting each input schema to JSON Schema.\n */\nexport function to_chat_tools(tools: ReadonlyArray<Tool>): Array<{\n type: 'function'\n function: { name: string; description: string; parameters: unknown }\n}> {\n return tools.map((tool) => ({\n type: 'function',\n function: {\n name: tool.name,\n description: tool.description,\n parameters: to_json_schema(tool.input_schema),\n },\n }))\n}\n\n/**\n * Write effort into the body in the dialect's shape. `none` writes nothing,\n * on either shape.\n */\nfunction apply_effort(\n body: Record<string, unknown>,\n effort: EffortLevel,\n dialect: OpenAICompatibleDialect,\n): void {\n if (effort === 'none') return\n if (dialect.effort_shape === 'nested') {\n body['reasoning'] = { effort }\n } else {\n body['reasoning_effort'] =\n dialect.clamp_effort === true ? CLAMPED_REASONING_EFFORT[effort] : effort\n }\n}\n\n/**\n * Build the Chat Completions request body for one turn: mapped messages and\n * tools, the token-limit field named per dialect, sampling params, effort in\n * the dialect's shape, and the dialect's `provider_options.<name>` wire\n * passthrough merged last.\n */\nexport function build_chat_completions_body(\n req: TurnRequest,\n dialect: OpenAICompatibleDialect,\n): Record<string, unknown> {\n const messages: ChatMessage[] = []\n if (req.system !== undefined && req.system.length > 0) {\n messages.push({ role: 'system', content: req.system })\n }\n messages.push(...to_chat_messages(req.messages, dialect.name))\n\n const body: Record<string, unknown> = {\n model: req.model_id,\n messages,\n }\n if (req.tools.length > 0) body['tools'] = to_chat_tools(req.tools)\n if (req.max_tokens !== undefined) body[dialect.token_limit_field] = req.max_tokens\n if (req.temperature !== undefined) body['temperature'] = req.temperature\n if (req.top_p !== undefined) body['top_p'] = req.top_p\n apply_effort(body, req.effort, dialect)\n if (req.stream) {\n body['stream'] = true\n // Usage arrives on the final pre-DONE chunk only when asked for; local\n // backends that ignore the flag fall under tolerant_usage.\n if (dialect.stream_include_usage) body['stream_options'] = { include_usage: true }\n }\n // provider_options.<name> is raw wire-format passthrough (snake_case\n // chat/completions keys), shallow-merged last so an explicit user key beats\n // every derived field: the effort field, the token limit, sampling params. Wire keys are the user asserting they know the\n // wire; the adapter does not reconcile interactions the API rejects.\n const passthrough = req.provider_options?.[dialect.name]\n return passthrough === undefined ? body : { ...body, ...passthrough }\n}\n\n/**\n * Map the Chat Completions finish_reason to the engine's FinishReason.\n */\nexport function map_chat_finish_reason(raw: unknown): FinishReason {\n switch (raw) {\n case 'tool_calls':\n return 'tool_calls'\n case 'length':\n return 'length'\n case 'content_filter':\n return 'content_filter'\n // stop and anything unrecognized both mean \"the model stopped on its own\".\n default:\n return 'stop'\n }\n}\n\n/**\n * Read a numeric field from a usage object, or undefined if absent or not a\n * number.\n */\nfunction read_number(source: object, key: string): number | undefined {\n const value: unknown = Reflect.get(source, key)\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Copy the cache counts in a usage object's prompt_tokens_details onto\n * totals, `cached_tokens` as reads and `cache_write_tokens` as writes,\n * leaving off any count that isn't a number.\n */\nfunction read_prompt_details(raw: object, totals: UsageTotals): void {\n const details: unknown = Reflect.get(raw, 'prompt_tokens_details')\n if (details === null || typeof details !== 'object') return\n const cached = read_number(details, 'cached_tokens')\n if (cached !== undefined) totals.cached_input_tokens = cached\n const cache_write = read_number(details, 'cache_write_tokens')\n if (cache_write !== undefined) totals.cache_write_tokens = cache_write\n}\n\n/**\n * Map the Chat Completions usage object to UsageTotals. prompt_tokens is\n * already INCLUSIVE of cached tokens on this API, unlike Anthropic's\n * exclusive accounting, so a straight copy is correct; compute_cost\n * subtracts the cached portion back out. OpenRouter adds\n * `prompt_tokens_details.cache_write_tokens` for a model with explicit\n * caching, and prompt_tokens counts those too: a live request to\n * anthropic/claude-sonnet-5.5 through Google Vertex on 2026-10-19 reported\n * prompt_tokens 16,358 with 16,299 cache writes, then 16,358 with 16,299\n * cache reads on the same request repeated, and its charge matched pricing\n * that subtracts both from prompt_tokens. A missing usage object throws\n * under a strict dialect (a hosted API omitting usage is a broken response)\n * and zeroes under a tolerant one.\n */\nexport function map_chat_usage(raw: unknown, dialect: OpenAICompatibleDialect): UsageTotals {\n if (raw === null || typeof raw !== 'object') {\n if (dialect.tolerant_usage) return { input_tokens: 0, output_tokens: 0 }\n throw new provider_error(\n `${dialect.name} native: response is missing its usage object`,\n )\n }\n const totals: UsageTotals = {\n input_tokens: read_number(raw, 'prompt_tokens') ?? 0,\n output_tokens: read_number(raw, 'completion_tokens') ?? 0,\n }\n read_prompt_details(raw, totals)\n const completion_details: unknown = Reflect.get(raw, 'completion_tokens_details')\n if (completion_details !== null && typeof completion_details === 'object') {\n const reasoning = read_number(completion_details, 'reasoning_tokens')\n if (reasoning !== undefined) totals.reasoning_tokens = reasoning\n }\n return totals\n}\n\n/**\n * Give a turn the charge a cost-reporting dialect puts on its usage object,\n * and leave every other turn as it was. `usage.cost` is the request's cost in\n * US dollars (OpenRouter's credits are dollars). On a bring-your-own-key\n * request it is only OpenRouter's fee, so the upstream provider's own charge\n * (`cost_details.upstream_inference_cost`) is added, a null one counting as\n * nothing. The raw fields ride `provider_reported` under the dialect's name\n * as sent. A usage object without a numeric `cost` reports nothing, so the\n * loop falls back to pricing.\n */\nfunction with_reported_cost(\n result: TurnResult,\n raw_usage: unknown,\n dialect: OpenAICompatibleDialect,\n): TurnResult {\n if (!dialect.reports_cost || !is_record(raw_usage)) return result\n const cost = raw_usage['cost']\n if (typeof cost !== 'number') return result\n const details = raw_usage['cost_details']\n const upstream = is_record(details) ? details['upstream_inference_cost'] : undefined\n const byok_upstream = raw_usage['is_byok'] === true && typeof upstream === 'number' ? upstream : 0\n const reported: Record<string, unknown> = { cost }\n if (raw_usage['is_byok'] !== undefined) reported['is_byok'] = raw_usage['is_byok']\n if (details !== undefined) reported['cost_details'] = details\n return {\n ...result,\n reported_cost_usd: cost + byok_upstream,\n provider_reported: { [dialect.name]: reported },\n }\n}\n\n/**\n * Parse one Chat Completions tool_calls entry into the engine's tool-call\n * shape, throwing a provider_error if the entry is missing id, function\n * name, or valid JSON arguments.\n */\nfunction parse_tool_call(raw: unknown, provider: string): TurnResult['tool_calls'][number] {\n if (raw === null || typeof raw !== 'object') {\n throw new provider_error(`${provider} native: malformed tool_calls entry in response`)\n }\n const id: unknown = Reflect.get(raw, 'id')\n const fn: unknown = Reflect.get(raw, 'function')\n if (typeof id !== 'string' || fn === null || typeof fn !== 'object') {\n throw new provider_error(`${provider} native: malformed tool_calls entry in response`)\n }\n const name: unknown = Reflect.get(fn, 'name')\n if (typeof name !== 'string') {\n throw new provider_error(`${provider} native: malformed tool_calls entry in response`)\n }\n // arguments is a JSON string on this wire.\n const input = parse_tool_call_arguments(Reflect.get(fn, 'arguments'), provider, name)\n return { id, name, input }\n}\n\n/**\n * The one response parser every path feeds: non-stream parses the payload\n * directly, and the streaming aggregator (create_chat_stream_aggregator)\n * rebuilds this same payload shape from deltas before calling it.\n */\nexport function parse_chat_completion(\n payload: unknown,\n dialect: OpenAICompatibleDialect,\n): TurnResult {\n if (payload === null || typeof payload !== 'object') {\n throw new provider_error(\n `${dialect.name} native: response payload is not a JSON object`,\n )\n }\n const choices: unknown = Reflect.get(payload, 'choices')\n const choice: unknown = Array.isArray(choices) ? choices[0] : undefined\n if (choice === null || choice === undefined || typeof choice !== 'object') {\n throw new provider_error(`${dialect.name} native: response has no choices`)\n }\n const message: unknown = Reflect.get(choice, 'message')\n if (message === null || typeof message !== 'object') {\n throw new provider_error(`${dialect.name} native: response choice has no message`)\n }\n const content: unknown = Reflect.get(message, 'content')\n const raw_tool_calls: unknown = Reflect.get(message, 'tool_calls')\n const tool_calls = Array.isArray(raw_tool_calls)\n ? raw_tool_calls.map((entry) => parse_tool_call(entry, dialect.name))\n : []\n const raw_usage: unknown = Reflect.get(payload, 'usage')\n const result = with_reasoning_content(\n {\n text: typeof content === 'string' ? content : '',\n tool_calls,\n finish_reason: map_chat_finish_reason(Reflect.get(choice, 'finish_reason')),\n usage: map_chat_usage(raw_usage, dialect),\n },\n read_reasoning_parts(message, dialect),\n )\n return with_reported_cost(result, raw_usage, dialect)\n}\n\n/**\n * Read a response message's reasoning_details into reasoning parts, one per\n * entry, in order, each keeping its entry under\n * `provider_options.<name>.detail` for the trip back. Empty unless the\n * dialect reads reasoning_details.\n */\nfunction read_reasoning_parts(message: object, dialect: OpenAICompatibleDialect): ReasoningPart[] {\n if (dialect.reasoning !== 'reasoning_details') return []\n const entries: unknown = Reflect.get(message, 'reasoning_details')\n if (!Array.isArray(entries)) return []\n return entries.filter(is_record).map((detail) => ({\n type: 'reasoning',\n text: reasoning_detail_text(detail),\n provider_options: { [dialect.name]: { detail } },\n }))\n}\n\n/**\n * Give a turn its `content` when it carries reasoning, and leave every other\n * turn exactly as it was. This wire keeps reasoning, text, and tool calls in\n * separate fields, so the parts go in that order.\n */\nfunction with_reasoning_content(result: TurnResult, reasoning: ReasoningPart[]): TurnResult {\n if (reasoning.length === 0) return result\n const content: AssistantContentPart[] = [...reasoning]\n if (result.text.length > 0) content.push({ type: 'text', text: result.text })\n for (const call of result.tool_calls) content.push({ type: 'tool_call', ...call })\n return { ...result, content }\n}\n\n/**\n * The error a compatible server reports after its stream began under HTTP\n * 200: a frame whose top-level `error` holds the server's message and, on\n * OpenRouter, the HTTP status the failure would have had as a numeric\n * `code`. Carrying that code as `status` lets the engine's retry ladder treat\n * it as it treats the same error at the start of a response, so a 429 or a\n * 5xx before any chunk retries, and any error after a chunk fails the turn as\n * a stream interruption that names the message.\n */\nfunction stream_error_frame(error: Record<string, unknown>, provider: string): provider_error {\n const message = error['message']\n const code = error['code']\n const detail = typeof message === 'string' && message.length > 0 ? message : '(no message)'\n const label = code === undefined ? '' : ` (code ${JSON.stringify(code)})`\n return new provider_error(\n `${provider} native: the server reported an error mid-stream${label}: ${detail}`,\n typeof code === 'number' ? { status: code } : {},\n )\n}\n\n/**\n * Join streamed reasoning_details fragments into whole entries, the way\n * OpenRouter's own AI SDK provider does. Consecutive `reasoning.text` or\n * `reasoning.summary` fragments of one type grow one entry until the type\n * changes or a signature closes a text entry, and any other entry (encrypted,\n * a server tool call) stands alone. `index` is ignored, since providers\n * repeat it. A later fragment fills only the fields its entry still lacks, so\n * the late signature lands and the first format stays. add() returns the\n * fragment's visible text, '' when it has none.\n */\nfunction create_reasoning_joiner(): {\n add: (fragment: unknown) => string\n entries: Array<Record<string, unknown>>\n} {\n // Stryker disable next-line ArrayDeclaration: a seeded initial element is not\n // an object, so read_reasoning_parts' is_record filter drops it.\n const entries: Array<Record<string, unknown>> = []\n let open: Record<string, unknown> | undefined\n return {\n entries,\n add(fragment: unknown): string {\n if (!is_record(fragment)) return ''\n const field = REASONING_TEXT_FIELD.get(fragment['type'])\n if (field === undefined) {\n entries.push(fragment)\n open = undefined\n return ''\n }\n const text = reasoning_detail_text(fragment)\n const joinable = open?.['type'] === fragment['type'] ? open : undefined\n let entry: Record<string, unknown>\n if (joinable === undefined) {\n entry = { ...fragment }\n entries.push(entry)\n } else {\n entry = joinable\n const joined = reasoning_detail_text(entry) + text\n for (const [key, value] of Object.entries(fragment)) entry[key] ??= value\n entry[field] = joined\n }\n const signature = entry['signature']\n open = typeof signature === 'string' && signature.length > 0 ? undefined : entry\n return text\n },\n }\n}\n\n/**\n * Consume Chat Completions stream frames (the JSON payload of each SSE\n * `data:` line, plus the literal `[DONE]` terminator), dispatching\n * StreamChunks as they arrive and rebuilding the non-stream payload as it\n * goes: `delta.content` accumulates into the message text,\n * `delta.tool_calls[]` entries accumulate `function.arguments` string deltas\n * keyed by their `index` field, and under a reasoning_details dialect each\n * `delta.reasoning_details` fragment dispatches a reasoning chunk and joins\n * into the message's entries. A tool call closes (parsed input dispatched)\n * when the choice's finish_reason frame arrives, or at `[DONE]` for servers\n * that never send one. A frame with a top-level `error` throws before its\n * choice is read, on any dialect. Usage rides the final pre-DONE frame\n * (stream_options.include_usage), and OpenRouter's reported cost rides\n * inside it, so the streamed turn reads the same charge as the whole\n * response; a stream that ends without `[DONE]` is\n * truncated output, so complete() fails loud instead of returning a partial\n * turn. complete() feeds the synthetic payload through parse_chat_completion,\n * which is what makes the streamed TurnResult equal the non-streamed one by\n * construction.\n */\nexport function create_chat_stream_aggregator(\n dialect: OpenAICompatibleDialect,\n step_index: number,\n dispatch: (chunk: StreamChunk) => Promise<void>,\n): {\n handle_data: (data: string) => Promise<void>\n complete: () => TurnResult\n} {\n type OpenToolCall = {\n index: number\n id: string\n name: string\n arguments: string\n closed: boolean\n }\n let text = ''\n const tool_calls: OpenToolCall[] = []\n const by_index = new Map<number, OpenToolCall>()\n const reasoning = create_reasoning_joiner()\n let finish_reason: string | undefined\n let usage: unknown\n let done = false\n\n const in_index_order = (): OpenToolCall[] =>\n tool_calls.toSorted((a, b) => a.index - b.index)\n\n const close_tool_calls = async (): Promise<void> => {\n for (const call of in_index_order()) {\n if (call.closed) continue\n call.closed = true\n // parse_tool_call applies the same argument rules as the non-stream\n // path ('' means '{}', bad JSON is a provider_error naming the tool).\n const { input } = parse_tool_call(\n { id: call.id, function: { name: call.name, arguments: call.arguments } },\n dialect.name,\n )\n // oxlint-disable-next-line no-await-in-loop\n await dispatch({ kind: 'tool_call_end', id: call.id, input, step_index })\n }\n }\n\n const on_tool_call_delta = async (entry: unknown): Promise<void> => {\n if (entry === null || typeof entry !== 'object') {\n throw new provider_error(\n `${dialect.name} native: malformed tool_calls delta in stream`,\n )\n }\n const index: unknown = Reflect.get(entry, 'index')\n if (typeof index !== 'number') {\n throw new provider_error(\n `${dialect.name} native: stream tool_calls delta is missing its index`,\n )\n }\n const fn: unknown = Reflect.get(entry, 'function')\n let call = by_index.get(index)\n if (call === undefined) {\n const id: unknown = Reflect.get(entry, 'id')\n const name: unknown =\n fn !== null && typeof fn === 'object' ? Reflect.get(fn, 'name') : undefined\n if (typeof id !== 'string' || typeof name !== 'string') {\n throw new provider_error(\n `${dialect.name} native: stream tool_calls delta opened without id and name`,\n )\n }\n call = { index, id, name, arguments: '', closed: false }\n by_index.set(index, call)\n tool_calls.push(call)\n await dispatch({ kind: 'tool_call_start', id, name, step_index })\n }\n if (fn === null || typeof fn !== 'object') return\n const args: unknown = Reflect.get(fn, 'arguments')\n if (typeof args === 'string' && args.length > 0) {\n call.arguments += args\n await dispatch({\n kind: 'tool_call_input_delta',\n id: call.id,\n delta: args,\n step_index,\n })\n }\n }\n\n // Each fragment streams as it arrives, before the frame's text, and keeps\n // being read after the text starts, since a signature arrives late. A bare\n // `reasoning` string with no entries streams but adds none: it has no\n // signature to send back.\n const on_reasoning_delta = async (delta: object): Promise<void> => {\n if (dialect.reasoning !== 'reasoning_details') return\n const fragments: unknown = Reflect.get(delta, 'reasoning_details')\n if (Array.isArray(fragments) && fragments.length > 0) {\n for (const fragment of fragments) {\n const shown = reasoning.add(fragment)\n // oxlint-disable-next-line no-await-in-loop\n if (shown.length > 0) await dispatch({ kind: 'reasoning', text: shown, step_index })\n }\n return\n }\n const bare: unknown = Reflect.get(delta, 'reasoning')\n if (typeof bare === 'string' && bare.length > 0) {\n await dispatch({ kind: 'reasoning', text: bare, step_index })\n }\n }\n\n const on_choice = async (choice: object): Promise<void> => {\n const delta: unknown = Reflect.get(choice, 'delta')\n if (delta !== null && typeof delta === 'object') {\n await on_reasoning_delta(delta)\n const content: unknown = Reflect.get(delta, 'content')\n if (typeof content === 'string' && content.length > 0) {\n text += content\n await dispatch({ kind: 'text', text: content, step_index })\n }\n const raw_calls: unknown = Reflect.get(delta, 'tool_calls')\n if (Array.isArray(raw_calls)) {\n for (const entry of raw_calls) {\n // oxlint-disable-next-line no-await-in-loop\n await on_tool_call_delta(entry)\n }\n }\n }\n const raw_finish: unknown = Reflect.get(choice, 'finish_reason')\n if (typeof raw_finish === 'string') {\n finish_reason = raw_finish\n // The finish frame is the wire's word that every argument delta has\n // arrived, so open tool calls close here, before the usage frame.\n await close_tool_calls()\n }\n }\n\n return {\n async handle_data(data: string): Promise<void> {\n if (data === '[DONE]') {\n if (done) return\n done = true\n // Covers servers that omit the finish_reason frame; a no-op after one.\n await close_tool_calls()\n await dispatch({\n kind: 'step_finish',\n step_index,\n finish_reason: map_chat_finish_reason(finish_reason),\n usage: map_chat_usage(usage, dialect),\n })\n return\n }\n let frame: unknown\n try {\n frame = JSON.parse(data)\n } catch {\n throw new provider_error(`${dialect.name} native: stream frame is not valid JSON`)\n }\n if (frame === null || typeof frame !== 'object') return\n // Read before the choice, which repeats the failure as\n // finish_reason 'error' and would otherwise read as a stop.\n const error: unknown = Reflect.get(frame, 'error')\n if (is_record(error)) throw stream_error_frame(error, dialect.name)\n const raw_usage: unknown = Reflect.get(frame, 'usage')\n if (raw_usage !== null && typeof raw_usage === 'object') usage = raw_usage\n const choices: unknown = Reflect.get(frame, 'choices')\n const choice: unknown = Array.isArray(choices) ? choices[0] : undefined\n if (choice !== null && choice !== undefined && typeof choice === 'object') {\n await on_choice(choice)\n }\n },\n complete(): TurnResult {\n if (!done) {\n throw new provider_error(\n `${dialect.name} native: stream ended before [DONE]; the result would be truncated`,\n )\n }\n const ordered = in_index_order()\n // The joined entries ride the synthetic message exactly as a whole\n // response carries them, an empty list being no entries at all.\n const message: Record<string, unknown> = {\n role: 'assistant',\n content: text.length > 0 || ordered.length === 0 ? text : null,\n reasoning_details: reasoning.entries,\n }\n if (ordered.length > 0) {\n message['tool_calls'] = ordered.map((call) => ({\n id: call.id,\n type: 'function',\n function: { name: call.name, arguments: call.arguments },\n }))\n }\n return parse_chat_completion(\n { choices: [{ index: 0, message, finish_reason: finish_reason ?? null }], usage },\n dialect,\n )\n },\n }\n}\n\n/**\n * Drain a streaming chat/completions response through the shared\n * framed-stream consumer: SSE framing feeding the aggregator, which\n * dispatches chunks through req.dispatch_chunk as they arrive. The\n * aggregator's `handle_data` name is part of its exported API, so it is\n * adapted to the consumer's `handle` shape here rather than renamed.\n */\nasync function consume_sse_response(\n response: Response,\n req: TurnRequest,\n dialect: OpenAICompatibleDialect,\n): Promise<TurnResult> {\n return consume_framed_stream(response, req, dialect.name, create_sse_decoder(), (dispatch) => {\n const aggregator = create_chat_stream_aggregator(dialect, req.step_index, dispatch)\n return { handle: aggregator.handle_data, complete: aggregator.complete }\n })\n}\n\n// 'structured_output' is intentionally absent (schema rides the prompt +\n// parse + repair loop); image parts are unmapped on this transport.\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n 'reasoning',\n])\n\n/**\n * Build a native OpenAI-compatible adapter from a dialect: validates the\n * dialect's api_key when auth is `bearer`, normalizes base_url, and wires\n * invoke_turn to POST /chat/completions directly (streamed or not) through\n * the mappers above.\n */\nexport const create_openai_compatible_adapter = (\n dialect: OpenAICompatibleDialect,\n): NativeProviderAdapter => {\n if (dialect.auth.kind === 'bearer' && dialect.auth.api_key.length === 0) {\n throw new engine_config_error(\n `${dialect.name} provider requires a non-empty api_key`,\n dialect.name,\n )\n }\n const base_url = dialect.base_url.replace(/\\/+$/, '')\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n ...dialect.extra_headers,\n }\n if (dialect.auth.kind === 'bearer') {\n headers['authorization'] = `Bearer ${dialect.auth.api_key}`\n }\n\n return {\n kind: 'native',\n name: dialect.name,\n async invoke_turn(req: TurnRequest): Promise<TurnResult> {\n return invoke_http_turn(\n req,\n dialect.name,\n {\n url: `${base_url}/chat/completions`,\n headers,\n build_body: () => build_chat_completions_body(req, dialect),\n },\n {\n stream: (response) => consume_sse_response(response, req, dialect),\n parse: (payload) => parse_chat_completion(payload, dialect),\n },\n )\n },\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * OpenAI provider adapter.\n *\n * Dispatches on `transport`: the default 'ai_sdk' backend wraps\n * @ai-sdk/openai as an optional peer; 'native' builds the openai dialect of\n * the shared OpenAI-compatible core, with Bearer auth, an\n * OpenAI-Organization header, `max_completion_tokens`, and\n * `reasoning_effort` (clamped to `high`). On the AI SDK, effort goes through\n * the SDK's own `reasoning` option, which @ai-sdk/openai passes on as\n * `reasoningEffort`. Non-reasoning models silently ignore the effort field\n * (providers without reasoning support drop it; signaling is model-specific\n * and handled by the orchestrator via the `effort_ignored` flag).\n */\n\nimport type { ProviderInit, UsageTotals } from '../types.js'\nimport {\n default_normalize_usage,\n load_optional_peer,\n resolve_transport,\n translate_effort_to_sdk_reasoning,\n type AiSdkProviderAdapter,\n type NativeProviderAdapter,\n type ProviderAdapter,\n type ProviderCapability,\n type RawProviderUsage,\n} from './types.js'\nimport { read_dialect_init } from './native_shared.js'\nimport {\n create_openai_compatible_adapter,\n type OpenAICompatibleDialect,\n} from './openai_compatible_native.js'\nimport { engine_config_error } from '../errors.js'\n\ntype OpenaiSdk = {\n createOpenAI: (config: {\n apiKey?: string\n baseURL?: string\n organization?: string\n }) => (model_id: string) => unknown\n}\n\n/**\n * Normalize OpenAI's raw usage payload into UsageTotals.\n */\nexport function normalize_openai_usage(raw: RawProviderUsage | undefined): UsageTotals {\n return default_normalize_usage(raw)\n}\n\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n 'image_input',\n 'reasoning',\n])\n\n/**\n * OpenAI's default API origin, matching the @ai-sdk/openai baseURL convention\n * (origin + /v1) so a base_url configured for the ai_sdk transport keeps\n * pointing at the same place when the transport flips to native.\n */\nconst DEFAULT_BASE_URL = 'https://api.openai.com/v1'\n\n/**\n * Build the OpenAI adapter, picking the native or ai_sdk backend per the\n * resolved `transport`.\n */\nexport const create_openai_adapter = (init: ProviderInit): ProviderAdapter => {\n if (resolve_transport(init, 'openai') === 'native') {\n return create_openai_native_adapter(init)\n }\n return create_openai_ai_sdk_adapter(init)\n}\n\n/**\n * Build the openai dialect and hand it to the shared OpenAI-compatible core:\n * Bearer auth, an optional OpenAI-Organization header, the\n * `max_completion_tokens` token-limit field, and strict usage (a hosted API\n * omitting usage is a broken response, not a local-runtime quirk). The\n * empty-api_key guard rides on the core, which throws the same\n * `openai provider requires a non-empty api_key` engine_config_error.\n */\nconst create_openai_native_adapter = (init: ProviderInit): NativeProviderAdapter => {\n const { api_key, base_url } = read_dialect_init(init, DEFAULT_BASE_URL)\n const organization = typeof init['organization'] === 'string' ? init['organization'] : undefined\n const dialect: OpenAICompatibleDialect = {\n name: 'openai',\n base_url,\n auth: { kind: 'bearer', api_key },\n token_limit_field: 'max_completion_tokens',\n stream_include_usage: true,\n tolerant_usage: false,\n reports_cost: false,\n ...(organization !== undefined\n ? { extra_headers: { 'OpenAI-Organization': organization } }\n : {}),\n }\n return create_openai_compatible_adapter(dialect)\n}\n\n/**\n * Build the OpenAI ai_sdk adapter: validates the required api_key and lazily\n * loads @ai-sdk/openai to build models.\n */\nconst create_openai_ai_sdk_adapter = (init: ProviderInit): AiSdkProviderAdapter => {\n const api_key = typeof init.api_key === 'string' ? init.api_key : ''\n if (api_key.length === 0) {\n throw new engine_config_error(\n 'openai provider requires a non-empty api_key',\n 'openai',\n )\n }\n const base_url = typeof init.base_url === 'string' ? init.base_url : undefined\n const organization = typeof init['organization'] === 'string' ? init['organization'] : undefined\n\n return {\n kind: 'ai_sdk',\n name: 'openai',\n async build_model(model_id: string): Promise<unknown> {\n const sdk = await load_optional_peer<OpenaiSdk>('@ai-sdk/openai')\n const config: { apiKey: string; baseURL?: string; organization?: string } = {\n apiKey: api_key,\n }\n if (base_url !== undefined) config.baseURL = base_url\n if (organization !== undefined) config.organization = organization\n const provider = sdk.createOpenAI(config)\n return provider(model_id)\n },\n translate_effort: translate_effort_to_sdk_reasoning,\n normalize_usage: normalize_openai_usage,\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * Google Gemini provider adapter.\n *\n * Wraps @ai-sdk/google as an optional peer. Effort goes through the AI SDK's\n * own `reasoning` option, which @ai-sdk/google maps per model: `thinkingLevel`\n * on Gemini 3 and a `thinkingBudget` on Gemini 2.5.\n */\n\nimport type { ProviderInit, UsageTotals } from '../types.js'\nimport {\n default_normalize_usage,\n load_optional_peer,\n translate_effort_to_sdk_reasoning,\n type AiSdkProviderAdapter,\n type ProviderCapability,\n type RawProviderUsage,\n} from './types.js'\nimport { engine_config_error } from '../errors.js'\n\ntype GoogleSdk = {\n createGoogleGenerativeAI: (config: {\n apiKey?: string\n baseURL?: string\n }) => (model_id: string) => unknown\n}\n\n/**\n * Normalize Google's raw usage payload into UsageTotals.\n */\nexport function normalize_google_usage(raw: RawProviderUsage | undefined): UsageTotals {\n // Google never reports cache-write tokens, and `default_normalize_usage` only\n // sets that field when the raw payload carries it, so the default is exact.\n return default_normalize_usage(raw)\n}\n\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n 'image_input',\n 'reasoning',\n])\n\n/**\n * Build the Google ai_sdk adapter: validates the required api_key and lazily\n * loads @ai-sdk/google to build models.\n */\nexport const create_google_adapter = (init: ProviderInit): AiSdkProviderAdapter => {\n const api_key = typeof init.api_key === 'string' ? init.api_key : ''\n if (api_key.length === 0) {\n throw new engine_config_error(\n 'google provider requires a non-empty api_key',\n 'google',\n )\n }\n const base_url = typeof init.base_url === 'string' ? init.base_url : undefined\n\n return {\n kind: 'ai_sdk',\n name: 'google',\n async build_model(model_id: string): Promise<unknown> {\n const sdk = await load_optional_peer<GoogleSdk>('@ai-sdk/google')\n const config: { apiKey: string; baseURL?: string } = { apiKey: api_key }\n if (base_url !== undefined) config.baseURL = base_url\n const provider = sdk.createGoogleGenerativeAI(config)\n return provider(model_id)\n },\n translate_effort: translate_effort_to_sdk_reasoning,\n normalize_usage: normalize_google_usage,\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * Ollama native adapter, talking raw HTTP to the daemon's own /api/chat\n * endpoint.\n *\n * Deliberately not the OpenAI-compatible core: the OpenAI-compatible tail is\n * already served by pointing the `openai` provider's base_url at Ollama's\n * /v1, while this endpoint exposes what that compat layer hides: `options`\n * (num_predict, temperature, top_p, and every other runtime knob),\n * `keep_alive`, and `think`, all reachable raw through\n * `provider_options.ollama`. The wire is its own dialect too:\n * newline-delimited JSON frames rather than SSE, tool-call `arguments` as\n * objects rather than JSON strings, no tool-call ids (the adapter\n * synthesizes deterministic ones), and tool results keyed by `tool_name`\n * rather than a call id.\n *\n * This module imports nothing from `ai` or `@ai-sdk/*`. The adapter owns\n * request/response mapping only: generate.ts wraps invoke_turn in retry +\n * classification + abort, so failures are thrown in the shapes the shared\n * classify_provider_error already understands (`status` + `responseHeaders`\n * for HTTP transients, `kind: 'network'` for transport failures), never\n * retried here. Schema requests ride the engine's prompt + parse + repair\n * loop, so `TurnRequest.schema` is intentionally unread; effort is ignored\n * entirely, since thinking is opt-in via `provider_options.ollama.think`.\n * Usage is always tolerant: a local daemon that omits eval counts zeroes the\n * totals instead of throwing. The NDJSON aggregator rebuilds the non-stream\n * payload shape and feeds it through the same parse_ollama_chat, so streamed\n * and non-streamed results are equal by construction.\n */\n\nimport type {\n AssistantContentPart,\n FinishReason,\n Message,\n StreamChunk,\n TurnRequest,\n TurnResult,\n UsageTotals,\n UserContentPart,\n} from '../types.js'\nimport {\n engine_config_error,\n provider_capability_error,\n provider_error,\n} from '../errors.js'\nimport {\n consume_framed_stream,\n create_line_splitter,\n invoke_http_turn,\n map_messages_by_role,\n parse_tool_call_arguments,\n split_assistant_parts,\n} from './native_shared.js'\nimport { to_chat_tools } from './openai_compatible_native.js'\nimport type { NativeProviderAdapter, ProviderCapability } from './types.js'\nimport type { ProviderInit } from '../types.js'\n\ntype OllamaToolCall = {\n function: { name: string; arguments: unknown }\n}\n\nexport type OllamaChatMessage =\n | { role: 'system'; content: string }\n | { role: 'user'; content: string }\n | { role: 'assistant'; content: string; tool_calls?: OllamaToolCall[] }\n | { role: 'tool'; content: string; tool_name: string }\n\n/**\n * Map user message content to a plain string, the shape this wire expects\n * (no part-array support). Image parts throw a capability error: they are\n * not mapped on the native transport.\n */\nfunction to_user_content(content: string | UserContentPart[]): string {\n if (typeof content === 'string') return content\n const parts: string[] = []\n for (const part of content) {\n if (part.type === 'image') {\n throw new provider_capability_error(\n 'ollama',\n 'image_input',\n \"image parts are not mapped on the native transport; use transport: 'ai_sdk'\",\n )\n }\n if (part.text.trim().length > 0) parts.push(part.text)\n }\n // Message content is a plain string on this wire (no part array), so\n // multi-part user content flattens with newlines between parts.\n return parts.join('\\n')\n}\n\n/**\n * Map assistant message content to this wire's message shape: text parts\n * join into `content`, and tool-call parts become `tool_calls` entries with\n * structured (not JSON-string) arguments. Reasoning parts are never sent:\n * this adapter maps no `thinking` field in either direction.\n */\nfunction to_assistant_message(content: string | AssistantContentPart[]): OllamaChatMessage {\n if (typeof content === 'string') return { role: 'assistant', content }\n // Stryker disable next-line StringLiteral: the key only filters the reasoning list, which this wire never reads, so any key is equivalent.\n const { texts, tool_parts } = split_assistant_parts(content, 'ollama')\n const message: OllamaChatMessage = { role: 'assistant', content: texts.join('') }\n if (tool_parts.length > 0) {\n // arguments is a structured object on this wire, not a JSON string, and\n // the API has no id field on tool calls, so the part's id is dropped\n // here and re-synthesized deterministically when a response is parsed.\n message.tool_calls = tool_parts.map((part) => ({\n function: { name: part.name, arguments: part.input },\n }))\n }\n return message\n}\n\n/**\n * Map Fascicle Message[] to the /api/chat shape. System messages map in place\n * (no top-level system field); tool results are `tool` role messages keyed by\n * `tool_name`, since this wire has no tool_call_id to round-trip.\n */\nexport function to_ollama_messages(messages: ReadonlyArray<Message>): OllamaChatMessage[] {\n return map_messages_by_role<OllamaChatMessage>(messages, {\n system: (content) => ({ role: 'system', content }),\n user: (content) => ({ role: 'user', content: to_user_content(content) }),\n assistant: to_assistant_message,\n tool: (message) => ({ role: 'tool', tool_name: message.name, content: message.content }),\n })\n}\n\n/**\n * Build the /api/chat request body for one turn: mapped messages and tools,\n * sampling params under the `options` bag, and the `provider_options.ollama`\n * wire passthrough merged last.\n */\nexport function build_ollama_chat_body(req: TurnRequest): Record<string, unknown> {\n const messages: OllamaChatMessage[] = []\n if (req.system !== undefined && req.system.length > 0) {\n messages.push({ role: 'system', content: req.system })\n }\n messages.push(...to_ollama_messages(req.messages))\n\n const body: Record<string, unknown> = {\n model: req.model_id,\n messages,\n // /api/chat streams by default, so the flag is always explicit: a\n // non-stream call that omits it would get NDJSON back.\n stream: req.stream,\n }\n // Tool definitions use the OpenAI function shape verbatim on this endpoint.\n if (req.tools.length > 0) body['tools'] = to_chat_tools(req.tools)\n // Sampling params live under the runtime's `options` bag, not at the top\n // level. Effort is intentionally unread: there is no reasoning_effort on\n // this wire, and `think` is opt-in via provider_options.ollama.\n const options: Record<string, unknown> = {}\n if (req.max_tokens !== undefined) options['num_predict'] = req.max_tokens\n if (req.temperature !== undefined) options['temperature'] = req.temperature\n if (req.top_p !== undefined) options['top_p'] = req.top_p\n if (Object.keys(options).length > 0) body['options'] = options\n // provider_options.ollama is raw wire-format passthrough (think, keep_alive,\n // format, options, ...), shallow-merged last so an explicit user key beats\n // every derived field. Shallow means a passthrough `options` object\n // replaces the engine-derived one wholesale rather than merging into it.\n const passthrough = req.provider_options?.['ollama']\n return passthrough === undefined ? body : { ...body, ...passthrough }\n}\n\n/**\n * Map the daemon's done_reason, plus whether the turn produced tool calls,\n * to the engine's FinishReason. The presence of tool calls wins, since the\n * wire reports done_reason 'stop' on a tool-call turn too, then `length`;\n * everything else ('stop', 'load', or absent) means the model stopped on its\n * own.\n */\nexport function map_ollama_finish_reason(raw: unknown, has_tool_calls: boolean): FinishReason {\n if (has_tool_calls) return 'tool_calls'\n return raw === 'length' ? 'length' : 'stop'\n}\n\n/**\n * Map the daemon's usage fields to UsageTotals: prompt_eval_count becomes\n * input_tokens, eval_count becomes output_tokens; no cache or reasoning\n * fields exist on this wire. Counts are always tolerant: a local daemon that\n * omits them (or a mid-stream frame, which never carries them) zeroes the\n * totals instead of throwing.\n */\nexport function map_ollama_usage(payload: unknown): UsageTotals {\n if (payload === null || typeof payload !== 'object') {\n return { input_tokens: 0, output_tokens: 0 }\n }\n const prompt: unknown = Reflect.get(payload, 'prompt_eval_count')\n const evaluated: unknown = Reflect.get(payload, 'eval_count')\n return {\n input_tokens: typeof prompt === 'number' ? prompt : 0,\n output_tokens: typeof evaluated === 'number' ? evaluated : 0,\n }\n}\n\nconst REPORTED_DURATION_FIELDS = [\n 'total_duration',\n 'load_duration',\n 'prompt_eval_duration',\n 'eval_duration',\n] as const\n\n/**\n * Collect the daemon's nanosecond duration fields for verbatim passthrough\n * under `provider_reported.ollama`: the daemon's own decode/prefill timing,\n * which is what an honest local tokens-per-second number derives from\n * (eval_count over eval_duration). Units and names stay the wire's own, per\n * the provider_reported contract; returns undefined when none are present\n * (mid-proxy shapes that strip them), never an empty object.\n */\nexport function map_ollama_reported(payload: object): Record<string, number> | undefined {\n const out: Record<string, number> = {}\n for (const key of REPORTED_DURATION_FIELDS) {\n const value: unknown = Reflect.get(payload, key)\n if (typeof value === 'number') out[key] = value\n }\n return Object.keys(out).length > 0 ? out : undefined\n}\n\n/**\n * This wire sends no tool-call id, so one is synthesized from the step index\n * and the call's ordinal within the turn: deterministic, so the streamed and\n * non-streamed parses of the same turn agree, and unique across steps so\n * transcript tool results stay unambiguous. A wire id is preferred if a\n * future daemon version starts sending one.\n */\nfunction parse_ollama_tool_call(\n raw: unknown,\n ordinal: number,\n step_index: number,\n): TurnResult['tool_calls'][number] {\n if (raw === null || typeof raw !== 'object') {\n throw new provider_error('ollama native: malformed tool_calls entry in response')\n }\n const fn: unknown = Reflect.get(raw, 'function')\n if (fn === null || typeof fn !== 'object') {\n throw new provider_error('ollama native: malformed tool_calls entry in response')\n }\n const name: unknown = Reflect.get(fn, 'name')\n if (typeof name !== 'string') {\n throw new provider_error('ollama native: malformed tool_calls entry in response')\n }\n const wire_id: unknown = Reflect.get(raw, 'id')\n const id = typeof wire_id === 'string' && wire_id.length > 0\n ? wire_id\n : `ollama_call_${step_index}_${ordinal}`\n // arguments is a structured object on this wire; a string is tolerated as\n // JSON for compat-shaped proxies ('' meaning '{}', like the OpenAI wire).\n const raw_args: unknown = Reflect.get(fn, 'arguments')\n const input: unknown =\n raw_args !== null && typeof raw_args === 'object'\n ? raw_args\n : parse_tool_call_arguments(raw_args, 'ollama', name)\n return { id, name, input }\n}\n\n/**\n * The one response parser every path feeds: non-stream parses the payload\n * directly, and the NDJSON aggregator rebuilds this same payload shape from\n * its frames before calling it.\n */\nexport function parse_ollama_chat(payload: unknown, step_index: number): TurnResult {\n if (payload === null || typeof payload !== 'object') {\n throw new provider_error('ollama native: response payload is not a JSON object')\n }\n const message: unknown = Reflect.get(payload, 'message')\n if (message === null || message === undefined || typeof message !== 'object') {\n throw new provider_error('ollama native: response has no message')\n }\n const content: unknown = Reflect.get(message, 'content')\n const raw_tool_calls: unknown = Reflect.get(message, 'tool_calls')\n const tool_calls = Array.isArray(raw_tool_calls)\n ? raw_tool_calls.map((entry, ordinal) => parse_ollama_tool_call(entry, ordinal, step_index))\n : []\n const reported = map_ollama_reported(payload)\n return {\n text: typeof content === 'string' ? content : '',\n tool_calls,\n finish_reason: map_ollama_finish_reason(\n Reflect.get(payload, 'done_reason'),\n tool_calls.length > 0,\n ),\n usage: map_ollama_usage(payload),\n ...(reported !== undefined ? { provider_reported: { ollama: reported } } : {}),\n }\n}\n\n/**\n * Incremental NDJSON framing: push() takes decoded text at any chunk\n * boundary (including mid-line) and returns the complete lines it finished\n * (blank lines dropped; JSON parsing is the aggregator's job); flush() drains\n * a final line left open when the stream ends without a trailing newline.\n */\nexport function create_ndjson_decoder(): {\n push: (text: string) => string[]\n flush: () => string[]\n} {\n return create_line_splitter((line, out) => {\n if (line.trim().length > 0) out.push(line)\n })\n}\n\n/**\n * Consume /api/chat NDJSON frames, dispatching StreamChunks as they arrive\n * and rebuilding the non-stream payload as it goes: `message.content`\n * accumulates into the turn text, and `message.tool_calls` entries arrive\n * whole per frame, since arguments are complete objects on this wire, so\n * each call dispatches tool_call_start then tool_call_end with no input\n * deltas between. The `done: true` frame carries done_reason and the eval\n * counts and closes the turn (step_finish); frames after it are ignored. A\n * frame whose top-level `error` is a string is the daemon failing mid-stream\n * and throws with its message. A stream that ends without a done frame is\n * truncated output, so complete() fails loud instead of returning a partial\n * turn. complete() feeds the synthetic payload through parse_ollama_chat,\n * which is what makes the streamed TurnResult equal the non-streamed one by\n * construction.\n */\nfunction create_ollama_stream_aggregator(\n step_index: number,\n dispatch: (chunk: StreamChunk) => Promise<void>,\n): {\n handle: (line: string) => Promise<void>\n complete: () => TurnResult\n} {\n let text = ''\n const tool_calls: Array<TurnResult['tool_calls'][number]> = []\n let done = false\n let done_reason: unknown\n let usage: UsageTotals = { input_tokens: 0, output_tokens: 0 }\n let reported: Record<string, number> | undefined\n\n const on_message = async (message: object): Promise<void> => {\n const content: unknown = Reflect.get(message, 'content')\n if (typeof content === 'string' && content.length > 0) {\n text += content\n await dispatch({ kind: 'text', text: content, step_index })\n }\n const raw_calls: unknown = Reflect.get(message, 'tool_calls')\n if (!Array.isArray(raw_calls)) return\n for (const entry of raw_calls) {\n const call = parse_ollama_tool_call(entry, tool_calls.length, step_index)\n tool_calls.push(call)\n // oxlint-disable-next-line no-await-in-loop\n await dispatch({ kind: 'tool_call_start', id: call.id, name: call.name, step_index })\n // oxlint-disable-next-line no-await-in-loop\n await dispatch({ kind: 'tool_call_end', id: call.id, input: call.input, step_index })\n }\n }\n\n return {\n async handle(line: string): Promise<void> {\n if (done) return\n let frame: unknown\n try {\n frame = JSON.parse(line)\n } catch {\n throw new provider_error('ollama native: stream frame is not valid JSON')\n }\n if (frame === null || typeof frame !== 'object') return\n const error: unknown = Reflect.get(frame, 'error')\n if (typeof error === 'string') {\n throw new provider_error(`ollama native: the daemon reported an error mid-stream: ${error}`)\n }\n const message: unknown = Reflect.get(frame, 'message')\n if (message !== null && message !== undefined && typeof message === 'object') {\n await on_message(message)\n }\n if (Reflect.get(frame, 'done') === true) {\n done = true\n done_reason = Reflect.get(frame, 'done_reason')\n usage = map_ollama_usage(frame)\n reported = map_ollama_reported(frame)\n await dispatch({\n kind: 'step_finish',\n step_index,\n finish_reason: map_ollama_finish_reason(done_reason, tool_calls.length > 0),\n usage,\n })\n }\n },\n complete(): TurnResult {\n if (!done) {\n throw new provider_error(\n 'ollama native: stream ended before its done frame; the result would be truncated',\n )\n }\n const message: Record<string, unknown> = { role: 'assistant', content: text }\n if (tool_calls.length > 0) {\n // Rebuilt entries carry the synthesized ids, which the parser prefers\n // over re-synthesizing, so streamed ids match the dispatched chunks.\n message['tool_calls'] = tool_calls.map((call) => ({\n id: call.id,\n function: { name: call.name, arguments: call.input },\n }))\n }\n // The done frame's duration fields rebuild into the synthetic payload\n // so the streamed parse reports them exactly as the non-streamed one.\n return parse_ollama_chat(\n {\n message,\n done: true,\n done_reason: done_reason ?? null,\n prompt_eval_count: usage.input_tokens,\n eval_count: usage.output_tokens,\n ...reported,\n },\n step_index,\n )\n },\n }\n}\n\n/**\n * Drain a streaming /api/chat response through the shared framed-stream\n * consumer: NDJSON framing feeding the aggregator, which dispatches chunks\n * through req.dispatch_chunk as they arrive.\n */\nasync function consume_ndjson_response(response: Response, req: TurnRequest): Promise<TurnResult> {\n return consume_framed_stream(response, req, 'ollama', create_ndjson_decoder(), (dispatch) =>\n create_ollama_stream_aggregator(req.step_index, dispatch),\n )\n}\n\n// 'structured_output' is intentionally absent: schema rides the prompt +\n// parse + repair loop, parity with native Anthropic, though the daemon's\n// `format` field stays reachable via provider_options.ollama.format.\n// 'reasoning' is absent because effort is ignored on this wire; image parts\n// are unmapped on this transport.\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n])\n\n/**\n * Build the native Ollama adapter: validates the required base_url and wires\n * invoke_turn to POST /api/chat directly (streamed or not) through the\n * mappers above.\n */\nexport const create_ollama_native_adapter = (init: ProviderInit): NativeProviderAdapter => {\n const raw_base_url = typeof init.base_url === 'string' ? init.base_url : ''\n if (raw_base_url.length === 0) {\n throw new engine_config_error('ollama provider requires a non-empty base_url', 'ollama')\n }\n // base_url is the daemon root (http://localhost:11434), the same value the\n // ai_sdk transport takes, so flipping transports never means re-pointing it.\n const base_url = raw_base_url.replace(/\\/+$/, '')\n\n return {\n kind: 'native',\n name: 'ollama',\n async invoke_turn(req: TurnRequest): Promise<TurnResult> {\n return invoke_http_turn(\n req,\n 'ollama',\n {\n url: `${base_url}/api/chat`,\n headers: { 'content-type': 'application/json' },\n build_body: () => build_ollama_chat_body(req),\n },\n {\n stream: (response) => consume_ndjson_response(response, req),\n parse: (payload) => parse_ollama_chat(payload, req.step_index),\n },\n )\n },\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * Ollama local-provider adapter.\n *\n * Dispatches on `transport`: the default 'ai_sdk' backend wraps\n * ai-sdk-ollama as an optional peer; 'native' talks to the daemon's own\n * /api/chat endpoint over its NDJSON wire. The OpenAI-compatible tail is\n * served instead by pointing the `openai` provider's base_url at Ollama's\n * /v1. No API key; base_url is the daemon root and is required on both\n * transports. Ollama does not support reasoning effort: the ai_sdk branch\n * drops the field and records `effort_ignored`; the native branch ignores it\n * entirely (thinking is opt-in via provider_options.ollama.think). Ollama\n * does not emit the image_input capability.\n */\n\nimport type { EffortLevel, ProviderInit } from '../types.js'\nimport {\n load_optional_peer,\n normalize_local_usage,\n resolve_transport,\n type AiSdkProviderAdapter,\n type EffortTranslation,\n type ProviderAdapter,\n type ProviderCapability,\n} from './types.js'\nimport { create_ollama_native_adapter } from './ollama_native.js'\nimport { engine_config_error } from '../errors.js'\n\ntype OllamaSdk = {\n createOllama: (config: { baseURL?: string }) => (model_id: string) => unknown\n}\n\n/**\n * Ollama has no reasoning-effort control on this transport, so every\n * non-`none` level is reported as ignored and no provider option is emitted.\n */\nexport function translate_ollama_effort(effort: EffortLevel): EffortTranslation {\n const ignored = effort !== 'none'\n return { provider_options: {}, effort_ignored: ignored }\n}\n\n/**\n * Normalize Ollama's raw usage payload into UsageTotals: the shared\n * local-backend mapper, since Ollama never reports cache or reasoning\n * tokens.\n */\nexport const normalize_ollama_usage = normalize_local_usage\n\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n // Ollama supports native constrained decoding via its `format` field, which\n // ai-sdk-ollama maps from the AI SDK responseFormat. The text-extraction\n // path is unreliable for local models, so prefer the constrained decode.\n 'structured_output',\n])\n\n/**\n * Build the Ollama adapter, picking the native or ai_sdk backend per the\n * resolved `transport`.\n */\nexport const create_ollama_adapter = (init: ProviderInit): ProviderAdapter => {\n if (resolve_transport(init, 'ollama') === 'native') {\n return create_ollama_native_adapter(init)\n }\n return create_ollama_ai_sdk_adapter(init)\n}\n\n/**\n * Build the Ollama ai_sdk adapter: validates the required base_url and\n * lazily loads ai-sdk-ollama to build models.\n */\nconst create_ollama_ai_sdk_adapter = (init: ProviderInit): AiSdkProviderAdapter => {\n const base_url = typeof init.base_url === 'string' ? init.base_url : ''\n if (base_url.length === 0) {\n throw new engine_config_error(\n 'ollama provider requires a non-empty base_url',\n 'ollama',\n )\n }\n\n return {\n kind: 'ai_sdk',\n name: 'ollama',\n async build_model(model_id: string): Promise<unknown> {\n const sdk = await load_optional_peer<OllamaSdk>('ai-sdk-ollama')\n const provider = sdk.createOllama({ baseURL: base_url })\n return provider(model_id)\n },\n translate_effort: translate_ollama_effort,\n normalize_usage: normalize_ollama_usage,\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * LM Studio provider adapter.\n *\n * Dispatches on `transport`: the default 'ai_sdk' backend wraps\n * @ai-sdk/openai-compatible as an optional peer; 'native' builds the lmstudio\n * dialect of the shared OpenAI-compatible core, with no auth, `max_tokens` as\n * the token-limit field, and tolerant usage, since a local server that omits\n * or approximates token counts is a fact of local-first running, not a broken\n * response. LM Studio exposes an OpenAI-compatible local server; base_url is\n * required on both transports. Reasoning effort differs by transport: the\n * ai_sdk branch drops it and records `effort_ignored`, while the native\n * branch sends it as the flat `reasoning_effort` field through the shared\n * core and leaves the server to honor or ignore it.\n */\n\nimport type { EffortLevel, ProviderInit } from '../types.js'\nimport {\n load_optional_peer,\n normalize_local_usage,\n resolve_transport,\n type AiSdkProviderAdapter,\n type EffortTranslation,\n type NativeProviderAdapter,\n type ProviderAdapter,\n type ProviderCapability,\n} from './types.js'\nimport {\n create_openai_compatible_adapter,\n type OpenAICompatibleDialect,\n} from './openai_compatible_native.js'\nimport { engine_config_error } from '../errors.js'\n\ntype OpenaiCompatibleSdk = {\n createOpenAICompatible: (config: {\n name: string\n baseURL: string\n apiKey?: string\n includeUsage?: boolean\n }) => (model_id: string) => unknown\n}\n\n/**\n * LM Studio has no reasoning-effort control, so every non-`none` level is\n * reported as ignored and no provider option is emitted.\n */\nexport function translate_lmstudio_effort(effort: EffortLevel): EffortTranslation {\n const ignored = effort !== 'none'\n return { provider_options: {}, effort_ignored: ignored }\n}\n\n/**\n * Normalize LM Studio's raw usage payload into UsageTotals: the shared\n * local-backend mapper, since LM Studio never reports cache or reasoning\n * tokens.\n */\nexport const normalize_lmstudio_usage = normalize_local_usage\n\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n // LM Studio's OpenAI-compatible server supports native constrained decoding\n // via a json_schema response format, surfaced through the AI SDK\n // responseFormat. Prefer it over the unreliable text-extraction path.\n 'structured_output',\n])\n\n/**\n * Build the LM Studio adapter, picking the native or ai_sdk backend per the\n * resolved `transport`.\n */\nexport const create_lmstudio_adapter = (init: ProviderInit): ProviderAdapter => {\n if (resolve_transport(init, 'lmstudio') === 'native') {\n return create_lmstudio_native_adapter(init)\n }\n return create_lmstudio_ai_sdk_adapter(init)\n}\n\n/**\n * Build the lmstudio dialect and hand it to the shared OpenAI-compatible\n * core: no auth, the `max_tokens` token-limit field, and tolerant usage. The\n * base_url guard mirrors the ai_sdk branch; the core has no api_key to check\n * under `auth: { kind: 'none' }`.\n */\nconst create_lmstudio_native_adapter = (init: ProviderInit): NativeProviderAdapter => {\n const base_url = typeof init.base_url === 'string' ? init.base_url : ''\n if (base_url.length === 0) {\n throw new engine_config_error(\n 'lmstudio provider requires a non-empty base_url',\n 'lmstudio',\n )\n }\n const dialect: OpenAICompatibleDialect = {\n name: 'lmstudio',\n base_url,\n auth: { kind: 'none' },\n token_limit_field: 'max_tokens',\n stream_include_usage: true,\n tolerant_usage: true,\n reports_cost: false,\n clamp_effort: true,\n }\n return create_openai_compatible_adapter(dialect)\n}\n\n/**\n * Build the LM Studio ai_sdk adapter: validates the required base_url and\n * lazily loads @ai-sdk/openai-compatible to build models.\n */\nconst create_lmstudio_ai_sdk_adapter = (init: ProviderInit): AiSdkProviderAdapter => {\n const base_url = typeof init.base_url === 'string' ? init.base_url : ''\n if (base_url.length === 0) {\n throw new engine_config_error(\n 'lmstudio provider requires a non-empty base_url',\n 'lmstudio',\n )\n }\n\n return {\n kind: 'ai_sdk',\n name: 'lmstudio',\n async build_model(model_id: string): Promise<unknown> {\n const sdk = await load_optional_peer<OpenaiCompatibleSdk>('@ai-sdk/openai-compatible')\n // Without includeUsage the OpenAI streaming protocol omits usage from\n // SSE responses entirely (stream_options.include_usage), so streamed\n // calls would report zero tokens on spec-strict servers.\n const provider = sdk.createOpenAICompatible({\n name: 'lmstudio',\n baseURL: base_url,\n includeUsage: true,\n })\n return provider(model_id)\n },\n translate_effort: translate_lmstudio_effort,\n normalize_usage: normalize_lmstudio_usage,\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * OpenRouter provider adapter.\n *\n * Dispatches on `transport`: the default 'ai_sdk' backend wraps\n * @openrouter/ai-sdk-provider as an optional peer; 'native' builds the\n * openrouter dialect of the shared OpenAI-compatible core, with Bearer auth\n * plus the optional `HTTP-Referer`/`X-Title` attribution headers,\n * `max_tokens` as the token-limit field, and strict usage (a hosted\n * aggregator omitting usage is a broken response, not a local-runtime\n * quirk).\n *\n * Reasoning effort support varies per upstream model; OpenRouter itself\n * forwards the `reasoning` provider option. Both backends send effort as\n * OpenRouter's `reasoning: { effort }`, every level passed through, since\n * that's the form OpenRouter's guide documents and it takes `max`, which one\n * reference page leaves out of the flat field. Effort_ignored is false so\n * that the orchestrator does not emit effort_ignored indiscriminately;\n * upstream models that don't support reasoning drop the field themselves.\n */\n\nimport type { EffortLevel, ProviderInit, UsageTotals } from '../types.js'\nimport {\n default_normalize_usage,\n load_optional_peer,\n resolve_transport,\n type AiSdkProviderAdapter,\n type EffortTranslation,\n type NativeProviderAdapter,\n type ProviderAdapter,\n type ProviderCapability,\n type RawProviderUsage,\n} from './types.js'\nimport { read_dialect_init } from './native_shared.js'\nimport {\n create_openai_compatible_adapter,\n type OpenAICompatibleDialect,\n} from './openai_compatible_native.js'\nimport { engine_config_error } from '../errors.js'\n\ntype OpenrouterSdk = {\n createOpenRouter: (config: {\n apiKey?: string\n baseURL?: string\n extraBody?: Record<string, unknown>\n headers?: Record<string, string>\n }) => (model_id: string) => unknown\n}\n\n/**\n * Map an EffortLevel to OpenRouter's `reasoning.effort` provider option.\n *\n * OpenRouter forwards the effort string verbatim to the upstream model.\n * `low`/`medium`/`high` work everywhere; `xhigh`/`max` flow through but only\n * the upstream model decides what they mean. Models that don't recognize\n * the value drop it silently.\n */\nexport function translate_openrouter_effort(effort: EffortLevel): EffortTranslation {\n if (effort === 'none') return { provider_options: {}, effort_ignored: false }\n return {\n provider_options: {\n openrouter: { reasoning: { effort } },\n },\n effort_ignored: false,\n }\n}\n\n/**\n * Normalize OpenRouter's raw usage payload into UsageTotals.\n */\nexport function normalize_openrouter_usage(raw: RawProviderUsage | undefined): UsageTotals {\n return default_normalize_usage(raw)\n}\n\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n 'image_input',\n 'reasoning',\n])\n\n/**\n * OpenRouter's default API origin, matching the @openrouter/ai-sdk-provider\n * baseURL convention so a base_url configured for the ai_sdk transport keeps\n * pointing at the same place when the transport flips to native.\n */\nconst DEFAULT_BASE_URL = 'https://openrouter.ai/api/v1'\n\n/**\n * Build the OpenRouter adapter, picking the native or ai_sdk backend per the\n * resolved `transport`.\n */\nexport const create_openrouter_adapter = (init: ProviderInit): ProviderAdapter => {\n if (resolve_transport(init, 'openrouter') === 'native') {\n return create_openrouter_native_adapter(init)\n }\n return create_openrouter_ai_sdk_adapter(init)\n}\n\n/**\n * Build the openrouter dialect and hand it to the shared OpenAI-compatible\n * core: Bearer auth, the optional `HTTP-Referer`/`X-Title` attribution\n * headers, the `max_tokens` token-limit field, the nested effort shape,\n * reasoning read from and sent back as `reasoning_details`, strict usage,\n * and the cost OpenRouter reports on every response. The empty-api_key guard\n * rides on the core, which throws the same\n * `openrouter provider requires a non-empty api_key` engine_config_error.\n */\nconst create_openrouter_native_adapter = (init: ProviderInit): NativeProviderAdapter => {\n const { api_key, base_url } = read_dialect_init(init, DEFAULT_BASE_URL)\n const http_referer = typeof init['http_referer'] === 'string' ? init['http_referer'] : undefined\n const x_title = typeof init['x_title'] === 'string' ? init['x_title'] : undefined\n const extra_headers: Record<string, string> = {}\n if (http_referer !== undefined) extra_headers['HTTP-Referer'] = http_referer\n if (x_title !== undefined) extra_headers['X-Title'] = x_title\n const dialect: OpenAICompatibleDialect = {\n name: 'openrouter',\n base_url,\n auth: { kind: 'bearer', api_key },\n token_limit_field: 'max_tokens',\n stream_include_usage: true,\n tolerant_usage: false,\n reports_cost: true,\n effort_shape: 'nested',\n reasoning: 'reasoning_details',\n // Stryker disable next-line ConditionalExpression,EqualityOperator: the core\n // spreads extra_headers into its own headers, so an empty object and no key\n // send the same request.\n ...(Object.keys(extra_headers).length > 0 ? { extra_headers } : {}),\n }\n return create_openai_compatible_adapter(dialect)\n}\n\n/**\n * Build the OpenRouter ai_sdk adapter: validates the required api_key and\n * lazily loads @openrouter/ai-sdk-provider to build models.\n */\nconst create_openrouter_ai_sdk_adapter = (init: ProviderInit): AiSdkProviderAdapter => {\n const api_key = typeof init.api_key === 'string' ? init.api_key : ''\n if (api_key.length === 0) {\n throw new engine_config_error(\n 'openrouter provider requires a non-empty api_key',\n 'openrouter',\n )\n }\n const base_url = typeof init.base_url === 'string' ? init.base_url : undefined\n const http_referer = typeof init['http_referer'] === 'string' ? init['http_referer'] : undefined\n const x_title = typeof init['x_title'] === 'string' ? init['x_title'] : undefined\n\n return {\n kind: 'ai_sdk',\n name: 'openrouter',\n async build_model(model_id: string): Promise<unknown> {\n const sdk = await load_optional_peer<OpenrouterSdk>('@openrouter/ai-sdk-provider')\n const headers: Record<string, string> = {}\n if (http_referer !== undefined) headers['HTTP-Referer'] = http_referer\n if (x_title !== undefined) headers['X-Title'] = x_title\n const config: {\n apiKey: string\n baseURL?: string\n headers?: Record<string, string>\n } = { apiKey: api_key }\n if (base_url !== undefined) config.baseURL = base_url\n if (Object.keys(headers).length > 0) config.headers = headers\n const provider = sdk.createOpenRouter(config)\n return provider(model_id)\n },\n translate_effort: translate_openrouter_effort,\n normalize_usage: normalize_openrouter_usage,\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * AWS Bedrock provider adapter.\n *\n * Wraps @ai-sdk/amazon-bedrock as an optional peer. `region` is required under\n * every auth mode; credentials are optional. The auth ladder, highest first:\n *\n * 1. `api_key` — Bedrock bearer token. Swaps the SDK's whole fetch function, so\n * it wins over every SigV4 mode below and short-circuits their resolution.\n * 2. Explicit SigV4 fields — `access_key_id` / `secret_access_key` /\n * `session_token`. Any one of them present means the caller is driving\n * credentials, so no dynamic source is attached.\n * 3. A dynamic source — `use_credential_chain: true` (Fascicle loads\n * @aws-sdk/credential-providers and attaches `fromNodeProviderChain()`) or a\n * caller-supplied `credential_provider` function. Supplying both is an\n * `engine_config_error`: they are two answers to one question, not a\n * fallback pair.\n * 4. Nothing — the SDK reads `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` from\n * the environment and throws if they are absent. Note this is *not* the AWS\n * credential chain: the SDK never reads `~/.aws/credentials`, so a profile\n * without exported env vars needs mode 3.\n *\n * Effort goes through the AI SDK's own `reasoning` option, which\n * @ai-sdk/amazon-bedrock maps per model into its `reasoningConfig`: adaptive\n * thinking or a budget for Claude, the level itself for the models that take\n * one.\n *\n * Guardrails ride `provider_options.bedrock.guardrailConfig`, which the peer\n * rest-spreads into the top level of the Converse command (an undocumented seam,\n * pinned by bedrock_guardrail_wire.test.ts). With `trace: 'enabled'` the\n * assessment comes back on `provider_reported.bedrock.trace`, which is the only\n * in-process evidence that a guardrail whose PII action is `NONE` ran at all:\n * that action detects and reports without rewriting, so the output is identical\n * whether such a guardrail is attached or absent.\n */\n\nimport type { BedrockCredentialProvider, ProviderInit, UsageTotals } from '../types.js'\nimport {\n default_normalize_usage,\n load_optional_peer,\n translate_effort_to_sdk_reasoning,\n type AiSdkProviderAdapter,\n type ProviderCapability,\n type RawProviderUsage,\n} from './types.js'\nimport { engine_config_error } from '../errors.js'\n\ntype BedrockSdk = {\n createAmazonBedrock: (config: {\n region?: string\n accessKeyId?: string\n secretAccessKey?: string\n sessionToken?: string\n apiKey?: string\n baseURL?: string\n credentialProvider?: BedrockCredentialProvider\n }) => (model_id: string) => unknown\n}\n\n// `fromNodeProviderChain()` returns a *memoized* provider: it caches resolved\n// credentials and refreshes them on expiry. The SDK calls `credentialProvider`\n// once per request, so the chain is built once per adapter and reused, never\n// rebuilt inside build_model.\ntype CredentialProvidersSdk = {\n fromNodeProviderChain: () => BedrockCredentialProvider\n}\n\n/**\n * Normalize Bedrock's raw usage payload into UsageTotals.\n */\nexport function normalize_bedrock_usage(raw: RawProviderUsage | undefined): UsageTotals {\n return default_normalize_usage(raw)\n}\n\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n 'image_input',\n 'reasoning',\n])\n\ntype BedrockConfig = Parameters<BedrockSdk['createAmazonBedrock']>[0]\n\n/** Read a config field only when it is a string, so junk values stay unset. */\nfunction read_string(init: ProviderInit, key: string): string | undefined {\n const value = init[key]\n return typeof value === 'string' ? value : undefined\n}\n\n/** The static credential fields the SDK accepts, mapped from snake_case init. */\ntype StaticCredentials = {\n readonly region: string\n readonly api_key: string | undefined\n readonly access_key_id: string | undefined\n readonly secret_access_key: string | undefined\n readonly session_token: string | undefined\n readonly base_url: string | undefined\n}\n\n/** Pull the static fields off init, rejecting a missing or non-string region. */\nfunction read_static_credentials(init: ProviderInit): StaticCredentials {\n const region = read_string(init, 'region') ?? ''\n if (region.length === 0) {\n throw new engine_config_error('bedrock provider requires a non-empty region', 'bedrock')\n }\n return {\n region,\n api_key: read_string(init, 'api_key'),\n access_key_id: read_string(init, 'access_key_id'),\n secret_access_key: read_string(init, 'secret_access_key'),\n session_token: read_string(init, 'session_token'),\n base_url: read_string(init, 'base_url'),\n }\n}\n\ntype DynamicSource =\n | { readonly kind: 'chain' }\n | { readonly kind: 'explicit', readonly provider: BedrockCredentialProvider }\n\n/** True when the caller is already supplying credentials in any static form. */\nfunction has_static_credentials(statics: StaticCredentials): boolean {\n return (\n statics.api_key !== undefined\n || statics.access_key_id !== undefined\n || statics.secret_access_key !== undefined\n || statics.session_token !== undefined\n )\n}\n\n/**\n * Pick the dynamic credential source, or none. A bearer token or any explicit\n * SigV4 field short-circuits it: attaching a provider anyway would either\n * override the caller's keys (the SDK prefers `credentialProvider` over\n * `accessKeyId`) or force the optional @aws-sdk/credential-providers peer on\n * bearer-token users who never need it. The conflict check runs first, since\n * naming two dynamic sources is a mistake whatever else is set.\n */\nfunction resolve_dynamic_source(\n init: ProviderInit,\n statics: StaticCredentials,\n): DynamicSource | undefined {\n const use_chain = init['use_credential_chain'] === true\n const raw = init['credential_provider']\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const provider = typeof raw === 'function' ? (raw as BedrockCredentialProvider) : undefined\n if (use_chain && provider !== undefined) {\n throw new engine_config_error(\n 'bedrock provider accepts use_credential_chain or credential_provider, not both',\n 'bedrock',\n )\n }\n if (has_static_credentials(statics)) return undefined\n if (provider !== undefined) return { kind: 'explicit', provider }\n return use_chain ? { kind: 'chain' } : undefined\n}\n\n/**\n * Build the camelCase config the SDK expects, assigning only fields that are\n * set so the object carries no `undefined` entries. The SDK reads either shape\n * identically; the tests assert on key presence, which is the cheaper signal\n * that a credential really was omitted rather than silently resolved.\n */\nfunction to_sdk_config(\n statics: StaticCredentials,\n credential_provider: BedrockCredentialProvider | undefined,\n): BedrockConfig {\n const config: BedrockConfig = { region: statics.region }\n if (statics.api_key !== undefined) config.apiKey = statics.api_key\n if (statics.access_key_id !== undefined) config.accessKeyId = statics.access_key_id\n if (statics.secret_access_key !== undefined) config.secretAccessKey = statics.secret_access_key\n if (statics.session_token !== undefined) config.sessionToken = statics.session_token\n if (statics.base_url !== undefined) config.baseURL = statics.base_url\n if (credential_provider !== undefined) config.credentialProvider = credential_provider\n return config\n}\n\n/**\n * Build the Bedrock ai_sdk adapter: validates the required region, resolves\n * the chosen auth mode (bearer token, explicit SigV4 keys, or a dynamic\n * credential source), and lazily loads @ai-sdk/amazon-bedrock to build models.\n * See the module docstring for the full precedence ladder.\n */\nexport const create_bedrock_adapter = (init: ProviderInit): AiSdkProviderAdapter => {\n const statics = read_static_credentials(init)\n const dynamic_source = resolve_dynamic_source(init, statics)\n\n let chain: BedrockCredentialProvider | undefined\n async function resolve_credential_provider(): Promise<BedrockCredentialProvider | undefined> {\n if (dynamic_source === undefined) return undefined\n if (dynamic_source.kind === 'explicit') return dynamic_source.provider\n chain ??= (\n await load_optional_peer<CredentialProvidersSdk>('@aws-sdk/credential-providers')\n ).fromNodeProviderChain()\n return chain\n }\n\n return {\n kind: 'ai_sdk',\n name: 'bedrock',\n async build_model(model_id: string): Promise<unknown> {\n const sdk = await load_optional_peer<BedrockSdk>('@ai-sdk/amazon-bedrock')\n const provider = sdk.createAmazonBedrock(\n to_sdk_config(statics, await resolve_credential_provider()),\n )\n return provider(model_id)\n },\n translate_effort: translate_effort_to_sdk_reasoning,\n normalize_usage: normalize_bedrock_usage,\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * Frozen constants for the claude_cli provider: startup and idle defaults,\n * the escalation window, and the auth failure pattern list.\n *\n * Arrays are Object.freeze-d at module load so downstream code cannot mutate\n * them.\n */\n\nexport const CLI_BINARY_DEFAULT = 'claude'\n\nexport const DEFAULT_STARTUP_TIMEOUT_MS = 120_000\n\nexport const DEFAULT_STALL_TIMEOUT_MS = 300_000\n\nexport const SIGKILL_ESCALATION_MS = 2000\n\nexport const CLI_AUTH_ERROR_PATTERNS: ReadonlyArray<string> = Object.freeze([\n 'authentication',\n 'unauthorized',\n 'forbidden',\n 'oauth token has expired',\n 'invalid_api_key',\n])\n\n/**\n * The error code on the assistant message that the CLI writes in the model's\n * place when it has no session to call with. It goes to stdout, not stderr,\n * so `CLI_AUTH_ERROR_PATTERNS` never sees it.\n */\nexport const CLI_AUTH_FAILED_ERROR = 'authentication_failed'\n\nexport const DEFAULT_SETTING_SOURCES: ReadonlyArray<'user' | 'project' | 'local'> =\n Object.freeze(['project', 'local'])\n","/**\n * Authentication enforcement for the claude_cli adapter.\n *\n * Composes the subprocess environment from provider config and call-level\n * overrides, validates that `auth_mode: 'api_key'` has a key to use, and\n * recognizes CLI stderr auth failures so they can be surfaced as\n * `provider_auth_error` instead of a generic exit-code error.\n */\n\nimport { engine_config_error } from '../../errors.js'\nimport type { AuthMode, ClaudeCliProviderConfig } from './types.js'\nimport { CLI_AUTH_ERROR_PATTERNS } from './constants.js'\n\n/**\n * Standard env keys forwarded from process.env so the spawn target\n * (greywall/bwrap on PATH, then `claude`) can be resolved and run.\n *\n * Mirrors `STANDARD_KEYS` in `src/forward_standard_env.ts`. Keep the two\n * lists in sync; engine cannot import from Fascicle (the umbrella depends\n * on engine, not the other way).\n */\nconst STANDARD_ENV_KEYS = [\n 'PATH',\n 'HOME',\n 'SHELL',\n 'USER',\n 'LOGNAME',\n 'LANG',\n 'TMPDIR',\n] as const\n\n/**\n * Throw `engine_config_error` synchronously when `auth_mode: 'api_key'` is\n * set without a non-empty `api_key`.\n *\n * Runs at adapter construction time so a misconfigured provider fails\n * fast, before any CLI subprocess is spawned.\n */\nexport function validate_auth_config(config: ClaudeCliProviderConfig): void {\n const auth_mode = config.auth_mode ?? 'auto'\n if (auth_mode === 'api_key') {\n const api_key = typeof config.api_key === 'string' ? config.api_key : ''\n if (api_key.length === 0) {\n throw new engine_config_error(\n 'api_key is required for auth_mode: api_key',\n 'claude_cli',\n )\n }\n }\n}\n\n/**\n * Copy the string-valued entries of `source` onto `target`, dropping any\n * `undefined` slot (the shape `process.env` and caller overrides both carry).\n */\nfunction copy_string_entries(\n target: Record<string, string>,\n source: Record<string, string | undefined>,\n): void {\n for (const [key, value] of Object.entries(source)) {\n if (typeof value === 'string') target[key] = value\n }\n}\n\n/**\n * Seed the base subprocess env before caller overrides and the auth scrub.\n *\n * `inherit_env: false` starts from an empty env. Otherwise `'oauth'` inherits\n * the full `process.env` (the CLI needs HOME plus session-specific vars to\n * reach the logged-in session); every other mode inherits only the standard\n * keys needed to resolve the sandbox wrapper and the claude binary on PATH.\n */\nfunction seed_base_env(\n config: ClaudeCliProviderConfig,\n auth_mode: AuthMode,\n): Record<string, string> {\n const env: Record<string, string> = {}\n if (config.inherit_env === false) return env\n if (auth_mode === 'oauth') {\n copy_string_entries(env, process.env)\n return env\n }\n for (const key of STANDARD_ENV_KEYS) {\n const value = process.env[key]\n if (typeof value === 'string') env[key] = value\n }\n return env\n}\n\n/**\n * Apply the auth-mode scrub last, after base and caller env are merged, so\n * nothing can re-introduce `ANTHROPIC_API_KEY` under `'oauth'`. `'api_key'`\n * forces the configured key (empty string when absent); `'auto'` forwards a\n * non-empty configured key and otherwise leaves the inherited env untouched.\n */\nfunction apply_auth_key(\n env: Record<string, string>,\n config: ClaudeCliProviderConfig,\n auth_mode: AuthMode,\n): void {\n if (auth_mode === 'oauth') {\n delete env['ANTHROPIC_API_KEY']\n return\n }\n if (auth_mode === 'api_key') {\n env['ANTHROPIC_API_KEY'] = typeof config.api_key === 'string' ? config.api_key : ''\n return\n }\n if (typeof config.api_key === 'string' && config.api_key.length > 0) {\n env['ANTHROPIC_API_KEY'] = config.api_key\n }\n}\n\n/**\n * Compose the subprocess environment for one claude CLI invocation.\n *\n * Regardless of `auth_mode`, seeds the standard process-env keys (PATH,\n * HOME, SHELL, USER, LOGNAME, LANG, TMPDIR) by default so the spawned\n * subprocess can locate the sandbox wrapper (greywall/bwrap) and the\n * claude binary on PATH. Set `inherit_env: false` on the provider config to\n * opt out and start from an empty env instead.\n *\n * Under `auth_mode: 'oauth'` the full `process.env` is inherited instead\n * of just the standard keys, because the CLI needs HOME plus\n * session-specific vars to reach the already-logged-in OAuth session. The\n * auth-mode scrub runs last, after config and caller overrides are merged\n * in, so nothing can re-introduce `ANTHROPIC_API_KEY` under `'oauth'`.\n */\nexport function build_env(\n config: ClaudeCliProviderConfig,\n caller_env: Record<string, string> | undefined,\n auth_mode: AuthMode,\n): Record<string, string> {\n const env = seed_base_env(config, auth_mode)\n if (caller_env !== undefined) copy_string_entries(env, caller_env)\n apply_auth_key(env, config, auth_mode)\n return env\n}\n\n/**\n * Check whether captured CLI stderr looks like an auth failure.\n *\n * Matches case-insensitively against the frozen `CLI_AUTH_ERROR_PATTERNS`\n * list; used to turn a nonzero CLI exit into `provider_auth_error` instead\n * of a generic `claude_cli_error`.\n */\nexport function stderr_is_auth_failure(stderr: string): boolean {\n if (stderr.length === 0) return false\n const lower = stderr.toLowerCase()\n for (const pattern of CLI_AUTH_ERROR_PATTERNS) {\n if (lower.includes(pattern.toLowerCase())) return true\n }\n return false\n}\n","/**\n * Argv builder for the claude CLI invocation.\n *\n * Every option value is a separate argv element; option names are never\n * string-interpolated with values. The returned array is a readonly frozen\n * copy; mutation would indicate a caller bug.\n */\n\nimport type { ClaudeCliCallOptions, ClaudeCliProviderConfig } from './types.js'\nimport { DEFAULT_SETTING_SOURCES } from './constants.js'\n\nexport type BuildArgvInput = {\n readonly model_id: string\n readonly provider_config: ClaudeCliProviderConfig\n readonly call_opts: ClaudeCliCallOptions\n readonly merged_allowed_tools: ReadonlyArray<string>\n readonly merged_system: string\n readonly compiled_schema?: string\n}\n\n/**\n * Assemble the full argv array for one `claude` CLI invocation.\n *\n * Always runs the CLI in non-interactive, streaming JSON mode (`-p\n * --output-format stream-json --verbose`) so the adapter can parse events\n * line by line. Flags are appended in a fixed order; `--resume` is only\n * added when a session id is present, and `--append-system-prompt` only\n * when there's a non-empty merged system prompt.\n */\nexport function build_cli_argv(input: BuildArgvInput): ReadonlyArray<string> {\n const args: string[] = []\n args.push('-p')\n args.push('--output-format', 'stream-json')\n args.push('--model', input.model_id)\n args.push('--verbose')\n\n const setting_sources =\n input.provider_config.setting_sources ?? DEFAULT_SETTING_SOURCES\n args.push('--setting-sources', setting_sources.join(','))\n\n for (const tool of input.merged_allowed_tools) {\n args.push('--allowedTools', tool)\n }\n\n if (typeof input.call_opts.session_id === 'string' && input.call_opts.session_id.length > 0) {\n args.push('--resume', input.call_opts.session_id)\n }\n\n if (input.call_opts.agents !== undefined) {\n args.push('--agents', JSON.stringify(input.call_opts.agents))\n }\n\n const plugin_dirs = input.provider_config.plugin_dirs ?? []\n for (const dir of plugin_dirs) {\n args.push('--plugin-dir', dir)\n }\n\n if (typeof input.compiled_schema === 'string' && input.compiled_schema.length > 0) {\n args.push('--json-schema', input.compiled_schema)\n }\n\n if (input.merged_system.length > 0) {\n args.push('--append-system-prompt', input.merged_system)\n }\n\n const extra_args = input.call_opts.extra_args ?? []\n for (const s of extra_args) {\n args.push(s)\n }\n\n return Object.freeze(args)\n}\n\n/**\n * Join the caller's `system` prompt and the `append_system_prompt` call\n * option into the single string passed to `--append-system-prompt`.\n *\n * Empty or undefined parts are dropped; when both parts are present they're\n * separated by a blank line.\n */\nexport function merge_system(\n opts_system: string | undefined,\n append: string | undefined,\n): string {\n const parts: string[] = []\n if (typeof opts_system === 'string' && opts_system.length > 0) parts.push(opts_system)\n if (typeof append === 'string' && append.length > 0) parts.push(append)\n return parts.join('\\n\\n')\n}\n\n/**\n * Merge the caller's `allowed_tools` allowlist with the tool names derived\n * from `opts.tools`, de-duplicating while preserving first-seen order.\n */\nexport function merge_allowed_tools(\n call_allowlist: ReadonlyArray<string> | undefined,\n tool_names: ReadonlyArray<string>,\n): ReadonlyArray<string> {\n const seen = new Set<string>()\n const merged: string[] = []\n const push_unique = (name: string): void => {\n if (seen.has(name)) return\n seen.add(name)\n merged.push(name)\n }\n if (call_allowlist !== undefined) {\n for (const t of call_allowlist) push_unique(t)\n }\n for (const n of tool_names) push_unique(n)\n return merged\n}\n","/**\n * Sandbox wrapper for the claude_cli adapter.\n *\n * Builds the `{ spawn_cmd, prefix_args }` pair for bwrap and greywall. When\n * no sandbox is configured, returns `{ spawn_cmd: binary, prefix_args: [] }`;\n * the caller then concatenates prefix_args before the CLI argv.\n *\n * Both wrappers allow the binary to execute while restricting network reach\n * to the allowlist and write access to additional paths on top of the\n * sandbox's default-read-only filesystem.\n *\n * greywall 0.3+ removed the `--allow-host` and `--rw` flags; policy now\n * lives in a JSON settings file passed via `--settings <path>`. Schema is\n * documented in `greywall --help`:\n *\n * {\n * \"network\": { \"allowHosts\": [...] },\n * \"filesystem\": { \"allowWrite\": [...] }\n * }\n *\n * `filesystem.allowWrite` is honored directly; `network.allowHosts` is\n * preserved for documentation/forward-compat (greywall ignores unknown\n * fields and host-level allowlisting is currently enforced at the\n * greyproxy layer).\n */\n\nimport { mkdtempSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nimport type { SandboxProviderConfig } from './types.js'\n\nexport type SandboxPlan = {\n readonly spawn_cmd: string\n readonly prefix_args: ReadonlyArray<string>\n}\n\n/**\n * Pick the sandbox wrapper (if any) and build its wrapping argv.\n *\n * Returns the unwrapped binary with no prefix args when `sandbox` is\n * undefined.\n */\nexport function build_sandbox_plan(\n binary: string,\n sandbox: SandboxProviderConfig | undefined,\n): SandboxPlan {\n if (sandbox === undefined) {\n return { spawn_cmd: binary, prefix_args: [] }\n }\n if (sandbox.kind === 'bwrap') {\n return { spawn_cmd: 'bwrap', prefix_args: build_bwrap_args(binary, sandbox) }\n }\n return { spawn_cmd: 'greywall', prefix_args: build_greywall_args(binary, sandbox) }\n}\n\n/**\n * Build the `bwrap` argv prefix that sandboxes the claude binary.\n *\n * Read-only binds the base OS directories, mounts fresh `/proc`, `/dev`,\n * and a tmpfs `/tmp`, and unshares the user/pid/ipc/uts/cgroup namespaces\n * so the child can't see or touch the host outside what's explicitly bound\n * in. Network access is off (`--unshare-net`) unless a non-empty\n * `network_allowlist` is given.\n */\nfunction build_bwrap_args(\n binary: string,\n sandbox: Extract<SandboxProviderConfig, { kind: 'bwrap' }>,\n): ReadonlyArray<string> {\n const args: string[] = []\n args.push('--ro-bind', '/usr', '/usr')\n args.push('--ro-bind', '/bin', '/bin')\n args.push('--ro-bind', '/lib', '/lib')\n args.push('--ro-bind-try', '/lib64', '/lib64')\n args.push('--ro-bind-try', '/etc/resolv.conf', '/etc/resolv.conf')\n args.push('--proc', '/proc')\n args.push('--dev', '/dev')\n args.push('--tmpfs', '/tmp')\n args.push('--unshare-user')\n args.push('--unshare-pid')\n args.push('--unshare-ipc')\n args.push('--unshare-uts')\n args.push('--unshare-cgroup-try')\n args.push('--die-with-parent')\n\n const allowlist = sandbox.network_allowlist ?? []\n if (allowlist.length > 0) {\n args.push('--share-net')\n for (const host of allowlist) {\n args.push('--setenv', 'CLAUDE_CLI_NET_ALLOW', host)\n }\n } else {\n // Empty or absent allowlist means network-off. Without an explicit\n // --unshare-net, bwrap leaves the child in the host network namespace, so\n // the documented \"network-off\" guarantee (docs/cli.md) would be a no-op.\n args.push('--unshare-net')\n }\n\n const write_paths = sandbox.additional_write_paths ?? []\n for (const p of write_paths) {\n args.push('--bind', p, p)\n }\n\n args.push('--')\n args.push(binary)\n return args\n}\n\n/**\n * Build the greywall argv prefix: `--settings <path> -- <binary>`.\n *\n * Uses `sandbox.settings_path` directly when the caller supplied one;\n * otherwise writes a fresh settings file derived from\n * `network_allowlist`/`additional_write_paths`.\n */\nfunction build_greywall_args(\n binary: string,\n sandbox: Extract<SandboxProviderConfig, { kind: 'greywall' }>,\n): ReadonlyArray<string> {\n const settings_path = sandbox.settings_path ?? write_greywall_settings(sandbox)\n return ['--settings', settings_path, '--', binary]\n}\n\n/**\n * Write a greywall JSON settings file for one sandboxed run to a fresh\n * temp directory and return its path.\n */\nfunction write_greywall_settings(\n sandbox: Extract<SandboxProviderConfig, { kind: 'greywall' }>,\n): string {\n const dir = mkdtempSync(join(tmpdir(), `fascicle-greywall-${process.pid}-`))\n const path = join(dir, 'greywall.json')\n const payload = {\n network: { allowHosts: [...(sandbox.network_allowlist ?? [])] },\n filesystem: { allowWrite: [...(sandbox.additional_write_paths ?? [])] },\n }\n writeFileSync(path, JSON.stringify(payload, null, 2), 'utf8')\n return path\n}\n","/**\n * Subprocess lifecycle for the claude_cli adapter.\n *\n * The factory exposes:\n * - `live_children`: a closure-captured Set<ChildProcess> per\n * adapter-factory call; no state is shared at module scope, so two\n * factory invocations track two independent sets of children.\n * - `spawn_cli(...)`: spawns the child with { detached: true, stdio: [...],\n * env, cwd, shell: false }; arms startup + stall timers; escalates\n * SIGTERM to SIGKILL on signal; removes the child from the live set on\n * close.\n * - `dispose_all()`: sends SIGTERM then SIGKILL to every live child and\n * awaits every close.\n *\n * A single process-wide `exit` handler synchronously SIGKILLs every live\n * child across every spawn registry, so a crashing or exiting host process\n * doesn't leak subprocesses. The handler is installed once per Node\n * process and iterates a registry of adapter live-sets.\n *\n * `node:child_process` imports are confined to this directory (enforced by\n * rules/no-child-process-outside-claude-cli.yml). The spawn call passes\n * `shell: false` via argv array form; no value is string-interpolated into\n * argv.\n */\n\nimport { spawn as node_spawn, type ChildProcess } from 'node:child_process'\nimport { aborted_error, claude_cli_error } from '../../errors.js'\nimport { SIGKILL_ESCALATION_MS } from './constants.js'\n\nexport type SpawnArgs = {\n readonly cmd: string\n readonly argv: ReadonlyArray<string>\n readonly env: Record<string, string>\n readonly cwd?: string\n readonly stdin: string\n readonly startup_timeout_ms: number\n readonly stall_timeout_ms: number\n readonly abort?: AbortSignal\n // A sandboxed run spawns the sandbox wrapper as `cmd`, so a failed spawn is\n // the wrapper's and reports `sandbox_unavailable`. Defaults to\n // `binary_not_found`.\n readonly spawn_failure_reason?: 'binary_not_found' | 'sandbox_unavailable'\n}\n\nexport type SpawnCloseOutcome = {\n readonly code: number | null\n readonly signal: NodeJS.Signals | null\n readonly stderr: string\n}\n\nexport type SpawnSession = {\n readonly child: ChildProcess\n readonly stdout_lines: AsyncIterable<string>\n readonly wait_close: () => Promise<SpawnCloseOutcome>\n readonly request_terminate: (reason: 'abort' | 'disposed' | 'timeout') => void\n}\n\ntype ChildRegistry = Set<ChildProcess>\n\nconst ALL_REGISTRIES: Set<ChildRegistry> = new Set()\nlet exit_handler_installed = false\n\n/**\n * SIGKILL every live child across every spawn registry.\n *\n * Children are spawned with `detached: true`, which makes each one the\n * leader of its own process group; signaling `-child.pid` (a negative pid)\n * targets the whole group instead of just the direct child, so any\n * grandchildren the CLI itself spawned die too.\n */\nfunction kill_live_children(): void {\n for (const reg of ALL_REGISTRIES) {\n for (const child of reg) {\n if (child.pid === undefined || child.exitCode !== null) continue\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch {\n // already exited, or signal failed; nothing more we can do synchronously\n }\n }\n }\n}\n\n/**\n * Install the process-wide `exit` handler that kills every live child.\n * Calling this more than once is a no-op.\n */\nfunction install_exit_handler_once(): void {\n if (exit_handler_installed) return\n exit_handler_installed = true\n process.on('exit', kill_live_children)\n}\n\nexport type SpawnRuntime = {\n readonly live_children: ChildRegistry\n readonly spawn_cli: (args: SpawnArgs) => Promise<SpawnSession>\n readonly dispose_all: () => Promise<void>\n}\n\n/**\n * Build a `SpawnRuntime`: a per-adapter-instance registry of live children\n * plus the `spawn_cli`/`dispose_all` operations that manage them.\n *\n * Registers `live_children` in the module-wide `ALL_REGISTRIES` set so the\n * process `exit` handler installed by `install_exit_handler_once` can find\n * and kill this runtime's children too.\n */\nexport function create_spawn_runtime(): SpawnRuntime {\n const live_children: ChildRegistry = new Set()\n ALL_REGISTRIES.add(live_children)\n install_exit_handler_once()\n\n const spawn_cli = async (args: SpawnArgs): Promise<SpawnSession> => {\n if (args.abort?.aborted === true) {\n throw new aborted_error('aborted', { reason: args.abort.reason })\n }\n const spawn_failure_reason = args.spawn_failure_reason ?? 'binary_not_found'\n \n let child: ChildProcess\n try {\n const spawn_opts: Parameters<typeof node_spawn>[2] = {\n stdio: ['pipe', 'pipe', 'pipe'],\n detached: true,\n env: args.env,\n shell: false,\n }\n if (args.cwd !== undefined) spawn_opts.cwd = args.cwd\n child = node_spawn(args.cmd, [...args.argv], spawn_opts)\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err)\n throw new claude_cli_error(spawn_failure_reason, `failed to spawn '${args.cmd}': ${message}`)\n }\n \n live_children.add(child)\n \n let spawn_error: Error | undefined\n let startup_error: claude_cli_error | undefined\n let stall_error: claude_cli_error | undefined\n let terminate_reason: 'abort' | 'disposed' | 'timeout' | undefined\n let startup_timer: NodeJS.Timeout | undefined\n let stall_timer: NodeJS.Timeout | undefined\n let sigkill_timer: NodeJS.Timeout | undefined\n let first_stdout_byte_seen = false\n \n const capture: { stderr: string } = { stderr: '' }\n child.stderr?.on('data', (buf: Buffer) => {\n capture.stderr += buf.toString('utf8')\n })\n child.on('error', (err) => {\n spawn_error = err\n })\n \n const clear_all_timers = (): void => {\n // clearTimeout is a no-op on undefined, so the timers need no guards.\n clearTimeout(startup_timer)\n clearTimeout(stall_timer)\n clearTimeout(sigkill_timer)\n startup_timer = undefined\n stall_timer = undefined\n sigkill_timer = undefined\n }\n \n const send_signal = (signal: NodeJS.Signals): void => {\n if (child.pid === undefined || child.exitCode !== null) return\n try {\n process.kill(-child.pid, signal)\n } catch {\n // child already exited, or kill failed; ignore\n }\n }\n \n const escalate = (reason: 'abort' | 'disposed' | 'timeout'): void => {\n if (terminate_reason !== undefined) return\n terminate_reason = reason\n send_signal('SIGTERM')\n sigkill_timer = setTimeout(() => {\n send_signal('SIGKILL')\n }, SIGKILL_ESCALATION_MS)\n }\n \n if (args.startup_timeout_ms > 0) {\n startup_timer = setTimeout(() => {\n if (first_stdout_byte_seen) return\n startup_error = new claude_cli_error(\n 'startup_timeout',\n `no stdout within ${String(args.startup_timeout_ms)}ms`,\n )\n escalate('timeout')\n }, args.startup_timeout_ms)\n }\n \n const arm_stall_timer = (): void => {\n if (args.stall_timeout_ms <= 0) return\n // clearTimeout no-ops on undefined; the previous stall timer (if any)\n // is replaced on every byte to reset the quiet-period window.\n clearTimeout(stall_timer)\n stall_timer = setTimeout(() => {\n stall_error = new claude_cli_error(\n 'stall_timeout',\n `no stdout for ${String(args.stall_timeout_ms)}ms`,\n )\n escalate('timeout')\n }, args.stall_timeout_ms)\n }\n \n const abort_listener = (): void => {\n escalate('abort')\n }\n if (args.abort !== undefined) {\n if (args.abort.aborted) abort_listener()\n else args.abort.addEventListener('abort', abort_listener, { once: true })\n }\n \n const close_promise = new Promise<SpawnCloseOutcome>((resolve) => {\n child.on('close', (code, signal) => {\n clear_all_timers()\n live_children.delete(child)\n if (args.abort !== undefined) {\n args.abort.removeEventListener('abort', abort_listener)\n }\n resolve({ code, signal, stderr: capture.stderr })\n })\n })\n \n const stdin = child.stdin\n if (stdin !== null) {\n stdin.on('error', () => {\n // CLI may close stdin before we finish writing; swallow.\n })\n stdin.write(args.stdin)\n stdin.end()\n }\n \n const stdout_lines = build_stdout_lines(child, () => {\n if (!first_stdout_byte_seen) {\n first_stdout_byte_seen = true\n if (startup_timer !== undefined) {\n clearTimeout(startup_timer)\n startup_timer = undefined\n }\n }\n arm_stall_timer()\n })\n \n return {\n child,\n stdout_lines,\n wait_close: async () => {\n const outcome = await close_promise\n if (spawn_error !== undefined) {\n const message = spawn_error.message\n throw new claude_cli_error(spawn_failure_reason, message)\n }\n if (startup_error !== undefined) throw startup_error\n if (stall_error !== undefined) throw stall_error\n if (terminate_reason === 'abort') {\n throw new aborted_error('aborted', { reason: args.abort?.reason })\n }\n if (terminate_reason === 'disposed') {\n throw new aborted_error('engine disposed', { reason: 'engine_disposed' })\n }\n return outcome\n },\n request_terminate: (reason) => escalate(reason),\n }\n }\n\n const dispose_all = async (): Promise<void> => {\n const pending: Promise<void>[] = []\n for (const child of live_children) {\n pending.push(\n new Promise<void>((resolve) => {\n if (child.exitCode !== null) {\n resolve()\n return\n }\n child.once('close', () => resolve())\n if (child.pid !== undefined) {\n try {\n process.kill(-child.pid, 'SIGTERM')\n } catch {\n // child already exited or signal failed; ignore\n }\n setTimeout(() => {\n if (child.exitCode === null && child.pid !== undefined) {\n try {\n process.kill(-child.pid, 'SIGKILL')\n } catch {\n // ignore\n }\n }\n }, SIGKILL_ESCALATION_MS)\n }\n }),\n )\n }\n await Promise.all(pending)\n ALL_REGISTRIES.delete(live_children)\n }\n\n return { live_children, spawn_cli, dispose_all }\n}\n\n/**\n * Turn a child process's stdout into an async iterable of complete lines.\n *\n * Buffers partial output across `data` events and yields only on `\\n`\n * boundaries; on `end`, flushes a trailing line that has no terminator.\n * Calls `on_data` on every chunk, before buffering, so the caller can reset\n * startup/stall timers on any byte of output rather than only on line\n * boundaries.\n */\nasync function* build_stdout_lines(\n child: ChildProcess,\n on_data: () => void,\n): AsyncIterable<string> {\n const stdout = child.stdout\n if (stdout === null) return\n let buffer = ''\n let ended = false\n const queue: string[] = []\n let resolver: (() => void) | undefined\n const wake = (): void => {\n const r = resolver\n if (r !== undefined) {\n resolver = undefined\n r()\n }\n }\n stdout.setEncoding('utf8')\n stdout.on('data', (chunk: string) => {\n on_data()\n buffer += chunk\n let nl = buffer.indexOf('\\n')\n while (nl !== -1) {\n queue.push(buffer.slice(0, nl))\n buffer = buffer.slice(nl + 1)\n nl = buffer.indexOf('\\n')\n }\n wake()\n })\n stdout.on('end', () => {\n if (buffer.length > 0) {\n queue.push(buffer)\n buffer = ''\n }\n ended = true\n wake()\n })\n stdout.on('error', () => {\n ended = true\n wake()\n })\n while (true) {\n if (queue.length > 0) {\n const next = queue.shift()\n if (next !== undefined) yield next\n continue\n }\n if (ended) return\n await new Promise<void>((r) => {\n resolver = r\n })\n }\n}\n","/**\n * JSON-lines stream parser for the claude CLI stdout.\n *\n * The CLI (run with `--output-format stream-json`) writes one JSON event per\n * line: `system` (session init), `assistant` (model output), `user` (tool\n * results echoed back into the conversation), `result` (the single terminal\n * event carrying totals), and `rate_limit_event` (informational rate-limit\n * budget report). The parser is a line-buffered state machine with minimal\n * state:\n * - buffered partial line\n * - last-seen event type (assistant | user/tool_result | system | result);\n * an `assistant` event that follows a user/tool_result marks a turn\n * boundary and increments `step_index`\n * - current `step_index`\n *\n * Malformed JSON records `{ kind: 'cli_parse_error', line }` to trajectory\n * and skips; unknown event types record `{ kind: 'cli_unknown_event', raw }`\n * and skip. Neither ever throws.\n *\n * Event shapes are validated by hand-written type guards. `as_event` is the\n * discriminated gate over the recognized CLI event types: a value must be a\n * non-array object whose `type` names a known event, and that event's own\n * fields must type-check, or the whole line is rejected as `cli_unknown_event`.\n * The gate is as strict as a `z.discriminatedUnion` would be: an optional\n * field carrying the wrong type rejects the event, unknown keys ride along\n * unused, and a sub-object (`usage`, `rate_limit_info`) is validated field\n * by field. Per-entry content arrays are the one deliberately permissive layer:\n * `as_assistant_part` / `as_user_part` recognize a single entry at a time and\n * the collector drops the ones that don't match, so a content type a future CLI\n * emits never rejects the surrounding event.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport type { StreamChunk, UsageTotals } from '../../types.js'\n\ntype CliUsageRaw = {\n input_tokens?: number\n output_tokens?: number\n cache_read_input_tokens?: number\n cache_creation_input_tokens?: number\n}\n\ntype CliTextPart = { type: 'text'; text: string }\ntype CliToolUsePart = { type: 'tool_use'; id: string; name: string; input: unknown }\ntype CliAssistantContent = CliTextPart | CliToolUsePart\n\ntype CliUserContent = {\n type: 'tool_result'\n tool_use_id: string\n content?: unknown\n is_error?: boolean\n}\n\ntype CliSystemEvent = {\n type: 'system'\n subtype?: string\n session_id?: string\n model?: string\n}\n\ntype CliAssistantEvent = {\n type: 'assistant'\n message: { content: CliAssistantContent[] }\n /**\n * Set when the CLI writes the message itself in the model's place, to say\n * why the call failed (`authentication_failed` for a logged-out session).\n */\n error?: string\n}\n\ntype CliUserEvent = {\n type: 'user'\n message: { content: CliUserContent[] }\n}\n\ntype CliResultEvent = {\n type: 'result'\n subtype?: string\n session_id?: string\n total_cost_usd?: number\n duration_ms?: number\n duration_api_ms?: number\n is_error?: boolean\n usage?: CliUsageRaw\n result?: string\n}\n\ntype CliRateLimitInfo = {\n status?: string\n resetsAt?: number\n rateLimitType?: string\n overageStatus?: string\n overageResetsAt?: number\n isUsingOverage?: boolean\n}\n\ntype CliRateLimitEvent = {\n type: 'rate_limit_event'\n rate_limit_info?: CliRateLimitInfo\n session_id?: string\n}\n\ntype CliEvent =\n | CliSystemEvent\n | CliAssistantEvent\n | CliUserEvent\n | CliResultEvent\n | CliRateLimitEvent\n\n/** A non-null, non-array object: the shape every CLI event and sub-object takes. */\nfunction is_record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** `key` is absent (or `undefined`), or holds a string. */\nfunction opt_string(rec: Record<string, unknown>, key: string): boolean {\n const value = rec[key]\n return value === undefined || typeof value === 'string'\n}\n\n/** `key` is absent (or `undefined`), or holds a number. */\nfunction opt_number(rec: Record<string, unknown>, key: string): boolean {\n const value = rec[key]\n return value === undefined || typeof value === 'number'\n}\n\n/** `key` is absent (or `undefined`), or holds a boolean. */\nfunction opt_boolean(rec: Record<string, unknown>, key: string): boolean {\n const value = rec[key]\n return value === undefined || typeof value === 'boolean'\n}\n\n/**\n * The optional `usage` sub-object of a `result` event. Absent is fine; a present\n * value must be an object whose known token counts are numbers when given. A\n * `null`, an array, or a mistyped count rejects the event.\n */\nfunction is_valid_usage(value: unknown): boolean {\n if (value === undefined) return true\n if (!is_record(value)) return false\n return (\n opt_number(value, 'input_tokens') &&\n opt_number(value, 'output_tokens') &&\n opt_number(value, 'cache_read_input_tokens') &&\n opt_number(value, 'cache_creation_input_tokens')\n )\n}\n\n/**\n * The optional `rate_limit_info` sub-object of a `rate_limit_event`, under the\n * same rule as usage: absent is fine, a present value is validated field by\n * field or the event is rejected.\n */\nfunction is_valid_rate_limit_info(value: unknown): boolean {\n if (value === undefined) return true\n if (!is_record(value)) return false\n return (\n opt_string(value, 'status') &&\n opt_number(value, 'resetsAt') &&\n opt_string(value, 'rateLimitType') &&\n opt_string(value, 'overageStatus') &&\n opt_number(value, 'overageResetsAt') &&\n opt_boolean(value, 'isUsingOverage')\n )\n}\n\n/**\n * Recognize one `assistant` content entry, or `undefined` for anything\n * unrecognized. `text` needs a string `text`; `tool_use` needs string `id` and\n * `name` and carries its opaque `input` through (absent `input` becomes\n * `undefined`, one deliberate tolerance the old `z.unknown()` did not grant).\n * Callers drop the `undefined` results, so an unknown entry type never rejects\n * the surrounding event.\n */\nfunction as_assistant_part(value: unknown): CliAssistantContent | undefined {\n if (!is_record(value)) return undefined\n if (value['type'] === 'text') {\n const text = value['text']\n return typeof text === 'string' ? { type: 'text', text } : undefined\n }\n if (value['type'] === 'tool_use') {\n const id = value['id']\n const name = value['name']\n if (typeof id !== 'string') return undefined\n if (typeof name !== 'string') return undefined\n return { type: 'tool_use', id, name, input: value['input'] }\n }\n return undefined\n}\n\n/**\n * Recognize one `user` content entry as a tool result, or `undefined`. Requires\n * a string `tool_use_id`; `is_error` must be boolean when present, and a present\n * `content` of any shape is carried through. Callers drop the `undefined`\n * results.\n */\nfunction as_user_part(value: unknown): CliUserContent | undefined {\n if (!is_record(value)) return undefined\n if (value['type'] !== 'tool_result') return undefined\n const tool_use_id = value['tool_use_id']\n if (typeof tool_use_id !== 'string') return undefined\n if (!opt_boolean(value, 'is_error')) return undefined\n const part: CliUserContent = { type: 'tool_result', tool_use_id }\n if ('content' in value) part.content = value['content']\n const is_error = value['is_error']\n if (typeof is_error === 'boolean') part.is_error = is_error\n return part\n}\n\n/**\n * Collect the valid parts of an `assistant`/`user` content array. Returns\n * `undefined` (rejecting the event) when `value` is not an array; otherwise maps\n * each entry through `recognize` and keeps the ones it accepts.\n */\nfunction collect_parts<T>(\n value: unknown,\n recognize: (entry: unknown) => T | undefined,\n): T[] | undefined {\n if (!Array.isArray(value)) return undefined\n const parts: T[] = []\n for (const entry of value) {\n const part = recognize(entry)\n if (part !== undefined) parts.push(part)\n }\n return parts\n}\n\n/** A `system` event whose optional metadata fields type-check. */\nfunction is_system_event(raw: Record<string, unknown>): raw is CliSystemEvent {\n return (\n opt_string(raw, 'subtype') &&\n opt_string(raw, 'session_id') &&\n opt_string(raw, 'model')\n )\n}\n\n/** A `result` event whose optional fields and `usage` sub-object type-check. */\nfunction is_result_event(raw: Record<string, unknown>): raw is CliResultEvent {\n return (\n opt_string(raw, 'subtype') &&\n opt_string(raw, 'session_id') &&\n opt_number(raw, 'total_cost_usd') &&\n opt_number(raw, 'duration_ms') &&\n opt_number(raw, 'duration_api_ms') &&\n opt_boolean(raw, 'is_error') &&\n is_valid_usage(raw['usage']) &&\n opt_string(raw, 'result')\n )\n}\n\n/** A `rate_limit_event` whose `rate_limit_info` sub-object and `session_id` type-check. */\nfunction is_rate_limit_event(raw: Record<string, unknown>): raw is CliRateLimitEvent {\n return is_valid_rate_limit_info(raw['rate_limit_info']) && opt_string(raw, 'session_id')\n}\n\n/**\n * Recognize a pass-through event in place: hand the original object back (extra\n * keys and all, since nothing downstream reads them) when `recognize` accepts\n * it, or `undefined` to reject. Narrowing keeps this cast-free.\n */\nfunction gate<T extends CliEvent>(\n raw: Record<string, unknown>,\n recognize: (value: Record<string, unknown>) => value is T,\n): T | undefined {\n return recognize(raw) ? raw : undefined\n}\n\n/**\n * Normalize an `assistant` event: its `message` must be an object and its\n * `content` an array, whose recognized parts are kept and the rest dropped. An\n * `error` code, when present, must be a string.\n */\nfunction as_assistant_event(raw: Record<string, unknown>): CliEvent | undefined {\n const message = raw['message']\n if (!is_record(message) || !opt_string(raw, 'error')) return undefined\n const content = collect_parts(message['content'], as_assistant_part)\n if (content === undefined) return undefined\n const error = raw['error']\n return typeof error === 'string'\n ? { type: 'assistant', message: { content }, error }\n : { type: 'assistant', message: { content } }\n}\n\n/** Normalize a `user` event, under the same rule as `as_assistant_event`. */\nfunction as_user_event(raw: Record<string, unknown>): CliEvent | undefined {\n const message = raw['message']\n if (!is_record(message)) return undefined\n const content = collect_parts(message['content'], as_user_part)\n return content === undefined ? undefined : { type: 'user', message: { content } }\n}\n\n/**\n * The wire gate: validate a parsed JSON value against the recognized CLI event\n * shapes, returning the typed event or `undefined` on any mismatch.\n *\n * `assistant` and `user` are normalized (their content arrays are filtered down\n * to the recognized parts); the pass-through events are recognized in place, so\n * unknown keys survive but are never read.\n */\nfunction as_event(raw: unknown): CliEvent | undefined {\n if (!is_record(raw)) return undefined\n switch (raw['type']) {\n case 'system':\n return gate(raw, is_system_event)\n case 'assistant':\n return as_assistant_event(raw)\n case 'user':\n return as_user_event(raw)\n case 'result':\n return gate(raw, is_result_event)\n case 'rate_limit_event':\n return gate(raw, is_rate_limit_event)\n default:\n return undefined\n }\n}\n\nexport type TurnCollected = {\n readonly step_index: number\n readonly text: string\n readonly tool_calls: ReadonlyArray<{ id: string; name: string; input: unknown }>\n readonly tool_results: ReadonlyArray<{\n id: string\n output?: unknown\n error?: { message: string }\n }>\n readonly usage: UsageTotals\n}\n\nexport type ParsedStream = {\n readonly session_id?: string\n readonly total_cost_usd?: number\n readonly duration_ms?: number\n readonly duration_api_ms?: number\n readonly final_text: string\n readonly final_usage: UsageTotals\n readonly turns: ReadonlyArray<TurnCollected>\n readonly is_error: boolean\n readonly received_result: boolean\n /** The error code on a message that the CLI wrote in the model's place. */\n readonly api_error?: string\n}\n\ntype ParserState = {\n buffer: string\n last_event_type: 'assistant' | 'user_tool_result' | 'system' | 'result' | 'none'\n current_step_index: number\n session_id?: string\n total_cost_usd?: number\n duration_ms?: number\n duration_api_ms?: number\n final_text: string\n final_usage: UsageTotals\n turns: TurnCollected[]\n turn_text: string\n turn_tool_calls: Array<{ id: string; name: string; input: unknown }>\n turn_tool_results: Array<{\n id: string\n output?: unknown\n error?: { message: string }\n }>\n turn_usage: UsageTotals\n is_error: boolean\n received_result: boolean\n api_error?: string\n}\n\n/**\n * Build a fresh, empty `ParserState` for one CLI invocation.\n */\nexport function create_parser_state(): ParserState {\n return {\n buffer: '',\n last_event_type: 'none',\n current_step_index: 0,\n final_text: '',\n final_usage: { input_tokens: 0, output_tokens: 0 },\n turns: [],\n turn_text: '',\n turn_tool_calls: [],\n turn_tool_results: [],\n turn_usage: { input_tokens: 0, output_tokens: 0 },\n is_error: false,\n received_result: false,\n }\n}\n\n/**\n * Convert the CLI's raw usage fields to Fascicle's `UsageTotals` shape.\n *\n * `cache_read_input_tokens` maps to `cached_input_tokens` and\n * `cache_creation_input_tokens` maps to `cache_write_tokens`; both are\n * omitted when the CLI didn't report them.\n *\n * The CLI reports `input_tokens` exclusive of its cache reads and writes, as\n * the Messages API does, while `UsageTotals.input_tokens` is inclusive and\n * cost decomposition subtracts both back out to find the fresh input. So the\n * inclusive total is the sum of all three; a straight copy would leave fresh\n * input with too small a share of a reported cost.\n */\nfunction map_usage(raw: CliUsageRaw | undefined): UsageTotals {\n if (raw === undefined) return { input_tokens: 0, output_tokens: 0 }\n const cache_read = raw.cache_read_input_tokens\n const cache_write = raw.cache_creation_input_tokens\n const out: UsageTotals = {\n input_tokens: (raw.input_tokens ?? 0) + (cache_read ?? 0) + (cache_write ?? 0),\n output_tokens: raw.output_tokens ?? 0,\n }\n if (cache_read !== undefined) out.cached_input_tokens = cache_read\n if (cache_write !== undefined) out.cache_write_tokens = cache_write\n return out\n}\n\n/**\n * Record a line that failed to parse as JSON to the trajectory logger.\n */\nfunction record_parse_error(\n trajectory: TrajectoryLogger | undefined,\n line: string,\n): void {\n trajectory?.record({ kind: 'cli_parse_error', line })\n}\n\n/**\n * Record a parsed-but-unrecognized CLI event to the trajectory logger.\n */\nfunction record_unknown_event(\n trajectory: TrajectoryLogger | undefined,\n raw: unknown,\n): void {\n trajectory?.record({ kind: 'cli_unknown_event', raw })\n}\n\n/**\n * Record the CLI's `system` (session init) event to the trajectory logger.\n */\nfunction record_session_started(\n trajectory: TrajectoryLogger | undefined,\n session_id: string | undefined,\n model: string | undefined,\n): void {\n trajectory?.record({ kind: 'cli_session_started', session_id, model })\n}\n\n/**\n * Record a `rate_limit_event` to the trajectory logger.\n */\nfunction record_rate_limit(\n trajectory: TrajectoryLogger | undefined,\n event: Extract<CliEvent, { type: 'rate_limit_event' }>,\n): void {\n const info = event.rate_limit_info\n trajectory?.record({\n kind: 'cli_rate_limit_event',\n session_id: event.session_id,\n status: info?.status,\n rate_limit_type: info?.rateLimitType,\n resets_at: info?.resetsAt,\n overage_status: info?.overageStatus,\n overage_resets_at: info?.overageResetsAt,\n is_using_overage: info?.isUsingOverage,\n })\n}\n\n/**\n * Push the in-progress turn onto `state.turns` and reset the per-turn\n * accumulators for the next turn.\n */\nfunction flush_turn(state: ParserState): void {\n state.turns.push({\n step_index: state.current_step_index,\n text: state.turn_text,\n tool_calls: state.turn_tool_calls.slice(),\n tool_results: state.turn_tool_results.slice(),\n usage: { ...state.turn_usage },\n })\n state.turn_text = ''\n state.turn_tool_calls = []\n state.turn_tool_results = []\n state.turn_usage = { input_tokens: 0, output_tokens: 0 }\n}\n\n/**\n * Append a `StreamChunk` to the output array and, if the caller passed an\n * `on_chunk` dispatcher, await its delivery too.\n */\nasync function emit_chunk(\n chunks: StreamChunk[],\n dispatch: ((chunk: StreamChunk) => Promise<void>) | undefined,\n chunk: StreamChunk,\n): Promise<void> {\n chunks.push(chunk)\n if (dispatch !== undefined) await dispatch(chunk)\n}\n\n/**\n * Handle one `assistant` event: emit `text`, `tool_call_start`, and\n * `tool_call_end` chunks for its content and accumulate them onto the\n * current turn.\n *\n * An `assistant` event that follows a `user`/tool-result event marks a new\n * turn boundary: it first emits a synthetic `step_finish` chunk for the\n * turn that just ended, flushes that turn onto `state.turns`, and advances\n * `current_step_index`.\n */\nasync function handle_assistant(\n state: ParserState,\n event: Extract<CliEvent, { type: 'assistant' }>,\n chunks: StreamChunk[],\n dispatch: ((chunk: StreamChunk) => Promise<void>) | undefined,\n): Promise<void> {\n if (state.last_event_type === 'user_tool_result') {\n const usage = { ...state.turn_usage }\n await emit_chunk(chunks, dispatch, {\n kind: 'step_finish',\n step_index: state.current_step_index,\n finish_reason: 'tool_calls',\n usage,\n })\n flush_turn(state)\n state.current_step_index += 1\n }\n if (event.error !== undefined) state.api_error = event.error\n\n for (const part of event.message.content) {\n if (part.type === 'text') {\n state.turn_text += part.text\n state.final_text += part.text\n await emit_chunk(chunks, dispatch, {\n kind: 'text',\n text: part.text,\n step_index: state.current_step_index,\n })\n continue\n }\n state.turn_tool_calls.push({ id: part.id, name: part.name, input: part.input })\n await emit_chunk(chunks, dispatch, {\n kind: 'tool_call_start',\n id: part.id,\n name: part.name,\n step_index: state.current_step_index,\n })\n await emit_chunk(chunks, dispatch, {\n kind: 'tool_call_end',\n id: part.id,\n input: part.input,\n step_index: state.current_step_index,\n })\n }\n state.last_event_type = 'assistant'\n}\n\n/**\n * Handle one `user` event: emit a `tool_result` chunk for each tool result\n * in its content and accumulate them onto the current turn.\n */\nasync function handle_user(\n state: ParserState,\n event: Extract<CliEvent, { type: 'user' }>,\n chunks: StreamChunk[],\n dispatch: ((chunk: StreamChunk) => Promise<void>) | undefined,\n): Promise<void> {\n for (const part of event.message.content) {\n if (part.type !== 'tool_result') continue\n const is_err = part.is_error === true\n const stream_chunk: StreamChunk = {\n kind: 'tool_result',\n id: part.tool_use_id,\n step_index: state.current_step_index,\n }\n if (is_err) {\n const content_str =\n typeof part.content === 'string' ? part.content : JSON.stringify(part.content)\n stream_chunk.error = { message: content_str }\n state.turn_tool_results.push({\n id: part.tool_use_id,\n error: { message: content_str },\n })\n } else {\n stream_chunk.output = part.content\n state.turn_tool_results.push({ id: part.tool_use_id, output: part.content })\n }\n await emit_chunk(chunks, dispatch, stream_chunk)\n }\n state.last_event_type = 'user_tool_result'\n}\n\n/**\n * Handle the terminal `result` event: capture the call's session id, cost,\n * wall-clock and API durations, and final usage, flush the last in-progress\n * turn, and emit the closing `finish` chunk.\n *\n * Falls back to `event.result` for `final_text` only when no assistant\n * text was collected during the stream.\n */\nasync function handle_result(\n state: ParserState,\n event: Extract<CliEvent, { type: 'result' }>,\n chunks: StreamChunk[],\n dispatch: ((chunk: StreamChunk) => Promise<void>) | undefined,\n): Promise<void> {\n state.received_result = true\n if (typeof event.session_id === 'string') state.session_id = event.session_id\n if (typeof event.total_cost_usd === 'number') state.total_cost_usd = event.total_cost_usd\n if (typeof event.duration_ms === 'number') state.duration_ms = event.duration_ms\n if (typeof event.duration_api_ms === 'number') state.duration_api_ms = event.duration_api_ms\n if (event.is_error === true) state.is_error = true\n const usage = map_usage(event.usage)\n state.final_usage = usage\n state.turn_usage = { ...usage }\n if (typeof event.result === 'string' && event.result.length > 0) {\n if (state.final_text.length === 0) state.final_text = event.result\n }\n flush_turn(state)\n state.last_event_type = 'result'\n await emit_chunk(chunks, dispatch, {\n kind: 'finish',\n finish_reason: 'stop',\n usage,\n })\n}\n\n/**\n * Dispatch one validated `CliEvent` to its type-specific handler.\n */\nasync function handle_event(\n state: ParserState,\n event: CliEvent,\n chunks: StreamChunk[],\n dispatch: ((chunk: StreamChunk) => Promise<void>) | undefined,\n trajectory: TrajectoryLogger | undefined,\n): Promise<void> {\n switch (event.type) {\n case 'system':\n record_session_started(trajectory, event.session_id, event.model)\n if (typeof event.session_id === 'string' && state.session_id === undefined) {\n state.session_id = event.session_id\n }\n state.last_event_type = 'system'\n return\n case 'assistant':\n await handle_assistant(state, event, chunks, dispatch)\n return\n case 'user':\n await handle_user(state, event, chunks, dispatch)\n return\n case 'result':\n await handle_result(state, event, chunks, dispatch)\n return\n case 'rate_limit_event':\n record_rate_limit(trajectory, event)\n return\n }\n}\n\n/**\n * Parse and handle one line of CLI stdout.\n *\n * Blank lines are skipped. Lines that aren't valid JSON, or that don't\n * match any known event shape, are recorded to the trajectory logger and\n * otherwise ignored; this function never throws.\n */\nasync function consume_line(\n state: ParserState,\n line: string,\n chunks: StreamChunk[],\n dispatch: ((chunk: StreamChunk) => Promise<void>) | undefined,\n trajectory: TrajectoryLogger | undefined,\n): Promise<void> {\n const trimmed = line.trim()\n if (trimmed.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(trimmed)\n } catch {\n record_parse_error(trajectory, line)\n return\n }\n const event = as_event(parsed)\n if (event === undefined) {\n record_unknown_event(trajectory, parsed)\n return\n }\n await handle_event(state, event, chunks, dispatch, trajectory)\n}\n\n/**\n * Append raw stdout text to the parser's line buffer and consume every\n * complete line it now contains.\n *\n * Any trailing partial line (no `\\n` yet) stays buffered for the next\n * call.\n */\nexport async function feed_chunk(\n state: ParserState,\n chunk: string,\n chunks: StreamChunk[],\n dispatch: ((chunk: StreamChunk) => Promise<void>) | undefined,\n trajectory: TrajectoryLogger | undefined,\n): Promise<void> {\n state.buffer += chunk\n let nl_index = state.buffer.indexOf('\\n')\n while (nl_index !== -1) {\n const line = state.buffer.slice(0, nl_index)\n state.buffer = state.buffer.slice(nl_index + 1)\n await consume_line(state, line, chunks, dispatch, trajectory)\n nl_index = state.buffer.indexOf('\\n')\n }\n}\n\n/**\n * Consume a final buffered line that has no trailing newline.\n *\n * `feed_chunk` only parses complete `\\n`-terminated lines, so a trailing\n * unterminated fragment stays in the buffer until the caller knows the\n * stream has actually ended. Call this once, after the last `feed_chunk`,\n * to parse that fragment as one last line.\n */\nexport async function flush_remaining(\n state: ParserState,\n chunks: StreamChunk[],\n dispatch: ((chunk: StreamChunk) => Promise<void>) | undefined,\n trajectory: TrajectoryLogger | undefined,\n): Promise<void> {\n if (state.buffer.length === 0) return\n const line = state.buffer\n state.buffer = ''\n await consume_line(state, line, chunks, dispatch, trajectory)\n}\n\n/**\n * Take an immutable copy of the parser state's accumulated results as a\n * `ParsedStream`.\n */\nexport function snapshot(state: ParserState): ParsedStream {\n const base: {\n final_text: string\n final_usage: UsageTotals\n turns: ReadonlyArray<TurnCollected>\n is_error: boolean\n received_result: boolean\n session_id?: string\n total_cost_usd?: number\n duration_ms?: number\n duration_api_ms?: number\n api_error?: string\n } = {\n final_text: state.final_text,\n final_usage: { ...state.final_usage },\n turns: state.turns.slice(),\n is_error: state.is_error,\n received_result: state.received_result,\n }\n if (state.session_id !== undefined) base.session_id = state.session_id\n if (state.total_cost_usd !== undefined) base.total_cost_usd = state.total_cost_usd\n if (state.duration_ms !== undefined) base.duration_ms = state.duration_ms\n if (state.duration_api_ms !== undefined) base.duration_api_ms = state.duration_api_ms\n if (state.api_error !== undefined) base.api_error = state.api_error\n return base\n}\n","/**\n * Cost allocation from the CLI's reported `total_cost_usd`.\n *\n * The CLI reports a single total_cost_usd and per-turn usage; it does not\n * break cost down by component or by turn. This module splits the total\n * across turns proportional to each turn's output tokens, then hands each\n * turn's share to the engine's `decompose_total_cost` for the component\n * split. Sum equality is preserved exactly by giving any floating-point\n * rounding remainder to the last turn.\n */\n\nimport { decompose_total_cost } from '../../pricing.js'\nimport type { CostBreakdown, UsageTotals } from '../../types.js'\n\nexport type TurnUsage = {\n readonly output_tokens: number\n readonly usage: UsageTotals\n}\n\n/**\n * Split a run-level `total` into a per-turn share for each turn, proportional\n * to its output tokens, falling back to an equal split when every turn reports\n * zero output (the proportional weights would otherwise all be zero). The last\n * turn absorbs the floating-point rounding remainder so the shares sum exactly\n * to `total`. Caller guarantees a non-empty `turns`.\n *\n * The CLI reports cost and API time for the whole run only, and both go\n * through this one split so a step's share of each stays consistent.\n */\nexport function split_total_across_turns(\n total: number,\n turns: ReadonlyArray<Pick<TurnUsage, 'output_tokens'>>,\n): number[] {\n const total_output = turns.reduce((sum, t) => sum + Math.max(0, t.output_tokens), 0)\n const per_turn = turns.map((t) =>\n total_output === 0\n ? total / turns.length\n : total * (Math.max(0, t.output_tokens) / total_output),\n )\n\n const assigned = per_turn.reduce((a, b) => a + b, 0)\n const last_index = turns.length - 1\n per_turn[last_index] = (per_turn[last_index] ?? 0) + (total - assigned)\n return per_turn\n}\n\n/**\n * Split a call's total cost across its turns, proportional to each turn's\n * output tokens, then decompose each turn's share into a `CostBreakdown`.\n *\n * Falls back to an equal split when every turn reports zero output tokens\n * (the proportional weights would otherwise all be zero). The last turn\n * absorbs the floating-point rounding remainder so the per-turn totals sum\n * exactly to `total_cost_usd`.\n */\nexport function allocate_cost_across_turns(\n total_cost_usd: number,\n turns: ReadonlyArray<TurnUsage>,\n): ReadonlyArray<CostBreakdown> {\n if (turns.length === 0) return []\n const per_turn = split_total_across_turns(total_cost_usd, turns)\n return turns.map((t, i) => decompose_total_cost(per_turn[i] ?? 0, t.usage))\n}\n","/**\n * Build a GenerateResult from a parsed CLI stream.\n *\n * Given a completed ParsedStream and the call's resolved model, this module\n * synthesizes:\n * - per-turn StepRecord entries with output-weighted cost\n * - aggregate GenerateResult with CLI-reported total_cost_usd\n * - per-turn blended StepTiming from the CLI-reported duration_api_ms\n * - provider_reported.claude_cli with session_id + duration_ms (and\n * duration_api_ms when reported)\n *\n * When no turns were collected (a `result` event arrived without any\n * assistant messages), the adapter synthesizes a single step whose text\n * equals the `result.result` field and whose usage equals the top-level\n * usage.\n */\n\nimport type { ToolSchema } from '#schema'\nimport type {\n ResolvedModel,\n CostBreakdown,\n FinishReason,\n GenerateResult,\n StepRecord,\n StepTiming,\n ToolCallRecord,\n UsageTotals,\n} from '../../types.js'\nimport type { ClaudeCliProviderReported } from './types.js'\nimport type { ParsedStream, TurnCollected } from './stream_parse.js'\nimport { allocate_cost_across_turns, split_total_across_turns, type TurnUsage } from './cost.js'\nimport { claude_cli_error } from '../../errors.js'\n\n/**\n * Sum a list of per-turn `UsageTotals` into one aggregate total.\n *\n * Optional fields (`cached_input_tokens`, `cache_write_tokens`,\n * `reasoning_tokens`) are included in the sum only when at least one input\n * reports them, so the aggregate omits a field entirely rather than\n * reporting a false zero.\n */\nfunction sum_usage(totals: ReadonlyArray<UsageTotals>): UsageTotals {\n let input = 0\n let output = 0\n let cached: number | undefined\n let cache_write: number | undefined\n let reasoning: number | undefined\n for (const u of totals) {\n input += u.input_tokens\n output += u.output_tokens\n if (u.cached_input_tokens !== undefined) cached = (cached ?? 0) + u.cached_input_tokens\n if (u.cache_write_tokens !== undefined) cache_write = (cache_write ?? 0) + u.cache_write_tokens\n if (u.reasoning_tokens !== undefined) reasoning = (reasoning ?? 0) + u.reasoning_tokens\n }\n const out: UsageTotals = { input_tokens: input, output_tokens: output }\n if (cached !== undefined) out.cached_input_tokens = cached\n if (cache_write !== undefined) out.cache_write_tokens = cache_write\n if (reasoning !== undefined) out.reasoning_tokens = reasoning\n return out\n}\n\n/**\n * Sum a list of per-turn `CostBreakdown`s into one aggregate breakdown.\n *\n * Returns `undefined` for an empty list. Optional cache fields are\n * included only when at least one input breakdown reports them.\n */\nfunction aggregate_cost_breakdowns(\n breakdowns: ReadonlyArray<CostBreakdown>,\n): CostBreakdown | undefined {\n if (breakdowns.length === 0) return undefined\n let total = 0\n let input = 0\n let output = 0\n let cached_present = false\n let cached = 0\n let cache_write_present = false\n let cache_write = 0\n for (const b of breakdowns) {\n total += b.total_usd\n input += b.input_usd\n output += b.output_usd\n if (b.cached_input_usd !== undefined) {\n cached_present = true\n cached += b.cached_input_usd\n }\n if (b.cache_write_usd !== undefined) {\n cache_write_present = true\n cache_write += b.cache_write_usd\n }\n }\n const agg: CostBreakdown = {\n total_usd: total,\n input_usd: input,\n output_usd: output,\n currency: 'USD',\n is_estimate: true,\n }\n if (cached_present) agg.cached_input_usd = cached\n if (cache_write_present) agg.cache_write_usd = cache_write\n return agg\n}\n\n/**\n * Return the parsed stream's collected turns, or synthesize a single turn\n * from the top-level result when none were collected.\n *\n * A `result` event with no preceding `assistant` events (an immediate\n * error, or a response with no visible turns) leaves `parsed.turns` empty;\n * this keeps `build_generate_result` from having to special-case that.\n */\nfunction normalize_turns(parsed: ParsedStream): ReadonlyArray<TurnCollected> {\n if (parsed.turns.length > 0) return parsed.turns\n const synth: TurnCollected = {\n step_index: 0,\n text: parsed.final_text,\n tool_calls: [],\n tool_results: [],\n usage: parsed.final_usage,\n }\n return [synth]\n}\n\n/**\n * Build a `ToolCallRecord` for one tool call, attaching its matching\n * result (output or error) when present.\n *\n * `duration_ms` is always 0: the CLI's stream-json events don't report\n * per-tool-call timing, so there's nothing to measure it against.\n */\nfunction tool_call_record(\n call: { id: string; name: string; input: unknown },\n results: ReadonlyArray<{\n id: string\n output?: unknown\n error?: { message: string }\n }>,\n now: number,\n): ToolCallRecord {\n const rec: ToolCallRecord = {\n id: call.id,\n name: call.name,\n input: call.input,\n duration_ms: 0,\n started_at: now,\n }\n const matched = results.find((r) => r.id === call.id)\n if (matched !== undefined) {\n if (matched.output !== undefined) rec.output = matched.output\n if (matched.error !== undefined) rec.error = matched.error\n }\n return rec\n}\n\n/**\n * Build each step's blended StepTiming from the run's reported API time.\n *\n * The CLI reports how long the whole run spent in API requests, not how long\n * each turn did, so each step gets its output-weighted share of\n * `duration_api_ms` in whole milliseconds (the last step absorbs the\n * remainder, so the windows sum to the reported figure), laid end to end\n * from the run's start. That start is `now`, when the result arrived, less\n * the CLI's own wall clock. No step carries `first_chunk_ms`, so\n * `throughput()` reads every window as blended. Returns undefined when the\n * CLI did not report `duration_api_ms`.\n */\nfunction blended_step_timings(\n parsed: ParsedStream,\n turn_usages: ReadonlyArray<TurnUsage>,\n now: number,\n): ReadonlyArray<StepTiming> | undefined {\n const api_ms = parsed.duration_api_ms\n if (api_ms === undefined) return undefined\n const shares = split_total_across_turns(api_ms, turn_usages)\n const last_index = shares.length - 1\n let assigned = 0\n let cursor = now - (parsed.duration_ms ?? api_ms)\n return shares.map((share, i) => {\n const duration_ms = i === last_index ? api_ms - assigned : Math.floor(share)\n assigned += duration_ms\n const timing: StepTiming = { started_at: cursor, duration_ms }\n cursor += duration_ms\n return timing\n })\n}\n\nexport type BuildResultInput<T> = {\n readonly parsed: ParsedStream\n readonly resolved: ResolvedModel\n readonly schema?: ToolSchema<T>\n readonly parsed_content?: T\n}\n\n/**\n * Assemble a `GenerateResult<T>` from a parsed CLI stream.\n *\n * Throws a `claude_cli_error` instead of returning when the CLI reported\n * an error result, since `FinishReason` has no `'error'` member and\n * returning `finish_reason: 'stop'` would make the failure look like a\n * successful call.\n */\nexport function build_generate_result<T>(input: BuildResultInput<T>): GenerateResult<T> {\n const { parsed, resolved } = input\n\n // An is_error result is a failed turn, not a clean stop. Returning it with\n // finish_reason 'stop' would make a CLI-side error look like success; throw\n // instead so the caller sees the failure. FinishReason has no 'error' member.\n if (parsed.is_error) {\n throw new claude_cli_error(\n 'result_error',\n parsed.final_text.length > 0\n ? parsed.final_text\n : 'claude_cli returned an error result',\n )\n }\n\n const turns = normalize_turns(parsed)\n const now = Date.now()\n\n const turn_usages: TurnUsage[] = turns.map((t) => ({\n output_tokens: t.usage.output_tokens,\n usage: t.usage,\n }))\n\n const total_cost_usd = parsed.total_cost_usd ?? 0\n const has_cost = parsed.total_cost_usd !== undefined\n const cost_per_turn: ReadonlyArray<CostBreakdown> = has_cost\n ? allocate_cost_across_turns(total_cost_usd, turn_usages)\n : []\n\n const step_timings = blended_step_timings(parsed, turn_usages, now)\n\n const finish_reason: FinishReason = 'stop'\n\n const steps: StepRecord[] = []\n const tool_calls_accum: ToolCallRecord[] = []\n turns.forEach((turn, i) => {\n const step_tool_calls: ToolCallRecord[] = turn.tool_calls.map((call) =>\n tool_call_record(call, turn.tool_results, now),\n )\n for (const tc of step_tool_calls) tool_calls_accum.push(tc)\n const record: StepRecord = {\n index: turn.step_index,\n text: turn.text,\n tool_calls: step_tool_calls,\n usage: turn.usage,\n finish_reason: i === turns.length - 1 ? finish_reason : 'tool_calls',\n }\n if (has_cost) {\n const cost = cost_per_turn[i]\n if (cost !== undefined) record.cost = cost\n }\n const timing = step_timings?.[i]\n if (timing !== undefined) record.timing = timing\n steps.push(record)\n })\n\n const total_usage = sum_usage(steps.map((s) => s.usage))\n const total_cost = has_cost ? aggregate_cost_breakdowns(cost_per_turn) : undefined\n\n const provider_reported: Record<string, unknown> = {}\n if (parsed.session_id !== undefined || parsed.duration_ms !== undefined) {\n const reported: ClaudeCliProviderReported = {\n session_id: parsed.session_id ?? '',\n duration_ms: parsed.duration_ms ?? 0,\n ...(parsed.duration_api_ms !== undefined ? { duration_api_ms: parsed.duration_api_ms } : {}),\n }\n provider_reported['claude_cli'] = reported\n }\n\n // A schema's value is the content even when it parses to `null`, so the\n // final text stands in only for a call that asked for no structure.\n const content_raw =\n input.schema === undefined\n ? // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n (parsed.final_text as T)\n : // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n (input.parsed_content as T)\n\n const result: GenerateResult<T> = {\n content: content_raw,\n tool_calls: tool_calls_accum,\n steps,\n usage: total_usage,\n finish_reason,\n model_resolved: { provider: resolved.provider, model_id: resolved.model_id },\n }\n if (total_cost !== undefined) result.cost = total_cost\n if (Object.keys(provider_reported).length > 0) {\n result.provider_reported = provider_reported\n }\n return result\n}\n","/**\n * Schema parse and repair helpers.\n *\n * The tool-loop / generate orchestrator owns the repair loop itself (counting\n * attempts toward `max_steps`, re-dispatching through the provider). This\n * module exposes only the parse primitive and the canonical repair-prompt\n * shape.\n */\n\nimport { format_schema_issues, validate_schema, type AnySchema, type SchemaIssue } from '#schema'\nimport type { Message } from './types.js'\nimport { schema_validation_error } from './errors.js'\n\nexport type ParseOutcome<t> =\n | { ok: true; value: t }\n | { ok: false; issues: ReadonlyArray<SchemaIssue> }\n\n/**\n * Attempt to parse `text` as JSON and validate it with `schema`. Returns a\n * tagged union; the caller decides whether to escalate to repair, throw, or\n * surface the failure.\n *\n * Even with --json-schema enforcement, models occasionally wrap structured\n * output in markdown fences and surrounding prose. We try a sequence of\n * candidates in increasing leniency: the trimmed text as-is, every fenced\n * block in the text, and the outermost {…} / […] slice. The first candidate\n * that both parses as JSON and matches the schema wins.\n *\n * When every candidate fails, we prefer the schema-validation issues from the\n * FIRST candidate that parsed as JSON: those issues reflect the model's\n * primary output and are what a repair prompt should feed back. Later\n * candidates (for example, the bracket-slice fallback) often produce noisy issues\n * like \"expected object, received array\" that misdirect the model. Only when\n * NO candidate parses as JSON do we surface the JSON parse error.\n *\n * Async because Standard Schema permits a vendor's `validate` to return a\n * promise; the ripple stops at generate.ts and the claude_cli adapter, both of\n * which already await their surrounding work.\n */\nexport async function parse_with_schema<t>(\n schema: AnySchema<t>,\n text: string,\n): Promise<ParseOutcome<t>> {\n const candidates = json_candidates(text)\n let json_parse_issues: ReadonlyArray<SchemaIssue> = [\n { message: 'No JSON-parseable content found in model output' },\n ]\n let first_schema_issues: ReadonlyArray<SchemaIssue> | undefined\n for (const candidate of candidates) {\n let parsed: unknown\n try {\n parsed = JSON.parse(candidate)\n } catch (err: unknown) {\n json_parse_issues = [{ message: err instanceof Error ? err.message : String(err) }]\n continue\n }\n const result = await validate_schema(schema, parsed)\n if (result.ok) return { ok: true, value: result.value }\n first_schema_issues ??= result.issues\n }\n return { ok: false, issues: first_schema_issues ?? json_parse_issues }\n}\n\nconst FENCE_BLOCK = /```(?:[\\w-]*)\\s*\\n?([\\s\\S]*?)\\n?```/g\n\n/**\n * Generate JSON substrings to try parsing, from strictest to most lenient:\n * the trimmed text as-is, the body of every fenced code block, and the\n * outermost `{...}` and `[...]` slices. Duplicate candidates are dropped.\n */\nfunction json_candidates(text: string): string[] {\n const candidates: string[] = []\n const seen = new Set<string>()\n const push = (s: string): void => {\n const trimmed = s.trim()\n if (trimmed.length === 0 || seen.has(trimmed)) return\n seen.add(trimmed)\n candidates.push(trimmed)\n }\n push(text)\n for (const match of text.matchAll(FENCE_BLOCK)) {\n const body = match[1]\n if (body !== undefined) push(body)\n }\n push(slice_outermost(text, '{', '}'))\n push(slice_outermost(text, '[', ']'))\n return candidates\n}\n\n/**\n * Slice `text` from its first `open` character through its last matching\n * `close` character, inclusive. Returns an empty string if `open` is absent\n * or `close` does not appear after it.\n */\nfunction slice_outermost(text: string, open: string, close: string): string {\n const first = text.indexOf(open)\n const last = text.lastIndexOf(close)\n if (first === -1 || last <= first) return ''\n return text.slice(first, last + 1)\n}\n\n/**\n * Build the canonical repair message appended after a schema parse failure.\n *\n * The wording is fixed rather than adapter-specific, so the repair prompt\n * stays predictable and is easy to read back from trajectory output.\n */\nexport function build_repair_message(issues: ReadonlyArray<SchemaIssue>): Message {\n return { role: 'user', content: build_repair_prompt_text(issues) }\n}\n\n/**\n * String form of the repair prompt for transports (subprocess CLIs) that take\n * a single stdin string rather than a Message. Same wording as\n * build_repair_message so the on-wire instruction is identical across providers.\n */\nexport function build_repair_prompt_text(issues: ReadonlyArray<SchemaIssue>): string {\n const serialized = format_schema_issues(issues)\n return (\n `Your previous response did not match the expected schema. Error: ${serialized}. ` +\n 'Please provide a corrected response that strictly conforms to the schema. ' +\n 'Return ONLY the JSON value: no markdown code fences, no surrounding prose, no commentary.'\n )\n}\n\n/**\n * Throw schema_validation_error carrying the schema issues and the raw model text.\n * Called by the orchestrator when all repair attempts are exhausted.\n */\nexport function throw_schema_validation(\n issues: ReadonlyArray<SchemaIssue>,\n raw_text: string,\n): never {\n throw new schema_validation_error(\n `schema validation failed: ${format_schema_issues(issues)}`,\n issues,\n raw_text,\n )\n}\n","/**\n * Trajectory span and record helpers for the engine.\n *\n * When a TrajectoryLogger is supplied to generate, these helpers emit the\n * engine's event vocabulary. When it is undefined, every helper is a no-op,\n * so call sites never need to branch on whether tracing is on. The tool loop\n * drives span lifecycle; these helpers capture the event shape and keep\n * dispatch consistent.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport type {\n CostBreakdown,\n FinishReason,\n SalvageFormat,\n StepTiming,\n UsageTotals,\n} from './types.js'\nimport type { RetryAttemptInfo } from './retry.js'\n\nexport type GenerateSpanStartMeta = {\n model: string\n provider: string\n model_id: string\n has_tools: boolean\n has_schema: boolean\n streaming: boolean\n}\n\n/**\n * Open the `engine.generate` span that brackets one whole generate call.\n */\nexport function start_generate_span(\n trajectory: TrajectoryLogger | undefined,\n meta: GenerateSpanStartMeta,\n): string | undefined {\n if (trajectory === undefined) return undefined\n return trajectory.start_span('engine.generate', { ...meta })\n}\n\n/**\n * Close the `engine.generate` span with usage, finish reason, resolved model,\n * or the error message on failure. `step_count` and `tool_call_count` are the\n * call-level totals (model turns and tool executions in the call), the\n * span-attribute analog of the GenAI semconv agent metrics\n * `inference_calls` / `tool_calls`.\n */\nexport function end_generate_span(\n trajectory: TrajectoryLogger | undefined,\n span_id: string | undefined,\n meta: {\n usage?: UsageTotals\n finish_reason?: FinishReason\n model_resolved?: { provider: string; model_id: string }\n step_count?: number\n tool_call_count?: number\n error?: string\n },\n): void {\n if (trajectory === undefined || span_id === undefined) return\n trajectory.end_span(span_id, { ...meta })\n}\n\n/**\n * Open an `engine.generate.step` span for one model turn in the tool loop.\n */\nexport function start_step_span(\n trajectory: TrajectoryLogger | undefined,\n index: number,\n): string | undefined {\n if (trajectory === undefined) return undefined\n return trajectory.start_span('engine.generate.step', { index })\n}\n\n/**\n * Close an `engine.generate.step` span with per-step usage or error.\n */\nexport function end_step_span(\n trajectory: TrajectoryLogger | undefined,\n span_id: string | undefined,\n meta: { usage?: UsageTotals; finish_reason?: FinishReason; error?: string },\n): void {\n if (trajectory === undefined || span_id === undefined) return\n trajectory.end_span(span_id, { ...meta })\n}\n\n/**\n * Record that a provider request went out, with an optional prompt-token\n * estimate for providers that report one before the response arrives.\n */\nexport function record_request_sent(\n trajectory: TrajectoryLogger | undefined,\n step_index: number,\n prompt_tokens_estimated: number | undefined,\n): void {\n if (trajectory === undefined) return\n const event: Record<string, unknown> = {\n kind: 'request_sent',\n step_index,\n }\n if (prompt_tokens_estimated !== undefined) {\n event['prompt_tokens_estimated'] = prompt_tokens_estimated\n }\n trajectory.record({ kind: 'request_sent', ...event })\n}\n\n/**\n * Record a provider response: finish reason, flat token counts, and the\n * engine-measured turn timing when the turn carried one.\n *\n * Every field is a flat number or string on purpose. An OTel span event or a\n * log pipeline can aggregate `input_tokens` / `duration_ms` /\n * `first_chunk_ms` directly, where a nested usage object would arrive as an\n * opaque JSON string. This is the one per-turn event a metrics dashboard\n * needs: tokens by direction, the cache and reasoning splits when the\n * provider reports them, and the model-only latency window.\n */\nexport function record_response_received(\n trajectory: TrajectoryLogger | undefined,\n step_index: number,\n turn: {\n usage: UsageTotals\n finish_reason: FinishReason\n timing?: StepTiming | undefined\n },\n span_id?: string,\n): void {\n if (trajectory === undefined) return\n const { usage, timing } = turn\n const event: Record<string, unknown> = {\n kind: 'response_received',\n step_index,\n input_tokens: usage.input_tokens,\n output_tokens: usage.output_tokens,\n finish_reason: turn.finish_reason,\n }\n if (span_id !== undefined) event['span_id'] = span_id\n if (usage.reasoning_tokens !== undefined) event['reasoning_tokens'] = usage.reasoning_tokens\n if (usage.cached_input_tokens !== undefined) {\n event['cached_input_tokens'] = usage.cached_input_tokens\n }\n if (usage.cache_write_tokens !== undefined) {\n event['cache_write_tokens'] = usage.cache_write_tokens\n }\n if (timing !== undefined) {\n event['started_at'] = timing.started_at\n event['duration_ms'] = timing.duration_ms\n if (timing.first_chunk_ms !== undefined) event['first_chunk_ms'] = timing.first_chunk_ms\n }\n trajectory.record({ kind: 'response_received', ...event })\n}\n\n/**\n * Record one failed-then-retried provider attempt as a `turn_retry` event:\n * the 1-based attempt count, the classified failure kind, the backoff this\n * retry waits, and the HTTP status / `Retry-After` when the failure carried\n * them. This is the event a rate-limit or error-budget dashboard counts;\n * without it, only the final exhaustion is visible (as a span error), and\n * every absorbed 429 or 5xx goes unrecorded.\n */\nexport function record_turn_retry(\n trajectory: TrajectoryLogger | undefined,\n step_index: number,\n info: RetryAttemptInfo,\n span_id?: string,\n): void {\n if (trajectory === undefined) return\n const event: Record<string, unknown> = {\n kind: 'turn_retry',\n step_index,\n attempt: info.attempt,\n failure_kind: info.failure_kind,\n delay_ms: info.delay_ms,\n }\n if (span_id !== undefined) event['span_id'] = span_id\n if (info.status !== undefined) event['status'] = info.status\n if (info.retry_after_ms !== undefined) event['retry_after_ms'] = info.retry_after_ms\n trajectory.record({ kind: 'turn_retry', ...event })\n}\n\nexport type ToolCallRecordEvent = {\n step_index: number\n name: string\n tool_call_id: string\n input: unknown\n duration_ms: number\n error?: { message: string }\n}\n\n/**\n * Record a tool invocation request: name, call id, input, and duration.\n */\nexport function record_tool_call(\n trajectory: TrajectoryLogger | undefined,\n meta: ToolCallRecordEvent,\n): void {\n if (trajectory === undefined) return\n const event: Record<string, unknown> = {\n kind: 'tool_call',\n step_index: meta.step_index,\n name: meta.name,\n tool_call_id: meta.tool_call_id,\n input: meta.input,\n duration_ms: meta.duration_ms,\n }\n if (meta.error !== undefined) event['error'] = meta.error\n trajectory.record({ kind: 'tool_call', ...event })\n}\n\nexport type ToolResultRecordEvent = {\n step_index: number\n name: string\n tool_call_id: string\n duration_ms: number\n output?: unknown\n error?: { message: string }\n}\n\n/**\n * Record a resolved tool call's result. `record_tool_call` captures the request\n * (input); without this event a successful tool's output never reaches the\n * trajectory, leaving the run record blind to what tools actually returned.\n */\nexport function record_tool_result(\n trajectory: TrajectoryLogger | undefined,\n meta: ToolResultRecordEvent,\n): void {\n if (trajectory === undefined) return\n const event: Record<string, unknown> = {\n kind: 'tool_result',\n step_index: meta.step_index,\n name: meta.name,\n tool_call_id: meta.tool_call_id,\n duration_ms: meta.duration_ms,\n }\n if (meta.error !== undefined) event['error'] = meta.error\n else event['output'] = meta.output\n trajectory.record({ kind: 'tool_result', ...event })\n}\n\n/**\n * Add a `ts` (epoch milliseconds) to span meta unless one is already set.\n */\nfunction stamp_ts(meta: Record<string, unknown> | undefined): Record<string, unknown> {\n const out: Record<string, unknown> = { ...meta }\n if (!('ts' in out)) out['ts'] = Date.now()\n return out\n}\n\n/**\n * Wrap a logger so engine events carry a `ts` (epoch milliseconds) even when\n * generate is called directly with a caller-supplied logger rather than\n * through the core runner. When the logger is already runner-decorated, the\n * existing `ts` is preserved.\n */\nexport function with_timestamps(\n inner: TrajectoryLogger | undefined,\n): TrajectoryLogger | undefined {\n if (inner === undefined) return undefined\n return {\n record: (event) => {\n if ('ts' in event) {\n inner.record(event)\n return\n }\n inner.record({ ...event, ts: Date.now() })\n },\n start_span: (name, meta) => inner.start_span(name, stamp_ts(meta)),\n end_span: (id, meta) => {\n inner.end_span(id, stamp_ts(meta))\n },\n }\n}\n\nexport type CostEventSource = 'engine_derived' | 'provider_reported'\n\n/**\n * Record a per-step cost breakdown, tagged with whether the engine derived it\n * from pricing tables or the provider reported it directly.\n *\n * `span_id` is the enclosing `engine.generate.step` span when the tool loop\n * emits, so a consumer attributes cost to its exact turn instead of guessing\n * from an open-span stack (which mis-attributes under `parallel`). It stays\n * optional so paths without that span in hand (a provider-reported CLI cost)\n * emit unattributed and legibly so.\n */\nexport function record_cost(\n trajectory: TrajectoryLogger | undefined,\n step_index: number,\n cost: CostBreakdown,\n source: CostEventSource,\n span_id?: string,\n): void {\n if (trajectory === undefined) return\n const event: Record<string, unknown> = {\n kind: 'cost',\n step_index,\n source,\n total_usd: cost.total_usd,\n input_usd: cost.input_usd,\n output_usd: cost.output_usd,\n }\n if (span_id !== undefined) event['span_id'] = span_id\n if (cost.cached_input_usd !== undefined) event['cached_input_usd'] = cost.cached_input_usd\n if (cost.cache_write_usd !== undefined) event['cache_write_usd'] = cost.cache_write_usd\n if (cost.reasoning_usd !== undefined) event['reasoning_usd'] = cost.reasoning_usd\n trajectory.record({ kind: 'cost', ...event })\n}\n\n/**\n * Deduplication helper for `pricing_missing`. The event fires at most once\n * per generate call per {provider, model_id}. Callers thread a single\n * instance through the per-call orchestration.\n */\nexport type PricingMissingDedup = {\n emit: (provider: string, model_id: string) => void\n}\n\n/**\n * Build the per-call dedup that emits `pricing_missing` once per model.\n */\nexport function create_pricing_missing_dedup(\n trajectory: TrajectoryLogger | undefined,\n): PricingMissingDedup {\n const seen = new Set<string>()\n return {\n emit(provider: string, model_id: string): void {\n if (trajectory === undefined) return\n const key = `${provider}:${model_id}`\n if (seen.has(key)) return\n seen.add(key)\n trajectory.record({ kind: 'pricing_missing', provider, model_id })\n },\n }\n}\n\n/**\n * Record that a requested reasoning-effort setting was ignored because the\n * model does not support it.\n */\nexport function record_effort_ignored(\n trajectory: TrajectoryLogger | undefined,\n model_id: string,\n): void {\n if (trajectory === undefined) return\n trajectory.record({ kind: 'effort_ignored', model_id })\n}\n\nexport type SchemaValidationFailedAttempt = 'initial' | 'repair'\n\nexport type SchemaValidationFailedEvent = {\n attempt: SchemaValidationFailedAttempt\n schema_issues: string\n raw_text: string\n}\n\n/**\n * Emit a structured event when a schema-driven generate call returns text\n * that fails parse + schema validation. Persists the raw model output and a\n * formatted schema issues summary to the trajectory so the failure is\n * debuggable without needing stdout.\n */\nexport function record_schema_validation_failed(\n trajectory: TrajectoryLogger | undefined,\n meta: SchemaValidationFailedEvent,\n): void {\n if (trajectory === undefined) return\n trajectory.record({\n kind: 'schema_validation_failed',\n attempt: meta.attempt,\n schema_issues: meta.schema_issues,\n raw_text: meta.raw_text,\n })\n}\n\nexport type SalvagedCallEventEntry = {\n tool_call_id: string\n name: string\n format: SalvageFormat\n}\n\n/**\n * Emitted once per step whose tool calls were recovered from assistant text\n * rather than returned structurally (tool_call_repair_attempts). The per-call\n * tool_call/tool_result events still fire for each salvaged call; this event\n * answers why the step has calls the provider never emitted, and persists the\n * raw text for debugging (precedent: schema_validation_failed).\n */\nexport function record_tool_call_salvaged(\n trajectory: TrajectoryLogger | undefined,\n meta: {\n step_index: number\n calls: ReadonlyArray<SalvagedCallEventEntry>\n raw_text: string\n },\n): void {\n if (trajectory === undefined) return\n trajectory.record({\n kind: 'tool_call_salvaged',\n step_index: meta.step_index,\n calls: meta.calls,\n raw_text: meta.raw_text,\n })\n}\n\n/**\n * Emitted when max_tool_calls_per_step drops calls beyond the cap. Dropped\n * calls also get ToolCallRecords with an error, but only this event carries\n * the configured cap alongside what was kept.\n */\nexport function record_tool_calls_dropped(\n trajectory: TrajectoryLogger | undefined,\n meta: {\n step_index: number\n max_tool_calls_per_step: number\n kept: number\n dropped: ReadonlyArray<{ tool_call_id: string; name: string }>\n },\n): void {\n if (trajectory === undefined) return\n trajectory.record({\n kind: 'tool_calls_dropped',\n step_index: meta.step_index,\n max_tool_calls_per_step: meta.max_tool_calls_per_step,\n kept: meta.kept,\n dropped: meta.dropped,\n })\n}\n\nexport type ToolApprovalEventKind =\n | 'tool_approval_requested'\n | 'tool_approval_granted'\n | 'tool_approval_denied'\n\n/**\n * Record one stage of the tool-approval handshake (requested, granted, or\n * denied) for a specific tool call.\n */\nexport function record_tool_approval(\n trajectory: TrajectoryLogger | undefined,\n kind: ToolApprovalEventKind,\n meta: { tool_name: string; step_index: number; tool_call_id: string },\n): void {\n if (trajectory === undefined) return\n trajectory.record({\n kind,\n tool_name: meta.tool_name,\n step_index: meta.step_index,\n tool_call_id: meta.tool_call_id,\n })\n}\n\n/**\n * Deduplication helper for `option_ignored`. The event fires at most once per\n * generate call per option key. External adapters whose transports do not\n * honor a caller-supplied option (max_steps, tool_error_policy,\n * on_tool_approval) route the emit through this dedup.\n */\nexport type OptionIgnoredDedup = {\n emit: (option: string, provider: string) => void\n}\n\n/**\n * Build the per-call dedup that emits `option_ignored` once per option key.\n */\nexport function create_option_ignored_dedup(\n trajectory: TrajectoryLogger | undefined,\n): OptionIgnoredDedup {\n const seen = new Set<string>()\n return {\n emit(option: string, provider: string): void {\n if (trajectory === undefined) return\n if (seen.has(option)) return\n seen.add(option)\n trajectory.record({ kind: 'option_ignored', option, provider })\n },\n }\n}\n","/**\n * claude_cli adapter factory.\n *\n * Exports a `create_claude_cli_adapter(init)` factory that returns a\n * `ExternalAgentAdapter`. The factory closure-captures a per-instance\n * `spawn_runtime` (which owns its own `Set<ChildProcess>` live registry), so\n * two factory invocations produce two independent registries; no state is\n * shared at module scope.\n *\n * The returned adapter exposes exactly `{ kind: 'external', name, generate,\n * dispose, supports }`, with no `build_model`, `translate_effort`, or\n * `normalize_usage` members.\n */\n\nimport { to_json_schema, type ToolSchema } from '#schema'\nimport type {\n ResolvedModel,\n EffortLevel,\n GenerateOptions,\n GenerateResult,\n Message,\n ProviderInit,\n StepRecord,\n StreamChunk,\n Tool,\n} from '../../types.js'\nimport type {\n ProviderCapability,\n ExternalAgentAdapter,\n} from '../types.js'\nimport type {\n ClaudeCliCallOptions,\n ClaudeCliProviderConfig,\n ToolBridgeMode,\n} from './types.js'\nimport {\n build_env,\n stderr_is_auth_failure,\n validate_auth_config,\n} from './auth.js'\nimport {\n build_cli_argv,\n merge_allowed_tools,\n merge_system,\n} from './argv.js'\nimport { build_sandbox_plan } from './sandbox.js'\nimport { create_spawn_runtime } from './spawn.js'\nimport {\n create_parser_state,\n feed_chunk,\n flush_remaining,\n snapshot,\n type ParsedStream,\n} from './stream_parse.js'\nimport { build_generate_result } from './stream_result.js'\nimport {\n CLI_AUTH_FAILED_ERROR,\n CLI_BINARY_DEFAULT,\n DEFAULT_STALL_TIMEOUT_MS,\n DEFAULT_STARTUP_TIMEOUT_MS,\n} from './constants.js'\nimport {\n aborted_error,\n claude_cli_error,\n engine_disposed_error,\n provider_auth_error,\n provider_capability_error,\n schema_validation_error,\n} from '../../errors.js'\nimport { format_schema_issues } from '#schema'\nimport {\n build_repair_prompt_text,\n parse_with_schema,\n} from '../../schema.js'\nimport {\n create_option_ignored_dedup,\n end_generate_span,\n end_step_span,\n record_cost,\n record_schema_validation_failed,\n start_generate_span,\n start_step_span,\n with_timestamps,\n} from '../../trajectory.js'\n\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set<ProviderCapability>([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n 'reasoning',\n])\n\nconst PROVIDER_NAME = 'claude_cli'\n\n// bubblewrap reports a failed exec of its target as\n// `bwrap: execvp <target>: <strerror>`, and the target is always the claude\n// binary, since the sandbox plan puts it right after `--`.\nconst BWRAP_EXEC_MISSING = /^bwrap: execvp (.+): No such file or directory$/m\n\n// Map Fascicle's EffortLevel to Claude Code's CLAUDE_CODE_EFFORT_LEVEL env var.\n// The CLI supports `low | medium | high | xhigh | max | auto`; we expose all\n// non-`none` levels of Fascicle's EffortLevel and let the user opt out via\n// `effort: 'none'` (which results in no env var being set, deferring to whatever\n// is already in the inherited environment).\nconst CLAUDE_CLI_EFFORT_VALUES: Record<Exclude<EffortLevel, 'none'>, string> = {\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n max: 'max',\n}\n\n/**\n * Build the `CLAUDE_CODE_EFFORT_LEVEL` env var entry for a given effort\n * level.\n *\n * Returns an empty object for `undefined` or `'none'`, which leaves the\n * inherited environment (and thus the CLI's own default) untouched.\n */\nexport function effort_env_for_claude_cli(\n effort: EffortLevel | undefined,\n): Record<string, string> {\n if (effort === undefined || effort === 'none') return {}\n return { CLAUDE_CODE_EFFORT_LEVEL: CLAUDE_CLI_EFFORT_VALUES[effort] }\n}\n\n/**\n * Pull the `claude_cli`-scoped provider options out of `provider_options`.\n *\n * Returns an empty object when the caller didn't set any, so downstream\n * code can read fields without an undefined check.\n */\nexport function extract_call_opts(opts: GenerateOptions<unknown>): ClaudeCliCallOptions {\n const raw = opts.provider_options?.['claude_cli']\n if (raw === undefined || raw === null || typeof raw !== 'object') {\n return {}\n }\n return raw\n}\n\n/**\n * Count how many `user` messages are in the prompt.\n *\n * A plain string prompt counts as a single user message.\n */\nexport function count_user_messages(prompt: string | Message[]): number {\n if (typeof prompt === 'string') return 1\n let count = 0\n for (const m of prompt) {\n if (m.role === 'user') count += 1\n }\n return count\n}\n\n/**\n * Extract the first user message's text to send as CLI stdin.\n *\n * `generate` rejects prompts with more than one user message (claude_cli\n * only supports a single turn per invocation), so only the first one is\n * ever relevant here.\n */\nexport function extract_prompt_text(prompt: string | Message[]): string {\n if (typeof prompt === 'string') return prompt\n for (const m of prompt) {\n if (m.role !== 'user') continue\n if (typeof m.content === 'string') return m.content\n const parts: string[] = []\n for (const p of m.content) {\n if (p.type === 'text') parts.push(p.text)\n }\n return parts.join('\\n')\n }\n return ''\n}\n\n/**\n * Pull the system message content out of a `Message[]` prompt.\n *\n * Returns `undefined` for a plain string prompt or when no system message\n * is present.\n */\nexport function extract_system_text(prompt: string | Message[]): string | undefined {\n if (typeof prompt === 'string') return undefined\n for (const m of prompt) {\n if (m.role === 'system') return m.content\n }\n return undefined\n}\n\n/**\n * Serialize a schema to the JSON Schema string the CLI's `--json-schema`\n * flag expects.\n *\n * `strip_meta` is what makes this CLI-specific: `claude --json-schema`\n * rejects a top-level `$schema`/`$id`, which every other provider tolerates.\n */\nexport function compile_schema<T>(schema: ToolSchema<T>): string {\n return JSON.stringify(to_json_schema(schema, { strip_meta: true }))\n}\n\n/**\n * Turn a closed CLI subprocess's exit code, signal, stderr, and what its\n * stream reported into an `Error`.\n *\n * Checks for an auth failure first, then for a claude binary that bwrap\n * started but couldn't find inside its sandbox, then for a missing sandbox\n * binary, then falls back to a generic exit-code error. The stderr snippet\n * attached to each error is truncated to 512 bytes.\n *\n * A logged-out CLI says so on stdout and leaves stderr empty: it writes an\n * assistant message with the `authentication_failed` error code and an error\n * result that reads \"Not logged in · Please run /login\". So the auth check\n * reads the stream's error code as well as stderr, and when stderr is empty,\n * an error result's text stands in for it in the message.\n *\n * The bwrap check has to come before the sandbox check: bwrap's own\n * \"execvp <binary>: No such file or directory\" names bwrap and says the file\n * is missing, so the sandbox check would blame bwrap for the claude binary.\n */\nexport function classify_close_error(\n code: number | null,\n signal: NodeJS.Signals | null,\n stderr: string,\n parsed?: Pick<ParsedStream, 'is_error' | 'final_text' | 'api_error'>,\n): Error {\n const snippet = stderr.slice(0, 512)\n // Text from a run that reported no error is the model's, not a reason.\n const reported = parsed?.is_error === true ? parsed.final_text.slice(0, 512) : ''\n const detail = snippet.length > 0 ? snippet : reported\n if (stderr_is_auth_failure(stderr) || parsed?.api_error === CLI_AUTH_FAILED_ERROR) {\n return new provider_auth_error(\n PROVIDER_NAME,\n `claude CLI reported an auth failure: ${detail}`,\n { refresh_command: 'claude auth login' },\n )\n }\n const sandboxed_binary = BWRAP_EXEC_MISSING.exec(stderr)?.[1]\n if (sandboxed_binary !== undefined) {\n return new claude_cli_error(\n 'binary_not_found',\n `bwrap ran but found no claude binary at '${sandboxed_binary}' inside its sandbox, which binds only /usr, /bin, /lib, /lib64, and additional_write_paths: ${snippet}`,\n { stderr_snippet: snippet },\n )\n }\n if (/bwrap|greywall|sandbox/i.test(stderr) && /not found|no such file|enoent/i.test(stderr)) {\n return new claude_cli_error('sandbox_unavailable', `sandbox binary unavailable: ${snippet}`, {\n stderr_snippet: snippet,\n })\n }\n const status = typeof code === 'number' ? code : undefined\n const signal_part = signal !== null ? ` (signal ${signal})` : ''\n const message = `claude CLI exited with code ${String(code)}${signal_part}: ${detail}`\n const metadata: { status?: number; stderr_snippet?: string } = {\n stderr_snippet: snippet,\n }\n if (status !== undefined) metadata.status = status\n return new claude_cli_error('subprocess_exit', message, metadata)\n}\n\ntype RunArgs = {\n readonly model_id: string\n readonly provider_config: ClaudeCliProviderConfig\n readonly stdin_text: string\n readonly merged_system: string\n readonly merged_allowed_tools: ReadonlyArray<string>\n readonly call_opts: ClaudeCliCallOptions\n readonly compiled_schema: string | undefined\n readonly env: Record<string, string>\n readonly spawn_cmd: string\n readonly prefix_args: ReadonlyArray<string>\n readonly cwd: string | undefined\n readonly startup_timeout_ms: number\n readonly stall_timeout_ms: number\n readonly abort: AbortSignal | undefined\n readonly dispatch_chunk:\n | ((chunk: StreamChunk) => Promise<void>)\n | undefined\n readonly trajectory: GenerateOptions<unknown>['trajectory']\n}\n\ntype RunOutcome = {\n readonly parsed: ReturnType<typeof snapshot>\n readonly chunks: StreamChunk[]\n}\n\n/**\n * Spawn one claude CLI invocation, stream its stdout into parsed events,\n * and wait for it to close.\n *\n * Runs `session.wait_close()` and the stdout-consuming loop concurrently:\n * the process can still be flushing stdout while it exits, so waiting for\n * close first would drop those trailing lines. Throws if the process\n * exits non-zero or closes without ever emitting a terminal `result`\n * event.\n */\nasync function run_cli(\n spawn_runtime: ReturnType<typeof create_spawn_runtime>,\n args: RunArgs,\n): Promise<RunOutcome> {\n const argv = build_cli_argv({\n model_id: args.model_id,\n provider_config: args.provider_config,\n call_opts: args.call_opts,\n merged_allowed_tools: args.merged_allowed_tools,\n merged_system: args.merged_system,\n ...(args.compiled_schema !== undefined ? { compiled_schema: args.compiled_schema } : {}),\n })\n const full_argv: string[] = [...args.prefix_args, ...argv]\n\n const session = await spawn_runtime.spawn_cli({\n cmd: args.spawn_cmd,\n argv: full_argv,\n env: args.env,\n stdin: args.stdin_text,\n startup_timeout_ms: args.startup_timeout_ms,\n stall_timeout_ms: args.stall_timeout_ms,\n ...(args.cwd !== undefined ? { cwd: args.cwd } : {}),\n ...(args.abort !== undefined ? { abort: args.abort } : {}),\n ...(args.provider_config.sandbox !== undefined\n ? { spawn_failure_reason: 'sandbox_unavailable' as const }\n : {}),\n })\n\n const state = create_parser_state()\n const chunks: StreamChunk[] = []\n\n const consume = (async (): Promise<void> => {\n for await (const line of session.stdout_lines) {\n await feed_chunk(state, `${line}\\n`, chunks, args.dispatch_chunk, args.trajectory)\n }\n await flush_remaining(state, chunks, args.dispatch_chunk, args.trajectory)\n })()\n\n let close_outcome: Awaited<ReturnType<typeof session.wait_close>>\n try {\n [close_outcome] = await Promise.all([session.wait_close(), consume])\n } catch (err: unknown) {\n try {\n await consume\n } catch {\n // ignore secondary consume errors\n }\n throw err\n }\n\n const parsed = snapshot(state)\n\n if (close_outcome.code !== 0) {\n throw classify_close_error(close_outcome.code, close_outcome.signal, close_outcome.stderr, parsed)\n }\n if (!parsed.received_result) {\n throw new claude_cli_error(\n 'no_result_event',\n 'claude CLI closed without emitting a terminal result event',\n { stderr_snippet: close_outcome.stderr.slice(0, 512) },\n )\n }\n\n return { parsed, chunks }\n}\n\n/** Span ids one generate call holds open; `first_step` is cleared once closed. */\ntype GenerateSpans = {\n generate: string | undefined\n first_step: string | undefined\n}\n\n/**\n * Emit `option_ignored` events for the loop-control options this provider\n * cannot honor: the CLI runs its own tool loop on the far side of the\n * subprocess boundary.\n */\nfunction emit_ignored_options<T>(\n opts: GenerateOptions<T>,\n trajectory: RunArgs['trajectory'],\n): void {\n const option_ignored = create_option_ignored_dedup(trajectory)\n if (opts.max_steps !== undefined) {\n option_ignored.emit('max_steps', PROVIDER_NAME)\n }\n if (opts.tool_error_policy !== undefined) {\n option_ignored.emit('tool_error_policy', PROVIDER_NAME)\n }\n if (opts.on_tool_approval !== undefined) {\n option_ignored.emit('on_tool_approval', PROVIDER_NAME)\n }\n if (opts.tool_call_repair_attempts !== undefined) {\n option_ignored.emit('tool_call_repair_attempts', PROVIDER_NAME)\n }\n if (opts.max_tool_calls_per_step !== undefined) {\n option_ignored.emit('max_tool_calls_per_step', PROVIDER_NAME)\n }\n}\n\n/**\n * Reject requests the CLI cannot express: multi-turn user history (one user\n * turn per invocation; continuation goes through `session_id`), and\n * executable tools under `tool_bridge: 'forbid'`.\n */\nfunction validate_request(\n prompt: string | Message[],\n tools_list: ReadonlyArray<Tool>,\n tool_bridge: ToolBridgeMode,\n): void {\n if (count_user_messages(prompt) >= 2) {\n throw new provider_capability_error(\n PROVIDER_NAME,\n 'multi_turn_history',\n 'use provider_options.claude_cli.session_id instead',\n )\n }\n if (tools_list.length > 0 && tool_bridge === 'forbid') {\n const has_execute = tools_list.some((t) => typeof t.execute === 'function')\n if (has_execute) {\n throw new provider_capability_error(\n PROVIDER_NAME,\n 'tool_execute',\n \"tool_bridge is 'forbid' and this tool has an execute closure — set tool_bridge: 'allowlist_only' or drop the closure\",\n )\n }\n }\n}\n\n/**\n * Record which executable tools the allowlist-only bridge is dropping:\n * their names still pass through `--allowedTools`, but their execute\n * closures cannot run on this side of the subprocess boundary.\n */\nfunction record_allowlist_only_drop(\n tools_list: ReadonlyArray<Tool>,\n tool_bridge: ToolBridgeMode,\n trajectory: RunArgs['trajectory'],\n): void {\n if (tools_list.length === 0 || tool_bridge !== 'allowlist_only' || trajectory === undefined) {\n return\n }\n const dropped = tools_list\n .filter((t) => typeof t.execute === 'function')\n .map((t) => t.name)\n trajectory.record({\n kind: 'cli_tool_bridge_allowlist_only',\n dropped,\n })\n}\n\n/**\n * Choose the JSON Schema string for `--json-schema`: a typed `opts.schema`\n * compiles and wins; otherwise a raw `output_json_schema` string passes\n * through verbatim.\n */\nfunction resolve_compiled_schema<T>(\n opts: GenerateOptions<T>,\n call_opts: ClaudeCliCallOptions,\n): string | undefined {\n if (opts.schema !== undefined) return compile_schema(opts.schema)\n if (\n typeof call_opts.output_json_schema === 'string' &&\n call_opts.output_json_schema.length > 0\n ) {\n return call_opts.output_json_schema\n }\n return undefined\n}\n\n/**\n * Wrap `opts.on_chunk` so sync and async callbacks dispatch the same way: a\n * returned thenable is awaited, any other return is fire-and-done. Returns\n * `undefined` when the caller isn't streaming, which downstream code uses\n * as the streaming flag.\n */\nfunction make_dispatch_chunk<T>(\n opts: GenerateOptions<T>,\n): ((chunk: StreamChunk) => Promise<void>) | undefined {\n if (opts.on_chunk === undefined) return undefined\n return async (chunk: StreamChunk): Promise<void> => {\n const maybe = opts.on_chunk?.(chunk)\n if (maybe !== undefined && typeof maybe.then === 'function') {\n await maybe\n }\n }\n}\n\n/**\n * Create this call's AbortController, register it in the adapter's\n * in-flight set (`dispose()` aborts everything still registered), and\n * forward the caller's abort signal into it, including one already aborted.\n * `unlink` undoes both and must run however generate settles, or the\n * registry would pin settled calls alive.\n */\nfunction link_caller_abort(\n in_flight: Set<AbortController>,\n caller_abort: AbortSignal | undefined,\n): { controller: AbortController; unlink: () => void } {\n const controller = new AbortController()\n in_flight.add(controller)\n const on_caller_abort = (): void => {\n controller.abort(caller_abort?.reason)\n }\n if (caller_abort !== undefined) {\n if (caller_abort.aborted) controller.abort(caller_abort.reason)\n else caller_abort.addEventListener('abort', on_caller_abort, { once: true })\n }\n return {\n controller,\n unlink: (): void => {\n if (caller_abort !== undefined) {\n caller_abort.removeEventListener('abort', on_caller_abort)\n }\n in_flight.delete(controller)\n },\n }\n}\n\n/**\n * Open the generate span and the first step span before the CLI spawns, so\n * their timing brackets the whole subprocess run.\n */\nfunction open_spans<T>(\n trajectory: RunArgs['trajectory'],\n opts: GenerateOptions<T>,\n resolved: ResolvedModel,\n has_tools: boolean,\n streaming: boolean,\n): GenerateSpans {\n return {\n generate: start_generate_span(trajectory, {\n model: opts.model ?? resolved.model_id,\n provider: PROVIDER_NAME,\n model_id: resolved.model_id,\n has_tools,\n has_schema: opts.schema !== undefined,\n streaming,\n }),\n first_step: start_step_span(trajectory, 0),\n }\n}\n\n/**\n * Failure message for schema validation that exhausted its repair budget.\n * Zero names the opt-out explicitly so \"repair disabled\" reads differently\n * from \"repairs tried and failed\".\n */\nfunction repair_exhausted_message(max_repairs: number): string {\n if (max_repairs === 0) {\n return 'schema validation failed and repair is disabled (schema_repair_attempts: 0)'\n }\n return `schema validation failed after ${String(max_repairs)} repair attempt${max_repairs === 1 ? '' : 's'}`\n}\n\n/**\n * Validate the CLI's final text against `schema`, re-invoking the CLI with\n * a repair prompt on failure, up to `max_repairs` times.\n *\n * Each repair resumes the previous attempt's `session_id`, so a snapshot\n * without one makes validation failure terminal immediately. The returned\n * snapshot is the one the repair loop settled on; the result must be built\n * from it, not from the first attempt's.\n */\nasync function parse_schema_with_repair<T>(\n spawn_runtime: ReturnType<typeof create_spawn_runtime>,\n base_args: RunArgs,\n schema: ToolSchema<T>,\n max_repairs: number,\n first_parsed: ParsedStream,\n trajectory: RunArgs['trajectory'],\n): Promise<{ parsed: ParsedStream; parsed_content: T }> {\n let parsed = first_parsed\n let repairs_done = 0\n for (;;) {\n const attempt = await parse_with_schema(schema, parsed.final_text)\n if (attempt.ok) {\n return { parsed, parsed_content: attempt.value }\n }\n record_schema_validation_failed(trajectory, {\n attempt: repairs_done === 0 ? 'initial' : 'repair',\n schema_issues: format_schema_issues(attempt.issues),\n raw_text: parsed.final_text,\n })\n if (repairs_done >= max_repairs) {\n throw new schema_validation_error(\n repair_exhausted_message(max_repairs),\n attempt.issues,\n parsed.final_text,\n )\n }\n const repair_session_id = parsed.session_id\n if (repair_session_id === undefined) {\n throw new schema_validation_error(\n 'schema validation failed and no session_id available for repair',\n attempt.issues,\n parsed.final_text,\n )\n }\n const repair_outcome = await run_cli(spawn_runtime, {\n ...base_args,\n stdin_text: build_repair_prompt_text(attempt.issues),\n call_opts: { ...base_args.call_opts, session_id: repair_session_id },\n })\n parsed = repair_outcome.parsed\n repairs_done += 1\n }\n}\n\n/**\n * Resolve the call's final parse snapshot and validated content. Without a\n * schema the first snapshot is final and content stays undefined; with one,\n * the repair loop takes over.\n */\nasync function resolve_content<T>(\n spawn_runtime: ReturnType<typeof create_spawn_runtime>,\n base_args: RunArgs,\n opts: GenerateOptions<T>,\n first_parsed: ParsedStream,\n): Promise<{ parsed: ParsedStream; parsed_content: T | undefined }> {\n if (opts.schema === undefined) {\n return { parsed: first_parsed, parsed_content: undefined }\n }\n return parse_schema_with_repair(\n spawn_runtime,\n base_args,\n opts.schema,\n opts.schema_repair_attempts ?? 1,\n first_parsed,\n base_args.trajectory,\n )\n}\n\n/**\n * Assemble the `build_generate_result` input, attaching the schema and its\n * validated value only when structured output was requested.\n */\nfunction assemble_result<T>(\n parsed: ParsedStream,\n resolved: ResolvedModel,\n schema: ToolSchema<T> | undefined,\n parsed_content: T | undefined,\n): GenerateResult<T> {\n return build_generate_result<T>({\n parsed,\n resolved,\n ...(schema !== undefined ? { schema } : {}),\n ...(parsed_content !== undefined ? { parsed_content } : {}),\n })\n}\n\n/**\n * Forward the CLI's per-turn provider-reported costs into the trajectory.\n */\nfunction record_provider_costs(\n trajectory: RunArgs['trajectory'],\n steps: ReadonlyArray<StepRecord>,\n): void {\n for (const step of steps) {\n if (step.cost !== undefined) {\n record_cost(trajectory, step.index, step.cost, 'provider_reported')\n }\n }\n}\n\n/**\n * Close the eagerly opened first step span against the steps the CLI\n * reported, then emit paired open/close spans for steps 1..n; those arrive\n * all at once on process close, so their spans carry usage, not timing.\n * Clears `spans.first_step` so the error path cannot close it twice.\n */\nfunction close_step_spans(\n trajectory: RunArgs['trajectory'],\n spans: GenerateSpans,\n steps: ReadonlyArray<StepRecord>,\n): void {\n if (steps.length === 0) {\n end_step_span(trajectory, spans.first_step, {})\n spans.first_step = undefined\n return\n }\n const head = steps[0]\n if (head !== undefined) {\n end_step_span(trajectory, spans.first_step, {\n usage: head.usage,\n finish_reason: head.finish_reason,\n })\n }\n spans.first_step = undefined\n for (let i = 1; i < steps.length; i += 1) {\n const s = steps[i]\n if (s === undefined) continue\n const id = start_step_span(trajectory, i)\n end_step_span(trajectory, id, {\n usage: s.usage,\n finish_reason: s.finish_reason,\n })\n }\n}\n\n/**\n * Emit the terminal `finish` chunk streaming callers expect; the CLI stream\n * has no equivalent event, so it is synthesized from the final result.\n */\nasync function dispatch_finish<T>(\n dispatch_chunk: ((chunk: StreamChunk) => Promise<void>) | undefined,\n result: GenerateResult<T>,\n): Promise<void> {\n if (dispatch_chunk === undefined) return\n await dispatch_chunk({\n kind: 'finish',\n finish_reason: result.finish_reason,\n usage: result.usage,\n })\n}\n\n/**\n * Close whatever spans are still open with the failure message. A failure\n * after the step spans already closed (for example, in the finish-chunk dispatch)\n * closes only the generate span.\n */\nfunction close_spans_on_error(\n trajectory: RunArgs['trajectory'],\n spans: GenerateSpans,\n err: unknown,\n): void {\n const message = err instanceof Error ? err.message : String(err)\n if (spans.first_step !== undefined) {\n end_step_span(trajectory, spans.first_step, { error: message })\n spans.first_step = undefined\n }\n end_generate_span(trajectory, spans.generate, { error: message })\n}\n\n/**\n * Build a claude_cli `ExternalAgentAdapter` bound to one config.\n *\n * Validates the auth config eagerly, before any call is made, and wires up\n * a spawn runtime plus an in-flight abort-controller registry that\n * `dispose()` uses to cancel every call still running.\n */\nexport function create_claude_cli_adapter(init: ProviderInit): ExternalAgentAdapter {\n const config = init as ClaudeCliProviderConfig\n validate_auth_config(config)\n\n const spawn_runtime = create_spawn_runtime()\n let disposed = false\n const in_flight: Set<AbortController> = new Set()\n\n const resolved_binary = typeof config.binary === 'string' && config.binary.length > 0\n ? config.binary\n : CLI_BINARY_DEFAULT\n const resolved_auth_mode = config.auth_mode ?? 'auto'\n const resolved_startup_timeout = config.startup_timeout_ms ?? DEFAULT_STARTUP_TIMEOUT_MS\n const resolved_stall_timeout = config.stall_timeout_ms ?? DEFAULT_STALL_TIMEOUT_MS\n\n const adapter: ExternalAgentAdapter = {\n kind: 'external',\n name: PROVIDER_NAME,\n supports: (capability) => SUPPORTED.has(capability),\n async generate<T>(\n opts: GenerateOptions<T>,\n resolved: ResolvedModel,\n ): Promise<GenerateResult<T>> {\n if (disposed) throw new engine_disposed_error()\n if (opts.abort?.aborted === true) {\n throw new aborted_error('aborted', { reason: opts.abort.reason })\n }\n\n // Stamp timestamps on this subprocess provider's trajectory events\n // too, matching the ai_sdk path: the external branch in generate.ts\n // returns before the main path's with_timestamps wrap runs, so it\n // has to happen here instead.\n const trajectory = with_timestamps(opts.trajectory)\n const call_opts = extract_call_opts(opts)\n emit_ignored_options(opts, trajectory)\n\n const tools_list: ReadonlyArray<Tool> = opts.tools ?? []\n const tool_bridge: ToolBridgeMode = call_opts.tool_bridge ?? 'allowlist_only'\n validate_request(opts.prompt, tools_list, tool_bridge)\n\n const merged_allowed_tools = merge_allowed_tools(\n call_opts.allowed_tools,\n tools_list.map((t) => t.name),\n )\n record_allowlist_only_drop(tools_list, tool_bridge, trajectory)\n\n const merged_system = merge_system(\n opts.system ?? extract_system_text(opts.prompt),\n call_opts.append_system_prompt,\n )\n const env = build_env(config, call_opts.env, resolved_auth_mode)\n Object.assign(env, effort_env_for_claude_cli(opts.effort))\n const sandbox_plan = build_sandbox_plan(resolved_binary, config.sandbox)\n const dispatch_chunk = make_dispatch_chunk(opts)\n\n const { controller, unlink } = link_caller_abort(in_flight, opts.abort)\n const spans = open_spans(\n trajectory,\n opts,\n resolved,\n tools_list.length > 0,\n dispatch_chunk !== undefined,\n )\n\n const base_args: RunArgs = {\n model_id: resolved.model_id,\n provider_config: config,\n stdin_text: extract_prompt_text(opts.prompt),\n merged_system,\n merged_allowed_tools,\n call_opts,\n compiled_schema: resolve_compiled_schema(opts, call_opts),\n env,\n spawn_cmd: sandbox_plan.spawn_cmd,\n prefix_args: sandbox_plan.prefix_args,\n cwd: config.default_cwd,\n startup_timeout_ms: resolved_startup_timeout,\n stall_timeout_ms: resolved_stall_timeout,\n abort: controller.signal,\n dispatch_chunk,\n trajectory,\n }\n\n try {\n const first_outcome = await run_cli(spawn_runtime, base_args)\n const { parsed, parsed_content } = await resolve_content(\n spawn_runtime,\n base_args,\n opts,\n first_outcome.parsed,\n )\n\n const result = assemble_result<T>(parsed, resolved, opts.schema, parsed_content)\n record_provider_costs(trajectory, result.steps)\n close_step_spans(trajectory, spans, result.steps)\n end_generate_span(trajectory, spans.generate, {\n usage: result.usage,\n finish_reason: result.finish_reason,\n model_resolved: result.model_resolved,\n })\n await dispatch_finish(dispatch_chunk, result)\n\n return result\n } catch (err: unknown) {\n close_spans_on_error(trajectory, spans, err)\n throw err\n } finally {\n unlink()\n }\n },\n async dispose(): Promise<void> {\n if (disposed) return\n disposed = true\n for (const controller of in_flight) {\n controller.abort('engine_disposed')\n }\n await spawn_runtime.dispose_all()\n },\n }\n\n return adapter\n}\n","/**\n * Provider name → adapter factory lookup for the built-in set.\n *\n * Unknown provider names throw engine_config_error: this lookup only runs at\n * engine construction, where an unknown name is a config typo, not a\n * call-time routing miss (that is provider_not_configured_error, thrown by\n * generate). Custom providers enter via `EngineConfig.custom_providers` at\n * construction, resolved custom-first in create_engine; there is no runtime\n * (post-construction) registration.\n */\n\nimport { engine_config_error } from '../errors.js'\nimport type { ProviderFactory } from './types.js'\nimport { create_anthropic_adapter } from './anthropic.js'\nimport { create_openai_adapter } from './openai.js'\nimport { create_google_adapter } from './google.js'\nimport { create_ollama_adapter } from './ollama.js'\nimport { create_lmstudio_adapter } from './lmstudio.js'\nimport { create_openrouter_adapter } from './openrouter.js'\nimport { create_bedrock_adapter } from './bedrock.js'\nimport { create_claude_cli_adapter } from './claude_cli/index.js'\n\nconst BUILTIN_PROVIDERS: ReadonlyMap<string, ProviderFactory> = new Map<string, ProviderFactory>([\n ['anthropic', create_anthropic_adapter],\n ['openai', create_openai_adapter],\n ['google', create_google_adapter],\n ['ollama', create_ollama_adapter],\n ['lmstudio', create_lmstudio_adapter],\n ['openrouter', create_openrouter_adapter],\n ['bedrock', create_bedrock_adapter],\n ['claude_cli', create_claude_cli_adapter],\n])\n\n/**\n * List the names of every built-in provider, in registration order.\n */\nexport function list_builtin_providers(): ReadonlyArray<string> {\n return [...BUILTIN_PROVIDERS.keys()]\n}\n\n/**\n * Look up a built-in provider's adapter factory by name, throwing\n * engine_config_error for unknown names (a construction-time typo, distinct\n * from generate's call-time provider_not_configured_error).\n */\nexport function get_provider_factory(name: string): ProviderFactory {\n const factory = BUILTIN_PROVIDERS.get(name)\n if (factory === undefined) {\n throw new engine_config_error(\n `unknown provider '${name}'; built-in providers are: ${list_builtin_providers().join(', ')}`,\n name,\n )\n }\n return factory\n}\n","/**\n * Default-merging helpers for engine-level `EngineDefaults`.\n */\n\n/**\n * Merge per-call `provider_options` over engine-level defaults.\n *\n * Scalar fields merge inline at the call site via `opts.x ?? defaults.x`, but\n * `provider_options` needs a two-level merge: outer keys are provider names\n * (`claude_cli`, `anthropic`, ...) and inner records hold per-provider\n * settings. Per-call inner keys override the matching default's inner keys;\n * provider keys unique to either side fall through unchanged. Recursion stops\n * at that second level, so deeper structures replace wholesale rather than\n * merging further.\n */\nexport function merge_provider_options(\n defaults: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined,\n call: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n if (defaults === undefined && call === undefined) return undefined\n if (defaults === undefined) return call\n if (call === undefined) {\n const out: Record<string, unknown> = {}\n for (const [provider, inner] of Object.entries(defaults)) {\n out[provider] = { ...inner }\n }\n return out\n }\n const out: Record<string, unknown> = {}\n for (const [provider, inner] of Object.entries(defaults)) {\n out[provider] = { ...inner }\n }\n for (const [provider, inner] of Object.entries(call)) {\n const existing = out[provider]\n if (is_plain_object(existing) && is_plain_object(inner)) {\n // Both sides are plain per-provider option records: merge their keys,\n // with the call's values winning on conflicts.\n out[provider] = { ...existing, ...inner }\n } else {\n // No default for this provider, or a non-object value on either side:\n // the call's value replaces the default wholesale.\n out[provider] = inner\n }\n }\n return out\n}\n\n/**\n * Narrow `value` to a plain (non-null, non-array) object.\n */\nfunction is_plain_object(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n","/**\n * Streaming chunk normalization and dispatch.\n *\n * Provider events are normalized into the discriminated `StreamChunk` union.\n * The dispatcher synchronously invokes on_chunk per provider event; on throw\n * or rejected promise it signals the caller to abort the in-flight request\n * (the request-abort itself is wired up in the generate orchestrator) and\n * surfaces on_chunk_error.\n *\n * Chunk ordering invariants (enforced by the orchestrator that feeds the\n * dispatcher, not here):\n * - text and reasoning interleave within a step.\n * - tool_call_start precedes its input_deltas and end.\n * - tool_result follows the matching tool_call_end.\n * - step_finish is the last STREAMED chunk of a step, but tool execution and\n * tool_result chunks are dispatched by the tool loop after it, so a step's\n * tool_result chunks (and, for a salvaged step, the synthetic\n * tool_call_start/tool_call_end that precede them) follow its step_finish.\n * A salvaged step's StepRecord also reports finish_reason 'tool_calls'\n * while its already-dispatched step_finish carries the provider's 'stop'.\n * - finish is the last chunk of the call.\n */\n\nimport type { FinishReason, StreamChunk, UsageTotals } from './types.js'\nimport { on_chunk_error } from './errors.js'\n\nexport type RawProviderStreamEvent =\n | { type: 'text-delta'; id?: string; delta: string }\n | { type: 'reasoning-delta'; id?: string; delta: string }\n | { type: 'tool-input-start'; id: string; tool_name: string }\n | { type: 'tool-input-delta'; id: string; delta: string }\n | { type: 'tool-input-end'; id: string; input: unknown }\n | { type: 'tool-result'; id: string; output?: unknown; error?: { message: string } }\n | { type: 'finish-step'; finish_reason: FinishReason; usage: UsageTotals }\n | { type: 'finish'; finish_reason: FinishReason; usage: UsageTotals }\n\n/**\n * Normalize a single AI SDK v6 stream event into a StreamChunk with the\n * supplied step_index. Unknown event types return undefined (caller drops).\n */\nexport function normalize_chunk(\n event: RawProviderStreamEvent,\n step_index: number,\n): StreamChunk | undefined {\n switch (event.type) {\n case 'text-delta':\n return { kind: 'text', text: event.delta, step_index }\n case 'reasoning-delta':\n return { kind: 'reasoning', text: event.delta, step_index }\n case 'tool-input-start':\n return { kind: 'tool_call_start', id: event.id, name: event.tool_name, step_index }\n case 'tool-input-delta':\n return { kind: 'tool_call_input_delta', id: event.id, delta: event.delta, step_index }\n case 'tool-input-end':\n return { kind: 'tool_call_end', id: event.id, input: event.input, step_index }\n case 'tool-result': {\n const chunk: StreamChunk = { kind: 'tool_result', id: event.id, step_index }\n if (event.output !== undefined) chunk.output = event.output\n if (event.error !== undefined) chunk.error = event.error\n return chunk\n }\n case 'finish-step':\n return {\n kind: 'step_finish',\n step_index,\n finish_reason: event.finish_reason,\n usage: event.usage,\n }\n case 'finish':\n return { kind: 'finish', finish_reason: event.finish_reason, usage: event.usage }\n default:\n return undefined\n }\n}\n\nexport type ChunkDispatcher = {\n readonly dispatch: (chunk: StreamChunk) => Promise<void>\n readonly aborted: () => boolean\n}\n\n/**\n * Build a dispatcher around a user-supplied on_chunk. Catches sync throws and\n * rejected promises; once an error is recorded subsequent dispatch calls are\n * no-ops and `aborted()` returns true so the orchestrator can short-circuit\n * the in-flight provider request. The first error is re-thrown from the first\n * failing dispatch() call, wrapped in on_chunk_error.\n */\nexport function create_chunk_dispatcher(\n on_chunk: ((chunk: StreamChunk) => void | Promise<void>) | undefined,\n): ChunkDispatcher {\n let failed = false\n return {\n aborted: () => failed,\n async dispatch(chunk: StreamChunk): Promise<void> {\n if (on_chunk === undefined || failed) return\n try {\n const maybe = on_chunk(chunk)\n if (maybe !== undefined && typeof maybe.then === 'function') {\n await maybe\n }\n } catch (err: unknown) {\n failed = true\n throw new on_chunk_error('on_chunk callback failed', err)\n }\n },\n }\n}\n","/**\n * Usage aggregation across a generate call's steps.\n */\n\nimport type { StepRecord, UsageTotals } from './types.js'\n\ntype OptionalFieldKey =\n | 'reasoning_tokens'\n | 'cached_input_tokens'\n | 'cache_write_tokens'\n\nconst OPTIONAL_FIELDS: ReadonlyArray<OptionalFieldKey> = [\n 'reasoning_tokens',\n 'cached_input_tokens',\n 'cache_write_tokens',\n]\n\n/**\n * Sum token usage across every step of a generate call.\n *\n * `input_tokens` and `output_tokens` always total. The optional fields\n * (`reasoning_tokens`, `cached_input_tokens`, `cache_write_tokens`) stay\n * absent on the result unless at least one step reported them; once\n * present, every step contributes to the sum, with steps that omit the\n * field counting as 0.\n */\nexport function sum_usage(steps: ReadonlyArray<StepRecord>): UsageTotals {\n let input_tokens = 0\n let output_tokens = 0\n const present: Record<OptionalFieldKey, boolean> = {\n reasoning_tokens: false,\n cached_input_tokens: false,\n cache_write_tokens: false,\n }\n const sums: Record<OptionalFieldKey, number> = {\n reasoning_tokens: 0,\n cached_input_tokens: 0,\n cache_write_tokens: 0,\n }\n for (const step of steps) {\n input_tokens += step.usage.input_tokens\n output_tokens += step.usage.output_tokens\n for (const key of OPTIONAL_FIELDS) {\n const value = step.usage[key]\n if (value !== undefined) {\n present[key] = true\n sums[key] += value\n }\n }\n }\n\n const total: UsageTotals = { input_tokens, output_tokens }\n for (const key of OPTIONAL_FIELDS) {\n if (present[key]) total[key] = sums[key]\n }\n return total\n}\n","/**\n * Salvage tool calls that a model emitted as assistant TEXT instead of a\n * structured tool_calls array. Local runtimes (Ollama native API, LM Studio\n * /v1) frequently mis-serialize tool definitions in the chat template, so the\n * model writes its call into the content in one of three well-known formats:\n *\n * hermes <tool_call>{\"name\":\"x\",\"arguments\":{...}}</tool_call>\n * json {\"name\":\"x\",\"arguments\":{...}} bare or ```json-fenced\n * qwen_xml <tool_call><function=x><parameter=k>v</parameter></function></tool_call>\n *\n * A candidate is accepted ONLY when its name resolves in the call's tool\n * registry AND its arguments validate against that tool's input_schema.\n * That double gate is the guard against a false positive on an ordinary\n * answer that merely contains JSON.\n *\n * Parsing rules that matter for correctness:\n * - Every <tool_call> block extent, accepted or rejected, is masked so the\n * bare-JSON pass never re-matches a payload inside it (a hermes block\n * contains a shape-valid bare object; double-matching would double-strip).\n * - All code fences are masked from the bare pass for the same reason;\n * only fences with no info string or `json` are parsed as candidates.\n * - A complete bare object that is not a call is skipped whole: descending\n * into it could false-positive on substructures of ordinary JSON output.\n * - An unterminated <tool_call> is ignored (finish_reason 'length'\n * truncation); its text is left intact.\n * - Qwen XML parameter values that contain a literal </parameter> mis-parse\n * under the non-greedy matcher; accepted limitation.\n *\n * Never throws; returns undefined when zero candidates survive validation.\n */\n\nimport { validate_schema } from '#schema'\nimport type { SalvageFormat, Tool } from './types.js'\n\nexport type SalvagedCall = {\n readonly name: string\n readonly input: unknown\n readonly format: SalvageFormat\n readonly span: { readonly start: number; readonly end: number }\n}\n\nexport type SalvageOutcome = {\n readonly calls: ReadonlyArray<SalvagedCall>\n readonly stripped_text: string\n}\n\ntype Span = { readonly start: number; readonly end: number }\n\ntype Candidate = {\n readonly name: string\n readonly args: Record<string, unknown>\n readonly format: SalvageFormat\n readonly span: Span\n}\n\nconst TOOL_CALL_OPEN = '<tool_call>'\nconst TOOL_CALL_CLOSE = '</tool_call>'\nconst FUNCTION_RE = /<function=([^>\\s]+)>([\\s\\S]*?)<\\/function>/g\nconst PARAMETER_RE = /<parameter=([^>\\s]+)>([\\s\\S]*?)<\\/parameter>/g\nconst FENCE_RE = /```([^\\n]*)\\n([\\s\\S]*?)```/g\nconst EMPTY_BLOCK_RE = /<tool_call>\\s*<\\/tool_call>/g\n\n/**\n * From `open` at an opening quote, return the index of the matching closing\n * quote, honoring backslash escapes. Returns `text.length` for an unterminated\n * string, so the caller's scan runs off the end and yields no object.\n */\nfunction skip_json_string(text: string, open: number): number {\n let escaped = false\n for (let i = open + 1; i < text.length; i += 1) {\n const ch = text[i]\n if (escaped) escaped = false\n else if (ch === '\\\\') escaped = true\n else if (ch === '\"') return i\n }\n return text.length\n}\n\n/**\n * Parse `text.slice(start, end)` as JSON, pairing the value with `end`, or\n * `undefined` when the slice is not valid JSON. JSON.parse is the sole\n * semantic authority; the scanner only fixed the extent.\n */\nfunction parse_json_extent(\n text: string,\n start: number,\n end: number,\n): { value: unknown; end: number } | undefined {\n try {\n return { value: JSON.parse(text.slice(start, end)), end }\n } catch {\n return undefined\n }\n}\n\n/**\n * Find the extent of one balanced JSON object starting at `start_index`\n * (which must point at `{`), respecting strings and escapes so braces inside\n * string values do not affect the depth count. The scanner only finds the\n * extent; JSON.parse remains the sole semantic authority.\n */\nexport function scan_balanced_json(\n text: string,\n start_index: number,\n): { value: unknown; end: number } | undefined {\n if (text[start_index] !== '{') return undefined\n let depth = 0\n for (let i = start_index; i < text.length; i += 1) {\n const ch = text[i]\n if (ch === '\"') {\n i = skip_json_string(text, i)\n } else if (ch === '{') {\n depth += 1\n } else if (ch === '}') {\n depth -= 1\n if (depth === 0) return parse_json_extent(text, start_index, i + 1)\n }\n }\n return undefined\n}\n\n/**\n * Check for a non-null, non-array object.\n */\nfunction is_plain_object(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Exactly {name, arguments} with a string name and object arguments. This is\n * the shape firewall against prose that happens to contain JSON.\n */\nfunction call_shape(\n value: unknown,\n): { name: string; args: Record<string, unknown> } | undefined {\n if (!is_plain_object(value)) return undefined\n if (Object.keys(value).length !== 2) return undefined\n const name = value['name']\n const args = value['arguments']\n if (typeof name !== 'string' || !is_plain_object(args)) return undefined\n return { name, args }\n}\n\n/**\n * Check whether a span intersects any masked region.\n */\nfunction overlaps_any(span: Span, masks: ReadonlyArray<Span>): boolean {\n return masks.some((m) => span.start < m.end && m.start < span.end)\n}\n\n/**\n * Find the mask covering a text index, if any, so scanners can jump past it.\n */\nfunction mask_containing(masks: ReadonlyArray<Span>, index: number): Span | undefined {\n return masks.find((m) => index >= m.start && index < m.end)\n}\n\n/**\n * Strip at most one leading and one trailing newline.\n *\n * Qwen XML parameter values are written on their own lines; the wrapping\n * newlines are markup, but interior whitespace is real data and stays.\n */\nfunction trim_one_newline(value: string): string {\n let out = value\n if (out.startsWith('\\n')) out = out.slice(1)\n if (out.endsWith('\\n')) out = out.slice(0, -1)\n return out\n}\n\n/**\n * Extract qwen_xml `<function=name>` candidates from a tool_call block body.\n *\n * Parameters land as a string map (typed coercion happens at validation).\n * Spans are offset by `inner_start` back into the full-text coordinate space.\n */\nfunction scan_qwen_functions(inner_start: number, inner: string): Candidate[] {\n const out: Candidate[] = []\n for (const fn of inner.matchAll(FUNCTION_RE)) {\n const body = fn[2] ?? ''\n const params: Record<string, string> = {}\n let leftover = body\n for (const pm of body.matchAll(PARAMETER_RE)) {\n params[pm[1] ?? ''] = trim_one_newline(pm[2] ?? '')\n leftover = leftover.replace(pm[0], '')\n }\n // Non-whitespace between parameter tags means the block is not a clean\n // call; skip it rather than guess at intent.\n if (leftover.trim().length !== 0) continue\n out.push({\n name: fn[1] ?? '',\n args: params,\n format: 'qwen_xml',\n span: { start: inner_start + fn.index, end: inner_start + fn.index + fn[0].length },\n })\n }\n return out\n}\n\n/**\n * Parse a hermes `<tool_call>{...}</tool_call>` payload into a candidate. The\n * block's whole extent (`span`) is used so a later strip removes the wrapper\n * too. Returns `undefined` when the inner object is not call-shaped.\n */\nfunction scan_hermes_block(text: string, inner_start: number, span: Span): Candidate | undefined {\n const brace = text.indexOf('{', inner_start)\n const scanned = brace === -1 ? undefined : scan_balanced_json(text, brace)\n const shaped = scanned === undefined ? undefined : call_shape(scanned.value)\n if (shaped === undefined) return undefined\n return { name: shaped.name, args: shaped.args, format: 'hermes', span }\n}\n\n/**\n * Parse one located `<tool_call>` block's inner content into candidates,\n * dispatching on whether it opens with a qwen `<function=` tag or a hermes\n * `{` object.\n */\nfunction scan_block_candidates(\n text: string,\n inner_start: number,\n close: number,\n span: Span,\n): Candidate[] {\n const inner = text.slice(inner_start, close)\n const trimmed = inner.trim()\n if (trimmed.startsWith('<function=')) return scan_qwen_functions(inner_start, inner)\n if (trimmed.startsWith('{')) {\n const candidate = scan_hermes_block(text, inner_start, span)\n return candidate === undefined ? [] : [candidate]\n }\n return []\n}\n\n/**\n * Scan `<tool_call>` blocks for hermes and qwen_xml candidates.\n *\n * Every block extent (accepted, rejected, or unterminated) is returned as a\n * mask so later passes never re-match payloads inside it.\n */\nfunction scan_tool_call_blocks(text: string): { candidates: Candidate[]; masks: Span[] } {\n const candidates: Candidate[] = []\n const masks: Span[] = []\n let pos = 0\n while (true) {\n const open = text.indexOf(TOOL_CALL_OPEN, pos)\n if (open === -1) break\n const close = text.indexOf(TOOL_CALL_CLOSE, open + TOOL_CALL_OPEN.length)\n if (close === -1) {\n // Unterminated block, likely 'length' truncation. Mask to end of text\n // so the bare pass cannot salvage a fragment of an incomplete call.\n masks.push({ start: open, end: text.length })\n break\n }\n const block_end = close + TOOL_CALL_CLOSE.length\n const span: Span = { start: open, end: block_end }\n masks.push(span)\n const inner_start = open + TOOL_CALL_OPEN.length\n candidates.push(...scan_block_candidates(text, inner_start, close, span))\n pos = block_end\n }\n return { candidates, masks }\n}\n\n/**\n * Scan code fences for JSON-format candidates.\n *\n * All fences become masks (keeping the bare pass out of code samples), but\n * only fences with no info string or `json` are parsed as candidates.\n */\nfunction scan_fences(\n text: string,\n block_masks: ReadonlyArray<Span>,\n): { candidates: Candidate[]; masks: Span[] } {\n const candidates: Candidate[] = []\n const masks: Span[] = []\n for (const m of text.matchAll(FENCE_RE)) {\n const span: Span = { start: m.index, end: m.index + m[0].length }\n if (overlaps_any(span, block_masks)) continue\n masks.push(span)\n const info = (m[1] ?? '').trim()\n if (info !== '' && info !== 'json') continue\n let value: unknown\n try {\n value = JSON.parse((m[2] ?? '').trim())\n } catch {\n continue\n }\n const shaped = call_shape(value)\n if (shaped === undefined) continue\n candidates.push({ name: shaped.name, args: shaped.args, format: 'json', span })\n }\n return { candidates, masks }\n}\n\n/**\n * Scan unmasked text for bare `{name, arguments}` JSON objects.\n *\n * A complete object that is not call-shaped is skipped whole rather than\n * descended into, so substructures of ordinary JSON output cannot\n * false-positive.\n */\nfunction scan_bare_json(text: string, masks: ReadonlyArray<Span>): Candidate[] {\n const out: Candidate[] = []\n let i = 0\n while (i < text.length) {\n const masked = mask_containing(masks, i)\n if (masked !== undefined) {\n i = masked.end\n continue\n }\n if (text[i] !== '{') {\n i += 1\n continue\n }\n const scanned = scan_balanced_json(text, i)\n if (scanned === undefined) {\n i += 1\n continue\n }\n const span: Span = { start: i, end: scanned.end }\n const shaped = overlaps_any(span, masks) ? undefined : call_shape(scanned.value)\n if (shaped !== undefined) {\n out.push({ name: shaped.name, args: shaped.args, format: 'json', span })\n }\n i = scanned.end\n }\n return out\n}\n\n/**\n * Promote a candidate to a `SalvagedCall` when its tool exists and its\n * arguments validate.\n *\n * This is the second half of the double gate described in the header.\n * qwen_xml candidates get one retry with per-parameter JSON coercion, since\n * XML parameter values always arrive as strings.\n */\nasync function validate_candidate(\n candidate: Candidate,\n tool_map: ReadonlyMap<string, Tool>,\n): Promise<SalvagedCall | undefined> {\n const tool = tool_map.get(candidate.name)\n if (tool === undefined) return undefined\n const schema = tool.input_schema\n const raw = await validate_schema(schema, candidate.args)\n if (raw.ok) {\n return {\n name: candidate.name,\n input: raw.value,\n format: candidate.format,\n span: candidate.span,\n }\n }\n if (candidate.format !== 'qwen_xml') return undefined\n // XML parameters arrive as strings; retry once with per-param JSON coercion\n // so numbers, booleans, and nested structures can validate. Raw-first order\n // keeps z.string() params as the literal string they were written as.\n const coerced: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(candidate.args)) {\n if (typeof v !== 'string') {\n coerced[k] = v\n continue\n }\n try {\n coerced[k] = JSON.parse(v)\n } catch {\n coerced[k] = v\n }\n }\n const retried = await validate_schema(schema, coerced)\n if (!retried.ok) return undefined\n return {\n name: candidate.name,\n input: retried.value,\n format: candidate.format,\n span: candidate.span,\n }\n}\n\n/**\n * Remove the accepted calls' spans from the text, back to front so earlier\n * offsets stay valid, then drop any emptied `<tool_call>` wrappers.\n */\nfunction strip_spans(text: string, spans: ReadonlyArray<Span>): string {\n let out = text\n const descending = spans.toSorted((a, b) => b.start - a.start)\n for (const s of descending) out = out.slice(0, s.start) + out.slice(s.end)\n // Qwen candidates strip only their <function=> extent; drop a wrapper left\n // empty so history does not retain dangling markup.\n return out.replace(EMPTY_BLOCK_RE, '').trim()\n}\n\n/**\n * Recover tool calls from assistant text, per the header's format rules.\n *\n * Runs the three scanners in masking order (blocks, fences, bare JSON),\n * validates every candidate against the tool registry, and returns the\n * surviving calls plus the text with their spans stripped. Returns undefined\n * when nothing survives.\n */\nexport async function salvage_tool_calls(\n text: string,\n tool_map: ReadonlyMap<string, Tool>,\n): Promise<SalvageOutcome | undefined> {\n if (text.length === 0) return undefined\n const blocks = scan_tool_call_blocks(text)\n const fences = scan_fences(text, blocks.masks)\n const all_masks = [...blocks.masks, ...fences.masks]\n const candidates = [\n ...blocks.candidates,\n ...fences.candidates,\n ...scan_bare_json(text, all_masks),\n ].toSorted((a, b) => a.span.start - b.span.start)\n\n // Validated together rather than in sequence: a Standard Schema validator\n // may be async, and candidates are independent, so awaiting them one at a\n // time would only add latency. Promise.all preserves the textual order the\n // candidates were sorted into.\n const validated = await Promise.all(candidates.map((c) => validate_candidate(c, tool_map)))\n const calls = validated.filter((c) => c !== undefined)\n if (calls.length === 0) return undefined\n return {\n calls,\n stripped_text: strip_spans(\n text,\n calls.map((c) => c.span),\n ),\n }\n}\n","/**\n * Tool-call loop orchestration.\n *\n * Invariants:\n * - Tools execute SEQUENTIALLY within a turn (no parallel dispatch).\n * - Abort is checked at the top of each loop iteration AND before each tool\n * call within a turn.\n * - Tool input is validated against tool.input_schema BEFORE execute is\n * invoked. Invalid input is fed back as a tool result with error: true and\n * consumes a step; execute is not called.\n * - tool_error_policy:\n * 'feed_back' (default) serializes the thrown error into a tool result\n * with { error: <message> }. Loop continues.\n * 'throw' wraps the error in tool_error and ends the call.\n * - needs_approval (boolean or predicate) gates execute. Abort fired during\n * the await rejects with aborted_error.\n * - Absent on_tool_approval with needs_approval truthy FAILS CLOSED\n * (tool_approval_denied_error thrown before execute).\n * - max_steps cap RESOLVES with finish_reason: 'max_steps' (does not throw).\n * Attempted-but-unexecuted tool calls from the final turn land in\n * tool_calls with error: { message: 'max_steps_exceeded_before_execution' }.\n * - salvage_budget (from tool_call_repair_attempts): a turn with NO\n * structured calls, finish_reason 'stop'|'length', and tools present is\n * scanned for calls the model emitted as text (a local-runtime failure).\n * Validated matches run the normal execute path and produce the same\n * records/events/chunks as native calls, marked salvaged. The budget is\n * a shared mutable holder so it spans schema-repair re-invocations.\n * - max_tool_calls_per_step: calls beyond the cap are dropped for the step\n * (the model can re-issue next turn), recorded with\n * error: { message: 'dropped_max_tool_calls_per_step' }, and excluded\n * from the assistant history message so providers that require a result\n * per emitted call do not reject the next request.\n * - ends_turn (Tool.ends_turn): a tool flagged terminal ends the loop when a\n * call to it executes SUCCESSFULLY. The call runs the normal execute path\n * (record, fed tool_result message, trajectory events + chunk), then the\n * loop breaks with finish_reason 'stop' instead of running another model\n * turn. Salvaged terminal calls behave identically. A denied, invalid,\n * dropped, or throwing terminal call does NOT end the loop. A successful\n * terminal call is exempt from the max_steps would_exceed_after skip (it\n * needs no follow-up turn), so a terminal finish wins over a coincident\n * max_steps cap (finish_reason 'stop', max_steps_reached false).\n *\n * The loop does not itself call the AI SDK. It invokes a supplied `invoke_once`\n * seam that returns a neutral TurnResult. generate.ts builds the real seam\n * (the ai_sdk transport in providers/ai_sdk/, or a native adapter's\n * invoke_turn); tests inject a mock seam directly.\n */\n\nimport { format_schema_issues, validate_schema } from '#schema'\nimport type { TrajectoryLogger } from '#core'\nimport type {\n AssistantContentPart,\n CostBreakdown,\n FinishReason,\n Message,\n PrepareStepHook,\n Pricing,\n SalvageFormat,\n StepRecord,\n StreamChunk,\n Tool,\n ToolApprovalHandler,\n ToolCallRecord,\n ToolExecContext,\n TurnResult,\n} from './types.js'\nimport { salvage_tool_calls, type SalvageOutcome } from './tool_call_salvage.js'\nimport {\n aborted_error,\n tool_approval_denied_error,\n tool_error,\n} from './errors.js'\nimport {\n record_cost,\n record_response_received,\n record_tool_approval,\n record_tool_call,\n record_tool_call_salvaged,\n record_tool_calls_dropped,\n record_tool_result,\n end_step_span,\n start_step_span,\n type PricingMissingDedup,\n} from './trajectory.js'\nimport { compute_cost, decompose_total_cost, FREE_PROVIDERS } from './pricing.js'\n\nexport type InvokeOnceArgs = {\n readonly step_index: number\n readonly messages: ReadonlyArray<Message>\n readonly tools: ReadonlyArray<Tool>\n readonly abort: AbortSignal\n readonly stream: boolean\n /**\n * The enclosing `engine.generate.step` span id, threaded so the transport's\n * retry wrapper can stamp it onto `turn_retry` (the one span-less engine\n * event emitted below the loop, inside retry_turn).\n */\n readonly step_span: string | undefined\n}\n\nexport type RawToolCall = {\n readonly id: string\n readonly name: string\n readonly input: unknown\n}\n\nexport type InvokeOnce = (args: InvokeOnceArgs) => Promise<TurnResult>\n\nexport type ToolLoopConfig = {\n readonly invoke_once: InvokeOnce\n readonly messages: Message[]\n readonly tools: ReadonlyArray<Tool>\n readonly max_steps: number\n readonly step_index_start: number\n readonly tool_error_policy: 'feed_back' | 'throw'\n readonly abort: AbortSignal\n readonly on_tool_approval: ToolApprovalHandler | undefined\n readonly trajectory: TrajectoryLogger | undefined\n readonly stream: boolean\n readonly dispatch_chunk: ((chunk: StreamChunk) => Promise<void>) | undefined\n readonly provider: string\n readonly model_id: string\n readonly resolve_pricing: () => Pricing | undefined\n readonly pricing_dedup: PricingMissingDedup\n readonly on_finish_step?: (record: StepRecord) => void\n /**\n * Per-turn message hook. Called before each turn with the would-be request\n * messages; a returned `{ messages }` replaces the request for THAT turn\n * only (config.messages, the canonical transcript, is untouched).\n * undefined disables the hook.\n */\n readonly prepare_step?: PrepareStepHook\n /**\n * Mutable so the budget survives schema-repair re-invocations of the loop\n * within one generate call, the same threading pattern as pricing_dedup.\n * undefined disables salvage.\n */\n readonly salvage_budget?: { remaining: number }\n readonly max_tool_calls_per_step?: number\n}\n\nexport type ToolLoopResult = {\n readonly text: string\n readonly steps: StepRecord[]\n readonly tool_calls: ToolCallRecord[]\n readonly finish_reason: FinishReason\n readonly max_steps_reached: boolean\n}\n\n/**\n * Throw `aborted_error` (tagged with the step index) if the signal has fired.\n */\nfunction throw_if_aborted(abort: AbortSignal, step_index: number): void {\n if (!abort.aborted) return\n throw new aborted_error('aborted', { reason: abort.reason, step_index })\n}\n\n/**\n * Like `throw_if_aborted`, but names the tool call that was about to run so\n * the error shows exactly where the abort landed.\n */\nfunction throw_if_aborted_in_flight(\n abort: AbortSignal,\n step_index: number,\n tool_call: { id: string; name: string },\n): void {\n if (!abort.aborted) return\n throw new aborted_error('aborted', {\n reason: abort.reason,\n step_index,\n tool_call_in_flight: { id: tool_call.id, name: tool_call.name },\n })\n}\n\n/**\n * Reduce any thrown value to a message string, never throwing itself.\n */\nfunction serialize_error(err: unknown): string {\n if (err instanceof Error) return err.message\n if (typeof err === 'string') return err\n try {\n return JSON.stringify(err) ?? String(err)\n } catch {\n return String(err)\n }\n}\n\n/**\n * Resolve whether a tool call may execute.\n *\n * Evaluates `needs_approval` (boolean or async predicate); when approval is\n * required, records the request event and awaits the handler in a race\n * against `abort`. A missing handler fails closed with\n * `tool_approval_denied_error` so approval-gated tools never run silently.\n */\nasync function request_approval(\n tool: Tool,\n input: unknown,\n step_index: number,\n tool_call_id: string,\n abort: AbortSignal,\n on_tool_approval: ToolApprovalHandler | undefined,\n trajectory: TrajectoryLogger | undefined,\n): Promise<boolean> {\n const needs_approval = tool.needs_approval\n const needs =\n typeof needs_approval === 'function'\n ? await needs_approval(input)\n : needs_approval === true\n if (!needs) return true\n\n record_tool_approval(trajectory, 'tool_approval_requested', {\n tool_name: tool.name,\n step_index,\n tool_call_id,\n })\n\n if (on_tool_approval === undefined) {\n record_tool_approval(trajectory, 'tool_approval_denied', {\n tool_name: tool.name,\n step_index,\n tool_call_id,\n })\n throw new tool_approval_denied_error(\n `tool approval required for '${tool.name}': pass an on_tool_approval handler to generate(), or clear needs_approval on the tool`,\n { tool_name: tool.name, step_index, tool_call_id },\n )\n }\n\n const approval_promise = Promise.resolve(\n on_tool_approval({ tool_name: tool.name, input, step_index, tool_call_id, abort }),\n )\n\n const approved = await new Promise<boolean>((resolve, reject) => {\n if (abort.aborted) {\n reject(new aborted_error('aborted', { reason: abort.reason, step_index }))\n return\n }\n const on_abort = (): void => {\n reject(new aborted_error('aborted', { reason: abort.reason, step_index }))\n }\n // Stryker disable next-line ObjectLiteral,BooleanLiteral: { once: true } is a cleanup optimization; the abort event is terminal and both then-handlers removeEventListener, so once:false is unobservable.\n abort.addEventListener('abort', on_abort, { once: true })\n approval_promise.then(\n (value) => {\n // Stryker disable next-line StringLiteral: removing the listener on the settled promise is cleanup only; an empty event name leaks a listener that can never fire observably.\n abort.removeEventListener('abort', on_abort)\n resolve(value)\n },\n (err: unknown) => {\n // Stryker disable next-line StringLiteral: same cleanup-only removal on the reject path.\n abort.removeEventListener('abort', on_abort)\n reject(err instanceof Error ? err : new Error(String(err)))\n },\n )\n })\n\n record_tool_approval(\n trajectory,\n approved ? 'tool_approval_granted' : 'tool_approval_denied',\n { tool_name: tool.name, step_index, tool_call_id },\n )\n\n return approved\n}\n\n/**\n * Emit a `tool_result` stream chunk when streaming is active.\n */\nasync function dispatch_tool_result_chunk(\n dispatch_chunk: ((chunk: StreamChunk) => Promise<void>) | undefined,\n step_index: number,\n id: string,\n output?: unknown,\n error?: { message: string },\n): Promise<void> {\n if (dispatch_chunk === undefined) return\n const chunk: StreamChunk = { kind: 'tool_result', id, step_index }\n if (output !== undefined) chunk.output = output\n if (error !== undefined) chunk.error = error\n await dispatch_chunk(chunk)\n}\n\n/**\n * Build the `role: 'tool'` message that feeds a tool's result back to the\n * model, JSON-serializing non-string content.\n */\nfunction build_tool_result_message(\n tool_call_id: string,\n tool_name: string,\n content: unknown,\n): Message {\n const serialized =\n typeof content === 'string' ? content : safe_json_stringify(content)\n return {\n role: 'tool',\n tool_call_id,\n name: tool_name,\n content: serialized,\n }\n}\n\n/**\n * JSON-stringify with a `String(value)` fallback for circular references and\n * other values `JSON.stringify` rejects.\n */\nfunction safe_json_stringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/**\n * Build the assistant history message for a turn. A turn with `content`\n * keeps the provider's parts in its order, data included, so reasoning goes\n * back beside the text and calls it came with. Any other turn is plain text\n * when there are no tool calls, otherwise text plus tool_call parts.\n */\nfunction build_assistant_message(\n turn: TurnResult,\n view: SalvageView,\n kept: ReadonlyArray<RawToolCall>,\n): Message {\n if (turn.content !== undefined) {\n return { role: 'assistant', content: history_parts(turn.content, view, kept) }\n }\n if (kept.length === 0) return { role: 'assistant', content: view.history_text }\n const parts: AssistantContentPart[] = []\n if (view.history_text.length > 0) parts.push({ type: 'text', text: view.history_text })\n for (const tc of kept) parts.push(tool_call_part(tc))\n return { role: 'assistant', content: parts }\n}\n\n/**\n * A raw call as a history part, carrying no provider data.\n */\nfunction tool_call_part(tc: RawToolCall): AssistantContentPart {\n return { type: 'tool_call', id: tc.id, name: tc.name, input: tc.input }\n}\n\n/**\n * A turn's own parts for history. A call the per-step clamp dropped leaves,\n * as it leaves the plain message, while everything around it stays.\n */\nfunction history_parts(\n content: ReadonlyArray<AssistantContentPart>,\n view: SalvageView,\n kept: ReadonlyArray<RawToolCall>,\n): AssistantContentPart[] {\n if (view.outcome !== undefined) return salvaged_parts(content, view.history_text, kept)\n const kept_ids = new Set(kept.map((tc) => tc.id))\n return content.filter((part) => part.type !== 'tool_call' || kept_ids.has(part.id))\n}\n\n/**\n * A salvaged turn's parts for history: the stripped text replaces the text\n * parts at the first one's place, and the salvaged calls follow the last\n * part. Salvage runs only on a turn with no native calls, so the provider\n * gave its calls no place of their own. The replacement carries no provider\n * data, since whatever the provider attached belonged to the text salvage\n * rewrote.\n */\nfunction salvaged_parts(\n content: ReadonlyArray<AssistantContentPart>,\n stripped_text: string,\n kept: ReadonlyArray<RawToolCall>,\n): AssistantContentPart[] {\n const parts: AssistantContentPart[] = []\n let text_placed = false\n for (const part of content) {\n if (part.type !== 'text') {\n parts.push(part)\n } else if (!text_placed) {\n text_placed = true\n if (stripped_text.length > 0) parts.push({ type: 'text', text: stripped_text })\n }\n }\n for (const tc of kept) parts.push(tool_call_part(tc))\n return parts\n}\n\n/**\n * Derive the step's cost and record it.\n *\n * A cost the provider reported wins over any pricing row, since it is what\n * was charged: it is split by token weight and recorded as\n * `provider_reported`, and the pricing lookup never runs, so no\n * `pricing_missing` either. Otherwise the cost comes from the pricing tables,\n * where missing pricing for a paid provider emits `pricing_missing` (deduped\n * per call) and yields no breakdown; free providers skip the emit entirely.\n */\nfunction compute_and_record_cost(\n config: ToolLoopConfig,\n step_index: number,\n turn: TurnResult,\n step_span: string | undefined,\n): CostBreakdown | undefined {\n if (turn.reported_cost_usd !== undefined) {\n const reported = decompose_total_cost(turn.reported_cost_usd, turn.usage)\n record_cost(config.trajectory, step_index, reported, 'provider_reported', step_span)\n return reported\n }\n const pricing = config.resolve_pricing()\n if (pricing === undefined && !FREE_PROVIDERS.has(config.provider)) {\n config.pricing_dedup.emit(config.provider, config.model_id)\n return undefined\n }\n const breakdown = compute_cost(turn.usage, pricing, config.provider)\n if (breakdown !== undefined) {\n record_cost(config.trajectory, step_index, breakdown, 'engine_derived', step_span)\n }\n return breakdown\n}\n\n/**\n * Validate a raw tool-call input against the tool's schema before execution,\n * returning the parsed value or a feedback-ready error message.\n */\nasync function validate_tool_input(\n tool: Tool,\n input: unknown,\n): Promise<{ ok: true; value: unknown } | { ok: false; message: string }> {\n const parsed = await validate_schema(tool.input_schema, input)\n if (parsed.ok) return { ok: true, value: parsed.value }\n return { ok: false, message: `invalid tool input: ${format_schema_issues(parsed.issues)}` }\n}\n\n/**\n * Apply the prepare_step hook for one turn. Returns the messages to send to\n * the transport: the hook's replacement when it returns `{ messages }`, else\n * config.messages unchanged. The replacement is ephemeral; it is fed ONLY to\n * invoke_once for this turn, never pushed onto config.messages, so the loop's\n * salvage/approval/ends_turn/schema-repair machinery keeps reading the real\n * transcript. A step_prepared event (recorded inline, as request_sent is)\n * makes the mid-loop mutation legible with the before/after message counts.\n */\nasync function apply_prepare_step(\n config: ToolLoopConfig,\n step_index: number,\n): Promise<ReadonlyArray<Message>> {\n if (config.prepare_step === undefined) return config.messages\n const prepared = await config.prepare_step({\n step_index,\n messages: config.messages,\n })\n const replacement = prepared?.messages\n if (replacement === undefined) return config.messages\n config.trajectory?.record({\n kind: 'step_prepared',\n step_index,\n message_count_before: config.messages.length,\n message_count_after: replacement.length,\n })\n return replacement\n}\n\n/**\n * Mutable accumulators shared across loop iterations: the step records and\n * the flat list of every tool call the loop resolved.\n */\ntype LoopAccumulator = {\n readonly steps: StepRecord[]\n readonly tool_calls: ToolCallRecord[]\n}\n\n/**\n * Per-step working state threaded through the call-execution helpers.\n * `records` and `feed` accumulate in call order; `all_records` aliases the\n * loop-wide accumulator; `terminal_fired` flips when a call to a Tool\n * flagged ends_turn executes successfully (see the header invariant).\n */\ntype StepContext = {\n readonly config: ToolLoopConfig\n readonly tool_map: ReadonlyMap<string, Tool>\n readonly step_index: number\n readonly step_span: string | undefined\n readonly would_exceed_after: boolean\n readonly records: ToolCallRecord[]\n readonly all_records: ToolCallRecord[]\n readonly feed: Message[]\n terminal_fired: boolean\n}\n\n/**\n * One turn's effective view of the model output after salvage: the calls to\n * execute, the text history should carry, and the per-call salvage formats.\n * `outcome` is undefined when no salvage applied (native calls pass through).\n */\ntype SalvageView = {\n readonly calls: ReadonlyArray<RawToolCall>\n readonly history_text: string\n readonly formats: ReadonlyMap<string, SalvageFormat>\n readonly outcome: SalvageOutcome | undefined\n}\n\n/**\n * Assemble the loop's return value from the accumulated steps and records.\n */\nfunction loop_result(\n acc: LoopAccumulator,\n text: string,\n finish_reason: FinishReason,\n max_steps_reached: boolean,\n): ToolLoopResult {\n return { text, steps: acc.steps, tool_calls: acc.tool_calls, finish_reason, max_steps_reached }\n}\n\n/**\n * Invoke the transport seam once for one turn, bracketed by request_sent /\n * response_received events. A thrown invoke (or prepare_step) closes the\n * step span with the error before rethrowing.\n */\nasync function invoke_turn(\n config: ToolLoopConfig,\n step_index: number,\n step_span: string | undefined,\n): Promise<TurnResult> {\n try {\n const request_messages = await apply_prepare_step(config, step_index)\n config.trajectory?.record({ kind: 'request_sent', step_index })\n const turn = await config.invoke_once({\n step_index,\n messages: request_messages,\n tools: config.tools,\n abort: config.abort,\n stream: config.stream,\n step_span,\n })\n record_response_received(config.trajectory, step_index, turn, step_span)\n return turn\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err)\n end_step_span(config.trajectory, step_span, { error: message })\n throw err\n }\n}\n\n/**\n * Salvage text-embedded tool calls from an eligible turn.\n *\n * A turn that \"stopped\" with plain text may hold a call the runtime failed\n * to parse into tool_calls; salvage before deciding the step ends the loop.\n * History gets the stripped text + structured parts (raw markup in history\n * would teach the model the text format works, and a tool result without a\n * matching call part is rejected by OpenAI-compatible APIs);\n * StepRecord.text keeps the raw text for debugging. Returns the native view\n * unchanged when the turn is ineligible or nothing salvages.\n */\nasync function salvage_turn(\n config: ToolLoopConfig,\n turn: TurnResult,\n tool_map: ReadonlyMap<string, Tool>,\n step_index: number,\n): Promise<SalvageView> {\n const native: SalvageView = {\n calls: turn.tool_calls,\n history_text: turn.text,\n formats: new Map(),\n outcome: undefined,\n }\n const budget = config.salvage_budget\n const eligible =\n turn.tool_calls.length === 0 &&\n (turn.finish_reason === 'stop' || turn.finish_reason === 'length') &&\n config.tools.length > 0 &&\n budget !== undefined &&\n budget.remaining > 0\n if (!eligible) return native\n\n const outcome = await salvage_tool_calls(turn.text, tool_map)\n if (outcome === undefined) return native\n budget.remaining -= 1\n const formats = new Map<string, SalvageFormat>()\n const calls = outcome.calls.map((c, n) => {\n const id = `salvaged_${step_index}_${n}`\n formats.set(id, c.format)\n return { id, name: c.name, input: c.input }\n })\n record_tool_call_salvaged(config.trajectory, {\n step_index,\n calls: calls.map((c) => ({\n tool_call_id: c.id,\n name: c.name,\n // Stryker disable next-line StringLiteral: formats has an entry for every id (set just above), so the ?? 'json' fallback is unreachable.\n format: formats.get(c.id) ?? 'json',\n })),\n raw_text: turn.text,\n })\n await dispatch_salvaged_call_chunks(config, calls, step_index)\n return { calls, history_text: outcome.stripped_text, formats, outcome }\n}\n\n/**\n * Mirror the native stream for salvaged calls, which emits start/end for\n * every call the model attempted, including ones the per-step clamp later\n * drops.\n */\nasync function dispatch_salvaged_call_chunks(\n config: ToolLoopConfig,\n calls: ReadonlyArray<RawToolCall>,\n step_index: number,\n): Promise<void> {\n if (config.dispatch_chunk === undefined) return\n for (const c of calls) {\n await config.dispatch_chunk({\n kind: 'tool_call_start',\n id: c.id,\n name: c.name,\n step_index,\n })\n await config.dispatch_chunk({\n kind: 'tool_call_end',\n id: c.id,\n input: c.input,\n step_index,\n })\n }\n}\n\n/**\n * Apply `max_tool_calls_per_step` to a turn's calls, native and salvaged\n * alike. Dropped calls never reach history; the model re-issues them on a\n * later turn if it still wants them.\n */\nfunction clamp_calls(\n config: ToolLoopConfig,\n calls: ReadonlyArray<RawToolCall>,\n step_index: number,\n): { kept: ReadonlyArray<RawToolCall>; dropped: ReadonlyArray<RawToolCall> } {\n const cap = config.max_tool_calls_per_step\n if (cap === undefined || calls.length <= cap) return { kept: calls, dropped: [] }\n const kept = calls.slice(0, cap)\n const dropped = calls.slice(cap)\n record_tool_calls_dropped(config.trajectory, {\n step_index,\n max_tool_calls_per_step: cap,\n kept: kept.length,\n dropped: dropped.map((d) => ({ tool_call_id: d.id, name: d.name })),\n })\n return { kept, dropped }\n}\n\n/**\n * Record a call that resolved to an error on the feed-back path: the error\n * record, the fed-back error tool_result message, the tool_call trajectory\n * event, and the stream chunk, in that order. Throw-policy paths raise\n * before reaching here.\n */\nasync function record_failed_call(\n ctx: StepContext,\n call: { id: string; name: string; input: unknown },\n message: string,\n timing: { duration_ms: number; started_at: number },\n): Promise<void> {\n const record: ToolCallRecord = {\n id: call.id,\n name: call.name,\n input: call.input,\n error: { message },\n duration_ms: timing.duration_ms,\n started_at: timing.started_at,\n }\n ctx.records.push(record)\n ctx.all_records.push(record)\n ctx.feed.push(\n build_tool_result_message(call.id, call.name, { error: message }),\n )\n record_tool_call(ctx.config.trajectory, {\n step_index: ctx.step_index,\n name: call.name,\n tool_call_id: call.id,\n input: call.input,\n duration_ms: timing.duration_ms,\n error: { message },\n })\n await dispatch_tool_result_chunk(\n ctx.config.dispatch_chunk,\n ctx.step_index,\n call.id,\n undefined,\n { message },\n )\n}\n\n/**\n * Record a call that never reached execution (the final-turn max_steps skip,\n * the per-step-cap drop): an error record and a tool_result stream chunk,\n * but no tool_call trajectory event, no execution, and no fed-back tool\n * message.\n */\nasync function record_unexecuted_call(\n ctx: StepContext,\n call: RawToolCall,\n message: string,\n): Promise<void> {\n const record: ToolCallRecord = {\n id: call.id,\n name: call.name,\n input: call.input,\n error: { message },\n duration_ms: 0,\n started_at: Date.now(),\n }\n ctx.records.push(record)\n ctx.all_records.push(record)\n await dispatch_tool_result_chunk(\n ctx.config.dispatch_chunk,\n ctx.step_index,\n call.id,\n undefined,\n { message },\n )\n}\n\n/**\n * Look up the named tool and validate the raw input against its schema.\n * Returns undefined when the failure was recorded on the feed-back path;\n * throws under 'throw' policy for an unknown tool.\n */\nasync function resolve_tool_and_input(\n ctx: StepContext,\n raw_call: RawToolCall,\n): Promise<{ tool: Tool; input: unknown } | undefined> {\n const tool = ctx.tool_map.get(raw_call.name)\n if (tool === undefined) {\n const err_message = `unknown tool '${raw_call.name}'`\n if (ctx.config.tool_error_policy === 'throw') {\n const thrown = new tool_error(err_message, {\n tool_name: raw_call.name,\n tool_call_id: raw_call.id,\n cause: new Error(err_message),\n })\n end_step_span(ctx.config.trajectory, ctx.step_span, { error: err_message })\n throw thrown\n }\n await record_failed_call(ctx, raw_call, err_message, {\n duration_ms: 0,\n started_at: Date.now(),\n })\n return undefined\n }\n\n const validation = await validate_tool_input(tool, raw_call.input)\n if (!validation.ok) {\n await record_failed_call(ctx, raw_call, validation.message, {\n duration_ms: 0,\n started_at: Date.now(),\n })\n return undefined\n }\n\n return { tool, input: validation.value }\n}\n\n/**\n * Resolve whether the call may execute (see request_approval). A denial\n * either throws ('throw' policy) or records the denied call and returns\n * false; an abort or handler rejection closes the step span and rethrows.\n */\nasync function approve_call(\n ctx: StepContext,\n tool: Tool,\n input: unknown,\n raw_call: RawToolCall,\n): Promise<boolean> {\n let approved: boolean\n try {\n approved = await request_approval(\n tool,\n input,\n ctx.step_index,\n raw_call.id,\n ctx.config.abort,\n ctx.config.on_tool_approval,\n ctx.config.trajectory,\n )\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err)\n end_step_span(ctx.config.trajectory, ctx.step_span, { error: message })\n throw err\n }\n if (approved) return true\n\n const denied_message = 'tool_approval_denied'\n if (ctx.config.tool_error_policy === 'throw') {\n const thrown = new tool_approval_denied_error(\n `tool '${tool.name}' approval denied`,\n { tool_name: tool.name, step_index: ctx.step_index, tool_call_id: raw_call.id },\n )\n end_step_span(ctx.config.trajectory, ctx.step_span, { error: denied_message })\n throw thrown\n }\n await record_failed_call(\n ctx,\n { id: raw_call.id, name: tool.name, input },\n denied_message,\n { duration_ms: 0, started_at: Date.now() },\n )\n return false\n}\n\n/**\n * Execute an approved call and record the outcome: a success record with\n * output (flipping terminal_fired for an ends_turn tool), or the error path\n * via record_execute_failure.\n */\nasync function execute_approved_call(\n ctx: StepContext,\n tool: Tool,\n input: unknown,\n raw_call: RawToolCall,\n): Promise<void> {\n const started_at = Date.now()\n const tool_ctx: ToolExecContext = {\n abort: ctx.config.abort,\n tool_call_id: raw_call.id,\n step_index: ctx.step_index,\n ...(ctx.config.trajectory !== undefined ? { trajectory: ctx.config.trajectory } : {}),\n }\n\n let output: unknown\n let err_message: string | undefined\n let thrown: unknown\n try {\n const execute = tool.execute\n const maybe = execute(input, tool_ctx)\n output = maybe instanceof Promise ? await maybe : maybe\n } catch (err: unknown) {\n thrown = err\n err_message = serialize_error(err)\n }\n\n const duration_ms = Date.now() - started_at\n\n // err_message, not thrown, marks the failure: a tool may throw undefined.\n if (err_message !== undefined) {\n await record_execute_failure(ctx, tool, raw_call, input, {\n thrown,\n err_message,\n duration_ms,\n started_at,\n })\n return\n }\n\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: tool.name,\n input,\n output,\n duration_ms,\n started_at,\n }\n ctx.records.push(record)\n ctx.all_records.push(record)\n if (tool.ends_turn === true) ctx.terminal_fired = true\n ctx.feed.push(build_tool_result_message(raw_call.id, tool.name, output ?? ''))\n record_tool_call(ctx.config.trajectory, {\n step_index: ctx.step_index,\n name: tool.name,\n tool_call_id: raw_call.id,\n input,\n duration_ms,\n })\n await dispatch_tool_result_chunk(ctx.config.dispatch_chunk, ctx.step_index, raw_call.id, output)\n}\n\n/**\n * Handle a throwing execute: an abort in flight or 'throw' policy closes\n * the step span and throws; feed-back policy records the failure with the\n * measured timing.\n */\nasync function record_execute_failure(\n ctx: StepContext,\n tool: Tool,\n raw_call: RawToolCall,\n input: unknown,\n failure: {\n thrown: unknown\n err_message: string | undefined\n duration_ms: number\n started_at: number\n },\n): Promise<void> {\n if (ctx.config.abort.aborted) {\n const abort_err = new aborted_error('aborted', {\n reason: ctx.config.abort.reason,\n step_index: ctx.step_index,\n tool_call_in_flight: { id: raw_call.id, name: tool.name },\n })\n end_step_span(ctx.config.trajectory, ctx.step_span, { error: 'aborted' })\n throw abort_err\n }\n if (ctx.config.tool_error_policy === 'throw') {\n const wrapped = new tool_error(\n `tool '${tool.name}' failed: ${failure.err_message ?? 'unknown'}`,\n {\n tool_name: tool.name,\n tool_call_id: raw_call.id,\n cause: failure.thrown,\n },\n )\n end_step_span(ctx.config.trajectory, ctx.step_span, {\n // Stryker disable next-line StringLiteral: err_message is always a string in this branch (set from serialize_error in the catch), so the ?? 'tool error' fallback is unreachable.\n error: failure.err_message ?? 'tool error',\n })\n throw wrapped\n }\n await record_failed_call(\n ctx,\n { id: raw_call.id, name: tool.name, input },\n // Stryker disable next-line StringLiteral: err_message is always a string here (see catch above), so this ?? 'unknown' fallback is unreachable.\n failure.err_message ?? 'unknown',\n { duration_ms: failure.duration_ms, started_at: failure.started_at },\n )\n}\n\n/**\n * Run one raw tool call through the guard chain (final-turn skip, tool\n * lookup, input validation, approval), then execute it. Each guard either\n * records the failure (feed-back policy) and stops, or throws (throw\n * policy / abort).\n */\nasync function process_call(ctx: StepContext, raw_call: RawToolCall): Promise<void> {\n throw_if_aborted_in_flight(ctx.config.abort, ctx.step_index, {\n id: raw_call.id,\n name: raw_call.name,\n })\n\n // A successful terminal call needs no follow-up turn, so it is exempt\n // from this skip: it executes below and ends the loop cleanly, winning\n // over the coincident max_steps cap.\n if (ctx.would_exceed_after && ctx.tool_map.get(raw_call.name)?.ends_turn !== true) {\n await record_unexecuted_call(ctx, raw_call, 'max_steps_exceeded_before_execution')\n return\n }\n\n const resolved = await resolve_tool_and_input(ctx, raw_call)\n if (resolved === undefined) return\n\n const approved = await approve_call(ctx, resolved.tool, resolved.input, raw_call)\n if (!approved) return\n\n throw_if_aborted_in_flight(ctx.config.abort, ctx.step_index, {\n id: raw_call.id,\n name: resolved.tool.name,\n })\n\n await execute_approved_call(ctx, resolved.tool, resolved.input, raw_call)\n}\n\n/**\n * Stamp salvage provenance onto the records of calls that came from text\n * salvage rather than structured output.\n */\nfunction mark_salvaged(\n records: ReadonlyArray<ToolCallRecord>,\n formats: ReadonlyMap<string, SalvageFormat>,\n): void {\n for (const r of records) {\n const format = formats.get(r.id)\n if (format !== undefined) {\n r.salvaged = true\n r.salvaged_format = format\n }\n }\n}\n\n/**\n * Emit a tool_result for every resolved call in this step (success carries\n * output, feed-back failures carry error). Throw-policy and aborted calls\n * exit before here and surface loudly as a thrown error instead.\n */\nfunction emit_tool_results(\n config: ToolLoopConfig,\n step_index: number,\n records: ReadonlyArray<ToolCallRecord>,\n): void {\n for (const r of records) {\n record_tool_result(config.trajectory, {\n step_index,\n name: r.name,\n tool_call_id: r.id,\n duration_ms: r.duration_ms,\n ...(r.error !== undefined ? { error: r.error } : { output: r.output }),\n })\n }\n}\n\n/**\n * The finish reason a tool-call step reports. A salvaged step reports\n * 'tool_calls': downstream consumers see the same shape a native tool turn\n * produces; the salvaged flags carry provenance. A terminal step reports\n * 'tool_calls' (it genuinely made calls); the loop-level finish_reason\n * 'stop' is the separate signal that generation ended.\n */\nfunction resolve_turn_finish_reason(\n ctx: StepContext,\n salvaged: boolean,\n turn_finish: FinishReason,\n): FinishReason {\n if (ctx.terminal_fired) return 'tool_calls'\n if (ctx.would_exceed_after) return 'max_steps'\n if (salvaged) return 'tool_calls'\n return turn_finish\n}\n\n/**\n * Build one StepRecord (cost derived and recorded, timing and\n * provider_reported passed through), push it, notify on_finish_step, and\n * close the step span.\n */\nfunction push_step_record(\n config: ToolLoopConfig,\n acc: LoopAccumulator,\n step_index: number,\n turn: TurnResult,\n tool_calls: ToolCallRecord[],\n finish_reason: FinishReason,\n step_span: string | undefined,\n): void {\n const record: StepRecord = {\n index: step_index,\n text: turn.text,\n tool_calls,\n usage: turn.usage,\n finish_reason,\n }\n const breakdown = compute_and_record_cost(config, step_index, turn, step_span)\n if (breakdown !== undefined) record.cost = breakdown\n if (turn.timing !== undefined) record.timing = turn.timing\n if (turn.provider_reported !== undefined) {\n record.provider_reported = turn.provider_reported\n }\n acc.steps.push(record)\n if (config.on_finish_step !== undefined) config.on_finish_step(record)\n end_step_span(config.trajectory, step_span, {\n usage: turn.usage,\n finish_reason,\n })\n}\n\n/**\n * Run one loop iteration: invoke the turn, salvage and clamp its calls,\n * execute them sequentially, and record the step. Returns the finished\n * ToolLoopResult when this step ends the loop (no calls, terminal tool,\n * max_steps), undefined when the loop should continue.\n */\nasync function run_loop_step(\n config: ToolLoopConfig,\n tool_map: ReadonlyMap<string, Tool>,\n acc: LoopAccumulator,\n step_index: number,\n): Promise<ToolLoopResult | undefined> {\n const step_span = start_step_span(config.trajectory, step_index)\n const turn = await invoke_turn(config, step_index, step_span)\n\n const view = await salvage_turn(config, turn, tool_map, step_index)\n const { kept, dropped } = clamp_calls(config, view.calls, step_index)\n config.messages.push(build_assistant_message(turn, view, kept))\n\n if (kept.length === 0) {\n push_step_record(config, acc, step_index, turn, [], turn.finish_reason, step_span)\n return loop_result(acc, turn.text, turn.finish_reason, false)\n }\n\n // This turn has tool calls. Execute them sequentially.\n const ctx: StepContext = {\n config,\n tool_map,\n step_index,\n step_span,\n would_exceed_after: step_index + 1 >= config.max_steps,\n records: [],\n all_records: acc.tool_calls,\n feed: [],\n terminal_fired: false,\n }\n for (const raw_call of kept) await process_call(ctx, raw_call)\n\n // Dropped calls mirror the max_steps precedent: a record with an error\n // and a tool_result event/chunk, but no tool_call event, no execution,\n // and no fed-back tool message (their call parts are not in history).\n for (const d of dropped) {\n await record_unexecuted_call(ctx, d, 'dropped_max_tool_calls_per_step')\n }\n\n mark_salvaged(ctx.records, view.formats)\n emit_tool_results(config, step_index, ctx.records)\n for (const m of ctx.feed) config.messages.push(m)\n\n const turn_finish_reason = resolve_turn_finish_reason(\n ctx,\n view.outcome !== undefined,\n turn.finish_reason,\n )\n push_step_record(config, acc, step_index, turn, ctx.records, turn_finish_reason, step_span)\n\n // A successful terminal call ends the loop cleanly. Placed before the\n // max_steps break so a terminal finish wins over a coincident cap: the\n // full step is already recorded, so the result stays complete.\n if (ctx.terminal_fired) return loop_result(acc, turn.text, 'stop', false)\n if (ctx.would_exceed_after) return loop_result(acc, turn.text, 'max_steps', true)\n return undefined\n}\n\n/**\n * Run the model-turn / tool-execution loop to completion.\n *\n * Each iteration invokes the transport seam once, salvages text-embedded\n * tool calls when eligible, clamps to `max_tool_calls_per_step`, executes\n * calls sequentially under the header invariants, and feeds results back\n * until the model stops, a terminal tool fires, or `max_steps` is reached.\n */\nexport async function run_tool_loop(config: ToolLoopConfig): Promise<ToolLoopResult> {\n const acc: LoopAccumulator = { steps: [], tool_calls: [] }\n const tool_map = new Map<string, Tool>()\n for (const t of config.tools) tool_map.set(t.name, t)\n\n let step_index = config.step_index_start\n while (true) {\n throw_if_aborted(config.abort, step_index)\n if (step_index >= config.max_steps) return loop_result(acc, '', 'max_steps', true)\n const finished = await run_loop_step(config, tool_map, acc, step_index)\n if (finished !== undefined) return finished\n step_index += 1\n }\n}\n","/**\n * `generate(opts)`: the single public entry point for model calls.\n *\n * This file is SDK-agnostic: it resolves options, gates capabilities, and\n * owns retry and trajectory recording, and it drives every turn\n * (both the `ai_sdk` and native transports) through the neutral\n * `invoke_turn` seam. The Vercel AI SDK call itself lives in\n * providers/ai_sdk/invoke.ts, the only module allowed to import from `ai`\n * (enforced by the no-ai-import-outside-ai-sdk-provider rule). tool_loop.ts\n * consumes the InvokeOnce seam built here.\n *\n * That seam is reached by `await import(...)` rather than a static import, and\n * the types it exports come in type-only (erased at compile time), so `ai`\n * enters the module graph only on a call that actually selects the ai_sdk\n * transport. A native-transport or claude_cli user never loads it.\n */\n\nimport type {\n AiSdkTelemetrySettings,\n CostBreakdown,\n EffortLevel,\n FinishReason,\n GenerateOptions,\n GenerateResult,\n GenerateTiming,\n Message,\n Pricing,\n PricingTable,\n ResolvedModel,\n RetryPolicy,\n StepTiming,\n StreamChunk,\n Tool,\n TurnRequest,\n TurnResult,\n} from './types.js'\nimport {\n aborted_error,\n engine_config_error,\n incomplete_generation_error,\n model_required_error,\n on_chunk_error,\n provider_capability_error,\n provider_error,\n provider_not_configured_error,\n provider_required_error,\n turn_timeout_error,\n} from './errors.js'\nimport { format_schema_issues, to_json_schema } from '#schema'\nimport type { ToolSchema } from '#schema'\nimport type { TrajectoryLogger } from '#core'\nimport { split_leading_system_run } from './leading_system.js'\nimport { merge_provider_options } from './merge_defaults.js'\nimport { FREE_PROVIDERS, pricing_key, round6 } from './pricing.js'\nimport { parse_retry_after, retry_with_policy } from './retry.js'\nimport {\n build_repair_message,\n parse_with_schema,\n throw_schema_validation,\n} from './schema.js'\nimport {\n create_chunk_dispatcher,\n type ChunkDispatcher,\n} from './streaming.js'\nimport {\n create_pricing_missing_dedup,\n end_generate_span,\n record_effort_ignored,\n record_schema_validation_failed,\n record_turn_retry,\n start_generate_span,\n with_timestamps,\n} from './trajectory.js'\nimport { sum_usage } from './usage.js'\nimport {\n run_tool_loop,\n type InvokeOnce,\n type InvokeOnceArgs,\n type ToolLoopConfig,\n} from './tool_loop.js'\nimport { missing_peer_error } from './providers/types.js'\nimport type {\n AiSdkProviderAdapter,\n NativeProviderAdapter,\n ProviderAdapter,\n} from './providers/types.js'\nimport type { AiSdkTurn, AiSdkTurnConfig } from './providers/ai_sdk/invoke.js'\n\nexport type EngineInternals = {\n readonly pricing: PricingTable\n readonly adapters: ReadonlyMap<string, ProviderAdapter>\n readonly default_retry: RetryPolicy\n readonly default_effort: EffortLevel\n readonly default_max_steps: number\n readonly default_turn_timeout_ms?: number\n readonly default_ai_sdk_telemetry?: AiSdkTelemetrySettings\n readonly default_model?: string\n readonly default_provider?: string\n readonly default_system?: string\n readonly default_temperature?: number\n readonly default_max_tokens?: number\n readonly default_top_p?: number\n readonly default_tool_error_policy?: 'feed_back' | 'throw'\n readonly default_schema_repair_attempts?: number\n readonly default_tool_call_repair_attempts?: number\n readonly default_max_tool_calls_per_step?: number\n readonly default_provider_options?: Readonly<Record<string, Readonly<Record<string, unknown>>>>\n}\n\n/**\n * Build the initial message list for a generate call from `opts.system` and\n * `opts.prompt`.\n *\n * A non-empty string `system` is prepended as a system message. A string\n * `prompt` becomes a single user message; a `Message[]` prompt is copied\n * through element-by-element so the returned array can be mutated without\n * affecting the caller's.\n */\nexport function build_initial_messages<T>(opts: GenerateOptions<T>): Message[] {\n const messages: Message[] = []\n if (typeof opts.system === 'string' && opts.system.length > 0) {\n messages.push({ role: 'system', content: opts.system })\n }\n if (typeof opts.prompt === 'string') {\n messages.push({ role: 'user', content: opts.prompt })\n return messages\n }\n for (const m of opts.prompt) messages.push({ ...m })\n return messages\n}\n\n/**\n * The engine-Message analog of the SDK-side split_leading_system\n * (providers/ai_sdk/invoke.ts): build_native_invoke hoists the leading system\n * run into TurnRequest.system so a native adapter maps conversation messages\n * only. Same guards as the SDK variant: only the leading run is hoisted, and\n * the original list is returned untouched when hoisting would leave `messages`\n * empty (provider APIs reject an empty messages array).\n */\nexport function split_leading_system_messages(messages: ReadonlyArray<Message>): {\n system?: string\n messages: Message[]\n} {\n return split_leading_system_run(messages, (m) => m.content)\n}\n\nconst RETRY_CLASSIFIED_KINDS = new Set(['rate_limit', 'provider_5xx', 'network', 'timeout'])\nconst NETWORK_ERROR_CODES = new Set(['ECONNRESET', 'ETIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED'])\n\n/**\n * True when `err` already carries a `kind` this layer treats as retryable, so\n * the classifier passes it through untouched.\n */\nfunction has_retry_kind(err: object): boolean {\n const kind = Reflect.get(err, 'kind')\n return typeof kind === 'string' && RETRY_CLASSIFIED_KINDS.has(kind)\n}\n\n/**\n * Read the HTTP status off either `statusCode` or `status`, in that order.\n */\nfunction resolve_error_status(err: object): number | undefined {\n const status = Reflect.get(err, 'statusCode')\n if (typeof status === 'number') return status\n const status_alt = Reflect.get(err, 'status')\n return typeof status_alt === 'number' ? status_alt : undefined\n}\n\n/**\n * Copy the error's `message` onto a classification record when it is a string,\n * returning the same record for chaining.\n */\nfunction with_error_message(\n err: object,\n out: Record<string, unknown>,\n): Record<string, unknown> {\n const message = Reflect.get(err, 'message')\n if (typeof message === 'string') out['message'] = message\n return out\n}\n\n/**\n * Parse a `Retry-After` value off the error's `responseHeaders`, if present.\n */\nfunction retry_after_from_error(err: object): number | undefined {\n const headers = Reflect.get(err, 'responseHeaders')\n if (headers === null || typeof headers !== 'object') return undefined\n const hv = Reflect.get(headers, 'retry-after')\n return typeof hv === 'string' ? parse_retry_after(hv) : undefined\n}\n\n/**\n * Build the `rate_limit` classification for a 429, attaching the message and a\n * parsed `Retry-After` when either is present.\n */\nfunction classify_rate_limit(err: object): Record<string, unknown> {\n const out = with_error_message(err, { kind: 'rate_limit', status: 429 })\n const retry_after_ms = retry_after_from_error(err)\n if (retry_after_ms !== undefined) out['retry_after_ms'] = retry_after_ms\n return out\n}\n\n/**\n * Build the `network` classification when `err.code` is a known network error\n * code, or `undefined` when it is not.\n */\nfunction classify_network_error(err: object): Record<string, unknown> | undefined {\n const code = Reflect.get(err, 'code')\n if (typeof code !== 'string' || !NETWORK_ERROR_CODES.has(code)) return undefined\n return with_error_message(err, { kind: 'network' })\n}\n\n/**\n * Classify a thrown provider error into the shape `retry_with_policy`\n * understands.\n *\n * Passes through anything that already carries a recognized `kind`.\n * Otherwise inspects `statusCode`/`status`: 429 becomes `rate_limit`\n * (reading `Retry-After` off `responseHeaders` when present), 5xx becomes\n * `provider_5xx`, and a known `ECONNRESET`/`ETIMEDOUT`/`ENOTFOUND`/\n * `ECONNREFUSED` error code becomes `network`. Anything else passes through\n * unclassified, which `retry_with_policy` treats as non-retryable.\n */\nexport function classify_provider_error(err: unknown): unknown {\n if (err === null || typeof err !== 'object') return err\n if (has_retry_kind(err)) return err\n const status = resolve_error_status(err)\n if (status === 429) return classify_rate_limit(err)\n if (status !== undefined && status >= 500 && status < 600) {\n return with_error_message(err, { kind: 'provider_5xx', status })\n }\n return classify_network_error(err) ?? err\n}\n\ntype AiSdkInvokeConfig = {\n readonly invoke_turn: AiSdkTurn\n readonly retry_policy: RetryPolicy\n readonly turn_timeout_ms: number | undefined\n readonly trajectory: TrajectoryLogger | undefined\n}\n\ntype NativeInvokeConfig = {\n readonly adapter: NativeProviderAdapter\n readonly model_id: string\n readonly retry_policy: RetryPolicy\n readonly turn_timeout_ms: number | undefined\n readonly trajectory: TrajectoryLogger | undefined\n readonly dispatcher: ChunkDispatcher\n readonly effort: EffortLevel\n readonly schema: TurnRequest['schema']\n readonly provider_options: TurnRequest['provider_options']\n readonly temperature: number | undefined\n readonly max_tokens: number | undefined\n readonly top_p: number | undefined\n}\n\ntype TurnDeadline = {\n readonly signal: AbortSignal\n readonly timed_out: () => boolean\n readonly dispose: () => void\n}\n\n/**\n * Compose the per-attempt turn signal: the user's abort OR'd with a fresh\n * `turn_timeout_ms` deadline via `AbortSignal.any` (the same pattern\n * `src/core/timeout.ts` uses). `timed_out()` distinguishes an expiry\n * (retryable) from a user abort (terminal) in the `retry_turn` ladder;\n * `dispose()` clears the timer so a settled attempt never leaves one armed.\n * With no budget configured, the user's abort signal passes through\n * unchanged. Armed fresh inside `retry_with_policy`'s callback so each retry\n * gets its own full budget rather than sharing one deadline across attempts.\n */\nfunction arm_turn_timeout(\n user_abort: AbortSignal,\n turn_timeout_ms: number | undefined,\n): TurnDeadline {\n if (turn_timeout_ms === undefined) {\n // Stryker disable next-line ArrowFunction: timed_out is only ever read as `if (deadline.timed_out())`, where () => undefined and () => false are both falsy, so the mutant is behaviorally identical.\n return { signal: user_abort, timed_out: () => false, dispose: () => {} }\n }\n const local = new AbortController()\n const composed = AbortSignal.any([user_abort, local.signal])\n let timed_out = false\n const timer = setTimeout(() => {\n timed_out = true\n local.abort()\n }, turn_timeout_ms)\n return {\n signal: composed,\n timed_out: () => timed_out,\n dispose: () => {\n clearTimeout(timer)\n },\n }\n}\n\n/**\n * Engine-owned wrapper shared by both transports: one turn attempt inside\n * retry_with_policy. The catch ladder classifies by CAUSE, not\n * by the shape the transport happened to throw: on_chunk_error passes through,\n * then a genuine user abort wins, then any error once a chunk has flowed is a\n * non-retryable stream interruption, then a pre-chunk `turn_timeout_ms` expiry\n * is a retryable typed timeout, and only a below-loop aborted_error unrelated\n * to either passes through. Cause-first ordering is what keeps the two\n * transports in parity: the ai_sdk transport reports a mid-stream abort as an\n * aborted_error and the native one as a raw AbortError, so both must be read as\n * the same interruption rather than the ai_sdk timeout masquerading as a user\n * cancel. call_once receives the composed abort+timeout signal so the deadline\n * actually cancels the in-flight request. Adapters may swap `classify`, but\n * never the ladder itself: the engine owns retry, so a hidden adapter-level\n * retry would be invisible to anything relying on this ladder.\n *\n * The wrapper also stamps StepTiming here, and only here, because this is the\n * one place that can see attempt boundaries: started_at re-stamps at every\n * attempt entry, so failed attempts and backoff waits never inflate\n * duration_ms. `first_chunk_at` (the builder's Date.now() from its first\n * dispatched chunk) can only belong to the returning attempt, since any\n * failure after a chunk has flowed is non-retryable by the ladder below.\n */\nfunction retry_turn(\n call_once: (turn_abort: AbortSignal) => Promise<TurnResult>,\n args: InvokeOnceArgs,\n first_chunk_at: () => number | undefined,\n retry_policy: RetryPolicy,\n classify: (err: unknown) => unknown,\n turn_timeout_ms: number | undefined,\n trajectory: TrajectoryLogger | undefined,\n): Promise<TurnResult> {\n const has_streamed = (): boolean => first_chunk_at() !== undefined\n return retry_with_policy(\n async () => {\n const started_at = Date.now()\n const deadline = arm_turn_timeout(args.abort, turn_timeout_ms)\n try {\n const turn = await call_once(deadline.signal)\n return { ...turn, timing: build_step_timing(started_at, first_chunk_at()) }\n } catch (err: unknown) {\n if (err instanceof on_chunk_error) throw err\n // A genuine user abort wins over everything below it, including a\n // deadline that fired in the same tick, so an intentional cancel\n // always surfaces as aborted_error.\n if (args.abort.aborted) {\n throw new aborted_error('aborted', {\n reason: args.abort.reason,\n step_index: args.step_index,\n })\n }\n // Any failure once a chunk has flowed is a non-retryable stream\n // interruption, a deadline expiry included (a retry would re-emit\n // output the consumer already saw). Checked before the aborted_error\n // pass-through so a mid-stream ai_sdk abort classifies here, in parity\n // with the native transport's raw AbortError.\n if (has_streamed()) {\n const message = err instanceof Error ? err.message : String(err)\n throw new provider_error(`stream interrupted: ${message}`, {\n cause_kind: 'unknown',\n })\n }\n // A pre-chunk deadline expiry is a retryable typed timeout, whatever\n // shape the transport threw when its signal aborted. turn_timeout_ms is\n // defined whenever timed_out() can be true.\n if (deadline.timed_out()) {\n throw new turn_timeout_error(turn_timeout_ms ?? 0, args.step_index)\n }\n // A below-loop aborted_error not attributable to the user or the\n // deadline passes through unclassified.\n if (err instanceof aborted_error) throw err\n throw classify(err)\n } finally {\n deadline.dispose()\n }\n },\n retry_policy,\n args.abort,\n (info) => {\n record_turn_retry(trajectory, args.step_index, info, args.step_span)\n },\n )\n}\n\n/**\n * Assemble one turn's StepTiming from the attempt's start stamp and the\n * builder's first-chunk stamp (undefined on non-streamed turns).\n */\nfunction build_step_timing(\n started_at: number,\n first_chunk: number | undefined,\n): StepTiming {\n const timing: StepTiming = { started_at, duration_ms: Date.now() - started_at }\n if (first_chunk !== undefined) timing.first_chunk_ms = first_chunk - started_at\n return timing\n}\n\n/**\n * Build the ai_sdk-transport InvokeOnce: the SDK turn built by\n * providers/ai_sdk/invoke.ts behind the same engine-owned retry_turn wrapper\n * the native path uses. The SDK call body lives behind the seam; this builder\n * owns only retry and the streamed-output tracking that makes a mid-stream\n * failure a non-retryable interruption (the same first-chunk stamp doubles as\n * StepTiming.first_chunk_ms).\n */\nfunction build_ai_sdk_invoke(cfg: AiSdkInvokeConfig): InvokeOnce {\n return async (args: InvokeOnceArgs): Promise<TurnResult> => {\n let first_chunk_at: number | undefined\n const call_once = (turn_abort: AbortSignal): Promise<TurnResult> =>\n cfg.invoke_turn({\n step_index: args.step_index,\n messages: args.messages,\n abort: turn_abort,\n stream: args.stream,\n on_first_chunk: () => {\n first_chunk_at ??= Date.now()\n },\n })\n\n return await retry_turn(\n call_once,\n args,\n () => first_chunk_at,\n cfg.retry_policy,\n classify_provider_error,\n cfg.turn_timeout_ms,\n cfg.trajectory,\n )\n }\n}\n\n/**\n * Build the native-transport InvokeOnce: maps the loop's InvokeOnceArgs to a\n * TurnRequest and calls adapter.invoke_turn inside the same retry_turn\n * wrapper as the ai_sdk path. The adapter sees a child abort signal so a\n * throwing on_chunk consumer cancels the in-flight request, and its chunk\n * emissions flow through the shared dispatcher, which is what lets\n * run_tool_loop treat both transports identically.\n */\nfunction build_native_invoke(cfg: NativeInvokeConfig): InvokeOnce {\n const classify = cfg.adapter.classify_error ?? classify_provider_error\n return async (args: InvokeOnceArgs): Promise<TurnResult> => {\n let first_chunk_at: number | undefined\n const call_once = async (turn_abort: AbortSignal): Promise<TurnResult> => {\n // turn_abort is the composed user-abort + turn_timeout deadline; the\n // internal controller adds one more reason to cancel (a throwing chunk\n // consumer) without losing either of those.\n const internal_controller = new AbortController()\n const cancel_on_turn_abort = (): void => {\n internal_controller.abort(turn_abort.reason)\n }\n // Stryker disable next-line BlockStatement: unreachable pre-abort guard. retry_with_policy re-checks abort.aborted at the top of every attempt and there is no await between that check and this synchronous read, so the composed turn_abort is never already-aborted when call_once begins.\n if (turn_abort.aborted) {\n internal_controller.abort(turn_abort.reason)\n } else {\n // Stryker disable next-line ObjectLiteral,BooleanLiteral: { once: true } is a cleanup optimization only. The abort event is terminal (fires at most once) and the finally below removes the listener, so once:false is unobservable.\n turn_abort.addEventListener('abort', cancel_on_turn_abort, { once: true })\n }\n const dispatch_chunk = async (chunk: StreamChunk): Promise<void> => {\n first_chunk_at ??= Date.now()\n try {\n await cfg.dispatcher.dispatch(chunk)\n } catch (err: unknown) {\n internal_controller.abort()\n throw err\n }\n }\n const { system, messages } = split_leading_system_messages(args.messages)\n const req: TurnRequest = {\n step_index: args.step_index,\n messages,\n tools: args.tools,\n abort: internal_controller.signal,\n stream: args.stream,\n model_id: cfg.model_id,\n effort: cfg.effort,\n ...(system !== undefined ? { system } : {}),\n ...(cfg.schema !== undefined ? { schema: cfg.schema } : {}),\n ...(cfg.provider_options !== undefined\n ? { provider_options: cfg.provider_options }\n : {}),\n ...(cfg.temperature !== undefined ? { temperature: cfg.temperature } : {}),\n ...(cfg.max_tokens !== undefined ? { max_tokens: cfg.max_tokens } : {}),\n ...(cfg.top_p !== undefined ? { top_p: cfg.top_p } : {}),\n ...(args.stream ? { dispatch_chunk } : {}),\n }\n try {\n return await cfg.adapter.invoke_turn(req)\n } finally {\n // The finally is listener cleanup only: with { once: true } the listener\n // self-removes on fire and the composed turn_abort is attempt-scoped, so\n // an emptied finally or an empty event name here leaks nothing\n // observable (the BlockStatement survivor is a documented equivalent).\n // Stryker disable next-line StringLiteral: unobservable cleanup, see above.\n turn_abort.removeEventListener('abort', cancel_on_turn_abort)\n }\n }\n\n return await retry_turn(\n call_once,\n args,\n () => first_chunk_at,\n cfg.retry_policy,\n classify,\n cfg.turn_timeout_ms,\n cfg.trajectory,\n )\n }\n}\n\n/**\n * Resolve the provider name: per-call, then the engine default, then the sole\n * configured adapter. With several providers configured and neither a per-call\n * provider nor a default, there is no sane guess, so this throws\n * provider_required_error naming the configured providers.\n */\nfunction resolve_provider<T>(\n opts_in: GenerateOptions<T>,\n engine: EngineInternals,\n): string {\n const sole_provider =\n engine.adapters.size === 1 ? [...engine.adapters.keys()][0] : undefined\n const resolved = opts_in.provider ?? engine.default_provider ?? sole_provider\n if (resolved === undefined) {\n throw new provider_required_error([...engine.adapters.keys()])\n }\n return resolved\n}\n\n/**\n * Resolve the model/provider pair for one call and freeze the resolved\n * options view.\n *\n * The model must resolve (per-call, then engine default) or the call cannot\n * proceed. Engine-default system, sampling knobs (temperature, max_tokens,\n * top_p), and provider_options merge under per-call ones here so every\n * transport downstream sees a single already-merged view instead of\n * re-merging per branch.\n */\nfunction resolve_target<T>(\n opts_in: GenerateOptions<T>,\n engine: EngineInternals,\n): { opts: GenerateOptions<T>; target: ResolvedModel } {\n const resolved_model = opts_in.model ?? engine.default_model\n if (resolved_model === undefined) throw new model_required_error()\n const resolved_provider = resolve_provider(opts_in, engine)\n\n const merged_provider_options = merge_provider_options(\n engine.default_provider_options,\n opts_in.provider_options,\n )\n\n const opts: GenerateOptions<T> = {\n ...opts_in,\n model: resolved_model,\n provider: resolved_provider,\n }\n if (opts_in.system === undefined && engine.default_system !== undefined) {\n opts.system = engine.default_system\n }\n if (opts_in.temperature === undefined && engine.default_temperature !== undefined) {\n opts.temperature = engine.default_temperature\n }\n if (opts_in.max_tokens === undefined && engine.default_max_tokens !== undefined) {\n opts.max_tokens = engine.default_max_tokens\n }\n if (opts_in.top_p === undefined && engine.default_top_p !== undefined) {\n opts.top_p = engine.default_top_p\n }\n if (merged_provider_options !== undefined) {\n opts.provider_options = merged_provider_options\n }\n return {\n opts,\n target: { provider: resolved_provider, model_id: resolved_model },\n }\n}\n\n/**\n * Reject a call that uses a capability the resolved adapter does not\n * implement. Checked up front, before any transport work, so the failure is a\n * typed capability error rather than a mid-call provider rejection.\n */\nfunction assert_capabilities<T>(\n adapter: AiSdkProviderAdapter | NativeProviderAdapter,\n provider: string,\n opts: GenerateOptions<T>,\n tools_list: ReadonlyArray<Tool>,\n on_chunk_provided: boolean,\n): void {\n if (opts.schema !== undefined && !adapter.supports('schema')) {\n throw new provider_capability_error(provider, 'schema')\n }\n if (tools_list.length > 0 && !adapter.supports('tools')) {\n throw new provider_capability_error(provider, 'tools')\n }\n if (on_chunk_provided && !adapter.supports('streaming')) {\n throw new provider_capability_error(provider, 'streaming')\n }\n}\n\ntype TurnConfig = {\n readonly effort: EffortLevel\n readonly retry_policy: RetryPolicy\n readonly turn_timeout_ms: number | undefined\n}\n\n/**\n * Resolve the per-turn knobs (effort, retry policy, turn timeout) against\n * engine defaults. Validated here, before any transport is built, so a bad\n * budget fails as a config error, never as a spurious timeout.\n */\nfunction resolve_turn_config<T>(\n opts: GenerateOptions<T>,\n engine: EngineInternals,\n): TurnConfig {\n const effort: EffortLevel = opts.effort ?? engine.default_effort\n const retry_policy = opts.retry ?? engine.default_retry\n const turn_timeout_ms = opts.turn_timeout_ms ?? engine.default_turn_timeout_ms\n if (turn_timeout_ms !== undefined && turn_timeout_ms <= 0) {\n // A zero/negative budget would fire the deadline before the request even\n // starts; reject rather than silently disable or hang.\n throw new engine_config_error(`turn_timeout_ms must be > 0, got ${String(turn_timeout_ms)}`)\n }\n return { effort, retry_policy, turn_timeout_ms }\n}\n\ntype LoopLimits = {\n readonly max_steps: number\n readonly tool_error_policy: 'feed_back' | 'throw'\n readonly schema_repair_attempts: number\n readonly salvage_budget: { remaining: number } | undefined\n readonly max_tool_calls_per_step: number | undefined\n}\n\n/**\n * Resolve the tool-call salvage budget. Returned as a holder rather than a\n * count: one holder per generate call so schema-repair re-invocations of the\n * loop cannot refill the salvage budget. undefined disables salvage.\n */\nfunction resolve_salvage_budget<T>(\n opts: GenerateOptions<T>,\n engine: EngineInternals,\n): { remaining: number } | undefined {\n const tool_call_repair_attempts =\n opts.tool_call_repair_attempts ?? engine.default_tool_call_repair_attempts ?? 0\n if (tool_call_repair_attempts < 0) {\n throw new engine_config_error(\n `tool_call_repair_attempts must be >= 0, got ${String(tool_call_repair_attempts)}`,\n )\n }\n return tool_call_repair_attempts > 0\n ? { remaining: tool_call_repair_attempts }\n : undefined\n}\n\n/**\n * Resolve the loop-level limits and policies against engine defaults,\n * rejecting configurations the tool loop cannot honor.\n */\nfunction resolve_loop_limits<T>(\n opts: GenerateOptions<T>,\n engine: EngineInternals,\n): LoopLimits {\n const max_steps = opts.max_steps ?? engine.default_max_steps\n const tool_error_policy =\n // Stryker disable next-line StringLiteral: run_tool_loop treats any non-'throw' policy as feed_back, so '' and 'feed_back' resolve to identical behavior.\n opts.tool_error_policy ?? engine.default_tool_error_policy ?? 'feed_back'\n const schema_repair_attempts =\n opts.schema_repair_attempts ?? engine.default_schema_repair_attempts ?? 1\n const salvage_budget = resolve_salvage_budget(opts, engine)\n const max_tool_calls_per_step =\n opts.max_tool_calls_per_step ?? engine.default_max_tool_calls_per_step\n if (max_tool_calls_per_step !== undefined && max_tool_calls_per_step < 1) {\n // A cap of 0 would drop every call and strand the loop in its stop\n // branch with orphaned records; reject rather than guess.\n throw new engine_config_error(\n `max_tool_calls_per_step must be >= 1, got ${String(max_tool_calls_per_step)}`,\n )\n }\n return {\n max_steps,\n tool_error_policy,\n schema_repair_attempts,\n salvage_budget,\n max_tool_calls_per_step,\n }\n}\n\ntype AiSdkTransportConfig<T> = {\n readonly adapter: AiSdkProviderAdapter\n readonly target: ResolvedModel\n readonly opts: GenerateOptions<T>\n readonly effort: EffortLevel\n readonly retry_policy: RetryPolicy\n readonly turn_timeout_ms: number | undefined\n readonly dispatcher: ChunkDispatcher\n readonly tools_list: ReadonlyArray<Tool>\n readonly trajectory: TrajectoryLogger | undefined\n readonly telemetry: AiSdkTelemetrySettings | undefined\n}\n\n/**\n * Build the ai_sdk-transport InvokeOnce for one call: translate effort, merge\n * provider options, load the SDK seam, and wrap it in the engine-owned retry\n * via build_ai_sdk_invoke.\n */\nasync function build_ai_sdk_transport<T>(\n cfg: AiSdkTransportConfig<T>,\n): Promise<InvokeOnce> {\n const { adapter, opts, effort } = cfg\n const effort_translation = adapter.translate_effort(effort)\n // Stryker disable next-line LogicalOperator,StringLiteral: no adapter reports effort_ignored for effort 'none', so && vs || and 'none' vs '' cannot change whether this records (the ConditionalExpression twins are covered by the effort tests).\n if (effort !== 'none' && effort_translation.effort_ignored) {\n record_effort_ignored(cfg.trajectory, cfg.target.model_id)\n }\n // Effort translation is the lowest-precedence layer; engine defaults and\n // per-call provider_options (already merged into opts.provider_options, with\n // per-call winning) override it.\n const combined_provider_options = merge_provider_options(\n effort_translation.provider_options,\n opts.provider_options,\n )\n const provider_options =\n combined_provider_options !== undefined &&\n Object.keys(combined_provider_options).length > 0\n ? combined_provider_options\n : undefined\n\n // All SDK specifics (message/tool mapping, Output.object structured-output\n // gating, the generateText/streamText call) live behind create_ai_sdk_turn;\n // this builder only threads resolved options through the seam.\n //\n // Imported here rather than at the top of the file because a static import\n // would put `ai` on every consumer's module graph: loading it inside the\n // ai_sdk branch keeps it off the graph of a native-transport install. The\n // module resolves once per process and is cached thereafter, so the cost\n // falls on the first ai_sdk call only. On failure this rethrows\n // via missing_peer_error naming `ai` (the peer this module's own static\n // `from 'ai'` import reaches for), not a raw module-resolution error\n // naming this local path.\n let ai_sdk_invoke_mod: typeof import('./providers/ai_sdk/invoke.js')\n try {\n ai_sdk_invoke_mod = await import('./providers/ai_sdk/invoke.js')\n } catch (err: unknown) {\n throw missing_peer_error('ai', err)\n }\n const { create_ai_sdk_turn } = ai_sdk_invoke_mod\n return build_ai_sdk_invoke({\n invoke_turn: create_ai_sdk_turn({\n adapter,\n model_id: cfg.target.model_id,\n dispatcher: cfg.dispatcher,\n tools: cfg.tools_list,\n schema: opts.schema,\n // The merge produces the two-level per-provider shape the seam\n // declares; the merged value is typed loosely upstream.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n provider_options: provider_options as AiSdkTurnConfig['provider_options'],\n temperature: opts.temperature,\n max_tokens: opts.max_tokens,\n top_p: opts.top_p,\n reasoning: effort_translation.reasoning,\n telemetry: cfg.telemetry,\n }),\n retry_policy: cfg.retry_policy,\n turn_timeout_ms: cfg.turn_timeout_ms,\n trajectory: cfg.trajectory,\n })\n}\n\n/**\n * Build the message list one generate call starts from. When a schema is set,\n * the JSON-only instruction folds into the existing system message (or is\n * prepended as one) so the model sees it exactly once, wherever the system\n * prompt came from.\n */\nfunction build_prompt_messages<T>(opts: GenerateOptions<T>): Message[] {\n const schema_prefix = opts.schema !== undefined ? schema_instruction(opts.schema) : undefined\n const initial_messages = build_initial_messages(opts)\n if (schema_prefix !== undefined) {\n const idx = initial_messages.findIndex((m) => m.role === 'system')\n if (idx >= 0) {\n const sys = initial_messages[idx]\n // Stryker disable next-line OptionalChaining: sys is initial_messages[idx] at a found index, so it is always a defined system Message; sys.role and sys?.role read identically.\n if (sys?.role === 'system') {\n initial_messages[idx] = {\n role: 'system',\n content: `${sys.content}\\n\\n${schema_prefix}`,\n }\n }\n } else {\n initial_messages.unshift({ role: 'system', content: schema_prefix })\n }\n }\n return initial_messages\n}\n\nconst JSON_ONLY = 'Return ONLY the JSON value, with no markdown or commentary.'\n\n/**\n * The instruction that asks for a JSON reply, with the schema that the reply has to fit.\n *\n * The instruction is the only place where most transports show the model the\n * schema. Only an `ai_sdk` adapter with the `structured_output` capability\n * hands the schema to the provider, and only on a call without tools, so\n * everywhere else a bare request would leave the model guessing the field\n * names while the repair loop taught them one failed reply at a time.\n *\n * A schema that can't be emitted keeps the bare request. A vendor without\n * Standard JSON Schema throws, and so does zod for a type that JSON Schema\n * can't express (a `Date`), and both of those schemas validate replies without\n * it, so a failed emission must not fail the call.\n */\nfunction schema_instruction(schema: ToolSchema): string {\n try {\n const shown = JSON.stringify(to_json_schema(schema, { strip_meta: true }))\n return `You must respond with a single JSON value that conforms to this JSON Schema:\\n\\n${shown}\\n\\n${JSON_ONLY}`\n } catch {\n return `You must respond with a single JSON value that conforms to the expected schema. ${JSON_ONLY}`\n }\n}\n\ntype LoopConfigInputs<T> = {\n readonly opts: GenerateOptions<T>\n readonly target: ResolvedModel\n readonly pricing: PricingTable\n readonly invoke_once: InvokeOnce\n readonly messages: Message[]\n readonly tools_list: ReadonlyArray<Tool>\n readonly trajectory: TrajectoryLogger | undefined\n readonly dispatcher: ChunkDispatcher\n readonly on_chunk_provided: boolean\n readonly limits: LoopLimits\n}\n\n/**\n * Assemble the ToolLoopConfig base shared by every loop invocation of one\n * generate call. Everything here is per-call state: the mutable transcript,\n * the pricing lookup, and the pricing_missing dedup all live for exactly one\n * call, which is what lets schema-repair re-invocations share them. The\n * conditional spreads keep optional fields absent rather than undefined for\n * exactOptionalPropertyTypes.\n */\nfunction build_loop_config<T>(\n cfg: LoopConfigInputs<T>,\n): Omit<ToolLoopConfig, 'step_index_start'> {\n const { opts, target, limits } = cfg\n const abort = opts.abort ?? new AbortController().signal\n const resolve_pricing = (): Pricing | undefined => {\n return cfg.pricing[pricing_key(target.provider, target.model_id)]\n }\n // The parentheses are for Stryker: Babel 8, which it parses source with,\n // rejects an async arrow with a return type as a branch of a ternary.\n const dispatch_chunk =\n cfg.on_chunk_provided\n ? (async (chunk: StreamChunk): Promise<void> => {\n await cfg.dispatcher.dispatch(chunk)\n })\n : undefined\n return {\n invoke_once: cfg.invoke_once,\n messages: cfg.messages,\n tools: cfg.tools_list,\n max_steps: limits.max_steps,\n tool_error_policy: limits.tool_error_policy,\n abort,\n on_tool_approval: opts.on_tool_approval,\n trajectory: cfg.trajectory,\n stream: cfg.on_chunk_provided,\n dispatch_chunk,\n provider: target.provider,\n model_id: target.model_id,\n resolve_pricing,\n pricing_dedup: create_pricing_missing_dedup(cfg.trajectory),\n ...(limits.salvage_budget !== undefined\n ? { salvage_budget: limits.salvage_budget }\n : {}),\n ...(limits.max_tool_calls_per_step !== undefined\n ? { max_tool_calls_per_step: limits.max_tool_calls_per_step }\n : {}),\n ...(opts.prepare_step !== undefined ? { prepare_step: opts.prepare_step } : {}),\n }\n}\n\ntype SchemaStepConfig<T> = {\n readonly schema: NonNullable<GenerateOptions<T>['schema']>\n readonly text: string\n readonly trajectory: TrajectoryLogger | undefined\n readonly attempt: 'initial' | 'repair'\n readonly can_repair: boolean\n}\n\ntype SchemaStepOutcome<T> =\n | { readonly parsed: { readonly value: T } }\n | { readonly repair_message: Message }\n\n/**\n * One schema-validation pass over the loop's final text. A successful parse\n * returns the value in a holder (a schema can legitimately validate to\n * undefined, which must stay distinguishable from \"nothing parsed\"). A failed\n * parse records the trajectory event first, then either throws (`can_repair`\n * false: the repair or step budget is spent) or hands back the repair message\n * to append before re-invoking the loop.\n */\nasync function parse_schema_step<T>(\n cfg: SchemaStepConfig<T>,\n): Promise<SchemaStepOutcome<T>> {\n const parse = await parse_with_schema(cfg.schema, cfg.text)\n if (parse.ok) return { parsed: { value: parse.value } }\n record_schema_validation_failed(cfg.trajectory, {\n attempt: cfg.attempt,\n schema_issues: format_schema_issues(parse.issues),\n raw_text: cfg.text,\n })\n if (!cfg.can_repair) throw_schema_validation(parse.issues, cfg.text)\n return { repair_message: build_repair_message(parse.issues) }\n}\n\ntype GenerateLoopConfig<T> = {\n readonly base: Omit<ToolLoopConfig, 'step_index_start'>\n readonly schema: GenerateOptions<T>['schema']\n readonly schema_repair_attempts: number\n}\n\ntype GenerateLoopOutcome<T> = {\n readonly steps: GenerateResult<T>['steps']\n readonly tool_calls: GenerateResult<T>['tool_calls']\n readonly text: string\n readonly finish_reason: FinishReason\n readonly content_parsed: { value: T } | undefined\n}\n\n/**\n * Drive run_tool_loop to a final answer, re-invoking it for schema repair.\n *\n * Without a schema this is a single loop invocation. With one, the final text\n * must parse: a non-'stop' finish reason means no validated value can exist\n * (a content filter, the token limit, the step cap), so this throws\n * incomplete_generation_error rather than returning unchecked text; a failed\n * parse appends the repair message to the shared transcript and re-enters the\n * loop until the response parses, repair attempts run out, or max_steps is\n * reached. step_index_start advances by the accumulated step count so step\n * indices stay call-global across re-invocations.\n */\nasync function run_generate_loop<T>(\n cfg: GenerateLoopConfig<T>,\n): Promise<GenerateLoopOutcome<T>> {\n const { base, schema } = cfg\n const steps_accum: GenerateResult<T>['steps'] = []\n const tool_calls_accum: GenerateResult<T>['tool_calls'] = []\n // Stryker disable next-line StringLiteral: text is overwritten by loop_result.text on the first (guaranteed) loop iteration before it is ever read.\n let text = ''\n // Stryker disable next-line StringLiteral: finish_reason is overwritten by loop_result.finish_reason before it is read.\n let finish_reason: FinishReason = 'stop'\n let repair_remaining = cfg.schema_repair_attempts\n // A holder rather than a bare `T | undefined`: a schema can legitimately\n // validate to undefined (a `.transform()` or `.catch()` that returns it), and\n // that has to stay distinguishable from \"nothing parsed\".\n let content_parsed: { value: T } | undefined\n\n while (true) {\n const loop_result = await run_tool_loop({\n ...base,\n step_index_start: steps_accum.length,\n })\n for (const s of loop_result.steps) steps_accum.push(s)\n for (const tc of loop_result.tool_calls) tool_calls_accum.push(tc)\n text = loop_result.text\n finish_reason = loop_result.finish_reason\n\n if (schema === undefined) break\n if (finish_reason !== 'stop') {\n throw new incomplete_generation_error(\n finish_reason,\n text,\n last_provider_reported(steps_accum),\n )\n }\n const schema_step = await parse_schema_step<T>({\n schema,\n text,\n trajectory: base.trajectory,\n attempt: repair_remaining === cfg.schema_repair_attempts ? 'initial' : 'repair',\n can_repair: repair_remaining > 0 && steps_accum.length < base.max_steps,\n })\n if ('parsed' in schema_step) {\n content_parsed = schema_step.parsed\n break\n }\n repair_remaining -= 1\n base.messages.push(schema_step.repair_message)\n }\n\n return {\n steps: steps_accum,\n tool_calls: tool_calls_accum,\n text,\n finish_reason,\n content_parsed,\n }\n}\n\n/**\n * Fold the loop outcome into the caller-facing GenerateResult: usage and cost\n * aggregate across every step (schema-repair re-invocations included), the\n * content is the parsed holder's value when a schema ran, and cost /\n * provider_reported attach only when a step actually reported them.\n */\nfunction assemble_result<T>(\n outcome: GenerateLoopOutcome<T>,\n target: ResolvedModel,\n): GenerateResult<T> {\n const aggregated_usage = sum_usage(outcome.steps)\n const aggregated_cost = aggregate_cost(outcome.steps, target.provider)\n\n let final_content: T\n if (outcome.content_parsed !== undefined) {\n final_content = outcome.content_parsed.value\n } else {\n // No schema, so there is nothing to validate and the raw text is the\n // content. A schema call cannot arrive here: the loop either filled the\n // holder or threw.\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n final_content = outcome.text as T\n }\n\n const result: GenerateResult<T> = {\n content: final_content,\n tool_calls: outcome.tool_calls,\n steps: outcome.steps,\n usage: aggregated_usage,\n finish_reason: outcome.finish_reason,\n model_resolved: { provider: target.provider, model_id: target.model_id },\n }\n if (aggregated_cost !== undefined) result.cost = aggregated_cost\n const aggregated_reported = last_provider_reported(outcome.steps)\n if (aggregated_reported !== undefined) result.provider_reported = aggregated_reported\n return result\n}\n\n/**\n * Resolve a `generate` call's options against engine defaults, run the tool\n * loop, and return the aggregated result.\n *\n * A provider whose adapter is `external` (`adapter.kind === 'external'`)\n * delegates the whole call to `adapter.generate` before any of the logic\n * below runs. For `ai_sdk` and native adapters, this function resolves\n * model, provider, system prompt, and `provider_options` against engine\n * defaults, checks the adapter supports every capability the call actually\n * uses (schema, tools, streaming), builds the `InvokeOnce` closure for the\n * resolved transport, and drives it through `run_tool_loop`. When a schema\n * is set and the model's output fails validation, it appends a repair\n * message and re-invokes the loop, until the response parses, repair\n * attempts run out, or `max_steps` is reached. When a schema is set and the\n * loop finishes for any reason other than `'stop'` (a content filter, the\n * token limit, the step cap), no validated value can exist, so it throws\n * `incomplete_generation_error` carrying the finish reason, the raw text,\n * and the last `provider_reported` payload rather than returning unchecked\n * text. Without a schema those finish reasons return normally. Every result,\n * an external adapter's included, leaves with `timing` stamped over the\n * whole call.\n */\nexport async function generate<T = string>(\n opts_in: GenerateOptions<T>,\n engine: EngineInternals,\n): Promise<GenerateResult<T>> {\n const started_at = Date.now()\n if (opts_in.abort?.aborted === true) {\n throw new aborted_error('aborted', { reason: opts_in.abort.reason })\n }\n\n const { opts, target } = resolve_target(opts_in, engine)\n\n const adapter = engine.adapters.get(target.provider)\n if (adapter === undefined) {\n throw new provider_not_configured_error(target.provider, [...engine.adapters.keys()])\n }\n\n if (adapter.kind === 'external') {\n const external = await adapter.generate<T>(opts, target)\n return { ...external, timing: call_timing(started_at) }\n }\n\n // Stamp engine events with `ts` when generate is called directly with a\n // caller-supplied logger. A runner-decorated logger already carries `ts`;\n // with_timestamps preserves it.\n const trajectory = with_timestamps(opts.trajectory)\n const on_chunk_provided = opts.on_chunk !== undefined\n const tools_list: ReadonlyArray<Tool> = opts.tools ?? []\n\n assert_capabilities(adapter, target.provider, opts, tools_list, on_chunk_provided)\n\n const turn = resolve_turn_config(opts, engine)\n const dispatcher = create_chunk_dispatcher(opts.on_chunk)\n\n let invoke_once: InvokeOnce\n if (adapter.kind === 'ai_sdk') {\n invoke_once = await build_ai_sdk_transport({\n adapter,\n target,\n opts,\n effort: turn.effort,\n retry_policy: turn.retry_policy,\n turn_timeout_ms: turn.turn_timeout_ms,\n dispatcher,\n tools_list,\n trajectory,\n telemetry: engine.default_ai_sdk_telemetry,\n })\n } else {\n // No effort translation here: a native adapter receives the resolved\n // effort level on TurnRequest and owns its own mapping, so\n // provider_options stays the plain defaults + per-call merge.\n invoke_once = build_native_invoke({\n adapter,\n model_id: target.model_id,\n retry_policy: turn.retry_policy,\n turn_timeout_ms: turn.turn_timeout_ms,\n trajectory,\n dispatcher,\n effort: turn.effort,\n schema: opts.schema,\n // The merge produces the two-level per-provider shape TurnRequest\n // declares; GenerateOptions types it loosely as Record<string, unknown>.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n provider_options: opts.provider_options as TurnRequest['provider_options'],\n temperature: opts.temperature,\n max_tokens: opts.max_tokens,\n top_p: opts.top_p,\n })\n }\n\n const limits = resolve_loop_limits(opts, engine)\n const initial_messages = build_prompt_messages(opts)\n\n const generate_span = start_generate_span(trajectory, {\n model: target.model_id,\n provider: target.provider,\n model_id: target.model_id,\n has_tools: tools_list.length > 0,\n has_schema: opts.schema !== undefined,\n streaming: on_chunk_provided,\n })\n\n const base = build_loop_config({\n opts,\n target,\n pricing: engine.pricing,\n invoke_once,\n messages: [...initial_messages],\n tools_list,\n trajectory,\n dispatcher,\n on_chunk_provided,\n limits,\n })\n\n try {\n const outcome = await run_generate_loop<T>({\n base,\n schema: opts.schema,\n schema_repair_attempts: limits.schema_repair_attempts,\n })\n const result = assemble_result(outcome, target)\n\n if (on_chunk_provided) {\n await dispatcher.dispatch({\n kind: 'finish',\n finish_reason: outcome.finish_reason,\n usage: result.usage,\n })\n }\n\n end_generate_span(trajectory, generate_span, {\n usage: result.usage,\n finish_reason: outcome.finish_reason,\n model_resolved: result.model_resolved,\n step_count: result.steps.length,\n tool_call_count: result.tool_calls.length,\n })\n result.timing = call_timing(started_at)\n return result\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err)\n end_generate_span(trajectory, generate_span, { error: message })\n throw err\n }\n}\n\n/**\n * Close a generate call's wall-clock window opened at `started_at`.\n */\nfunction call_timing(started_at: number): GenerateTiming {\n return { started_at, duration_ms: Date.now() - started_at }\n}\n\n/**\n * Pick the call-level `provider_reported` from the step records: the payload of\n * the last step that reported one.\n *\n * Provider payloads are opaque, so unlike usage and cost there is nothing to\n * sum and no safe way to merge two turns' keys (a provider reports the same keys\n * every turn, so merging would silently overwrite rather than combine). Taking\n * the final reporting turn matches how `content` and `finish_reason` are drawn\n * from the last turn; every turn's own payload stays on `steps[i]`.\n */\nexport function last_provider_reported(\n steps: ReadonlyArray<GenerateResult['steps'][number]>,\n): Record<string, unknown> | undefined {\n return steps.findLast((s) => s.provider_reported !== undefined)?.provider_reported\n}\n\n/**\n * Running totals accumulated across per-step cost breakdowns. Each optional\n * field carries a `_present` flag so the final breakdown can include it only\n * when at least one step reported it, distinct from a summed zero.\n */\ninterface CostAccumulator {\n any_present: boolean\n total: number\n input: number\n output: number\n cached_present: boolean\n cached: number\n cache_write_present: boolean\n cache_write: number\n reasoning_present: boolean\n reasoning: number\n}\n\n/**\n * Fold every step's `cost` into a single {@link CostAccumulator}, skipping steps\n * that reported none. The required fields always sum; each optional field sums\n * and flips its `_present` flag only on the steps that carried it.\n */\nfunction sum_step_costs(\n steps: ReadonlyArray<GenerateResult['steps'][number]>,\n): CostAccumulator {\n const acc: CostAccumulator = {\n any_present: false,\n total: 0,\n input: 0,\n output: 0,\n cached_present: false,\n cached: 0,\n cache_write_present: false,\n cache_write: 0,\n reasoning_present: false,\n reasoning: 0,\n }\n for (const s of steps) {\n if (s.cost === undefined) continue\n acc.any_present = true\n acc.total += s.cost.total_usd\n acc.input += s.cost.input_usd\n acc.output += s.cost.output_usd\n if (s.cost.cached_input_usd !== undefined) {\n acc.cached_present = true\n acc.cached += s.cost.cached_input_usd\n }\n if (s.cost.cache_write_usd !== undefined) {\n acc.cache_write_present = true\n acc.cache_write += s.cost.cache_write_usd\n }\n if (s.cost.reasoning_usd !== undefined) {\n acc.reasoning_present = true\n acc.reasoning += s.cost.reasoning_usd\n }\n }\n return acc\n}\n\n/**\n * Sum per-step cost breakdowns into a single `CostBreakdown` for the whole\n * generate call.\n *\n * Returns `undefined` if no step reports a cost, unless `provider` is free\n * (`FREE_PROVIDERS`) and at least one step ran; in that case it returns an\n * explicit all-zero breakdown instead of omitting cost entirely. The\n * optional fields (`cached_input_usd`, `cache_write_usd`, `reasoning_usd`)\n * are included only when at least one step reported them.\n */\nexport function aggregate_cost(\n steps: ReadonlyArray<GenerateResult['steps'][number]>,\n provider: string,\n): CostBreakdown | undefined {\n const acc = sum_step_costs(steps)\n if (!acc.any_present) {\n if (FREE_PROVIDERS.has(provider) && steps.length > 0) {\n return {\n total_usd: 0,\n input_usd: 0,\n output_usd: 0,\n currency: 'USD',\n is_estimate: true,\n }\n }\n return undefined\n }\n const out: CostBreakdown = {\n total_usd: round6(acc.total),\n input_usd: round6(acc.input),\n output_usd: round6(acc.output),\n currency: 'USD',\n is_estimate: true,\n }\n if (acc.cached_present) out.cached_input_usd = round6(acc.cached)\n if (acc.cache_write_present) out.cache_write_usd = round6(acc.cache_write)\n if (acc.reasoning_present) out.reasoning_usd = round6(acc.reasoning)\n return out\n}\n\n","/**\n * Engine factory.\n *\n * `create_engine` validates each provider entry at construction, merges user\n * pricing over DEFAULT_PRICING into a per-instance table, and returns an\n * Engine whose methods close over this instance state. Model resolution is a\n * verbatim pass-through: `model` is sent to the provider unchanged.\n */\n\nimport type {\n Engine,\n EngineConfig,\n EngineDefaults,\n GenerateOptions,\n GenerateResult,\n Pricing,\n PricingTable,\n ProviderConfigMap,\n} from './types.js'\nimport { DEFAULT_PRICING, pricing_key } from './pricing.js'\nimport { DEFAULT_RETRY } from './retry.js'\nimport {\n engine_config_error,\n engine_disposed_error,\n} from './errors.js'\nimport { get_provider_factory, list_builtin_providers } from './providers/registry.js'\nimport type { ProviderAdapter, ProviderFactory } from './providers/types.js'\nimport { generate, type EngineInternals } from './generate.js'\n\n/**\n * Build the provider-name to adapter map from `providers`, resolving each\n * name to a `custom_providers` factory when one is supplied, or the built-in\n * registry factory otherwise.\n *\n * Each factory validates its init value synchronously, so a bad credential\n * throws here at construction time rather than later; loading the\n * underlying SDK is deferred until the first `generate` call. Throws if\n * `custom_providers` tries to shadow a built-in provider name.\n */\nfunction build_provider_adapters(\n providers: EngineConfig['providers'],\n custom_providers: EngineConfig['custom_providers'],\n): Map<string, ProviderAdapter> {\n if (custom_providers !== undefined) {\n const builtins = new Set(list_builtin_providers())\n for (const name of Object.keys(custom_providers)) {\n if (builtins.has(name)) {\n throw new engine_config_error(\n `custom_providers must not shadow built-in provider '${name}'`,\n name,\n )\n }\n }\n }\n const adapters = new Map<string, ProviderAdapter>()\n for (const [name, init] of Object.entries(providers)) {\n if (init === undefined) continue\n const custom =\n custom_providers !== undefined && Object.hasOwn(custom_providers, name)\n ? custom_providers[name]\n : undefined\n const factory = custom ?? get_provider_factory(name)\n const adapter = factory(init)\n adapters.set(name, adapter)\n }\n return adapters\n}\n\n/**\n * Mutable draft of a deeply `readonly` type, used to assemble an object field\n * by field before returning it under its public, frozen-looking type.\n */\ntype Writable<T> = { -readonly [K in keyof T]: T[K] }\n\n/**\n * Seed a fresh, mutable pricing table from DEFAULT_PRICING and layer any\n * per-engine `config.pricing` overrides on top.\n *\n * The result is the engine's own table: register_price mutates it in place,\n * and DEFAULT_PRICING (frozen at module load) is never touched.\n */\nfunction merge_pricing(overrides: EngineConfig['pricing']): Record<string, Pricing> {\n const pricing: Record<string, Pricing> = { ...DEFAULT_PRICING }\n if (overrides !== undefined) {\n for (const [key, value] of Object.entries(overrides)) {\n pricing[key] = value\n }\n }\n return pricing\n}\n\n/**\n * Resolve the three always-present scalar defaults.\n *\n * `config.defaults.*` is the current nested layer; `config.default_retry`,\n * `config.default_effort`, and `config.default_max_steps` are older top-level\n * fields kept for compatibility. The nested value wins where both are set, and\n * the built-in constant is the last resort.\n */\nfunction resolve_default_scalars(\n config: EngineConfig,\n): Pick<EngineInternals, 'default_retry' | 'default_effort' | 'default_max_steps'> {\n const defaults: EngineDefaults = config.defaults ?? {}\n return {\n default_retry: defaults.retry_policy ?? config.default_retry ?? DEFAULT_RETRY,\n default_effort: defaults.effort ?? config.default_effort ?? 'none',\n default_max_steps: defaults.max_steps ?? config.default_max_steps ?? 10,\n }\n}\n\n/**\n * Validate the numeric defaults once, at construction: a bad bound should fail\n * fast here rather than surfacing deep inside the first generate call that ends\n * up using the default.\n */\nfunction validate_numeric_defaults(defaults: EngineDefaults | undefined): void {\n if (defaults === undefined) return\n const { tool_call_repair_attempts, max_tool_calls_per_step, turn_timeout_ms } = defaults\n if (tool_call_repair_attempts !== undefined && tool_call_repair_attempts < 0) {\n throw new engine_config_error(\n `defaults.tool_call_repair_attempts must be >= 0, got ${String(tool_call_repair_attempts)}`,\n )\n }\n if (max_tool_calls_per_step !== undefined && max_tool_calls_per_step < 1) {\n throw new engine_config_error(\n `defaults.max_tool_calls_per_step must be >= 1, got ${String(max_tool_calls_per_step)}`,\n )\n }\n if (turn_timeout_ms !== undefined && turn_timeout_ms <= 0) {\n throw new engine_config_error(`defaults.turn_timeout_ms must be > 0, got ${String(turn_timeout_ms)}`)\n }\n}\n\n/**\n * Copy `value` onto `target[key]` only when it is defined, so an absent optional\n * default leaves the key off the object rather than present-as-undefined.\n */\nfunction assign_if_present<T, K extends keyof T>(target: T, key: K, value: T[K]): void {\n if (value !== undefined) target[key] = value\n}\n\n/**\n * Assemble the per-instance EngineInternals from the resolved required fields\n * plus whichever optional `defaults.*` knobs were supplied.\n *\n * The optional defaults form a fixed source-to-target table (`defaults.model` ->\n * `default_model`, and so on), and each is folded in only when present, so an\n * omitted knob leaves its key off the object rather than present-as-undefined.\n */\nfunction build_internals(\n base: Pick<\n EngineInternals,\n 'pricing' | 'adapters' | 'default_retry' | 'default_effort' | 'default_max_steps'\n >,\n defaults: EngineDefaults | undefined,\n): EngineInternals {\n const internals: Writable<EngineInternals> = {\n pricing: base.pricing,\n adapters: base.adapters,\n default_retry: base.default_retry,\n default_effort: base.default_effort,\n default_max_steps: base.default_max_steps,\n }\n if (defaults !== undefined) {\n assign_if_present(internals, 'default_model', defaults.model)\n assign_if_present(internals, 'default_provider', defaults.provider)\n assign_if_present(internals, 'default_system', defaults.system)\n assign_if_present(internals, 'default_temperature', defaults.temperature)\n assign_if_present(internals, 'default_max_tokens', defaults.max_tokens)\n assign_if_present(internals, 'default_top_p', defaults.top_p)\n assign_if_present(internals, 'default_tool_error_policy', defaults.tool_error_policy)\n assign_if_present(internals, 'default_schema_repair_attempts', defaults.schema_repair_attempts)\n assign_if_present(\n internals,\n 'default_tool_call_repair_attempts',\n defaults.tool_call_repair_attempts,\n )\n assign_if_present(internals, 'default_max_tool_calls_per_step', defaults.max_tool_calls_per_step)\n assign_if_present(internals, 'default_turn_timeout_ms', defaults.turn_timeout_ms)\n assign_if_present(internals, 'default_ai_sdk_telemetry', defaults.ai_sdk_telemetry)\n assign_if_present(internals, 'default_provider_options', defaults.provider_options)\n }\n return internals\n}\n\n/**\n * Validate `config` and construct an `Engine`.\n *\n * Provider entries are validated synchronously via `build_provider_adapters`.\n * A `generate` call that names a provider absent from `config.providers`\n * still throws `provider_not_configured_error`, but only at call time.\n */\nexport function create_engine(config: EngineConfig): Engine {\n if (config.providers === null || typeof config.providers !== 'object') {\n throw new engine_config_error('EngineConfig.providers is required')\n }\n\n const adapters = build_provider_adapters(config.providers, config.custom_providers)\n const pricing = merge_pricing(config.pricing)\n const { default_retry, default_effort, default_max_steps } = resolve_default_scalars(config)\n validate_numeric_defaults(config.defaults)\n\n const get_internals = (): EngineInternals =>\n build_internals(\n { pricing, adapters, default_retry, default_effort, default_max_steps },\n config.defaults,\n )\n\n let disposed = false\n let dispose_promise: Promise<void> | undefined\n\n const engine: Engine = {\n generate<t = string>(opts: GenerateOptions<t>): Promise<GenerateResult<t>> {\n if (disposed) throw new engine_disposed_error()\n return generate<t>(opts, get_internals())\n },\n register_price(provider: string, model_id: string, value: Pricing): void {\n pricing[pricing_key(provider, model_id)] = value\n },\n resolve_price(provider: string, model_id: string): Pricing | undefined {\n return pricing[pricing_key(provider, model_id)]\n },\n list_prices(): PricingTable {\n // Defensive shallow copy: mutating the returned object does not affect\n // engine state.\n return { ...pricing }\n },\n with_providers(\n providers: ProviderConfigMap,\n custom_providers?: Record<string, ProviderFactory>,\n ): Engine {\n // Derives a NEW engine from the retained construction config:\n // `providers`/`custom_providers` shallow-merge by name over the\n // originals, the merged config is re-validated by a recursive\n // create_engine call (same validation, fresh adapters, independent\n // disposal), and this engine is left untouched. This is the\n // value-semantic way to add providers at runtime, not a mutable\n // registry.\n //\n // Since `...config` below already carries `config.custom_providers`\n // forward unconditionally, this merge only changes the result when the\n // `custom_providers` ARGUMENT contributes entries. That leaves a cluster of\n // genuine equivalents as documented survivors here, all rooted in the left\n // disjunct being redundant: mutating `config.custom_providers !== undefined`\n // (to `false`, or `!==` to `===`) only swaps `merged_custom` between\n // `undefined`, `{}`, and a shallow copy of `config.custom_providers`, and\n // given `...config` those build identical adapters; forcing the whole\n // condition true likewise yields `{}` for `undefined` when both are absent;\n // and forcing the spread-in below on always passes the `undefined` \"no\n // customs\" sentinel. A Stryker-disable can't fence these off: on the same\n // lines the whole-condition `false` and the right-disjunct mutants DO change\n // behavior, they drop a supplied argument, and the suite kills those.\n const merged_custom =\n config.custom_providers !== undefined || custom_providers !== undefined\n ? { ...config.custom_providers, ...custom_providers }\n : undefined\n return create_engine({\n ...config,\n providers: { ...config.providers, ...providers },\n ...(merged_custom !== undefined ? { custom_providers: merged_custom } : {}),\n })\n },\n dispose(): Promise<void> {\n if (dispose_promise !== undefined) return dispose_promise\n disposed = true\n // Stryker disable next-line ArrayDeclaration: seeding this accumulator\n // non-empty is observationally identical: every element is awaited by\n // the Promise.all below and then discarded by `.then(() => undefined)`,\n // so a stray value cannot change what dispose() resolves to or when.\n const tasks: Promise<void>[] = []\n for (const adapter of adapters.values()) {\n // Any adapter kind may hold resources: external always defines\n // dispose, native optionally (keep-alive agents, connection pools).\n if ('dispose' in adapter && adapter.dispose !== undefined) {\n tasks.push(adapter.dispose())\n }\n }\n dispose_promise = Promise.all(tasks).then(() => undefined)\n return dispose_promise\n },\n }\n\n return engine\n}\n"],"mappings":";;;;;;;;;;;;;;AAOA,IAAa,+BAAb,cAAkD,MAAM;CAItD,OAAgB;CAChB;CACA,YAAY,QAAgB,SAAkB;EAC5C,MACE,WACE,kBAAkB,OAAO,0FAC7B;EACA,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;;;;;;;;;;;;;;;;;;;ACAA,MAAM,iBAAiB;;;;;;;;;;AAWvB,SAAgB,eACd,QACA,UAA6B,CAAC,GACL;CACzB,MAAM,QAAQ,OAAO;CACrB,IAAI,OAAO,MAAM,YAAY,UAAU,YACrC,MAAM,IAAI,6BAA6B,MAAM,MAAM;CAErD,MAAM,OAAO,cAAc,MAAM,WAAW,MAAM,EAAE,QAAQ,QAAQ,UAAU,eAAe,CAAC,CAAC;CAC/F,OAAO,QAAQ,eAAe,OAAO,gBAAgB,IAAI,IAAI;AAC/D;;AAGA,MAAM,cAAc;CAAC;CAAc;CAAqB;CAAS;AAAa;;AAG9E,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAS,cAAc,MAAwD;CAC7E,MAAM,SAAS,aAAa,IAAI;CAChC,OAAO,cAAc,MAAM,IAAI;EAAE,GAAG;EAAQ,sBAAsB;CAAM,IAAI;AAC9E;;AAGA,SAAS,aAAa,MAAwD;CAC5E,MAAM,SAAkC,EAAE,GAAG,KAAK;CAClD,KA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