combined-ai 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/combine/index.ts","../src/combine/shared.ts","../src/combine/broadcast.ts","../src/combine/consensus.ts","../src/combine/ensemble.ts","../src/combine/pipeline.ts","../src/providers/extract.ts","../src/providers/sse.ts","../src/providers/structured.ts","../src/transport.ts","../src/providers/anthropic.ts","../src/providers/google.ts","../src/providers/openai.ts","../src/registry.ts","../src/errors.ts"],"names":["event","DEFAULT_MODEL","DEFAULT_BASE_URL","DEFAULT_MAX_TOKENS","DEFAULT_STREAM_MAX_TOKENS","extractFinishReason","extractText","extractToolCalls","normalizeFinishReason","extractUsage","toArray","extractRefusal","isRecord"],"mappings":";;;AAgBO,IAAM,cAAA,GAAiB;AAAA,EAC5B,WAAA;AAAA,EACA,UAAA;AAAA,EACA,UAAA;AAAA,EACA;AACF,CAAA;;;AC6BO,SAAS,YACd,OAAA,EAC+B;AAC/B,EAAA,OAAO,CAAC,KAAA,KAAU;AAChB,IAAA,IAAI;AACF,MAAA,OAAA,GAAU,KAAK,CAAA;AAAA,IACjB,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF,CAAA;AACF;AASA,IAAM,gBAAA,GACJ,ggBAAA;AAaK,SAAS,aAAA,CACd,OAAA,EACA,MAAA,EACA,QAAA,EACA,SAAA,EACmB;AACnB,EAAA,MAAM,UAAA,GAAgC,EAAE,QAAA,EAAS;AACjD,EAAA,IAAI,WAAW,MAAA,EAAW;AACxB,IAAA,UAAA,CAAW,MAAA,GAAS,MAAA;AAAA,EACtB;AACA,EAAA,MAAM,KAAA,GAAQ,SAAA,EAAW,KAAA,IAAS,OAAA,CAAQ,KAAA;AAC1C,EAAA,IAAI,UAAU,MAAA,EAAW;AACvB,IAAA,UAAA,CAAW,KAAA,GAAQ,KAAA;AAAA,EACrB;AACA,EAAA,MAAM,SAAA,GAAY,SA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AS,eAAe,IAAA,EAAgD;AACtE,EAAA,IAAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EAC1B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACA,EAAA,OAAO,iBAAiB,MAAM,CAAA;AAChC;AAGA,SAAS,iBAAiB,MAAA,EAAmD;AAC3E,EAAA,IAAI,CAACC,SAAAA,CAAS,MAAM,CAAA,EAAG;AACrB,IAAA,OAAO,EAAC;AAAA,EACV;AACA,EAAA,MAAM,QAAQA,SAAAA,CAAS,MAAA,CAAO,KAAK,CAAA,GAAI,OAAO,KAAA,GAAQ,MAAA;AACtD,EAAA,MAAM,OAAO,OAAO,KAAA,CAAM,IAAA,KAAS,QAAA,GAAW,MAAM,IAAA,GAAO,MAAA;AAC3D,EAAA,MAAM,IAAA,GACJ,OAAO,KAAA,CAAM,IAAA,KAAS,QAAA,GAClB,KAAA,CAAM,IAAA,GACN,OAAO,KAAA,CAAM,MAAA,KAAW,QAAA,GACtB,KAAA,CAAM,MAAA,GACN,MAAA;AACR,EAAA,OAAO,EAAE,MAAM,IAAA,EAAK;AACtB;AAEA,SAASA,UAAS,KAAA,EAAkD;AAClE,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,IAAA;AAChD","file":"index.cjs","sourcesContent":["/**\n * Public types for the **combine** feature — multiple providers cooperating on\n * one prompt via a selectable strategy. The strategy implementations live in\n * sibling files (e.g. `consensus.ts`); the public entry point is\n * {@link ProviderRegistry.combine}.\n */\n\nimport { type ProviderName } from \"../registry\";\nimport {\n type CompletionRequest,\n type CompletionResult,\n type ResponseFormat,\n type Usage,\n} from \"../types\";\n\n/** The cooperation strategies the registry knows how to run. */\nexport const STRATEGY_NAMES = [\n \"consensus\",\n \"pipeline\",\n \"ensemble\",\n \"broadcast\",\n] as const;\n\nexport type StrategyName = (typeof STRATEGY_NAMES)[number];\n\n/**\n * One participant in a combine. A bare provider name uses that provider's\n * configured default model; the object form overrides the model and/or maxTokens\n * for this participant only — letting one combine mix cheap drafters with a strong\n * synthesizer, or run the same provider twice with different models.\n */\nexport type ParticipantSpec =\n | ProviderName\n | {\n /** Which configured provider to run this participant on (validated by the registry). */\n provider: ProviderName;\n /** Model for this participant. Falls back to `request.model`, then the provider default. */\n model?: string;\n /** maxTokens for this participant. Falls back to `request.maxTokens`. */\n maxTokens?: number;\n /**\n * Unique id for this participant in results/events/usage and for `synthesizer`.\n * Defaults to the provider name, or `<provider>-<model>` when `model` is set.\n * Required (must be set explicitly) only to disambiguate two participants that\n * would otherwise resolve to the same id (e.g. the same provider+model twice).\n */\n label?: string;\n };\n\n/**\n * The fields every combine strategy's request shares: the underlying\n * {@link CompletionRequest} (messages, model, maxTokens, system, signal, …) plus\n * the roster of participants. The per-strategy request types\n * ({@link ConsensusRequest}, {@link PipelineRequest}, {@link EnsembleRequest},\n * {@link BroadcastRequest}) extend this with only the options that strategy uses.\n */\nexport type CombineRequestBase = CompletionRequest & {\n /**\n * Who participates. A bare provider name uses its configured default model; the\n * object form ({@link ParticipantSpec}) overrides model/maxTokens per participant.\n * Resolved to a unique id each (see {@link ParticipantSpec.label}); validated by\n * the registry.\n */\n participants: ParticipantSpec[];\n};\n\n/**\n * Request for the `consensus` strategy (draft → critique → synthesize). Call\n * {@link ProviderRegistry.consensus} directly, or pass `strategy: \"consensus\"`\n * (the default) to {@link ProviderRegistry.combine}.\n */\nexport type ConsensusRequest = CombineRequestBase & {\n /**\n * Which participant writes the final synthesized answer, referenced by its\n * **id** (see {@link ParticipantSpec.label}). Defaults to the first participant.\n */\n synthesizer?: string;\n /**\n * Whether drafts are attributed to their provider in the text shown to the\n * other providers. `\"anonymized\"` (default) shows `Answer A`/`Answer B`/… to\n * neutralize brand and self-preference bias; `\"attributed\"` shows participant\n * ids. The returned {@link ConsensusResult} always keeps ids regardless.\n */\n attribution?: \"attributed\" | \"anonymized\";\n /**\n * Minimum number of participants that must successfully produce a draft for a\n * consensus run to proceed. Defaults to 2. A single-provider combine always\n * degrades to a plain completion regardless of this value.\n */\n minParticipants?: number;\n};\n\n/**\n * Request for the `pipeline` strategy (sequential refinement). Call\n * {@link ProviderRegistry.pipeline} directly, or pass `strategy: \"pipeline\"` to\n * {@link ProviderRegistry.combine}. No strategy-specific options — participant\n * order is the conveyor order.\n */\nexport type PipelineRequest = CombineRequestBase;\n\n/**\n * Request for the `ensemble` strategy (multi-model vote on structured output).\n * Call {@link ProviderRegistry.ensemble} directly, or pass `strategy: \"ensemble\"`\n * to {@link ProviderRegistry.combine}. `responseFormat` is **required** (every\n * participant answers under this schema, and the field-wise vote needs an\n * object-root schema).\n */\nexport type EnsembleRequest = CombineRequestBase & {\n responseFormat: ResponseFormat;\n};\n\n/**\n * Request for the `broadcast` strategy (fan-out, no combine). Call\n * {@link ProviderRegistry.broadcast} directly, or pass `strategy: \"broadcast\"` to\n * {@link ProviderRegistry.combine}. No strategy-specific options.\n */\nexport type BroadcastRequest = CombineRequestBase;\n\n/**\n * The broad request accepted by the strategy-dispatching\n * {@link ProviderRegistry.combine}: {@link CombineRequestBase} plus every\n * strategy's options and the `strategy` selector. Today only consensus adds\n * options, so this is {@link ConsensusRequest} plus `strategy` (each strategy\n * reads only the options it uses; `responseFormat` stays optional here, inherited\n * from {@link CompletionRequest}). Prefer a per-strategy method\n * ({@link ProviderRegistry.consensus} etc.) when the strategy is known at the\n * call site — they take the precise {@link ConsensusRequest}/… type and return\n * the concrete result without narrowing.\n */\nexport type CombineRequest = ConsensusRequest & {\n /** Cooperation strategy. Defaults to `\"consensus\"`. */\n strategy?: StrategyName;\n};\n\n/**\n * The outcome of one participant in one phase — either its result or its failure.\n * `id` is the participant's unique id (see {@link ParticipantSpec.label}); `provider`\n * is the actual provider it ran on (these differ when a model override gives the\n * participant a `<provider>-<model>` id, or two participants share one provider).\n * A failure's `error` is typically a `ProviderError` (carrying `status`/`kind`/\n * `code`); narrow with `instanceof ProviderError` to read those fields.\n */\nexport type ParticipantOutcome =\n | {\n id: string;\n provider: ProviderName;\n status: \"ok\";\n result: CompletionResult;\n }\n | { id: string; provider: ProviderName; status: \"failed\"; error: Error };\n\n/**\n * Aggregated token usage across all the model calls a combine made — the true\n * cost of a run, which is several times one completion (a default 3-way\n * consensus is ~8 calls: 3 drafts + 3 critiques + synthesis + sanitize).\n * `undefined` if no participating provider reported usage.\n */\nexport type CombineUsage = {\n /** Total usage summed across every call the combine made. */\n total: Usage;\n /** Usage per participant id, summed across all of that participant's calls. */\n byParticipant: Partial<Record<string, Usage>>;\n};\n\n/** The result of the `consensus` strategy (draft → critique → synthesize). */\nexport type ConsensusResult = {\n /** The final synthesized answer. */\n text: string;\n strategy: \"consensus\";\n /** The id of the participant that wrote the final answer (may be a fallback if the chosen one failed). */\n synthesizer: string;\n /** The model the synthesizer actually used. */\n model: string;\n /** Phase 1 drafts, in participant order (includes any failures). */\n drafts: ParticipantOutcome[];\n /** Phase 2 critiques, in surviving-participant order (includes any failures). */\n critiques: ParticipantOutcome[];\n /** Aggregated token usage across every call, or `undefined` if none was reported. */\n usage?: CombineUsage;\n};\n\n/** The result of the `pipeline` strategy (sequential refinement). */\nexport type PipelineResult = {\n /** The final answer — the output of the last stage that produced one. */\n text: string;\n strategy: \"pipeline\";\n /** The id of the participant that produced the final answer (the last advancing stage). */\n finalParticipant: string;\n /** The model that produced the final answer. */\n model: string;\n /** Every stage in pipeline (participant) order, including any failures. */\n stages: ParticipantOutcome[];\n /** Aggregated token usage across every stage, or `undefined` if none was reported. */\n usage?: CombineUsage;\n};\n\n/**\n * How strongly the ensemble participants agreed on the merged object — the\n * confidence signal a multi-model vote gives you that a single model can't.\n */\nexport type EnsembleAgreement = {\n /** Mean of the per-field agreement scores (0–1), or 1 for an empty object. */\n overall: number;\n /**\n * Per-field agreement: the fraction of the merged responses that voted for the\n * field's merged value (0–1). The denominator is **all** the valid responses,\n * not just the ones that returned the field — so a field most models omitted\n * scores low. 1 means every model returned the field and agreed on its value; a\n * low value flags either disagreement or sparse coverage.\n */\n byField: Record<string, number>;\n};\n\n/**\n * The result of the `ensemble` strategy (each participant returns the same typed\n * object; the objects are merged field-wise by majority vote — with no LLM\n * synthesis — so every merged value is one a model actually returned).\n */\nexport type EnsembleResult = {\n /** The merged object serialized as JSON (the same content as `merged`). */\n text: string;\n strategy: \"ensemble\";\n /** The merged typed object. Cast to your schema's type. */\n merged: Record<string, unknown>;\n /** How strongly the participants agreed, overall and per field. */\n agreement: EnsembleAgreement;\n /** Each participant's structured response, in participant order (includes failures). */\n responses: ParticipantOutcome[];\n /** Aggregated token usage across every participant call, or `undefined` if none was reported. */\n usage?: CombineUsage;\n};\n\n/**\n * The result of the `broadcast` strategy (fan-out to every participant in\n * parallel, no cooperation). There is no single combined answer — hence no\n * `text` field — just every participant's raw response. Narrow on\n * `result.strategy` to reach `responses`.\n */\nexport type BroadcastResult = {\n strategy: \"broadcast\";\n /** Each participant's raw completion, in participant order (includes failures). */\n responses: ParticipantOutcome[];\n /** Aggregated token usage across every participant call, or `undefined` if none was reported. */\n usage?: CombineUsage;\n};\n\n/**\n * The result of a combine, discriminated on `strategy`. Narrow on\n * `result.strategy` to reach the strategy-specific artifacts. Note that\n * `BroadcastResult` has no `text` (it returns every raw response, not one answer).\n */\nexport type CombineResult =\n | ConsensusResult\n | PipelineResult\n | EnsembleResult\n | BroadcastResult;\n\n/**\n * Maps a strategy name to its request type — e.g. `StrategyRequest<\"ensemble\">`\n * is {@link EnsembleRequest}. A utility for callers writing code generic over the\n * strategy.\n */\nexport type StrategyRequest<S extends StrategyName> = {\n consensus: ConsensusRequest;\n pipeline: PipelineRequest;\n ensemble: EnsembleRequest;\n broadcast: BroadcastRequest;\n}[S];\n\n/**\n * Maps a strategy name to its concrete result type — e.g.\n * `ResultFor<\"ensemble\">` is {@link EnsembleResult}. A utility for callers\n * writing code generic over the strategy.\n */\nexport type ResultFor<S extends StrategyName> = Extract<\n CombineResult,\n { strategy: S }\n>;\n\n/**\n * A progress event emitted while a combine runs. For `consensus`, `phase` marks\n * a phase boundary and `draft`/`critique` fire as each participant's call settles\n * (in completion order, which may differ from participant order). For `pipeline`,\n * a `stage` event fires as each stage settles (in conveyor order). For `ensemble`\n * and `broadcast`, a `response` event fires as each participant settles (in\n * completion order, which may differ from participant order). The final answer is\n * the resolved {@link CombineResult}, so there is no terminal event.\n */\nexport type CombineEvent =\n | { type: \"phase\"; phase: \"drafting\" | \"critiquing\" | \"synthesizing\" }\n | {\n type: \"draft\";\n id: string;\n provider: ProviderName;\n status: \"ok\" | \"failed\";\n }\n | {\n type: \"critique\";\n id: string;\n provider: ProviderName;\n status: \"ok\" | \"failed\";\n }\n | {\n /** A `pipeline` stage settled. `index` is its 0-based position in the conveyor. */\n type: \"stage\";\n id: string;\n provider: ProviderName;\n status: \"ok\" | \"failed\";\n index: number;\n }\n | {\n /** A participant settled in an `ensemble` or `broadcast` run. */\n type: \"response\";\n id: string;\n provider: ProviderName;\n status: \"ok\" | \"failed\";\n };\n\nexport type CombineOptions = {\n /**\n * Called with progress events as the combine runs. Errors thrown from the\n * handler are swallowed so a progress listener can never break the run.\n */\n onEvent?: (event: CombineEvent) => void;\n};\n","/**\n * Helpers shared by more than one combine strategy. A helper lives here only\n * once a second strategy actually reuses it (the 2–3x rule); strategy-private\n * helpers stay in that strategy's own file.\n */\n\nimport {\n type CombineEvent,\n type CombineRequest,\n type CombineUsage,\n type ParticipantOutcome,\n} from \"./index\";\nimport { aggregateError } from \"../errors\";\nimport { type ProviderName } from \"../registry\";\nimport {\n type CompletionRequest,\n type CompletionResult,\n type ContentPart,\n type Message,\n type Provider,\n type TextPart,\n type Usage,\n} from \"../types\";\n\n/**\n * A participant, kept with its resolved provider for the orchestration phases.\n * `id` is its unique label (surfaced in results/events); `providerName` is the\n * actual provider it runs on; `model`/`maxTokens` are its optional per-participant\n * overrides (applied by {@link completionFor}, falling back to the request's).\n */\nexport type RosterEntry = {\n id: string;\n providerName: ProviderName;\n provider: Provider;\n model?: string;\n maxTokens?: number;\n};\n\n/**\n * The per-participant request overrides {@link completionFor} applies on top of\n * the request-wide values. A {@link RosterEntry} (or `Survivor`/`Running.entry`)\n * is structurally a valid value, so callers pass the entry directly.\n */\nexport type ParticipantOverrides = Pick<RosterEntry, \"model\" | \"maxTokens\">;\n\n/**\n * Wrap an optional progress callback into an `emit` that swallows handler errors\n * — a progress listener must never break the run. Returns a no-op-safe emitter\n * whether or not `onEvent` was supplied.\n */\nexport function makeEmitter(\n onEvent?: (event: CombineEvent) => void,\n): (event: CombineEvent) => void {\n return (event) => {\n try {\n onEvent?.(event);\n } catch {\n // A progress listener must not break the run.\n }\n };\n}\n\n/**\n * Second pass over a user-facing answer. Prompt instructions in the generating\n * step alone don't reliably stop a model from narrating the process (\"synthesizes\n * the drafts\", \"I improved the previous answer\", \"Answer A\"), so this rewrite\n * strips that meta-commentary. It sees only the answer text — never the inputs or\n * the fact that there were several — so it has nothing to narrate.\n */\nconst SANITIZE_FRAMING =\n \"Rewrite the following answer so it reads as a single, self-contained reply \" +\n \"addressed directly to the user. Remove any meta-commentary about how it was \" +\n \"produced — any reference to other answers, drafts, candidates, sources, \" +\n 'reviewers, or a synthesis or selection process (for example \"this answer ' +\n 'synthesizes the drafts\", \"among the candidates\", or \"Answer A\"). Preserve the ' +\n \"substance, wording, and length as much as possible; change only what is \" +\n \"needed. Output only the rewritten answer, with no preamble.\";\n\n/**\n * Build a per-phase completion request, carrying over the caller's\n * model/maxTokens/signal. A participant's per-participant `overrides` take\n * precedence over the request-wide `model`/`maxTokens` (which act as the fallback).\n */\nexport function completionFor(\n request: CombineRequest,\n system: string | undefined,\n messages: Message[],\n overrides?: ParticipantOverrides,\n): CompletionRequest {\n const completion: CompletionRequest = { messages };\n if (system !== undefined) {\n completion.system = system;\n }\n const model = overrides?.model ?? request.model;\n if (model !== undefined) {\n completion.model = model;\n }\n const maxTokens = overrides?.maxTokens ?? request.maxTokens;\n if (maxTokens !== undefined) {\n completion.maxTokens = maxTokens;\n }\n // Carry the abort signal into every phase so one signal cancels the whole\n // combine (aborting all in-flight provider calls at once).\n if (request.signal !== undefined) {\n completion.signal = request.signal;\n }\n // Carry the response schema through (used by the ensemble strategy, where every\n // participant answers under the same schema; consensus/pipeline reject it at the\n // registry, so it's only ever set here for ensemble).\n if (request.responseFormat !== undefined) {\n completion.responseFormat = request.responseFormat;\n }\n return completion;\n}\n\n/** Prepend the caller's system prompt (if any) to a phase's framing instruction. */\nexport function composeSystem(\n userSystem: string | undefined,\n framing: string,\n): string {\n return userSystem === undefined ? framing : `${userSystem}\\n\\n${framing}`;\n}\n\n/** Run one participant's completion, capturing success or failure as an outcome. */\nexport async function runOutcome(\n id: string,\n provider: ProviderName,\n run: () => Promise<CompletionResult>,\n): Promise<ParticipantOutcome> {\n try {\n return { id, provider, status: \"ok\", result: await run() };\n } catch (error) {\n return {\n id,\n provider,\n status: \"failed\",\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n}\n\n/**\n * Run every participant against the **verbatim** prompt (the caller's own\n * `system` + `messages`, with no shaped framing) in parallel, capturing each as a\n * {@link ParticipantOutcome} and emitting a `response` event as it settles. Shared\n * by the fan-out strategies (`ensemble`, `broadcast`); each strategy keeps its own\n * accept/throw policy on the returned outcomes. Per-participant model/maxTokens\n * overrides and the abort `signal` thread through {@link completionFor}.\n */\nexport async function respondAll(\n roster: RosterEntry[],\n request: CombineRequest,\n emit: (event: CombineEvent) => void,\n): Promise<ParticipantOutcome[]> {\n return Promise.all(\n roster.map(async (entry) => {\n const outcome = await runOutcome(entry.id, entry.providerName, () =>\n entry.provider.complete(\n completionFor(request, request.system, request.messages, entry),\n ),\n );\n emit({\n type: \"response\",\n id: entry.id,\n provider: entry.providerName,\n status: outcome.status,\n });\n return outcome;\n }),\n );\n}\n\n/**\n * Build the error a strategy throws when no participant produced a usable result.\n * The combine-specific adapter over {@link aggregateError}: it collects the failed\n * participants' own errors (each a `ProviderError` with status/kind/abort cause)\n * so the thrown error carries them as `.errors` when any participant failed, and\n * degrades to a plain `Error` when every participant succeeded but none was usable\n * (e.g. all empty or non-object). The `message` is preserved either way, so\n * existing `toThrow(...)` assertions still pass.\n */\nexport function noResultError(\n message: string,\n outcomes: ParticipantOutcome[],\n): Error {\n return aggregateError(\n message,\n outcomes.flatMap((o) => (o.status === \"failed\" ? [o.error] : [])),\n );\n}\n\n/**\n * Rewrite a user-facing answer to remove process narration (see\n * {@link SANITIZE_FRAMING}). On failure or empty output, returns the original\n * answer unchanged — a working (if slightly leaky) answer beats no answer.\n */\nexport async function sanitizeAnswer(\n provider: Provider,\n request: CombineRequest,\n answer: string,\n overrides?: ParticipantOverrides,\n): Promise<{ text: string; usage?: Usage }> {\n try {\n const result = await provider.complete(\n completionFor(\n request,\n composeSystem(request.system, SANITIZE_FRAMING),\n [{ role: \"user\", content: answer }],\n overrides,\n ),\n );\n // The call was billed whether or not we keep its output, so report its usage.\n return {\n text: result.text.trim() === \"\" ? answer : result.text,\n usage: result.usage,\n };\n } catch {\n return { text: answer };\n }\n}\n\n/** A single model call's token usage, attributed (by id) to the participant that made it. */\nexport type UsageEntry = { id: string; usage?: Usage };\n\n/** Map per-participant outcomes to usage entries (a failed outcome has no usage). */\nexport function outcomeUsage(outcomes: ParticipantOutcome[]): UsageEntry[] {\n return outcomes.map((o) => ({\n id: o.id,\n usage: o.status === \"ok\" ? o.result.usage : undefined,\n }));\n}\n\n/**\n * Sum per-call usages into a {@link CombineUsage} (overall total + per-participant\n * breakdown). Entries with no usage are ignored; returns `undefined` if no call\n * reported any usage at all.\n */\nexport function aggregateUsage(\n entries: UsageEntry[],\n): CombineUsage | undefined {\n const byParticipant: Partial<Record<string, Usage>> = {};\n const total: Usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n for (const { id, usage } of entries) {\n if (usage === undefined) {\n continue;\n }\n total.inputTokens += usage.inputTokens;\n total.outputTokens += usage.outputTokens;\n total.totalTokens += usage.totalTokens;\n const acc = byParticipant[id];\n byParticipant[id] = {\n inputTokens: (acc?.inputTokens ?? 0) + usage.inputTokens,\n outputTokens: (acc?.outputTokens ?? 0) + usage.outputTokens,\n totalTokens: (acc?.totalTokens ?? 0) + usage.totalTokens,\n };\n }\n // byParticipant is non-empty iff at least one entry carried usage.\n return Object.keys(byParticipant).length === 0\n ? undefined\n : { total, byParticipant };\n}\n\n/**\n * Extract the plain text from a message's content: a `string` is returned as-is;\n * a `ContentPart[]` has its text parts concatenated. (Combine renders prompts as\n * text, so non-text parts don't propagate through the phases — a known limit.)\n */\nfunction textOf(content: string | ContentPart[]): string {\n return typeof content === \"string\"\n ? content\n : content\n .filter((part): part is TextPart => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\");\n}\n\n/** Render the original messages as the \"question\" block for later phases. */\nexport function renderConversation(messages: Message[]): string {\n if (messages.length === 1) {\n return textOf(messages[0]?.content ?? \"\");\n }\n return messages\n .map(\n (m) =>\n `${m.role === \"user\" ? \"User\" : \"Assistant\"}: ${textOf(m.content)}`,\n )\n .join(\"\\n\\n\");\n}\n","/**\n * The **broadcast** combine strategy: fan one prompt out to every participant in\n * parallel and return *all* of their raw answers — no cooperation, no critique,\n * no synthesis, no vote. This is the simplest strategy: where consensus/pipeline/\n * ensemble combine the participants' work into one answer, broadcast deliberately\n * does not combine at all. Use it to compare models side by side, or to drive your\n * own selection/UI over the raw outputs.\n *\n * Each participant answers the user's prompt *verbatim* (no shaped framing — the\n * point is the unmodified per-model answer). Builds only on the {@link Provider}\n * contract (`complete()`), so it needs no provider-specific code and is\n * unit-testable with fake providers. Structured output is out of scope (the\n * registry rejects `responseFormat` for this strategy), as is any merge.\n */\n\nimport {\n type BroadcastResult,\n type CombineEvent,\n type CombineRequest,\n} from \"./index\";\nimport {\n aggregateUsage,\n makeEmitter,\n noResultError,\n outcomeUsage,\n respondAll,\n type RosterEntry,\n} from \"./shared\";\n\n/**\n * Run the broadcast strategy. `roster` lists the resolved participants. `onEvent`,\n * if given, receives a `response` event as each participant settles. Internal —\n * exposed to consumers only through {@link ProviderRegistry.combine}.\n */\nexport async function broadcast(\n roster: RosterEntry[],\n request: CombineRequest,\n onEvent?: (event: CombineEvent) => void,\n): Promise<BroadcastResult> {\n const emit = makeEmitter(onEvent);\n\n // Every participant answers the same prompt, verbatim, in parallel.\n const responses = await respondAll(roster, request, emit);\n\n // Broadcast returns whatever each model gave back, so a successful call counts\n // even if its text is empty — unlike consensus/pipeline, which drop empty\n // answers because an empty draft can't advance or satisfy minParticipants.\n // Only an all-failed run has nothing to return.\n if (!responses.some((o) => o.status === \"ok\")) {\n throw noResultError(\n \"Broadcast failed: no participant returned a response.\",\n responses,\n );\n }\n\n return {\n strategy: \"broadcast\",\n responses,\n usage: aggregateUsage(outcomeUsage(responses)),\n };\n}\n","/**\n * The **consensus** combine strategy: every participant drafts an answer in\n * parallel, then every participant critiques all drafts, then one designated\n * participant synthesizes the final answer.\n *\n * Builds only on the provider-agnostic {@link Provider} contract — each phase is\n * a `complete()` call with a shaped `system` + message — so it needs no\n * provider-specific code and is trivially unit-testable with fake providers.\n */\n\nimport {\n type CombineEvent,\n type CombineRequest,\n type ConsensusResult,\n type ParticipantOutcome,\n} from \"./index\";\nimport {\n aggregateUsage,\n composeSystem,\n completionFor,\n makeEmitter,\n noResultError,\n outcomeUsage,\n renderConversation,\n type RosterEntry,\n runOutcome,\n sanitizeAnswer,\n type UsageEntry,\n} from \"./shared\";\nimport { type CompletionResult } from \"../types\";\n\n/**\n * Prepended to the draft and critique phases — the messages that travel from one\n * AI to another. It strips ceremony (greetings/sign-offs/preamble) to save\n * tokens but deliberately KEEPS reasoning: those phases feed other AIs that need\n * the \"why\" to critique it, not an end user. The user-facing synthesis omits this.\n */\nconst CONCISE_DIRECTIVE =\n \"Skip greetings, sign-offs, and preamble — begin directly with the content. \" +\n \"Include your reasoning, assumptions, and any caveats; your reply is read by \" +\n \"other AI assistants, not an end user, so favor complete substance over \" +\n \"brevity of style.\";\n\nconst CRITIQUE_FRAMING =\n \"You are one of several AI assistants that independently answered the same \" +\n \"question. Below are all the drafts. Critically evaluate them: \" +\n \"point out errors, gaps, and risks in each, and scrutinize the reasoning, \" +\n \"not just the conclusions. Judge every answer on its merits regardless of \" +\n \"which assistant wrote it, including any you may have written yourself; refer \" +\n \"to answers by their heading. Do not write the final answer yet — produce \" +\n \"only a critique, then end with exactly three lines:\\n\" +\n \"BEST: <heading of the strongest answer>\\n\" +\n \"KEY FIX: <the single most important improvement to it>\\n\" +\n \"CONFIDENCE: <low | medium | high>\";\n\nconst SYNTH_FRAMING =\n \"You are the lead assistant writing the final answer to the user's question \" +\n \"below. You are given several draft answers from other assistants, plus their \" +\n \"critiques (each ending with that critic's pick and most important fix), as \" +\n \"private input material — the user has not seen any of it and must not learn \" +\n \"it exists. Use it to produce the most correct answer. Prefer correctness \" +\n \"over popularity: a single correct draft beats a wrong majority, so adopt it \" +\n \"and do not average conflicting claims; blend points only when they are \" +\n \"genuinely complementary, not contradictory; if the material is inconclusive, \" +\n \"say so plainly rather than papering over it. Judge every draft on its merits \" +\n \"regardless of source — one may be your own, which you must not favor. Write \" +\n \"ONLY the answer itself, addressed to the user as if answering for the first \" +\n \"time. Do not mention or allude to this material, the other assistants, the \" +\n \"drafting or critique process, or the existence of multiple answers, and do \" +\n 'not use words like \"candidates\", \"the drafts\", or \"the options\" or labels ' +\n 'like \"Answer A\"/\"Answer B\".';\n\nconst LETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n/** A participant whose draft succeeded, kept with its roster entry for later phases. */\ntype Survivor = RosterEntry & {\n result: CompletionResult;\n};\n\n/**\n * Run the consensus strategy. `roster` lists the resolved participants;\n * `synthesizer` names which of them writes the final answer (it falls back to\n * other survivors if that one is unavailable). `onEvent`, if given, receives\n * progress events. Internal — exposed to consumers only through\n * {@link ProviderRegistry.combine}.\n */\nexport async function consensus(\n roster: RosterEntry[],\n synthesizer: string,\n request: CombineRequest,\n onEvent?: (event: CombineEvent) => void,\n): Promise<ConsensusResult> {\n const anonymized = (request.attribution ?? \"anonymized\") === \"anonymized\";\n const minParticipants = request.minParticipants ?? 2;\n const emit = makeEmitter(onEvent);\n\n // ── Phase 1: drafts (parallel fan-out) ──\n emit({ type: \"phase\", phase: \"drafting\" });\n const draftSystem = composeSystem(request.system, CONCISE_DIRECTIVE);\n const draftResults = await Promise.all(\n roster.map(async (entry) => {\n const outcome = await runOutcome(entry.id, entry.providerName, () =>\n entry.provider.complete(\n completionFor(request, draftSystem, request.messages, entry),\n ),\n );\n emit({\n type: \"draft\",\n id: entry.id,\n provider: entry.providerName,\n status: outcome.status,\n });\n return { entry, outcome };\n }),\n );\n const drafts: ParticipantOutcome[] = draftResults.map((d) => d.outcome);\n\n // Keep only drafts that succeeded AND produced non-empty text: an empty draft\n // (e.g. Gemini spending its whole budget on thinking) would otherwise count\n // toward minParticipants and render as a blank `### Answer A` into the critique\n // prompts — wasted tokens and degraded consensus. Mirrors the synthesis guard.\n const survivors: Survivor[] = draftResults.flatMap((d) =>\n d.outcome.status === \"ok\" && d.outcome.result.text.trim() !== \"\"\n ? [{ ...d.entry, result: d.outcome.result }]\n : [],\n );\n\n const [firstSurvivor] = survivors;\n if (firstSurvivor === undefined) {\n throw noResultError(\n \"Consensus failed: no participant produced a draft.\",\n drafts,\n );\n }\n // A single-provider combine is just that provider answering.\n if (roster.length === 1) {\n return {\n text: firstSurvivor.result.text,\n strategy: \"consensus\",\n synthesizer: firstSurvivor.id,\n model: firstSurvivor.result.model,\n drafts,\n critiques: [],\n usage: aggregateUsage(outcomeUsage(drafts)),\n };\n }\n if (survivors.length < minParticipants) {\n throw noResultError(\n `Consensus failed: only ${String(survivors.length)} of ` +\n `${String(roster.length)} participants produced a draft ` +\n `(minimum ${String(minParticipants)}).`,\n drafts,\n );\n }\n\n // ── Phase 2: critiques (parallel fan-out over survivors) ──\n emit({ type: \"phase\", phase: \"critiquing\" });\n const answersBlock = renderAnswers(survivors, anonymized);\n const question = renderConversation(request.messages);\n const critiqueBody = `## Original question\\n${question}\\n\\n## Drafts\\n${answersBlock}`;\n const critiqueSystem = composeSystem(\n request.system,\n `${CONCISE_DIRECTIVE}\\n\\n${CRITIQUE_FRAMING}`,\n );\n const critiques: ParticipantOutcome[] = await Promise.all(\n survivors.map(async (s) => {\n const outcome = await runOutcome(s.id, s.providerName, () =>\n s.provider.complete(\n completionFor(\n request,\n critiqueSystem,\n [{ role: \"user\", content: critiqueBody }],\n s,\n ),\n ),\n );\n emit({\n type: \"critique\",\n id: s.id,\n provider: s.providerName,\n status: outcome.status,\n });\n return outcome;\n }),\n );\n // ── Phase 3: synthesis (single call, one fallback hop per remaining survivor) ──\n emit({ type: \"phase\", phase: \"synthesizing\" });\n const critiquesRendered = renderCritiques(critiques, anonymized);\n const critiquesBlock =\n critiquesRendered === \"\" ? \"\" : `\\n\\n## Critiques\\n${critiquesRendered}`;\n const synthBody = `${critiqueBody}${critiquesBlock}`;\n const synthSystem = composeSystem(request.system, SYNTH_FRAMING);\n\n let lastError: Error | undefined;\n // Usage from synthesis attempts that were billed but discarded (an empty\n // synthesis that fell back to the next survivor) — counted so the reported\n // cost reflects every call made, not just the winning one.\n const synthUsage: UsageEntry[] = [];\n for (const candidate of synthesizerOrder(survivors, synthesizer)) {\n try {\n const result = await candidate.provider.complete(\n completionFor(\n request,\n synthSystem,\n [{ role: \"user\", content: synthBody }],\n candidate,\n ),\n );\n synthUsage.push({ id: candidate.id, usage: result.usage });\n // A resolved-but-empty synthesis (e.g. Gemini consuming the whole token\n // budget on thinking) is treated as a failure so the next survivor is tried.\n if (result.text.trim() === \"\") {\n lastError = new Error(`${candidate.id} produced an empty synthesis`);\n continue;\n }\n // Second pass strips any process narration the synthesis framing\n // failed to suppress (e.g. \"synthesizes the drafts\", \"Answer A\").\n const sanitized = await sanitizeAnswer(\n candidate.provider,\n request,\n result.text,\n candidate,\n );\n synthUsage.push({ id: candidate.id, usage: sanitized.usage });\n return {\n text: sanitized.text,\n strategy: \"consensus\",\n synthesizer: candidate.id,\n model: result.model,\n drafts,\n critiques,\n usage: aggregateUsage([\n ...outcomeUsage(drafts),\n ...outcomeUsage(critiques),\n ...synthUsage,\n ]),\n };\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n }\n }\n throw new Error(\n `Consensus synthesis failed for all participants: ${lastError?.message ?? \"unknown error\"}`,\n );\n}\n\n/** The requested synthesizer first (if it survived), then the other survivors as fallbacks. */\nfunction synthesizerOrder(\n survivors: Survivor[],\n synthesizer: string,\n): Survivor[] {\n const requested = survivors.find((s) => s.id === synthesizer);\n const rest = survivors.filter((s) => s !== requested);\n return requested ? [requested, ...rest] : rest;\n}\n\nfunction renderAnswers(survivors: Survivor[], anonymized: boolean): string {\n return survivors\n .map((s, i) => {\n const label = anonymized\n ? `Answer ${LETTERS[i] ?? `#${String(i + 1)}`}`\n : `Answer from ${s.id}`;\n return `### ${label}\\n${s.result.text}`;\n })\n .join(\"\\n\\n\");\n}\n\n/**\n * Render critiques, labelled by each critic's position in the survivor order so\n * the letters line up with {@link renderAnswers} even when some critiques\n * failed (a failed critique is skipped, not re-lettered).\n */\nfunction renderCritiques(\n critiques: ParticipantOutcome[],\n anonymized: boolean,\n): string {\n const blocks: string[] = [];\n for (const [i, critique] of critiques.entries()) {\n if (critique.status !== \"ok\") {\n continue;\n }\n const label = anonymized\n ? `Critique ${LETTERS[i] ?? `#${String(i + 1)}`}`\n : `Critique from ${critique.id}`;\n blocks.push(`### ${label}\\n${critique.result.text}`);\n }\n return blocks.join(\"\\n\\n\");\n}\n","/**\n * The **ensemble** combine strategy: every participant answers the prompt\n * independently under the *same* JSON Schema (`request.responseFormat`), then the\n * resulting typed objects are merged **mechanically** — no LLM synthesis. This is\n * the multi-model differentiator: where consensus has a model adjudicate prose,\n * ensemble does a deterministic field-wise vote over structured output and reports\n * how strongly the models agreed, a confidence signal a single model can't give.\n *\n * Merge policy (field-wise over the union of top-level keys):\n * - every field → **majority vote**: the most common value by deep equality,\n * ties broken by participant order. The merged value is therefore always a\n * value some model actually returned — never a synthesized/averaged one — so it\n * stays within the schema's types and the agreement score below describes the\n * exact value you get back.\n * - per-field **agreement** = the fraction of the valid responses that agreed on\n * the merged value. The denominator is *all* the merged responses (not just the\n * ones that returned the field), so a field most models omitted scores low —\n * honest confidence rather than an inflated one.\n *\n * Builds only on the {@link Provider} contract (`complete()` with the schema) so\n * it needs no provider-specific code; unit-testable with fake providers. The\n * registry requires `responseFormat` for this strategy and rejects it for the\n * others, so by the time this runs `request.responseFormat` is set.\n */\n\nimport {\n type CombineEvent,\n type CombineRequest,\n type EnsembleAgreement,\n type EnsembleResult,\n} from \"./index\";\nimport {\n aggregateUsage,\n makeEmitter,\n noResultError,\n outcomeUsage,\n respondAll,\n type RosterEntry,\n} from \"./shared\";\n\n/**\n * Run the ensemble strategy. `roster` lists the resolved participants. `onEvent`,\n * if given, receives a `response` event as each participant settles. Internal —\n * exposed to consumers only through {@link ProviderRegistry.combine}.\n */\nexport async function ensemble(\n roster: RosterEntry[],\n request: CombineRequest,\n onEvent?: (event: CombineEvent) => void,\n): Promise<EnsembleResult> {\n const emit = makeEmitter(onEvent);\n\n // Every participant answers the same prompt under the same schema, in parallel.\n // completionFor (inside respondAll) carries responseFormat through, so each\n // provider returns a parsed object on its result.\n const responses = await respondAll(roster, request, emit);\n\n // A response counts toward the merge only if it succeeded and parsed into a\n // plain object (the schema's shape); a failed call, an empty/invalid-JSON\n // answer (parsed undefined), or a non-object top-level value is dropped.\n // `isPlainObject` narrows `parsed` inside the `&&`, so no cast is needed.\n const objects = responses.flatMap((o) =>\n o.status === \"ok\" && isPlainObject(o.result.parsed)\n ? [o.result.parsed]\n : [],\n );\n\n if (objects.length === 0) {\n throw noResultError(\n \"Ensemble failed: no participant returned a valid structured object.\",\n responses,\n );\n }\n\n const { merged, agreement } = mergeObjects(objects);\n\n return {\n text: JSON.stringify(merged),\n strategy: \"ensemble\",\n merged,\n agreement,\n responses,\n usage: aggregateUsage(outcomeUsage(responses)),\n };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Merge the participant objects field-wise and compute the agreement scores. */\nfunction mergeObjects(objects: Array<Record<string, unknown>>): {\n merged: Record<string, unknown>;\n agreement: EnsembleAgreement;\n} {\n // Group each field's values in one pass. A Map preserves first-seen key order\n // (so the merged object's shape is stable) and per-key participant order (so\n // mergeField's first-seen tie-break is honored).\n const byKey = new Map<string, unknown[]>();\n for (const object of objects) {\n for (const [key, value] of Object.entries(object)) {\n const values = byKey.get(key);\n if (values === undefined) {\n byKey.set(key, [value]);\n } else {\n values.push(value);\n }\n }\n }\n\n const merged: Record<string, unknown> = {};\n const byField: Record<string, number> = {};\n for (const [key, values] of byKey) {\n // Denominator is the total number of merged responses, not just the ones\n // that returned this field, so a field most models omitted scores low.\n const field = mergeField(values, objects.length);\n merged[key] = field.value;\n byField[key] = field.agreement;\n }\n\n const scores = Object.values(byField);\n const overall =\n scores.length === 0 ? 1 : scores.reduce((a, b) => a + b, 0) / scores.length;\n return { merged, agreement: { overall, byField } };\n}\n\n/**\n * Merge one field by majority vote: the most common value (deep equality via\n * {@link stableKey}, first-seen wins ties). The merged value is always one a model\n * actually returned. `agreement` is the share of all `total` responses that voted\n * for it. `values` (the values present for this field) is non-empty — only fields\n * in at least one object reach here.\n */\nfunction mergeField(\n values: unknown[],\n total: number,\n): { value: unknown; agreement: number } {\n const counts = new Map<string, number>();\n let mode: unknown = values[0];\n let maxCount = 0;\n for (const value of values) {\n const key = stableKey(value);\n const count = (counts.get(key) ?? 0) + 1;\n counts.set(key, count);\n // Strict `>` means the first value to reach a given count keeps the lead, so\n // ties are broken by first-seen (participant) order.\n if (count > maxCount) {\n maxCount = count;\n mode = value;\n }\n }\n return { value: mode, agreement: maxCount / total };\n}\n\n/**\n * A deep-equality key for tallying values. Object keys are sorted recursively so\n * that two models emitting the same object with different key order count as\n * agreeing. (JSON values can't be `undefined`, so `JSON.stringify` is total here.)\n */\nfunction stableKey(value: unknown): string {\n return JSON.stringify(value, (_key, val: unknown) => {\n if (!isPlainObject(val)) {\n return val;\n }\n // eslint-disable-next-line unicorn/no-array-sort -- toSorted() needs ES2023; the lib target is ES2022.\n const sortedKeys = Object.keys(val).sort();\n return Object.fromEntries(sortedKeys.map((key) => [key, val[key]]));\n });\n}\n","/**\n * The **pipeline** combine strategy: a conveyor belt of providers that refine\n * one answer in sequence. The first participant writes an initial answer; each\n * later participant receives the question plus the current running answer and\n * improves it; the last stage to produce an answer wins.\n *\n * Builds only on the provider-agnostic {@link Provider} contract — each stage is\n * a `complete()` call with a shaped `system` + message — so it needs no\n * provider-specific code and is trivially unit-testable with fake providers.\n *\n * Unlike consensus there is no separate synthesizer and no critique round, so a\n * weak refiner's regression is permanent; the refine framing therefore treats\n * the current answer as a strong baseline to preserve. `synthesizer`,\n * `attribution`, and `minParticipants` from the request are consensus-specific\n * and ignored here.\n */\n\nimport {\n type CombineEvent,\n type CombineRequest,\n type ParticipantOutcome,\n type PipelineResult,\n} from \"./index\";\nimport {\n aggregateUsage,\n composeSystem,\n completionFor,\n makeEmitter,\n noResultError,\n outcomeUsage,\n renderConversation,\n type RosterEntry,\n runOutcome,\n sanitizeAnswer,\n} from \"./shared\";\n\n/**\n * The first stage has no prior answer to build on, so it just writes the best\n * standalone answer. Kept answer-shaped (not reasoning-shaped) because its output\n * is fed to the next stage as the answer to improve, not as notes to critique.\n */\nconst PIPELINE_FIRST_FRAMING =\n \"You are the first stage in a pipeline of AI assistants answering the user's \" +\n \"question below. Write the best, most complete and correct answer you can. \" +\n \"Output only the answer itself, addressed to the user — no preamble and no \" +\n \"notes about your process.\";\n\n/**\n * Refining stages see the question and the current answer. The preservation /\n * ratchet wording is deliberate: there is no downstream synthesizer to catch a\n * regression, so a refiner must improve the answer or leave it alone, never\n * rewrite it worse. The \"do not mention the earlier answer\" clause keeps process\n * narration out of what is ultimately the user-facing answer.\n */\nconst PIPELINE_REFINE_FRAMING =\n \"You are one stage in a pipeline of AI assistants improving an answer to the \" +\n \"user's question. Below are the question and the current answer from an \" +\n \"earlier stage. Treat the current answer as a strong baseline: revise the \" +\n \"current answer only to improve its correctness and completeness — fix errors, \" +\n \"fill genuine gaps, and sharpen unclear wording. Preserve everything that is \" +\n \"already correct and keep its substance and length; do not drop correct \" +\n \"content or rewrite it merely to sound different. If you cannot improve it, \" +\n \"return it unchanged. Output only the improved answer, addressed to the user \" +\n \"as if answering for the first time — do not mention the earlier answer, the \" +\n \"revision, or that multiple assistants were involved.\";\n\n/** The running answer carried from one stage to the next (its producing stage + its output). */\ntype Running = {\n /** The roster entry (id/provider/overrides) of the stage that produced this answer. */\n entry: RosterEntry;\n text: string;\n /** The model that actually produced this answer (the stage's `result.model`). */\n model: string;\n /**\n * Whether this answer may carry process narration and so needs the sanitizing\n * pass: true once a refining stage actually rewrote the text. A first-stage\n * answer (no prior context) and a verbatim passthrough (a refiner that left\n * the text unchanged) inherit the provenance of what they built on.\n */\n needsSanitize: boolean;\n};\n\n/**\n * Run the pipeline strategy. `roster` lists the resolved participants in\n * conveyor order. `onEvent`, if given, receives a `stage` event as each stage\n * settles. Internal — exposed to consumers only through\n * {@link ProviderRegistry.combine}.\n */\nexport async function pipeline(\n roster: RosterEntry[],\n request: CombineRequest,\n onEvent?: (event: CombineEvent) => void,\n): Promise<PipelineResult> {\n const emit = makeEmitter(onEvent);\n\n const question = renderConversation(request.messages);\n const firstSystem = composeSystem(request.system, PIPELINE_FIRST_FRAMING);\n const refineSystem = composeSystem(request.system, PIPELINE_REFINE_FRAMING);\n\n const stages: ParticipantOutcome[] = [];\n let current: Running | undefined;\n\n for (const [index, entry] of roster.entries()) {\n // The first stage that has a running answer to build on refines; a leading\n // run of failed stages each start fresh until one produces an answer.\n const completion =\n current === undefined\n ? completionFor(request, firstSystem, request.messages, entry)\n : completionFor(\n request,\n refineSystem,\n [\n {\n role: \"user\",\n content: `## Question\\n${question}\\n\\n## Current answer\\n${current.text}`,\n },\n ],\n entry,\n );\n\n const outcome = await runOutcome(entry.id, entry.providerName, () =>\n entry.provider.complete(completion),\n );\n stages.push(outcome);\n emit({\n type: \"stage\",\n id: entry.id,\n provider: entry.providerName,\n status: outcome.status,\n index,\n });\n\n // A stage advances the running answer only if it produced non-empty text;\n // otherwise the previous answer carries forward unchanged.\n if (outcome.status === \"ok\" && outcome.result.text.trim() !== \"\") {\n const text = outcome.result.text;\n // A refining stage that actually changed the text may have narrated the\n // revision; a verbatim passthrough (or the first stage) inherits the\n // sanitize-need of the answer it built on, so a no-op refiner doesn't\n // trigger a wasted sanitizing call. `current` here is still the prior answer.\n const needsSanitize =\n current !== undefined &&\n (text !== current.text || current.needsSanitize);\n current = { entry, text, model: outcome.result.model, needsSanitize };\n }\n }\n\n if (current === undefined) {\n throw noResultError(\n \"Pipeline failed: no participant produced an answer.\",\n stages,\n );\n }\n\n // Strip any process narration a refining stage may have leaked. Skipped when\n // the answer needs no sanitizing (a lone first-stage answer, or an unchanged\n // passthrough), so the extra model call only runs when it can matter.\n const sanitized = current.needsSanitize\n ? await sanitizeAnswer(\n current.entry.provider,\n request,\n current.text,\n current.entry,\n )\n : { text: current.text };\n\n return {\n text: sanitized.text,\n strategy: \"pipeline\",\n finalParticipant: current.entry.id,\n model: current.model,\n stages,\n usage: aggregateUsage([\n ...outcomeUsage(stages),\n { id: current.entry.id, usage: sanitized.usage },\n ]),\n };\n}\n","/**\n * Shared helpers for reading fields off a provider's response body.\n */\n\n/** Whether a value is a non-null object — the shared guard for parsing JSON bodies. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * The model name a provider reports on its response, falling back to the\n * requested model when absent or non-string. The field differs by provider\n * (Anthropic and OpenAI use `model`, Gemini uses `modelVersion`), so it's a\n * parameter that defaults to `\"model\"`.\n */\nexport function extractModel(\n data: unknown,\n fallback: string,\n field = \"model\",\n): string {\n if (isRecord(data)) {\n const value = data[field];\n if (typeof value === \"string\") {\n return value;\n }\n }\n return fallback;\n}\n","/**\n * Server-Sent Events parsing shared by the providers' streaming paths.\n */\n\nimport { isRecord } from \"./extract\";\n\n/** Returned by {@link classifyLine} for the end-of-stream sentinel some providers send. */\nconst DONE = Symbol(\"sse-done\");\n\n/**\n * Read an SSE response body and yield each `data:` line's parsed JSON object, in\n * order. Blank lines, non-`data:` lines, and any payload that isn't a JSON object\n * are skipped; the `[DONE]` sentinel ends the stream (so a server that holds the\n * connection open past it doesn't hang the consumer). The reader is always\n * released — on normal completion, the `[DONE]` sentinel, an early `return` from\n * the consumer, or a throw.\n *\n * Each event these providers send is a single `data:` line, so multi-line `data:`\n * field concatenation (which the SSE spec allows) is intentionally not\n * implemented — none of the target APIs use it.\n */\nexport async function* sseJson(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<Record<string, unknown>, void, void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n for (\n let result = await reader.read();\n !result.done;\n result = await reader.read()\n ) {\n buffer += decoder.decode(result.value, { stream: true });\n const lines = buffer.split(\"\\n\");\n // The last segment is the line after the final newline — still incomplete,\n // so hold it for the next chunk.\n buffer = lines.pop() ?? \"\";\n for (const line of lines) {\n const event = classifyLine(line);\n if (event === DONE) {\n return;\n }\n if (event !== undefined) {\n yield event;\n }\n }\n }\n\n // Flush a final line the stream may have left without a trailing newline.\n const event = classifyLine(buffer);\n if (event !== undefined && event !== DONE) {\n yield event;\n }\n } finally {\n await reader.cancel();\n }\n}\n\n/**\n * Classify one SSE line: the parsed JSON object of its `data:` payload, the\n * {@link DONE} sentinel, or `undefined` to skip (blank/non-`data:`/non-JSON-object).\n */\nfunction classifyLine(\n rawLine: string,\n): Record<string, unknown> | typeof DONE | undefined {\n const line = rawLine.trim();\n if (!line.startsWith(\"data:\")) {\n return undefined;\n }\n const payload = line.slice(\"data:\".length).trim();\n if (payload === \"\") {\n return undefined;\n }\n if (payload === \"[DONE]\") {\n return DONE;\n }\n try {\n const parsed: unknown = JSON.parse(payload);\n return isRecord(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n","/**\n * Shared structured-output parsing, used by every provider.\n */\n\nimport { type CompletionRequest } from \"../types\";\n\n/**\n * Parse the structured-output JSON when a `responseFormat` was requested. Returns\n * `undefined` when no schema was asked for or the text wasn't valid JSON (e.g.\n * truncated at the token cap) — the raw text is still returned on\n * `CompletionResult.text`. Provider-agnostic: the model returns the JSON in the\n * response text regardless of which native mechanism produced it.\n */\nexport function parseStructured(\n request: CompletionRequest,\n text: string,\n): unknown {\n if (request.responseFormat === undefined) {\n return undefined;\n }\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n","/**\n * HTTP transport for the providers: a `fetch` wrapper that turns network\n * failures into typed errors, plus bounded retry/backoff on routine retryable\n * statuses. The error *vocabulary* (`ProviderError`, `apiError`) lives in\n * `./errors`; this module is about how a request is made.\n */\n\nimport { ProviderError } from \"./errors\";\nimport { type ProviderName } from \"./registry\";\n\n/**\n * `fetch` over the global, translating a rejected request (network/DNS failure,\n * aborted signal) into a `transport` {@link ProviderError} so the caller always\n * gets provider context instead of a bare `TypeError`.\n */\nasync function providerFetch(\n provider: ProviderName,\n input: string,\n init: RequestInit,\n): Promise<Response> {\n try {\n return await fetch(input, init);\n } catch (cause) {\n const reason = cause instanceof Error ? cause.message : String(cause);\n throw new ProviderError(`${provider} request failed: ${reason}`, {\n provider,\n kind: \"transport\",\n cause,\n });\n }\n}\n\n/** Tuning for {@link requestWithRetry}'s bounded exponential backoff. */\nexport type RetryOptions = {\n /**\n * How many times to retry after the initial attempt on a retryable status\n * (429/503/529). `0` disables retry. Defaults to {@link DEFAULT_MAX_RETRIES}.\n */\n maxRetries?: number;\n /**\n * Base backoff in ms; the nth retry waits `baseDelayMs * 2 ** n` (capped at\n * {@link MAX_BACKOFF_MS}), unless the response carries a `Retry-After` header.\n * Defaults to {@link DEFAULT_BASE_DELAY_MS}.\n */\n baseDelayMs?: number;\n};\n\n/** Routine, retryable failures: rate limit, transient unavailable, Anthropic overloaded. */\nconst RETRYABLE_STATUSES = new Set([429, 503, 529]);\nconst DEFAULT_MAX_RETRIES = 2;\nconst DEFAULT_BASE_DELAY_MS = 500;\n/** Ceiling so a server-sent `Retry-After` or a high attempt count can't park us forever. */\nconst MAX_BACKOFF_MS = 60_000;\n\n/**\n * {@link providerFetch} with bounded exponential backoff on the retryable\n * statuses ({@link RETRYABLE_STATUSES}). Returns the first non-retryable\n * response (success or otherwise) for the caller to handle via `apiError`;\n * transport rejections propagate immediately (not retried). Honors the\n * response's `Retry-After` header when present; the wait is abortable via\n * `init.signal` (an abort during backoff lets the next attempt's `fetch` reject\n * into a transport {@link ProviderError}).\n */\nexport async function requestWithRetry(\n provider: ProviderName,\n input: string,\n init: RequestInit,\n retry?: RetryOptions,\n): Promise<Response> {\n const maxRetries = Math.max(0, retry?.maxRetries ?? DEFAULT_MAX_RETRIES);\n const baseDelayMs = retry?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;\n\n for (let attempt = 0; ; attempt++) {\n const response = await providerFetch(provider, input, init);\n if (\n response.ok ||\n !RETRYABLE_STATUSES.has(response.status) ||\n attempt >= maxRetries\n ) {\n return response;\n }\n const delayMs = retryDelayMs(response, attempt, baseDelayMs);\n // Free the connection — we won't read this error body before retrying.\n await response.body?.cancel();\n await sleep(delayMs, init.signal ?? undefined);\n }\n}\n\nfunction retryDelayMs(\n response: Response,\n attempt: number,\n baseDelayMs: number,\n): number {\n const retryAfter = parseRetryAfter(response.headers.get(\"retry-after\"));\n if (retryAfter !== undefined) {\n return Math.min(retryAfter, MAX_BACKOFF_MS);\n }\n return Math.min(baseDelayMs * 2 ** attempt, MAX_BACKOFF_MS);\n}\n\n/** `Retry-After` is either an integer count of seconds or an HTTP date. */\nfunction parseRetryAfter(value: string | null): number | undefined {\n if (value === null) {\n return undefined;\n }\n const trimmed = value.trim();\n if (trimmed === \"\") {\n return undefined;\n }\n const seconds = Number(trimmed);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * 1000);\n }\n const date = Date.parse(trimmed);\n if (Number.isNaN(date)) {\n return undefined;\n }\n return Math.max(0, date - Date.now());\n}\n\n/**\n * Resolve after `ms`, or early if `signal` aborts (the caller's next `fetch`\n * then rejects with the abort, producing a transport {@link ProviderError}).\n */\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve();\n return;\n }\n const onAbort = (): void => {\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * Anthropic (Claude) provider, talking to the Messages API directly over\n * `fetch` — no SDK dependency.\n */\n\nimport { apiError, apiErrorFromBody } from \"../errors\";\nimport { extractModel, isRecord } from \"./extract\";\nimport { sseJson } from \"./sse\";\nimport { parseStructured } from \"./structured\";\nimport { requestWithRetry, type RetryOptions } from \"../transport\";\nimport {\n type CompletionRequest,\n type CompletionResult,\n type ContentPart,\n type FinishReason,\n type MediaSource,\n type Message,\n type Provider,\n type Role,\n type ToolCall,\n type ToolChoice,\n type Usage,\n} from \"../types\";\n\nexport type AnthropicProviderOptions = {\n apiKey: string;\n /** Defaults to {@link DEFAULT_MODEL}. */\n model?: string;\n /** Defaults to `https://api.anthropic.com`. */\n baseUrl?: string;\n /** Bounded retry/backoff on 429/503/529. Defaults applied when omitted. */\n retry?: RetryOptions;\n};\n\nconst DEFAULT_MODEL = \"claude-opus-4-8\";\nconst DEFAULT_BASE_URL = \"https://api.anthropic.com\";\nconst ANTHROPIC_VERSION = \"2023-06-01\";\n\n/** Non-streaming default keeps responses under the SDK/HTTP timeout window. */\nconst DEFAULT_MAX_TOKENS = 16000;\n/** Streaming has no timeout concern, so give the model more room. */\nconst DEFAULT_STREAM_MAX_TOKENS = 64000;\n\nexport class AnthropicProvider implements Provider {\n readonly name = \"anthropic\";\n\n readonly #apiKey: string;\n readonly #model: string;\n readonly #baseUrl: string;\n readonly #retry?: RetryOptions;\n\n constructor(options: AnthropicProviderOptions) {\n this.#apiKey = options.apiKey;\n this.#model = options.model ?? DEFAULT_MODEL;\n this.#baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n this.#retry = options.retry;\n }\n\n async complete(request: CompletionRequest): Promise<CompletionResult> {\n const model = request.model ?? this.#model;\n const response = await requestWithRetry(\n \"anthropic\",\n `${this.#baseUrl}/v1/messages`,\n {\n method: \"POST\",\n headers: this.#headers(),\n body: JSON.stringify(\n this.#buildBody(request, model, DEFAULT_MAX_TOKENS, false),\n ),\n signal: request.signal,\n },\n this.#retry,\n );\n\n if (!response.ok) {\n throw await apiError(\"anthropic\", response);\n }\n\n const data: unknown = await response.json();\n if (isRecord(data) && isRecord(data.error)) {\n throw apiErrorFromBody(\"anthropic\", response.status, data);\n }\n const rawFinishReason = extractFinishReason(data);\n const text = extractText(data);\n return {\n text,\n model: extractModel(data, model),\n finishReason: normalizeFinishReason(rawFinishReason),\n rawFinishReason,\n refusal: extractRefusal(data),\n usage: extractUsage(data),\n parsed: parseStructured(request, text),\n toolCalls: extractToolCalls(data),\n };\n }\n\n async *stream(\n request: CompletionRequest,\n ): AsyncGenerator<string, void, void> {\n const model = request.model ?? this.#model;\n const response = await requestWithRetry(\n \"anthropic\",\n `${this.#baseUrl}/v1/messages`,\n {\n method: \"POST\",\n headers: this.#headers(),\n body: JSON.stringify(\n this.#buildBody(request, model, DEFAULT_STREAM_MAX_TOKENS, true),\n ),\n signal: request.signal,\n },\n this.#retry,\n );\n\n if (!response.ok) {\n throw await apiError(\"anthropic\", response);\n }\n if (!response.body) {\n throw new Error(\"Anthropic streaming response had no body\");\n }\n\n for await (const event of sseJson(response.body)) {\n if (event.type === \"message_stop\") {\n return;\n }\n if (event.type === \"error\") {\n throw new Error(`Anthropic stream error: ${JSON.stringify(event)}`);\n }\n if (event.type === \"content_block_delta\") {\n const delta = event.delta;\n if (\n isRecord(delta) &&\n delta.type === \"text_delta\" &&\n typeof delta.text === \"string\"\n ) {\n yield delta.text;\n }\n }\n }\n }\n\n #headers(): Record<string, string> {\n return {\n \"x-api-key\": this.#apiKey,\n \"anthropic-version\": ANTHROPIC_VERSION,\n \"content-type\": \"application/json\",\n };\n }\n\n #buildBody(\n request: CompletionRequest,\n model: string,\n defaultMaxTokens: number,\n stream: boolean,\n ): Record<string, unknown> {\n const body: Record<string, unknown> = {\n model,\n max_tokens: request.maxTokens ?? defaultMaxTokens,\n messages: request.messages.map((message) => toAnthropicMessage(message)),\n };\n if (request.system !== undefined) {\n body.system = request.system;\n }\n if (request.responseFormat !== undefined) {\n // Anthropic's native structured output: a top-level output_config.format\n // (no name/strict wrapper). The schema is passed through as-is.\n body.output_config = {\n format: { type: \"json_schema\", schema: request.responseFormat.schema },\n };\n }\n if (request.tools !== undefined) {\n body.tools = request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n input_schema: tool.parameters,\n }));\n }\n if (request.toolChoice !== undefined) {\n body.tool_choice = toAnthropicToolChoice(request.toolChoice);\n }\n if (stream) {\n body.stream = true;\n }\n return body;\n }\n}\n\n/** Map the provider-agnostic tool choice onto Anthropic's `tool_choice`. */\nfunction toAnthropicToolChoice(choice: ToolChoice): Record<string, unknown> {\n if (typeof choice === \"object\") {\n return { type: \"tool\", name: choice.name };\n }\n // \"auto\" | \"any\" | \"none\" map to Anthropic's own type names directly.\n return { type: choice };\n}\n\ntype AnthropicSource =\n | { type: \"base64\"; media_type: string; data: string }\n | { type: \"url\"; url: string };\n\ntype AnthropicBlock =\n | { type: \"text\"; text: string }\n | { type: \"image\"; source: AnthropicSource }\n | { type: \"document\"; source: AnthropicSource }\n | {\n type: \"tool_use\";\n id?: string;\n name: string;\n input: Record<string, unknown>;\n }\n | {\n type: \"tool_result\";\n tool_use_id?: string;\n content: string;\n is_error?: boolean;\n };\n\n/**\n * Map a message onto Anthropic's wire shape. A bare-`string` content is sent\n * as-is (Anthropic accepts a string or an array of content blocks); structured\n * content is mapped block-by-block. An image is an `image` block, a file a\n * `document` block (PDF/text).\n */\nfunction toAnthropicMessage(message: Message): {\n role: Role;\n content: string | AnthropicBlock[];\n} {\n if (typeof message.content === \"string\") {\n return { role: message.role, content: message.content };\n }\n const blocks = message.content.map((part) => toAnthropicBlock(part));\n // Anthropic requires tool_result blocks to come first in a user turn, so hoist\n // them ahead of any text the caller placed before them (a no-op when there are\n // none). Relative order within each group is preserved.\n const toolResults = blocks.filter((b) => b.type === \"tool_result\");\n const rest = blocks.filter((b) => b.type !== \"tool_result\");\n return { role: message.role, content: [...toolResults, ...rest] };\n}\n\nfunction toAnthropicBlock(part: ContentPart): AnthropicBlock {\n switch (part.type) {\n case \"text\":\n return { type: \"text\", text: part.text };\n case \"image\":\n return { type: \"image\", source: toAnthropicSource(part.source) };\n case \"file\":\n return { type: \"document\", source: toAnthropicSource(part.source) };\n case \"tool_use\":\n return {\n type: \"tool_use\",\n id: part.id,\n name: part.name,\n input: part.input,\n };\n case \"tool_result\":\n // Anthropic wants tool_result blocks first in the user turn; the caller is\n // responsible for ordering (the low-level protocol puts them in their own\n // message). is_error is omitted unless set.\n return {\n type: \"tool_result\",\n tool_use_id: part.toolUseId,\n content: part.content,\n ...(part.isError === undefined ? {} : { is_error: part.isError }),\n };\n }\n}\n\nfunction toAnthropicSource(source: MediaSource): AnthropicSource {\n return source.kind === \"base64\"\n ? { type: \"base64\", media_type: source.mediaType, data: source.data }\n : { type: \"url\", url: source.url };\n}\n\nfunction toArray(value: unknown): unknown[] {\n return Array.isArray(value) ? (value as unknown[]) : [];\n}\n\nfunction extractText(data: unknown): string {\n const content = isRecord(data) ? toArray(data.content) : [];\n let text = \"\";\n for (const block of content) {\n if (\n isRecord(block) &&\n block.type === \"text\" &&\n typeof block.text === \"string\"\n ) {\n text += block.text;\n }\n }\n return text;\n}\n\n/** Collect any `tool_use` content blocks as provider-agnostic tool calls. */\nfunction extractToolCalls(data: unknown): ToolCall[] | undefined {\n const content = isRecord(data) ? toArray(data.content) : [];\n const calls: ToolCall[] = [];\n for (const block of content) {\n if (\n isRecord(block) &&\n block.type === \"tool_use\" &&\n typeof block.name === \"string\"\n ) {\n calls.push({\n id: typeof block.id === \"string\" ? block.id : undefined,\n name: block.name,\n input: isRecord(block.input) ? block.input : {},\n });\n }\n }\n return calls.length > 0 ? calls : undefined;\n}\n\nfunction extractFinishReason(data: unknown): string | undefined {\n if (isRecord(data) && typeof data.stop_reason === \"string\") {\n return data.stop_reason;\n }\n return undefined;\n}\n\n/** Maps Anthropic's `stop_reason` onto the provider-agnostic union. */\nfunction normalizeFinishReason(\n raw: string | undefined,\n): FinishReason | undefined {\n switch (raw) {\n case undefined:\n return undefined;\n case \"end_turn\":\n case \"stop_sequence\":\n return \"stop\";\n case \"max_tokens\":\n return \"length\";\n case \"refusal\":\n return \"content_filter\";\n case \"tool_use\":\n return \"tool_use\";\n default:\n return \"other\";\n }\n}\n\n/** Anthropic reports `usage.input_tokens`/`output_tokens`; it has no total field. */\nfunction extractUsage(data: unknown): Usage | undefined {\n const usage = isRecord(data) ? data.usage : undefined;\n if (!isRecord(usage)) {\n return undefined;\n }\n const inputTokens =\n typeof usage.input_tokens === \"number\" ? usage.input_tokens : 0;\n const outputTokens =\n typeof usage.output_tokens === \"number\" ? usage.output_tokens : 0;\n return { inputTokens, outputTokens, totalTokens: inputTokens + outputTokens };\n}\n\n/** Text from any `type: \"refusal\"` content blocks `extractText` skips. */\nfunction extractRefusal(data: unknown): string | undefined {\n const content = isRecord(data) ? toArray(data.content) : [];\n let refusal = \"\";\n for (const block of content) {\n if (\n isRecord(block) &&\n block.type === \"refusal\" &&\n typeof block.text === \"string\"\n ) {\n refusal += block.text;\n }\n }\n return refusal === \"\" ? undefined : refusal;\n}\n","/**\n * Google Gemini provider, talking to the Generative Language API directly over\n * `fetch` — no SDK dependency.\n */\n\nimport { apiError, apiErrorFromBody } from \"../errors\";\nimport { extractModel, isRecord } from \"./extract\";\nimport { sseJson } from \"./sse\";\nimport { parseStructured } from \"./structured\";\nimport { requestWithRetry, type RetryOptions } from \"../transport\";\nimport {\n type CompletionRequest,\n type CompletionResult,\n type ContentPart,\n type FinishReason,\n type MediaSource,\n type Message,\n type Provider,\n type ToolCall,\n type ToolChoice,\n type Usage,\n} from \"../types\";\n\nexport type GoogleProviderOptions = {\n apiKey: string;\n /** Defaults to {@link DEFAULT_MODEL}. */\n model?: string;\n /** Defaults to `https://generativelanguage.googleapis.com`. */\n baseUrl?: string;\n /** Bounded retry/backoff on 429/503/529. Defaults applied when omitted. */\n retry?: RetryOptions;\n};\n\nconst DEFAULT_MODEL = \"gemini-2.5-pro\";\nconst DEFAULT_BASE_URL = \"https://generativelanguage.googleapis.com\";\n\n/** Non-streaming default keeps responses under the HTTP timeout window. */\nconst DEFAULT_MAX_TOKENS = 16000;\n/** Streaming has no timeout concern, so give the model more room. */\nconst DEFAULT_STREAM_MAX_TOKENS = 64000;\n\nexport class GoogleProvider implements Provider {\n readonly name = \"google\";\n\n readonly #apiKey: string;\n readonly #model: string;\n readonly #baseUrl: string;\n readonly #retry?: RetryOptions;\n\n constructor(options: GoogleProviderOptions) {\n this.#apiKey = options.apiKey;\n this.#model = options.model ?? DEFAULT_MODEL;\n this.#baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n this.#retry = options.retry;\n }\n\n async complete(request: CompletionRequest): Promise<CompletionResult> {\n const model = request.model ?? this.#model;\n const response = await requestWithRetry(\n \"google\",\n this.#url(model, false),\n {\n method: \"POST\",\n headers: this.#headers(),\n body: JSON.stringify(this.#buildBody(request, DEFAULT_MAX_TOKENS)),\n signal: request.signal,\n },\n this.#retry,\n );\n\n if (!response.ok) {\n throw await apiError(\"google\", response);\n }\n\n const data: unknown = await response.json();\n if (isRecord(data) && isRecord(data.error)) {\n throw apiErrorFromBody(\"google\", response.status, data);\n }\n const rawFinishReason = extractFinishReason(data);\n const text = extractText(data);\n const toolCalls = extractToolCalls(data);\n const finishReason = normalizeFinishReason(rawFinishReason);\n return {\n text,\n model: extractModel(data, model, \"modelVersion\"),\n // Gemini reports `STOP` even when it emits a function call, so surface\n // `tool_use` — but only on a clean stop. A real `MAX_TOKENS`/`SAFETY` stop\n // (e.g. truncated args) must not be masked, so keep its normalized reason.\n finishReason:\n toolCalls !== undefined &&\n (finishReason === \"stop\" || finishReason === undefined)\n ? \"tool_use\"\n : finishReason,\n rawFinishReason,\n usage: extractUsage(data),\n parsed: parseStructured(request, text),\n toolCalls,\n };\n }\n\n async *stream(\n request: CompletionRequest,\n ): AsyncGenerator<string, void, void> {\n const model = request.model ?? this.#model;\n const response = await requestWithRetry(\n \"google\",\n this.#url(model, true),\n {\n method: \"POST\",\n headers: this.#headers(),\n body: JSON.stringify(\n this.#buildBody(request, DEFAULT_STREAM_MAX_TOKENS),\n ),\n signal: request.signal,\n },\n this.#retry,\n );\n\n if (!response.ok) {\n throw await apiError(\"google\", response);\n }\n if (!response.body) {\n throw new Error(\"Google streaming response had no body\");\n }\n\n for await (const event of sseJson(response.body)) {\n if (isRecord(event.error)) {\n throw new Error(`Google stream error: ${JSON.stringify(event)}`);\n }\n const text = extractText(event);\n if (text.length > 0) {\n yield text;\n }\n }\n }\n\n /**\n * Gemini puts the model and the action in the path (`:generateContent` vs\n * `:streamGenerateContent`); streaming additionally needs `?alt=sse` to get an\n * SSE body rather than a streamed JSON array.\n */\n #url(model: string, stream: boolean): string {\n const action = stream ? \"streamGenerateContent?alt=sse\" : \"generateContent\";\n return `${this.#baseUrl}/v1beta/models/${model}:${action}`;\n }\n\n #headers(): Record<string, string> {\n return {\n \"x-goog-api-key\": this.#apiKey,\n \"content-type\": \"application/json\",\n };\n }\n\n #buildBody(\n request: CompletionRequest,\n defaultMaxTokens: number,\n ): Record<string, unknown> {\n const generationConfig: Record<string, unknown> = {\n maxOutputTokens: request.maxTokens ?? defaultMaxTokens,\n };\n if (request.responseFormat !== undefined) {\n // Gemini's native structured output lives on generationConfig: a JSON MIME\n // type plus an OpenAPI-3-subset schema (UPPERCASE types — see toGeminiSchema).\n generationConfig.responseMimeType = \"application/json\";\n generationConfig.responseSchema = toGeminiSchema(\n request.responseFormat.schema,\n );\n }\n const body: Record<string, unknown> = {\n contents: request.messages.map((message) => toGeminiContent(message)),\n generationConfig,\n };\n if (request.system !== undefined) {\n body.systemInstruction = { parts: [{ text: request.system }] };\n }\n if (request.tools !== undefined) {\n // Tool parameter schemas need the same OpenAPI-3-subset transform as\n // structured output (UPPERCASE types).\n body.tools = [\n {\n functionDeclarations: request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: toGeminiSchema(tool.parameters),\n })),\n },\n ];\n }\n if (request.toolChoice !== undefined) {\n body.toolConfig = {\n functionCallingConfig: toGeminiFunctionCallingConfig(\n request.toolChoice,\n ),\n };\n }\n return body;\n }\n}\n\n/** Map the provider-agnostic tool choice onto Gemini's `functionCallingConfig`. */\nfunction toGeminiFunctionCallingConfig(\n choice: ToolChoice,\n): Record<string, unknown> {\n if (typeof choice === \"object\") {\n // Force this one tool: ANY mode restricted to its name.\n return { mode: \"ANY\", allowedFunctionNames: [choice.name] };\n }\n const mode = { auto: \"AUTO\", any: \"ANY\", none: \"NONE\" }[choice];\n return { mode };\n}\n\n/**\n * Convert a JSON Schema to Gemini's OpenAPI-3 subset. The load-bearing\n * difference is that `type` values are UPPERCASE (`\"string\"` → `\"STRING\"`); we\n * recurse through `properties`/`items`/`anyOf`/`allOf`/`oneOf` and uppercase\n * each scalar `type`. Other keywords pass through (Gemini silently ignores ones\n * it doesn't support); advanced features (null-union types, `$ref`, numeric/\n * length constraints) aren't translated — keep schemas within the documented\n * cross-provider subset.\n */\nfunction toGeminiSchema(schema: unknown): unknown {\n if (Array.isArray(schema)) {\n return schema.map((entry) => toGeminiSchema(entry));\n }\n if (!isRecord(schema)) {\n return schema;\n }\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(schema)) {\n if (key === \"type\" && typeof value === \"string\") {\n out[key] = value.toUpperCase();\n } else if (key === \"properties\" && isRecord(value)) {\n out[key] = Object.fromEntries(\n Object.entries(value).map(([name, propSchema]) => [\n name,\n toGeminiSchema(propSchema),\n ]),\n );\n } else if (key === \"items\") {\n out[key] = toGeminiSchema(value);\n } else if (\n [\"anyOf\", \"allOf\", \"oneOf\"].includes(key) &&\n Array.isArray(value)\n ) {\n out[key] = value.map((entry) => toGeminiSchema(entry));\n } else {\n out[key] = value;\n }\n }\n return out;\n}\n\ntype GeminiPart =\n | { text: string }\n | { inlineData: { mimeType: string; data: string } }\n | { fileData: { mimeType?: string; fileUri: string } }\n | {\n functionCall: {\n name: string;\n id?: string;\n args: Record<string, unknown>;\n };\n }\n | {\n functionResponse: {\n name?: string;\n id?: string;\n response: Record<string, unknown>;\n };\n };\n\n/**\n * Gemini names the assistant role `model` and carries content inside a `parts`\n * array. A bare-`string` content becomes a single text part; structured content\n * is mapped part-by-part. Images and files map alike: inline base64 bytes become\n * an `inlineData` part, a URL becomes a `fileData` reference (see {@link toGeminiMedia}).\n */\nfunction toGeminiContent(message: Message): {\n role: string;\n parts: GeminiPart[];\n} {\n return {\n role: message.role === \"assistant\" ? \"model\" : \"user\",\n parts:\n typeof message.content === \"string\"\n ? [{ text: message.content }]\n : message.content.map((part) => toGeminiPart(part)),\n };\n}\n\nfunction toGeminiPart(part: ContentPart): GeminiPart {\n switch (part.type) {\n case \"text\":\n return { text: part.text };\n case \"image\":\n case \"file\":\n return toGeminiMedia(part.source);\n case \"tool_use\":\n return {\n functionCall: {\n name: part.name,\n ...(part.id === undefined ? {} : { id: part.id }),\n args: part.input,\n },\n };\n case \"tool_result\":\n // Gemini correlates a result to its call by function name, so name is\n // required here (unlike Anthropic/OpenAI, which match by id).\n if (part.name === undefined) {\n throw new Error(\n \"Gemini requires the tool name on each tool result; set ToolResultPart.name to the called tool's name.\",\n );\n }\n // Gemini's functionResponse.response is an object; wrap the text output.\n return {\n functionResponse: {\n name: part.name,\n ...(part.toolUseId === undefined ? {} : { id: part.toolUseId }),\n response: { result: part.content },\n },\n };\n }\n}\n\n/**\n * Map a media source to a Gemini part. Base64 bytes become inline `inlineData`.\n * A URL becomes a `fileData` reference — but Gemini's `fileData.fileUri` only\n * accepts a Files API URI or a `gs://` Cloud Storage URI, **not** an arbitrary\n * public web URL (unlike Anthropic/OpenAI image URLs). Passing a plain `https://`\n * URL will be rejected by Gemini; use a base64 source or a Files API URI instead.\n */\nfunction toGeminiMedia(source: MediaSource): GeminiPart {\n if (source.kind === \"base64\") {\n return { inlineData: { mimeType: source.mediaType, data: source.data } };\n }\n return {\n fileData:\n source.mediaType === undefined\n ? { fileUri: source.url }\n : { mimeType: source.mediaType, fileUri: source.url },\n };\n}\n\nfunction toArray(value: unknown): unknown[] {\n return Array.isArray(value) ? (value as unknown[]) : [];\n}\n\n/** The first candidate of a response (`candidates[0]`), or `undefined`. */\nfunction firstCandidate(data: unknown): Record<string, unknown> | undefined {\n const candidates = isRecord(data) ? toArray(data.candidates) : [];\n const first = candidates[0];\n return isRecord(first) ? first : undefined;\n}\n\n/** The parts of the first candidate's content (`candidates[0].content.parts`). */\nfunction firstCandidateParts(data: unknown): unknown[] {\n const content = firstCandidate(data)?.content;\n return isRecord(content) ? toArray(content.parts) : [];\n}\n\nfunction extractText(data: unknown): string {\n let text = \"\";\n for (const part of firstCandidateParts(data)) {\n if (isRecord(part) && typeof part.text === \"string\") {\n text += part.text;\n }\n }\n return text;\n}\n\n/** Collect any `functionCall` parts as provider-agnostic tool calls. */\nfunction extractToolCalls(data: unknown): ToolCall[] | undefined {\n const parts = firstCandidateParts(data);\n const calls: ToolCall[] = [];\n for (const part of parts) {\n const call = isRecord(part) ? part.functionCall : undefined;\n if (isRecord(call) && typeof call.name === \"string\") {\n calls.push({\n id: typeof call.id === \"string\" ? call.id : undefined,\n name: call.name,\n input: isRecord(call.args) ? call.args : {},\n });\n }\n }\n return calls.length > 0 ? calls : undefined;\n}\n\n/**\n * Gemini reports the stop reason on the first candidate. When the prompt itself\n * was blocked there are no candidates, so fall back to `promptFeedback.blockReason`.\n */\nfunction extractFinishReason(data: unknown): string | undefined {\n const first = firstCandidate(data);\n if (first !== undefined && typeof first.finishReason === \"string\") {\n return first.finishReason;\n }\n const feedback = isRecord(data) ? data.promptFeedback : undefined;\n if (isRecord(feedback) && typeof feedback.blockReason === \"string\") {\n return feedback.blockReason;\n }\n return undefined;\n}\n\n/**\n * Gemini reports `usageMetadata.promptTokenCount`/`candidatesTokenCount`/\n * `totalTokenCount`. `totalTokenCount` includes thinking tokens, so it can\n * exceed prompt + candidates — we keep the provider's own total verbatim.\n */\nfunction extractUsage(data: unknown): Usage | undefined {\n const usage = isRecord(data) ? data.usageMetadata : undefined;\n if (!isRecord(usage)) {\n return undefined;\n }\n const inputTokens =\n typeof usage.promptTokenCount === \"number\" ? usage.promptTokenCount : 0;\n const outputTokens =\n typeof usage.candidatesTokenCount === \"number\"\n ? usage.candidatesTokenCount\n : 0;\n const totalTokens =\n typeof usage.totalTokenCount === \"number\"\n ? usage.totalTokenCount\n : inputTokens + outputTokens;\n return { inputTokens, outputTokens, totalTokens };\n}\n\n/** Maps Gemini's `finishReason` (and prompt block reasons) onto the union. */\nfunction normalizeFinishReason(\n raw: string | undefined,\n): FinishReason | undefined {\n switch (raw) {\n case undefined:\n return undefined;\n case \"STOP\":\n return \"stop\";\n case \"MAX_TOKENS\":\n return \"length\";\n case \"SAFETY\":\n case \"RECITATION\":\n case \"BLOCKLIST\":\n case \"PROHIBITED_CONTENT\":\n case \"SPII\":\n return \"content_filter\";\n default:\n return \"other\";\n }\n}\n","/**\n * OpenAI provider, talking to the Chat Completions API directly over `fetch` —\n * no SDK dependency.\n */\n\nimport { apiError, apiErrorFromBody } from \"../errors\";\nimport { extractModel, isRecord } from \"./extract\";\nimport { sseJson } from \"./sse\";\nimport { parseStructured } from \"./structured\";\nimport { requestWithRetry, type RetryOptions } from \"../transport\";\nimport {\n type CompletionRequest,\n type CompletionResult,\n type FilePart,\n type FinishReason,\n type ImagePart,\n type MediaSource,\n type Message,\n type Provider,\n type TextPart,\n type ToolCall,\n type ToolChoice,\n type Usage,\n} from \"../types\";\n\nexport type OpenAIProviderOptions = {\n apiKey: string;\n /** Defaults to {@link DEFAULT_MODEL}. */\n model?: string;\n /** Defaults to `https://api.openai.com`. */\n baseUrl?: string;\n /**\n * Extra headers merged into (and able to override) every request's headers —\n * for an OpenAI-compatible gateway's auth/routing (e.g. OpenRouter's\n * `HTTP-Referer`/`X-Title`) or a proxy. Use lowercase header names.\n */\n headers?: Record<string, string>;\n /** Bounded retry/backoff on 429/503/529. Defaults applied when omitted. */\n retry?: RetryOptions;\n};\n\nconst DEFAULT_MODEL = \"gpt-4.1\";\nconst DEFAULT_BASE_URL = \"https://api.openai.com\";\n\n/** Non-streaming default keeps responses under the HTTP timeout window. */\nconst DEFAULT_MAX_TOKENS = 16000;\n/** Streaming has no timeout concern, so give the model more room. */\nconst DEFAULT_STREAM_MAX_TOKENS = 64000;\n\nexport class OpenAIProvider implements Provider {\n readonly name: string;\n\n readonly #apiKey: string;\n readonly #model: string;\n readonly #baseUrl: string;\n readonly #extraHeaders?: Record<string, string>;\n readonly #retry?: RetryOptions;\n\n /**\n * `name` is the provider's identity, used as `this.name` and in error\n * attribution (`ProviderError.provider`). It defaults to `\"openai\"`; the\n * registry passes a custom name for an OpenAI-compatible gateway so its errors\n * aren't mislabeled `\"openai\"`. It's a constructor argument rather than a\n * public option because only the registry sets it — it isn't user config.\n */\n constructor(options: OpenAIProviderOptions, name = \"openai\") {\n this.name = name;\n this.#apiKey = options.apiKey;\n this.#model = options.model ?? DEFAULT_MODEL;\n this.#baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;\n this.#extraHeaders = options.headers;\n this.#retry = options.retry;\n }\n\n async complete(request: CompletionRequest): Promise<CompletionResult> {\n const model = request.model ?? this.#model;\n const response = await requestWithRetry(\n this.name,\n `${this.#baseUrl}/v1/chat/completions`,\n {\n method: \"POST\",\n headers: this.#headers(),\n body: JSON.stringify(\n this.#buildBody(request, model, DEFAULT_MAX_TOKENS, false),\n ),\n signal: request.signal,\n },\n this.#retry,\n );\n\n if (!response.ok) {\n throw await apiError(this.name, response);\n }\n\n const data: unknown = await response.json();\n if (isRecord(data) && isRecord(data.error)) {\n throw apiErrorFromBody(this.name, response.status, data);\n }\n const rawFinishReason = extractFinishReason(data);\n const refusal = extractRefusal(data);\n const text = extractText(data);\n return {\n text,\n model: extractModel(data, model),\n // A refusal is a content-filter outcome even though OpenAI still reports\n // finish_reason: \"stop\", so surface it as such regardless of the raw value.\n finishReason:\n refusal === undefined\n ? normalizeFinishReason(rawFinishReason)\n : \"content_filter\",\n rawFinishReason,\n refusal,\n usage: extractUsage(data),\n parsed: parseStructured(request, text),\n toolCalls: extractToolCalls(data),\n };\n }\n\n async *stream(\n request: CompletionRequest,\n ): AsyncGenerator<string, void, void> {\n const model = request.model ?? this.#model;\n const response = await requestWithRetry(\n this.name,\n `${this.#baseUrl}/v1/chat/completions`,\n {\n method: \"POST\",\n headers: this.#headers(),\n body: JSON.stringify(\n this.#buildBody(request, model, DEFAULT_STREAM_MAX_TOKENS, true),\n ),\n signal: request.signal,\n },\n this.#retry,\n );\n\n if (!response.ok) {\n throw await apiError(this.name, response);\n }\n if (!response.body) {\n throw new Error(\"OpenAI streaming response had no body\");\n }\n\n for await (const event of sseJson(response.body)) {\n if (isRecord(event.error)) {\n throw new Error(`OpenAI stream error: ${JSON.stringify(event)}`);\n }\n const delta = firstChoiceDelta(event);\n if (isRecord(delta) && typeof delta.content === \"string\") {\n yield delta.content;\n }\n }\n }\n\n #headers(): Record<string, string> {\n return {\n authorization: `Bearer ${this.#apiKey}`,\n \"content-type\": \"application/json\",\n ...this.#extraHeaders,\n };\n }\n\n #buildBody(\n request: CompletionRequest,\n model: string,\n defaultMaxTokens: number,\n stream: boolean,\n ): Record<string, unknown> {\n const body: Record<string, unknown> = {\n model,\n max_completion_tokens: request.maxTokens ?? defaultMaxTokens,\n messages: toOpenAIMessages(request),\n };\n if (request.responseFormat !== undefined) {\n // OpenAI Structured Outputs: response_format.json_schema with strict:true\n // (requires additionalProperties:false + every property in `required`).\n // `name` is required and must match ^[A-Za-z0-9_-]+$.\n body.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: request.responseFormat.name ?? \"response\",\n strict: true,\n schema: request.responseFormat.schema,\n },\n };\n }\n if (request.tools !== undefined) {\n body.tools = request.tools.map((tool) => ({\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n }\n if (request.toolChoice !== undefined) {\n body.tool_choice = toOpenAIToolChoice(request.toolChoice);\n }\n if (stream) {\n body.stream = true;\n }\n return body;\n }\n}\n\n/** Map the provider-agnostic tool choice onto OpenAI's `tool_choice`. */\nfunction toOpenAIToolChoice(choice: ToolChoice): unknown {\n if (typeof choice === \"object\") {\n return { type: \"function\", function: { name: choice.name } };\n }\n // \"any\" is OpenAI's \"required\"; \"auto\"/\"none\" map by name.\n return choice === \"any\" ? \"required\" : choice;\n}\n\ntype OpenAIPart =\n | { type: \"text\"; text: string }\n | { type: \"image_url\"; image_url: { url: string } }\n | { type: \"file\"; file: { filename?: string; file_data: string } };\n\ntype OpenAIToolCall = {\n id?: string;\n type: \"function\";\n function: { name: string; arguments: string };\n};\n\ntype OpenAIMessage =\n | {\n role: string;\n content: string | OpenAIPart[] | null;\n tool_calls?: OpenAIToolCall[];\n }\n | { role: \"tool\"; tool_call_id?: string; content: string };\n\n/** Content parts other than tool parts (which OpenAI carries at the message level). */\ntype OpenAIContentPart = TextPart | ImagePart | FilePart;\n\n/**\n * OpenAI carries the system prompt as a leading `system` message rather than a\n * top-level field, so fold {@link CompletionRequest.system} into the array. A\n * message may expand to several wire messages: OpenAI represents tool calls on an\n * assistant message's `tool_calls`, and each tool result as its own `tool`-role\n * message — so tool parts are handled at the message level, not as content parts.\n */\nfunction toOpenAIMessages(request: CompletionRequest): OpenAIMessage[] {\n const messages = request.messages.flatMap((message) =>\n toOpenAIWireMessages(message),\n );\n if (request.system !== undefined) {\n messages.unshift({ role: \"system\", content: request.system });\n }\n return messages;\n}\n\nfunction toOpenAIWireMessages(message: Message): OpenAIMessage[] {\n if (typeof message.content === \"string\") {\n return [{ role: message.role, content: message.content }];\n }\n\n const toolUses = message.content.filter((p) => p.type === \"tool_use\");\n const toolResults = message.content.filter((p) => p.type === \"tool_result\");\n const rest = message.content.filter((p): p is OpenAIContentPart =>\n [\"text\", \"image\", \"file\"].includes(p.type),\n );\n\n // An assistant turn that called tools: content (if any) plus `tool_calls`.\n if (toolUses.length > 0) {\n return [\n {\n role: message.role,\n content: rest.length > 0 ? rest.map((p) => toOpenAIPart(p)) : null,\n tool_calls: toolUses.map((u) => {\n if (u.id === undefined) {\n throw new Error(\n \"OpenAI requires an id on each tool call; replay the ToolCall.id you received from the model.\",\n );\n }\n return {\n id: u.id,\n type: \"function\",\n function: { name: u.name, arguments: JSON.stringify(u.input) },\n };\n }),\n },\n ];\n }\n\n // Tool results become one `tool`-role message each; any other parts follow as a\n // normal message.\n const out: OpenAIMessage[] = toolResults.map((r) => {\n if (r.toolUseId === undefined) {\n throw new Error(\n \"OpenAI requires toolUseId on each tool result; set it to the id of the ToolCall you are answering.\",\n );\n }\n return { role: \"tool\", tool_call_id: r.toolUseId, content: r.content };\n });\n if (rest.length > 0) {\n out.push({ role: message.role, content: rest.map((p) => toOpenAIPart(p)) });\n }\n return out;\n}\n\nfunction toOpenAIPart(part: OpenAIContentPart): OpenAIPart {\n switch (part.type) {\n case \"text\":\n return { type: \"text\", text: part.text };\n case \"image\":\n return {\n type: \"image_url\",\n image_url: { url: toOpenAIUrl(part.source) },\n };\n case \"file\":\n return { type: \"file\", file: toOpenAIFile(part) };\n }\n}\n\n/** An image source becomes either an https URL or a base64 `data:` URI. */\nfunction toOpenAIUrl(source: MediaSource): string {\n return source.kind === \"base64\"\n ? `data:${source.mediaType};base64,${source.data}`\n : source.url;\n}\n\n/**\n * Chat Completions takes a file only as inline base64 (`file_data`, a `data:`\n * URI) — there is no URL file source — so a `url` file source is unsupported.\n */\nfunction toOpenAIFile(part: FilePart): {\n filename?: string;\n file_data: string;\n} {\n if (part.source.kind !== \"base64\") {\n throw new Error(\n \"OpenAI (Chat Completions) does not support a URL file source; use a base64 source.\",\n );\n }\n const file_data = `data:${part.source.mediaType};base64,${part.source.data}`;\n return part.filename === undefined\n ? { file_data }\n : { filename: part.filename, file_data };\n}\n\nfunction toArray(value: unknown): unknown[] {\n return Array.isArray(value) ? (value as unknown[]) : [];\n}\n\nfunction firstChoice(data: unknown): Record<string, unknown> | undefined {\n const choices = isRecord(data) ? toArray(data.choices) : [];\n const first = choices[0];\n return isRecord(first) ? first : undefined;\n}\n\nfunction extractText(data: unknown): string {\n const message = firstChoice(data)?.message;\n if (isRecord(message) && typeof message.content === \"string\") {\n return message.content;\n }\n return \"\";\n}\n\nfunction firstChoiceDelta(data: unknown): unknown {\n return firstChoice(data)?.delta;\n}\n\n/**\n * Collect `choices[0].message.tool_calls` as provider-agnostic tool calls.\n * OpenAI's `arguments` is a JSON **string**, so it's parsed into the `input`\n * object (a malformed/empty string yields `{}`).\n */\nfunction extractToolCalls(data: unknown): ToolCall[] | undefined {\n const message = firstChoice(data)?.message;\n const toolCalls = isRecord(message) ? toArray(message.tool_calls) : [];\n const calls: ToolCall[] = [];\n for (const call of toolCalls) {\n if (!isRecord(call) || !isRecord(call.function)) {\n continue;\n }\n const fn = call.function;\n if (typeof fn.name !== \"string\") {\n continue;\n }\n calls.push({\n id: typeof call.id === \"string\" ? call.id : undefined,\n name: fn.name,\n input: parseArguments(fn.arguments),\n });\n }\n return calls.length > 0 ? calls : undefined;\n}\n\nfunction parseArguments(args: unknown): Record<string, unknown> {\n if (typeof args !== \"string\") {\n return {};\n }\n try {\n const parsed: unknown = JSON.parse(args);\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction extractFinishReason(data: unknown): string | undefined {\n const reason = firstChoice(data)?.finish_reason;\n return typeof reason === \"string\" ? reason : undefined;\n}\n\n/** Maps OpenAI's `finish_reason` onto the provider-agnostic union. */\nfunction normalizeFinishReason(\n raw: string | undefined,\n): FinishReason | undefined {\n switch (raw) {\n case undefined:\n return undefined;\n case \"stop\":\n return \"stop\";\n case \"length\":\n return \"length\";\n case \"content_filter\":\n return \"content_filter\";\n case \"tool_calls\":\n case \"function_call\":\n return \"tool_use\";\n default:\n return \"other\";\n }\n}\n\n/** OpenAI reports `usage.prompt_tokens`/`completion_tokens`/`total_tokens`. */\nfunction extractUsage(data: unknown): Usage | undefined {\n const usage = isRecord(data) ? data.usage : undefined;\n if (!isRecord(usage)) {\n return undefined;\n }\n const inputTokens =\n typeof usage.prompt_tokens === \"number\" ? usage.prompt_tokens : 0;\n const outputTokens =\n typeof usage.completion_tokens === \"number\" ? usage.completion_tokens : 0;\n const totalTokens =\n typeof usage.total_tokens === \"number\"\n ? usage.total_tokens\n : inputTokens + outputTokens;\n return { inputTokens, outputTokens, totalTokens };\n}\n\nfunction extractRefusal(data: unknown): string | undefined {\n const message = firstChoice(data)?.message;\n if (\n isRecord(message) &&\n typeof message.refusal === \"string\" &&\n message.refusal !== \"\"\n ) {\n return message.refusal;\n }\n return undefined;\n}\n","/**\n * Provider registry — the package's single point of access to its providers.\n *\n * You configure the registry with the providers you want (and their API keys);\n * the library constructs the built-in providers by name and hands one back via\n * {@link ProviderRegistry.select}. Consumers never import the provider classes\n * directly. It never reads env vars — keys are always passed in the config.\n */\n\nimport {\n type BroadcastRequest,\n type BroadcastResult,\n type CombineOptions,\n type CombineRequest,\n type CombineRequestBase,\n type CombineResult,\n type ConsensusRequest,\n type ConsensusResult,\n type EnsembleRequest,\n type EnsembleResult,\n type ParticipantSpec,\n type PipelineRequest,\n type PipelineResult,\n type ResultFor,\n type StrategyName,\n STRATEGY_NAMES,\n} from \"./combine\";\nimport { broadcast as runBroadcast } from \"./combine/broadcast\";\nimport { consensus as runConsensus } from \"./combine/consensus\";\nimport { ensemble as runEnsemble } from \"./combine/ensemble\";\nimport { pipeline as runPipeline } from \"./combine/pipeline\";\nimport { type RosterEntry } from \"./combine/shared\";\nimport {\n AnthropicProvider,\n type AnthropicProviderOptions,\n} from \"./providers/anthropic\";\nimport { GoogleProvider, type GoogleProviderOptions } from \"./providers/google\";\nimport { OpenAIProvider, type OpenAIProviderOptions } from \"./providers/openai\";\nimport { type RetryOptions } from \"./transport\";\nimport { type Provider } from \"./types\";\n\n/**\n * An OpenAI Chat Completions–compatible endpoint registered under a custom name.\n * The library reuses its OpenAI provider against your `baseUrl`, so any service\n * that speaks the Chat Completions wire format works — OpenRouter, Together,\n * Groq, Ollama, a local server, etc.\n */\nexport type OpenAICompatibleConfig = {\n kind: \"openai-compatible\";\n apiKey: string;\n /**\n * Base URL of the endpoint, **excluding** the `/v1/chat/completions` path the\n * provider appends (e.g. `https://api.groq.com/openai`, `http://localhost:11434`).\n */\n baseUrl: string;\n /**\n * The model id to send. Required — unlike the built-ins there is no sensible\n * default for a third-party endpoint. `request.model` (or combine's `model`)\n * still overrides it per call.\n */\n model: string;\n /** Extra headers merged into every request (e.g. OpenRouter's `HTTP-Referer`/`X-Title`). */\n headers?: Record<string, string>;\n /** Bounded retry/backoff on 429/503/529. Defaults applied when omitted. */\n retry?: RetryOptions;\n};\n\n/**\n * A provider you implement yourself (anything satisfying {@link Provider}),\n * registered under a custom name. The escape hatch for an API the library\n * doesn't speak natively, or for wrapping a built-in with instrumentation.\n */\nexport type CustomProviderInstance = {\n kind: \"provider\";\n provider: Provider;\n};\n\n/** How a custom (non-built-in) provider is registered. */\nexport type CustomProviderConfig =\n | OpenAICompatibleConfig\n | CustomProviderInstance;\n\n/** The names the library constructs as built-in providers (the single source of truth). */\nconst BUILT_IN_NAMES = [\"anthropic\", \"openai\", \"google\"] as const;\n\n/** The provider names the library constructs from its own config. */\nexport type BuiltInProviderName = (typeof BUILT_IN_NAMES)[number];\n\n/** Per-provider configuration. Include a provider's key to register it. */\nexport type ProviderRegistryConfig = {\n anthropic?: AnthropicProviderOptions;\n openai?: OpenAIProviderOptions;\n google?: GoogleProviderOptions;\n /**\n * Extra providers registered under names you choose — an OpenAI-compatible\n * gateway/local endpoint or a {@link Provider} you bring yourself. Each name\n * must not collide with a built-in.\n */\n custom?: Record<string, CustomProviderConfig>;\n};\n\n/**\n * A configured provider's name: the three built-ins, or any custom name you\n * registered. The `string & Record<never, never>` intersection keeps editor\n * autocomplete for the built-in literals while still accepting an arbitrary\n * custom string.\n */\nexport type ProviderName =\n | BuiltInProviderName\n | (string & Record<never, never>);\n\nexport class ProviderRegistry {\n readonly #providers = new Map<ProviderName, Provider>();\n\n /**\n * Construct the providers present in `config`. A provider is registered only\n * if its entry is supplied; the rest are left out.\n */\n constructor(config: ProviderRegistryConfig) {\n if (config.anthropic) {\n this.#providers.set(\"anthropic\", new AnthropicProvider(config.anthropic));\n }\n if (config.openai) {\n this.#providers.set(\"openai\", new OpenAIProvider(config.openai));\n }\n if (config.google) {\n this.#providers.set(\"google\", new GoogleProvider(config.google));\n }\n if (config.custom) {\n const builtInNames: readonly string[] = BUILT_IN_NAMES;\n for (const [name, custom] of Object.entries(config.custom)) {\n if (builtInNames.includes(name)) {\n throw new Error(\n `Custom provider name \"${name}\" collides with a built-in; choose a different name.`,\n );\n }\n this.#providers.set(name, constructCustom(name, custom));\n }\n }\n }\n\n /**\n * Return the provider registered under `name`. Throws a clear error listing\n * the configured names if that provider was not configured.\n */\n select(name: ProviderName): Provider {\n const provider = this.#providers.get(name);\n if (provider === undefined) {\n throw new Error(\n `No provider \"${name}\" configured. Configured: ${this.#configuredList()}`,\n );\n }\n return provider;\n }\n\n /**\n * Combine several configured providers to cooperate on one prompt, dispatching\n * on `request.strategy` (defaults to `\"consensus\"`).\n *\n * Generic over the strategy: `S` is inferred from the `strategy` field, so a\n * **literal** `strategy` at the call site makes the return that strategy's\n * concrete result (e.g. `strategy: \"ensemble\"` → `EnsembleResult`) — the caller\n * does **not** narrow a union. When `strategy` is only known at runtime, `S`\n * widens to {@link StrategyName} and the return is the full\n * {@link CombineResult} union to narrow.\n *\n * The request stays the broad {@link CombineRequest} here; for compile-time\n * enforcement of a strategy's specific options (e.g. `responseFormat` required\n * for ensemble) call the per-strategy method ({@link ProviderRegistry.consensus},\n * {@link ProviderRegistry.pipeline}, {@link ProviderRegistry.ensemble},\n * {@link ProviderRegistry.broadcast}), which takes that strategy's request type.\n */\n async combine<S extends StrategyName = \"consensus\">(\n request: Omit<CombineRequest, \"strategy\"> & { strategy?: S },\n options?: CombineOptions,\n ): Promise<ResultFor<S>> {\n const strategy: StrategyName = request.strategy ?? \"consensus\";\n const knownStrategies: readonly string[] = STRATEGY_NAMES;\n if (!knownStrategies.includes(strategy)) {\n throw new Error(\n `Unknown combine strategy \"${strategy}\". Known: ${STRATEGY_NAMES.join(\", \")}`,\n );\n }\n let result: CombineResult;\n switch (strategy) {\n case \"consensus\":\n result = await this.consensus(request, options);\n break;\n case \"pipeline\":\n result = await this.pipeline(request, options);\n break;\n case \"ensemble\":\n // The request is the broad type here; the `ensemble` method re-checks\n // responseFormat at runtime (it's required by EnsembleRequest's type).\n result = await this.ensemble(request as EnsembleRequest, options);\n break;\n case \"broadcast\":\n result = await this.broadcast(request, options);\n break;\n default: {\n const unreachable: never = strategy;\n throw new Error(`Unhandled combine strategy \"${String(unreachable)}\"`);\n }\n }\n return result as ResultFor<S>;\n }\n\n /**\n * Run the `consensus` strategy (draft → critique → synthesize) over the\n * configured participants. Strategy-specific: `synthesizer` (defaults to the\n * first participant), `attribution`, `minParticipants` (default 2).\n */\n async consensus(\n request: ConsensusRequest,\n options?: CombineOptions,\n ): Promise<ConsensusResult> {\n const { roster, ids, firstId } = this.#prepare(request);\n this.#rejectResponseFormat(request, \"consensus\");\n this.#validateConsensusOptions(request, ids);\n const synthesizer = request.synthesizer ?? firstId;\n return runConsensus(roster, synthesizer, request, options?.onEvent);\n }\n\n /**\n * Run the `pipeline` strategy (sequential refinement) — participants refine a\n * running answer in roster order; the last advancing stage wins.\n */\n async pipeline(\n request: PipelineRequest,\n options?: CombineOptions,\n ): Promise<PipelineResult> {\n const { roster } = this.#prepare(request);\n this.#rejectResponseFormat(request, \"pipeline\");\n return runPipeline(roster, request, options?.onEvent);\n }\n\n /**\n * Run the `ensemble` strategy (multi-model vote on structured output) — every\n * participant answers under `request.responseFormat`; the typed objects are\n * merged field-wise by majority vote with a per-field agreement score.\n */\n async ensemble(\n request: EnsembleRequest,\n options?: CombineOptions,\n ): Promise<EnsembleResult> {\n const { roster } = this.#prepare(request);\n // responseFormat is required by the type, but a JS caller (or the `combine`\n // dispatcher's cast) can still omit it — re-check at runtime.\n const { responseFormat } = request as CombineRequest;\n if (responseFormat === undefined) {\n throw new Error(\n 'The \"ensemble\" strategy requires a responseFormat (the JSON Schema every participant answers under).',\n );\n }\n // The field-wise merge needs named fields, so the schema's root must be an\n // object. Reject array/scalar roots up front with a clear error rather than\n // failing opaquely after paying for every participant's call.\n const rootType = responseFormat.schema.type;\n if (typeof rootType === \"string\" && rootType !== \"object\") {\n throw new Error(\n `The \"ensemble\" strategy requires an object schema (its field-wise vote needs named fields); got a \"${rootType}\" schema.`,\n );\n }\n return runEnsemble(roster, request, options?.onEvent);\n }\n\n /**\n * Run the `broadcast` strategy (fan-out, no combine) — every participant\n * answers the raw prompt in parallel; all raw responses are returned.\n */\n async broadcast(\n request: BroadcastRequest,\n options?: CombineOptions,\n ): Promise<BroadcastResult> {\n const { roster } = this.#prepare(request);\n this.#rejectResponseFormat(request, \"broadcast\");\n return runBroadcast(roster, request, options?.onEvent);\n }\n\n /**\n * Shared combine validation: normalize the participant specs, enforce ≥1\n * participant with unique ids, require ≥1 message, and reject tool calling\n * (no strategy supports it). Returns the resolved roster, the participant ids,\n * and the first participant's id (the default consensus synthesizer).\n */\n #prepare(request: CombineRequestBase): {\n roster: RosterEntry[];\n ids: string[];\n firstId: string;\n } {\n // Normalize each participant spec to its id + provider + per-participant\n // overrides. Two participants resolving to the same id (e.g. the same\n // provider+model twice without an explicit `label`) is rejected.\n const normalized = request.participants.map((spec) =>\n normalizeParticipant(spec),\n );\n const [first] = normalized;\n if (first === undefined) {\n throw new Error(\"combine requires at least one participant\");\n }\n const ids = normalized.map((p) => p.id);\n if (new Set(ids).size !== ids.length) {\n throw new Error(\n `combine participant labels must be unique: ${ids.join(\", \")}. ` +\n \"Set a distinct `label` when two participants share a provider and model.\",\n );\n }\n if (request.messages.length === 0) {\n throw new Error(\"combine requires at least one message\");\n }\n // No combine strategy does tool calling (a multi-model tool loop has no\n // coherent shared state), and `completionFor` doesn't forward these — so\n // reject them loudly instead of silently ignoring a tools-bearing request.\n if (request.tools !== undefined || request.toolChoice !== undefined) {\n throw new Error(\n \"combine does not support tool calling (tools/toolChoice); use registry.select() for a single-provider tool loop.\",\n );\n }\n const roster: RosterEntry[] = normalized.map((p) => ({\n ...p,\n provider: this.select(p.providerName),\n }));\n return { roster, ids, firstId: first.id };\n }\n\n /**\n * Reject `responseFormat` on a non-ensemble strategy. It only means something\n * for ensemble (where every participant answers under the schema); on the prose\n * strategies it would be silently forwarded, so reject it loudly instead.\n */\n #rejectResponseFormat(\n request: CombineRequestBase,\n strategy: StrategyName,\n ): void {\n if (request.responseFormat !== undefined) {\n throw new Error(\n `responseFormat is only supported by the \"ensemble\" strategy, not \"${strategy}\".`,\n );\n }\n }\n\n /** Validate the consensus-only request options (`minParticipants`, `synthesizer`). */\n #validateConsensusOptions(request: ConsensusRequest, ids: string[]): void {\n const { minParticipants } = request;\n if (minParticipants !== undefined) {\n if (!Number.isInteger(minParticipants) || minParticipants < 1) {\n throw new Error(\"combine minParticipants must be a positive integer\");\n }\n if (minParticipants > ids.length) {\n throw new Error(\n `combine minParticipants (${String(minParticipants)}) cannot exceed the number of participants (${String(ids.length)})`,\n );\n }\n }\n if (\n request.synthesizer !== undefined &&\n !ids.includes(request.synthesizer)\n ) {\n throw new Error(\n `Synthesizer \"${request.synthesizer}\" must be one of the participants: ${ids.join(\", \")}`,\n );\n }\n }\n\n /** Whether a provider is configured under `name`. */\n has(name: string): boolean {\n return this.#providers.has(name);\n }\n\n /** The names of all configured providers. */\n names(): ProviderName[] {\n return [...this.#providers.keys()];\n }\n\n #configuredList(): string {\n const names = this.names();\n return names.length > 0 ? names.join(\", \") : \"(none)\";\n }\n}\n\n/**\n * Resolve a {@link ParticipantSpec} to its id, provider name, and per-participant\n * overrides. A bare string uses the provider's default model and an id equal to\n * the provider name; the object form derives the id as `<provider>-<model>` when a\n * model is set (else the provider name), unless an explicit `label` is given.\n */\nfunction normalizeParticipant(\n spec: ParticipantSpec,\n): Omit<RosterEntry, \"provider\"> {\n if (typeof spec === \"string\") {\n return { id: spec, providerName: spec };\n }\n // Reject falsy overrides up front: `??` in completionFor preserves \"\" / 0, so an\n // empty model would be sent to the API (and yield a malformed `<provider>-` id)\n // and a non-positive maxTokens would truncate — omit the field to use the default.\n if (spec.model?.trim() === \"\") {\n throw new Error(\n `combine participant for \"${spec.provider}\" has an empty model; omit \\`model\\` to use the default.`,\n );\n }\n if (\n spec.maxTokens !== undefined &&\n (!Number.isInteger(spec.maxTokens) || spec.maxTokens < 1)\n ) {\n throw new Error(\n `combine participant for \"${spec.provider}\" has an invalid maxTokens (${String(spec.maxTokens)}); must be a positive integer.`,\n );\n }\n const id =\n spec.label ??\n (spec.model === undefined\n ? spec.provider\n : `${spec.provider}-${spec.model}`);\n return {\n id,\n providerName: spec.provider,\n model: spec.model,\n maxTokens: spec.maxTokens,\n };\n}\n\n/** Build the {@link Provider} for a custom registry entry registered under `name`. */\nfunction constructCustom(name: string, custom: CustomProviderConfig): Provider {\n switch (custom.kind) {\n case \"openai-compatible\":\n // The OpenAI provider already speaks Chat Completions against any baseUrl,\n // so an OpenAI-compatible gateway is just it pointed elsewhere. Pass `name`\n // so its errors attribute to this gateway, not a hardcoded \"openai\".\n return new OpenAIProvider(\n {\n apiKey: custom.apiKey,\n baseUrl: custom.baseUrl,\n model: custom.model,\n headers: custom.headers,\n retry: custom.retry,\n },\n name,\n );\n case \"provider\":\n return custom.provider;\n default: {\n // Exhaustiveness guard: a future `kind` added without a case here becomes a\n // compile error rather than silently returning undefined (noImplicitReturns\n // is off). Mirrors the strategy switch in combine().\n const unreachable: never = custom;\n throw new Error(\n `Unhandled custom provider kind: ${JSON.stringify(unreachable)}`,\n );\n }\n }\n}\n","/**\n * Typed provider errors. Every provider throws a {@link ProviderError} so\n * consumers can branch on `err.status` / `err.kind` / `err.code` instead of\n * regex-matching a message string.\n */\n\nimport { type ProviderName } from \"./registry\";\n\n/**\n * Whether the failure happened after the provider responded (`\"api\"` — an\n * HTTP error status, so `status` is set) or before any response arrived\n * (`\"transport\"` — a network/DNS failure or an aborted request, so `status` is\n * undefined). Branch on this to tell \"the provider said no\" from \"we never\n * reached the provider\".\n */\nexport type ProviderErrorKind = \"api\" | \"transport\";\n\ntype ProviderErrorInit = {\n provider: ProviderName;\n kind: ProviderErrorKind;\n status?: number;\n code?: string;\n type?: string;\n body?: string;\n cause?: unknown;\n};\n\n/** An error from a provider call, carrying enough structure to handle it programmatically. */\nexport class ProviderError extends Error {\n override readonly name = \"ProviderError\";\n /** Which provider produced the failure. */\n readonly provider: ProviderName;\n /** Transport failure (no response) vs API failure (error response). */\n readonly kind: ProviderErrorKind;\n /** HTTP status for `kind: \"api\"`; `undefined` for transport failures. */\n readonly status?: number;\n /** Machine-readable code parsed from the error body, where the provider sends one. */\n readonly code?: string;\n /** Error category parsed from the body (Anthropic/OpenAI `type`, Gemini `status`). */\n readonly type?: string;\n /** The raw response body, for `kind: \"api\"`. */\n readonly body?: string;\n\n constructor(message: string, init: ProviderErrorInit) {\n super(\n message,\n init.cause === undefined ? undefined : { cause: init.cause },\n );\n this.provider = init.provider;\n this.kind = init.kind;\n this.status = init.status;\n this.code = init.code;\n this.type = init.type;\n this.body = init.body;\n }\n}\n\n/**\n * Build an `api` {@link ProviderError} from a non-2xx response, parsing the\n * provider's error body for a machine `code`/`type` where present.\n */\nexport async function apiError(\n provider: ProviderName,\n response: Response,\n): Promise<ProviderError> {\n const body = await response.text();\n const { code, type } = parseErrorBody(body);\n return new ProviderError(\n `${provider} request failed (${String(response.status)}): ${body}`,\n { provider, kind: \"api\", status: response.status, code, type, body },\n );\n}\n\n/**\n * Build an `api` {@link ProviderError} from a 2xx response whose JSON body\n * nevertheless carries an `{ error }` payload (a provider or proxy returning\n * HTTP 200 with an error). Mirrors {@link apiError} but for an already-parsed\n * success-status body, so the call surfaces as a typed failure instead of a\n * silent empty result.\n */\nexport function apiErrorFromBody(\n provider: ProviderName,\n status: number,\n data: unknown,\n): ProviderError {\n const body = JSON.stringify(data);\n const { code, type } = parseErrorFields(data);\n return new ProviderError(\n `${provider} request failed (${String(status)}): ${body}`,\n { provider, kind: \"api\", status, code, type, body },\n );\n}\n\n/**\n * Build the error for a batch operation that produced no usable result. When some\n * sub-operations actually failed, their errors are attached as an\n * {@link AggregateError} (`.errors`) so the caller can inspect each underlying\n * cause; when `causes` is empty (the batch yielded nothing usable but nothing\n * threw), a plain {@link Error} is returned. `message` is preserved on both, so\n * message-based assertions hold either way. Provider/feature-agnostic — the caller\n * supplies the causes it collected.\n */\nexport function aggregateError(message: string, causes: Error[]): Error {\n return causes.length > 0\n ? new AggregateError(causes, message)\n : new Error(message);\n}\n\n/**\n * Pull a machine `code`/`type` out of an error body across the three vendors'\n * shapes: all nest the detail under `error`; the human code is OpenAI's\n * `error.code` (a string — Gemini's `code` is the numeric HTTP status, so it's\n * skipped), and the category is `error.type` (Anthropic/OpenAI) or `error.status`\n * (Gemini).\n */\nfunction parseErrorBody(body: string): { code?: string; type?: string } {\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n return {};\n }\n return parseErrorFields(parsed);\n}\n\n/** Extract `code`/`type` from an already-parsed error body (see {@link parseErrorBody}). */\nfunction parseErrorFields(parsed: unknown): { code?: string; type?: string } {\n if (!isRecord(parsed)) {\n return {};\n }\n const error = isRecord(parsed.error) ? parsed.error : parsed;\n const code = typeof error.code === \"string\" ? error.code : undefined;\n const type =\n typeof error.type === \"string\"\n ? error.type\n : typeof error.status === \"string\"\n ? error.status\n : undefined;\n return { code, type };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n"]}