fascicle 0.15.0 → 0.16.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.
Files changed (65) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/README.md +8 -8
  3. package/dist/acp.d.ts +9 -2
  4. package/dist/acp.js +1538 -1472
  5. package/dist/acp.js.map +1 -1
  6. package/dist/{adapters-DNnzeLxr.js → adapters-CDUzZlby.js} +35 -13
  7. package/dist/adapters-CDUzZlby.js.map +1 -0
  8. package/dist/adapters.d.ts +8 -1
  9. package/dist/adapters.js +1 -1
  10. package/dist/agents.d.ts +1 -1
  11. package/dist/agents.js +15 -8
  12. package/dist/agents.js.map +1 -1
  13. package/dist/bin/fascicle-viewer.js +4 -1
  14. package/dist/console-CdB4pcFO.js +37 -0
  15. package/dist/console-CdB4pcFO.js.map +1 -0
  16. package/dist/{core-CDrz0NM1.js → core-CErsxGF6.js} +246 -147
  17. package/dist/core-CErsxGF6.js.map +1 -0
  18. package/dist/diagram_bin.js +2 -2
  19. package/dist/diagram_bin.js.map +1 -1
  20. package/dist/{engine-ha9xmgwE.js → engine-CR8q2IqV.js} +173 -67
  21. package/dist/engine-CR8q2IqV.js.map +1 -0
  22. package/dist/index.d.ts +529 -73
  23. package/dist/index.js +440 -137
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-px31fffH.js → invoke-COaeZ-vy.js} +6 -5
  26. package/dist/invoke-COaeZ-vy.js.map +1 -0
  27. package/dist/{json_schema_to_standard-BTWD0J6p.js → json_schema_to_standard-C4F4lXHE.js} +9 -12
  28. package/dist/json_schema_to_standard-C4F4lXHE.js.map +1 -0
  29. package/dist/{leading_system-DfJLqpGi.js → leading_system-PoHzNHuV.js} +28 -8
  30. package/dist/leading_system-PoHzNHuV.js.map +1 -0
  31. package/dist/mcp.d.ts +3 -2
  32. package/dist/mcp.js +8 -4
  33. package/dist/mcp.js.map +1 -1
  34. package/dist/otel.js +10 -10
  35. package/dist/otel.js.map +1 -1
  36. package/dist/{search-CA_OqFeW.js → search-CpCJYMUm.js} +53 -6
  37. package/dist/search-CpCJYMUm.js.map +1 -0
  38. package/dist/search_worker.js +1 -1
  39. package/dist/stdio.js +7 -3
  40. package/dist/stdio.js.map +1 -1
  41. package/dist/testing.d.ts +1 -1
  42. package/dist/testing.js +3 -3
  43. package/dist/testing.js.map +1 -1
  44. package/dist/{trajectory-Bm-mOtqw.d.ts → trajectory-BKGNxi7u.d.ts} +10 -9
  45. package/dist/{trajectory-BI-mrVFT.js → trajectory-DeURWIhj.js} +6 -5
  46. package/dist/trajectory-DeURWIhj.js.map +1 -0
  47. package/dist/{types-De-TVQxS.d.ts → types-Sw0oHW-_.d.ts} +6 -7
  48. package/dist/ui.d.ts +2 -1
  49. package/dist/ui.js +8 -1
  50. package/dist/ui.js.map +1 -1
  51. package/dist/viewer-app/assets/index-BYF5Dp7d.js +2 -0
  52. package/dist/viewer-app/index.html +2 -1
  53. package/dist/viewer.d.ts +26 -12
  54. package/dist/viewer.js +282 -63
  55. package/dist/viewer.js.map +1 -1
  56. package/package.json +5 -5
  57. package/dist/adapters-DNnzeLxr.js.map +0 -1
  58. package/dist/core-CDrz0NM1.js.map +0 -1
  59. package/dist/engine-ha9xmgwE.js.map +0 -1
  60. package/dist/invoke-px31fffH.js.map +0 -1
  61. package/dist/json_schema_to_standard-BTWD0J6p.js.map +0 -1
  62. package/dist/leading_system-DfJLqpGi.js.map +0 -1
  63. package/dist/search-CA_OqFeW.js.map +0 -1
  64. package/dist/trajectory-BI-mrVFT.js.map +0 -1
  65. package/dist/viewer-app/assets/index-Fnh5HKSU.js +0 -2
@@ -1,5 +1,5 @@
1
- import { k as aborted_error } from "./core-CDrz0NM1.js";
2
- import { a as is_own_reasoning, d as load_optional_peer, t as split_leading_system_run, u as default_normalize_usage } from "./leading_system-DfJLqpGi.js";
1
+ import { k as aborted_error } from "./core-CErsxGF6.js";
2
+ import { a as is_own_reasoning, d as load_optional_peer, t as split_leading_system_run, u as default_normalize_usage } from "./leading_system-PoHzNHuV.js";
3
3
  import { NoObjectGeneratedError, Output, generateText, isStepCount, streamText, tool } from "ai";
4
4
  //#region src/engine/providers/ai_sdk/telemetry.ts
5
5
  /**
@@ -149,7 +149,8 @@ function to_provider_reported(metadata) {
149
149
  * assistant part's provider_options go back as its providerOptions, which is
150
150
  * where the SDK reads a signature or a thought signature back from, and a
151
151
  * reasoning part goes back only when it carries data under `metadata_key`,
152
- * the key the adapter's package writes (D3 own-reasoning-only).
152
+ * the key the adapter's package writes, so a turn only ever sends back its
153
+ * own provider's reasoning.
153
154
  */
