fascicle 0.17.7 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +25 -2
  3. package/dist/AGENTS.md +23 -11
  4. package/dist/acp.d.ts +3 -17
  5. package/dist/acp.js +25 -44
  6. package/dist/acp.js.map +1 -1
  7. package/dist/{adapters-CDUzZlby.js → adapters-CpKpDk7r.js} +9 -17
  8. package/dist/{adapters-CDUzZlby.js.map → adapters-CpKpDk7r.js.map} +1 -1
  9. package/dist/adapters.d.ts +1 -13
  10. package/dist/adapters.js +1 -1
  11. package/dist/agents.d.ts +3 -5
  12. package/dist/agents.js +2 -3
  13. package/dist/{console-CdB4pcFO.js → console-B1ozi_ii.js} +2 -3
  14. package/dist/{console-CdB4pcFO.js.map → console-B1ozi_ii.js.map} +1 -1
  15. package/dist/{core-Bfzt55Fl.js → core-BH7sWpEG.js} +34 -66
  16. package/dist/{core-Bfzt55Fl.js.map → core-BH7sWpEG.js.map} +1 -1
  17. package/dist/diagram_bin.d.ts +0 -2
  18. package/dist/diagram_bin.js +3 -5
  19. package/dist/diagram_bin.js.map +1 -1
  20. package/dist/{engine-B5iQ3if9.js → engine-fOjYHcv6.js} +302 -98
  21. package/dist/engine-fOjYHcv6.js.map +1 -0
  22. package/dist/index.d.ts +4 -98
  23. package/dist/index.js +27 -47
  24. package/dist/index.js.map +1 -1
  25. package/dist/{invoke-DnmWf8gE.js → invoke-7iu8db6V.js} +19 -12
  26. package/dist/{invoke-DnmWf8gE.js.map → invoke-7iu8db6V.js.map} +1 -1
  27. package/dist/{json_schema_to_standard-C4F4lXHE.js → json_schema_to_standard-BstoXjM8.js} +3 -4
  28. package/dist/{json_schema_to_standard-C4F4lXHE.js.map → json_schema_to_standard-BstoXjM8.js.map} +1 -1
  29. package/dist/{leading_system-CHSYz0h9.js → leading_system-BeQUSAim.js} +6 -10
  30. package/dist/{leading_system-CHSYz0h9.js.map → leading_system-BeQUSAim.js.map} +1 -1
  31. package/dist/{mcp-8mKK7eDY.js → mcp-CHJ88HiG.js} +9 -14
  32. package/dist/{mcp-8mKK7eDY.js.map → mcp-CHJ88HiG.js.map} +1 -1
  33. package/dist/mcp.d.ts +3 -11
  34. package/dist/mcp.js +2 -2
  35. package/dist/otel.d.ts +1 -5
  36. package/dist/otel.js +3 -6
  37. package/dist/otel.js.map +1 -1
  38. package/dist/{records-1HU7mWXf.js → records-Btlmvunj.js} +2 -3
  39. package/dist/{records-1HU7mWXf.js.map → records-Btlmvunj.js.map} +1 -1
  40. package/dist/{search-DjhdMsJ8.js → search-BZagxXtd.js} +7 -11
  41. package/dist/{search-DjhdMsJ8.js.map → search-BZagxXtd.js.map} +1 -1
  42. package/dist/search_worker.js +2 -3
  43. package/dist/stdio.d.ts +2 -6
  44. package/dist/stdio.js +5 -7
  45. package/dist/stdio.js.map +1 -1
  46. package/dist/testing.d.ts +2 -18
  47. package/dist/testing.js +12 -21
  48. package/dist/testing.js.map +1 -1
  49. package/dist/{trajectory-DeURWIhj.js → trajectory-CkCFZWNR.js} +2 -3
  50. package/dist/{trajectory-DeURWIhj.js.map → trajectory-CkCFZWNR.js.map} +1 -1
  51. package/dist/{trajectory-BKGNxi7u.d.ts → trajectory-Dt0-A7kb.d.ts} +1 -3
  52. package/dist/{types-CPqLZOEr.d.ts → types-BUXt_zgJ.d.ts} +1 -3
  53. package/dist/{types-BK0UW28o.d.ts → types-CvghbZ0x.d.ts} +1 -5
  54. package/dist/{types-xYjCEd6i.d.ts → types-Dk9tLpUq.d.ts} +42 -9
  55. package/dist/ui.d.ts +1 -3
  56. package/dist/ui.js +1 -2
  57. package/dist/viewer-app/assets/index-D8Tb3drm.js +4 -0
  58. package/dist/viewer-app/index.html +1 -1
  59. package/dist/viewer.d.ts +1 -11
  60. package/dist/viewer.js +8 -14
  61. package/dist/viewer.js.map +1 -1
  62. package/dist/web.d.ts +83 -0
  63. package/dist/web.js +2888 -0
  64. package/dist/web.js.map +1 -0
  65. package/package.json +34 -28
  66. package/dist/engine-B5iQ3if9.js.map +0 -1
  67. package/dist/viewer-app/assets/index-YrQFld-l.js +0 -4
