fascicle 0.11.1 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import { A as aborted_error } from "./core-DgH4mDbK.js";
2
- import { n as default_normalize_usage, r as load_optional_peer, t as split_leading_system_run } from "./leading_system-CpkjHoCQ.js";
1
+ import { P as aborted_error } from "./core-DDRhHu5P.js";
2
+ import { i as load_optional_peer, n as split_leading_system_run, r as default_normalize_usage } from "./engine-b4ZH8esY.js";
3
3
  import { NoObjectGeneratedError, Output, generateText, isStepCount, streamText, tool } from "ai";
4
4
  //#region src/engine/providers/ai_sdk/telemetry.ts
5
5
  /**
@@ -483,4 +483,4 @@ function create_ai_sdk_turn(cfg) {
483
483
  //#endregion
484
484
  export { create_ai_sdk_turn, default_usage_from_sdk, map_finish_reason, map_stream_part_to_chunk, split_leading_system, to_provider_reported, to_raw_provider_usage, to_sdk_messages, to_sdk_tools };
485
485
 
486
- //# sourceMappingURL=invoke-BjrbCBSV.js.map
486
+ //# sourceMappingURL=invoke-CyKNhvBw.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"invoke-BjrbCBSV.js","names":["ai_tool"],"sources":["../src/engine/providers/ai_sdk/telemetry.ts","../src/engine/providers/ai_sdk/invoke.ts"],"sourcesContent":["/**\n * AI SDK telemetry wiring, confined to the ai_sdk transport.\n *\n * `@ai-sdk/otel` is adopted strictly below the turn seam: it instruments one\n * turn inside this module, never the loop. The peer is loaded lazily and only\n * when telemetry is explicitly enabled, so the disabled default (every call\n * that does not opt in) pulls in nothing.\n *\n * This is the ONLY place `@ai-sdk/otel` is referenced. generate.ts and\n * create_engine.ts thread a plain `AiSdkTelemetrySettings` value through the\n * seam and stay SDK-agnostic; loop-level, transport-neutral tracing is the\n * separate `fascicle/otel` bridge.\n */\n\nimport type { AiSdkTelemetrySettings } from '../../types.js'\nimport { load_optional_peer } from '../types.js'\n\ntype OpenTelemetryCtor = new (options?: { tracer?: unknown }) => unknown\n\ntype AiSdkOtelModule = {\n readonly OpenTelemetry: OpenTelemetryCtor\n}\n\n/**\n * The subset of the AI SDK's telemetry option shape this module produces, using\n * the SDK's own (camelCase) keys. Cast onto `experimental_telemetry` at the\n * call site.\n */\nexport type AiSdkTelemetryPassthrough = {\n isEnabled: true\n integrations: unknown[]\n functionId?: string\n recordInputs?: boolean\n recordOutputs?: boolean\n metadata?: Readonly<Record<string, string | number | boolean>>\n}\n\n/**\n * Build the AI SDK's `experimental_telemetry` option from engine settings,\n * loading the `@ai-sdk/otel` peer only when telemetry is enabled.\n */\nexport async function build_ai_sdk_telemetry(\n settings: AiSdkTelemetrySettings | undefined,\n): Promise<AiSdkTelemetryPassthrough | undefined> {\n if (!settings?.enabled) return undefined\n const mod = await load_optional_peer<AiSdkOtelModule>('@ai-sdk/otel')\n const integration = new mod.OpenTelemetry(\n settings.tracer !== undefined ? { tracer: settings.tracer } : {},\n )\n const out: AiSdkTelemetryPassthrough = { isEnabled: true, integrations: [integration] }\n if (settings.function_id !== undefined) out.functionId = settings.function_id\n if (settings.record_inputs !== undefined) out.recordInputs = settings.record_inputs\n if (settings.record_outputs !== undefined) out.recordOutputs = settings.record_outputs\n if (settings.metadata !== undefined) out.metadata = settings.metadata\n return out\n}\n","/**\n * The ai_sdk transport: the engine's only Vercel AI SDK call site.\n *\n * Only this module imports from `ai` or invokes generateText / streamText.\n * generate.ts drives this transport through create_ai_sdk_turn and stays\n * SDK-agnostic; run_tool_loop sees the same neutral TurnResult a native\n * adapter produces. Enforced by rules/no-ai-import-outside-ai-sdk-provider.yml.\n *\n * Retry stays out of this module on purpose: generate.ts wraps the turn\n * returned here in the engine-owned retry_turn, exactly as it wraps a native\n * adapter's invoke_turn. This module owns request/response mapping only.\n */\n\nimport {\n generateText,\n NoObjectGeneratedError,\n Output,\n isStepCount,\n streamText,\n tool as ai_tool,\n type LanguageModel,\n type ModelMessage,\n type TextStreamPart,\n type ToolSet,\n} from 'ai'\nimport type { ToolSchema } from '#schema'\nimport type {\n AiSdkTelemetrySettings,\n FinishReason,\n Message,\n StreamChunk,\n Tool,\n TurnResult,\n UsageTotals,\n} from '../../types.js'\nimport { aborted_error } from '../../errors.js'\nimport { split_leading_system_run } from '../../leading_system.js'\nimport type { ChunkDispatcher } from '../../streaming.js'\nimport type { RawToolCall } from '../../tool_loop.js'\nimport {\n default_normalize_usage,\n type AiSdkProviderAdapter,\n type RawProviderUsage,\n} from '../types.js'\nimport { build_ai_sdk_telemetry, type AiSdkTelemetryPassthrough } from './telemetry.js'\n\n/**\n * Map the AI SDK's finish reason string to the engine's FinishReason.\n */\nexport function map_finish_reason(raw: string | undefined): FinishReason {\n switch (raw) {\n case 'stop':\n return 'stop'\n case 'length':\n return 'length'\n case 'content-filter':\n case 'content_filter':\n return 'content_filter'\n case 'tool-calls':\n case 'tool_calls':\n return 'tool_calls'\n default:\n return 'stop'\n }\n}\n\n/**\n * Read a numeric field off an object by key, or undefined when it is absent or\n * not a number. The single typeof guard behind every usage-field read below.\n */\nfunction read_number(source: object, key: string): number | undefined {\n const value = Reflect.get(source, key)\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Read the AI SDK's nested `inputTokenDetails` (cache read/write counts) onto\n * `raw`. Present-but-empty details still seed `input_token_details` so the\n * \"the SDK reported details\" signal survives even when both counts are absent.\n */\nfunction read_input_details(usage: object, raw: RawProviderUsage): void {\n const details = Reflect.get(usage, 'inputTokenDetails')\n if (details === null || typeof details !== 'object') return\n raw.input_token_details = {}\n const cache_read = read_number(details, 'cacheReadTokens')\n if (cache_read !== undefined) raw.input_token_details.cached_tokens = cache_read\n const cache_write = read_number(details, 'cacheWriteTokens')\n if (cache_write !== undefined) raw.input_token_details.cache_creation_input_tokens = cache_write\n}\n\n/**\n * Read the AI SDK's nested `outputTokenDetails` (reasoning-token count) onto\n * `raw`, seeding `output_token_details` whenever the details object is present.\n */\nfunction read_output_details(usage: object, raw: RawProviderUsage): void {\n const details = Reflect.get(usage, 'outputTokenDetails')\n if (details === null || typeof details !== 'object') return\n raw.output_token_details = {}\n const reasoning = read_number(details, 'reasoningTokens')\n if (reasoning !== undefined) raw.output_token_details.reasoning_tokens = reasoning\n}\n\n/**\n * Read the flattened snake_case usage fields some provider mocks return\n * directly. The `input_tokens`/`output_tokens` flats are fallbacks: they fill\n * in only when the camelCase read did not already set the same total.\n */\nfunction read_flat_usage(usage: object, raw: RawProviderUsage): void {\n const cached = read_number(usage, 'cached_input_tokens')\n if (cached !== undefined) raw.cached_input_tokens = cached\n const cache_write = read_number(usage, 'cache_write_tokens')\n if (cache_write !== undefined) raw.cache_write_tokens = cache_write\n const reasoning = read_number(usage, 'reasoning_tokens')\n if (reasoning !== undefined) raw.reasoning_tokens = reasoning\n const input_flat = read_number(usage, 'input_tokens')\n if (raw.input_tokens === undefined && input_flat !== undefined) raw.input_tokens = input_flat\n const output_flat = read_number(usage, 'output_tokens')\n if (raw.output_tokens === undefined && output_flat !== undefined) raw.output_tokens = output_flat\n}\n\n/**\n * Extract the usage fields `default_normalize_usage` understands from an AI\n * SDK usage object, tolerating both the SDK's camelCase shape and the\n * flattened snake_case fields some provider mocks return directly.\n */\nexport function to_raw_provider_usage(usage: unknown): RawProviderUsage {\n if (usage === null || typeof usage !== 'object') return {}\n const raw: RawProviderUsage = {}\n const input_tokens = read_number(usage, 'inputTokens')\n if (input_tokens !== undefined) raw.input_tokens = input_tokens\n const output_tokens = read_number(usage, 'outputTokens')\n if (output_tokens !== undefined) raw.output_tokens = output_tokens\n read_input_details(usage, raw)\n read_output_details(usage, raw)\n read_flat_usage(usage, raw)\n return raw\n}\n\n/**\n * Normalize an AI SDK `providerMetadata` value into the neutral\n * TurnResult.provider_reported shape.\n *\n * The SDK's metadata is already keyed by provider name, which is the shape\n * provider_reported documents, so the keys ride through untranslated and every\n * ai_sdk provider is served by this one seam: bedrock's guardrail `trace`,\n * anthropic's cache detail, openai's own fields. The payloads stay opaque\n * (callers narrow them at the use site), so this copies the top level and\n * inspects nothing below it. An absent or empty map returns undefined, keeping\n * \"the provider reported nothing\" spelled one way.\n */\nexport function to_provider_reported(metadata: unknown): Record<string, unknown> | undefined {\n if (metadata === null || typeof metadata !== 'object') return undefined\n const keys = Object.keys(metadata)\n if (keys.length === 0) return undefined\n const reported: Record<string, unknown> = {}\n for (const key of keys) reported[key] = Reflect.get(metadata, key)\n return reported\n}\n\n/**\n * Map fascicle's Message[] to the AI SDK's ModelMessage[] shape.\n */\nexport function to_sdk_messages(messages: ReadonlyArray<Message>): ModelMessage[] {\n const out: ModelMessage[] = []\n for (const m of messages) {\n if (m.role === 'system') {\n out.push({ role: 'system', content: m.content })\n continue\n }\n if (m.role === 'user') {\n if (typeof m.content === 'string') {\n out.push({ role: 'user', content: m.content })\n } else {\n const parts: Array<\n | { type: 'text'; text: string }\n | { type: 'image'; image: string | Uint8Array; mediaType?: string }\n > = m.content.map((p) => {\n if (p.type === 'text') return { type: 'text', text: p.text }\n const image_part: { type: 'image'; image: string | Uint8Array; mediaType?: string } = {\n type: 'image',\n image: p.image,\n }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n return image_part\n })\n out.push({ role: 'user', content: parts })\n }\n continue\n }\n if (m.role === 'tool') {\n out.push({\n role: 'tool',\n content: [\n {\n type: 'tool-result',\n toolCallId: m.tool_call_id,\n toolName: m.name,\n output: { type: 'text', value: m.content },\n },\n ],\n })\n continue\n }\n // assistant\n if (typeof m.content === 'string') {\n out.push({ role: 'assistant', content: m.content })\n continue\n }\n const parts = m.content.map((p) => {\n if (p.type === 'text') return { type: 'text' as const, text: p.text }\n return {\n type: 'tool-call' as const,\n toolCallId: p.id,\n toolName: p.name,\n input: p.input,\n }\n })\n out.push({ role: 'assistant', content: parts })\n }\n return out\n}\n\n/**\n * Hoist a leading run of system messages out of the SDK message list into the\n * AI SDK's top-level `system` option.\n *\n * Passing a `role: 'system'` entry inside `messages` makes the AI SDK treat it\n * as potentially attacker-controlled: it warns on every call (and newer `ai`\n * versions throw unless `allowSystemInMessages` is set). fascicle's system\n * content is the developer's own prompt, and the SDK's own recommendation is to\n * deliver it through the top-level `instructions` option (v7's rename of the\n * former `system` option), which removes the warning at its source rather than\n * suppressing it.\n *\n * Only the *leading* run is hoisted (fascicle's only shape: one or more system\n * messages, then the conversation). A system message that appears after a\n * non-system message keeps its position rather than being silently reordered to\n * the top, and the original list is returned untouched when hoisting would leave\n * `messages` empty, since the SDK rejects an empty messages array.\n */\nexport function split_leading_system(messages: ReadonlyArray<ModelMessage>): {\n system?: string\n messages: ModelMessage[]\n} {\n return split_leading_system_run(messages, (m) => m.content)\n}\n\n/**\n * Map fascicle's Tool[] to the AI SDK's ToolSet.\n *\n * Returns undefined for an empty tool list so the caller can omit `tools`\n * from the call params entirely instead of passing an empty object.\n */\nexport function to_sdk_tools(tools: ReadonlyArray<Tool>): ToolSet | undefined {\n if (tools.length === 0) return undefined\n const entries: ToolSet = {}\n for (const t of tools) {\n entries[t.name] = ai_tool({\n description: t.description,\n inputSchema: t.input_schema,\n })\n }\n return entries\n}\n\n/**\n * Map one AI SDK stream part to the engine's StreamChunk shape, or undefined\n * for a part kind the engine does not model.\n */\nexport function map_stream_part_to_chunk(\n part: TextStreamPart<ToolSet>,\n step_index: number,\n): StreamChunk | undefined {\n switch (part.type) {\n case 'text-delta':\n return { kind: 'text', text: part.text, step_index }\n case 'reasoning-delta':\n return { kind: 'reasoning', text: part.text, step_index }\n case 'tool-input-start':\n return {\n kind: 'tool_call_start',\n id: part.id,\n name: part.toolName,\n step_index,\n }\n case 'tool-input-delta':\n return {\n kind: 'tool_call_input_delta',\n id: part.id,\n delta: part.delta,\n step_index,\n }\n case 'tool-call':\n return {\n kind: 'tool_call_end',\n id: part.toolCallId,\n input: part.input,\n step_index,\n }\n case 'finish-step':\n return {\n kind: 'step_finish',\n step_index,\n finish_reason: map_finish_reason(part.finishReason),\n usage: default_usage_from_sdk(part.usage),\n }\n default:\n // v7 parts with no engine StreamChunk kind (file, reasoning-file,\n // source, block framing) drop here on purpose: the engine models\n // text, reasoning, and tool traffic, not generated files.\n return undefined\n }\n}\n\n/**\n * Normalize a raw AI SDK usage object into UsageTotals for a streamed\n * step_finish chunk.\n */\nexport function default_usage_from_sdk(usage: unknown): UsageTotals {\n // Streamed step_finish chunks must carry the same cache/reasoning\n // granularity the step record gets via adapter.normalize_usage; every\n // built-in adapter routes through default_normalize_usage, so this keeps\n // the chunk surface consistent with the non-streamed result.\n return default_normalize_usage(to_raw_provider_usage(usage))\n}\n\n/**\n * The running TurnResult fields collect_stream builds as it consumes the SDK\n * stream: text and tool calls accrue across parts, while finish reason, usage,\n * and provider_reported are overwritten by the terminal finish-step.\n */\ntype StreamAccumulator = {\n text: string\n tool_calls: RawToolCall[]\n finish_reason: FinishReason\n raw_usage: RawProviderUsage\n provider_reported: Record<string, unknown> | undefined\n}\n\n/**\n * Fold one stream part's accumulated state into `acc`: text deltas append,\n * tool-call parts push a RawToolCall, and the finish-step overwrites finish\n * reason, usage, and provider_reported. The finish-step's providerMetadata is\n * the same value generateText returns on its result, which is what keeps a\n * streamed run's provider_reported identical to a plain run's. Parts with no\n * accumulated state (error, abort, stream framing) are the caller's to handle.\n */\nfunction accumulate_stream_part(part: TextStreamPart<ToolSet>, acc: StreamAccumulator): void {\n if (part.type === 'text-delta') {\n acc.text += part.text\n return\n }\n if (part.type === 'tool-call') {\n acc.tool_calls.push({\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n })\n return\n }\n if (part.type === 'finish-step') {\n acc.finish_reason = map_finish_reason(part.finishReason)\n acc.raw_usage = to_raw_provider_usage(part.usage)\n acc.provider_reported = to_provider_reported(part.providerMetadata)\n }\n}\n\n/**\n * Run one streamText call, dispatching StreamChunks as parts arrive and\n * accumulating them into a TurnResult once the stream completes.\n */\nasync function collect_stream(\n params: Parameters<typeof streamText>[0],\n step_index: number,\n dispatcher: ChunkDispatcher,\n on_first_chunk: () => void,\n internal_controller: AbortController,\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n const stream_result = streamText(params)\n const acc: StreamAccumulator = {\n text: '',\n tool_calls: [],\n finish_reason: 'stop',\n raw_usage: {},\n provider_reported: undefined,\n }\n let first = true\n\n for await (const part of stream_result.stream) {\n if (first) {\n first = false\n on_first_chunk()\n }\n accumulate_stream_part(part, acc)\n if (part.type === 'error') {\n throw part.error\n }\n if (part.type === 'abort') {\n throw new aborted_error('aborted', { step_index })\n }\n const chunk = map_stream_part_to_chunk(part, step_index)\n if (chunk === undefined) continue\n try {\n await dispatcher.dispatch(chunk)\n } catch (err: unknown) {\n internal_controller.abort()\n throw err\n }\n }\n\n return {\n text: acc.text,\n tool_calls: acc.tool_calls,\n finish_reason: acc.finish_reason,\n usage: adapter.normalize_usage(acc.raw_usage),\n // Stryker disable next-line ConditionalExpression: an always-true spread only adds an explicit `provider_reported: undefined` key, which every reader of TurnResult treats identically to the absent key.\n ...(acc.provider_reported !== undefined ? { provider_reported: acc.provider_reported } : {}),\n }\n}\n\n/**\n * Run one generateText call and map its result into a TurnResult, recovering\n * a schema-validation failure from the SDK via recover_no_object_generated\n * instead of letting it throw.\n */\nasync function collect_non_stream(\n params: Parameters<typeof generateText>[0],\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n let result: Awaited<ReturnType<typeof generateText>>\n try {\n result = await generateText(params)\n } catch (err: unknown) {\n const recovered = recover_no_object_generated(err, adapter)\n if (recovered !== undefined) return recovered\n throw err\n }\n const tool_calls: RawToolCall[] = []\n for (const tc of result.toolCalls) {\n tool_calls.push({\n id: tc.toolCallId,\n name: tc.toolName,\n input: tc.input,\n })\n }\n const raw_usage = to_raw_provider_usage(result.usage)\n // result.providerMetadata rather than result.finalStep.providerMetadata: the\n // two are the same value under stopWhen isStepCount(1), and the flat field\n // exists across the whole `ai` ^7 peer range this package declares.\n const provider_reported = to_provider_reported(result.providerMetadata)\n return {\n text: result.text,\n tool_calls,\n finish_reason: map_finish_reason(result.finishReason),\n usage: adapter.normalize_usage(raw_usage),\n // Stryker disable next-line ConditionalExpression: see collect_stream; the always-true spread is unobservable through every TurnResult reader.\n ...(provider_reported !== undefined ? { provider_reported } : {}),\n }\n}\n\n/**\n * When `output` (structured output) is in play, `generateText` eagerly parses the\n * model's text against the schema and throws `NoObjectGeneratedError` if it\n * does not conform. That parse is the SDK's, not fascicle's: turning it into a\n * thrown error would skip the engine's own schema-parse + repair loop (and the\n * error is not a retryable transient, so it would surface raw). Instead we\n * recover the model's raw text from the error and hand it back as a normal\n * turn result, so `parse_with_schema` re-validates it and the repair loop\n * engages exactly as it does for the prompt-based path. Returns undefined for\n * any other error so the caller rethrows.\n *\n * The recovered turn carries no provider_reported: the SDK's error exposes\n * text, usage, finishReason and response metadata, but not providerMetadata,\n * so there is nothing to read. The repair turn that follows reports normally.\n */\nfunction recover_no_object_generated(\n err: unknown,\n adapter: AiSdkProviderAdapter,\n): TurnResult | undefined {\n if (!NoObjectGeneratedError.isInstance(err)) return undefined\n const text_field = Reflect.get(err, 'text')\n const finish_field = Reflect.get(err, 'finishReason')\n const raw_usage = to_raw_provider_usage(Reflect.get(err, 'usage'))\n return {\n text: typeof text_field === 'string' ? text_field : '',\n tool_calls: [],\n finish_reason: map_finish_reason(typeof finish_field === 'string' ? finish_field : undefined),\n usage: adapter.normalize_usage(raw_usage),\n }\n}\n\ntype AiSdkCallParams = Parameters<typeof streamText>[0] & Parameters<typeof generateText>[0]\n\nexport type AiSdkTurnConfig = {\n readonly adapter: AiSdkProviderAdapter\n readonly model_id: string\n readonly dispatcher: ChunkDispatcher\n readonly tools: ReadonlyArray<Tool>\n readonly schema: ToolSchema | undefined\n readonly provider_options: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined\n readonly temperature: number | undefined\n readonly max_tokens: number | undefined\n readonly top_p: number | undefined\n readonly telemetry: AiSdkTelemetrySettings | undefined\n}\n\nexport type AiSdkTurnArgs = {\n readonly step_index: number\n readonly messages: ReadonlyArray<Message>\n readonly abort: AbortSignal\n readonly stream: boolean\n readonly on_first_chunk: () => void\n}\n\nexport type AiSdkTurn = (args: AiSdkTurnArgs) => Promise<TurnResult>\n\n/**\n * Build the single-attempt SDK turn for one generate call: the\n * generateText/streamText call body behind the same neutral seam a native\n * adapter's invoke_turn implements. The built model is memoized across steps\n * of one generate call. No retry here: generate.ts wraps the returned turn in\n * the engine-owned retry_turn.\n */\nexport function create_ai_sdk_turn(cfg: AiSdkTurnConfig): AiSdkTurn {\n let model_instance: LanguageModel | undefined\n const get_model = async (): Promise<LanguageModel> => {\n if (model_instance === undefined) {\n const built = await cfg.adapter.build_model(cfg.model_id)\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n model_instance = built as LanguageModel\n }\n return model_instance\n }\n\n // Telemetry is resolved once per generate call and memoized across its steps,\n // mirroring get_model. build_ai_sdk_telemetry returns undefined immediately\n // (no peer load) unless telemetry is explicitly enabled, so the disabled\n // default costs nothing.\n let telemetry_options: AiSdkTelemetryPassthrough | undefined\n let telemetry_resolved = false\n const get_telemetry = async (): Promise<AiSdkTelemetryPassthrough | undefined> => {\n if (!telemetry_resolved) {\n telemetry_options = await build_ai_sdk_telemetry(cfg.telemetry)\n telemetry_resolved = true\n }\n return telemetry_options\n }\n\n const sdk_tools = to_sdk_tools(cfg.tools)\n\n // Native structured output: when a schema is requested and the provider\n // constrains decoding to it (the 'structured_output' capability), route\n // through the AI SDK's Output.object seam so the schema becomes the\n // provider's responseFormat (e.g. Ollama's `format`) instead of a\n // prompt-for-JSON-then-scrape. Gated on no tools: forcing a JSON\n // responseFormat alongside tool calls breaks tool dispatch on most\n // providers, so tool runs keep the prompt-based schema path. The engine's\n // schema parse + repair loop still owns validation either way. This seam\n // is ai_sdk-only: a native adapter that constrains decoding honors\n // TurnRequest.schema inside its own invoke_turn.\n let output_spec: NonNullable<AiSdkCallParams['output']> | undefined\n if (\n cfg.schema !== undefined &&\n cfg.tools.length === 0 &&\n cfg.adapter.supports('structured_output')\n ) {\n // Output.object<T> is not structurally assignable to the SDK's default\n // Output<string, string> param slot, but the runtime shape is exactly\n // what generateText/streamText consume to set responseFormat.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n output_spec = Output.object({ schema: cfg.schema }) as NonNullable<\n AiSdkCallParams['output']\n >\n }\n\n // provider_options is Record<string, Record<string, unknown>>; the SDK\n // expects SharedV3ProviderOptions (Record<string, JSONObject>) which is\n // structurally compatible for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const provider_options = cfg.provider_options as AiSdkCallParams['providerOptions']\n\n return async (args: AiSdkTurnArgs): Promise<TurnResult> => {\n const model = await get_model()\n const telemetry = await get_telemetry()\n const internal_controller = new AbortController()\n const cancel_on_user_abort = (): void => {\n internal_controller.abort(args.abort.reason)\n }\n if (args.abort.aborted) {\n internal_controller.abort(args.abort.reason)\n } else {\n args.abort.addEventListener('abort', cancel_on_user_abort, { once: true })\n }\n const { system: hoisted_system, messages: sdk_messages } = split_leading_system(\n to_sdk_messages(args.messages),\n )\n const base_params: AiSdkCallParams = {\n model,\n messages: sdk_messages,\n abortSignal: internal_controller.signal,\n stopWhen: isStepCount(1),\n // The engine owns retry via retry_turn in generate.ts; disable the AI\n // SDK's own retry (default 2) so it does not nest inside each of our\n // attempts and inflate provider round-trips / distort backoff.\n maxRetries: 0,\n }\n if (hoisted_system !== undefined) base_params.instructions = hoisted_system\n if (sdk_tools !== undefined) base_params.tools = sdk_tools\n if (output_spec !== undefined) base_params.output = output_spec\n if (provider_options !== undefined) base_params.providerOptions = provider_options\n if (cfg.temperature !== undefined) base_params.temperature = cfg.temperature\n if (cfg.max_tokens !== undefined) base_params.maxOutputTokens = cfg.max_tokens\n if (cfg.top_p !== undefined) base_params.topP = cfg.top_p\n if (telemetry !== undefined) {\n // AiSdkTelemetryPassthrough uses the SDK's own telemetry keys; the slot's\n // generic (RUNTIME_CONTEXT/TOOLS) is erased for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n base_params.experimental_telemetry = telemetry as NonNullable<\n AiSdkCallParams['experimental_telemetry']\n >\n }\n\n try {\n if (args.stream) {\n return await collect_stream(\n base_params,\n args.step_index,\n cfg.dispatcher,\n args.on_first_chunk,\n internal_controller,\n cfg.adapter,\n )\n }\n return await collect_non_stream(base_params, cfg.adapter)\n } finally {\n args.abort.removeEventListener('abort', cancel_on_user_abort)\n }\n }\n}\n"],"mappings":";;;;;;;;AAyCA,eAAsB,uBACpB,UACgD;CAChD,IAAI,CAAC,UAAU,SAAS,OAAO,KAAA;CAK/B,MAAM,MAAiC;EAAE,WAAW;EAAM,cAAc,CAAC,KAHjD,OADN,mBAAoC,cAAc,GAAA,CACxC,cAC1B,SAAS,WAAW,KAAA,IAAY,EAAE,QAAQ,SAAS,OAAO,IAAI,CAAC,CAEkB,CAAC;CAAE;CACtF,IAAI,SAAS,gBAAgB,KAAA,GAAW,IAAI,aAAa,SAAS;CAClE,IAAI,SAAS,kBAAkB,KAAA,GAAW,IAAI,eAAe,SAAS;CACtE,IAAI,SAAS,mBAAmB,KAAA,GAAW,IAAI,gBAAgB,SAAS;CACxE,IAAI,SAAS,aAAa,KAAA,GAAW,IAAI,WAAW,SAAS;CAC7D,OAAO;AACT;;;;;;;;;;;;;;;;;;ACNA,SAAgB,kBAAkB,KAAuC;CACvE,QAAQ,KAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK;EACL,KAAK,kBACH,OAAO;EACT,KAAK;EACL,KAAK,cACH,OAAO;EACT,SACE,OAAO;CACX;AACF;;;;;AAMA,SAAS,YAAY,QAAgB,KAAiC;CACpE,MAAM,QAAQ,QAAQ,IAAI,QAAQ,GAAG;CACrC,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;;;;;AAOA,SAAS,mBAAmB,OAAe,KAA6B;CACtE,MAAM,UAAU,QAAQ,IAAI,OAAO,mBAAmB;CACtD,IAAI,YAAY,QAAQ,OAAO,YAAY,UAAU;CACrD,IAAI,sBAAsB,CAAC;CAC3B,MAAM,aAAa,YA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UAAU,KAAA,GAAW,YAAY,OAAO,IAAI;EACpD,IAAI,cAAc,KAAA,GAIhB,YAAY,yBAAyB;EAKvC,IAAI;GACF,IAAI,KAAK,QACP,OAAO,MAAM,eACX,aACA,KAAK,YACL,IAAI,YACJ,KAAK,gBACL,qBACA,IAAI,OACN;GAEF,OAAO,MAAM,mBAAmB,aAAa,IAAI,OAAO;EAC1D,UAAU;GACR,KAAK,MAAM,oBAAoB,SAAS,oBAAoB;EAC9D;CACF;AACF"}
1
+ {"version":3,"file":"invoke-CyKNhvBw.js","names":["ai_tool"],"sources":["../src/engine/providers/ai_sdk/telemetry.ts","../src/engine/providers/ai_sdk/invoke.ts"],"sourcesContent":["/**\n * AI SDK telemetry wiring, confined to the ai_sdk transport.\n *\n * `@ai-sdk/otel` is adopted strictly below the turn seam: it instruments one\n * turn inside this module, never the loop. The peer is loaded lazily and only\n * when telemetry is explicitly enabled, so the disabled default (every call\n * that does not opt in) pulls in nothing.\n *\n * This is the ONLY place `@ai-sdk/otel` is referenced. generate.ts and\n * create_engine.ts thread a plain `AiSdkTelemetrySettings` value through the\n * seam and stay SDK-agnostic; loop-level, transport-neutral tracing is the\n * separate `fascicle/otel` bridge.\n */\n\nimport type { AiSdkTelemetrySettings } from '../../types.js'\nimport { load_optional_peer } from '../types.js'\n\ntype OpenTelemetryCtor = new (options?: { tracer?: unknown }) => unknown\n\ntype AiSdkOtelModule = {\n readonly OpenTelemetry: OpenTelemetryCtor\n}\n\n/**\n * The subset of the AI SDK's telemetry option shape this module produces, using\n * the SDK's own (camelCase) keys. Cast onto `experimental_telemetry` at the\n * call site.\n */\nexport type AiSdkTelemetryPassthrough = {\n isEnabled: true\n integrations: unknown[]\n functionId?: string\n recordInputs?: boolean\n recordOutputs?: boolean\n metadata?: Readonly<Record<string, string | number | boolean>>\n}\n\n/**\n * Build the AI SDK's `experimental_telemetry` option from engine settings,\n * loading the `@ai-sdk/otel` peer only when telemetry is enabled.\n */\nexport async function build_ai_sdk_telemetry(\n settings: AiSdkTelemetrySettings | undefined,\n): Promise<AiSdkTelemetryPassthrough | undefined> {\n if (!settings?.enabled) return undefined\n const mod = await load_optional_peer<AiSdkOtelModule>('@ai-sdk/otel')\n const integration = new mod.OpenTelemetry(\n settings.tracer !== undefined ? { tracer: settings.tracer } : {},\n )\n const out: AiSdkTelemetryPassthrough = { isEnabled: true, integrations: [integration] }\n if (settings.function_id !== undefined) out.functionId = settings.function_id\n if (settings.record_inputs !== undefined) out.recordInputs = settings.record_inputs\n if (settings.record_outputs !== undefined) out.recordOutputs = settings.record_outputs\n if (settings.metadata !== undefined) out.metadata = settings.metadata\n return out\n}\n","/**\n * The ai_sdk transport: the engine's only Vercel AI SDK call site.\n *\n * Only this module imports from `ai` or invokes generateText / streamText.\n * generate.ts drives this transport through create_ai_sdk_turn and stays\n * SDK-agnostic; run_tool_loop sees the same neutral TurnResult a native\n * adapter produces. Enforced by rules/no-ai-import-outside-ai-sdk-provider.yml.\n *\n * Retry stays out of this module on purpose: generate.ts wraps the turn\n * returned here in the engine-owned retry_turn, exactly as it wraps a native\n * adapter's invoke_turn. This module owns request/response mapping only.\n */\n\nimport {\n generateText,\n NoObjectGeneratedError,\n Output,\n isStepCount,\n streamText,\n tool as ai_tool,\n type LanguageModel,\n type ModelMessage,\n type TextStreamPart,\n type ToolSet,\n} from 'ai'\nimport type { ToolSchema } from '#schema'\nimport type {\n AiSdkTelemetrySettings,\n FinishReason,\n Message,\n StreamChunk,\n Tool,\n TurnResult,\n UsageTotals,\n} from '../../types.js'\nimport { aborted_error } from '../../errors.js'\nimport { split_leading_system_run } from '../../leading_system.js'\nimport type { ChunkDispatcher } from '../../streaming.js'\nimport type { RawToolCall } from '../../tool_loop.js'\nimport {\n default_normalize_usage,\n type AiSdkProviderAdapter,\n type RawProviderUsage,\n} from '../types.js'\nimport { build_ai_sdk_telemetry, type AiSdkTelemetryPassthrough } from './telemetry.js'\n\n/**\n * Map the AI SDK's finish reason string to the engine's FinishReason.\n */\nexport function map_finish_reason(raw: string | undefined): FinishReason {\n switch (raw) {\n case 'stop':\n return 'stop'\n case 'length':\n return 'length'\n case 'content-filter':\n case 'content_filter':\n return 'content_filter'\n case 'tool-calls':\n case 'tool_calls':\n return 'tool_calls'\n default:\n return 'stop'\n }\n}\n\n/**\n * Read a numeric field off an object by key, or undefined when it is absent or\n * not a number. The single typeof guard behind every usage-field read below.\n */\nfunction read_number(source: object, key: string): number | undefined {\n const value = Reflect.get(source, key)\n return typeof value === 'number' ? value : undefined\n}\n\n/**\n * Read the AI SDK's nested `inputTokenDetails` (cache read/write counts) onto\n * `raw`. Present-but-empty details still seed `input_token_details` so the\n * \"the SDK reported details\" signal survives even when both counts are absent.\n */\nfunction read_input_details(usage: object, raw: RawProviderUsage): void {\n const details = Reflect.get(usage, 'inputTokenDetails')\n if (details === null || typeof details !== 'object') return\n raw.input_token_details = {}\n const cache_read = read_number(details, 'cacheReadTokens')\n if (cache_read !== undefined) raw.input_token_details.cached_tokens = cache_read\n const cache_write = read_number(details, 'cacheWriteTokens')\n if (cache_write !== undefined) raw.input_token_details.cache_creation_input_tokens = cache_write\n}\n\n/**\n * Read the AI SDK's nested `outputTokenDetails` (reasoning-token count) onto\n * `raw`, seeding `output_token_details` whenever the details object is present.\n */\nfunction read_output_details(usage: object, raw: RawProviderUsage): void {\n const details = Reflect.get(usage, 'outputTokenDetails')\n if (details === null || typeof details !== 'object') return\n raw.output_token_details = {}\n const reasoning = read_number(details, 'reasoningTokens')\n if (reasoning !== undefined) raw.output_token_details.reasoning_tokens = reasoning\n}\n\n/**\n * Read the flattened snake_case usage fields some provider mocks return\n * directly. The `input_tokens`/`output_tokens` flats are fallbacks: they fill\n * in only when the camelCase read did not already set the same total.\n */\nfunction read_flat_usage(usage: object, raw: RawProviderUsage): void {\n const cached = read_number(usage, 'cached_input_tokens')\n if (cached !== undefined) raw.cached_input_tokens = cached\n const cache_write = read_number(usage, 'cache_write_tokens')\n if (cache_write !== undefined) raw.cache_write_tokens = cache_write\n const reasoning = read_number(usage, 'reasoning_tokens')\n if (reasoning !== undefined) raw.reasoning_tokens = reasoning\n const input_flat = read_number(usage, 'input_tokens')\n if (raw.input_tokens === undefined && input_flat !== undefined) raw.input_tokens = input_flat\n const output_flat = read_number(usage, 'output_tokens')\n if (raw.output_tokens === undefined && output_flat !== undefined) raw.output_tokens = output_flat\n}\n\n/**\n * Extract the usage fields `default_normalize_usage` understands from an AI\n * SDK usage object, tolerating both the SDK's camelCase shape and the\n * flattened snake_case fields some provider mocks return directly.\n */\nexport function to_raw_provider_usage(usage: unknown): RawProviderUsage {\n if (usage === null || typeof usage !== 'object') return {}\n const raw: RawProviderUsage = {}\n const input_tokens = read_number(usage, 'inputTokens')\n if (input_tokens !== undefined) raw.input_tokens = input_tokens\n const output_tokens = read_number(usage, 'outputTokens')\n if (output_tokens !== undefined) raw.output_tokens = output_tokens\n read_input_details(usage, raw)\n read_output_details(usage, raw)\n read_flat_usage(usage, raw)\n return raw\n}\n\n/**\n * Normalize an AI SDK `providerMetadata` value into the neutral\n * TurnResult.provider_reported shape.\n *\n * The SDK's metadata is already keyed by provider name, which is the shape\n * provider_reported documents, so the keys ride through untranslated and every\n * ai_sdk provider is served by this one seam: bedrock's guardrail `trace`,\n * anthropic's cache detail, openai's own fields. The payloads stay opaque\n * (callers narrow them at the use site), so this copies the top level and\n * inspects nothing below it. An absent or empty map returns undefined, keeping\n * \"the provider reported nothing\" spelled one way.\n */\nexport function to_provider_reported(metadata: unknown): Record<string, unknown> | undefined {\n if (metadata === null || typeof metadata !== 'object') return undefined\n const keys = Object.keys(metadata)\n if (keys.length === 0) return undefined\n const reported: Record<string, unknown> = {}\n for (const key of keys) reported[key] = Reflect.get(metadata, key)\n return reported\n}\n\n/**\n * Map fascicle's Message[] to the AI SDK's ModelMessage[] shape.\n */\nexport function to_sdk_messages(messages: ReadonlyArray<Message>): ModelMessage[] {\n const out: ModelMessage[] = []\n for (const m of messages) {\n if (m.role === 'system') {\n out.push({ role: 'system', content: m.content })\n continue\n }\n if (m.role === 'user') {\n if (typeof m.content === 'string') {\n out.push({ role: 'user', content: m.content })\n } else {\n const parts: Array<\n | { type: 'text'; text: string }\n | { type: 'image'; image: string | Uint8Array; mediaType?: string }\n > = m.content.map((p) => {\n if (p.type === 'text') return { type: 'text', text: p.text }\n const image_part: { type: 'image'; image: string | Uint8Array; mediaType?: string } = {\n type: 'image',\n image: p.image,\n }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n return image_part\n })\n out.push({ role: 'user', content: parts })\n }\n continue\n }\n if (m.role === 'tool') {\n out.push({\n role: 'tool',\n content: [\n {\n type: 'tool-result',\n toolCallId: m.tool_call_id,\n toolName: m.name,\n output: { type: 'text', value: m.content },\n },\n ],\n })\n continue\n }\n // assistant\n if (typeof m.content === 'string') {\n out.push({ role: 'assistant', content: m.content })\n continue\n }\n const parts = m.content.map((p) => {\n if (p.type === 'text') return { type: 'text' as const, text: p.text }\n return {\n type: 'tool-call' as const,\n toolCallId: p.id,\n toolName: p.name,\n input: p.input,\n }\n })\n out.push({ role: 'assistant', content: parts })\n }\n return out\n}\n\n/**\n * Hoist a leading run of system messages out of the SDK message list into the\n * AI SDK's top-level `system` option.\n *\n * Passing a `role: 'system'` entry inside `messages` makes the AI SDK treat it\n * as potentially attacker-controlled: it warns on every call (and newer `ai`\n * versions throw unless `allowSystemInMessages` is set). fascicle's system\n * content is the developer's own prompt, and the SDK's own recommendation is to\n * deliver it through the top-level `instructions` option (v7's rename of the\n * former `system` option), which removes the warning at its source rather than\n * suppressing it.\n *\n * Only the *leading* run is hoisted (fascicle's only shape: one or more system\n * messages, then the conversation). A system message that appears after a\n * non-system message keeps its position rather than being silently reordered to\n * the top, and the original list is returned untouched when hoisting would leave\n * `messages` empty, since the SDK rejects an empty messages array.\n */\nexport function split_leading_system(messages: ReadonlyArray<ModelMessage>): {\n system?: string\n messages: ModelMessage[]\n} {\n return split_leading_system_run(messages, (m) => m.content)\n}\n\n/**\n * Map fascicle's Tool[] to the AI SDK's ToolSet.\n *\n * Returns undefined for an empty tool list so the caller can omit `tools`\n * from the call params entirely instead of passing an empty object.\n */\nexport function to_sdk_tools(tools: ReadonlyArray<Tool>): ToolSet | undefined {\n if (tools.length === 0) return undefined\n const entries: ToolSet = {}\n for (const t of tools) {\n entries[t.name] = ai_tool({\n description: t.description,\n inputSchema: t.input_schema,\n })\n }\n return entries\n}\n\n/**\n * Map one AI SDK stream part to the engine's StreamChunk shape, or undefined\n * for a part kind the engine does not model.\n */\nexport function map_stream_part_to_chunk(\n part: TextStreamPart<ToolSet>,\n step_index: number,\n): StreamChunk | undefined {\n switch (part.type) {\n case 'text-delta':\n return { kind: 'text', text: part.text, step_index }\n case 'reasoning-delta':\n return { kind: 'reasoning', text: part.text, step_index }\n case 'tool-input-start':\n return {\n kind: 'tool_call_start',\n id: part.id,\n name: part.toolName,\n step_index,\n }\n case 'tool-input-delta':\n return {\n kind: 'tool_call_input_delta',\n id: part.id,\n delta: part.delta,\n step_index,\n }\n case 'tool-call':\n return {\n kind: 'tool_call_end',\n id: part.toolCallId,\n input: part.input,\n step_index,\n }\n case 'finish-step':\n return {\n kind: 'step_finish',\n step_index,\n finish_reason: map_finish_reason(part.finishReason),\n usage: default_usage_from_sdk(part.usage),\n }\n default:\n // v7 parts with no engine StreamChunk kind (file, reasoning-file,\n // source, block framing) drop here on purpose: the engine models\n // text, reasoning, and tool traffic, not generated files.\n return undefined\n }\n}\n\n/**\n * Normalize a raw AI SDK usage object into UsageTotals for a streamed\n * step_finish chunk.\n */\nexport function default_usage_from_sdk(usage: unknown): UsageTotals {\n // Streamed step_finish chunks must carry the same cache/reasoning\n // granularity the step record gets via adapter.normalize_usage; every\n // built-in adapter routes through default_normalize_usage, so this keeps\n // the chunk surface consistent with the non-streamed result.\n return default_normalize_usage(to_raw_provider_usage(usage))\n}\n\n/**\n * The running TurnResult fields collect_stream builds as it consumes the SDK\n * stream: text and tool calls accrue across parts, while finish reason, usage,\n * and provider_reported are overwritten by the terminal finish-step.\n */\ntype StreamAccumulator = {\n text: string\n tool_calls: RawToolCall[]\n finish_reason: FinishReason\n raw_usage: RawProviderUsage\n provider_reported: Record<string, unknown> | undefined\n}\n\n/**\n * Fold one stream part's accumulated state into `acc`: text deltas append,\n * tool-call parts push a RawToolCall, and the finish-step overwrites finish\n * reason, usage, and provider_reported. The finish-step's providerMetadata is\n * the same value generateText returns on its result, which is what keeps a\n * streamed run's provider_reported identical to a plain run's. Parts with no\n * accumulated state (error, abort, stream framing) are the caller's to handle.\n */\nfunction accumulate_stream_part(part: TextStreamPart<ToolSet>, acc: StreamAccumulator): void {\n if (part.type === 'text-delta') {\n acc.text += part.text\n return\n }\n if (part.type === 'tool-call') {\n acc.tool_calls.push({\n id: part.toolCallId,\n name: part.toolName,\n input: part.input,\n })\n return\n }\n if (part.type === 'finish-step') {\n acc.finish_reason = map_finish_reason(part.finishReason)\n acc.raw_usage = to_raw_provider_usage(part.usage)\n acc.provider_reported = to_provider_reported(part.providerMetadata)\n }\n}\n\n/**\n * Run one streamText call, dispatching StreamChunks as parts arrive and\n * accumulating them into a TurnResult once the stream completes.\n */\nasync function collect_stream(\n params: Parameters<typeof streamText>[0],\n step_index: number,\n dispatcher: ChunkDispatcher,\n on_first_chunk: () => void,\n internal_controller: AbortController,\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n const stream_result = streamText(params)\n const acc: StreamAccumulator = {\n text: '',\n tool_calls: [],\n finish_reason: 'stop',\n raw_usage: {},\n provider_reported: undefined,\n }\n let first = true\n\n for await (const part of stream_result.stream) {\n if (first) {\n first = false\n on_first_chunk()\n }\n accumulate_stream_part(part, acc)\n if (part.type === 'error') {\n throw part.error\n }\n if (part.type === 'abort') {\n throw new aborted_error('aborted', { step_index })\n }\n const chunk = map_stream_part_to_chunk(part, step_index)\n if (chunk === undefined) continue\n try {\n await dispatcher.dispatch(chunk)\n } catch (err: unknown) {\n internal_controller.abort()\n throw err\n }\n }\n\n return {\n text: acc.text,\n tool_calls: acc.tool_calls,\n finish_reason: acc.finish_reason,\n usage: adapter.normalize_usage(acc.raw_usage),\n // Stryker disable next-line ConditionalExpression: an always-true spread only adds an explicit `provider_reported: undefined` key, which every reader of TurnResult treats identically to the absent key.\n ...(acc.provider_reported !== undefined ? { provider_reported: acc.provider_reported } : {}),\n }\n}\n\n/**\n * Run one generateText call and map its result into a TurnResult, recovering\n * a schema-validation failure from the SDK via recover_no_object_generated\n * instead of letting it throw.\n */\nasync function collect_non_stream(\n params: Parameters<typeof generateText>[0],\n adapter: AiSdkProviderAdapter,\n): Promise<TurnResult> {\n let result: Awaited<ReturnType<typeof generateText>>\n try {\n result = await generateText(params)\n } catch (err: unknown) {\n const recovered = recover_no_object_generated(err, adapter)\n if (recovered !== undefined) return recovered\n throw err\n }\n const tool_calls: RawToolCall[] = []\n for (const tc of result.toolCalls) {\n tool_calls.push({\n id: tc.toolCallId,\n name: tc.toolName,\n input: tc.input,\n })\n }\n const raw_usage = to_raw_provider_usage(result.usage)\n // result.providerMetadata rather than result.finalStep.providerMetadata: the\n // two are the same value under stopWhen isStepCount(1), and the flat field\n // exists across the whole `ai` ^7 peer range this package declares.\n const provider_reported = to_provider_reported(result.providerMetadata)\n return {\n text: result.text,\n tool_calls,\n finish_reason: map_finish_reason(result.finishReason),\n usage: adapter.normalize_usage(raw_usage),\n // Stryker disable next-line ConditionalExpression: see collect_stream; the always-true spread is unobservable through every TurnResult reader.\n ...(provider_reported !== undefined ? { provider_reported } : {}),\n }\n}\n\n/**\n * When `output` (structured output) is in play, `generateText` eagerly parses the\n * model's text against the schema and throws `NoObjectGeneratedError` if it\n * does not conform. That parse is the SDK's, not fascicle's: turning it into a\n * thrown error would skip the engine's own schema-parse + repair loop (and the\n * error is not a retryable transient, so it would surface raw). Instead we\n * recover the model's raw text from the error and hand it back as a normal\n * turn result, so `parse_with_schema` re-validates it and the repair loop\n * engages exactly as it does for the prompt-based path. Returns undefined for\n * any other error so the caller rethrows.\n *\n * The recovered turn carries no provider_reported: the SDK's error exposes\n * text, usage, finishReason and response metadata, but not providerMetadata,\n * so there is nothing to read. The repair turn that follows reports normally.\n */\nfunction recover_no_object_generated(\n err: unknown,\n adapter: AiSdkProviderAdapter,\n): TurnResult | undefined {\n if (!NoObjectGeneratedError.isInstance(err)) return undefined\n const text_field = Reflect.get(err, 'text')\n const finish_field = Reflect.get(err, 'finishReason')\n const raw_usage = to_raw_provider_usage(Reflect.get(err, 'usage'))\n return {\n text: typeof text_field === 'string' ? text_field : '',\n tool_calls: [],\n finish_reason: map_finish_reason(typeof finish_field === 'string' ? finish_field : undefined),\n usage: adapter.normalize_usage(raw_usage),\n }\n}\n\ntype AiSdkCallParams = Parameters<typeof streamText>[0] & Parameters<typeof generateText>[0]\n\nexport type AiSdkTurnConfig = {\n readonly adapter: AiSdkProviderAdapter\n readonly model_id: string\n readonly dispatcher: ChunkDispatcher\n readonly tools: ReadonlyArray<Tool>\n readonly schema: ToolSchema | undefined\n readonly provider_options: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined\n readonly temperature: number | undefined\n readonly max_tokens: number | undefined\n readonly top_p: number | undefined\n readonly telemetry: AiSdkTelemetrySettings | undefined\n}\n\nexport type AiSdkTurnArgs = {\n readonly step_index: number\n readonly messages: ReadonlyArray<Message>\n readonly abort: AbortSignal\n readonly stream: boolean\n readonly on_first_chunk: () => void\n}\n\nexport type AiSdkTurn = (args: AiSdkTurnArgs) => Promise<TurnResult>\n\n/**\n * Build the single-attempt SDK turn for one generate call: the\n * generateText/streamText call body behind the same neutral seam a native\n * adapter's invoke_turn implements. The built model is memoized across steps\n * of one generate call. No retry here: generate.ts wraps the returned turn in\n * the engine-owned retry_turn.\n */\nexport function create_ai_sdk_turn(cfg: AiSdkTurnConfig): AiSdkTurn {\n let model_instance: LanguageModel | undefined\n const get_model = async (): Promise<LanguageModel> => {\n if (model_instance === undefined) {\n const built = await cfg.adapter.build_model(cfg.model_id)\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n model_instance = built as LanguageModel\n }\n return model_instance\n }\n\n // Telemetry is resolved once per generate call and memoized across its steps,\n // mirroring get_model. build_ai_sdk_telemetry returns undefined immediately\n // (no peer load) unless telemetry is explicitly enabled, so the disabled\n // default costs nothing.\n let telemetry_options: AiSdkTelemetryPassthrough | undefined\n let telemetry_resolved = false\n const get_telemetry = async (): Promise<AiSdkTelemetryPassthrough | undefined> => {\n if (!telemetry_resolved) {\n telemetry_options = await build_ai_sdk_telemetry(cfg.telemetry)\n telemetry_resolved = true\n }\n return telemetry_options\n }\n\n const sdk_tools = to_sdk_tools(cfg.tools)\n\n // Native structured output: when a schema is requested and the provider\n // constrains decoding to it (the 'structured_output' capability), route\n // through the AI SDK's Output.object seam so the schema becomes the\n // provider's responseFormat (e.g. Ollama's `format`) instead of a\n // prompt-for-JSON-then-scrape. Gated on no tools: forcing a JSON\n // responseFormat alongside tool calls breaks tool dispatch on most\n // providers, so tool runs keep the prompt-based schema path. The engine's\n // schema parse + repair loop still owns validation either way. This seam\n // is ai_sdk-only: a native adapter that constrains decoding honors\n // TurnRequest.schema inside its own invoke_turn.\n let output_spec: NonNullable<AiSdkCallParams['output']> | undefined\n if (\n cfg.schema !== undefined &&\n cfg.tools.length === 0 &&\n cfg.adapter.supports('structured_output')\n ) {\n // Output.object<T> is not structurally assignable to the SDK's default\n // Output<string, string> param slot, but the runtime shape is exactly\n // what generateText/streamText consume to set responseFormat.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n output_spec = Output.object({ schema: cfg.schema }) as NonNullable<\n AiSdkCallParams['output']\n >\n }\n\n // provider_options is Record<string, Record<string, unknown>>; the SDK\n // expects SharedV3ProviderOptions (Record<string, JSONObject>) which is\n // structurally compatible for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n const provider_options = cfg.provider_options as AiSdkCallParams['providerOptions']\n\n return async (args: AiSdkTurnArgs): Promise<TurnResult> => {\n const model = await get_model()\n const telemetry = await get_telemetry()\n const internal_controller = new AbortController()\n const cancel_on_user_abort = (): void => {\n internal_controller.abort(args.abort.reason)\n }\n if (args.abort.aborted) {\n internal_controller.abort(args.abort.reason)\n } else {\n args.abort.addEventListener('abort', cancel_on_user_abort, { once: true })\n }\n const { system: hoisted_system, messages: sdk_messages } = split_leading_system(\n to_sdk_messages(args.messages),\n )\n const base_params: AiSdkCallParams = {\n model,\n messages: sdk_messages,\n abortSignal: internal_controller.signal,\n stopWhen: isStepCount(1),\n // The engine owns retry via retry_turn in generate.ts; disable the AI\n // SDK's own retry (default 2) so it does not nest inside each of our\n // attempts and inflate provider round-trips / distort backoff.\n maxRetries: 0,\n }\n if (hoisted_system !== undefined) base_params.instructions = hoisted_system\n if (sdk_tools !== undefined) base_params.tools = sdk_tools\n if (output_spec !== undefined) base_params.output = output_spec\n if (provider_options !== undefined) base_params.providerOptions = provider_options\n if (cfg.temperature !== undefined) base_params.temperature = cfg.temperature\n if (cfg.max_tokens !== undefined) base_params.maxOutputTokens = cfg.max_tokens\n if (cfg.top_p !== undefined) base_params.topP = cfg.top_p\n if (telemetry !== undefined) {\n // AiSdkTelemetryPassthrough uses the SDK's own telemetry keys; the slot's\n // generic (RUNTIME_CONTEXT/TOOLS) is erased for our usage.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n base_params.experimental_telemetry = telemetry as NonNullable<\n AiSdkCallParams['experimental_telemetry']\n >\n }\n\n try {\n if (args.stream) {\n return await collect_stream(\n base_params,\n args.step_index,\n cfg.dispatcher,\n args.on_first_chunk,\n internal_controller,\n cfg.adapter,\n )\n }\n return await collect_non_stream(base_params, cfg.adapter)\n } finally {\n args.abort.removeEventListener('abort', cancel_on_user_abort)\n }\n }\n}\n"],"mappings":";;;;;;;;AAyCA,eAAsB,uBACpB,UACgD;CAChD,IAAI,CAAC,UAAU,SAAS,OAAO,KAAA;CAK/B,MAAM,MAAiC;EAAE,WAAW;EAAM,cAAc,CAAC,KAHjD,OADN,mBAAoC,cAAc,GAAA,CACxC,cAC1B,SAA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
+ import { a as Step, d as TrajectoryLogger } from "./types-BqUY6nRX.js";
2
2
  import { r as ToolSchema } from "./types-BCtKsxrX.js";
3
- import { w as Tool } from "./types-B3HIsBBD.js";
3
+ import { w as Tool } from "./types-CXBB4aIM.js";
4
4
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
5
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
6
  import { z } from "zod";
package/dist/mcp.js CHANGED
@@ -1,4 +1,4 @@
1
- import { k as run } from "./core-DgH4mDbK.js";
1
+ import { N as run } from "./core-DDRhHu5P.js";
2
2
  //#region src/mcp/errors.ts
3
3
  /**
4
4
  * Typed errors for the MCP adapter.
package/dist/otel.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { s as TrajectoryLogger } from "./types-BDSbSUAO.js";
1
+ import { d as TrajectoryLogger } from "./types-BqUY6nRX.js";
2
2
  import { Tracer } from "@opentelemetry/api";
3
3
 
4
4
  //#region src/otel/trajectory_logger.d.ts
@@ -245,7 +245,8 @@
245
245
  $log.replaceChildren()
246
246
  for (const row of slice) {
247
247
  const div = document.createElement('div')
248
- div.className = 'row' + (row.kind === 'error' ? ' err' : '')
248
+ const failed_run = row.kind === 'run_end' && row.event.status === 'failed'
249
+ div.className = 'row' + (row.kind === 'error' || failed_run ? ' err' : '')
249
250
  const ts = document.createElement('span'); ts.className = 'ts'
250
251
  ts.textContent = new Date(row.ts).toLocaleTimeString()
251
252
  const kind = document.createElement('span'); kind.className = 'kind'; kind.textContent = row.kind
package/dist/stdio.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { r as Step, s as TrajectoryLogger } from "./types-BDSbSUAO.js";
1
+ import { a as Step, d as TrajectoryLogger } from "./types-BqUY6nRX.js";
2
2
  import { t as AnySchema } from "./types-BCtKsxrX.js";
3
3
 
4
4
  //#region src/stdio/execute_stdio.d.ts
package/dist/stdio.js CHANGED
@@ -1,4 +1,4 @@
1
- import { k as run, p as validate_schema } from "./core-DgH4mDbK.js";
1
+ import { N as run, g as validate_schema } from "./core-DDRhHu5P.js";
2
2
  import { r as stderr_logger } from "./adapters-hmnJOOgf.js";
3
3
  import { text } from "node:stream/consumers";
4
4
  //#region src/stdio/execute_stdio.ts
@@ -0,0 +1,90 @@
1
+ import { D as ToolCallRecord, a as Engine, c as FinishReason, j as UsageTotals, l as GenerateOptions, u as GenerateResult } from "./types-CXBB4aIM.js";
2
+
3
+ //#region src/testing/engine_from_generate.d.ts
4
+ /**
5
+ * Build an `Engine` whose only live member is the supplied `generate`.
6
+ *
7
+ * A custom double MUST implement only `generate`: accept `GenerateOptions`
8
+ * and resolve a complete `GenerateResult` (content, tool_calls, steps,
9
+ * usage, finish_reason, model_resolved). Honoring `opts.abort`,
10
+ * `opts.on_chunk`, and `opts.schema` is optional; honor whichever the code
11
+ * under test exercises. It need NOT implement pricing, `with_providers`, or
12
+ * `dispose`: this shell supplies the inert versions.
13
+ */
14
+ declare function engine_from_generate(generate: Engine['generate']): Engine;
15
+ //#endregion
16
+ //#region src/testing/make_capture_engine.d.ts
17
+ type CaptureEngineOptions = {
18
+ readonly result?: GenerateResult<unknown>;
19
+ readonly on_generate?: (opts: GenerateOptions) => Promise<void> | void;
20
+ };
21
+ type CaptureEngine = {
22
+ readonly engine: Engine;
23
+ readonly calls: GenerateOptions[];
24
+ };
25
+ /**
26
+ * Build an `Engine` that records each call's `GenerateOptions` into the
27
+ * returned `calls` array and answers with the canned result.
28
+ */
29
+ declare function make_capture_engine(options?: CaptureEngineOptions): CaptureEngine;
30
+ //#endregion
31
+ //#region src/testing/make_script_engine.d.ts
32
+ type ScriptResponse = {
33
+ readonly content?: unknown;
34
+ readonly tool_calls?: ReadonlyArray<ToolCallRecord>;
35
+ readonly finish_reason?: FinishReason;
36
+ readonly usage?: UsageTotals; /** An error to throw for this call instead of answering. */
37
+ readonly throw?: Error;
38
+ };
39
+ type ScriptEngineOptions = {
40
+ readonly usage?: UsageTotals;
41
+ readonly model_id?: string;
42
+ };
43
+ /**
44
+ * Build an `Engine` that answers generate calls strictly in call order from
45
+ * `responses`, throwing once the queue is exhausted.
46
+ *
47
+ * `options` mirrors make_stub_engine's: `usage` is the default usage for
48
+ * entries that do not set their own (default `{ input_tokens: 40,
49
+ * output_tokens: 20 }`) and `model_id` sets `model_resolved.model_id`
50
+ * (default `'script'`). The provider always reports as `'stub'`.
51
+ */
52
+ declare function make_script_engine(responses: ReadonlyArray<unknown>, options?: ScriptEngineOptions): Engine;
53
+ //#endregion
54
+ //#region src/testing/make_stub_engine.d.ts
55
+ /**
56
+ * The function form of canned content: called with the routed call's options
57
+ * and how many times this prefix route has matched before (starting 0). May
58
+ * be async; the returned value is validated and answered like static content.
59
+ */
60
+ type StubContentFn = (opts: GenerateOptions, call_index: number) => unknown;
61
+ type StubResponse = {
62
+ readonly prefix: string; /** Static content, or a `StubContentFn` invoked per matched call. */
63
+ readonly content: unknown;
64
+ };
65
+ type StubEngineOptions = {
66
+ readonly usage?: UsageTotals;
67
+ readonly model_id?: string;
68
+ };
69
+ /**
70
+ * Build an `Engine` that answers every generate call from `canned`,
71
+ * routed by system-prompt prefix.
72
+ *
73
+ * `options.usage` sets the usage totals reported on every result (default
74
+ * `{ input_tokens: 40, output_tokens: 20 }`, so cost lines render non-zero
75
+ * numbers); `options.model_id` sets `model_resolved.model_id` (default
76
+ * `'stub'`). The provider always reports as `'stub'`.
77
+ */
78
+ declare function make_stub_engine(canned: ReadonlyArray<StubResponse>, options?: StubEngineOptions): Engine;
79
+ //#endregion
80
+ //#region src/testing/text_of.d.ts
81
+ /**
82
+ * Flatten the prompt's user-facing text into one string: a string prompt
83
+ * verbatim, otherwise every user turn's text (string content, or the `text`
84
+ * parts of a content-part array) joined with newlines. Total: absent or
85
+ * non-text content yields ''.
86
+ */
87
+ declare function text_of<t = unknown>(opts: GenerateOptions<t>): string;
88
+ //#endregion
89
+ export { type CaptureEngine, type CaptureEngineOptions, type ScriptEngineOptions, type ScriptResponse, type StubContentFn, type StubEngineOptions, type StubResponse, engine_from_generate, make_capture_engine, make_script_engine, make_stub_engine, text_of };
90
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1,255 @@
1
+ import { P as aborted_error } from "./core-DDRhHu5P.js";
2
+ import { _ as schema_validation_error } from "./engine-b4ZH8esY.js";
3
+ //#region src/testing/engine_from_generate.ts
4
+ /**
5
+ * Build an `Engine` whose only live member is the supplied `generate`.
6
+ *
7
+ * A custom double MUST implement only `generate`: accept `GenerateOptions`
8
+ * and resolve a complete `GenerateResult` (content, tool_calls, steps,
9
+ * usage, finish_reason, model_resolved). Honoring `opts.abort`,
10
+ * `opts.on_chunk`, and `opts.schema` is optional; honor whichever the code
11
+ * under test exercises. It need NOT implement pricing, `with_providers`, or
12
+ * `dispose`: this shell supplies the inert versions.
13
+ */
14
+ function engine_from_generate(generate) {
15
+ return {
16
+ generate,
17
+ register_price: () => {},
18
+ resolve_price: () => void 0,
19
+ list_prices: () => ({}),
20
+ with_providers: () => {
21
+ throw new Error("testing engines do not support with_providers");
22
+ },
23
+ dispose: async () => {}
24
+ };
25
+ }
26
+ //#endregion
27
+ //#region src/testing/make_capture_engine.ts
28
+ const DEFAULT_RESULT = {
29
+ content: "ok",
30
+ tool_calls: [],
31
+ steps: [],
32
+ usage: {
33
+ input_tokens: 1,
34
+ output_tokens: 1
35
+ },
36
+ finish_reason: "stop",
37
+ model_resolved: {
38
+ provider: "stub",
39
+ model_id: "capture"
40
+ }
41
+ };
42
+ /**
43
+ * Build an `Engine` that records each call's `GenerateOptions` into the
44
+ * returned `calls` array and answers with the canned result.
45
+ */
46
+ function make_capture_engine(options = {}) {
47
+ const calls = [];
48
+ const result = options.result ?? DEFAULT_RESULT;
49
+ return {
50
+ engine: engine_from_generate(async (opts) => {
51
+ const loose = opts;
52
+ calls.push(loose);
53
+ if (options.on_generate) await options.on_generate(loose);
54
+ return result;
55
+ }),
56
+ calls
57
+ };
58
+ }
59
+ //#endregion
60
+ //#region src/testing/canned.ts
61
+ /**
62
+ * Shared plumbing for the canned engine doubles.
63
+ *
64
+ * make_stub_engine and make_script_engine answer calls from fixtures rather
65
+ * than a provider, but the surrounding contract stays the engine's: a call
66
+ * under an already-aborted signal throws `aborted_error`, a streaming caller
67
+ * sees chunks before the result resolves, and content that fails the
68
+ * caller's schema surfaces as `schema_validation_error` carrying the issues.
69
+ * Keeping that contract here keeps every double interchangeable with a real
70
+ * engine at the seams tests exercise.
71
+ */
72
+ const DEFAULT_USAGE = {
73
+ input_tokens: 40,
74
+ output_tokens: 20
75
+ };
76
+ /**
77
+ * Mirror the engine's entry guard: a generate call under an already-aborted
78
+ * signal never reaches a provider, so a double must refuse it the same way
79
+ * for cancellation tests to be trustworthy.
80
+ */
81
+ function throw_if_aborted(abort) {
82
+ if (abort?.aborted === true) throw new aborted_error("aborted", { reason: abort.reason });
83
+ }
84
+ /**
85
+ * Render canned content as the text a provider would have put on the wire:
86
+ * strings pass through, everything else is serialized as JSON (which is what
87
+ * a schema-bearing call would have streamed).
88
+ */
89
+ function render_text(content) {
90
+ if (typeof content === "string") return content;
91
+ return JSON.stringify(content) ?? "";
92
+ }
93
+ /**
94
+ * Emit the minimal chunk sequence a streaming caller expects: the whole
95
+ * content as one text chunk, then the finish marker. Enough for model_chunk
96
+ * trajectory events and stream-consuming UIs to fire without a network.
97
+ */
98
+ async function emit_chunks(on_chunk, content, finish_reason, usage) {
99
+ if (on_chunk === void 0) return;
100
+ await on_chunk({
101
+ kind: "text",
102
+ text: render_text(content),
103
+ step_index: 0
104
+ });
105
+ await on_chunk({
106
+ kind: "finish",
107
+ finish_reason,
108
+ usage
109
+ });
110
+ }
111
+ /**
112
+ * Render issues as one `path: message` line per issue, dotted the same way
113
+ * the engine's own repair prompts and error messages format them.
114
+ */
115
+ function format_issues(issues) {
116
+ return issues.map((issue) => issue.path === void 0 || issue.path.length === 0 ? issue.message : `${issue.path.map(String).join(".")}: ${issue.message}`).join("; ");
117
+ }
118
+ /**
119
+ * Validate canned content through the caller's schema, throwing the engine's
120
+ * own `schema_validation_error` on failure so `instanceof` handling in the
121
+ * code under test sees exactly what a real engine throws when its repair
122
+ * attempts run out. Absent a schema, the content passes through untouched.
123
+ */
124
+ async function validate_canned(schema, content, described) {
125
+ if (schema === void 0) return content;
126
+ const checked = await schema["~standard"].validate(content);
127
+ if (checked.issues !== void 0) {
128
+ const issues = checked.issues.map((issue) => issue.path === void 0 ? { message: issue.message } : {
129
+ message: issue.message,
130
+ path: issue.path.map((segment) => typeof segment === "object" ? segment.key : segment)
131
+ });
132
+ throw new schema_validation_error(`${described} failed the caller's schema: ${format_issues(issues)}`, issues, render_text(content));
133
+ }
134
+ return checked.value;
135
+ }
136
+ //#endregion
137
+ //#region src/testing/make_script_engine.ts
138
+ const SCRIPT_KEYS = /* @__PURE__ */ new Set([
139
+ "content",
140
+ "tool_calls",
141
+ "finish_reason",
142
+ "usage",
143
+ "throw"
144
+ ]);
145
+ /**
146
+ * Decide whether a queue entry is a ScriptResponse or plain content. Only a
147
+ * non-null, non-array object whose keys all belong to the ScriptResponse
148
+ * shape is scripted, so an arbitrary content fixture with its own keys
149
+ * passes through untouched rather than being half-read as a script entry.
150
+ */
151
+ function is_script_response(entry) {
152
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return false;
153
+ const keys = Object.keys(entry);
154
+ return keys.length > 0 && keys.every((key) => SCRIPT_KEYS.has(key));
155
+ }
156
+ /**
157
+ * Build an `Engine` that answers generate calls strictly in call order from
158
+ * `responses`, throwing once the queue is exhausted.
159
+ *
160
+ * `options` mirrors make_stub_engine's: `usage` is the default usage for
161
+ * entries that do not set their own (default `{ input_tokens: 40,
162
+ * output_tokens: 20 }`) and `model_id` sets `model_resolved.model_id`
163
+ * (default `'script'`). The provider always reports as `'stub'`.
164
+ */
165
+ function make_script_engine(responses, options = {}) {
166
+ const default_usage = options.usage ?? DEFAULT_USAGE;
167
+ const model_id = options.model_id ?? "script";
168
+ let call_count = 0;
169
+ return engine_from_generate(async (opts) => {
170
+ throw_if_aborted(opts.abort);
171
+ call_count += 1;
172
+ const index = call_count - 1;
173
+ if (index >= responses.length) throw new Error(`make_script_engine: script exhausted: ${responses.length} response(s) scripted, call ${call_count} received`);
174
+ const entry = responses[index];
175
+ const scripted = is_script_response(entry) ? entry : { content: entry };
176
+ if (scripted.throw !== void 0) throw scripted.throw;
177
+ const usage = scripted.usage ?? default_usage;
178
+ const finish_reason = scripted.finish_reason ?? "stop";
179
+ await emit_chunks(opts.on_chunk, scripted.content, finish_reason, usage);
180
+ return {
181
+ content: await validate_canned(opts.schema, scripted.content, `make_script_engine: scripted response ${index}`),
182
+ tool_calls: scripted.tool_calls === void 0 ? [] : [...scripted.tool_calls],
183
+ steps: [],
184
+ usage,
185
+ finish_reason,
186
+ model_resolved: {
187
+ provider: "stub",
188
+ model_id
189
+ }
190
+ };
191
+ });
192
+ }
193
+ //#endregion
194
+ //#region src/testing/make_stub_engine.ts
195
+ /**
196
+ * Build an `Engine` that answers every generate call from `canned`,
197
+ * routed by system-prompt prefix.
198
+ *
199
+ * `options.usage` sets the usage totals reported on every result (default
200
+ * `{ input_tokens: 40, output_tokens: 20 }`, so cost lines render non-zero
201
+ * numbers); `options.model_id` sets `model_resolved.model_id` (default
202
+ * `'stub'`). The provider always reports as `'stub'`.
203
+ */
204
+ function make_stub_engine(canned, options = {}) {
205
+ const usage = options.usage ?? DEFAULT_USAGE;
206
+ const model_id = options.model_id ?? "stub";
207
+ const match_counts = /* @__PURE__ */ new Map();
208
+ return engine_from_generate(async (opts) => {
209
+ throw_if_aborted(opts.abort);
210
+ const system = opts.system ?? "";
211
+ const match = canned.find((c) => system.startsWith(c.prefix));
212
+ if (match === void 0) throw new Error(`make_stub_engine: no canned response for system: ${system || "(none)"}`);
213
+ const call_index = match_counts.get(match) ?? 0;
214
+ match_counts.set(match, call_index + 1);
215
+ const loose = opts;
216
+ const produced = typeof match.content === "function" ? await match.content(loose, call_index) : match.content;
217
+ await emit_chunks(opts.on_chunk, produced, "stop", usage);
218
+ return {
219
+ content: await validate_canned(opts.schema, produced, `make_stub_engine: canned response for prefix '${match.prefix}'`),
220
+ tool_calls: [],
221
+ steps: [],
222
+ usage,
223
+ finish_reason: "stop",
224
+ model_resolved: {
225
+ provider: "stub",
226
+ model_id
227
+ }
228
+ };
229
+ });
230
+ }
231
+ //#endregion
232
+ //#region src/testing/text_of.ts
233
+ /**
234
+ * Flatten the prompt's user-facing text into one string: a string prompt
235
+ * verbatim, otherwise every user turn's text (string content, or the `text`
236
+ * parts of a content-part array) joined with newlines. Total: absent or
237
+ * non-text content yields ''.
238
+ */
239
+ function text_of(opts) {
240
+ if (typeof opts.prompt === "string") return opts.prompt;
241
+ const texts = [];
242
+ for (const message of opts.prompt) {
243
+ if (message.role !== "user") continue;
244
+ if (typeof message.content === "string") {
245
+ texts.push(message.content);
246
+ continue;
247
+ }
248
+ for (const part of message.content) if (part.type === "text") texts.push(part.text);
249
+ }
250
+ return texts.join("\n");
251
+ }
252
+ //#endregion
253
+ export { engine_from_generate, make_capture_engine, make_script_engine, make_stub_engine, text_of };
254
+
255
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","names":[],"sources":["../src/testing/engine_from_generate.ts","../src/testing/make_capture_engine.ts","../src/testing/canned.ts","../src/testing/make_script_engine.ts","../src/testing/make_stub_engine.ts","../src/testing/text_of.ts"],"sourcesContent":["/**\n * Wrap a canned `generate` function in a complete `Engine`.\n *\n * The remaining members are inert: pricing calls are no-ops that resolve\n * nothing, `dispose` resolves immediately, and `with_providers` throws\n * because a canned engine has no provider registry to derive from. Both\n * testing factories share this shell so a test double differs from a real\n * engine only in how `generate` answers.\n */\n\nimport type { Engine } from '#engine'\n\n/**\n * Build an `Engine` whose only live member is the supplied `generate`.\n *\n * A custom double MUST implement only `generate`: accept `GenerateOptions`\n * and resolve a complete `GenerateResult` (content, tool_calls, steps,\n * usage, finish_reason, model_resolved). Honoring `opts.abort`,\n * `opts.on_chunk`, and `opts.schema` is optional; honor whichever the code\n * under test exercises. It need NOT implement pricing, `with_providers`, or\n * `dispose`: this shell supplies the inert versions.\n */\nexport function engine_from_generate(generate: Engine['generate']): Engine {\n return {\n generate,\n register_price: () => {},\n resolve_price: () => undefined,\n list_prices: () => ({}),\n with_providers: () => {\n throw new Error('testing engines do not support with_providers')\n },\n dispose: async () => {},\n }\n}\n","/**\n * make_capture_engine: an `Engine` that records every generate call.\n *\n * Returns the engine together with the live `calls` array, which receives\n * the `GenerateOptions` of each call in order. Every call resolves with the\n * same canned result (`options.result`, or a minimal `'ok'` result), so the\n * double is for asserting what reached the engine, not for scripting\n * multi-role conversations: that is `make_stub_engine`'s job.\n *\n * `options.on_generate` runs after the call is recorded and is awaited\n * before the result resolves, which is the hook for driving streaming\n * chunks, spans, or aborts against the captured options.\n */\n\nimport type { Engine, GenerateOptions, GenerateResult } from '#engine'\nimport { engine_from_generate } from './engine_from_generate.js'\n\nexport type CaptureEngineOptions = {\n readonly result?: GenerateResult<unknown>\n readonly on_generate?: (opts: GenerateOptions) => Promise<void> | void\n}\n\nexport type CaptureEngine = {\n readonly engine: Engine\n readonly calls: GenerateOptions[]\n}\n\nconst DEFAULT_RESULT: GenerateResult<unknown> = {\n content: 'ok',\n tool_calls: [],\n steps: [],\n usage: { input_tokens: 1, output_tokens: 1 },\n finish_reason: 'stop',\n model_resolved: { provider: 'stub', model_id: 'capture' },\n}\n\n/**\n * Build an `Engine` that records each call's `GenerateOptions` into the\n * returned `calls` array and answers with the canned result.\n */\nexport function make_capture_engine(options: CaptureEngineOptions = {}): CaptureEngine {\n const calls: GenerateOptions[] = []\n const result = options.result ?? DEFAULT_RESULT\n\n const engine = engine_from_generate(\n async <t = string>(opts: GenerateOptions<t>): Promise<GenerateResult<t>> => {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const loose = opts as GenerateOptions\n calls.push(loose)\n if (options.on_generate) await options.on_generate(loose)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return result as GenerateResult<t>\n },\n )\n return { engine, calls }\n}\n","/**\n * Shared plumbing for the canned engine doubles.\n *\n * make_stub_engine and make_script_engine answer calls from fixtures rather\n * than a provider, but the surrounding contract stays the engine's: a call\n * under an already-aborted signal throws `aborted_error`, a streaming caller\n * sees chunks before the result resolves, and content that fails the\n * caller's schema surfaces as `schema_validation_error` carrying the issues.\n * Keeping that contract here keeps every double interchangeable with a real\n * engine at the seams tests exercise.\n */\n\nimport { aborted_error, schema_validation_error } from '#engine'\nimport type { FinishReason, GenerateOptions, UsageTotals } from '#engine'\n\nexport const DEFAULT_USAGE: UsageTotals = { input_tokens: 40, output_tokens: 20 }\n\n/**\n * Mirror the engine's entry guard: a generate call under an already-aborted\n * signal never reaches a provider, so a double must refuse it the same way\n * for cancellation tests to be trustworthy.\n */\nexport function throw_if_aborted(abort: AbortSignal | undefined): void {\n if (abort?.aborted === true) {\n throw new aborted_error('aborted', { reason: abort.reason })\n }\n}\n\n/**\n * Render canned content as the text a provider would have put on the wire:\n * strings pass through, everything else is serialized as JSON (which is what\n * a schema-bearing call would have streamed).\n */\nfunction render_text(content: unknown): string {\n if (typeof content === 'string') return content\n return JSON.stringify(content) ?? ''\n}\n\n/**\n * Emit the minimal chunk sequence a streaming caller expects: the whole\n * content as one text chunk, then the finish marker. Enough for model_chunk\n * trajectory events and stream-consuming UIs to fire without a network.\n */\nexport async function emit_chunks(\n on_chunk: GenerateOptions['on_chunk'],\n content: unknown,\n finish_reason: FinishReason,\n usage: UsageTotals,\n): Promise<void> {\n if (on_chunk === undefined) return\n await on_chunk({ kind: 'text', text: render_text(content), step_index: 0 })\n await on_chunk({ kind: 'finish', finish_reason, usage })\n}\n\ntype CannedIssue = {\n readonly message: string\n readonly path?: ReadonlyArray<PropertyKey>\n}\n\n/**\n * Render issues as one `path: message` line per issue, dotted the same way\n * the engine's own repair prompts and error messages format them.\n */\nfunction format_issues(issues: ReadonlyArray<CannedIssue>): string {\n return issues\n .map((issue) =>\n issue.path === undefined || issue.path.length === 0\n ? issue.message\n : `${issue.path.map(String).join('.')}: ${issue.message}`,\n )\n .join('; ')\n}\n\n/**\n * Validate canned content through the caller's schema, throwing the engine's\n * own `schema_validation_error` on failure so `instanceof` handling in the\n * code under test sees exactly what a real engine throws when its repair\n * attempts run out. Absent a schema, the content passes through untouched.\n */\nexport async function validate_canned(\n schema: GenerateOptions<unknown>['schema'],\n content: unknown,\n described: string,\n): Promise<unknown> {\n if (schema === undefined) return content\n const checked = await schema['~standard'].validate(content)\n if (checked.issues !== undefined) {\n // The spec allows a path segment to be a bare key or a `{ key }` wrapper;\n // normalize to bare keys so schema_issues reads one shape, as the real\n // engine's validator does.\n const issues: CannedIssue[] = checked.issues.map((issue) =>\n issue.path === undefined\n ? { message: issue.message }\n : {\n message: issue.message,\n path: issue.path.map((segment) =>\n typeof segment === 'object' ? segment.key : segment,\n ),\n },\n )\n throw new schema_validation_error(\n `${described} failed the caller's schema: ${format_issues(issues)}`,\n issues,\n render_text(content),\n )\n }\n return checked.value\n}\n","/**\n * make_script_engine: a queue of canned responses consumed in call order.\n *\n * Where make_stub_engine routes by system-prompt prefix and cannot tell\n * call 3 from call 1, a script cares only about order: the first generate\n * call gets the first entry, the second the next, and a call past the end\n * throws naming how many responses were scripted versus received, so a flow\n * that makes an unexpected extra model call fails loudly. That makes it the\n * double for loops that must converge, retry paths, and flows whose calls a\n * prefix cannot distinguish (a markdown-only define_agent sends no system\n * prompt at all, so every call looks alike to a stub).\n *\n * An entry is plain content, or a `ScriptResponse` object when the call\n * should carry tool calls, report a different finish reason or usage, or\n * throw a scripted error (a rate_limit_error, a provider_error) instead of\n * answering. Only an object whose keys ALL belong to the ScriptResponse\n * shape is treated as scripted; any other value, `{ verdict: 'ship' }`\n * included, becomes content as-is. Wrap literal content that collides with\n * the shape in `{ content }`.\n *\n * Scripted content is validated through the caller's schema, and the abort\n * and on_chunk contracts match make_stub_engine's; see ./canned.ts.\n */\n\nimport type {\n Engine,\n FinishReason,\n GenerateOptions,\n GenerateResult,\n ToolCallRecord,\n UsageTotals,\n} from '#engine'\nimport { DEFAULT_USAGE, emit_chunks, throw_if_aborted, validate_canned } from './canned.js'\nimport { engine_from_generate } from './engine_from_generate.js'\n\nexport type ScriptResponse = {\n readonly content?: unknown\n readonly tool_calls?: ReadonlyArray<ToolCallRecord>\n readonly finish_reason?: FinishReason\n readonly usage?: UsageTotals\n /** An error to throw for this call instead of answering. */\n readonly throw?: Error\n}\n\nexport type ScriptEngineOptions = {\n readonly usage?: UsageTotals\n readonly model_id?: string\n}\n\nconst SCRIPT_KEYS = new Set(['content', 'tool_calls', 'finish_reason', 'usage', 'throw'])\n\n/**\n * Decide whether a queue entry is a ScriptResponse or plain content. Only a\n * non-null, non-array object whose keys all belong to the ScriptResponse\n * shape is scripted, so an arbitrary content fixture with its own keys\n * passes through untouched rather than being half-read as a script entry.\n */\nfunction is_script_response(entry: unknown): entry is ScriptResponse {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return false\n const keys = Object.keys(entry)\n return keys.length > 0 && keys.every((key) => SCRIPT_KEYS.has(key))\n}\n\n/**\n * Build an `Engine` that answers generate calls strictly in call order from\n * `responses`, throwing once the queue is exhausted.\n *\n * `options` mirrors make_stub_engine's: `usage` is the default usage for\n * entries that do not set their own (default `{ input_tokens: 40,\n * output_tokens: 20 }`) and `model_id` sets `model_resolved.model_id`\n * (default `'script'`). The provider always reports as `'stub'`.\n */\nexport function make_script_engine(\n responses: ReadonlyArray<unknown>,\n options: ScriptEngineOptions = {},\n): Engine {\n const default_usage = options.usage ?? DEFAULT_USAGE\n const model_id = options.model_id ?? 'script'\n let call_count = 0\n\n return engine_from_generate(\n async <t = string>(opts: GenerateOptions<t>): Promise<GenerateResult<t>> => {\n throw_if_aborted(opts.abort)\n call_count += 1\n const index = call_count - 1\n if (index >= responses.length) {\n throw new Error(\n `make_script_engine: script exhausted: ${responses.length} response(s) scripted, call ${call_count} received`,\n )\n }\n const entry = responses[index]\n const scripted: ScriptResponse = is_script_response(entry) ? entry : { content: entry }\n if (scripted.throw !== undefined) throw scripted.throw\n const usage = scripted.usage ?? default_usage\n const finish_reason = scripted.finish_reason ?? 'stop'\n // Chunks carry the raw scripted content, before validation, mirroring a\n // real stream where text flows and only then gets validated.\n await emit_chunks(opts.on_chunk, scripted.content, finish_reason, usage)\n const content = await validate_canned(\n opts.schema,\n scripted.content,\n `make_script_engine: scripted response ${index}`,\n )\n return {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n content: content as t,\n tool_calls: scripted.tool_calls === undefined ? [] : [...scripted.tool_calls],\n steps: [],\n usage,\n finish_reason,\n model_resolved: { provider: 'stub', model_id },\n }\n },\n )\n}\n","/**\n * make_stub_engine: a canned, network-free `Engine` for tests and demos.\n *\n * Each generate call is routed by the system prompt's stable first line:\n * the first canned response whose `prefix` the system prompt starts with\n * answers the call, and an unmatched system throws, so a flow that grows a\n * new model boundary fails loudly instead of silently reusing a fixture.\n * A response with the empty-string prefix matches every call, which is the\n * single-model-boundary case.\n *\n * A response's `content` may be a function of `(opts, call_index)` for\n * routes a flow hits more than once (a converging loop, a judged retry):\n * `call_index` counts how many times that route has matched before,\n * starting at 0, so each pass can answer differently.\n *\n * Canned content is validated through the caller's own schema\n * (`opts.schema['~standard'].validate`), so fixtures cannot drift from the\n * contracts they stand in for. A failure throws the engine's own\n * `schema_validation_error` carrying the issues and the canned content as\n * `raw_text`, exactly what a real engine throws when repair attempts run\n * out, so `instanceof` handling in the code under test stays testable.\n *\n * The engine's streaming and cancellation contract holds too: an\n * already-aborted `opts.abort` throws `aborted_error`, and a provided\n * `opts.on_chunk` receives the canned content as a text chunk plus a finish\n * chunk before the result resolves.\n */\n\nimport type { Engine, GenerateOptions, GenerateResult, UsageTotals } from '#engine'\nimport { DEFAULT_USAGE, emit_chunks, throw_if_aborted, validate_canned } from './canned.js'\nimport { engine_from_generate } from './engine_from_generate.js'\n\n/**\n * The function form of canned content: called with the routed call's options\n * and how many times this prefix route has matched before (starting 0). May\n * be async; the returned value is validated and answered like static content.\n */\nexport type StubContentFn = (opts: GenerateOptions, call_index: number) => unknown\n\nexport type StubResponse = {\n readonly prefix: string\n /** Static content, or a `StubContentFn` invoked per matched call. */\n readonly content: unknown\n}\n\nexport type StubEngineOptions = {\n readonly usage?: UsageTotals\n readonly model_id?: string\n}\n\n/**\n * Build an `Engine` that answers every generate call from `canned`,\n * routed by system-prompt prefix.\n *\n * `options.usage` sets the usage totals reported on every result (default\n * `{ input_tokens: 40, output_tokens: 20 }`, so cost lines render non-zero\n * numbers); `options.model_id` sets `model_resolved.model_id` (default\n * `'stub'`). The provider always reports as `'stub'`.\n */\nexport function make_stub_engine(\n canned: ReadonlyArray<StubResponse>,\n options: StubEngineOptions = {},\n): Engine {\n const usage = options.usage ?? DEFAULT_USAGE\n const model_id = options.model_id ?? 'stub'\n const match_counts = new Map<StubResponse, number>()\n\n return engine_from_generate(\n async <t = string>(opts: GenerateOptions<t>): Promise<GenerateResult<t>> => {\n throw_if_aborted(opts.abort)\n const system = opts.system ?? ''\n const match = canned.find((c) => system.startsWith(c.prefix))\n if (match === undefined) {\n throw new Error(`make_stub_engine: no canned response for system: ${system || '(none)'}`)\n }\n const call_index = match_counts.get(match) ?? 0\n match_counts.set(match, call_index + 1)\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const loose = opts as GenerateOptions\n const produced =\n typeof match.content === 'function'\n ? // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n await (match.content as StubContentFn)(loose, call_index)\n : match.content\n // Chunks carry the raw canned content, before validation, mirroring a\n // real stream where text flows and only then gets validated.\n await emit_chunks(opts.on_chunk, produced, 'stop', usage)\n const content = await validate_canned(\n opts.schema,\n produced,\n `make_stub_engine: canned response for prefix '${match.prefix}'`,\n )\n return {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n content: content as t,\n tool_calls: [],\n steps: [],\n usage,\n finish_reason: 'stop',\n model_resolved: { provider: 'stub', model_id },\n }\n },\n )\n}\n","/**\n * text_of: the user-visible prompt text of a captured GenerateOptions.\n *\n * Capture assertions care about what the model was asked, not how the prompt\n * was encoded. A prompt is a bare string or a Message[] whose user turns\n * carry either a string or typed content parts; navigating\n * `calls[0].prompt[0].content[0].text` by hand couples every assertion to\n * one encoding. System and assistant text are excluded on purpose: assert\n * those through `opts.system` and the raw messages.\n */\n\nimport type { GenerateOptions } from '#engine'\n\n/**\n * Flatten the prompt's user-facing text into one string: a string prompt\n * verbatim, otherwise every user turn's text (string content, or the `text`\n * parts of a content-part array) joined with newlines. Total: absent or\n * non-text content yields ''.\n */\nexport function text_of<t = unknown>(opts: GenerateOptions<t>): string {\n if (typeof opts.prompt === 'string') return opts.prompt\n const texts: string[] = []\n for (const message of opts.prompt) {\n if (message.role !== 'user') continue\n if (typeof message.content === 'string') {\n texts.push(message.content)\n continue\n }\n for (const part of message.content) {\n if (part.type === 'text') texts.push(part.text)\n }\n }\n return texts.join('\\n')\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAgB,qBAAqB,UAAsC;CACzE,OAAO;EACL;EACA,sBAAsB,CAAC;EACvB,qBAAqB,KAAA;EACrB,oBAAoB,CAAC;EACrB,sBAAsB;GACpB,MAAM,IAAI,MAAM,+CAA+C;EACjE;EACA,SAAS,YAAY,CAAC;CACxB;AACF;;;ACNA,MAAM,iBAA0C;CAC9C,SAAS;CACT,YAAY,CAAC;CACb,OAAO,CAAC;CACR,OAAO;EAAE,cAAc;EAAG,eAAe;CAAE;CAC3C,eAAe;CACf,gBAAgB;EAAE,UAAU;EAAQ,UAAU;CAAU;AAC1D;;;;;AAMA,SAAgB,oBAAoB,UAAgC,CAAC,GAAkB;CACrF,MAAM,QAA2B,CAAC;CAClC,MAAM,SAAS,QAAQ,UAAU;CAYjC,OAAO;EAAE,QAVM,qBACb,OAAmB,SAAyD;GAE1E,MAAM,QAAQ;GACd,MAAM,KAAK,KAAK;GAChB,IAAI,QAAQ,aAAa,MAAM,QAAQ,YAAY,KAAK;GAExD,OAAO;EACT,CAEY;EAAG;CAAM;AAC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