fascicle 0.13.0 → 0.14.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +20 -1
  3. package/dist/acp.d.ts +226 -0
  4. package/dist/acp.js +1886 -0
  5. package/dist/acp.js.map +1 -0
  6. package/dist/adapters.js +1 -2
  7. package/dist/agents.d.ts +1 -1
  8. package/dist/agents.js +1 -1
  9. package/dist/{core-B-M7nAkg.js → core-CDrz0NM1.js} +184 -53
  10. package/dist/core-CDrz0NM1.js.map +1 -0
  11. package/dist/diagram_bin.js +5 -2
  12. package/dist/diagram_bin.js.map +1 -1
  13. package/dist/{engine-BRzVcTBB.js → engine-BDWB2jdn.js} +12 -333
  14. package/dist/engine-BDWB2jdn.js.map +1 -0
  15. package/dist/index.d.ts +485 -623
  16. package/dist/index.js +20 -12
  17. package/dist/index.js.map +1 -1
  18. package/dist/{invoke-CIdhjChw.js → invoke-tjTjZLHj.js} +3 -3
  19. package/dist/{invoke-CIdhjChw.js.map → invoke-tjTjZLHj.js.map} +1 -1
  20. package/dist/json_schema_to_standard-r21kW2LI.js +288 -0
  21. package/dist/json_schema_to_standard-r21kW2LI.js.map +1 -0
  22. package/dist/leading_system-BQe_405V.js +330 -0
  23. package/dist/leading_system-BQe_405V.js.map +1 -0
  24. package/dist/mcp.d.ts +17 -16
  25. package/dist/mcp.js +2 -266
  26. package/dist/mcp.js.map +1 -1
  27. package/dist/search-CqH5hmuF.js +563 -0
  28. package/dist/search-CqH5hmuF.js.map +1 -0
  29. package/dist/search_worker.d.ts +1 -0
  30. package/dist/search_worker.js +19 -0
  31. package/dist/search_worker.js.map +1 -0
  32. package/dist/stdio.js +1 -1
  33. package/dist/testing.d.ts +1 -1
  34. package/dist/testing.js +3 -2
  35. package/dist/testing.js.map +1 -1
  36. package/dist/{types-CZ83Q5nm.d.ts → types-C_Rmcgck.d.ts} +7 -1
  37. package/dist/viewer-app/assets/index-Fnh5HKSU.js +2 -0
  38. package/dist/viewer-app/index.html +1 -1
  39. package/dist/viewer.js +1 -1
  40. package/package.json +30 -19
  41. package/dist/core-B-M7nAkg.js.map +0 -1
  42. package/dist/engine-BRzVcTBB.js.map +0 -1
  43. package/dist/viewer-app/assets/index-DXsB0byD.js +0 -2
@@ -1,5 +1,5 @@
1
- import { k as aborted_error } from "./core-B-M7nAkg.js";
2
- import { i as load_optional_peer, n as split_leading_system_run, r as default_normalize_usage } from "./engine-BRzVcTBB.js";
1
+ import { k as aborted_error } from "./core-CDrz0NM1.js";
2
+ import { n as default_normalize_usage, r as load_optional_peer, t as split_leading_system_run } from "./leading_system-BQe_405V.js";
3
3
  import { NoObjectGeneratedError, Output, generateText, isStepCount, streamText, tool } from "ai";
4
4
  //#region src/engine/providers/ai_sdk/telemetry.ts