@@ -1 +1 @@
1
- {"version":3,"file":"leading_system-CHSYz0h9.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 override readonly cause: unknown;\n constructor(\n message: string,\n metadata: { retry_after_ms?: number; attempts?: number; status?: number; cause?: unknown } = {},\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 this.cause = metadata.cause\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 readonly attempts: number | undefined;\n override readonly cause: unknown;\n constructor(\n message: string,\n metadata: {\n status?: number\n body?: string | undefined\n cause_kind?: 'provider_5xx' | 'network' | 'unknown'\n attempts?: number\n cause?: 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 this.attempts = metadata.attempts\n this.cause = metadata.cause\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 reached a\n * consumer.\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. An expiry after a\n * chunk has reached an on_chunk consumer never reaches here; retry_turn\n * converts it to a non-retryable 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 override readonly cause: unknown;\n constructor(\n provider: string,\n message: string,\n metadata: { refresh_command?: string; cause?: unknown } = {},\n ) {\n super(message)\n this.name = 'provider_auth_error'\n this.provider = provider\n this.refresh_command = metadata.refresh_command\n this.cause = metadata.cause\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 CacheSetting,\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\n/**\n * How an adapter caches prompts, which decides what a call's `cache` setting\n * does on it. `'with_tools'` caches for five minutes by default on a call\n * with tools, `'opt_in'` caches only when the call or the engine asks, and\n * `'automatic'` marks a provider that caches on its own, so an explicit\n * setting is ignored. An adapter that declares nothing requests no caching.\n */\ntype PromptCacheDeclaration = 'with_tools' | 'opt_in' | 'automatic'\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 /**\n * Map the SDK's usage to UsageTotals. The engine also hands it the step's\n * `providerMetadata`, for a split that the SDK's usage object leaves out.\n */\n readonly normalize_usage: (raw: RawProviderUsage | undefined, provider_metadata?: unknown) => UsageTotals\n readonly supports: (capability: ProviderCapability) => boolean\n readonly prompt_cache?: PromptCacheDeclaration\n /**\n * Turn the call's resolved cache setting into call-level provider options,\n * given the caller's own (engine defaults merged with the call's). The\n * engine merges the result beneath the caller's options, where effort's\n * translation goes. An adapter that declares `'with_tools'` or `'opt_in'`\n * without this hook asks for no cache, as one that declares nothing.\n */\n readonly translate_cache?: (\n cache: CacheSetting,\n provider_options: Readonly<Record<string, unknown>> | undefined,\n ) => Record<string, Record<string, unknown>>\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 prompt_cache?: PromptCacheDeclaration\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.cache_write_1h_tokens\n delete base.reasoning_tokens\n return base\n}\n\n/**\n * The error for a provider config that's missing a value the provider can't\n * run without. It names the key to pass to create_engine and where the value\n * usually comes from, an environment variable or a local server's address.\n * It says \"pass\" because the engine never reads the environment itself.\n */\nexport function missing_config_error(\n provider: string,\n key: string,\n usual: string,\n): engine_config_error {\n return new engine_config_error(\n `${provider} provider requires a non-empty ${key}: pass providers.${provider}.${key} to create_engine, usually ${usual}`,\n provider,\n )\n}\n\n/** The built-in providers that send no credentials of their own. */\nconst KEYLESS_PROVIDERS: ReadonlySet<string> = new Set(['ollama', 'lmstudio'])\n\n/**\n * Whether `base_url` puts a user name or password before its host, with a\n * scheme or without one, as `http://user:pass@host` and `user@host:11434`\n * do. Only the authority counts, the part before the first `/`, `?`, or `#`,\n * so an `@` in a path or a query isn't one.\n */\nfunction has_userinfo(base_url: string): boolean {\n const scheme_end = base_url.indexOf('://')\n const rest = scheme_end === -1 ? base_url : base_url.slice(scheme_end + 3)\n const authority_end = rest.search(/[/?#]/)\n const authority = authority_end === -1 ? rest : rest.slice(0, authority_end)\n return authority.includes('@')\n}\n\n/**\n * Throw `engine_config_error` for a built-in provider whose `base_url` holds\n * a user name or password. Node's fetch refuses to send a request to such a\n * URL, and its error repeats the whole URL, credentials included, so the\n * engine refuses it as it's built, without repeating the URL.\n */\nexport function refuse_credentials_in_base_url(provider: string, init: ProviderInit): void {\n const base_url: unknown = init.base_url\n if (typeof base_url !== 'string' || !has_userinfo(base_url)) return\n const fix = KEYLESS_PROVIDERS.has(provider)\n ? `since the ${provider} provider sends no credentials`\n : `and pass the key as providers.${provider}.api_key`\n throw new engine_config_error(\n `${provider} provider's base_url holds a user name or password, which fetch refuses to send: take them out of base_url, ${fix}`,\n provider,\n )\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 * `value` when it is a non-empty string, or undefined.\n */\nfunction non_empty_string(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * The message under a JSON error envelope's `error` key, or else its\n * top-level `message`, or undefined when the shape carries none worth\n * surfacing.\n */\nfunction error_field_message(parsed: unknown): string | undefined {\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 if (error !== null && typeof error === 'object') {\n const message = non_empty_string(Reflect.get(error, 'message'))\n if (message !== undefined) return message\n }\n return non_empty_string(Reflect.get(parsed, 'message'))\n}\n\n/**\n * The message a non-2xx JSON body carries, or undefined when the body isn't\n * JSON or carries none. The wires share one envelope family: Anthropic sends\n * `{ type: 'error', error: { message } }`, OpenAI-style wires send\n * `{ error: { message } }`, Ollama sends `{ error: \"message\" }` (with the\n * nested shape appearing behind proxies), and Bedrock sends `{ message }`, so\n * one parser accepts a string or a `{ message }` object under `error`, and\n * then a top-level `message`. The engine's classifier reads an AI SDK error's\n * `responseBody` through it too.\n */\nexport function error_body_message(body: string): string | undefined {\n let parsed: unknown\n try {\n parsed = JSON.parse(body)\n } catch {\n // Not JSON, so it carries no message.\n }\n return error_field_message(parsed)\n}\n\n/**\n * Pull a human-readable message out of a non-2xx body: the one its JSON\n * carries (see error_body_message), or else the raw body, truncated to 300\n * chars.\n */\nfunction extract_error_message(body: string): string {\n if (body.length === 0) return '(empty body)'\n const message = error_body_message(body)\n if (message !== undefined) return message\n return body.length > 300 ? `${body.slice(0, 300)}...` : body\n}\n\nconst LOCAL_PROVIDERS: ReadonlySet<string> = new Set(['ollama', 'lmstudio'])\n\n/** The model name in Ollama's `model 'x' not found` reply, either quote. */\nconst OLLAMA_MISSING_MODEL = /model ['\"]([^'\"]+)['\"] not found/\n\n/**\n * `detail` without the one period a provider's sentence ends on, so that an\n * action can follow it after a colon. A `...` truncation tail keeps its dots.\n */\nfunction strip_trailing_period(detail: string): string {\n return detail.replace(/(?<!\\.)\\.$/, '')\n}\n\n/**\n * What to do about a 404: pull the model, when Ollama names one it doesn't\n * have, and otherwise check the model id and where `base_url` points, since\n * a path the provider doesn't serve answers 404 too.\n */\nfunction not_found_action(provider: string, detail: string): string {\n const missing = provider === 'ollama' ? OLLAMA_MISSING_MODEL.exec(detail)?.[1] : undefined\n if (missing !== undefined) return `run ollama pull ${missing}`\n return `check the model id against the ${provider} model list, and that base_url points at the ${provider} API`\n}\n\n/**\n * What a caller does about a non-retryable status, or '' for a status whose\n * fix only the provider's own text can say, such as a 400 or a 422. The\n * ollama and lmstudio providers send no credentials, so a 401 from either\n * comes from something in front of the server.\n */\nfunction status_action(provider: string, status: number, detail: string): string {\n if (status === 401) {\n return LOCAL_PROVIDERS.has(provider)\n ? `the ${provider} provider sends no credentials, so check that base_url reaches the server without a proxy that asks for them`\n : `check providers.${provider}.api_key`\n }\n if (status === 403) return 'the credentials lack access to this model or endpoint'\n if (status === 404) return not_found_action(provider, detail)\n return ''\n}\n\n/**\n * The error a status that won't be retried becomes, on either transport: a\n * 401 is a provider_auth_error, and any other status a provider_error that\n * carries it and the body. The message leads with the provider and the\n * status, then the provider's own text, then what to do when the status says\n * it. The native transport's response_error and the engine's ai_sdk\n * classifier both build theirs here, so a wrong key or a wrong model id reads\n * the same whichever transport the call took, and `cause` holds the SDK's\n * error on the ai_sdk one.\n */\nexport function non_retryable_status_error(\n provider: string,\n status: number,\n detail: string,\n metadata: { body?: string | undefined; cause?: unknown } = {},\n): provider_auth_error | provider_error {\n const action = status_action(provider, status, detail)\n const tail = action === '' ? detail : `${strip_trailing_period(detail)}: ${action}`\n if (status === 401) {\n return new provider_auth_error(provider, `${provider} authentication failed (401): ${tail}`, {\n cause: metadata.cause,\n })\n }\n return new provider_error(`${provider} API error ${status}: ${tail}`, { status, ...metadata })\n}\n\n/**\n * Map a non-2xx response to what the engine's retry stack expects: 429/5xx\n * keep `status`, `body`, and `responseHeaders` so classify_provider_error\n * marks them retryable (rate_limit honoring retry-after, provider_5xx) and\n * the exhausted error still has the body, and any other status is the\n * permanent error that non_retryable_status_error builds, which surfaces\n * 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 === 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, body },\n retry_after !== null ? { responseHeaders: { 'retry-after': retry_after } } : {},\n )\n }\n return non_retryable_status_error(provider, status, detail, { body })\n}\n\n/**\n * A transport failure in the `kind: 'network'` shape that the shared\n * classify_provider_error marks retryable. A stream that ends before its\n * closing event throws it too, since a cut-off stream is a dropped\n * connection, so the engine retries it whenever nothing consumed its chunks.\n */\nexport function network_failure(message: string): Error {\n return Object.assign(new Error(message), { kind: 'network' })\n}\n\n/**\n * The `code` that `value` carries, such as `ECONNREFUSED`, when it's an\n * object whose `code` is a string.\n */\nfunction error_code(value: unknown): string | undefined {\n if (value === null || typeof value !== 'object') return undefined\n const code: unknown = Reflect.get(value, 'code')\n return typeof code === 'string' ? code : undefined\n}\n\n/**\n * A transport failure's own message, followed by the system error code that\n * the error or its `cause` carries when the message doesn't already name it,\n * as in `fetch failed (ECONNREFUSED)`. Undici's `fetch failed` alone doesn't\n * say whether the host refused, timed out, or doesn't resolve. A failure with\n * no message, such as the `AggregateError` that Node raises when every\n * address of a host refuses, is named by its code alone.\n */\nexport function network_detail(err: unknown): string {\n const message = err instanceof Error ? err.message : String(err)\n const cause: unknown = err !== null && typeof err === 'object' ? Reflect.get(err, 'cause') : undefined\n const code = error_code(err) ?? error_code(cause)\n if (message.length === 0) return code ?? '(no detail)'\n return code === undefined || message.includes(code) ? message : `${message} (${code})`\n}\n\n/**\n * `url` as its origin and path, without the credentials, query, or fragment\n * that can carry a key, so that a message that names it is safe to log. A\n * string that doesn't parse is named only as not being a URL.\n */\nfunction log_safe_url(url: string): string {\n try {\n const parsed = new URL(url)\n return `${parsed.origin}${parsed.pathname}`\n } catch {\n return 'a base_url that is not a valid URL'\n }\n}\n\n/**\n * The message for a request that never reached the provider: the URL it was\n * sent to (see log_safe_url), what failed, and what to check, with the\n * command that starts the server for Ollama, the one provider that's usually\n * a daemon on the same machine. A failure whose own text repeats the URL,\n * as undici's does for one that it can't parse or that holds credentials,\n * gets the same log-safe URL in its place.\n */\nexport function unreachable_message(provider: string, url: string, detail: string): string {\n const safe = log_safe_url(url)\n const scrubbed = url.length > 0 ? detail.replaceAll(url, safe) : detail\n const start = provider === 'ollama' ? ' (ollama serve)' : ''\n return `${provider} could not be reached at ${safe}: ${scrubbed}: check base_url, and that the server is running${start}`\n}\n\n/**\n * The message for a connection that dropped after the response began, which\n * names no URL, since the request reached the server.\n */\nfunction dropped_message(provider: string, detail: string): string {\n return `${provider} connection dropped while reading the response: ${detail}`\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 as a network_failure, whose message `message`\n * builds from the failure's network_detail.\n */\nfunction rethrow_network_failure(\n err: unknown,\n abort: AbortSignal,\n message: (detail: string) => string,\n): never {\n if (abort.aborted) throw err\n throw network_failure(message(network_detail(err)))\n}\n\n/**\n * The response's media type, lowercased and without its parameters, or ''\n * when it names none.\n */\nfunction media_type(response: Response): string {\n const header = response.headers.get('content-type') ?? ''\n return (header.split(';')[0] ?? '').trim().toLowerCase()\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, (detail) => dropped_message(provider, detail))\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 * The error for a response that isn't the provider's protocol: what was\n * wrong with it, then what to check, since a body of the wrong shape most\n * often comes from a `base_url` that points somewhere else. `also` names the\n * other fix when there is one.\n */\nexport function protocol_error(provider: string, what: string, also?: string): provider_error {\n const other = also === undefined ? '' : `, or ${also}`\n return new provider_error(\n `${provider} native: ${what}: check that base_url points at the ${provider} API${other}`,\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. A streamed request whose reply doesn't arrive as the\n * dialect's stream media type (`text/event-stream`, or NDJSON for Ollama) is\n * read as a whole JSON body, so a server that answers with JSON still works,\n * and a page that isn't JSON fails with the `base_url` hint rather than as a\n * cut-off stream. `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. `req.on_wire`, when the call captures the wire, sees the\n * URL and the body object just before the body is serialized, and never a\n * header.\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 /** The media type that a streamed reply arrives as. */\n stream_media_type: string\n },\n): Promise<TurnResult> {\n const built = request.build_body()\n req.on_wire?.({ url: request.url, body: built })\n const body = JSON.stringify(built)\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, (detail) => unreachable_message(provider, request.url, detail))\n }\n if (!response.ok) throw await response_error(response, provider)\n if (req.stream && media_type(response) === consume.stream_media_type) {\n return consume.stream(response)\n }\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, (detail) => dropped_message(provider, detail))\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). An\n * opaque part belongs to the provider that sent it, and these formats carry\n * no such block, so it is skipped.\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 (part.type === 'reasoning' && 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 === 'system'\n}\n"],"mappings":";;AAyBA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,OAAgB;CAEhB;CACA;CACA;CACA;CACA,YACE,SACA,WAA6F,CAAC,GAC9F;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,iBAAiB,SAAS;EAC/B,KAAK,WAAW,SAAS,YAAY;EACrC,KAAK,SAAS,SAAS;EACvB,KAAK,QAAQ,SAAS;CACxB;AACF;AAEA,IAAa,iBAAb,cAAoC,MAAM;CACxC,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA,YACE,SACA,WAMI,CAAC,GACL;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS,SAAS;EACvB,KAAK,OAAO,SAAS;EACrB,KAAK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C,IAAI,KAAK,SAAS,aAAa,WAAW,KAAK,IAAI;MACnD,IAAI,KAAK,SAAS,eAAe,iBAAiB,MAAM,QAAQ,GAAG,UAAU,KAAK,IAAI;CAE7F,OAAO;EAAE;EAAO;EAAY;CAAU;AACxC;;;;;;AAOA,SAAgB,kBACd,MACA,kBACuC;CACvC,OAAO;EACL,SAAS,OAAO,KAAK,YAAY,WAAW,KAAK,UAAU;EAC3D,UACE,OAAO,KAAK,aAAa,YAAY,KAAK,SAAS,SAAS,IACxD,KAAK,WACL;CACR;AACF;;;;;;;;;;;;;;;;;AC7iBA,SAAgB,yBACd,UACA,aACoC;CACpC,IAAI,UAAU;CACd,MAAM,eAAyB,CAAC;CAChC,OAAO,UAAU,SAAS,QAAQ;EAChC,MAAM,IAAI,SAAS;EACnB,IAAI,CAAC,kBAAkB,CAAC,GAAG;EAC3B,aAAa,KAAK,YAAY,CAAC,CAAC;EAChC,WAAW;CACb;CACA,MAAM,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"}
1
+ {"version":3,"file":"leading_system-BeQUSAim.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 override readonly cause: unknown;\n constructor(\n message: string,\n metadata: { retry_after_ms?: number; attempts?: number; status?: number; cause?: unknown } = {},\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 this.cause = metadata.cause\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 readonly attempts: number | undefined;\n override readonly cause: unknown;\n constructor(\n message: string,\n metadata: {\n status?: number\n body?: string | undefined\n cause_kind?: 'provider_5xx' | 'network' | 'unknown'\n attempts?: number\n cause?: 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 this.attempts = metadata.attempts\n this.cause = metadata.cause\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 reached a\n * consumer.\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. An expiry after a\n * chunk has reached an on_chunk consumer never reaches here; retry_turn\n * converts it to a non-retryable 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 override readonly cause: unknown;\n constructor(\n provider: string,\n message: string,\n metadata: { refresh_command?: string; cause?: unknown } = {},\n ) {\n super(message)\n this.name = 'provider_auth_error'\n this.provider = provider\n this.refresh_command = metadata.refresh_command\n this.cause = metadata.cause\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 CacheSetting,\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\n/**\n * How an adapter caches prompts, which decides what a call's `cache` setting\n * does on it. `'with_tools'` caches for five minutes by default on a call\n * with tools, `'opt_in'` caches only when the call or the engine asks, and\n * `'automatic'` marks a provider that caches on its own, so an explicit\n * setting is ignored. An adapter that declares nothing requests no caching.\n */\ntype PromptCacheDeclaration = 'with_tools' | 'opt_in' | 'automatic'\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 /**\n * Map the SDK's usage to UsageTotals. The engine also hands it the step's\n * `providerMetadata`, for a split that the SDK's usage object leaves out.\n */\n readonly normalize_usage: (raw: RawProviderUsage | undefined, provider_metadata?: unknown) => UsageTotals\n readonly supports: (capability: ProviderCapability) => boolean\n readonly prompt_cache?: PromptCacheDeclaration\n /**\n * Turn the call's resolved cache setting into call-level provider options,\n * given the caller's own (engine defaults merged with the call's). The\n * engine merges the result beneath the caller's options, where effort's\n * translation goes. An adapter that declares `'with_tools'` or `'opt_in'`\n * without this hook asks for no cache, as one that declares nothing.\n */\n readonly translate_cache?: (\n cache: CacheSetting,\n provider_options: Readonly<Record<string, unknown>> | undefined,\n ) => Record<string, Record<string, unknown>>\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 prompt_cache?: PromptCacheDeclaration\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.cache_write_1h_tokens\n delete base.reasoning_tokens\n return base\n}\n\n/**\n * The error for a provider config that's missing a value the provider can't\n * run without. It names the key to pass to create_engine and where the value\n * usually comes from, an environment variable or a local server's address.\n * It says \"pass\" because the engine never reads the environment itself.\n */\nexport function missing_config_error(\n provider: string,\n key: string,\n usual: string,\n): engine_config_error {\n return new engine_config_error(\n `${provider} provider requires a non-empty ${key}: pass providers.${provider}.${key} to create_engine, usually ${usual}`,\n provider,\n )\n}\n\n/** The built-in providers that send no credentials of their own. */\nconst KEYLESS_PROVIDERS: ReadonlySet<string> = new Set(['ollama', 'lmstudio'])\n\n/**\n * Whether `base_url` puts a user name or password before its host, with a\n * scheme or without one, as `http://user:pass@host` and `user@host:11434`\n * do. Only the authority counts, the part before the first `/`, `?`, or `#`,\n * so an `@` in a path or a query isn't one.\n */\nfunction has_userinfo(base_url: string): boolean {\n const scheme_end = base_url.indexOf('://')\n const rest = scheme_end === -1 ? base_url : base_url.slice(scheme_end + 3)\n const authority_end = rest.search(/[/?#]/)\n const authority = authority_end === -1 ? rest : rest.slice(0, authority_end)\n return authority.includes('@')\n}\n\n/**\n * Throw `engine_config_error` for a built-in provider whose `base_url` holds\n * a user name or password. Node's fetch refuses to send a request to such a\n * URL, and its error repeats the whole URL, credentials included, so the\n * engine refuses it as it's built, without repeating the URL.\n */\nexport function refuse_credentials_in_base_url(provider: string, init: ProviderInit): void {\n const base_url: unknown = init.base_url\n if (typeof base_url !== 'string' || !has_userinfo(base_url)) return\n const fix = KEYLESS_PROVIDERS.has(provider)\n ? `since the ${provider} provider sends no credentials`\n : `and pass the key as providers.${provider}.api_key`\n throw new engine_config_error(\n `${provider} provider's base_url holds a user name or password, which fetch refuses to send: take them out of base_url, ${fix}`,\n provider,\n )\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 * `value` when it is a non-empty string, or undefined.\n */\nfunction non_empty_string(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/**\n * The message under a JSON error envelope's `error` key, or else its\n * top-level `message`, or undefined when the shape carries none worth\n * surfacing.\n */\nfunction error_field_message(parsed: unknown): string | undefined {\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 if (error !== null && typeof error === 'object') {\n const message = non_empty_string(Reflect.get(error, 'message'))\n if (message !== undefined) return message\n }\n return non_empty_string(Reflect.get(parsed, 'message'))\n}\n\n/**\n * The message a non-2xx JSON body carries, or undefined when the body isn't\n * JSON or carries none. The wires share one envelope family: Anthropic sends\n * `{ type: 'error', error: { message } }`, OpenAI-style wires send\n * `{ error: { message } }`, Ollama sends `{ error: \"message\" }` (with the\n * nested shape appearing behind proxies), and Bedrock sends `{ message }`, so\n * one parser accepts a string or a `{ message }` object under `error`, and\n * then a top-level `message`. The engine's classifier reads an AI SDK error's\n * `responseBody` through it too.\n */\nexport function error_body_message(body: string): string | undefined {\n let parsed: unknown\n try {\n parsed = JSON.parse(body)\n } catch {\n // Not JSON, so it carries no message.\n }\n return error_field_message(parsed)\n}\n\n/**\n * Pull a human-readable message out of a non-2xx body: the one its JSON\n * carries (see error_body_message), or else the raw body, truncated to 300\n * chars.\n */\nfunction extract_error_message(body: string): string {\n if (body.length === 0) return '(empty body)'\n const message = error_body_message(body)\n if (message !== undefined) return message\n return body.length > 300 ? `${body.slice(0, 300)}...` : body\n}\n\nconst LOCAL_PROVIDERS: ReadonlySet<string> = new Set(['ollama', 'lmstudio'])\n\n/** The model name in Ollama's `model 'x' not found` reply, either quote. */\nconst OLLAMA_MISSING_MODEL = /model ['\"]([^'\"]+)['\"] not found/\n\n/**\n * `detail` without the one period a provider's sentence ends on, so that an\n * action can follow it after a colon. A `...` truncation tail keeps its dots.\n */\nfunction strip_trailing_period(detail: string): string {\n return detail.replace(/(?<!\\.)\\.$/, '')\n}\n\n/**\n * What to do about a 404: pull the model, when Ollama names one it doesn't\n * have, and otherwise check the model id and where `base_url` points, since\n * a path the provider doesn't serve answers 404 too.\n */\nfunction not_found_action(provider: string, detail: string): string {\n const missing = provider === 'ollama' ? OLLAMA_MISSING_MODEL.exec(detail)?.[1] : undefined\n if (missing !== undefined) return `run ollama pull ${missing}`\n return `check the model id against the ${provider} model list, and that base_url points at the ${provider} API`\n}\n\n/**\n * What a caller does about a non-retryable status, or '' for a status whose\n * fix only the provider's own text can say, such as a 400 or a 422. The\n * ollama and lmstudio providers send no credentials, so a 401 from either\n * comes from something in front of the server.\n */\nfunction status_action(provider: string, status: number, detail: string): string {\n if (status === 401) {\n return LOCAL_PROVIDERS.has(provider)\n ? `the ${provider} provider sends no credentials, so check that base_url reaches the server without a proxy that asks for them`\n : `check providers.${provider}.api_key`\n }\n if (status === 403) return 'the credentials lack access to this model or endpoint'\n if (status === 404) return not_found_action(provider, detail)\n return ''\n}\n\n/**\n * The error a status that won't be retried becomes, on either transport: a\n * 401 is a provider_auth_error, and any other status a provider_error that\n * carries it and the body. The message leads with the provider and the\n * status, then the provider's own text, then what to do when the status says\n * it. The native transport's response_error and the engine's ai_sdk\n * classifier both build theirs here, so a wrong key or a wrong model id reads\n * the same whichever transport the call took, and `cause` holds the SDK's\n * error on the ai_sdk one.\n */\nexport function non_retryable_status_error(\n provider: string,\n status: number,\n detail: string,\n metadata: { body?: string | undefined; cause?: unknown } = {},\n): provider_auth_error | provider_error {\n const action = status_action(provider, status, detail)\n const tail = action === '' ? detail : `${strip_trailing_period(detail)}: ${action}`\n if (status === 401) {\n return new provider_auth_error(provider, `${provider} authentication failed (401): ${tail}`, {\n cause: metadata.cause,\n })\n }\n return new provider_error(`${provider} API error ${status}: ${tail}`, { status, ...metadata })\n}\n\n/**\n * Map a non-2xx response to what the engine's retry stack expects: 429/5xx\n * keep `status`, `body`, and `responseHeaders` so classify_provider_error\n * marks them retryable (rate_limit honoring retry-after, provider_5xx) and\n * the exhausted error still has the body, and any other status is the\n * permanent error that non_retryable_status_error builds, which surfaces\n * 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 === 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, body },\n retry_after !== null ? { responseHeaders: { 'retry-after': retry_after } } : {},\n )\n }\n return non_retryable_status_error(provider, status, detail, { body })\n}\n\n/**\n * A transport failure in the `kind: 'network'` shape that the shared\n * classify_provider_error marks retryable. A stream that ends before its\n * closing event throws it too, since a cut-off stream is a dropped\n * connection, so the engine retries it whenever nothing consumed its chunks.\n */\nexport function network_failure(message: string): Error {\n return Object.assign(new Error(message), { kind: 'network' })\n}\n\n/**\n * The `code` that `value` carries, such as `ECONNREFUSED`, when it's an\n * object whose `code` is a string.\n */\nfunction error_code(value: unknown): string | undefined {\n if (value === null || typeof value !== 'object') return undefined\n const code: unknown = Reflect.get(value, 'code')\n return typeof code === 'string' ? code : undefined\n}\n\n/**\n * A transport failure's own message, followed by the system error code that\n * the error or its `cause` carries when the message doesn't already name it,\n * as in `fetch failed (ECONNREFUSED)`. Undici's `fetch failed` alone doesn't\n * say whether the host refused, timed out, or doesn't resolve. A failure with\n * no message, such as the `AggregateError` that Node raises when every\n * address of a host refuses, is named by its code alone.\n */\nexport function network_detail(err: unknown): string {\n const message = err instanceof Error ? err.message : String(err)\n const cause: unknown = err !== null && typeof err === 'object' ? Reflect.get(err, 'cause') : undefined\n const code = error_code(err) ?? error_code(cause)\n if (message.length === 0) return code ?? '(no detail)'\n return code === undefined || message.includes(code) ? message : `${message} (${code})`\n}\n\n/**\n * `url` as its origin and path, without the credentials, query, or fragment\n * that can carry a key, so that a message that names it is safe to log. A\n * string that doesn't parse is named only as not being a URL.\n */\nfunction log_safe_url(url: string): string {\n try {\n const parsed = new URL(url)\n return `${parsed.origin}${parsed.pathname}`\n } catch {\n return 'a base_url that is not a valid URL'\n }\n}\n\n/**\n * The message for a request that never reached the provider: the URL it was\n * sent to (see log_safe_url), what failed, and what to check, with the\n * command that starts the server for Ollama, the one provider that's usually\n * a daemon on the same machine. A failure whose own text repeats the URL,\n * as undici's does for one that it can't parse or that holds credentials,\n * gets the same log-safe URL in its place.\n */\nexport function unreachable_message(provider: string, url: string, detail: string): string {\n const safe = log_safe_url(url)\n const scrubbed = url.length > 0 ? detail.replaceAll(url, safe) : detail\n const start = provider === 'ollama' ? ' (ollama serve)' : ''\n return `${provider} could not be reached at ${safe}: ${scrubbed}: check base_url, and that the server is running${start}`\n}\n\n/**\n * The message for a connection that dropped after the response began, which\n * names no URL, since the request reached the server.\n */\nfunction dropped_message(provider: string, detail: string): string {\n return `${provider} connection dropped while reading the response: ${detail}`\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 as a network_failure, whose message `message`\n * builds from the failure's network_detail.\n */\nfunction rethrow_network_failure(\n err: unknown,\n abort: AbortSignal,\n message: (detail: string) => string,\n): never {\n if (abort.aborted) throw err\n throw network_failure(message(network_detail(err)))\n}\n\n/**\n * The response's media type, lowercased and without its parameters, or ''\n * when it names none.\n */\nfunction media_type(response: Response): string {\n const header = response.headers.get('content-type') ?? ''\n return (header.split(';')[0] ?? '').trim().toLowerCase()\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, (detail) => dropped_message(provider, detail))\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 * The error for a response that isn't the provider's protocol: what was\n * wrong with it, then what to check, since a body of the wrong shape most\n * often comes from a `base_url` that points somewhere else. `also` names the\n * other fix when there is one.\n */\nexport function protocol_error(provider: string, what: string, also?: string): provider_error {\n const other = also === undefined ? '' : `, or ${also}`\n return new provider_error(\n `${provider} native: ${what}: check that base_url points at the ${provider} API${other}`,\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. A streamed request whose reply doesn't arrive as the\n * dialect's stream media type (`text/event-stream`, or NDJSON for Ollama) is\n * read as a whole JSON body, so a server that answers with JSON still works,\n * and a page that isn't JSON fails with the `base_url` hint rather than as a\n * cut-off stream. `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. `req.on_wire`, when the call captures the wire, sees the\n * URL and the body object just before the body is serialized, and never a\n * header.\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 /** The media type that a streamed reply arrives as. */\n stream_media_type: string\n },\n): Promise<TurnResult> {\n const built = request.build_body()\n req.on_wire?.({ url: request.url, body: built })\n const body = JSON.stringify(built)\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, (detail) => unreachable_message(provider, request.url, detail))\n }\n if (!response.ok) throw await response_error(response, provider)\n if (req.stream && media_type(response) === consume.stream_media_type) {\n return consume.stream(response)\n }\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, (detail) => dropped_message(provider, detail))\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). An\n * opaque part belongs to the provider that sent it, and these formats carry\n * no such block, so it is skipped.\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 (part.type === 'reasoning' && 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 === 'system'\n}\n"],"mappings":";;AAyBA,IAAa,mBAAb,cAAsC,MAAM;CAC1C,OAAgB;CAEhB;CACA;CACA;CACA;CACA,YACE,SACA,WAA6F,CAAC,GAC9F;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,iBAAiB,SAAS;EAC/B,KAAK,WAAW,SAAS,YAAY;EACrC,KAAK,SAAS,SAAS;EACvB,KAAK,QAAQ,SAAS;CACxB;AACF;AAEA,IAAa,iBAAb,cAAoC,MAAM;CACxC,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA,YACE,SACA,WAMI,CAAC,GACL;EACA,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS,SAAS;EACvB,KAAK,OAAO,SAAS;EACrB,KAAK,aAAa,SAAS;EAC3B,KAAK,WAAW,SAAS;EACzB,KAAK,QAAQ,SAAS;CACxB;AACF;;;;;;;;;;;;AAaA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,OAAgB;CAEhB;CACA;CACA,YAAY,YAAoB,YAAqB;EACnD,MAAM,2CAA2C,WAAW,GAAG;EAC/D,KAAK,OAAO;EACZ,KAAK,aAAa;EAClB,KAAK,aAAa;CACpB;AACF;AAEA,IAAa,0BAAb,cAA6C,MAAM;CACjD,OAAgB;CAEhB;CACA;CACA,YAAY,SAAiB,eAA2C,UAAkB;EACxF,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,gBAAgB;EACrB,KAAK,WAAW;CAClB;AACF;AAEA,IAAa,aAAb,cAAgC,MAAM;CACpC,OAAgB;CAEhB;CACA;CACA;CACA,YACE,SACA,UACA;EAC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3B,aAAa,KAAK,YAAY,CAAC,CAAC;EAChC,WAAW;CACb;CACA,MAAM,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"}
@@ -1,7 +1,7 @@
1
- import { w as run } from "./core-Bfzt55Fl.js";
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-C4F4lXHE.js";
4
- //#region src/mcp/errors.ts
1
+ import { n as is_record, t as as_record } from "./records-Btlmvunj.js";
2
+ import { t as json_schema_to_standard } from "./json_schema_to_standard-BstoXjM8.js";
3
+ import { w as run } from "./core-BH7sWpEG.js";
4
+ // src/mcp/errors.ts
5
5
  /**
6
6
  * Typed errors for the MCP adapter.
7
7
  *
@@ -25,8 +25,7 @@ var mcp_error = class extends Error {
25
25
  this.tool_name = metadata.tool_name;
26
26
  }
27
27
  };
28
- //#endregion
29
- //#region src/mcp/result_mapping.ts
28
+ // src/mcp/result_mapping.ts
30
29
  /**
31
30
  * Mapping between MCP `CallToolResult` payloads and Fascicle tool values, in
32
31
  * both directions: inbound results from `mcp_client` tools, outbound results
@@ -104,8 +103,7 @@ function stringify(value) {
104
103
  return String(value);
105
104
  }
106
105
  }
107
- //#endregion
108
- //#region src/mcp/sdk_loader.ts
106
+ // src/mcp/sdk_loader.ts
109
107
  /**
110
108
  * Lazy loader for the optional `@modelcontextprotocol/sdk` peer.
111
109
  *
@@ -139,8 +137,7 @@ async function load_client_sdk() {
139
137
  throw new mcp_sdk_missing_error(`@modelcontextprotocol/sdk is required for fascicle/mcp; install it: pnpm add @modelcontextprotocol/sdk (cause: ${err instanceof Error ? err.message : String(err)})`);
140
138
  }
141
139
  }
142
- //#endregion
143
- //#region src/mcp/client.ts
140
+ // src/mcp/client.ts
144
141
  const DEFAULT_CLIENT_INFO = {
145
142
  name: "fascicle",
146
143
  version: "0.0.0"
@@ -228,8 +225,7 @@ function to_fascicle_tool(client, advertised, options) {
228
225
  }
229
226
  };
230
227
  }
231
- //#endregion
232
- //#region src/mcp/serve.ts
228
+ // src/mcp/serve.ts
233
229
  /**
234
230
  * Registers a Fascicle flow as a tool on a caller-owned MCP server.
235
231
  *
@@ -261,7 +257,6 @@ function serve_flow(config) {
261
257
  }
262
258
  });
263
259
  }
264
- //#endregion
265
260
  export { mcp_sdk_missing_error as i, mcp_client as n, mcp_error as r, serve_flow as t };
266
261
 
267
- //# sourceMappingURL=mcp-8mKK7eDY.js.map
262
+ //# sourceMappingURL=mcp-CHJ88HiG.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-8mKK7eDY.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 // Prepended, as written, to each surfaced tool's name, so two servers'\n // tools can share a call without colliding. The server is still called by\n // its own name, and `include` and `default_description` see that name too.\n name_prefix?: 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. Only the `Tool`'s name carries\n * `name_prefix`; the call, the fallback description, and the errors use the\n * server's own name.\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: `${options.name_prefix ?? ''}${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,IA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,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-CHJ88HiG.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 // Prepended, as written, to each surfaced tool's name, so two servers'\n // tools can share a call without colliding. The server is still called by\n // its own name, and `include` and `default_description` see that name too.\n name_prefix?: 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 return new sdk.StreamableHTTPClientTransport(new URL(config.url), opts)\n}\n\n/**\n * Wraps one advertised MCP tool as a Fascicle `Tool` whose `execute` forwards\n * to `callTool` on the shared client. Only the `Tool`'s name carries\n * `name_prefix`; the call, the fallback description, and the errors use the\n * server's own name.\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: `${options.name_prefix ?? ''}${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,OAAO,MAAM,CAAC;AACp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,MAAM,OAAO,WAAW;CACxB,MAAM,cACJ,WAAW,eAAe,QAAQ,sBAAsB,IAAI,KAAK,YAAY;CAC/E,OAAO;EACL,MAAM,GAAG,QAAQ,eAAe,KAAK;EACrC;EACA,cAAc,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;;;;;;;;;;AChIA,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"}
package/dist/mcp.d.ts CHANGED
@@ -1,10 +1,9 @@
1
- import { c as Step, h as TrajectoryLogger } from "./types-CPqLZOEr.js";
2
- import { r as ToolSchema } from "./types-BK0UW28o.js";
3
- import { M as Tool } from "./types-xYjCEd6i.js";
1
+ import { M as Tool } from "./types-Dk9tLpUq.js";
2
+ import { c as Step, h as TrajectoryLogger } from "./types-BUXt_zgJ.js";
3
+ import { r as ToolSchema } from "./types-CvghbZ0x.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";
7
- //#region src/schema/json_schema_to_standard.d.ts
8
7
  /**
9
8
  * Builds a `ToolSchema` over a JSON Schema, such as an MCP server's advertised
10
9
  * tool input.
@@ -17,8 +16,6 @@ import { z } from "zod";
17
16
  * nothing.
18
17
  */