154
155
  function to_sdk_messages(messages, metadata_key) {
155
156
  const out = [];
@@ -298,7 +299,7 @@ function with_part_options(turn_part, metadata) {
298
299
  * Map an SDK step's content to TurnResult.content: its text, reasoning, and
299
300
  * tool calls in the order the provider sent them, each with its
300
301
  * providerMetadata as provider_options. Undefined when no part is reasoning
301
- * or carries data, so every other turn stays exactly what it was (D18).
302
+ * or carries data, so every other turn stays exactly what it was.
302
303
  */
303
304
  function to_turn_content(content) {
304
305
  const parts = content.flatMap((part) => to_turn_part(part) ?? []);
@@ -559,4 +560,4 @@ function create_ai_sdk_turn(cfg) {
559
560
  //#endregion
560
561
  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, to_turn_content };
561
562
 
562
- //# sourceMappingURL=invoke-px31fffH.js.map
563
+ //# sourceMappingURL=invoke-COaeZ-vy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invoke-COaeZ-vy.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 AssistantContent,\n type ContentPart,\n type ImagePart,\n type LanguageModel,\n type ModelMessage,\n type TextPart,\n type TextStreamPart,\n type ToolCallPart,\n type ToolSet,\n} from 'ai'\nimport type { ToolSchema } from '#schema'\nimport type {\n AiSdkTelemetrySettings,\n AssistantContentPart,\n FinishReason,\n Message,\n ProviderOptions,\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 EffortTranslation,\n type RawProviderUsage,\n} from '../types.js'\nimport { is_own_reasoning } from '../native_shared.js'\nimport { build_ai_sdk_telemetry, type AiSdkTelemetryPassthrough } from './telemetry.js'\n\n// The SDK exports no name for an assistant reasoning part, so it is read off\n// the assistant content union.\ntype SdkReasoningPart = Extract<Exclude<AssistantContent, string>[number], { type: 'reasoning' }>\n\n/**\n * Attach a Fascicle part's provider_options to an SDK prompt part as its\n * providerOptions, the key the SDK reads a part's provider data back from.\n */\nfunction with_provider_options<part extends { providerOptions?: TextPart['providerOptions'] }>(\n sdk_part: part,\n provider_options: ProviderOptions | undefined,\n): part {\n if (provider_options === undefined) return sdk_part\n // ProviderOptions is the two-level provider map the SDK's shared provider\n // options spell with JSON values; the payloads are the SDK's own metadata.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return { ...sdk_part, providerOptions: provider_options as NonNullable<part['providerOptions']> }\n}\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. Each\n * assistant part's provider_options go back as its providerOptions, which is\n * where the SDK reads a signature or a thought signature back from, and a\n * reasoning part goes back only when it carries data under `metadata_key`,\n * the key the adapter's package writes, so a turn only ever sends back its\n * own provider's reasoning.\n */\nexport function to_sdk_messages(\n messages: ReadonlyArray<Message>,\n metadata_key: string,\n): 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 if (p.type === 'text') {\n return with_provider_options<TextPart>({ type: 'text', text: p.text }, p.provider_options)\n }\n const image_part: ImagePart = { type: 'image', image: p.image }\n if (p.media_type !== undefined) image_part.mediaType = p.media_type\n return with_provider_options(image_part, p.provider_options)\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.flatMap((p): Array<TextPart | SdkReasoningPart | ToolCallPart> => {\n if (p.type === 'text') {\n return [with_provider_options<TextPart>({ type: 'text', text: p.text }, p.provider_options)]\n }\n if (p.type === 'reasoning') {\n // Another package's reasoning, or reasoning with no data, would draw a\n // warning or a refusal from this one.\n if (!is_own_reasoning(p, metadata_key)) return []\n return [\n with_provider_options<SdkReasoningPart>(\n { type: 'reasoning', text: p.text },\n p.provider_options,\n ),\n ]\n }\n return [\n with_provider_options<ToolCallPart>(\n { type: 'tool-call', toolCallId: p.id, toolName: p.name, input: p.input },\n p.provider_options,\n ),\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 * Read a part's providerMetadata as provider_options, or undefined when it\n * carries none, so a part with nothing to send back stays bare.\n */\nfunction to_part_options(metadata: ProviderOptions | undefined): ProviderOptions | undefined {\n return metadata !== undefined && Object.keys(metadata).length > 0 ? metadata : undefined\n}\n\n/**\n * Map one SDK content part to an assistant part with its providerMetadata as\n * provider_options, or undefined for a kind with nothing to send back\n * (sources, files, tool results).\n */\nfunction to_turn_part(part: ContentPart<ToolSet>): AssistantContentPart | undefined {\n if (part.type === 'text') {\n return with_part_options({ type: 'text', text: part.text }, part.providerMetadata)\n }\n if (part.type === 'reasoning') {\n return with_part_options({ type: 'reasoning', text: part.text }, part.providerMetadata)\n }\n if (part.type === 'tool-call') {\n return with_part_options(\n { type: 'tool_call', id: part.toolCallId, name: part.toolName, input: part.input },\n part.providerMetadata,\n )\n }\n return undefined\n}\n\n/**\n * Give an assistant part the provider_options its metadata carries, leaving\n * the key off when there is none.\n */\nfunction with_part_options<part extends AssistantContentPart>(\n turn_part: part,\n metadata: ProviderOptions | undefined,\n): part {\n const provider_options = to_part_options(metadata)\n return provider_options === undefined ? turn_part : { ...turn_part, provider_options }\n}\n\n/**\n * Map an SDK step's content to TurnResult.content: its text, reasoning, and\n * tool calls in the order the provider sent them, each with its\n * providerMetadata as provider_options. Undefined when no part is reasoning\n * or carries data, so every other turn stays exactly what it was.\n */\nexport function to_turn_content(\n content: ReadonlyArray<ContentPart<ToolSet>>,\n): AssistantContentPart[] | undefined {\n const parts = content.flatMap((part) => to_turn_part(part) ?? [])\n const carries = parts.some(\n (part) => part.type === 'reasoning' || part.provider_options !== undefined,\n )\n return carries ? parts : undefined\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 // The step's content settles once the stream has drained, so it is read\n // only after the loop and never on a failed stream.\n const content = to_turn_content(await stream_result.content)\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 ...(content !== undefined ? { content } : {}),\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 const content = to_turn_content(result.content)\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 ...(content !== undefined ? { content } : {}),\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 reasoning: EffortTranslation['reasoning']\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, cfg.adapter.metadata_key ?? cfg.adapter.name),\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 // The SDK's own effort option; the provider package maps the level per\n // model, and leaving it out is the provider's default.\n if (cfg.reasoning !== undefined) base_params.reasoning = cfg.reasoning\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;;;;;;;;;;;;;;;;;;;ACQA,SAAS,sBACP,UACA,kBACM;CACN,IAAI,qBAAqB,KAAA,GAAW,OAAO;CAI3C,OAAO;EAAE,GAAG;EAAU,iBAAiB;CAAyD;AAClG;;;;AAKA,SAAgB,kBAAkB,KAAuC;CACvE,QAAQ,KAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK;EACL,KAAK,kBACH,OAAO;E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M,KAAK,CAAC;EAE3E,MAAM,EAAE,QAAQ,gBAAgB,UAAU,iBAAiB,qBACzD,gBAAgB,KAAK,UAAU,IAAI,QAAQ,gBAAgB,IAAI,QAAQ,IAAI,CAC7E;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;EAGpD,IAAI,IAAI,cAAc,KAAA,GAAW,YAAY,YAAY,IAAI;EAC7D,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"}
@@ -12,18 +12,15 @@ import { n as is_record, t as as_record } from "./records-1HU7mWXf.js";
12
12
  * builds both directly over the schema it is given: emission hands that schema
13
13
  * back unchanged, and validation walks it.
14
14
  *
15
- * The old MCP bridge converted the advertised schema into Zod so the provider
16
- * path could convert it back, a round trip that was lossy by construction.
17
- * Verbatim emission is strictly higher fidelity: whatever the schema declares
18
- * is what the model is told, including the constraints (`minLength`, `format`,
19
- * `pattern`) the Zod conversion dropped.
15
+ * Emitting the schema verbatim keeps it lossless: whatever the schema declares
16
+ * is what the model is told, constraints (`minLength`, `format`, `pattern`)
17
+ * included, with no conversion through a validator library to drop them.
20
18
  *
21
- * Validation stays deliberately loose, unchanged from the Zod bridge's reach:
22
- * structure, types, enums, const, unions, and required keys are checked, value
23
- * constraints are not, extra keys pass through, and anything unrecognized
24
- * accepts. Whatever runs the call is the authority on its arguments (an MCP
25
- * server re-validates its own), so this check is a guard against an obviously
26
- * wrong call, not the contract.
19
+ * Validation is deliberately loose: structure, types, enums, const, unions,
20
+ * and required keys are checked, value constraints are not, extra keys pass
21
+ * through, and anything unrecognized accepts. Whatever runs the call is the
22
+ * authority on its arguments (an MCP server re-validates its own), so this
23
+ * check is a guard against an obviously wrong call, not the contract.
27
24
  */
28
25
  /**
29
26
  * Builds a `ToolSchema` over a JSON Schema, such as an MCP server's advertised
@@ -267,4 +264,4 @@ function issue(message, path) {
267
264
  //#endregion
268
265
  export { json_schema_to_standard as t };
269
266
 
270
- //# sourceMappingURL=json_schema_to_standard-BTWD0J6p.js.map
267
+ //# sourceMappingURL=json_schema_to_standard-C4F4lXHE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"json_schema_to_standard-C4F4lXHE.js","names":[],"sources":["../src/schema/json_schema_to_standard.ts"],"sourcesContent":["/**\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 * Emitting the schema verbatim keeps it lossless: whatever the schema declares\n * is what the model is told, constraints (`minLength`, `format`, `pattern`)\n * included, with no conversion through a validator library to drop them.\n *\n * Validation is deliberately loose: structure, types, enums, const, unions,\n * and required keys are checked, value constraints are not, extra keys pass\n * through, and anything unrecognized accepts. Whatever runs the call is the\n * authority on its arguments (an MCP server re-validates its own), so this\n * check is a guard against an obviously 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: ReadonlyArray<PropertyKey>): SchemaIssue {\n return path.length === 0 ? { message } : { message, path: [...path] }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,wBAAwB,QAA6B;CACnE,MAAM,aAAa,SAAS,MAAM;CAClC,OAAO,EACL,aAAa;EACX,SAAS;EACT,QAAQ;EACR,WAAW,UAAmB;GAC5B,MAAM,SAAS,MAAM,YAAY,OAAO,CAAC,CAAC;GAC1C,OAAO,OAAO,WAAW,IAAI,EAAE,MAAM,IAAI,EAAE,OAAO;EACpD;EACA,YAAY;GAOV,aAAa,aAAa,UAAU;GACpC,cAAc,aAAa,UAAU;EACvC;CACF,EACF;AACF;;;;;;;;AASA,SAAS,SAAS,QAA0C;CAC1D,IAAI;EACF,OAAO,aAAa,UAAU,MAAM,KAAK,CAAC,CAAC;CAC7C,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;;;AAKA,SAAS,aAAa,QAA0D;CAC9E,MAAM,OAAgC,CAAC;CACvC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAAG,KAAK,OAAO,YAAY,KAAK;CAChF,OAAO;A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MAAM,UAAU,MAAM,OAAO,UAAU,MAAM,CAAC,GAAG,MAAM,KAAK,CAAC,CAAC;AACtF;;;;AAKA,SAAS,WACP,UACA,OACA,MACa;CACb,OAAO,MAAM,YAAY,SAAS,aAAa,SAAS,KAAK,KAAK,IAAI;AACxE;;;;;AAMA,SAAS,SAAS,OAAwB;CACxC,IAAI,UAAU,MAAM,OAAO;CAC3B,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,OAAO;AAChB;;;;;AAMA,SAAS,MAAM,SAAiB,MAA+C;CAC7E,OAAO,KAAK,WAAW,IAAI,EAAE,QAAQ,IAAI;EAAE;EAAS,MAAM,CAAC,GAAG,IAAI;CAAE;AACtE"}
@@ -1,4 +1,4 @@
1
- import "./core-CDrz0NM1.js";
1
+ import "./core-CErsxGF6.js";
2
2
  //#region src/engine/errors.ts
3
3
  var rate_limit_error = class extends Error {
4
4
  kind = "rate_limit_error";
@@ -368,19 +368,40 @@ function rethrow_network_failure(err, abort, provider) {
368
368
  throw Object.assign(/* @__PURE__ */ new Error(`${provider} native: network failure: ${detail}`), { kind: "network" });
369
369
  }
370
370
  /**
371
+ * Read a non-stream response body and parse it as JSON. A read that fails
372
+ * partway is a transport failure, wrapped as network the way a failed stream
373
+ * read is; a body that arrives whole but does not parse is a permanent
374
+ * provider_error naming what came back.
375
+ */
376
+ async function read_json_body(response, abort, provider) {
377
+ let text;
378
+ try {
379
+ text = await response.text();
380
+ } catch (err) {
381
+ rethrow_network_failure(err, abort, provider);
382
+ }
383
+ try {
384
+ return JSON.parse(text);
385
+ } catch {
386
+ throw new provider_error(`${provider} native: response body is not valid JSON: check that base_url points at the ${provider} API (body: ${extract_error_message(text)})`);
387
+ }
388
+ }
389
+ /**
371
390
  * Run one native turn over HTTP: POST the dialect's body, map a non-2xx to
372
391
  * the retry stack's shapes, and hand the response to the dialect's stream or
373
- * JSON consumer. `build_body` is called inside the network try/catch on
374
- * purpose, so a mapper that throws surfaces as a retryable network failure
375
- * rather than escaping the turn unclassified.
392
+ * JSON consumer. `build_body` runs before the network try/catch, so a mapper
393
+ * that rejects the request (e.g., a provider_capability_error for a part the
394
+ * wire cannot carry) propagates unchanged instead of being retried as a
395
+ * network failure.
376
396
  */
377
397
  async function invoke_http_turn(req, provider, request, consume) {
398
+ const body = JSON.stringify(request.build_body());
378
399
  let response;
379
400
  try {
380
401
  response = await fetch(request.url, {
381
402
  method: "POST",
382
403
  headers: request.headers,
383
- body: JSON.stringify(request.build_body()),
404
+ body,
384
405
  signal: req.abort
385
406
  });
386
407
  } catch (err) {
@@ -388,8 +409,7 @@ async function invoke_http_turn(req, provider, request, consume) {
388
409
  }
389
410
  if (!response.ok) throw await response_error(response, provider);
390
411
  if (req.stream) return consume.stream(response);
391
- const payload = await response.json();
392
- return consume.parse(payload);
412
+ return consume.parse(await read_json_body(response, req.abort, provider));
393
413
  }
394
414
  /**
395
415
  * Drain a streaming response: decode bytes, reassemble framed payloads (SSE
@@ -581,4 +601,4 @@ function is_leading_system(m) {
581
601
  //#endregion
582
602
  export { tool_error as A, provider_capability_error as C, rate_limit_error as D, provider_required_error as E, schema_validation_error as O, provider_auth_error as S, provider_not_configured_error as T, engine_config_error as _, is_own_reasoning as a, model_required_error as b, read_dialect_init as c, load_optional_peer as d, missing_peer_error as f, claude_cli_error as g, translate_effort_to_sdk_reasoning as h, invoke_http_turn as i, turn_timeout_error as j, tool_approval_denied_error as k, split_assistant_parts as l, resolve_transport as m, consume_framed_stream as n, map_messages_by_role as o, normalize_local_usage as p, create_line_splitter as r, parse_tool_call_arguments as s, split_leading_system_run as t, default_normalize_usage as u, engine_disposed_error as v, provider_error as w, on_chunk_error as x, incomplete_generation_error as y };
583
603
 
584
- //# sourceMappingURL=leading_system-DfJLqpGi.js.map
604
+ //# sourceMappingURL=leading_system-PoHzNHuV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leading_system-PoHzNHuV.js","names":[],"sources":["../src/engine/errors.ts","../src/engine/providers/types.ts","../src/engine/providers/native_shared.ts","../src/engine/leading_system.ts"],"sourcesContent":["/**\n * Typed errors for the AI engine layer.\n *\n * This is the only source file in the engine module permitted to use the\n * `class` keyword. `Error` is a built-in and `instanceof` branching is how\n * the retry helper and composition-layer composers distinguish failure modes.\n * Every other engine file stays class-free.\n *\n * `aborted_error` is defined in the core module and re-exported here so that\n * `instanceof aborted_error` is true regardless of which layer surfaced it.\n * This is the one value-level import from core permitted in engine source;\n * see the ignores in `rules/no-core-value-import-in-engine.yml`.\n *\n * Every class declares an optional `path`: the chain of step ids the error\n * crossed while bubbling through the core runner's dispatch. The runner\n * attaches it via Reflect.set (`prepend_path` in core's runner.ts), so the\n * `declare` modifier types what arrives without emitting a field;\n * construction never sets it.\n */\n\nimport type { SchemaIssue } from '#schema'\nimport type { FinishReason } from './types.js'\n\nexport { aborted_error } from '#core'\n\nexport class rate_limit_error extends Error {\n readonly kind = 'rate_limit_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly retry_after_ms: number | undefined;\n readonly attempts: number;\n readonly status: number | undefined;\n constructor(\n message: string,\n metadata: { retry_after_ms?: number; attempts?: number; status?: number } = {},\n ) {\n super(message)\n this.name = 'rate_limit_error'\n this.retry_after_ms = metadata.retry_after_ms\n this.attempts = metadata.attempts ?? 0\n this.status = metadata.status\n }\n}\n\nexport class provider_error extends Error {\n readonly kind = 'provider_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly status: number | undefined;\n readonly body: string | undefined;\n readonly cause_kind: 'provider_5xx' | 'network' | 'unknown' | undefined;\n constructor(\n message: string,\n metadata: {\n status?: number\n body?: string\n cause_kind?: 'provider_5xx' | 'network' | 'unknown'\n } = {},\n ) {\n super(message)\n this.name = 'provider_error'\n this.status = metadata.status\n this.body = metadata.body\n this.cause_kind = metadata.cause_kind\n }\n}\n\n/**\n * Turn-timeout expiry. Thrown by the engine-owned retry_turn wrapper when a\n * single invoke_turn exceeds `turn_timeout_ms` before any chunk streamed.\n * Its `kind` is the RetryFailureKind wire value `'timeout'` (not the class\n * name) on purpose: that is the discriminant classify_retryable /\n * classify_provider_error already key on, so the shared classifier treats an\n * expiry as retryable without any timeout-specific branch. A mid-stream\n * expiry never reaches here; retry_turn converts it to a non-retryable\n * stream interruption first.\n */\nexport class turn_timeout_error extends Error {\n readonly kind = 'timeout' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly timeout_ms: number;\n readonly step_index: number | undefined;\n constructor(timeout_ms: number, step_index?: number) {\n super(`turn exceeded turn_timeout_ms budget of ${timeout_ms}ms`)\n this.name = 'turn_timeout_error'\n this.timeout_ms = timeout_ms\n this.step_index = step_index\n }\n}\n\nexport class schema_validation_error extends Error {\n readonly kind = 'schema_validation_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly schema_issues: ReadonlyArray<SchemaIssue>;\n readonly raw_text: string;\n constructor(message: string, schema_issues: ReadonlyArray<SchemaIssue>, raw_text: string) {\n super(message)\n this.name = 'schema_validation_error'\n this.schema_issues = schema_issues\n this.raw_text = raw_text\n }\n}\n\nexport class tool_error extends Error {\n readonly kind = 'tool_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly tool_name: string;\n readonly tool_call_id: string;\n override readonly cause: unknown;\n constructor(\n message: string,\n metadata: { tool_name: string; tool_call_id: string; cause: unknown },\n ) {\n super(message)\n this.name = 'tool_error'\n this.tool_name = metadata.tool_name\n this.tool_call_id = metadata.tool_call_id\n this.cause = metadata.cause\n }\n}\n\nexport class tool_approval_denied_error extends Error {\n readonly kind = 'tool_approval_denied_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly tool_name: string;\n readonly step_index: number;\n readonly tool_call_id: string;\n constructor(\n message: string,\n metadata: { tool_name: string; step_index: number; tool_call_id: string },\n ) {\n super(message)\n this.name = 'tool_approval_denied_error'\n this.tool_name = metadata.tool_name\n this.step_index = metadata.step_index\n this.tool_call_id = metadata.tool_call_id\n }\n}\n\nexport class model_required_error extends Error {\n readonly kind = 'model_required_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n constructor(\n message = 'no model specified: pass `model` to generate() or set `defaults.model` on the engine',\n ) {\n super(message)\n this.name = 'model_required_error'\n }\n}\n\n/**\n * A generate call named a provider the engine has no adapter for. Carries the\n * configured names, and the message repeats them, so a typo is visible from\n * the message alone rather than needing the engine config alongside it.\n */\nexport class provider_not_configured_error extends Error {\n readonly kind = 'provider_not_configured_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly provider: string;\n readonly configured: ReadonlyArray<string>;\n constructor(provider: string, configured: ReadonlyArray<string> = []) {\n const state = configured.length > 0 ? configured.join(', ') : 'none'\n super(\n `provider '${provider}' is not configured on this engine: pass it to create_engine({ providers }) (configured: ${state})`,\n )\n this.name = 'provider_not_configured_error'\n this.provider = provider\n this.configured = configured\n }\n}\n\n/**\n * No provider could be resolved for a generate call: several providers are\n * configured, the call named none, and no `defaults.provider` is set. Carries\n * the configured provider names so the message tells the caller exactly what\n * the engine can route to.\n */\nexport class provider_required_error extends Error {\n readonly kind = 'provider_required_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly configured: ReadonlyArray<string>;\n constructor(configured: ReadonlyArray<string>) {\n super(\n `no provider specified: pass \\`provider\\` to generate() or set \\`defaults.provider\\` (configured: ${configured.join(', ')})`,\n )\n this.name = 'provider_required_error'\n this.configured = configured\n }\n}\n\nexport class engine_config_error extends Error {\n readonly kind = 'engine_config_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly provider: string | undefined;\n constructor(message: string, provider?: string) {\n super(message)\n this.name = 'engine_config_error'\n this.provider = provider\n }\n}\n\nexport class on_chunk_error extends Error {\n readonly kind = 'on_chunk_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n override readonly cause: unknown;\n constructor(message: string, cause: unknown) {\n super(message)\n this.name = 'on_chunk_error'\n this.cause = cause\n }\n}\n\nexport class provider_capability_error extends Error {\n readonly kind = 'provider_capability_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly provider: string;\n readonly capability: string;\n constructor(provider: string, capability: string, detail?: string) {\n const suffix = detail !== undefined ? `: ${detail}` : ''\n super(`provider '${provider}' does not support '${capability}'${suffix}`)\n this.name = 'provider_capability_error'\n this.provider = provider\n this.capability = capability\n }\n}\n\nexport class engine_disposed_error extends Error {\n readonly kind = 'engine_disposed_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n constructor(message = 'engine has been disposed: build a new one with create_engine()') {\n super(message)\n this.name = 'engine_disposed_error'\n }\n}\n\nexport type ClaudeCliErrorReason =\n | 'binary_not_found'\n | 'startup_timeout'\n | 'stall_timeout'\n | 'no_result_event'\n | 'result_error'\n | 'subprocess_exit'\n | 'sandbox_unavailable'\n\nexport class claude_cli_error extends Error {\n readonly kind = 'claude_cli_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly reason: ClaudeCliErrorReason;\n readonly status: number | undefined;\n readonly stderr_snippet: string | undefined;\n constructor(\n reason: ClaudeCliErrorReason,\n message: string,\n metadata: { status?: number; stderr_snippet?: string } = {},\n ) {\n super(message)\n this.name = 'claude_cli_error'\n this.reason = reason\n this.status = metadata.status\n this.stderr_snippet = metadata.stderr_snippet\n }\n}\n\nexport class provider_auth_error extends Error {\n readonly kind = 'provider_auth_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly provider: string;\n readonly refresh_command: string | undefined;\n constructor(\n provider: string,\n message: string,\n metadata: { refresh_command?: string } = {},\n ) {\n super(message)\n this.name = 'provider_auth_error'\n this.provider = provider\n this.refresh_command = metadata.refresh_command\n }\n}\n\n/**\n * A generate call that set a schema finished for a reason other than 'stop'\n * (content_filter, length, max_steps, tool_calls), so no schema-validated\n * value exists and validation was never attempted. Carries the raw model text\n * and the last provider-reported payload, so a guardrail trace or other\n * block detail stays reachable from the catch. Distinct from\n * schema_validation_error, which covers a response that completed normally\n * and then failed validation after its repair attempts ran out.\n */\nexport class incomplete_generation_error extends Error {\n readonly kind = 'incomplete_generation_error' as const;\n declare readonly path?: ReadonlyArray<string>;\n readonly finish_reason: FinishReason;\n readonly raw_text: string;\n readonly provider_reported: Record<string, unknown> | undefined;\n constructor(\n finish_reason: FinishReason,\n raw_text: string,\n provider_reported?: Record<string, unknown>,\n ) {\n super(\n `generation finished with '${finish_reason}' before a schema-validated response was produced`,\n )\n this.name = 'incomplete_generation_error'\n this.finish_reason = finish_reason\n this.raw_text = raw_text\n this.provider_reported = provider_reported\n }\n}\n","/**\n * Shared provider-adapter shape.\n *\n * Each file under src/engine/providers/ exports a factory that accepts a\n * ProviderInit shape and returns a ProviderAdapter. Factories are\n * synchronous; build_model is async so SDK loading is deferred until a model\n * is actually needed. A missing peer dependency surfaces on the first\n * build_model call as a plain Error naming the peer and its install command\n * (see missing_peer_error).\n *\n * Only the ai_sdk transport module (providers/ai_sdk/invoke.ts) may import\n * from `ai` or invoke generateText/streamText. ai_sdk adapters build the\n * provider model and translate parameters; they do not orchestrate the call.\n */\n\nimport type {\n ResolvedModel,\n EffortLevel,\n GenerateOptions,\n GenerateResult,\n ProviderInit,\n TurnRequest,\n TurnResult,\n UsageTotals,\n} from '../types.js'\nimport { engine_config_error } from '../errors.js'\n\n/**\n * Which backend a provider factory returns: 'ai_sdk' wraps the Vercel AI SDK\n * provider package, 'native' talks to the provider's HTTP API directly. The\n * provider name stays the same across transports so pricing keys and usage\n * fields carry over; only the wire implementation changes.\n */\nexport type ProviderTransport = 'ai_sdk' | 'native'\n\n/**\n * Read the `transport` selector off a provider init. Defaults to 'ai_sdk';\n * anything but the two known backends throws at construction so a typo\n * fails loud instead of silently running the default.\n */\nexport function resolve_transport(\n init: ProviderInit,\n provider: string,\n): ProviderTransport {\n const raw = init['transport']\n if (raw === undefined || raw === 'ai_sdk') return 'ai_sdk'\n if (raw === 'native') return 'native'\n throw new engine_config_error(\n `${provider} provider: transport must be 'ai_sdk' or 'native', got ${JSON.stringify(raw)}`,\n provider,\n )\n}\n\nexport type EffortTranslation = {\n // Outer keys are provider names, inner records hold per-provider settings,\n // matching the two-level shape merge_provider_options expects.\n provider_options: Record<string, Record<string, unknown>>\n effort_ignored: boolean\n // A level for the AI SDK's own `reasoning` call option, which the provider\n // package maps per model. Left out, the SDK uses the provider's default.\n reasoning?: Exclude<EffortLevel, 'none'>\n}\n\n/**\n * Hand effort to the AI SDK's `reasoning` option and build no provider\n * options of its own, so the provider package maps each level per model from\n * the capability table it keeps (adaptive thinking or a budget for Claude,\n * `thinkingLevel` or a budget for Gemini, `reasoningEffort` for OpenAI).\n * `none` sends neither, which is the SDK's provider default. The anthropic,\n * bedrock, google, and openai ai_sdk adapters all translate this way.\n */\nexport function translate_effort_to_sdk_reasoning(effort: EffortLevel): EffortTranslation {\n if (effort === 'none') return { provider_options: {}, effort_ignored: false }\n return { provider_options: {}, effort_ignored: false, reasoning: effort }\n}\n\nexport type ProviderCapability =\n | 'text'\n | 'tools'\n | 'schema'\n | 'streaming'\n | 'image_input'\n | 'reasoning'\n // Provider performs native constrained decoding (the AI SDK responseFormat /\n // Output.object path), as opposed to the prompt-for-JSON-then-extract path.\n // Distinct from 'schema': every provider can satisfy a schema via repair, but\n // only some constrain the decode to it.\n | 'structured_output'\n\nexport type RawProviderUsage = {\n input_tokens?: number\n output_tokens?: number\n reasoning_tokens?: number\n cached_input_tokens?: number\n cache_write_tokens?: number\n // The Vercel AI SDK also surfaces details via *Details containers; adapters\n // accept the flattened shape above for testability.\n input_token_details?: {\n cached_tokens?: number\n cache_creation_input_tokens?: number\n }\n output_token_details?: {\n reasoning_tokens?: number\n }\n [k: string]: unknown\n}\n\nexport type AiSdkProviderAdapter = {\n readonly kind: 'ai_sdk'\n readonly name: string\n // The key the adapter's package writes providerMetadata under, which is\n // the only key a reasoning part may carry to be sent back. Defaults\n // to `name`; a custom adapter over a built-in package (@ai-sdk/anthropic on\n // Vertex, say) can't take the built-in name, so it sets the package's key.\n readonly metadata_key?: string\n readonly build_model: (model_id: string) => Promise<unknown>\n readonly translate_effort: (effort: EffortLevel) => EffortTranslation\n readonly normalize_usage: (raw: RawProviderUsage | undefined) => UsageTotals\n readonly supports: (capability: ProviderCapability) => boolean\n}\n\n/**\n * Raw-HTTP transport: implements a single turn against a provider's own\n * API with zero `ai` / `@ai-sdk/*` in its module graph. generate.ts wraps\n * invoke_turn in retry + classification + abort, so a native adapter owns only\n * request/response mapping (and streaming via TurnRequest.dispatch_chunk); it\n * MUST NOT implement its own retry. classify_error optionally overrides the\n * shared classifier; dispose is optional (keep-alive agents, connection pools).\n */\nexport type NativeProviderAdapter = {\n readonly kind: 'native'\n readonly name: string\n readonly invoke_turn: (req: TurnRequest) => Promise<TurnResult>\n readonly supports: (capability: ProviderCapability) => boolean\n readonly dispose?: () => Promise<void>\n readonly classify_error?: (err: unknown) => unknown\n}\n\nexport type ExternalAgentAdapter = {\n readonly kind: 'external'\n readonly name: string\n readonly generate: <t>(\n opts: GenerateOptions<t>,\n resolved: ResolvedModel,\n ) => Promise<GenerateResult<t>>\n readonly dispose: () => Promise<void>\n readonly supports: (capability: ProviderCapability) => boolean\n}\n\nexport type ProviderAdapter =\n | AiSdkProviderAdapter\n | NativeProviderAdapter\n | ExternalAgentAdapter\n\nexport type ProviderFactory = (init: ProviderInit) => ProviderAdapter\n\n/**\n * Map raw provider usage to UsageTotals, the mapper most adapters share.\n *\n * Missing usage zeroes the totals. Optional fields (reasoning and cache\n * tokens) are set only when the raw payload carries them, reading the\n * flattened field first and the AI SDK's *_details container second.\n */\nexport function default_normalize_usage(\n raw: RawProviderUsage | undefined,\n): UsageTotals {\n if (raw === undefined) return { input_tokens: 0, output_tokens: 0 }\n const input_tokens = typeof raw.input_tokens === 'number' ? raw.input_tokens : 0\n const output_tokens = typeof raw.output_tokens === 'number' ? raw.output_tokens : 0\n const totals: UsageTotals = { input_tokens, output_tokens }\n if (typeof raw.reasoning_tokens === 'number') totals.reasoning_tokens = raw.reasoning_tokens\n else if (typeof raw.output_token_details?.reasoning_tokens === 'number') {\n totals.reasoning_tokens = raw.output_token_details.reasoning_tokens\n }\n if (typeof raw.cached_input_tokens === 'number') totals.cached_input_tokens = raw.cached_input_tokens\n else if (typeof raw.input_token_details?.cached_tokens === 'number') {\n totals.cached_input_tokens = raw.input_token_details.cached_tokens\n }\n if (typeof raw.cache_write_tokens === 'number') totals.cache_write_tokens = raw.cache_write_tokens\n else if (typeof raw.input_token_details?.cache_creation_input_tokens === 'number') {\n totals.cache_write_tokens = raw.input_token_details.cache_creation_input_tokens\n }\n return totals\n}\n\n/**\n * Usage mapper for local backends (Ollama, LM Studio) whose servers never\n * report cache or reasoning tokens: default-normalize, then strip those\n * fields so a stray *_details container cannot invent them.\n */\nexport function normalize_local_usage(raw: RawProviderUsage | undefined): UsageTotals {\n const base = default_normalize_usage(raw)\n delete base.cached_input_tokens\n delete base.cache_write_tokens\n delete base.reasoning_tokens\n return base\n}\n\n/**\n * Build the standard missing-peer error: names the package and the install\n * command so a missing peer is diagnosable from the message alone. Shared so\n * every optional-peer failure reads identically, whether the failing\n * `import()` names the peer directly (load_optional_peer below) or a local\n * module that reaches the peer through its own static import (the ai_sdk\n * turn seam in generate.ts, whose dynamic import must stay written in\n * generate.ts for its relative specifier to resolve correctly).\n */\nexport function missing_peer_error(peer_name: string, cause: unknown): Error {\n const detail = cause instanceof Error ? cause.message : JSON.stringify(cause)\n const message =\n `missing peer dependency '${peer_name}'. Install it with your package manager, e.g., \\`pnpm add ${peer_name}\\` or \\`npm install ${peer_name}\\`. Cause: ${detail}`\n return new Error(message, { cause })\n}\n\n/**\n * Dynamically import an optional peer dependency, rethrowing an import\n * failure via missing_peer_error so a missing peer is diagnosable from the\n * message alone.\n */\nexport async function load_optional_peer<t>(\n specifier: string,\n): Promise<t> {\n let mod: unknown\n try {\n mod = await import(specifier)\n } catch (err: unknown) {\n throw missing_peer_error(specifier, err)\n }\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return mod as t\n}\n","/**\n * Shared plumbing for the native (raw-HTTP) provider adapters.\n *\n * Everything here is wire-neutral: how a turn travels HTTP (POST, non-2xx\n * mapping, stream-vs-JSON dispatch), how streamed bytes become framed\n * payloads, and the engine-message folds the 1:1 wires share. Each adapter\n * keeps what is genuinely its own dialect (request bodies, response parsers,\n * stream aggregators) and delegates the rest here, so the three adapters\n * cannot drift apart on retry classification or stream draining. This module\n * imports nothing from `ai` or `@ai-sdk/*` and nothing from the adapters, so\n * every adapter can import it cycle-free.\n */\n\nimport type {\n AssistantContentPart,\n Message,\n ProviderInit,\n StreamChunk,\n TurnRequest,\n TurnResult,\n UserContentPart,\n} from '../types.js'\nimport { provider_auth_error, provider_error } from '../errors.js'\n\n/**\n * The message under a JSON error envelope's `error` key, or undefined when\n * the shape carries none worth surfacing.\n */\nfunction error_field_message(parsed: unknown): string | undefined {\n // Stryker disable next-line ConditionalExpression,LogicalOperator: the\n // caller's try/catch already funnels every non-object parse to the raw\n // snippet, so this guard only narrows unknown -> object for Reflect.get;\n // forcing it either way throws-and-catches to the same fallback (equivalent).\n if (parsed === null || typeof parsed !== 'object') return undefined\n const error: unknown = Reflect.get(parsed, 'error')\n if (typeof error === 'string' && error.length > 0) return error\n // Stryker disable next-line ConditionalExpression,LogicalOperator: same as\n // above -- a non-object error still reaches the raw-snippet fallback via the\n // catch or the message-not-a-string check, so both boundaries are equivalent.\n if (error === null || typeof error !== 'object') return undefined\n const message: unknown = Reflect.get(error, 'message')\n return typeof message === 'string' && message.length > 0 ? message : undefined\n}\n\n/**\n * Pull a human-readable message out of a non-2xx body. The native wires share\n * one envelope family: Anthropic sends `{ type: 'error', error: { message } }`,\n * OpenAI-style wires send `{ error: { message } }`, and Ollama sends\n * `{ error: \"message\" }` (with the nested shape appearing behind proxies), so\n * one parser accepts a string or a `{ message }` object under `error` and\n * falls back to the raw body, truncated to 300 chars.\n */\nfunction extract_error_message(body: string): string {\n if (body.length === 0) return '(empty body)'\n let message: string | undefined\n try {\n message = error_field_message(JSON.parse(body))\n } catch {\n // Not JSON; fall through to the raw snippet.\n }\n if (message !== undefined) return message\n return body.length > 300 ? `${body.slice(0, 300)}...` : body\n}\n\n/**\n * Map a non-2xx response to what the engine's retry stack expects: 401\n * becomes a typed provider_auth_error, 429/5xx keep `status` +\n * `responseHeaders` so classify_provider_error marks them retryable\n * (rate_limit honoring retry-after, provider_5xx), and any other 4xx is a\n * permanent provider_error that surfaces as-is.\n */\nasync function response_error(response: Response, provider: string): Promise<Error> {\n let body = ''\n try {\n body = await response.text()\n } catch {\n // Body is best-effort detail; classification needs only the status.\n }\n const detail = extract_error_message(body)\n const status = response.status\n if (status === 401) {\n return new provider_auth_error(\n provider,\n `${provider} authentication failed (401): ${detail}`,\n )\n }\n if (status === 429 || status >= 500) {\n const retry_after = response.headers.get('retry-after')\n return Object.assign(\n new Error(`${provider} API error ${status}: ${detail}`),\n { status },\n retry_after !== null ? { responseHeaders: { 'retry-after': retry_after } } : {},\n )\n }\n return new provider_error(`${provider} API error ${status}: ${detail}`, { status, body })\n}\n\n/**\n * A user abort surfaces as the fetch/reader AbortError; retry_turn converts\n * it via its own signal check, so it is rethrown untouched. Everything else\n * is a transport failure wrapped in the `kind: 'network'` shape the shared\n * classify_provider_error marks retryable.\n */\nfunction rethrow_network_failure(err: unknown, abort: AbortSignal, provider: string): never {\n if (abort.aborted) throw err\n const detail = err instanceof Error ? err.message : String(err)\n throw Object.assign(new Error(`${provider} native: network failure: ${detail}`), {\n kind: 'network',\n })\n}\n\n/**\n * Read a non-stream response body and parse it as JSON. A read that fails\n * partway is a transport failure, wrapped as network the way a failed stream\n * read is; a body that arrives whole but does not parse is a permanent\n * provider_error naming what came back.\n */\nasync function read_json_body(\n response: Response,\n abort: AbortSignal,\n provider: string,\n): Promise<unknown> {\n let text: string\n try {\n text = await response.text()\n } catch (err: unknown) {\n rethrow_network_failure(err, abort, provider)\n }\n try {\n return JSON.parse(text)\n } catch {\n throw new provider_error(\n `${provider} native: response body is not valid JSON: check that base_url points at the ${provider} API (body: ${extract_error_message(text)})`,\n )\n }\n}\n\n/**\n * Run one native turn over HTTP: POST the dialect's body, map a non-2xx to\n * the retry stack's shapes, and hand the response to the dialect's stream or\n * JSON consumer. `build_body` runs before the network try/catch, so a mapper\n * that rejects the request (e.g., a provider_capability_error for a part the\n * wire cannot carry) propagates unchanged instead of being retried as a\n * network failure.\n */\nexport async function invoke_http_turn(\n req: TurnRequest,\n provider: string,\n request: {\n url: string\n headers: Record<string, string>\n build_body: () => Record<string, unknown>\n },\n consume: {\n stream: (response: Response) => Promise<TurnResult>\n parse: (payload: unknown) => TurnResult\n },\n): Promise<TurnResult> {\n const body = JSON.stringify(request.build_body())\n let response: Response\n try {\n response = await fetch(request.url, {\n method: 'POST',\n headers: request.headers,\n body,\n signal: req.abort,\n })\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort, provider)\n }\n if (!response.ok) throw await response_error(response, provider)\n if (req.stream) return consume.stream(response)\n return consume.parse(await read_json_body(response, req.abort, provider))\n}\n\n/**\n * Drain a streaming response: decode bytes, reassemble framed payloads (SSE\n * events or NDJSON lines), and feed them to the dialect's aggregator, which\n * dispatches chunks through req.dispatch_chunk as they arrive. Transport\n * failures mid-read wrap as network errors; aggregator throws (malformed\n * frames, mid-stream error events, a rejecting on_chunk) pass through\n * untouched, with the reader cancelled so the connection is released.\n */\nexport async function consume_framed_stream(\n response: Response,\n req: TurnRequest,\n provider: string,\n framing: { push: (text: string) => string[]; flush: () => string[] },\n create_aggregator: (dispatch: (chunk: StreamChunk) => Promise<void>) => {\n handle: (data: string) => Promise<void>\n complete: () => TurnResult\n },\n): Promise<TurnResult> {\n const body = response.body\n if (body === null) {\n throw new provider_error(`${provider} native: streaming response has no body`)\n }\n const aggregator = create_aggregator(req.dispatch_chunk ?? (async (): Promise<void> => {}))\n const reader = body.getReader()\n const text_decoder = new TextDecoder()\n\n const next_bytes = async (): Promise<Uint8Array | undefined> => {\n let step: Awaited<ReturnType<typeof reader.read>>\n try {\n step = await reader.read()\n } catch (err: unknown) {\n rethrow_network_failure(err, req.abort, provider)\n }\n return step.done ? undefined : step.value\n }\n\n // Sequential awaits are the contract here: chunk order is an engine\n // invariant and each frame mutates aggregator state, so no parallelism.\n try {\n while (true) {\n const bytes = await next_bytes()\n if (bytes === undefined) break\n for (const data of framing.push(text_decoder.decode(bytes, { stream: true }))) {\n await aggregator.handle(data)\n }\n }\n } finally {\n // Frees the connection when an error exits the loop early; a no-op on a\n // fully drained stream.\n void reader.cancel().catch(() => {})\n }\n const tail = [...framing.push(text_decoder.decode()), ...framing.flush()]\n for (const data of tail) {\n await aggregator.handle(data)\n }\n return aggregator.complete()\n}\n\n/**\n * Incremental newline framing shared by the SSE and NDJSON decoders: buffer\n * decoded text across arbitrary chunk boundaries, hand each completed line\n * (CR trimmed) to `handle_line`, and on flush hand over an unterminated tail\n * line, then `on_flush` for state a decoder holds across lines (an SSE event\n * never closed by a blank line).\n */\nexport function create_line_splitter(\n handle_line: (line: string, out: string[]) => void,\n on_flush?: (out: string[]) => void,\n): { push: (text: string) => string[]; flush: () => string[] } {\n let buffer = ''\n\n const take_line = (raw: string, out: string[]): void => {\n handle_line(raw.endsWith('\\r') ? raw.slice(0, -1) : raw, out)\n }\n\n return {\n push(text: string): string[] {\n buffer += text\n const out: string[] = []\n let newline = buffer.indexOf('\\n')\n while (newline >= 0) {\n take_line(buffer.slice(0, newline), out)\n buffer = buffer.slice(newline + 1)\n newline = buffer.indexOf('\\n')\n }\n return out\n },\n flush(): string[] {\n const out: string[] = []\n if (buffer.length > 0) take_line(buffer, out)\n buffer = ''\n on_flush?.(out)\n return out\n },\n }\n}\n\n/**\n * Decode a tool call's wire `arguments` string into the engine's input value:\n * non-empty JSON parses (bad JSON is a provider_error naming the tool), and\n * an absent or empty value means `{}`, the shape some servers send for\n * no-argument calls. The Ollama wire's structured-object arguments are its\n * caller's business before this runs.\n */\nexport function parse_tool_call_arguments(\n raw_args: unknown,\n provider: string,\n tool_name: string,\n): unknown {\n if (typeof raw_args === 'string' && raw_args.length > 0) {\n try {\n return JSON.parse(raw_args)\n } catch {\n throw new provider_error(\n `${provider} native: tool_calls arguments for ${tool_name} is not valid JSON`,\n )\n }\n }\n return {}\n}\n\n/**\n * Fold engine messages into a wire's message array by role. Serves the wires\n * whose messages map 1:1 in place (chat/completions, Ollama's /api/chat); the\n * Messages API's system-hoisting and role-merging rules live in its own\n * mapper instead.\n */\nexport function map_messages_by_role<m>(\n messages: ReadonlyArray<Message>,\n wire: {\n system: (content: string) => m\n user: (content: string | UserContentPart[]) => m\n assistant: (content: string | AssistantContentPart[]) => m\n tool: (message: Extract<Message, { role: 'tool' }>) => m\n },\n): m[] {\n const out: m[] = []\n for (const message of messages) {\n switch (message.role) {\n case 'system':\n out.push(wire.system(message.content))\n break\n case 'user':\n out.push(wire.user(message.content))\n break\n case 'assistant':\n out.push(wire.assistant(message.content))\n break\n case 'tool':\n out.push(wire.tool(message))\n break\n }\n }\n return out\n}\n\ntype ReasoningPart = Extract<AssistantContentPart, { type: 'reasoning' }>\n\n/**\n * Whether a reasoning part is one this provider may send back: only a part\n * carrying data under the provider's own key goes. A part keyed for another\n * vendor stays behind, so a `fallback` never hands one vendor's signature to\n * another, and so does a part with no data, whose text alone is what a\n * signing wire refuses.\n */\nexport function is_own_reasoning(part: ReasoningPart, key: string): boolean {\n return part.provider_options?.[key] !== undefined\n}\n\n/**\n * Partition assistant content parts into the text runs, tool calls, and\n * reasoning the wire mappers serialize separately. `reasoning` holds only\n * the parts `provider` may send back, in order (see is_own_reasoning).\n */\nexport function split_assistant_parts(\n parts: ReadonlyArray<AssistantContentPart>,\n provider: string,\n): {\n texts: string[]\n tool_parts: Array<Extract<AssistantContentPart, { type: 'tool_call' }>>\n reasoning: ReasoningPart[]\n} {\n const texts: string[] = []\n const tool_parts: Array<Extract<AssistantContentPart, { type: 'tool_call' }>> = []\n const reasoning: ReasoningPart[] = []\n for (const part of parts) {\n if (part.type === 'text') texts.push(part.text)\n else if (part.type === 'tool_call') tool_parts.push(part)\n else if (is_own_reasoning(part, provider)) reasoning.push(part)\n }\n return { texts, tool_parts, reasoning }\n}\n\n/**\n * Read the api_key and base_url every OpenAI-compatible dialect starts from:\n * a missing or non-string api_key becomes '' (the core's empty-key guard owns\n * the throw), and an absent base_url falls back to the dialect's default.\n */\nexport function read_dialect_init(\n init: ProviderInit,\n default_base_url: string,\n): { api_key: string; base_url: string } {\n return {\n api_key: typeof init.api_key === 'string' ? init.api_key : '',\n base_url:\n typeof init.base_url === 'string' && init.base_url.length > 0\n ? init.base_url\n : default_base_url,\n }\n}\n","/**\n * Collapse a leading run of system messages into a single joined string,\n * returning the remaining messages.\n *\n * Both message paths hoist a leading system run out of their list the same way:\n * the engine-Message side (generate.ts split_leading_system_messages) hands the\n * run to a native adapter's TurnRequest.system, and the AI SDK side\n * (providers/ai_sdk/invoke.ts split_leading_system) hands it to the SDK's\n * top-level `instructions` option. Same guard, same '\\n\\n' join, and the same\n * \"return the list untouched when hoisting would leave `messages` empty\" rule,\n * since provider APIs reject an empty messages array. They differ only in the\n * element type and how a system message's text is read, so each caller supplies\n * `system_text`; the traversal and its guards live here once.\n */\nexport function split_leading_system_run<T extends { readonly role: string }>(\n messages: ReadonlyArray<T>,\n system_text: (message: Extract<T, { role: 'system' }>) => string,\n): { system?: string; messages: T[] } {\n let run_end = 0\n const system_parts: string[] = []\n while (run_end < messages.length) {\n const m = messages[run_end]\n if (!is_leading_system(m)) break\n system_parts.push(system_text(m))\n run_end += 1\n }\n const rest = messages.slice(run_end)\n if (system_parts.length === 0 || rest.length === 0) {\n return { messages: [...messages] }\n }\n return { system: system_parts.join('\\n\\n'), messages: rest }\n}\n\n/**\n * Narrow a possibly undefined message to the system member of its union.\n *\n * A cast-free type guard so `split_leading_system_run` can hand the narrowed\n * message straight to `system_text` without a `T`-eroding assertion; the\n * optional chain covers the out-of-bounds `undefined` the index access yields.\n */\nfunction is_leading_system<T extends { readonly role: string }>(\n m: T | undefined,\n): m is Extract<T, { role: 'system' }> {\n // Stryker disable next-line OptionalChaining: within the loop guard run_end < messages.length, m is always an in-bounds (defined) message, so m.role and m?.role read identically.\n return m?.role ===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AM,OAAO,SAAS,MAAM,OAAO;CACnC,IAAI,aAAa,WAAW,KAAK,KAAK,WAAW,GAC/C,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,EAAE;CAEnC,OAAO;EAAE,QAAQ,aAAa,KAAK,MAAM;EAAG,UAAU;CAAK;AAC7D;;;;;;;;AASA,SAAS,kBACP,GACqC;CAErC,OAAO,GAAG,SAAS;AACrB"}
package/dist/mcp.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { c as Step, h as TrajectoryLogger } from "./types-CPqLZOEr.js";
2
2
  import { r as ToolSchema } from "./types-BK0UW28o.js";
3
- import { D as Tool } from "./types-De-TVQxS.js";
3
+ import { k as Tool } from "./types-Sw0oHW-_.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";
@@ -58,7 +58,8 @@ type McpClientHandle = {
58
58
  * the loop validates against and the provider receives back unchanged, and
59
59
  * `execute` forwards to `callTool`, propagating the run's abort signal. For the
60
60
  * `client` transport variant the caller keeps ownership of the connection, so
61
- * `close` is a no-op.
61
+ * `close` is a no-op. A connection this call opened is closed again when
62
+ * listing its tools fails.
62
63
  */
63
64
  export declare function mcp_client(config: McpClientConfig, options?: McpClientOptions): Promise<McpClientHandle>;
64
65
  //#endregion
package/dist/mcp.js CHANGED
@@ -1,6 +1,6 @@
1
- import { E as run } from "./core-CDrz0NM1.js";
1
+ import { E as run } from "./core-CErsxGF6.js";
2
2
  import { n as is_record, t as as_record } from "./records-1HU7mWXf.js";
3
- import { t as json_schema_to_standard } from "./json_schema_to_standard-BTWD0J6p.js";
3
+ import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
4
4
  //#region src/mcp/errors.ts
5
5
  /**
6
6
  * Typed errors for the MCP adapter.
@@ -155,13 +155,17 @@ const DEFAULT_CLIENT_INFO = {
155
155
  * the loop validates against and the provider receives back unchanged, and
156
156
  * `execute` forwards to `callTool`, propagating the run's abort signal. For the
157
157
  * `client` transport variant the caller keeps ownership of the connection, so
158
- * `close` is a no-op.
158
+ * `close` is a no-op. A connection this call opened is closed again when
159
+ * listing its tools fails.
159
160
  */
160
161
  async function mcp_client(config, options = {}) {
161
162
  const owns_client = config.transport !== "client";
162
163
  const client = await connect_client(config, options);
163
164
  const include = options.include !== void 0 ? new Set(options.include) : void 0;
164
- const listed = await client.listTools();
165
+ const listed = await client.listTools().catch(async (err) => {
166
+ if (owns_client) await client.close().catch(() => void 0);
167
+ throw err;
168
+ });
165
169
  const tools = [];
166
170
  for (const advertised of listed.tools) {
167
171
  if (include !== void 0 && !include.has(advertised.name)) continue;
package/dist/mcp.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp/errors.ts","../src/mcp/result_mapping.ts","../src/mcp/sdk_loader.ts","../src/mcp/client.ts","../src/mcp/serve.ts"],"sourcesContent":["/**\n * Typed errors for the MCP adapter.\n *\n * Listed alongside src/core/errors.ts and src/engine/errors.ts in the\n * `no-class` rule ignores: `instanceof` branching is how callers distinguish a\n * missing optional peer from a tool-level failure surfaced over the wire.\n */\n\nexport class mcp_sdk_missing_error extends Error {\n readonly kind = 'mcp_sdk_missing_error' as const;\n constructor(\n message = '@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk',\n ) {\n super(message)\n this.name = 'mcp_sdk_missing_error'\n }\n}\n\nexport class mcp_error extends Error {\n readonly kind = 'mcp_error' as const;\n readonly tool_name: string | undefined;\n constructor(message: string, metadata: { tool_name?: string } = {}) {\n super(message)\n this.name = 'mcp_error'\n this.tool_name = metadata.tool_name\n }\n}\n","/**\n * Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in\n * both directions: inbound results from `mcp_client` tools, outbound results\n * for `serve_flow`.\n */\n\nimport { as_record, is_record } from '#schema'\nimport { mcp_error } from './errors.js'\n\nexport type McpToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n}\n\n/**\n * Converts a remote tool's `CallToolResult` into the value a Fascicle\n * `Tool.execute` returns.\n *\n * `isError: true` marks a tool-level failure, so it throws `mcp_error` rather\n * than returning, letting the tool loop's error policy feed it back to the\n * model. `structuredContent` is preferred over joined text parts when present;\n * with neither, the raw `content` (or `null`) is returned.\n */\nexport function call_result_to_output(result: unknown, tool_name?: string): unknown {\n const record = as_record(result) ?? {}\n\n if (record['isError'] === true) {\n const detail = join_text(record['content']) ?? 'MCP tool returned an error'\n throw new mcp_error(detail, tool_name !== undefined ? { tool_name } : {})\n }\n\n if (is_record(record['structuredContent'])) return record['structuredContent']\n\n const text = join_text(record['content'])\n if (text !== undefined) return text\n\n return record['content'] ?? null\n}\n\n/**\n * Converts a Fascicle flow's output into a `CallToolResult` for `serve_flow`.\n *\n * A `to_result` override takes precedence over the default mapping. By\n * default, objects are emitted as both a JSON text part (every MCP host can\n * read text) and `structuredContent` (typed hosts get the object); everything\n * else becomes a single text part.\n */\nexport function output_to_call_result<o>(\n output: o,\n to_result?: (output: o) => { text: string; structured?: Record<string, unknown> },\n): McpToolResult {\n if (to_result !== undefined) {\n const shaped = to_result(output)\n return build_result(shaped.text, shaped.structured)\n }\n if (typeof output === 'string') return build_result(output)\n if (is_record(output)) return build_result(stringify(output), output)\n if (Array.isArray(output)) return build_result(stringify(output))\n return build_result(String(output))\n}\n\n/**\n * Assembles a `CallToolResult` with one text part and, when given, structured\n * content.\n */\nfunction build_result(text: string, structured?: Record<string, unknown>): McpToolResult {\n return structured !== undefined\n ? { content: [{ type: 'text', text }], structuredContent: structured }\n : { content: [{ type: 'text', text }] }\n}\n\n/**\n * Joins the `text` parts of an MCP content array with newlines, skipping\n * non-text parts; `undefined` when there is nothing to join.\n */\nfunction join_text(content: unknown): string | undefined {\n if (!Array.isArray(content)) return undefined\n const parts: string[] = []\n for (const part of content) {\n if (is_record(part) && part['type'] === 'text' && typeof part['text'] === 'string') {\n parts.push(part['text'])\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined\n}\n\n/**\n * `JSON.stringify` that falls back to `String` instead of throwing on\n * unserializable values (circular references, BigInt).\n */\nfunction stringify(value: unknown): string {\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * Lazy loader for the optional `@modelcontextprotocol/sdk` peer.\n *\n * `mcp_client` needs SDK values (the Client and transport constructors), so it\n * imports them dynamically rather than statically: a consumer can import\n * `fascicle/mcp` without the SDK installed and only pays the cost when they\n * actually connect. A missing peer surfaces as a typed `mcp_sdk_missing_error`\n * with install guidance, mirroring the engine's `load_optional_peer`.\n *\n * `serve_flow` is not covered here: it operates on a caller-constructed\n * `McpServer`, so it needs only a type-only import and no runtime SDK load.\n */\n\nimport { mcp_sdk_missing_error } from './errors.js'\n\nexport type McpClientSdk = Awaited<ReturnType<typeof load_client_sdk>>\n\n/**\n * Dynamically imports the `@modelcontextprotocol/sdk` client modules,\n * throwing a typed `mcp_sdk_missing_error` when the optional peer is not\n * installed.\n */\nexport async function load_client_sdk() {\n try {\n const [client_mod, stdio_mod, http_mod] = await Promise.all([\n import('@modelcontextprotocol/sdk/client/index.js'),\n import('@modelcontextprotocol/sdk/client/stdio.js'),\n import('@modelcontextprotocol/sdk/client/streamableHttp.js'),\n ])\n return {\n Client: client_mod.Client,\n StdioClientTransport: stdio_mod.StdioClientTransport,\n StreamableHTTPClientTransport: http_mod.StreamableHTTPClientTransport,\n }\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new mcp_sdk_missing_error(\n `@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk (cause: ${detail})`,\n )\n }\n}\n","/**\n * Inbound MCP: connect to an external MCP server and surface its tools as plain\n * Fascicle `Tool[]`.\n */\n\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'\nimport type { Tool, ToolExecContext } from '#engine'\nimport { is_record, json_schema_to_standard } from '#schema'\nimport { mcp_error } from './errors.js'\nimport { call_result_to_output } from './result_mapping.js'\nimport { load_client_sdk, type McpClientSdk } from './sdk_loader.js'\n\nconst DEFAULT_CLIENT_INFO = { name: 'fascicle', version: '0.0.0' }\n\nexport type McpStdioConfig = {\n transport: 'stdio'\n command: string\n args?: string[]\n env?: Record<string, string>\n cwd?: string\n}\n\nexport type McpStreamableHttpConfig = {\n transport: 'http'\n url: string\n headers?: Record<string, string>\n}\n\n// Escape hatch: hand in an already-connected Client (a transport the adapter\n// does not build, a test harness, a shared connection). Its lifecycle stays\n// with the caller, so the returned `close` is a no-op for this variant.\nexport type McpExistingClientConfig = {\n transport: 'client'\n client: Client\n}\n\nexport type McpClientConfig =\n | McpStdioConfig\n | McpStreamableHttpConfig\n | McpExistingClientConfig\n\nexport type McpClientOptions = {\n // Identity sent in the MCP handshake; defaults to Fascicle.\n client_info?: { name: string; version: string }\n // When set, only tools whose name is listed are surfaced.\n include?: ReadonlyArray<string>\n // Supplies a description for tools that advertise none.\n default_description?: (tool_name: string) => string\n}\n\nexport type McpClientHandle = {\n readonly tools: ReadonlyArray<Tool>\n readonly close: () => Promise<void>\n}\n\n/**\n * Connects to an MCP server and surfaces its advertised tools as Fascicle\n * `Tool[]`, plus a `close` handle for the connection.\n *\n * Owns the connection lifecycle (config in, `{ tools, close }` out) so callers\n * do not have to import SDK transport classes themselves. Each advertised MCP\n * tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`\n * the loop validates against and the provider receives back unchanged, and\n * `execute` forwards to `callTool`, propagating the run's abort signal. For the\n * `client` transport variant the caller keeps ownership of the connection, so\n * `close` is a no-op.\n */\nexport async function mcp_client(\n config: McpClientConfig,\n options: McpClientOptions = {},\n): Promise<McpClientHandle> {\n const owns_client = config.transport !== 'client'\n const client = await connect_client(config, options)\n\n const include = options.include !== undefined ? new Set(options.include) : undefined\n const listed = await client.listTools()\n const tools: Tool[] = []\n for (const advertised of listed.tools) {\n if (include !== undefined && !include.has(advertised.name)) continue\n tools.push(to_fascicle_tool(client, advertised, options))\n }\n\n return {\n tools,\n close: async () => {\n if (owns_client) await client.close()\n },\n }\n}\n\n/**\n * Returns the caller's already-connected client as-is, or lazily loads the\n * SDK and connects a fresh client over the configured transport.\n */\nasync function connect_client(\n config: McpClientConfig,\n options: McpClientOptions,\n): Promise<Client> {\n if (config.transport === 'client') return config.client\n const sdk = await load_client_sdk()\n const client = new sdk.Client(options.client_info ?? DEFAULT_CLIENT_INFO)\n await client.connect(build_transport(sdk, config))\n return client\n}\n\n/**\n * Constructs the SDK transport matching the config: a spawned child process\n * for `stdio`, a Streamable HTTP connection for `http`.\n */\nfunction build_transport(\n sdk: McpClientSdk,\n config: McpStdioConfig | McpStreamableHttpConfig,\n): Transport {\n if (config.transport === 'stdio') {\n return new sdk.StdioClientTransport({\n command: config.command,\n ...(config.args !== undefined ? { args: config.args } : {}),\n ...(config.env !== undefined ? { env: config.env } : {}),\n ...(config.cwd !== undefined ? { cwd: config.cwd } : {}),\n })\n }\n const opts = config.headers !== undefined ? { requestInit: { headers: config.headers } } : {}\n // The SDK declares this class `implements Transport`, but its `onmessage`\n // overload is narrower than the interface's, which only strict mode flags.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts) as Transport\n}\n\n/**\n * Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards\n * to `callTool` on the shared client.\n *\n * An already-aborted signal short-circuits before the wire call; otherwise the\n * signal is passed through so cancelling the run cancels the remote call.\n */\nfunction to_fascicle_tool(\n client: Client,\n advertised: { name: string; description?: string | undefined; inputSchema: unknown },\n options: McpClientOptions,\n): Tool {\n const name = advertised.name\n const description =\n advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`\n return {\n name,\n description,\n input_schema: json_schema_to_standard(advertised.inputSchema),\n execute: async (input: unknown, ctx: ToolExecContext) => {\n if (ctx.abort.aborted) {\n throw ctx.abort.reason instanceof Error\n ? ctx.abort.reason\n : new mcp_error(`MCP tool ${name} aborted before invocation`, { tool_name: name })\n }\n const result = await client.callTool(\n { name, arguments: is_record(input) ? input : undefined },\n undefined,\n { signal: ctx.abort },\n )\n return call_result_to_output(result, name)\n },\n }\n}\n","/**\n * Outbound MCP: expose a composed Fascicle flow as an MCP tool.\n *\n * `serve_flow` registers onto a caller-constructed `McpServer` (the caller owns\n * the transport, identity, and lifecycle, and can host many flows on one\n * server), so it needs only a type-only SDK import. The registered handler\n * drives the existing `run`, threading the per-request abort signal so an MCP\n * client cancellation aborts the in-flight flow, and maps the result into a\n * `CallToolResult`. A thrown flow becomes an `isError` result rather than a\n * JSON-RPC protocol error.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { z } from 'zod'\nimport { run } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport { output_to_call_result } from './result_mapping.js'\n\nexport type ServeFlowConfig<i, o> = {\n server: McpServer\n flow: Step<i, o>\n name: string\n description: string\n /**\n * Stays zod rather than joining the rest of the surface on `ToolSchema`.\n * `McpServer.registerTool` types `inputSchema` as a zod schema and offers no\n * JSON Schema entry point, and the SDK carries zod as a hard runtime\n * dependency, so a `serve_flow` caller already has zod resolved. Widening\n * this to a neutral schema would typecheck and then fail inside the SDK.\n */\n input_schema: z.ZodType<i>\n trajectory?: TrajectoryLogger\n // Overrides the default value-to-CallToolResult mapping.\n to_result?: (output: o) => { text: string; structured?: Record<string, unknown> }\n}\n\n/**\n * Registers a Fascicle flow as a tool on a caller-owned MCP server.\n *\n * Drives the flow with `run`, threading the per-request abort signal so an\n * MCP client cancellation aborts the in-flight flow, and maps the result\n * into a `CallToolResult`. A thrown flow becomes an `isError` result rather\n * than a JSON-RPC protocol error.\n */\nexport function serve_flow<i, o>(config: ServeFlowConfig<i, o>): void {\n const { server, flow, name, description, input_schema, trajectory, to_result } = config\n server.registerTool(\n name,\n { description, inputSchema: input_schema },\n async (input: i, extra) => {\n try {\n const output = await run(flow, input, {\n install_signal_handlers: false,\n abort: extra.signal,\n ...(trajectory !== undefined ? { trajectory } : {}),\n })\n return output_to_call_result(output, to_result)\n } catch (err: unknown) {\n return {\n isError: true,\n content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }],\n }\n }\n },\n )\n}\n"],"mappings":";;;;;;;;;;;AAQA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,OAAgB;CAChB,YACE,UAAU,0GACV;EACA,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,IAAa,YAAb,cAA+B,MAAM;CACnC,OAAgB;CAChB;CACA,YAAY,SAAiB,WAAmC,CAAC,GAAG;EAClE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,YAAY,SAAS;CAC5B;AACF;;;;;;;;;;;;;;;;;ACHA,SAAgB,sBAAsB,QAAiB,WAA6B;CAClF,MAAM,SAAS,UAAU,MAAM,KAAK,CAAC;CAErC,IAAI,OAAO,eAAe,MAExB,MAAM,IAAI,UADK,UAAU,OAAO,UAAU,KAAK,8BACnB,cAAc,KAAA,IAAY,EAAE,UAAU,IAAI,CAAC,CAAC;CAG1E,IAAI,UAAU,OAAO,oBAAoB,GAAG,OAAO,OAAO;CAE1D,MAAM,OAAO,UAAU,OAAO,UAAU;CACxC,IAAI,SAAS,KAAA,GAAW,OAAO;CAE/B,OAAO,OAAO,cAAc;AAC9B;;;;;;;;;AAUA,SAAgB,sBACd,QACA,WACe;CACf,IAAI,cAAc,KAAA,GAAW;EAC3B,MAAM,SAAS,UAAU,MAAM;EAC/B,OAAO,aAAa,OAAO,MAAM,OAAO,UAAU;CACpD;CACA,IAAI,OAAO,WAAW,UAAU,OAAO,aAAa,MAAM;CAC1D,IAAI,UAAU,MAAM,GAAG,OAAO,aAAa,UAAU,MAAM,GAAG,MAAM;CACpE,IAAI,MAAM,QAAQ,MAAM,GAAG,OAAO,aAAa,UAAU,MAAM,CAAC;CAChE,OAAO,aAAa,OA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c,wBAAwB,WAAW,WAAW;EAC5D,SAAS,OAAO,OAAgB,QAAyB;GACvD,IAAI,IAAI,MAAM,SACZ,MAAM,IAAI,MAAM,kBAAkB,QAC9B,IAAI,MAAM,SACV,IAAI,UAAU,YAAY,KAAK,6BAA6B,EAAE,WAAW,KAAK,CAAC;GAOrF,OAAO,sBAAsB,MALR,OAAO,SAC1B;IAAE;IAAM,WAAW,UAAU,KAAK,IAAI,QAAQ,KAAA;GAAU,GACxD,KAAA,GACA,EAAE,QAAQ,IAAI,MAAM,CACtB,GACqC,IAAI;EAC3C;CACF;AACF;;;;;;;;;;;ACtHA,SAAgB,WAAiB,QAAqC;CACpE,MAAM,EAAE,QAAQ,MAAM,MAAM,aAAa,cAAc,YAAY,cAAc;CACjF,OAAO,aACL,MACA;EAAE;EAAa,aAAa;CAAa,GACzC,OAAO,OAAU,UAAU;EACzB,IAAI;GAMF,OAAO,sBAAsB,MALR,IAAI,MAAM,OAAO;IACpC,yBAAyB;IACzB,OAAO,MAAM;IACb,GAAI,eAAe,KAAA,IAAY,EAAE,WAAW,IAAI,CAAC;GACnD,CAAC,GACoC,SAAS;EAChD,SAAS,KAAc;GACrB,OAAO;IACL,SAAS;IACT,SAAS,CAAC;KAAE,MAAM;KAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;IAAE,CAAC;GACpF;EACF;CACF,CACF;AACF"}
1
+ {"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp/errors.ts","../src/mcp/result_mapping.ts","../src/mcp/sdk_loader.ts","../src/mcp/client.ts","../src/mcp/serve.ts"],"sourcesContent":["/**\n * Typed errors for the MCP adapter.\n *\n * Listed alongside src/core/errors.ts and src/engine/errors.ts in the\n * `no-class` rule ignores: `instanceof` branching is how callers distinguish a\n * missing optional peer from a tool-level failure surfaced over the wire.\n */\n\nexport class mcp_sdk_missing_error extends Error {\n readonly kind = 'mcp_sdk_missing_error' as const;\n constructor(\n message = '@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk',\n ) {\n super(message)\n this.name = 'mcp_sdk_missing_error'\n }\n}\n\nexport class mcp_error extends Error {\n readonly kind = 'mcp_error' as const;\n readonly tool_name: string | undefined;\n constructor(message: string, metadata: { tool_name?: string } = {}) {\n super(message)\n this.name = 'mcp_error'\n this.tool_name = metadata.tool_name\n }\n}\n","/**\n * Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in\n * both directions: inbound results from `mcp_client` tools, outbound results\n * for `serve_flow`.\n */\n\nimport { as_record, is_record } from '#schema'\nimport { mcp_error } from './errors.js'\n\nexport type McpToolResult = {\n content: Array<{ type: 'text'; text: string }>\n structuredContent?: Record<string, unknown>\n}\n\n/**\n * Converts a remote tool's `CallToolResult` into the value a Fascicle\n * `Tool.execute` returns.\n *\n * `isError: true` marks a tool-level failure, so it throws `mcp_error` rather\n * than returning, letting the tool loop's error policy feed it back to the\n * model. `structuredContent` is preferred over joined text parts when present;\n * with neither, the raw `content` (or `null`) is returned.\n */\nexport function call_result_to_output(result: unknown, tool_name?: string): unknown {\n const record = as_record(result) ?? {}\n\n if (record['isError'] === true) {\n const detail = join_text(record['content']) ?? 'MCP tool returned an error'\n throw new mcp_error(detail, tool_name !== undefined ? { tool_name } : {})\n }\n\n if (is_record(record['structuredContent'])) return record['structuredContent']\n\n const text = join_text(record['content'])\n if (text !== undefined) return text\n\n return record['content'] ?? null\n}\n\n/**\n * Converts a Fascicle flow's output into a `CallToolResult` for `serve_flow`.\n *\n * A `to_result` override takes precedence over the default mapping. By\n * default, objects are emitted as both a JSON text part (every MCP host can\n * read text) and `structuredContent` (typed hosts get the object); everything\n * else becomes a single text part.\n */\nexport function output_to_call_result<o>(\n output: o,\n to_result?: (output: o) => { text: string; structured?: Record<string, unknown> },\n): McpToolResult {\n if (to_result !== undefined) {\n const shaped = to_result(output)\n return build_result(shaped.text, shaped.structured)\n }\n if (typeof output === 'string') return build_result(output)\n if (is_record(output)) return build_result(stringify(output), output)\n if (Array.isArray(output)) return build_result(stringify(output))\n return build_result(String(output))\n}\n\n/**\n * Assembles a `CallToolResult` with one text part and, when given, structured\n * content.\n */\nfunction build_result(text: string, structured?: Record<string, unknown>): McpToolResult {\n return structured !== undefined\n ? { content: [{ type: 'text', text }], structuredContent: structured }\n : { content: [{ type: 'text', text }] }\n}\n\n/**\n * Joins the `text` parts of an MCP content array with newlines, skipping\n * non-text parts; `undefined` when there is nothing to join.\n */\nfunction join_text(content: unknown): string | undefined {\n if (!Array.isArray(content)) return undefined\n const parts: string[] = []\n for (const part of content) {\n if (is_record(part) && part['type'] === 'text' && typeof part['text'] === 'string') {\n parts.push(part['text'])\n }\n }\n return parts.length > 0 ? parts.join('\\n') : undefined\n}\n\n/**\n * `JSON.stringify` that falls back to `String` instead of throwing on\n * unserializable values (circular references, BigInt).\n */\nfunction stringify(value: unknown): string {\n try {\n return JSON.stringify(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * Lazy loader for the optional `@modelcontextprotocol/sdk` peer.\n *\n * `mcp_client` needs SDK values (the Client and transport constructors), so it\n * imports them dynamically rather than statically: a consumer can import\n * `fascicle/mcp` without the SDK installed and only pays the cost when they\n * actually connect. A missing peer surfaces as a typed `mcp_sdk_missing_error`\n * with install guidance, mirroring the engine's `load_optional_peer`.\n *\n * `serve_flow` is not covered here: it operates on a caller-constructed\n * `McpServer`, so it needs only a type-only import and no runtime SDK load.\n */\n\nimport { mcp_sdk_missing_error } from './errors.js'\n\nexport type McpClientSdk = Awaited<ReturnType<typeof load_client_sdk>>\n\n/**\n * Dynamically imports the `@modelcontextprotocol/sdk` client modules,\n * throwing a typed `mcp_sdk_missing_error` when the optional peer is not\n * installed.\n */\nexport async function load_client_sdk() {\n try {\n const [client_mod, stdio_mod, http_mod] = await Promise.all([\n import('@modelcontextprotocol/sdk/client/index.js'),\n import('@modelcontextprotocol/sdk/client/stdio.js'),\n import('@modelcontextprotocol/sdk/client/streamableHttp.js'),\n ])\n return {\n Client: client_mod.Client,\n StdioClientTransport: stdio_mod.StdioClientTransport,\n StreamableHTTPClientTransport: http_mod.StreamableHTTPClientTransport,\n }\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : String(err)\n throw new mcp_sdk_missing_error(\n `@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk (cause: ${detail})`,\n )\n }\n}\n","/**\n * Inbound MCP: connect to an external MCP server and surface its tools as plain\n * Fascicle `Tool[]`.\n */\n\nimport type { Client } from '@modelcontextprotocol/sdk/client/index.js'\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'\nimport type { Tool, ToolExecContext } from '#engine'\nimport { is_record, json_schema_to_standard } from '#schema'\nimport { mcp_error } from './errors.js'\nimport { call_result_to_output } from './result_mapping.js'\nimport { load_client_sdk, type McpClientSdk } from './sdk_loader.js'\n\nconst DEFAULT_CLIENT_INFO = { name: 'fascicle', version: '0.0.0' }\n\nexport type McpStdioConfig = {\n transport: 'stdio'\n command: string\n args?: string[]\n env?: Record<string, string>\n cwd?: string\n}\n\nexport type McpStreamableHttpConfig = {\n transport: 'http'\n url: string\n headers?: Record<string, string>\n}\n\n// Escape hatch: hand in an already-connected Client (a transport the adapter\n// does not build, a test harness, a shared connection). Its lifecycle stays\n// with the caller, so the returned `close` is a no-op for this variant.\nexport type McpExistingClientConfig = {\n transport: 'client'\n client: Client\n}\n\nexport type McpClientConfig =\n | McpStdioConfig\n | McpStreamableHttpConfig\n | McpExistingClientConfig\n\nexport type McpClientOptions = {\n // Identity sent in the MCP handshake; defaults to Fascicle.\n client_info?: { name: string; version: string }\n // When set, only tools whose name is listed are surfaced.\n include?: ReadonlyArray<string>\n // Supplies a description for tools that advertise none.\n default_description?: (tool_name: string) => string\n}\n\nexport type McpClientHandle = {\n readonly tools: ReadonlyArray<Tool>\n readonly close: () => Promise<void>\n}\n\n/**\n * Connects to an MCP server and surfaces its advertised tools as Fascicle\n * `Tool[]`, plus a `close` handle for the connection.\n *\n * Owns the connection lifecycle (config in, `{ tools, close }` out) so callers\n * do not have to import SDK transport classes themselves. Each advertised MCP\n * tool becomes an ordinary `Tool`: its JSON Schema is wrapped as a `ToolSchema`\n * the loop validates against and the provider receives back unchanged, and\n * `execute` forwards to `callTool`, propagating the run's abort signal. For the\n * `client` transport variant the caller keeps ownership of the connection, so\n * `close` is a no-op. A connection this call opened is closed again when\n * listing its tools fails.\n */\nexport async function mcp_client(\n config: McpClientConfig,\n options: McpClientOptions = {},\n): Promise<McpClientHandle> {\n const owns_client = config.transport !== 'client'\n const client = await connect_client(config, options)\n\n const include = options.include !== undefined ? new Set(options.include) : undefined\n const listed = await client.listTools().catch(async (err: unknown) => {\n // A client this call connected has no other owner yet, so it closes here,\n // taking a spawned stdio server with it. The listing failure is the one\n // the caller sees, even if the close fails too.\n if (owns_client) await client.close().catch(() => undefined)\n throw err\n })\n const tools: Tool[] = []\n for (const advertised of listed.tools) {\n if (include !== undefined && !include.has(advertised.name)) continue\n tools.push(to_fascicle_tool(client, advertised, options))\n }\n\n return {\n tools,\n close: async () => {\n if (owns_client) await client.close()\n },\n }\n}\n\n/**\n * Returns the caller's already-connected client as-is, or lazily loads the\n * SDK and connects a fresh client over the configured transport.\n */\nasync function connect_client(\n config: McpClientConfig,\n options: McpClientOptions,\n): Promise<Client> {\n if (config.transport === 'client') return config.client\n const sdk = await load_client_sdk()\n const client = new sdk.Client(options.client_info ?? DEFAULT_CLIENT_INFO)\n await client.connect(build_transport(sdk, config))\n return client\n}\n\n/**\n * Constructs the SDK transport matching the config: a spawned child process\n * for `stdio`, a Streamable HTTP connection for `http`.\n */\nfunction build_transport(\n sdk: McpClientSdk,\n config: McpStdioConfig | McpStreamableHttpConfig,\n): Transport {\n if (config.transport === 'stdio') {\n return new sdk.StdioClientTransport({\n command: config.command,\n ...(config.args !== undefined ? { args: config.args } : {}),\n ...(config.env !== undefined ? { env: config.env } : {}),\n ...(config.cwd !== undefined ? { cwd: config.cwd } : {}),\n })\n }\n const opts = config.headers !== undefined ? { requestInit: { headers: config.headers } } : {}\n // The SDK declares this class `implements Transport`, but its `onmessage`\n // overload is narrower than the interface's, which only strict mode flags.\n // eslint-disable-next-line typescript-eslint/no-unsafe-type-assertion\n return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts) as Transport\n}\n\n/**\n * Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards\n * to `callTool` on the shared client.\n *\n * An already-aborted signal short-circuits before the wire call; otherwise the\n * signal is passed through so cancelling the run cancels the remote call.\n */\nfunction to_fascicle_tool(\n client: Client,\n advertised: { name: string; description?: string | undefined; inputSchema: unknown },\n options: McpClientOptions,\n): Tool {\n const name = advertised.name\n const description =\n advertised.description ?? options.default_description?.(name) ?? `MCP tool ${name}`\n return {\n name,\n description,\n input_schema: json_schema_to_standard(advertised.inputSchema),\n execute: async (input: unknown, ctx: ToolExecContext) => {\n if (ctx.abort.aborted) {\n throw ctx.abort.reason instanceof Error\n ? ctx.abort.reason\n : new mcp_error(`MCP tool ${name} aborted before invocation`, { tool_name: name })\n }\n const result = await client.callTool(\n { name, arguments: is_record(input) ? input : undefined },\n undefined,\n { signal: ctx.abort },\n )\n return call_result_to_output(result, name)\n },\n }\n}\n","/**\n * Outbound MCP: expose a composed Fascicle flow as an MCP tool.\n *\n * `serve_flow` registers onto a caller-constructed `McpServer` (the caller owns\n * the transport, identity, and lifecycle, and can host many flows on one\n * server), so it needs only a type-only SDK import. The registered handler\n * drives the existing `run`, threading the per-request abort signal so an MCP\n * client cancellation aborts the in-flight flow, and maps the result into a\n * `CallToolResult`. A thrown flow becomes an `isError` result rather than a\n * JSON-RPC protocol error.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { z } from 'zod'\nimport { run } from '#core'\nimport type { Step, TrajectoryLogger } from '#core'\nimport { output_to_call_result } from './result_mapping.js'\n\nexport type ServeFlowConfig<i, o> = {\n server: McpServer\n flow: Step<i, o>\n name: string\n description: string\n /**\n * Stays zod rather than joining the rest of the surface on `ToolSchema`.\n * `McpServer.registerTool` types `inputSchema` as a zod schema and offers no\n * JSON Schema entry point, and the SDK carries zod as a hard runtime\n * dependency, so a `serve_flow` caller already has zod resolved. Widening\n * this to a neutral schema would typecheck and then fail inside the SDK.\n */\n input_schema: z.ZodType<i>\n trajectory?: TrajectoryLogger\n // Overrides the default value-to-CallToolResult mapping.\n to_result?: (output: o) => { text: string; structured?: Record<string, unknown> }\n}\n\n/**\n * Registers a Fascicle flow as a tool on a caller-owned MCP server.\n *\n * Drives the flow with `run`, threading the per-request abort signal so an\n * MCP client cancellation aborts the in-flight flow, and maps the result\n * into a `CallToolResult`. A thrown flow becomes an `isError` result rather\n * than a JSON-RPC protocol error.\n */\nexport function serve_flow<i, o>(config: ServeFlowConfig<i, o>): void {\n const { server, flow, name, description, input_schema, trajectory, to_result } = config\n server.registerTool(\n name,\n { description, inputSchema: input_schema },\n async (input: i, extra) => {\n try {\n const output = await run(flow, input, {\n install_signal_handlers: false,\n abort: extra.signal,\n ...(trajectory !== undefined ? { trajectory } : {}),\n })\n return output_to_call_result(output, to_result)\n } catch (err: unknown) {\n return {\n isError: true,\n content: [{ type: 'text', text: err instanceof Error ? err.message : String(err) }],\n }\n }\n },\n )\n}\n"],"mappings":";;;;;;;;;;;AAQA,IAAa,wBAAb,cAA2C,MAAM;CAC/C,OAAgB;CAChB,YACE,UAAU,0GACV;EACA,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,IAAa,YAAb,cAA+B,MAAM;CACnC,OAAgB;CAChB;CACA,YAAY,SAAiB,WAAmC,CAAC,GAAG;EAClE,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,YAAY,SAAS;CAC5B;AACF;;;;;;;;;;;;;;;;;ACHA,SAAgB,sBAAsB,QAAiB,WAA6B;CAClF,MAAM,SAAS,UAAU,MAAM,KAAK,CAAC;CAErC,IAAI,OAAO,eAAe,MAExB,MAAM,IAAI,UADK,UAAU,OAAO,UAAU,KAAK,8BACnB,c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,OAAO,sBAAsB,MALR,IAAI,MAAM,OAAO;IACpC,yBAAyB;IACzB,OAAO,MAAM;IACb,GAAI,eAAe,KAAA,IAAY,EAAE,WAAW,IAAI,CAAC;GACnD,CAAC,GACoC,SAAS;EAChD,SAAS,KAAc;GACrB,OAAO;IACL,SAAS;IACT,SAAS,CAAC;KAAE,MAAM;KAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;IAAE,CAAC;GACpF;EACF;CACF,CACF;AACF"}
package/dist/otel.js CHANGED
@@ -28,9 +28,9 @@ import { SpanStatusCode, context, metrics, trace } from "@opentelemetry/api";
28
28
  * Provider and model attributes come from the enclosing `engine.generate`
29
29
  * span's start meta, tracked on a stack with the same documented
30
30
  * approximation as the span bridge: concurrent generates sharing one logger
31
- * attribute to the innermost open call. The semantic conventions are still
32
- * experimental (mid-2026), so a semconv revision may rename instruments;
33
- * this module tracks the names at implementation time.
31
+ * attribute to the innermost open call. The GenAI semantic conventions are
32
+ * experimental, so a revision of them may rename an instrument this module
33
+ * records.
34
34
  */
35
35
  /** Semconv-suggested boundaries for the duration histograms, in seconds. */
36
36
  const DURATION_BOUNDARIES = [
@@ -112,7 +112,6 @@ function create_metrics_recorder(options) {
112
112
  unit: "{retry}",
113
113
  description: "Provider turn attempts that failed and were retried"
114
114
  });
115
- const generate_ids = /* @__PURE__ */ new Set();
116
115
  const context_stack = [];
117
116
  const base_attributes = () => {
118
117
  const attrs = { "gen_ai.operation.name": "chat" };
@@ -141,17 +140,17 @@ function create_metrics_recorder(options) {
141
140
  return {
142
141
  on_start_span(id, name, meta) {
143
142
  if (name !== "engine.generate") return;
144
- generate_ids.add(id);
145
143
  const provider = meta?.["provider"];
146
144
  const model = meta?.["model_id"];
147
145
  context_stack.push({
146
+ id,
148
147
  ...typeof provider === "string" ? { provider } : {},
149
148
  ...typeof model === "string" ? { model } : {}
150
149
  });
151
150
  },
152
151
  on_end_span(id) {
153
- if (!generate_ids.delete(id)) return;
154
- context_stack.pop();
152
+ const idx = context_stack.findIndex((entry) => entry.id === id);
153
+ if (idx !== -1) context_stack.splice(idx, 1);
155
154
  },
156
155
  on_record(event) {
157
156
  if (event.kind === "response_received") {
@@ -197,9 +196,10 @@ function create_metrics_recorder(options) {
197
196
  * transports get traces without any AI-SDK involvement.
198
197
  *
199
198
  * `@opentelemetry/api` is imported ONLY under `src/otel/` (this module and
200
- * metrics.ts), outside `src/engine/` on purpose: the engine's `ai + zod`
201
- * npm-dep invariant holds unmodified, and an app that never imports
202
- * `fascicle/otel` pulls in zero OTel packages at runtime.
199
+ * metrics.ts), outside `src/engine/` on purpose: engine code outside
200
+ * `providers/` imports no npm package (rules/no-engine-npm-dep.yml), and an
201
+ * app that never imports `fascicle/otel` pulls in zero OTel packages at
202
+ * runtime.
203
203
  *
204
204
  * Nesting is resolved two ways, in order: an explicit `parent_span_id` on the
205
205
  * start meta (how the composition runner threads composer-span parenthood) wins;