5
5
  /**
@@ -488,4 +488,4 @@ function create_ai_sdk_turn(cfg) {
488
488
  //#endregion
489
489
  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 };
490
490
 
491
- //# sourceMappingURL=invoke-CIdhjChw.js.map
491
+ //# sourceMappingURL=invoke-tjTjZLHj.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"invoke-CIdhjChw.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 ImagePart,\n type LanguageModel,\n type ModelMessage,\n type TextPart,\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<TextPart | ImagePart> = m.content.map((p) => {\n let part: TextPart | ImagePart\n if (p.type === 'text') {\n part = { type: 'text', text: p.text }\n } else {\n const image_part: ImagePart = { type: 'image', image: p.image }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n part = image_part\n }\n if (p.provider_options !== undefined) {\n // Same structural cast as the call-level provider_options in\n // create_ai_sdk_turn.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n part.providerOptions = p.provider_options as NonNullable<TextPart['providerOptions']>\n }\n return 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 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 // Stamped on the first dispatched chunk, not the first stream part: the\n // SDK opens every stream with `start` and `start-step` framing before the\n // model has produced a token, and a stamp there would leave prefill inside\n // the decode window throughput() measures. This is also the native\n // transport's rule (build_native_invoke stamps in dispatch_chunk), so a\n // failure before the first token stays retryable on both.\n if (first) {\n first = false\n on_first_chunk()\n }\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 (for example, 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;;;;;;;;;;;;;;;;;;ACJA,SAAgB,kBAAkB,KAAuC;CACvE,QAAQ,KAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,UACH,OAAO;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AK,CAAC;EAE3E,MAAM,EAAE,QAAQ,gBAAgB,UAAU,iBAAiB,qBACzD,gBAAgB,KAAK,QAAQ,CAC/B;EACA,MAAM,cAA+B;GACnC;GACA,UAAU;GACV,aAAa,oBAAoB;GACjC,UAAU,YAAY,CAAC;GAIvB,YAAY;EACd;EACA,IAAI,mBAAmB,KAAA,GAAW,YAAY,eAAe;EAC7D,IAAI,cAAc,KAAA,GAAW,YAAY,QAAQ;EACjD,IAAI,gBAAgB,KAAA,GAAW,YAAY,SAAS;EACpD,IAAI,qBAAqB,KAAA,GAAW,YAAY,kBAAkB;EAClE,IAAI,IAAI,gBAAgB,KAAA,GAAW,YAAY,cAAc,IAAI;EACjE,IAAI,IAAI,eAAe,KAAA,GAAW,YAAY,kBAAkB,IAAI;EACpE,IAAI,IAAI,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-tjTjZLHj.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 ImagePart,\n type LanguageModel,\n type ModelMessage,\n type TextPart,\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<TextPart | ImagePart> = m.content.map((p) => {\n let part: TextPart | ImagePart\n if (p.type === 'text') {\n part = { type: 'text', text: p.text }\n } else {\n const image_part: ImagePart = { type: 'image', image: p.image }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n part = image_part\n }\n if (p.provider_options !== undefined) {\n // Same structural cast as the call-level provider_options in\n // create_ai_sdk_turn.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n part.providerOptions = p.provider_options as NonNullable<TextPart['providerOptions']>\n }\n return 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 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 // Stamped on the first dispatched chunk, not the first stream part: the\n // SDK opens every stream with `start` and `start-step` framing before the\n // model has produced a token, and a stamp there would leave prefill inside\n // the decode window throughput() measures. This is also the native\n // transport's rule (build_native_invoke stamps in dispatch_chunk), so a\n // failure before the first token stays retryable on both.\n if (first) {\n first = false\n on_first_chunk()\n }\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 (for example, 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;;;;;;;;;;;;;;;;;;ACJA,SAAgB,kBAAkB,KAAuC;CACvE,QAAQ,KAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,UACH,O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M,KAAK,CAAC;EAE3E,MAAM,EAAE,QAAQ,gBAAgB,UAAU,iBAAiB,qBACzD,gBAAgB,KAAK,QAAQ,CAC/B;EACA,MAAM,cAA+B;GACnC;GACA,UAAU;GACV,aAAa,oBAAoB;GACjC,UAAU,YAAY,CAAC;GAIvB,YAAY;EACd;EACA,IAAI,mBAAmB,KAAA,GAAW,YAAY,eAAe;EAC7D,IAAI,cAAc,KAAA,GAAW,YAAY,QAAQ;EACjD,IAAI,gBAAgB,KAAA,GAAW,YAAY,SAAS;EACpD,IAAI,qBAAqB,KAAA,GAAW,YAAY,kBAAkB;EAClE,IAAI,IAAI,gBAAgB,KAAA,GAAW,YAAY,cAAc,IAAI;EACjE,IAAI,IAAI,eAAe,KAAA,GAAW,YAAY,kBAAkB,IAAI;EACpE,IAAI,IAAI,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"}
@@ -0,0 +1,288 @@
1
+ //#region src/schema/records.ts
2
+ /**
3
+ * Small shared guards for reading untyped JSON. They live beside the JSON
4
+ * Schema bridge that needs them and are exported, so MCP's client and result
5
+ * mapping read payloads through the same copy rather than carrying their own.
6
+ */
7
+ /**
8
+ * Narrows a value to a plain object: non-null, `typeof` object, not an array.
9
+ */
10
+ function is_record(value) {
11
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12
+ }
13
+ /**
14
+ * Returns the value when it is a plain object, otherwise `undefined`.
15
+ */
16
+ function as_record(value) {
17
+ return is_record(value) ? value : void 0;
18
+ }
19
+ //#endregion
20
+ //#region src/schema/json_schema_to_standard.ts
21
+ /**
22
+ * A Standard Schema over a plain JSON Schema, with no validator library behind
23
+ * it.
24
+ *
25
+ * Built for inbound MCP tools, which advertise their input as JSON Schema, and
26
+ * kept in the schema seam so any tool that declares its input that way can use
27
+ * it without importing zod. A Fascicle `Tool` carries a `ToolSchema` that the
28
+ * tool loop validates before `execute` and the engine emits back to the
29
+ * provider as JSON Schema. Those are two faces of one object, so this bridge
30
+ * builds both directly over the schema it is given: emission hands that schema
31
+ * back unchanged, and validation walks it.
32
+ *
33
+ * The old MCP bridge converted the advertised schema into Zod so the provider
34
+ * path could convert it back, a round trip that was lossy by construction.
35
+ * Verbatim emission is strictly higher fidelity: whatever the schema declares
36
+ * is what the model is told, including the constraints (`minLength`, `format`,
37
+ * `pattern`) the Zod conversion dropped.
38
+ *
39
+ * Validation stays deliberately loose, unchanged from the Zod bridge's reach:
40
+ * structure, types, enums, const, unions, and required keys are checked, value
41
+ * constraints are not, extra keys pass through, and anything unrecognized
42
+ * accepts. Whatever runs the call is the authority on its arguments (an MCP
43
+ * server re-validates its own), so this check is a guard against an obviously
44
+ * wrong call, not the contract.
45
+ */
46
+ /**
47
+ * Builds a `ToolSchema` over a JSON Schema, such as an MCP server's advertised
48
+ * tool input.
49
+ *
50
+ * The schema is snapshotted once, deeply, and both faces of the returned object
51
+ * read that snapshot. A malformed or hostile schema degrades to the empty
52
+ * schema during the snapshot rather than propagating an error, since an
53
+ * arbitrary remote server's advertisement must never crash tool discovery, and
54
+ * it leaves both faces describing the same thing: accept anything, emit
55
+ * nothing.
56
+ */
57
+ function json_schema_to_standard(schema) {
58
+ const advertised = snapshot(schema);
59
+ return { "~standard": {
60
+ version: 1,
61
+ vendor: "fascicle",
62
+ validate: (value) => {
63
+ const issues = check(advertised, value, []);
64
+ return issues.length === 0 ? { value } : { issues };
65
+ },
66
+ jsonSchema: {
67
+ input: () => clone_schema(advertised),
68
+ output: () => clone_schema(advertised)
69
+ }
70
+ } };
71
+ }
72
+ /**
73
+ * Deep-copies the advertised schema, or yields the empty schema when it is not
74
+ * an object or cannot be read.
75
+ *
76
+ * Copying here means every later read walks plain data: a schema with throwing
77
+ * accessors or a cycle fails once, at discovery, instead of on some later call.
78
+ */
79
+ function snapshot(schema) {
80
+ try {
81
+ return clone_schema(as_record(schema) ?? {});
82
+ } catch {
83
+ return {};
84
+ }
85
+ }
86
+ /**
87
+ * Deep-copies one JSON Schema node.
88
+ */
89
+ function clone_schema(schema) {
90
+ const copy = {};
91
+ for (const [key, value] of Object.entries(schema)) copy[key] = clone_value(value);
92
+ return copy;
93
+ }
94
+ /**
95
+ * Deep-copies a value inside a schema, recursing through arrays and objects and
96
+ * returning every other value as is.
97
+ */
98
+ function clone_value(value) {
99
+ if (Array.isArray(value)) return value.map(clone_value);
100
+ return is_record(value) ? clone_schema(value) : value;
101
+ }
102
+ /**
103
+ * Checks one value against one JSON Schema node, returning the issues it
104
+ * violated, or an empty array when it passes.
105
+ *
106
+ * A node that is not an object constrains nothing and accepts, which is what
107
+ * makes a construct this bridge does not model degrade rather than reject.
108
+ */
109
+ function check(node, value, path) {
110
+ const schema = as_record(node);
111
+ if (schema === void 0) return [];
112
+ return check_keywords(schema, value, path) ?? check_shape(schema, value, path);
113
+ }
114
+ /**
115
+ * Checks the keywords that stand on their own, returning `undefined` when the
116
+ * node carries none of them.
117
+ *
118
+ * These are checked before `type` because they can appear without one and take
119
+ * precedence when they do: a node with both `enum` and `type` is constrained by
120
+ * the enum, which is the narrower of the two.
121
+ */
122
+ function check_keywords(schema, value, path) {
123
+ if ("const" in schema) return check_const(schema["const"], value, path);
124
+ if (Array.isArray(schema["enum"])) return check_enum(schema["enum"], value, path);
125
+ if (Array.isArray(schema["anyOf"])) return check_any_of(schema["anyOf"], value, path);
126
+ if (Array.isArray(schema["oneOf"])) return check_any_of(schema["oneOf"], value, path);
127
+ if (Array.isArray(schema["allOf"])) return check_all_of(schema["allOf"], value, path);
128
+ }
129
+ /**
130
+ * Checks the node's declared shape: its `type`, in either the single or the
131
+ * array form.
132
+ *
133
+ * A node with no `type` but declared `properties` is still an object; a node
134
+ * with neither says nothing structural and accepts.
135
+ */
136
+ function check_shape(schema, value, path) {
137
+ const type = schema["type"];
138
+ if (Array.isArray(type)) return check_type_union(type, schema, value, path);
139
+ if (typeof type === "string") return check_type(type, schema, value, path);
140
+ if (is_record(schema["properties"])) return check_object(schema, value, path);
141
+ return [];
142
+ }
143
+ /**
144
+ * Checks a `const`, which pins the value to one JSON literal.
145
+ *
146
+ * An object or array `const` accepts anything: matching it would mean a deep
147
+ * comparison the server performs itself, and rejecting a valid argument is the
148
+ * one failure mode this bridge must not have.
149
+ */
150
+ function check_const(expected, value, path) {
151
+ if (expected === null) return value === null ? [] : [issue("expected null", path)];
152
+ if (typeof expected === "string" || typeof expected === "number" || typeof expected === "boolean") return value === expected ? [] : [issue(`expected ${JSON.stringify(expected)}`, path)];
153
+ return [];
154
+ }
155
+ /**
156
+ * Checks an `enum`, which pins the value to one of a list of JSON literals.
157
+ * An empty enum constrains nothing and accepts.
158
+ */
159
+ function check_enum(values, value, path) {
160
+ if (values.length === 0) return [];
161
+ if (values.some((candidate) => check_const(candidate, value, path).length === 0)) return [];
162
+ return [issue(`expected one of ${values.map((v) => JSON.stringify(v)).join(", ")}`, path)];
163
+ }
164
+ /**
165
+ * Checks an `anyOf` or `oneOf`, which passes when any branch passes.
166
+ *
167
+ * `oneOf` demands one match and only one; the bridge deliberately relaxes that
168
+ * to at least one, since the distinction only ever rejects a value the server
169
+ * would accept.
170
+ *
171
+ * A single-branch union reports that branch's own issues rather than a generic
172
+ * "no variant matched", since with one variant there is no ambiguity about
173
+ * which one failed.
174
+ */
175
+ function check_any_of(nodes, value, path) {
176
+ if (nodes.length === 0) return [];
177
+ if (nodes.length === 1) return check(nodes[0], value, path);
178
+ if (nodes.some((node) => check(node, value, path).length === 0)) return [];
179
+ return [issue(`expected one of ${nodes.length} variants`, path)];
180
+ }
181
+ /**
182
+ * Checks an `allOf`, which passes only when every branch passes.
183
+ */
184
+ function check_all_of(nodes, value, path) {
185
+ return nodes.flatMap((node) => check(node, value, path));
186
+ }
187
+ /**
188
+ * Checks the array form of `type` (`["string", "null"]`), which passes when the
189
+ * value matches any listed type. The other keywords on the node apply to
190
+ * whichever type matched, so each branch sees the whole node.
191
+ */
192
+ function check_type_union(types, schema, value, path) {
193
+ if (types.length === 0) return [];
194
+ if (types.length === 1) return check_type(String(types[0]), schema, value, path);
195
+ if (types.some((type) => check_type(String(type), schema, value, path).length === 0)) return [];
196
+ return [issue(`expected one of ${types.map(String).join(", ")}`, path)];
197
+ }
198
+ /**
199
+ * The scalar `type` keywords, as predicates over the value.
200
+ *
201
+ * `number` rejects `NaN` and infinities because neither survives JSON, and
202
+ * `integer` is the same check narrowed to whole values.
203
+ */
204
+ const SCALAR_TYPES = {
205
+ string: (value) => typeof value === "string",
206
+ number: (value) => Number.isFinite(value),
207
+ integer: (value) => Number.isInteger(value),
208
+ boolean: (value) => typeof value === "boolean",
209
+ null: (value) => value === null
210
+ };
211
+ /**
212
+ * Checks one `type` keyword. `object` and `array` recurse into the node's own
213
+ * `properties` and `items`; everything else is a scalar predicate.
214
+ *
215
+ * An unrecognized type accepts, so a vendor extension cannot reject an argument
216
+ * the server would take.
217
+ */
218
+ function check_type(type, schema, value, path) {
219
+ if (type === "object") return check_object(schema, value, path);
220
+ if (type === "array") return check_array(schema, value, path);
221
+ const matches = SCALAR_TYPES[type];
222
+ if (matches === void 0) return [];
223
+ return matches(value) ? [] : [type_issue(type, value, path)];
224
+ }
225
+ /**
226
+ * Checks an object against its `properties` and `required`.
227
+ *
228
+ * Keys the schema does not declare are left alone rather than rejected, so an
229
+ * argument this bridge did not anticipate still reaches the server, which
230
+ * re-validates and is the real authority. A `required` name with no entry in
231
+ * `properties` is likewise not enforced: there is nothing to check it against.
232
+ * Nor is a `required` that is not an array, which is malformed.
233
+ */
234
+ function check_object(schema, value, path) {
235
+ if (!is_record(value)) return [type_issue("object", value, path)];
236
+ const properties = as_record(schema["properties"]) ?? {};
237
+ const required = schema["required"];
238
+ const issues = [];
239
+ for (const [key, property] of Object.entries(properties)) {
240
+ const child = value[key];
241
+ if (child === void 0) {
242
+ if (Array.isArray(required) && required.includes(key)) issues.push(issue("required", [...path, key]));
243
+ continue;
244
+ }
245
+ issues.push(...check(property, child, [...path, key]));
246
+ }
247
+ return issues;
248
+ }
249
+ /**
250
+ * Checks an array against its `items`.
251
+ *
252
+ * A positional-tuple `items` (an array rather than a node) is not a record, so
253
+ * every element accepts. Tuple schemas are rare in MCP tools and the server
254
+ * re-validates them anyway.
255
+ */
256
+ function check_array(schema, value, path) {
257
+ if (!Array.isArray(value)) return [type_issue("array", value, path)];
258
+ return value.flatMap((item, index) => check(schema["items"], item, [...path, index]));
259
+ }
260
+ /**
261
+ * Builds a type-mismatch issue naming what was expected and what arrived.
262
+ */
263
+ function type_issue(expected, value, path) {
264
+ return issue(`expected ${expected}, received ${describe(value)}`, path);
265
+ }
266
+ /**
267
+ * Names a value's type the way a JSON Schema reader would, separating `null`
268
+ * and arrays out of `typeof`'s `object`.
269
+ */
270
+ function describe(value) {
271
+ if (value === null) return "null";
272
+ if (Array.isArray(value)) return "array";
273
+ return typeof value;
274
+ }
275
+ /**
276
+ * Builds one issue, omitting the path entirely at the root so a failure about
277
+ * the value as a whole does not report an empty path.
278
+ */
279
+ function issue(message, path) {
280
+ return path.length === 0 ? { message } : {
281
+ message,
282
+ path: [...path]
283
+ };
284
+ }
285
+ //#endregion
286
+ export { as_record as n, is_record as r, json_schema_to_standard as t };
287
+
288
+ //# sourceMappingURL=json_schema_to_standard-r21kW2LI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json_schema_to_standard-r21kW2LI.js","names":[],"sources":["../src/schema/records.ts","../src/schema/json_schema_to_standard.ts"],"sourcesContent":["/**\n * Small shared guards for reading untyped JSON. They live beside the JSON\n * Schema bridge that needs them and are exported, so MCP's client and result\n * mapping read payloads through the same copy rather than carrying their own.\n */\n\n/**\n * Narrows a value to a plain object: non-null, `typeof` object, not an array.\n */\nexport function is_record(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/**\n * Returns the value when it is a plain object, otherwise `undefined`.\n */\nexport function as_record(value: unknown): Record<string, unknown> | undefined {\n return is_record(value) ? value : undefined\n}\n","/**\n * A Standard Schema over a plain JSON Schema, with no validator library behind\n * it.\n *\n * Built for inbound MCP tools, which advertise their input as JSON Schema, and\n * kept in the schema seam so any tool that declares its input that way can use\n * it without importing zod. A Fascicle `Tool` carries a `ToolSchema` that the\n * tool loop validates before `execute` and the engine emits back to the\n * provider as JSON Schema. Those are two faces of one object, so this bridge\n * builds both directly over the schema it is given: emission hands that schema\n * back unchanged, and validation walks it.\n *\n * The old MCP bridge converted the advertised schema into Zod so the provider\n * path could convert it back, a round trip that was lossy by construction.\n * Verbatim emission is strictly higher fidelity: whatever the schema declares\n * is what the model is told, including the constraints (`minLength`, `format`,\n * `pattern`) the Zod conversion dropped.\n *\n * Validation stays deliberately loose, unchanged from the Zod bridge's reach:\n * structure, types, enums, const, unions, and required keys are checked, value\n * constraints are not, extra keys pass through, and anything unrecognized\n * accepts. Whatever runs the call is the authority on its arguments (an MCP\n * server re-validates its own), so this check is a guard against an obviously\n * wrong call, not the contract.\n */\n\nimport { as_record, is_record } from './records.js'\nimport type { SchemaIssue, ToolSchema } from './types.js'\n\n/**\n * Builds a `ToolSchema` over a JSON Schema, such as an MCP server's advertised\n * tool input.\n *\n * The schema is snapshotted once, deeply, and both faces of the returned object\n * read that snapshot. A malformed or hostile schema degrades to the empty\n * schema during the snapshot rather than propagating an error, since an\n * arbitrary remote server's advertisement must never crash tool discovery, and\n * it leaves both faces describing the same thing: accept anything, emit\n * nothing.\n */\nexport function json_schema_to_standard(schema: unknown): ToolSchema {\n const advertised = snapshot(schema)\n return {\n '~standard': {\n version: 1,\n vendor: 'fascicle',\n validate: (value: unknown) => {\n const issues = check(advertised, value, [])\n return issues.length === 0 ? { value } : { issues }\n },\n jsonSchema: {\n // `target` is ignored in both directions: fascicle applies no transform,\n // so there is no re-targeting to do, and the dialect on the wire is\n // whichever one the server chose to advertise. Each call returns a fresh\n // copy because consumers mutate what they are handed (the AI SDK stamps\n // `additionalProperties` onto it in place), and a shared snapshot would\n // stop being verbatim after the first turn.\n input: () => clone_schema(advertised),\n output: () => clone_schema(advertised),\n },\n },\n }\n}\n\n/**\n * Deep-copies the advertised schema, or yields the empty schema when it is not\n * an object or cannot be read.\n *\n * Copying here means every later read walks plain data: a schema with throwing\n * accessors or a cycle fails once, at discovery, instead of on some later call.\n */\nfunction snapshot(schema: unknown): Record<string, unknown> {\n try {\n return clone_schema(as_record(schema) ?? {})\n } catch {\n return {}\n }\n}\n\n/**\n * Deep-copies one JSON Schema node.\n */\nfunction clone_schema(schema: Record<string, unknown>): Record<string, unknown> {\n const copy: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(schema)) copy[key] = clone_value(value)\n return copy\n}\n\n/**\n * Deep-copies a value inside a schema, recursing through arrays and objects and\n * returning every other value as is.\n */\nfunction clone_value(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(clone_value)\n return is_record(value) ? clone_schema(value) : value\n}\n\n/**\n * Checks one value against one JSON Schema node, returning the issues it\n * violated, or an empty array when it passes.\n *\n * A node that is not an object constrains nothing and accepts, which is what\n * makes a construct this bridge does not model degrade rather than reject.\n */\nfunction check(node: unknown, value: unknown, path: ReadonlyArray<PropertyKey>): SchemaIssue[] {\n const schema = as_record(node)\n if (schema === undefined) return []\n return check_keywords(schema, value, path) ?? check_shape(schema, value, path)\n}\n\n/**\n * Checks the keywords that stand on their own, returning `undefined` when the\n * node carries none of them.\n *\n * These are checked before `type` because they can appear without one and take\n * precedence when they do: a node with both `enum` and `type` is constrained by\n * the enum, which is the narrower of the two.\n */\nfunction check_keywords(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] | undefined {\n if ('const' in schema) return check_const(schema['const'], value, path)\n if (Array.isArray(schema['enum'])) return check_enum(schema['enum'], value, path)\n if (Array.isArray(schema['anyOf'])) return check_any_of(schema['anyOf'], value, path)\n if (Array.isArray(schema['oneOf'])) return check_any_of(schema['oneOf'], value, path)\n if (Array.isArray(schema['allOf'])) return check_all_of(schema['allOf'], value, path)\n return undefined\n}\n\n/**\n * Checks the node's declared shape: its `type`, in either the single or the\n * array form.\n *\n * A node with no `type` but declared `properties` is still an object; a node\n * with neither says nothing structural and accepts.\n */\nfunction check_shape(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n const type = schema['type']\n if (Array.isArray(type)) return check_type_union(type, schema, value, path)\n if (typeof type === 'string') return check_type(type, schema, value, path)\n if (is_record(schema['properties'])) return check_object(schema, value, path)\n return []\n}\n\n/**\n * Checks a `const`, which pins the value to one JSON literal.\n *\n * An object or array `const` accepts anything: matching it would mean a deep\n * comparison the server performs itself, and rejecting a valid argument is the\n * one failure mode this bridge must not have.\n */\nfunction check_const(\n expected: unknown,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (expected === null) return value === null ? [] : [issue('expected null', path)]\n if (\n typeof expected === 'string' ||\n typeof expected === 'number' ||\n typeof expected === 'boolean'\n ) {\n return value === expected ? [] : [issue(`expected ${JSON.stringify(expected)}`, path)]\n }\n return []\n}\n\n/**\n * Checks an `enum`, which pins the value to one of a list of JSON literals.\n * An empty enum constrains nothing and accepts.\n */\nfunction check_enum(\n values: unknown[],\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (values.length === 0) return []\n if (values.some((candidate) => check_const(candidate, value, path).length === 0)) return []\n return [issue(`expected one of ${values.map((v) => JSON.stringify(v)).join(', ')}`, path)]\n}\n\n/**\n * Checks an `anyOf` or `oneOf`, which passes when any branch passes.\n *\n * `oneOf` demands one match and only one; the bridge deliberately relaxes that\n * to at least one, since the distinction only ever rejects a value the server\n * would accept.\n *\n * A single-branch union reports that branch's own issues rather than a generic\n * \"no variant matched\", since with one variant there is no ambiguity about\n * which one failed.\n */\nfunction check_any_of(\n nodes: unknown[],\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (nodes.length === 0) return []\n if (nodes.length === 1) return check(nodes[0], value, path)\n if (nodes.some((node) => check(node, value, path).length === 0)) return []\n return [issue(`expected one of ${nodes.length} variants`, path)]\n}\n\n/**\n * Checks an `allOf`, which passes only when every branch passes.\n */\nfunction check_all_of(\n nodes: unknown[],\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n return nodes.flatMap((node) => check(node, value, path))\n}\n\n/**\n * Checks the array form of `type` (`[\"string\", \"null\"]`), which passes when the\n * value matches any listed type. The other keywords on the node apply to\n * whichever type matched, so each branch sees the whole node.\n */\nfunction check_type_union(\n types: unknown[],\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (types.length === 0) return []\n if (types.length === 1) return check_type(String(types[0]), schema, value, path)\n if (types.some((type) => check_type(String(type), schema, value, path).length === 0)) return []\n return [issue(`expected one of ${types.map(String).join(', ')}`, path)]\n}\n\n/**\n * The scalar `type` keywords, as predicates over the value.\n *\n * `number` rejects `NaN` and infinities because neither survives JSON, and\n * `integer` is the same check narrowed to whole values.\n */\nconst SCALAR_TYPES: Record<string, (value: unknown) => boolean> = {\n string: (value) => typeof value === 'string',\n number: (value) => Number.isFinite(value),\n integer: (value) => Number.isInteger(value),\n boolean: (value) => typeof value === 'boolean',\n null: (value) => value === null,\n}\n\n/**\n * Checks one `type` keyword. `object` and `array` recurse into the node's own\n * `properties` and `items`; everything else is a scalar predicate.\n *\n * An unrecognized type accepts, so a vendor extension cannot reject an argument\n * the server would take.\n */\nfunction check_type(\n type: string,\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (type === 'object') return check_object(schema, value, path)\n if (type === 'array') return check_array(schema, value, path)\n const matches = SCALAR_TYPES[type]\n if (matches === undefined) return []\n return matches(value) ? [] : [type_issue(type, value, path)]\n}\n\n/**\n * Checks an object against its `properties` and `required`.\n *\n * Keys the schema does not declare are left alone rather than rejected, so an\n * argument this bridge did not anticipate still reaches the server, which\n * re-validates and is the real authority. A `required` name with no entry in\n * `properties` is likewise not enforced: there is nothing to check it against.\n * Nor is a `required` that is not an array, which is malformed.\n */\nfunction check_object(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (!is_record(value)) return [type_issue('object', value, path)]\n const properties = as_record(schema['properties']) ?? {}\n const required = schema['required']\n const issues: SchemaIssue[] = []\n for (const [key, property] of Object.entries(properties)) {\n const child = value[key]\n if (child === undefined) {\n if (Array.isArray(required) && required.includes(key)) {\n issues.push(issue('required', [...path, key]))\n }\n continue\n }\n issues.push(...check(property, child, [...path, key]))\n }\n return issues\n}\n\n/**\n * Checks an array against its `items`.\n *\n * A positional-tuple `items` (an array rather than a node) is not a record, so\n * every element accepts. Tuple schemas are rare in MCP tools and the server\n * re-validates them anyway.\n */\nfunction check_array(\n schema: Record<string, unknown>,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue[] {\n if (!Array.isArray(value)) return [type_issue('array', value, path)]\n return value.flatMap((item, index) => check(schema['items'], item, [...path, index]))\n}\n\n/**\n * Builds a type-mismatch issue naming what was expected and what arrived.\n */\nfunction type_issue(\n expected: string,\n value: unknown,\n path: ReadonlyArray<PropertyKey>,\n): SchemaIssue {\n return issue(`expected ${expected}, received ${describe(value)}`, path)\n}\n\n/**\n * Names a value's type the way a JSON Schema reader would, separating `null`\n * and arrays out of `typeof`'s `object`.\n */\nfunction describe(value: unknown): string {\n if (value === null) return 'null'\n if (Array.isArray(value)) return 'array'\n return typeof value\n}\n\n/**\n * Builds one issue, omitting the path entirely at the root so a failure about\n * the value as a whole does not report an empty path.\n */\nfunction issue(message: string, path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