19
18
  export declare function json_schema_to_standard(schema: unknown): ToolSchema;
20
- //#endregion
21
- //#region src/mcp/client.d.ts
22
19
  type McpStdioConfig = {
23
20
  transport: 'stdio';
24
21
  command: string;
@@ -63,8 +60,6 @@ type McpClientHandle = {
63
60
  * listing its tools fails.
64
61
  */
65
62
  export declare function mcp_client(config: McpClientConfig, options?: McpClientOptions): Promise<McpClientHandle>;
66
- //#endregion
67
- //#region src/mcp/serve.d.ts
68
63
  type ServeFlowConfig<i, o> = {
69
64
  server: McpServer;
70
65
  flow: Step<i, o>;
@@ -93,8 +88,6 @@ type ServeFlowConfig<i, o> = {
93
88
  * than a JSON-RPC protocol error.
94
89
  */
95
90
  export declare function serve_flow<i, o>(config: ServeFlowConfig<i, o>): void;
96
- //#endregion
97
- //#region src/mcp/errors.d.ts
98
91
  /**
99
92
  * Typed errors for the MCP adapter.
100
93
  *
@@ -113,6 +106,5 @@ export declare class mcp_error extends Error {
113
106
  tool_name?: string;
114
107
  });
115
108
  }
116
- //#endregion
117
109
  export type { McpClientConfig, McpClientHandle, McpClientOptions, McpExistingClientConfig, McpStdioConfig, McpStreamableHttpConfig, ServeFlowConfig };
118
110
  //# sourceMappingURL=mcp.d.ts.map
package/dist/mcp.js CHANGED
@@ -1,3 +1,3 @@
1
- import { t as json_schema_to_standard } from "./json_schema_to_standard-C4F4lXHE.js";
2
- import { i as mcp_sdk_missing_error, n as mcp_client, r as mcp_error, t as serve_flow } from "./mcp-8mKK7eDY.js";
1
+ import { t as json_schema_to_standard } from "./json_schema_to_standard-BstoXjM8.js";
2
+ import { i as mcp_sdk_missing_error, n as mcp_client, r as mcp_error, t as serve_flow } from "./mcp-CHJ88HiG.js";
3
3
  export { json_schema_to_standard, mcp_client, mcp_error, mcp_sdk_missing_error, serve_flow };
package/dist/otel.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { h as TrajectoryLogger } from "./types-CPqLZOEr.js";
1
+ import { h as TrajectoryLogger } from "./types-BUXt_zgJ.js";
2
2
  import { Meter, Tracer } from "@opentelemetry/api";
3
- //#region src/otel/metrics.d.ts
4
3
  type OtelMetricsOptions = {
5
4
  /**
6
5
  * Meter to create instruments on. Defaults to
@@ -9,8 +8,6 @@ type OtelMetricsOptions = {
9
8
  */
10
9
  readonly meter?: Meter;
11
10
  };
12
- //#endregion
13
- //#region src/otel/trajectory_logger.d.ts
14
11
  type OtelTrajectoryLoggerOptions = {
15
12
  /**
16
13
  * Tracer to open spans on. Defaults to `trace.getTracer('fascicle')`, which
@@ -39,6 +36,5 @@ type OtelTrajectoryLoggerOptions = {
39
36
  * otherwise it falls back to the currently open span on an internal stack.
40
37
  */
41
38
  export declare function create_otel_trajectory_logger(options?: OtelTrajectoryLoggerOptions): TrajectoryLogger;
42
- //#endregion
43
39
  export type { OtelMetricsOptions, OtelTrajectoryLoggerOptions };
44
40
  //# sourceMappingURL=otel.d.ts.map
package/dist/otel.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { SpanStatusCode, context, metrics, trace } from "@opentelemetry/api";
2
- //#region src/otel/metrics.ts
2
+ // src/otel/metrics.ts
3
3
  /**
4
4
  * Opt-in OpenTelemetry metrics derived from the trajectory stream.
5
5
  *
@@ -203,8 +203,7 @@ function create_metrics_recorder(options) {
203
203
  }
204
204
  };
205
205
  }
206
- //#endregion
207
- //#region src/otel/trajectory_logger.ts
206
+ // src/otel/trajectory_logger.ts
208
207
  /**
209
208
  * OpenTelemetry bridge for Fascicle trajectory events.
210
209
  *
@@ -255,8 +254,7 @@ function safe_json(value) {
255
254
  */
256
255
  function to_attribute_value(value) {
257
256
  if (value === null || value === void 0) return void 0;
258
- const kind = typeof value;
259
- if (kind === "string" || kind === "number" || kind === "boolean") return value;
257
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
260
258
  if (Array.isArray(value)) {
261
259
  if (value.every((v) => typeof v === "string")) return value;
262
260
  if (value.every((v) => typeof v === "number")) return value;
@@ -411,7 +409,6 @@ function create_otel_trajectory_logger(options = {}) {
411
409
  }
412
410
  };
413
411
  }
414
- //#endregion
415
412
  export { create_otel_trajectory_logger };
416
413
 
417
414
  //# sourceMappingURL=otel.js.map