fascicle 0.9.6 → 0.9.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["throw_if_aborted","e","round6","read_number","DEFAULT_BASE_URL","extract_error_message","response_error","rethrow_network_failure","consume_sse_response","SUPPORTED","SUPPORTED","to_user_content","to_assistant_message","extract_error_message","response_error","rethrow_network_failure","SUPPORTED","SUPPORTED","DEFAULT_BASE_URL","SUPPORTED","SUPPORTED","SUPPORTED","SUPPORTED","SUPPORTED","SUPPORTED","node_spawn","sum_usage","is_plain_object","ai_tool","fs_watch"],"sources":["../src/composites/adversarial.ts","../src/composites/consensus.ts","../src/composites/ensemble.ts","../src/composites/ensemble_step.ts","../src/composites/improve.ts","../src/composites/learn.ts","../src/composites/tournament.ts","../src/composites/bench.ts","../src/composites/judges.ts","../src/composites/regression.ts","../src/engine/pricing.ts","../src/engine/errors.ts","../src/engine/retry.ts","../src/engine/providers/types.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/providers/ai_sdk/telemetry.ts","../src/engine/providers/ai_sdk/invoke.ts","../src/engine/generate.ts","../src/engine/create_engine.ts","../src/model_call.ts","../src/forward_standard_env.ts","../src/viewer/broadcast.ts","../src/viewer/server.ts","../src/viewer/tail.ts","../src/viewer/start_viewer.ts","../src/viewer/cli.ts"],"sourcesContent":["/**\n * adversarial: build-and-critique loop.\n *\n * `adversarial({ build, critique, accept, max_rounds })` runs up to\n * `max_rounds` iterations of: build a candidate (receiving the prior\n * candidate and critique notes when available) -> critique the candidate\n * -> check `accept(critique_result)`. Returns `{ candidate, converged,\n * rounds }`. Does not throw on non-convergence.\n *\n * Implemented as a `compose`d `loop` whose body builds a new candidate\n * and whose guard runs the critique step and checks `accept`. State is\n * threaded through `scope`/`stash`/`use` so the build and critique steps\n * remain unmodified user-supplied `Step` values.\n *\n * This file is the canonical example of how a user-built composite is\n * structured — the entire implementation is a composition of core\n * primitives. Read it as documentation.\n */\n\nimport { compose, loop, pipe, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type AdversarialBuildInput<input, candidate> = {\n readonly input: input\n readonly prior?: candidate\n readonly critique?: string\n}\n\nexport type AdversarialCritiqueResult = { readonly notes: string } & Record<string, unknown>\n\nexport type AdversarialResult<candidate> = {\n readonly candidate: candidate\n readonly converged: boolean\n readonly rounds: number\n}\n\nexport type AdversarialConfig<input, candidate> = {\n readonly name?: string\n readonly build: Step<AdversarialBuildInput<input, candidate>, candidate>\n readonly critique: Step<candidate, AdversarialCritiqueResult>\n readonly accept: (critique_result: AdversarialCritiqueResult) => boolean\n readonly max_rounds: number\n}\n\ntype AdversarialState<input, candidate> = {\n readonly input: input\n readonly candidate?: candidate\n readonly critique_notes?: string\n readonly last_critique?: AdversarialCritiqueResult\n}\n\nfunction build_input_from_state<i, c>(\n s: AdversarialState<i, c>,\n): AdversarialBuildInput<i, c> {\n if (s.candidate === undefined) return { input: s.input }\n if (s.critique_notes === undefined) return { input: s.input, prior: s.candidate }\n return { input: s.input, prior: s.candidate, critique: s.critique_notes }\n}\n\nexport function adversarial<input, candidate>(\n config: AdversarialConfig<input, candidate>,\n): Step<input, AdversarialResult<candidate>> {\n const { build, critique, accept, max_rounds } = config\n\n type S = AdversarialState<input, candidate>\n\n const body: Step<S, S> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('to_build_input', (s: S) => build_input_from_state(s)),\n build,\n use(['state'], (vars, candidate: candidate) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return { ...prior, candidate }\n }),\n ])\n\n const guard: Step<S, { stop: boolean; state: S }> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('extract_candidate', (s: S) => {\n if (s.candidate === undefined) {\n throw new Error('adversarial: guard reached without a candidate')\n }\n return s.candidate\n }),\n critique,\n use(['state'], (vars, critique_result: AdversarialCritiqueResult) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return {\n stop: accept(critique_result),\n state: {\n ...prior,\n last_critique: critique_result,\n critique_notes: critique_result.notes,\n },\n }\n }),\n ])\n\n const inner = pipe(\n loop<input, S, candidate>({\n init: (input) => ({ input }),\n body,\n guard,\n finish: (s) => {\n if (s.candidate === undefined) {\n throw new Error('adversarial: finished without a candidate')\n }\n return s.candidate\n },\n max_rounds,\n }),\n (result) => ({\n candidate: result.value,\n converged: result.converged,\n rounds: result.rounds,\n }),\n )\n\n return compose(config.name ?? 'adversarial', inner)\n}\n","/**\n * consensus: run-until-agreement.\n *\n * `consensus({ members, agree, max_rounds })` runs every member concurrently\n * with the same input. If `agree(results)` is true, returns the results with\n * `converged: true`. Otherwise re-runs all members up to `max_rounds` times,\n * returning the last results with `converged: false` if no agreement is\n * reached.\n *\n * Implemented as a `compose`d `loop` whose body runs `parallel(members)` and\n * whose guard evaluates `agree`. State carries the original input alongside\n * the most recent results so each round receives the same input.\n */\n\nimport { compose, loop, parallel, pipe, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type ConsensusConfig<i, o> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly agree: (results: Record<string, o>) => boolean\n readonly max_rounds: number\n}\n\nexport type ConsensusResult<o> = {\n readonly result: Record<string, o>\n readonly converged: boolean\n}\n\ntype ConsensusState<i, o> = {\n readonly input: i\n readonly results: Record<string, o>\n}\n\nexport function consensus<i, o>(\n config: ConsensusConfig<i, o>,\n): Step<i, ConsensusResult<o>> {\n const { members, agree, max_rounds } = config\n\n type S = ConsensusState<i, o>\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const round_step = parallel(members) as Step<i, Record<string, o>>\n\n const body: Step<S, S> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('extract_input', (s: S) => s.input),\n round_step,\n use(['state'], (vars, results: Record<string, o>) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return { ...prior, results }\n }),\n ])\n\n const guard: Step<S, { stop: boolean; state: S }> = step('agree', (s: S) => ({\n stop: agree(s.results),\n state: s,\n }))\n\n const inner = pipe(\n loop<i, S, Record<string, o>>({\n init: (input) => ({ input, results: {} }),\n body,\n guard,\n finish: (s) => s.results,\n max_rounds,\n }),\n (result) => ({ result: result.value, converged: result.converged }),\n )\n\n return compose(config.name ?? 'consensus', inner)\n}\n","/**\n * ensemble: N-of-M pick-best.\n *\n * `ensemble({ members, score, select? })` runs every member concurrently with\n * the same input, scores each result, and returns the winner (highest or\n * lowest by `select`) plus the complete score map. Tie-breaking is \"any tied\n * result is acceptable\".\n *\n * Implemented as a `compose`d `sequence` of `parallel(members)` followed by\n * a single picking step. Cancellation, fan-out, and abort propagation come\n * from `parallel`'s own contract.\n */\n\nimport { compose, parallel, sequence, step } from '#core'\nimport type { Step } from '#core'\n\nexport type EnsembleConfig<i, o> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly score: (result: o, member_id: string) => number | Promise<number>\n readonly select?: 'max' | 'min'\n}\n\nexport type EnsembleResult<o> = {\n readonly winner: o\n readonly scores: Record<string, number>\n}\n\nexport function ensemble<i, o>(\n config: EnsembleConfig<i, o>,\n): Step<i, EnsembleResult<o>> {\n const select: 'max' | 'min' = config.select ?? 'max'\n const score_fn = config.score\n const keys = Object.keys(config.members)\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const fan_out = parallel(config.members) as Step<i, Record<string, o>>\n\n const pick = step('pick_winner', async (results: Record<string, o>) => {\n const scores: Record<string, number> = {}\n for (const k of keys) {\n const value = results[k]\n if (value === undefined) continue\n scores[k] = await score_fn(value, k)\n }\n \n let winner_key: string | undefined = undefined\n let winner_score: number | undefined = undefined\n for (const k of keys) {\n const current = scores[k]\n if (current === undefined) continue\n if (winner_score === undefined) {\n winner_key = k\n winner_score = current\n continue\n }\n const better = select === 'max' ? current > winner_score : current < winner_score\n if (better) {\n winner_key = k\n winner_score = current\n }\n }\n \n if (winner_key === undefined) {\n throw new Error('ensemble: no members produced a result')\n }\n const winner = results[winner_key]\n if (winner === undefined) {\n throw new Error('ensemble: winner missing from results')\n }\n return { winner, scores }\n })\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const inner = sequence([fan_out, pick]) as Step<i, EnsembleResult<o>>\n\n return compose(config.name ?? 'ensemble', inner)\n}\n","/**\n * ensemble_step: N-of-M pick-best with a Step-based scorer.\n *\n * `ensemble_step({ members, score, rank_by, select? })` is the sibling of\n * `ensemble` for the case where scoring is itself a `Step` (e.g. a separate\n * model call, a sub-flow, anything that wants its own trajectory span and\n * abort routing). Each member runs concurrently with the same input; the\n * `score` step is dispatched once per result; `rank_by` projects a number\n * out of the structured scored output; the highest- or lowest-ranking\n * winner is returned alongside its full structured score and the score\n * map for the rest.\n *\n * Returning `winner_scored` avoids the cost of re-scoring the winner — the\n * structured output from the round's scoring run is preserved verbatim.\n *\n * Implemented as a `compose`d `scope` over (`stash(parallel(members))` →\n * `to_pairs` → `map(score per result, threading id)` → `use` to pick\n * winner). Cancellation, fan-out, and abort propagation come from the\n * underlying `parallel` and `map` contracts.\n */\n\nimport { compose, map, parallel, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type EnsembleStepConfig<i, o, ranked> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly score: Step<o, ranked>\n readonly rank_by: (r: ranked) => number\n readonly select?: 'max' | 'min'\n}\n\nexport type EnsembleStepResult<o, ranked> = {\n readonly winner_id: string\n readonly winner: o\n readonly winner_scored: ranked\n readonly scored: Record<string, ranked>\n}\n\nconst RESULTS_KEY = '__ensemble_step_results'\nconst ITEM_KEY = '__ensemble_step_item'\n\ntype Pair<o> = { readonly id: string; readonly value: o }\ntype ScoredPair<ranked> = { readonly id: string; readonly scored: ranked }\n\nexport function ensemble_step<i, o, ranked>(\n config: EnsembleStepConfig<i, o, ranked>,\n): Step<i, EnsembleStepResult<o, ranked>> {\n const { members, score, rank_by } = config\n const select: 'max' | 'min' = config.select ?? 'max'\n const keys = Object.keys(members)\n\n if (keys.length === 0) {\n throw new Error('ensemble_step: at least one member required')\n }\n\n const fan_out = parallel(members)\n\n const score_one = scope([\n stash(ITEM_KEY, step('ensemble_step_item_snapshot', (item: Pair<o>) => item)),\n step('ensemble_step_extract_value', (item: Pair<o>) => item.value),\n score,\n use([ITEM_KEY], (vars, scored: ranked): ScoredPair<ranked> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const item = vars[ITEM_KEY] as Pair<o>\n return { id: item.id, scored }\n }),\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<Pair<o>, ScoredPair<ranked>>\n\n const to_pairs = step(\n 'ensemble_step_to_pairs',\n (results: Record<string, o>): ReadonlyArray<Pair<o>> => {\n const out: Pair<o>[] = []\n for (const id of keys) {\n if (id in results) {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n out.push({ id, value: results[id] as o })\n }\n }\n return out\n },\n )\n\n const score_each = map<ReadonlyArray<Pair<o>>, Pair<o>, ScoredPair<ranked>>({\n items: (pairs) => pairs,\n do: score_one,\n })\n\n const pick = use(\n [RESULTS_KEY],\n (vars, scored_pairs: ReadonlyArray<ScoredPair<ranked>>): EnsembleStepResult<o, ranked> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const results = vars[RESULTS_KEY] as Record<string, o>\n const scored: Record<string, ranked> = {}\n let winner_id: string | undefined\n let winner_rank: number | undefined\n let winner_scored: ranked | undefined\n for (const pair of scored_pairs) {\n scored[pair.id] = pair.scored\n const rank = rank_by(pair.scored)\n const better =\n winner_rank === undefined\n ? true\n : select === 'max'\n ? rank > winner_rank\n : rank < winner_rank\n if (better) {\n winner_id = pair.id\n winner_rank = rank\n winner_scored = pair.scored\n }\n }\n if (winner_id === undefined || winner_scored === undefined) {\n throw new Error('ensemble_step: no members produced a result')\n }\n const winner = results[winner_id]\n if (winner === undefined) {\n throw new Error('ensemble_step: winner missing from results')\n }\n return { winner_id, winner, winner_scored, scored }\n },\n )\n\n const inner = scope([\n stash(RESULTS_KEY, fan_out),\n to_pairs,\n score_each,\n pick,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<i, EnsembleStepResult<o, ranked>>\n\n return compose(config.name ?? 'ensemble_step', inner)\n}\n","/**\n * improve: bounded online self-improvement loop.\n *\n * `improve({ seed, propose, score, budget })` runs a round-bounded loop that\n * threads a `parent` candidate through repeated propose → score → accept/reject\n * cycles. The kernel decides acceptance via a hard gate (`scored.accepted`) and\n * an epsilon-improvement test (`scored.score > parent_score + epsilon`).\n * Plateau detection stops the loop early when no progress has been made for\n * `patience` rounds; an optional wall-clock budget caps total runtime.\n *\n * `improve` is the *online* counterpart to `learn`: where `learn` reflects on\n * recorded trajectories offline, `improve` runs the propose/score loop live\n * inside a single run. The amplify example is a domain-specific consumer of\n * this same pattern (filesystem mutation, test-suite gates, subprocess\n * research). `improve` strips those opinions out so any domain can plug in\n * its own `propose` and `score` steps.\n *\n * Implemented as a `compose`d `scope` of (seed) → (init state) → (loop) →\n * (unwrap). The loop body is itself a small `scope` that snapshots prior\n * state, builds a round input, dispatches the proposers + scorer via\n * `ensemble_step`, and merges the outcome back into state via `use`.\n * State threading is the entire job.\n */\n\nimport { compose, loop, scope, step, stash, use } from '#core'\nimport type { LoopResult, Step } from '#core'\nimport { ensemble_step } from './ensemble_step.js'\n\nexport type Candidate<c> = {\n readonly content: c\n readonly proposer_id: string\n readonly rationale?: string\n}\n\nexport type ScoredCandidate<c> = {\n readonly candidate: Candidate<c>\n readonly score: number\n readonly accepted: boolean\n readonly reason?: string\n}\n\nexport type Lesson = {\n readonly round: number\n readonly proposer_id: string\n readonly reason: string\n}\n\nexport type ImproveRoundInput<c> = {\n readonly parent: c\n readonly parent_score: number\n readonly round: number\n readonly lessons: ReadonlyArray<Lesson>\n}\n\nexport type ImproveBudget = {\n readonly max_rounds: number\n readonly max_wallclock_ms?: number\n readonly patience: number\n}\n\nexport type ImproveConfig<i, c> = {\n readonly name?: string\n readonly seed: Step<i, { readonly content: c; readonly score: number }>\n readonly propose: Step<ImproveRoundInput<c>, Candidate<c>>\n readonly score: Step<Candidate<c>, ScoredCandidate<c>>\n readonly budget: ImproveBudget\n readonly epsilon?: number\n readonly proposers_per_round?: number\n readonly lessons_capacity?: number\n}\n\nexport type HistoryEntry<c> = {\n readonly round: number\n readonly winner: ScoredCandidate<c>\n readonly accepted: boolean\n}\n\nexport type ImproveResult<c> = {\n readonly best: { readonly content: c; readonly score: number }\n readonly rounds_used: number\n readonly stopped_by: 'budget' | 'plateau'\n readonly history: ReadonlyArray<HistoryEntry<c>>\n}\n\nconst PRIOR_KEY = '__improve_prior'\n\ntype ImproveState<c> = {\n readonly parent: c\n readonly parent_score: number\n readonly round: number\n readonly rounds_since_progress: number\n readonly started_at_ms: number\n readonly history: ReadonlyArray<HistoryEntry<c>>\n readonly lessons: ReadonlyArray<Lesson>\n readonly stopped_by?: 'budget' | 'plateau'\n}\n\nexport function improve<i, c>(\n config: ImproveConfig<i, c>,\n): Step<i, ImproveResult<c>> {\n const { seed, propose, score, budget } = config\n const epsilon = config.epsilon ?? 0\n const proposers_per_round = Math.max(1, config.proposers_per_round ?? 1)\n const lessons_capacity = Math.max(0, config.lessons_capacity ?? 5)\n const { max_rounds, max_wallclock_ms, patience } = budget\n\n const proposers: Record<string, Step<ImproveRoundInput<c>, Candidate<c>>> = {}\n for (let i = 0; i < proposers_per_round; i += 1) {\n proposers[`p${String(i)}`] = propose\n }\n\n const round_ensemble = ensemble_step<\n ImproveRoundInput<c>,\n Candidate<c>,\n ScoredCandidate<c>\n >({\n name: 'improve_round',\n members: proposers,\n score,\n rank_by: (s) => s.score,\n })\n\n type RoundResult = {\n readonly winner_id: string\n readonly winner: Candidate<c>\n readonly winner_scored: ScoredCandidate<c>\n readonly scored: Record<string, ScoredCandidate<c>>\n }\n\n const project_round = use(\n [PRIOR_KEY],\n (vars, ensemble_result: RoundResult, ctx): ScoredCandidate<c> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars[PRIOR_KEY] as ImproveState<c>\n const round = prior.round + 1\n for (const slot_id of Object.keys(ensemble_result.scored)) {\n const scored = ensemble_result.scored[slot_id]\n if (scored === undefined) continue\n ctx.trajectory.record({\n kind: 'improve.candidate',\n round,\n proposer_id: slot_id,\n score: scored.score,\n accepted: scored.accepted,\n ...(scored.reason === undefined ? {} : { reason: scored.reason }),\n })\n }\n const w = ensemble_result.winner_scored\n return {\n ...w,\n candidate: { ...w.candidate, proposer_id: ensemble_result.winner_id },\n }\n },\n )\n\n const init_state = step(\n 'improve_init_state',\n (seed_result: { content: c; score: number }): ImproveState<c> => ({\n parent: seed_result.content,\n parent_score: seed_result.score,\n round: 0,\n rounds_since_progress: 0,\n started_at_ms: Date.now(),\n history: [],\n lessons: [],\n }),\n )\n\n const to_round_input = step(\n 'improve_to_round_input',\n (s: ImproveState<c>, ctx): ImproveRoundInput<c> => {\n const round = s.round + 1\n ctx.trajectory.record({\n kind: 'improve.round_start',\n round,\n parent_score: s.parent_score,\n lessons_count: s.lessons.length,\n })\n return {\n parent: s.parent,\n parent_score: s.parent_score,\n round,\n lessons: s.lessons,\n }\n },\n )\n\n const merge_outcome = use(\n [PRIOR_KEY],\n (vars, scored: ScoredCandidate<c>, ctx): ImproveState<c> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars[PRIOR_KEY] as ImproveState<c>\n const next_round = prior.round + 1\n const better = scored.score > prior.parent_score + epsilon\n const accepted = scored.accepted && better\n const next_lessons = !accepted && scored.reason !== undefined\n ? [\n ...prior.lessons,\n {\n round: next_round,\n proposer_id: scored.candidate.proposer_id,\n reason: scored.reason,\n },\n ].slice(-lessons_capacity)\n : prior.lessons\n ctx.trajectory.record({\n kind: accepted ? 'improve.accept' : 'improve.reject',\n round: next_round,\n proposer_id: scored.candidate.proposer_id,\n score: scored.score,\n prior_score: prior.parent_score,\n ...(accepted ? { delta: scored.score - prior.parent_score } : {}),\n ...(scored.reason === undefined ? {} : { reason: scored.reason }),\n })\n return {\n parent: accepted ? scored.candidate.content : prior.parent,\n parent_score: accepted ? scored.score : prior.parent_score,\n round: next_round,\n rounds_since_progress: accepted ? 0 : prior.rounds_since_progress + 1,\n started_at_ms: prior.started_at_ms,\n history: [\n ...prior.history,\n { round: next_round, winner: scored, accepted },\n ],\n lessons: next_lessons,\n }\n },\n )\n\n const body = scope([\n stash(PRIOR_KEY, step('improve_snapshot', (s: ImproveState<c>) => s)),\n to_round_input,\n round_ensemble,\n project_round,\n merge_outcome,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<ImproveState<c>, ImproveState<c>>\n\n const guard = step(\n 'improve_guard',\n (s: ImproveState<c>): { stop: boolean; state: ImproveState<c> } => {\n if (s.rounds_since_progress >= patience) {\n return { stop: true, state: { ...s, stopped_by: 'plateau' } }\n }\n if (\n max_wallclock_ms !== undefined &&\n Date.now() - s.started_at_ms >= max_wallclock_ms\n ) {\n return { stop: true, state: { ...s, stopped_by: 'budget' } }\n }\n return { stop: false, state: s }\n },\n )\n\n const round_loop = loop<ImproveState<c>, ImproveState<c>, ImproveResult<c>>({\n init: (s) => s,\n body,\n guard,\n finish: (s): ImproveResult<c> => ({\n best: { content: s.parent, score: s.parent_score },\n rounds_used: s.round,\n stopped_by: s.stopped_by ?? 'budget',\n history: s.history,\n }),\n max_rounds,\n })\n\n const unwrap = step(\n 'improve_unwrap',\n (result: LoopResult<ImproveResult<c>>, ctx): ImproveResult<c> => {\n ctx.trajectory.record({\n kind: 'improve.stop',\n stopped_by: result.value.stopped_by,\n rounds_used: result.value.rounds_used,\n final_score: result.value.best.score,\n })\n return result.value\n },\n )\n\n const inner = scope([\n seed,\n init_state,\n round_loop,\n unwrap,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<i, ImproveResult<c>>\n\n return compose(config.name ?? 'improve', inner)\n}\n","/**\n * learn: offline self-improvement composer.\n *\n * `learn({ flow, source, analyzer })` reads recorded trajectory events from\n * past runs of `flow`, hands them to a user-supplied `analyzer` step alongside\n * `describe(flow)`, and returns the analyzer's proposals plus summary metadata\n * (events considered, distinct run ids).\n *\n * The amplify example is the *online* counterpart of this pattern: propose →\n * score → accept/reject inside a single run. `learn` is the *offline*\n * counterpart: reflect on what already happened across one or many recorded\n * runs without an evaluator in the loop.\n *\n * Implemented as a `compose`d `scope` of (compute meta) → (build LearnInput) →\n * (analyzer) → (wrap result with meta). No engine dependency; the analyzer\n * decides how to use the events.\n *\n * Three source kinds: `events` (in-memory), `paths` (explicit JSONL files),\n * `dir` (recursive *.jsonl walk). File reads honor `ctx.abort` at file-level\n * granularity; malformed lines are skipped and surface as `learn.parse_error`\n * trajectory events with 1-indexed line offsets. When `max_events` clips the\n * filtered set, a `learn.truncated` event records `available`, `kept`, and the\n * configured cap.\n */\n\nimport { readFile, readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n aborted_error,\n compose,\n describe,\n scope,\n stash,\n step,\n trajectory_event_schema,\n use,\n} from '#core'\nimport type { RunContext, Step, TrajectoryEvent } from '#core'\n\nexport type TrajectorySource =\n | { readonly kind: 'events'; readonly events: ReadonlyArray<TrajectoryEvent> }\n | { readonly kind: 'paths'; readonly paths: ReadonlyArray<string> }\n | { readonly kind: 'dir'; readonly dir: string }\n\nexport type LearnInput = {\n readonly flow_description: string\n readonly events: ReadonlyArray<TrajectoryEvent>\n readonly prior?: unknown\n}\n\nexport type Improvement = {\n readonly target: string\n readonly kind: 'prompt' | 'config' | 'structure' | 'note'\n readonly rationale: string\n readonly suggestion: string\n}\n\nexport type LearnConfig<i extends LearnInput, o> = {\n readonly name?: string\n readonly flow: Step<unknown, unknown>\n readonly source: TrajectorySource\n readonly analyzer: Step<i, o>\n readonly filter?: (event: TrajectoryEvent) => boolean\n readonly max_events?: number\n}\n\nexport type LearnResult<o> = {\n readonly proposals: o\n readonly events_considered: number\n readonly run_ids: ReadonlyArray<string>\n}\n\nconst DEFAULT_MAX_EVENTS = 10_000\nconst META_KEY = '__learn_meta'\n\ntype LearnMeta = {\n readonly events_considered: number\n readonly run_ids: ReadonlyArray<string>\n}\n\ntype MetaPlus = LearnMeta & {\n readonly events: ReadonlyArray<TrajectoryEvent>\n readonly prior: unknown\n}\n\nasync function walk_jsonl(dir: string): Promise<string[]> {\n const out: string[] = []\n const entries = await readdir(dir, { withFileTypes: true })\n for (const entry of entries) {\n const full = join(dir, entry.name)\n if (entry.isDirectory()) {\n out.push(...(await walk_jsonl(full)))\n } else if (entry.isFile() && entry.name.endsWith('.jsonl')) {\n out.push(full)\n }\n }\n return out\n}\n\nasync function read_jsonl(file_path: string, ctx: RunContext): Promise<TrajectoryEvent[]> {\n const content = await readFile(file_path, 'utf8')\n const lines = content.split('\\n')\n const events: TrajectoryEvent[] = []\n for (let i = 0; i < lines.length; i += 1) {\n const raw = lines[i]\n if (raw === undefined || raw.trim() === '') continue\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n ctx.trajectory.record({ kind: 'learn.parse_error', path: file_path, line: i + 1 })\n continue\n }\n const result = trajectory_event_schema.safeParse(parsed)\n if (result.success) {\n events.push(result.data)\n } else {\n ctx.trajectory.record({ kind: 'learn.parse_error', path: file_path, line: i + 1 })\n }\n }\n return events\n}\n\nfunction throw_if_aborted(ctx: RunContext): void {\n if (!ctx.abort.aborted) return\n const reason = ctx.abort.reason\n if (reason instanceof aborted_error) throw reason\n throw new aborted_error('aborted', reason === undefined ? {} : { reason })\n}\n\nasync function resolve_events(\n source: TrajectorySource,\n ctx: RunContext,\n): Promise<ReadonlyArray<TrajectoryEvent>> {\n if (source.kind === 'events') return source.events\n\n const file_paths =\n source.kind === 'paths' ? [...source.paths] : (await walk_jsonl(source.dir)).toSorted()\n\n const all: TrajectoryEvent[] = []\n for (const p of file_paths) {\n throw_if_aborted(ctx)\n const events = await read_jsonl(p, ctx)\n all.push(...events)\n }\n return all\n}\n\nfunction collect_run_ids(events: ReadonlyArray<TrajectoryEvent>): ReadonlyArray<string> {\n const seen = new Set<string>()\n const out: string[] = []\n for (const event of events) {\n const id = event['run_id']\n if (typeof id === 'string' && !seen.has(id)) {\n seen.add(id)\n out.push(id)\n }\n }\n return out\n}\n\nexport function learn<i extends LearnInput, o>(\n config: LearnConfig<i, o>,\n): Step<unknown, LearnResult<o>> {\n const { flow, source, analyzer, filter } = config\n const max = config.max_events ?? DEFAULT_MAX_EVENTS\n\n const compute_meta = step(\n 'learn_compute_meta',\n async (prior: unknown, ctx): Promise<MetaPlus> => {\n const all = await resolve_events(source, ctx)\n const filtered = filter ? all.filter(filter) : all\n const truncated = filtered.length > max\n const capped = truncated ? filtered.slice(0, max) : filtered\n if (truncated) {\n ctx.trajectory.record({\n kind: 'learn.truncated',\n available: filtered.length,\n kept: capped.length,\n max_events: max,\n })\n }\n return {\n events_considered: capped.length,\n run_ids: collect_run_ids(capped),\n events: capped,\n prior,\n }\n },\n )\n\n const build_input = step(\n 'learn_build_input',\n (meta: MetaPlus): LearnInput => ({\n flow_description: describe(flow),\n events: meta.events,\n prior: meta.prior,\n }),\n )\n\n const wrap_result = use(\n [META_KEY],\n (vars, proposals: o, ctx): LearnResult<o> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const meta = vars[META_KEY] as LearnMeta\n ctx.trajectory.record({\n kind: 'learn.summary',\n events_considered: meta.events_considered,\n run_ids: meta.run_ids,\n })\n return {\n proposals,\n events_considered: meta.events_considered,\n run_ids: meta.run_ids,\n }\n },\n )\n\n const inner = scope([\n stash(META_KEY, compute_meta),\n build_input,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n analyzer as unknown as Step<unknown, unknown>,\n wrap_result,\n ])\n\n return compose(config.name ?? 'learn', inner)\n}\n","/**\n * tournament: pairwise bracket.\n *\n * `tournament({ members, compare })` runs every member, then pairs them off\n * in a single-elimination bracket. `compare(a, b)` returns which result\n * advances. An odd member count yields one bye per affected round. Returns\n * `{ winner, bracket }` where `bracket` lists every match record.\n *\n * Implemented as a `compose`d `sequence` of `parallel(members)` followed\n * by a single bracket-reduction step. Cancellation, fan-out, and abort\n * propagation come from `parallel`'s contract; the bracket step only runs\n * after all members settle.\n */\n\nimport { compose, parallel, sequence, step } from '#core'\nimport type { Step } from '#core'\n\nexport type BracketRecord = {\n readonly round: number\n readonly a_id: string\n readonly b_id: string\n readonly winner_id: string\n}\n\nexport type TournamentConfig<i, o> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly compare: (a: o, b: o) => Promise<'a' | 'b'> | 'a' | 'b'\n}\n\nexport type TournamentResult<o> = {\n readonly winner: o\n readonly bracket: ReadonlyArray<BracketRecord>\n}\n\nexport function tournament<i, o>(\n config: TournamentConfig<i, o>,\n): Step<i, TournamentResult<o>> {\n const compare_fn = config.compare\n const keys = Object.keys(config.members)\n\n if (keys.length === 0) {\n throw new Error('tournament: at least one member required')\n }\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const fan_out = parallel(config.members) as Step<i, Record<string, o>>\n\n const bracket_step = step('bracket', async (results: Record<string, o>) => {\n let current: string[] = [...keys]\n const bracket: BracketRecord[] = []\n let round = 0\n \n while (current.length > 1) {\n round += 1\n const next_round: string[] = []\n for (let i = 0; i < current.length; i += 2) {\n const a_id = current[i]\n const b_id = current[i + 1]\n if (a_id === undefined) continue\n if (b_id === undefined) {\n next_round.push(a_id)\n continue\n }\n const a_val = results[a_id]\n const b_val = results[b_id]\n if (a_val === undefined || b_val === undefined) {\n throw new Error('tournament: missing result for match')\n }\n const pick = await compare_fn(a_val, b_val)\n const winner_id = pick === 'a' ? a_id : b_id\n bracket.push({ round, a_id, b_id, winner_id })\n next_round.push(winner_id)\n }\n current = next_round\n }\n \n const final_id = current[0]\n if (final_id === undefined) {\n throw new Error('tournament: no winner')\n }\n const winner = results[final_id]\n if (winner === undefined) {\n throw new Error('tournament: winner missing from results')\n }\n return { winner, bracket }\n })\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const inner = sequence([fan_out, bracket_step]) as Step<i, TournamentResult<o>>\n\n return compose(config.name ?? 'tournament', inner)\n}\n","/**\n * bench: run a flow against a fixture set, score each result, return a report.\n *\n * Online counterpart to `learn`: where `learn` reflects on past trajectories\n * after the fact, `bench` runs the flow live against fresh `cases`, judges\n * each output, and produces a `BenchReport` you can compare against a\n * committed baseline via `regression_compare`.\n *\n * Each case becomes one `run(flow, case.input, ...)`. Per-case observability:\n * - `trajectory_dir` writes `${dir}/${case.id}.jsonl` via filesystem_logger\n * - `live_url` POSTs each event via http_logger to a viewer's /api/ingest\n * - both can be combined; bench tees them with an internal cost tracker\n *\n * Cost is tracked per-case in-process by intercepting `kind: 'cost'` events\n * on the trajectory pipeline. The cost number matches what would be on disk\n * even when no trajectory_dir is set.\n *\n * Judges run as Steps after each case, with the same trajectory logger so\n * judge spans land in the case's trajectory file (or push). A judge that\n * throws or returns undefined abstains: the entry is omitted from\n * `case.scores` and the case does not contribute to that judge's mean.\n */\n\nimport { mkdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { run } from '#core'\nimport type { Step, TrajectoryEvent, TrajectoryLogger } from '#core'\nimport { filesystem_logger, http_logger, tee_logger } from '#adapters'\n\nexport type Score = { readonly score: number; readonly reason?: string }\n\nexport type BenchCase<I> = {\n readonly id: string\n readonly input: I\n readonly meta?: Readonly<Record<string, unknown>>\n}\n\nexport type JudgeArgs<I, O> = {\n readonly input: I\n readonly output: O\n readonly meta?: Readonly<Record<string, unknown>>\n}\n\nexport type Judge<I, O, S = Score> = Step<JudgeArgs<I, O>, S | undefined>\n\nexport type CaseResult<I = unknown, O = unknown, S = Score> = {\n readonly case_id: string\n readonly ok: boolean\n readonly output?: O\n readonly error?: string\n readonly scores: Record<string, S>\n readonly duration_ms: number\n readonly cost_usd: number\n readonly trajectory_path?: string\n readonly _input?: I\n}\n\nexport type BenchSummary = {\n readonly pass_rate: number\n readonly mean_scores: Record<string, number>\n readonly total_duration_ms: number\n readonly total_cost_usd: number\n readonly mean_cost_usd: number\n}\n\nexport type BenchReport<I = unknown, O = unknown, S = Score> = {\n readonly flow_name: string\n readonly run_id: string\n readonly cases: ReadonlyArray<CaseResult<I, O, S>>\n readonly summary: BenchSummary\n}\n\nexport type BenchOptions = {\n readonly concurrency?: number\n readonly on_case?: (result: CaseResult) => void\n readonly trajectory_dir?: string\n readonly live_url?: string\n readonly run_id?: string\n readonly install_signal_handlers?: boolean\n}\n\nexport async function bench<I, O, S = Score>(\n flow: Step<I, O>,\n cases: ReadonlyArray<BenchCase<I>>,\n judges: Record<string, Judge<I, O, S>>,\n options: BenchOptions = {},\n): Promise<BenchReport<I, O, S>> {\n const run_id = options.run_id ?? `bench-${String(Date.now())}-${random_suffix()}`\n const flow_name = describe_flow_name(flow)\n const concurrency = resolve_concurrency(options.concurrency, cases.length)\n const install_signal_handlers = options.install_signal_handlers ?? false\n\n if (options.trajectory_dir !== undefined) {\n await mkdir(options.trajectory_dir, { recursive: true })\n }\n\n const judge_entries = Object.entries(judges)\n\n const run_one = async (bc: BenchCase<I>): Promise<CaseResult<I, O, S>> => {\n const trajectory_path =\n options.trajectory_dir === undefined\n ? undefined\n : join(options.trajectory_dir, `${bc.id}.jsonl`)\n const sinks: TrajectoryLogger[] = []\n if (trajectory_path !== undefined) {\n sinks.push(filesystem_logger({ output_path: trajectory_path }))\n }\n if (options.live_url !== undefined) {\n sinks.push(http_logger({ url: options.live_url }))\n }\n const cost_tracker = create_cost_tracker()\n const case_logger: TrajectoryLogger =\n sinks.length === 0\n ? cost_tracker.logger\n : tee_logger(...sinks, cost_tracker.logger)\n\n const start = Date.now()\n let output: O | undefined\n let error: string | undefined\n let ok = false\n try {\n output = await run(flow, bc.input, {\n trajectory: case_logger,\n install_signal_handlers,\n })\n ok = true\n } catch (err) {\n error = err instanceof Error ? err.message : String(err)\n ok = false\n }\n\n const scores: Record<string, S> = {}\n if (ok && output !== undefined) {\n const judge_input: JudgeArgs<I, O> = bc.meta === undefined\n ? { input: bc.input, output }\n : { input: bc.input, output, meta: bc.meta }\n for (const [name, judge] of judge_entries) {\n let raw: unknown\n try {\n // oxlint-disable-next-line no-await-in-loop\n raw = await run(judge, judge_input, {\n trajectory: case_logger,\n install_signal_handlers,\n })\n } catch {\n continue\n }\n const normalized = normalize_score(raw)\n if (normalized === undefined) continue\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n scores[name] = normalized as S\n }\n }\n\n const duration_ms = Date.now() - start\n const result: CaseResult<I, O, S> = {\n case_id: bc.id,\n ok,\n ...(output !== undefined ? { output } : {}),\n ...(error !== undefined ? { error } : {}),\n scores,\n duration_ms,\n cost_usd: cost_tracker.total(),\n ...(trajectory_path !== undefined ? { trajectory_path } : {}),\n }\n if (options.on_case) {\n // The on_case callback receives the lossy-typed shape — bench's S is\n // generic but the callback hook is a single concrete signature.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n options.on_case(result as unknown as CaseResult)\n }\n return result\n }\n\n const cases_out = await run_with_concurrency(cases, concurrency, run_one)\n const summary = summarize(cases_out, judge_entries.map(([n]) => n))\n\n return {\n flow_name,\n run_id,\n cases: cases_out,\n summary,\n }\n}\n\nfunction summarize<I, O, S>(\n cases: ReadonlyArray<CaseResult<I, O, S>>,\n judge_names: ReadonlyArray<string>,\n): BenchSummary {\n const total_duration_ms = cases.reduce((acc, c) => acc + c.duration_ms, 0)\n const total_cost_usd = cases.reduce((acc, c) => acc + c.cost_usd, 0)\n const ok_count = cases.filter((c) => c.ok).length\n const pass_rate = cases.length === 0 ? 0 : ok_count / cases.length\n const mean_cost_usd = cases.length === 0 ? 0 : total_cost_usd / cases.length\n\n const mean_scores: Record<string, number> = {}\n for (const name of judge_names) {\n let sum = 0\n let count = 0\n for (const c of cases) {\n const n = score_value_of(c.scores[name])\n if (n === undefined) continue\n sum += n\n count += 1\n }\n if (count > 0) mean_scores[name] = sum / count\n }\n\n return {\n pass_rate,\n mean_scores,\n total_duration_ms,\n total_cost_usd,\n mean_cost_usd,\n }\n}\n\nexport function normalize_score(raw: unknown): Score | undefined {\n if (raw === undefined || raw === null) return undefined\n if (typeof raw === 'number') {\n return Number.isFinite(raw) ? { score: raw } : undefined\n }\n if (typeof raw === 'object' && 'score' in raw) {\n const r = raw as { score: unknown; reason?: unknown }\n if (typeof r.score !== 'number' || !Number.isFinite(r.score)) return undefined\n if (r.reason !== undefined && typeof r.reason !== 'string') {\n return { score: r.score }\n }\n return r.reason === undefined ? { score: r.score } : { score: r.score, reason: r.reason }\n }\n return undefined\n}\n\nfunction score_value_of(s: unknown): number | undefined {\n if (s === undefined || s === null) return undefined\n if (typeof s === 'number') return Number.isFinite(s) ? s : undefined\n if (typeof s === 'object' && 'score' in s) {\n const raw = (s as Record<string, unknown>)['score']\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined\n }\n return undefined\n}\n\nfunction create_cost_tracker(): {\n readonly logger: TrajectoryLogger\n readonly total: () => number\n} {\n let total = 0\n return {\n total: () => total,\n logger: {\n record: (event: TrajectoryEvent) => {\n if (event.kind !== 'cost') return\n const e: Record<string, unknown> = event\n const value = e['total_usd']\n if (typeof value === 'number' && Number.isFinite(value)) total += value\n },\n start_span: (name) => `cost-tracker:${name}`,\n end_span: () => {},\n },\n }\n}\n\nasync function run_with_concurrency<t, r>(\n items: ReadonlyArray<t>,\n limit: number,\n fn: (item: t) => Promise<r>,\n): Promise<r[]> {\n if (items.length === 0) return []\n if (limit >= items.length) {\n return Promise.all(items.map((it) => fn(it)))\n }\n const results: r[] = Array.from({ length: items.length })\n let next = 0\n const worker = async (): Promise<void> => {\n while (true) {\n const idx = next\n next += 1\n if (idx >= items.length) return\n const item = items[idx]\n if (item === undefined) continue\n // oxlint-disable-next-line no-await-in-loop\n results[idx] = await fn(item)\n }\n }\n const workers: Promise<void>[] = []\n for (let i = 0; i < limit; i += 1) workers.push(worker())\n await Promise.all(workers)\n return results\n}\n\nfunction resolve_concurrency(value: number | undefined, n_cases: number): number {\n if (value === undefined) return Math.max(1, n_cases)\n if (!Number.isFinite(value) || value <= 0) return Math.max(1, n_cases)\n return Math.max(1, Math.floor(value))\n}\n\nfunction describe_flow_name<I, O>(flow: Step<I, O>): string {\n const display = flow.config?.['display_name']\n if (typeof display === 'string' && display.length > 0) return display\n return flow.id ?? flow.kind ?? 'flow'\n}\n\nfunction random_suffix(): string {\n return Math.random().toString(36).slice(2, 8)\n}\n","/**\n * Stock judges for `bench`.\n *\n * A `Judge<I, O, S>` is a `Step<{ input, output, meta }, S>` — i.e. just a\n * step that scores a flow's input/output/metadata triple. Returning\n * `undefined` (or throwing) means the judge abstains; bench records the\n * absence as a missing key in `case.scores` and excludes the case from that\n * judge's `mean_scores` denominator.\n *\n * judge_equals — strict equality vs. `meta.expected`\n * judge_with — wrap a user-supplied scoring function\n * judge_llm — prompt a model + parse the rubric score out of the reply\n *\n * `judge_llm` is engine-agnostic: callers pass their already-configured\n * model_call step (Step<string, string>), which keeps composites decoupled\n * from engine. The user-facing wiring lives in their own code.\n */\n\nimport { compose, sequence, step } from '#core'\nimport type { Step } from '#core'\nimport { normalize_score } from './bench.js'\nimport type { Judge, JudgeArgs, Score } from './bench.js'\n\nexport function is_record(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\nexport function deep_equal(a: unknown, b: unknown): boolean {\n if (a === b) return true\n // null, primitives, and array/record mismatches all fall through to the\n // Array.isArray and is_record guards below, so no separate null/typeof\n // pre-checks are needed.\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b)) return false\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i += 1) {\n if (!deep_equal(a[i], b[i])) return false\n }\n return true\n }\n if (!is_record(a) || !is_record(b)) return false\n const ak = Object.keys(a).toSorted()\n const bk = Object.keys(b).toSorted()\n if (ak.length !== bk.length) return false\n for (let i = 0; i < ak.length; i += 1) {\n const ka = ak[i]\n const kb = bk[i]\n if (ka === undefined || kb === undefined || ka !== kb) return false\n if (!deep_equal(a[ka], b[kb])) return false\n }\n return true\n}\n\nexport function judge_equals<O>(): Judge<unknown, O> {\n return step('judge_equals', (args: JudgeArgs<unknown, O>): Score | undefined => {\n if (args.meta === undefined) return undefined\n if (!('expected' in args.meta)) return undefined\n const expected = args.meta['expected']\n const matches = deep_equal(args.output, expected)\n return { score: matches ? 1 : 0, reason: matches ? 'match' : 'mismatch' }\n })\n}\n\nexport type JudgeWithFn<I, O> = (\n args: JudgeArgs<I, O>,\n) => number | Score | undefined | Promise<number | Score | undefined>\n\nexport function judge_with<I, O>(fn: JudgeWithFn<I, O>): Judge<I, O> {\n return step('judge_with', async (args: JudgeArgs<I, O>): Promise<Score | undefined> => {\n const raw = await fn(args)\n return normalize_score(raw)\n })\n}\n\nexport type JudgeLlmConfig = {\n readonly model: Step<string, string>\n readonly rubric: string\n readonly scale?: { readonly min: number; readonly max: number }\n}\n\nexport function judge_llm<I, O>(config: JudgeLlmConfig): Judge<I, O> {\n const scale = config.scale ?? { min: 0, max: 1 }\n const build_prompt = step('judge_llm_build_prompt', (args: JudgeArgs<I, O>): string =>\n render_prompt(config.rubric, scale, args),\n )\n const parse = step('judge_llm_parse', (reply: string): Score | undefined =>\n parse_score(reply, scale),\n )\n const inner = sequence([build_prompt, config.model, parse])\n return compose('judge_llm', inner)\n}\n\nexport function render_prompt<I, O>(\n rubric: string,\n scale: { min: number; max: number },\n args: JudgeArgs<I, O>,\n): string {\n return [\n `You are an evaluator. Score the model output against the rubric below.`,\n ``,\n `Rubric:`,\n rubric,\n ``,\n `Return a single line of JSON with exactly two keys: {\"score\": <number ${String(scale.min)}..${String(scale.max)}>, \"reason\": \"<short>\"}.`,\n `Do not include prose outside the JSON.`,\n ``,\n `Input:`,\n JSON.stringify(args.input),\n ``,\n `Output:`,\n JSON.stringify(args.output),\n ].join('\\n')\n}\n\nexport function parse_score(\n reply: string,\n scale: { min: number; max: number },\n): Score | undefined {\n const trimmed = reply.trim()\n const candidate = extract_json_object(trimmed)\n if (candidate === undefined) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(candidate)\n } catch {\n return undefined\n }\n if (!is_record(parsed)) return undefined\n const raw_score = parsed['score']\n if (typeof raw_score !== 'number' || !Number.isFinite(raw_score)) return undefined\n const clamped = Math.max(scale.min, Math.min(scale.max, raw_score))\n const raw_reason = parsed['reason']\n const reason = typeof raw_reason === 'string' ? raw_reason : undefined\n return reason === undefined ? { score: clamped } : { score: clamped, reason }\n}\n\nexport function extract_json_object(text: string): string | undefined {\n if (text.startsWith('{')) return text\n const start = text.indexOf('{')\n const end = text.lastIndexOf('}')\n if (start === -1 || end === -1 || end < start) return undefined\n return text.slice(start, end + 1)\n}\n","/**\n * regression_compare: diff two BenchReports for regressions.\n *\n * The contract: given a `current` report and a `baseline` report, produce a\n * `RegressionReport` whose `ok` flag is false when any tracked metric got\n * worse beyond a threshold. The function does NOT short-circuit on first\n * failure — every metric and every per-case delta is computed so callers can\n * print or assert against the whole report.\n *\n * Tracked metrics:\n * - pass_rate (any drop is a regression by default)\n * - mean_scores.<name> (per judge; any drop is a regression by default)\n * - total_cost_usd (a relative cost increase above cost_threshold\n * counts as a regression; default 10%)\n *\n * Baselines are plain JSON, written via `write_baseline` and read via\n * `read_baseline`. They live wherever the caller decides — typically\n * `bench/<flow>/baseline.json`, checked into git per\n * `research/explorations/2026-04-eval-surface.md` §3.\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport type { BenchReport, CaseResult } from './bench.js'\n\nexport type RegressionDelta = {\n readonly metric: string\n readonly baseline: number\n readonly current: number\n readonly delta: number\n readonly is_regression: boolean\n}\n\nexport type PerCaseDelta = {\n readonly case_id: string\n readonly baseline?: CaseResult\n readonly current?: CaseResult\n readonly score_deltas: Record<string, number>\n readonly cost_delta: number\n readonly is_regression: boolean\n}\n\nexport type RegressionReport = {\n readonly ok: boolean\n readonly deltas: ReadonlyArray<RegressionDelta>\n readonly per_case: ReadonlyArray<PerCaseDelta>\n}\n\nexport type RegressionCompareOptions = {\n readonly score_threshold?: number\n readonly cost_threshold?: number\n}\n\nexport function regression_compare(\n current: BenchReport,\n baseline: BenchReport,\n options: RegressionCompareOptions = {},\n): RegressionReport {\n const score_threshold = options.score_threshold ?? 0\n const cost_threshold = options.cost_threshold ?? 0.1\n\n const deltas: RegressionDelta[] = []\n\n const pass_delta = current.summary.pass_rate - baseline.summary.pass_rate\n deltas.push({\n metric: 'pass_rate',\n baseline: baseline.summary.pass_rate,\n current: current.summary.pass_rate,\n delta: pass_delta,\n is_regression: pass_delta < -score_threshold,\n })\n\n const judge_names = collect_judge_names(current, baseline)\n for (const name of judge_names) {\n const c = current.summary.mean_scores[name] ?? 0\n const b = baseline.summary.mean_scores[name] ?? 0\n const d = c - b\n deltas.push({\n metric: `mean_scores.${name}`,\n baseline: b,\n current: c,\n delta: d,\n is_regression: d < -score_threshold,\n })\n }\n\n const cb = baseline.summary.total_cost_usd\n const cc = current.summary.total_cost_usd\n const cost_delta = cc - cb\n const cost_ratio = cb === 0 ? (cc > 0 ? Infinity : 0) : cost_delta / cb\n deltas.push({\n metric: 'total_cost_usd',\n baseline: cb,\n current: cc,\n delta: cost_delta,\n is_regression: cost_ratio > cost_threshold,\n })\n\n const per_case = compute_per_case(current, baseline, score_threshold, cost_threshold)\n const ok = !deltas.some((d) => d.is_regression) && !per_case.some((c) => c.is_regression)\n\n return { ok, deltas, per_case }\n}\n\nfunction compute_per_case(\n current: BenchReport,\n baseline: BenchReport,\n score_threshold: number,\n cost_threshold: number,\n): PerCaseDelta[] {\n const by_id_current = index_by_case_id(current.cases)\n const by_id_baseline = index_by_case_id(baseline.cases)\n const all_ids = new Set<string>([...by_id_current.keys(), ...by_id_baseline.keys()])\n\n const out: PerCaseDelta[] = []\n for (const id of all_ids) {\n const c = by_id_current.get(id)\n const b = by_id_baseline.get(id)\n const score_deltas: Record<string, number> = {}\n let any_score_regression = false\n const judge_names = new Set<string>([\n ...Object.keys(c?.scores ?? {}),\n ...Object.keys(b?.scores ?? {}),\n ])\n for (const name of judge_names) {\n const c_score = score_value(c?.scores[name])\n const b_score = score_value(b?.scores[name])\n const delta = c_score - b_score\n score_deltas[name] = delta\n if (delta < -score_threshold) any_score_regression = true\n }\n const cost_delta = (c?.cost_usd ?? 0) - (b?.cost_usd ?? 0)\n const cost_ratio_regression =\n b?.cost_usd !== undefined && b.cost_usd > 0\n ? cost_delta / b.cost_usd > cost_threshold\n : (c?.cost_usd ?? 0) > 0 && (b?.cost_usd ?? 0) === 0 && cost_threshold < Infinity\n const ok_regression = b?.ok === true && c?.ok !== true\n out.push({\n case_id: id,\n ...(b !== undefined ? { baseline: b } : {}),\n ...(c !== undefined ? { current: c } : {}),\n score_deltas,\n cost_delta,\n is_regression: any_score_regression || cost_ratio_regression || ok_regression,\n })\n }\n return out\n}\n\nfunction score_value(s: unknown): number {\n if (s === undefined || s === null) return 0\n if (typeof s === 'number') return Number.isFinite(s) ? s : 0\n if (typeof s === 'object' && 'score' in s) {\n const v = (s as Record<string, unknown>)['score']\n return typeof v === 'number' && Number.isFinite(v) ? v : 0\n }\n return 0\n}\n\nfunction index_by_case_id<I, O, S>(\n cases: ReadonlyArray<CaseResult<I, O, S>>,\n): Map<string, CaseResult<I, O, S>> {\n const m = new Map<string, CaseResult<I, O, S>>()\n for (const c of cases) m.set(c.case_id, c)\n return m\n}\n\nfunction collect_judge_names(a: BenchReport, b: BenchReport): string[] {\n const names = new Set<string>([\n ...Object.keys(a.summary.mean_scores),\n ...Object.keys(b.summary.mean_scores),\n ])\n return [...names].toSorted()\n}\n\nexport async function read_baseline(path: string): Promise<BenchReport> {\n const text = await readFile(path, 'utf8')\n const parsed: unknown = JSON.parse(text)\n validate_report(parsed, path)\n return parsed\n}\n\nexport async function write_baseline(path: string, report: BenchReport): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, `${JSON.stringify(report, null, 2)}\\n`, 'utf8')\n}\n\nfunction validate_report(value: unknown, path: string): asserts value is BenchReport {\n if (value === null || typeof value !== 'object') {\n throw new Error(`baseline at ${path} is not an object`)\n }\n const v = value as Partial<BenchReport>\n if (typeof v.flow_name !== 'string' || typeof v.run_id !== 'string') {\n throw new Error(`baseline at ${path} missing flow_name/run_id`)\n }\n if (!Array.isArray(v.cases) || typeof v.summary !== 'object' || v.summary === null) {\n throw new Error(`baseline at ${path} missing cases/summary`)\n }\n}\n\n// Runtime-side type re-export: regression consumers want both the diff types\n// and the underlying CaseResult/Score shapes from one import.\nexport type { Score } from './bench.js'\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 (spec §5.10):\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: see §5.10 / F17. compute_cost is\n * called per-turn, so it reports the fields that saw usage in THIS turn. The\n * top-level aggregation stage is responsible for deciding which fields to\n * omit on the aggregated CostBreakdown.\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 DEFAULT_PRICING: PricingTable = Object.freeze({\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-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 '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: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 'google:gemini-2.5-pro': { input_per_million: 1.25, output_per_million: 5.0 },\n 'google:gemini-2.5-flash': { input_per_million: 0.075, output_per_million: 0.3 },\n})\n\nexport function pricing_key(provider: string, model_id: string): string {\n return `${provider}:${model_id}`\n}\n\nfunction round6(value: number): number {\n return Math.round(value * 1e6) / 1e6\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) {\n if (!FREE_PROVIDERS.has(provider)) return undefined\n const breakdown: CostBreakdown = {\n total_usd: 0,\n input_usd: 0,\n output_usd: 0,\n currency: 'USD',\n is_estimate: true,\n }\n return breakdown\n }\n\n const input_tokens = usage.input_tokens\n const output_tokens = usage.output_tokens\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, 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 has_reasoning_rate = pricing.reasoning_per_million !== undefined\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, output_tokens - reasoning)\n const plain_output_usd_raw = (plain_output_tokens * pricing.output_per_million) / 1e6\n\n const input_usd = round6(input_usd_raw)\n\n let output_usd_raw = plain_output_usd_raw\n let surface_reasoning_usd: number | undefined\n if (reasoning > 0) {\n if (has_reasoning_rate) {\n surface_reasoning_usd = round6(reasoning_usd_raw)\n } else {\n output_usd_raw = plain_output_usd_raw + reasoning_usd_raw\n }\n }\n const output_usd = round6(output_usd_raw)\n\n let cached_input_usd: number | undefined\n let cache_write_usd: number | undefined\n if (cached > 0) cached_input_usd = round6(cached_usd_raw)\n if (cache_write > 0) cache_write_usd = round6(cache_write_usd_raw)\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,\n output_usd,\n currency: 'USD',\n is_estimate: true,\n }\n if (cached_input_usd !== undefined) breakdown.cached_input_usd = cached_input_usd\n if (cache_write_usd !== undefined) breakdown.cache_write_usd = cache_write_usd\n if (surface_reasoning_usd !== undefined) breakdown.reasoning_usd = surface_reasoning_usd\n return breakdown\n}\n","/**\n * Typed errors for the AI engine layer.\n *\n * This is the only source file in the engine module permitted to use the\n * `class` keyword. `Error` is a built-in and `instanceof` branching is how\n * the retry helper and composition-layer composers distinguish failure modes.\n * See constraints §2.\n *\n * `aborted_error` is defined in the core module and re-exported here so that\n * `instanceof aborted_error` is true regardless of which layer surfaced it\n * (D5 in NOTES.md). This is the one value-level import from core permitted\n * in engine source — see `rules/no-core-value-import-in-engine.yml` ignores.\n */\n\nexport { aborted_error } from '#core'\n\nexport class rate_limit_error extends Error {\n readonly kind = 'rate_limit_error' as const;\n readonly retry_after_ms: number | undefined;\n readonly attempts: number;\n readonly status: number | undefined;\n constructor(\n message: string,\n metadata: { retry_after_ms?: number; attempts?: number; status?: number } = {},\n ) {\n super(message)\n this.name = 'rate_limit_error'\n this.retry_after_ms = metadata.retry_after_ms\n this.attempts = metadata.attempts ?? 0\n this.status = metadata.status\n }\n}\n\nexport class provider_error extends Error {\n readonly kind = 'provider_error' as const;\n readonly status: number | undefined;\n readonly body: string | undefined;\n readonly cause_kind: 'provider_5xx' | 'network' | 'unknown' | undefined;\n constructor(\n message: string,\n metadata: {\n status?: number\n body?: string\n cause_kind?: 'provider_5xx' | 'network' | 'unknown'\n } = {},\n ) {\n super(message)\n this.name = 'provider_error'\n this.status = metadata.status\n this.body = metadata.body\n this.cause_kind = metadata.cause_kind\n }\n}\n\n/**\n * Turn-timeout expiry (D5). Thrown by the engine-owned retry_turn wrapper when\n * a depth-1 invoke_turn exceeds `turn_timeout_ms` before any chunk streamed.\n * Its `kind` is the RetryFailureKind wire value `'timeout'` (not the class\n * name) on purpose: that is the discriminant classify_retryable /\n * classify_provider_error already key on, so the shared classifier treats an\n * expiry as retryable without any timeout-specific branch. A mid-stream expiry\n * never reaches here — retry_turn converts it to a non-retryable stream\n * interruption first (C4 parity).\n */\nexport class turn_timeout_error extends Error {\n readonly kind = 'timeout' as const;\n readonly timeout_ms: number;\n readonly step_index: number | undefined;\n constructor(timeout_ms: number, step_index?: number) {\n super(`turn exceeded turn_timeout_ms budget of ${timeout_ms}ms`)\n this.name = 'turn_timeout_error'\n this.timeout_ms = timeout_ms\n this.step_index = step_index\n }\n}\n\nexport class schema_validation_error extends Error {\n readonly kind = 'schema_validation_error' as const;\n readonly zod_error: unknown;\n readonly raw_text: string;\n constructor(message: string, zod_error: unknown, raw_text: string) {\n super(message)\n this.name = 'schema_validation_error'\n this.zod_error = zod_error\n this.raw_text = raw_text\n }\n}\n\nexport class tool_error extends Error {\n readonly kind = 'tool_error' as const;\n readonly tool_name: string;\n readonly tool_call_id: string;\n override readonly cause: unknown;\n constructor(\n message: string,\n metadata: { tool_name: string; tool_call_id: string; cause: unknown },\n ) {\n super(message)\n this.name = 'tool_error'\n this.tool_name = metadata.tool_name\n this.tool_call_id = metadata.tool_call_id\n this.cause = metadata.cause\n }\n}\n\nexport class tool_approval_denied_error extends Error {\n readonly kind = 'tool_approval_denied_error' as const;\n readonly tool_name: string;\n readonly step_index: number;\n readonly tool_call_id: string;\n constructor(\n message: string,\n metadata: { tool_name: string; step_index: number; tool_call_id: string },\n ) {\n super(message)\n this.name = 'tool_approval_denied_error'\n this.tool_name = metadata.tool_name\n this.step_index = metadata.step_index\n this.tool_call_id = metadata.tool_call_id\n }\n}\n\nexport class model_required_error extends Error {\n readonly kind = 'model_required_error' as const;\n constructor(\n message = 'no model specified: pass `model` to generate() or set `defaults.model` on the engine',\n ) {\n super(message)\n this.name = 'model_required_error'\n }\n}\n\nexport class provider_not_configured_error extends Error {\n readonly kind = 'provider_not_configured_error' as const;\n readonly provider: string;\n constructor(provider: string) {\n super(`provider '${provider}' is not configured on this engine`)\n this.name = 'provider_not_configured_error'\n this.provider = provider\n }\n}\n\nexport class engine_config_error extends Error {\n readonly kind = 'engine_config_error' as const;\n readonly provider: string | undefined;\n constructor(message: string, provider?: string) {\n super(message)\n this.name = 'engine_config_error'\n this.provider = provider\n }\n}\n\nexport class on_chunk_error extends Error {\n readonly kind = 'on_chunk_error' as const;\n override readonly cause: unknown;\n constructor(message: string, cause: unknown) {\n super(message)\n this.name = 'on_chunk_error'\n this.cause = cause\n }\n}\n\nexport class provider_capability_error extends Error {\n readonly kind = 'provider_capability_error' as const;\n readonly provider: string;\n readonly capability: string;\n constructor(provider: string, capability: string, detail?: string) {\n const suffix = detail !== undefined ? `: ${detail}` : ''\n super(`provider '${provider}' does not support '${capability}'${suffix}`)\n this.name = 'provider_capability_error'\n this.provider = provider\n this.capability = capability\n }\n}\n\nexport class engine_disposed_error extends Error {\n readonly kind = 'engine_disposed_error' as const;\n constructor(message = 'engine has been disposed; further calls are not permitted') {\n super(message)\n this.name = 'engine_disposed_error'\n }\n}\n\nexport type ClaudeCliErrorReason =\n | 'binary_not_found'\n | 'auth_missing'\n | 'auth_expired'\n | 'api_key_missing'\n | 'startup_timeout'\n | 'stall_timeout'\n | 'no_result_event'\n | 'result_error'\n | 'subprocess_exit'\n | 'sandbox_unavailable'\n | 'engine_disposed'\n | 'parse_error'\n\nexport class claude_cli_error extends Error {\n readonly kind = 'claude_cli_error' as const;\n readonly reason: ClaudeCliErrorReason;\n readonly status: number | undefined;\n readonly stderr_snippet: string | undefined;\n constructor(\n reason: ClaudeCliErrorReason,\n message: string,\n metadata: { status?: number; stderr_snippet?: string } = {},\n ) {\n super(message)\n this.name = 'claude_cli_error'\n this.reason = reason\n this.status = metadata.status\n this.stderr_snippet = metadata.stderr_snippet\n }\n}\n\nexport class provider_auth_error extends Error {\n readonly kind = 'provider_auth_error' as const;\n readonly provider: string;\n readonly refresh_command: string | undefined;\n constructor(\n provider: string,\n message: string,\n metadata: { refresh_command?: string } = {},\n ) {\n super(message)\n this.name = 'provider_auth_error'\n this.provider = provider\n this.refresh_command = metadata.refresh_command\n }\n}\n","/**\n * Retry policy for provider-side failures.\n *\n * Narrow scope: retry 429 rate limits, provider 5xx, network errors, and\n * engine turn-timeout expiry (D5: `turn_timeout_ms` throws a typed timeout the\n * shared classifier treats as retryable). Composition-layer retry wraps the\n * whole generate call; this helper transparently retries a single provider\n * call between tool-loop turns.\n *\n * Invariants:\n * - abort.aborted interrupts backoff waits and throws aborted_error.\n * - Once a streaming response has delivered a chunk, the caller MUST NOT\n * retry (spec §6.8). This helper is not wrapped around streaming calls\n * past first chunk; the orchestrator enforces that boundary.\n * - rate_limit respects Retry-After in both numeric seconds and HTTP-date\n * forms.\n */\n\nimport type { RetryFailureKind, RetryPolicy } from './types.js'\nimport { aborted_error, provider_error, rate_limit_error } from './errors.js'\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\nexport type 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\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\nfunction compute_backoff(policy: RetryPolicy, attempt: number): number {\n const base = policy.initial_delay_ms * 2 ** attempt\n const jitter = Math.random() * policy.initial_delay_ms\n return Math.min(base + jitter, policy.max_delay_ms)\n}\n\nfunction wait_ms(ms: number, abort?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (ms <= 0) {\n resolve()\n return\n }\n if (abort?.aborted === true) {\n reject(new aborted_error('aborted', { reason: abort.reason }))\n return\n }\n const timer = setTimeout(() => {\n if (abort !== undefined) abort.removeEventListener('abort', on_abort)\n resolve()\n }, ms)\n const on_abort = (): void => {\n clearTimeout(timer)\n reject(new aborted_error('aborted', { reason: abort?.reason }))\n }\n abort?.addEventListener('abort', on_abort, { once: true })\n })\n}\n\nfunction is_retryable(kind: RetryFailureKind, policy: RetryPolicy): boolean {\n return policy.retry_on.includes(kind)\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 * Returns the value from the last successful fn() call. On exhaustion, throws\n * rate_limit_error (for 429s) or provider_error (for 5xx/network/timeout).\n */\nexport async function retry_with_policy<t>(\n fn: (attempt: number) => Promise<t>,\n policy: RetryPolicy = DEFAULT_RETRY,\n abort?: AbortSignal,\n): Promise<t> {\n let attempt = 0\n let last_rate_limit_after: number | undefined\n while (true) {\n if (abort?.aborted === true) {\n throw new aborted_error('aborted', { reason: abort.reason })\n }\n try {\n return await fn(attempt)\n } catch (err: unknown) {\n const retryable = classify_retryable(err)\n if (retryable === undefined) throw err\n if (!is_retryable(retryable.kind, policy)) throw err\n attempt += 1\n if (attempt >= policy.max_attempts) {\n if (retryable.kind === 'rate_limit') {\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 throw new rate_limit_error(\n retryable.message ?? `rate limited after ${attempt} attempts`,\n metadata,\n )\n }\n const cause_kind =\n 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 throw new provider_error(\n retryable.message ?? `${retryable.kind} after ${attempt} attempts`,\n metadata,\n )\n }\n\n let delay = compute_backoff(policy, attempt - 1)\n if (retryable.kind === 'rate_limit' && retryable.retry_after_ms !== undefined) {\n // When the server supplies Retry-After, honor it even if it exceeds\n // max_delay_ms; the server's instruction outranks the local backoff cap.\n delay = Math.max(delay, retryable.retry_after_ms)\n last_rate_limit_after = retryable.retry_after_ms\n }\n await wait_ms(delay, abort)\n }\n }\n}\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\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\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') {\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 if (kind === 'provider_5xx') {\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 if (kind === 'network' || kind === 'timeout') {\n const base: RetryableError = { kind }\n const message = read_string(err, 'message')\n if (message !== undefined) base.message = message\n return base\n }\n return undefined\n}\n","/**\n * Shared provider-adapter shape.\n *\n * Each file under packages/engine/src/providers/ exports a factory that\n * accepts a ProviderInit shape and returns a ProviderAdapter. Factories are\n * synchronous; build_model is async so SDK loading is deferred until a model\n * is actually needed. Missing peer dependencies surface as engine_config_error\n * on first build_model call with a clear message naming the missing peer.\n *\n * Invariant 13 (inverted): only the ai_sdk transport module\n * (providers/ai_sdk/invoke.ts) may import from `ai` or invoke\n * generateText/streamText. ai_sdk adapters build the provider model and\n * translate parameters; they do not orchestrate the call.\n */\n\nimport type {\n ResolvedModel,\n EffortLevel,\n GenerateOptions,\n GenerateResult,\n ProviderInit,\n TurnRequest,\n TurnResult,\n UsageTotals,\n} from '../types.js'\nimport { engine_config_error } from '../errors.js'\n\n/**\n * Which depth-1 backend a provider factory returns (D3). The provider name\n * stays the same across transports so pricing keys and usage fields carry\n * over; only the wire implementation changes.\n */\nexport type ProviderTransport = 'ai_sdk' | 'native'\n\n/**\n * Read the `transport` selector off a provider init. Defaults to 'ai_sdk';\n * anything but the two known backends throws at construction so a typo\n * fails loud instead of silently running the default.\n */\nexport function resolve_transport(\n init: ProviderInit,\n provider: string,\n): ProviderTransport {\n const raw = init['transport']\n if (raw === undefined || raw === 'ai_sdk') return 'ai_sdk'\n if (raw === 'native') return 'native'\n throw new engine_config_error(\n `${provider} provider: transport must be 'ai_sdk' or 'native', got ${JSON.stringify(raw)}`,\n provider,\n )\n}\n\nexport type EffortTranslation = {\n // Outer keys are provider names, inner records hold per-provider settings,\n // matching the two-level shape merge_provider_options expects.\n provider_options: Record<string, Record<string, unknown>>\n effort_ignored: boolean\n}\n\nexport type ProviderCapability =\n | 'text'\n | 'tools'\n | 'schema'\n | 'streaming'\n | 'image_input'\n | 'reasoning'\n // Provider performs native constrained decoding (the AI SDK responseFormat /\n // Output.object path), as opposed to the prompt-for-JSON-then-extract path.\n // Distinct from 'schema': every provider can satisfy a schema via repair, but\n // only some constrain the decode to it.\n | 'structured_output'\n\nexport type RawProviderUsage = {\n input_tokens?: number\n output_tokens?: number\n reasoning_tokens?: number\n cached_input_tokens?: number\n cache_write_tokens?: number\n // Vercel AI SDK v6 also surfaces details via *Details containers; adapters\n // accept the flattened shape above for testability.\n input_token_details?: {\n cached_tokens?: number\n cache_creation_input_tokens?: number\n }\n output_token_details?: {\n reasoning_tokens?: number\n }\n [k: string]: unknown\n}\n\nexport type AiSdkProviderAdapter = {\n readonly kind: 'ai_sdk'\n readonly name: string\n readonly build_model: (model_id: string) => Promise<unknown>\n readonly translate_effort: (effort: EffortLevel) => EffortTranslation\n readonly normalize_usage: (raw: RawProviderUsage | undefined) => UsageTotals\n readonly supports: (capability: ProviderCapability) => boolean\n}\n\n/**\n * Depth-1 raw-HTTP transport: implements a single turn against a provider's own\n * API with zero `ai` / `@ai-sdk/*` in its module graph. generate.ts wraps\n * invoke_turn in retry + classification + abort, so a native adapter owns only\n * request/response mapping (and streaming via TurnRequest.dispatch_chunk); it\n * MUST NOT implement its own retry. classify_error optionally overrides the\n * shared classifier; dispose is optional (keep-alive agents, connection pools).\n */\nexport type NativeProviderAdapter = {\n readonly kind: 'native'\n readonly name: string\n readonly invoke_turn: (req: TurnRequest) => Promise<TurnResult>\n readonly supports: (capability: ProviderCapability) => boolean\n readonly dispose?: () => Promise<void>\n readonly classify_error?: (err: unknown) => unknown\n}\n\nexport type ExternalAgentAdapter = {\n readonly kind: 'external'\n readonly name: string\n readonly generate: <t>(\n opts: GenerateOptions<t>,\n resolved: ResolvedModel,\n ) => Promise<GenerateResult<t>>\n readonly dispose: () => Promise<void>\n readonly supports: (capability: ProviderCapability) => boolean\n}\n\nexport type ProviderAdapter =\n | AiSdkProviderAdapter\n | NativeProviderAdapter\n | ExternalAgentAdapter\n\nexport type ProviderFactory = (init: ProviderInit) => ProviderAdapter\n\nexport function default_normalize_usage(\n raw: RawProviderUsage | undefined,\n): UsageTotals {\n if (raw === undefined) return { input_tokens: 0, output_tokens: 0 }\n const input_tokens = typeof raw.input_tokens === 'number' ? raw.input_tokens : 0\n const output_tokens = typeof raw.output_tokens === 'number' ? raw.output_tokens : 0\n const totals: UsageTotals = { input_tokens, output_tokens }\n if (typeof raw.reasoning_tokens === 'number') totals.reasoning_tokens = raw.reasoning_tokens\n else if (typeof raw.output_token_details?.reasoning_tokens === 'number') {\n totals.reasoning_tokens = raw.output_token_details.reasoning_tokens\n }\n if (typeof raw.cached_input_tokens === 'number') totals.cached_input_tokens = raw.cached_input_tokens\n else if (typeof raw.input_token_details?.cached_tokens === 'number') {\n totals.cached_input_tokens = raw.input_token_details.cached_tokens\n }\n if (typeof raw.cache_write_tokens === 'number') totals.cache_write_tokens = raw.cache_write_tokens\n else if (typeof raw.input_token_details?.cache_creation_input_tokens === 'number') {\n totals.cache_write_tokens = raw.input_token_details.cache_creation_input_tokens\n }\n return totals\n}\n\nexport async function load_optional_peer<t>(\n specifier: string,\n): Promise<t> {\n let mod: unknown\n try {\n mod = await import(specifier)\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : JSON.stringify(err)\n const message =\n `missing peer dependency '${specifier}'. Install it with: pnpm add ${specifier}. Cause: ${detail}`\n throw new Error(message, { cause: err })\n }\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return mod as t\n}\n","/**\n * Incremental SSE decoder shared by the native (raw-HTTP) provider adapters.\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 buffer = ''\n let data_lines: string[] = []\n\n const take_line = (raw: string, out: string[]): void => {\n const line = raw.endsWith('\\r') ? raw.slice(0, -1) : raw\n if (line.length === 0) {\n if (data_lines.length > 0) {\n out.push(data_lines.join('\\n'))\n data_lines = []\n }\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\n return {\n push(text: string): string[] {\n buffer += text\n const out: string[] = []\n let newline = buffer.indexOf('\\n')\n while (newline >= 0) {\n take_line(buffer.slice(0, newline), out)\n buffer = buffer.slice(newline + 1)\n newline = buffer.indexOf('\\n')\n }\n return out\n },\n flush(): string[] {\n const out: string[] = []\n if (buffer.length > 0) take_line(buffer, out)\n buffer = ''\n if (data_lines.length > 0) {\n out.push(data_lines.join('\\n'))\n data_lines = []\n }\n return out\n },\n }\n}\n","/**\n * Native Anthropic provider adapter (depth-1 raw HTTP).\n *\n * Talks to the Messages API directly over global fetch with zero `ai` /\n * `@ai-sdk/*` in its module graph (D4). It owns request/response mapping\n * only: generate.ts wraps invoke_turn in retry + classification + abort\n * (D5), so failures are thrown in shapes the shared classify_provider_error\n * already 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 (C6). Schema requests ride the\n * engine's prompt + parse + repair loop (D6), so `TurnRequest.schema` is\n * intentionally unread. Streaming hand-rolls the SSE parse; the aggregator\n * rebuilds the 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 (C4) rather than by parallel code paths.\n */\n\nimport { z } from 'zod'\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_auth_error,\n provider_capability_error,\n provider_error,\n} from '../errors.js'\nimport { create_sse_decoder } from './sse_native.js'\nimport type { NativeProviderAdapter, ProviderCapability } from './types.js'\n\n/**\n * Effort → extended-thinking budget tokens per spec §6.3. Lives here (not in\n * anthropic.ts) because both transports map effort from this table and the\n * ai_sdk factory already imports this module for transport dispatch; the\n * reverse import would be a cycle.\n */\nexport const 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. When extended\n * thinking is enabled the budget counts against max_tokens, so the default\n * rides on top of the thinking budget 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\nexport type AnthropicMessage = {\n role: 'user' | 'assistant'\n content: AnthropicContentBlock[]\n}\n\nfunction to_user_blocks(content: string | UserContentPart[]): AnthropicContentBlock[] {\n if (typeof content === 'string') {\n return content.trim().length > 0 ? [{ type: 'text', text: content }] : []\n }\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 if (part.text.trim().length > 0) blocks.push({ type: 'text', text: part.text })\n }\n return blocks\n}\n\nfunction to_assistant_blocks(\n content: string | AssistantContentPart[],\n): AnthropicContentBlock[] {\n if (typeof content === 'string') {\n return content.trim().length > 0 ? [{ type: 'text', text: content }] : []\n }\n const blocks: AnthropicContentBlock[] = []\n for (const part of content) {\n if (part.type === 'text') {\n if (part.text.trim().length > 0) blocks.push({ type: 'text', text: part.text })\n } else {\n blocks.push({ type: 'tool_use', id: part.id, name: part.name, input: part.input })\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\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: z.toJSONSchema(tool.input_schema),\n }))\n}\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 const budget = ANTHROPIC_THINKING_BUDGETS[req.effort]\n const thinking_enabled = budget > 0\n\n const body: Record<string, unknown> = {\n model: req.model_id,\n messages,\n max_tokens:\n req.max_tokens ?? (thinking_enabled ? budget + DEFAULT_MAX_TOKENS : 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 (thinking_enabled) {\n body['thinking'] = { type: 'enabled', budget_tokens: budget }\n } else {\n // The API rejects temperature/top_p alongside extended thinking, so\n // sampling params apply only when thinking is off (parity with the\n // @ai-sdk/anthropic backend, which strips them the same way). The inner\n // guards already gate each key, so the branch is a plain else rather than\n // a redundant `else if` on the same two conditions.\n if (req.temperature !== undefined) body['temperature'] = req.temperature\n if (req.top_p !== undefined) body['top_p'] = req.top_p\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 effort-derived thinking block, the max_tokens default, sampling\n // params. The adapter does not reconcile interactions the API rejects\n // (e.g. a passthrough temperature alongside thinking); wire keys are the\n // 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\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 * 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\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 content: unknown = Reflect.get(payload, 'content')\n const text_parts: string[] = []\n const tool_calls: Array<{ id: string; name: string; input: unknown }> = []\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block === null || typeof block !== 'object') continue\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') text_parts.push(text)\n } else if (type === 'tool_use') {\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(\n 'anthropic native: malformed tool_use block in response content',\n )\n }\n tool_calls.push({ id, name, input: Reflect.get(block, 'input') })\n }\n // thinking / redacted_thinking blocks have no TurnResult field; skipped.\n }\n }\n return {\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}\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\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 * 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 (C4). A stream that ends without\n * message_stop is truncated output, so complete() fails loud instead of\n * returning a partial turn.\n */\nexport function create_stream_aggregator(\n step_index: number,\n dispatch: (chunk: StreamChunk) => Promise<void>,\n): {\n handle_event: (data: string) => Promise<void>\n complete: () => TurnResult\n} {\n type SyntheticToolUse = { type: 'tool_use'; id: string; name: string; input: 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: Array<{ type: 'text'; text: string } | SyntheticToolUse> = []\n const open_text = new Map<number, { type: 'text'; text: string }>()\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 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: 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 stream')\n }\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 }\n // thinking / redacted_thinking blocks carry no TurnResult state; their\n // deltas dispatch reasoning chunks directly.\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') {\n const thinking: unknown = Reflect.get(delta, 'thinking')\n if (typeof thinking === 'string') {\n await dispatch({ kind: 'reasoning', text: thinking, step_index })\n }\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 // signature_delta and 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 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_event(data: string): Promise<void> {\n let event: unknown\n try {\n event = JSON.parse(data)\n } catch {\n throw new provider_error('anthropic native: stream event is not valid JSON')\n }\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/** Anthropic error bodies are `{ type: 'error', error: { message } }`; fall back to the raw body. */\nfunction extract_error_message(body: string): string {\n if (body.length === 0) return '(empty body)'\n try {\n const parsed: unknown = JSON.parse(body)\n // Stryker disable next-line ConditionalExpression,LogicalOperator: the\n // enclosing try/catch already funnels every non-object parse to the raw\n // snippet, so this guard only narrows unknown -> object for Reflect.get;\n // forcing it true/false throws-and-catches to the same fallback (equivalent).\n if (parsed !== null && typeof parsed === 'object') {\n const error: unknown = Reflect.get(parsed, 'error')\n // Stryker disable next-line ConditionalExpression,LogicalOperator: same as\n // above -- a non-object error still reaches the raw-snippet fallback via the\n // catch or the message-not-a-string check, so both boundaries are equivalent.\n if (error !== null && typeof error === 'object') {\n const message: unknown = Reflect.get(error, 'message')\n if (typeof message === 'string' && message.length > 0) return message\n }\n }\n } catch {\n // Not JSON; fall through to the raw snippet.\n }\n return body.length > 300 ? `${body.slice(0, 300)}...` : body\n}\n\n/**\n * Map a non-2xx response to what the engine's retry stack expects: 401\n * becomes a typed provider_auth_error, 429/5xx keep `status` +\n * `responseHeaders` so classify_provider_error marks them retryable\n * (rate_limit honoring retry-after, provider_5xx), and any other 4xx is a\n * permanent provider_error that surfaces as-is.\n */\nasync function response_error(response: Response): Promise<Error> {\n let body = ''\n try {\n body = await response.text()\n } catch {\n // Body is best-effort detail; classification needs only the status.\n }\n const detail = extract_error_message(body)\n const status = response.status\n if (status === 401) {\n return new provider_auth_error(\n 'anthropic',\n `anthropic authentication failed (401): ${detail}`,\n )\n }\n if (status === 429 || status >= 500) {\n const retry_after = response.headers.get('retry-after')\n return Object.assign(\n new Error(`anthropic API error ${status}: ${detail}`),\n { status },\n retry_after !== null ? { responseHeaders: { 'retry-after': retry_after } } : {},\n )\n }\n return new provider_error(`anthropic API error ${status}: ${detail}`, { status, body })\n}\n\n/**\n * A user abort surfaces as the fetch/reader AbortError; retry_turn converts\n * it via its own signal check, so it is rethrown untouched. Everything else\n * is a transport failure wrapped in the `kind: 'network'` shape the shared\n * classify_provider_error marks retryable.\n */\nfunction rethrow_network_failure(err: unknown, abort: AbortSignal): never {\n if (abort.aborted) throw err\n const detail = err instanceof Error ? err.message : String(err)\n throw Object.assign(new Error(`anthropic native: network failure: ${detail}`), {\n kind: 'network',\n })\n}\n\n/**\n * Drain a streaming Messages response: decode bytes, reassemble SSE events,\n * and feed them to the aggregator, which dispatches chunks through\n * req.dispatch_chunk as they arrive. Transport failures mid-read wrap as\n * network errors; aggregator throws (malformed events, mid-stream error\n * events, a rejecting on_chunk) pass through untouched, with the reader\n * cancelled so the connection is released.\n */\nasync function consume_sse_response(response: Response, req: TurnRequest): Promise<TurnResult> {\n const body = response.body\n if (body === null) {\n throw new provider_error('anthropic native: streaming response has no body')\n }\n const dispatch = req.dispatch_chunk ?? (async (): Promise<void> => {})\n const aggregator = create_stream_aggregator(req.step_index, dispatch)\n const reader = body.getReader()\n const text_decoder = new TextDecoder()\n const sse = create_sse_decoder()\n\n const next_bytes = async (): Promise<Uint8Array | undefined> => {\n let step: Awaited<ReturnType<typeof reader.read>>\n try {\n step = await reader.read()\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort)\n }\n return step.done ? undefined : step.value\n }\n\n // Sequential awaits are the contract here: chunk order is an engine\n // invariant and each event mutates aggregator state, so no parallelism.\n try {\n while (true) {\n // oxlint-disable-next-line no-await-in-loop\n const bytes = await next_bytes()\n if (bytes === undefined) break\n for (const data of sse.push(text_decoder.decode(bytes, { stream: true }))) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_event(data)\n }\n }\n } finally {\n // Frees the connection when an error exits the loop early; a no-op on a\n // fully drained stream.\n void reader.cancel().catch(() => {})\n }\n const tail = [...sse.push(text_decoder.decode()), ...sse.flush()]\n for (const data of tail) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_event(data)\n }\n return aggregator.complete()\n}\n\n// 'structured_output' is intentionally absent, schema rides the prompt +\n// parse + repair loop (D6); 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\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 let response: Response\n try {\n response = await fetch(`${base_url}/messages`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-api-key': api_key,\n 'anthropic-version': ANTHROPIC_VERSION,\n },\n body: JSON.stringify(build_messages_body(req)),\n signal: req.abort,\n })\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort)\n }\n if (!response.ok) throw await response_error(response)\n if (req.stream) return consume_sse_response(response, req)\n const payload: unknown = await response.json()\n return parse_messages_response(payload)\n },\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * Anthropic provider adapter.\n *\n * Dispatches on `transport` (D3): 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. Effort levels map to extended-thinking\n * budget tokens per spec §6.3.\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 ProviderAdapter,\n type ProviderCapability,\n type RawProviderUsage,\n} from './types.js'\nimport {\n ANTHROPIC_THINKING_BUDGETS,\n create_anthropic_native_adapter,\n} 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\nexport function translate_anthropic_effort(effort: EffortLevel): EffortTranslation {\n const budget = ANTHROPIC_THINKING_BUDGETS[effort]\n if (effort === 'none' || budget === 0) {\n return { provider_options: {}, effort_ignored: false }\n }\n return {\n provider_options: {\n anthropic: {\n // @ai-sdk/anthropic reads `budgetTokens` (camelCase) and maps it to the\n // API's `budget_tokens`. Passing snake_case here is silently stripped by\n // the provider's zod schema, so the budget never reaches the wire.\n thinking: { type: 'enabled', budgetTokens: budget },\n },\n },\n effort_ignored: false,\n }\n}\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\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\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_anthropic_effort,\n normalize_usage: normalize_anthropic_usage,\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * OpenAI-compatible native core (depth-1 raw HTTP).\n *\n * One `chat/completions` implementation parameterized by a dialect config\n * (D1): base_url, auth strategy, extra headers, stream-usage behavior,\n * token-limit field name, and usage tolerance (D10). The `openai`,\n * `openrouter`, and `lmstudio` factories each build a dialect and share this\n * core; pointing base_url at any compat server (including Ollama's /v1)\n * rides the same path.\n *\n * Zero `ai` / `@ai-sdk/*` in the module graph (C3). 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 (C4) rather\n * than by parallel code paths.\n */\n\nimport { z } from 'zod'\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_auth_error,\n provider_capability_error,\n provider_error,\n} from '../errors.js'\nimport { create_sse_decoder } from './sse_native.js'\nimport type { NativeProviderAdapter, ProviderCapability } from './types.js'\n\n/**\n * Per-dialect wire knobs (Appendix A1). `name` is the provider name the\n * adapter reports and the `provider_options` key it reads, kept stable across\n * transports so pricing keys and usage fields carry over (C6).\n * `tolerant_usage` marks backends whose usage may be absent or approximate\n * (lmstudio, ollama-compat): the mapper returns zeroed totals instead of\n * throwing (D10).\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}\n\n/**\n * Effort map per Appendix A4: the wire enum is `low | medium | high` only, so\n * `xhigh` and `max` clamp to `high`, the same clamp as the ai_sdk transport's\n * `reasoningEffort`. `none` omits the field entirely. Non-reasoning models\n * ignore the field server-side; the adapter does not model-sniff.\n */\nexport const OPENAI_COMPATIBLE_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 | { role: 'assistant'; content: string | null; tool_calls?: ChatToolCall[] }\n | { role: 'tool'; tool_call_id: string; content: string }\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\nfunction to_assistant_message(content: string | AssistantContentPart[]): ChatMessage {\n if (typeof content === 'string') return { role: 'assistant', content }\n const text_parts: string[] = []\n const tool_calls: ChatToolCall[] = []\n for (const part of content) {\n if (part.type === 'text') {\n text_parts.push(part.text)\n } else {\n tool_calls.push({\n id: part.id,\n type: 'function',\n function: { name: part.name, arguments: JSON.stringify(part.input) },\n })\n }\n }\n const text = text_parts.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 return message\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 const out: ChatMessage[] = []\n for (const message of messages) {\n switch (message.role) {\n case 'system':\n out.push({ role: 'system', content: message.content })\n break\n case 'user':\n out.push({ role: 'user', content: to_user_content(message.content, provider) })\n break\n case 'assistant':\n out.push(to_assistant_message(message.content))\n break\n case 'tool':\n out.push({\n role: 'tool',\n tool_call_id: message.tool_call_id,\n content: message.content,\n })\n break\n }\n }\n return out\n}\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: z.toJSONSchema(tool.input_schema),\n },\n }))\n}\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 if (req.effort !== 'none') {\n body['reasoning_effort'] = OPENAI_COMPATIBLE_REASONING_EFFORT[req.effort]\n }\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 (D10).\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-derived reasoning_effort, the token\n // limit, sampling params (D9). Wire keys are the user asserting they know\n // the 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\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 // (Appendix A2).\n default:\n return 'stop'\n }\n}\n\n/**\n * Usage map per Appendix A3. prompt_tokens is already INCLUSIVE of cached\n * tokens on this API, unlike Anthropic's exclusive accounting, so a straight\n * copy is correct; compute_cost subtracts the cached portion back out. There\n * is no cache-write concept on this wire. A missing usage object throws under\n * a strict dialect (a hosted API omitting usage is a broken response) and\n * zeroes under a tolerant one (D10).\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\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 const prompt_details: unknown = Reflect.get(raw, 'prompt_tokens_details')\n if (prompt_details !== null && typeof prompt_details === 'object') {\n const cached = read_number(prompt_details, 'cached_tokens')\n if (cached !== undefined) totals.cached_input_tokens = cached\n }\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\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; some servers send '' for\n // no-argument calls, which means the same as '{}'.\n const raw_args: unknown = Reflect.get(fn, 'arguments')\n let input: unknown = {}\n if (typeof raw_args === 'string' && raw_args.length > 0) {\n try {\n input = JSON.parse(raw_args)\n } catch {\n throw new provider_error(\n `${provider} native: tool_calls arguments for ${name} is not valid JSON`,\n )\n }\n }\n return { id, name, input }\n}\n\n/**\n * The one response parser every path feeds (C4): non-stream parses the\n * payload directly, and the streaming aggregator (next step) rebuilds this\n * 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 return {\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(Reflect.get(payload, 'usage'), dialect),\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, and\n * `delta.tool_calls[]` entries accumulate `function.arguments` string deltas\n * keyed by their `index` field (A5). A tool call closes — parsed input\n * dispatched — when the choice's finish_reason frame arrives, or at `[DONE]`\n * for servers that never send one. Usage rides the final pre-DONE frame\n * (stream_options.include_usage); 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 (C4).\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 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 const on_choice = async (choice: object): Promise<void> => {\n const delta: unknown = Reflect.get(choice, 'delta')\n if (delta !== null && typeof delta === 'object') {\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 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 const message: Record<string, unknown> = {\n role: 'assistant',\n content: text.length > 0 || ordered.length === 0 ? text : null,\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/** OpenAI-style error bodies are `{ error: { message } }`; fall back to the raw body. */\nfunction extract_error_message(body: string): string {\n if (body.length === 0) return '(empty body)'\n try {\n const parsed: unknown = JSON.parse(body)\n if (parsed !== null && typeof parsed === 'object') {\n const error: unknown = Reflect.get(parsed, 'error')\n if (error !== null && typeof error === 'object') {\n const message: unknown = Reflect.get(error, 'message')\n if (typeof message === 'string' && message.length > 0) return message\n }\n }\n } catch {\n // Not JSON; fall through to the raw snippet.\n }\n return body.length > 300 ? `${body.slice(0, 300)}...` : body\n}\n\n/**\n * Map a non-2xx response to what the engine's retry stack expects: 401\n * becomes a typed provider_auth_error, 429/5xx keep `status` +\n * `responseHeaders` so classify_provider_error marks them retryable\n * (rate_limit honoring retry-after, provider_5xx), and any other 4xx is a\n * permanent provider_error that surfaces as-is.\n */\nasync function response_error(response: Response, provider: string): Promise<Error> {\n let body = ''\n try {\n body = await response.text()\n } catch {\n // Body is best-effort detail; classification needs only the status.\n }\n const detail = extract_error_message(body)\n const status = response.status\n if (status === 401) {\n return new provider_auth_error(\n provider,\n `${provider} authentication failed (401): ${detail}`,\n )\n }\n if (status === 429 || status >= 500) {\n const retry_after = response.headers.get('retry-after')\n return Object.assign(\n new Error(`${provider} API error ${status}: ${detail}`),\n { status },\n retry_after !== null ? { responseHeaders: { 'retry-after': retry_after } } : {},\n )\n }\n return new provider_error(`${provider} API error ${status}: ${detail}`, { status, body })\n}\n\n/**\n * A user abort surfaces as the fetch AbortError; retry_turn converts it via\n * its own signal check, so it is rethrown untouched. Everything else is a\n * transport failure wrapped in the `kind: 'network'` shape the shared\n * classify_provider_error marks retryable.\n */\nfunction rethrow_network_failure(err: unknown, abort: AbortSignal, provider: string): never {\n if (abort.aborted) throw err\n const detail = err instanceof Error ? err.message : String(err)\n throw Object.assign(new Error(`${provider} native: network failure: ${detail}`), {\n kind: 'network',\n })\n}\n\n/**\n * Drain a streaming chat/completions response: decode bytes, reassemble SSE\n * events, and feed each data payload to the aggregator, which dispatches\n * chunks through req.dispatch_chunk as they arrive. Transport failures\n * mid-read wrap as network errors; aggregator throws (malformed frames, a\n * rejecting on_chunk) pass through untouched, with the reader cancelled so\n * the connection is released.\n */\nasync function consume_sse_response(\n response: Response,\n req: TurnRequest,\n dialect: OpenAICompatibleDialect,\n): Promise<TurnResult> {\n const body = response.body\n if (body === null) {\n throw new provider_error(`${dialect.name} native: streaming response has no body`)\n }\n const dispatch = req.dispatch_chunk ?? (async (): Promise<void> => {})\n const aggregator = create_chat_stream_aggregator(dialect, req.step_index, dispatch)\n const reader = body.getReader()\n const text_decoder = new TextDecoder()\n const sse = create_sse_decoder()\n\n const next_bytes = async (): Promise<Uint8Array | undefined> => {\n let step: Awaited<ReturnType<typeof reader.read>>\n try {\n step = await reader.read()\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort, dialect.name)\n }\n return step.done ? undefined : step.value\n }\n\n // Sequential awaits are the contract here: chunk order is an engine\n // invariant and each frame mutates aggregator state, so no parallelism.\n try {\n while (true) {\n // oxlint-disable-next-line no-await-in-loop\n const bytes = await next_bytes()\n if (bytes === undefined) break\n for (const data of sse.push(text_decoder.decode(bytes, { stream: true }))) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_data(data)\n }\n }\n } finally {\n // Frees the connection when an error exits the loop early; a no-op on a\n // fully drained stream.\n void reader.cancel().catch(() => {})\n }\n const tail = [...sse.push(text_decoder.decode()), ...sse.flush()]\n for (const data of tail) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_data(data)\n }\n return aggregator.complete()\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\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 let response: Response\n try {\n response = await fetch(`${base_url}/chat/completions`, {\n method: 'POST',\n headers,\n body: JSON.stringify(build_chat_completions_body(req, dialect)),\n signal: req.abort,\n })\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort, dialect.name)\n }\n if (!response.ok) throw await response_error(response, dialect.name)\n if (req.stream) return consume_sse_response(response, req, dialect)\n const payload: unknown = await response.json()\n return parse_chat_completion(payload, dialect)\n },\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * OpenAI provider adapter.\n *\n * Dispatches on `transport` (D3): 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 (D1) — Bearer auth, an OpenAI-Organization\n * header, `max_completion_tokens`, and `reasoning_effort` per Appendix A4.\n * Effort maps to the o-series `reasoning_effort` string per spec §6.3.\n * Non-reasoning models silently ignore the effort field (providers without\n * reasoning support drop it; signaling is model-specific and handled by the\n * orchestrator via the `effort_ignored` flag).\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 {\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// OpenAI's reasoning effort enum is `low | medium | high` only.\n// `xhigh` and `max` clamp to `high` until OpenAI exposes more levels.\nconst OPENAI_REASONING_EFFORT: Record<Exclude<EffortLevel, 'none'>, string> = {\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'high',\n max: 'high',\n}\n\nexport function translate_openai_effort(effort: EffortLevel): EffortTranslation {\n if (effort === 'none') {\n return { provider_options: {}, effort_ignored: false }\n }\n return {\n provider_options: {\n openai: { reasoningEffort: OPENAI_REASONING_EFFORT[effort] },\n },\n effort_ignored: false,\n }\n}\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\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 (Appendix A1) and hand it to the shared\n * OpenAI-compatible core: Bearer auth, an optional OpenAI-Organization header,\n * the `max_completion_tokens` token-limit field, and strict usage (a hosted\n * API 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 = typeof init.api_key === 'string' ? init.api_key : ''\n const base_url =\n typeof init.base_url === 'string' && init.base_url.length > 0 ? init.base_url : 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 ...(organization !== undefined\n ? { extra_headers: { 'OpenAI-Organization': organization } }\n : {}),\n }\n return create_openai_compatible_adapter(dialect)\n}\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_openai_effort,\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 maps to the\n * `thinking_budget` provider option per spec §6.3.\n */\n\nimport type { EffortLevel, ProviderInit, UsageTotals } from '../types.js'\nimport {\n default_normalize_usage,\n load_optional_peer,\n type AiSdkProviderAdapter,\n type EffortTranslation,\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// @ai-sdk/google's `thinkingConfig.thinkingBudget` is a token count (number),\n// not an enum: passing a string fails the provider's zod validation. Gemini 2.5\n// Pro accepts up to 32768 thinking tokens; lighter models clamp the high end.\n// `none` omits thinkingConfig entirely (see translate_google_effort).\nconst GOOGLE_THINKING_BUDGET: Record<Exclude<EffortLevel, 'none'>, number> = {\n low: 1024,\n medium: 8192,\n high: 24576,\n xhigh: 32768,\n max: 32768,\n}\n\nexport function translate_google_effort(effort: EffortLevel): EffortTranslation {\n if (effort === 'none') {\n return { provider_options: {}, effort_ignored: false }\n }\n return {\n provider_options: {\n google: { thinkingConfig: { thinkingBudget: GOOGLE_THINKING_BUDGET[effort] } },\n },\n effort_ignored: false,\n }\n}\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\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_google_effort,\n normalize_usage: normalize_google_usage,\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * Ollama native adapter (depth-1 raw HTTP) on the daemon's own /api/chat.\n *\n * Deliberately NOT the OpenAI-compatible core (D2): the compat tail is already\n * served by pointing the `openai` provider's base_url at Ollama's /v1, while\n * this endpoint exposes what compat hides — `options` (num_predict,\n * temperature, top_p and every other runtime knob), `keep_alive`, and `think`,\n * all reachable raw through `provider_options.ollama` (D9). The wire is its\n * own dialect too: newline-delimited JSON frames rather than SSE, tool-call\n * `arguments` as objects rather than JSON strings, no tool-call ids (the\n * adapter synthesizes deterministic ones), and tool results keyed by\n * `tool_name` rather than a call id.\n *\n * Zero `ai` / `@ai-sdk/*` in the module graph (C3). 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 (D2 — thinking is opt-in via `provider_options.ollama.think`).\n * Usage is always tolerant (D10): a local daemon that omits eval counts\n * zeroes the totals, never throws. The NDJSON aggregator rebuilds the\n * non-stream payload shape and feeds it through the same parse_ollama_chat,\n * so streamed and non-streamed results are equal by construction (C4).\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_auth_error,\n provider_capability_error,\n provider_error,\n} from '../errors.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\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\nfunction to_assistant_message(content: string | AssistantContentPart[]): OllamaChatMessage {\n if (typeof content === 'string') return { role: 'assistant', content }\n const text_parts: string[] = []\n const tool_calls: OllamaToolCall[] = []\n for (const part of content) {\n if (part.type === 'text') {\n text_parts.push(part.text)\n } else {\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 tool_calls.push({ function: { name: part.name, arguments: part.input } })\n }\n }\n const message: OllamaChatMessage = { role: 'assistant', content: text_parts.join('') }\n if (tool_calls.length > 0) message.tool_calls = tool_calls\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 const out: OllamaChatMessage[] = []\n for (const message of messages) {\n switch (message.role) {\n case 'system':\n out.push({ role: 'system', content: message.content })\n break\n case 'user':\n out.push({ role: 'user', content: to_user_content(message.content) })\n break\n case 'assistant':\n out.push(to_assistant_message(message.content))\n break\n case 'tool':\n out.push({ role: 'tool', tool_name: message.name, content: message.content })\n break\n }\n }\n return out\n}\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 (D2): there is no reasoning_effort\n // on 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 (D9). 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 * Appendix A2, Ollama row: the presence of tool calls wins (the wire reports\n * done_reason 'stop' on a tool-call turn), then `length`; everything else —\n * 'stop', 'load', absent — means the model stopped on its 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 * Appendix A3, Ollama row: prompt_eval_count → input_tokens, eval_count →\n * output_tokens; no cache or reasoning fields exist on this wire. Counts are\n * always tolerant (D10): a local daemon that omits them (or a mid-stream\n * frame, which never carries them) zeroes the totals, never throws.\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\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 (C4), 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 let input: unknown = {}\n if (typeof raw_args === 'string' && raw_args.length > 0) {\n try {\n input = JSON.parse(raw_args)\n } catch {\n throw new provider_error(\n `ollama native: tool_calls arguments for ${name} is not valid JSON`,\n )\n }\n } else if (raw_args !== null && typeof raw_args === 'object') {\n input = raw_args\n }\n return { id, name, input }\n}\n\n/**\n * The one response parser every path feeds (C4): non-stream parses the\n * payload directly, and the NDJSON aggregator rebuilds this same payload\n * shape from 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 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 }\n}\n\n/**\n * Incremental NDJSON framing: push() takes decoded text at any chunk boundary\n * (including mid-line) and returns the complete lines it finished; flush()\n * drains a final line left open when the stream ends without a trailing\n * newline. Blank lines are dropped; JSON parsing is the aggregator's job.\n */\nfunction take_line(raw: string, out: string[]): void {\n const line = raw.endsWith('\\r') ? raw.slice(0, -1) : raw\n if (line.trim().length > 0) out.push(line)\n}\n\nexport function create_ndjson_decoder(): {\n push: (text: string) => string[]\n flush: () => string[]\n} {\n let buffer = ''\n\n return {\n push(text: string): string[] {\n buffer += text\n const out: string[] = []\n let newline = buffer.indexOf('\\n')\n while (newline >= 0) {\n take_line(buffer.slice(0, newline), out)\n buffer = buffer.slice(newline + 1)\n newline = buffer.indexOf('\\n')\n }\n return out\n },\n flush(): string[] {\n const out: string[] = []\n if (buffer.length > 0) take_line(buffer, out)\n buffer = ''\n return out\n },\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 — arguments are complete objects on this wire, so each call\n * dispatches tool_call_start then tool_call_end with no input deltas between.\n * The `done: true` frame carries done_reason and the eval counts and closes\n * the turn (step_finish); frames after it are ignored. A stream that ends\n * without one is truncated output, so complete() fails loud instead of\n * returning a partial turn. complete() feeds the synthetic payload through\n * parse_ollama_chat, which is what makes the streamed TurnResult equal the\n * non-streamed one by construction (C4).\n */\nexport function create_ollama_stream_aggregator(\n step_index: number,\n dispatch: (chunk: StreamChunk) => Promise<void>,\n): {\n handle_line: (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\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(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 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 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 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 },\n step_index,\n )\n },\n }\n}\n\n/** Ollama error bodies are `{ error: \"message\" }`; tolerate the nested OpenAI shape too. */\nfunction extract_error_message(body: string): string {\n if (body.length === 0) return '(empty body)'\n try {\n const parsed: unknown = JSON.parse(body)\n if (parsed !== null && typeof parsed === 'object') {\n const error: unknown = Reflect.get(parsed, 'error')\n if (typeof error === 'string' && error.length > 0) return error\n if (error !== null && typeof error === 'object') {\n const message: unknown = Reflect.get(error, 'message')\n if (typeof message === 'string' && message.length > 0) return message\n }\n }\n } catch {\n // Not JSON; fall through to the raw snippet.\n }\n return body.length > 300 ? `${body.slice(0, 300)}...` : body\n}\n\n/**\n * Map a non-2xx response to what the engine's retry stack expects: 401\n * becomes a typed provider_auth_error (rare locally, but base_url may point\n * at a fronted daemon), 429/5xx keep `status` + `responseHeaders` so\n * classify_provider_error marks them retryable, and any other 4xx (a missing\n * model, a malformed request) is a permanent provider_error.\n */\nasync function response_error(response: Response): Promise<Error> {\n let body = ''\n try {\n body = await response.text()\n } catch {\n // Body is best-effort detail; classification needs only the status.\n }\n const detail = extract_error_message(body)\n const status = response.status\n if (status === 401) {\n return new provider_auth_error('ollama', `ollama authentication failed (401): ${detail}`)\n }\n if (status === 429 || status >= 500) {\n const retry_after = response.headers.get('retry-after')\n return Object.assign(\n new Error(`ollama API error ${status}: ${detail}`),\n { status },\n retry_after !== null ? { responseHeaders: { 'retry-after': retry_after } } : {},\n )\n }\n return new provider_error(`ollama API error ${status}: ${detail}`, { status, body })\n}\n\n/**\n * A user abort surfaces as the fetch AbortError; retry_turn converts it via\n * its own signal check, so it is rethrown untouched. Everything else is a\n * transport failure wrapped in the `kind: 'network'` shape the shared\n * classify_provider_error marks retryable.\n */\nfunction rethrow_network_failure(err: unknown, abort: AbortSignal): never {\n if (abort.aborted) throw err\n const detail = err instanceof Error ? err.message : String(err)\n throw Object.assign(new Error(`ollama native: network failure: ${detail}`), {\n kind: 'network',\n })\n}\n\n/**\n * Drain a streaming /api/chat response: decode bytes, reassemble NDJSON\n * lines, and feed each to the aggregator, which dispatches chunks through\n * req.dispatch_chunk as they arrive. Transport failures mid-read wrap as\n * network errors; aggregator throws (malformed frames, a rejecting on_chunk)\n * pass through untouched, with the reader cancelled so the connection is\n * released.\n */\nasync function consume_ndjson_response(response: Response, req: TurnRequest): Promise<TurnResult> {\n const body = response.body\n if (body === null) {\n throw new provider_error('ollama native: streaming response has no body')\n }\n const dispatch = req.dispatch_chunk ?? (async (): Promise<void> => {})\n const aggregator = create_ollama_stream_aggregator(req.step_index, dispatch)\n const reader = body.getReader()\n const text_decoder = new TextDecoder()\n const ndjson = create_ndjson_decoder()\n\n const next_bytes = async (): Promise<Uint8Array | undefined> => {\n let step: Awaited<ReturnType<typeof reader.read>>\n try {\n step = await reader.read()\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort)\n }\n return step.done ? undefined : step.value\n }\n\n // Sequential awaits are the contract here: chunk order is an engine\n // invariant and each frame mutates aggregator state, so no parallelism.\n try {\n while (true) {\n // oxlint-disable-next-line no-await-in-loop\n const bytes = await next_bytes()\n if (bytes === undefined) break\n for (const line of ndjson.push(text_decoder.decode(bytes, { stream: true }))) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_line(line)\n }\n }\n } finally {\n // Frees the connection when an error exits the loop early; a no-op on a\n // fully drained stream.\n void reader.cancel().catch(() => {})\n }\n const tail = [...ndjson.push(text_decoder.decode()), ...ndjson.flush()]\n for (const line of tail) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_line(line)\n }\n return aggregator.complete()\n}\n\n// 'structured_output' is intentionally absent (schema rides the prompt +\n// parse + repair loop, parity with native Anthropic; the daemon's `format`\n// field stays reachable via provider_options.ollama.format); 'reasoning' is\n// absent because effort is ignored on this wire (D2); image parts are\n// unmapped on this transport.\nconst SUPPORTED: ReadonlySet<ProviderCapability> = new Set([\n 'text',\n 'tools',\n 'schema',\n 'streaming',\n])\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 let response: Response\n try {\n response = await fetch(`${base_url}/api/chat`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(build_ollama_chat_body(req)),\n signal: req.abort,\n })\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort)\n }\n if (!response.ok) throw await response_error(response)\n if (req.stream) return consume_ndjson_response(response, req)\n const payload: unknown = await response.json()\n return parse_ollama_chat(payload, req.step_index)\n },\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * Ollama local-provider adapter.\n *\n * Dispatches on `transport` (D3): 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 (D2, NDJSON wire) — the compat tail is served by\n * pointing the `openai` provider's base_url at /v1 instead. No API key;\n * base_url is the daemon root and is required on both transports. Ollama\n * does not support reasoning effort: the ai_sdk branch drops the field and\n * records `effort_ignored`; the native branch ignores it entirely (thinking\n * is opt-in via provider_options.ollama.think). Ollama does not emit\n * image_input capability by default in v1.\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 ProviderAdapter,\n type ProviderCapability,\n type RawProviderUsage,\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\nexport function translate_ollama_effort(effort: EffortLevel): EffortTranslation {\n const ignored = effort !== 'none'\n return { provider_options: {}, effort_ignored: ignored }\n}\n\nexport function normalize_ollama_usage(raw: RawProviderUsage | undefined): UsageTotals {\n // default_normalize_usage already maps undefined to a zero total; Ollama\n // additionally never reports cache or reasoning tokens, so strip them.\n const base = default_normalize_usage(raw)\n delete base.cached_input_tokens\n delete base.cache_write_tokens\n delete base.reasoning_tokens\n return base\n}\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\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\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` (D3): 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 (D1) — no auth, `max_tokens` as\n * the token-limit field, and tolerant usage (D10), since a local server that\n * omits or approximates token counts is a fact of local-first running, not a\n * broken response. LM Studio exposes an OpenAI-compatible local server; base_url\n * is required on both transports. No reasoning support.\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 {\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\nexport function translate_lmstudio_effort(effort: EffortLevel): EffortTranslation {\n const ignored = effort !== 'none'\n return { provider_options: {}, effort_ignored: ignored }\n}\n\nexport function normalize_lmstudio_usage(raw: RawProviderUsage | undefined): UsageTotals {\n // default_normalize_usage already maps undefined to a zero total; LM Studio\n // additionally never reports cache or reasoning tokens, so strip them.\n const base = default_normalize_usage(raw)\n delete base.cached_input_tokens\n delete base.cache_write_tokens\n delete base.reasoning_tokens\n return base\n}\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\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 (Appendix A1) and hand it to the shared\n * OpenAI-compatible core: no auth, the `max_tokens` token-limit field, and\n * tolerant usage (D10). The base_url guard mirrors the ai_sdk branch; the core\n * has no api_key to check 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 }\n return create_openai_compatible_adapter(dialect)\n}\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` (D3): 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 (D1) — Bearer auth\n * plus the optional `HTTP-Referer`/`X-Title` attribution headers, `max_tokens`\n * as the token-limit field, and strict usage (a hosted aggregator omitting\n * usage is a broken response, not a local-runtime quirk).\n *\n * Reasoning effort support varies per upstream model; OpenRouter itself\n * forwards the `reasoning` provider option. The ai_sdk backend translates\n * effort to the OpenRouter `reasoning.effort` shape; the native core maps it to\n * the flat `reasoning_effort` field per Appendix A4. Effort_ignored is false so\n * that the orchestrator does not emit effort_ignored indiscriminately; upstream\n * models that don't support reasoning will drop the field.\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 {\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// OpenRouter forwards the effort string verbatim to the upstream model.\n// `low`/`medium`/`high` work everywhere; `xhigh`/`max` flow through but\n// only the upstream model decides what they mean. Models that don't\n// recognize the value drop it silently.\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\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\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 (Appendix A1) and hand it to the shared\n * OpenAI-compatible core: Bearer auth, the optional `HTTP-Referer`/`X-Title`\n * attribution headers, the `max_tokens` token-limit field, and strict usage.\n * The empty-api_key guard 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 = typeof init.api_key === 'string' ? init.api_key : ''\n const base_url =\n typeof init.base_url === 'string' && init.base_url.length > 0 ? init.base_url : 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 ...(Object.keys(extra_headers).length > 0 ? { extra_headers } : {}),\n }\n return create_openai_compatible_adapter(dialect)\n}\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. Supply an `api_key` (Bedrock bearer\n * token, takes precedence over SigV4), SigV4 keys (`access_key_id` /\n * `secret_access_key`, optional `session_token`), or omit all three to use the\n * ambient AWS credential chain. Effort maps to the Anthropic extended-thinking\n * budget, emitted under the bedrock `reasoningConfig` provider option; models\n * that do not support reasoning drop the field upstream.\n */\n\nimport type { EffortLevel, ProviderInit, UsageTotals } from '../types.js'\nimport {\n default_normalize_usage,\n load_optional_peer,\n type AiSdkProviderAdapter,\n type EffortTranslation,\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 }) => (model_id: string) => unknown\n}\n\n// Bedrock hosts Anthropic Claude models; reasoning maps to the same\n// extended-thinking budget the anthropic adapter uses, emitted under the bedrock\n// provider option. Budgets stay within Bedrock's 1024..64000 window.\nconst BEDROCK_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\nexport function translate_bedrock_effort(effort: EffortLevel): EffortTranslation {\n // `none` is the only level with a 0 budget, so the budget alone decides\n // whether reasoning is requested.\n const budget = BEDROCK_THINKING_BUDGETS[effort]\n if (budget === 0) {\n return { provider_options: {}, effort_ignored: false }\n }\n return {\n provider_options: {\n bedrock: {\n reasoningConfig: { type: 'enabled', budgetTokens: budget },\n },\n },\n effort_ignored: false,\n }\n}\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\nexport const create_bedrock_adapter = (init: ProviderInit): AiSdkProviderAdapter => {\n const region = typeof init['region'] === 'string' ? init['region'] : ''\n if (region.length === 0) {\n throw new engine_config_error('bedrock provider requires a non-empty region', 'bedrock')\n }\n const api_key = typeof init.api_key === 'string' ? init.api_key : undefined\n const access_key_id = typeof init['access_key_id'] === 'string' ? init['access_key_id'] : undefined\n const secret_access_key =\n typeof init['secret_access_key'] === 'string' ? init['secret_access_key'] : undefined\n const session_token = typeof init['session_token'] === 'string' ? init['session_token'] : undefined\n const base_url = typeof init.base_url === 'string' ? init.base_url : undefined\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 config: {\n region: string\n accessKeyId?: string\n secretAccessKey?: string\n sessionToken?: string\n apiKey?: string\n baseURL?: string\n } = { region }\n if (api_key !== undefined) config.apiKey = api_key\n if (access_key_id !== undefined) config.accessKeyId = access_key_id\n if (secret_access_key !== undefined) config.secretAccessKey = secret_access_key\n if (session_token !== undefined) config.sessionToken = session_token\n if (base_url !== undefined) config.baseURL = base_url\n const provider = sdk.createAmazonBedrock(config)\n return provider(model_id)\n },\n translate_effort: translate_bedrock_effort,\n normalize_usage: normalize_bedrock_usage,\n supports: (capability) => SUPPORTED.has(capability),\n }\n}\n","/**\n * Frozen constants for the claude_cli provider (spec §5.1 defaults, §6.3\n * escalation window, §10.2 cost decomposition multipliers, §11 F19 auth\n * pattern list).\n *\n * Arrays are Object.freeze-d at module load so downstream code cannot mutate\n * them (constraints §7 invariant 25).\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 CACHE_READ_MULTIPLIER = 0.1\n\nexport const CACHE_WRITE_MULTIPLIER = 1.25\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\nexport const DEFAULT_SETTING_SOURCES: ReadonlyArray<'user' | 'project' | 'local'> =\n Object.freeze(['project', 'local'])\n","/**\n * Authentication enforcement for the claude_cli adapter (spec §4, §6.1).\n *\n * - build_env composes the subprocess env from config + caller overrides.\n * Regardless of auth_mode, it seeds the standard process-env keys\n * (PATH, HOME, SHELL, USER, LOGNAME, LANG, TMPDIR) so the spawned\n * subprocess can locate the sandbox wrapper (greywall/bwrap) and the\n * claude binary on PATH. Set `inherit_env: false` to opt out and start\n * from an empty env. Under oauth mode the *full* process.env is also\n * inherited (the CLI needs HOME/etc plus session-specific vars to reach\n * the logged-in OAuth session). Auth-mode scrub runs last on the merged\n * result so nothing — caller env, inherited env, or config — can\n * re-introduce ANTHROPIC_API_KEY under 'oauth'.\n * - validate_auth_config throws engine_config_error synchronously when\n * auth_mode === 'api_key' without a non-empty api_key.\n * - stderr_is_auth_failure matches captured stderr against the frozen\n * CLI_AUTH_ERROR_PATTERNS list, case-insensitively.\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\n * packages/fascicle/src/forward_standard_env.ts. Keep the two lists in\n * sync; engine cannot import from fascicle (the umbrella depends on\n * 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\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\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: Record<string, string> = {}\n const inherit_env = config.inherit_env !== false\n if (inherit_env) {\n if (auth_mode === 'oauth') {\n for (const [k, v] of Object.entries(process.env)) {\n if (typeof v === 'string') env[k] = v\n }\n } else {\n for (const key of STANDARD_ENV_KEYS) {\n const v = process.env[key]\n if (typeof v === 'string') env[key] = v\n }\n }\n }\n if (caller_env !== undefined) {\n for (const [k, v] of Object.entries(caller_env)) {\n if (typeof v === 'string') env[k] = v\n }\n }\n if (auth_mode === 'oauth') {\n delete env['ANTHROPIC_API_KEY']\n return env\n }\n if (auth_mode === 'api_key') {\n const api_key = typeof config.api_key === 'string' ? config.api_key : ''\n env['ANTHROPIC_API_KEY'] = api_key\n return env\n }\n if (typeof config.api_key === 'string' && config.api_key.length > 0) {\n env['ANTHROPIC_API_KEY'] = config.api_key\n }\n return env\n}\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 (spec §6.1).\n *\n * Every option value is a separate argv element; option names are never\n * string-interpolated with values (constraints §3 subprocess discipline #8).\n * The returned array is a readonly frozen copy; mutation would indicate a\n * 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\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\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\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 (spec §5.1, F30).\n *\n * Builds the `{ spawn_cmd, prefix_args }` pair for bwrap and greywall. When no\n * sandbox is configured, returns { spawn_cmd: binary, prefix_args: [] } — the\n * 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\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\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\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\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 (spec §6, constraints §5.10).\n *\n * The factory exposes:\n * - `live_children`: a closure-captured Set<ChildProcess> per-adapter-factory\n * call (constraints §7 invariant 5: no module-level mutable state).\n * - `spawn_cli(...)`: spawns the child with { detached: true, stdio: [...],\n * env, cwd, shell: false }; arms startup + stall timers; SIGTERM→SIGKILL\n * escalation on signal; removes from live set on close.\n * - `dispose_all()`: issues SIGTERM→SIGKILL for every live child and awaits\n * every close.\n *\n * A single process-wide `exit` handler synchronously SIGKILLs every live\n * child across every spawn registry (constraints §5.10 #5). The handler is\n * installed once per Node process and iterates a registry of adapter\n * 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}\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\nfunction install_exit_handler_once(): void {\n if (exit_handler_installed) return\n exit_handler_installed = true\n const handler = (): 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 process.on('exit', handler)\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\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 \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('binary_not_found', `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('binary_not_found', 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\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 (spec §7).\n *\n * The parser is a line-buffered state machine with minimal state:\n * - buffered partial line\n * - last-seen event type (assistant | user/tool_result | system | result)\n * used to increment step_index on the turn boundary (new assistant\n * following a user/tool_result)\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 (spec §7.1, §7.4). Neither ever throws.\n *\n * Event shapes are Zod-validated via `cli_event_schema` (a\n * `z.discriminatedUnion` over the recognized CLI event types: system,\n * assistant, user, result, rate_limit_event). Per-entry content arrays use\n * `.transform` to silently drop invalid entries rather than rejecting the\n * whole event — this preserves forward compatibility with new CLI content\n * types.\n *\n * `rate_limit_event` is informational: the CLI emits it between turns to\n * report current rate-limit budget. The parser records a structured\n * `cli_rate_limit_event` to trajectory and does not affect turn state.\n */\n\nimport { z } from 'zod'\nimport type { TrajectoryLogger } from '#core'\nimport type { StreamChunk, UsageTotals } from '../../types.js'\n\nconst cli_usage_schema = z.object({\n input_tokens: z.number().optional(),\n output_tokens: z.number().optional(),\n cache_read_input_tokens: z.number().optional(),\n cache_creation_input_tokens: z.number().optional(),\n})\n\nconst assistant_text_part_schema = z.object({\n type: z.literal('text'),\n text: z.string(),\n})\n\nconst assistant_tool_use_part_schema = z.object({\n type: z.literal('tool_use'),\n id: z.string(),\n name: z.string(),\n input: z.unknown(),\n})\n\nconst assistant_content_part_schema = z.discriminatedUnion('type', [\n assistant_text_part_schema,\n assistant_tool_use_part_schema,\n])\n\nconst user_tool_result_part_schema = z.object({\n type: z.literal('tool_result'),\n tool_use_id: z.string(),\n content: z.unknown().optional(),\n is_error: z.boolean().optional(),\n})\n\ntype AssistantContentPart = z.infer<typeof assistant_content_part_schema>\ntype UserToolResultPart = z.infer<typeof user_tool_result_part_schema>\n\nconst assistant_content_array_schema = z.array(z.unknown()).transform((arr) => {\n const out: AssistantContentPart[] = []\n for (const entry of arr) {\n const result = assistant_content_part_schema.safeParse(entry)\n if (result.success) out.push(result.data)\n }\n return out\n})\n\nconst user_content_array_schema = z.array(z.unknown()).transform((arr) => {\n const out: UserToolResultPart[] = []\n for (const entry of arr) {\n const result = user_tool_result_part_schema.safeParse(entry)\n if (result.success) out.push(result.data)\n }\n return out\n})\n\nconst system_event_schema = z.object({\n type: z.literal('system'),\n subtype: z.string().optional(),\n session_id: z.string().optional(),\n model: z.string().optional(),\n})\n\nconst assistant_event_schema = z.object({\n type: z.literal('assistant'),\n message: z.object({ content: assistant_content_array_schema }),\n})\n\nconst user_event_schema = z.object({\n type: z.literal('user'),\n message: z.object({ content: user_content_array_schema }),\n})\n\nconst result_event_schema = z.object({\n type: z.literal('result'),\n subtype: z.string().optional(),\n session_id: z.string().optional(),\n total_cost_usd: z.number().optional(),\n duration_ms: z.number().optional(),\n is_error: z.boolean().optional(),\n usage: cli_usage_schema.optional(),\n result: z.string().optional(),\n})\n\nconst rate_limit_info_schema = z.object({\n status: z.string().optional(),\n resetsAt: z.number().optional(),\n rateLimitType: z.string().optional(),\n overageStatus: z.string().optional(),\n overageResetsAt: z.number().optional(),\n isUsingOverage: z.boolean().optional(),\n})\n\nconst rate_limit_event_schema = z.object({\n type: z.literal('rate_limit_event'),\n rate_limit_info: rate_limit_info_schema.optional(),\n session_id: z.string().optional(),\n})\n\nconst cli_event_schema = z.discriminatedUnion('type', [\n system_event_schema,\n assistant_event_schema,\n user_event_schema,\n result_event_schema,\n rate_limit_event_schema,\n])\n\nexport type CliUsageRaw = z.infer<typeof cli_usage_schema>\nexport type CliAssistantContent = AssistantContentPart\nexport type CliUserContent = UserToolResultPart\nexport type CliEvent = z.infer<typeof cli_event_schema>\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 final_text: string\n readonly final_usage: UsageTotals\n readonly turns: ReadonlyArray<TurnCollected>\n readonly is_error: boolean\n readonly received_result: boolean\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 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}\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\nfunction map_usage(raw: CliUsageRaw | undefined): UsageTotals {\n if (raw === undefined) return { input_tokens: 0, output_tokens: 0 }\n const out: UsageTotals = {\n input_tokens: typeof raw.input_tokens === 'number' ? raw.input_tokens : 0,\n output_tokens: typeof raw.output_tokens === 'number' ? raw.output_tokens : 0,\n }\n if (typeof raw.cache_read_input_tokens === 'number') {\n out.cached_input_tokens = raw.cache_read_input_tokens\n }\n if (typeof raw.cache_creation_input_tokens === 'number') {\n out.cache_write_tokens = raw.cache_creation_input_tokens\n }\n return out\n}\n\nfunction record_parse_error(\n trajectory: TrajectoryLogger | undefined,\n line: string,\n): void {\n trajectory?.record({ kind: 'cli_parse_error', line })\n}\n\nfunction record_unknown_event(\n trajectory: TrajectoryLogger | undefined,\n raw: unknown,\n): void {\n trajectory?.record({ kind: 'cli_unknown_event', raw })\n}\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\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\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\nfunction as_event(raw: unknown): CliEvent | undefined {\n const result = cli_event_schema.safeParse(raw)\n return result.success ? result.data : undefined\n}\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\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\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\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\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 (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\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\nexport async 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\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\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\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 } = {\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 return base\n}\n","/**\n * Cost decomposition from CLI-reported total_cost_usd (spec §10).\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. The adapter synthesizes a\n * component split by computing an implied per-million rate from the total\n * and allocating that rate to each token component, weighted by\n * CACHE_READ_MULTIPLIER and CACHE_WRITE_MULTIPLIER.\n *\n * Per-turn allocation splits total_cost_usd across turns proportional to\n * each turn's output_tokens. Sum equality is preserved exactly by giving any\n * floating-point rounding remainder to the last turn.\n */\n\nimport type { CostBreakdown, UsageTotals } from '../../types.js'\nimport { CACHE_READ_MULTIPLIER, CACHE_WRITE_MULTIPLIER } from './constants.js'\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\nexport type TurnUsage = {\n readonly output_tokens: number\n readonly usage: UsageTotals\n}\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\n const total_output = turns.reduce((sum, t) => sum + Math.max(0, t.output_tokens), 0)\n\n const per_turn_totals: number[] = Array.from({ length: turns.length }, () => 0)\n if (total_output === 0) {\n const equal_share = total_cost_usd / turns.length\n for (let i = 0; i < turns.length; i += 1) per_turn_totals[i] = equal_share\n } else {\n for (let i = 0; i < turns.length; i += 1) {\n const t = turns[i]\n if (t === undefined) continue\n const share = Math.max(0, t.output_tokens) / total_output\n per_turn_totals[i] = total_cost_usd * share\n }\n }\n\n const running_sum = per_turn_totals.reduce((a, b) => a + b, 0)\n const remainder = total_cost_usd - running_sum\n if (turns.length > 0) {\n const last_index = turns.length - 1\n const current = per_turn_totals[last_index] ?? 0\n per_turn_totals[last_index] = current + remainder\n }\n\n const out: CostBreakdown[] = []\n for (let i = 0; i < turns.length; i += 1) {\n const t = turns[i]\n if (t === undefined) continue\n const total = per_turn_totals[i] ?? 0\n out.push(decompose_total_cost(total, t.usage))\n }\n return out\n}\n","/**\n * Build a GenerateResult from a parsed CLI stream (spec §5.4, §7.3, §10).\n *\n * Given a completed ParsedStream and the call's resolved alias, this module\n * synthesizes:\n * - per-turn StepRecord entries with output-weighted cost\n * - aggregate GenerateResult with CLI-reported total_cost_usd\n * - provider_reported.claude_cli with session_id + duration_ms\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 { z } from 'zod'\nimport type {\n ResolvedModel,\n CostBreakdown,\n FinishReason,\n GenerateResult,\n StepRecord,\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, type TurnUsage } from './cost.js'\nimport { claude_cli_error } from '../../errors.js'\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\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\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\nfunction tool_call_record(\n step_index: number,\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\nexport type BuildResultInput<T> = {\n readonly parsed: ParsedStream\n readonly resolved: ResolvedModel\n readonly schema?: z.ZodType<T>\n readonly parsed_content?: T\n}\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 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(turn.step_index, 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 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 }\n provider_reported['claude_cli'] = reported\n }\n\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const content_raw = input.parsed_content ?? (parsed.final_text 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 (phase 2) owns the repair loop itself\n * (counting toward max_steps, re-dispatching through the provider). This\n * module exposes the parse primitive and the canonical repair-prompt shape.\n */\n\nimport type { z } from 'zod'\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; error: unknown }\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 error from the\n * FIRST candidate that parsed as JSON — that error reflects the model's\n * primary output and is what a repair prompt should feed back. Later\n * candidates (e.g. the bracket-slice fallback) often produce noisy errors\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 */\nexport function parse_with_schema<t>(\n schema: z.ZodType<t>,\n text: string,\n): ParseOutcome<t> {\n const candidates = json_candidates(text)\n let json_parse_error: unknown = new Error('No JSON-parseable content found in model output')\n let first_schema_error: unknown\n for (const candidate of candidates) {\n let parsed: unknown\n try {\n parsed = JSON.parse(candidate)\n } catch (err: unknown) {\n json_parse_error = err\n continue\n }\n const result = schema.safeParse(parsed)\n if (result.success) return { ok: true, value: result.data }\n if (first_schema_error === undefined) first_schema_error = result.error\n }\n return { ok: false, error: first_schema_error ?? json_parse_error }\n}\n\nconst FENCE_BLOCK = /```(?:[\\w-]*)\\s*\\n?([\\s\\S]*?)\\n?```/g\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\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 * Content mirrors spec §6.5 exactly so the repair prompt is predictable and\n * user-inspectable in trajectory output.\n */\nexport function build_repair_message(zod_error: unknown): Message {\n return { role: 'user', content: build_repair_prompt_text(zod_error) }\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(zod_error: unknown): string {\n const serialized = format_zod_error(zod_error)\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 zod error and the raw model text.\n * Called by the orchestrator when all repair attempts are exhausted.\n */\nexport function throw_schema_validation(zod_error: unknown, raw_text: string): never {\n throw new schema_validation_error(\n `schema validation failed: ${format_zod_error(zod_error)}`,\n zod_error,\n raw_text,\n )\n}\n\nexport function format_zod_error(err: unknown): string {\n if (err === null || err === undefined) return 'unknown error'\n if (typeof err === 'string') return err\n if (err instanceof Error) return err.message\n if (typeof err === 'object' && 'message' in err) {\n const msg = (err as { message?: unknown }).message\n if (typeof msg === 'string') return msg\n }\n try {\n return JSON.stringify(err) ?? 'unknown error'\n } catch {\n return 'unknown error'\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 * documented engine events (spec §5.3, §6.2). When undefined, every helper\n * is a no-op. Higher-level orchestration (phase 2) drives span lifecycle;\n * these helpers capture the event shape and keep dispatch consistent.\n */\n\nimport type { TrajectoryLogger } from '#core'\nimport type {\n CostBreakdown,\n FinishReason,\n UsageTotals,\n} from './types.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\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\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 error?: string\n },\n): void {\n if (trajectory === undefined || span_id === undefined) return\n trajectory.end_span(span_id, { ...meta })\n}\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\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\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\nexport function record_response_received(\n trajectory: TrajectoryLogger | undefined,\n step_index: number,\n output_tokens: number | undefined,\n finish_reason: FinishReason,\n): void {\n if (trajectory === undefined) return\n const event: Record<string, unknown> = {\n kind: 'response_received',\n step_index,\n finish_reason,\n }\n if (output_tokens !== undefined) event['output_tokens'] = output_tokens\n trajectory.record({ kind: 'response_received', ...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\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 * 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 through\n * the core runner. When the logger is already runner-decorated, the existing\n * `ts` is preserved. Private to the engine to avoid widening the public surface.\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\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\nexport function record_cost(\n trajectory: TrajectoryLogger | undefined,\n step_index: number,\n cost: CostBreakdown,\n source: CostEventSource,\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 (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 spec requires emission at\n * most once per generate call per {provider, model_id}. Callers thread a\n * single instance through the per-call orchestration.\n */\nexport type PricingMissingDedup = {\n emit: (provider: string, model_id: string) => void\n}\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\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 zod_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 + zod validation. Persists the raw model output and a\n * formatted zod issues summary to the trajectory so the failure is debuggable\n * without needing stdout. Spec §6.5.\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 zod_issues: meta.zod_issues,\n raw_text: meta.raw_text,\n })\n}\n\nexport type SalvagedCallEventEntry = {\n tool_call_id: string\n name: string\n format: 'hermes' | 'json' | 'qwen_xml'\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\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`. Spec constraints §5.3 / taste\n * principle 12 require emission at most once per generate call per option\n * key. External adapters whose transports do not honor a caller-supplied\n * option (max_steps, tool_error_policy, on_tool_approval) route the emit\n * through this dedup.\n */\nexport type OptionIgnoredDedup = {\n emit: (option: string, provider: string) => void\n}\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 (spec §5.5, §6, §8, §13).\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 (constraints §7\n * invariant 5: no module-level mutable state).\n *\n * The returned adapter exposes exactly `{ kind: 'external', name, generate,\n * dispose, supports }` — no `build_model`, `translate_effort`, or\n * `normalize_usage` members.\n */\n\nimport { z } from 'zod'\nimport type {\n ResolvedModel,\n EffortLevel,\n GenerateOptions,\n GenerateResult,\n Message,\n ProviderInit,\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} from './stream_parse.js'\nimport { build_generate_result } from './stream_result.js'\nimport {\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 {\n build_repair_prompt_text,\n format_zod_error,\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// 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\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\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\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\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\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\nexport function compile_schema<T>(schema: z.ZodType<T>): string {\n // `claude --json-schema` rejects a top-level $schema/$id (the draft-2020-12 URI\n // z.toJSONSchema stamps); strip them — the field constraints drive constrained decode.\n const { $schema: _schema, $id: _id, ...json } = z.toJSONSchema(schema)\n return JSON.stringify(json)\n}\n\nexport function classify_close_error(\n code: number | null,\n signal: NodeJS.Signals | null,\n stderr: string,\n): Error {\n const snippet = stderr.slice(0, 512)\n if (stderr_is_auth_failure(stderr)) {\n return new provider_auth_error(\n PROVIDER_NAME,\n `claude CLI reported an auth failure: ${snippet}`,\n { refresh_command: 'claude login' },\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}: ${snippet}`\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 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\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: {},\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 spawn_args: Parameters<typeof spawn_runtime.spawn_cli>[0] = {\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 }\n if (args.cwd !== undefined) {\n (spawn_args as { cwd?: string }).cwd = args.cwd\n }\n if (args.abort !== undefined) {\n (spawn_args as { abort?: AbortSignal }).abort = args.abort\n }\n\n const session = await spawn_runtime.spawn_cli(spawn_args)\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)\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\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 ts on this subprocess provider's events too, matching the\n // ai_sdk path. The external branch in generate.ts returns before the\n // main path's with_timestamps wrap, so it has to happen here.\n const trajectory = with_timestamps(opts.trajectory)\n const call_opts = extract_call_opts(opts)\n const option_ignored = create_option_ignored_dedup(trajectory)\n\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 const user_count = count_user_messages(opts.prompt)\n if (user_count >= 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\n const tools_list: ReadonlyArray<Tool> = opts.tools ?? []\n const tool_bridge: ToolBridgeMode = call_opts.tool_bridge ?? 'allowlist_only'\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; tools with execute closures cannot run under claude_cli',\n )\n }\n }\n\n const tool_names: string[] = tools_list.map((t) => t.name)\n const merged_allowed_tools = merge_allowed_tools(call_opts.allowed_tools, tool_names)\n if (tools_list.length > 0 && tool_bridge === 'allowlist_only' && trajectory !== undefined) {\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 let compiled_schema: string | undefined\n if (opts.schema !== undefined) {\n compiled_schema = compile_schema(opts.schema)\n } else if (\n typeof call_opts.output_json_schema === 'string' &&\n call_opts.output_json_schema.length > 0\n ) {\n compiled_schema = call_opts.output_json_schema\n }\n\n const system_from_prompt = extract_system_text(opts.prompt)\n const merged_system = merge_system(\n opts.system ?? system_from_prompt,\n call_opts.append_system_prompt,\n )\n\n const stdin_text = extract_prompt_text(opts.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\n const sandbox_plan = build_sandbox_plan(resolved_binary, config.sandbox)\n\n const cwd = config.default_cwd\n const dispatch_chunk =\n opts.on_chunk !== undefined\n ? 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 : undefined\n\n const controller = new AbortController()\n in_flight.add(controller)\n\n const caller_abort = opts.abort\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\n const generate_span = start_generate_span(trajectory, {\n model: opts.model ?? resolved.model_id,\n provider: PROVIDER_NAME,\n model_id: resolved.model_id,\n has_tools: tools_list.length > 0,\n has_schema: opts.schema !== undefined,\n streaming: dispatch_chunk !== undefined,\n })\n let first_step_span: string | undefined = start_step_span(trajectory, 0)\n\n const base_args: RunArgs = {\n model_id: resolved.model_id,\n stdin_text,\n merged_system,\n merged_allowed_tools,\n call_opts,\n compiled_schema,\n env,\n spawn_cmd: sandbox_plan.spawn_cmd,\n prefix_args: sandbox_plan.prefix_args,\n 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 let parsed = first_outcome.parsed\n\n let parsed_content: T | undefined\n if (opts.schema !== undefined) {\n const max_repairs = opts.schema_repair_attempts ?? 1\n let repairs_done = 0\n for (;;) {\n const attempt = parse_with_schema(opts.schema, parsed.final_text)\n if (attempt.ok) {\n parsed_content = attempt.value\n break\n }\n record_schema_validation_failed(trajectory, {\n attempt: repairs_done === 0 ? 'initial' : 'repair',\n zod_issues: format_zod_error(attempt.error),\n raw_text: parsed.final_text,\n })\n if (repairs_done >= max_repairs) {\n throw new schema_validation_error(\n max_repairs === 0\n ? 'schema validation failed and repair is disabled (schema_repair_attempts: 0)'\n : `schema validation failed after ${String(max_repairs)} repair attempt${max_repairs === 1 ? '' : 's'}`,\n attempt.error,\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.error,\n parsed.final_text,\n )\n }\n const repair_call_opts: ClaudeCliCallOptions = {\n ...call_opts,\n session_id: repair_session_id,\n }\n const repair_outcome = await run_cli(spawn_runtime, {\n ...base_args,\n stdin_text: build_repair_prompt_text(attempt.error),\n call_opts: repair_call_opts,\n })\n parsed = repair_outcome.parsed\n repairs_done += 1\n }\n }\n\n\n const result_input: {\n parsed: typeof parsed\n resolved: ResolvedModel\n schema?: typeof opts.schema\n parsed_content?: T\n } = {\n parsed,\n resolved,\n }\n if (opts.schema !== undefined) result_input.schema = opts.schema\n if (parsed_content !== undefined) result_input.parsed_content = parsed_content\n\n const result = build_generate_result<T>(result_input)\n\n for (const step of result.steps) {\n if (step.cost !== undefined) {\n record_cost(trajectory, step.index, step.cost, 'provider_reported')\n }\n }\n\n if (result.steps.length > 0) {\n const head = result.steps[0]\n if (head !== undefined) {\n end_step_span(trajectory, first_step_span, {\n usage: head.usage,\n finish_reason: head.finish_reason,\n })\n }\n first_step_span = undefined\n for (let i = 1; i < result.steps.length; i += 1) {\n const s = result.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 } else {\n end_step_span(trajectory, first_step_span, {})\n first_step_span = undefined\n }\n\n end_generate_span(trajectory, generate_span, {\n usage: result.usage,\n finish_reason: result.finish_reason,\n model_resolved: result.model_resolved,\n })\n\n if (dispatch_chunk !== undefined) {\n await dispatch_chunk({\n kind: 'finish',\n finish_reason: result.finish_reason,\n usage: result.usage,\n })\n }\n\n return result\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err)\n if (first_step_span !== undefined) {\n end_step_span(trajectory, first_step_span, { error: message })\n first_step_span = undefined\n }\n end_generate_span(trajectory, generate_span, { error: message })\n throw err\n } finally {\n if (caller_abort !== undefined) {\n caller_abort.removeEventListener('abort', on_caller_abort)\n }\n in_flight.delete(controller)\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 provider_not_configured_error. Custom\n * providers enter via `EngineConfig.custom_providers` at construction,\n * resolved custom-first in create_engine; runtime (post-construction)\n * registration stays deferred.\n */\n\nimport { provider_not_configured_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\nexport function list_builtin_providers(): ReadonlyArray<string> {\n return [...BUILTIN_PROVIDERS.keys()]\n}\n\nexport function get_provider_factory(name: string): ProviderFactory {\n const factory = BUILTIN_PROVIDERS.get(name)\n if (factory === undefined) throw new provider_not_configured_error(name)\n return factory\n}\n","/**\n * Default-merging helpers for engine-level `EngineDefaults`.\n *\n * Scalar fields are merged inline at the consumer via `opts.x ?? defaults.x`.\n * `provider_options` needs a two-level merge: outer keys are provider names\n * (claude_cli, anthropic, ...) and inner records hold per-provider settings.\n * Per-call inner keys override defaults' inner keys; provider keys unique\n * to either side fall through. No recursion beyond that — deeper structures\n * replace wholesale to keep the rule predictable.\n */\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 out[provider] = { ...existing, ...inner }\n } else {\n out[provider] = inner\n }\n }\n return out\n}\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 from\n * spec §5.6. The dispatcher synchronously invokes on_chunk per provider event;\n * on throw or rejected promise it signals the caller to abort the in-flight\n * request (the actual request-abort is wired in phase 2's generate\n * orchestrator) and 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.\n *\n * Absent fields stay absent on the aggregated total if no step reported them\n * at all. Fields present on any step are summed with absent values contributing\n * 0 for arithmetic purposes (spec §5.3).\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\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 zod 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 type { z } from 'zod'\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 * 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 let in_string = false\n let escaped = false\n for (let i = start_index; i < text.length; i += 1) {\n const ch = text[i]\n if (in_string) {\n if (escaped) escaped = false\n else if (ch === '\\\\') escaped = true\n else if (ch === '\"') in_string = false\n continue\n }\n if (ch === '\"') {\n in_string = true\n } else if (ch === '{') {\n depth += 1\n } else if (ch === '}') {\n depth -= 1\n if (depth === 0) {\n const end = i + 1\n try {\n return { value: JSON.parse(text.slice(start_index, end)), end }\n } catch {\n return undefined\n }\n }\n }\n }\n return undefined\n}\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\nfunction overlaps_any(span: Span, masks: ReadonlyArray<Span>): boolean {\n return masks.some((m) => span.start < m.end && m.start < span.end)\n}\n\nfunction mask_containing(masks: ReadonlyArray<Span>, index: number): Span | undefined {\n return masks.find((m) => index >= m.start && index < m.end)\n}\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\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\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 masks.push({ start: open, end: block_end })\n const inner_start = open + TOOL_CALL_OPEN.length\n const inner = text.slice(inner_start, close)\n const trimmed = inner.trim()\n if (trimmed.startsWith('<function=')) {\n candidates.push(...scan_qwen_functions(inner_start, inner))\n } else if (trimmed.startsWith('{')) {\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) {\n candidates.push({\n name: shaped.name,\n args: shaped.args,\n format: 'hermes',\n span: { start: open, end: block_end },\n })\n }\n }\n pos = block_end\n }\n return { candidates, masks }\n}\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\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\nfunction validate_candidate(\n candidate: Candidate,\n tool_map: ReadonlyMap<string, Tool>,\n): SalvagedCall | undefined {\n const tool = tool_map.get(candidate.name)\n if (tool === undefined) return undefined\n const schema: z.ZodType = tool.input_schema\n const raw = schema.safeParse(candidate.args)\n if (raw.success) {\n return {\n name: candidate.name,\n input: raw.data,\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 = schema.safeParse(coerced)\n if (!retried.success) return undefined\n return {\n name: candidate.name,\n input: retried.data,\n format: candidate.format,\n span: candidate.span,\n }\n}\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\nexport function salvage_tool_calls(\n text: string,\n tool_map: ReadonlyMap<string, Tool>,\n): 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 const calls: SalvagedCall[] = []\n for (const c of candidates) {\n const validated = validate_candidate(c, tool_map)\n if (validated !== undefined) calls.push(validated)\n }\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 (spec §6.4).\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 type { z } from 'zod'\nimport type { TrajectoryLogger } from '#core'\nimport type {\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 UsageTotals,\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_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, 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\nexport type RawToolCall = {\n readonly id: string\n readonly name: string\n readonly input: unknown\n}\n\n/**\n * Retained alias of the neutral TurnResult (types.ts). Callers built against\n * the loop-local name keep working while TurnResult is the shared spelling.\n */\nexport type InvokeOnceResult = TurnResult\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 (D6). Called before each turn with the would-be\n * request messages; a returned `{ messages }` replaces the request for THAT\n * turn 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 (precedent: pricing_dedup). undefined = salvage\n * disabled.\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\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\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\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\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}' but no on_tool_approval handler was provided`,\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, 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\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\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\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\nfunction build_assistant_message(text: string, tool_calls: ReadonlyArray<RawToolCall>): Message {\n if (tool_calls.length === 0) return { role: 'assistant', content: text }\n const parts: Array<\n | { type: 'text'; text: string }\n | { type: 'tool_call'; id: string; name: string; input: unknown }\n > = []\n if (text.length > 0) parts.push({ type: 'text', text })\n for (const tc of tool_calls) {\n parts.push({ type: 'tool_call', id: tc.id, name: tc.name, input: tc.input })\n }\n return { role: 'assistant', content: parts }\n}\n\nfunction compute_and_record_cost(\n config: ToolLoopConfig,\n step_index: number,\n usage: UsageTotals,\n): CostBreakdown | undefined {\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(usage, pricing, config.provider)\n if (breakdown !== undefined) {\n record_cost(config.trajectory, step_index, breakdown, 'engine_derived')\n }\n return breakdown\n}\n\nfunction validate_tool_input(\n tool: Tool,\n input: unknown,\n): { ok: true; value: unknown } | { ok: false; message: string } {\n // The schema field is typed as z.ZodType<i>; we call safeParse in the\n // runtime position where the input has not been narrowed.\n const schema: z.ZodType = tool.input_schema\n const parsed = schema.safeParse(input)\n if (parsed.success) return { ok: true, value: parsed.data }\n const error_message = serialize_error(parsed.error)\n return { ok: false, message: `invalid tool input: ${error_message}` }\n}\n\n/**\n * Apply the prepare_step hook (D6) for one turn. Returns the messages to send\n * to 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) makes\n * 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\nexport async function run_tool_loop(config: ToolLoopConfig): Promise<ToolLoopResult> {\n const steps: StepRecord[] = []\n const tool_calls_all: ToolCallRecord[] = []\n let text = ''\n let finish_reason: FinishReason = 'stop'\n let step_index = config.step_index_start\n let max_steps_reached = false\n\n const tool_map = new Map<string, Tool>()\n for (const t of config.tools) tool_map.set(t.name, t)\n\n while (true) {\n throw_if_aborted(config.abort, step_index)\n\n if (step_index >= config.max_steps) {\n max_steps_reached = true\n finish_reason = 'max_steps'\n break\n }\n\n const step_span = start_step_span(config.trajectory, step_index)\n\n let turn: TurnResult\n try {\n const request_messages = await apply_prepare_step(config, step_index)\n config.trajectory?.record({ kind: 'request_sent', step_index })\n 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 })\n config.trajectory?.record({\n kind: 'response_received',\n step_index,\n output_tokens: turn.usage.output_tokens,\n finish_reason: turn.finish_reason,\n })\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 // A turn that \"stopped\" with plain text may hold a call the runtime\n // failed to parse into tool_calls; salvage before deciding the step ends\n // the loop. History gets the stripped text + structured parts (raw markup\n // in history would teach the model the text format works, and a tool\n // result without a matching call part is rejected by OpenAI-compatible\n // APIs); StepRecord.text keeps the raw text for debugging.\n let effective_calls: ReadonlyArray<RawToolCall> = turn.tool_calls\n let history_text = turn.text\n let salvage: SalvageOutcome | undefined\n const salvaged_formats = new Map<string, SalvageFormat>()\n if (\n turn.tool_calls.length === 0 &&\n (turn.finish_reason === 'stop' || turn.finish_reason === 'length') &&\n config.tools.length > 0 &&\n config.salvage_budget !== undefined &&\n config.salvage_budget.remaining > 0\n ) {\n salvage = salvage_tool_calls(turn.text, tool_map)\n if (salvage !== undefined) {\n config.salvage_budget.remaining -= 1\n history_text = salvage.stripped_text\n effective_calls = salvage.calls.map((c, n) => {\n const id = `salvaged_${step_index}_${n}`\n salvaged_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: effective_calls.map((c) => ({\n tool_call_id: c.id,\n name: c.name,\n // Stryker disable next-line StringLiteral: salvaged_formats has an entry for every id (set just above), so the ?? 'json' fallback is unreachable.\n format: salvaged_formats.get(c.id) ?? 'json',\n })),\n raw_text: turn.text,\n })\n if (config.dispatch_chunk !== undefined) {\n // Mirror the native stream, which emits start/end for every call\n // the model attempted, including ones the clamp below drops.\n for (const c of effective_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\n // Clamp applies to native and salvaged calls alike. Dropped calls never\n // reach history; the model re-issues them on a later turn if it still\n // wants them.\n let dropped_calls: ReadonlyArray<RawToolCall> = []\n const per_step_cap = config.max_tool_calls_per_step\n if (per_step_cap !== undefined && effective_calls.length > per_step_cap) {\n dropped_calls = effective_calls.slice(per_step_cap)\n effective_calls = effective_calls.slice(0, per_step_cap)\n record_tool_calls_dropped(config.trajectory, {\n step_index,\n max_tool_calls_per_step: per_step_cap,\n kept: effective_calls.length,\n dropped: dropped_calls.map((d) => ({ tool_call_id: d.id, name: d.name })),\n })\n }\n\n const step_tool_records: ToolCallRecord[] = []\n const assistant_message = build_assistant_message(history_text, effective_calls)\n config.messages.push(assistant_message)\n\n if (effective_calls.length === 0) {\n text = turn.text\n finish_reason = turn.finish_reason\n const record_step: StepRecord = {\n index: step_index,\n text: turn.text,\n tool_calls: [],\n usage: turn.usage,\n finish_reason: turn.finish_reason,\n }\n const breakdown = compute_and_record_cost(config, step_index, turn.usage)\n if (breakdown !== undefined) record_step.cost = breakdown\n steps.push(record_step)\n if (config.on_finish_step !== undefined) config.on_finish_step(record_step)\n end_step_span(config.trajectory, step_span, {\n usage: turn.usage,\n finish_reason: turn.finish_reason,\n })\n break\n }\n\n // This turn has tool calls. Execute them sequentially.\n const would_exceed_after = step_index + 1 >= config.max_steps\n const tool_results_to_feed: Message[] = []\n // Set true when a call to a Tool flagged ends_turn executes successfully;\n // ends the loop after this step (see the terminal-finish break below).\n let terminal_fired = false\n\n for (const raw_call of effective_calls) {\n throw_if_aborted_in_flight(config.abort, step_index, { id: raw_call.id, name: raw_call.name })\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 (would_exceed_after && tool_map.get(raw_call.name)?.ends_turn !== true) {\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: raw_call.name,\n input: raw_call.input,\n error: { message: 'max_steps_exceeded_before_execution' },\n duration_ms: 0,\n started_at: Date.now(),\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n raw_call.id,\n undefined,\n { message: 'max_steps_exceeded_before_execution' },\n )\n continue\n }\n\n const tool = tool_map.get(raw_call.name)\n if (tool === undefined) {\n const err_message = `unknown tool '${raw_call.name}'`\n if (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(config.trajectory, step_span, { error: err_message })\n throw thrown\n }\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: raw_call.name,\n input: raw_call.input,\n error: { message: err_message },\n duration_ms: 0,\n started_at: Date.now(),\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n tool_results_to_feed.push(\n build_tool_result_message(raw_call.id, raw_call.name, {\n error: err_message,\n }),\n )\n record_tool_call(config.trajectory, {\n step_index,\n name: raw_call.name,\n tool_call_id: raw_call.id,\n input: raw_call.input,\n duration_ms: 0,\n error: { message: err_message },\n })\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n raw_call.id,\n undefined,\n { message: err_message },\n )\n continue\n }\n\n const validation = validate_tool_input(tool, raw_call.input)\n if (!validation.ok) {\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: raw_call.name,\n input: raw_call.input,\n error: { message: validation.message },\n duration_ms: 0,\n started_at: Date.now(),\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n tool_results_to_feed.push(\n build_tool_result_message(raw_call.id, raw_call.name, {\n error: validation.message,\n }),\n )\n record_tool_call(config.trajectory, {\n step_index,\n name: raw_call.name,\n tool_call_id: raw_call.id,\n input: raw_call.input,\n duration_ms: 0,\n error: { message: validation.message },\n })\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n raw_call.id,\n undefined,\n { message: validation.message },\n )\n continue\n }\n\n let approved: boolean\n try {\n approved = await request_approval(\n tool,\n validation.value,\n step_index,\n raw_call.id,\n config.abort,\n config.on_tool_approval,\n config.trajectory,\n )\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 if (!approved) {\n const denied_message = 'tool_approval_denied'\n if (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, tool_call_id: raw_call.id },\n )\n end_step_span(config.trajectory, step_span, { error: denied_message })\n throw thrown\n }\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: tool.name,\n input: validation.value,\n error: { message: denied_message },\n duration_ms: 0,\n started_at: Date.now(),\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n tool_results_to_feed.push(\n build_tool_result_message(raw_call.id, tool.name, { error: denied_message }),\n )\n record_tool_call(config.trajectory, {\n step_index,\n name: tool.name,\n tool_call_id: raw_call.id,\n input: validation.value,\n duration_ms: 0,\n error: { message: denied_message },\n })\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n raw_call.id,\n undefined,\n { message: denied_message },\n )\n continue\n }\n\n throw_if_aborted_in_flight(config.abort, step_index, {\n id: raw_call.id,\n name: tool.name,\n })\n\n const started_at = Date.now()\n const tool_ctx: ToolExecContext = {\n abort: config.abort,\n tool_call_id: raw_call.id,\n step_index,\n ...(config.trajectory !== undefined ? { trajectory: 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(validation.value, 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 if (thrown !== undefined) {\n if (config.abort.aborted) {\n const abort_err = new aborted_error('aborted', {\n reason: config.abort.reason,\n step_index,\n tool_call_in_flight: { id: raw_call.id, name: tool.name },\n })\n end_step_span(config.trajectory, step_span, { error: 'aborted' })\n throw abort_err\n }\n if (config.tool_error_policy === 'throw') {\n const wrapped = new tool_error(`tool '${tool.name}' failed: ${err_message ?? 'unknown'}`, {\n tool_name: tool.name,\n tool_call_id: raw_call.id,\n cause: thrown,\n })\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 end_step_span(config.trajectory, step_span, { error: err_message ?? 'tool error' })\n throw wrapped\n }\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: tool.name,\n input: validation.value,\n // Stryker disable next-line StringLiteral: err_message is always a string here (see catch above), so this ?? 'unknown' fallback is unreachable.\n error: { message: err_message ?? 'unknown' },\n duration_ms,\n started_at,\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n tool_results_to_feed.push(\n // Stryker disable next-line StringLiteral: unreachable ?? 'unknown' fallback (err_message is always a string here).\n build_tool_result_message(raw_call.id, tool.name, { error: err_message ?? 'unknown' }),\n )\n record_tool_call(config.trajectory, {\n step_index,\n name: tool.name,\n tool_call_id: raw_call.id,\n input: validation.value,\n duration_ms,\n // Stryker disable next-line StringLiteral: unreachable ?? 'unknown' fallback (err_message is always a string here).\n error: { message: err_message ?? 'unknown' },\n })\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n raw_call.id,\n undefined,\n // Stryker disable next-line StringLiteral: unreachable ?? 'unknown' fallback (err_message is always a string here).\n { message: err_message ?? 'unknown' },\n )\n continue\n }\n\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: tool.name,\n input: validation.value,\n output,\n duration_ms,\n started_at,\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n if (tool.ends_turn === true) terminal_fired = true\n tool_results_to_feed.push(\n build_tool_result_message(raw_call.id, tool.name, output ?? ''),\n )\n record_tool_call(config.trajectory, {\n step_index,\n name: tool.name,\n tool_call_id: raw_call.id,\n input: validation.value,\n duration_ms,\n })\n await dispatch_tool_result_chunk(config.dispatch_chunk, step_index, raw_call.id, output)\n }\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_calls) {\n const record: ToolCallRecord = {\n id: d.id,\n name: d.name,\n input: d.input,\n error: { message: 'dropped_max_tool_calls_per_step' },\n duration_ms: 0,\n started_at: Date.now(),\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n d.id,\n undefined,\n { message: 'dropped_max_tool_calls_per_step' },\n )\n }\n\n for (const r of step_tool_records) {\n const format = salvaged_formats.get(r.id)\n if (format !== undefined) {\n r.salvaged = true\n r.salvaged_format = format\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 for (const r of step_tool_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 for (const m of tool_results_to_feed) config.messages.push(m)\n\n // A salvaged step reports 'tool_calls': downstream consumers see the same\n // shape a native tool turn produces; the salvaged flags carry provenance.\n // A terminal step reports 'tool_calls' (it genuinely made calls); the loop\n // finish_reason 'stop' below is the separate signal that generation ended.\n const turn_finish_reason: FinishReason = terminal_fired\n ? 'tool_calls'\n : would_exceed_after\n ? 'max_steps'\n : salvage !== undefined\n ? 'tool_calls'\n : turn.finish_reason\n const step_record: StepRecord = {\n index: step_index,\n text: turn.text,\n tool_calls: step_tool_records,\n usage: turn.usage,\n finish_reason: turn_finish_reason,\n }\n const breakdown = compute_and_record_cost(config, step_index, turn.usage)\n if (breakdown !== undefined) step_record.cost = breakdown\n steps.push(step_record)\n if (config.on_finish_step !== undefined) config.on_finish_step(step_record)\n end_step_span(config.trajectory, step_span, {\n usage: turn.usage,\n finish_reason: turn_finish_reason,\n })\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 (terminal_fired) {\n finish_reason = 'stop'\n text = turn.text\n break\n }\n\n if (would_exceed_after) {\n max_steps_reached = true\n finish_reason = 'max_steps'\n text = turn.text\n break\n }\n\n step_index += 1\n }\n\n return { text, steps, tool_calls: tool_calls_all, finish_reason, max_steps_reached }\n}\n","/**\n * AI SDK telemetry wiring (D7, Layer 2), confined to the ai_sdk transport.\n *\n * `@ai-sdk/otel` is adopted strictly below the turn seam (the ADR's\n * boundary-litmus: it instruments one turn inside this module, never the loop).\n * The peer is loaded lazily and only when telemetry is explicitly enabled, so\n * the disabled default (every call that does not opt in) pulls in nothing.\n *\n * This is the ONLY place `@ai-sdk/otel` is referenced. generate.ts and\n * create_engine.ts thread a plain `AiSdkTelemetrySettings` value through the\n * seam and stay SDK-agnostic; loop-level, transport-neutral tracing is the\n * separate `fascicle/otel` bridge (Layer 1).\n */\n\nimport type { AiSdkTelemetrySettings } from '../../types.js'\nimport { load_optional_peer } from '../types.js'\n\ntype OpenTelemetryCtor = new (options?: { tracer?: unknown }) => unknown\n\ntype AiSdkOtelModule = {\n readonly OpenTelemetry: OpenTelemetryCtor\n}\n\n/**\n * The subset of the AI SDK's telemetry option shape this module produces, using\n * the SDK's own (camelCase) keys. Cast onto `experimental_telemetry` at the\n * call site.\n */\nexport type AiSdkTelemetryPassthrough = {\n isEnabled: true\n integrations: unknown[]\n functionId?: string\n recordInputs?: boolean\n recordOutputs?: boolean\n metadata?: Readonly<Record<string, string | number | boolean>>\n}\n\nexport async function build_ai_sdk_telemetry(\n settings: AiSdkTelemetrySettings | undefined,\n): Promise<AiSdkTelemetryPassthrough | undefined> {\n if (!settings?.enabled) return undefined\n const mod = await load_optional_peer<AiSdkOtelModule>('@ai-sdk/otel')\n const integration = new mod.OpenTelemetry(\n settings.tracer !== undefined ? { tracer: settings.tracer } : {},\n )\n const out: AiSdkTelemetryPassthrough = { isEnabled: true, integrations: [integration] }\n if (settings.function_id !== undefined) out.functionId = settings.function_id\n if (settings.record_inputs !== undefined) out.recordInputs = settings.record_inputs\n if (settings.record_outputs !== undefined) out.recordOutputs = settings.record_outputs\n if (settings.metadata !== undefined) out.metadata = settings.metadata\n return out\n}\n","/**\n * The ai_sdk transport: the engine's only Vercel AI SDK call site.\n *\n * Invariant 13 (constraints §7, inverted): only this module imports from `ai`\n * or invokes generateText / streamText. generate.ts drives this transport\n * through create_ai_sdk_turn and stays SDK-agnostic; run_tool_loop sees the\n * same neutral TurnResult a native adapter produces. Rule-enforced by\n * rules/no-ai-import-outside-ai-sdk-provider.yml.\n *\n * Retry stays out of this module on purpose (D5): generate.ts wraps the turn\n * returned here in the engine-owned retry_turn, exactly as it wraps a native\n * adapter's invoke_turn. This module owns request/response mapping only.\n */\n\nimport {\n generateText,\n NoObjectGeneratedError,\n Output,\n isStepCount,\n streamText,\n tool as ai_tool,\n type LanguageModel,\n type ModelMessage,\n type TextStreamPart,\n type ToolSet,\n} from 'ai'\nimport type { z } from 'zod'\nimport type {\n AiSdkTelemetrySettings,\n FinishReason,\n Message,\n StreamChunk,\n Tool,\n TurnResult,\n UsageTotals,\n} from '../../types.js'\nimport { aborted_error } from '../../errors.js'\nimport type { ChunkDispatcher } from '../../streaming.js'\nimport type { RawToolCall } from '../../tool_loop.js'\nimport {\n default_normalize_usage,\n type AiSdkProviderAdapter,\n type RawProviderUsage,\n} from '../types.js'\nimport { build_ai_sdk_telemetry, type AiSdkTelemetryPassthrough } from './telemetry.js'\n\nexport function map_finish_reason(raw: string | undefined): FinishReason {\n switch (raw) {\n case 'stop':\n return 'stop'\n case 'length':\n return 'length'\n case 'content-filter':\n case 'content_filter':\n return 'content_filter'\n case 'tool-calls':\n case 'tool_calls':\n return 'tool_calls'\n default:\n return 'stop'\n }\n}\n\nexport function to_raw_provider_usage(usage: unknown): RawProviderUsage {\n if (usage === null || typeof usage !== 'object') return {}\n const raw: RawProviderUsage = {}\n const input_tokens = Reflect.get(usage, 'inputTokens')\n if (typeof input_tokens === 'number') raw.input_tokens = input_tokens\n const output_tokens = Reflect.get(usage, 'outputTokens')\n if (typeof output_tokens === 'number') raw.output_tokens = output_tokens\n const input_details = Reflect.get(usage, 'inputTokenDetails')\n if (input_details !== null && typeof input_details === 'object') {\n const cache_read = Reflect.get(input_details, 'cacheReadTokens')\n const cache_write = Reflect.get(input_details, 'cacheWriteTokens')\n raw.input_token_details = {}\n if (typeof cache_read === 'number') raw.input_token_details.cached_tokens = cache_read\n if (typeof cache_write === 'number') raw.input_token_details.cache_creation_input_tokens = cache_write\n }\n const output_details = Reflect.get(usage, 'outputTokenDetails')\n if (output_details !== null && typeof output_details === 'object') {\n const reasoning = Reflect.get(output_details, 'reasoningTokens')\n raw.output_token_details = {}\n if (typeof reasoning === 'number') raw.output_token_details.reasoning_tokens = reasoning\n }\n // Passthrough for mocks that provide flattened fields directly.\n const cached_flat = Reflect.get(usage, 'cached_input_tokens')\n if (typeof cached_flat === 'number') raw.cached_input_tokens = cached_flat\n const cache_write_flat = Reflect.get(usage, 'cache_write_tokens')\n if (typeof cache_write_flat === 'number') raw.cache_write_tokens = cache_write_flat\n const reasoning_flat = Reflect.get(usage, 'reasoning_tokens')\n if (typeof reasoning_flat === 'number') raw.reasoning_tokens = reasoning_flat\n const input_flat = Reflect.get(usage, 'input_tokens')\n if (raw.input_tokens === undefined && typeof input_flat === 'number') raw.input_tokens = input_flat\n const output_flat = Reflect.get(usage, 'output_tokens')\n if (raw.output_tokens === undefined && typeof output_flat === 'number') raw.output_tokens = output_flat\n return raw\n}\n\nexport function to_sdk_messages(messages: ReadonlyArray<Message>): ModelMessage[] {\n const out: ModelMessage[] = []\n for (const m of messages) {\n if (m.role === 'system') {\n out.push({ role: 'system', content: m.content })\n continue\n }\n if (m.role === 'user') {\n if (typeof m.content === 'string') {\n out.push({ role: 'user', content: m.content })\n } else {\n const parts: Array<\n | { type: 'text'; text: string }\n | { type: 'image'; image: string | Uint8Array; mediaType?: string }\n > = m.content.map((p) => {\n if (p.type === 'text') return { type: 'text', text: p.text }\n const image_part: { type: 'image'; image: string | Uint8Array; mediaType?: string } = {\n type: 'image',\n image: p.image,\n }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n return image_part\n })\n out.push({ role: 'user', content: parts })\n }\n continue\n }\n if (m.role === 'tool') {\n out.push({\n role: 'tool',\n content: [\n {\n type: 'tool-result',\n toolCallId: m.tool_call_id,\n toolName: m.name,\n output: { type: 'text', value: m.content },\n },\n ],\n })\n continue\n }\n // assistant\n if (typeof m.content === 'string') {\n out.push({ role: 'assistant', content: m.content })\n continue\n }\n const parts = m.content.map((p) => {\n if (p.type === 'text') return { type: 'text' as const, text: p.text }\n return {\n type: 'tool-call' as const,\n toolCallId: p.id,\n toolName: p.name,\n input: p.input,\n }\n })\n out.push({ role: 'assistant', content: parts })\n }\n return out\n}\n\n/**\n * Hoist a leading run of system messages out of the SDK message list into the\n * AI SDK's top-level `system` option.\n *\n * Passing a `role: 'system'` entry inside `messages` makes the AI SDK treat it\n * as potentially attacker-controlled: it warns on every call (and newer `ai`\n * versions throw unless `allowSystemInMessages` is set). fascicle's system\n * content is the developer's own prompt, and the SDK's own recommendation is to\n * deliver it through the top-level `instructions` option (v7's rename of the\n * former `system` option), which removes the warning at its source rather than\n * suppressing it.\n *\n * Only the *leading* run is hoisted (fascicle's only shape: one or more system\n * messages, then the conversation). A system message that appears after a\n * non-system message keeps its position rather than being silently reordered to\n * the top, and the original list is returned untouched when hoisting would leave\n * `messages` empty, since the SDK rejects an empty messages array.\n */\nexport function split_leading_system(messages: ReadonlyArray<ModelMessage>): {\n system?: string\n messages: ModelMessage[]\n} {\n let run_end = 0\n const system_parts: string[] = []\n while (run_end < messages.length) {\n const m = messages[run_end]\n if (m?.role !== 'system') break\n system_parts.push(m.content)\n run_end += 1\n }\n const rest = messages.slice(run_end)\n if (system_parts.length === 0 || rest.length === 0) {\n return { messages: [...messages] }\n }\n return { system: system_parts.join('\\n\\n'), messages: rest }\n}\n\nexport function to_sdk_tools(tools: ReadonlyArray<Tool>): ToolSet | undefined {\n if (tools.length === 0) return undefined\n const entries: ToolSet = {}\n for (const t of tools) {\n entries[t.name] = ai_tool({\n description: t.description,\n inputSchema: t.input_schema,\n })\n }\n return entries\n}\n\nexport function map_stream_part_to_chunk(\n part: TextStreamPart<ToolSet>,\n step_index: number,\n): StreamChunk | undefined {\n switch (part.type) {\n case 'text-delta':\n return { kind: 'text', text: part.text, step_index }\n case 'reasoning-delta':\n return { kind: 'reasoning', text: part.text, step_index }\n case 'tool-input-start':\n return {\n kind: 'tool_call_start',\n id: part.id,\n name: part.toolName,\n step_index,\n }\n case 'tool-input-delta':\n return {\n kind: 'tool_call_input_delta',\n id: part.id,\n delta: part.delta,\n step_index,\n }\n case 'tool-call':\n return {\n kind: 'tool_call_end',\n id: part.toolCallId,\n input: part.input,\n step_index,\n }\n case 'finish-step':\n return {\n kind: 'step_finish',\n step_index,\n finish_reason: map_finish_reason(part.finishReason),\n usage: default_usage_from_sdk(part.usage),\n }\n default:\n // v7 parts with no engine StreamChunk kind (file, reasoning-file,\n // source, block framing) drop here on purpose: the engine models\n // text, reasoning, and tool traffic, not generated files.\n return undefined\n }\n}\n\nexport function default_usage_from_sdk(usage: unknown): UsageTotals {\n // Streamed step_finish chunks must carry the same cache/reasoning\n // granularity the step record gets via adapter.normalize_usage; every\n // built-in adapter routes through default_normalize_usage, so this keeps\n // the chunk surface consistent with the non-streamed result.\n return default_normalize_usage(to_raw_provider_usage(usage))\n}\n\nasync function collect_stream(\n params: Parameters<typeof streamText>[0],\n step_index: number,\n dispatcher: ChunkDispatcher,\n on_first_chunk: () => void,\n internal_controller: AbortController,\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n const stream_result = streamText(params)\n let text = ''\n const tool_calls: RawToolCall[] = []\n let finish_reason: FinishReason = 'stop'\n let raw_usage: RawProviderUsage = {}\n let first = true\n\n for await (const part of stream_result.stream) {\n if (first) {\n first = false\n on_first_chunk()\n }\n if (part.type === 'text-delta') {\n text += part.text\n }\n if (part.type === 'tool-call') {\n tool_calls.push({\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n })\n }\n if (part.type === 'finish-step') {\n finish_reason = map_finish_reason(part.finishReason)\n raw_usage = to_raw_provider_usage(part.usage)\n }\n if (part.type === 'error') {\n throw part.error\n }\n if (part.type === 'abort') {\n throw new aborted_error('aborted', { step_index })\n }\n const chunk = map_stream_part_to_chunk(part, step_index)\n if (chunk === undefined) continue\n try {\n await dispatcher.dispatch(chunk)\n } catch (err: unknown) {\n internal_controller.abort()\n throw err\n }\n }\n\n return {\n text,\n tool_calls,\n finish_reason,\n usage: adapter.normalize_usage(raw_usage),\n }\n}\n\nasync function collect_non_stream(\n params: Parameters<typeof generateText>[0],\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n let result: Awaited<ReturnType<typeof generateText>>\n try {\n result = await generateText(params)\n } catch (err: unknown) {\n const recovered = recover_no_object_generated(err, adapter)\n if (recovered !== undefined) return recovered\n throw err\n }\n const tool_calls: RawToolCall[] = []\n for (const tc of result.toolCalls) {\n tool_calls.push({\n id: tc.toolCallId,\n name: tc.toolName,\n input: tc.input,\n })\n }\n const raw_usage = to_raw_provider_usage(result.usage)\n return {\n text: result.text,\n tool_calls,\n finish_reason: map_finish_reason(result.finishReason),\n usage: adapter.normalize_usage(raw_usage),\n }\n}\n\n/**\n * When `output` (structured output) is in play, `generateText` eagerly parses the\n * model's text against the schema and throws `NoObjectGeneratedError` if it\n * does not conform. That parse is the SDK's, not fascicle's: turning it into a\n * thrown error would skip the engine's own schema-parse + repair loop (and the\n * error is not a retryable transient, so it would surface raw). Instead we\n * recover the model's raw text from the error and hand it back as a normal\n * turn result, so `parse_with_schema` re-validates it and the repair loop\n * engages exactly as it does for the prompt-based path. Returns undefined for\n * any other error so the caller rethrows.\n */\nfunction recover_no_object_generated(\n err: unknown,\n adapter: AiSdkProviderAdapter,\n): TurnResult | undefined {\n if (!NoObjectGeneratedError.isInstance(err)) return undefined\n const text_field = Reflect.get(err, 'text')\n const finish_field = Reflect.get(err, 'finishReason')\n const raw_usage = to_raw_provider_usage(Reflect.get(err, 'usage'))\n return {\n text: typeof text_field === 'string' ? text_field : '',\n tool_calls: [],\n finish_reason: map_finish_reason(typeof finish_field === 'string' ? finish_field : undefined),\n usage: adapter.normalize_usage(raw_usage),\n }\n}\n\ntype AiSdkCallParams = Parameters<typeof streamText>[0] & Parameters<typeof generateText>[0]\n\nexport type AiSdkTurnConfig = {\n readonly adapter: AiSdkProviderAdapter\n readonly model_id: string\n readonly dispatcher: ChunkDispatcher\n readonly tools: ReadonlyArray<Tool>\n readonly schema: z.ZodType | undefined\n readonly provider_options: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined\n readonly temperature: number | undefined\n readonly max_tokens: number | undefined\n readonly top_p: number | undefined\n readonly telemetry: AiSdkTelemetrySettings | undefined\n}\n\nexport type AiSdkTurnArgs = {\n readonly step_index: number\n readonly messages: ReadonlyArray<Message>\n readonly abort: AbortSignal\n readonly stream: boolean\n readonly on_first_chunk: () => void\n}\n\nexport type AiSdkTurn = (args: AiSdkTurnArgs) => Promise<TurnResult>\n\n/**\n * Build the single-attempt SDK turn for one generate call: the\n * generateText/streamText call body behind the same neutral seam a native\n * adapter's invoke_turn implements. The built model is memoized across steps\n * of one generate call. No retry here: generate.ts wraps the returned turn in\n * the engine-owned retry_turn.\n */\nexport function create_ai_sdk_turn(cfg: AiSdkTurnConfig): AiSdkTurn {\n let model_instance: LanguageModel | undefined\n const get_model = async (): Promise<LanguageModel> => {\n if (model_instance === undefined) {\n const built = await cfg.adapter.build_model(cfg.model_id)\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n model_instance = built as LanguageModel\n }\n return model_instance\n }\n\n // Telemetry is resolved once per generate call and memoized across its steps,\n // mirroring get_model. build_ai_sdk_telemetry returns undefined immediately\n // (no peer load) unless telemetry is explicitly enabled, so the disabled\n // default costs nothing.\n let telemetry_options: AiSdkTelemetryPassthrough | undefined\n let telemetry_resolved = false\n const get_telemetry = async (): Promise<AiSdkTelemetryPassthrough | undefined> => {\n if (!telemetry_resolved) {\n telemetry_options = await build_ai_sdk_telemetry(cfg.telemetry)\n telemetry_resolved = true\n }\n return telemetry_options\n }\n\n const sdk_tools = to_sdk_tools(cfg.tools)\n\n // Native structured output: when a schema is requested and the provider\n // constrains decoding to it (the 'structured_output' capability), route\n // through the AI SDK's Output.object seam so the schema becomes the\n // provider's responseFormat (e.g. Ollama's `format`) instead of a\n // prompt-for-JSON-then-scrape. Gated on no tools: forcing a JSON\n // responseFormat alongside tool calls breaks tool dispatch on most\n // providers, so tool runs keep the prompt-based schema path. The engine's\n // schema parse + repair loop still owns validation either way. This seam\n // is ai_sdk-only: a native adapter that constrains decoding honors\n // TurnRequest.schema inside its own invoke_turn.\n let output_spec: NonNullable<AiSdkCallParams['output']> | undefined\n if (\n cfg.schema !== undefined &&\n cfg.tools.length === 0 &&\n cfg.adapter.supports('structured_output')\n ) {\n // Output.object<T> is not structurally assignable to the SDK's default\n // Output<string, string> param slot, but the runtime shape is exactly\n // what generateText/streamText consume to set responseFormat.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n output_spec = Output.object({ schema: cfg.schema }) as NonNullable<\n AiSdkCallParams['output']\n >\n }\n\n // provider_options is Record<string, Record<string, unknown>>; the SDK\n // expects SharedV3ProviderOptions (Record<string, JSONObject>) which is\n // structurally compatible for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const provider_options = cfg.provider_options as AiSdkCallParams['providerOptions']\n\n return async (args: AiSdkTurnArgs): Promise<TurnResult> => {\n const model = await get_model()\n const telemetry = await get_telemetry()\n const internal_controller = new AbortController()\n const cancel_on_user_abort = (): void => {\n internal_controller.abort(args.abort.reason)\n }\n if (args.abort.aborted) {\n internal_controller.abort(args.abort.reason)\n } else {\n args.abort.addEventListener('abort', cancel_on_user_abort, { once: true })\n }\n const { system: hoisted_system, messages: sdk_messages } = split_leading_system(\n to_sdk_messages(args.messages),\n )\n const base_params: AiSdkCallParams = {\n model,\n messages: sdk_messages,\n abortSignal: internal_controller.signal,\n stopWhen: isStepCount(1),\n // The engine owns retry via retry_turn in generate.ts; disable the AI\n // SDK's own retry (default 2) so it does not nest inside each of our\n // attempts and inflate provider round-trips / distort backoff.\n maxRetries: 0,\n }\n if (hoisted_system !== undefined) base_params.instructions = hoisted_system\n if (sdk_tools !== undefined) base_params.tools = sdk_tools\n if (output_spec !== undefined) base_params.output = output_spec\n if (provider_options !== undefined) base_params.providerOptions = provider_options\n if (cfg.temperature !== undefined) base_params.temperature = cfg.temperature\n if (cfg.max_tokens !== undefined) base_params.maxOutputTokens = cfg.max_tokens\n if (cfg.top_p !== undefined) base_params.topP = cfg.top_p\n if (telemetry !== undefined) {\n // AiSdkTelemetryPassthrough uses the SDK's own telemetry keys; the slot's\n // generic (RUNTIME_CONTEXT/TOOLS) is erased for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n base_params.experimental_telemetry = telemetry as NonNullable<\n AiSdkCallParams['experimental_telemetry']\n >\n }\n\n try {\n if (args.stream) {\n return await collect_stream(\n base_params,\n args.step_index,\n cfg.dispatcher,\n args.on_first_chunk,\n internal_controller,\n cfg.adapter,\n )\n }\n return await collect_non_stream(base_params, cfg.adapter)\n } finally {\n args.abort.removeEventListener('abort', cancel_on_user_abort)\n }\n }\n}\n","/**\n * generate(opts) — single public entry point for model calls.\n *\n * This file is SDK-agnostic (constraints §7 invariant 13, inverted): it\n * resolves options, gates capabilities, and owns retry + trajectory, and it\n * drives every depth-1 turn — ai_sdk and native alike — 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 * (rule no-ai-import-outside-ai-sdk-provider). tool_loop.ts consumes the\n * InvokeOnce seam built here.\n */\n\nimport type {\n AiSdkTelemetrySettings,\n CostBreakdown,\n EffortLevel,\n FinishReason,\n GenerateOptions,\n GenerateResult,\n Message,\n Pricing,\n PricingTable,\n ResolvedModel,\n RetryPolicy,\n StreamChunk,\n Tool,\n TurnRequest,\n TurnResult,\n} from './types.js'\nimport {\n aborted_error,\n engine_config_error,\n model_required_error,\n on_chunk_error,\n provider_capability_error,\n provider_error,\n provider_not_configured_error,\n turn_timeout_error,\n} from './errors.js'\nimport { merge_provider_options } from './merge_defaults.js'\nimport { FREE_PROVIDERS, pricing_key } from './pricing.js'\nimport { parse_retry_after, retry_with_policy } from './retry.js'\nimport {\n build_repair_message,\n format_zod_error,\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 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 InvokeOnceResult,\n} from './tool_loop.js'\nimport type {\n NativeProviderAdapter,\n ProviderAdapter,\n} from './providers/types.js'\nimport {\n create_ai_sdk_turn,\n type AiSdkTurn,\n type AiSdkTurnConfig,\n} 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_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\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 let run_end = 0\n const system_parts: string[] = []\n while (run_end < messages.length) {\n const m = messages[run_end]\n // Stryker disable next-line OptionalChaining: within the loop guard run_end < messages.length, m is always an in-bounds (defined) Message, so m.role and m?.role read identically.\n if (m?.role !== 'system') break\n system_parts.push(m.content)\n run_end += 1\n }\n const rest = messages.slice(run_end)\n if (system_parts.length === 0 || rest.length === 0) {\n return { messages: [...messages] }\n }\n return { system: system_parts.join('\\n\\n'), messages: rest }\n}\n\nexport function classify_provider_error(err: unknown): unknown {\n if (err === null || typeof err !== 'object') return err\n // Already-classified shape: pass through.\n const existing_kind = Reflect.get(err, 'kind')\n if (\n typeof existing_kind === 'string' &&\n (existing_kind === 'rate_limit' ||\n existing_kind === 'provider_5xx' ||\n existing_kind === 'network' ||\n existing_kind === 'timeout')\n ) {\n return err\n }\n const status = Reflect.get(err, 'statusCode')\n const status_alt = Reflect.get(err, 'status')\n const resolved_status =\n typeof status === 'number'\n ? status\n : typeof status_alt === 'number'\n ? status_alt\n : undefined\n if (resolved_status === 429) {\n const headers = Reflect.get(err, 'responseHeaders')\n let retry_after_ms: number | undefined\n if (headers !== null && typeof headers === 'object') {\n const hv = Reflect.get(headers, 'retry-after')\n if (typeof hv === 'string') retry_after_ms = parse_retry_after(hv)\n }\n const message = Reflect.get(err, 'message')\n const out: Record<string, unknown> = { kind: 'rate_limit', status: 429 }\n if (typeof message === 'string') out['message'] = message\n if (retry_after_ms !== undefined) out['retry_after_ms'] = retry_after_ms\n return out\n }\n if (resolved_status !== undefined && resolved_status >= 500 && resolved_status < 600) {\n const message = Reflect.get(err, 'message')\n const out: Record<string, unknown> = { kind: 'provider_5xx', status: resolved_status }\n if (typeof message === 'string') out['message'] = message\n return out\n }\n const code = Reflect.get(err, 'code')\n if (\n code === 'ECONNRESET' ||\n code === 'ETIMEDOUT' ||\n code === 'ENOTFOUND' ||\n code === 'ECONNREFUSED'\n ) {\n const message = Reflect.get(err, 'message')\n const out: Record<string, unknown> = { kind: 'network' }\n if (typeof message === 'string') out['message'] = message\n return out\n }\n return err\n}\n\ntype AiSdkInvokeConfig = {\n readonly invoke_turn: AiSdkTurn\n readonly retry_policy: RetryPolicy\n readonly turn_timeout_ms: number | 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 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 (D5): the user's abort OR'd with a fresh\n * `turn_timeout_ms` deadline via AbortSignal.any (the src/core/timeout.ts\n * precedent). `timed_out()` distinguishes an expiry (retryable) from a user\n * abort (terminal) in the retry_turn ladder; `dispose()` clears the timer so a\n * settled attempt never leaves one armed. With no budget the user's abort\n * passes through untouched, so the un-timed path stays byte-for-byte as before.\n * Armed fresh inside retry_with_policy's callback so each retry gets its own\n * 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 verbatim by both depth-1 transports: one turn\n * attempt inside 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`, never\n * the ladder (D5: the engine owns retry; hidden adapter retries are illegible).\n */\nfunction retry_turn(\n call_once: (turn_abort: AbortSignal) => Promise<TurnResult>,\n args: InvokeOnceArgs,\n has_streamed: () => boolean,\n retry_policy: RetryPolicy,\n classify: (err: unknown) => unknown,\n turn_timeout_ms: number | undefined,\n): Promise<TurnResult> {\n return retry_with_policy(\n async () => {\n const deadline = arm_turn_timeout(args.abort, turn_timeout_ms)\n try {\n return await call_once(deadline.signal)\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 )\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.\n */\nfunction build_ai_sdk_invoke(cfg: AiSdkInvokeConfig): InvokeOnce {\n return async (args: InvokeOnceArgs): Promise<InvokeOnceResult> => {\n let chunks_started = false\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 chunks_started = true\n },\n })\n\n return await retry_turn(\n call_once,\n args,\n () => chunks_started,\n cfg.retry_policy,\n classify_provider_error,\n cfg.turn_timeout_ms,\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 chunks_started = false\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 chunks_started = true\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 () => chunks_started,\n cfg.retry_policy,\n classify,\n cfg.turn_timeout_ms,\n )\n }\n}\n\nexport async function generate<T = string>(\n opts_in: GenerateOptions<T>,\n engine: EngineInternals,\n): Promise<GenerateResult<T>> {\n if (opts_in.abort?.aborted === true) {\n throw new aborted_error('aborted', { reason: opts_in.abort.reason })\n }\n\n const resolved_model = opts_in.model ?? engine.default_model\n if (resolved_model === undefined) throw new model_required_error()\n const sole_provider =\n engine.adapters.size === 1 ? [...engine.adapters.keys()][0] : undefined\n const resolved_provider =\n opts_in.provider ?? engine.default_provider ?? sole_provider ?? 'anthropic'\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 (merged_provider_options !== undefined) {\n opts.provider_options = merged_provider_options\n }\n\n const target: ResolvedModel = { provider: resolved_provider, model_id: resolved_model }\n\n const adapter = engine.adapters.get(target.provider)\n if (adapter === undefined) {\n throw new provider_not_configured_error(target.provider)\n }\n\n if (adapter.kind === 'external') {\n return adapter.generate<T>(opts, target)\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 if (opts.schema !== undefined && !adapter.supports('schema')) {\n throw new provider_capability_error(target.provider, 'schema')\n }\n if (tools_list.length > 0 && !adapter.supports('tools')) {\n throw new provider_capability_error(target.provider, 'tools')\n }\n if (on_chunk_provided && !adapter.supports('streaming')) {\n throw new provider_capability_error(target.provider, 'streaming')\n }\n\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')\n }\n const dispatcher = create_chunk_dispatcher(opts.on_chunk)\n\n let invoke_once: InvokeOnce\n if (adapter.kind === 'ai_sdk') {\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(trajectory, 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. Without this merge the user's provider_options\n // were computed then dropped, a silent no-op for every provider.\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 branch only threads resolved options through the seam.\n invoke_once = build_ai_sdk_invoke({\n invoke_turn: create_ai_sdk_turn({\n adapter,\n model_id: target.model_id,\n dispatcher,\n tools: 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 telemetry: engine.default_ai_sdk_telemetry,\n }),\n retry_policy,\n turn_timeout_ms,\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,\n turn_timeout_ms,\n dispatcher,\n 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 abort = opts.abort ?? new AbortController().signal\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 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('tool_call_repair_attempts must be >= 0')\n }\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('max_tool_calls_per_step must be >= 1')\n }\n\n const schema_prefix =\n opts.schema !== undefined\n ? 'You must respond with a single JSON value that conforms to the expected schema. Return ONLY the JSON value, with no markdown or commentary.'\n : 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\n const generate_span = start_generate_span(trajectory, {\n model: resolved_model,\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 pricing_dedup = create_pricing_missing_dedup(trajectory)\n\n const resolve_pricing = (): Pricing | undefined => {\n return engine.pricing[pricing_key(target.provider, target.model_id)]\n }\n\n const dispatch_chunk =\n on_chunk_provided\n ? async (chunk: StreamChunk): Promise<void> => {\n await dispatcher.dispatch(chunk)\n }\n : undefined\n\n const messages_mutable: Message[] = [...initial_messages]\n let total_steps = 0\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 = schema_repair_attempts\n let content_parsed: T | undefined\n // Stryker disable next-line ConditionalExpression,EqualityOperator: for a schema call this is overwritten in the loop before use; for a no-schema call schema_satisfied is never read (the opts.schema === undefined final-content branch wins).\n let schema_satisfied = opts.schema === undefined\n // One holder per generate call so schema-repair re-invocations of the loop\n // cannot refill the salvage budget.\n const salvage_budget =\n tool_call_repair_attempts > 0 ? { remaining: tool_call_repair_attempts } : undefined\n\n try {\n while (true) {\n const loop_result = await run_tool_loop({\n invoke_once,\n messages: messages_mutable,\n tools: tools_list,\n max_steps,\n step_index_start: total_steps,\n tool_error_policy,\n abort,\n on_tool_approval: opts.on_tool_approval,\n trajectory,\n stream: on_chunk_provided,\n dispatch_chunk,\n provider: target.provider,\n model_id: target.model_id,\n resolve_pricing,\n pricing_dedup,\n ...(salvage_budget !== undefined ? { salvage_budget } : {}),\n ...(max_tool_calls_per_step !== undefined ? { max_tool_calls_per_step } : {}),\n ...(opts.prepare_step !== undefined ? { prepare_step: opts.prepare_step } : {}),\n })\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 total_steps = steps_accum.length\n text = loop_result.text\n finish_reason = loop_result.finish_reason\n\n if (opts.schema === undefined) break\n if (finish_reason !== 'stop') break\n\n const parse = parse_with_schema(opts.schema, text)\n if (parse.ok) {\n content_parsed = parse.value\n schema_satisfied = true\n break\n }\n record_schema_validation_failed(trajectory, {\n attempt: repair_remaining === schema_repair_attempts ? 'initial' : 'repair',\n zod_issues: format_zod_error(parse.error),\n raw_text: text,\n })\n if (repair_remaining <= 0 || total_steps >= max_steps) {\n throw_schema_validation(parse.error, text)\n }\n repair_remaining -= 1\n messages_mutable.push(build_repair_message(parse.error))\n }\n\n const aggregated_usage = sum_usage(steps_accum)\n const aggregated_cost = aggregate_cost(steps_accum, target.provider)\n\n let final_content: T\n if (opts.schema === undefined) {\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n final_content = text as T\n } else if (schema_satisfied && content_parsed !== undefined) {\n final_content = content_parsed\n } else {\n // Unreachable: if schema set and not satisfied we throw above.\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n final_content = text as T\n }\n\n const result: GenerateResult<T> = {\n content: final_content,\n tool_calls: tool_calls_accum,\n steps: steps_accum,\n usage: aggregated_usage,\n finish_reason,\n model_resolved: { provider: target.provider, model_id: target.model_id },\n }\n if (aggregated_cost !== undefined) result.cost = aggregated_cost\n\n if (on_chunk_provided) {\n await dispatcher.dispatch({\n kind: 'finish',\n finish_reason,\n usage: aggregated_usage,\n })\n }\n\n end_generate_span(trajectory, generate_span, {\n usage: aggregated_usage,\n finish_reason,\n model_resolved: result.model_resolved,\n })\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\nexport function round6(v: number): number {\n return Math.round(v * 1e6) / 1e6\n}\n\nexport function aggregate_cost(\n steps: ReadonlyArray<GenerateResult['steps'][number]>,\n provider: string,\n): CostBreakdown | undefined {\n let any_present = false\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 let reasoning_present = false\n let reasoning = 0\n for (const s of steps) {\n if (s.cost === undefined) continue\n any_present = true\n total += s.cost.total_usd\n input += s.cost.input_usd\n output += s.cost.output_usd\n if (s.cost.cached_input_usd !== undefined) {\n cached_present = true\n cached += s.cost.cached_input_usd\n }\n if (s.cost.cache_write_usd !== undefined) {\n cache_write_present = true\n cache_write += s.cost.cache_write_usd\n }\n if (s.cost.reasoning_usd !== undefined) {\n reasoning_present = true\n reasoning += s.cost.reasoning_usd\n }\n }\n if (!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(total),\n input_usd: round6(input),\n output_usd: round6(output),\n currency: 'USD',\n is_estimate: true,\n }\n if (cached_present) out.cached_input_usd = round6(cached)\n if (cache_write_present) out.cache_write_usd = round6(cache_write)\n if (reasoning_present) out.reasoning_usd = round6(reasoning)\n return out\n}\n\n","/**\n * Engine factory (spec §5.8).\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 Engine\n * whose methods close over this instance state. Model resolution is a verbatim\n * pass-through: `model` is sent to the provider unchanged.\n *\n * Credentials / init values are validated synchronously by each provider\n * adapter factory; SDK loading is deferred to the first generate call. A\n * generate call that references a provider absent from the construction\n * providers map throws provider_not_configured_error at call time.\n *\n * list_prices returns a defensive shallow copy; mutating the returned object\n * does not affect engine state.\n *\n * with_providers derives a NEW engine from the retained construction config\n * (D8): incoming providers / custom_providers shallow-merge by name over the\n * originals, the merged config is re-validated by a recursive create_engine\n * (same shadow-throws rule, fresh adapters, independent disposal), and this\n * engine is left untouched. It is the value-semantic answer to runtime\n * registration, not a mutable registry.\n */\n\nimport type {\n Engine,\n EngineConfig,\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\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\nexport function create_engine(config: EngineConfig): Engine {\n if (\n config.providers === null ||\n typeof config.providers !== 'object'\n ) {\n throw new engine_config_error('EngineConfig.providers is required')\n }\n\n const adapters = build_provider_adapters(config.providers, config.custom_providers)\n\n const pricing: Record<string, Pricing> = { ...DEFAULT_PRICING }\n if (config.pricing !== undefined) {\n for (const [key, value] of Object.entries(config.pricing)) {\n pricing[key] = value\n }\n }\n\n const defaults = config.defaults\n const default_retry = defaults?.retry_policy ?? config.default_retry ?? DEFAULT_RETRY\n const default_effort = defaults?.effort ?? config.default_effort ?? 'none'\n const default_max_steps = defaults?.max_steps ?? config.default_max_steps ?? 10\n if (defaults?.tool_call_repair_attempts !== undefined && defaults.tool_call_repair_attempts < 0) {\n throw new engine_config_error('defaults.tool_call_repair_attempts must be >= 0')\n }\n if (defaults?.max_tool_calls_per_step !== undefined && defaults.max_tool_calls_per_step < 1) {\n throw new engine_config_error('defaults.max_tool_calls_per_step must be >= 1')\n }\n if (defaults?.turn_timeout_ms !== undefined && defaults.turn_timeout_ms <= 0) {\n throw new engine_config_error('defaults.turn_timeout_ms must be > 0')\n }\n\n const get_internals = (): EngineInternals => ({\n pricing,\n adapters,\n default_retry,\n default_effort,\n default_max_steps,\n ...(defaults?.model !== undefined ? { default_model: defaults.model } : {}),\n ...(defaults?.provider !== undefined ? { default_provider: defaults.provider } : {}),\n ...(defaults?.system !== undefined ? { default_system: defaults.system } : {}),\n ...(defaults?.tool_error_policy !== undefined\n ? { default_tool_error_policy: defaults.tool_error_policy }\n : {}),\n ...(defaults?.schema_repair_attempts !== undefined\n ? { default_schema_repair_attempts: defaults.schema_repair_attempts }\n : {}),\n ...(defaults?.tool_call_repair_attempts !== undefined\n ? { default_tool_call_repair_attempts: defaults.tool_call_repair_attempts }\n : {}),\n ...(defaults?.max_tool_calls_per_step !== undefined\n ? { default_max_tool_calls_per_step: defaults.max_tool_calls_per_step }\n : {}),\n ...(defaults?.turn_timeout_ms !== undefined\n ? { default_turn_timeout_ms: defaults.turn_timeout_ms }\n : {}),\n ...(defaults?.ai_sdk_telemetry !== undefined\n ? { default_ai_sdk_telemetry: defaults.ai_sdk_telemetry }\n : {}),\n ...(defaults?.provider_options !== undefined\n ? { default_provider_options: defaults.provider_options }\n : {}),\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 return { ...pricing }\n },\n with_providers(\n providers: ProviderConfigMap,\n custom_providers?: Record<string, ProviderFactory>,\n ): Engine {\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 the\n // Promise.all below and then discarded by `.then(() => undefined)`, so a\n // 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","/**\n * model_call — the single sanctioned bridge between the composition and\n * engine layers.\n *\n * This is the only file under packages/fascicle/src/ permitted to import\n * value symbols from both core and engine (enforced by the\n * model-call-is-sole-bridge ast-grep rule in rules/).\n *\n * The returned Step auto-threads ctx.abort, ctx.trajectory, and — only when\n * run.stream is driving — an on_chunk forwarder into ctx.emit. Callers cannot\n * override these; the composition layer owns cancellation and trajectory\n * plumbing. Cost events flow out via ctx.trajectory per the engine's own\n * emission rules (constraints §5.3).\n */\n\nimport { createHash } from 'node:crypto'\nimport { aborted_error, step } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport type {\n EffortLevel,\n Engine,\n GenerateOptions,\n GenerateResult,\n Message,\n RetryPolicy,\n Tool,\n ToolApprovalHandler,\n} from '#engine'\nimport type { z } from 'zod'\n\nexport type ModelCallInput = string | ReadonlyArray<Message>\n\nexport type ModelCallConfig<T = string> = {\n readonly engine: Engine\n /**\n * Model or alias string. Optional: if omitted, the engine's\n * `defaults.model` is used. Errors at call time if neither is set.\n */\n readonly model?: string\n /**\n * Transport for the model: `anthropic` | `claude_cli` | `openrouter` | ...\n * Optional: if omitted, the engine's `defaults.provider` (or sole configured\n * provider, else `anthropic`) is used.\n */\n readonly provider?: string\n readonly id?: string\n readonly system?: string\n readonly tools?: ReadonlyArray<Tool>\n readonly schema?: z.ZodType<T>\n readonly effort?: EffortLevel\n readonly max_steps?: number\n readonly provider_options?: Record<string, unknown>\n readonly retry_policy?: RetryPolicy\n readonly tool_error_policy?: 'feed_back' | 'throw'\n readonly schema_repair_attempts?: number\n readonly tool_call_repair_attempts?: number\n readonly max_tool_calls_per_step?: number\n readonly on_tool_approval?: ToolApprovalHandler\n}\n\n/**\n * Wrap the run's trajectory so the engine's own spans (engine.generate and its\n * step spans) nest under the model_call step rather than floating. The wrapper\n * keeps a private span stack seeded with the model_call step's id, so nesting\n * is correct and concurrency-safe even when several model_calls run together\n * under `parallel`/`map` (each invocation builds its own wrapper). A\n * caller-supplied `parent_span_id` is never overridden.\n */\nfunction engine_trajectory(\n inner: TrajectoryLogger,\n root_parent: string | undefined,\n): TrajectoryLogger {\n const stack: string[] = root_parent !== undefined ? [root_parent] : []\n return {\n record: (event) => {\n inner.record(event)\n },\n start_span: (name, meta) => {\n const has_parent = meta !== undefined && 'parent_span_id' in meta\n const parent = stack.length > 0 ? stack[stack.length - 1] : undefined\n const next_meta =\n has_parent || parent === undefined ? meta : { ...meta, parent_span_id: parent }\n const id = inner.start_span(name, next_meta)\n stack.push(id)\n return id\n },\n end_span: (id, meta) => {\n inner.end_span(id, meta)\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n },\n }\n}\n\nfunction stable_signature(input: {\n model: string | undefined\n provider: string | undefined\n system: string | undefined\n has_tools: boolean\n has_schema: boolean\n}): string {\n const payload = JSON.stringify({\n model: input.model ?? null,\n provider: input.provider ?? null,\n system: input.system ?? null,\n has_tools: input.has_tools,\n has_schema: input.has_schema,\n })\n return createHash('sha256').update(payload).digest('hex').slice(0, 8)\n}\n\nexport function model_call<T = string>(\n cfg: ModelCallConfig<T>,\n): Step<ModelCallInput, GenerateResult<T>> {\n const has_tools = Boolean(cfg.tools && cfg.tools.length > 0)\n const has_schema = cfg.schema !== undefined\n const step_id =\n cfg.id ??\n `model_call:${stable_signature({\n model: cfg.model,\n provider: cfg.provider,\n system: cfg.system,\n has_tools,\n has_schema,\n })}`\n\n const describe_config: {\n model?: string\n provider?: string\n has_tools: boolean\n has_schema: boolean\n system?: string\n effort?: EffortLevel\n } = {\n has_tools,\n has_schema,\n }\n if (cfg.model !== undefined) describe_config.model = cfg.model\n if (cfg.provider !== undefined) describe_config.provider = cfg.provider\n if (cfg.system !== undefined) describe_config.system = cfg.system\n if (cfg.effort !== undefined) describe_config.effort = cfg.effort\n\n const inner = step<ModelCallInput, GenerateResult<T>>(step_id, async (input, ctx) => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before model_call', {\n reason: { signal: 'abort' },\n step_index: 0,\n })\n }\n \n const prompt: Message[] =\n typeof input === 'string'\n ? [{ role: 'user', content: [{ type: 'text', text: input }] }]\n : [...input]\n \n const opts: GenerateOptions<T> = {\n prompt,\n abort: ctx.abort,\n trajectory: engine_trajectory(ctx.trajectory, ctx.parent_span_id),\n }\n if (cfg.model !== undefined) opts.model = cfg.model\n if (cfg.provider !== undefined) opts.provider = cfg.provider\n if (cfg.system !== undefined) opts.system = cfg.system\n if (cfg.tools !== undefined) opts.tools = [...cfg.tools]\n if (cfg.schema !== undefined) opts.schema = cfg.schema\n if (cfg.effort !== undefined) opts.effort = cfg.effort\n if (cfg.max_steps !== undefined) opts.max_steps = cfg.max_steps\n if (cfg.provider_options !== undefined) opts.provider_options = cfg.provider_options\n if (cfg.retry_policy !== undefined) opts.retry = cfg.retry_policy\n if (cfg.tool_error_policy !== undefined) opts.tool_error_policy = cfg.tool_error_policy\n if (cfg.schema_repair_attempts !== undefined) {\n opts.schema_repair_attempts = cfg.schema_repair_attempts\n }\n if (cfg.tool_call_repair_attempts !== undefined) {\n opts.tool_call_repair_attempts = cfg.tool_call_repair_attempts\n }\n if (cfg.max_tool_calls_per_step !== undefined) {\n opts.max_tool_calls_per_step = cfg.max_tool_calls_per_step\n }\n if (cfg.on_tool_approval !== undefined) opts.on_tool_approval = cfg.on_tool_approval\n \n if (ctx.streaming) {\n opts.on_chunk = (chunk) => {\n // Record with kind preserved. ctx.emit would clobber kind to 'emit'\n // and bury the chunk, so stream consumers would have to un-nest a\n // generic event; recording keeps a clean top-level `model_chunk` event\n // (what docs/concepts.md already documents) carrying the StreamChunk.\n ctx.trajectory.record({ kind: 'model_chunk', step_id, chunk })\n }\n }\n \n return cfg.engine.generate(opts)\n })\n\n return {\n id: inner.id,\n kind: inner.kind,\n run: (input, ctx) => inner.run(input, ctx),\n config: Object.freeze({ ...describe_config }),\n }\n}\n","/**\n * Returns the standard set of env vars a typical CLI subprocess needs\n * to reach a user's logged-in session: PATH, HOME, SHELL, USER,\n * LOGNAME, LANG, TMPDIR. Values absent from `process.env` are skipped.\n *\n * Useful when passing explicit env to `claude_cli` under api_key mode\n * (oauth mode inherits automatically), or when you want an explicit,\n * minimal allowlist instead of inheriting the full parent env.\n *\n * @example\n * provider_options: {\n * claude_cli: { env: forward_standard_env() },\n * }\n */\nconst STANDARD_KEYS = ['PATH', 'HOME', 'SHELL', 'USER', 'LOGNAME', 'LANG', 'TMPDIR'] as const\n\nexport function forward_standard_env(): Record<string, string> {\n const out: Record<string, string> = {}\n for (const key of STANDARD_KEYS) {\n const v = process.env[key]\n if (typeof v === 'string') out[key] = v\n }\n return out\n}\n","/**\n * In-process pub/sub for trajectory events.\n *\n * One ring buffer of the last N events plus a Set of subscriber callbacks.\n * Both producers (file-tail and HTTP ingest) push into the same broadcaster;\n * SSE writers fan out via subscribe(). Each event gets a monotonic `id` so\n * SSE clients can replay from a known cursor on reconnect.\n *\n * Slow-client backpressure is the subscriber's responsibility — emit() does\n * not await delivery. If a subscriber throws, it is unsubscribed and the\n * `on_subscriber_error` callback fires once with the captured error so the\n * server can log it.\n */\n\nimport type { ParsedTrajectoryEvent } from '#core'\n\nexport type BroadcastEvent = {\n readonly id: number\n readonly event: ParsedTrajectoryEvent\n}\n\nexport type Subscriber = (entry: BroadcastEvent) => void\n\nexport type Broadcaster = {\n readonly emit: (event: ParsedTrajectoryEvent) => BroadcastEvent\n readonly subscribe: (fn: Subscriber) => () => void\n readonly snapshot: () => readonly BroadcastEvent[]\n readonly snapshot_after: (last_id: number) => readonly BroadcastEvent[]\n readonly size: () => number\n}\n\nexport type BroadcasterOptions = {\n readonly buffer: number\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\nexport function create_broadcaster(options: BroadcasterOptions): Broadcaster {\n const max = Math.max(1, options.buffer | 0)\n const ring: BroadcastEvent[] = []\n const subscribers = new Set<Subscriber>()\n let next_id = 1\n\n const emit = (event: ParsedTrajectoryEvent): BroadcastEvent => {\n const entry: BroadcastEvent = { id: next_id++, event }\n ring.push(entry)\n if (ring.length > max) ring.splice(0, ring.length - max)\n for (const fn of Array.from(subscribers)) {\n try {\n fn(entry)\n } catch (err) {\n subscribers.delete(fn)\n if (options.on_subscriber_error) options.on_subscriber_error(err)\n }\n }\n return entry\n }\n\n const subscribe = (fn: Subscriber): (() => void) => {\n subscribers.add(fn)\n return () => { subscribers.delete(fn) }\n }\n\n const snapshot = (): readonly BroadcastEvent[] => [...ring]\n\n const snapshot_after = (last_id: number): readonly BroadcastEvent[] =>\n ring.filter((e) => e.id > last_id)\n\n const size = (): number => ring.length\n\n return { emit, subscribe, snapshot, snapshot_after, size }\n}\n","/**\n * Tiny HTTP server: 5 routes, SSE fan-out, NDJSON ingest.\n *\n * GET / -> static viewer.html\n * GET /api/events -> text/event-stream replaying the ring buffer\n * GET /api/snapshot -> JSON dump of the ring buffer\n * POST /api/ingest -> newline-delimited trajectory events (http_logger)\n * GET /api/health -> { ok: true }\n *\n * The server owns nothing but the socket. The broadcaster owns the event\n * history; the static html lives on disk. SSE clients reconnect with\n * `Last-Event-ID` and the server replays anything past their cursor from\n * the ring buffer; older events are gone (bounded memory by design).\n */\n\nimport { createReadStream, statSync } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { dirname, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { trajectory_event_schema, type ParsedTrajectoryEvent } from '#core'\nimport type { Broadcaster } from './broadcast.js'\n\nconst SSE_HEARTBEAT_MS = 15_000\nconst HERE = dirname(fileURLToPath(import.meta.url))\nconst STATIC_HTML = resolve(HERE, 'static', 'viewer.html')\n\nexport type ServerOptions = {\n readonly broadcaster: Broadcaster\n readonly host: string\n readonly port: number\n readonly on_parse_error?: (err: unknown, line: string) => void\n}\n\nexport type ViewerServer = {\n readonly url: string\n readonly close: () => Promise<void>\n}\n\nexport function start_server(options: ServerOptions): Promise<ViewerServer> {\n const { broadcaster, host, port, on_parse_error } = options\n\n const handler = (req: IncomingMessage, res: ServerResponse): void => {\n const route = resolve_route(req, host, port)\n\n if (route === 'GET /' || route === 'GET /index.html') {\n serve_static_html(res)\n return\n }\n if (route === 'GET /api/health') {\n send_json(res, 200, { ok: true })\n return\n }\n if (route === 'GET /api/snapshot') {\n send_json(res, 200, { events: broadcaster.snapshot() })\n return\n }\n if (route === 'GET /api/events') {\n handle_sse(req, res, broadcaster)\n return\n }\n if (route === 'POST /api/ingest') {\n handle_ingest(req, res, broadcaster, on_parse_error)\n return\n }\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify({ error: 'not_found', route }))\n }\n\n const http_server = createServer(handler)\n\n return new Promise((res_ok, res_err) => {\n http_server.once('error', res_err)\n http_server.listen(port, host, () => {\n http_server.removeListener('error', res_err)\n const addr = http_server.address()\n const bound_port =\n addr !== null && typeof addr === 'object' && 'port' in addr ? addr.port : port\n const url = `http://${host}:${bound_port}`\n res_ok({\n url,\n close: () => close_server(http_server),\n })\n })\n })\n}\n\nexport function resolve_route(\n req: {\n url?: string | undefined\n method?: string | undefined\n headers: { host?: string | undefined }\n },\n host: string,\n port: number,\n): string {\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? `${host}:${port}`}`)\n return `${req.method ?? 'GET'} ${url.pathname}`\n}\n\nfunction close_server(server: Server): Promise<void> {\n return new Promise((res_ok, res_err) => {\n server.close((err) => {\n if (err) res_err(err)\n else res_ok()\n })\n server.closeAllConnections?.()\n })\n}\n\nfunction send_json(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify(body))\n}\n\nfunction serve_static_html(res: ServerResponse): void {\n let size: number\n try {\n size = statSync(STATIC_HTML).size\n } catch {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain')\n res.end('viewer.html missing')\n return\n }\n res.statusCode = 200\n res.setHeader('content-type', 'text/html; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('content-length', String(size))\n createReadStream(STATIC_HTML).pipe(res)\n}\n\nfunction handle_sse(req: IncomingMessage, res: ServerResponse, broadcaster: Broadcaster): void {\n res.statusCode = 200\n res.setHeader('content-type', 'text/event-stream')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('connection', 'keep-alive')\n res.setHeader('x-accel-buffering', 'no')\n\n const last_event_id = parse_last_event_id(req.headers['last-event-id'])\n for (const entry of broadcaster.snapshot_after(last_event_id)) {\n write_event(res, entry.id, entry.event)\n }\n\n const heartbeat = setInterval(() => {\n res.write(': heartbeat\\n\\n')\n }, SSE_HEARTBEAT_MS)\n\n const unsubscribe = broadcaster.subscribe((entry) => {\n write_event(res, entry.id, entry.event)\n })\n\n const close = (): void => {\n clearInterval(heartbeat)\n unsubscribe()\n if (!res.writableEnded) {\n res.write('event: close\\ndata: {}\\n\\n')\n res.end()\n }\n }\n\n req.on('close', close)\n req.on('error', close)\n}\n\nfunction parse_last_event_id(value: string | string[] | undefined): number {\n if (typeof value !== 'string') return 0\n const n = Number.parseInt(value, 10)\n return Number.isFinite(n) && n > 0 ? n : 0\n}\n\nfunction write_event(res: ServerResponse, id: number, event: ParsedTrajectoryEvent): void {\n res.write(`id: ${id}\\nevent: trajectory\\ndata: ${JSON.stringify(event)}\\n\\n`)\n}\n\nfunction handle_ingest(\n req: IncomingMessage,\n res: ServerResponse,\n broadcaster: Broadcaster,\n on_parse_error?: (err: unknown, line: string) => void,\n): void {\n let buf = ''\n let accepted = 0\n let rejected = 0\n\n const consume_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n rejected++\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = trajectory_event_schema.safeParse(parsed)\n if (!result.success) {\n rejected++\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n broadcaster.emit(result.data)\n accepted++\n }\n\n req.setEncoding('utf8')\n req.on('data', (chunk: string) => {\n buf += chunk\n let nl = buf.indexOf('\\n')\n while (nl !== -1) {\n consume_line(buf.slice(0, nl))\n buf = buf.slice(nl + 1)\n nl = buf.indexOf('\\n')\n }\n })\n req.on('end', () => {\n if (buf.length > 0) consume_line(buf)\n send_json(res, 200, { accepted, rejected })\n })\n req.on('error', (err: unknown) => {\n if (on_parse_error) on_parse_error(err, '')\n send_json(res, 400, { error: 'bad_request' })\n })\n}\n\nexport const internals_for_test = { STATIC_HTML, SSE_HEARTBEAT_MS, parse_last_event_id }\n","/**\n * JSONL file tailer.\n *\n * Watches a file for appends and emits one parsed trajectory event per\n * complete line. Handles three pathological cases the spec calls out:\n *\n * - Truncation / rotation: a watcher event whose stat is shorter than the\n * current offset means the file shrunk. Reset offset to 0 and re-stream.\n * - Partial last line: if the trailing chunk has no `\\n`, buffer it and\n * wait. Never parse a half-written line.\n * - Schema failures: a line that fails `trajectory_event_schema.parse` is\n * dropped and surfaced to `on_parse_error`. The stream keeps going.\n *\n * The watcher is fs.watch-based with a debounced re-read; on platforms where\n * fs.watch is flaky for appends we still catch up because the next tick\n * re-stats and re-reads from the saved offset.\n */\n\nimport { type FSWatcher, watch as fs_watch } from 'node:fs'\nimport { open, stat } from 'node:fs/promises'\nimport { trajectory_event_schema, type ParsedTrajectoryEvent } from '#core'\n\nexport type TailOptions = {\n readonly path: string\n readonly on_event: (event: ParsedTrajectoryEvent) => void\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n}\n\nexport type Tail = {\n readonly stop: () => void\n readonly drain: () => Promise<void>\n}\n\nexport function start_tail(options: TailOptions): Tail {\n const { path, on_event, on_parse_error, on_io_error } = options\n let offset = 0\n let buffer = ''\n let busy = false\n let pending = false\n let closed = false\n let watcher: FSWatcher | null = null\n let last_drain: Promise<void> = Promise.resolve()\n\n const handle_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = trajectory_event_schema.safeParse(parsed)\n if (!result.success) {\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n on_event(result.data)\n }\n\n const read_more = async (): Promise<void> => {\n let st\n try {\n st = await stat(path)\n } catch (err) {\n if (on_io_error) on_io_error(err)\n return\n }\n if (st.size < offset) {\n offset = 0\n buffer = ''\n }\n if (st.size === offset) return\n\n const fh = await open(path, 'r').catch((err: unknown) => {\n if (on_io_error) on_io_error(err)\n return null\n })\n if (!fh) return\n try {\n const length = st.size - offset\n const buf = Buffer.alloc(length)\n const { bytesRead } = await fh.read(buf, 0, length, offset)\n offset += bytesRead\n buffer += buf.subarray(0, bytesRead).toString('utf8')\n } finally {\n await fh.close()\n }\n\n let nl = buffer.indexOf('\\n')\n while (nl !== -1) {\n const line = buffer.slice(0, nl)\n buffer = buffer.slice(nl + 1)\n handle_line(line)\n nl = buffer.indexOf('\\n')\n }\n }\n\n const schedule = (): void => {\n if (closed) return\n if (busy) {\n pending = true\n return\n }\n busy = true\n last_drain = (async (): Promise<void> => {\n try {\n let keep_going = true\n while (keep_going) {\n pending = false\n await read_more()\n keep_going = pending && !closed\n }\n } finally {\n busy = false\n }\n })()\n }\n\n schedule()\n\n try {\n watcher = fs_watch(path, { persistent: true }, () => { schedule() })\n } catch (err) {\n if (on_io_error) on_io_error(err)\n }\n\n const stop = (): void => {\n closed = true\n if (watcher) {\n watcher.close()\n watcher = null\n }\n }\n\n const drain = async (): Promise<void> => {\n schedule()\n await last_drain\n }\n\n return { stop, drain }\n}\n","/**\n * `start_viewer` programmatic embed implementation.\n *\n * Spin up the server, optionally start tailing a JSONL file, and return a\n * handle that can stop both. `start_viewer` only depends on core's wire-format\n * schema; it never reaches into the engine, composites, or any provider.\n */\n\nimport { create_broadcaster } from './broadcast.js'\nimport { start_server, type ViewerServer } from './server.js'\nimport { start_tail, type Tail } from './tail.js'\n\nexport type StartViewerOptions = {\n readonly path?: string\n readonly host?: string\n readonly port?: number\n readonly buffer?: number\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\nexport type ViewerHandle = {\n readonly url: string\n readonly host: string\n readonly port: number\n readonly close: () => Promise<void>\n}\n\nexport async function start_viewer(options: StartViewerOptions = {}): Promise<ViewerHandle> {\n const host = options.host ?? '127.0.0.1'\n const port = options.port ?? 4242\n const buffer = options.buffer ?? 1000\n const broadcaster = create_broadcaster({\n buffer,\n ...(options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}),\n })\n const server = await start_server({\n broadcaster,\n host,\n port,\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n })\n\n let tail: Tail | null = null\n if (options.path !== undefined) {\n tail = start_tail({\n path: options.path,\n on_event: (event) => { broadcaster.emit(event) },\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n ...(options.on_io_error ? { on_io_error: options.on_io_error } : {}),\n })\n }\n\n return wrap_handle(server, tail, host, port)\n}\n\nfunction wrap_handle(\n server: ViewerServer,\n tail: Tail | null,\n host: string,\n port: number,\n): ViewerHandle {\n return {\n url: server.url,\n host,\n port,\n close: async () => {\n if (tail) tail.stop()\n await server.close()\n },\n }\n}\n","#!/usr/bin/env tsx\n/**\n * fascicle-viewer CLI.\n *\n * fascicle-viewer <path> # tail a JSONL file (primary)\n * fascicle-viewer --listen # accept HTTP push only\n * fascicle-viewer <path> --listen # both producers feed the same broadcaster\n *\n * Flags: --port <n> --host <h> --buffer <n> --no-open --help\n *\n * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT\n * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`\n * so the umbrella's bin shim can drive it from a bundled `dist/index.js`.\n */\n\nimport { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { parseArgs } from 'node:util'\nimport { fileURLToPath } from 'node:url'\nimport { start_viewer } from './index.js'\n\ntype CliArgs = {\n readonly path?: string\n readonly host: string\n readonly port: number\n readonly buffer: number\n readonly listen: boolean\n readonly open: boolean\n}\n\nconst HELP = `\\\nfascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.\n\nUsage:\n fascicle-viewer <path> tail a JSONL file\n fascicle-viewer --listen accept HTTP push only\n fascicle-viewer <path> --listen both producers feed the same broadcaster\n\nOptions:\n --port <n> port (default 4242)\n --host <h> bind host (default 127.0.0.1; --host 0.0.0.0 warns)\n --buffer <n> ring-buffer size (default 1000)\n --no-open do not open the browser\n --help show this message\n`\n\nfunction parse(argv: readonly string[]): CliArgs {\n const { values, positionals } = parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n port: { type: 'string', default: '4242' },\n host: { type: 'string', default: '127.0.0.1' },\n buffer: { type: 'string', default: '1000' },\n listen: { type: 'boolean', default: false },\n open: { type: 'boolean', default: true },\n 'no-open': { type: 'boolean', default: false },\n help: { type: 'boolean', default: false },\n },\n })\n if (values.help) {\n process.stdout.write(HELP)\n process.exit(0)\n }\n const port_raw = values.port ?? '4242'\n const buffer_raw = values.buffer ?? '1000'\n const port = Number.parseInt(port_raw, 10)\n const buffer = Number.parseInt(buffer_raw, 10)\n if (!Number.isFinite(port) || port <= 0) {\n process.stderr.write(`invalid --port: ${port_raw}\\n`)\n process.exit(2)\n }\n if (!Number.isFinite(buffer) || buffer <= 0) {\n process.stderr.write(`invalid --buffer: ${buffer_raw}\\n`)\n process.exit(2)\n }\n const path = positionals[0]\n const listen = values.listen ?? false\n if (path === undefined && !listen) {\n process.stderr.write('fascicle-viewer: a <path> is required unless --listen is set\\n')\n process.stderr.write(HELP)\n process.exit(2)\n }\n return {\n ...(path !== undefined ? { path } : {}),\n host: values.host ?? '127.0.0.1',\n port,\n buffer,\n listen,\n open: !values['no-open'] && (values.open ?? true),\n }\n}\n\nfunction open_browser(url: string): void {\n const platform = process.platform\n const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open'\n const args = platform === 'win32' ? ['/c', 'start', '\"\"', url] : [url]\n try {\n const child = spawn(cmd, args, { stdio: 'ignore', detached: true })\n child.on('error', () => {})\n child.unref()\n } catch {\n // Best-effort. The CLI logs the URL anyway.\n }\n}\n\nexport async function run_viewer_cli(argv: readonly string[]): Promise<void> {\n const args = parse(argv)\n\n if (args.path !== undefined && !existsSync(args.path)) {\n process.stderr.write(\n `fascicle-viewer: warning: ${args.path} does not exist yet — will pick up events once it is created\\n`,\n )\n }\n if (args.host === '0.0.0.0') {\n process.stderr.write(\n 'fascicle-viewer: warning: binding 0.0.0.0 — this dashboard has no auth and exposes whatever is in your trajectory stream\\n',\n )\n }\n\n const handle = await start_viewer({\n ...(args.path !== undefined ? { path: args.path } : {}),\n host: args.host,\n port: args.port,\n buffer: args.buffer,\n on_parse_error: (err, line) => {\n const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line\n process.stderr.write(\n `fascicle-viewer: skipped malformed line: ${preview}\\n ${describe_error(err)}\\n`,\n )\n },\n on_io_error: (err) => {\n process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\\n`)\n },\n })\n\n if (args.path !== undefined) process.stderr.write(`watching ${args.path}\\n`)\n if (args.listen || args.path === undefined) process.stderr.write(`listening for HTTP push on ${handle.url}/api/ingest\\n`)\n process.stderr.write(`viewer at ${handle.url}\\n`)\n\n if (args.open) open_browser(handle.url)\n\n const shutdown = async (): Promise<void> => {\n process.stderr.write('\\nfascicle-viewer: shutting down\\n')\n await handle.close()\n process.exit(0)\n }\n process.on('SIGINT', () => { void shutdown() })\n process.on('SIGTERM', () => { void shutdown() })\n}\n\nfunction describe_error(err: unknown): string {\n if (err instanceof Error) return err.message\n try {\n return JSON.stringify(err)\n } catch {\n return String(err)\n }\n}\n\n// ESM main-module detection. The bundler inlines this file into dist/index.js,\n// so a fragile suffix check (`endsWith('/cli.js')`) would fire whenever a\n// consumer's own entry script happened to be named cli.js — see\n// https://nodejs.org/api/esm.html#importmetaurl. Compare the resolved path of\n// this module against argv[1] so the auto-execute only fires when the file is\n// run directly (e.g. `tsx packages/viewer/src/cli.ts`), not when imported.\nconst invoked_directly =\n process.argv[1] !== undefined &&\n process.argv[1] === fileURLToPath(import.meta.url)\n\nif (invoked_directly) {\n void run_viewer_cli(process.argv.slice(2)).catch((err: unknown) => {\n process.stderr.write(`fascicle-viewer: ${describe_error(err)}\\n`)\n process.exit(1)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAS,uBACP,GAC6B;CAC7B,IAAI,EAAE,cAAc,KAAA,GAAW,OAAO,EAAE,OAAO,EAAE,MAAM;CACvD,IAAI,EAAE,mBAAmB,KAAA,GAAW,OAAO;EAAE,OAAO,EAAE;EAAO,OAAO,EAAE;CAAU;CAChF,OAAO;EAAE,OAAO,EAAE;EAAO,OAA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8B,OAAO,IAAI,cAAc;CACxH,QAAQ,OAAO,MAAM,aAAa,OAAO,IAAI,GAAG;CAEhD,IAAI,KAAK,MAAM,aAAa,OAAO,GAAG;CAEtC,MAAM,WAAW,YAA2B;EAC1C,QAAQ,OAAO,MAAM,oCAAoC;EACzD,MAAM,OAAO,MAAM;EACnB,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,GAAG,gBAAgB;EAAE,SAAc;CAAE,CAAC;CAC9C,QAAQ,GAAG,iBAAiB;EAAE,SAAc;CAAE,CAAC;AACjD;AAEA,SAAS,eAAe,KAAsB;CAC5C,IAAI,eAAe,OAAO,OAAO,IAAI;CACrC,IAAI;EACF,OAAO,KAAK,UAAU,GAAG;CAC3B,QAAQ;EACN,OAAO,OAAO,GAAG;CACnB;AACF;AAYA,IAHE,QAAQ,KAAK,OAAO,KAAA,KACpB,QAAQ,KAAK,OAAO,cAAc,OAAO,KAAK,GAAG,GAGjD,eAAoB,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,QAAiB;CACjE,QAAQ,OAAO,MAAM,oBAAoB,eAAe,GAAG,EAAE,GAAG;CAChE,QAAQ,KAAK,CAAC;AAChB,CAAC"}
1
+ {"version":3,"file":"index.js","names":["throw_if_aborted","e","round6","read_number","DEFAULT_BASE_URL","extract_error_message","response_error","rethrow_network_failure","consume_sse_response","SUPPORTED","SUPPORTED","to_user_content","to_assistant_message","extract_error_message","response_error","rethrow_network_failure","SUPPORTED","SUPPORTED","DEFAULT_BASE_URL","SUPPORTED","SUPPORTED","SUPPORTED","SUPPORTED","SUPPORTED","SUPPORTED","node_spawn","sum_usage","is_plain_object","ai_tool","fs_watch"],"sources":["../src/composites/adversarial.ts","../src/composites/consensus.ts","../src/composites/ensemble.ts","../src/composites/ensemble_step.ts","../src/composites/improve.ts","../src/composites/learn.ts","../src/composites/tournament.ts","../src/composites/bench.ts","../src/composites/judges.ts","../src/composites/regression.ts","../src/engine/pricing.ts","../src/engine/errors.ts","../src/engine/retry.ts","../src/engine/providers/types.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/providers/ai_sdk/telemetry.ts","../src/engine/providers/ai_sdk/invoke.ts","../src/engine/generate.ts","../src/engine/create_engine.ts","../src/model_call.ts","../src/forward_standard_env.ts","../src/viewer/broadcast.ts","../src/viewer/server.ts","../src/viewer/tail.ts","../src/viewer/start_viewer.ts","../src/viewer/cli.ts"],"sourcesContent":["/**\n * adversarial: build-and-critique loop.\n *\n * This file is the canonical example of how a user-built composite is\n * structured: the entire implementation is a composition of core\n * primitives. Read it as documentation.\n */\n\nimport { compose, loop, pipe, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type AdversarialBuildInput<input, candidate> = {\n readonly input: input\n readonly prior?: candidate\n readonly critique?: string\n}\n\nexport type AdversarialCritiqueResult = { readonly notes: string } & Record<string, unknown>\n\nexport type AdversarialResult<candidate> = {\n readonly candidate: candidate\n readonly converged: boolean\n readonly rounds: number\n}\n\nexport type AdversarialConfig<input, candidate> = {\n readonly name?: string\n readonly build: Step<AdversarialBuildInput<input, candidate>, candidate>\n readonly critique: Step<candidate, AdversarialCritiqueResult>\n readonly accept: (critique_result: AdversarialCritiqueResult) => boolean\n readonly max_rounds: number\n}\n\ntype AdversarialState<input, candidate> = {\n readonly input: input\n readonly candidate?: candidate\n readonly critique_notes?: string\n readonly last_critique?: AdversarialCritiqueResult\n}\n\n/**\n * Projects loop state into the build step's input.\n *\n * Omits `prior` and `critique` until they exist, so the first round's build\n * sees only the original input and later rounds see what came before.\n */\nfunction build_input_from_state<i, c>(\n s: AdversarialState<i, c>,\n): AdversarialBuildInput<i, c> {\n if (s.candidate === undefined) return { input: s.input }\n if (s.critique_notes === undefined) return { input: s.input, prior: s.candidate }\n return { input: s.input, prior: s.candidate, critique: s.critique_notes }\n}\n\n/**\n * Builds a Step that runs up to `max_rounds` iterations of build ->\n * critique -> accept.\n *\n * Each round builds a candidate (receiving the prior candidate and critique\n * notes when available), critiques it, then checks `accept(critique_result)`.\n * Returns `{ candidate, converged, rounds }`. Does not throw on\n * non-convergence; `converged: false` reports it instead.\n *\n * Implemented as a `compose`d `loop` whose body builds a new candidate and\n * whose guard runs the critique step and checks `accept`. State is threaded\n * through `scope`/`stash`/`use` so the build and critique steps remain\n * unmodified user-supplied `Step` values.\n */\nexport function adversarial<input, candidate>(\n config: AdversarialConfig<input, candidate>,\n): Step<input, AdversarialResult<candidate>> {\n const { build, critique, accept, max_rounds } = config\n\n type S = AdversarialState<input, candidate>\n\n const body: Step<S, S> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('to_build_input', (s: S) => build_input_from_state(s)),\n build,\n use(['state'], (vars, candidate: candidate) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return { ...prior, candidate }\n }),\n ])\n\n const guard: Step<S, { stop: boolean; state: S }> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('extract_candidate', (s: S) => {\n if (s.candidate === undefined) {\n throw new Error('adversarial: guard reached without a candidate')\n }\n return s.candidate\n }),\n critique,\n use(['state'], (vars, critique_result: AdversarialCritiqueResult) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return {\n stop: accept(critique_result),\n state: {\n ...prior,\n last_critique: critique_result,\n critique_notes: critique_result.notes,\n },\n }\n }),\n ])\n\n const inner = pipe(\n loop<input, S, candidate>({\n init: (input) => ({ input }),\n body,\n guard,\n finish: (s) => {\n if (s.candidate === undefined) {\n throw new Error('adversarial: finished without a candidate')\n }\n return s.candidate\n },\n max_rounds,\n }),\n (result) => ({\n candidate: result.value,\n converged: result.converged,\n rounds: result.rounds,\n }),\n )\n\n return compose(config.name ?? 'adversarial', inner)\n}\n","/**\n * consensus: run-until-agreement composite over concurrent members.\n */\n\nimport { compose, loop, parallel, pipe, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type ConsensusConfig<i, o> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly agree: (results: Record<string, o>) => boolean\n readonly max_rounds: number\n}\n\nexport type ConsensusResult<o> = {\n readonly result: Record<string, o>\n readonly converged: boolean\n}\n\ntype ConsensusState<i, o> = {\n readonly input: i\n readonly results: Record<string, o>\n}\n\n/**\n * Builds a Step that runs every member concurrently with the same input\n * until `agree(results)` accepts a round.\n *\n * On agreement, returns the round's results with `converged: true`.\n * Otherwise re-runs all members up to `max_rounds` times and returns the\n * last results with `converged: false` if no agreement is reached.\n *\n * Implemented as a `compose`d `loop` whose body runs `parallel(members)` and\n * whose guard evaluates `agree`. State carries the original input alongside\n * the most recent results so each round receives the same input.\n */\nexport function consensus<i, o>(\n config: ConsensusConfig<i, o>,\n): Step<i, ConsensusResult<o>> {\n const { members, agree, max_rounds } = config\n\n type S = ConsensusState<i, o>\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const round_step = parallel(members) as Step<i, Record<string, o>>\n\n const body: Step<S, S> = scope([\n stash('state', step('snapshot', (s: S) => s)),\n step('extract_input', (s: S) => s.input),\n round_step,\n use(['state'], (vars, results: Record<string, o>) => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars['state'] as S\n return { ...prior, results }\n }),\n ])\n\n const guard: Step<S, { stop: boolean; state: S }> = step('agree', (s: S) => ({\n stop: agree(s.results),\n state: s,\n }))\n\n const inner = pipe(\n loop<i, S, Record<string, o>>({\n init: (input) => ({ input, results: {} }),\n body,\n guard,\n finish: (s) => s.results,\n max_rounds,\n }),\n (result) => ({ result: result.value, converged: result.converged }),\n )\n\n return compose(config.name ?? 'consensus', inner)\n}\n","/**\n * ensemble: N-of-M pick-best with a plain-function scorer.\n */\n\nimport { compose, parallel, sequence, step } from '#core'\nimport type { Step } from '#core'\n\nexport type EnsembleConfig<i, o> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly score: (result: o, member_id: string) => number | Promise<number>\n readonly select?: 'max' | 'min'\n}\n\nexport type EnsembleResult<o> = {\n readonly winner: o\n readonly scores: Record<string, number>\n}\n\n/**\n * Builds a Step that runs every member concurrently with the same input,\n * scores each result, and returns the winner plus the complete score map.\n *\n * `select` picks the highest (`'max'`, the default) or lowest (`'min'`)\n * score. Tie-breaking is \"any tied result is acceptable\": the first member\n * (in `members` key order) holding the best score wins.\n *\n * Implemented as a `compose`d `sequence` of `parallel(members)` followed by\n * a single picking step. Cancellation, fan-out, and abort propagation come\n * from `parallel`'s own contract.\n */\nexport function ensemble<i, o>(\n config: EnsembleConfig<i, o>,\n): Step<i, EnsembleResult<o>> {\n const select: 'max' | 'min' = config.select ?? 'max'\n const score_fn = config.score\n const keys = Object.keys(config.members)\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const fan_out = parallel(config.members) as Step<i, Record<string, o>>\n\n const pick = step('pick_winner', async (results: Record<string, o>) => {\n const scores: Record<string, number> = {}\n for (const k of keys) {\n const value = results[k]\n if (value === undefined) continue\n scores[k] = await score_fn(value, k)\n }\n \n let winner_key: string | undefined = undefined\n let winner_score: number | undefined = undefined\n for (const k of keys) {\n const current = scores[k]\n if (current === undefined) continue\n if (winner_score === undefined) {\n winner_key = k\n winner_score = current\n continue\n }\n const better = select === 'max' ? current > winner_score : current < winner_score\n if (better) {\n winner_key = k\n winner_score = current\n }\n }\n \n if (winner_key === undefined) {\n throw new Error('ensemble: no members produced a result')\n }\n const winner = results[winner_key]\n if (winner === undefined) {\n throw new Error('ensemble: winner missing from results')\n }\n return { winner, scores }\n })\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const inner = sequence([fan_out, pick]) as Step<i, EnsembleResult<o>>\n\n return compose(config.name ?? 'ensemble', inner)\n}\n","/**\n * ensemble_step: N-of-M pick-best with a Step-based scorer.\n */\n\nimport { compose, map, parallel, scope, stash, step, use } from '#core'\nimport type { Step } from '#core'\n\nexport type EnsembleStepConfig<i, o, ranked> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly score: Step<o, ranked>\n readonly rank_by: (r: ranked) => number\n readonly select?: 'max' | 'min'\n}\n\nexport type EnsembleStepResult<o, ranked> = {\n readonly winner_id: string\n readonly winner: o\n readonly winner_scored: ranked\n readonly scored: Record<string, ranked>\n}\n\n// Scope variable keys, underscore-prefixed to avoid colliding with any\n// stashes a user-supplied step might set in the same scope chain.\nconst RESULTS_KEY = '__ensemble_step_results'\nconst ITEM_KEY = '__ensemble_step_item'\n\ntype Pair<o> = { readonly id: string; readonly value: o }\ntype ScoredPair<ranked> = { readonly id: string; readonly scored: ranked }\n\n/**\n * Builds a Step that runs every member concurrently, scores each result via\n * a scoring `Step`, and returns the best-ranking winner.\n *\n * Sibling of `ensemble` for the case where scoring is itself a `Step` (e.g.\n * a separate model call, a sub-flow, anything that wants its own trajectory\n * span and abort routing). The `score` step is dispatched once per member\n * result; `rank_by` projects a number out of the structured scored output;\n * `select` picks the highest (`'max'`, default) or lowest (`'min'`) rank.\n *\n * The result carries `winner_scored`, the structured output from the round's\n * scoring run preserved verbatim, so callers never pay to re-score the\n * winner. `scored` holds the structured score for every member.\n *\n * Implemented as a `compose`d `scope` over (`stash(parallel(members))` ->\n * `to_pairs` -> `map(score per result, threading id)` -> `use` to pick the\n * winner). Cancellation, fan-out, and abort propagation come from the\n * underlying `parallel` and `map` contracts.\n */\nexport function ensemble_step<i, o, ranked>(\n config: EnsembleStepConfig<i, o, ranked>,\n): Step<i, EnsembleStepResult<o, ranked>> {\n const { members, score, rank_by } = config\n const select: 'max' | 'min' = config.select ?? 'max'\n const keys = Object.keys(members)\n\n if (keys.length === 0) {\n throw new Error('ensemble_step: at least one member required')\n }\n\n const fan_out = parallel(members)\n\n const score_one = scope([\n stash(ITEM_KEY, step('ensemble_step_item_snapshot', (item: Pair<o>) => item)),\n step('ensemble_step_extract_value', (item: Pair<o>) => item.value),\n score,\n use([ITEM_KEY], (vars, scored: ranked): ScoredPair<ranked> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const item = vars[ITEM_KEY] as Pair<o>\n return { id: item.id, scored }\n }),\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<Pair<o>, ScoredPair<ranked>>\n\n const to_pairs = step(\n 'ensemble_step_to_pairs',\n (results: Record<string, o>): ReadonlyArray<Pair<o>> => {\n const out: Pair<o>[] = []\n for (const id of keys) {\n if (id in results) {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n out.push({ id, value: results[id] as o })\n }\n }\n return out\n },\n )\n\n const score_each = map<ReadonlyArray<Pair<o>>, Pair<o>, ScoredPair<ranked>>({\n items: (pairs) => pairs,\n do: score_one,\n })\n\n const pick = use(\n [RESULTS_KEY],\n (vars, scored_pairs: ReadonlyArray<ScoredPair<ranked>>): EnsembleStepResult<o, ranked> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const results = vars[RESULTS_KEY] as Record<string, o>\n const scored: Record<string, ranked> = {}\n let winner_id: string | undefined\n let winner_rank: number | undefined\n let winner_scored: ranked | undefined\n for (const pair of scored_pairs) {\n scored[pair.id] = pair.scored\n const rank = rank_by(pair.scored)\n const better =\n winner_rank === undefined\n ? true\n : select === 'max'\n ? rank > winner_rank\n : rank < winner_rank\n if (better) {\n winner_id = pair.id\n winner_rank = rank\n winner_scored = pair.scored\n }\n }\n if (winner_id === undefined || winner_scored === undefined) {\n throw new Error('ensemble_step: no members produced a result')\n }\n const winner = results[winner_id]\n if (winner === undefined) {\n throw new Error('ensemble_step: winner missing from results')\n }\n return { winner_id, winner, winner_scored, scored }\n },\n )\n\n const inner = scope([\n stash(RESULTS_KEY, fan_out),\n to_pairs,\n score_each,\n pick,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<i, EnsembleStepResult<o, ranked>>\n\n return compose(config.name ?? 'ensemble_step', inner)\n}\n","/**\n * improve: bounded online self-improvement loop.\n *\n * The *online* counterpart to `learn`: where `learn` reflects on recorded\n * trajectories offline, `improve` runs a propose/score loop live inside a\n * single run. The amplify example is a domain-specific consumer of this\n * same pattern (filesystem mutation, test-suite gates, subprocess\n * research); `improve` strips those opinions out so any domain can plug in\n * its own `propose` and `score` steps.\n */\n\nimport { compose, loop, scope, step, stash, use } from '#core'\nimport type { LoopResult, Step } from '#core'\nimport { ensemble_step } from './ensemble_step.js'\n\nexport type Candidate<c> = {\n readonly content: c\n readonly proposer_id: string\n readonly rationale?: string\n}\n\nexport type ScoredCandidate<c> = {\n readonly candidate: Candidate<c>\n readonly score: number\n readonly accepted: boolean\n readonly reason?: string\n}\n\nexport type Lesson = {\n readonly round: number\n readonly proposer_id: string\n readonly reason: string\n}\n\nexport type ImproveRoundInput<c> = {\n readonly parent: c\n readonly parent_score: number\n readonly round: number\n readonly lessons: ReadonlyArray<Lesson>\n}\n\nexport type ImproveBudget = {\n readonly max_rounds: number\n readonly max_wallclock_ms?: number\n readonly patience: number\n}\n\nexport type ImproveConfig<i, c> = {\n readonly name?: string\n readonly seed: Step<i, { readonly content: c; readonly score: number }>\n readonly propose: Step<ImproveRoundInput<c>, Candidate<c>>\n readonly score: Step<Candidate<c>, ScoredCandidate<c>>\n readonly budget: ImproveBudget\n readonly epsilon?: number\n readonly proposers_per_round?: number\n readonly lessons_capacity?: number\n}\n\nexport type HistoryEntry<c> = {\n readonly round: number\n readonly winner: ScoredCandidate<c>\n readonly accepted: boolean\n}\n\nexport type ImproveResult<c> = {\n readonly best: { readonly content: c; readonly score: number }\n readonly rounds_used: number\n readonly stopped_by: 'budget' | 'plateau'\n readonly history: ReadonlyArray<HistoryEntry<c>>\n}\n\n// Scope variable key for the pre-round state snapshot, underscore-prefixed\n// to avoid colliding with stashes set by user-supplied steps.\nconst PRIOR_KEY = '__improve_prior'\n\ntype ImproveState<c> = {\n readonly parent: c\n readonly parent_score: number\n readonly round: number\n readonly rounds_since_progress: number\n readonly started_at_ms: number\n readonly history: ReadonlyArray<HistoryEntry<c>>\n readonly lessons: ReadonlyArray<Lesson>\n readonly stopped_by?: 'budget' | 'plateau'\n}\n\n/**\n * Builds a Step that runs a round-bounded loop threading a `parent`\n * candidate through repeated propose -> score -> accept/reject cycles.\n *\n * Acceptance requires both a hard gate (`scored.accepted`) and an\n * epsilon-improvement test (`scored.score > parent_score + epsilon`).\n * Rejected rounds with a `reason` feed a bounded lessons list back into the\n * next round's input. Plateau detection stops the loop early when no\n * progress has been made for `patience` rounds; an optional wall-clock\n * budget caps total runtime.\n *\n * Implemented as a `compose`d `scope` of (seed) -> (init state) -> (loop) ->\n * (unwrap). The loop body is itself a small `scope` that snapshots prior\n * state, builds a round input, dispatches the proposers + scorer via\n * `ensemble_step`, and merges the outcome back into state via `use`.\n * State threading is the entire job.\n */\nexport function improve<i, c>(\n config: ImproveConfig<i, c>,\n): Step<i, ImproveResult<c>> {\n const { seed, propose, score, budget } = config\n const epsilon = config.epsilon ?? 0\n const proposers_per_round = Math.max(1, config.proposers_per_round ?? 1)\n const lessons_capacity = Math.max(0, config.lessons_capacity ?? 5)\n const { max_rounds, max_wallclock_ms, patience } = budget\n\n const proposers: Record<string, Step<ImproveRoundInput<c>, Candidate<c>>> = {}\n for (let i = 0; i < proposers_per_round; i += 1) {\n proposers[`p${String(i)}`] = propose\n }\n\n const round_ensemble = ensemble_step<\n ImproveRoundInput<c>,\n Candidate<c>,\n ScoredCandidate<c>\n >({\n name: 'improve_round',\n members: proposers,\n score,\n rank_by: (s) => s.score,\n })\n\n type RoundResult = {\n readonly winner_id: string\n readonly winner: Candidate<c>\n readonly winner_scored: ScoredCandidate<c>\n readonly scored: Record<string, ScoredCandidate<c>>\n }\n\n const project_round = use(\n [PRIOR_KEY],\n (vars, ensemble_result: RoundResult, ctx): ScoredCandidate<c> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars[PRIOR_KEY] as ImproveState<c>\n const round = prior.round + 1\n for (const slot_id of Object.keys(ensemble_result.scored)) {\n const scored = ensemble_result.scored[slot_id]\n if (scored === undefined) continue\n ctx.trajectory.record({\n kind: 'improve.candidate',\n round,\n proposer_id: slot_id,\n score: scored.score,\n accepted: scored.accepted,\n ...(scored.reason === undefined ? {} : { reason: scored.reason }),\n })\n }\n const w = ensemble_result.winner_scored\n return {\n ...w,\n candidate: { ...w.candidate, proposer_id: ensemble_result.winner_id },\n }\n },\n )\n\n const init_state = step(\n 'improve_init_state',\n (seed_result: { content: c; score: number }): ImproveState<c> => ({\n parent: seed_result.content,\n parent_score: seed_result.score,\n round: 0,\n rounds_since_progress: 0,\n started_at_ms: Date.now(),\n history: [],\n lessons: [],\n }),\n )\n\n const to_round_input = step(\n 'improve_to_round_input',\n (s: ImproveState<c>, ctx): ImproveRoundInput<c> => {\n const round = s.round + 1\n ctx.trajectory.record({\n kind: 'improve.round_start',\n round,\n parent_score: s.parent_score,\n lessons_count: s.lessons.length,\n })\n return {\n parent: s.parent,\n parent_score: s.parent_score,\n round,\n lessons: s.lessons,\n }\n },\n )\n\n const merge_outcome = use(\n [PRIOR_KEY],\n (vars, scored: ScoredCandidate<c>, ctx): ImproveState<c> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const prior = vars[PRIOR_KEY] as ImproveState<c>\n const next_round = prior.round + 1\n const better = scored.score > prior.parent_score + epsilon\n const accepted = scored.accepted && better\n const next_lessons = !accepted && scored.reason !== undefined\n ? [\n ...prior.lessons,\n {\n round: next_round,\n proposer_id: scored.candidate.proposer_id,\n reason: scored.reason,\n },\n ].slice(-lessons_capacity)\n : prior.lessons\n ctx.trajectory.record({\n kind: accepted ? 'improve.accept' : 'improve.reject',\n round: next_round,\n proposer_id: scored.candidate.proposer_id,\n score: scored.score,\n prior_score: prior.parent_score,\n ...(accepted ? { delta: scored.score - prior.parent_score } : {}),\n ...(scored.reason === undefined ? {} : { reason: scored.reason }),\n })\n return {\n parent: accepted ? scored.candidate.content : prior.parent,\n parent_score: accepted ? scored.score : prior.parent_score,\n round: next_round,\n rounds_since_progress: accepted ? 0 : prior.rounds_since_progress + 1,\n started_at_ms: prior.started_at_ms,\n history: [\n ...prior.history,\n { round: next_round, winner: scored, accepted },\n ],\n lessons: next_lessons,\n }\n },\n )\n\n const body = scope([\n stash(PRIOR_KEY, step('improve_snapshot', (s: ImproveState<c>) => s)),\n to_round_input,\n round_ensemble,\n project_round,\n merge_outcome,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<ImproveState<c>, ImproveState<c>>\n\n const guard = step(\n 'improve_guard',\n (s: ImproveState<c>): { stop: boolean; state: ImproveState<c> } => {\n if (s.rounds_since_progress >= patience) {\n return { stop: true, state: { ...s, stopped_by: 'plateau' } }\n }\n if (\n max_wallclock_ms !== undefined &&\n Date.now() - s.started_at_ms >= max_wallclock_ms\n ) {\n return { stop: true, state: { ...s, stopped_by: 'budget' } }\n }\n return { stop: false, state: s }\n },\n )\n\n const round_loop = loop<ImproveState<c>, ImproveState<c>, ImproveResult<c>>({\n init: (s) => s,\n body,\n guard,\n finish: (s): ImproveResult<c> => ({\n best: { content: s.parent, score: s.parent_score },\n rounds_used: s.round,\n stopped_by: s.stopped_by ?? 'budget',\n history: s.history,\n }),\n max_rounds,\n })\n\n const unwrap = step(\n 'improve_unwrap',\n (result: LoopResult<ImproveResult<c>>, ctx): ImproveResult<c> => {\n ctx.trajectory.record({\n kind: 'improve.stop',\n stopped_by: result.value.stopped_by,\n rounds_used: result.value.rounds_used,\n final_score: result.value.best.score,\n })\n return result.value\n },\n )\n\n const inner = scope([\n seed,\n init_state,\n round_loop,\n unwrap,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n ]) as Step<i, ImproveResult<c>>\n\n return compose(config.name ?? 'improve', inner)\n}\n","/**\n * learn: offline self-improvement composer.\n *\n * `learn({ flow, source, analyzer })` reads recorded trajectory events from\n * past runs of `flow`, hands them to a user-supplied `analyzer` step alongside\n * `describe(flow)`, and returns the analyzer's proposals plus summary metadata\n * (events considered, distinct run ids).\n *\n * The amplify example is the *online* counterpart of this pattern: propose →\n * score → accept/reject inside a single run. `learn` is the *offline*\n * counterpart: reflect on what already happened across one or many recorded\n * runs without an evaluator in the loop.\n *\n * Implemented as a `compose`d `scope` of (compute meta) → (build LearnInput) →\n * (analyzer) → (wrap result with meta). No engine dependency; the analyzer\n * decides how to use the events.\n *\n * Three source kinds: `events` (in-memory), `paths` (explicit JSONL files),\n * `dir` (recursive *.jsonl walk). File reads honor `ctx.abort` at file-level\n * granularity; malformed lines are skipped and surface as `learn.parse_error`\n * trajectory events with 1-indexed line offsets. When `max_events` clips the\n * filtered set, a `learn.truncated` event records `available`, `kept`, and the\n * configured cap.\n */\n\nimport { readFile, readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n aborted_error,\n compose,\n describe,\n scope,\n stash,\n step,\n trajectory_event_schema,\n use,\n} from '#core'\nimport type { RunContext, Step, TrajectoryEvent } from '#core'\n\nexport type TrajectorySource =\n | { readonly kind: 'events'; readonly events: ReadonlyArray<TrajectoryEvent> }\n | { readonly kind: 'paths'; readonly paths: ReadonlyArray<string> }\n | { readonly kind: 'dir'; readonly dir: string }\n\nexport type LearnInput = {\n readonly flow_description: string\n readonly events: ReadonlyArray<TrajectoryEvent>\n readonly prior?: unknown\n}\n\nexport type Improvement = {\n readonly target: string\n readonly kind: 'prompt' | 'config' | 'structure' | 'note'\n readonly rationale: string\n readonly suggestion: string\n}\n\nexport type LearnConfig<i extends LearnInput, o> = {\n readonly name?: string\n readonly flow: Step<unknown, unknown>\n readonly source: TrajectorySource\n readonly analyzer: Step<i, o>\n readonly filter?: (event: TrajectoryEvent) => boolean\n readonly max_events?: number\n}\n\nexport type LearnResult<o> = {\n readonly proposals: o\n readonly events_considered: number\n readonly run_ids: ReadonlyArray<string>\n}\n\nconst DEFAULT_MAX_EVENTS = 10_000\nconst META_KEY = '__learn_meta'\n\ntype LearnMeta = {\n readonly events_considered: number\n readonly run_ids: ReadonlyArray<string>\n}\n\ntype MetaPlus = LearnMeta & {\n readonly events: ReadonlyArray<TrajectoryEvent>\n readonly prior: unknown\n}\n\n/**\n * Recursively collect every `.jsonl` file path under a directory.\n */\nasync function walk_jsonl(dir: string): Promise<string[]> {\n const out: string[] = []\n const entries = await readdir(dir, { withFileTypes: true })\n for (const entry of entries) {\n const full = join(dir, entry.name)\n if (entry.isDirectory()) {\n out.push(...(await walk_jsonl(full)))\n } else if (entry.isFile() && entry.name.endsWith('.jsonl')) {\n out.push(full)\n }\n }\n return out\n}\n\n/**\n * Parse one JSONL file into validated trajectory events.\n *\n * Malformed JSON lines and lines that fail schema validation are skipped,\n * each recorded as a `learn.parse_error` event with a 1-indexed line number,\n * so a single corrupt line never sinks an analysis run.\n */\nasync function read_jsonl(file_path: string, ctx: RunContext): Promise<TrajectoryEvent[]> {\n const content = await readFile(file_path, 'utf8')\n const lines = content.split('\\n')\n const events: TrajectoryEvent[] = []\n for (let i = 0; i < lines.length; i += 1) {\n const raw = lines[i]\n if (raw === undefined || raw.trim() === '') continue\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n ctx.trajectory.record({ kind: 'learn.parse_error', path: file_path, line: i + 1 })\n continue\n }\n const result = trajectory_event_schema.safeParse(parsed)\n if (result.success) {\n events.push(result.data)\n } else {\n ctx.trajectory.record({ kind: 'learn.parse_error', path: file_path, line: i + 1 })\n }\n }\n return events\n}\n\n/**\n * Throw the abort reason (wrapped in `aborted_error` if needed) when the run\n * has been cancelled.\n */\nfunction throw_if_aborted(ctx: RunContext): void {\n if (!ctx.abort.aborted) return\n const reason = ctx.abort.reason\n if (reason instanceof aborted_error) throw reason\n throw new aborted_error('aborted', reason === undefined ? {} : { reason })\n}\n\n/**\n * Materialize a `TrajectorySource` into an event array.\n *\n * `dir` sources walk recursively and sort paths for deterministic order.\n * File-backed sources check `ctx.abort` between files, so cancellation lands\n * at file-level granularity.\n */\nasync function resolve_events(\n source: TrajectorySource,\n ctx: RunContext,\n): Promise<ReadonlyArray<TrajectoryEvent>> {\n if (source.kind === 'events') return source.events\n\n const file_paths =\n source.kind === 'paths' ? [...source.paths] : (await walk_jsonl(source.dir)).toSorted()\n\n const all: TrajectoryEvent[] = []\n for (const p of file_paths) {\n throw_if_aborted(ctx)\n const events = await read_jsonl(p, ctx)\n all.push(...events)\n }\n return all\n}\n\n/**\n * List the distinct `run_id` values in the events, in first-seen order.\n */\nfunction collect_run_ids(events: ReadonlyArray<TrajectoryEvent>): ReadonlyArray<string> {\n const seen = new Set<string>()\n const out: string[] = []\n for (const event of events) {\n const id = event['run_id']\n if (typeof id === 'string' && !seen.has(id)) {\n seen.add(id)\n out.push(id)\n }\n }\n return out\n}\n\n/**\n * Build the offline self-improvement step.\n *\n * Composes a scope that resolves and caps the recorded events, builds the\n * `LearnInput` (including `describe(flow)`), runs the user's analyzer, and\n * wraps its proposals with the stashed meta (event count, run ids) into a\n * `LearnResult`.\n */\nexport function learn<i extends LearnInput, o>(\n config: LearnConfig<i, o>,\n): Step<unknown, LearnResult<o>> {\n const { flow, source, analyzer, filter } = config\n const max = config.max_events ?? DEFAULT_MAX_EVENTS\n\n const compute_meta = step(\n 'learn_compute_meta',\n async (prior: unknown, ctx): Promise<MetaPlus> => {\n const all = await resolve_events(source, ctx)\n const filtered = filter ? all.filter(filter) : all\n const truncated = filtered.length > max\n const capped = truncated ? filtered.slice(0, max) : filtered\n if (truncated) {\n ctx.trajectory.record({\n kind: 'learn.truncated',\n available: filtered.length,\n kept: capped.length,\n max_events: max,\n })\n }\n return {\n events_considered: capped.length,\n run_ids: collect_run_ids(capped),\n events: capped,\n prior,\n }\n },\n )\n\n const build_input = step(\n 'learn_build_input',\n (meta: MetaPlus): LearnInput => ({\n flow_description: describe(flow),\n events: meta.events,\n prior: meta.prior,\n }),\n )\n\n const wrap_result = use(\n [META_KEY],\n (vars, proposals: o, ctx): LearnResult<o> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const meta = vars[META_KEY] as LearnMeta\n ctx.trajectory.record({\n kind: 'learn.summary',\n events_considered: meta.events_considered,\n run_ids: meta.run_ids,\n })\n return {\n proposals,\n events_considered: meta.events_considered,\n run_ids: meta.run_ids,\n }\n },\n )\n\n const inner = scope([\n stash(META_KEY, compute_meta),\n build_input,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n analyzer as unknown as Step<unknown, unknown>,\n wrap_result,\n ])\n\n return compose(config.name ?? 'learn', inner)\n}\n","/**\n * tournament: pairwise bracket.\n *\n * `tournament({ members, compare })` runs every member, then pairs them off\n * in a single-elimination bracket. `compare(a, b)` returns which result\n * advances. An odd member count yields one bye per affected round. Returns\n * `{ winner, bracket }` where `bracket` lists every match record.\n *\n * Implemented as a `compose`d `sequence` of `parallel(members)` followed\n * by a single bracket-reduction step. Cancellation, fan-out, and abort\n * propagation come from `parallel`'s contract; the bracket step only runs\n * after all members settle.\n */\n\nimport { compose, parallel, sequence, step } from '#core'\nimport type { Step } from '#core'\n\nexport type BracketRecord = {\n readonly round: number\n readonly a_id: string\n readonly b_id: string\n readonly winner_id: string\n}\n\nexport type TournamentConfig<i, o> = {\n readonly name?: string\n readonly members: Record<string, Step<i, o>>\n readonly compare: (a: o, b: o) => Promise<'a' | 'b'> | 'a' | 'b'\n}\n\nexport type TournamentResult<o> = {\n readonly winner: o\n readonly bracket: ReadonlyArray<BracketRecord>\n}\n\n/**\n * Build a single-elimination bracket step over named members.\n *\n * All members run concurrently via `parallel`; the bracket step then reduces\n * survivors round by round with `compare`, recording every match. Requires at\n * least one member so a winner always exists.\n */\nexport function tournament<i, o>(\n config: TournamentConfig<i, o>,\n): Step<i, TournamentResult<o>> {\n const compare_fn = config.compare\n const keys = Object.keys(config.members)\n\n if (keys.length === 0) {\n throw new Error('tournament: at least one member required')\n }\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const fan_out = parallel(config.members) as Step<i, Record<string, o>>\n\n const bracket_step = step('bracket', async (results: Record<string, o>) => {\n let current: string[] = [...keys]\n const bracket: BracketRecord[] = []\n let round = 0\n \n while (current.length > 1) {\n round += 1\n const next_round: string[] = []\n for (let i = 0; i < current.length; i += 2) {\n const a_id = current[i]\n const b_id = current[i + 1]\n if (a_id === undefined) continue\n if (b_id === undefined) {\n next_round.push(a_id)\n continue\n }\n const a_val = results[a_id]\n const b_val = results[b_id]\n if (a_val === undefined || b_val === undefined) {\n throw new Error('tournament: missing result for match')\n }\n const pick = await compare_fn(a_val, b_val)\n const winner_id = pick === 'a' ? a_id : b_id\n bracket.push({ round, a_id, b_id, winner_id })\n next_round.push(winner_id)\n }\n current = next_round\n }\n \n const final_id = current[0]\n if (final_id === undefined) {\n throw new Error('tournament: no winner')\n }\n const winner = results[final_id]\n if (winner === undefined) {\n throw new Error('tournament: winner missing from results')\n }\n return { winner, bracket }\n })\n\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const inner = sequence([fan_out, bracket_step]) as Step<i, TournamentResult<o>>\n\n return compose(config.name ?? 'tournament', inner)\n}\n","/**\n * bench: run a flow against a fixture set, score each result, return a report.\n *\n * Online counterpart to `learn`: where `learn` reflects on past trajectories\n * after the fact, `bench` runs the flow live against fresh cases and judges\n * each output.\n */\n\nimport { mkdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { run } from '#core'\nimport type { Step, TrajectoryEvent, TrajectoryLogger } from '#core'\nimport { filesystem_logger, http_logger, tee_logger } from '#adapters'\n\nexport type Score = { readonly score: number; readonly reason?: string }\n\nexport type BenchCase<I> = {\n readonly id: string\n readonly input: I\n readonly meta?: Readonly<Record<string, unknown>>\n}\n\nexport type JudgeArgs<I, O> = {\n readonly input: I\n readonly output: O\n readonly meta?: Readonly<Record<string, unknown>>\n}\n\nexport type Judge<I, O, S = Score> = Step<JudgeArgs<I, O>, S | undefined>\n\nexport type CaseResult<I = unknown, O = unknown, S = Score> = {\n readonly case_id: string\n readonly ok: boolean\n readonly output?: O\n readonly error?: string\n readonly scores: Record<string, S>\n readonly duration_ms: number\n readonly cost_usd: number\n readonly trajectory_path?: string\n readonly _input?: I\n}\n\nexport type BenchSummary = {\n readonly pass_rate: number\n readonly mean_scores: Record<string, number>\n readonly total_duration_ms: number\n readonly total_cost_usd: number\n readonly mean_cost_usd: number\n}\n\nexport type BenchReport<I = unknown, O = unknown, S = Score> = {\n readonly flow_name: string\n readonly run_id: string\n readonly cases: ReadonlyArray<CaseResult<I, O, S>>\n readonly summary: BenchSummary\n}\n\nexport type BenchOptions = {\n readonly concurrency?: number\n readonly on_case?: (result: CaseResult) => void\n readonly trajectory_dir?: string\n readonly live_url?: string\n readonly run_id?: string\n readonly install_signal_handlers?: boolean\n}\n\n/**\n * Runs `flow` against every case, judges each output, and produces a\n * `BenchReport` you can compare against a committed baseline via\n * `regression_compare`.\n *\n * Each case becomes one `run(flow, case.input, ...)`. Per-case observability:\n * - `trajectory_dir` writes `${dir}/${case.id}.jsonl` via `filesystem_logger`\n * - `live_url` POSTs each event via `http_logger` to a viewer's /api/ingest\n * - both can be combined; bench tees them with an internal cost tracker\n *\n * Cost is tracked per-case in-process by intercepting `kind: 'cost'` events\n * on the trajectory pipeline, so the cost number matches what would be on\n * disk even when no `trajectory_dir` is set.\n *\n * Judges run as Steps after each case, with the same trajectory logger so\n * judge spans land in the case's trajectory file (or push). A judge that\n * throws or returns undefined abstains: the entry is omitted from\n * `case.scores` and the case does not contribute to that judge's mean.\n */\nexport async function bench<I, O, S = Score>(\n flow: Step<I, O>,\n cases: ReadonlyArray<BenchCase<I>>,\n judges: Record<string, Judge<I, O, S>>,\n options: BenchOptions = {},\n): Promise<BenchReport<I, O, S>> {\n const run_id = options.run_id ?? `bench-${String(Date.now())}-${random_suffix()}`\n const flow_name = describe_flow_name(flow)\n const concurrency = resolve_concurrency(options.concurrency, cases.length)\n const install_signal_handlers = options.install_signal_handlers ?? false\n\n if (options.trajectory_dir !== undefined) {\n await mkdir(options.trajectory_dir, { recursive: true })\n }\n\n const judge_entries = Object.entries(judges)\n\n const run_one = async (bc: BenchCase<I>): Promise<CaseResult<I, O, S>> => {\n const trajectory_path =\n options.trajectory_dir === undefined\n ? undefined\n : join(options.trajectory_dir, `${bc.id}.jsonl`)\n const sinks: TrajectoryLogger[] = []\n if (trajectory_path !== undefined) {\n sinks.push(filesystem_logger({ output_path: trajectory_path }))\n }\n if (options.live_url !== undefined) {\n sinks.push(http_logger({ url: options.live_url }))\n }\n const cost_tracker = create_cost_tracker()\n const case_logger: TrajectoryLogger =\n sinks.length === 0\n ? cost_tracker.logger\n : tee_logger(...sinks, cost_tracker.logger)\n\n const start = Date.now()\n let output: O | undefined\n let error: string | undefined\n let ok = false\n try {\n output = await run(flow, bc.input, {\n trajectory: case_logger,\n install_signal_handlers,\n })\n ok = true\n } catch (err) {\n error = err instanceof Error ? err.message : String(err)\n ok = false\n }\n\n const scores: Record<string, S> = {}\n if (ok && output !== undefined) {\n const judge_input: JudgeArgs<I, O> = bc.meta === undefined\n ? { input: bc.input, output }\n : { input: bc.input, output, meta: bc.meta }\n for (const [name, judge] of judge_entries) {\n let raw: unknown\n try {\n // oxlint-disable-next-line no-await-in-loop\n raw = await run(judge, judge_input, {\n trajectory: case_logger,\n install_signal_handlers,\n })\n } catch {\n continue\n }\n const normalized = normalize_score(raw)\n if (normalized === undefined) continue\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n scores[name] = normalized as S\n }\n }\n\n const duration_ms = Date.now() - start\n const result: CaseResult<I, O, S> = {\n case_id: bc.id,\n ok,\n ...(output !== undefined ? { output } : {}),\n ...(error !== undefined ? { error } : {}),\n scores,\n duration_ms,\n cost_usd: cost_tracker.total(),\n ...(trajectory_path !== undefined ? { trajectory_path } : {}),\n }\n if (options.on_case) {\n // The on_case callback receives the lossy-typed shape: bench's S is\n // generic but the callback hook is a single concrete signature.\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n options.on_case(result as unknown as CaseResult)\n }\n return result\n }\n\n const cases_out = await run_with_concurrency(cases, concurrency, run_one)\n const summary = summarize(cases_out, judge_entries.map(([n]) => n))\n\n return {\n flow_name,\n run_id,\n cases: cases_out,\n summary,\n }\n}\n\n/**\n * Aggregates per-case results into the report summary.\n *\n * A judge's mean only averages the cases where that judge produced a score;\n * abstained cases do not drag the mean down, and a judge that never scored\n * is omitted from `mean_scores` entirely.\n */\nfunction summarize<I, O, S>(\n cases: ReadonlyArray<CaseResult<I, O, S>>,\n judge_names: ReadonlyArray<string>,\n): BenchSummary {\n const total_duration_ms = cases.reduce((acc, c) => acc + c.duration_ms, 0)\n const total_cost_usd = cases.reduce((acc, c) => acc + c.cost_usd, 0)\n const ok_count = cases.filter((c) => c.ok).length\n const pass_rate = cases.length === 0 ? 0 : ok_count / cases.length\n const mean_cost_usd = cases.length === 0 ? 0 : total_cost_usd / cases.length\n\n const mean_scores: Record<string, number> = {}\n for (const name of judge_names) {\n let sum = 0\n let count = 0\n for (const c of cases) {\n const n = score_value_of(c.scores[name])\n if (n === undefined) continue\n sum += n\n count += 1\n }\n if (count > 0) mean_scores[name] = sum / count\n }\n\n return {\n pass_rate,\n mean_scores,\n total_duration_ms,\n total_cost_usd,\n mean_cost_usd,\n }\n}\n\n/**\n * Coerces a raw judge return value into a `Score`.\n *\n * Accepts a bare finite number or an object with a finite numeric `score`\n * and optional string `reason`. Anything else (including NaN/Infinity, or a\n * non-string `reason`, which is dropped) normalizes toward `undefined` or a\n * reason-less score; `undefined` means the judge abstained.\n */\nexport function normalize_score(raw: unknown): Score | undefined {\n if (raw === undefined || raw === null) return undefined\n if (typeof raw === 'number') {\n return Number.isFinite(raw) ? { score: raw } : undefined\n }\n if (typeof raw === 'object' && 'score' in raw) {\n const r = raw as { score: unknown; reason?: unknown }\n if (typeof r.score !== 'number' || !Number.isFinite(r.score)) return undefined\n if (r.reason !== undefined && typeof r.reason !== 'string') {\n return { score: r.score }\n }\n return r.reason === undefined ? { score: r.score } : { score: r.score, reason: r.reason }\n }\n return undefined\n}\n\n/**\n * Extracts the numeric value from a score-shaped entry, tolerating both bare\n * numbers and `{ score }` objects since `S` is caller-defined.\n */\nfunction score_value_of(s: unknown): number | undefined {\n if (s === undefined || s === null) return undefined\n if (typeof s === 'number') return Number.isFinite(s) ? s : undefined\n if (typeof s === 'object' && 'score' in s) {\n const raw = (s as Record<string, unknown>)['score']\n return typeof raw === 'number' && Number.isFinite(raw) ? raw : undefined\n }\n return undefined\n}\n\n/**\n * Builds a minimal `TrajectoryLogger` that ignores everything except\n * `kind: 'cost'` events and accumulates their `total_usd` into a running\n * total, read back via `total()` after the case finishes.\n */\nfunction create_cost_tracker(): {\n readonly logger: TrajectoryLogger\n readonly total: () => number\n} {\n let total = 0\n return {\n total: () => total,\n logger: {\n record: (event: TrajectoryEvent) => {\n if (event.kind !== 'cost') return\n const e: Record<string, unknown> = event\n const value = e['total_usd']\n if (typeof value === 'number' && Number.isFinite(value)) total += value\n },\n start_span: (name) => `cost-tracker:${name}`,\n end_span: () => {},\n },\n }\n}\n\n/**\n * Runs `fn` over `items` with at most `limit` calls in flight, preserving\n * input order in the results.\n *\n * Uses a shared-index worker pool: each of the `limit` workers claims the\n * next unclaimed index and writes its result into that slot, so completion\n * order never reorders the output.\n */\nasync function run_with_concurrency<t, r>(\n items: ReadonlyArray<t>,\n limit: number,\n fn: (item: t) => Promise<r>,\n): Promise<r[]> {\n if (items.length === 0) return []\n if (limit >= items.length) {\n return Promise.all(items.map((it) => fn(it)))\n }\n const results: r[] = Array.from({ length: items.length })\n let next = 0\n const worker = async (): Promise<void> => {\n while (true) {\n const idx = next\n next += 1\n if (idx >= items.length) return\n const item = items[idx]\n if (item === undefined) continue\n // oxlint-disable-next-line no-await-in-loop\n results[idx] = await fn(item)\n }\n }\n const workers: Promise<void>[] = []\n for (let i = 0; i < limit; i += 1) workers.push(worker())\n await Promise.all(workers)\n return results\n}\n\n/**\n * Clamps the requested concurrency to a positive integer, defaulting to full\n * fan-out (one worker per case) when unset or invalid.\n */\nfunction resolve_concurrency(value: number | undefined, n_cases: number): number {\n if (value === undefined) return Math.max(1, n_cases)\n if (!Number.isFinite(value) || value <= 0) return Math.max(1, n_cases)\n return Math.max(1, Math.floor(value))\n}\n\n/**\n * Picks a human-readable name for the report: the flow's `display_name`\n * config when set, else its step id or kind.\n */\nfunction describe_flow_name<I, O>(flow: Step<I, O>): string {\n const display = flow.config?.['display_name']\n if (typeof display === 'string' && display.length > 0) return display\n return flow.id ?? flow.kind ?? 'flow'\n}\n\n/**\n * Short random base36 suffix to keep default run ids unique across\n * same-millisecond starts.\n */\nfunction random_suffix(): string {\n return Math.random().toString(36).slice(2, 8)\n}\n","/**\n * Stock judges for `bench`.\n *\n * A `Judge<I, O, S>` is a `Step<{ input, output, meta }, S>`: just a step\n * that scores a flow's input/output/metadata triple. Returning `undefined`\n * (or throwing) means the judge abstains; bench records the absence as a\n * missing key in `case.scores` and excludes the case from that judge's\n * `mean_scores` denominator.\n *\n * judge_equals: strict equality vs. `meta.expected`\n * judge_with: wrap a user-supplied scoring function\n * judge_llm: prompt a model + parse the rubric score out of the reply\n *\n * `judge_llm` is engine-agnostic: callers pass their already-configured\n * model_call step (`Step<string, string>`), which keeps composites decoupled\n * from engine. The user-facing wiring lives in their own code.\n */\n\nimport { compose, sequence, step } from '#core'\nimport type { Step } from '#core'\nimport { normalize_score } from './bench.js'\nimport type { Judge, JudgeArgs, Score } from './bench.js'\n\n/**\n * Narrows an unknown value to a plain string-keyed record (non-null object,\n * not an array).\n */\nexport function is_record(v: unknown): v is Record<string, unknown> {\n return v !== null && typeof v === 'object' && !Array.isArray(v)\n}\n\n/**\n * Structural equality over JSON-shaped values: primitives by `===`, arrays\n * element-wise, records key-by-key with sorted keys. Anything else (class\n * instances, functions) only compares equal by reference.\n */\nexport function deep_equal(a: unknown, b: unknown): boolean {\n if (a === b) return true\n // null, primitives, and array/record mismatches all fall through to the\n // Array.isArray and is_record guards below, so no separate null/typeof\n // pre-checks are needed.\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b)) return false\n if (a.length !== b.length) return false\n for (let i = 0; i < a.length; i += 1) {\n if (!deep_equal(a[i], b[i])) return false\n }\n return true\n }\n if (!is_record(a) || !is_record(b)) return false\n const ak = Object.keys(a).toSorted()\n const bk = Object.keys(b).toSorted()\n if (ak.length !== bk.length) return false\n for (let i = 0; i < ak.length; i += 1) {\n const ka = ak[i]\n const kb = bk[i]\n if (ka === undefined || kb === undefined || ka !== kb) return false\n if (!deep_equal(a[ka], b[kb])) return false\n }\n return true\n}\n\n/**\n * Judge that scores 1 when the output deep-equals `meta.expected`, 0\n * otherwise. Abstains when the case has no `meta` or no `expected` key.\n */\nexport function judge_equals<O>(): Judge<unknown, O> {\n return step('judge_equals', (args: JudgeArgs<unknown, O>): Score | undefined => {\n if (args.meta === undefined) return undefined\n if (!('expected' in args.meta)) return undefined\n const expected = args.meta['expected']\n const matches = deep_equal(args.output, expected)\n return { score: matches ? 1 : 0, reason: matches ? 'match' : 'mismatch' }\n })\n}\n\nexport type JudgeWithFn<I, O> = (\n args: JudgeArgs<I, O>,\n) => number | Score | undefined | Promise<number | Score | undefined>\n\n/**\n * Wraps a plain scoring function as a Judge. The function may return a bare\n * number, a `Score`, or `undefined` to abstain; the result is normalized\n * via `normalize_score`.\n */\nexport function judge_with<I, O>(fn: JudgeWithFn<I, O>): Judge<I, O> {\n return step('judge_with', async (args: JudgeArgs<I, O>): Promise<Score | undefined> => {\n const raw = await fn(args)\n return normalize_score(raw)\n })\n}\n\nexport type JudgeLlmConfig = {\n readonly model: Step<string, string>\n readonly rubric: string\n readonly scale?: { readonly min: number; readonly max: number }\n}\n\n/**\n * Judge that prompts a model with a rubric and parses the score out of the\n * reply.\n *\n * Built as a three-step sequence: render the rubric prompt, run the\n * caller-supplied model step, parse the JSON score from the reply. An\n * unparseable reply makes the judge abstain rather than fail the case.\n */\nexport function judge_llm<I, O>(config: JudgeLlmConfig): Judge<I, O> {\n const scale = config.scale ?? { min: 0, max: 1 }\n const build_prompt = step('judge_llm_build_prompt', (args: JudgeArgs<I, O>): string =>\n render_prompt(config.rubric, scale, args),\n )\n const parse = step('judge_llm_parse', (reply: string): Score | undefined =>\n parse_score(reply, scale),\n )\n const inner = sequence([build_prompt, config.model, parse])\n return compose('judge_llm', inner)\n}\n\n/**\n * Renders the evaluator prompt: rubric, required JSON reply shape with the\n * score scale, and the case's input/output serialized as JSON.\n */\nexport function render_prompt<I, O>(\n rubric: string,\n scale: { min: number; max: number },\n args: JudgeArgs<I, O>,\n): string {\n return [\n `You are an evaluator. Score the model output against the rubric below.`,\n ``,\n `Rubric:`,\n rubric,\n ``,\n `Return a single line of JSON with exactly two keys: {\"score\": <number ${String(scale.min)}..${String(scale.max)}>, \"reason\": \"<short>\"}.`,\n `Do not include prose outside the JSON.`,\n ``,\n `Input:`,\n JSON.stringify(args.input),\n ``,\n `Output:`,\n JSON.stringify(args.output),\n ].join('\\n')\n}\n\n/**\n * Parses a model reply into a `Score`, or `undefined` (abstain) when no\n * valid JSON object with a finite numeric `score` can be extracted.\n *\n * Tolerates prose around the JSON via `extract_json_object` and clamps the\n * score into the configured scale rather than rejecting out-of-range values.\n */\nexport function parse_score(\n reply: string,\n scale: { min: number; max: number },\n): Score | undefined {\n const trimmed = reply.trim()\n const candidate = extract_json_object(trimmed)\n if (candidate === undefined) return undefined\n let parsed: unknown\n try {\n parsed = JSON.parse(candidate)\n } catch {\n return undefined\n }\n if (!is_record(parsed)) return undefined\n const raw_score = parsed['score']\n if (typeof raw_score !== 'number' || !Number.isFinite(raw_score)) return undefined\n const clamped = Math.max(scale.min, Math.min(scale.max, raw_score))\n const raw_reason = parsed['reason']\n const reason = typeof raw_reason === 'string' ? raw_reason : undefined\n return reason === undefined ? { score: clamped } : { score: clamped, reason }\n}\n\n/**\n * Pulls the outermost `{...}` slice out of a reply that may wrap the JSON\n * in prose or code fences. Returns the text as-is when it already starts\n * with `{`.\n */\nexport function extract_json_object(text: string): string | undefined {\n if (text.startsWith('{')) return text\n const start = text.indexOf('{')\n const end = text.lastIndexOf('}')\n if (start === -1 || end === -1 || end < start) return undefined\n return text.slice(start, end + 1)\n}\n","/**\n * regression_compare: diff two BenchReports for regressions.\n *\n * The contract: given a `current` report and a `baseline` report, produce a\n * `RegressionReport` whose `ok` flag is false when any tracked metric got\n * worse beyond a threshold. The function does NOT short-circuit on first\n * failure; every metric and every per-case delta is computed so callers can\n * print or assert against the whole report.\n *\n * Tracked metrics:\n * - pass_rate (any drop is a regression by default)\n * - mean_scores.<name> (per judge; any drop is a regression by default)\n * - total_cost_usd (a relative cost increase above cost_threshold\n * counts as a regression; default 10%)\n *\n * Baselines are plain JSON, written via `write_baseline` and read via\n * `read_baseline`. They live wherever the caller decides, typically\n * `bench/<flow>/baseline.json` checked into git.\n */\n\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport type { BenchReport, CaseResult } from './bench.js'\n\nexport type RegressionDelta = {\n readonly metric: string\n readonly baseline: number\n readonly current: number\n readonly delta: number\n readonly is_regression: boolean\n}\n\nexport type PerCaseDelta = {\n readonly case_id: string\n readonly baseline?: CaseResult\n readonly current?: CaseResult\n readonly score_deltas: Record<string, number>\n readonly cost_delta: number\n readonly is_regression: boolean\n}\n\nexport type RegressionReport = {\n readonly ok: boolean\n readonly deltas: ReadonlyArray<RegressionDelta>\n readonly per_case: ReadonlyArray<PerCaseDelta>\n}\n\nexport type RegressionCompareOptions = {\n readonly score_threshold?: number\n readonly cost_threshold?: number\n}\n\n/**\n * Diff a current `BenchReport` against a baseline.\n *\n * Compares `pass_rate`, each judge's mean score, and total cost, then every\n * individual case. Score metrics regress on any drop beyond\n * `score_threshold` (default 0); cost regresses on a relative increase above\n * `cost_threshold` (default 10%).\n */\nexport function regression_compare(\n current: BenchReport,\n baseline: BenchReport,\n options: RegressionCompareOptions = {},\n): RegressionReport {\n const score_threshold = options.score_threshold ?? 0\n const cost_threshold = options.cost_threshold ?? 0.1\n\n const deltas: RegressionDelta[] = []\n\n const pass_delta = current.summary.pass_rate - baseline.summary.pass_rate\n deltas.push({\n metric: 'pass_rate',\n baseline: baseline.summary.pass_rate,\n current: current.summary.pass_rate,\n delta: pass_delta,\n is_regression: pass_delta < -score_threshold,\n })\n\n const judge_names = collect_judge_names(current, baseline)\n for (const name of judge_names) {\n const c = current.summary.mean_scores[name] ?? 0\n const b = baseline.summary.mean_scores[name] ?? 0\n const d = c - b\n deltas.push({\n metric: `mean_scores.${name}`,\n baseline: b,\n current: c,\n delta: d,\n is_regression: d < -score_threshold,\n })\n }\n\n const cb = baseline.summary.total_cost_usd\n const cc = current.summary.total_cost_usd\n const cost_delta = cc - cb\n const cost_ratio = cb === 0 ? (cc > 0 ? Infinity : 0) : cost_delta / cb\n deltas.push({\n metric: 'total_cost_usd',\n baseline: cb,\n current: cc,\n delta: cost_delta,\n is_regression: cost_ratio > cost_threshold,\n })\n\n const per_case = compute_per_case(current, baseline, score_threshold, cost_threshold)\n const ok = !deltas.some((d) => d.is_regression) && !per_case.some((c) => c.is_regression)\n\n return { ok, deltas, per_case }\n}\n\n/**\n * Compute per-case deltas across the union of case ids in both reports.\n *\n * Cases present on only one side still appear (missing side scores count as\n * 0). A case regresses when a judge score drops beyond the threshold, its\n * cost rises beyond the relative threshold, or it flips from ok to failing.\n */\nfunction compute_per_case(\n current: BenchReport,\n baseline: BenchReport,\n score_threshold: number,\n cost_threshold: number,\n): PerCaseDelta[] {\n const by_id_current = index_by_case_id(current.cases)\n const by_id_baseline = index_by_case_id(baseline.cases)\n const all_ids = new Set<string>([...by_id_current.keys(), ...by_id_baseline.keys()])\n\n const out: PerCaseDelta[] = []\n for (const id of all_ids) {\n const c = by_id_current.get(id)\n const b = by_id_baseline.get(id)\n const score_deltas: Record<string, number> = {}\n let any_score_regression = false\n const judge_names = new Set<string>([\n ...Object.keys(c?.scores ?? {}),\n ...Object.keys(b?.scores ?? {}),\n ])\n for (const name of judge_names) {\n const c_score = score_value(c?.scores[name])\n const b_score = score_value(b?.scores[name])\n const delta = c_score - b_score\n score_deltas[name] = delta\n if (delta < -score_threshold) any_score_regression = true\n }\n const cost_delta = (c?.cost_usd ?? 0) - (b?.cost_usd ?? 0)\n const cost_ratio_regression =\n b?.cost_usd !== undefined && b.cost_usd > 0\n ? cost_delta / b.cost_usd > cost_threshold\n : (c?.cost_usd ?? 0) > 0 && (b?.cost_usd ?? 0) === 0 && cost_threshold < Infinity\n const ok_regression = b?.ok === true && c?.ok !== true\n out.push({\n case_id: id,\n ...(b !== undefined ? { baseline: b } : {}),\n ...(c !== undefined ? { current: c } : {}),\n score_deltas,\n cost_delta,\n is_regression: any_score_regression || cost_ratio_regression || ok_regression,\n })\n }\n return out\n}\n\n/**\n * Extract a finite numeric score from a raw score entry.\n *\n * Accepts a bare number or an object with a numeric `score` field; anything\n * else (missing, NaN, non-numeric) counts as 0 so deltas stay well-defined.\n */\nfunction score_value(s: unknown): number {\n if (s === undefined || s === null) return 0\n if (typeof s === 'number') return Number.isFinite(s) ? s : 0\n if (typeof s === 'object' && 'score' in s) {\n const v = (s as Record<string, unknown>)['score']\n return typeof v === 'number' && Number.isFinite(v) ? v : 0\n }\n return 0\n}\n\n/**\n * Index case results by their `case_id` for pairwise lookup.\n */\nfunction index_by_case_id<I, O, S>(\n cases: ReadonlyArray<CaseResult<I, O, S>>,\n): Map<string, CaseResult<I, O, S>> {\n const m = new Map<string, CaseResult<I, O, S>>()\n for (const c of cases) m.set(c.case_id, c)\n return m\n}\n\n/**\n * Union the judge names appearing in either report, sorted for stable output.\n */\nfunction collect_judge_names(a: BenchReport, b: BenchReport): string[] {\n const names = new Set<string>([\n ...Object.keys(a.summary.mean_scores),\n ...Object.keys(b.summary.mean_scores),\n ])\n return [...names].toSorted()\n}\n\n/**\n * Read and validate a baseline `BenchReport` from a JSON file.\n *\n * Validation is structural (required fields present), so a hand-edited or\n * truncated baseline fails loudly with the offending path in the message.\n */\nexport async function read_baseline(path: string): Promise<BenchReport> {\n const text = await readFile(path, 'utf8')\n const parsed: unknown = JSON.parse(text)\n validate_report(parsed, path)\n return parsed\n}\n\n/**\n * Write a `BenchReport` as pretty-printed JSON, creating parent directories.\n */\nexport async function write_baseline(path: string, report: BenchReport): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(path, `${JSON.stringify(report, null, 2)}\\n`, 'utf8')\n}\n\n/**\n * Assert that parsed JSON has the structural shape of a `BenchReport`.\n */\nfunction validate_report(value: unknown, path: string): asserts value is BenchReport {\n if (value === null || typeof value !== 'object') {\n throw new Error(`baseline at ${path} is not an object`)\n }\n const v = value as Partial<BenchReport>\n if (typeof v.flow_name !== 'string' || typeof v.run_id !== 'string') {\n throw new Error(`baseline at ${path} missing flow_name/run_id`)\n }\n if (!Array.isArray(v.cases) || typeof v.summary !== 'object' || v.summary === null) {\n throw new Error(`baseline at ${path} missing cases/summary`)\n }\n}\n\n// Runtime-side type re-export: regression consumers want both the diff types\n// and the underlying CaseResult/Score shapes from one import.\nexport type { Score } from './bench.js'\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\nimport type { CostBreakdown, Pricing, PricingTable, UsageTotals } from './types.js'\n\nexport const FREE_PROVIDERS: ReadonlySet<string> = new Set(['ollama', 'lmstudio'])\n\nexport const DEFAULT_PRICING: PricingTable = Object.freeze({\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-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 '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: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 'google:gemini-2.5-pro': { input_per_million: 1.25, output_per_million: 5.0 },\n 'google:gemini-2.5-flash': { input_per_million: 0.075, output_per_million: 0.3 },\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 */\nfunction round6(value: number): number {\n return Math.round(value * 1e6) / 1e6\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) {\n if (!FREE_PROVIDERS.has(provider)) return undefined\n const breakdown: CostBreakdown = {\n total_usd: 0,\n input_usd: 0,\n output_usd: 0,\n currency: 'USD',\n is_estimate: true,\n }\n return breakdown\n }\n\n const input_tokens = usage.input_tokens\n const output_tokens = usage.output_tokens\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, 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 has_reasoning_rate = pricing.reasoning_per_million !== undefined\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, output_tokens - reasoning)\n const plain_output_usd_raw = (plain_output_tokens * pricing.output_per_million) / 1e6\n\n const input_usd = round6(input_usd_raw)\n\n let output_usd_raw = plain_output_usd_raw\n let surface_reasoning_usd: number | undefined\n if (reasoning > 0) {\n if (has_reasoning_rate) {\n surface_reasoning_usd = round6(reasoning_usd_raw)\n } else {\n output_usd_raw = plain_output_usd_raw + reasoning_usd_raw\n }\n }\n const output_usd = round6(output_usd_raw)\n\n let cached_input_usd: number | undefined\n let cache_write_usd: number | undefined\n if (cached > 0) cached_input_usd = round6(cached_usd_raw)\n if (cache_write > 0) cache_write_usd = round6(cache_write_usd_raw)\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,\n output_usd,\n currency: 'USD',\n is_estimate: true,\n }\n if (cached_input_usd !== undefined) breakdown.cached_input_usd = cached_input_usd\n if (cache_write_usd !== undefined) breakdown.cache_write_usd = cache_write_usd\n if (surface_reasoning_usd !== undefined) breakdown.reasoning_usd = surface_reasoning_usd\n return breakdown\n}\n","/**\n * Typed errors for the AI engine layer.\n *\n * This is the only source file in the engine module permitted to use the\n * `class` keyword. `Error` is a built-in and `instanceof` branching is how\n * the retry helper and composition-layer composers distinguish failure modes.\n * Every other engine file stays class-free.\n *\n * `aborted_error` is defined in the core module and re-exported here so that\n * `instanceof aborted_error` is true regardless of which layer surfaced it.\n * This is the one value-level import from core permitted in engine source;\n * see the ignores in `rules/no-core-value-import-in-engine.yml`.\n */\n\nexport { aborted_error } from '#core'\n\nexport class rate_limit_error extends Error {\n readonly kind = 'rate_limit_error' as const;\n readonly retry_after_ms: number | undefined;\n readonly attempts: number;\n readonly status: number | undefined;\n constructor(\n message: string,\n metadata: { retry_after_ms?: number; attempts?: number; status?: number } = {},\n ) {\n super(message)\n this.name = 'rate_limit_error'\n this.retry_after_ms = metadata.retry_after_ms\n this.attempts = metadata.attempts ?? 0\n this.status = metadata.status\n }\n}\n\nexport class provider_error extends Error {\n readonly kind = 'provider_error' as const;\n readonly status: number | undefined;\n readonly body: string | undefined;\n readonly cause_kind: 'provider_5xx' | 'network' | 'unknown' | undefined;\n constructor(\n message: string,\n metadata: {\n status?: number\n body?: string\n cause_kind?: 'provider_5xx' | 'network' | 'unknown'\n } = {},\n ) {\n super(message)\n this.name = 'provider_error'\n this.status = metadata.status\n this.body = metadata.body\n this.cause_kind = metadata.cause_kind\n }\n}\n\n/**\n * Turn-timeout expiry. Thrown by the engine-owned retry_turn wrapper when a\n * single invoke_turn exceeds `turn_timeout_ms` before any chunk streamed.\n * Its `kind` is the RetryFailureKind wire value `'timeout'` (not the class\n * name) on purpose: that is the discriminant classify_retryable /\n * classify_provider_error already key on, so the shared classifier treats an\n * expiry as retryable without any timeout-specific branch. A mid-stream\n * expiry never reaches here; retry_turn converts it to a non-retryable\n * stream interruption first.\n */\nexport class turn_timeout_error extends Error {\n readonly kind = 'timeout' as const;\n readonly timeout_ms: number;\n readonly step_index: number | undefined;\n constructor(timeout_ms: number, step_index?: number) {\n super(`turn exceeded turn_timeout_ms budget of ${timeout_ms}ms`)\n this.name = 'turn_timeout_error'\n this.timeout_ms = timeout_ms\n this.step_index = step_index\n }\n}\n\nexport class schema_validation_error extends Error {\n readonly kind = 'schema_validation_error' as const;\n readonly zod_error: unknown;\n readonly raw_text: string;\n constructor(message: string, zod_error: unknown, raw_text: string) {\n super(message)\n this.name = 'schema_validation_error'\n this.zod_error = zod_error\n this.raw_text = raw_text\n }\n}\n\nexport class tool_error extends Error {\n readonly kind = 'tool_error' as const;\n readonly tool_name: string;\n readonly tool_call_id: string;\n override readonly cause: unknown;\n constructor(\n message: string,\n metadata: { tool_name: string; tool_call_id: string; cause: unknown },\n ) {\n super(message)\n this.name = 'tool_error'\n this.tool_name = metadata.tool_name\n this.tool_call_id = metadata.tool_call_id\n this.cause = metadata.cause\n }\n}\n\nexport class tool_approval_denied_error extends Error {\n readonly kind = 'tool_approval_denied_error' as const;\n readonly tool_name: string;\n readonly step_index: number;\n readonly tool_call_id: string;\n constructor(\n message: string,\n metadata: { tool_name: string; step_index: number; tool_call_id: string },\n ) {\n super(message)\n this.name = 'tool_approval_denied_error'\n this.tool_name = metadata.tool_name\n this.step_index = metadata.step_index\n this.tool_call_id = metadata.tool_call_id\n }\n}\n\nexport class model_required_error extends Error {\n readonly kind = 'model_required_error' as const;\n constructor(\n message = 'no model specified: pass `model` to generate() or set `defaults.model` on the engine',\n ) {\n super(message)\n this.name = 'model_required_error'\n }\n}\n\nexport class provider_not_configured_error extends Error {\n readonly kind = 'provider_not_configured_error' as const;\n readonly provider: string;\n constructor(provider: string) {\n super(`provider '${provider}' is not configured on this engine`)\n this.name = 'provider_not_configured_error'\n this.provider = provider\n }\n}\n\nexport class engine_config_error extends Error {\n readonly kind = 'engine_config_error' as const;\n readonly provider: string | undefined;\n constructor(message: string, provider?: string) {\n super(message)\n this.name = 'engine_config_error'\n this.provider = provider\n }\n}\n\nexport class on_chunk_error extends Error {\n readonly kind = 'on_chunk_error' as const;\n override readonly cause: unknown;\n constructor(message: string, cause: unknown) {\n super(message)\n this.name = 'on_chunk_error'\n this.cause = cause\n }\n}\n\nexport class provider_capability_error extends Error {\n readonly kind = 'provider_capability_error' as const;\n readonly provider: string;\n readonly capability: string;\n constructor(provider: string, capability: string, detail?: string) {\n const suffix = detail !== undefined ? `: ${detail}` : ''\n super(`provider '${provider}' does not support '${capability}'${suffix}`)\n this.name = 'provider_capability_error'\n this.provider = provider\n this.capability = capability\n }\n}\n\nexport class engine_disposed_error extends Error {\n readonly kind = 'engine_disposed_error' as const;\n constructor(message = 'engine has been disposed; further calls are not permitted') {\n super(message)\n this.name = 'engine_disposed_error'\n }\n}\n\nexport type ClaudeCliErrorReason =\n | 'binary_not_found'\n | 'auth_missing'\n | 'auth_expired'\n | 'api_key_missing'\n | 'startup_timeout'\n | 'stall_timeout'\n | 'no_result_event'\n | 'result_error'\n | 'subprocess_exit'\n | 'sandbox_unavailable'\n | 'engine_disposed'\n | 'parse_error'\n\nexport class claude_cli_error extends Error {\n readonly kind = 'claude_cli_error' as const;\n readonly reason: ClaudeCliErrorReason;\n readonly status: number | undefined;\n readonly stderr_snippet: string | undefined;\n constructor(\n reason: ClaudeCliErrorReason,\n message: string,\n metadata: { status?: number; stderr_snippet?: string } = {},\n ) {\n super(message)\n this.name = 'claude_cli_error'\n this.reason = reason\n this.status = metadata.status\n this.stderr_snippet = metadata.stderr_snippet\n }\n}\n\nexport class provider_auth_error extends Error {\n readonly kind = 'provider_auth_error' as const;\n readonly provider: string;\n readonly refresh_command: string | undefined;\n constructor(\n provider: string,\n message: string,\n metadata: { refresh_command?: string } = {},\n ) {\n super(message)\n this.name = 'provider_auth_error'\n this.provider = provider\n this.refresh_command = metadata.refresh_command\n }\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'\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\nexport type 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 * Compute the delay before the next retry attempt.\n *\n * Exponential backoff (`initial_delay_ms * 2^attempt`) plus up to one\n * `initial_delay_ms` of random jitter, capped at `max_delay_ms`. The jitter\n * spreads retries from concurrent callers apart so they don't all retry in\n * lockstep.\n */\nfunction compute_backoff(policy: RetryPolicy, attempt: number): number {\n const base = policy.initial_delay_ms * 2 ** attempt\n const jitter = Math.random() * policy.initial_delay_ms\n return Math.min(base + jitter, policy.max_delay_ms)\n}\n\n/**\n * Wait `ms` milliseconds, or reject immediately with `aborted_error` if\n * `abort` fires first.\n *\n * A zero or negative `ms` resolves synchronously without arming a timer.\n */\nfunction wait_ms(ms: number, abort?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (ms <= 0) {\n resolve()\n return\n }\n if (abort?.aborted === true) {\n reject(new aborted_error('aborted', { reason: abort.reason }))\n return\n }\n const timer = setTimeout(() => {\n if (abort !== undefined) abort.removeEventListener('abort', on_abort)\n resolve()\n }, ms)\n const on_abort = (): void => {\n clearTimeout(timer)\n reject(new aborted_error('aborted', { reason: abort?.reason }))\n }\n abort?.addEventListener('abort', on_abort, { once: true })\n })\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 * 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 */\nexport async function retry_with_policy<t>(\n fn: (attempt: number) => Promise<t>,\n policy: RetryPolicy = DEFAULT_RETRY,\n abort?: AbortSignal,\n): Promise<t> {\n let attempt = 0\n let last_rate_limit_after: number | undefined\n while (true) {\n if (abort?.aborted === true) {\n throw new aborted_error('aborted', { reason: abort.reason })\n }\n try {\n return await fn(attempt)\n } catch (err: unknown) {\n const retryable = classify_retryable(err)\n if (retryable === undefined) throw err\n if (!is_retryable(retryable.kind, policy)) throw err\n attempt += 1\n if (attempt >= policy.max_attempts) {\n if (retryable.kind === 'rate_limit') {\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 throw new rate_limit_error(\n retryable.message ?? `rate limited after ${attempt} attempts`,\n metadata,\n )\n }\n const cause_kind =\n 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 throw new provider_error(\n retryable.message ?? `${retryable.kind} after ${attempt} attempts`,\n metadata,\n )\n }\n\n let delay = compute_backoff(policy, attempt - 1)\n if (retryable.kind === 'rate_limit' && retryable.retry_after_ms !== undefined) {\n // When the server supplies Retry-After, honor it even if it exceeds\n // max_delay_ms; the server's instruction outranks the local backoff cap.\n delay = Math.max(delay, retryable.retry_after_ms)\n last_rate_limit_after = retryable.retry_after_ms\n }\n await wait_ms(delay, abort)\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 * 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') {\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 if (kind === 'provider_5xx') {\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 if (kind === 'network' || kind === 'timeout') {\n const base: RetryableError = { kind }\n const message = read_string(err, 'message')\n if (message !== undefined) base.message = message\n return base\n }\n return undefined\n}\n","/**\n * Shared provider-adapter shape.\n *\n * Each file under src/engine/providers/ exports a factory that accepts a\n * ProviderInit shape and returns a ProviderAdapter. Factories are\n * synchronous; build_model is async so SDK loading is deferred until a model\n * is actually needed. Missing peer dependencies surface as engine_config_error\n * on first build_model call with a clear message naming the missing peer.\n *\n * Only the ai_sdk transport module (providers/ai_sdk/invoke.ts) may import\n * from `ai` or invoke generateText/streamText. ai_sdk adapters build the\n * provider model and translate parameters; they do not orchestrate the call.\n */\n\nimport type {\n ResolvedModel,\n EffortLevel,\n GenerateOptions,\n GenerateResult,\n ProviderInit,\n TurnRequest,\n TurnResult,\n UsageTotals,\n} from '../types.js'\nimport { engine_config_error } from '../errors.js'\n\n/**\n * Which backend a provider factory returns: 'ai_sdk' wraps the Vercel AI SDK\n * provider package, 'native' talks to the provider's HTTP API directly. The\n * provider name stays the same across transports so pricing keys and usage\n * fields carry over; only the wire implementation changes.\n */\nexport type ProviderTransport = 'ai_sdk' | 'native'\n\n/**\n * Read the `transport` selector off a provider init. Defaults to 'ai_sdk';\n * anything but the two known backends throws at construction so a typo\n * fails loud instead of silently running the default.\n */\nexport function resolve_transport(\n init: ProviderInit,\n provider: string,\n): ProviderTransport {\n const raw = init['transport']\n if (raw === undefined || raw === 'ai_sdk') return 'ai_sdk'\n if (raw === 'native') return 'native'\n throw new engine_config_error(\n `${provider} provider: transport must be 'ai_sdk' or 'native', got ${JSON.stringify(raw)}`,\n provider,\n )\n}\n\nexport type EffortTranslation = {\n // Outer keys are provider names, inner records hold per-provider settings,\n // matching the two-level shape merge_provider_options expects.\n provider_options: Record<string, Record<string, unknown>>\n effort_ignored: boolean\n}\n\nexport type ProviderCapability =\n | 'text'\n | 'tools'\n | 'schema'\n | 'streaming'\n | 'image_input'\n | 'reasoning'\n // Provider performs native constrained decoding (the AI SDK responseFormat /\n // Output.object path), as opposed to the prompt-for-JSON-then-extract path.\n // Distinct from 'schema': every provider can satisfy a schema via repair, but\n // only some constrain the decode to it.\n | 'structured_output'\n\nexport type RawProviderUsage = {\n input_tokens?: number\n output_tokens?: number\n reasoning_tokens?: number\n cached_input_tokens?: number\n cache_write_tokens?: number\n // Vercel AI SDK v6 also surfaces details via *Details containers; adapters\n // accept the flattened shape above for testability.\n input_token_details?: {\n cached_tokens?: number\n cache_creation_input_tokens?: number\n }\n output_token_details?: {\n reasoning_tokens?: number\n }\n [k: string]: unknown\n}\n\nexport type AiSdkProviderAdapter = {\n readonly kind: 'ai_sdk'\n readonly name: string\n readonly build_model: (model_id: string) => Promise<unknown>\n readonly translate_effort: (effort: EffortLevel) => EffortTranslation\n readonly normalize_usage: (raw: RawProviderUsage | undefined) => UsageTotals\n readonly supports: (capability: ProviderCapability) => boolean\n}\n\n/**\n * Raw-HTTP transport: implements a single turn against a provider's own\n * API with zero `ai` / `@ai-sdk/*` in its module graph. generate.ts wraps\n * invoke_turn in retry + classification + abort, so a native adapter owns only\n * request/response mapping (and streaming via TurnRequest.dispatch_chunk); it\n * MUST NOT implement its own retry. classify_error optionally overrides the\n * shared classifier; dispose is optional (keep-alive agents, connection pools).\n */\nexport type NativeProviderAdapter = {\n readonly kind: 'native'\n readonly name: string\n readonly invoke_turn: (req: TurnRequest) => Promise<TurnResult>\n readonly supports: (capability: ProviderCapability) => boolean\n readonly dispose?: () => Promise<void>\n readonly classify_error?: (err: unknown) => unknown\n}\n\nexport type ExternalAgentAdapter = {\n readonly kind: 'external'\n readonly name: string\n readonly generate: <t>(\n opts: GenerateOptions<t>,\n resolved: ResolvedModel,\n ) => Promise<GenerateResult<t>>\n readonly dispose: () => Promise<void>\n readonly supports: (capability: ProviderCapability) => boolean\n}\n\nexport type ProviderAdapter =\n | AiSdkProviderAdapter\n | NativeProviderAdapter\n | ExternalAgentAdapter\n\nexport type ProviderFactory = (init: ProviderInit) => ProviderAdapter\n\n/**\n * Map raw provider usage to UsageTotals, the mapper most adapters share.\n *\n * Missing usage zeroes the totals. Optional fields (reasoning and cache\n * tokens) are set only when the raw payload carries them, reading the\n * flattened field first and the AI SDK's *_details container second.\n */\nexport function default_normalize_usage(\n raw: RawProviderUsage | undefined,\n): UsageTotals {\n if (raw === undefined) return { input_tokens: 0, output_tokens: 0 }\n const input_tokens = typeof raw.input_tokens === 'number' ? raw.input_tokens : 0\n const output_tokens = typeof raw.output_tokens === 'number' ? raw.output_tokens : 0\n const totals: UsageTotals = { input_tokens, output_tokens }\n if (typeof raw.reasoning_tokens === 'number') totals.reasoning_tokens = raw.reasoning_tokens\n else if (typeof raw.output_token_details?.reasoning_tokens === 'number') {\n totals.reasoning_tokens = raw.output_token_details.reasoning_tokens\n }\n if (typeof raw.cached_input_tokens === 'number') totals.cached_input_tokens = raw.cached_input_tokens\n else if (typeof raw.input_token_details?.cached_tokens === 'number') {\n totals.cached_input_tokens = raw.input_token_details.cached_tokens\n }\n if (typeof raw.cache_write_tokens === 'number') totals.cache_write_tokens = raw.cache_write_tokens\n else if (typeof raw.input_token_details?.cache_creation_input_tokens === 'number') {\n totals.cache_write_tokens = raw.input_token_details.cache_creation_input_tokens\n }\n return totals\n}\n\n/**\n * Dynamically import an optional peer dependency, rethrowing an import\n * failure as an error that names the package and the install command so a\n * missing peer is diagnosable from the message alone.\n */\nexport async function load_optional_peer<t>(\n specifier: string,\n): Promise<t> {\n let mod: unknown\n try {\n mod = await import(specifier)\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : JSON.stringify(err)\n const message =\n `missing peer dependency '${specifier}'. Install it with: pnpm add ${specifier}. Cause: ${detail}`\n throw new Error(message, { cause: err })\n }\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return mod as t\n}\n","/**\n * Incremental SSE decoder shared by the native (raw-HTTP) provider adapters.\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 buffer = ''\n let data_lines: string[] = []\n\n const take_line = (raw: string, out: string[]): void => {\n const line = raw.endsWith('\\r') ? raw.slice(0, -1) : raw\n if (line.length === 0) {\n if (data_lines.length > 0) {\n out.push(data_lines.join('\\n'))\n data_lines = []\n }\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\n return {\n push(text: string): string[] {\n buffer += text\n const out: string[] = []\n let newline = buffer.indexOf('\\n')\n while (newline >= 0) {\n take_line(buffer.slice(0, newline), out)\n buffer = buffer.slice(newline + 1)\n newline = buffer.indexOf('\\n')\n }\n return out\n },\n flush(): string[] {\n const out: string[] = []\n if (buffer.length > 0) take_line(buffer, out)\n buffer = ''\n if (data_lines.length > 0) {\n out.push(data_lines.join('\\n'))\n data_lines = []\n }\n return out\n },\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 { z } from 'zod'\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_auth_error,\n provider_capability_error,\n provider_error,\n} from '../errors.js'\nimport { create_sse_decoder } from './sse_native.js'\nimport type { NativeProviderAdapter, ProviderCapability } from './types.js'\n\n/**\n * Effort level to extended-thinking budget tokens. Lives here (not in\n * anthropic.ts) because both transports map effort from this table and the\n * ai_sdk factory already imports this module for transport dispatch; the\n * reverse import would be a cycle.\n */\nexport const 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. When extended\n * thinking is enabled the budget counts against max_tokens, so the default\n * rides on top of the thinking budget 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\nexport type AnthropicMessage = {\n role: 'user' | 'assistant'\n content: AnthropicContentBlock[]\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') {\n return content.trim().length > 0 ? [{ type: 'text', text: content }] : []\n }\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 if (part.text.trim().length > 0) blocks.push({ type: 'text', text: part.text })\n }\n return blocks\n}\n\n/**\n * Map assistant message content to Messages-API blocks: text parts become\n * text blocks (empties dropped), tool-call parts become tool_use blocks.\n */\nfunction to_assistant_blocks(\n content: string | AssistantContentPart[],\n): AnthropicContentBlock[] {\n if (typeof content === 'string') {\n return content.trim().length > 0 ? [{ type: 'text', text: content }] : []\n }\n const blocks: AnthropicContentBlock[] = []\n for (const part of content) {\n if (part.type === 'text') {\n if (part.text.trim().length > 0) blocks.push({ type: 'text', text: part.text })\n } else {\n blocks.push({ type: 'tool_use', id: part.id, name: part.name, input: part.input })\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 zod 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: z.toJSONSchema(tool.input_schema),\n }))\n}\n\n/**\n * Build the Messages-API request body for one turn: mapped messages and\n * tools, the effort-derived thinking block, the required max_tokens default,\n * and the `provider_options.anthropic` wire 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 const budget = ANTHROPIC_THINKING_BUDGETS[req.effort]\n const thinking_enabled = budget > 0\n\n const body: Record<string, unknown> = {\n model: req.model_id,\n messages,\n max_tokens:\n req.max_tokens ?? (thinking_enabled ? budget + DEFAULT_MAX_TOKENS : 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 (thinking_enabled) {\n body['thinking'] = { type: 'enabled', budget_tokens: budget }\n } else {\n // The API rejects temperature/top_p alongside extended thinking, so\n // sampling params apply only when thinking is off (parity with the\n // @ai-sdk/anthropic backend, which strips them the same way). The inner\n // guards already gate each key, so the branch is a plain else rather than\n // a redundant `else if` on the same two conditions.\n if (req.temperature !== undefined) body['temperature'] = req.temperature\n if (req.top_p !== undefined) body['top_p'] = req.top_p\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 effort-derived thinking block, the max_tokens default, sampling\n // params. The adapter does not reconcile interactions the API rejects\n // (e.g. a passthrough temperature alongside thinking); wire keys are the\n // 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 * 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.\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 content: unknown = Reflect.get(payload, 'content')\n const text_parts: string[] = []\n const tool_calls: Array<{ id: string; name: string; input: unknown }> = []\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block === null || typeof block !== 'object') continue\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') text_parts.push(text)\n } else if (type === 'tool_use') {\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(\n 'anthropic native: malformed tool_use block in response content',\n )\n }\n tool_calls.push({ id, name, input: Reflect.get(block, 'input') })\n }\n // thinking / redacted_thinking blocks have no TurnResult field; skipped.\n }\n }\n return {\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}\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 * 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 */\nexport function create_stream_aggregator(\n step_index: number,\n dispatch: (chunk: StreamChunk) => Promise<void>,\n): {\n handle_event: (data: string) => Promise<void>\n complete: () => TurnResult\n} {\n type SyntheticToolUse = { type: 'tool_use'; id: string; name: string; input: 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: Array<{ type: 'text'; text: string } | SyntheticToolUse> = []\n const open_text = new Map<number, { type: 'text'; text: string }>()\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 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: 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 stream')\n }\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 }\n // thinking / redacted_thinking blocks carry no TurnResult state; their\n // deltas dispatch reasoning chunks directly.\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') {\n const thinking: unknown = Reflect.get(delta, 'thinking')\n if (typeof thinking === 'string') {\n await dispatch({ kind: 'reasoning', text: thinking, step_index })\n }\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 // signature_delta and 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 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_event(data: string): Promise<void> {\n let event: unknown\n try {\n event = JSON.parse(data)\n } catch {\n throw new provider_error('anthropic native: stream event is not valid JSON')\n }\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/** Anthropic error bodies are `{ type: 'error', error: { message } }`; fall back to the raw body. */\nfunction extract_error_message(body: string): string {\n if (body.length === 0) return '(empty body)'\n try {\n const parsed: unknown = JSON.parse(body)\n // Stryker disable next-line ConditionalExpression,LogicalOperator: the\n // enclosing try/catch already funnels every non-object parse to the raw\n // snippet, so this guard only narrows unknown -> object for Reflect.get;\n // forcing it true/false throws-and-catches to the same fallback (equivalent).\n if (parsed !== null && typeof parsed === 'object') {\n const error: unknown = Reflect.get(parsed, 'error')\n // Stryker disable next-line ConditionalExpression,LogicalOperator: same as\n // above -- a non-object error still reaches the raw-snippet fallback via the\n // catch or the message-not-a-string check, so both boundaries are equivalent.\n if (error !== null && typeof error === 'object') {\n const message: unknown = Reflect.get(error, 'message')\n if (typeof message === 'string' && message.length > 0) return message\n }\n }\n } catch {\n // Not JSON; fall through to the raw snippet.\n }\n return body.length > 300 ? `${body.slice(0, 300)}...` : body\n}\n\n/**\n * Map a non-2xx response to what the engine's retry stack expects: 401\n * becomes a typed provider_auth_error, 429/5xx keep `status` +\n * `responseHeaders` so classify_provider_error marks them retryable\n * (rate_limit honoring retry-after, provider_5xx), and any other 4xx is a\n * permanent provider_error that surfaces as-is.\n */\nasync function response_error(response: Response): Promise<Error> {\n let body = ''\n try {\n body = await response.text()\n } catch {\n // Body is best-effort detail; classification needs only the status.\n }\n const detail = extract_error_message(body)\n const status = response.status\n if (status === 401) {\n return new provider_auth_error(\n 'anthropic',\n `anthropic authentication failed (401): ${detail}`,\n )\n }\n if (status === 429 || status >= 500) {\n const retry_after = response.headers.get('retry-after')\n return Object.assign(\n new Error(`anthropic API error ${status}: ${detail}`),\n { status },\n retry_after !== null ? { responseHeaders: { 'retry-after': retry_after } } : {},\n )\n }\n return new provider_error(`anthropic API error ${status}: ${detail}`, { status, body })\n}\n\n/**\n * A user abort surfaces as the fetch/reader AbortError; retry_turn converts\n * it via its own signal check, so it is rethrown untouched. Everything else\n * is a transport failure wrapped in the `kind: 'network'` shape the shared\n * classify_provider_error marks retryable.\n */\nfunction rethrow_network_failure(err: unknown, abort: AbortSignal): never {\n if (abort.aborted) throw err\n const detail = err instanceof Error ? err.message : String(err)\n throw Object.assign(new Error(`anthropic native: network failure: ${detail}`), {\n kind: 'network',\n })\n}\n\n/**\n * Drain a streaming Messages response: decode bytes, reassemble SSE events,\n * and feed them to the aggregator, which dispatches chunks through\n * req.dispatch_chunk as they arrive. Transport failures mid-read wrap as\n * network errors; aggregator throws (malformed events, mid-stream error\n * events, a rejecting on_chunk) pass through untouched, with the reader\n * cancelled so the connection is released.\n */\nasync function consume_sse_response(response: Response, req: TurnRequest): Promise<TurnResult> {\n const body = response.body\n if (body === null) {\n throw new provider_error('anthropic native: streaming response has no body')\n }\n const dispatch = req.dispatch_chunk ?? (async (): Promise<void> => {})\n const aggregator = create_stream_aggregator(req.step_index, dispatch)\n const reader = body.getReader()\n const text_decoder = new TextDecoder()\n const sse = create_sse_decoder()\n\n const next_bytes = async (): Promise<Uint8Array | undefined> => {\n let step: Awaited<ReturnType<typeof reader.read>>\n try {\n step = await reader.read()\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort)\n }\n return step.done ? undefined : step.value\n }\n\n // Sequential awaits are the contract here: chunk order is an engine\n // invariant and each event mutates aggregator state, so no parallelism.\n try {\n while (true) {\n // oxlint-disable-next-line no-await-in-loop\n const bytes = await next_bytes()\n if (bytes === undefined) break\n for (const data of sse.push(text_decoder.decode(bytes, { stream: true }))) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_event(data)\n }\n }\n } finally {\n // Frees the connection when an error exits the loop early; a no-op on a\n // fully drained stream.\n void reader.cancel().catch(() => {})\n }\n const tail = [...sse.push(text_decoder.decode()), ...sse.flush()]\n for (const data of tail) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_event(data)\n }\n return aggregator.complete()\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 let response: Response\n try {\n response = await fetch(`${base_url}/messages`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n 'x-api-key': api_key,\n 'anthropic-version': ANTHROPIC_VERSION,\n },\n body: JSON.stringify(build_messages_body(req)),\n signal: req.abort,\n })\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort)\n }\n if (!response.ok) throw await response_error(response)\n if (req.stream) return consume_sse_response(response, req)\n const payload: unknown = await response.json()\n return parse_messages_response(payload)\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. Effort levels map to extended-thinking\n * budget tokens.\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 ProviderAdapter,\n type ProviderCapability,\n type RawProviderUsage,\n} from './types.js'\nimport {\n ANTHROPIC_THINKING_BUDGETS,\n create_anthropic_native_adapter,\n} 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 * Map an effort level to Anthropic's extended-thinking provider options.\n *\n * `none` (a zero budget) sends no thinking config at all rather than an\n * explicit \"disabled\" value, so non-reasoning models see a plain request.\n */\nexport function translate_anthropic_effort(effort: EffortLevel): EffortTranslation {\n const budget = ANTHROPIC_THINKING_BUDGETS[effort]\n if (effort === 'none' || budget === 0) {\n return { provider_options: {}, effort_ignored: false }\n }\n return {\n provider_options: {\n anthropic: {\n // @ai-sdk/anthropic reads `budgetTokens` (camelCase) and maps it to the\n // API's `budget_tokens`. Passing snake_case here is silently stripped by\n // the provider's zod schema, so the budget never reaches the wire.\n thinking: { type: 'enabled', budgetTokens: budget },\n },\n },\n effort_ignored: false,\n }\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_anthropic_effort,\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 { z } from 'zod'\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_auth_error,\n provider_capability_error,\n provider_error,\n} from '../errors.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.\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}\n\n/**\n * The wire enum is `low | medium | high` only, so `xhigh` and `max` clamp to\n * `high`, the same clamp as the ai_sdk transport's `reasoningEffort`. `none`\n * omits the field entirely. Non-reasoning models ignore the field\n * server-side; the adapter does not model-sniff.\n */\nexport const OPENAI_COMPATIBLE_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 | { role: 'assistant'; content: string | null; tool_calls?: ChatToolCall[] }\n | { role: 'tool'; tool_call_id: string; content: string }\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`, and tool-call parts become `tool_calls` entries with\n * JSON-stringified arguments.\n */\nfunction to_assistant_message(content: string | AssistantContentPart[]): ChatMessage {\n if (typeof content === 'string') return { role: 'assistant', content }\n const text_parts: string[] = []\n const tool_calls: ChatToolCall[] = []\n for (const part of content) {\n if (part.type === 'text') {\n text_parts.push(part.text)\n } else {\n tool_calls.push({\n id: part.id,\n type: 'function',\n function: { name: part.name, arguments: JSON.stringify(part.input) },\n })\n }\n }\n const text = text_parts.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 return message\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 const out: ChatMessage[] = []\n for (const message of messages) {\n switch (message.role) {\n case 'system':\n out.push({ role: 'system', content: message.content })\n break\n case 'user':\n out.push({ role: 'user', content: to_user_content(message.content, provider) })\n break\n case 'assistant':\n out.push(to_assistant_message(message.content))\n break\n case 'tool':\n out.push({\n role: 'tool',\n tool_call_id: message.tool_call_id,\n content: message.content,\n })\n break\n }\n }\n return out\n}\n\n/**\n * Map fascicle Tool[] to the Chat Completions function-tool shape,\n * converting each zod 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: z.toJSONSchema(tool.input_schema),\n },\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, the\n * effort-derived reasoning_effort, and the dialect's\n * `provider_options.<name>` wire 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 if (req.effort !== 'none') {\n body['reasoning_effort'] = OPENAI_COMPATIBLE_REASONING_EFFORT[req.effort]\n }\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-derived reasoning_effort, the token\n // 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 * 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. There is no cache-write concept on\n * this wire. A missing usage object throws under a strict dialect (a hosted\n * API omitting usage is a broken response) 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 const prompt_details: unknown = Reflect.get(raw, 'prompt_tokens_details')\n if (prompt_details !== null && typeof prompt_details === 'object') {\n const cached = read_number(prompt_details, 'cached_tokens')\n if (cached !== undefined) totals.cached_input_tokens = cached\n }\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 * 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; some servers send '' for\n // no-argument calls, which means the same as '{}'.\n const raw_args: unknown = Reflect.get(fn, 'arguments')\n let input: unknown = {}\n if (typeof raw_args === 'string' && raw_args.length > 0) {\n try {\n input = JSON.parse(raw_args)\n } catch {\n throw new provider_error(\n `${provider} native: tool_calls arguments for ${name} is not valid JSON`,\n )\n }\n }\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 (next step) rebuilds this same\n * 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 return {\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(Reflect.get(payload, 'usage'), dialect),\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, and\n * `delta.tool_calls[]` entries accumulate `function.arguments` string deltas\n * keyed by their `index` field. 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. Usage rides the final pre-DONE frame\n * (stream_options.include_usage); 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 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 const on_choice = async (choice: object): Promise<void> => {\n const delta: unknown = Reflect.get(choice, 'delta')\n if (delta !== null && typeof delta === 'object') {\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 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 const message: Record<string, unknown> = {\n role: 'assistant',\n content: text.length > 0 || ordered.length === 0 ? text : null,\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/** OpenAI-style error bodies are `{ error: { message } }`; fall back to the raw body. */\nfunction extract_error_message(body: string): string {\n if (body.length === 0) return '(empty body)'\n try {\n const parsed: unknown = JSON.parse(body)\n if (parsed !== null && typeof parsed === 'object') {\n const error: unknown = Reflect.get(parsed, 'error')\n if (error !== null && typeof error === 'object') {\n const message: unknown = Reflect.get(error, 'message')\n if (typeof message === 'string' && message.length > 0) return message\n }\n }\n } catch {\n // Not JSON; fall through to the raw snippet.\n }\n return body.length > 300 ? `${body.slice(0, 300)}...` : body\n}\n\n/**\n * Map a non-2xx response to what the engine's retry stack expects: 401\n * becomes a typed provider_auth_error, 429/5xx keep `status` +\n * `responseHeaders` so classify_provider_error marks them retryable\n * (rate_limit honoring retry-after, provider_5xx), and any other 4xx is a\n * permanent provider_error that surfaces as-is.\n */\nasync function response_error(response: Response, provider: string): Promise<Error> {\n let body = ''\n try {\n body = await response.text()\n } catch {\n // Body is best-effort detail; classification needs only the status.\n }\n const detail = extract_error_message(body)\n const status = response.status\n if (status === 401) {\n return new provider_auth_error(\n provider,\n `${provider} authentication failed (401): ${detail}`,\n )\n }\n if (status === 429 || status >= 500) {\n const retry_after = response.headers.get('retry-after')\n return Object.assign(\n new Error(`${provider} API error ${status}: ${detail}`),\n { status },\n retry_after !== null ? { responseHeaders: { 'retry-after': retry_after } } : {},\n )\n }\n return new provider_error(`${provider} API error ${status}: ${detail}`, { status, body })\n}\n\n/**\n * A user abort surfaces as the fetch AbortError; retry_turn converts it via\n * its own signal check, so it is rethrown untouched. Everything else is a\n * transport failure wrapped in the `kind: 'network'` shape the shared\n * classify_provider_error marks retryable.\n */\nfunction rethrow_network_failure(err: unknown, abort: AbortSignal, provider: string): never {\n if (abort.aborted) throw err\n const detail = err instanceof Error ? err.message : String(err)\n throw Object.assign(new Error(`${provider} native: network failure: ${detail}`), {\n kind: 'network',\n })\n}\n\n/**\n * Drain a streaming chat/completions response: decode bytes, reassemble SSE\n * events, and feed each data payload to the aggregator, which dispatches\n * chunks through req.dispatch_chunk as they arrive. Transport failures\n * mid-read wrap as network errors; aggregator throws (malformed frames, a\n * rejecting on_chunk) pass through untouched, with the reader cancelled so\n * the connection is released.\n */\nasync function consume_sse_response(\n response: Response,\n req: TurnRequest,\n dialect: OpenAICompatibleDialect,\n): Promise<TurnResult> {\n const body = response.body\n if (body === null) {\n throw new provider_error(`${dialect.name} native: streaming response has no body`)\n }\n const dispatch = req.dispatch_chunk ?? (async (): Promise<void> => {})\n const aggregator = create_chat_stream_aggregator(dialect, req.step_index, dispatch)\n const reader = body.getReader()\n const text_decoder = new TextDecoder()\n const sse = create_sse_decoder()\n\n const next_bytes = async (): Promise<Uint8Array | undefined> => {\n let step: Awaited<ReturnType<typeof reader.read>>\n try {\n step = await reader.read()\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort, dialect.name)\n }\n return step.done ? undefined : step.value\n }\n\n // Sequential awaits are the contract here: chunk order is an engine\n // invariant and each frame mutates aggregator state, so no parallelism.\n try {\n while (true) {\n // oxlint-disable-next-line no-await-in-loop\n const bytes = await next_bytes()\n if (bytes === undefined) break\n for (const data of sse.push(text_decoder.decode(bytes, { stream: true }))) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_data(data)\n }\n }\n } finally {\n // Frees the connection when an error exits the loop early; a no-op on a\n // fully drained stream.\n void reader.cancel().catch(() => {})\n }\n const tail = [...sse.push(text_decoder.decode()), ...sse.flush()]\n for (const data of tail) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_data(data)\n }\n return aggregator.complete()\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 let response: Response\n try {\n response = await fetch(`${base_url}/chat/completions`, {\n method: 'POST',\n headers,\n body: JSON.stringify(build_chat_completions_body(req, dialect)),\n signal: req.abort,\n })\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort, dialect.name)\n }\n if (!response.ok) throw await response_error(response, dialect.name)\n if (req.stream) return consume_sse_response(response, req, dialect)\n const payload: unknown = await response.json()\n return parse_chat_completion(payload, dialect)\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`. Effort maps to the o-series `reasoning_effort` string.\n * Non-reasoning models silently ignore the effort field (providers without\n * reasoning support drop it; signaling is model-specific and handled by the\n * orchestrator via the `effort_ignored` flag).\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 {\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// OpenAI's reasoning effort enum is `low | medium | high` only.\n// `xhigh` and `max` clamp to `high` until OpenAI exposes more levels.\nconst OPENAI_REASONING_EFFORT: Record<Exclude<EffortLevel, 'none'>, string> = {\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'high',\n max: 'high',\n}\n\n/**\n * Map an EffortLevel to OpenAI's `reasoningEffort` provider option.\n */\nexport function translate_openai_effort(effort: EffortLevel): EffortTranslation {\n if (effort === 'none') {\n return { provider_options: {}, effort_ignored: false }\n }\n return {\n provider_options: {\n openai: { reasoningEffort: OPENAI_REASONING_EFFORT[effort] },\n },\n effort_ignored: false,\n }\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 = typeof init.api_key === 'string' ? init.api_key : ''\n const base_url =\n typeof init.base_url === 'string' && init.base_url.length > 0 ? init.base_url : 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 ...(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_openai_effort,\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 maps to the\n * `thinking_budget` provider option.\n */\n\nimport type { EffortLevel, ProviderInit, UsageTotals } from '../types.js'\nimport {\n default_normalize_usage,\n load_optional_peer,\n type AiSdkProviderAdapter,\n type EffortTranslation,\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// @ai-sdk/google's `thinkingConfig.thinkingBudget` is a token count (number),\n// not an enum: passing a string fails the provider's zod validation. Gemini 2.5\n// Pro accepts up to 32768 thinking tokens; lighter models clamp the high end.\n// `none` omits thinkingConfig entirely (see translate_google_effort).\nconst GOOGLE_THINKING_BUDGET: Record<Exclude<EffortLevel, 'none'>, number> = {\n low: 1024,\n medium: 8192,\n high: 24576,\n xhigh: 32768,\n max: 32768,\n}\n\n/**\n * Map an EffortLevel to Google's `thinkingConfig.thinkingBudget` provider\n * option.\n */\nexport function translate_google_effort(effort: EffortLevel): EffortTranslation {\n if (effort === 'none') {\n return { provider_options: {}, effort_ignored: false }\n }\n return {\n provider_options: {\n google: { thinkingConfig: { thinkingBudget: GOOGLE_THINKING_BUDGET[effort] } },\n },\n effort_ignored: false,\n }\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_google_effort,\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_auth_error,\n provider_capability_error,\n provider_error,\n} from '../errors.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.\n */\nfunction to_assistant_message(content: string | AssistantContentPart[]): OllamaChatMessage {\n if (typeof content === 'string') return { role: 'assistant', content }\n const text_parts: string[] = []\n const tool_calls: OllamaToolCall[] = []\n for (const part of content) {\n if (part.type === 'text') {\n text_parts.push(part.text)\n } else {\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 tool_calls.push({ function: { name: part.name, arguments: part.input } })\n }\n }\n const message: OllamaChatMessage = { role: 'assistant', content: text_parts.join('') }\n if (tool_calls.length > 0) message.tool_calls = tool_calls\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 const out: OllamaChatMessage[] = []\n for (const message of messages) {\n switch (message.role) {\n case 'system':\n out.push({ role: 'system', content: message.content })\n break\n case 'user':\n out.push({ role: 'user', content: to_user_content(message.content) })\n break\n case 'assistant':\n out.push(to_assistant_message(message.content))\n break\n case 'tool':\n out.push({ role: 'tool', tool_name: message.name, content: message.content })\n break\n }\n }\n return out\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\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 let input: unknown = {}\n if (typeof raw_args === 'string' && raw_args.length > 0) {\n try {\n input = JSON.parse(raw_args)\n } catch {\n throw new provider_error(\n `ollama native: tool_calls arguments for ${name} is not valid JSON`,\n )\n }\n } else if (raw_args !== null && typeof raw_args === 'object') {\n input = raw_args\n }\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 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 }\n}\n\n/**\n * Append one decoded line to `out`, trimming a trailing `\\r` and dropping\n * blank lines; JSON parsing is the aggregator's job.\n */\nfunction take_line(raw: string, out: string[]): void {\n const line = raw.endsWith('\\r') ? raw.slice(0, -1) : raw\n if (line.trim().length > 0) out.push(line)\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 * flush() drains a final line left open when the stream ends without a\n * trailing newline.\n */\nexport function create_ndjson_decoder(): {\n push: (text: string) => string[]\n flush: () => string[]\n} {\n let buffer = ''\n\n return {\n push(text: string): string[] {\n buffer += text\n const out: string[] = []\n let newline = buffer.indexOf('\\n')\n while (newline >= 0) {\n take_line(buffer.slice(0, newline), out)\n buffer = buffer.slice(newline + 1)\n newline = buffer.indexOf('\\n')\n }\n return out\n },\n flush(): string[] {\n const out: string[] = []\n if (buffer.length > 0) take_line(buffer, out)\n buffer = ''\n return out\n },\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 * stream that ends without one is truncated output, so complete() fails\n * loud instead of returning a partial turn. complete() feeds the synthetic\n * payload through parse_ollama_chat, which is what makes the streamed\n * TurnResult equal the non-streamed one by construction.\n */\nexport function create_ollama_stream_aggregator(\n step_index: number,\n dispatch: (chunk: StreamChunk) => Promise<void>,\n): {\n handle_line: (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\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(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 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 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 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 },\n step_index,\n )\n },\n }\n}\n\n/** Ollama error bodies are `{ error: \"message\" }`; tolerate the nested OpenAI shape too. */\nfunction extract_error_message(body: string): string {\n if (body.length === 0) return '(empty body)'\n try {\n const parsed: unknown = JSON.parse(body)\n if (parsed !== null && typeof parsed === 'object') {\n const error: unknown = Reflect.get(parsed, 'error')\n if (typeof error === 'string' && error.length > 0) return error\n if (error !== null && typeof error === 'object') {\n const message: unknown = Reflect.get(error, 'message')\n if (typeof message === 'string' && message.length > 0) return message\n }\n }\n } catch {\n // Not JSON; fall through to the raw snippet.\n }\n return body.length > 300 ? `${body.slice(0, 300)}...` : body\n}\n\n/**\n * Map a non-2xx response to what the engine's retry stack expects: 401\n * becomes a typed provider_auth_error (rare locally, but base_url may point\n * at a fronted daemon), 429/5xx keep `status` + `responseHeaders` so\n * classify_provider_error marks them retryable, and any other 4xx (a missing\n * model, a malformed request) is a permanent provider_error.\n */\nasync function response_error(response: Response): Promise<Error> {\n let body = ''\n try {\n body = await response.text()\n } catch {\n // Body is best-effort detail; classification needs only the status.\n }\n const detail = extract_error_message(body)\n const status = response.status\n if (status === 401) {\n return new provider_auth_error('ollama', `ollama authentication failed (401): ${detail}`)\n }\n if (status === 429 || status >= 500) {\n const retry_after = response.headers.get('retry-after')\n return Object.assign(\n new Error(`ollama API error ${status}: ${detail}`),\n { status },\n retry_after !== null ? { responseHeaders: { 'retry-after': retry_after } } : {},\n )\n }\n return new provider_error(`ollama API error ${status}: ${detail}`, { status, body })\n}\n\n/**\n * A user abort surfaces as the fetch AbortError; retry_turn converts it via\n * its own signal check, so it is rethrown untouched. Everything else is a\n * transport failure wrapped in the `kind: 'network'` shape the shared\n * classify_provider_error marks retryable.\n */\nfunction rethrow_network_failure(err: unknown, abort: AbortSignal): never {\n if (abort.aborted) throw err\n const detail = err instanceof Error ? err.message : String(err)\n throw Object.assign(new Error(`ollama native: network failure: ${detail}`), {\n kind: 'network',\n })\n}\n\n/**\n * Drain a streaming /api/chat response: decode bytes, reassemble NDJSON\n * lines, and feed each to the aggregator, which dispatches chunks through\n * req.dispatch_chunk as they arrive. Transport failures mid-read wrap as\n * network errors; aggregator throws (malformed frames, a rejecting on_chunk)\n * pass through untouched, with the reader cancelled so the connection is\n * released.\n */\nasync function consume_ndjson_response(response: Response, req: TurnRequest): Promise<TurnResult> {\n const body = response.body\n if (body === null) {\n throw new provider_error('ollama native: streaming response has no body')\n }\n const dispatch = req.dispatch_chunk ?? (async (): Promise<void> => {})\n const aggregator = create_ollama_stream_aggregator(req.step_index, dispatch)\n const reader = body.getReader()\n const text_decoder = new TextDecoder()\n const ndjson = create_ndjson_decoder()\n\n const next_bytes = async (): Promise<Uint8Array | undefined> => {\n let step: Awaited<ReturnType<typeof reader.read>>\n try {\n step = await reader.read()\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort)\n }\n return step.done ? undefined : step.value\n }\n\n // Sequential awaits are the contract here: chunk order is an engine\n // invariant and each frame mutates aggregator state, so no parallelism.\n try {\n while (true) {\n // oxlint-disable-next-line no-await-in-loop\n const bytes = await next_bytes()\n if (bytes === undefined) break\n for (const line of ndjson.push(text_decoder.decode(bytes, { stream: true }))) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_line(line)\n }\n }\n } finally {\n // Frees the connection when an error exits the loop early; a no-op on a\n // fully drained stream.\n void reader.cancel().catch(() => {})\n }\n const tail = [...ndjson.push(text_decoder.decode()), ...ndjson.flush()]\n for (const line of tail) {\n // oxlint-disable-next-line no-await-in-loop\n await aggregator.handle_line(line)\n }\n return aggregator.complete()\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 let response: Response\n try {\n response = await fetch(`${base_url}/api/chat`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(build_ollama_chat_body(req)),\n signal: req.abort,\n })\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort)\n }\n if (!response.ok) throw await response_error(response)\n if (req.stream) return consume_ndjson_response(response, req)\n const payload: unknown = await response.json()\n return parse_ollama_chat(payload, req.step_index)\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, UsageTotals } from '../types.js'\nimport {\n default_normalize_usage,\n load_optional_peer,\n resolve_transport,\n type AiSdkProviderAdapter,\n type EffortTranslation,\n type ProviderAdapter,\n type ProviderCapability,\n type RawProviderUsage,\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.\n */\nexport function normalize_ollama_usage(raw: RawProviderUsage | undefined): UsageTotals {\n // default_normalize_usage already maps undefined to a zero total; Ollama\n // additionally never reports cache or reasoning tokens, so strip them.\n const base = default_normalize_usage(raw)\n delete base.cached_input_tokens\n delete base.cache_write_tokens\n delete base.reasoning_tokens\n return base\n}\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. No reasoning support.\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 {\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.\n */\nexport function normalize_lmstudio_usage(raw: RawProviderUsage | undefined): UsageTotals {\n // default_normalize_usage already maps undefined to a zero total; LM Studio\n // additionally never reports cache or reasoning tokens, so strip them.\n const base = default_normalize_usage(raw)\n delete base.cached_input_tokens\n delete base.cache_write_tokens\n delete base.reasoning_tokens\n return base\n}\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 }\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. The ai_sdk backend translates\n * effort to the OpenRouter `reasoning.effort` shape; the native core maps it\n * to the flat `reasoning_effort` field. Effort_ignored is false so that the\n * orchestrator does not emit effort_ignored indiscriminately; upstream\n * 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 {\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, and strict usage. The\n * empty-api_key guard 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 = typeof init.api_key === 'string' ? init.api_key : ''\n const base_url =\n typeof init.base_url === 'string' && init.base_url.length > 0 ? init.base_url : 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 ...(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. Supply an `api_key` (Bedrock bearer\n * token, takes precedence over SigV4), SigV4 keys (`access_key_id` /\n * `secret_access_key`, optional `session_token`), or omit all three to use the\n * ambient AWS credential chain. Effort maps to the Anthropic extended-thinking\n * budget, emitted under the bedrock `reasoningConfig` provider option; models\n * that do not support reasoning drop the field upstream.\n */\n\nimport type { EffortLevel, ProviderInit, UsageTotals } from '../types.js'\nimport {\n default_normalize_usage,\n load_optional_peer,\n type AiSdkProviderAdapter,\n type EffortTranslation,\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 }) => (model_id: string) => unknown\n}\n\n// Bedrock hosts Anthropic Claude models; reasoning maps to the same\n// extended-thinking budget the anthropic adapter uses, emitted under the bedrock\n// provider option. Budgets stay within Bedrock's 1024..64000 window.\nconst BEDROCK_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\n/**\n * Map an EffortLevel to the Bedrock `reasoningConfig` provider option.\n */\nexport function translate_bedrock_effort(effort: EffortLevel): EffortTranslation {\n // `none` is the only level with a 0 budget, so the budget alone decides\n // whether reasoning is requested.\n const budget = BEDROCK_THINKING_BUDGETS[effort]\n if (budget === 0) {\n return { provider_options: {}, effort_ignored: false }\n }\n return {\n provider_options: {\n bedrock: {\n reasoningConfig: { type: 'enabled', budgetTokens: budget },\n },\n },\n effort_ignored: false,\n }\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\n/**\n * Build the Bedrock ai_sdk adapter: validates the required region, resolves\n * the chosen auth mode (bearer token, SigV4 keys, or the ambient AWS\n * credential chain), and lazily loads @ai-sdk/amazon-bedrock to build models.\n */\nexport const create_bedrock_adapter = (init: ProviderInit): AiSdkProviderAdapter => {\n const region = typeof init['region'] === 'string' ? init['region'] : ''\n if (region.length === 0) {\n throw new engine_config_error('bedrock provider requires a non-empty region', 'bedrock')\n }\n const api_key = typeof init.api_key === 'string' ? init.api_key : undefined\n const access_key_id = typeof init['access_key_id'] === 'string' ? init['access_key_id'] : undefined\n const secret_access_key =\n typeof init['secret_access_key'] === 'string' ? init['secret_access_key'] : undefined\n const session_token = typeof init['session_token'] === 'string' ? init['session_token'] : undefined\n const base_url = typeof init.base_url === 'string' ? init.base_url : undefined\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 config: {\n region: string\n accessKeyId?: string\n secretAccessKey?: string\n sessionToken?: string\n apiKey?: string\n baseURL?: string\n } = { region }\n if (api_key !== undefined) config.apiKey = api_key\n if (access_key_id !== undefined) config.accessKeyId = access_key_id\n if (secret_access_key !== undefined) config.secretAccessKey = secret_access_key\n if (session_token !== undefined) config.sessionToken = session_token\n if (base_url !== undefined) config.baseURL = base_url\n const provider = sdk.createAmazonBedrock(config)\n return provider(model_id)\n },\n translate_effort: translate_bedrock_effort,\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, cost decomposition multipliers, and the auth\n * 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 CACHE_READ_MULTIPLIER = 0.1\n\nexport const CACHE_WRITE_MULTIPLIER = 1.25\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\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 * 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: Record<string, string> = {}\n const inherit_env = config.inherit_env !== false\n if (inherit_env) {\n if (auth_mode === 'oauth') {\n for (const [k, v] of Object.entries(process.env)) {\n if (typeof v === 'string') env[k] = v\n }\n } else {\n for (const key of STANDARD_ENV_KEYS) {\n const v = process.env[key]\n if (typeof v === 'string') env[key] = v\n }\n }\n }\n if (caller_env !== undefined) {\n for (const [k, v] of Object.entries(caller_env)) {\n if (typeof v === 'string') env[k] = v\n }\n }\n if (auth_mode === 'oauth') {\n delete env['ANTHROPIC_API_KEY']\n return env\n }\n if (auth_mode === 'api_key') {\n const api_key = typeof config.api_key === 'string' ? config.api_key : ''\n env['ANTHROPIC_API_KEY'] = api_key\n return env\n }\n if (typeof config.api_key === 'string' && config.api_key.length > 0) {\n env['ANTHROPIC_API_KEY'] = config.api_key\n }\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}\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 * Install the process-wide `exit` handler that SIGKILLs every live child\n * across every spawn registry. Calling this more than once is a no-op.\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 install_exit_handler_once(): void {\n if (exit_handler_installed) return\n exit_handler_installed = true\n const handler = (): 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 process.on('exit', handler)\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 \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('binary_not_found', `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('binary_not_found', 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 Zod-validated via `cli_event_schema` (a\n * `z.discriminatedUnion` over the recognized CLI event types). Per-entry\n * content arrays use `.transform` to silently drop invalid entries rather\n * than rejecting the whole event; this preserves forward compatibility with\n * new CLI content types.\n */\n\nimport { z } from 'zod'\nimport type { TrajectoryLogger } from '#core'\nimport type { StreamChunk, UsageTotals } from '../../types.js'\n\nconst cli_usage_schema = z.object({\n input_tokens: z.number().optional(),\n output_tokens: z.number().optional(),\n cache_read_input_tokens: z.number().optional(),\n cache_creation_input_tokens: z.number().optional(),\n})\n\nconst assistant_text_part_schema = z.object({\n type: z.literal('text'),\n text: z.string(),\n})\n\nconst assistant_tool_use_part_schema = z.object({\n type: z.literal('tool_use'),\n id: z.string(),\n name: z.string(),\n input: z.unknown(),\n})\n\nconst assistant_content_part_schema = z.discriminatedUnion('type', [\n assistant_text_part_schema,\n assistant_tool_use_part_schema,\n])\n\nconst user_tool_result_part_schema = z.object({\n type: z.literal('tool_result'),\n tool_use_id: z.string(),\n content: z.unknown().optional(),\n is_error: z.boolean().optional(),\n})\n\ntype AssistantContentPart = z.infer<typeof assistant_content_part_schema>\ntype UserToolResultPart = z.infer<typeof user_tool_result_part_schema>\n\nconst assistant_content_array_schema = z.array(z.unknown()).transform((arr) => {\n const out: AssistantContentPart[] = []\n for (const entry of arr) {\n const result = assistant_content_part_schema.safeParse(entry)\n if (result.success) out.push(result.data)\n }\n return out\n})\n\nconst user_content_array_schema = z.array(z.unknown()).transform((arr) => {\n const out: UserToolResultPart[] = []\n for (const entry of arr) {\n const result = user_tool_result_part_schema.safeParse(entry)\n if (result.success) out.push(result.data)\n }\n return out\n})\n\nconst system_event_schema = z.object({\n type: z.literal('system'),\n subtype: z.string().optional(),\n session_id: z.string().optional(),\n model: z.string().optional(),\n})\n\nconst assistant_event_schema = z.object({\n type: z.literal('assistant'),\n message: z.object({ content: assistant_content_array_schema }),\n})\n\nconst user_event_schema = z.object({\n type: z.literal('user'),\n message: z.object({ content: user_content_array_schema }),\n})\n\nconst result_event_schema = z.object({\n type: z.literal('result'),\n subtype: z.string().optional(),\n session_id: z.string().optional(),\n total_cost_usd: z.number().optional(),\n duration_ms: z.number().optional(),\n is_error: z.boolean().optional(),\n usage: cli_usage_schema.optional(),\n result: z.string().optional(),\n})\n\nconst rate_limit_info_schema = z.object({\n status: z.string().optional(),\n resetsAt: z.number().optional(),\n rateLimitType: z.string().optional(),\n overageStatus: z.string().optional(),\n overageResetsAt: z.number().optional(),\n isUsingOverage: z.boolean().optional(),\n})\n\nconst rate_limit_event_schema = z.object({\n type: z.literal('rate_limit_event'),\n rate_limit_info: rate_limit_info_schema.optional(),\n session_id: z.string().optional(),\n})\n\nconst cli_event_schema = z.discriminatedUnion('type', [\n system_event_schema,\n assistant_event_schema,\n user_event_schema,\n result_event_schema,\n rate_limit_event_schema,\n])\n\nexport type CliUsageRaw = z.infer<typeof cli_usage_schema>\nexport type CliAssistantContent = AssistantContentPart\nexport type CliUserContent = UserToolResultPart\nexport type CliEvent = z.infer<typeof cli_event_schema>\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 final_text: string\n readonly final_usage: UsageTotals\n readonly turns: ReadonlyArray<TurnCollected>\n readonly is_error: boolean\n readonly received_result: boolean\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 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}\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 */\nfunction map_usage(raw: CliUsageRaw | undefined): UsageTotals {\n if (raw === undefined) return { input_tokens: 0, output_tokens: 0 }\n const out: UsageTotals = {\n input_tokens: typeof raw.input_tokens === 'number' ? raw.input_tokens : 0,\n output_tokens: typeof raw.output_tokens === 'number' ? raw.output_tokens : 0,\n }\n if (typeof raw.cache_read_input_tokens === 'number') {\n out.cached_input_tokens = raw.cache_read_input_tokens\n }\n if (typeof raw.cache_creation_input_tokens === 'number') {\n out.cache_write_tokens = raw.cache_creation_input_tokens\n }\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 * Validate a parsed JSON value against `cli_event_schema`, returning\n * `undefined` instead of throwing on a mismatch.\n */\nfunction as_event(raw: unknown): CliEvent | undefined {\n const result = cli_event_schema.safeParse(raw)\n return result.success ? result.data : undefined\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\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 * duration, and final usage, flush the last in-progress turn, and emit the\n * 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 (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 */\nexport async 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 } = {\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 return base\n}\n","/**\n * Cost decomposition 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 synthesizes a\n * component split by computing an implied per-million-token rate from the\n * total and allocating that rate to each token component, weighted by\n * `CACHE_READ_MULTIPLIER` and `CACHE_WRITE_MULTIPLIER`.\n *\n * Per-turn allocation splits `total_cost_usd` across turns proportional to\n * each turn's output tokens. Sum equality is preserved exactly by giving\n * any floating-point rounding remainder to the last turn.\n */\n\nimport type { CostBreakdown, UsageTotals } from '../../types.js'\nimport { CACHE_READ_MULTIPLIER, CACHE_WRITE_MULTIPLIER } from './constants.js'\n\n/**\n * Split a single `total_cost_usd` figure into an input/output cost\n * breakdown, weighted 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. Returns an all-zero\n * estimate when there's no usage or 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\nexport type TurnUsage = {\n readonly output_tokens: number\n readonly usage: UsageTotals\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\n const total_output = turns.reduce((sum, t) => sum + Math.max(0, t.output_tokens), 0)\n\n const per_turn_totals: number[] = Array.from({ length: turns.length }, () => 0)\n if (total_output === 0) {\n const equal_share = total_cost_usd / turns.length\n for (let i = 0; i < turns.length; i += 1) per_turn_totals[i] = equal_share\n } else {\n for (let i = 0; i < turns.length; i += 1) {\n const t = turns[i]\n if (t === undefined) continue\n const share = Math.max(0, t.output_tokens) / total_output\n per_turn_totals[i] = total_cost_usd * share\n }\n }\n\n const running_sum = per_turn_totals.reduce((a, b) => a + b, 0)\n const remainder = total_cost_usd - running_sum\n if (turns.length > 0) {\n const last_index = turns.length - 1\n const current = per_turn_totals[last_index] ?? 0\n per_turn_totals[last_index] = current + remainder\n }\n\n const out: CostBreakdown[] = []\n for (let i = 0; i < turns.length; i += 1) {\n const t = turns[i]\n if (t === undefined) continue\n const total = per_turn_totals[i] ?? 0\n out.push(decompose_total_cost(total, t.usage))\n }\n return out\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 * - provider_reported.claude_cli with session_id + duration_ms\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 { z } from 'zod'\nimport type {\n ResolvedModel,\n CostBreakdown,\n FinishReason,\n GenerateResult,\n StepRecord,\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, 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 step_index: number,\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\nexport type BuildResultInput<T> = {\n readonly parsed: ParsedStream\n readonly resolved: ResolvedModel\n readonly schema?: z.ZodType<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 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(turn.step_index, 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 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 }\n provider_reported['claude_cli'] = reported\n }\n\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const content_raw = input.parsed_content ?? (parsed.final_text 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 type { z } from 'zod'\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; error: unknown }\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 error from the\n * FIRST candidate that parsed as JSON: that error reflects the model's\n * primary output and is what a repair prompt should feed back. Later\n * candidates (e.g. the bracket-slice fallback) often produce noisy errors\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 */\nexport function parse_with_schema<t>(\n schema: z.ZodType<t>,\n text: string,\n): ParseOutcome<t> {\n const candidates = json_candidates(text)\n let json_parse_error: unknown = new Error('No JSON-parseable content found in model output')\n let first_schema_error: unknown\n for (const candidate of candidates) {\n let parsed: unknown\n try {\n parsed = JSON.parse(candidate)\n } catch (err: unknown) {\n json_parse_error = err\n continue\n }\n const result = schema.safeParse(parsed)\n if (result.success) return { ok: true, value: result.data }\n if (first_schema_error === undefined) first_schema_error = result.error\n }\n return { ok: false, error: first_schema_error ?? json_parse_error }\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(zod_error: unknown): Message {\n return { role: 'user', content: build_repair_prompt_text(zod_error) }\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(zod_error: unknown): string {\n const serialized = format_zod_error(zod_error)\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 zod error and the raw model text.\n * Called by the orchestrator when all repair attempts are exhausted.\n */\nexport function throw_schema_validation(zod_error: unknown, raw_text: string): never {\n throw new schema_validation_error(\n `schema validation failed: ${format_zod_error(zod_error)}`,\n zod_error,\n raw_text,\n )\n}\n\n/**\n * Render an unknown error value as a display string.\n *\n * Handles `Error` instances, plain strings, and objects with a string\n * `message` directly; falls back to `JSON.stringify`, and finally to a fixed\n * placeholder if even that throws.\n */\nexport function format_zod_error(err: unknown): string {\n if (err === null || err === undefined) return 'unknown error'\n if (typeof err === 'string') return err\n if (err instanceof Error) return err.message\n if (typeof err === 'object' && 'message' in err) {\n const msg = (err as { message?: unknown }).message\n if (typeof msg === 'string') return msg\n }\n try {\n return JSON.stringify(err) ?? 'unknown error'\n } catch {\n return 'unknown error'\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 UsageTotals,\n} from './types.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.\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 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 with its finish reason and output token count.\n */\nexport function record_response_received(\n trajectory: TrajectoryLogger | undefined,\n step_index: number,\n output_tokens: number | undefined,\n finish_reason: FinishReason,\n): void {\n if (trajectory === undefined) return\n const event: Record<string, unknown> = {\n kind: 'response_received',\n step_index,\n finish_reason,\n }\n if (output_tokens !== undefined) event['output_tokens'] = output_tokens\n trajectory.record({ kind: 'response_received', ...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 */\nexport function record_cost(\n trajectory: TrajectoryLogger | undefined,\n step_index: number,\n cost: CostBreakdown,\n source: CostEventSource,\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 (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 zod_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 + zod validation. Persists the raw model output and a\n * formatted zod issues summary to the trajectory so the failure is debuggable\n * 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 zod_issues: meta.zod_issues,\n raw_text: meta.raw_text,\n })\n}\n\nexport type SalvagedCallEventEntry = {\n tool_call_id: string\n name: string\n format: 'hermes' | 'json' | 'qwen_xml'\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 { z } from 'zod'\nimport type {\n ResolvedModel,\n EffortLevel,\n GenerateOptions,\n GenerateResult,\n Message,\n ProviderInit,\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} from './stream_parse.js'\nimport { build_generate_result } from './stream_result.js'\nimport {\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 {\n build_repair_prompt_text,\n format_zod_error,\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// 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 Zod schema to the JSON Schema string the CLI's\n * `--json-schema` flag expects.\n */\nexport function compile_schema<T>(schema: z.ZodType<T>): string {\n // `claude --json-schema` rejects a top-level $schema/$id (the\n // draft-2020-12 URI z.toJSONSchema stamps); strip them, the field\n // constraints alone drive constrained decode.\n const { $schema: _schema, $id: _id, ...json } = z.toJSONSchema(schema)\n return JSON.stringify(json)\n}\n\n/**\n * Turn a closed CLI subprocess's exit code, signal, and stderr into an\n * `Error`.\n *\n * Checks stderr for an auth failure first, then for a missing sandbox\n * binary, then falls back to a generic exit-code error. The stderr\n * snippet attached to each error is truncated to 512 bytes.\n */\nexport function classify_close_error(\n code: number | null,\n signal: NodeJS.Signals | null,\n stderr: string,\n): Error {\n const snippet = stderr.slice(0, 512)\n if (stderr_is_auth_failure(stderr)) {\n return new provider_auth_error(\n PROVIDER_NAME,\n `claude CLI reported an auth failure: ${snippet}`,\n { refresh_command: 'claude login' },\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}: ${snippet}`\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 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: {},\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 spawn_args: Parameters<typeof spawn_runtime.spawn_cli>[0] = {\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 }\n if (args.cwd !== undefined) {\n (spawn_args as { cwd?: string }).cwd = args.cwd\n }\n if (args.abort !== undefined) {\n (spawn_args as { abort?: AbortSignal }).abort = args.abort\n }\n\n const session = await spawn_runtime.spawn_cli(spawn_args)\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)\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/**\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 const option_ignored = create_option_ignored_dedup(trajectory)\n\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 const user_count = count_user_messages(opts.prompt)\n if (user_count >= 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\n const tools_list: ReadonlyArray<Tool> = opts.tools ?? []\n const tool_bridge: ToolBridgeMode = call_opts.tool_bridge ?? 'allowlist_only'\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; tools with execute closures cannot run under claude_cli',\n )\n }\n }\n\n const tool_names: string[] = tools_list.map((t) => t.name)\n const merged_allowed_tools = merge_allowed_tools(call_opts.allowed_tools, tool_names)\n if (tools_list.length > 0 && tool_bridge === 'allowlist_only' && trajectory !== undefined) {\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 let compiled_schema: string | undefined\n if (opts.schema !== undefined) {\n compiled_schema = compile_schema(opts.schema)\n } else if (\n typeof call_opts.output_json_schema === 'string' &&\n call_opts.output_json_schema.length > 0\n ) {\n compiled_schema = call_opts.output_json_schema\n }\n\n const system_from_prompt = extract_system_text(opts.prompt)\n const merged_system = merge_system(\n opts.system ?? system_from_prompt,\n call_opts.append_system_prompt,\n )\n\n const stdin_text = extract_prompt_text(opts.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\n const sandbox_plan = build_sandbox_plan(resolved_binary, config.sandbox)\n\n const cwd = config.default_cwd\n const dispatch_chunk =\n opts.on_chunk !== undefined\n ? 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 : undefined\n\n const controller = new AbortController()\n in_flight.add(controller)\n\n const caller_abort = opts.abort\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\n const generate_span = start_generate_span(trajectory, {\n model: opts.model ?? resolved.model_id,\n provider: PROVIDER_NAME,\n model_id: resolved.model_id,\n has_tools: tools_list.length > 0,\n has_schema: opts.schema !== undefined,\n streaming: dispatch_chunk !== undefined,\n })\n let first_step_span: string | undefined = start_step_span(trajectory, 0)\n\n const base_args: RunArgs = {\n model_id: resolved.model_id,\n stdin_text,\n merged_system,\n merged_allowed_tools,\n call_opts,\n compiled_schema,\n env,\n spawn_cmd: sandbox_plan.spawn_cmd,\n prefix_args: sandbox_plan.prefix_args,\n 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 let parsed = first_outcome.parsed\n\n let parsed_content: T | undefined\n if (opts.schema !== undefined) {\n const max_repairs = opts.schema_repair_attempts ?? 1\n let repairs_done = 0\n for (;;) {\n const attempt = parse_with_schema(opts.schema, parsed.final_text)\n if (attempt.ok) {\n parsed_content = attempt.value\n break\n }\n record_schema_validation_failed(trajectory, {\n attempt: repairs_done === 0 ? 'initial' : 'repair',\n zod_issues: format_zod_error(attempt.error),\n raw_text: parsed.final_text,\n })\n if (repairs_done >= max_repairs) {\n throw new schema_validation_error(\n max_repairs === 0\n ? 'schema validation failed and repair is disabled (schema_repair_attempts: 0)'\n : `schema validation failed after ${String(max_repairs)} repair attempt${max_repairs === 1 ? '' : 's'}`,\n attempt.error,\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.error,\n parsed.final_text,\n )\n }\n const repair_call_opts: ClaudeCliCallOptions = {\n ...call_opts,\n session_id: repair_session_id,\n }\n const repair_outcome = await run_cli(spawn_runtime, {\n ...base_args,\n stdin_text: build_repair_prompt_text(attempt.error),\n call_opts: repair_call_opts,\n })\n parsed = repair_outcome.parsed\n repairs_done += 1\n }\n }\n\n\n const result_input: {\n parsed: typeof parsed\n resolved: ResolvedModel\n schema?: typeof opts.schema\n parsed_content?: T\n } = {\n parsed,\n resolved,\n }\n if (opts.schema !== undefined) result_input.schema = opts.schema\n if (parsed_content !== undefined) result_input.parsed_content = parsed_content\n\n const result = build_generate_result<T>(result_input)\n\n for (const step of result.steps) {\n if (step.cost !== undefined) {\n record_cost(trajectory, step.index, step.cost, 'provider_reported')\n }\n }\n\n if (result.steps.length > 0) {\n const head = result.steps[0]\n if (head !== undefined) {\n end_step_span(trajectory, first_step_span, {\n usage: head.usage,\n finish_reason: head.finish_reason,\n })\n }\n first_step_span = undefined\n for (let i = 1; i < result.steps.length; i += 1) {\n const s = result.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 } else {\n end_step_span(trajectory, first_step_span, {})\n first_step_span = undefined\n }\n\n end_generate_span(trajectory, generate_span, {\n usage: result.usage,\n finish_reason: result.finish_reason,\n model_resolved: result.model_resolved,\n })\n\n if (dispatch_chunk !== undefined) {\n await dispatch_chunk({\n kind: 'finish',\n finish_reason: result.finish_reason,\n usage: result.usage,\n })\n }\n\n return result\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err)\n if (first_step_span !== undefined) {\n end_step_span(trajectory, first_step_span, { error: message })\n first_step_span = undefined\n }\n end_generate_span(trajectory, generate_span, { error: message })\n throw err\n } finally {\n if (caller_abort !== undefined) {\n caller_abort.removeEventListener('abort', on_caller_abort)\n }\n in_flight.delete(controller)\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 provider_not_configured_error. Custom\n * providers enter via `EngineConfig.custom_providers` at construction,\n * resolved custom-first in create_engine; there is no runtime\n * (post-construction) registration.\n */\n\nimport { provider_not_configured_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 * provider_not_configured_error for unknown names.\n */\nexport function get_provider_factory(name: string): ProviderFactory {\n const factory = BUILTIN_PROVIDERS.get(name)\n if (factory === undefined) throw new provider_not_configured_error(name)\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. There is no\n * recursion past that second level, so deeper structures replace wholesale\n * rather than 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 zod 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 type { z } from 'zod'\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 * 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 let in_string = false\n let escaped = false\n for (let i = start_index; i < text.length; i += 1) {\n const ch = text[i]\n if (in_string) {\n if (escaped) escaped = false\n else if (ch === '\\\\') escaped = true\n else if (ch === '\"') in_string = false\n continue\n }\n if (ch === '\"') {\n in_string = true\n } else if (ch === '{') {\n depth += 1\n } else if (ch === '}') {\n depth -= 1\n if (depth === 0) {\n const end = i + 1\n try {\n return { value: JSON.parse(text.slice(start_index, end)), end }\n } catch {\n return undefined\n }\n }\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 * 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 masks.push({ start: open, end: block_end })\n const inner_start = open + TOOL_CALL_OPEN.length\n const inner = text.slice(inner_start, close)\n const trimmed = inner.trim()\n if (trimmed.startsWith('<function=')) {\n candidates.push(...scan_qwen_functions(inner_start, inner))\n } else if (trimmed.startsWith('{')) {\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) {\n candidates.push({\n name: shaped.name,\n args: shaped.args,\n format: 'hermes',\n span: { start: open, end: block_end },\n })\n }\n }\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 */\nfunction validate_candidate(\n candidate: Candidate,\n tool_map: ReadonlyMap<string, Tool>,\n): SalvagedCall | undefined {\n const tool = tool_map.get(candidate.name)\n if (tool === undefined) return undefined\n const schema: z.ZodType = tool.input_schema\n const raw = schema.safeParse(candidate.args)\n if (raw.success) {\n return {\n name: candidate.name,\n input: raw.data,\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 = schema.safeParse(coerced)\n if (!retried.success) return undefined\n return {\n name: candidate.name,\n input: retried.data,\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 function salvage_tool_calls(\n text: string,\n tool_map: ReadonlyMap<string, Tool>,\n): 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 const calls: SalvagedCall[] = []\n for (const c of candidates) {\n const validated = validate_candidate(c, tool_map)\n if (validated !== undefined) calls.push(validated)\n }\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 type { z } from 'zod'\nimport type { TrajectoryLogger } from '#core'\nimport type {\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 UsageTotals,\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_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, 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\nexport type RawToolCall = {\n readonly id: string\n readonly name: string\n readonly input: unknown\n}\n\n/**\n * Retained alias of the neutral TurnResult (types.ts). Callers built against\n * the loop-local name keep working while TurnResult is the shared spelling.\n */\nexport type InvokeOnceResult = TurnResult\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}' but no on_tool_approval handler was provided`,\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, 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: plain text when there are\n * no tool calls, otherwise structured text plus tool_call parts.\n */\nfunction build_assistant_message(text: string, tool_calls: ReadonlyArray<RawToolCall>): Message {\n if (tool_calls.length === 0) return { role: 'assistant', content: text }\n const parts: Array<\n | { type: 'text'; text: string }\n | { type: 'tool_call'; id: string; name: string; input: unknown }\n > = []\n if (text.length > 0) parts.push({ type: 'text', text })\n for (const tc of tool_calls) {\n parts.push({ type: 'tool_call', id: tc.id, name: tc.name, input: tc.input })\n }\n return { role: 'assistant', content: parts }\n}\n\n/**\n * Derive the step's cost from pricing tables and record it.\n *\n * Missing pricing for a paid provider emits `pricing_missing` (deduped per\n * 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 usage: UsageTotals,\n): CostBreakdown | undefined {\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(usage, pricing, config.provider)\n if (breakdown !== undefined) {\n record_cost(config.trajectory, step_index, breakdown, 'engine_derived')\n }\n return breakdown\n}\n\n/**\n * Validate a raw tool-call input against the tool's zod schema before\n * execution, returning the parsed value or a feedback-ready error message.\n */\nfunction validate_tool_input(\n tool: Tool,\n input: unknown,\n): { ok: true; value: unknown } | { ok: false; message: string } {\n // The schema field is typed as z.ZodType<i>; we call safeParse in the\n // runtime position where the input has not been narrowed.\n const schema: z.ZodType = tool.input_schema\n const parsed = schema.safeParse(input)\n if (parsed.success) return { ok: true, value: parsed.data }\n const error_message = serialize_error(parsed.error)\n return { ok: false, message: `invalid tool input: ${error_message}` }\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 * 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 steps: StepRecord[] = []\n const tool_calls_all: ToolCallRecord[] = []\n let text = ''\n let finish_reason: FinishReason = 'stop'\n let step_index = config.step_index_start\n let max_steps_reached = false\n\n const tool_map = new Map<string, Tool>()\n for (const t of config.tools) tool_map.set(t.name, t)\n\n while (true) {\n throw_if_aborted(config.abort, step_index)\n\n if (step_index >= config.max_steps) {\n max_steps_reached = true\n finish_reason = 'max_steps'\n break\n }\n\n const step_span = start_step_span(config.trajectory, step_index)\n\n let turn: TurnResult\n try {\n const request_messages = await apply_prepare_step(config, step_index)\n config.trajectory?.record({ kind: 'request_sent', step_index })\n 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 })\n config.trajectory?.record({\n kind: 'response_received',\n step_index,\n output_tokens: turn.usage.output_tokens,\n finish_reason: turn.finish_reason,\n })\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 // A turn that \"stopped\" with plain text may hold a call the runtime\n // failed to parse into tool_calls; salvage before deciding the step ends\n // the loop. History gets the stripped text + structured parts (raw markup\n // in history would teach the model the text format works, and a tool\n // result without a matching call part is rejected by OpenAI-compatible\n // APIs); StepRecord.text keeps the raw text for debugging.\n let effective_calls: ReadonlyArray<RawToolCall> = turn.tool_calls\n let history_text = turn.text\n let salvage: SalvageOutcome | undefined\n const salvaged_formats = new Map<string, SalvageFormat>()\n if (\n turn.tool_calls.length === 0 &&\n (turn.finish_reason === 'stop' || turn.finish_reason === 'length') &&\n config.tools.length > 0 &&\n config.salvage_budget !== undefined &&\n config.salvage_budget.remaining > 0\n ) {\n salvage = salvage_tool_calls(turn.text, tool_map)\n if (salvage !== undefined) {\n config.salvage_budget.remaining -= 1\n history_text = salvage.stripped_text\n effective_calls = salvage.calls.map((c, n) => {\n const id = `salvaged_${step_index}_${n}`\n salvaged_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: effective_calls.map((c) => ({\n tool_call_id: c.id,\n name: c.name,\n // Stryker disable next-line StringLiteral: salvaged_formats has an entry for every id (set just above), so the ?? 'json' fallback is unreachable.\n format: salvaged_formats.get(c.id) ?? 'json',\n })),\n raw_text: turn.text,\n })\n if (config.dispatch_chunk !== undefined) {\n // Mirror the native stream, which emits start/end for every call\n // the model attempted, including ones the clamp below drops.\n for (const c of effective_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\n // Clamp applies to native and salvaged calls alike. Dropped calls never\n // reach history; the model re-issues them on a later turn if it still\n // wants them.\n let dropped_calls: ReadonlyArray<RawToolCall> = []\n const per_step_cap = config.max_tool_calls_per_step\n if (per_step_cap !== undefined && effective_calls.length > per_step_cap) {\n dropped_calls = effective_calls.slice(per_step_cap)\n effective_calls = effective_calls.slice(0, per_step_cap)\n record_tool_calls_dropped(config.trajectory, {\n step_index,\n max_tool_calls_per_step: per_step_cap,\n kept: effective_calls.length,\n dropped: dropped_calls.map((d) => ({ tool_call_id: d.id, name: d.name })),\n })\n }\n\n const step_tool_records: ToolCallRecord[] = []\n const assistant_message = build_assistant_message(history_text, effective_calls)\n config.messages.push(assistant_message)\n\n if (effective_calls.length === 0) {\n text = turn.text\n finish_reason = turn.finish_reason\n const record_step: StepRecord = {\n index: step_index,\n text: turn.text,\n tool_calls: [],\n usage: turn.usage,\n finish_reason: turn.finish_reason,\n }\n const breakdown = compute_and_record_cost(config, step_index, turn.usage)\n if (breakdown !== undefined) record_step.cost = breakdown\n steps.push(record_step)\n if (config.on_finish_step !== undefined) config.on_finish_step(record_step)\n end_step_span(config.trajectory, step_span, {\n usage: turn.usage,\n finish_reason: turn.finish_reason,\n })\n break\n }\n\n // This turn has tool calls. Execute them sequentially.\n const would_exceed_after = step_index + 1 >= config.max_steps\n const tool_results_to_feed: Message[] = []\n // Set true when a call to a Tool flagged ends_turn executes successfully;\n // ends the loop after this step (see the terminal-finish break below).\n let terminal_fired = false\n\n for (const raw_call of effective_calls) {\n throw_if_aborted_in_flight(config.abort, step_index, { id: raw_call.id, name: raw_call.name })\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 (would_exceed_after && tool_map.get(raw_call.name)?.ends_turn !== true) {\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: raw_call.name,\n input: raw_call.input,\n error: { message: 'max_steps_exceeded_before_execution' },\n duration_ms: 0,\n started_at: Date.now(),\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n raw_call.id,\n undefined,\n { message: 'max_steps_exceeded_before_execution' },\n )\n continue\n }\n\n const tool = tool_map.get(raw_call.name)\n if (tool === undefined) {\n const err_message = `unknown tool '${raw_call.name}'`\n if (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(config.trajectory, step_span, { error: err_message })\n throw thrown\n }\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: raw_call.name,\n input: raw_call.input,\n error: { message: err_message },\n duration_ms: 0,\n started_at: Date.now(),\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n tool_results_to_feed.push(\n build_tool_result_message(raw_call.id, raw_call.name, {\n error: err_message,\n }),\n )\n record_tool_call(config.trajectory, {\n step_index,\n name: raw_call.name,\n tool_call_id: raw_call.id,\n input: raw_call.input,\n duration_ms: 0,\n error: { message: err_message },\n })\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n raw_call.id,\n undefined,\n { message: err_message },\n )\n continue\n }\n\n const validation = validate_tool_input(tool, raw_call.input)\n if (!validation.ok) {\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: raw_call.name,\n input: raw_call.input,\n error: { message: validation.message },\n duration_ms: 0,\n started_at: Date.now(),\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n tool_results_to_feed.push(\n build_tool_result_message(raw_call.id, raw_call.name, {\n error: validation.message,\n }),\n )\n record_tool_call(config.trajectory, {\n step_index,\n name: raw_call.name,\n tool_call_id: raw_call.id,\n input: raw_call.input,\n duration_ms: 0,\n error: { message: validation.message },\n })\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n raw_call.id,\n undefined,\n { message: validation.message },\n )\n continue\n }\n\n let approved: boolean\n try {\n approved = await request_approval(\n tool,\n validation.value,\n step_index,\n raw_call.id,\n config.abort,\n config.on_tool_approval,\n config.trajectory,\n )\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 if (!approved) {\n const denied_message = 'tool_approval_denied'\n if (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, tool_call_id: raw_call.id },\n )\n end_step_span(config.trajectory, step_span, { error: denied_message })\n throw thrown\n }\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: tool.name,\n input: validation.value,\n error: { message: denied_message },\n duration_ms: 0,\n started_at: Date.now(),\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n tool_results_to_feed.push(\n build_tool_result_message(raw_call.id, tool.name, { error: denied_message }),\n )\n record_tool_call(config.trajectory, {\n step_index,\n name: tool.name,\n tool_call_id: raw_call.id,\n input: validation.value,\n duration_ms: 0,\n error: { message: denied_message },\n })\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n raw_call.id,\n undefined,\n { message: denied_message },\n )\n continue\n }\n\n throw_if_aborted_in_flight(config.abort, step_index, {\n id: raw_call.id,\n name: tool.name,\n })\n\n const started_at = Date.now()\n const tool_ctx: ToolExecContext = {\n abort: config.abort,\n tool_call_id: raw_call.id,\n step_index,\n ...(config.trajectory !== undefined ? { trajectory: 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(validation.value, 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 if (thrown !== undefined) {\n if (config.abort.aborted) {\n const abort_err = new aborted_error('aborted', {\n reason: config.abort.reason,\n step_index,\n tool_call_in_flight: { id: raw_call.id, name: tool.name },\n })\n end_step_span(config.trajectory, step_span, { error: 'aborted' })\n throw abort_err\n }\n if (config.tool_error_policy === 'throw') {\n const wrapped = new tool_error(`tool '${tool.name}' failed: ${err_message ?? 'unknown'}`, {\n tool_name: tool.name,\n tool_call_id: raw_call.id,\n cause: thrown,\n })\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 end_step_span(config.trajectory, step_span, { error: err_message ?? 'tool error' })\n throw wrapped\n }\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: tool.name,\n input: validation.value,\n // Stryker disable next-line StringLiteral: err_message is always a string here (see catch above), so this ?? 'unknown' fallback is unreachable.\n error: { message: err_message ?? 'unknown' },\n duration_ms,\n started_at,\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n tool_results_to_feed.push(\n // Stryker disable next-line StringLiteral: unreachable ?? 'unknown' fallback (err_message is always a string here).\n build_tool_result_message(raw_call.id, tool.name, { error: err_message ?? 'unknown' }),\n )\n record_tool_call(config.trajectory, {\n step_index,\n name: tool.name,\n tool_call_id: raw_call.id,\n input: validation.value,\n duration_ms,\n // Stryker disable next-line StringLiteral: unreachable ?? 'unknown' fallback (err_message is always a string here).\n error: { message: err_message ?? 'unknown' },\n })\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n raw_call.id,\n undefined,\n // Stryker disable next-line StringLiteral: unreachable ?? 'unknown' fallback (err_message is always a string here).\n { message: err_message ?? 'unknown' },\n )\n continue\n }\n\n const record: ToolCallRecord = {\n id: raw_call.id,\n name: tool.name,\n input: validation.value,\n output,\n duration_ms,\n started_at,\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n if (tool.ends_turn === true) terminal_fired = true\n tool_results_to_feed.push(\n build_tool_result_message(raw_call.id, tool.name, output ?? ''),\n )\n record_tool_call(config.trajectory, {\n step_index,\n name: tool.name,\n tool_call_id: raw_call.id,\n input: validation.value,\n duration_ms,\n })\n await dispatch_tool_result_chunk(config.dispatch_chunk, step_index, raw_call.id, output)\n }\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_calls) {\n const record: ToolCallRecord = {\n id: d.id,\n name: d.name,\n input: d.input,\n error: { message: 'dropped_max_tool_calls_per_step' },\n duration_ms: 0,\n started_at: Date.now(),\n }\n step_tool_records.push(record)\n tool_calls_all.push(record)\n await dispatch_tool_result_chunk(\n config.dispatch_chunk,\n step_index,\n d.id,\n undefined,\n { message: 'dropped_max_tool_calls_per_step' },\n )\n }\n\n for (const r of step_tool_records) {\n const format = salvaged_formats.get(r.id)\n if (format !== undefined) {\n r.salvaged = true\n r.salvaged_format = format\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 for (const r of step_tool_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 for (const m of tool_results_to_feed) config.messages.push(m)\n\n // A salvaged step reports 'tool_calls': downstream consumers see the same\n // shape a native tool turn produces; the salvaged flags carry provenance.\n // A terminal step reports 'tool_calls' (it genuinely made calls); the loop\n // finish_reason 'stop' below is the separate signal that generation ended.\n const turn_finish_reason: FinishReason = terminal_fired\n ? 'tool_calls'\n : would_exceed_after\n ? 'max_steps'\n : salvage !== undefined\n ? 'tool_calls'\n : turn.finish_reason\n const step_record: StepRecord = {\n index: step_index,\n text: turn.text,\n tool_calls: step_tool_records,\n usage: turn.usage,\n finish_reason: turn_finish_reason,\n }\n const breakdown = compute_and_record_cost(config, step_index, turn.usage)\n if (breakdown !== undefined) step_record.cost = breakdown\n steps.push(step_record)\n if (config.on_finish_step !== undefined) config.on_finish_step(step_record)\n end_step_span(config.trajectory, step_span, {\n usage: turn.usage,\n finish_reason: turn_finish_reason,\n })\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 (terminal_fired) {\n finish_reason = 'stop'\n text = turn.text\n break\n }\n\n if (would_exceed_after) {\n max_steps_reached = true\n finish_reason = 'max_steps'\n text = turn.text\n break\n }\n\n step_index += 1\n }\n\n return { text, steps, tool_calls: tool_calls_all, finish_reason, max_steps_reached }\n}\n","/**\n * AI SDK telemetry wiring, confined to the ai_sdk transport.\n *\n * `@ai-sdk/otel` is adopted strictly below the turn seam: it instruments one\n * turn inside this module, never the loop. The peer is loaded lazily and only\n * when telemetry is explicitly enabled, so the disabled default (every call\n * that does not opt in) pulls in nothing.\n *\n * This is the ONLY place `@ai-sdk/otel` is referenced. generate.ts and\n * create_engine.ts thread a plain `AiSdkTelemetrySettings` value through the\n * seam and stay SDK-agnostic; loop-level, transport-neutral tracing is the\n * separate `fascicle/otel` bridge.\n */\n\nimport type { AiSdkTelemetrySettings } from '../../types.js'\nimport { load_optional_peer } from '../types.js'\n\ntype OpenTelemetryCtor = new (options?: { tracer?: unknown }) => unknown\n\ntype AiSdkOtelModule = {\n readonly OpenTelemetry: OpenTelemetryCtor\n}\n\n/**\n * The subset of the AI SDK's telemetry option shape this module produces, using\n * the SDK's own (camelCase) keys. Cast onto `experimental_telemetry` at the\n * call site.\n */\nexport type AiSdkTelemetryPassthrough = {\n isEnabled: true\n integrations: unknown[]\n functionId?: string\n recordInputs?: boolean\n recordOutputs?: boolean\n metadata?: Readonly<Record<string, string | number | boolean>>\n}\n\n/**\n * Build the AI SDK's `experimental_telemetry` option from engine settings,\n * loading the `@ai-sdk/otel` peer only when telemetry is enabled.\n */\nexport async function build_ai_sdk_telemetry(\n settings: AiSdkTelemetrySettings | undefined,\n): Promise<AiSdkTelemetryPassthrough | undefined> {\n if (!settings?.enabled) return undefined\n const mod = await load_optional_peer<AiSdkOtelModule>('@ai-sdk/otel')\n const integration = new mod.OpenTelemetry(\n settings.tracer !== undefined ? { tracer: settings.tracer } : {},\n )\n const out: AiSdkTelemetryPassthrough = { isEnabled: true, integrations: [integration] }\n if (settings.function_id !== undefined) out.functionId = settings.function_id\n if (settings.record_inputs !== undefined) out.recordInputs = settings.record_inputs\n if (settings.record_outputs !== undefined) out.recordOutputs = settings.record_outputs\n if (settings.metadata !== undefined) out.metadata = settings.metadata\n return out\n}\n","/**\n * The ai_sdk transport: the engine's only Vercel AI SDK call site.\n *\n * Only this module imports from `ai` or invokes generateText / streamText.\n * generate.ts drives this transport through create_ai_sdk_turn and stays\n * SDK-agnostic; run_tool_loop sees the same neutral TurnResult a native\n * adapter produces. Enforced by rules/no-ai-import-outside-ai-sdk-provider.yml.\n *\n * Retry stays out of this module on purpose: generate.ts wraps the turn\n * returned here in the engine-owned retry_turn, exactly as it wraps a native\n * adapter's invoke_turn. This module owns request/response mapping only.\n */\n\nimport {\n generateText,\n NoObjectGeneratedError,\n Output,\n isStepCount,\n streamText,\n tool as ai_tool,\n type LanguageModel,\n type ModelMessage,\n type TextStreamPart,\n type ToolSet,\n} from 'ai'\nimport type { z } from 'zod'\nimport type {\n AiSdkTelemetrySettings,\n FinishReason,\n Message,\n StreamChunk,\n Tool,\n TurnResult,\n UsageTotals,\n} from '../../types.js'\nimport { aborted_error } from '../../errors.js'\nimport type { ChunkDispatcher } from '../../streaming.js'\nimport type { RawToolCall } from '../../tool_loop.js'\nimport {\n default_normalize_usage,\n type AiSdkProviderAdapter,\n type RawProviderUsage,\n} from '../types.js'\nimport { build_ai_sdk_telemetry, type AiSdkTelemetryPassthrough } from './telemetry.js'\n\n/**\n * Map the AI SDK's finish reason string to the engine's FinishReason.\n */\nexport function map_finish_reason(raw: string | undefined): FinishReason {\n switch (raw) {\n case 'stop':\n return 'stop'\n case 'length':\n return 'length'\n case 'content-filter':\n case 'content_filter':\n return 'content_filter'\n case 'tool-calls':\n case 'tool_calls':\n return 'tool_calls'\n default:\n return 'stop'\n }\n}\n\n/**\n * Extract the usage fields `default_normalize_usage` understands from an AI\n * SDK usage object, tolerating both the SDK's camelCase shape and the\n * flattened snake_case fields some provider mocks return directly.\n */\nexport function to_raw_provider_usage(usage: unknown): RawProviderUsage {\n if (usage === null || typeof usage !== 'object') return {}\n const raw: RawProviderUsage = {}\n const input_tokens = Reflect.get(usage, 'inputTokens')\n if (typeof input_tokens === 'number') raw.input_tokens = input_tokens\n const output_tokens = Reflect.get(usage, 'outputTokens')\n if (typeof output_tokens === 'number') raw.output_tokens = output_tokens\n const input_details = Reflect.get(usage, 'inputTokenDetails')\n if (input_details !== null && typeof input_details === 'object') {\n const cache_read = Reflect.get(input_details, 'cacheReadTokens')\n const cache_write = Reflect.get(input_details, 'cacheWriteTokens')\n raw.input_token_details = {}\n if (typeof cache_read === 'number') raw.input_token_details.cached_tokens = cache_read\n if (typeof cache_write === 'number') raw.input_token_details.cache_creation_input_tokens = cache_write\n }\n const output_details = Reflect.get(usage, 'outputTokenDetails')\n if (output_details !== null && typeof output_details === 'object') {\n const reasoning = Reflect.get(output_details, 'reasoningTokens')\n raw.output_token_details = {}\n if (typeof reasoning === 'number') raw.output_token_details.reasoning_tokens = reasoning\n }\n // Passthrough for mocks that provide flattened fields directly.\n const cached_flat = Reflect.get(usage, 'cached_input_tokens')\n if (typeof cached_flat === 'number') raw.cached_input_tokens = cached_flat\n const cache_write_flat = Reflect.get(usage, 'cache_write_tokens')\n if (typeof cache_write_flat === 'number') raw.cache_write_tokens = cache_write_flat\n const reasoning_flat = Reflect.get(usage, 'reasoning_tokens')\n if (typeof reasoning_flat === 'number') raw.reasoning_tokens = reasoning_flat\n const input_flat = Reflect.get(usage, 'input_tokens')\n if (raw.input_tokens === undefined && typeof input_flat === 'number') raw.input_tokens = input_flat\n const output_flat = Reflect.get(usage, 'output_tokens')\n if (raw.output_tokens === undefined && typeof output_flat === 'number') raw.output_tokens = output_flat\n return raw\n}\n\n/**\n * Map fascicle's Message[] to the AI SDK's ModelMessage[] shape.\n */\nexport function to_sdk_messages(messages: ReadonlyArray<Message>): ModelMessage[] {\n const out: ModelMessage[] = []\n for (const m of messages) {\n if (m.role === 'system') {\n out.push({ role: 'system', content: m.content })\n continue\n }\n if (m.role === 'user') {\n if (typeof m.content === 'string') {\n out.push({ role: 'user', content: m.content })\n } else {\n const parts: Array<\n | { type: 'text'; text: string }\n | { type: 'image'; image: string | Uint8Array; mediaType?: string }\n > = m.content.map((p) => {\n if (p.type === 'text') return { type: 'text', text: p.text }\n const image_part: { type: 'image'; image: string | Uint8Array; mediaType?: string } = {\n type: 'image',\n image: p.image,\n }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n return image_part\n })\n out.push({ role: 'user', content: parts })\n }\n continue\n }\n if (m.role === 'tool') {\n out.push({\n role: 'tool',\n content: [\n {\n type: 'tool-result',\n toolCallId: m.tool_call_id,\n toolName: m.name,\n output: { type: 'text', value: m.content },\n },\n ],\n })\n continue\n }\n // assistant\n if (typeof m.content === 'string') {\n out.push({ role: 'assistant', content: m.content })\n continue\n }\n const parts = m.content.map((p) => {\n if (p.type === 'text') return { type: 'text' as const, text: p.text }\n return {\n type: 'tool-call' as const,\n toolCallId: p.id,\n toolName: p.name,\n input: p.input,\n }\n })\n out.push({ role: 'assistant', content: parts })\n }\n return out\n}\n\n/**\n * Hoist a leading run of system messages out of the SDK message list into the\n * AI SDK's top-level `system` option.\n *\n * Passing a `role: 'system'` entry inside `messages` makes the AI SDK treat it\n * as potentially attacker-controlled: it warns on every call (and newer `ai`\n * versions throw unless `allowSystemInMessages` is set). fascicle's system\n * content is the developer's own prompt, and the SDK's own recommendation is to\n * deliver it through the top-level `instructions` option (v7's rename of the\n * former `system` option), which removes the warning at its source rather than\n * suppressing it.\n *\n * Only the *leading* run is hoisted (fascicle's only shape: one or more system\n * messages, then the conversation). A system message that appears after a\n * non-system message keeps its position rather than being silently reordered to\n * the top, and the original list is returned untouched when hoisting would leave\n * `messages` empty, since the SDK rejects an empty messages array.\n */\nexport function split_leading_system(messages: ReadonlyArray<ModelMessage>): {\n system?: string\n messages: ModelMessage[]\n} {\n let run_end = 0\n const system_parts: string[] = []\n while (run_end < messages.length) {\n const m = messages[run_end]\n if (m?.role !== 'system') break\n system_parts.push(m.content)\n run_end += 1\n }\n const rest = messages.slice(run_end)\n if (system_parts.length === 0 || rest.length === 0) {\n return { messages: [...messages] }\n }\n return { system: system_parts.join('\\n\\n'), messages: rest }\n}\n\n/**\n * Map fascicle's Tool[] to the AI SDK's ToolSet.\n *\n * Returns undefined for an empty tool list so the caller can omit `tools`\n * from the call params entirely instead of passing an empty object.\n */\nexport function to_sdk_tools(tools: ReadonlyArray<Tool>): ToolSet | undefined {\n if (tools.length === 0) return undefined\n const entries: ToolSet = {}\n for (const t of tools) {\n entries[t.name] = ai_tool({\n description: t.description,\n inputSchema: t.input_schema,\n })\n }\n return entries\n}\n\n/**\n * Map one AI SDK stream part to the engine's StreamChunk shape, or undefined\n * for a part kind the engine does not model.\n */\nexport function map_stream_part_to_chunk(\n part: TextStreamPart<ToolSet>,\n step_index: number,\n): StreamChunk | undefined {\n switch (part.type) {\n case 'text-delta':\n return { kind: 'text', text: part.text, step_index }\n case 'reasoning-delta':\n return { kind: 'reasoning', text: part.text, step_index }\n case 'tool-input-start':\n return {\n kind: 'tool_call_start',\n id: part.id,\n name: part.toolName,\n step_index,\n }\n case 'tool-input-delta':\n return {\n kind: 'tool_call_input_delta',\n id: part.id,\n delta: part.delta,\n step_index,\n }\n case 'tool-call':\n return {\n kind: 'tool_call_end',\n id: part.toolCallId,\n input: part.input,\n step_index,\n }\n case 'finish-step':\n return {\n kind: 'step_finish',\n step_index,\n finish_reason: map_finish_reason(part.finishReason),\n usage: default_usage_from_sdk(part.usage),\n }\n default:\n // v7 parts with no engine StreamChunk kind (file, reasoning-file,\n // source, block framing) drop here on purpose: the engine models\n // text, reasoning, and tool traffic, not generated files.\n return undefined\n }\n}\n\n/**\n * Normalize a raw AI SDK usage object into UsageTotals for a streamed\n * step_finish chunk.\n */\nexport function default_usage_from_sdk(usage: unknown): UsageTotals {\n // Streamed step_finish chunks must carry the same cache/reasoning\n // granularity the step record gets via adapter.normalize_usage; every\n // built-in adapter routes through default_normalize_usage, so this keeps\n // the chunk surface consistent with the non-streamed result.\n return default_normalize_usage(to_raw_provider_usage(usage))\n}\n\n/**\n * Run one streamText call, dispatching StreamChunks as parts arrive and\n * accumulating them into a TurnResult once the stream completes.\n */\nasync function collect_stream(\n params: Parameters<typeof streamText>[0],\n step_index: number,\n dispatcher: ChunkDispatcher,\n on_first_chunk: () => void,\n internal_controller: AbortController,\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n const stream_result = streamText(params)\n let text = ''\n const tool_calls: RawToolCall[] = []\n let finish_reason: FinishReason = 'stop'\n let raw_usage: RawProviderUsage = {}\n let first = true\n\n for await (const part of stream_result.stream) {\n if (first) {\n first = false\n on_first_chunk()\n }\n if (part.type === 'text-delta') {\n text += part.text\n }\n if (part.type === 'tool-call') {\n tool_calls.push({\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n })\n }\n if (part.type === 'finish-step') {\n finish_reason = map_finish_reason(part.finishReason)\n raw_usage = to_raw_provider_usage(part.usage)\n }\n if (part.type === 'error') {\n throw part.error\n }\n if (part.type === 'abort') {\n throw new aborted_error('aborted', { step_index })\n }\n const chunk = map_stream_part_to_chunk(part, step_index)\n if (chunk === undefined) continue\n try {\n await dispatcher.dispatch(chunk)\n } catch (err: unknown) {\n internal_controller.abort()\n throw err\n }\n }\n\n return {\n text,\n tool_calls,\n finish_reason,\n usage: adapter.normalize_usage(raw_usage),\n }\n}\n\n/**\n * Run one generateText call and map its result into a TurnResult, recovering\n * a schema-validation failure from the SDK via recover_no_object_generated\n * instead of letting it throw.\n */\nasync function collect_non_stream(\n params: Parameters<typeof generateText>[0],\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n let result: Awaited<ReturnType<typeof generateText>>\n try {\n result = await generateText(params)\n } catch (err: unknown) {\n const recovered = recover_no_object_generated(err, adapter)\n if (recovered !== undefined) return recovered\n throw err\n }\n const tool_calls: RawToolCall[] = []\n for (const tc of result.toolCalls) {\n tool_calls.push({\n id: tc.toolCallId,\n name: tc.toolName,\n input: tc.input,\n })\n }\n const raw_usage = to_raw_provider_usage(result.usage)\n return {\n text: result.text,\n tool_calls,\n finish_reason: map_finish_reason(result.finishReason),\n usage: adapter.normalize_usage(raw_usage),\n }\n}\n\n/**\n * When `output` (structured output) is in play, `generateText` eagerly parses the\n * model's text against the schema and throws `NoObjectGeneratedError` if it\n * does not conform. That parse is the SDK's, not fascicle's: turning it into a\n * thrown error would skip the engine's own schema-parse + repair loop (and the\n * error is not a retryable transient, so it would surface raw). Instead we\n * recover the model's raw text from the error and hand it back as a normal\n * turn result, so `parse_with_schema` re-validates it and the repair loop\n * engages exactly as it does for the prompt-based path. Returns undefined for\n * any other error so the caller rethrows.\n */\nfunction recover_no_object_generated(\n err: unknown,\n adapter: AiSdkProviderAdapter,\n): TurnResult | undefined {\n if (!NoObjectGeneratedError.isInstance(err)) return undefined\n const text_field = Reflect.get(err, 'text')\n const finish_field = Reflect.get(err, 'finishReason')\n const raw_usage = to_raw_provider_usage(Reflect.get(err, 'usage'))\n return {\n text: typeof text_field === 'string' ? text_field : '',\n tool_calls: [],\n finish_reason: map_finish_reason(typeof finish_field === 'string' ? finish_field : undefined),\n usage: adapter.normalize_usage(raw_usage),\n }\n}\n\ntype AiSdkCallParams = Parameters<typeof streamText>[0] & Parameters<typeof generateText>[0]\n\nexport type AiSdkTurnConfig = {\n readonly adapter: AiSdkProviderAdapter\n readonly model_id: string\n readonly dispatcher: ChunkDispatcher\n readonly tools: ReadonlyArray<Tool>\n readonly schema: z.ZodType | undefined\n readonly provider_options: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined\n readonly temperature: number | undefined\n readonly max_tokens: number | undefined\n readonly top_p: number | undefined\n readonly telemetry: AiSdkTelemetrySettings | undefined\n}\n\nexport type AiSdkTurnArgs = {\n readonly step_index: number\n readonly messages: ReadonlyArray<Message>\n readonly abort: AbortSignal\n readonly stream: boolean\n readonly on_first_chunk: () => void\n}\n\nexport type AiSdkTurn = (args: AiSdkTurnArgs) => Promise<TurnResult>\n\n/**\n * Build the single-attempt SDK turn for one generate call: the\n * generateText/streamText call body behind the same neutral seam a native\n * adapter's invoke_turn implements. The built model is memoized across steps\n * of one generate call. No retry here: generate.ts wraps the returned turn in\n * the engine-owned retry_turn.\n */\nexport function create_ai_sdk_turn(cfg: AiSdkTurnConfig): AiSdkTurn {\n let model_instance: LanguageModel | undefined\n const get_model = async (): Promise<LanguageModel> => {\n if (model_instance === undefined) {\n const built = await cfg.adapter.build_model(cfg.model_id)\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n model_instance = built as LanguageModel\n }\n return model_instance\n }\n\n // Telemetry is resolved once per generate call and memoized across its steps,\n // mirroring get_model. build_ai_sdk_telemetry returns undefined immediately\n // (no peer load) unless telemetry is explicitly enabled, so the disabled\n // default costs nothing.\n let telemetry_options: AiSdkTelemetryPassthrough | undefined\n let telemetry_resolved = false\n const get_telemetry = async (): Promise<AiSdkTelemetryPassthrough | undefined> => {\n if (!telemetry_resolved) {\n telemetry_options = await build_ai_sdk_telemetry(cfg.telemetry)\n telemetry_resolved = true\n }\n return telemetry_options\n }\n\n const sdk_tools = to_sdk_tools(cfg.tools)\n\n // Native structured output: when a schema is requested and the provider\n // constrains decoding to it (the 'structured_output' capability), route\n // through the AI SDK's Output.object seam so the schema becomes the\n // provider's responseFormat (e.g. Ollama's `format`) instead of a\n // prompt-for-JSON-then-scrape. Gated on no tools: forcing a JSON\n // responseFormat alongside tool calls breaks tool dispatch on most\n // providers, so tool runs keep the prompt-based schema path. The engine's\n // schema parse + repair loop still owns validation either way. This seam\n // is ai_sdk-only: a native adapter that constrains decoding honors\n // TurnRequest.schema inside its own invoke_turn.\n let output_spec: NonNullable<AiSdkCallParams['output']> | undefined\n if (\n cfg.schema !== undefined &&\n cfg.tools.length === 0 &&\n cfg.adapter.supports('structured_output')\n ) {\n // Output.object<T> is not structurally assignable to the SDK's default\n // Output<string, string> param slot, but the runtime shape is exactly\n // what generateText/streamText consume to set responseFormat.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n output_spec = Output.object({ schema: cfg.schema }) as NonNullable<\n AiSdkCallParams['output']\n >\n }\n\n // provider_options is Record<string, Record<string, unknown>>; the SDK\n // expects SharedV3ProviderOptions (Record<string, JSONObject>) which is\n // structurally compatible for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const provider_options = cfg.provider_options as AiSdkCallParams['providerOptions']\n\n return async (args: AiSdkTurnArgs): Promise<TurnResult> => {\n const model = await get_model()\n const telemetry = await get_telemetry()\n const internal_controller = new AbortController()\n const cancel_on_user_abort = (): void => {\n internal_controller.abort(args.abort.reason)\n }\n if (args.abort.aborted) {\n internal_controller.abort(args.abort.reason)\n } else {\n args.abort.addEventListener('abort', cancel_on_user_abort, { once: true })\n }\n const { system: hoisted_system, messages: sdk_messages } = split_leading_system(\n to_sdk_messages(args.messages),\n )\n const base_params: AiSdkCallParams = {\n model,\n messages: sdk_messages,\n abortSignal: internal_controller.signal,\n stopWhen: isStepCount(1),\n // The engine owns retry via retry_turn in generate.ts; disable the AI\n // SDK's own retry (default 2) so it does not nest inside each of our\n // attempts and inflate provider round-trips / distort backoff.\n maxRetries: 0,\n }\n if (hoisted_system !== undefined) base_params.instructions = hoisted_system\n if (sdk_tools !== undefined) base_params.tools = sdk_tools\n if (output_spec !== undefined) base_params.output = output_spec\n if (provider_options !== undefined) base_params.providerOptions = provider_options\n if (cfg.temperature !== undefined) base_params.temperature = cfg.temperature\n if (cfg.max_tokens !== undefined) base_params.maxOutputTokens = cfg.max_tokens\n if (cfg.top_p !== undefined) base_params.topP = cfg.top_p\n if (telemetry !== undefined) {\n // AiSdkTelemetryPassthrough uses the SDK's own telemetry keys; the slot's\n // generic (RUNTIME_CONTEXT/TOOLS) is erased for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n base_params.experimental_telemetry = telemetry as NonNullable<\n AiSdkCallParams['experimental_telemetry']\n >\n }\n\n try {\n if (args.stream) {\n return await collect_stream(\n base_params,\n args.step_index,\n cfg.dispatcher,\n args.on_first_chunk,\n internal_controller,\n cfg.adapter,\n )\n }\n return await collect_non_stream(base_params, cfg.adapter)\n } finally {\n args.abort.removeEventListener('abort', cancel_on_user_abort)\n }\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\nimport type {\n AiSdkTelemetrySettings,\n CostBreakdown,\n EffortLevel,\n FinishReason,\n GenerateOptions,\n GenerateResult,\n Message,\n Pricing,\n PricingTable,\n ResolvedModel,\n RetryPolicy,\n StreamChunk,\n Tool,\n TurnRequest,\n TurnResult,\n} from './types.js'\nimport {\n aborted_error,\n engine_config_error,\n model_required_error,\n on_chunk_error,\n provider_capability_error,\n provider_error,\n provider_not_configured_error,\n turn_timeout_error,\n} from './errors.js'\nimport { merge_provider_options } from './merge_defaults.js'\nimport { FREE_PROVIDERS, pricing_key } from './pricing.js'\nimport { parse_retry_after, retry_with_policy } from './retry.js'\nimport {\n build_repair_message,\n format_zod_error,\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 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 InvokeOnceResult,\n} from './tool_loop.js'\nimport type {\n NativeProviderAdapter,\n ProviderAdapter,\n} from './providers/types.js'\nimport {\n create_ai_sdk_turn,\n type AiSdkTurn,\n type AiSdkTurnConfig,\n} 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_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 let run_end = 0\n const system_parts: string[] = []\n while (run_end < messages.length) {\n const m = messages[run_end]\n // Stryker disable next-line OptionalChaining: within the loop guard run_end < messages.length, m is always an in-bounds (defined) Message, so m.role and m?.role read identically.\n if (m?.role !== 'system') break\n system_parts.push(m.content)\n run_end += 1\n }\n const rest = messages.slice(run_end)\n if (system_parts.length === 0 || rest.length === 0) {\n return { messages: [...messages] }\n }\n return { system: system_parts.join('\\n\\n'), messages: rest }\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 // Already-classified shape: pass through.\n const existing_kind = Reflect.get(err, 'kind')\n if (\n typeof existing_kind === 'string' &&\n (existing_kind === 'rate_limit' ||\n existing_kind === 'provider_5xx' ||\n existing_kind === 'network' ||\n existing_kind === 'timeout')\n ) {\n return err\n }\n const status = Reflect.get(err, 'statusCode')\n const status_alt = Reflect.get(err, 'status')\n const resolved_status =\n typeof status === 'number'\n ? status\n : typeof status_alt === 'number'\n ? status_alt\n : undefined\n if (resolved_status === 429) {\n const headers = Reflect.get(err, 'responseHeaders')\n let retry_after_ms: number | undefined\n if (headers !== null && typeof headers === 'object') {\n const hv = Reflect.get(headers, 'retry-after')\n if (typeof hv === 'string') retry_after_ms = parse_retry_after(hv)\n }\n const message = Reflect.get(err, 'message')\n const out: Record<string, unknown> = { kind: 'rate_limit', status: 429 }\n if (typeof message === 'string') out['message'] = message\n if (retry_after_ms !== undefined) out['retry_after_ms'] = retry_after_ms\n return out\n }\n if (resolved_status !== undefined && resolved_status >= 500 && resolved_status < 600) {\n const message = Reflect.get(err, 'message')\n const out: Record<string, unknown> = { kind: 'provider_5xx', status: resolved_status }\n if (typeof message === 'string') out['message'] = message\n return out\n }\n const code = Reflect.get(err, 'code')\n if (\n code === 'ECONNRESET' ||\n code === 'ETIMEDOUT' ||\n code === 'ENOTFOUND' ||\n code === 'ECONNREFUSED'\n ) {\n const message = Reflect.get(err, 'message')\n const out: Record<string, unknown> = { kind: 'network' }\n if (typeof message === 'string') out['message'] = message\n return out\n }\n return err\n}\n\ntype AiSdkInvokeConfig = {\n readonly invoke_turn: AiSdkTurn\n readonly retry_policy: RetryPolicy\n readonly turn_timeout_ms: number | 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 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 */\nfunction retry_turn(\n call_once: (turn_abort: AbortSignal) => Promise<TurnResult>,\n args: InvokeOnceArgs,\n has_streamed: () => boolean,\n retry_policy: RetryPolicy,\n classify: (err: unknown) => unknown,\n turn_timeout_ms: number | undefined,\n): Promise<TurnResult> {\n return retry_with_policy(\n async () => {\n const deadline = arm_turn_timeout(args.abort, turn_timeout_ms)\n try {\n return await call_once(deadline.signal)\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 )\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.\n */\nfunction build_ai_sdk_invoke(cfg: AiSdkInvokeConfig): InvokeOnce {\n return async (args: InvokeOnceArgs): Promise<InvokeOnceResult> => {\n let chunks_started = false\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 chunks_started = true\n },\n })\n\n return await retry_turn(\n call_once,\n args,\n () => chunks_started,\n cfg.retry_policy,\n classify_provider_error,\n cfg.turn_timeout_ms,\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 chunks_started = false\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 chunks_started = true\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 () => chunks_started,\n cfg.retry_policy,\n classify,\n cfg.turn_timeout_ms,\n )\n }\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.\n */\nexport async function generate<T = string>(\n opts_in: GenerateOptions<T>,\n engine: EngineInternals,\n): Promise<GenerateResult<T>> {\n if (opts_in.abort?.aborted === true) {\n throw new aborted_error('aborted', { reason: opts_in.abort.reason })\n }\n\n const resolved_model = opts_in.model ?? engine.default_model\n if (resolved_model === undefined) throw new model_required_error()\n const sole_provider =\n engine.adapters.size === 1 ? [...engine.adapters.keys()][0] : undefined\n const resolved_provider =\n opts_in.provider ?? engine.default_provider ?? sole_provider ?? 'anthropic'\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 (merged_provider_options !== undefined) {\n opts.provider_options = merged_provider_options\n }\n\n const target: ResolvedModel = { provider: resolved_provider, model_id: resolved_model }\n\n const adapter = engine.adapters.get(target.provider)\n if (adapter === undefined) {\n throw new provider_not_configured_error(target.provider)\n }\n\n if (adapter.kind === 'external') {\n return adapter.generate<T>(opts, target)\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 if (opts.schema !== undefined && !adapter.supports('schema')) {\n throw new provider_capability_error(target.provider, 'schema')\n }\n if (tools_list.length > 0 && !adapter.supports('tools')) {\n throw new provider_capability_error(target.provider, 'tools')\n }\n if (on_chunk_provided && !adapter.supports('streaming')) {\n throw new provider_capability_error(target.provider, 'streaming')\n }\n\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')\n }\n const dispatcher = create_chunk_dispatcher(opts.on_chunk)\n\n let invoke_once: InvokeOnce\n if (adapter.kind === 'ai_sdk') {\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(trajectory, 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. Without this merge the user's provider_options\n // were computed then dropped, a silent no-op for every provider.\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 branch only threads resolved options through the seam.\n invoke_once = build_ai_sdk_invoke({\n invoke_turn: create_ai_sdk_turn({\n adapter,\n model_id: target.model_id,\n dispatcher,\n tools: 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 telemetry: engine.default_ai_sdk_telemetry,\n }),\n retry_policy,\n turn_timeout_ms,\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,\n turn_timeout_ms,\n dispatcher,\n 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 abort = opts.abort ?? new AbortController().signal\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 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('tool_call_repair_attempts must be >= 0')\n }\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('max_tool_calls_per_step must be >= 1')\n }\n\n const schema_prefix =\n opts.schema !== undefined\n ? 'You must respond with a single JSON value that conforms to the expected schema. Return ONLY the JSON value, with no markdown or commentary.'\n : 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\n const generate_span = start_generate_span(trajectory, {\n model: resolved_model,\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 pricing_dedup = create_pricing_missing_dedup(trajectory)\n\n const resolve_pricing = (): Pricing | undefined => {\n return engine.pricing[pricing_key(target.provider, target.model_id)]\n }\n\n const dispatch_chunk =\n on_chunk_provided\n ? async (chunk: StreamChunk): Promise<void> => {\n await dispatcher.dispatch(chunk)\n }\n : undefined\n\n const messages_mutable: Message[] = [...initial_messages]\n let total_steps = 0\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 = schema_repair_attempts\n let content_parsed: T | undefined\n // Stryker disable next-line ConditionalExpression,EqualityOperator: for a schema call this is overwritten in the loop before use; for a no-schema call schema_satisfied is never read (the opts.schema === undefined final-content branch wins).\n let schema_satisfied = opts.schema === undefined\n // One holder per generate call so schema-repair re-invocations of the loop\n // cannot refill the salvage budget.\n const salvage_budget =\n tool_call_repair_attempts > 0 ? { remaining: tool_call_repair_attempts } : undefined\n\n try {\n while (true) {\n const loop_result = await run_tool_loop({\n invoke_once,\n messages: messages_mutable,\n tools: tools_list,\n max_steps,\n step_index_start: total_steps,\n tool_error_policy,\n abort,\n on_tool_approval: opts.on_tool_approval,\n trajectory,\n stream: on_chunk_provided,\n dispatch_chunk,\n provider: target.provider,\n model_id: target.model_id,\n resolve_pricing,\n pricing_dedup,\n ...(salvage_budget !== undefined ? { salvage_budget } : {}),\n ...(max_tool_calls_per_step !== undefined ? { max_tool_calls_per_step } : {}),\n ...(opts.prepare_step !== undefined ? { prepare_step: opts.prepare_step } : {}),\n })\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 total_steps = steps_accum.length\n text = loop_result.text\n finish_reason = loop_result.finish_reason\n\n if (opts.schema === undefined) break\n if (finish_reason !== 'stop') break\n\n const parse = parse_with_schema(opts.schema, text)\n if (parse.ok) {\n content_parsed = parse.value\n schema_satisfied = true\n break\n }\n record_schema_validation_failed(trajectory, {\n attempt: repair_remaining === schema_repair_attempts ? 'initial' : 'repair',\n zod_issues: format_zod_error(parse.error),\n raw_text: text,\n })\n if (repair_remaining <= 0 || total_steps >= max_steps) {\n throw_schema_validation(parse.error, text)\n }\n repair_remaining -= 1\n messages_mutable.push(build_repair_message(parse.error))\n }\n\n const aggregated_usage = sum_usage(steps_accum)\n const aggregated_cost = aggregate_cost(steps_accum, target.provider)\n\n let final_content: T\n if (opts.schema === undefined) {\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n final_content = text as T\n } else if (schema_satisfied && content_parsed !== undefined) {\n final_content = content_parsed\n } else {\n // Unreachable: if schema set and not satisfied we throw above.\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n final_content = text as T\n }\n\n const result: GenerateResult<T> = {\n content: final_content,\n tool_calls: tool_calls_accum,\n steps: steps_accum,\n usage: aggregated_usage,\n finish_reason,\n model_resolved: { provider: target.provider, model_id: target.model_id },\n }\n if (aggregated_cost !== undefined) result.cost = aggregated_cost\n\n if (on_chunk_provided) {\n await dispatcher.dispatch({\n kind: 'finish',\n finish_reason,\n usage: aggregated_usage,\n })\n }\n\n end_generate_span(trajectory, generate_span, {\n usage: aggregated_usage,\n finish_reason,\n model_resolved: result.model_resolved,\n })\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 * Round `v` to 6 decimal places, the resolution used for the USD cost fields.\n */\nexport function round6(v: number): number {\n return Math.round(v * 1e6) / 1e6\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 let any_present = false\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 let reasoning_present = false\n let reasoning = 0\n for (const s of steps) {\n if (s.cost === undefined) continue\n any_present = true\n total += s.cost.total_usd\n input += s.cost.input_usd\n output += s.cost.output_usd\n if (s.cost.cached_input_usd !== undefined) {\n cached_present = true\n cached += s.cost.cached_input_usd\n }\n if (s.cost.cache_write_usd !== undefined) {\n cache_write_present = true\n cache_write += s.cost.cache_write_usd\n }\n if (s.cost.reasoning_usd !== undefined) {\n reasoning_present = true\n reasoning += s.cost.reasoning_usd\n }\n }\n if (!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(total),\n input_usd: round6(input),\n output_usd: round6(output),\n currency: 'USD',\n is_estimate: true,\n }\n if (cached_present) out.cached_input_usd = round6(cached)\n if (cache_write_present) out.cache_write_usd = round6(cache_write)\n if (reasoning_present) out.reasoning_usd = round6(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 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 * 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 (\n config.providers === null ||\n typeof config.providers !== 'object'\n ) {\n throw new engine_config_error('EngineConfig.providers is required')\n }\n\n const adapters = build_provider_adapters(config.providers, config.custom_providers)\n\n const pricing: Record<string, Pricing> = { ...DEFAULT_PRICING }\n if (config.pricing !== undefined) {\n for (const [key, value] of Object.entries(config.pricing)) {\n pricing[key] = value\n }\n }\n\n const defaults = config.defaults\n // `config.defaults.*` is the current nested layer; `config.default_retry`,\n // `config.default_effort`, and `config.default_max_steps` are older\n // top-level fields kept for compatibility. Where both are set, the nested\n // `defaults` value wins, and the built-in constant is the last resort.\n const default_retry = defaults?.retry_policy ?? config.default_retry ?? DEFAULT_RETRY\n const default_effort = defaults?.effort ?? config.default_effort ?? 'none'\n const default_max_steps = defaults?.max_steps ?? config.default_max_steps ?? 10\n // Validated once here, at construction, rather than on every generate call\n // that ends up using the default: a bad default should fail fast instead\n // of surfacing deep inside the first call that needs it.\n if (defaults?.tool_call_repair_attempts !== undefined && defaults.tool_call_repair_attempts < 0) {\n throw new engine_config_error('defaults.tool_call_repair_attempts must be >= 0')\n }\n if (defaults?.max_tool_calls_per_step !== undefined && defaults.max_tool_calls_per_step < 1) {\n throw new engine_config_error('defaults.max_tool_calls_per_step must be >= 1')\n }\n if (defaults?.turn_timeout_ms !== undefined && defaults.turn_timeout_ms <= 0) {\n throw new engine_config_error('defaults.turn_timeout_ms must be > 0')\n }\n\n const get_internals = (): EngineInternals => ({\n pricing,\n adapters,\n default_retry,\n default_effort,\n default_max_steps,\n ...(defaults?.model !== undefined ? { default_model: defaults.model } : {}),\n ...(defaults?.provider !== undefined ? { default_provider: defaults.provider } : {}),\n ...(defaults?.system !== undefined ? { default_system: defaults.system } : {}),\n ...(defaults?.tool_error_policy !== undefined\n ? { default_tool_error_policy: defaults.tool_error_policy }\n : {}),\n ...(defaults?.schema_repair_attempts !== undefined\n ? { default_schema_repair_attempts: defaults.schema_repair_attempts }\n : {}),\n ...(defaults?.tool_call_repair_attempts !== undefined\n ? { default_tool_call_repair_attempts: defaults.tool_call_repair_attempts }\n : {}),\n ...(defaults?.max_tool_calls_per_step !== undefined\n ? { default_max_tool_calls_per_step: defaults.max_tool_calls_per_step }\n : {}),\n ...(defaults?.turn_timeout_ms !== undefined\n ? { default_turn_timeout_ms: defaults.turn_timeout_ms }\n : {}),\n ...(defaults?.ai_sdk_telemetry !== undefined\n ? { default_ai_sdk_telemetry: defaults.ai_sdk_telemetry }\n : {}),\n ...(defaults?.provider_options !== undefined\n ? { default_provider_options: defaults.provider_options }\n : {}),\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","/**\n * model_call: the single sanctioned bridge between the composition and\n * engine layers.\n *\n * This is the only file under `src/` permitted to import value symbols from\n * both `core` and `engine` (enforced by the model-call-is-sole-bridge\n * ast-grep rule in `rules/`).\n *\n * The returned Step auto-threads ctx.abort, ctx.trajectory, and, only when\n * run.stream is driving, an on_chunk forwarder that records each chunk as a\n * `model_chunk` trajectory event. Callers cannot override these: the\n * composition layer owns cancellation and trajectory plumbing. Cost events\n * flow out via ctx.trajectory per the engine's own emission rules.\n */\n\nimport { createHash } from 'node:crypto'\nimport { aborted_error, step } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport type {\n EffortLevel,\n Engine,\n GenerateOptions,\n GenerateResult,\n Message,\n RetryPolicy,\n Tool,\n ToolApprovalHandler,\n} from '#engine'\nimport type { z } from 'zod'\n\nexport type ModelCallInput = string | ReadonlyArray<Message>\n\nexport type ModelCallConfig<T = string> = {\n readonly engine: Engine\n /**\n * Model or alias string. Optional: if omitted, the engine's\n * `defaults.model` is used. Errors at call time if neither is set.\n */\n readonly model?: string\n /**\n * Transport for the model: `anthropic` | `claude_cli` | `openrouter` | ...\n * Optional: if omitted, the engine's `defaults.provider` (or sole configured\n * provider, else `anthropic`) is used.\n */\n readonly provider?: string\n readonly id?: string\n readonly system?: string\n readonly tools?: ReadonlyArray<Tool>\n readonly schema?: z.ZodType<T>\n readonly effort?: EffortLevel\n readonly max_steps?: number\n readonly provider_options?: Record<string, unknown>\n readonly retry_policy?: RetryPolicy\n readonly tool_error_policy?: 'feed_back' | 'throw'\n readonly schema_repair_attempts?: number\n readonly tool_call_repair_attempts?: number\n readonly max_tool_calls_per_step?: number\n readonly on_tool_approval?: ToolApprovalHandler\n}\n\n/**\n * Wrap the run's trajectory so the engine's own spans (engine.generate and its\n * step spans) nest under the model_call step rather than floating. The wrapper\n * keeps a private span stack seeded with the model_call step's id, so nesting\n * is correct and concurrency-safe even when several model_calls run together\n * under `parallel`/`map` (each invocation builds its own wrapper). A\n * caller-supplied `parent_span_id` is never overridden.\n */\nfunction engine_trajectory(\n inner: TrajectoryLogger,\n root_parent: string | undefined,\n): TrajectoryLogger {\n const stack: string[] = root_parent !== undefined ? [root_parent] : []\n return {\n record: (event) => {\n inner.record(event)\n },\n start_span: (name, meta) => {\n const has_parent = meta !== undefined && 'parent_span_id' in meta\n const parent = stack.length > 0 ? stack[stack.length - 1] : undefined\n const next_meta =\n has_parent || parent === undefined ? meta : { ...meta, parent_span_id: parent }\n const id = inner.start_span(name, next_meta)\n stack.push(id)\n return id\n },\n end_span: (id, meta) => {\n inner.end_span(id, meta)\n const idx = stack.lastIndexOf(id)\n if (idx !== -1) stack.splice(idx, 1)\n },\n }\n}\n\n/**\n * Derive a short, stable hash from the call's model, provider, system\n * prompt, and tool/schema shape.\n *\n * Used to build a default step id when the caller doesn't supply `cfg.id`.\n */\nfunction stable_signature(input: {\n model: string | undefined\n provider: string | undefined\n system: string | undefined\n has_tools: boolean\n has_schema: boolean\n}): string {\n const payload = JSON.stringify({\n model: input.model ?? null,\n provider: input.provider ?? null,\n system: input.system ?? null,\n has_tools: input.has_tools,\n has_schema: input.has_schema,\n })\n return createHash('sha256').update(payload).digest('hex').slice(0, 8)\n}\n\n/**\n * Build a `Step` that calls `cfg.engine.generate` with `cfg` translated into\n * `GenerateOptions`.\n *\n * Threads `ctx.abort` and `ctx.trajectory` (nested under the model_call\n * step's own span) into every call, and, when `run.stream` is driving,\n * records each chunk as a `model_chunk` trajectory event.\n */\nexport function model_call<T = string>(\n cfg: ModelCallConfig<T>,\n): Step<ModelCallInput, GenerateResult<T>> {\n const has_tools = Boolean(cfg.tools && cfg.tools.length > 0)\n const has_schema = cfg.schema !== undefined\n const step_id =\n cfg.id ??\n `model_call:${stable_signature({\n model: cfg.model,\n provider: cfg.provider,\n system: cfg.system,\n has_tools,\n has_schema,\n })}`\n\n const describe_config: {\n model?: string\n provider?: string\n has_tools: boolean\n has_schema: boolean\n system?: string\n effort?: EffortLevel\n } = {\n has_tools,\n has_schema,\n }\n if (cfg.model !== undefined) describe_config.model = cfg.model\n if (cfg.provider !== undefined) describe_config.provider = cfg.provider\n if (cfg.system !== undefined) describe_config.system = cfg.system\n if (cfg.effort !== undefined) describe_config.effort = cfg.effort\n\n const inner = step<ModelCallInput, GenerateResult<T>>(step_id, async (input, ctx) => {\n if (ctx.abort.aborted) {\n throw new aborted_error('aborted before model_call', {\n reason: { signal: 'abort' },\n step_index: 0,\n })\n }\n \n const prompt: Message[] =\n typeof input === 'string'\n ? [{ role: 'user', content: [{ type: 'text', text: input }] }]\n : [...input]\n \n const opts: GenerateOptions<T> = {\n prompt,\n abort: ctx.abort,\n trajectory: engine_trajectory(ctx.trajectory, ctx.parent_span_id),\n }\n if (cfg.model !== undefined) opts.model = cfg.model\n if (cfg.provider !== undefined) opts.provider = cfg.provider\n if (cfg.system !== undefined) opts.system = cfg.system\n if (cfg.tools !== undefined) opts.tools = [...cfg.tools]\n if (cfg.schema !== undefined) opts.schema = cfg.schema\n if (cfg.effort !== undefined) opts.effort = cfg.effort\n if (cfg.max_steps !== undefined) opts.max_steps = cfg.max_steps\n if (cfg.provider_options !== undefined) opts.provider_options = cfg.provider_options\n if (cfg.retry_policy !== undefined) opts.retry = cfg.retry_policy\n if (cfg.tool_error_policy !== undefined) opts.tool_error_policy = cfg.tool_error_policy\n if (cfg.schema_repair_attempts !== undefined) {\n opts.schema_repair_attempts = cfg.schema_repair_attempts\n }\n if (cfg.tool_call_repair_attempts !== undefined) {\n opts.tool_call_repair_attempts = cfg.tool_call_repair_attempts\n }\n if (cfg.max_tool_calls_per_step !== undefined) {\n opts.max_tool_calls_per_step = cfg.max_tool_calls_per_step\n }\n if (cfg.on_tool_approval !== undefined) opts.on_tool_approval = cfg.on_tool_approval\n \n if (ctx.streaming) {\n opts.on_chunk = (chunk) => {\n // Record with kind preserved. ctx.emit would clobber kind to 'emit'\n // and bury the chunk, so stream consumers would have to un-nest a\n // generic event; recording keeps a clean top-level `model_chunk` event\n // (what docs/concepts.md already documents) carrying the StreamChunk.\n ctx.trajectory.record({ kind: 'model_chunk', step_id, chunk })\n }\n }\n \n return cfg.engine.generate(opts)\n })\n\n return {\n id: inner.id,\n kind: inner.kind,\n run: (input, ctx) => inner.run(input, ctx),\n config: Object.freeze({ ...describe_config }),\n }\n}\n","/**\n * Env forwarding allowlist for CLI subprocesses.\n *\n * Useful when passing explicit env to `claude_cli` under api_key mode\n * (oauth mode inherits the parent env automatically), or whenever an\n * explicit, minimal allowlist is preferred over inheriting the full parent\n * env.\n */\nconst STANDARD_KEYS = ['PATH', 'HOME', 'SHELL', 'USER', 'LOGNAME', 'LANG', 'TMPDIR'] as const\n\n/**\n * Return the standard env vars a CLI subprocess needs to reach a user's\n * logged-in session: PATH, HOME, SHELL, USER, LOGNAME, LANG, TMPDIR.\n *\n * Keys absent from `process.env` are skipped.\n *\n * @example\n * provider_options: {\n * claude_cli: { env: forward_standard_env() },\n * }\n */\nexport function forward_standard_env(): Record<string, string> {\n const out: Record<string, string> = {}\n for (const key of STANDARD_KEYS) {\n const v = process.env[key]\n if (typeof v === 'string') out[key] = v\n }\n return out\n}\n","/**\n * In-process pub/sub for trajectory events.\n *\n * One ring buffer of the last N events plus a Set of subscriber callbacks.\n * Both producers (file tail and HTTP ingest) push into the same broadcaster;\n * SSE writers fan out via `subscribe`.\n */\n\nimport type { ParsedTrajectoryEvent } from '#core'\n\nexport type BroadcastEvent = {\n readonly id: number\n readonly event: ParsedTrajectoryEvent\n}\n\nexport type Subscriber = (entry: BroadcastEvent) => void\n\nexport type Broadcaster = {\n readonly emit: (event: ParsedTrajectoryEvent) => BroadcastEvent\n readonly subscribe: (fn: Subscriber) => () => void\n readonly snapshot: () => readonly BroadcastEvent[]\n readonly snapshot_after: (last_id: number) => readonly BroadcastEvent[]\n readonly size: () => number\n}\n\nexport type BroadcasterOptions = {\n readonly buffer: number\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\n/**\n * Creates a broadcaster: a bounded ring buffer plus subscriber fan-out.\n *\n * Each event gets a monotonic `id` so SSE clients can replay from a known\n * cursor on reconnect (`snapshot_after`). `emit` does not await delivery, so\n * slow-client backpressure is the subscriber's responsibility. A subscriber\n * that throws is unsubscribed, and the `on_subscriber_error` callback fires\n * once with the captured error so the server can log it.\n */\nexport function create_broadcaster(options: BroadcasterOptions): Broadcaster {\n // `| 0` truncates fractional sizes; clamp so the ring keeps at least one\n // event.\n const max = Math.max(1, options.buffer | 0)\n const ring: BroadcastEvent[] = []\n const subscribers = new Set<Subscriber>()\n let next_id = 1\n\n const emit = (event: ParsedTrajectoryEvent): BroadcastEvent => {\n const entry: BroadcastEvent = { id: next_id++, event }\n ring.push(entry)\n if (ring.length > max) ring.splice(0, ring.length - max)\n // Iterate a copy so deleting a throwing subscriber (or an unsubscribe\n // triggered from inside a callback) cannot upset the live Set.\n for (const fn of Array.from(subscribers)) {\n try {\n fn(entry)\n } catch (err) {\n subscribers.delete(fn)\n if (options.on_subscriber_error) options.on_subscriber_error(err)\n }\n }\n return entry\n }\n\n const subscribe = (fn: Subscriber): (() => void) => {\n subscribers.add(fn)\n return () => { subscribers.delete(fn) }\n }\n\n const snapshot = (): readonly BroadcastEvent[] => [...ring]\n\n const snapshot_after = (last_id: number): readonly BroadcastEvent[] =>\n ring.filter((e) => e.id > last_id)\n\n const size = (): number => ring.length\n\n return { emit, subscribe, snapshot, snapshot_after, size }\n}\n","/**\n * Tiny HTTP server: 5 routes, SSE fan-out, NDJSON ingest.\n *\n * GET / -> static viewer.html\n * GET /api/events -> text/event-stream replaying the ring buffer\n * GET /api/snapshot -> JSON dump of the ring buffer\n * POST /api/ingest -> newline-delimited trajectory events (http_logger)\n * GET /api/health -> { ok: true }\n *\n * The server owns nothing but the socket. The broadcaster owns the event\n * history; the static html lives on disk. SSE clients reconnect with\n * `Last-Event-ID` and the server replays anything past their cursor from\n * the ring buffer; older events are gone (bounded memory by design).\n */\n\nimport { createReadStream, statSync } from 'node:fs'\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'\nimport { dirname, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { trajectory_event_schema, type ParsedTrajectoryEvent } from '#core'\nimport type { Broadcaster } from './broadcast.js'\n\nconst SSE_HEARTBEAT_MS = 15_000\nconst HERE = dirname(fileURLToPath(import.meta.url))\nconst STATIC_HTML = resolve(HERE, 'static', 'viewer.html')\n\nexport type ServerOptions = {\n readonly broadcaster: Broadcaster\n readonly host: string\n readonly port: number\n readonly on_parse_error?: (err: unknown, line: string) => void\n}\n\nexport type ViewerServer = {\n readonly url: string\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the HTTP server and resolves once it is listening.\n *\n * Wires the five routes (static HTML, health, snapshot, SSE, ingest) to a\n * single request handler and resolves with the bound URL and a `close`\n * that shuts the socket down.\n */\nexport function start_server(options: ServerOptions): Promise<ViewerServer> {\n const { broadcaster, host, port, on_parse_error } = options\n\n const handler = (req: IncomingMessage, res: ServerResponse): void => {\n const route = resolve_route(req, host, port)\n\n if (route === 'GET /' || route === 'GET /index.html') {\n serve_static_html(res)\n return\n }\n if (route === 'GET /api/health') {\n send_json(res, 200, { ok: true })\n return\n }\n if (route === 'GET /api/snapshot') {\n send_json(res, 200, { events: broadcaster.snapshot() })\n return\n }\n if (route === 'GET /api/events') {\n handle_sse(req, res, broadcaster)\n return\n }\n if (route === 'POST /api/ingest') {\n handle_ingest(req, res, broadcaster, on_parse_error)\n return\n }\n res.statusCode = 404\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify({ error: 'not_found', route }))\n }\n\n const http_server = createServer(handler)\n\n return new Promise((res_ok, res_err) => {\n // `listen` can fail (e.g. port already in use); reject instead of\n // leaving the returned promise pending forever.\n http_server.once('error', res_err)\n http_server.listen(port, host, () => {\n http_server.removeListener('error', res_err)\n // `address().port` is the port actually bound. It only differs from\n // the requested `port` when the caller passed 0 and asked the OS to\n // pick a free port.\n const addr = http_server.address()\n const bound_port =\n addr !== null && typeof addr === 'object' && 'port' in addr ? addr.port : port\n const url = `http://${host}:${bound_port}`\n res_ok({\n url,\n close: () => close_server(http_server),\n })\n })\n })\n}\n\n/**\n * Builds a `\"METHOD /path\"` route key from a request.\n *\n * Falls back to the server's own `host`/`port` when the request has no\n * `Host` header, so a malformed or missing header never throws inside\n * `new URL`.\n */\nexport function resolve_route(\n req: {\n url?: string | undefined\n method?: string | undefined\n headers: { host?: string | undefined }\n },\n host: string,\n port: number,\n): string {\n const url = new URL(req.url ?? '/', `http://${req.headers.host ?? `${host}:${port}`}`)\n return `${req.method ?? 'GET'} ${url.pathname}`\n}\n\n/**\n * Closes the HTTP server and resolves once every connection is torn down.\n */\nfunction close_server(server: Server): Promise<void> {\n return new Promise((res_ok, res_err) => {\n server.close((err) => {\n if (err) res_err(err)\n else res_ok()\n })\n // `close` alone only stops new connections and waits for existing ones\n // (including open SSE streams) to end on their own, which can hang\n // indefinitely. Force them closed so shutdown actually completes.\n server.closeAllConnections?.()\n })\n}\n\n/**\n * Writes a JSON response with the given status code.\n */\nfunction send_json(res: ServerResponse, status: number, body: unknown): void {\n res.statusCode = status\n res.setHeader('content-type', 'application/json')\n res.end(JSON.stringify(body))\n}\n\n/**\n * Streams the bundled `viewer.html` as the response body.\n */\nfunction serve_static_html(res: ServerResponse): void {\n let size: number\n try {\n // Stat first so a missing file produces a clean 500 response instead\n // of a stream error after headers have already been sent.\n size = statSync(STATIC_HTML).size\n } catch {\n res.statusCode = 500\n res.setHeader('content-type', 'text/plain')\n res.end('viewer.html missing')\n return\n }\n res.statusCode = 200\n res.setHeader('content-type', 'text/html; charset=utf-8')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('content-length', String(size))\n createReadStream(STATIC_HTML).pipe(res)\n}\n\n/**\n * Handles `GET /api/events` by turning the connection into an SSE stream.\n *\n * Replays whatever the client missed since its `Last-Event-ID` cursor,\n * subscribes it to the broadcaster for new events, and keeps the\n * connection alive with a periodic heartbeat comment.\n */\nfunction handle_sse(req: IncomingMessage, res: ServerResponse, broadcaster: Broadcaster): void {\n res.statusCode = 200\n res.setHeader('content-type', 'text/event-stream')\n res.setHeader('cache-control', 'no-store')\n res.setHeader('connection', 'keep-alive')\n // Disables response buffering in nginx so SSE frames reach the client as\n // soon as they are written instead of sitting in a proxy buffer.\n res.setHeader('x-accel-buffering', 'no')\n\n // Replay everything after the client's cursor before subscribing. Both\n // calls run synchronously back to back, so there is no window in which\n // an event could land between the replay and the live subscription.\n const last_event_id = parse_last_event_id(req.headers['last-event-id'])\n for (const entry of broadcaster.snapshot_after(last_event_id)) {\n write_event(res, entry.id, entry.event)\n }\n\n // Comment frames keep the connection alive through idle proxies and\n // load balancers that would otherwise time out a quiet SSE stream.\n const heartbeat = setInterval(() => {\n res.write(': heartbeat\\n\\n')\n }, SSE_HEARTBEAT_MS)\n\n const unsubscribe = broadcaster.subscribe((entry) => {\n write_event(res, entry.id, entry.event)\n })\n\n const close = (): void => {\n clearInterval(heartbeat)\n unsubscribe()\n if (!res.writableEnded) {\n res.write('event: close\\ndata: {}\\n\\n')\n res.end()\n }\n }\n\n // A clean disconnect and a socket error both need the same cleanup.\n req.on('close', close)\n req.on('error', close)\n}\n\n/**\n * Parses the `Last-Event-ID` header into a replay cursor, defaulting to 0.\n *\n * Treats a missing header or a non-numeric or non-positive value as \"no\n * cursor\", which makes `handle_sse` replay the full ring buffer.\n */\nfunction parse_last_event_id(value: string | string[] | undefined): number {\n if (typeof value !== 'string') return 0\n const n = Number.parseInt(value, 10)\n return Number.isFinite(n) && n > 0 ? n : 0\n}\n\n/**\n * Writes one SSE `trajectory` event frame to the response stream.\n */\nfunction write_event(res: ServerResponse, id: number, event: ParsedTrajectoryEvent): void {\n res.write(`id: ${id}\\nevent: trajectory\\ndata: ${JSON.stringify(event)}\\n\\n`)\n}\n\n/**\n * Handles `POST /api/ingest`: parses newline-delimited trajectory events\n * from the request body and feeds valid ones into the broadcaster.\n *\n * Reports how many lines were accepted vs rejected in the response body;\n * a malformed line is skipped and reported via `on_parse_error`, not\n * treated as a fatal request error.\n */\nfunction handle_ingest(\n req: IncomingMessage,\n res: ServerResponse,\n broadcaster: Broadcaster,\n on_parse_error?: (err: unknown, line: string) => void,\n): void {\n let buf = ''\n let accepted = 0\n let rejected = 0\n\n const consume_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n rejected++\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = trajectory_event_schema.safeParse(parsed)\n if (!result.success) {\n rejected++\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n broadcaster.emit(result.data)\n accepted++\n }\n\n req.setEncoding('utf8')\n req.on('data', (chunk: string) => {\n buf += chunk\n // Consume every complete line in the buffer so far; a trailing partial\n // line (no `\\n` yet) stays in `buf` until a later chunk completes it.\n let nl = buf.indexOf('\\n')\n while (nl !== -1) {\n consume_line(buf.slice(0, nl))\n buf = buf.slice(nl + 1)\n nl = buf.indexOf('\\n')\n }\n })\n req.on('end', () => {\n // Flush a final line that arrived without a trailing newline.\n if (buf.length > 0) consume_line(buf)\n send_json(res, 200, { accepted, rejected })\n })\n req.on('error', (err: unknown) => {\n if (on_parse_error) on_parse_error(err, '')\n send_json(res, 400, { error: 'bad_request' })\n })\n}\n\nexport const internals_for_test = { STATIC_HTML, SSE_HEARTBEAT_MS, parse_last_event_id }\n","/**\n * JSONL file tailer.\n *\n * Watches a file for appends and emits one parsed trajectory event per\n * complete line. Handles three pathological cases:\n *\n * - Truncation / rotation: a watcher event whose stat is shorter than the\n * current offset means the file shrunk. Reset offset to 0 and re-stream.\n * - Partial last line: if the trailing chunk has no `\\n`, buffer it and\n * wait. Never parse a half-written line.\n * - Schema failures: a line that fails `trajectory_event_schema.parse` is\n * dropped and surfaced to `on_parse_error`. The stream keeps going.\n *\n * The watcher is fs.watch-based; reads are serialized and change events\n * that arrive mid-read are coalesced into one extra pass rather than\n * dropped, so a burst of appends never starts overlapping reads. Each pass\n * re-stats and re-reads from the saved offset, which also covers platforms\n * where fs.watch misses some append notifications: the next successful\n * change event catches the file up regardless.\n */\n\nimport { type FSWatcher, watch as fs_watch } from 'node:fs'\nimport { open, stat } from 'node:fs/promises'\nimport { trajectory_event_schema, type ParsedTrajectoryEvent } from '#core'\n\nexport type TailOptions = {\n readonly path: string\n readonly on_event: (event: ParsedTrajectoryEvent) => void\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n}\n\nexport type Tail = {\n readonly stop: () => void\n readonly drain: () => Promise<void>\n}\n\n/**\n * Starts tailing `path` and returns a handle to stop or drain it.\n *\n * Watches the file with `fs.watch` and re-reads from the last known offset\n * on every change, buffering an incomplete trailing line until the rest\n * arrives. Overlapping change events are coalesced: a read already in\n * flight absorbs any events that fire while it runs instead of starting a\n * second concurrent read.\n */\nexport function start_tail(options: TailOptions): Tail {\n const { path, on_event, on_parse_error, on_io_error } = options\n let offset = 0\n let buffer = ''\n let busy = false\n let pending = false\n let closed = false\n let watcher: FSWatcher | null = null\n let last_drain: Promise<void> = Promise.resolve()\n\n const handle_line = (line: string): void => {\n if (line.length === 0) return\n let parsed: unknown\n try {\n parsed = JSON.parse(line)\n } catch (err) {\n if (on_parse_error) on_parse_error(err, line)\n return\n }\n const result = trajectory_event_schema.safeParse(parsed)\n if (!result.success) {\n if (on_parse_error) on_parse_error(result.error, line)\n return\n }\n on_event(result.data)\n }\n\n const read_more = async (): Promise<void> => {\n let st\n try {\n st = await stat(path)\n } catch (err) {\n if (on_io_error) on_io_error(err)\n return\n }\n if (st.size < offset) {\n // File is shorter than our offset: it was truncated or rotated.\n // Restart from the top instead of seeking to a now-invalid offset.\n offset = 0\n buffer = ''\n }\n if (st.size === offset) return\n\n const fh = await open(path, 'r').catch((err: unknown) => {\n if (on_io_error) on_io_error(err)\n return null\n })\n if (!fh) return\n try {\n const length = st.size - offset\n const buf = Buffer.alloc(length)\n const { bytesRead } = await fh.read(buf, 0, length, offset)\n offset += bytesRead\n buffer += buf.subarray(0, bytesRead).toString('utf8')\n } finally {\n await fh.close()\n }\n\n let nl = buffer.indexOf('\\n')\n while (nl !== -1) {\n const line = buffer.slice(0, nl)\n buffer = buffer.slice(nl + 1)\n handle_line(line)\n nl = buffer.indexOf('\\n')\n }\n // Anything left in `buffer` has no trailing newline yet; keep it for\n // the next read instead of parsing a half-written line.\n }\n\n // Coalesces watcher bursts: if `schedule` fires while a read is already\n // running, it just flags `pending` and returns. The running loop below\n // checks `pending` after each pass and does one more pass if it was set,\n // so a burst of change events never starts overlapping reads.\n const schedule = (): void => {\n if (closed) return\n if (busy) {\n pending = true\n return\n }\n busy = true\n last_drain = (async (): Promise<void> => {\n try {\n let keep_going = true\n while (keep_going) {\n pending = false\n await read_more()\n keep_going = pending && !closed\n }\n } finally {\n busy = false\n }\n })()\n }\n\n schedule()\n\n try {\n watcher = fs_watch(path, { persistent: true }, () => { schedule() })\n } catch (err) {\n if (on_io_error) on_io_error(err)\n }\n\n const stop = (): void => {\n closed = true\n if (watcher) {\n watcher.close()\n watcher = null\n }\n }\n\n const drain = async (): Promise<void> => {\n schedule()\n await last_drain\n }\n\n return { stop, drain }\n}\n","/**\n * `start_viewer` programmatic embed implementation.\n *\n * Spin up the server, optionally start tailing a JSONL file, and return a\n * handle that can stop both. `start_viewer` only depends on core's wire-format\n * schema; it never reaches into the engine, composites, or any provider.\n */\n\nimport { create_broadcaster } from './broadcast.js'\nimport { start_server, type ViewerServer } from './server.js'\nimport { start_tail, type Tail } from './tail.js'\n\nexport type StartViewerOptions = {\n readonly path?: string\n readonly host?: string\n readonly port?: number\n readonly buffer?: number\n readonly on_parse_error?: (err: unknown, line: string) => void\n readonly on_io_error?: (err: unknown) => void\n readonly on_subscriber_error?: (err: unknown) => void\n}\n\nexport type ViewerHandle = {\n readonly url: string\n readonly host: string\n readonly port: number\n readonly close: () => Promise<void>\n}\n\n/**\n * Starts the viewer: brings up the HTTP/SSE server and, if `options.path`\n * is set, a file tail that feeds the same broadcaster.\n *\n * Defaults to `127.0.0.1:4242` with a 1000-event ring buffer. HTTP ingest\n * and SSE are always available; tailing is opt-in via `path`.\n */\nexport async function start_viewer(options: StartViewerOptions = {}): Promise<ViewerHandle> {\n const host = options.host ?? '127.0.0.1'\n const port = options.port ?? 4242\n const buffer = options.buffer ?? 1000\n const broadcaster = create_broadcaster({\n buffer,\n ...(options.on_subscriber_error ? { on_subscriber_error: options.on_subscriber_error } : {}),\n })\n const server = await start_server({\n broadcaster,\n host,\n port,\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n })\n\n let tail: Tail | null = null\n if (options.path !== undefined) {\n tail = start_tail({\n path: options.path,\n on_event: (event) => { broadcaster.emit(event) },\n ...(options.on_parse_error ? { on_parse_error: options.on_parse_error } : {}),\n ...(options.on_io_error ? { on_io_error: options.on_io_error } : {}),\n })\n }\n\n return wrap_handle(server, tail, host, port)\n}\n\n/**\n * Combines the server and optional tail into a single `ViewerHandle`.\n *\n * `close` stops the tail first, then closes the server, mirroring the\n * startup order (server first, tail second) in reverse.\n */\nfunction wrap_handle(\n server: ViewerServer,\n tail: Tail | null,\n host: string,\n port: number,\n): ViewerHandle {\n return {\n url: server.url,\n host,\n port,\n close: async () => {\n if (tail) tail.stop()\n await server.close()\n },\n }\n}\n","#!/usr/bin/env tsx\n/**\n * fascicle-viewer CLI.\n *\n * fascicle-viewer <path> # tail a JSONL file (primary)\n * fascicle-viewer --listen # accept HTTP push only\n * fascicle-viewer <path> --listen # both producers feed the same broadcaster\n *\n * Flags: --port <n> --host <h> --buffer <n> --no-open --help\n *\n * Defaults bind 127.0.0.1:4242 and open the user's default browser. SIGINT\n * shuts everything down cleanly. The CLI body is exposed as `run_viewer_cli`\n * so the umbrella's bin shim can drive it from a bundled `dist/index.js`.\n */\n\nimport { spawn } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { parseArgs } from 'node:util'\nimport { fileURLToPath } from 'node:url'\nimport { start_viewer } from './index.js'\n\ntype CliArgs = {\n readonly path?: string\n readonly host: string\n readonly port: number\n readonly buffer: number\n readonly listen: boolean\n readonly open: boolean\n}\n\nconst HELP = `\\\nfascicle-viewer — minimal in-repo dashboard for fascicle trajectory streams.\n\nUsage:\n fascicle-viewer <path> tail a JSONL file\n fascicle-viewer --listen accept HTTP push only\n fascicle-viewer <path> --listen both producers feed the same broadcaster\n\nOptions:\n --port <n> port (default 4242)\n --host <h> bind host (default 127.0.0.1; --host 0.0.0.0 warns)\n --buffer <n> ring-buffer size (default 1000)\n --no-open do not open the browser\n --help show this message\n`\n\n/**\n * Parses CLI argv into a validated `CliArgs`, exiting on bad input.\n *\n * `--help` prints usage and exits 0. Invalid numeric flags, or a missing\n * <path> without `--listen`, write to stderr and exit 2.\n */\nfunction parse(argv: readonly string[]): CliArgs {\n const { values, positionals } = parseArgs({\n args: [...argv],\n allowPositionals: true,\n options: {\n port: { type: 'string', default: '4242' },\n host: { type: 'string', default: '127.0.0.1' },\n buffer: { type: 'string', default: '1000' },\n listen: { type: 'boolean', default: false },\n open: { type: 'boolean', default: true },\n 'no-open': { type: 'boolean', default: false },\n help: { type: 'boolean', default: false },\n },\n })\n if (values.help) {\n process.stdout.write(HELP)\n process.exit(0)\n }\n const port_raw = values.port ?? '4242'\n const buffer_raw = values.buffer ?? '1000'\n const port = Number.parseInt(port_raw, 10)\n const buffer = Number.parseInt(buffer_raw, 10)\n if (!Number.isFinite(port) || port <= 0) {\n process.stderr.write(`invalid --port: ${port_raw}\\n`)\n process.exit(2)\n }\n if (!Number.isFinite(buffer) || buffer <= 0) {\n process.stderr.write(`invalid --buffer: ${buffer_raw}\\n`)\n process.exit(2)\n }\n const path = positionals[0]\n const listen = values.listen ?? false\n if (path === undefined && !listen) {\n process.stderr.write('fascicle-viewer: a <path> is required unless --listen is set\\n')\n process.stderr.write(HELP)\n process.exit(2)\n }\n return {\n ...(path !== undefined ? { path } : {}),\n host: values.host ?? '127.0.0.1',\n port,\n buffer,\n listen,\n open: !values['no-open'] && (values.open ?? true),\n }\n}\n\n/**\n * Opens `url` in the platform's default browser, best-effort.\n *\n * Spawns the platform opener (`open`, `cmd /c start`, or `xdg-open`)\n * detached and swallows failures; the CLI prints the URL either way.\n */\nfunction open_browser(url: string): void {\n const platform = process.platform\n const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open'\n const args = platform === 'win32' ? ['/c', 'start', '\"\"', url] : [url]\n try {\n const child = spawn(cmd, args, { stdio: 'ignore', detached: true })\n child.on('error', () => {})\n child.unref()\n } catch {\n // Best-effort. The CLI logs the URL anyway.\n }\n}\n\n/**\n * CLI entry point: parses argv, starts the viewer, and wires shutdown.\n *\n * Warns but proceeds when the tailed path does not exist yet or when the\n * bind host is 0.0.0.0 (the dashboard has no auth). Optionally opens the\n * browser, then installs SIGINT/SIGTERM handlers that close the viewer\n * before exiting.\n */\nexport async function run_viewer_cli(argv: readonly string[]): Promise<void> {\n const args = parse(argv)\n\n if (args.path !== undefined && !existsSync(args.path)) {\n process.stderr.write(\n `fascicle-viewer: warning: ${args.path} does not exist yet — will pick up events once it is created\\n`,\n )\n }\n if (args.host === '0.0.0.0') {\n process.stderr.write(\n 'fascicle-viewer: warning: binding 0.0.0.0 — this dashboard has no auth and exposes whatever is in your trajectory stream\\n',\n )\n }\n\n const handle = await start_viewer({\n ...(args.path !== undefined ? { path: args.path } : {}),\n host: args.host,\n port: args.port,\n buffer: args.buffer,\n on_parse_error: (err, line) => {\n const preview = line.length > 120 ? `${line.slice(0, 120)}…` : line\n process.stderr.write(\n `fascicle-viewer: skipped malformed line: ${preview}\\n ${describe_error(err)}\\n`,\n )\n },\n on_io_error: (err) => {\n process.stderr.write(`fascicle-viewer: io error: ${describe_error(err)}\\n`)\n },\n })\n\n if (args.path !== undefined) process.stderr.write(`watching ${args.path}\\n`)\n if (args.listen || args.path === undefined) process.stderr.write(`listening for HTTP push on ${handle.url}/api/ingest\\n`)\n process.stderr.write(`viewer at ${handle.url}\\n`)\n\n if (args.open) open_browser(handle.url)\n\n const shutdown = async (): Promise<void> => {\n process.stderr.write('\\nfascicle-viewer: shutting down\\n')\n await handle.close()\n process.exit(0)\n }\n process.on('SIGINT', () => { void shutdown() })\n process.on('SIGTERM', () => { void shutdown() })\n}\n\n/**\n * Renders an unknown thrown value as a human-readable message.\n */\nfunction describe_error(err: unknown): string {\n if (err instanceof Error) return err.message\n try {\n return JSON.stringify(err)\n } catch {\n return String(err)\n }\n}\n\n// ESM main-module detection. The bundler inlines this file into dist/index.js,\n// so a fragile suffix check (`endsWith('/cli.js')`) would fire whenever a\n// consumer's own entry script happened to be named cli.js, see\n// https://nodejs.org/api/esm.html#importmetaurl. Compare the resolved path of\n// this module against argv[1] so the auto-execute only fires when the file is\n// run directly (e.g. `tsx packages/viewer/src/cli.ts`), not when imported.\nconst invoked_directly =\n process.argv[1] !== undefined &&\n process.argv[1] === fileURLToPath(import.meta.url)\n\nif (invoked_directly) {\n void run_viewer_cli(process.argv.slice(2)).catch((err: unknown) => {\n process.stderr.write(`fascicle-viewer: ${describe_error(err)}\\n`)\n process.exit(1)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAS,uBACP,GAC6B;CAC7B,IAAI,EAAE,cAAc,KAAA,GAAW,OAAO,EAAE,OAAO,EAAE,MAAM;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