@jaypie/llm 1.3.15 → 1.3.16
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.
- package/dist/cjs/constants.d.ts +56 -1
- package/dist/cjs/index.cjs +180 -5
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +61 -4
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/operate/adapters/BedrockAdapter.d.ts +2 -0
- package/dist/esm/constants.d.ts +56 -1
- package/dist/esm/index.d.ts +61 -4
- package/dist/esm/index.js +180 -5
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/operate/adapters/BedrockAdapter.d.ts +2 -0
- package/package.json +1 -1
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/constants.ts","../../../src/util/determineModelProvider.ts","../../../src/util/resolveModelChain.ts","../../../src/operate/exchange/buildExchangeEnvelope.ts","../../../src/util/cacheControl.ts","../../../src/util/extractReasoning.ts","../../../src/util/naturalZodSchema.ts","../../../src/util/fillFormatArrays.ts","../../../src/types/LlmProvider.interface.ts","../../../src/util/formatOperateMessage.ts","../../../src/util/formatOperateInput.ts","../../../src/util/jsonSchema.ts","../../../src/util/jsonSchemaToOpenApi3.ts","../../../src/util/logger.ts","../../../src/util/maxOutputTokens.ts","../../../src/util/maxTurnsFromOptions.ts","../../../src/util/random.ts","../../../src/util/repairFormatKeys.ts","../../../src/util/sse.ts","../../../src/util/tallyOperate.ts","../../../src/util/tryParseNumber.ts","../../../src/operate/exchange/emitExchange.ts","../../../src/observability/exchangeStore.ts","../../../src/operate/adapters/ProviderAdapter.interface.ts","../../../src/util/effort.ts","../../../src/types/LlmStreamChunk.interface.ts","../../../src/operate/types.ts","../../../src/operate/retry/isTransientNetworkError.ts","../../../src/util/classifyProviderError.ts","../../../src/operate/adapters/AnthropicAdapter.ts","../../../src/operate/adapters/BedrockAdapter.ts","../../../src/operate/adapters/FireworksAdapter.ts","../../../src/operate/adapters/GoogleAdapter.ts","../../../src/providers/openai/client.ts","../../../src/providers/openai/responseFormat.ts","../../../src/operate/adapters/OpenAiAdapter.ts","../../../src/operate/adapters/OpenRouterAdapter.ts","../../../src/operate/adapters/XaiAdapter.ts","../../../src/tools/Toolkit.class.ts","../../../src/observability/llmobs.ts","../../../src/operate/hooks/HookRunner.ts","../../../src/types/LlmOperateInput.guards.ts","../../../src/upload/detectMimeType.ts","../../../src/upload/extractPdfPages.ts","../../../src/upload/loadLocalFile.ts","../../../src/upload/loadS3File.ts","../../../src/upload/resolveOperateInput.ts","../../../src/operate/input/InputProcessor.ts","../../../src/operate/progress/emitProgress.ts","../../../src/operate/response/ResponseBuilder.ts","../../../src/operate/retry/RetryPolicy.ts","../../../src/operate/retry/createStaleRejectionGuard.ts","../../../src/errors/LlmError.ts","../../../src/errors/toLlmError.ts","../../../src/operate/retry/RetryExecutor.ts","../../../src/operate/OperateLoop.ts","../../../src/operate/StreamLoop.ts","../../../src/providers/anthropic/client.ts","../../../src/providers/anthropic/utils.ts","../../../src/providers/anthropic/types.ts","../../../src/providers/anthropic/AnthropicProvider.class.ts","../../../src/providers/bedrock/utils.ts","../../../src/providers/bedrock/BedrockProvider.class.ts","../../../src/providers/fireworks/client.ts","../../../src/providers/fireworks/utils.ts","../../../src/providers/fireworks/FireworksProvider.class.ts","../../../src/providers/google/client.ts","../../../src/providers/google/utils.ts","../../../src/providers/google/GoogleProvider.class.ts","../../../src/providers/openai/utils.ts","../../../src/providers/openai/OpenAiProvider.class.ts","../../../src/providers/openrouter/client.ts","../../../src/providers/openrouter/utils.ts","../../../src/providers/openrouter/OpenRouterProvider.class.ts","../../../src/providers/xai/utils.ts","../../../src/providers/xai/XaiProvider.class.ts","../../../src/Llm.ts","../../../src/tools/random.ts","../../../src/tools/roll.ts","../../../src/tools/time.ts","../../../src/tools/weather.ts","../../../src/tools/index.ts","../../../src/providers/google/types.ts"],"sourcesContent":["/**\n * Provider-neutral reasoning-effort levels — a five-point relative scale that\n * deliberately borrows no provider's vocabulary. Each adapter translates these\n * to its provider's native control (OpenAI `reasoning.effort`, Anthropic\n * `output_config.effort`, Gemini `thinkingLevel`/`thinkingBudget`, Grok\n * `reasoning_effort`, OpenRouter `reasoning.effort`), spreading the scale across\n * the provider's available range. Omitting `effort` leaves the provider default\n * untouched, so it is safe to set across a fallback chain.\n */\nexport const EFFORT = {\n LOWEST: \"lowest\",\n LOW: \"low\",\n MEDIUM: \"medium\",\n HIGH: \"high\",\n HIGHEST: \"highest\",\n} as const;\n\nexport type LlmEffort = (typeof EFFORT)[keyof typeof EFFORT];\n\nexport const MODEL = {\n // Anthropic\n FABLE: \"claude-fable-5\",\n OPUS: \"claude-opus-4-8\",\n SONNET: \"claude-sonnet-5\",\n HAIKU: \"claude-haiku-4-5\",\n MYTHOS: \"claude-mythos-5\",\n // Fireworks (serverless open models; ids provided by operator)\n FIREWORKS: {\n DEEPSEEK: \"accounts/fireworks/models/deepseek-v4-pro\",\n GLM: \"accounts/fireworks/models/glm-5p2\",\n KIMI: \"accounts/fireworks/models/kimi-k2p7-code\",\n MINIMAX: \"accounts/fireworks/models/minimax-m2p7\",\n QWEN: \"accounts/fireworks/models/qwen3p7-plus\",\n },\n // Google\n GEMINI_FLASH: \"gemini-3.5-flash\",\n GEMINI_FLASH_LITE: \"gemini-3.1-flash-lite\",\n GEMINI_PRO: \"gemini-3.1-pro-preview\",\n // OpenAI\n SOL: \"gpt-5.6-sol\",\n TERRA: \"gpt-5.6-terra\",\n LUNA: \"gpt-5.6-luna\",\n /** @deprecated use MODEL.SOL (gpt-5.6-sol) */\n GPT: \"gpt-5.5\",\n /** @deprecated use MODEL.TERRA (gpt-5.6-terra) */\n GPT_MINI: \"gpt-5.4-mini\",\n /** @deprecated use MODEL.LUNA (gpt-5.6-luna) */\n GPT_NANO: \"gpt-5.4-nano\",\n // xAI\n GROK: \"grok-latest\",\n // OpenRouter (provider-prefixed routes; traversed by the OpenRouter hot test)\n OPENROUTER: {\n GLM: \"z-ai/glm-5.2\",\n LUNA: \"openai/gpt-5.6-luna\",\n SONNET: \"anthropic/claude-sonnet-5\",\n },\n};\n\nconst GOOGLE_PROVIDER = {\n // https://ai.google.dev/gemini-api/docs/models\n DEFAULT: MODEL.GEMINI_FLASH,\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.GOOGLE.DEFAULT, or pick a specific model from MODEL.*. */\n MODEL: {\n DEFAULT: \"gemini-3.1-pro-preview\",\n LARGE: \"gemini-3.1-pro-preview\",\n SMALL: \"gemini-3.5-flash\",\n TINY: \"gemini-3.1-flash-lite\",\n },\n MODEL_MATCH_WORDS: [\"gemini\", \"google\"] as const,\n NAME: \"google\" as const,\n ROLE: {\n MODEL: \"model\" as const,\n USER: \"user\" as const,\n },\n} as const;\n\nexport const PROVIDER = {\n // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html\n BEDROCK: {\n // Bedrock has no MODEL.* catalog entry yet; keep the literal default id.\n // nova-pro is the Amazon-native model that reliably does tools+structured.\n DEFAULT: \"amazon.nova-pro-v1:0\" as const,\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.BEDROCK.DEFAULT. */\n MODEL: {\n DEFAULT: \"amazon.nova-lite-v1:0\" as const,\n LARGE: \"amazon.nova-pro-v1:0\" as const,\n SMALL: \"amazon.nova-lite-v1:0\" as const,\n TINY: \"amazon.nova-micro-v1:0\" as const,\n },\n MODEL_MATCH_WORDS: [\n \"amazon.nova\",\n \"amazon.titan\",\n \"anthropic.claude\",\n \"cohere.command\",\n \"meta.llama\",\n \"mistral.mistral\",\n \"ai21.\",\n ] as const,\n NAME: \"bedrock\" as const,\n REGION: \"AWS_REGION\" as const,\n },\n ANTHROPIC: {\n // https://docs.anthropic.com/en/docs/about-claude/models/overview\n DEFAULT: MODEL.SONNET,\n MAX_TOKENS: {\n // Non-streaming ceiling: responses above ~16K output tokens risk HTTP\n // timeouts; streaming requests resolve to the model maximum instead\n // (see util/maxOutputTokens.ts)\n DEFAULT: 16384 as const,\n },\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.ANTHROPIC.DEFAULT, or pick a specific model from MODEL.*. */\n MODEL: {\n DEFAULT: \"claude-sonnet-4-6\",\n LARGE: \"claude-opus-4-8\",\n SMALL: \"claude-sonnet-4-6\",\n TINY: \"claude-haiku-4-5\",\n },\n MODEL_MATCH_WORDS: [\n \"anthropic\",\n \"claude\",\n \"fable\",\n \"haiku\",\n \"mythos\",\n \"opus\",\n \"sonnet\",\n ] as const,\n NAME: \"anthropic\" as const,\n PROMPT: {\n AI: \"\\n\\nAssistant:\" as const,\n HUMAN: \"\\n\\nHuman:\" as const,\n },\n ROLE: {\n ASSISTANT: \"assistant\" as const,\n SYSTEM: \"system\" as const,\n USER: \"user\" as const,\n },\n TOOLS: {\n SCHEMA_VERSION: \"v2\" as const,\n },\n },\n FIREWORKS: {\n // https://docs.fireworks.ai/\n API_KEY: \"FIREWORKS_API_KEY\" as const,\n BASE_URL: \"https://api.fireworks.ai/inference/v1\" as const,\n DEFAULT: MODEL.FIREWORKS.GLM,\n MODEL_MATCH_WORDS: [\"fireworks\"] as const,\n NAME: \"fireworks\" as const,\n },\n /** @deprecated Use PROVIDER.GOOGLE — \"Google\" is the provider; Gemini is the model family */\n GEMINI: GOOGLE_PROVIDER,\n GOOGLE: GOOGLE_PROVIDER,\n OPENAI: {\n // https://platform.openai.com/docs/models\n DEFAULT: MODEL.SOL,\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.OPENAI.DEFAULT, or pick a specific model from MODEL.*. */\n MODEL: {\n DEFAULT: \"gpt-5.4\",\n LARGE: \"gpt-5.5\",\n SMALL: \"gpt-5.4-mini\",\n TINY: \"gpt-5.4-nano\",\n },\n MODEL_MATCH_WORDS: [\"gpt\", \"luna\", \"openai\", \"sol\", \"terra\", /^o\\d/],\n NAME: \"openai\" as const,\n },\n OPENROUTER: {\n DEFAULT: MODEL.OPENROUTER.SONNET,\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.OPENROUTER.DEFAULT, or pick a specific route from MODEL.OPENROUTER.*. */\n MODEL: {\n DEFAULT: \"anthropic/claude-sonnet-4-6\" as const,\n LARGE: \"anthropic/claude-opus-4-8\" as const,\n SMALL: \"anthropic/claude-sonnet-4-6\" as const,\n TINY: \"anthropic/claude-haiku-4-5\" as const,\n },\n MODEL_MATCH_WORDS: [\"openrouter\"] as const,\n NAME: \"openrouter\" as const,\n ROLE: {\n ASSISTANT: \"assistant\" as const,\n SYSTEM: \"system\" as const,\n TOOL: \"tool\" as const,\n USER: \"user\" as const,\n },\n },\n XAI: {\n // https://docs.x.ai/docs/models\n API_KEY: \"XAI_API_KEY\" as const,\n BASE_URL: \"https://api.x.ai/v1\" as const,\n DEFAULT: MODEL.GROK,\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.XAI.DEFAULT, or pick a specific model from MODEL.*. */\n MODEL: {\n DEFAULT: \"grok-latest\",\n LARGE: \"grok-latest\",\n SMALL: \"grok-4-1-fast-reasoning\",\n TINY: \"grok-4-1-fast-non-reasoning\",\n },\n MODEL_MATCH_WORDS: [\"grok\", \"xai\"] as const,\n NAME: \"xai\" as const,\n },\n} as const;\n\nexport type LlmProviderName =\n | typeof PROVIDER.ANTHROPIC.NAME\n | typeof PROVIDER.BEDROCK.NAME\n | typeof PROVIDER.FIREWORKS.NAME\n | typeof PROVIDER.GOOGLE.NAME\n | typeof PROVIDER.OPENAI.NAME\n | typeof PROVIDER.OPENROUTER.NAME\n | typeof PROVIDER.XAI.NAME;\n\n// Last: Defaults\nexport const DEFAULT = {\n /** @deprecated Size tiers are retired in 2.0. Use DEFAULT.PROVIDER.DEFAULT, or pick a specific model from MODEL.*. */\n MODEL: {\n BASE: PROVIDER.OPENAI.MODEL.DEFAULT,\n LARGE: PROVIDER.OPENAI.MODEL.LARGE,\n SMALL: PROVIDER.OPENAI.MODEL.SMALL,\n TINY: PROVIDER.OPENAI.MODEL.TINY,\n },\n PROVIDER: PROVIDER.OPENAI,\n} as const;\n\n/**\n * @deprecated Size-tier catalogs are retired in 2.0. Pick specific models from\n * MODEL.* (grouped by provider via MODEL_MATCH_WORDS / determineModelProvider).\n */\n// Only include \"first class\" models, not OpenRouter or other proxy services\nexport const ALL = {\n BASE: [\n PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n PROVIDER.GOOGLE.MODEL.DEFAULT,\n PROVIDER.OPENAI.MODEL.DEFAULT,\n PROVIDER.XAI.MODEL.DEFAULT,\n ],\n COMBINED: [\n ...new Set([\n PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n PROVIDER.ANTHROPIC.MODEL.LARGE,\n PROVIDER.ANTHROPIC.MODEL.SMALL,\n PROVIDER.ANTHROPIC.MODEL.TINY,\n PROVIDER.GOOGLE.MODEL.DEFAULT,\n PROVIDER.GOOGLE.MODEL.LARGE,\n PROVIDER.GOOGLE.MODEL.SMALL,\n PROVIDER.GOOGLE.MODEL.TINY,\n PROVIDER.OPENAI.MODEL.DEFAULT,\n PROVIDER.OPENAI.MODEL.LARGE,\n PROVIDER.OPENAI.MODEL.SMALL,\n PROVIDER.OPENAI.MODEL.TINY,\n PROVIDER.XAI.MODEL.DEFAULT,\n PROVIDER.XAI.MODEL.LARGE,\n PROVIDER.XAI.MODEL.SMALL,\n PROVIDER.XAI.MODEL.TINY,\n ]),\n ],\n LARGE: [\n PROVIDER.ANTHROPIC.MODEL.LARGE,\n PROVIDER.GOOGLE.MODEL.LARGE,\n PROVIDER.OPENAI.MODEL.LARGE,\n PROVIDER.XAI.MODEL.LARGE,\n ],\n SMALL: [\n PROVIDER.ANTHROPIC.MODEL.SMALL,\n PROVIDER.GOOGLE.MODEL.SMALL,\n PROVIDER.OPENAI.MODEL.SMALL,\n PROVIDER.XAI.MODEL.SMALL,\n ],\n TINY: [\n PROVIDER.ANTHROPIC.MODEL.TINY,\n PROVIDER.GOOGLE.MODEL.TINY,\n PROVIDER.OPENAI.MODEL.TINY,\n PROVIDER.XAI.MODEL.TINY,\n ],\n} as const;\n","import { DEFAULT, PROVIDER } from \"../constants\";\n\nexport function determineModelProvider(input?: string): {\n model: string;\n provider?: string;\n} {\n if (!input) {\n return {\n model: DEFAULT.PROVIDER.DEFAULT,\n provider: DEFAULT.PROVIDER.NAME,\n };\n }\n\n // Check for explicit openrouter: prefix\n if (input.startsWith(\"openrouter:\")) {\n const model = input.slice(\"openrouter:\".length);\n return {\n model,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n\n // Check for explicit fireworks: prefix\n if (input.startsWith(\"fireworks:\")) {\n const model = input.slice(\"fireworks:\".length);\n return {\n model,\n provider: PROVIDER.FIREWORKS.NAME,\n };\n }\n\n // Check for explicit bedrock: prefix\n if (input.startsWith(\"bedrock:\")) {\n const model = input.slice(\"bedrock:\".length);\n return {\n model,\n provider: PROVIDER.BEDROCK.NAME,\n };\n }\n\n // Check if input is a provider name\n if (input === PROVIDER.BEDROCK.NAME) {\n return {\n model: PROVIDER.BEDROCK.DEFAULT,\n provider: PROVIDER.BEDROCK.NAME,\n };\n }\n if (input === PROVIDER.FIREWORKS.NAME) {\n return {\n model: PROVIDER.FIREWORKS.DEFAULT,\n provider: PROVIDER.FIREWORKS.NAME,\n };\n }\n if (input === PROVIDER.ANTHROPIC.NAME) {\n return {\n model: PROVIDER.ANTHROPIC.DEFAULT,\n provider: PROVIDER.ANTHROPIC.NAME,\n };\n }\n if (input === PROVIDER.GOOGLE.NAME || input === \"gemini\") {\n return {\n model: PROVIDER.GOOGLE.DEFAULT,\n provider: PROVIDER.GOOGLE.NAME,\n };\n }\n if (input === PROVIDER.OPENAI.NAME) {\n return {\n model: PROVIDER.OPENAI.DEFAULT,\n provider: PROVIDER.OPENAI.NAME,\n };\n }\n if (input === PROVIDER.OPENROUTER.NAME) {\n return {\n model: PROVIDER.OPENROUTER.DEFAULT,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n if (input === PROVIDER.XAI.NAME) {\n return {\n model: PROVIDER.XAI.DEFAULT,\n provider: PROVIDER.XAI.NAME,\n };\n }\n\n // Exact model ids are classified by the \"/\" rule and MODEL_MATCH_WORDS below,\n // so no per-provider id catalog is consulted here.\n\n // Check Fireworks match words before the \"/\" rule — Fireworks ids contain\n // \"/\" (e.g., \"accounts/fireworks/models/glm-5p2\") and would otherwise route\n // to OpenRouter\n const lowerInputEarly = input.toLowerCase();\n for (const matchWord of PROVIDER.FIREWORKS.MODEL_MATCH_WORDS) {\n if (lowerInputEarly.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.FIREWORKS.NAME,\n };\n }\n }\n\n // Assume OpenRouter for models containing \"/\" (e.g., \"openai/gpt-4\", \"anthropic/claude-3-opus\")\n // This check must come before match words so that \"openai/gpt-4\" is not matched by \"openai\" keyword\n if (input.includes(\"/\")) {\n return {\n model: input,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n\n // Check Bedrock match words (before Anthropic — \"anthropic.claude-*\" is a Bedrock model ID)\n const lowerInput = input.toLowerCase();\n for (const matchWord of PROVIDER.BEDROCK.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.BEDROCK.NAME,\n };\n }\n }\n\n // Check Anthropic match words\n for (const matchWord of PROVIDER.ANTHROPIC.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.ANTHROPIC.NAME,\n };\n }\n }\n\n // Check Gemini match words\n for (const matchWord of PROVIDER.GOOGLE.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.GOOGLE.NAME,\n };\n }\n }\n\n // Check OpenAI match words\n for (const matchWord of PROVIDER.OPENAI.MODEL_MATCH_WORDS) {\n if (typeof matchWord === \"string\") {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.OPENAI.NAME,\n };\n }\n } else if (matchWord instanceof RegExp) {\n if (matchWord.test(input)) {\n return {\n model: input,\n provider: PROVIDER.OPENAI.NAME,\n };\n }\n }\n }\n\n // Check xAI match words\n for (const matchWord of PROVIDER.XAI.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.XAI.NAME,\n };\n }\n }\n\n // Check OpenRouter match words\n for (const matchWord of PROVIDER.OPENROUTER.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n }\n\n // Default fallback if model not recognized\n return {\n model: input,\n };\n}\n","import { ConfigurationError } from \"@jaypie/errors\";\nimport { LlmFallbackConfig } from \"../types/LlmProvider.interface.js\";\nimport { determineModelProvider } from \"./determineModelProvider.js\";\n\n/**\n * Normalizes a `model` option that may be a single model name or a\n * preference-ordered array of model names.\n *\n * A `string[]` is interpreted as a fallback chain: index `0` is the primary\n * model, indices `1..` become fallback entries with an auto-detected provider\n * (reusing `determineModelProvider`, exactly as the constructor's first\n * argument does).\n *\n * Returns the primary model plus the derived fallback chain. A bare string\n * yields an empty chain and is unchanged.\n */\nexport function resolveModelChain(model?: string | string[]): {\n model?: string;\n fallback: LlmFallbackConfig[];\n} {\n if (!Array.isArray(model)) {\n return { fallback: [], model };\n }\n\n if (model.length === 0) {\n throw new ConfigurationError(\n \"model array must contain at least one model name\",\n );\n }\n\n const [primary, ...rest] = model;\n const fallback = rest.map((name) => {\n const determined = determineModelProvider(name);\n if (!determined.provider) {\n throw new ConfigurationError(\n `Unable to determine provider from model: ${name}`,\n );\n }\n return { model: determined.model, provider: determined.provider };\n });\n\n return { fallback, model: primary };\n}\n","import {\n LlmExchangeEnvelope,\n LlmHistory,\n LlmInputMessage,\n LlmOperateInput,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { OperateLoopState } from \"../types.js\";\n\n//\n//\n// Helpers\n//\n\nfunction sumUsageByProviderModel(\n usage: LlmUsageItem[],\n): Record<string, LlmUsageItem> | undefined {\n if (!usage.length) {\n return undefined;\n }\n const totals: Record<string, LlmUsageItem> = {};\n for (const item of usage) {\n const key = `${item.provider ?? \"unknown\"}:${item.model ?? \"unknown\"}`;\n if (!totals[key]) {\n totals[key] = {\n input: 0,\n model: item.model,\n output: 0,\n provider: item.provider,\n reasoning: 0,\n total: 0,\n };\n }\n totals[key].input += item.input;\n totals[key].output += item.output;\n totals[key].reasoning += item.reasoning;\n totals[key].total += item.total;\n if (item.cacheRead !== undefined) {\n totals[key].cacheRead = (totals[key].cacheRead ?? 0) + item.cacheRead;\n }\n if (item.cacheWrite !== undefined) {\n totals[key].cacheWrite = (totals[key].cacheWrite ?? 0) + item.cacheWrite;\n }\n }\n return totals;\n}\n\nfunction extractResponseIds(responses: unknown[]): string[] | undefined {\n const ids = responses\n .map((response) =>\n response && typeof response === \"object\"\n ? (response as { id?: unknown }).id\n : undefined,\n )\n .filter((id): id is string => typeof id === \"string\");\n return ids.length ? ids : undefined;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Assemble the serializable exchange envelope for one operate() settlement.\n * The `resolution` block is stamped by the Llm facade, which is the layer\n * that knows fallback outcome; the loop fills provider/model best-effort.\n */\nexport function buildExchangeEnvelope({\n duration,\n initialHistoryLength,\n input,\n options,\n response,\n startedAt,\n state,\n}: {\n duration: number;\n initialHistoryLength: number;\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput;\n options: LlmOperateOptions;\n response: LlmOperateResponse;\n startedAt: string;\n state: OperateLoopState;\n}): LlmExchangeEnvelope {\n const historyDelta = response.history.slice(initialHistoryLength);\n return {\n ids: extractResponseIds(response.responses),\n request: {\n cache: options.cache,\n data: options.data,\n effort: options.effort,\n explain: options.explain,\n format: state.formattedFormat,\n input,\n instructions: options.instructions,\n model: options.model,\n placeholders: options.placeholders,\n providerOptions: options.providerOptions,\n system: options.system,\n temperature: options.temperature,\n tools: state.formattedTools?.map(({ name }) => name),\n turns: options.turns,\n user: options.user,\n },\n resolution: {\n model: response.model,\n provider: response.provider,\n retries: state.retries,\n },\n response: {\n content: response.content,\n error: response.error,\n historyDelta,\n reasoning: response.reasoning,\n status: response.status,\n stopReason: state.lastStopReason,\n usage: response.usage,\n usageTotals: sumUsageByProviderModel(response.usage),\n },\n timing: {\n duration,\n startedAt,\n },\n };\n}\n","import { type LlmCache } from \"../types/LlmProvider.interface.js\";\n\nexport const CACHE_TTL_DEFAULT = \"5m\" as const;\n\nexport type CacheTtl = \"5m\" | \"1h\";\n\nexport interface ResolvedCache {\n enabled: boolean;\n ttl: CacheTtl;\n}\n\n/**\n * Normalize the caller-facing `cache` option into a concrete decision.\n * - `undefined` / `true` → enabled at the default TTL\n * - `false` / `0` → disabled\n * - `\"5m\"` / `\"1h\"` → enabled at that TTL\n */\nexport function resolveCache(cache: LlmCache | undefined): ResolvedCache {\n if (cache === false || cache === 0) {\n return { enabled: false, ttl: CACHE_TTL_DEFAULT };\n }\n if (cache === \"5m\" || cache === \"1h\") {\n return { enabled: true, ttl: cache };\n }\n // undefined or true\n return { enabled: true, ttl: CACHE_TTL_DEFAULT };\n}\n\n/**\n * Deterministic short key for providers with automatic, prefix-based caching\n * (e.g. OpenAI `prompt_cache_key`). Derived from the stable prefix so the same\n * system prompt + tools + model always routes to the same cache. Dependency-\n * free FNV-1a; not cryptographic.\n */\nexport function promptCacheKey(seed: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < seed.length; i += 1) {\n hash ^= seed.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return `jaypie-${(hash >>> 0).toString(16)}`;\n}\n","import { LlmHistory } from \"../types/LlmProvider.interface.js\";\n\n/**\n * Represents a reasoning item with optional summary array (OpenAI format).\n * This type is used internally for type-safe access to reasoning-specific properties.\n */\ninterface ReasoningItem {\n content?: string;\n id?: string;\n summary?: Array<{ text?: string }>;\n type: \"reasoning\";\n}\n\n/**\n * Represents a thinking item (Anthropic format).\n * Anthropic extended thinking uses `thinking` blocks with type \"thinking\".\n */\ninterface ThinkingItem {\n thinking?: string;\n type: \"thinking\";\n}\n\n/**\n * Represents a message item that may contain a reasoning property.\n * Used by some providers like OpenRouter/z-ai that include reasoning as a message property.\n */\ninterface MessageWithReasoning {\n reasoning?: string;\n role?: string;\n type?: string;\n}\n\n/**\n * Type guard to check if an item is a dedicated reasoning item (OpenAI)\n */\nfunction isReasoningItem(item: unknown): item is ReasoningItem {\n return (\n typeof item === \"object\" &&\n item !== null &&\n (item as { type?: string }).type === \"reasoning\"\n );\n}\n\n/**\n * Type guard to check if an item is a thinking item (Anthropic)\n */\nfunction isThinkingItem(item: unknown): item is ThinkingItem {\n return (\n typeof item === \"object\" &&\n item !== null &&\n (item as { type?: string }).type === \"thinking\" &&\n typeof (item as ThinkingItem).thinking === \"string\"\n );\n}\n\n/**\n * Type guard to check if an item has a reasoning property\n */\nfunction hasReasoningProperty(item: unknown): item is MessageWithReasoning {\n return (\n typeof item === \"object\" &&\n item !== null &&\n typeof (item as MessageWithReasoning).reasoning === \"string\" &&\n (item as MessageWithReasoning).reasoning !== \"\"\n );\n}\n\n/**\n * Extracts reasoning text from LLM history items.\n *\n * Reasoning items may have text in different locations depending on the provider:\n * - OpenAI: `summary` array with objects containing `text` property (type: \"reasoning\")\n * - OpenAI: `content` property on reasoning items (type: \"reasoning\")\n * - Anthropic: `thinking` property on thinking items (type: \"thinking\")\n * - OpenRouter/z-ai: `reasoning` property on message items\n *\n * @param history - The LLM history array to extract reasoning from\n * @returns Array of reasoning text strings\n */\nexport function extractReasoning(history: LlmHistory): string[] {\n const reasoningTexts: string[] = [];\n\n for (const item of history) {\n // Cast to unknown first for type checking\n const entry = item as unknown;\n\n // Handle dedicated reasoning items (OpenAI extended thinking)\n if (isReasoningItem(entry)) {\n // Handle summary array format\n if (Array.isArray(entry.summary)) {\n for (const summaryItem of entry.summary) {\n if (summaryItem?.text && typeof summaryItem.text === \"string\") {\n reasoningTexts.push(summaryItem.text);\n }\n }\n }\n\n // Handle direct content format\n if (entry.content && typeof entry.content === \"string\") {\n reasoningTexts.push(entry.content);\n }\n }\n\n // Handle thinking items (Anthropic extended thinking)\n if (isThinkingItem(entry)) {\n reasoningTexts.push(entry.thinking!);\n }\n\n // Handle reasoning property on message items (OpenRouter/z-ai format)\n if (hasReasoningProperty(entry)) {\n reasoningTexts.push(entry.reasoning!);\n }\n }\n\n return reasoningTexts;\n}\n","import { z } from \"zod/v4\";\nimport { NaturalSchema } from \"@jaypie/types\";\n\nexport function naturalZodSchema(definition: NaturalSchema): z.ZodTypeAny {\n if (Array.isArray(definition)) {\n if (definition.length === 0) {\n // Handle empty array - accept any[]\n return z.array(z.any());\n } else if (definition.length === 1) {\n // Handle array types\n const itemType = definition[0];\n switch (itemType) {\n case String:\n return z.array(z.string());\n case Number:\n return z.array(z.number());\n case Boolean:\n return z.array(z.boolean());\n default:\n if (typeof itemType === \"object\") {\n // Handle array of objects\n return z.array(naturalZodSchema(itemType));\n }\n // Handle enum arrays\n return z.enum(definition as [string, ...string[]]);\n }\n } else {\n // Handle enum arrays\n return z.enum(definition as [string, ...string[]]);\n }\n } else if (definition && typeof definition === \"object\") {\n if (Object.keys(definition).length === 0) {\n // Handle empty object - accept any key-value pairs\n return z.record(z.string(), z.any());\n } else {\n // Handle object with properties\n const schemaShape: Record<string, z.ZodTypeAny> = {};\n for (const [key, value] of Object.entries(definition)) {\n schemaShape[key] = naturalZodSchema(value);\n }\n return z.object(schemaShape);\n }\n } else {\n switch (definition) {\n case String:\n return z.string();\n case Number:\n return z.number();\n case Boolean:\n return z.boolean();\n case Object:\n return z.record(z.string(), z.any());\n case Array:\n return z.array(z.any());\n default:\n throw new Error(`Unsupported type: ${definition}`);\n }\n }\n}\n","import { z } from \"zod/v4\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\n\nimport { naturalZodSchema } from \"./naturalZodSchema.js\";\n\n//\n//\n// Types\n//\n\ntype Format = JsonObject | NaturalSchema | z.ZodType;\n\n//\n//\n// Helpers\n//\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Convert a `format` declaration (Zod schema, NaturalSchema, or a JSON Schema\n * JsonObject) into a plain JSON Schema we can walk. Mirrors the conversion the\n * provider adapters perform in `formatOutputSchema`, but without any\n * provider-specific sanitization.\n */\nfunction formatToJsonSchema(format: Format): JsonObject | undefined {\n if (format instanceof z.ZodType) {\n return z.toJSONSchema(format) as JsonObject;\n }\n if (isPlainObject(format) && (format as JsonObject).type === \"json_schema\") {\n const clone = structuredClone(format) as JsonObject;\n clone.type = \"object\";\n return clone;\n }\n try {\n return z.toJSONSchema(\n naturalZodSchema(format as NaturalSchema),\n ) as JsonObject;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Walk a JSON Schema alongside a parsed value, filling any declared array field\n * that is absent (`undefined`/`null`) with `[]`. Recurses into object\n * properties and array items so nested declared arrays are also backfilled.\n */\nfunction fillFromSchema(schema: unknown, value: unknown): unknown {\n if (!isPlainObject(schema)) {\n return value;\n }\n\n const type = schema.type;\n const isArray = type === \"array\" || (type === undefined && \"items\" in schema);\n if (isArray) {\n if (value === undefined || value === null) {\n return [];\n }\n const items = schema.items;\n if (Array.isArray(value) && isPlainObject(items)) {\n return value.map((entry) => fillFromSchema(items, entry));\n }\n return value;\n }\n\n const isObject =\n type === \"object\" || (type === undefined && \"properties\" in schema);\n if (isObject) {\n if (!isPlainObject(value)) {\n return value;\n }\n const properties = schema.properties;\n if (isPlainObject(properties)) {\n for (const [key, propSchema] of Object.entries(properties)) {\n value[key] = fillFromSchema(propSchema, value[key]);\n }\n }\n return value;\n }\n\n return value;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Ensure every array field declared in `format` is present in `content` as an\n * array. A declared `format` is a schema contract: an empty list should surface\n * as `[]`, not be dropped from the response. Some providers/models omit empty\n * array fields entirely, leaving consumers to read `.length` on `undefined`.\n *\n * Only mutates a (cloned) structured object; strings and non-objects pass\n * through untouched.\n */\nexport function fillFormatArrays({\n content,\n format,\n}: {\n content: JsonObject;\n format: Format;\n}): JsonObject {\n const schema = formatToJsonSchema(format);\n if (!schema) {\n return content;\n }\n return fillFromSchema(schema, structuredClone(content)) as JsonObject;\n}\n","import {\n AnyValue,\n JsonObject,\n JsonReturn,\n NaturalMap,\n NaturalSchema,\n} from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\nimport { type LlmEffort } from \"../constants.js\";\nimport { LlmTool } from \"./LlmTool.interface.js\";\nimport { LlmStreamChunk } from \"./LlmStreamChunk.interface.js\";\nimport { Toolkit } from \"../tools/Toolkit.class.js\";\n\n// Enums\n\nexport enum LlmMessageRole {\n Assistant = \"assistant\",\n Developer = \"developer\",\n System = \"system\",\n User = \"user\",\n}\n\nexport enum LlmMessageType {\n FunctionCall = \"function_call\",\n FunctionCallOutput = \"function_call_output\",\n InputFile = \"input_file\",\n InputImage = \"input_image\",\n InputText = \"input_text\",\n ItemReference = \"item_reference\",\n Message = \"message\",\n OutputText = \"output_text\",\n Refusal = \"refusal\",\n}\n\nexport enum LlmResponseStatus {\n Completed = \"completed\",\n Incomplete = \"incomplete\",\n InProgress = \"in_progress\",\n}\n\n// Errors\n\nexport interface LlmError {\n detail?: string;\n status: number | string;\n title: string;\n}\n\n// Input\n\nexport interface LlmInputContentFile {\n type: LlmMessageType.InputFile;\n file_data: File | string;\n file_id?: string;\n filename?: string;\n}\n\nexport interface LlmInputContentImage {\n type: LlmMessageType.InputImage;\n detail?: File;\n file_id?: string;\n image_url?: string;\n}\n\nexport interface LlmInputContentText {\n type: LlmMessageType.InputText;\n text: string;\n}\n\nexport type LlmInputContent =\n LlmInputContentFile | LlmInputContentImage | LlmInputContentText;\n\n/**\n * Represents the \"Input message object\" in the \"input item list\"\n * from [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses/create)\n */\nexport interface LlmInputMessage {\n content: string | Array<LlmInputContent>;\n role: LlmMessageRole;\n type?: LlmMessageType.Message;\n}\n\n// LlmOperateInput - Simplified input format with automatic file resolution\n\n/**\n * File input that can be loaded from local filesystem, S3, or provided as base64 data.\n * For PDFs, specific pages can be extracted via the `pages` property.\n * If the file extension is an image type, it will be treated as an image internally.\n */\nexport interface LlmOperateInputFile {\n /** Path or filename (extension determines type via /\\.(\\w+)$/) */\n file: string;\n /** S3 bucket name (if present, load from S3) */\n bucket?: string;\n /** Specific pages to extract from PDF (omit = all pages) */\n pages?: number[];\n /** Base64 data (if present, use directly instead of loading from file) */\n data?: string;\n}\n\n/**\n * Image input that can be loaded from local filesystem, S3, or provided as base64 data.\n */\nexport interface LlmOperateInputImage {\n /** Path or filename */\n image: string;\n /** S3 bucket name (if present, load from S3) */\n bucket?: string;\n /** Base64 data (if present, use directly instead of loading from file) */\n data?: string;\n}\n\n/**\n * Content item in LlmOperateInput array.\n * Can be a string (text), file object, or image object.\n */\nexport type LlmOperateInputContent =\n string | LlmOperateInputFile | LlmOperateInputImage;\n\n/**\n * Simplified input format for operate() that supports automatic file resolution.\n * Files/images are loaded from local filesystem, S3, or provided data.\n *\n * @example\n * ```typescript\n * const input: LlmOperateInput = [\n * \"Extract text from these documents\",\n * { file: \"document.pdf\", bucket: \"my-bucket\", pages: [1, 2, 3] },\n * { image: \"photo.png\" }, // loads from local filesystem\n * ];\n * ```\n */\nexport type LlmOperateInput = LlmOperateInputContent[];\n\n// Output\nexport interface LlmOutputContentText {\n annotations?: AnyValue[];\n text: string;\n type: LlmMessageType.OutputText;\n}\n\ninterface LlmOutputRefusal {\n refusal: string;\n type: LlmMessageType.Refusal;\n}\n\ntype LlmOutputContent = LlmOutputContentText | LlmOutputRefusal;\n\n/**\n * Represents the \"Output message object\" in the \"input item list\"\n * from [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses/create)\n */\nexport interface LlmOutputMessage {\n content: string | Array<LlmOutputContent>;\n id?: string;\n role: LlmMessageRole.Assistant;\n status?: LlmResponseStatus;\n type?: LlmMessageType.Message;\n}\n\ntype LlmOutputItem = LlmToolCall | LlmToolResult | LlmOutputMessage;\n\ntype LlmOutput = LlmOutputItem[];\n\n// Tools\n\nexport interface LlmToolCall {\n arguments: string;\n call_id: string;\n id: string;\n name: string;\n type: LlmMessageType.FunctionCall;\n status: LlmResponseStatus;\n}\nexport interface LlmToolResult {\n call_id: string;\n output: string;\n status?: LlmResponseStatus;\n type: LlmMessageType.FunctionCallOutput;\n}\n\ninterface LlmItemReference {\n type: LlmMessageType.ItemReference;\n id: string;\n}\n\n// Options\n\nexport type LlmHistoryItem =\n LlmInputMessage | LlmItemReference | LlmOutputItem | LlmToolResult;\n\nexport type LlmHistory = LlmHistoryItem[];\n\n/**\n * Configuration for a fallback provider.\n * Used when the primary provider fails with an unrecoverable error.\n */\nexport interface LlmFallbackConfig {\n /** Provider name (e.g., \"openai\", \"anthropic\", \"google\") */\n provider: string;\n /** Model to use with this provider (optional, uses provider default if not specified) */\n model?: string;\n /** API key for this provider (optional, uses environment variable if not specified) */\n apiKey?: string;\n}\n\nexport interface LlmMessageOptions {\n data?: NaturalMap;\n model?: string;\n placeholders?: {\n message?: boolean;\n system?: boolean;\n };\n response?: NaturalSchema | z.ZodType;\n system?: string;\n}\n\n// Progress\n\nexport enum LlmProgressEventType {\n Done = \"done\",\n ModelRequest = \"model_request\",\n ModelResponse = \"model_response\",\n Retry = \"retry\",\n Start = \"start\",\n ToolCall = \"tool_call\",\n ToolError = \"tool_error\",\n ToolResult = \"tool_result\",\n}\n\nexport interface LlmProgressToolCall {\n /** JSON string of arguments (tool_call events only) */\n arguments?: string;\n /** Resolved `LlmTool.message`, when the tool defines one (tool_call events only) */\n message?: string;\n /** Tool name */\n name: string;\n}\n\n/**\n * Lightweight, serializable progress event emitted by the operate loop.\n * Suitable for forwarding directly to websockets, queues, or UI updates.\n */\nexport interface LlmProgressEvent {\n /** Text or structured content (model_response, done) */\n content?: string | JsonObject;\n /** Error message (tool_error, retry) */\n error?: string;\n /** Maximum turns allowed for the loop (start) */\n maxTurns?: number;\n /** Model handling the request (start, model_request) */\n model?: string;\n /** Provider name (start) */\n provider?: string;\n /** The tool involved (tool_call, tool_result, tool_error) */\n tool?: LlmProgressToolCall;\n /** Tools the model requested (model_response) */\n toolCalls?: LlmProgressToolCall[];\n /** Current turn, 1-indexed */\n turn?: number;\n /** Event type */\n type: LlmProgressEventType;\n /** Usage: this turn for model_response, cumulative for done */\n usage?: LlmUsage;\n}\n\nexport type LlmProgressCallback = (\n event: LlmProgressEvent,\n) => unknown | Promise<unknown>;\n\n// Exchange\n\n/**\n * Serializable snapshot of the request side of one operate() call.\n * `input` is the raw, pre-interpolation input with multimodal parts preserved.\n */\nexport interface LlmExchangeRequest {\n cache?: LlmCache;\n data?: NaturalMap;\n effort?: LlmEffort;\n explain?: boolean;\n /** Format normalized to JSON Schema (Zod/Natural already rendered) */\n format?: JsonObject;\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput;\n instructions?: string;\n /** Requested model (pre-fallback) */\n model?: string;\n placeholders?: {\n input?: boolean;\n instructions?: boolean;\n system?: boolean;\n };\n providerOptions?: JsonObject;\n system?: string;\n temperature?: number;\n /** Names of tools offered to the model */\n tools?: string[];\n turns?: boolean | number;\n user?: string;\n}\n\n/**\n * Serializable snapshot of the response side of one operate() call.\n */\nexport interface LlmExchangeResponse {\n content?: string | JsonObject;\n error?: LlmError;\n /** Turns this call added to history (tool calls/results included); never the resent history */\n historyDelta: LlmHistory;\n reasoning?: string[];\n status: LlmResponseStatus;\n stopReason?: string;\n /** Per-model-call usage items (provider/model on each item) */\n usage: LlmUsage;\n /** Cumulative usage keyed `provider:model` */\n usageTotals?: Record<string, LlmUsageItem>;\n}\n\n/**\n * How the call was actually served after fallback and retry resolution.\n */\nexport interface LlmExchangeResolution {\n fallbackAttempts?: number;\n fallbackUsed?: boolean;\n /** Served model */\n model?: string;\n /** Served provider */\n provider?: string;\n /** Model-request retries within the served attempt */\n retries?: number;\n}\n\nexport interface LlmExchangeTiming {\n /** Milliseconds from start to settlement */\n duration: number;\n /** ISO 8601 */\n startedAt: string;\n}\n\n/**\n * One serializable request/response envelope per operate() settlement\n * (success or failure). Contains no functions.\n */\nexport interface LlmExchangeEnvelope {\n /** Provider response id(s) per model turn, when available */\n ids?: string[];\n request: LlmExchangeRequest;\n resolution: LlmExchangeResolution;\n response: LlmExchangeResponse;\n timing: LlmExchangeTiming;\n}\n\nexport type LlmExchangeCallback = (\n envelope: LlmExchangeEnvelope,\n) => unknown | Promise<unknown>;\n\n/**\n * Prompt-caching control for operate()/stream().\n * - `true` / omitted → caching enabled at the default `\"5m\"` TTL\n * - `false` / `0` → caching disabled\n * - `\"5m\"` / `\"1h\"` → enabled at that TTL (TTL honored by Anthropic/OpenRouter;\n * other providers ignore it and cache with their own defaults)\n */\nexport type LlmCache = boolean | 0 | \"5m\" | \"1h\";\n\nexport interface LlmOperateOptions {\n /**\n * Prompt caching for the stable request prefix (system prompt + tools).\n * Enabled by default; pass `false`/`0` to opt out, or `\"5m\"`/`\"1h\"` to set\n * the TTL. See {@link LlmCache}.\n */\n cache?: LlmCache;\n data?: NaturalMap;\n /**\n * Provider-neutral reasoning effort (lowest | low | medium | high | highest).\n * Each provider translates it to its native control, spreading the scale\n * across the provider's range; omitting it leaves the provider default\n * untouched, so it is safe across a fallback chain. Providers without\n * reasoning control ignore it.\n */\n effort?: LlmEffort;\n explain?: boolean;\n /** Chain of fallback providers to try if primary fails. Set to false to disable instance-level fallback. */\n fallback?: LlmFallbackConfig[] | false;\n format?: JsonObject | NaturalSchema | z.ZodType;\n history?: LlmHistory;\n hooks?: {\n afterEachModelResponse?: ({\n input,\n options,\n providerRequest,\n providerResponse,\n content,\n usage,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n providerResponse: any;\n content: string | JsonObject;\n usage: LlmUsage;\n }) => unknown | Promise<unknown>;\n afterEachTool?: ({\n result,\n toolName,\n args,\n message,\n }: {\n result: unknown;\n toolName: string;\n args: string;\n /** Resolved `LlmTool.message`, when the tool defines one */\n message?: string;\n }) => unknown | Promise<unknown>;\n beforeEachModelRequest?: ({\n input,\n options,\n providerRequest,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n }) => unknown | Promise<unknown>;\n beforeEachTool?: ({\n toolName,\n args,\n message,\n }: {\n toolName: string;\n args: string;\n /** Resolved `LlmTool.message`, when the tool defines one */\n message?: string;\n }) => unknown | Promise<unknown>;\n onRetryableModelError?: ({\n input,\n options,\n providerRequest,\n error,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n error: any;\n }) => unknown | Promise<unknown>;\n onToolError?: ({\n error,\n toolName,\n args,\n message,\n }: {\n error: Error;\n toolName: string;\n args: string;\n /** Resolved `LlmTool.message`, when the tool defines one */\n message?: string;\n }) => unknown | Promise<unknown>;\n onUnrecoverableModelError?: ({\n input,\n options,\n providerRequest,\n error,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n error: any;\n }) => unknown | Promise<unknown>;\n };\n instructions?: string;\n model?: string;\n /**\n * Fires once per operate() settlement (success or failure) with a fully\n * serializable request/response envelope. Errors thrown by the callback\n * are logged and never interrupt the call.\n */\n onExchange?: LlmExchangeCallback;\n /**\n * Receives lightweight progress events as the operate loop runs:\n * start, model_request, model_response, tool_call, tool_result,\n * tool_error, retry, done. Errors thrown by the callback are logged\n * and never interrupt the loop.\n */\n onProgress?: LlmProgressCallback;\n placeholders?: {\n input?: boolean;\n instructions?: boolean;\n system?: boolean;\n };\n providerOptions?: JsonObject;\n system?: string;\n temperature?: number;\n tools?: LlmTool[] | Toolkit;\n turns?: boolean | number;\n user?: string;\n}\n\n/**\n * A single model name, or a preference-ordered array of model names.\n * An array is interpreted as a fallback chain: index 0 is primary, later\n * entries are tried in order when earlier ones fail (provider auto-detected\n * per entry). Accepted by the `Llm` constructor and static/instance\n * `operate`/`send`/`stream` methods; normalized to a scalar model plus a\n * derived fallback chain before reaching providers.\n */\nexport type LlmModelOption = string | string[];\n\nexport interface LlmOptions {\n apiKey?: string;\n /** Chain of fallback providers to try if primary fails */\n fallback?: LlmFallbackConfig[];\n model?: string;\n}\n\n// Responses\n\nexport interface LlmUsageItem {\n input: number;\n output: number;\n reasoning: number;\n total: number;\n /** Prompt-cache tokens served from cache this call (billed at ~0.1x input) */\n cacheRead?: number;\n /** Prompt-cache tokens written to cache this call (billed at ~1.25x input) */\n cacheWrite?: number;\n provider?: string;\n model?: string;\n}\n\nexport type LlmUsage = LlmUsageItem[];\n\nexport interface LlmOperateResponse {\n content?: string | JsonObject;\n error?: LlmError;\n /**\n * Serializable exchange envelope for this call. Present only when\n * `onExchange` was passed or exchange persistence is enabled.\n */\n exchange?: LlmExchangeEnvelope;\n /** Number of providers attempted (1 = primary only, >1 = fallback(s) used) */\n fallbackAttempts?: number;\n /** Whether a fallback provider was used instead of the primary */\n fallbackUsed?: boolean;\n history: LlmHistory;\n model?: string;\n output: LlmOutput;\n /** Which provider actually handled the request */\n provider?: string;\n reasoning: string[];\n responses: JsonReturn[];\n status: LlmResponseStatus;\n usage: LlmUsage;\n}\n\n// Main\n\nexport interface LlmProvider {\n operate?(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options?: LlmOperateOptions,\n ): Promise<LlmOperateResponse>;\n send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject>;\n stream?(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options?: LlmOperateOptions,\n ): AsyncIterable<LlmStreamChunk>;\n}\n","import { placeholders } from \"@jaypie/kit\";\nimport {\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n} from \"../types/LlmProvider.interface.js\";\nimport { NaturalMap } from \"@jaypie/types\";\n\n/**\n * Options for formatOperateMessage function\n */\nexport interface FormatOperateMessageOptions {\n /**\n * Data to use for placeholder substitution\n */\n data?: NaturalMap;\n\n /**\n * Role to use for the message\n */\n role?: LlmMessageRole;\n}\n\n/**\n * Converts a string to a standardized LlmInputMessage\n * @param input - String to format\n * @param options - Optional configuration\n * @param options.data - Data to use for placeholder substitution\n * @param options.role - Role to use for the message (defaults to User)\n * @returns LlmInputMessage\n */\nexport function formatOperateMessage(\n input: string,\n options?: FormatOperateMessageOptions,\n): LlmInputMessage {\n const content = options?.data ? placeholders(input, options.data) : input;\n\n return {\n content,\n role: options?.role || LlmMessageRole.User,\n type: LlmMessageType.Message,\n };\n}\n","import {\n LlmHistory,\n LlmInputMessage,\n LlmMessageRole,\n} from \"../types/LlmProvider.interface.js\";\nimport { NaturalMap } from \"@jaypie/types\";\nimport { formatOperateMessage } from \"./formatOperateMessage.js\";\n\n/**\n * Options for formatOperateInput function\n */\nexport interface FormatOperateInputOptions {\n /**\n * Data to use for placeholder substitution\n */\n data?: NaturalMap;\n\n /**\n * Role to use when converting a string to LlmInputMessage\n */\n role?: LlmMessageRole;\n}\n\n/**\n * Converts various input types to a standardized LlmHistory format\n * @param input - String, LlmInputMessage, or LlmHistory to format\n * @param options - Optional configuration\n * @param options.data - Data to use for placeholder substitution\n * @param options.role - Role to use when converting a string to LlmInputMessage (defaults to User)\n * @returns Standardized LlmHistory array\n */\nexport function formatOperateInput(\n input: string | LlmInputMessage | LlmHistory,\n options?: FormatOperateInputOptions,\n): LlmHistory {\n // If input is already LlmHistory, return it\n if (Array.isArray(input)) {\n return input;\n }\n\n // If input is a string, convert it to LlmInputMessage\n if (typeof input === \"string\") {\n return [formatOperateMessage(input, options)];\n }\n\n // If input is LlmInputMessage, apply placeholders if data is provided\n if (options?.data && typeof input.content === \"string\") {\n return [\n formatOperateMessage(input.content, {\n data: options.data,\n role: input.role || options?.role,\n }),\n ];\n }\n\n // Otherwise, just wrap the input in an array\n return [input];\n}\n","import log from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema, NaturalSchemaObject } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { naturalZodSchema } from \"./naturalZodSchema.js\";\n\n// Keywords a JSON Schema object node can carry that Natural Schema has no\n// representation for. Anything present here (or any other unrecognized key)\n// is dropped silently and logged, never thrown.\nconst LOSSY_OBJECT_KEYWORDS = [\n \"$defs\",\n \"$id\",\n \"$ref\",\n \"$schema\",\n \"additionalProperties\",\n \"const\",\n \"default\",\n \"description\",\n \"format\",\n \"maxLength\",\n \"maximum\",\n \"minLength\",\n \"minimum\",\n \"multipleOf\",\n \"nullable\",\n \"allOf\",\n \"anyOf\",\n \"oneOf\",\n \"pattern\",\n] as const;\n\nconst KNOWN_KEYWORDS = new Set<string>([\n \"type\",\n \"properties\",\n \"required\",\n \"items\",\n \"enum\",\n ...LOSSY_OBJECT_KEYWORDS,\n]);\n\n/**\n * Duck-type check for a bare JSON Schema object node: `{ type: \"object\", properties: {...} }`.\n * Does not require the OpenAI-style `{ type: \"json_schema\", ... }` envelope.\n */\nexport function isJsonSchema(value: unknown): value is JsonObject {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const schema = value as JsonObject;\n return (\n schema.type === \"object\" &&\n typeof schema.properties === \"object\" &&\n schema.properties !== null &&\n !Array.isArray(schema.properties)\n );\n}\n\n/**\n * Convert a Natural Schema to JSON Schema. Lossless: Natural Schema is a\n * strict subset of what JSON Schema can express.\n */\nexport function naturalSchemaToJsonSchema(schema: NaturalSchema): JsonObject {\n return z.toJSONSchema(naturalZodSchema(schema)) as JsonObject;\n}\n\nfunction logDroppedKeywords(schema: JsonObject, path: string): void {\n for (const key of Object.keys(schema)) {\n if (!KNOWN_KEYWORDS.has(key)) {\n log.debug(\n `[jsonSchemaToNaturalSchema] Dropping unrecognized keyword \"${key}\" at \"${path}\"`,\n );\n } else if (\n (LOSSY_OBJECT_KEYWORDS as readonly string[]).includes(key) &&\n schema[key] !== undefined\n ) {\n log.debug(\n `[jsonSchemaToNaturalSchema] Dropping unsupported keyword \"${key}\" at \"${path}\"`,\n );\n }\n }\n}\n\nfunction convertNode(schema: JsonObject, path: string): NaturalSchema {\n logDroppedKeywords(schema, path);\n\n if (Array.isArray(schema.enum)) {\n return schema.enum as string[];\n }\n\n switch (schema.type) {\n case \"string\":\n return String;\n case \"number\":\n case \"integer\":\n return Number;\n case \"boolean\":\n return Boolean;\n case \"array\": {\n const items = schema.items;\n if (typeof items !== \"object\" || items === null || Array.isArray(items)) {\n return Array;\n }\n return [convertNode(items as JsonObject, `${path}[]`)];\n }\n case \"object\": {\n const properties = schema.properties as\n Record<string, JsonObject> | undefined;\n if (!properties || Object.keys(properties).length === 0) {\n return Object;\n }\n const required = new Set(\n Array.isArray(schema.required) ? (schema.required as string[]) : [],\n );\n const result: NaturalSchemaObject = {};\n for (const [key, value] of Object.entries(properties)) {\n if (!required.has(key)) {\n log.debug(\n `[jsonSchemaToNaturalSchema] Field \"${path}.${key}\" is optional; Natural Schema has no optional marker — treating as required`,\n );\n }\n result[key] = convertNode(value, `${path}.${key}`);\n }\n return result;\n }\n default:\n log.debug(\n `[jsonSchemaToNaturalSchema] Unsupported type \"${String(schema.type)}\" at \"${path}\"; defaulting to Object`,\n );\n return Object;\n }\n}\n\n/**\n * Convert a JSON Schema object node to Natural Schema. Lossy: constraints,\n * descriptions, defaults, unions, and optionality have no Natural Schema\n * representation. Dropped keywords are logged at debug level, never thrown.\n */\nexport function jsonSchemaToNaturalSchema(schema: JsonObject): NaturalSchema {\n return convertNode(schema, \"$\");\n}\n","import { JsonObject } from \"@jaypie/types\";\n\n/**\n * Converts a JSON Schema (Draft 2020-12) object to the OpenAPI 3.0 schema subset\n * that Gemini's `responseSchema` accepts. This constrains generation (not just validation)\n * and avoids the `items`-keyword leakage bug in `responseJsonSchema`.\n *\n * Strips: $schema, additionalProperties, $defs, $ref (inlines where possible), const\n * Preserves: type, properties, required, items, enum, description, nullable\n */\nexport function jsonSchemaToOpenApi3(schema: JsonObject): JsonObject {\n if (typeof schema !== \"object\" || schema === null || Array.isArray(schema)) {\n return schema;\n }\n\n const result: JsonObject = {};\n\n for (const [key, value] of Object.entries(schema)) {\n // Strip JSON Schema keywords not in OpenAPI 3.0 subset\n if (\n key === \"$schema\" ||\n key === \"$defs\" ||\n key === \"additionalProperties\" ||\n key === \"const\" ||\n key === \"$ref\"\n ) {\n continue;\n }\n\n if (\n key === \"properties\" &&\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value)\n ) {\n const convertedProps: JsonObject = {};\n for (const [propKey, propValue] of Object.entries(\n value as Record<string, JsonObject>,\n )) {\n convertedProps[propKey] = jsonSchemaToOpenApi3(propValue);\n }\n result[key] = convertedProps;\n } else if (key === \"items\" && typeof value === \"object\" && value !== null) {\n result[key] = jsonSchemaToOpenApi3(value as JsonObject);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n","import { JAYPIE } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\n\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n","import { PROVIDER } from \"../constants.js\";\n\n//\n//\n// Constants\n//\n\n// Non-streaming requests above ~16K output tokens risk HTTP timeouts\n// (Anthropic guidance is to stream anything larger), so non-streaming\n// defaults are capped here and only streaming requests resolve to the\n// full model maximum.\nconst NON_STREAMING_MAX_TOKENS = PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT;\n\n// Maximum output tokens by model; first match wins.\n// Providers without low output ceilings (OpenAI, xAI) are intentionally\n// absent — their requests leave the limit unset.\nconst MODEL_MAX_OUTPUT_TOKENS: { pattern: RegExp; tokens: number }[] = [\n // Anthropic — https://platform.claude.com/docs/en/about-claude/models/overview\n { pattern: /^claude-opus-4-(0$|1$|1-|2025)/, tokens: 32_000 },\n { pattern: /^claude-opus-4-5/, tokens: 64_000 },\n { pattern: /^claude-sonnet-4-(0$|5$|5-|2025)/, tokens: 64_000 },\n { pattern: /haiku/, tokens: 64_000 },\n { pattern: /claude|fable|mythos|opus|sonnet/, tokens: 128_000 },\n // Google — https://ai.google.dev/gemini-api/docs/models\n { pattern: /gemini-(2\\.5|3)/, tokens: 65_536 },\n { pattern: /gemini/, tokens: 8_192 },\n];\n\n//\n//\n// Main\n//\n\n/**\n * Maximum output tokens the model supports, or undefined when unknown.\n */\nexport function maxOutputTokens(model: string): number | undefined {\n const match = MODEL_MAX_OUTPUT_TOKENS.find(({ pattern }) =>\n pattern.test(model),\n );\n return match?.tokens;\n}\n\n/**\n * Default output token limit for a request: the model maximum when\n * streaming, capped at the non-streaming maximum otherwise. Returns\n * undefined when the model's maximum is unknown.\n */\nexport function resolveMaxOutputTokens(\n model: string,\n { stream = false }: { stream?: boolean } = {},\n): number | undefined {\n const max = maxOutputTokens(model);\n if (max === undefined) return undefined;\n return stream ? max : Math.min(max, NON_STREAMING_MAX_TOKENS);\n}\n","import { LlmOperateOptions } from \"../types/LlmProvider.interface.js\";\n\n// Turn policy constants\nexport const MAX_TURNS_ABSOLUTE_LIMIT = 72;\nexport const MAX_TURNS_DEFAULT_LIMIT = 24;\n\n/**\n * Determines the maximum number of turns based on the provided options\n *\n * @param options - The LLM operate options\n * @returns The maximum number of turns\n */\nexport function maxTurnsFromOptions(options: LlmOperateOptions): number {\n // Default to single turn (1) when turns are disabled\n\n // Handle the turns parameter\n if (options.turns === undefined) {\n // Default to default limit when undefined\n return MAX_TURNS_DEFAULT_LIMIT;\n } else if (options.turns === true) {\n // Explicitly set to true\n return MAX_TURNS_DEFAULT_LIMIT;\n } else if (typeof options.turns === \"number\") {\n if (options.turns > 0) {\n // Positive number - use that limit (capped at absolute limit)\n return Math.min(options.turns, MAX_TURNS_ABSOLUTE_LIMIT);\n } else if (options.turns < 0) {\n // Negative number - use default limit\n return MAX_TURNS_DEFAULT_LIMIT;\n }\n // If turns is 0, return 1 (disabled)\n return 1;\n }\n // All other values (false, null, etc.) will return 1 (disabled)\n return 1;\n}\n","import RandomLib from \"random\";\nimport { ConfigurationError } from \"@jaypie/errors\";\n\n//\n// Types\n//\n\ninterface RandomOptions {\n min?: number;\n max?: number;\n mean?: number;\n stddev?: number;\n integer?: boolean;\n start?: number;\n seed?: string;\n precision?: number;\n currency?: boolean;\n}\n\ntype RandomFunction = {\n (options?: RandomOptions): number;\n};\n\n//\n// Constants\n//\n\nexport const DEFAULT_MIN = 0;\nexport const DEFAULT_MAX = 1;\n\n//\n// Helper Functions\n//\n\n/**\n * Clamps a number between optional minimum and maximum values\n * @param num - The number to clamp\n * @param min - Optional minimum value\n * @param max - Optional maximum value\n * @returns The clamped number\n */\nconst clamp = (num: number, min?: number, max?: number): number => {\n let result = num;\n if (typeof min === \"number\") result = Math.max(result, min);\n if (typeof max === \"number\") result = Math.min(result, max);\n return result;\n};\n\n/**\n * Validates that min is not greater than max\n * @param min - Optional minimum value\n * @param max - Optional maximum value\n * @throws {ConfigurationError} If min is greater than max\n */\nconst validateBounds = (\n min: number | undefined,\n max: number | undefined,\n): void => {\n if (typeof min === \"number\" && typeof max === \"number\" && min > max) {\n throw new ConfigurationError(\n `Invalid bounds: min (${min}) cannot be greater than max (${max})`,\n );\n }\n};\n\n//\n// Main\n//\n\n/**\n * Creates a random number generator with optional seeding\n *\n * @param defaultSeed - Seed string for the default RNG\n * @returns A function that generates random numbers based on provided options\n *\n * @example\n * const rng = random(\"default-seed\");\n *\n * // Generate a random float between 0 and 1\n * const basic = rng();\n *\n * // Generate an integer between 1 and 10\n * const integer = rng({ min: 1, max: 10, integer: true });\n *\n * // Generate from normal distribution\n * const normal = rng({ mean: 50, stddev: 10 });\n *\n * // Use consistent seeding\n * const seeded = rng({ seed: \"my-seed\" });\n */\nexport function random(defaultSeed?: string): RandomFunction {\n // Initialize default seeded RNG\n const defaultRng = RandomLib.clone(defaultSeed);\n\n // Store per-seed RNGs\n const seedMap = new Map<string, ReturnType<typeof RandomLib.clone>>();\n\n const rngFn = ({\n min,\n max: providedMax,\n mean,\n stddev,\n integer = false,\n start = 0,\n seed,\n precision,\n currency = false,\n }: RandomOptions = {}): number => {\n // Select the appropriate RNG based on seed\n const rng = seed\n ? seedMap.get(seed) ||\n (() => {\n const newRng = RandomLib.clone(seed);\n seedMap.set(seed, newRng);\n return newRng;\n })()\n : defaultRng;\n\n // If only min is set, set max to min*2, but keep track of whether max was provided\n let max = providedMax;\n if (typeof min === \"number\" && typeof max !== \"number\") {\n max = min * 2;\n }\n\n validateBounds(min, max);\n\n // Determine effective precision based on parameters\n const getEffectivePrecision = (): number | undefined => {\n if (integer) return 0;\n\n const precisions: number[] = [];\n if (typeof precision === \"number\" && precision >= 0) {\n precisions.push(precision);\n }\n if (currency) {\n precisions.push(2);\n }\n\n // Return the lowest precision if any are set, undefined otherwise\n return precisions.length > 0 ? Math.min(...precisions) : undefined;\n };\n\n // Helper function to apply precision\n const applyPrecision = (value: number): number => {\n const effectivePrecision = getEffectivePrecision();\n if (typeof effectivePrecision === \"number\") {\n const factor = Math.pow(10, effectivePrecision);\n return Math.round(value * factor) / factor;\n }\n return value;\n };\n\n // Use normal distribution if both mean and stddev are provided\n if (typeof mean === \"number\" && typeof stddev === \"number\") {\n const normalDist = rng.normal(mean, stddev);\n const value = normalDist();\n\n // Only clamp if min/max are defined\n const clampedValue = clamp(value, min, providedMax);\n\n // Switch to uniform distribution only if both bounds were explicitly provided and exceeded\n if (\n typeof min === \"number\" &&\n typeof providedMax === \"number\" &&\n clampedValue !== value\n ) {\n const baseValue = integer ? rng.int(min, max) : rng.float(min, max);\n return applyPrecision(start + baseValue);\n }\n\n return applyPrecision(\n start + (integer ? Math.round(clampedValue) : clampedValue),\n );\n }\n\n // For uniform distribution, use defaults if min/max are undefined\n const uniformMin = typeof min === \"number\" ? min : DEFAULT_MIN;\n const uniformMax = typeof max === \"number\" ? max : DEFAULT_MAX;\n\n const baseValue = integer\n ? rng.int(uniformMin, uniformMax)\n : rng.float(uniformMin, uniformMax);\n return applyPrecision(start + baseValue);\n };\n\n return rngFn;\n}\n","import { z } from \"zod/v4\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\n\nimport { naturalZodSchema } from \"./naturalZodSchema.js\";\n\n//\n//\n// Types\n//\n\ntype Format = JsonObject | NaturalSchema | z.ZodType;\n\n//\n//\n// Helpers\n//\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Convert a `format` declaration (Zod schema, NaturalSchema, or a JSON Schema\n * JsonObject) into a plain JSON Schema we can walk. Mirrors the conversion the\n * provider adapters perform in `formatOutputSchema`, but without any\n * provider-specific sanitization.\n */\nfunction formatToJsonSchema(format: Format): JsonObject | undefined {\n if (format instanceof z.ZodType) {\n return z.toJSONSchema(format) as JsonObject;\n }\n if (isPlainObject(format) && (format as JsonObject).type === \"json_schema\") {\n const clone = structuredClone(format) as JsonObject;\n clone.type = \"object\";\n return clone;\n }\n try {\n return z.toJSONSchema(\n naturalZodSchema(format as NaturalSchema),\n ) as JsonObject;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Strip a single pair of surrounding double quotes from a key, if present.\n * `\"Merchant Request\"` -> `Merchant Request`; `Confidence` -> `Confidence`.\n */\nfunction dequoteKey(key: string): string {\n if (key.length >= 2 && key.startsWith('\"') && key.endsWith('\"')) {\n return key.slice(1, -1);\n }\n return key;\n}\n\n/**\n * Walk a JSON Schema alongside a parsed value, renaming any object key whose\n * de-quoted form matches a declared property name. Recurses into declared\n * object properties and array items so nested corrupted keys are also repaired.\n */\nfunction repairFromSchema(schema: unknown, value: unknown): unknown {\n if (!isPlainObject(schema)) {\n return value;\n }\n\n const type = schema.type;\n const isArray = type === \"array\" || (type === undefined && \"items\" in schema);\n if (isArray) {\n const items = schema.items;\n if (Array.isArray(value) && isPlainObject(items)) {\n return value.map((entry) => repairFromSchema(items, entry));\n }\n return value;\n }\n\n const isObject =\n type === \"object\" || (type === undefined && \"properties\" in schema);\n if (isObject && isPlainObject(value)) {\n const properties = schema.properties;\n if (isPlainObject(properties)) {\n const declared = new Set(Object.keys(properties));\n // Repair keys: rename a quote-wrapped key to its declared form, unless\n // the correct key is already present (then drop the corrupted duplicate).\n for (const key of Object.keys(value)) {\n if (declared.has(key)) {\n continue;\n }\n const repaired = dequoteKey(key);\n if (repaired !== key && declared.has(repaired)) {\n if (!(repaired in value)) {\n value[repaired] = value[key];\n }\n delete value[key];\n }\n }\n // Recurse into declared properties now that keys are aligned.\n for (const [key, propSchema] of Object.entries(properties)) {\n if (key in value) {\n value[key] = repairFromSchema(propSchema, value[key]);\n }\n }\n }\n return value;\n }\n\n return value;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Repair structured-output keys that a provider/model corrupted by wrapping\n * them in literal double quotes (observed on OpenAI for multi-word `format`\n * keys: `Merchant Request` returned as `\"Merchant Request\"`). A declared\n * `format` is a schema contract: returned keys should match the declared names\n * exactly. Any returned key whose de-quoted form matches a declared key is\n * renamed back to the declared key.\n *\n * Only mutates a (cloned) structured object; strings and non-objects pass\n * through untouched.\n */\nexport function repairFormatKeys({\n content,\n format,\n}: {\n content: JsonObject;\n format: Format;\n}): JsonObject {\n const schema = formatToJsonSchema(format);\n if (!schema) {\n return content;\n }\n return repairFromSchema(schema, structuredClone(content)) as JsonObject;\n}\n","import { JsonObject } from \"@jaypie/types\";\n\nconst DEFAULT_DONE_SENTINEL = \"[DONE]\";\n\n/**\n * Parse a Server-Sent Events stream into decoded JSON chunks. Buffers across\n * network reads, dispatches on newline-delimited `data:` lines, and stops at\n * the done sentinel (OpenAI-style `[DONE]`; Gemini omits it and simply ends\n * the stream). Comment lines (`: ...`, used for keep-alive) are ignored.\n *\n * Shared by the provider HTTP clients that replaced their vendor SDKs.\n */\nexport async function* parseSseStream(\n body: ReadableStream<Uint8Array>,\n { doneSentinel = DEFAULT_DONE_SENTINEL }: { doneSentinel?: string } = {},\n): AsyncIterable<JsonObject> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let newlineIndex: number;\n while ((newlineIndex = buffer.indexOf(\"\\n\")) !== -1) {\n const line = buffer.slice(0, newlineIndex).replace(/\\r$/, \"\");\n buffer = buffer.slice(newlineIndex + 1);\n\n if (line === \"\" || line.startsWith(\":\")) continue;\n if (!line.startsWith(\"data:\")) continue;\n\n const data = line.slice(\"data:\".length).trim();\n if (data === doneSentinel) return;\n\n yield JSON.parse(data) as JsonObject;\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n","import { log } from \"@jaypie/logger\";\n\nimport { LlmUsageItem } from \"../types/LlmProvider.interface.js\";\n\nconst UNKNOWN = \"unknown\";\n\ninterface TallyOperateOptions {\n toolCallNames?: string[];\n turns: number;\n usage?: LlmUsageItem[];\n}\n\n/**\n * Tally loop totals onto the root logger's report session so handlers\n * (express, lambda) include llm activity in the report emitted at teardown.\n * Silently no-ops outside an active session or when the logger predates\n * tally support.\n */\nexport function tallyOperate({\n toolCallNames = [],\n turns,\n usage = [],\n}: TallyOperateOptions): void {\n if (typeof log.tally !== \"function\") return;\n const llm: Record<string, unknown> = {\n operates: 1,\n toolCalls: toolCallNames.length,\n turns,\n };\n if (toolCallNames.length > 0) {\n const tools: Record<string, number> = {};\n for (const name of toolCallNames) {\n tools[name] = (tools[name] ?? 0) + 1;\n }\n llm.tools = tools;\n }\n if (usage.length > 0) {\n const usageByModel: Record<string, Record<string, number>> = {};\n for (const item of usage) {\n const key =\n [item.provider, item.model].filter(Boolean).join(\":\") || UNKNOWN;\n usageByModel[key] ??= { input: 0, output: 0, reasoning: 0, total: 0 };\n usageByModel[key].input += item.input;\n usageByModel[key].output += item.output;\n usageByModel[key].reasoning += item.reasoning;\n usageByModel[key].total += item.total;\n if (item.cacheRead !== undefined) {\n usageByModel[key].cacheRead =\n (usageByModel[key].cacheRead ?? 0) + item.cacheRead;\n }\n if (item.cacheWrite !== undefined) {\n usageByModel[key].cacheWrite =\n (usageByModel[key].cacheWrite ?? 0) + item.cacheWrite;\n }\n }\n llm.usage = usageByModel;\n }\n log.tally({ llm });\n}\n","/**\n * Options for tryParseNumber function\n */\nexport interface TryParseNumberOptions {\n /**\n * Default value to return if parsing fails or results in NaN\n */\n defaultValue?: number;\n /**\n * Function to call with warning message if parsing fails or results in NaN\n */\n warnFunction?: (message: string) => void;\n}\n\n/**\n * Helper function to safely call a function that might throw\n * @param fn Function to call safely\n */\nfunction callSafely(fn: () => void): void {\n try {\n fn();\n } catch {\n // Silently catch any errors from the function\n }\n}\n\n/**\n * Attempts to parse a value as a number. Returns the original input if parsing fails or results in NaN.\n * @param input - The value to attempt to parse as a number\n * @param options - Optional configuration\n * @param options.defaultValue - Default value to return if parsing fails or results in NaN\n * @param options.warnFunction - Function to call with warning message if parsing fails or results in NaN\n * @returns The parsed number, defaultValue (if specified and parsing fails), or the original input\n */\nexport function tryParseNumber(\n input: unknown,\n options?: TryParseNumberOptions,\n): number | unknown {\n if (input === null || input === undefined) {\n return input;\n }\n\n try {\n const parsed = Number(input);\n\n if (Number.isNaN(parsed)) {\n if (options?.warnFunction) {\n const warningMessage = `Failed to parse \"${String(input)}\" as number`;\n callSafely(() => options.warnFunction!(warningMessage));\n }\n\n return typeof options?.defaultValue === \"number\"\n ? options.defaultValue\n : input;\n }\n\n return parsed;\n } catch (error: unknown) {\n if (options?.warnFunction) {\n let errorMessage = \"\";\n if (error instanceof Error) {\n errorMessage = error.message;\n }\n const warningMessage = `Error parsing \"${String(input)}\" as number${errorMessage ? \"; \" + errorMessage : \"\"}`;\n callSafely(() => options.warnFunction!(warningMessage));\n }\n\n return typeof options?.defaultValue === \"number\"\n ? options.defaultValue\n : input;\n }\n}\n","import {\n LlmExchangeCallback,\n LlmExchangeEnvelope,\n} from \"../../types/LlmProvider.interface.js\";\nimport { getLogger } from \"../../util/index.js\";\n\n/**\n * Truthy-except-\"false\"/\"0\" gate on LLM_EXCHANGE_ENABLED, matching the\n * DD_LLMOBS_ENABLED convention in observability/llmobs.ts.\n */\nexport function isExchangeStoreEnabled(): boolean {\n const flag = process.env.LLM_EXCHANGE_ENABLED;\n if (!flag) {\n return false;\n }\n return flag.toLowerCase() !== \"false\" && flag !== \"0\";\n}\n\n/**\n * Whether the loop should assemble an exchange envelope at settlement.\n */\nexport function isExchangeRequested({\n onExchange,\n}: {\n onExchange?: LlmExchangeCallback;\n}): boolean {\n return Boolean(onExchange) || isExchangeStoreEnabled();\n}\n\n/**\n * Deliver an exchange envelope to a callback. Errors thrown by the callback\n * are logged and swallowed — exchange capture must never interrupt the call.\n */\nexport async function emitExchange({\n envelope,\n onExchange,\n}: {\n envelope: LlmExchangeEnvelope;\n onExchange?: LlmExchangeCallback;\n}): Promise<void> {\n if (!onExchange) {\n return;\n }\n try {\n await onExchange(envelope);\n } catch (error) {\n const log = getLogger();\n log.warn(\"[operate] onExchange callback threw\");\n log.var({ error });\n }\n}\n","import { LlmExchangeEnvelope } from \"../types/LlmProvider.interface.js\";\nimport { getLogger } from \"../util/index.js\";\nimport { isExchangeStoreEnabled } from \"../operate/exchange/emitExchange.js\";\n\n//\n//\n// Types\n//\n\n/** Minimal shape of the @jaypie/dynamodb surface this module uses. */\ninterface ExchangeStoreSdk {\n storeExchange: (envelope: LlmExchangeEnvelope) => Promise<unknown>;\n}\n\n//\n//\n// Constants\n//\n\nconst MODULE = {\n // Computed at runtime so bundlers (esbuild) do not attempt to include\n // @jaypie/dynamodb, which is an optional peer dependency.\n JAYPIE_DYNAMODB: [\"@jaypie\", \"dynamodb\"].join(\"/\"),\n};\n\n//\n//\n// Helpers\n//\n\n// Native dynamic import that neither rollup nor tsc rewrites to require(), so\n// a CJS-bundled build still loads @jaypie/dynamodb's ESM entry and shares the\n// host's initialized module instance. A require()-based resolution would load\n// the CJS build, whose module-level client state is separate from the ESM\n// instance an ESM host initializes (dual-package hazard, issue #429).\nconst dynamicImport = new Function(\"s\", \"return import(s)\") as (\n s: string,\n) => Promise<Record<string, unknown>>;\n\nlet resolved = false;\nlet cachedSdk: ExchangeStoreSdk | null = null;\nlet injectedSdk: ExchangeStoreSdk | null = null;\n\n/**\n * Lazily resolve @jaypie/dynamodb's storeExchange. Returns null (and never\n * throws) when the peer is absent. Cached after the first attempt.\n */\nasync function resolveExchangeStore(): Promise<ExchangeStoreSdk | null> {\n if (resolved) {\n return cachedSdk;\n }\n resolved = true;\n try {\n const dynamodb = await dynamicImport(MODULE.JAYPIE_DYNAMODB);\n const sdk = (dynamodb?.default ?? dynamodb) as Partial<ExchangeStoreSdk>;\n if (sdk && typeof sdk.storeExchange === \"function\") {\n cachedSdk = sdk as ExchangeStoreSdk;\n }\n } catch {\n cachedSdk = null;\n }\n return cachedSdk;\n}\n\n/** Reset the cached resolution. Exposed for tests. */\nexport function _resetExchangeStore(): void {\n resolved = false;\n cachedSdk = null;\n injectedSdk = null;\n}\n\n/**\n * Inject a store to bypass @jaypie/dynamodb resolution. Test-only: the peer\n * is optional, so the enabled path cannot otherwise be exercised in unit\n * tests without it installed.\n */\nexport function _setExchangeStore(sdk: ExchangeStoreSdk | null): void {\n injectedSdk = sdk;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Persist an exchange envelope via @jaypie/dynamodb when\n * LLM_EXCHANGE_ENABLED is set. Silent no-op when the flag is unset or the\n * peer is absent; persister failures are logged and never thrown.\n */\nexport async function persistExchange(\n envelope: LlmExchangeEnvelope,\n): Promise<void> {\n if (!isExchangeStoreEnabled()) {\n return;\n }\n const sdk = injectedSdk ?? (await resolveExchangeStore());\n if (!sdk) {\n return;\n }\n try {\n await sdk.storeExchange(envelope);\n } catch (error) {\n const log = getLogger();\n log.warn(\"[operate] Exchange persistence failed\");\n log.var({ error });\n }\n}\n","import { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport {\n LlmHistory,\n LlmOperateOptions,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n ClassifiedError,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\n\n//\n//\n// Provider Adapter Interface\n//\n\n/**\n * ProviderAdapter defines the contract that each LLM provider must implement\n * to work with the shared operate loop.\n *\n * The adapter pattern allows the core operate loop to be provider-agnostic\n * while each provider handles its specific API format and quirks.\n */\nexport interface ProviderAdapter {\n //\n // Provider Identification\n //\n\n /**\n * Unique identifier for this provider (e.g., \"openai\", \"anthropic\")\n */\n readonly name: string;\n\n /**\n * Default model for this provider\n */\n readonly defaultModel: string;\n\n /**\n * Whether OperateLoop may take a corrective turn when a `format` request\n * completes with prose instead of structured output (tool-emulation\n * providers opt in).\n */\n readonly supportsStructuredOutputRetry?: boolean;\n\n //\n // Request Building\n //\n\n /**\n * Build a provider-specific request from the standardized format\n *\n * @param request - Standardized request options\n * @returns Provider-specific request object ready for the API\n */\n buildRequest(request: OperateRequest): unknown;\n\n /**\n * Convert a Toolkit to provider-specific tool definitions\n *\n * @param toolkit - The toolkit containing tool definitions\n * @param outputSchema - Optional JSON schema for structured output\n * @returns Array of provider-specific tool definitions\n */\n formatTools(\n toolkit: Toolkit,\n outputSchema?: JsonObject,\n ): ProviderToolDefinition[];\n\n /**\n * Format a structured output schema for the provider\n *\n * @param schema - JSON schema, NaturalSchema, or Zod schema for the expected output\n * @returns Provider-specific format configuration\n */\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject;\n\n //\n // API Execution\n //\n\n /**\n * Execute an API request to the provider\n *\n * @param client - The provider's SDK client instance\n * @param request - Provider-specific request object (from buildRequest)\n * @param signal - Optional AbortSignal to cancel the request on retry\n * @returns Raw provider response\n */\n executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<unknown>;\n\n /**\n * Execute a streaming API request to the provider\n *\n * @param client - The provider's SDK client instance\n * @param request - Provider-specific request object (from buildRequest)\n * @param signal - Optional AbortSignal to cancel the request on retry\n * @returns AsyncIterable of stream chunks\n */\n executeStreamRequest?(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk>;\n\n //\n // Response Parsing\n //\n\n /**\n * Parse a provider response into standardized format\n *\n * @param response - Raw provider response\n * @param options - Original operate options (for context)\n * @returns Parsed response with content, tool calls, usage, etc.\n */\n parseResponse(response: unknown, options?: LlmOperateOptions): ParsedResponse;\n\n /**\n * Extract tool calls from a provider response\n *\n * @param response - Raw provider response\n * @returns Array of standardized tool calls\n */\n extractToolCalls(response: unknown): StandardToolCall[];\n\n /**\n * Extract usage information from a provider response\n *\n * @param response - Raw provider response\n * @param model - The model used (for tracking)\n * @returns Usage item with token counts\n */\n extractUsage(response: unknown, model: string): LlmUsageItem;\n\n //\n // Tool Result Handling\n //\n\n /**\n * Format a tool result to append to the conversation\n *\n * @param toolCall - The original tool call\n * @param result - The standardized tool result\n * @returns Provider-specific message/item to add to history\n */\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): unknown;\n\n /**\n * Append tool call and result to the request for the next turn\n *\n * @param request - Current provider request\n * @param toolCall - The tool call that was made\n * @param result - The result of the tool call\n * @returns Updated request with tool result appended\n */\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): unknown;\n\n //\n // History Management\n //\n\n /**\n * Convert provider response items to LlmHistory format for storage\n *\n * @param response - Raw provider response\n * @returns History items to append\n */\n responseToHistoryItems(response: unknown): LlmHistory;\n\n //\n // Error Classification\n //\n\n /**\n * Classify an error for retry logic\n *\n * @param error - The error that occurred\n * @returns Classified error with retry recommendation\n */\n classifyError(error: unknown): ClassifiedError;\n\n /**\n * Check if an error is retryable\n *\n * @param error - The error to check\n * @returns True if the error can be retried\n */\n isRetryableError(error: unknown): boolean;\n\n /**\n * Check if an error is due to rate limiting\n *\n * @param error - The error to check\n * @returns True if this is a rate limit error\n */\n isRateLimitError(error: unknown): boolean;\n\n //\n // Provider-Specific Features\n //\n\n /**\n * Check if a response indicates the model wants to stop (vs tool use)\n *\n * @param response - Raw provider response\n * @returns True if the model has finished responding\n */\n isComplete(response: unknown): boolean;\n\n /**\n * Check if a response contains a structured output result\n *\n * @param response - Raw provider response\n * @returns True if structured output was returned\n */\n hasStructuredOutput(response: unknown): boolean;\n\n /**\n * Extract structured output from a response\n *\n * @param response - Raw provider response\n * @returns Parsed JSON object\n */\n extractStructuredOutput(response: unknown): JsonObject | undefined;\n}\n\n//\n//\n// Abstract Base Adapter\n//\n\n/**\n * BaseProviderAdapter provides default implementations for common adapter methods.\n * Providers can extend this class to reduce boilerplate.\n */\nexport abstract class BaseProviderAdapter implements ProviderAdapter {\n abstract readonly name: string;\n abstract readonly defaultModel: string;\n\n abstract buildRequest(request: OperateRequest): unknown;\n abstract formatTools(\n toolkit: Toolkit,\n outputSchema?: JsonObject,\n ): ProviderToolDefinition[];\n abstract formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject;\n abstract executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<unknown>;\n abstract parseResponse(\n response: unknown,\n options?: LlmOperateOptions,\n ): ParsedResponse;\n abstract extractToolCalls(response: unknown): StandardToolCall[];\n abstract extractUsage(response: unknown, model: string): LlmUsageItem;\n abstract formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): unknown;\n abstract appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): unknown;\n abstract responseToHistoryItems(response: unknown): LlmHistory;\n abstract classifyError(error: unknown): ClassifiedError;\n abstract isComplete(response: unknown): boolean;\n\n /**\n * Whether OperateLoop may take a corrective turn when a `format` request\n * completes with prose instead of structured output. Providers whose\n * structured output rides a tool emulation (where compliance is a model\n * decision) opt in; native grammar-constrained providers do not need it.\n */\n readonly supportsStructuredOutputRetry: boolean = false;\n\n /**\n * Default implementation checks if error is retryable via classifyError\n */\n isRetryableError(error: unknown): boolean {\n const classified = this.classifyError(error);\n return classified.shouldRetry;\n }\n\n /**\n * Default implementation checks error category via classifyError\n */\n isRateLimitError(error: unknown): boolean {\n const classified = this.classifyError(error);\n return classified.category === \"rate_limit\";\n }\n\n /**\n * Default implementation returns false - override for providers with native structured output\n */\n\n hasStructuredOutput(_response: unknown): boolean {\n return false;\n }\n\n /**\n * Default implementation returns undefined - override for providers with native structured output\n */\n\n extractStructuredOutput(_response: unknown): JsonObject | undefined {\n return undefined;\n }\n}\n","import { EFFORT, type LlmEffort } from \"../constants.js\";\n\n/**\n * Result of translating the provider-neutral {@link LlmEffort} scale to a\n * provider's native reasoning control.\n */\nexport interface LlmEffortMapping<T extends string | number = string> {\n /**\n * True when the requested neutral level had no distinct native rung and was\n * collapsed or clamped onto a neighbor (e.g. `highest` -> Grok `high`, or\n * `highest` -> OpenAI `high` on a model predating `xhigh`). Adapters log\n * these at debug so a papered-over request stays on the record.\n */\n papered: boolean;\n /** Native effort value for the target provider. */\n value: T;\n}\n\n/**\n * Per-provider translation of the provider-neutral {@link LlmEffort} scale.\n *\n * The neutral enum (lowest → low → medium → high → highest) is a relative\n * five-point scale. Each table below maps it onto the target provider's native\n * effort control, keeping `medium`/`high` semantically aligned across providers\n * and using each provider's extra bottom (`minimal`) or top (`xhigh`/`max`)\n * rung where one exists. Providers with fewer levels collapse the ends and mark\n * the result `papered`. A single `effort` value is therefore safe to reuse\n * across providers and fallback chains.\n */\n\n/** Consistent debug message for a papered-over effort level. */\nexport function paperedEffortMessage({\n model,\n provider,\n requested,\n value,\n}: {\n model: string;\n provider: string;\n requested: LlmEffort;\n value: string | number;\n}): string {\n return `[llm] effort '${requested}' has no distinct tier on ${provider} model '${model}'; using '${value}'`;\n}\n\n// OpenAI Responses API `reasoning.effort`.\n// Full ladder: minimal | low | medium | high | xhigh (plus `none`). Availability\n// is not uniform across the gpt-5 line:\n// - `xhigh` was introduced at gpt-5.2 and has been continuous since, so it is\n// safe for our gpt-5.4 default and everything newer.\n// - `minimal` shipped on gpt-5/5.1, was dropped at gpt-5.2, and returned on\n// the current line; because that history is non-monotonic we only trust it\n// from gpt-5.4 (our default floor) onward.\n// Outside those windows (older gpt-5, o-series) the extreme rung is clamped and\n// the mapping reports `papered: true`.\nconst OPENAI_EFFORT: Record<LlmEffort, string> = {\n [EFFORT.LOWEST]: \"minimal\",\n [EFFORT.LOW]: \"low\",\n [EFFORT.MEDIUM]: \"medium\",\n [EFFORT.HIGH]: \"high\",\n [EFFORT.HIGHEST]: \"xhigh\",\n};\n\ninterface GptVersion {\n major: number;\n minor: number;\n}\n\nfunction openAiGptVersion(model: string): GptVersion | null {\n const match = model.match(/^gpt-(\\d+)(?:\\.(\\d+))?/);\n if (!match) return null;\n return { major: Number(match[1]), minor: match[2] ? Number(match[2]) : 0 };\n}\n\nfunction atLeast(\n version: GptVersion | null,\n major: number,\n minor: number,\n): boolean {\n if (!version) return false;\n return (\n version.major > major || (version.major === major && version.minor >= minor)\n );\n}\n\nexport function toOpenAiEffort(\n effort: LlmEffort,\n { model }: { model: string },\n): LlmEffortMapping {\n const native = OPENAI_EFFORT[effort];\n const version = openAiGptVersion(model);\n // `minimal` only from gpt-5.4 (non-monotonic history; absent on o-series)\n if (native === \"minimal\" && !atLeast(version, 5, 4)) {\n return { papered: true, value: \"low\" };\n }\n // `xhigh` from gpt-5.2 onward (absent on older gpt-5 and o-series)\n if (native === \"xhigh\" && !atLeast(version, 5, 2)) {\n return { papered: true, value: \"high\" };\n }\n return { papered: false, value: native };\n}\n\n// xAI Grok `reasoning_effort` — low | medium | high. No sub-low or top rung, so\n// `lowest` collapses onto `low` and `highest` onto `high`.\nconst XAI_EFFORT: Record<LlmEffort, LlmEffortMapping> = {\n [EFFORT.LOWEST]: { papered: true, value: \"low\" },\n [EFFORT.LOW]: { papered: false, value: \"low\" },\n [EFFORT.MEDIUM]: { papered: false, value: \"medium\" },\n [EFFORT.HIGH]: { papered: false, value: \"high\" },\n [EFFORT.HIGHEST]: { papered: true, value: \"high\" },\n};\n\nexport function toXaiEffort(effort: LlmEffort): LlmEffortMapping {\n return XAI_EFFORT[effort];\n}\n\n// Anthropic `output_config.effort` — low | medium | high | xhigh | max. No\n// sub-low rung, so `lowest` collapses onto `low`; `highest` reaches `max`.\nconst ANTHROPIC_EFFORT: Record<LlmEffort, LlmEffortMapping> = {\n [EFFORT.LOWEST]: { papered: true, value: \"low\" },\n [EFFORT.LOW]: { papered: false, value: \"low\" },\n [EFFORT.MEDIUM]: { papered: false, value: \"medium\" },\n [EFFORT.HIGH]: { papered: false, value: \"high\" },\n [EFFORT.HIGHEST]: { papered: false, value: \"max\" },\n};\n\nexport function toAnthropicEffort(effort: LlmEffort): LlmEffortMapping {\n return ANTHROPIC_EFFORT[effort];\n}\n\n// Gemini 3.x `thinkingConfig.thinkingLevel` — MINIMAL | LOW | MEDIUM | HIGH. No\n// top rung above HIGH, so `highest` collapses onto HIGH.\nconst GEMINI_THINKING_LEVEL: Record<LlmEffort, LlmEffortMapping> = {\n [EFFORT.LOWEST]: { papered: false, value: \"MINIMAL\" },\n [EFFORT.LOW]: { papered: false, value: \"LOW\" },\n [EFFORT.MEDIUM]: { papered: false, value: \"MEDIUM\" },\n [EFFORT.HIGH]: { papered: false, value: \"HIGH\" },\n [EFFORT.HIGHEST]: { papered: true, value: \"HIGH\" },\n};\n\nexport function toGeminiThinkingLevel(effort: LlmEffort): LlmEffortMapping {\n return GEMINI_THINKING_LEVEL[effort];\n}\n\n// Gemini 2.5 `thinkingConfig.thinkingBudget` — every tier is a distinct token\n// budget, so nothing is papered over. Floor (512) clears every 2.5 minimum;\n// ceiling (24,576) is valid across 2.5 Pro (max 32,768) and Flash (max 24,576).\nconst GEMINI_THINKING_BUDGET: Record<LlmEffort, number> = {\n [EFFORT.LOWEST]: 512,\n [EFFORT.LOW]: 4096,\n [EFFORT.MEDIUM]: 8192,\n [EFFORT.HIGH]: 16384,\n [EFFORT.HIGHEST]: 24576,\n};\n\nexport function toGeminiThinkingBudget(\n effort: LlmEffort,\n): LlmEffortMapping<number> {\n return { papered: false, value: GEMINI_THINKING_BUDGET[effort] };\n}\n\n// Fireworks `reasoning_effort` — low | medium | high. Accepted on every model\n// (the API no-ops where unsupported). No sub-low or top rung, so `lowest`\n// collapses onto `low` and `highest` onto `high`.\nconst FIREWORKS_EFFORT: Record<LlmEffort, LlmEffortMapping> = {\n [EFFORT.LOWEST]: { papered: true, value: \"low\" },\n [EFFORT.LOW]: { papered: false, value: \"low\" },\n [EFFORT.MEDIUM]: { papered: false, value: \"medium\" },\n [EFFORT.HIGH]: { papered: false, value: \"high\" },\n [EFFORT.HIGHEST]: { papered: true, value: \"high\" },\n};\n\nexport function toFireworksEffort(effort: LlmEffort): LlmEffortMapping {\n return FIREWORKS_EFFORT[effort];\n}\n\n// OpenRouter `reasoning.effort` — accepts the full minimal..xhigh ladder and\n// maps to the routed provider's nearest supported level itself, so nothing is\n// papered here.\nconst OPENROUTER_EFFORT: Record<LlmEffort, string> = {\n [EFFORT.LOWEST]: \"minimal\",\n [EFFORT.LOW]: \"low\",\n [EFFORT.MEDIUM]: \"medium\",\n [EFFORT.HIGH]: \"high\",\n [EFFORT.HIGHEST]: \"xhigh\",\n};\n\nexport function toOpenRouterEffort(effort: LlmEffort): LlmEffortMapping {\n return { papered: false, value: OPENROUTER_EFFORT[effort] };\n}\n","import { LlmUsage } from \"./LlmProvider.interface.js\";\n\n//\n//\n// Types\n//\n\nexport enum LlmStreamChunkType {\n Done = \"done\",\n Error = \"error\",\n Text = \"text\",\n ToolCall = \"tool_call\",\n ToolResult = \"tool_result\",\n}\n\nexport interface LlmStreamChunkText {\n type: LlmStreamChunkType.Text;\n content: string;\n}\n\nexport interface LlmStreamChunkToolCall {\n type: LlmStreamChunkType.ToolCall;\n toolCall: {\n id: string;\n name: string;\n arguments: string;\n /** Provider-specific metadata preserved through tool-call roundtrip */\n metadata?: Record<string, unknown>;\n };\n}\n\nexport interface LlmStreamChunkToolResult {\n type: LlmStreamChunkType.ToolResult;\n toolResult: {\n id: string;\n name: string;\n result: unknown;\n };\n}\n\nexport interface LlmStreamChunkDone {\n type: LlmStreamChunkType.Done;\n usage: LlmUsage;\n}\n\nexport interface LlmStreamChunkError {\n type: LlmStreamChunkType.Error;\n error: {\n detail?: string;\n status: number | string;\n title: string;\n };\n}\n\nexport type LlmStreamChunk =\n | LlmStreamChunkDone\n | LlmStreamChunkError\n | LlmStreamChunkText\n | LlmStreamChunkToolCall\n | LlmStreamChunkToolResult;\n","import { JsonObject } from \"@jaypie/types\";\n\nimport { type LlmEffort } from \"../constants.js\";\n\nimport {\n LlmCache,\n LlmHistory,\n LlmMessageType,\n LlmOperateOptions,\n LlmUsageItem,\n} from \"../types/LlmProvider.interface.js\";\nimport { Toolkit } from \"../tools/Toolkit.class.js\";\n\n//\n//\n// Provider-Agnostic Types\n//\n\n/**\n * Standardized tool call representation across providers\n */\nexport interface StandardToolCall {\n /** Unique identifier for this tool call */\n callId: string;\n /** Name of the tool being called */\n name: string;\n /** JSON string of arguments */\n arguments: string;\n /** Original provider-specific tool call object */\n raw: unknown;\n}\n\n/**\n * Standardized tool result to send back to the provider\n */\nexport interface StandardToolResult {\n /** The call ID this result corresponds to */\n callId: string;\n /** JSON string of the result */\n output: string;\n /** Whether the tool call was successful */\n success: boolean;\n /** Error message if the tool call failed */\n error?: string;\n}\n\n/**\n * Parsed response from a provider API call\n */\nexport interface ParsedResponse {\n /** The text content of the response, if any */\n content?: string | JsonObject;\n /** Whether the response contains tool calls */\n hasToolCalls: boolean;\n /** The stop reason from the provider */\n stopReason?: string;\n /** Usage information for this response */\n usage?: LlmUsageItem;\n /** Raw provider response for storage */\n raw: unknown;\n}\n\n/**\n * Context passed to hooks and utilities during the operate loop\n */\nexport interface OperateContext {\n /** The hooks configuration */\n hooks: LlmOperateOptions[\"hooks\"];\n /** The operate options */\n options: LlmOperateOptions;\n}\n\n//\n//\n// Provider Request/Response Types\n//\n\n/**\n * Provider-agnostic request options\n * Each adapter will convert this to provider-specific format\n */\nexport interface OperateRequest {\n /** The model to use */\n model: string;\n /** The conversation history/messages */\n messages: LlmHistory;\n /** System instructions (if separate from messages) */\n system?: string;\n /** Additional instructions to append */\n instructions?: string;\n /** Tools available for the model */\n tools?: ProviderToolDefinition[];\n /** Structured output format */\n format?: JsonObject;\n /** Normalized reasoning effort; adapters translate to provider-native control */\n effort?: LlmEffort;\n /** Provider-specific options */\n providerOptions?: JsonObject;\n /**\n * Prompt-caching control for the stable prefix (system + tools). `true`/\n * omitted = enabled@5m, `false`/`0` = disabled, `\"5m\"`/`\"1h\"` = enabled@ttl.\n */\n cache?: LlmCache;\n /** Whether the request will execute over a streaming transport */\n stream?: boolean;\n /** Sampling temperature (0-2 for most providers) */\n temperature?: number;\n /**\n * Set by OperateLoop on a corrective turn after a format request came back\n * as prose. Adapters that support the retry (see\n * `ProviderAdapter.supportsStructuredOutputRetry`) should offer only the\n * structured-output mechanism on this turn.\n */\n structuredOutputRetry?: boolean;\n /** User identifier for tracking */\n user?: string;\n}\n\n/**\n * Tool definition in provider-agnostic format\n */\nexport interface ProviderToolDefinition {\n /** Tool name */\n name: string;\n /** Tool description */\n description: string;\n /** JSON Schema for parameters */\n parameters: JsonObject;\n}\n\n//\n//\n// Error Classification Types\n//\n\n/**\n * Categories of errors for retry logic\n */\nexport enum ErrorCategory {\n /** Error is transient and can be retried */\n Retryable = \"retryable\",\n /** Error is due to short-term rate limiting (retry after a delay) */\n RateLimit = \"rate_limit\",\n /**\n * Provider quota is exhausted or the account cannot be billed\n * (insufficient funds, daily quota, plan limit). Terminal and actionable —\n * retrying within the request budget will not help.\n */\n Quota = \"quota\",\n /** Error cannot be recovered from */\n Unrecoverable = \"unrecoverable\",\n /** Error type is unknown */\n Unknown = \"unknown\",\n}\n\n/**\n * Classified error with metadata\n */\nexport interface ClassifiedError {\n /** The original error */\n error: unknown;\n /** Category of the error */\n category: ErrorCategory;\n /** Whether a retry should be attempted */\n shouldRetry: boolean;\n /** Suggested delay before retry (if applicable) */\n suggestedDelayMs?: number;\n /**\n * For {@link ErrorCategory.Quota}, distinguishes an exhausted usage quota\n * from an account that cannot be billed (insufficient funds).\n */\n reason?: \"quota\" | \"billing\";\n}\n\n//\n//\n// Operate Loop State\n//\n\n// Import ResponseBuilder for type declaration\nimport type { ResponseBuilder } from \"./response/ResponseBuilder.js\";\n\n/**\n * Internal state of the operate loop\n */\nexport interface OperateLoopState {\n /** Count of consecutive tool errors (resets on success) */\n consecutiveToolErrors: number;\n /** Set when the loop has taken a corrective structured-output turn */\n structuredOutputRetry?: boolean;\n /** Current conversation input/messages */\n currentInput: LlmHistory;\n /** Current turn number (0-indexed, incremented at start of each turn) */\n currentTurn: number;\n /** Formatted output schema for structured output */\n formattedFormat?: JsonObject;\n /** Stop reason from the most recent model response */\n lastStopReason?: string;\n /** Model-request retries across all turns (exchange envelope) */\n retries: number;\n /** Formatted tools for the provider */\n formattedTools?: ProviderToolDefinition[];\n /** Maximum allowed turns */\n maxTurns: number;\n /** Response builder instance */\n responseBuilder: ResponseBuilder;\n /** Names of tool calls executed across all turns (report tally) */\n toolCallNames: string[];\n /** The toolkit for tool calls */\n toolkit?: Toolkit;\n}\n\n//\n//\n// Message Type Constants\n//\n\n/**\n * Re-export message type for convenience in adapters\n */\nexport { LlmMessageType };\n","/**\n * Transient network error detection utility.\n *\n * Detects low-level Node.js/undici network errors that indicate\n * a temporary network issue (not a provider API error).\n * These errors should always be retried.\n */\n\n//\n//\n// Constants\n//\n\n/** Error codes from Node.js net/dns subsystems that indicate transient failures */\nconst TRANSIENT_ERROR_CODES = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EAI_AGAIN\",\n \"ENETRESET\",\n \"ENETUNREACH\",\n \"ENOTFOUND\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n]);\n\n/** Substrings in error messages that indicate transient network issues */\nconst TRANSIENT_MESSAGE_PATTERNS = [\n \"network\",\n \"socket hang up\",\n \"terminated\",\n] as const;\n\n//\n//\n// Helpers\n//\n\n/**\n * Check a single error (without walking the cause chain)\n */\nfunction matchesSingleError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n\n // Check error code (e.g., ECONNRESET)\n const code = (error as { code?: string }).code;\n if (code && TRANSIENT_ERROR_CODES.has(code)) {\n return true;\n }\n\n // Check error message for transient patterns\n const message = error.message.toLowerCase();\n for (const pattern of TRANSIENT_MESSAGE_PATTERNS) {\n if (message.includes(pattern)) {\n return true;\n }\n }\n\n return false;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Detect transient network errors by inspecting the error and its cause chain.\n *\n * Undici (Node.js fetch) wraps low-level errors like ECONNRESET inside\n * `TypeError: terminated`. This function recursively walks `error.cause`\n * to detect these wrapped errors.\n *\n * @param error - The error to inspect\n * @returns true if the error (or any cause in its chain) is a transient network error\n */\nexport function isTransientNetworkError(error: unknown): boolean {\n let current: unknown = error;\n\n while (current) {\n if (matchesSingleError(current)) {\n return true;\n }\n\n // Walk the cause chain (cause is ES2022, cast for compatibility)\n const cause = (current as { cause?: unknown }).cause;\n if (current instanceof Error && cause) {\n current = cause;\n } else {\n break;\n }\n }\n\n return false;\n}\n","import { ClassifiedError, ErrorCategory } from \"../operate/types.js\";\n\n//\n//\n// Constants\n//\n\n/**\n * Transient structured-output compile failures. The provider caches the\n * compiled grammar after a successful compile, so an immediate retry of the\n * identical request typically succeeds (issue #422).\n */\nconst RETRYABLE_MESSAGE_PATTERNS = [\n \"grammar compilation timed out\",\n \"grammar compilation timeout\",\n] as const;\n\n/** Billing / insufficient-funds signals — the account cannot be charged. */\nconst BILLING_MESSAGE_PATTERNS = [\n \"insufficient_quota\",\n \"insufficient funds\",\n \"insufficient credit\",\n \"credit balance\",\n \"billing\",\n \"payment required\",\n \"plan and billing\",\n] as const;\n\n/** Exhausted usage quota (per-day / per-model limits). */\nconst QUOTA_MESSAGE_PATTERNS = [\n \"quota exceeded\",\n \"exceeded your current quota\",\n \"resource_exhausted\",\n \"quota_exceeded\",\n] as const;\n\n//\n//\n// Helpers\n//\n\nfunction extractMessage(error: unknown): string {\n if (error instanceof Error) return error.message.toLowerCase();\n if (typeof error === \"string\") return error.toLowerCase();\n if (error && typeof error === \"object\") {\n const message = (error as { message?: unknown }).message;\n if (typeof message === \"string\") return message.toLowerCase();\n }\n return \"\";\n}\n\n//\n//\n// Main\n//\n\n/**\n * Shared, provider-agnostic first pass over an error. Returns a\n * {@link ClassifiedError} when the message unambiguously identifies a\n * cross-provider condition (retryable structured-output timeout, exhausted\n * quota, or a billing failure), or `undefined` to defer to the adapter's own\n * status/name classification.\n *\n * Adapters call this before their existing logic so that, for example, a\n * `429` carrying a daily-quota message is classified as {@link\n * ErrorCategory.Quota} rather than {@link ErrorCategory.RateLimit}.\n */\nexport function classifyProviderError(\n error: unknown,\n): ClassifiedError | undefined {\n const message = extractMessage(error);\n if (!message) return undefined;\n\n for (const pattern of RETRYABLE_MESSAGE_PATTERNS) {\n if (message.includes(pattern)) {\n return { category: ErrorCategory.Retryable, error, shouldRetry: true };\n }\n }\n\n for (const pattern of BILLING_MESSAGE_PATTERNS) {\n if (message.includes(pattern)) {\n return {\n category: ErrorCategory.Quota,\n error,\n reason: \"billing\",\n shouldRetry: false,\n };\n }\n }\n\n for (const pattern of QUOTA_MESSAGE_PATTERNS) {\n if (message.includes(pattern)) {\n return {\n category: ErrorCategory.Quota,\n error,\n reason: \"quota\",\n shouldRetry: false,\n };\n }\n }\n\n return undefined;\n}\n","import { log } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { paperedEffortMessage, toAnthropicEffort } from \"../../util/effort.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmInputContent,\n LlmMessageType,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n isJsonSchema as isBareJsonSchema,\n naturalZodSchema,\n resolveCache,\n resolveMaxOutputTokens,\n} from \"../../util/index.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { AnthropicClient } from \"../../providers/anthropic/client.js\";\nimport { Anthropic } from \"../../providers/anthropic/types.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\n/**\n * Local extension of the SDK's `MessageCreateParams` to carry\n * `output_config.format` (Anthropic native structured outputs). The SDK 0.71\n * shipped with the older `output_format` field which the API has since\n * deprecated in favor of `output_config.format`. We send the new shape via\n * an untyped passthrough so callers don't need a newer SDK; remove this\n * extension once the SDK types `output_config` directly.\n */\ntype AnthropicRequestParams = Anthropic.MessageCreateParams & {\n output_config?: {\n effort?: string;\n format?: {\n type: \"json_schema\";\n schema: JsonObject;\n };\n };\n};\n\n/**\n * Whether `output_config.effort` may be sent for this model. Anthropic added\n * the effort control on the Claude 4.5 line and up (the 5 family); older models\n * reject it. Parsing major/minor avoids matching a minor \"5\" in legacy ids\n * like `claude-3-5-sonnet`.\n */\nfunction supportsAnthropicEffort(model: string): boolean {\n const match = model.match(/claude-[a-z]+-(\\d+)(?:-(\\d+))?/);\n if (!match) return false;\n const major = Number(match[1]);\n const minor = match[2] !== undefined ? Number(match[2]) : 0;\n if (major >= 5) return true;\n return major === 4 && minor >= 5;\n}\n\n/**\n * Anthropic responses we annotate at receive time so downstream stateless\n * methods (`hasStructuredOutput`, `extractStructuredOutput`) can tell whether\n * the request asked for structured output without re-threading the request.\n */\ntype AnnotatedAnthropicMessage = Anthropic.Message & {\n __jaypieStructuredOutput?: boolean;\n};\n\nconst STRUCTURED_OUTPUT_NON_PARSE_STOP_REASONS = new Set([\n \"refusal\",\n \"max_tokens\",\n]);\n\n// Regular expression to parse data URLs: data:mime/type;base64,data\nconst DATA_URL_REGEX = /^data:([^;]+);base64,(.+)$/;\n\n// String formats accepted by Anthropic's structured-output grammar compiler.\n// Other formats are stripped (move to description) so the API does not 400.\nconst SUPPORTED_STRING_FORMATS = new Set([\n \"date\",\n \"date-time\",\n \"duration\",\n \"email\",\n \"hostname\",\n \"ipv4\",\n \"ipv6\",\n \"time\",\n \"uri\",\n \"uuid\",\n]);\n\n// Top-level keywords stripped wholesale before sending: not part of the spec\n// the API enforces and the validator can reject them.\nconst STRIPPED_TOP_LEVEL_KEYWORDS = new Set([\"$schema\", \"$id\"]);\n\n// Keywords Anthropic's structured-output grammar does not support. They are\n// removed from the schema and appended to `description` so the model still\n// sees the intent.\nconst UNSUPPORTED_CONSTRAINT_KEYWORDS = new Set([\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"uniqueItems\",\n]);\n\n/**\n * Recursively transform a JSON Schema into the strict shape Anthropic's\n * structured-output grammar accepts: object types must have\n * `additionalProperties: false`, unsupported numeric/string/array\n * constraints are appended to `description`, and unsupported string\n * formats are stripped. Mirrors @anthropic-ai/sdk's `transformJSONSchema`\n * but inline so we do not take a runtime dependency on the optional\n * peer SDK.\n */\nfunction sanitizeJsonSchemaForAnthropic(\n schema: JsonObject,\n isRoot = true,\n): JsonObject {\n const result: JsonObject = {};\n const carriedConstraints: string[] = [];\n\n for (const [key, value] of Object.entries(schema)) {\n if (isRoot && STRIPPED_TOP_LEVEL_KEYWORDS.has(key)) {\n continue;\n }\n\n if (UNSUPPORTED_CONSTRAINT_KEYWORDS.has(key)) {\n carriedConstraints.push(`${key}: ${JSON.stringify(value)}`);\n continue;\n }\n\n if (key === \"format\" && typeof value === \"string\") {\n if (SUPPORTED_STRING_FORMATS.has(value)) {\n result[key] = value;\n } else {\n carriedConstraints.push(`format: ${JSON.stringify(value)}`);\n }\n continue;\n }\n\n if (key === \"minItems\" && typeof value === \"number\") {\n if (value === 0 || value === 1) {\n result[key] = value;\n } else {\n carriedConstraints.push(`minItems: ${value}`);\n }\n continue;\n }\n\n if (\n key === \"properties\" &&\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n ) {\n const transformedProps: JsonObject = {};\n for (const [propName, propSchema] of Object.entries(\n value as JsonObject,\n )) {\n transformedProps[propName] = isJsonSchema(propSchema)\n ? sanitizeJsonSchemaForAnthropic(propSchema, false)\n : propSchema;\n }\n result[key] = transformedProps;\n continue;\n }\n\n if (\n (key === \"items\" || key === \"additionalItems\" || key === \"contains\") &&\n isJsonSchema(value)\n ) {\n result[key] = sanitizeJsonSchemaForAnthropic(value, false);\n continue;\n }\n\n if (\n (key === \"anyOf\" || key === \"oneOf\" || key === \"allOf\") &&\n Array.isArray(value)\n ) {\n const targetKey = key === \"oneOf\" ? \"anyOf\" : key;\n result[targetKey] = value.map((entry) =>\n isJsonSchema(entry)\n ? sanitizeJsonSchemaForAnthropic(entry, false)\n : entry,\n );\n continue;\n }\n\n if (key === \"$defs\" && value && typeof value === \"object\") {\n const transformedDefs: JsonObject = {};\n for (const [defName, defSchema] of Object.entries(value as JsonObject)) {\n transformedDefs[defName] = isJsonSchema(defSchema)\n ? sanitizeJsonSchemaForAnthropic(defSchema, false)\n : defSchema;\n }\n result[key] = transformedDefs;\n continue;\n }\n\n if (key === \"additionalProperties\") {\n // Always force `false` on objects below; ignore caller-supplied value.\n continue;\n }\n\n result[key] = value;\n }\n\n if (result.type === \"object\") {\n result.additionalProperties = false;\n }\n\n if (carriedConstraints.length > 0) {\n const existing =\n typeof result.description === \"string\" ? result.description : \"\";\n const suffix = `{${carriedConstraints.join(\", \")}}`;\n result.description = existing ? `${existing}\\n\\n${suffix}` : suffix;\n }\n\n return result;\n}\n\nfunction isJsonSchema(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Parse a data URL into its components\n */\nfunction parseDataUrl(\n dataUrl: string,\n): { data: string; mediaType: string } | null {\n const match = dataUrl.match(DATA_URL_REGEX);\n if (!match) return null;\n return { mediaType: match[1], data: match[2] };\n}\n\n/**\n * Convert standardized content items to Anthropic format\n */\nfunction convertContentToAnthropic(\n content: string | LlmInputContent[],\n): Anthropic.ContentBlockParam[] | string {\n if (typeof content === \"string\") {\n return content;\n }\n\n return content.map((item): Anthropic.ContentBlockParam => {\n // Text content\n if (item.type === LlmMessageType.InputText) {\n return { type: \"text\", text: item.text };\n }\n\n // Image content\n if (item.type === LlmMessageType.InputImage) {\n const imageUrl = item.image_url || \"\";\n const parsed = parseDataUrl(imageUrl);\n if (parsed) {\n return {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type:\n parsed.mediaType as Anthropic.Base64ImageSource[\"media_type\"],\n data: parsed.data,\n },\n };\n }\n // Fallback for URL-based images (not base64)\n return {\n type: \"image\",\n source: {\n type: \"url\",\n url: imageUrl,\n },\n };\n }\n\n // File/Document content (PDF, etc.)\n if (item.type === LlmMessageType.InputFile) {\n const fileData = typeof item.file_data === \"string\" ? item.file_data : \"\";\n const parsed = parseDataUrl(fileData);\n if (parsed) {\n return {\n type: \"document\",\n source: {\n type: \"base64\",\n media_type:\n parsed.mediaType as Anthropic.Base64PDFSource[\"media_type\"],\n data: parsed.data,\n },\n };\n }\n // Fallback - return as text with the filename\n return { type: \"text\", text: `[File: ${item.filename || \"unknown\"}]` };\n }\n\n // Unknown type - return as text\n return { type: \"text\", text: JSON.stringify(item) };\n });\n}\n\n// Error names for classification (using string names since SDK is optional)\nconst RETRYABLE_ERROR_NAMES = [\n \"APIConnectionError\",\n \"APIConnectionTimeoutError\",\n \"InternalServerError\",\n];\n\nconst NOT_RETRYABLE_ERROR_NAMES = [\n \"AuthenticationError\",\n \"BadRequestError\",\n \"NotFoundError\",\n \"PermissionDeniedError\",\n];\n\n// Models known not to accept `temperature`.\n// Patterns (not exact names) so dated variants and future releases are covered\n// without code changes — Anthropic is trending toward removing temperature on\n// newer Claude models.\nconst MODELS_WITHOUT_TEMPERATURE: RegExp[] = [\n /^claude-opus-4-[789]/,\n /^claude-opus-[5-9]/,\n];\n\nfunction isTemperatureDeprecationError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n message?: string;\n error?: { message?: string };\n };\n const name = (error as Error)?.constructor?.name;\n if (name !== \"BadRequestError\" && err.status !== 400) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) => m.toLowerCase().includes(\"temperature\"));\n}\n\n/**\n * Detect 400 errors that indicate the model itself does not support native\n * structured outputs (`output_config.format`). Citations + structured output\n * is also a 400 case but is a caller error rather than a model-capability\n * gap, so we explicitly skip it to avoid masking the real problem under a\n * tool-emulation retry. The deprecated-`output_format` 400 (API renamed the\n * field) is also explicitly excluded — that's a code-path bug, not a model\n * gap; it should propagate so we notice and fix it.\n */\nfunction isStructuredOutputUnsupportedError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n message?: string;\n error?: { message?: string };\n };\n const name = (error as Error)?.constructor?.name;\n if (name !== \"BadRequestError\" && err.status !== 400) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n if (messages.some((m) => /citation/i.test(m))) return false;\n if (messages.some((m) => /deprecated/i.test(m))) return false;\n return messages.some((m) =>\n /output_config|output_format|json[_ ]schema|structured/i.test(m),\n );\n}\n\n//\n//\n// Main\n//\n\n/**\n * AnthropicAdapter implements the ProviderAdapter interface for Anthropic's API.\n * It handles request building, response parsing, and error classification\n * specific to Anthropic's Messages API.\n */\nexport class AnthropicAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.ANTHROPIC.NAME;\n readonly defaultModel = PROVIDER.ANTHROPIC.DEFAULT;\n\n // Session-level cache of models observed to reject `temperature` at runtime.\n // Populated by executeRequest on 400 errors so repeat calls skip the param.\n private runtimeNoTemperatureModels = new Set<string>();\n\n // Session-level cache of models observed to reject `output_format`. When a\n // model is in this set, buildRequest engages the legacy fake-tool path\n // instead of native structured output.\n private runtimeNoStructuredOutputModels = new Set<string>();\n\n rememberModelRejectsTemperature(model: string): void {\n this.runtimeNoTemperatureModels.add(model);\n }\n\n clearRuntimeNoTemperatureModels(): void {\n this.runtimeNoTemperatureModels.clear();\n }\n\n rememberModelRejectsStructuredOutput(model: string): void {\n this.runtimeNoStructuredOutputModels.add(model);\n }\n\n clearRuntimeNoStructuredOutputModels(): void {\n this.runtimeNoStructuredOutputModels.clear();\n }\n\n private supportsTemperature(model: string): boolean {\n if (this.runtimeNoTemperatureModels.has(model)) return false;\n return !MODELS_WITHOUT_TEMPERATURE.some((pattern) => pattern.test(model));\n }\n\n private supportsStructuredOutput(model: string): boolean {\n return !this.runtimeNoStructuredOutputModels.has(model);\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): AnthropicRequestParams {\n // Convert messages to Anthropic format\n // Handle different message types: regular messages, function calls, and function outputs\n const messages: Anthropic.MessageParam[] = [];\n\n for (const msg of request.messages) {\n const typedMsg = msg as {\n type?: string;\n role?: string;\n content?: string | LlmInputContent[];\n name?: string;\n arguments?: string;\n call_id?: string;\n output?: string;\n };\n\n // Skip system messages - Anthropic only accepts system as a top-level field\n if (typedMsg.role === \"system\") {\n continue;\n }\n\n // Handle FunctionCall messages - convert to assistant message with tool_use\n if (typedMsg.type === LlmMessageType.FunctionCall) {\n messages.push({\n role: \"assistant\",\n content: [\n {\n type: \"tool_use\",\n id: typedMsg.call_id || \"\",\n name: typedMsg.name || \"\",\n input: JSON.parse(typedMsg.arguments || \"{}\"),\n },\n ],\n });\n continue;\n }\n\n // Handle FunctionCallOutput messages - convert to user message with tool_result\n if (typedMsg.type === LlmMessageType.FunctionCallOutput) {\n messages.push({\n role: \"user\",\n content: [\n {\n type: \"tool_result\",\n tool_use_id: typedMsg.call_id || \"\",\n content: typedMsg.output || \"\",\n },\n ],\n });\n continue;\n }\n\n // Handle regular messages with role and content\n if (typedMsg.role && typedMsg.content !== undefined) {\n messages.push({\n role: typedMsg.role as \"user\" | \"assistant\",\n content: convertContentToAnthropic(typedMsg.content),\n } as Anthropic.MessageParam);\n }\n }\n\n // Append instructions to last message if provided\n if (request.instructions && messages.length > 0) {\n const lastMsg = messages[messages.length - 1];\n if (typeof lastMsg.content === \"string\") {\n lastMsg.content = lastMsg.content + \"\\n\\n\" + request.instructions;\n }\n }\n\n const model = (request.model ||\n this.defaultModel) as Anthropic.MessageCreateParams[\"model\"];\n const anthropicRequest: AnthropicRequestParams = {\n model,\n messages,\n max_tokens:\n resolveMaxOutputTokens(model as string, { stream: request.stream }) ??\n PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n stream: false,\n };\n\n const cache = resolveCache(request.cache);\n const cacheControl: Anthropic.CacheControlEphemeral | undefined =\n cache.enabled\n ? {\n type: \"ephemeral\",\n ...(cache.ttl === \"1h\" ? { ttl: \"1h\" as const } : {}),\n }\n : undefined;\n\n if (request.system) {\n // A cache breakpoint on the system block caches tools+system together\n // (render order is tools -> system -> messages).\n anthropicRequest.system = cacheControl\n ? [{ type: \"text\", text: request.system, cache_control: cacheControl }]\n : request.system;\n }\n\n const useFallbackStructuredOutput =\n Boolean(request.format) &&\n !this.supportsStructuredOutput(anthropicRequest.model as string);\n\n const allTools: ProviderToolDefinition[] = request.tools\n ? [...request.tools]\n : [];\n if (useFallbackStructuredOutput && request.format) {\n log.warn(\n `[AnthropicAdapter] Using legacy structured_output tool fallback for model ${anthropicRequest.model as string}; native output_config previously rejected for this model.`,\n );\n allTools.push({\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"Output a structured JSON object, \" +\n \"use this before your final response to give structured outputs to the user\",\n parameters: request.format,\n });\n }\n\n if (allTools.length > 0) {\n anthropicRequest.tools = allTools.map((tool, index) => ({\n name: tool.name,\n description: tool.description,\n input_schema: {\n ...tool.parameters,\n type: \"object\",\n } as Anthropic.Messages.Tool.InputSchema,\n type: \"custom\" as const,\n // Breakpoint on the last tool caches the tool list (which renders\n // before system) when there is no system prompt to anchor it.\n ...(cacheControl && index === allTools.length - 1\n ? { cache_control: cacheControl }\n : {}),\n }));\n\n anthropicRequest.tool_choice = useFallbackStructuredOutput\n ? { type: \"any\" }\n : { type: \"auto\" };\n }\n\n // Native structured output: send schema as `output_config.format`. The\n // legacy tool-emulation path is engaged only as a runtime fallback for\n // models the API has flagged as not supporting native structured output.\n if (request.format && !useFallbackStructuredOutput) {\n anthropicRequest.output_config = {\n format: {\n type: \"json_schema\",\n schema: request.format,\n },\n };\n }\n\n if (request.providerOptions) {\n Object.assign(anthropicRequest, request.providerOptions);\n }\n\n // Normalized reasoning effort -> output_config.effort (merged so a format\n // config above survives). First-class effort wins over providerOptions.\n if (\n request.effort &&\n supportsAnthropicEffort(anthropicRequest.model as string)\n ) {\n const mapping = toAnthropicEffort(request.effort);\n if (mapping.papered) {\n log.debug(\n paperedEffortMessage({\n model: anthropicRequest.model as string,\n provider: this.name,\n requested: request.effort,\n value: mapping.value,\n }),\n );\n }\n anthropicRequest.output_config = {\n ...anthropicRequest.output_config,\n effort: mapping.value,\n };\n }\n\n // First-class temperature takes precedence over providerOptions\n if (request.temperature !== undefined) {\n anthropicRequest.temperature = request.temperature;\n }\n\n // Strip temperature for models that don't support it (denylist + runtime cache)\n if (\n anthropicRequest.temperature !== undefined &&\n !this.supportsTemperature(anthropicRequest.model as string)\n ) {\n delete anthropicRequest.temperature;\n }\n\n return anthropicRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n // outputSchema is part of the interface contract but Anthropic now uses\n // native `output_format` (set in buildRequest), so we no longer inject a\n // synthetic structured-output tool here.\n\n _outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: {\n ...tool.parameters,\n type: \"object\",\n } as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n let jsonSchema: JsonObject;\n\n // Check if schema is already a JsonObject — either the OpenAI-style\n // `{ type: \"json_schema\", ... }` envelope or a bare `{ type: \"object\", properties }` node\n if (\n (typeof schema === \"object\" &&\n schema !== null &&\n !Array.isArray(schema) &&\n (schema as JsonObject).type === \"json_schema\") ||\n isBareJsonSchema(schema)\n ) {\n jsonSchema = structuredClone(schema) as JsonObject;\n jsonSchema.type = \"object\"; // Validator does not recognize \"json_schema\"\n } else {\n // Convert NaturalSchema to JSON schema through Zod\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n jsonSchema = z.toJSONSchema(zodSchema) as JsonObject;\n }\n\n return sanitizeJsonSchemaForAnthropic(jsonSchema);\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<Anthropic.Message> {\n const anthropic = client as AnthropicClient;\n const anthropicRequest = request as AnthropicRequestParams;\n const wantsStructuredOutput = Boolean(anthropicRequest.output_config);\n try {\n const response = (await anthropic.messages.create(\n anthropicRequest as Anthropic.MessageCreateParams,\n signal ? { signal } : undefined,\n )) as AnnotatedAnthropicMessage;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as Anthropic.Message;\n\n // If the model rejected `temperature`, cache it and retry without the param\n if (\n anthropicRequest.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(anthropicRequest.model as string);\n const retryRequest = { ...anthropicRequest };\n delete retryRequest.temperature;\n const response = (await anthropic.messages.create(\n retryRequest as Anthropic.MessageCreateParams,\n signal ? { signal } : undefined,\n )) as AnnotatedAnthropicMessage;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n }\n\n // If the model rejected native structured output, cache it and retry\n // via the legacy fake-tool emulation path.\n if (wantsStructuredOutput && isStructuredOutputUnsupportedError(error)) {\n const model = anthropicRequest.model as string;\n this.rememberModelRejectsStructuredOutput(model);\n log.warn(\n `[AnthropicAdapter] Model ${model} rejected native output_config; falling back to legacy structured_output tool emulation.`,\n );\n const fallbackRequest =\n this.toFallbackStructuredOutputRequest(anthropicRequest);\n return (await anthropic.messages.create(\n fallbackRequest as Anthropic.MessageCreateParams,\n signal ? { signal } : undefined,\n )) as Anthropic.Message;\n }\n\n throw error;\n }\n }\n\n /**\n * Rebuild a structured-output request without `output_format`, swapping in\n * the legacy fake-tool emulation. Used as a runtime fallback when a model\n * rejects native `output_config.format`.\n */\n private toFallbackStructuredOutputRequest(\n request: AnthropicRequestParams,\n ): AnthropicRequestParams {\n const { output_config, ...rest } = request;\n if (!output_config?.format) return request;\n const fallbackRequest: AnthropicRequestParams = { ...rest };\n // Preserve an effort setting; only the structured-output format falls back.\n if (output_config.effort) {\n fallbackRequest.output_config = { effort: output_config.effort };\n }\n const fakeTool = {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"Output a structured JSON object, \" +\n \"use this before your final response to give structured outputs to the user\",\n input_schema: {\n ...output_config.format.schema,\n type: \"object\",\n } as Anthropic.Messages.Tool.InputSchema,\n type: \"custom\" as const,\n };\n fallbackRequest.tools = [...(fallbackRequest.tools ?? []), fakeTool];\n fallbackRequest.tool_choice = { type: \"any\" };\n return fallbackRequest;\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const anthropic = client as AnthropicClient;\n // Preserve `output_config` when passing through to the SDK by typing\n // through the local extension instead of the upstream\n // MessageCreateParams shape.\n let streamRequest = {\n ...(request as AnthropicRequestParams),\n stream: true,\n } as AnthropicRequestParams & { stream: true };\n\n let stream;\n try {\n stream = await anthropic.messages.create(\n streamRequest as Anthropic.MessageCreateParamsStreaming,\n signal ? { signal } : undefined,\n );\n } catch (error) {\n if (\n streamRequest.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(streamRequest.model as string);\n streamRequest = {\n ...streamRequest,\n };\n delete streamRequest.temperature;\n stream = await anthropic.messages.create(\n streamRequest as Anthropic.MessageCreateParamsStreaming,\n signal ? { signal } : undefined,\n );\n } else {\n throw error;\n }\n }\n\n // Track current tool call being built\n let currentToolCall: {\n id: string;\n name: string;\n arguments: string;\n } | null = null;\n\n // Track usage for final chunk\n let inputTokens = 0;\n let outputTokens = 0;\n let thinkingTokens = 0;\n let model = streamRequest.model;\n\n for await (const event of stream) {\n if (event.type === \"message_start\") {\n // Extract initial usage and model info\n const message = event.message;\n if (message.usage) {\n inputTokens = message.usage.input_tokens;\n }\n model = message.model;\n } else if (event.type === \"content_block_start\") {\n const contentBlock = event.content_block;\n if (contentBlock.type === \"tool_use\") {\n // Start building a tool call\n currentToolCall = {\n id: contentBlock.id,\n name: contentBlock.name,\n arguments: \"\",\n };\n }\n } else if (event.type === \"content_block_delta\") {\n const delta = event.delta;\n if (delta.type === \"text_delta\") {\n yield {\n type: LlmStreamChunkType.Text,\n content: delta.text,\n };\n } else if (delta.type === \"input_json_delta\" && currentToolCall) {\n // Accumulate tool call arguments\n currentToolCall.arguments += delta.partial_json;\n }\n } else if (event.type === \"content_block_stop\") {\n // If we were building a tool call, emit it now\n if (currentToolCall) {\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.id,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n currentToolCall = null;\n }\n } else if (event.type === \"message_delta\") {\n // Extract final usage\n if (event.usage) {\n outputTokens = event.usage.output_tokens;\n // Check for thinking tokens in extended thinking responses\n const extendedUsage = event.usage as { thinking_tokens?: number };\n if (extendedUsage.thinking_tokens) {\n thinkingTokens = extendedUsage.thinking_tokens;\n }\n }\n } else if (event.type === \"message_stop\") {\n // Emit done chunk with usage\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: thinkingTokens,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n }\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n _options?: LlmOperateOptions,\n ): ParsedResponse {\n const anthropicResponse = response as Anthropic.Message;\n\n const content = this.extractContent(anthropicResponse);\n const hasToolCalls = anthropicResponse.stop_reason === \"tool_use\";\n\n return {\n content,\n hasToolCalls,\n stopReason: anthropicResponse.stop_reason ?? undefined,\n usage: this.extractUsage(anthropicResponse, anthropicResponse.model),\n raw: anthropicResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const anthropicResponse = response as Anthropic.Message;\n const toolCalls: StandardToolCall[] = [];\n\n for (const block of anthropicResponse.content) {\n if (block.type === \"tool_use\") {\n toolCalls.push({\n callId: block.id,\n name: block.name,\n arguments: JSON.stringify(block.input),\n raw: block,\n });\n }\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const anthropicResponse = response as Anthropic.Message;\n\n // Check for thinking tokens in the usage (extended thinking feature)\n // Anthropic includes thinking tokens in a separate field when enabled\n const usage = anthropicResponse.usage as {\n input_tokens: number;\n output_tokens: number;\n thinking_tokens?: number;\n cache_read_input_tokens?: number;\n cache_creation_input_tokens?: number;\n };\n\n return {\n input: usage.input_tokens,\n output: usage.output_tokens,\n reasoning: usage.thinking_tokens || 0,\n total: usage.input_tokens + usage.output_tokens,\n ...(usage.cache_read_input_tokens !== undefined\n ? { cacheRead: usage.cache_read_input_tokens }\n : {}),\n ...(usage.cache_creation_input_tokens !== undefined\n ? { cacheWrite: usage.cache_creation_input_tokens }\n : {}),\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): Anthropic.ToolResultBlockParam {\n return {\n type: \"tool_result\",\n tool_use_id: toolCall.callId,\n content: result.output,\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): Anthropic.MessageCreateParams {\n const anthropicRequest = request as Anthropic.MessageCreateParams;\n const toolCallRaw = toolCall.raw as Anthropic.ToolUseBlock;\n\n // Add assistant message with the tool use\n anthropicRequest.messages.push({\n role: \"assistant\",\n content: [toolCallRaw],\n });\n\n // Add user message with the tool result\n anthropicRequest.messages.push({\n role: \"user\",\n content: [this.formatToolResult(toolCall, result)],\n });\n\n return anthropicRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const anthropicResponse = response as Anthropic.Message;\n const historyItems: LlmHistory = [];\n\n // Check if this is a tool use response\n if (anthropicResponse.stop_reason === \"tool_use\") {\n // Don't add to history yet - will be added after tool execution\n return historyItems;\n }\n\n // Include thinking blocks for extended thinking support\n // Thinking blocks are preserved in history so extractReasoning can find them\n for (const block of anthropicResponse.content) {\n if (block.type === \"thinking\") {\n // Push raw block - types are loosely checked at runtime\n // This allows extractReasoning to access the thinking property\n historyItems.push(block as unknown as LlmOutputMessage);\n }\n }\n\n // Extract text content for non-tool responses\n const textBlock = anthropicResponse.content.find(\n (block) => block.type === \"text\",\n ) as Anthropic.TextBlock | undefined;\n\n if (textBlock) {\n historyItems.push({\n content: textBlock.text,\n role: PROVIDER.ANTHROPIC.ROLE.ASSISTANT,\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n const errorName = (error as Error)?.constructor?.name;\n\n // Check for rate limit error\n if (errorName === \"RateLimitError\") {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Check for retryable errors\n if (RETRYABLE_ERROR_NAMES.includes(errorName)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Check for non-retryable errors\n if (NOT_RETRYABLE_ERROR_NAMES.includes(errorName)) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n\n // Check for transient network errors (ECONNRESET, etc.)\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Unknown error - treat as potentially retryable\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Provider-Specific Features\n //\n\n isComplete(response: unknown): boolean {\n const anthropicResponse = response as Anthropic.Message;\n return anthropicResponse.stop_reason !== \"tool_use\";\n }\n\n override hasStructuredOutput(response: unknown): boolean {\n const anthropicResponse = response as AnnotatedAnthropicMessage;\n\n // Native path: executeRequest annotates the response when we sent\n // `output_format`, so we can detect intent statelessly.\n if (anthropicResponse.__jaypieStructuredOutput) {\n return this.extractStructuredOutput(response) !== undefined;\n }\n\n // Fallback path: legacy fake-tool emulation, kept for models that the\n // runtime has cached as not supporting `output_format`.\n const lastBlock =\n anthropicResponse.content[anthropicResponse.content.length - 1];\n return (\n lastBlock?.type === \"tool_use\" &&\n (lastBlock as Anthropic.ToolUseBlock).name === STRUCTURED_OUTPUT_TOOL_NAME\n );\n }\n\n override extractStructuredOutput(response: unknown): JsonObject | undefined {\n const anthropicResponse = response as AnnotatedAnthropicMessage;\n\n if (anthropicResponse.__jaypieStructuredOutput) {\n // Refusal and truncation are explicit non-JSON outcomes per Anthropic\n // structured-outputs docs — surface the text upstream instead of\n // forcing a JSON.parse on what is not JSON.\n if (\n anthropicResponse.stop_reason &&\n STRUCTURED_OUTPUT_NON_PARSE_STOP_REASONS.has(\n anthropicResponse.stop_reason,\n )\n ) {\n return undefined;\n }\n\n const textBlock = anthropicResponse.content.find(\n (block) => block.type === \"text\",\n ) as Anthropic.TextBlock | undefined;\n if (!textBlock) return undefined;\n\n try {\n const parsed = JSON.parse(textBlock.text);\n return parsed as JsonObject;\n } catch {\n return undefined;\n }\n }\n\n // Fallback path: legacy fake-tool emulation\n const lastBlock =\n anthropicResponse.content[anthropicResponse.content.length - 1];\n if (\n lastBlock?.type === \"tool_use\" &&\n (lastBlock as Anthropic.ToolUseBlock).name === STRUCTURED_OUTPUT_TOOL_NAME\n ) {\n return (lastBlock as Anthropic.ToolUseBlock).input as JsonObject;\n }\n\n return undefined;\n }\n\n //\n // Private Helpers\n //\n\n private extractContent(\n response: Anthropic.Message,\n ): string | JsonObject | undefined {\n // Check for structured output first\n if (this.hasStructuredOutput(response)) {\n return this.extractStructuredOutput(response);\n }\n\n // Extract text content\n const textBlock = response.content.find(\n (block) => block.type === \"text\",\n ) as Anthropic.TextBlock | undefined;\n\n return textBlock?.text;\n }\n}\n\n// Export singleton instance\nexport const anthropicAdapter = new AnthropicAdapter();\n","import type {\n BedrockRuntimeClient,\n ConverseCommandInput,\n ConverseCommandOutput,\n DocumentFormat,\n} from \"@aws-sdk/client-bedrock-runtime\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmInputContent,\n LlmMessageType,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n isJsonSchema,\n naturalZodSchema,\n resolveCache,\n} from \"../../util/index.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\n\n//\n//\n// Types\n//\n\ntype BedrockContentBlock =\n | { text: string }\n | { toolUse: { toolUseId: string; name: string; input: JsonObject } }\n | { toolResult: { toolUseId: string; content: Array<{ text: string }> } }\n | { image: { format: string; source: { bytes: Uint8Array } } }\n | {\n document: {\n format: DocumentFormat;\n name: string;\n source: { bytes: Uint8Array };\n };\n };\n\ntype BedrockMessage = {\n role: \"user\" | \"assistant\";\n content: BedrockContentBlock[];\n};\n\ntype BedrockRequest = Omit<ConverseCommandInput, \"messages\"> & {\n messages: BedrockMessage[];\n};\n\n//\n//\n// Helpers\n//\n\n// Regular expression to parse data URLs\nconst DATA_URL_REGEX = /^data:([^;]+);base64,(.+)$/;\n\nconst MIME_TO_DOCUMENT_FORMAT: Record<string, DocumentFormat> = {\n \"application/pdf\": \"pdf\",\n \"text/csv\": \"csv\",\n \"application/msword\": \"doc\",\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":\n \"docx\",\n \"application/vnd.ms-excel\": \"xls\",\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": \"xlsx\",\n \"text/html\": \"html\",\n \"text/plain\": \"txt\",\n \"text/markdown\": \"md\",\n};\n\nfunction convertContentToBedrock(\n content: string | LlmInputContent[],\n): BedrockContentBlock[] {\n if (typeof content === \"string\") {\n return [{ text: content }];\n }\n\n return content.map((item): BedrockContentBlock => {\n if (item.type === LlmMessageType.InputText) {\n return { text: item.text };\n }\n\n if (item.type === LlmMessageType.InputImage) {\n const imageUrl = item.image_url || \"\";\n const match = imageUrl.match(DATA_URL_REGEX);\n if (match) {\n const format = match[1].split(\"/\")[1] || \"jpeg\";\n const bytes = Buffer.from(match[2], \"base64\");\n return {\n image: {\n format,\n source: { bytes: new Uint8Array(bytes) },\n },\n };\n }\n return { text: `[Image: ${imageUrl}]` };\n }\n\n if (item.type === LlmMessageType.InputFile) {\n const fileData = typeof item.file_data === \"string\" ? item.file_data : \"\";\n const match = fileData.match(DATA_URL_REGEX);\n if (match) {\n const mimeType = match[1];\n const documentFormat = MIME_TO_DOCUMENT_FORMAT[mimeType];\n if (documentFormat) {\n const bytes = Buffer.from(match[2], \"base64\");\n const rawName = item.filename || \"document\";\n const name = rawName.replace(/[^a-zA-Z0-9 \\-()[\\]]/g, \"_\");\n return {\n document: {\n format: documentFormat,\n name,\n source: { bytes: new Uint8Array(bytes) },\n },\n };\n }\n }\n return { text: `[File: ${item.filename || \"unknown\"}]` };\n }\n\n return { text: JSON.stringify(item) };\n });\n}\n\n//\n//\n// Constants / helpers\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\ntype AnnotatedBedrockResponse = ConverseCommandOutput & {\n __jaypieStructuredOutput?: boolean;\n};\n\nfunction isOutputConfigUnsupportedError(error: unknown): boolean {\n const msg = (error as Error)?.message ?? \"\";\n return /outputConfig|output_config/i.test(msg);\n}\n\nfunction isTemperatureDeprecationError(error: unknown): boolean {\n const msg = (error as Error)?.message ?? \"\";\n return /temperature.*deprecated|deprecated.*temperature/i.test(msg);\n}\n\nfunction isCachePointUnsupportedError(error: unknown): boolean {\n const name = (error as Error)?.constructor?.name ?? \"\";\n const msg = (error as Error)?.message ?? \"\";\n // A model that cannot cache rejects the cachePoint block with a\n // ValidationException naming caching / cachePoint.\n return (\n /ValidationException|invalid|not support/i.test(name + \" \" + msg) &&\n /cachePoint|cache_point|prompt caching|caching/i.test(msg)\n );\n}\n\nfunction extractJson(text: string): JsonObject | undefined {\n // Try direct parse first\n try {\n const parsed = JSON.parse(text) as JsonObject;\n if (typeof parsed === \"object\" && parsed !== null) return parsed;\n } catch {\n // fall through\n }\n // Try stripping markdown code fences\n const fenceMatch = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (fenceMatch) {\n try {\n const parsed = JSON.parse(fenceMatch[1].trim()) as JsonObject;\n if (typeof parsed === \"object\" && parsed !== null) return parsed;\n } catch {\n // fall through\n }\n }\n return undefined;\n}\n\n//\n//\n// Main\n//\n\nexport class BedrockAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.BEDROCK.NAME;\n readonly defaultModel = PROVIDER.BEDROCK.DEFAULT;\n\n private _modelsFallbackToStructuredOutputTool = new Set<string>();\n private _modelsWithoutTemperature = new Set<string>();\n private _modelsWithoutCachePoint = new Set<string>();\n\n private rememberModelRejectsCachePoint(model: string): void {\n this._modelsWithoutCachePoint.add(model);\n }\n\n private supportsCachePoint(model: string): boolean {\n return !this._modelsWithoutCachePoint.has(model);\n }\n\n private rememberModelRejectsOutputConfig(model: string): void {\n this._modelsFallbackToStructuredOutputTool.add(model);\n }\n\n private useFakeToolForStructuredOutput(model: string): boolean {\n return this._modelsFallbackToStructuredOutputTool.has(model);\n }\n\n private rememberModelRejectsTemperature(model: string): void {\n this._modelsWithoutTemperature.add(model);\n }\n\n private supportsTemperature(model: string): boolean {\n return !this._modelsWithoutTemperature.has(model);\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): BedrockRequest {\n const messages: BedrockMessage[] = [];\n\n for (const msg of request.messages) {\n const typedMsg = msg as {\n type?: string;\n role?: string;\n content?: string | LlmInputContent[];\n name?: string;\n arguments?: string;\n call_id?: string;\n output?: string;\n };\n\n if (typedMsg.role === \"system\") continue;\n\n if (typedMsg.type === LlmMessageType.FunctionCall) {\n let parsedInput: JsonObject;\n try {\n parsedInput = JSON.parse(typedMsg.arguments || \"{}\") as JsonObject;\n } catch {\n parsedInput = {};\n }\n messages.push({\n role: \"assistant\",\n content: [\n {\n toolUse: {\n toolUseId: typedMsg.call_id || \"\",\n name: typedMsg.name || \"\",\n input: parsedInput,\n },\n },\n ],\n });\n continue;\n }\n\n if (typedMsg.type === LlmMessageType.FunctionCallOutput) {\n messages.push({\n role: \"user\",\n content: [\n {\n toolResult: {\n toolUseId: typedMsg.call_id || \"\",\n content: [{ text: typedMsg.output || \"\" }],\n },\n },\n ],\n });\n continue;\n }\n\n if (typedMsg.role && typedMsg.content !== undefined) {\n messages.push({\n role: typedMsg.role as \"user\" | \"assistant\",\n content: convertContentToBedrock(typedMsg.content),\n });\n }\n }\n\n const model = request.model || this.defaultModel;\n const bedrockRequest: BedrockRequest = {\n modelId: model,\n messages,\n inferenceConfig: {\n maxTokens: 4096,\n },\n };\n\n if (request.system) {\n bedrockRequest.system = [{ text: request.system }];\n }\n\n if (request.temperature !== undefined && this.supportsTemperature(model)) {\n bedrockRequest.inferenceConfig = {\n ...bedrockRequest.inferenceConfig,\n temperature: request.temperature,\n };\n }\n\n if (request.tools && request.tools.length > 0) {\n bedrockRequest.toolConfig = {\n tools: request.tools.map((tool) => ({\n toolSpec: {\n name: tool.name,\n description: tool.description,\n inputSchema: {\n json: tool.parameters as Record<string, unknown>,\n },\n },\n })) as NonNullable<ConverseCommandInput[\"toolConfig\"]>[\"tools\"],\n };\n }\n\n if (request.instructions && messages.length > 0) {\n const lastMsg = messages[messages.length - 1];\n if (lastMsg.content.length > 0) {\n const firstBlock = lastMsg.content[0];\n if (\"text\" in firstBlock) {\n firstBlock.text = firstBlock.text + \"\\n\\n\" + request.instructions;\n }\n }\n }\n\n if (request.format) {\n if (this.useFakeToolForStructuredOutput(model)) {\n const fakeTool = {\n toolSpec: {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n inputSchema: { json: request.format as Record<string, unknown> },\n },\n };\n bedrockRequest.toolConfig = {\n tools: [\n ...(bedrockRequest.toolConfig?.tools ?? []),\n fakeTool,\n ] as NonNullable<ConverseCommandInput[\"toolConfig\"]>[\"tools\"],\n };\n } else {\n bedrockRequest.outputConfig = {\n textFormat: {\n type: \"json_schema\",\n structure: {\n jsonSchema: {\n schema: JSON.stringify(request.format),\n name: \"structured_output\",\n },\n },\n },\n };\n }\n }\n\n // Prompt caching via Converse cachePoint blocks (5-min default TTL; the\n // `ttl` option does not apply). Gated per model — cachePoint 400s on\n // unsupported models, which executeRequest catches and denylists.\n if (resolveCache(request.cache).enabled && this.supportsCachePoint(model)) {\n const cachePoint = { cachePoint: { type: \"default\" as const } };\n if (bedrockRequest.system && bedrockRequest.system.length > 0) {\n bedrockRequest.system = [\n ...bedrockRequest.system,\n cachePoint,\n ] as BedrockRequest[\"system\"];\n }\n if (bedrockRequest.toolConfig?.tools?.length) {\n bedrockRequest.toolConfig = {\n ...bedrockRequest.toolConfig,\n tools: [\n ...bedrockRequest.toolConfig.tools,\n cachePoint,\n ] as NonNullable<ConverseCommandInput[\"toolConfig\"]>[\"tools\"],\n };\n }\n }\n\n if (request.providerOptions) {\n Object.assign(bedrockRequest, request.providerOptions);\n }\n\n return bedrockRequest;\n }\n\n /** Remove any cachePoint blocks so the request can be retried unsupported. */\n private stripCachePoints(request: BedrockRequest): BedrockRequest {\n const stripped: BedrockRequest = { ...request };\n if (stripped.system) {\n stripped.system = stripped.system.filter(\n (block) => !(\"cachePoint\" in block),\n ) as BedrockRequest[\"system\"];\n }\n if (stripped.toolConfig?.tools) {\n stripped.toolConfig = {\n ...stripped.toolConfig,\n tools: stripped.toolConfig.tools.filter(\n (tool) => !(\"cachePoint\" in tool),\n ) as NonNullable<ConverseCommandInput[\"toolConfig\"]>[\"tools\"],\n };\n }\n return stripped;\n }\n\n private requestHasCachePoints(request: BedrockRequest): boolean {\n const inSystem = (request.system ?? []).some(\n (block) => \"cachePoint\" in block,\n );\n const inTools = (request.toolConfig?.tools ?? []).some(\n (tool) => \"cachePoint\" in tool,\n );\n return inSystem || inTools;\n }\n\n formatTools(toolkit: Toolkit): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: {\n ...tool.parameters,\n type: \"object\",\n } as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n // Bare JSON Schema node: `{ type: \"object\", properties: {...} }`\n if (isJsonSchema(schema)) {\n return structuredClone(schema);\n }\n\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n return z.toJSONSchema(zodSchema) as JsonObject;\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<AnnotatedBedrockResponse> {\n const bedrockClient = client as BedrockRuntimeClient;\n const bedrockRequest = request as BedrockRequest;\n\n const { ConverseCommand } = await import(\"@aws-sdk/client-bedrock-runtime\");\n const wantsStructuredOutput = Boolean(bedrockRequest.outputConfig);\n\n try {\n const response = (await bedrockClient.send(\n new ConverseCommand(bedrockRequest as ConverseCommandInput),\n signal ? { abortSignal: signal } : undefined,\n )) as AnnotatedBedrockResponse;\n if (wantsStructuredOutput) response.__jaypieStructuredOutput = true;\n return response;\n } catch (error) {\n if (\n bedrockRequest.inferenceConfig?.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(\n bedrockRequest.modelId || this.defaultModel,\n );\n const retryRequest: BedrockRequest = {\n ...bedrockRequest,\n inferenceConfig: { ...bedrockRequest.inferenceConfig },\n };\n delete retryRequest.inferenceConfig!.temperature;\n const response = (await bedrockClient.send(\n new ConverseCommand(retryRequest as ConverseCommandInput),\n signal ? { abortSignal: signal } : undefined,\n )) as AnnotatedBedrockResponse;\n if (wantsStructuredOutput) response.__jaypieStructuredOutput = true;\n return response;\n }\n\n if (wantsStructuredOutput && isOutputConfigUnsupportedError(error)) {\n const model = bedrockRequest.modelId || this.defaultModel;\n this.rememberModelRejectsOutputConfig(model);\n const fallbackRequest =\n this.toFallbackStructuredOutputRequest(bedrockRequest);\n return (await bedrockClient.send(\n new ConverseCommand(fallbackRequest as ConverseCommandInput),\n signal ? { abortSignal: signal } : undefined,\n )) as AnnotatedBedrockResponse;\n }\n\n if (\n this.requestHasCachePoints(bedrockRequest) &&\n isCachePointUnsupportedError(error)\n ) {\n this.rememberModelRejectsCachePoint(\n bedrockRequest.modelId || this.defaultModel,\n );\n const retryRequest = this.stripCachePoints(bedrockRequest);\n const response = (await bedrockClient.send(\n new ConverseCommand(retryRequest as ConverseCommandInput),\n signal ? { abortSignal: signal } : undefined,\n )) as AnnotatedBedrockResponse;\n if (wantsStructuredOutput) response.__jaypieStructuredOutput = true;\n return response;\n }\n throw error;\n }\n }\n\n private toFallbackStructuredOutputRequest(\n request: BedrockRequest,\n ): BedrockRequest {\n const { outputConfig, ...rest } = request;\n if (!outputConfig?.textFormat?.structure) return request;\n let schema: Record<string, unknown>;\n try {\n schema = JSON.parse(\n (\n outputConfig.textFormat.structure as {\n jsonSchema?: { schema?: string };\n }\n ).jsonSchema?.schema ?? \"{}\",\n ) as Record<string, unknown>;\n } catch {\n schema = {};\n }\n const fakeTool = {\n toolSpec: {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n inputSchema: { json: schema },\n },\n };\n return {\n ...rest,\n toolConfig: {\n tools: [...(rest.toolConfig?.tools ?? []), fakeTool] as NonNullable<\n ConverseCommandInput[\"toolConfig\"]\n >[\"tools\"],\n },\n };\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const bedrockClient = client as BedrockRuntimeClient;\n const bedrockRequest = request as BedrockRequest;\n\n const { ConverseStreamCommand } =\n await import(\"@aws-sdk/client-bedrock-runtime\");\n\n const response = await bedrockClient.send(\n new ConverseStreamCommand(bedrockRequest as ConverseCommandInput),\n signal ? { abortSignal: signal } : undefined,\n );\n\n if (!response.stream) return;\n\n let currentToolCall: {\n toolUseId: string;\n name: string;\n arguments: string;\n } | null = null;\n\n let inputTokens = 0;\n let outputTokens = 0;\n const model = bedrockRequest.modelId || this.defaultModel;\n\n for await (const event of response.stream) {\n if (event.contentBlockStart?.start?.toolUse) {\n const toolUse = event.contentBlockStart.start.toolUse;\n currentToolCall = {\n toolUseId: toolUse.toolUseId || \"\",\n name: toolUse.name || \"\",\n arguments: \"\",\n };\n } else if (event.contentBlockDelta?.delta) {\n const delta = event.contentBlockDelta.delta;\n if (delta.text !== undefined) {\n yield { type: LlmStreamChunkType.Text, content: delta.text };\n } else if (delta.toolUse?.input && currentToolCall) {\n currentToolCall.arguments += delta.toolUse.input;\n }\n } else if (event.contentBlockStop && currentToolCall) {\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.toolUseId,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n currentToolCall = null;\n } else if (event.metadata?.usage) {\n inputTokens = event.metadata.usage.inputTokens ?? 0;\n outputTokens = event.metadata.usage.outputTokens ?? 0;\n } else if (event.messageStop) {\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: 0,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n }\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n options?: LlmOperateOptions,\n ): ParsedResponse {\n const bedrockResponse = response as ConverseCommandOutput;\n const message = bedrockResponse.output?.message;\n const rawContent = this.extractContentFromMessage(message);\n\n let content: string | JsonObject | undefined = rawContent;\n if (options?.format && typeof rawContent === \"string\") {\n content = extractJson(rawContent) ?? rawContent;\n }\n\n // Don't surface structured_output fake tool as a real tool call\n const allToolUses = (\n (bedrockResponse.output?.message?.content ?? []) as BedrockContentBlock[]\n ).filter((b) => \"toolUse\" in b) as {\n toolUse: { name: string };\n }[];\n const hasOnlyStructuredOutputTool =\n allToolUses.length > 0 &&\n allToolUses.every((b) => b.toolUse.name === STRUCTURED_OUTPUT_TOOL_NAME);\n const hasToolCalls =\n bedrockResponse.stopReason === \"tool_use\" && !hasOnlyStructuredOutputTool;\n\n return {\n content,\n hasToolCalls,\n stopReason: bedrockResponse.stopReason ?? undefined,\n usage: this.extractUsage(\n bedrockResponse,\n (bedrockResponse as unknown as BedrockRequest).modelId ||\n this.defaultModel,\n ),\n raw: bedrockResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const bedrockResponse = response as ConverseCommandOutput;\n const content = bedrockResponse.output?.message?.content ?? [];\n const toolCalls: StandardToolCall[] = [];\n\n for (const block of content) {\n const typedBlock = block as BedrockContentBlock;\n if (\"toolUse\" in typedBlock && typedBlock.toolUse) {\n const toolUse = typedBlock.toolUse;\n toolCalls.push({\n callId: toolUse.toolUseId,\n name: toolUse.name,\n arguments: JSON.stringify(toolUse.input),\n raw: typedBlock,\n });\n }\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const bedrockResponse = response as ConverseCommandOutput;\n const usage = bedrockResponse.usage as\n | {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n cacheReadInputTokens?: number;\n cacheWriteInputTokens?: number;\n }\n | undefined;\n\n return {\n input: usage?.inputTokens ?? 0,\n output: usage?.outputTokens ?? 0,\n reasoning: 0,\n total:\n usage?.totalTokens ??\n (usage?.inputTokens ?? 0) + (usage?.outputTokens ?? 0),\n ...(usage?.cacheReadInputTokens !== undefined\n ? { cacheRead: usage.cacheReadInputTokens }\n : {}),\n ...(usage?.cacheWriteInputTokens !== undefined\n ? { cacheWrite: usage.cacheWriteInputTokens }\n : {}),\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): BedrockContentBlock {\n return {\n toolResult: {\n toolUseId: toolCall.callId,\n content: [{ text: result.output }],\n },\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): BedrockRequest {\n const bedrockRequest = request as BedrockRequest;\n const toolCallRaw = toolCall.raw as BedrockContentBlock;\n\n bedrockRequest.messages.push({\n role: \"assistant\",\n content: [toolCallRaw],\n });\n\n bedrockRequest.messages.push({\n role: \"user\",\n content: [this.formatToolResult(toolCall, result)],\n });\n\n return bedrockRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const bedrockResponse = response as ConverseCommandOutput;\n const historyItems: LlmHistory = [];\n\n if (bedrockResponse.stopReason === \"tool_use\") {\n return historyItems;\n }\n\n const content = bedrockResponse.output?.message?.content ?? [];\n const textBlock = (content as BedrockContentBlock[]).find(\n (block) => \"text\" in block,\n ) as { text: string } | undefined;\n\n if (textBlock) {\n historyItems.push({\n content: textBlock.text,\n role: \"assistant\",\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n const errorName = (error as Error)?.constructor?.name;\n const errorMessage = (error as Error)?.message ?? \"\";\n\n if (\n errorName === \"ThrottlingException\" ||\n errorMessage.includes(\"ThrottlingException\") ||\n errorMessage.includes(\"Too Many Requests\")\n ) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n if (\n errorName === \"ServiceUnavailableException\" ||\n errorName === \"InternalServerException\" ||\n errorMessage.includes(\"ServiceUnavailableException\") ||\n errorMessage.includes(\"InternalServerException\")\n ) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n if (\n errorName === \"AccessDeniedException\" ||\n errorName === \"ValidationException\" ||\n errorName === \"ResourceNotFoundException\" ||\n errorMessage.includes(\"AccessDeniedException\") ||\n errorMessage.includes(\"ValidationException\")\n ) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Structured Output\n //\n\n override hasStructuredOutput(response: unknown): boolean {\n const bedrockResponse = response as AnnotatedBedrockResponse;\n if (bedrockResponse.__jaypieStructuredOutput) {\n return this.extractStructuredOutput(response) !== undefined;\n }\n // Fake-tool path: last content block is a structured_output toolUse\n const content = (bedrockResponse.output?.message?.content ??\n []) as BedrockContentBlock[];\n const last = content[content.length - 1];\n return (\n !!last &&\n \"toolUse\" in last &&\n last.toolUse.name === STRUCTURED_OUTPUT_TOOL_NAME\n );\n }\n\n override extractStructuredOutput(response: unknown): JsonObject | undefined {\n const bedrockResponse = response as AnnotatedBedrockResponse;\n\n if (bedrockResponse.__jaypieStructuredOutput) {\n const content = (bedrockResponse.output?.message?.content ??\n []) as BedrockContentBlock[];\n const textBlock = content.find((b) => \"text\" in b) as\n { text: string } | undefined;\n if (!textBlock) return undefined;\n return extractJson(textBlock.text);\n }\n\n // Fake-tool path\n const content = (bedrockResponse.output?.message?.content ??\n []) as BedrockContentBlock[];\n const last = content[content.length - 1];\n if (\n last &&\n \"toolUse\" in last &&\n last.toolUse.name === STRUCTURED_OUTPUT_TOOL_NAME\n ) {\n return last.toolUse.input as JsonObject;\n }\n return undefined;\n }\n\n //\n // Completion Detection\n //\n\n isComplete(response: unknown): boolean {\n const bedrockResponse = response as ConverseCommandOutput;\n return bedrockResponse.stopReason !== \"tool_use\";\n }\n\n //\n // Private Helpers\n //\n\n private extractContentFromMessage(\n message: { content?: unknown[] } | undefined,\n ): string | JsonObject | undefined {\n if (!message?.content) return undefined;\n\n const content = message.content as BedrockContentBlock[];\n const textBlock = content.find((block) => \"text\" in block) as\n { text: string } | undefined;\n\n return textBlock?.text;\n }\n}\n\nexport const bedrockAdapter = new BedrockAdapter();\n","import { log } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { paperedEffortMessage, toFireworksEffort } from \"../../util/effort.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmInputContent,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport { isJsonSchema, naturalZodSchema } from \"../../util/index.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { FireworksClient } from \"../../providers/fireworks/client.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\n\n//\n//\n// Types\n//\n\ninterface FireworksMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content?: string | FireworksContentPart[] | null;\n toolCalls?: FireworksToolCall[];\n toolCallId?: string;\n}\n\ninterface FireworksToolCall {\n id: string;\n type: \"function\";\n function: {\n name: string;\n arguments: string;\n };\n}\n\ninterface FireworksResponseMessage {\n role: \"assistant\";\n content?: string | null;\n toolCalls?: FireworksToolCall[];\n refusal?: string | null;\n reasoning?: string | null;\n reasoning_content?: string | null;\n}\n\ninterface FireworksChoice {\n index: number;\n message: FireworksResponseMessage;\n finishReason: string | null;\n finish_reason?: string | null;\n}\n\ninterface FireworksUsage {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n completionTokensDetails?: {\n reasoningTokens?: number;\n };\n}\n\ninterface FireworksResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: FireworksChoice[];\n usage?: FireworksUsage;\n}\n\ninterface FireworksTool {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: JsonObject;\n };\n}\n\ninterface FireworksJsonSchemaConfig {\n name: string;\n description?: string;\n schema: JsonObject;\n strict?: boolean;\n}\n\ntype FireworksResponseFormat =\n | { type: \"json_schema\"; json_schema: FireworksJsonSchemaConfig }\n | { type: \"json_object\" }\n | { type: \"text\" };\n\ninterface FireworksRequest {\n model: string;\n messages: FireworksMessage[];\n tools?: FireworksTool[];\n tool_choice?: \"auto\" | \"none\" | \"required\";\n response_format?: FireworksResponseFormat;\n reasoning_effort?: string;\n user?: string;\n}\n\n/**\n * Fireworks responses we annotate at receive time so downstream stateless\n * methods (`hasStructuredOutput`, `extractStructuredOutput`) can tell whether\n * the request asked for native structured output without re-threading the\n * request.\n */\ntype AnnotatedFireworksResponse = FireworksResponse & {\n __jaypieStructuredOutput?: boolean;\n};\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\nconst STRUCTURED_OUTPUT_SCHEMA_NAME = \"response\";\n\n/**\n * Detect 4xx errors that indicate the model itself does not support\n * `response_format: json_schema`. We only trigger the fake-tool fallback when\n * the failure is plausibly a capability gap, not a generic 400.\n */\nfunction isStructuredOutputUnsupportedError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n statusCode?: number;\n message?: string;\n error?: { message?: string };\n };\n const status = err.status ?? err.statusCode;\n if (status !== 400 && status !== 422) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) =>\n /response[_ ]format|json[_ ]schema|structured[_ ]output/i.test(m),\n );\n}\n\nfunction isTemperatureDeprecationError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n statusCode?: number;\n message?: string;\n error?: { message?: string };\n };\n const status = err.status ?? err.statusCode;\n if (status !== 400) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) => m.toLowerCase().includes(\"temperature\"));\n}\n\n/**\n * Fireworks content part types. Fireworks follows the OpenAI Chat Completions\n * multimodal schema for `image_url` parts (URL or base64 data URI). There is\n * no OpenAI-style `file` part, and the API rejects `data:` URIs for documents\n * (\"Unsupported URL scheme 'data'\"), so file inputs cannot be delivered.\n */\ntype FireworksContentPart =\n | { type: \"text\"; text: string }\n | { type: \"image_url\"; imageUrl: { url: string } };\n\n/**\n * Convert standardized content items to Fireworks format. Images become\n * `image_url` parts (vision models only; non-vision models 4xx — a\n * model-capability mismatch surfaced by the call). File inputs are warned\n * and discarded: Fireworks has no `file` part and rejects document `data:`\n * URIs outright, so there is no wire shape that can carry them.\n */\nfunction convertContentToFireworks(\n content: string | LlmInputContent[],\n): string | FireworksContentPart[] {\n if (typeof content === \"string\") {\n return content;\n }\n\n const parts: FireworksContentPart[] = [];\n\n for (const item of content) {\n if (item.type === LlmMessageType.InputText) {\n parts.push({ type: \"text\", text: item.text });\n continue;\n }\n\n if (item.type === LlmMessageType.InputImage) {\n const url = item.image_url ?? \"\";\n if (!url) {\n log.warn(\"Fireworks image content missing image_url; image discarded\");\n continue;\n }\n parts.push({ type: \"image_url\", imageUrl: { url } });\n continue;\n }\n\n if (item.type === LlmMessageType.InputFile) {\n log.warn(\n { filename: item.filename },\n \"Fireworks does not support file inputs (no file part; document data: URIs rejected); file discarded\",\n );\n continue;\n }\n\n // Unknown type - warn and skip\n log.warn({ item }, \"Unknown content type for Fireworks; discarded\");\n }\n\n // If no parts remain, return empty string to avoid empty array\n if (parts.length === 0) {\n return \"\";\n }\n\n return parts;\n}\n\n/**\n * Convert internal content parts to the OpenAI-compatible wire shape. The\n * internal representation uses camelCase keys (`imageUrl`); the REST API wants\n * snake_case (`image_url`).\n */\nfunction contentToWire(\n content: string | FireworksContentPart[] | null | undefined,\n): unknown {\n if (\n content === null ||\n content === undefined ||\n typeof content === \"string\"\n ) {\n return content;\n }\n return content.map((part) => {\n if (part.type === \"image_url\") {\n return { type: \"image_url\", image_url: part.imageUrl };\n }\n return part;\n });\n}\n\n/**\n * Serialize an internal message to the OpenAI-compatible wire shape, mapping\n * camelCase tool fields (`toolCalls`, `toolCallId`) to snake_case. Tool-call\n * objects are already wire-shaped (`{ id, type, function: { name, arguments } }`).\n */\nfunction messageToWire(message: FireworksMessage): Record<string, unknown> {\n const wire: Record<string, unknown> = { role: message.role };\n if (message.content !== undefined) {\n wire.content = contentToWire(message.content);\n }\n if (message.toolCalls) {\n wire.tool_calls = message.toolCalls;\n }\n if (message.toolCallId) {\n wire.tool_call_id = message.toolCallId;\n }\n return wire;\n}\n\n// Fireworks error types based on HTTP status codes\nconst RETRYABLE_STATUS_CODES = [408, 500, 502, 503, 524, 529];\nconst RATE_LIMIT_STATUS_CODE = 429;\n\n/**\n * Walk the JSON schema and force `additionalProperties: false` on every\n * object node. Required by the OpenAI-style json_schema response_format when\n * `strict: true`.\n */\nfunction enforceAdditionalPropertiesFalse(schema: JsonObject): void {\n const stack: JsonObject[] = [schema];\n while (stack.length > 0) {\n const node = stack.pop() as JsonObject;\n if (node.type === \"object\") {\n node.additionalProperties = false;\n }\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const entry of value) {\n if (entry && typeof entry === \"object\" && !Array.isArray(entry)) {\n stack.push(entry as JsonObject);\n }\n }\n } else if (value && typeof value === \"object\") {\n stack.push(value as JsonObject);\n }\n }\n }\n}\n\n//\n//\n// Main\n//\n\n/**\n * FireworksAdapter implements the ProviderAdapter interface for Fireworks AI's\n * OpenAI-compatible Chat Completions API. It handles request building,\n * response parsing, and error classification specific to Fireworks.\n */\nexport class FireworksAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.FIREWORKS.NAME;\n readonly defaultModel = PROVIDER.FIREWORKS.DEFAULT;\n\n // Structured output with tools rides the structured_output tool emulation\n // (Fireworks rejects response_format + tools), and emulation compliance is\n // a model decision — opt in to OperateLoop's corrective retry turn.\n override readonly supportsStructuredOutputRetry = true;\n\n // Session-level cache of models observed to reject native\n // `response_format: json_schema`. When a model is in this set, buildRequest\n // engages the legacy fake-tool path instead of native structured output.\n private runtimeNoStructuredOutputModels = new Set<string>();\n\n rememberModelRejectsStructuredOutput(model: string): void {\n this.runtimeNoStructuredOutputModels.add(model);\n }\n\n clearRuntimeNoStructuredOutputModels(): void {\n this.runtimeNoStructuredOutputModels.clear();\n }\n\n private supportsStructuredOutput(model: string): boolean {\n return !this.runtimeNoStructuredOutputModels.has(model);\n }\n\n // Session-level cache of models observed to reject `temperature`. Populated\n // by executeRequest on 400 errors so repeat calls skip the param.\n private runtimeNoTemperatureModels = new Set<string>();\n\n rememberModelRejectsTemperature(model: string): void {\n this.runtimeNoTemperatureModels.add(model);\n }\n\n clearRuntimeNoTemperatureModels(): void {\n this.runtimeNoTemperatureModels.clear();\n }\n\n private supportsTemperature(model: string): boolean {\n return !this.runtimeNoTemperatureModels.has(model);\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): FireworksRequest {\n // Convert messages to Fireworks format (OpenAI-compatible)\n const messages: FireworksMessage[] = this.convertMessagesToFireworks(\n request.messages,\n request.system,\n );\n\n // Append instructions to last message if provided\n if (request.instructions && messages.length > 0) {\n const lastMsg = messages[messages.length - 1];\n if (lastMsg.content && typeof lastMsg.content === \"string\") {\n lastMsg.content = lastMsg.content + \"\\n\\n\" + request.instructions;\n }\n }\n\n const fireworksRequest: FireworksRequest = {\n model: request.model || this.defaultModel,\n messages,\n };\n\n if (request.user) {\n fireworksRequest.user = request.user;\n }\n\n // Fireworks rejects `response_format` combined with `tools` (\"You cannot\n // specify response format and function call at the same time\"), so a\n // request with both preemptively uses the structured_output tool\n // emulation — same approach as Gemini 2.5.\n const hasCallerTools = Boolean(request.tools?.length);\n const useFallbackStructuredOutput =\n Boolean(request.format) &&\n (hasCallerTools ||\n !this.supportsStructuredOutput(fireworksRequest.model));\n\n // On a corrective retry turn (the model answered a format request with\n // prose), offer only the structured_output tool so the demanded call is\n // the sole option.\n const allTools: ProviderToolDefinition[] =\n request.tools && !request.structuredOutputRetry ? [...request.tools] : [];\n if (useFallbackStructuredOutput && request.format) {\n log.warn(\n hasCallerTools\n ? `[FireworksAdapter] Fireworks does not support response_format combined with tools; using structured_output tool emulation for model ${fireworksRequest.model}.`\n : `[FireworksAdapter] Using legacy structured_output tool fallback for model ${fireworksRequest.model}; native response_format previously rejected for this model.`,\n );\n allTools.push({\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n parameters: request.format,\n });\n }\n\n if (allTools.length > 0) {\n fireworksRequest.tools = allTools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n\n // Use \"auto\" for tool_choice - not all Fireworks models support \"required\"\n // The structured_output tool prompt already emphasizes it must be called\n fireworksRequest.tool_choice = \"auto\";\n }\n\n // Native structured output: send schema as `response_format`. The legacy\n // tool-emulation path is engaged only as a runtime fallback for models the\n // API has flagged as not supporting native json_schema.\n if (request.format && !useFallbackStructuredOutput) {\n fireworksRequest.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: STRUCTURED_OUTPUT_SCHEMA_NAME,\n schema: request.format,\n strict: true,\n },\n };\n }\n\n if (request.providerOptions) {\n Object.assign(fireworksRequest, request.providerOptions);\n }\n\n // Normalized reasoning effort -> reasoning_effort. Fireworks accepts the\n // param on every model and no-ops where unsupported, so no per-model\n // gating. First-class effort wins over providerOptions.\n if (request.effort) {\n const mapping = toFireworksEffort(request.effort);\n if (mapping.papered) {\n log.debug(\n paperedEffortMessage({\n model: fireworksRequest.model,\n provider: this.name,\n requested: request.effort,\n value: mapping.value,\n }),\n );\n }\n fireworksRequest.reasoning_effort = mapping.value as string;\n }\n\n // First-class temperature takes precedence over providerOptions\n if (request.temperature !== undefined) {\n (fireworksRequest as unknown as Record<string, unknown>).temperature =\n request.temperature;\n }\n\n // Strip temperature for models the runtime has cached as rejecting it\n const requestRecord = fireworksRequest as unknown as Record<\n string,\n unknown\n >;\n if (\n requestRecord.temperature !== undefined &&\n !this.supportsTemperature(fireworksRequest.model)\n ) {\n delete requestRecord.temperature;\n }\n\n return fireworksRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n // outputSchema is part of the interface contract but Fireworks uses native\n // `response_format` (set in buildRequest); the legacy fake-tool injection\n // happens in buildRequest only as a runtime fallback.\n\n _outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n let jsonSchema: JsonObject;\n\n // Check if schema is already a JsonObject — either the OpenAI-style\n // `{ type: \"json_schema\", ... }` envelope or a bare `{ type: \"object\", properties }` node\n if (\n (typeof schema === \"object\" &&\n schema !== null &&\n !Array.isArray(schema) &&\n (schema as JsonObject).type === \"json_schema\") ||\n isJsonSchema(schema)\n ) {\n jsonSchema = structuredClone(schema) as JsonObject;\n jsonSchema.type = \"object\"; // Normalize type\n } else {\n // Convert NaturalSchema to JSON schema through Zod. Re-spread into a\n // plain object to drop Zod v4's non-enumerable `~standard` marker.\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n jsonSchema = { ...(z.toJSONSchema(zodSchema) as JsonObject) };\n }\n\n // Remove $schema property (can cause issues with some providers)\n if (jsonSchema.$schema) {\n delete jsonSchema.$schema;\n }\n\n // Strict json_schema response_format requires additionalProperties: false\n // on every object.\n enforceAdditionalPropertiesFalse(jsonSchema);\n\n return jsonSchema;\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<FireworksResponse> {\n const fireworks = client as FireworksClient;\n const fireworksRequest = request as FireworksRequest;\n const wantsStructuredOutput = Boolean(fireworksRequest.response_format);\n\n try {\n const response = (await fireworks.chatCompletion(\n this.toWireBody(fireworksRequest),\n signal ? { signal } : undefined,\n )) as unknown as AnnotatedFireworksResponse;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as FireworksResponse;\n\n // If the model rejected `temperature`, cache it and retry without the param.\n const requestRecord = fireworksRequest as unknown as Record<\n string,\n unknown\n >;\n if (\n requestRecord.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(fireworksRequest.model);\n const retryRequest = { ...fireworksRequest } as FireworksRequest;\n delete (retryRequest as unknown as Record<string, unknown>).temperature;\n const response = (await fireworks.chatCompletion(\n this.toWireBody(retryRequest),\n signal ? { signal } : undefined,\n )) as unknown as AnnotatedFireworksResponse;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n }\n\n // If the model rejected `response_format`, cache it and retry with the\n // legacy fake-tool emulation path.\n if (wantsStructuredOutput && isStructuredOutputUnsupportedError(error)) {\n const model = fireworksRequest.model;\n this.rememberModelRejectsStructuredOutput(model);\n log.warn(\n `[FireworksAdapter] Model ${model} rejected native response_format; falling back to legacy structured_output tool emulation.`,\n );\n const fallbackRequest =\n this.toFallbackStructuredOutputRequest(fireworksRequest);\n return (await fireworks.chatCompletion(\n this.toWireBody(fallbackRequest),\n signal ? { signal } : undefined,\n )) as unknown as FireworksResponse;\n }\n\n throw error;\n }\n }\n\n /**\n * Serialize the internal request into the OpenAI-compatible wire body for\n * Fireworks' Chat Completions endpoint. Top-level fields (model, tools,\n * tool_choice, response_format, reasoning_effort, user, temperature, and any\n * providerOptions) are already wire-shaped (snake_case); only messages carry\n * camelCase tool fields that must become snake_case on the wire.\n */\n private toWireBody(\n fireworksRequest: FireworksRequest,\n ): Record<string, unknown> {\n return {\n ...fireworksRequest,\n messages: fireworksRequest.messages.map(messageToWire),\n };\n }\n\n /**\n * Rebuild a structured-output request without `response_format`, swapping in\n * the legacy fake-tool emulation. Used as a runtime fallback when a model\n * rejects native json_schema.\n */\n private toFallbackStructuredOutputRequest(\n request: FireworksRequest,\n ): FireworksRequest {\n if (\n !request.response_format ||\n request.response_format.type !== \"json_schema\"\n ) {\n return request;\n }\n const { response_format, ...rest } = request;\n const fallbackRequest: FireworksRequest = { ...rest };\n const schema = response_format.json_schema.schema;\n const fakeTool: FireworksTool = {\n type: \"function\" as const,\n function: {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n parameters: schema,\n },\n };\n fallbackRequest.tools = [...(fallbackRequest.tools ?? []), fakeTool];\n fallbackRequest.tool_choice = \"auto\";\n return fallbackRequest;\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const fireworks = client as FireworksClient;\n const fireworksRequest = request as FireworksRequest;\n\n // streamChatCompletion adds `stream: true` + `stream_options.include_usage`\n // and yields decoded SSE chunks in OpenAI-compatible (snake_case) shape.\n const stream = fireworks.streamChatCompletion(\n this.toWireBody(fireworksRequest),\n signal ? { signal } : undefined,\n ) as AsyncIterable<unknown>;\n\n // Track current tool call being built\n let currentToolCall: {\n id: string;\n name: string;\n arguments: string;\n } | null = null;\n\n // Track usage for final chunk\n let inputTokens = 0;\n let outputTokens = 0;\n const model = fireworksRequest.model || this.defaultModel;\n\n for await (const chunk of stream) {\n // Handle different chunk types from Fireworks (OpenAI-compatible format)\n interface StreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n // Reasoning deltas arrive on reasoning_content; kept out of the\n // text stream so `content` remains the final answer only.\n reasoning_content?: string;\n tool_calls?: Array<{\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason?: string;\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n promptTokens?: number;\n completionTokens?: number;\n };\n }\n const typedChunk = chunk as StreamChunk;\n const choices = typedChunk.choices;\n\n if (choices && choices.length > 0) {\n const delta = choices[0].delta;\n\n // Handle text content\n if (delta?.content) {\n yield {\n type: LlmStreamChunkType.Text,\n content: delta.content,\n };\n }\n\n // Handle tool calls\n if (delta?.tool_calls && delta.tool_calls.length > 0) {\n for (const toolCallDelta of delta.tool_calls) {\n if (toolCallDelta.id) {\n // New tool call starting\n if (currentToolCall) {\n // Emit the previous tool call\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.id,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n }\n currentToolCall = {\n id: toolCallDelta.id,\n name: toolCallDelta.function?.name || \"\",\n arguments: toolCallDelta.function?.arguments || \"\",\n };\n } else if (currentToolCall) {\n // Continuing existing tool call\n if (toolCallDelta.function?.name) {\n currentToolCall.name += toolCallDelta.function.name;\n }\n if (toolCallDelta.function?.arguments) {\n currentToolCall.arguments += toolCallDelta.function.arguments;\n }\n }\n }\n }\n\n // Check for finish reason\n if (choices[0].finish_reason) {\n // Emit any pending tool call\n if (currentToolCall) {\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.id,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n currentToolCall = null;\n }\n }\n }\n\n // Extract usage if present (usually in the final chunk)\n if (typedChunk.usage) {\n inputTokens =\n typedChunk.usage.prompt_tokens || typedChunk.usage.promptTokens || 0;\n outputTokens =\n typedChunk.usage.completion_tokens ||\n typedChunk.usage.completionTokens ||\n 0;\n }\n }\n\n // Emit done chunk with final usage\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: 0,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n _options?: LlmOperateOptions,\n ): ParsedResponse {\n const fireworksResponse = response as FireworksResponse;\n const choice = fireworksResponse.choices[0];\n\n const content = this.extractContent(fireworksResponse);\n const hasToolCalls = this.hasToolCalls(fireworksResponse);\n\n const stopReason =\n choice?.finishReason ?? choice?.finish_reason ?? undefined;\n\n return {\n content,\n hasToolCalls,\n stopReason,\n usage: this.extractUsage(fireworksResponse, fireworksResponse.model),\n raw: fireworksResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const fireworksResponse = response as FireworksResponse;\n const toolCalls: StandardToolCall[] = [];\n const choice = fireworksResponse.choices[0];\n\n if (!choice?.message?.toolCalls) {\n return toolCalls;\n }\n\n for (const toolCall of choice.message.toolCalls) {\n toolCalls.push({\n callId: toolCall.id,\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n raw: toolCall,\n });\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const fireworksResponse = response as FireworksResponse;\n\n if (!fireworksResponse.usage) {\n return {\n input: 0,\n output: 0,\n reasoning: 0,\n total: 0,\n provider: this.name,\n model,\n };\n }\n\n const usage = fireworksResponse.usage;\n return {\n input: usage.promptTokens || usage.prompt_tokens || 0,\n output: usage.completionTokens || usage.completion_tokens || 0,\n reasoning: usage.completionTokensDetails?.reasoningTokens || 0,\n total: usage.totalTokens || usage.total_tokens || 0,\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): FireworksMessage {\n return {\n role: \"tool\",\n toolCallId: toolCall.callId,\n content: result.output,\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): FireworksRequest {\n const fireworksRequest = request as FireworksRequest;\n const toolCallRaw = toolCall.raw as FireworksToolCall;\n\n // Add assistant message with the tool call\n fireworksRequest.messages.push({\n role: \"assistant\",\n content: null,\n toolCalls: [toolCallRaw],\n });\n\n // Add tool result message\n fireworksRequest.messages.push(this.formatToolResult(toolCall, result));\n\n return fireworksRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const fireworksResponse = response as FireworksResponse;\n const historyItems: LlmHistory = [];\n const choice = fireworksResponse.choices[0];\n\n if (!choice?.message) {\n return historyItems;\n }\n\n // Check if this is a tool use response\n if (choice.message.toolCalls && choice.message.toolCalls.length > 0) {\n // Don't add to history yet - will be added after tool execution\n return historyItems;\n }\n\n // Extract text content for non-tool responses\n if (choice.message.content) {\n const historyItem: LlmOutputMessage & { reasoning?: string } = {\n content: choice.message.content,\n role: LlmMessageRole.Assistant,\n type: LlmMessageType.Message,\n };\n\n // Preserve reasoning if present. Fireworks reasoning models return it in\n // reasoning_content; some routes use reasoning.\n const reasoning =\n choice.message.reasoning_content ?? choice.message.reasoning;\n if (reasoning) {\n historyItem.reasoning = reasoning;\n }\n\n historyItems.push(historyItem as LlmOutputMessage);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n // Check if error has a status code (HTTP error)\n const errorWithStatus = error as { status?: number; statusCode?: number };\n const statusCode = errorWithStatus.status || errorWithStatus.statusCode;\n\n if (statusCode) {\n // Rate limit error\n if (statusCode === RATE_LIMIT_STATUS_CODE) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Retryable errors (server errors, timeouts, etc.)\n if (RETRYABLE_STATUS_CODES.includes(statusCode)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Client errors (4xx except 429) are unrecoverable\n if (statusCode >= 400 && statusCode < 500) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n }\n\n // Check error message for rate limit indicators\n const errorMessage =\n error instanceof Error ? error.message.toLowerCase() : \"\";\n if (\n errorMessage.includes(\"rate limit\") ||\n errorMessage.includes(\"too many requests\")\n ) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Check for transient network errors (ECONNRESET, etc.)\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Unknown error - treat as potentially retryable\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Provider-Specific Features\n //\n\n isComplete(response: unknown): boolean {\n const fireworksResponse = response as FireworksResponse;\n const choice = fireworksResponse.choices[0];\n\n // Complete if no tool calls\n if (!choice?.message?.toolCalls?.length) {\n return true;\n }\n\n return false;\n }\n\n override hasStructuredOutput(response: unknown): boolean {\n const fireworksResponse = response as AnnotatedFireworksResponse;\n\n // Native path: executeRequest annotates the response when we sent\n // `response_format`, so we can detect intent statelessly.\n if (fireworksResponse.__jaypieStructuredOutput) {\n return this.extractStructuredOutput(response) !== undefined;\n }\n\n // Fallback path: legacy fake-tool emulation, kept for models that the\n // runtime has cached as not supporting native `response_format`.\n const choice = fireworksResponse.choices[0];\n\n if (!choice?.message?.toolCalls?.length) {\n return false;\n }\n\n // Check if the last tool call is structured_output\n const lastToolCall =\n choice.message.toolCalls[choice.message.toolCalls.length - 1];\n return lastToolCall?.function?.name === STRUCTURED_OUTPUT_TOOL_NAME;\n }\n\n override extractStructuredOutput(response: unknown): JsonObject | undefined {\n const fireworksResponse = response as AnnotatedFireworksResponse;\n\n if (fireworksResponse.__jaypieStructuredOutput) {\n const choice = fireworksResponse.choices[0];\n const content = choice?.message?.content;\n if (typeof content !== \"string\" || content.length === 0) {\n return undefined;\n }\n try {\n return JSON.parse(content) as JsonObject;\n } catch {\n return undefined;\n }\n }\n\n // Fallback path: legacy fake-tool emulation\n const choice = fireworksResponse.choices[0];\n\n if (!choice?.message?.toolCalls?.length) {\n return undefined;\n }\n\n const lastToolCall =\n choice.message.toolCalls[choice.message.toolCalls.length - 1];\n if (lastToolCall?.function?.name === STRUCTURED_OUTPUT_TOOL_NAME) {\n try {\n return JSON.parse(lastToolCall.function.arguments) as JsonObject;\n } catch {\n return undefined;\n }\n }\n\n return undefined;\n }\n\n //\n // Private Helpers\n //\n\n private hasToolCalls(response: FireworksResponse): boolean {\n const choice = response.choices[0];\n return (choice?.message?.toolCalls?.length ?? 0) > 0;\n }\n\n private extractContent(\n response: FireworksResponse,\n ): string | JsonObject | undefined {\n // Check for structured output first\n if (this.hasStructuredOutput(response)) {\n return this.extractStructuredOutput(response);\n }\n\n const choice = response.choices[0];\n return choice?.message?.content ?? undefined;\n }\n\n private convertMessagesToFireworks(\n messages: LlmHistory,\n system?: string,\n ): FireworksMessage[] {\n const fireworksMessages: FireworksMessage[] = [];\n\n // Add system message if provided\n if (system) {\n fireworksMessages.push({\n role: \"system\",\n content: system,\n });\n }\n\n for (const msg of messages) {\n const message = msg as unknown as Record<string, unknown>;\n\n // Handle different message types\n if (message.role === \"system\") {\n fireworksMessages.push({\n role: \"system\",\n content: message.content as string,\n });\n } else if (message.role === \"user\") {\n fireworksMessages.push({\n role: \"user\",\n content: convertContentToFireworks(\n message.content as string | LlmInputContent[],\n ),\n });\n } else if (message.role === \"assistant\") {\n const assistantMsg: FireworksMessage = {\n role: \"assistant\",\n content: (message.content as string) || null,\n };\n\n // Include toolCalls if present (check both camelCase and snake_case for compatibility)\n if (message.toolCalls) {\n assistantMsg.toolCalls = message.toolCalls as FireworksToolCall[];\n } else if (message.tool_calls) {\n assistantMsg.toolCalls = message.tool_calls as FireworksToolCall[];\n }\n\n fireworksMessages.push(assistantMsg);\n } else if (message.role === \"tool\") {\n fireworksMessages.push({\n role: \"tool\",\n toolCallId:\n (message.toolCallId as string) || (message.tool_call_id as string),\n content: message.content as string,\n });\n } else if (message.type === LlmMessageType.Message) {\n // Handle internal message format\n const role = (message.role as string)?.toLowerCase();\n if (role === \"assistant\") {\n fireworksMessages.push({\n role: \"assistant\",\n content: message.content as string,\n });\n } else {\n fireworksMessages.push({\n role: \"user\",\n content: convertContentToFireworks(\n message.content as string | LlmInputContent[],\n ),\n });\n }\n } else if (message.type === LlmMessageType.FunctionCall) {\n fireworksMessages.push({\n role: \"assistant\",\n content: null,\n toolCalls: [\n {\n id: message.call_id as string,\n type: \"function\" as const,\n function: {\n name: message.name as string,\n arguments: (message.arguments as string) || \"{}\",\n },\n },\n ],\n });\n } else if (message.type === LlmMessageType.FunctionCallOutput) {\n fireworksMessages.push({\n role: \"tool\",\n toolCallId: message.call_id as string,\n content: (message.output as string) || \"\",\n });\n }\n }\n\n return fireworksMessages;\n }\n}\n\n// Export singleton instance\nexport const fireworksAdapter = new FireworksAdapter();\n","import { log } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n paperedEffortMessage,\n toGeminiThinkingBudget,\n toGeminiThinkingLevel,\n} from \"../../util/effort.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n isJsonSchema,\n jsonSchemaToOpenApi3,\n naturalZodSchema,\n resolveMaxOutputTokens,\n} from \"../../util/index.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { GoogleClient } from \"../../providers/google/client.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\nimport {\n GeminiContent,\n GeminiErrorInfo,\n GeminiFunctionCall,\n GeminiFunctionDeclaration,\n GeminiPart,\n GeminiRawResponse,\n GeminiRequest,\n} from \"../../providers/google/types.js\";\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\n// Gemini 3 family supports combining tools (function calling) with native\n// structured output via `responseJsonSchema`. Earlier Gemini families\n// (including 2.5 thinking) do not support the combo and fall back to the\n// legacy `structured_output` fake-tool emulation.\nconst GEMINI_3_PATTERN = /^gemini-3/;\n\n// Reasoning-effort control differs by generation: Gemini 3.x takes the\n// `thinkingLevel` enum, Gemini 2.5 takes an integer `thinkingBudget`. Sending\n// the wrong one errors, and models outside these families have no thinking\n// control, so effort is only applied when one of these matches.\nconst GEMINI_25_PATTERN = /^gemini-2\\.5/;\n\n/**\n * Detect 4xx errors that indicate the model itself does not support the\n * `responseJsonSchema` + tools combo. Triggers the runtime fallback to the\n * fake-tool emulation path. Other 400s propagate.\n */\nfunction isStructuredOutputComboUnsupportedError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n code?: number;\n message?: string;\n error?: { message?: string };\n };\n const status = err.status ?? err.code;\n if (status !== 400) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) =>\n /response[_ ]?json[_ ]?schema|response[_ ]?schema|response[_ ]?mime|function[_ ]?call|tools/i.test(\n m,\n ),\n );\n}\n\n// Gemini uses HTTP status codes for error classification\n// Documented at: https://ai.google.dev/api/rest/v1beta/Status\nconst RETRYABLE_STATUS_CODES = [\n 408, // Request Timeout\n 429, // Too Many Requests (Rate Limit)\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n];\n\nconst NOT_RETRYABLE_STATUS_CODES = [\n 400, // Bad Request\n 401, // Unauthorized\n 403, // Forbidden\n 404, // Not Found\n 409, // Conflict\n 422, // Unprocessable Entity\n];\n\n//\n//\n// Main\n//\n\n/**\n * GoogleAdapter implements the ProviderAdapter interface for Google's Gemini API.\n * It handles request building, response parsing, and error classification\n * specific to Gemini's generateContent API.\n */\nexport class GoogleAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.GOOGLE.NAME;\n readonly defaultModel = PROVIDER.GOOGLE.DEFAULT;\n\n // Session-level cache of Gemini 3 models observed to reject the native\n // `responseJsonSchema` + tools combo. When a model is in this set,\n // buildRequest engages the legacy fake-tool path instead.\n private runtimeNoStructuredOutputComboModels = new Set<string>();\n\n rememberModelRejectsStructuredOutputCombo(model: string): void {\n this.runtimeNoStructuredOutputComboModels.add(model);\n }\n\n clearRuntimeNoStructuredOutputComboModels(): void {\n this.runtimeNoStructuredOutputComboModels.clear();\n }\n\n private supportsStructuredOutputCombo(model: string): boolean {\n if (this.runtimeNoStructuredOutputComboModels.has(model)) return false;\n return GEMINI_3_PATTERN.test(model);\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): GeminiRequest {\n // Convert messages to Gemini format (Content[])\n const contents: GeminiContent[] = this.convertMessagesToContents(\n request.messages,\n );\n\n const geminiRequest: GeminiRequest = {\n model: request.model || this.defaultModel,\n contents,\n };\n\n // Add system instruction if provided\n if (request.system) {\n geminiRequest.config = {\n ...geminiRequest.config,\n systemInstruction: request.system,\n };\n }\n\n // Append instructions to the last user message if provided\n if (request.instructions && contents.length > 0) {\n const lastContent = contents[contents.length - 1];\n if (lastContent.role === \"user\" && lastContent.parts) {\n const lastPart = lastContent.parts[lastContent.parts.length - 1];\n if (lastPart.text) {\n lastPart.text = lastPart.text + \"\\n\\n\" + request.instructions;\n }\n }\n }\n\n const hasUserTools = !!(request.tools && request.tools.length > 0);\n const useNativeCombo =\n Boolean(request.format) &&\n hasUserTools &&\n this.supportsStructuredOutputCombo(geminiRequest.model);\n\n // When tools+format are combined and the model does not support the native\n // combo, inject the legacy `structured_output` fake tool here so the model\n // is forced to call it before its final answer.\n const allTools: ProviderToolDefinition[] = request.tools\n ? [...request.tools]\n : [];\n if (request.format && hasUserTools && !useNativeCombo) {\n log.warn(\n `[GoogleAdapter] Using legacy structured_output tool fallback for model ${geminiRequest.model}; native responseJsonSchema + tools combo is only available on Gemini 3.`,\n );\n allTools.push({\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"Output a structured JSON object, \" +\n \"use this before your final response to give structured outputs to the user\",\n parameters: request.format,\n });\n }\n\n if (allTools.length > 0) {\n const functionDeclarations: GeminiFunctionDeclaration[] = allTools.map(\n (tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n }),\n );\n\n geminiRequest.config = {\n ...geminiRequest.config,\n tools: [{ functionDeclarations }],\n };\n }\n\n // Native structured output: send schema as `responseJsonSchema`\n // (or `responseSchema` for Gemini 2.5+ no-tools path). The legacy\n // fake-tool emulation only runs when format+tools is combined on a model\n // that doesn't support the native combo.\n const wantsNativeStructured =\n Boolean(request.format) && (!hasUserTools || useNativeCombo);\n\n if (wantsNativeStructured) {\n const useJsonSchema =\n useNativeCombo || request.providerOptions?.useJsonSchema === true;\n\n if (useJsonSchema) {\n geminiRequest.config = {\n ...geminiRequest.config,\n responseMimeType: \"application/json\",\n responseJsonSchema: request.format,\n };\n } else {\n geminiRequest.config = {\n ...geminiRequest.config,\n responseMimeType: \"application/json\",\n responseSchema: jsonSchemaToOpenApi3(request.format!),\n };\n }\n }\n\n // Legacy fake-tool path needs a system-prompt nudge so the model actually\n // calls the synthetic tool before its final answer.\n if (request.format && hasUserTools && !useNativeCombo) {\n const structuredOutputInstruction =\n \"IMPORTANT: Before providing your final response, you MUST use the structured_output tool \" +\n \"to output your answer in the required JSON format.\";\n\n const existingSystem = geminiRequest.config?.systemInstruction || \"\";\n geminiRequest.config = {\n ...geminiRequest.config,\n systemInstruction: existingSystem\n ? `${existingSystem}\\n\\n${structuredOutputInstruction}`\n : structuredOutputInstruction,\n };\n }\n\n // Default output ceiling: Google's own default (8,192) silently\n // truncates long generations, so resolve to the model maximum (capped\n // for non-streaming); providerOptions below override\n const maxOutputTokens = resolveMaxOutputTokens(geminiRequest.model, {\n stream: request.stream,\n });\n if (maxOutputTokens !== undefined) {\n geminiRequest.config = {\n ...geminiRequest.config,\n maxOutputTokens,\n };\n }\n\n // Add provider-specific options\n if (request.providerOptions) {\n geminiRequest.config = {\n ...geminiRequest.config,\n ...request.providerOptions,\n };\n }\n\n // Normalized reasoning effort -> thinkingConfig. Gemini 3.x uses the\n // thinkingLevel enum; 2.5 uses an integer thinkingBudget. Merged so a\n // providerOptions.thinkingConfig survives; first-class effort wins.\n if (request.effort) {\n const model = geminiRequest.model;\n let thinkingConfig:\n { thinkingLevel?: string; thinkingBudget?: number } | undefined;\n let papered = false;\n let value: string | number | undefined;\n if (GEMINI_3_PATTERN.test(model)) {\n const mapping = toGeminiThinkingLevel(request.effort);\n ({ papered, value } = mapping);\n thinkingConfig = { thinkingLevel: mapping.value };\n } else if (GEMINI_25_PATTERN.test(model)) {\n const mapping = toGeminiThinkingBudget(request.effort);\n ({ papered, value } = mapping);\n thinkingConfig = { thinkingBudget: mapping.value };\n }\n if (thinkingConfig) {\n if (papered) {\n log.debug(\n paperedEffortMessage({\n model,\n provider: this.name,\n requested: request.effort,\n value: value!,\n }),\n );\n }\n geminiRequest.config = {\n ...geminiRequest.config,\n thinkingConfig: {\n ...geminiRequest.config?.thinkingConfig,\n ...thinkingConfig,\n },\n };\n }\n }\n\n // First-class temperature takes precedence over providerOptions\n if (request.temperature !== undefined) {\n geminiRequest.config = {\n ...geminiRequest.config,\n temperature: request.temperature,\n };\n }\n\n return geminiRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n // outputSchema is part of the interface contract but Gemini now handles\n // structured output via `responseJsonSchema`/`responseSchema` (or the\n // legacy fake-tool injected in buildRequest as a fallback). We no longer\n // inject a synthetic structured-output tool here.\n\n _outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: {\n ...tool.parameters,\n type: \"object\",\n } as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n let jsonSchema: JsonObject;\n\n // Check if schema is already a JsonObject — either the OpenAI-style\n // `{ type: \"json_schema\", ... }` envelope or a bare `{ type: \"object\", properties }` node\n if (\n (typeof schema === \"object\" &&\n schema !== null &&\n !Array.isArray(schema) &&\n (schema as JsonObject).type === \"json_schema\") ||\n isJsonSchema(schema)\n ) {\n jsonSchema = structuredClone(schema) as JsonObject;\n jsonSchema.type = \"object\";\n } else {\n // Convert NaturalSchema to JSON schema through Zod\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n jsonSchema = z.toJSONSchema(zodSchema) as JsonObject;\n }\n\n return jsonSchemaToOpenApi3(jsonSchema);\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<GeminiRawResponse> {\n const genAI = client as GoogleClient;\n const geminiRequest = request as GeminiRequest;\n const wantsNativeCombo =\n !!geminiRequest.config?.responseJsonSchema &&\n !!geminiRequest.config?.tools;\n\n try {\n // Cast config to any to bypass strict type checking between our internal types\n // and the SDK's types. The SDK will validate at runtime.\n const response = await genAI.models.generateContent({\n model: geminiRequest.model,\n contents: geminiRequest.contents as any,\n config: geminiRequest.config as any,\n });\n\n return response as unknown as GeminiRawResponse;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as GeminiRawResponse;\n\n // If the model rejected the native responseJsonSchema + tools combo,\n // cache it and retry with the legacy fake-tool emulation path.\n if (wantsNativeCombo && isStructuredOutputComboUnsupportedError(error)) {\n const model = geminiRequest.model;\n this.rememberModelRejectsStructuredOutputCombo(model);\n log.warn(\n `[GoogleAdapter] Model ${model} rejected native responseJsonSchema + tools combo; falling back to legacy structured_output tool emulation.`,\n );\n const fallbackRequest =\n this.toFallbackStructuredOutputRequest(geminiRequest);\n const response = await genAI.models.generateContent({\n model: fallbackRequest.model,\n contents: fallbackRequest.contents as any,\n config: fallbackRequest.config as any,\n });\n return response as unknown as GeminiRawResponse;\n }\n\n throw error;\n }\n }\n\n /**\n * Rebuild a Gemini 3 native-combo request without `responseJsonSchema`/\n * `responseMimeType`, swapping in the legacy fake-tool emulation. Used as\n * a runtime fallback when a Gemini 3 model rejects the combo.\n */\n private toFallbackStructuredOutputRequest(\n request: GeminiRequest,\n ): GeminiRequest {\n if (!request.config?.responseJsonSchema) return request;\n const schema = request.config.responseJsonSchema as JsonObject;\n const newConfig: GeminiRequest[\"config\"] = { ...request.config };\n delete (newConfig as Record<string, unknown>).responseJsonSchema;\n delete (newConfig as Record<string, unknown>).responseMimeType;\n\n const fakeTool: GeminiFunctionDeclaration = {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"Output a structured JSON object, \" +\n \"use this before your final response to give structured outputs to the user\",\n parameters: schema,\n };\n const existingDeclarations =\n newConfig.tools?.[0]?.functionDeclarations ?? [];\n newConfig.tools = [\n { functionDeclarations: [...existingDeclarations, fakeTool] },\n ];\n\n const structuredOutputInstruction =\n \"IMPORTANT: Before providing your final response, you MUST use the structured_output tool \" +\n \"to output your answer in the required JSON format.\";\n const existingSystem = newConfig.systemInstruction || \"\";\n newConfig.systemInstruction = existingSystem\n ? `${existingSystem}\\n\\n${structuredOutputInstruction}`\n : structuredOutputInstruction;\n\n return {\n ...request,\n config: newConfig,\n };\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n // signal is accepted for interface conformance; Gemini SDK does not natively support it\n void signal;\n const genAI = client as GoogleClient;\n const geminiRequest = request as GeminiRequest;\n\n // Use generateContentStream for streaming\n const stream = await genAI.models.generateContentStream({\n model: geminiRequest.model,\n contents: geminiRequest.contents as any,\n config: geminiRequest.config as any,\n });\n\n // Track usage for final chunk\n let inputTokens = 0;\n let outputTokens = 0;\n let reasoningTokens = 0;\n const model = geminiRequest.model || this.defaultModel;\n\n for await (const chunk of stream) {\n // Extract text content from the chunk\n const candidate = chunk.candidates?.[0];\n if (candidate?.content?.parts) {\n for (const part of candidate.content.parts) {\n // Handle text content (excluding thought parts)\n if (part.text && !part.thought) {\n yield {\n type: LlmStreamChunkType.Text,\n content: part.text,\n };\n }\n\n // Handle function calls\n if (part.functionCall) {\n const functionCall = part.functionCall as GeminiFunctionCall;\n const currentFunctionCall = {\n id: functionCall.id || this.generateCallId(),\n name: functionCall.name || \"\",\n arguments: functionCall.args || {},\n };\n\n // Preserve thoughtSignature for Gemini 3 models\n // Required to maintain tool call context between turns\n const metadata: Record<string, unknown> | undefined =\n part.thoughtSignature\n ? { thoughtSignature: part.thoughtSignature }\n : undefined;\n\n // Emit the function call immediately\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentFunctionCall.id,\n name: currentFunctionCall.name,\n arguments: JSON.stringify(currentFunctionCall.arguments),\n metadata,\n },\n };\n }\n }\n }\n\n // Extract usage metadata if present\n if (chunk.usageMetadata) {\n inputTokens = chunk.usageMetadata.promptTokenCount || 0;\n outputTokens = chunk.usageMetadata.candidatesTokenCount || 0;\n reasoningTokens = chunk.usageMetadata.thoughtsTokenCount || 0;\n }\n }\n\n // Emit done chunk with final usage\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: reasoningTokens,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n options?: LlmOperateOptions,\n ): ParsedResponse {\n const geminiResponse = response as GeminiRawResponse;\n\n const content = this.extractContent(geminiResponse, options);\n const hasToolCalls = this.hasToolCalls(geminiResponse);\n\n return {\n content,\n hasToolCalls,\n stopReason: this.getFinishReason(geminiResponse),\n usage: this.extractUsage(\n geminiResponse,\n options?.model || this.defaultModel,\n ),\n raw: geminiResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const geminiResponse = response as GeminiRawResponse;\n const toolCalls: StandardToolCall[] = [];\n\n const candidate = geminiResponse.candidates?.[0];\n if (!candidate?.content?.parts) {\n return toolCalls;\n }\n\n for (const part of candidate.content.parts) {\n if (part.functionCall) {\n const functionCall = part.functionCall as GeminiFunctionCall;\n toolCalls.push({\n callId: functionCall.id || this.generateCallId(),\n name: functionCall.name || \"\",\n arguments: JSON.stringify(functionCall.args || {}),\n raw: part,\n });\n }\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const geminiResponse = response as GeminiRawResponse;\n\n if (!geminiResponse.usageMetadata) {\n return {\n input: 0,\n output: 0,\n reasoning: 0,\n total: 0,\n provider: this.name,\n model,\n };\n }\n\n const usage = geminiResponse.usageMetadata;\n\n return {\n input: usage.promptTokenCount || 0,\n output: usage.candidatesTokenCount || 0,\n reasoning: usage.thoughtsTokenCount || 0,\n total: usage.totalTokenCount || 0,\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): GeminiPart {\n // Gemini's `function_response.response` is a protobuf Struct, which only\n // accepts plain objects. Some models (e.g. gemini-3.1-pro) accept scalar\n // values silently; gemini-3.1-flash-lite rejects them. Parse the output\n // and wrap any non-object value (string, number, boolean, array, null)\n // in `{ result: value }` so every tool result is a valid Struct.\n let responseData: Record<string, unknown>;\n try {\n const parsed = JSON.parse(result.output);\n if (\n parsed !== null &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ) {\n responseData = parsed as Record<string, unknown>;\n } else {\n responseData = { result: parsed };\n }\n } catch {\n responseData = { result: result.output };\n }\n\n return {\n functionResponse: {\n name: toolCall.name,\n response: responseData,\n },\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): GeminiRequest {\n const geminiRequest = request as GeminiRequest;\n const toolCallRaw = toolCall.raw as GeminiPart;\n const toolResponse = this.formatToolResult(toolCall, result);\n\n // Get the last two contents to check for existing tool call/response pattern\n const lastContent =\n geminiRequest.contents[geminiRequest.contents.length - 1];\n const secondLastContent =\n geminiRequest.contents[geminiRequest.contents.length - 2];\n\n // Check if we're adding to an existing tool call batch\n // Pattern: [..., model (with functionCall), user (with functionResponse)]\n const hasExistingToolBatch =\n lastContent?.role === \"user\" &&\n lastContent?.parts?.some((p) => p.functionResponse) &&\n secondLastContent?.role === \"model\" &&\n secondLastContent?.parts?.some((p) => p.functionCall);\n\n if (hasExistingToolBatch) {\n // Append to existing batch\n secondLastContent.parts!.push(toolCallRaw);\n lastContent.parts!.push(toolResponse);\n } else {\n // Create new batch\n geminiRequest.contents.push({\n role: \"model\",\n parts: [toolCallRaw],\n });\n geminiRequest.contents.push({\n role: \"user\",\n parts: [toolResponse],\n });\n }\n\n return geminiRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const geminiResponse = response as GeminiRawResponse;\n const historyItems: LlmHistory = [];\n\n const candidate = geminiResponse.candidates?.[0];\n if (!candidate?.content?.parts) {\n return historyItems;\n }\n\n // Check if this is a function call response\n const hasFunctionCalls = candidate.content.parts.some(\n (part) => part.functionCall,\n );\n\n if (hasFunctionCalls) {\n // Don't add to history yet - will be added after tool execution\n return historyItems;\n }\n\n // Extract text content for non-tool responses\n const textParts = candidate.content.parts.filter(\n (part) => part.text && !part.thought,\n );\n\n if (textParts.length > 0) {\n const textContent = textParts.map((part) => part.text).join(\"\");\n historyItems.push({\n content: textContent,\n role: LlmMessageRole.Assistant,\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n const geminiError = error as GeminiErrorInfo;\n\n // Extract status code from error\n const statusCode = geminiError.status || geminiError.code;\n\n // Check for rate limit error (429)\n if (statusCode === 429) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Check for retryable errors\n if (\n typeof statusCode === \"number\" &&\n RETRYABLE_STATUS_CODES.includes(statusCode)\n ) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Check for non-retryable errors\n if (\n typeof statusCode === \"number\" &&\n NOT_RETRYABLE_STATUS_CODES.includes(statusCode)\n ) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n\n // Check error message for common patterns\n const errorMessage = geminiError.message || String(error) || \"\";\n\n if (\n errorMessage.includes(\"rate limit\") ||\n errorMessage.includes(\"quota exceeded\")\n ) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n if (\n errorMessage.includes(\"timeout\") ||\n errorMessage.includes(\"connection\") ||\n errorMessage.includes(\"ECONNREFUSED\")\n ) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Check for transient network errors (ECONNRESET, etc.)\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Unknown error - treat as potentially retryable\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Provider-Specific Features\n //\n\n isComplete(response: unknown): boolean {\n const geminiResponse = response as GeminiRawResponse;\n\n const candidate = geminiResponse.candidates?.[0];\n if (!candidate?.content?.parts) {\n return true;\n }\n\n // Check if there are any function calls\n const hasFunctionCalls = candidate.content.parts.some(\n (part) => part.functionCall,\n );\n\n return !hasFunctionCalls;\n }\n\n override hasStructuredOutput(response: unknown): boolean {\n const geminiResponse = response as GeminiRawResponse;\n\n const candidate = geminiResponse.candidates?.[0];\n if (!candidate?.content?.parts) {\n return false;\n }\n\n // Check if the last part is a function call with structured_output\n const lastPart =\n candidate.content.parts[candidate.content.parts.length - 1];\n return lastPart?.functionCall?.name === STRUCTURED_OUTPUT_TOOL_NAME;\n }\n\n override extractStructuredOutput(response: unknown): JsonObject | undefined {\n const geminiResponse = response as GeminiRawResponse;\n\n const candidate = geminiResponse.candidates?.[0];\n if (!candidate?.content?.parts) {\n return undefined;\n }\n\n const lastPart =\n candidate.content.parts[candidate.content.parts.length - 1];\n if (lastPart?.functionCall?.name === STRUCTURED_OUTPUT_TOOL_NAME) {\n return lastPart.functionCall.args as JsonObject;\n }\n\n return undefined;\n }\n\n //\n // Private Helpers\n //\n\n private convertMessagesToContents(messages: LlmHistory): GeminiContent[] {\n const contents: GeminiContent[] = [];\n\n for (const message of messages) {\n // Handle input/output messages\n if (\"role\" in message && \"content\" in message) {\n const role = this.mapRole(message.role as LlmMessageRole);\n const parts = this.convertContentToParts(message.content);\n\n contents.push({\n role,\n parts,\n });\n }\n // Handle function call items\n else if (\n \"type\" in message &&\n message.type === LlmMessageType.FunctionCall\n ) {\n // Build the function call part, including thoughtSignature if present\n // (required for Gemini 3 models)\n const functionCallPart: GeminiPart = {\n functionCall: {\n name: (message as any).name,\n args: JSON.parse((message as any).arguments || \"{}\"),\n id: (message as any).call_id,\n },\n };\n // Preserve thoughtSignature for Gemini 3 models\n if ((message as any).thoughtSignature) {\n functionCallPart.thoughtSignature = (message as any).thoughtSignature;\n }\n contents.push({\n role: \"model\",\n parts: [functionCallPart],\n });\n }\n // Handle function call output items\n else if (\n \"type\" in message &&\n message.type === LlmMessageType.FunctionCallOutput\n ) {\n // Parse the output to get the actual response object\n let responseData: Record<string, unknown>;\n try {\n responseData = JSON.parse((message as any).output || \"{}\");\n } catch {\n responseData = { result: (message as any).output };\n }\n\n contents.push({\n role: \"user\",\n parts: [\n {\n functionResponse: {\n name: (message as any).name || \"function\",\n response: responseData,\n },\n },\n ],\n });\n }\n }\n\n return contents;\n }\n\n private convertContentToParts(content: unknown): GeminiPart[] {\n // Handle string content\n if (typeof content === \"string\") {\n return [{ text: content }];\n }\n\n // Handle array content\n if (Array.isArray(content)) {\n const parts: GeminiPart[] = [];\n\n for (const item of content) {\n // Handle Gemini-native parts (already have inlineData, text, etc.)\n if (item.inlineData) {\n parts.push({ inlineData: item.inlineData });\n continue;\n }\n\n if (item.text && !item.type) {\n // Plain text part\n parts.push({ text: item.text });\n continue;\n }\n\n if (item.fileData) {\n parts.push({ fileData: item.fileData });\n continue;\n }\n\n // Handle standardized LlmInputContentText\n if (item.type === LlmMessageType.InputText) {\n parts.push({ text: item.text });\n continue;\n }\n\n // Handle standardized LlmInputContentImage\n if (item.type === LlmMessageType.InputImage) {\n const imageUrl = item.image_url as string;\n // Parse data URL format: data:image/png;base64,<data>\n if (imageUrl?.startsWith(\"data:\")) {\n const match = imageUrl.match(/^data:([^;]+);base64,(.+)$/);\n if (match) {\n parts.push({\n inlineData: {\n mimeType: match[1],\n data: match[2],\n },\n });\n continue;\n }\n }\n // If not a data URL, try to use as file URI\n if (imageUrl) {\n parts.push({\n fileData: {\n mimeType: \"image/png\",\n fileUri: imageUrl,\n },\n });\n }\n continue;\n }\n\n // Handle standardized LlmInputContentFile\n if (item.type === LlmMessageType.InputFile) {\n const fileData = item.file_data as string;\n // Parse data URL format: data:application/pdf;base64,<data>\n if (fileData?.startsWith(\"data:\")) {\n const match = fileData.match(/^data:([^;]+);base64,(.+)$/);\n if (match) {\n parts.push({\n inlineData: {\n mimeType: match[1],\n data: match[2],\n },\n });\n continue;\n }\n }\n // If not a data URL, just add as text (fallback)\n if (typeof fileData === \"string\") {\n parts.push({ text: `[File: ${item.filename || \"unknown\"}]` });\n }\n continue;\n }\n\n // Fallback: stringify unknown content\n parts.push({ text: JSON.stringify(item) });\n }\n\n return parts;\n }\n\n // Fallback for other types\n return [{ text: JSON.stringify(content) }];\n }\n\n private mapRole(role: LlmMessageRole): \"user\" | \"model\" {\n switch (role) {\n case LlmMessageRole.User:\n case LlmMessageRole.System:\n case LlmMessageRole.Developer:\n return \"user\";\n case LlmMessageRole.Assistant:\n return \"model\";\n default:\n return \"user\";\n }\n }\n\n private hasToolCalls(response: GeminiRawResponse): boolean {\n const candidate = response.candidates?.[0];\n if (!candidate?.content?.parts) {\n return false;\n }\n\n return candidate.content.parts.some((part) => part.functionCall);\n }\n\n private getFinishReason(response: GeminiRawResponse): string | undefined {\n const candidate = response.candidates?.[0];\n return candidate?.finishReason;\n }\n\n private extractContent(\n response: GeminiRawResponse,\n options?: LlmOperateOptions,\n ): string | JsonObject | undefined {\n // Check for structured output first\n if (this.hasStructuredOutput(response)) {\n return this.extractStructuredOutput(response);\n }\n\n const candidate = response.candidates?.[0];\n if (!candidate?.content?.parts) {\n return undefined;\n }\n\n // Extract text content (excluding thought parts)\n const textParts = candidate.content.parts.filter(\n (part) => part.text && !part.thought,\n );\n\n if (textParts.length === 0) {\n return undefined;\n }\n\n const textContent = textParts.map((part) => part.text).join(\"\");\n\n // If format is provided, try to parse the content as JSON\n if (options?.format && typeof textContent === \"string\") {\n try {\n return JSON.parse(textContent);\n } catch {\n // Strip markdown code fences and retry (Gemini sometimes wraps JSON in fences)\n const jsonMatch =\n textContent.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/) ||\n textContent.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n return JSON.parse(jsonMatch[1] || jsonMatch[0]);\n } catch {\n // Fall through to return original string\n }\n }\n return textContent;\n }\n }\n\n return textContent;\n }\n\n private generateCallId(): string {\n return `call_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;\n }\n}\n\n// Export singleton instance\nexport const googleAdapter = new GoogleAdapter();\n","import { JsonObject } from \"@jaypie/types\";\n\nimport { parseSseStream } from \"../../util/sse.js\";\n\n//\n//\n// Constants\n//\n\nconst OPENAI_BASE_URL = \"https://api.openai.com/v1\";\n\n//\n//\n// Errors\n//\n// The adapter's `classifyError` uses `instanceof` against these classes, so the\n// client throws them directly. Status → class mapping mirrors the SDK; the\n// non-HTTP classes (connection/abort) are thrown when `fetch` itself rejects.\n//\n\nexport class OpenAiApiError extends Error {\n readonly status: number;\n readonly error?: { message?: string };\n\n constructor(status: number, message: string, error?: { message?: string }) {\n super(message);\n this.name = this.constructor.name;\n this.status = status;\n this.error = error;\n }\n}\n\nexport class BadRequestError extends OpenAiApiError {}\nexport class AuthenticationError extends OpenAiApiError {}\nexport class PermissionDeniedError extends OpenAiApiError {}\nexport class NotFoundError extends OpenAiApiError {}\nexport class ConflictError extends OpenAiApiError {}\nexport class UnprocessableEntityError extends OpenAiApiError {}\nexport class RateLimitError extends OpenAiApiError {}\nexport class InternalServerError extends OpenAiApiError {}\nexport class APIConnectionError extends OpenAiApiError {}\nexport class APIConnectionTimeoutError extends APIConnectionError {}\nexport class APIUserAbortError extends OpenAiApiError {}\n\nfunction errorForStatus(\n status: number,\n message: string,\n error?: { message?: string },\n): OpenAiApiError {\n if (status === 400) return new BadRequestError(status, message, error);\n if (status === 401) return new AuthenticationError(status, message, error);\n if (status === 403) return new PermissionDeniedError(status, message, error);\n if (status === 404) return new NotFoundError(status, message, error);\n if (status === 409) return new ConflictError(status, message, error);\n if (status === 422) {\n return new UnprocessableEntityError(status, message, error);\n }\n if (status === 429) return new RateLimitError(status, message, error);\n if (status >= 500) return new InternalServerError(status, message, error);\n return new OpenAiApiError(status, message, error);\n}\n\n//\n//\n// Types\n//\n\nexport interface OpenAIClientOptions {\n apiKey: string;\n baseURL?: string;\n}\n\nexport interface RequestOptions {\n signal?: AbortSignal;\n}\n\ninterface ResponsesApi {\n create(\n params: Record<string, unknown> & { stream: true },\n options?: RequestOptions,\n ): Promise<AsyncIterable<Record<string, unknown>>>;\n create(\n params: Record<string, unknown>,\n options?: RequestOptions,\n ): Promise<JsonObject>;\n}\n\ninterface ChatCompletionsApi {\n create(\n params: Record<string, unknown>,\n options?: RequestOptions,\n ): Promise<JsonObject>;\n parse(\n params: Record<string, unknown>,\n options?: RequestOptions,\n ): Promise<JsonObject>;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Minimal `fetch`-based client for the OpenAI API. Replaces the `openai` SDK —\n * the adapters and provider utilities only need the Responses API\n * (`/responses`, streaming and non-streaming) for `operate`/`stream` and the\n * Chat Completions API (`/chat/completions`, plus a `parse` helper for\n * structured output) for `send`. Mirrors the SDK's `responses.create` and\n * `chat.completions.create` / `chat.completions.parse` surface so call sites are\n * unchanged. Also serves xAI via a custom `baseURL`.\n */\nexport class OpenAIClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n readonly responses: ResponsesApi;\n readonly chat: { completions: ChatCompletionsApi };\n\n constructor({ apiKey, baseURL = OPENAI_BASE_URL }: OpenAIClientOptions) {\n this.apiKey = apiKey;\n this.baseURL = baseURL;\n this.responses = {\n create: ((params: Record<string, unknown>, options?: RequestOptions) =>\n params.stream\n ? this.createResponseStream(params, options)\n : this.createResponse(params, options)) as ResponsesApi[\"create\"],\n };\n this.chat = {\n completions: {\n create: (params, options) =>\n this.chatCompletion(params, options, { parse: false }),\n parse: (params, options) =>\n this.chatCompletion(params, options, { parse: true }),\n },\n };\n }\n\n private headers(extra?: Record<string, string>): Record<string, string> {\n return {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...extra,\n };\n }\n\n private async post(\n path: string,\n body: Record<string, unknown>,\n { signal }: RequestOptions = {},\n { stream = false }: { stream?: boolean } = {},\n ): Promise<Response> {\n let response: Response;\n try {\n response = await fetch(`${this.baseURL}${path}`, {\n method: \"POST\",\n headers: this.headers(\n stream ? { Accept: \"text/event-stream\" } : undefined,\n ),\n body: JSON.stringify(body),\n signal,\n });\n } catch (cause) {\n if (signal?.aborted) {\n throw new APIUserAbortError(0, \"Request was aborted\");\n }\n const message =\n cause instanceof Error ? cause.message : \"Connection error\";\n const error = new APIConnectionError(0, message);\n (error as { cause?: unknown }).cause = cause;\n throw error;\n }\n if (!response.ok) throw await this.toError(response);\n return response;\n }\n\n private async toError(response: Response): Promise<OpenAiApiError> {\n let message = `OpenAI request failed with status ${response.status}`;\n let error: { message?: string } | undefined;\n try {\n const body = (await response.json()) as { error?: { message?: string } };\n if (body?.error?.message) {\n message = body.error.message;\n error = body.error;\n }\n } catch {\n // Non-JSON error body; keep the status-based message.\n }\n return errorForStatus(response.status, message, error);\n }\n\n private async createResponse(\n params: Record<string, unknown>,\n options?: RequestOptions,\n ): Promise<JsonObject> {\n const response = await this.post(\"/responses\", params, options);\n return (await response.json()) as JsonObject;\n }\n\n private async createResponseStream(\n params: Record<string, unknown>,\n options?: RequestOptions,\n ): Promise<AsyncIterable<Record<string, unknown>>> {\n const response = await this.post(\"/responses\", params, options, {\n stream: true,\n });\n if (!response.body) return (async function* () {})();\n // The Responses API streams typed events and does not emit a `[DONE]`\n // sentinel; the empty default sentinel never matches, so the stream ends\n // when the connection closes.\n return parseSseStream(response.body);\n }\n\n private async chatCompletion(\n params: Record<string, unknown>,\n options: RequestOptions | undefined,\n { parse }: { parse: boolean },\n ): Promise<JsonObject> {\n const response = await this.post(\"/chat/completions\", params, options);\n const json = (await response.json()) as JsonObject;\n // `chat.completions.parse` surfaces parsed JSON on each message; replicate\n // the SDK by JSON-parsing the assistant content into `message.parsed`.\n if (parse) {\n const choices = json.choices as\n Array<Record<string, unknown>> | undefined;\n if (Array.isArray(choices)) {\n for (const choice of choices) {\n const message = choice.message as Record<string, unknown> | undefined;\n if (\n message &&\n typeof message.content === \"string\" &&\n !message.refusal\n ) {\n try {\n message.parsed = JSON.parse(message.content);\n } catch {\n message.parsed = null;\n }\n }\n }\n }\n }\n return json;\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\n//\n//\n// Types\n//\n\nexport interface JsonSchemaResponseFormat {\n type: \"json_schema\";\n json_schema: {\n name: string;\n strict: boolean;\n schema: JsonObject;\n };\n}\n\n//\n//\n// Main\n//\n\n/**\n * Local replacement for `openai/helpers/zod`'s `zodResponseFormat`. Builds the\n * `response_format` payload OpenAI's Chat Completions / Responses APIs expect\n * from a Zod schema. The SDK always emits `strict: true`; callers re-derive or\n * sanitize `schema` as needed (e.g. forcing `additionalProperties: false`).\n */\nexport function zodResponseFormat(\n schema: z.ZodType,\n name: string,\n): JsonSchemaResponseFormat {\n return {\n type: \"json_schema\",\n json_schema: {\n name,\n strict: true,\n schema: z.toJSONSchema(schema) as JsonObject,\n },\n };\n}\n","import { log } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { type LlmEffort, PROVIDER } from \"../../constants.js\";\nimport {\n type LlmEffortMapping,\n paperedEffortMessage,\n toOpenAiEffort,\n} from \"../../util/effort.js\";\nimport {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n InternalServerError,\n NotFoundError,\n OpenAIClient,\n PermissionDeniedError,\n RateLimitError,\n UnprocessableEntityError,\n} from \"../../providers/openai/client.js\";\nimport { zodResponseFormat } from \"../../providers/openai/responseFormat.js\";\n\n// Patterns for OpenAI reasoning models that support extended thinking\nconst REASONING_MODEL_PATTERNS = [\n /^gpt-[5-9]/, // GPT-5 and above (gpt-5, gpt-5.1, gpt-5.2, gpt-6, etc.)\n /^o\\d/, // O-series (o1, o3, o4, o5, etc.)\n] as const;\n\n/**\n * Check if a model is a reasoning model that supports extended thinking\n */\nfunction isReasoningModel(model: string): boolean {\n return REASONING_MODEL_PATTERNS.some((pattern) => pattern.test(model));\n}\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmMessageType,\n LlmOperateOptions,\n LlmToolResult,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n isJsonSchema,\n naturalZodSchema,\n promptCacheKey,\n resolveCache,\n} from \"../../util/index.js\";\nimport { OpenAIRawResponse } from \"../../providers/openai/types.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\n\n//\n//\n// Constants\n//\n\nconst RETRYABLE_ERROR_TYPES = [\n APIConnectionError,\n APIConnectionTimeoutError,\n InternalServerError,\n];\n\nconst NOT_RETRYABLE_ERROR_TYPES = [\n APIUserAbortError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n NotFoundError,\n PermissionDeniedError,\n RateLimitError,\n UnprocessableEntityError,\n];\n\n// Models known not to accept `temperature`.\n// Patterns (not exact names) so dated variants and future releases are covered\n// without code changes — OpenAI is removing temperature on newer reasoning\n// models.\nconst MODELS_WITHOUT_TEMPERATURE: RegExp[] = [\n /^gpt-5\\.5/, // gpt-5.5 series deprecated temperature\n /^o\\d/, // o-series reasoning models (o1, o3, o4, ...)\n];\n\nfunction isTemperatureDeprecationError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n if (\n !(error instanceof BadRequestError) &&\n (error as { status?: number }).status !== 400\n ) {\n return false;\n }\n const messages = [\n (error as { message?: string }).message,\n (error as { error?: { message?: string } }).error?.message,\n ].filter((m): m is string => typeof m === \"string\");\n return messages.some((m) => m.toLowerCase().includes(\"temperature\"));\n}\n\n//\n//\n// Main\n//\n\n/**\n * OpenAiAdapter implements the ProviderAdapter interface for OpenAI's API.\n * It handles request building, response parsing, and error classification\n * specific to OpenAI's Responses API.\n */\nexport class OpenAiAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.OPENAI.NAME;\n readonly defaultModel = PROVIDER.OPENAI.DEFAULT;\n\n // Session-level cache of models observed to reject `temperature` at runtime.\n // Populated by executeRequest on 400 errors so repeat calls skip the param.\n private runtimeNoTemperatureModels = new Set<string>();\n\n rememberModelRejectsTemperature(model: string): void {\n this.runtimeNoTemperatureModels.add(model);\n }\n\n clearRuntimeNoTemperatureModels(): void {\n this.runtimeNoTemperatureModels.clear();\n }\n\n private supportsTemperature(model: string): boolean {\n if (this.runtimeNoTemperatureModels.has(model)) return false;\n return !MODELS_WITHOUT_TEMPERATURE.some((pattern) => pattern.test(model));\n }\n\n /** Whether `reasoning.effort` may be sent for this model. Overridden by xAI. */\n protected supportsReasoningEffort(model: string): boolean {\n return isReasoningModel(model);\n }\n\n /**\n * Whether to emit `prompt_cache_key` (OpenAI Responses API). Overridable by\n * OpenAI-compatible subclasses whose backend rejects the field.\n */\n protected supportsPromptCacheKey(): boolean {\n return true;\n }\n\n /** Translate a normalized effort to this provider's `reasoning.effort` value. */\n protected mapReasoningEffort(\n effort: LlmEffort,\n model: string,\n ): LlmEffortMapping {\n return toOpenAiEffort(effort, { model });\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): unknown {\n const model = request.model || this.defaultModel;\n const openaiRequest: Record<string, unknown> = {\n model,\n input: this.sanitizeInputItems(request.messages),\n };\n\n if (request.user) {\n openaiRequest.user = request.user;\n }\n\n if (request.instructions) {\n openaiRequest.instructions = request.instructions;\n }\n\n if (request.tools && request.tools.length > 0) {\n openaiRequest.tools = request.tools.map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n }));\n }\n\n if (request.format) {\n openaiRequest.text = {\n format: request.format,\n };\n }\n\n // Enable reasoning summary for reasoning models (o1, o3, etc.)\n // This allows us to extract reasoning text from the response\n if (isReasoningModel(model)) {\n openaiRequest.reasoning = {\n summary: \"auto\",\n };\n }\n\n // OpenAI prompt caching is automatic (prefix-based). Setting a stable\n // prompt_cache_key routes repeat traffic to the same cache across\n // instances. Keyed on the stable prefix only (system + instructions +\n // tools + model), never the volatile user turn.\n if (this.supportsPromptCacheKey() && resolveCache(request.cache).enabled) {\n openaiRequest.prompt_cache_key = promptCacheKey(\n JSON.stringify([\n model,\n request.system ?? \"\",\n request.instructions ?? \"\",\n request.tools ?? [],\n ]),\n );\n }\n\n if (request.providerOptions) {\n Object.assign(openaiRequest, request.providerOptions);\n }\n\n // Normalized reasoning effort -> reasoning.effort (merged so the\n // summary:auto above survives). First-class effort wins over providerOptions.\n if (request.effort && this.supportsReasoningEffort(model)) {\n const mapping = this.mapReasoningEffort(request.effort, model);\n if (mapping.papered) {\n log.debug(\n paperedEffortMessage({\n model,\n provider: this.name,\n requested: request.effort,\n value: mapping.value,\n }),\n );\n }\n const existingReasoning =\n (openaiRequest.reasoning as Record<string, unknown> | undefined) ?? {};\n openaiRequest.reasoning = {\n ...existingReasoning,\n effort: mapping.value,\n };\n }\n\n // First-class temperature takes precedence over providerOptions\n if (request.temperature !== undefined) {\n openaiRequest.temperature = request.temperature;\n }\n\n // Strip temperature for models that don't support it (denylist + runtime cache)\n if (\n openaiRequest.temperature !== undefined &&\n !this.supportsTemperature(openaiRequest.model as string)\n ) {\n delete openaiRequest.temperature;\n }\n\n return openaiRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n _outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n // Check if schema is already a JsonObject with type \"json_schema\"\n if (\n typeof schema === \"object\" &&\n schema !== null &&\n !Array.isArray(schema) &&\n (schema as JsonObject).type === \"json_schema\"\n ) {\n return schema as JsonObject;\n }\n\n // Bare JSON Schema node: `{ type: \"object\", properties: {...} }`\n // Skip the zod round-trip and use it directly (still needs the\n // additionalProperties + envelope treatment below).\n let jsonSchema: Record<string, unknown>;\n let name = \"response\";\n let strict = true;\n if (isJsonSchema(schema)) {\n jsonSchema = { ...structuredClone(schema) };\n delete jsonSchema.$schema;\n } else {\n // Convert NaturalSchema to Zod schema if needed\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n\n const responseFormat = zodResponseFormat(zodSchema as any, \"response\");\n // Re-spread to drop zod v4's non-enumerable `~standard` Standard-Schema\n // interop marker, then strip `$schema`: OpenAI's strict json_schema subset\n // does not recognize the draft-2020-12 `$schema` keyword, and shipping it\n // can leave strict structured-output enforcement silently disabled (the\n // model then free-forms, omitting required fields and corrupting keys).\n // Mirrors the OpenRouter adapter's sanitization.\n jsonSchema = {\n ...(z.toJSONSchema(zodSchema) as Record<string, unknown>),\n };\n delete jsonSchema.$schema;\n name = responseFormat.json_schema.name;\n strict = responseFormat.json_schema.strict as boolean;\n }\n\n // OpenAI requires additionalProperties to be false on all objects\n const checks = [jsonSchema];\n while (checks.length > 0) {\n const current = checks[0] as Record<string, unknown>;\n if (current.type === \"object\") {\n current.additionalProperties = false;\n }\n Object.keys(current).forEach((key) => {\n if (typeof current[key] === \"object\" && current[key] !== null) {\n checks.push(current[key] as Record<string, unknown>);\n }\n });\n checks.shift();\n }\n\n return {\n name,\n schema: jsonSchema as JsonObject,\n strict,\n type: \"json_schema\",\n };\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<unknown> {\n const openai = client as OpenAIClient;\n const openaiRequest = request as Record<string, unknown>;\n try {\n return await openai.responses.create(\n openaiRequest,\n signal ? { signal } : undefined,\n );\n } catch (error) {\n if (signal?.aborted) return undefined;\n\n // If the model rejected `temperature`, cache it and retry without the param\n if (\n openaiRequest.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(openaiRequest.model as string);\n const retryRequest = { ...openaiRequest };\n delete retryRequest.temperature;\n return await openai.responses.create(\n retryRequest,\n signal ? { signal } : undefined,\n );\n }\n\n throw error;\n }\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const openai = client as OpenAIClient;\n const baseRequest = request as Record<string, unknown>;\n const streamRequest = {\n ...baseRequest,\n stream: true as const,\n };\n\n const stream = await openai.responses.create(\n streamRequest,\n signal ? { signal } : undefined,\n );\n\n // Track current function call being built\n let currentFunctionCall: {\n id: string;\n callId: string;\n name: string;\n arguments: string;\n } | null = null;\n\n // Track usage for final chunk\n let inputTokens = 0;\n let outputTokens = 0;\n let reasoningTokens = 0;\n const model = (baseRequest.model as string) || this.defaultModel;\n\n // Cast to async iterable - when stream: true, this is always a Stream<ResponseStreamEvent>\n const asyncStream = stream as AsyncIterable<Record<string, unknown>>;\n for await (const event of asyncStream) {\n const eventType = event.type as string;\n\n if (eventType === \"response.output_text.delta\") {\n // Text content delta\n const delta = (event as { delta?: string }).delta;\n if (delta) {\n yield {\n type: LlmStreamChunkType.Text,\n content: delta,\n };\n }\n } else if (eventType === \"response.function_call_arguments.delta\") {\n // Function call arguments delta - accumulate\n const delta = (event as { delta?: string }).delta;\n if (delta && currentFunctionCall) {\n currentFunctionCall.arguments += delta;\n }\n } else if (eventType === \"response.output_item.added\") {\n // New output item - check if it's a function call\n const item = (\n event as {\n item?: {\n type?: string;\n id?: string;\n call_id?: string;\n name?: string;\n };\n }\n ).item;\n if (item?.type === \"function_call\") {\n currentFunctionCall = {\n id: item.id || \"\",\n callId: item.call_id || \"\",\n name: item.name || \"\",\n arguments: \"\",\n };\n }\n } else if (eventType === \"response.output_item.done\") {\n // Output item completed - emit function call if that's what we were building\n if (currentFunctionCall) {\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentFunctionCall.callId,\n name: currentFunctionCall.name,\n arguments: currentFunctionCall.arguments,\n // Preserve the item ID (fc_...) separately from call_id (call_...)\n // OpenAI Responses API requires both with correct prefixes\n metadata: { itemId: currentFunctionCall.id },\n },\n };\n currentFunctionCall = null;\n }\n } else if (eventType === \"response.completed\") {\n // Response completed - extract final usage\n const response = (event as { response?: OpenAIRawResponse }).response;\n if (response?.usage) {\n inputTokens = response.usage.input_tokens || 0;\n outputTokens = response.usage.output_tokens || 0;\n reasoningTokens =\n response.usage.output_tokens_details?.reasoning_tokens || 0;\n }\n } else if (eventType === \"response.done\") {\n // Stream done - emit final chunk with usage\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: reasoningTokens,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n }\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n options?: LlmOperateOptions,\n ): ParsedResponse {\n const openaiResponse = response as OpenAIRawResponse;\n\n const content = this.extractContent(openaiResponse, options);\n const hasToolCalls = this.hasToolCalls(openaiResponse);\n\n return {\n content,\n hasToolCalls,\n stopReason: openaiResponse.status as string | undefined,\n usage: this.extractUsage(\n openaiResponse,\n options?.model || this.defaultModel,\n ),\n raw: openaiResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const openaiResponse = response as OpenAIRawResponse;\n const toolCalls: StandardToolCall[] = [];\n\n if (!openaiResponse.output || !Array.isArray(openaiResponse.output)) {\n return toolCalls;\n }\n\n for (const output of openaiResponse.output) {\n if (output.type === LlmMessageType.FunctionCall) {\n toolCalls.push({\n callId: output.call_id,\n name: output.name,\n arguments: output.arguments,\n raw: output,\n });\n }\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const openaiResponse = response as OpenAIRawResponse;\n\n if (!openaiResponse.usage) {\n return {\n input: 0,\n output: 0,\n reasoning: 0,\n total: 0,\n provider: this.name,\n model,\n };\n }\n\n const cachedTokens =\n openaiResponse.usage.input_tokens_details?.cached_tokens;\n return {\n input: openaiResponse.usage.input_tokens || 0,\n output: openaiResponse.usage.output_tokens || 0,\n reasoning:\n openaiResponse.usage.output_tokens_details?.reasoning_tokens || 0,\n total: openaiResponse.usage.total_tokens || 0,\n ...(cachedTokens !== undefined ? { cacheRead: cachedTokens } : {}),\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): LlmToolResult {\n return {\n call_id: toolCall.callId,\n output: result.output,\n type: LlmMessageType.FunctionCallOutput,\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): unknown {\n const openaiRequest = request as Record<string, unknown>;\n const input = openaiRequest.input as unknown[];\n\n // Note: The function_call item has already been added via responseToHistoryItems\n // which is called before processing tool calls. This includes any required\n // reasoning items that precede the function_call.\n\n // Add only the function call result\n input.push({\n call_id: toolCall.callId,\n output: result.output,\n type: LlmMessageType.FunctionCallOutput,\n });\n\n return openaiRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const openaiResponse = response as OpenAIRawResponse;\n const historyItems: LlmHistory = [];\n\n if (!openaiResponse.output || !Array.isArray(openaiResponse.output)) {\n return historyItems;\n }\n\n // Include all output items, including reasoning items\n // OpenAI requires reasoning items to be present when a function_call references them\n for (const output of openaiResponse.output) {\n historyItems.push(output);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n // Check for rate limit error\n if (error instanceof RateLimitError) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false, // Rate limit requires waiting, not immediate retry\n suggestedDelayMs: 60000, // 1 minute default\n };\n }\n\n // Check for retryable errors\n for (const ErrorType of RETRYABLE_ERROR_TYPES) {\n if (error instanceof ErrorType) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n }\n\n // Check for non-retryable errors\n for (const ErrorType of NOT_RETRYABLE_ERROR_TYPES) {\n if (error instanceof ErrorType) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n }\n\n // Check for transient network errors (ECONNRESET, etc.)\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Unknown error - treat as potentially retryable\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Provider-Specific Features\n //\n\n isComplete(response: unknown): boolean {\n const openaiResponse = response as OpenAIRawResponse;\n\n // Check if there are any function calls in the output\n if (!openaiResponse.output || !Array.isArray(openaiResponse.output)) {\n return true;\n }\n\n for (const output of openaiResponse.output) {\n if (output.type === LlmMessageType.FunctionCall) {\n return false;\n }\n }\n\n return true;\n }\n\n //\n // Private Helpers\n //\n\n /**\n * Sanitize history items for the OpenAI Responses API.\n * Strips fields not accepted by specific item types (e.g., `name` on\n * function_call_output items) to prevent 400 \"Unknown parameter\" errors.\n */\n private sanitizeInputItems(messages: LlmHistory): unknown[] {\n return messages.map((item) => {\n const typedItem = item as unknown as Record<string, unknown>;\n\n // function_call_output only accepts: type, call_id, output, id, status\n if (typedItem.type === LlmMessageType.FunctionCallOutput) {\n const sanitized: Record<string, unknown> = {\n type: typedItem.type,\n call_id: typedItem.call_id,\n output: typedItem.output,\n };\n if (typedItem.id) sanitized.id = typedItem.id;\n if (typedItem.status) sanitized.status = typedItem.status;\n return sanitized;\n }\n\n // All other items pass through as-is\n return item;\n });\n }\n\n private hasToolCalls(response: OpenAIRawResponse): boolean {\n if (!response.output || !Array.isArray(response.output)) {\n return false;\n }\n\n return response.output.some(\n (output) => output.type === LlmMessageType.FunctionCall,\n );\n }\n\n private extractContent(\n response: OpenAIRawResponse,\n options?: LlmOperateOptions,\n ): string | JsonObject | undefined {\n if (!response.output || !Array.isArray(response.output)) {\n return undefined;\n }\n\n for (const output of response.output) {\n if (output.type === LlmMessageType.Message) {\n if (\n output.content?.[0] &&\n output.content[0].type === LlmMessageType.OutputText\n ) {\n const rawContent = output.content[0].text;\n\n // If format is provided, try to parse the content as JSON\n if (options?.format && typeof rawContent === \"string\") {\n try {\n return JSON.parse(rawContent);\n } catch {\n // If parsing fails, return the original string\n return rawContent;\n }\n }\n\n return rawContent;\n }\n }\n\n // Skip reasoning and function call items when extracting content\n if (\n output.type === \"reasoning\" ||\n output.type === LlmMessageType.FunctionCall\n ) {\n continue;\n }\n }\n\n return undefined;\n }\n}\n\n// Export singleton instance\nexport const openAiAdapter = new OpenAiAdapter();\n","import { log } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { toOpenRouterEffort } from \"../../util/effort.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmInputContent,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n isJsonSchema,\n naturalZodSchema,\n resolveCache,\n} from \"../../util/index.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { OpenRouterClient } from \"../../providers/openrouter/client.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\n\n//\n//\n// Types\n//\n\n// Request types - SDK validates using camelCase internally\ninterface OpenRouterMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content?: string | OpenRouterContentPart[] | null;\n toolCalls?: OpenRouterToolCall[];\n toolCallId?: string;\n}\n\ninterface OpenRouterToolCall {\n id: string;\n type: \"function\";\n function: {\n name: string;\n arguments: string;\n };\n}\n\n// Response types (camelCase - what SDK returns)\ninterface OpenRouterResponseMessage {\n role: \"assistant\";\n content?: string | null;\n toolCalls?: OpenRouterToolCall[];\n refusal?: string | null;\n reasoning?: string | null;\n}\n\ninterface OpenRouterChoice {\n index: number;\n message: OpenRouterResponseMessage;\n finishReason: string | null;\n finish_reason?: string | null; // Some responses may use snake_case\n}\n\ninterface OpenRouterUsage {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n // Also support snake_case for backward compatibility\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n // Reasoning tokens (some models like z-ai/glm include this)\n completionTokensDetails?: {\n reasoningTokens?: number;\n };\n // Cache-read tokens forwarded from Anthropic/Gemini backends\n promptTokensDetails?: {\n cachedTokens?: number;\n cached_tokens?: number;\n };\n prompt_tokens_details?: {\n cached_tokens?: number;\n };\n}\n\ninterface OpenRouterResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: OpenRouterChoice[];\n usage?: OpenRouterUsage;\n}\n\ninterface OpenRouterTool {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: JsonObject;\n };\n}\n\ninterface OpenRouterJsonSchemaConfig {\n name: string;\n description?: string;\n schema: JsonObject;\n strict?: boolean;\n}\n\ntype OpenRouterResponseFormat =\n | { type: \"json_schema\"; json_schema: OpenRouterJsonSchemaConfig }\n | { type: \"json_object\" }\n | { type: \"text\" };\n\ninterface OpenRouterRequest {\n model: string;\n messages: OpenRouterMessage[];\n tools?: OpenRouterTool[];\n tool_choice?: \"auto\" | \"none\" | \"required\";\n response_format?: OpenRouterResponseFormat;\n reasoning?: { effort?: string; max_tokens?: number };\n user?: string;\n}\n\n/**\n * OpenRouter responses we annotate at receive time so downstream stateless\n * methods (`hasStructuredOutput`, `extractStructuredOutput`) can tell whether\n * the request asked for native structured output without re-threading the\n * request.\n */\ntype AnnotatedOpenRouterResponse = OpenRouterResponse & {\n __jaypieStructuredOutput?: boolean;\n};\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\nconst STRUCTURED_OUTPUT_SCHEMA_NAME = \"response\";\n\n/**\n * Detect 4xx errors that indicate the model itself does not support\n * `response_format: json_schema`. Mirrors the Anthropic pattern: we only\n * trigger the fake-tool fallback when the failure is plausibly a capability\n * gap, not a generic 400.\n */\nfunction isStructuredOutputUnsupportedError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n statusCode?: number;\n message?: string;\n error?: { message?: string };\n };\n const status = err.status ?? err.statusCode;\n if (status !== 400 && status !== 422) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) =>\n /response_format|json[_ ]schema|structured[_ ]output|require[_ ]parameters/i.test(\n m,\n ),\n );\n}\n\n// OpenRouter routes that don't accept `temperature`. Patterns match the\n// vendor-prefixed route id (e.g. `openai/gpt-5.5`) so dated variants are\n// covered without code changes.\nconst MODELS_WITHOUT_TEMPERATURE: RegExp[] = [\n /^openai\\/gpt-5\\.5/,\n /^openai\\/o\\d/,\n /^anthropic\\/claude-opus-4-[789]/,\n /^anthropic\\/claude-opus-[5-9]/,\n];\n\nfunction isTemperatureDeprecationError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n statusCode?: number;\n message?: string;\n error?: { message?: string };\n };\n const status = err.status ?? err.statusCode;\n if (status !== 400) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) => m.toLowerCase().includes(\"temperature\"));\n}\n\n/**\n * OpenRouter content part types. OpenRouter follows the OpenAI Chat\n * Completions multimodal schema and forwards `image_url` and `file` parts\n * to vision/PDF-capable backends. The SDK accepts camelCase fields at the\n * input boundary (`imageUrl`, `fileData`) and transforms to snake_case on\n * the wire.\n */\ntype OpenRouterContentPart =\n | {\n type: \"text\";\n text: string;\n cache_control?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" };\n }\n | { type: \"image_url\"; imageUrl: { url: string } }\n | { type: \"file\"; file: { filename?: string; fileData: string } };\n\n/**\n * Convert standardized content items to OpenRouter format. Images become\n * `image_url` parts and files become `file` parts; both pass through to\n * OpenRouter which routes to the selected backend. Backends that don't\n * support the modality 4xx — that's a model-capability mismatch, surfaced\n * by the call rather than silently dropped here.\n */\nfunction convertContentToOpenRouter(\n content: string | LlmInputContent[],\n): string | OpenRouterContentPart[] {\n if (typeof content === \"string\") {\n return content;\n }\n\n const parts: OpenRouterContentPart[] = [];\n\n for (const item of content) {\n if (item.type === LlmMessageType.InputText) {\n parts.push({ type: \"text\", text: item.text });\n continue;\n }\n\n if (item.type === LlmMessageType.InputImage) {\n const url = item.image_url ?? \"\";\n if (!url) {\n log.warn(\"OpenRouter image content missing image_url; image discarded\");\n continue;\n }\n parts.push({ type: \"image_url\", imageUrl: { url } });\n continue;\n }\n\n if (item.type === LlmMessageType.InputFile) {\n const fileData = typeof item.file_data === \"string\" ? item.file_data : \"\";\n if (!fileData) {\n log.warn(\n { filename: item.filename },\n \"OpenRouter file content missing file_data; file discarded\",\n );\n continue;\n }\n parts.push({\n type: \"file\",\n file: {\n filename: item.filename,\n fileData,\n },\n });\n continue;\n }\n\n // Unknown type - warn and skip\n log.warn({ item }, \"Unknown content type for OpenRouter; discarded\");\n }\n\n // If no parts remain, return empty string to avoid empty array\n if (parts.length === 0) {\n return \"\";\n }\n\n return parts;\n}\n\n/**\n * Convert internal content parts to the OpenAI-compatible wire shape. The\n * internal representation uses camelCase keys (`imageUrl`, `fileData`) that the\n * SDK accepted; the REST API wants snake_case (`image_url`, `file_data`).\n */\nfunction contentToWire(\n content: string | OpenRouterContentPart[] | null | undefined,\n): unknown {\n if (\n content === null ||\n content === undefined ||\n typeof content === \"string\"\n ) {\n return content;\n }\n return content.map((part) => {\n if (part.type === \"image_url\") {\n return { type: \"image_url\", image_url: part.imageUrl };\n }\n if (part.type === \"file\") {\n return {\n type: \"file\",\n file: { filename: part.file.filename, file_data: part.file.fileData },\n };\n }\n return part;\n });\n}\n\n/**\n * Serialize an internal message to the OpenAI-compatible wire shape, mapping\n * camelCase tool fields (`toolCalls`, `toolCallId`) to snake_case. Tool-call\n * objects are already wire-shaped (`{ id, type, function: { name, arguments } }`).\n */\nfunction messageToWire(message: OpenRouterMessage): Record<string, unknown> {\n const wire: Record<string, unknown> = { role: message.role };\n if (message.content !== undefined) {\n wire.content = contentToWire(message.content);\n }\n if (message.toolCalls) {\n wire.tool_calls = message.toolCalls;\n }\n if (message.toolCallId) {\n wire.tool_call_id = message.toolCallId;\n }\n return wire;\n}\n\n// OpenRouter error types based on HTTP status codes\nconst RETRYABLE_STATUS_CODES = [408, 500, 502, 503, 524, 529];\nconst RATE_LIMIT_STATUS_CODE = 429;\n\n/**\n * Walk the JSON schema and force `additionalProperties: false` on every\n * object node. Required by the OpenAI-style json_schema response_format\n * (which OpenRouter accepts) when `strict: true`.\n */\nfunction enforceAdditionalPropertiesFalse(schema: JsonObject): void {\n const stack: JsonObject[] = [schema];\n while (stack.length > 0) {\n const node = stack.pop() as JsonObject;\n if (node.type === \"object\") {\n node.additionalProperties = false;\n }\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const entry of value) {\n if (entry && typeof entry === \"object\" && !Array.isArray(entry)) {\n stack.push(entry as JsonObject);\n }\n }\n } else if (value && typeof value === \"object\") {\n stack.push(value as JsonObject);\n }\n }\n }\n}\n\n//\n//\n// Main\n//\n\n/**\n * OpenRouterAdapter implements the ProviderAdapter interface for OpenRouter's API.\n * OpenRouter provides a unified API to access hundreds of AI models through OpenAI-compatible endpoints.\n * It handles request building, response parsing, and error classification\n * specific to OpenRouter's Chat Completions API.\n */\nexport class OpenRouterAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.OPENROUTER.NAME;\n readonly defaultModel = PROVIDER.OPENROUTER.DEFAULT;\n\n // Session-level cache of models observed to reject native\n // `response_format: json_schema`. When a model is in this set, buildRequest\n // engages the legacy fake-tool path instead of native structured output.\n private runtimeNoStructuredOutputModels = new Set<string>();\n\n rememberModelRejectsStructuredOutput(model: string): void {\n this.runtimeNoStructuredOutputModels.add(model);\n }\n\n clearRuntimeNoStructuredOutputModels(): void {\n this.runtimeNoStructuredOutputModels.clear();\n }\n\n private supportsStructuredOutput(model: string): boolean {\n return !this.runtimeNoStructuredOutputModels.has(model);\n }\n\n // Session-level cache of routes observed to reject `temperature`. Populated\n // by executeRequest on 400 errors so repeat calls skip the param.\n private runtimeNoTemperatureModels = new Set<string>();\n\n rememberModelRejectsTemperature(model: string): void {\n this.runtimeNoTemperatureModels.add(model);\n }\n\n clearRuntimeNoTemperatureModels(): void {\n this.runtimeNoTemperatureModels.clear();\n }\n\n private supportsTemperature(model: string): boolean {\n if (this.runtimeNoTemperatureModels.has(model)) return false;\n return !MODELS_WITHOUT_TEMPERATURE.some((pattern) => pattern.test(model));\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): OpenRouterRequest {\n // Convert messages to OpenRouter format (OpenAI-compatible)\n const cache = resolveCache(request.cache);\n const messages: OpenRouterMessage[] = this.convertMessagesToOpenRouter(\n request.messages,\n request.system,\n cache.enabled\n ? {\n type: \"ephemeral\",\n ...(cache.ttl === \"1h\" ? { ttl: \"1h\" as const } : {}),\n }\n : undefined,\n );\n\n // Append instructions to last message if provided\n if (request.instructions && messages.length > 0) {\n const lastMsg = messages[messages.length - 1];\n if (lastMsg.content && typeof lastMsg.content === \"string\") {\n lastMsg.content = lastMsg.content + \"\\n\\n\" + request.instructions;\n }\n }\n\n const openRouterRequest: OpenRouterRequest = {\n model: request.model || this.defaultModel,\n messages,\n };\n\n if (request.user) {\n openRouterRequest.user = request.user;\n }\n\n const useFallbackStructuredOutput =\n Boolean(request.format) &&\n !this.supportsStructuredOutput(openRouterRequest.model);\n\n const allTools: ProviderToolDefinition[] = request.tools\n ? [...request.tools]\n : [];\n if (useFallbackStructuredOutput && request.format) {\n log.warn(\n `[OpenRouterAdapter] Using legacy structured_output tool fallback for model ${openRouterRequest.model}; native response_format previously rejected for this model.`,\n );\n allTools.push({\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n parameters: request.format,\n });\n }\n\n if (allTools.length > 0) {\n openRouterRequest.tools = allTools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n\n // Use \"auto\" for tool_choice - many OpenRouter models don't support \"required\"\n // The structured_output tool prompt already emphasizes it must be called\n openRouterRequest.tool_choice = \"auto\";\n }\n\n // Native structured output: send schema as `response_format`. The legacy\n // tool-emulation path is engaged only as a runtime fallback for models the\n // API has flagged as not supporting native json_schema.\n if (request.format && !useFallbackStructuredOutput) {\n openRouterRequest.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: STRUCTURED_OUTPUT_SCHEMA_NAME,\n schema: request.format,\n strict: true,\n },\n };\n }\n\n if (request.providerOptions) {\n Object.assign(openRouterRequest, request.providerOptions);\n }\n\n // Normalized reasoning effort -> reasoning.effort. OpenRouter accepts the\n // full ladder and maps to the routed provider's nearest supported level.\n // First-class effort wins over providerOptions.\n if (request.effort) {\n openRouterRequest.reasoning = {\n ...openRouterRequest.reasoning,\n effort: toOpenRouterEffort(request.effort).value,\n };\n }\n\n // First-class temperature takes precedence over providerOptions\n if (request.temperature !== undefined) {\n (openRouterRequest as unknown as Record<string, unknown>).temperature =\n request.temperature;\n }\n\n // Strip temperature for routes that don't support it (denylist + runtime cache)\n const requestRecord = openRouterRequest as unknown as Record<\n string,\n unknown\n >;\n if (\n requestRecord.temperature !== undefined &&\n !this.supportsTemperature(openRouterRequest.model)\n ) {\n delete requestRecord.temperature;\n }\n\n return openRouterRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n // outputSchema is part of the interface contract but OpenRouter now uses\n // native `response_format` (set in buildRequest), so we no longer inject a\n // synthetic structured-output tool here. The legacy fake-tool injection\n // happens in buildRequest only as a runtime fallback.\n\n _outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n let jsonSchema: JsonObject;\n\n // Check if schema is already a JsonObject — either the OpenAI-style\n // `{ type: \"json_schema\", ... }` envelope or a bare `{ type: \"object\", properties }` node\n if (\n (typeof schema === \"object\" &&\n schema !== null &&\n !Array.isArray(schema) &&\n (schema as JsonObject).type === \"json_schema\") ||\n isJsonSchema(schema)\n ) {\n jsonSchema = structuredClone(schema) as JsonObject;\n jsonSchema.type = \"object\"; // Normalize type\n } else {\n // Convert NaturalSchema to JSON schema through Zod. Re-spread into a\n // plain object: Zod v4's z.toJSONSchema returns an object that carries\n // a non-configurable `~standard` Standard-Schema interop marker as a\n // non-enumerable own property. Anthropic's output_config.format\n // validation is strict and rejects unknown properties when OpenRouter\n // forwards the schema, so we drop the marker here. JSON.stringify\n // already skips it but the OpenRouter SDK enumerates own properties\n // during serialization.\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n jsonSchema = { ...(z.toJSONSchema(zodSchema) as JsonObject) };\n }\n\n // Remove $schema property (can cause issues with some providers)\n if (jsonSchema.$schema) {\n delete jsonSchema.$schema;\n }\n\n // OpenRouter (and most backends behind it) require additionalProperties:\n // false on every object when using strict json_schema response_format.\n enforceAdditionalPropertiesFalse(jsonSchema);\n\n return jsonSchema;\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<OpenRouterResponse> {\n const openRouter = client as OpenRouterClient;\n const openRouterRequest = request as OpenRouterRequest;\n const wantsStructuredOutput = Boolean(openRouterRequest.response_format);\n\n try {\n const response = (await openRouter.chatCompletion(\n this.toWireBody(openRouterRequest),\n signal ? { signal } : undefined,\n )) as unknown as AnnotatedOpenRouterResponse;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as OpenRouterResponse;\n\n // If the route rejected `temperature` (e.g., openai/gpt-5.5 forwarding),\n // cache it and retry without the param.\n const requestRecord = openRouterRequest as unknown as Record<\n string,\n unknown\n >;\n if (\n requestRecord.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(openRouterRequest.model);\n const retryRequest = { ...openRouterRequest } as OpenRouterRequest;\n delete (retryRequest as unknown as Record<string, unknown>).temperature;\n const response = (await openRouter.chatCompletion(\n this.toWireBody(retryRequest),\n signal ? { signal } : undefined,\n )) as unknown as AnnotatedOpenRouterResponse;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n }\n\n // If the model rejected `response_format`, cache it and retry with the\n // legacy fake-tool emulation path.\n if (wantsStructuredOutput && isStructuredOutputUnsupportedError(error)) {\n const model = openRouterRequest.model;\n this.rememberModelRejectsStructuredOutput(model);\n log.warn(\n `[OpenRouterAdapter] Model ${model} rejected native response_format; falling back to legacy structured_output tool emulation.`,\n );\n const fallbackRequest =\n this.toFallbackStructuredOutputRequest(openRouterRequest);\n return (await openRouter.chatCompletion(\n this.toWireBody(fallbackRequest),\n signal ? { signal } : undefined,\n )) as unknown as OpenRouterResponse;\n }\n\n throw error;\n }\n }\n\n /**\n * Translate our internal snake_case `OpenRouterRequest` into the SDK's\n * camelCase shape, forwarding only the fields we care about (the SDK\n * silently strips unknown fields).\n */\n /**\n * Serialize the internal request into the OpenAI-compatible wire body for\n * OpenRouter's Chat Completions endpoint. Top-level fields (model, tools,\n * tool_choice, response_format, user, temperature, and any providerOptions)\n * are already wire-shaped (snake_case); only messages carry camelCase tool\n * fields that must become snake_case on the wire.\n */\n private toWireBody(\n openRouterRequest: OpenRouterRequest,\n ): Record<string, unknown> {\n return {\n ...openRouterRequest,\n messages: openRouterRequest.messages.map(messageToWire),\n };\n }\n\n /**\n * Rebuild a structured-output request without `response_format`, swapping in\n * the legacy fake-tool emulation. Used as a runtime fallback when a model\n * rejects native json_schema.\n */\n private toFallbackStructuredOutputRequest(\n request: OpenRouterRequest,\n ): OpenRouterRequest {\n if (\n !request.response_format ||\n request.response_format.type !== \"json_schema\"\n ) {\n return request;\n }\n const { response_format, ...rest } = request;\n const fallbackRequest: OpenRouterRequest = { ...rest };\n const schema = response_format.json_schema.schema;\n const fakeTool: OpenRouterTool = {\n type: \"function\" as const,\n function: {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n parameters: schema,\n },\n };\n fallbackRequest.tools = [...(fallbackRequest.tools ?? []), fakeTool];\n fallbackRequest.tool_choice = \"auto\";\n return fallbackRequest;\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const openRouter = client as OpenRouterClient;\n const openRouterRequest = request as OpenRouterRequest;\n\n // streamChatCompletion adds `stream: true` + `stream_options.include_usage`\n // and yields decoded SSE chunks in OpenAI-compatible (snake_case) shape.\n const stream = openRouter.streamChatCompletion(\n this.toWireBody(openRouterRequest),\n signal ? { signal } : undefined,\n ) as AsyncIterable<unknown>;\n\n // Track current tool call being built\n let currentToolCall: {\n id: string;\n name: string;\n arguments: string;\n } | null = null;\n\n // Track usage for final chunk\n let inputTokens = 0;\n let outputTokens = 0;\n const model = openRouterRequest.model || this.defaultModel;\n\n for await (const chunk of stream) {\n // Handle different chunk types from OpenRouter (OpenAI-compatible format)\n interface StreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n tool_calls?: Array<{\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason?: string;\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n promptTokens?: number;\n completionTokens?: number;\n };\n }\n const typedChunk = chunk as StreamChunk;\n const choices = typedChunk.choices;\n\n if (choices && choices.length > 0) {\n const delta = choices[0].delta;\n\n // Handle text content\n if (delta?.content) {\n yield {\n type: LlmStreamChunkType.Text,\n content: delta.content,\n };\n }\n\n // Handle tool calls\n if (delta?.tool_calls && delta.tool_calls.length > 0) {\n for (const toolCallDelta of delta.tool_calls) {\n if (toolCallDelta.id) {\n // New tool call starting\n if (currentToolCall) {\n // Emit the previous tool call\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.id,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n }\n currentToolCall = {\n id: toolCallDelta.id,\n name: toolCallDelta.function?.name || \"\",\n arguments: toolCallDelta.function?.arguments || \"\",\n };\n } else if (currentToolCall) {\n // Continuing existing tool call\n if (toolCallDelta.function?.name) {\n currentToolCall.name += toolCallDelta.function.name;\n }\n if (toolCallDelta.function?.arguments) {\n currentToolCall.arguments += toolCallDelta.function.arguments;\n }\n }\n }\n }\n\n // Check for finish reason\n if (choices[0].finish_reason) {\n // Emit any pending tool call\n if (currentToolCall) {\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.id,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n currentToolCall = null;\n }\n }\n }\n\n // Extract usage if present (usually in the final chunk)\n if (typedChunk.usage) {\n inputTokens =\n typedChunk.usage.prompt_tokens || typedChunk.usage.promptTokens || 0;\n outputTokens =\n typedChunk.usage.completion_tokens ||\n typedChunk.usage.completionTokens ||\n 0;\n }\n }\n\n // Emit done chunk with final usage\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: 0,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n _options?: LlmOperateOptions,\n ): ParsedResponse {\n const openRouterResponse = response as OpenRouterResponse;\n const choice = openRouterResponse.choices[0];\n\n const content = this.extractContent(openRouterResponse);\n const hasToolCalls = this.hasToolCalls(openRouterResponse);\n\n // SDK returns camelCase (finishReason), but support snake_case as fallback\n const stopReason =\n choice?.finishReason ?? choice?.finish_reason ?? undefined;\n\n return {\n content,\n hasToolCalls,\n stopReason,\n usage: this.extractUsage(openRouterResponse, openRouterResponse.model),\n raw: openRouterResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const openRouterResponse = response as OpenRouterResponse;\n const toolCalls: StandardToolCall[] = [];\n const choice = openRouterResponse.choices[0];\n\n // SDK returns camelCase (toolCalls)\n if (!choice?.message?.toolCalls) {\n return toolCalls;\n }\n\n for (const toolCall of choice.message.toolCalls) {\n toolCalls.push({\n callId: toolCall.id,\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n raw: toolCall,\n });\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const openRouterResponse = response as OpenRouterResponse;\n\n if (!openRouterResponse.usage) {\n return {\n input: 0,\n output: 0,\n reasoning: 0,\n total: 0,\n provider: this.name,\n model,\n };\n }\n\n // SDK returns camelCase, but support snake_case as fallback\n const usage = openRouterResponse.usage;\n const cachedTokens =\n usage.promptTokensDetails?.cachedTokens ??\n usage.promptTokensDetails?.cached_tokens ??\n usage.prompt_tokens_details?.cached_tokens;\n return {\n input: usage.promptTokens || usage.prompt_tokens || 0,\n output: usage.completionTokens || usage.completion_tokens || 0,\n reasoning: usage.completionTokensDetails?.reasoningTokens || 0,\n total: usage.totalTokens || usage.total_tokens || 0,\n ...(cachedTokens !== undefined ? { cacheRead: cachedTokens } : {}),\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): OpenRouterMessage {\n return {\n role: \"tool\",\n toolCallId: toolCall.callId,\n content: result.output,\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): OpenRouterRequest {\n const openRouterRequest = request as OpenRouterRequest;\n const toolCallRaw = toolCall.raw as OpenRouterToolCall;\n\n // Add assistant message with the tool call (SDK uses camelCase)\n openRouterRequest.messages.push({\n role: \"assistant\",\n content: null,\n toolCalls: [toolCallRaw],\n });\n\n // Add tool result message\n openRouterRequest.messages.push(this.formatToolResult(toolCall, result));\n\n return openRouterRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const openRouterResponse = response as OpenRouterResponse;\n const historyItems: LlmHistory = [];\n const choice = openRouterResponse.choices[0];\n\n if (!choice?.message) {\n return historyItems;\n }\n\n // Check if this is a tool use response (SDK returns camelCase)\n if (choice.message.toolCalls && choice.message.toolCalls.length > 0) {\n // Don't add to history yet - will be added after tool execution\n return historyItems;\n }\n\n // Extract text content for non-tool responses\n if (choice.message.content) {\n const historyItem: LlmOutputMessage & { reasoning?: string } = {\n content: choice.message.content,\n role: LlmMessageRole.Assistant,\n type: LlmMessageType.Message,\n };\n\n // Preserve reasoning if present (z-ai/glm models include this)\n if (choice.message.reasoning) {\n historyItem.reasoning = choice.message.reasoning;\n }\n\n historyItems.push(historyItem as LlmOutputMessage);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n // Check if error has a status code (HTTP error)\n const errorWithStatus = error as { status?: number; statusCode?: number };\n const statusCode = errorWithStatus.status || errorWithStatus.statusCode;\n\n if (statusCode) {\n // Rate limit error\n if (statusCode === RATE_LIMIT_STATUS_CODE) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Retryable errors (server errors, timeouts, etc.)\n if (RETRYABLE_STATUS_CODES.includes(statusCode)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Client errors (4xx except 429) are unrecoverable\n if (statusCode >= 400 && statusCode < 500) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n }\n\n // Check error message for rate limit indicators\n const errorMessage =\n error instanceof Error ? error.message.toLowerCase() : \"\";\n if (\n errorMessage.includes(\"rate limit\") ||\n errorMessage.includes(\"too many requests\")\n ) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Check for transient network errors (ECONNRESET, etc.)\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Unknown error - treat as potentially retryable\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Provider-Specific Features\n //\n\n isComplete(response: unknown): boolean {\n const openRouterResponse = response as OpenRouterResponse;\n const choice = openRouterResponse.choices[0];\n\n // Complete if no tool calls (SDK returns camelCase)\n if (!choice?.message?.toolCalls?.length) {\n return true;\n }\n\n return false;\n }\n\n override hasStructuredOutput(response: unknown): boolean {\n const openRouterResponse = response as AnnotatedOpenRouterResponse;\n\n // Native path: executeRequest annotates the response when we sent\n // `response_format`, so we can detect intent statelessly.\n if (openRouterResponse.__jaypieStructuredOutput) {\n return this.extractStructuredOutput(response) !== undefined;\n }\n\n // Fallback path: legacy fake-tool emulation, kept for models that the\n // runtime has cached as not supporting native `response_format`.\n const choice = openRouterResponse.choices[0];\n\n // SDK returns camelCase (toolCalls)\n if (!choice?.message?.toolCalls?.length) {\n return false;\n }\n\n // Check if the last tool call is structured_output\n const lastToolCall =\n choice.message.toolCalls[choice.message.toolCalls.length - 1];\n return lastToolCall?.function?.name === STRUCTURED_OUTPUT_TOOL_NAME;\n }\n\n override extractStructuredOutput(response: unknown): JsonObject | undefined {\n const openRouterResponse = response as AnnotatedOpenRouterResponse;\n\n if (openRouterResponse.__jaypieStructuredOutput) {\n const choice = openRouterResponse.choices[0];\n const content = choice?.message?.content;\n if (typeof content !== \"string\" || content.length === 0) {\n return undefined;\n }\n try {\n return JSON.parse(content) as JsonObject;\n } catch {\n return undefined;\n }\n }\n\n // Fallback path: legacy fake-tool emulation\n const choice = openRouterResponse.choices[0];\n\n // SDK returns camelCase (toolCalls)\n if (!choice?.message?.toolCalls?.length) {\n return undefined;\n }\n\n const lastToolCall =\n choice.message.toolCalls[choice.message.toolCalls.length - 1];\n if (lastToolCall?.function?.name === STRUCTURED_OUTPUT_TOOL_NAME) {\n try {\n return JSON.parse(lastToolCall.function.arguments) as JsonObject;\n } catch {\n return undefined;\n }\n }\n\n return undefined;\n }\n\n //\n // Private Helpers\n //\n\n private hasToolCalls(response: OpenRouterResponse): boolean {\n const choice = response.choices[0];\n // SDK returns camelCase (toolCalls)\n return (choice?.message?.toolCalls?.length ?? 0) > 0;\n }\n\n private extractContent(\n response: OpenRouterResponse,\n ): string | JsonObject | undefined {\n // Check for structured output first\n if (this.hasStructuredOutput(response)) {\n return this.extractStructuredOutput(response);\n }\n\n const choice = response.choices[0];\n return choice?.message?.content ?? undefined;\n }\n\n private convertMessagesToOpenRouter(\n messages: LlmHistory,\n system?: string,\n cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" },\n ): OpenRouterMessage[] {\n const openRouterMessages: OpenRouterMessage[] = [];\n\n // Add system message if provided. A cache_control breakpoint on the system\n // content is forwarded by OpenRouter to Anthropic/Gemini backends (and\n // ignored by others), caching the stable system prefix.\n if (system) {\n openRouterMessages.push({\n role: \"system\",\n content: cacheControl\n ? [{ type: \"text\", text: system, cache_control: cacheControl }]\n : system,\n });\n }\n\n for (const msg of messages) {\n const message = msg as unknown as Record<string, unknown>;\n\n // Handle different message types\n if (message.role === \"system\") {\n openRouterMessages.push({\n role: \"system\",\n content: message.content as string,\n });\n } else if (message.role === \"user\") {\n openRouterMessages.push({\n role: \"user\",\n content: convertContentToOpenRouter(\n message.content as string | LlmInputContent[],\n ),\n });\n } else if (message.role === \"assistant\") {\n const assistantMsg: OpenRouterMessage = {\n role: \"assistant\",\n content: (message.content as string) || null,\n };\n\n // Include toolCalls if present (check both camelCase and snake_case for compatibility)\n if (message.toolCalls) {\n assistantMsg.toolCalls = message.toolCalls as OpenRouterToolCall[];\n } else if (message.tool_calls) {\n assistantMsg.toolCalls = message.tool_calls as OpenRouterToolCall[];\n }\n\n openRouterMessages.push(assistantMsg);\n } else if (message.role === \"tool\") {\n openRouterMessages.push({\n role: \"tool\",\n toolCallId:\n (message.toolCallId as string) || (message.tool_call_id as string),\n content: message.content as string,\n });\n } else if (message.type === LlmMessageType.Message) {\n // Handle internal message format\n const role = (message.role as string)?.toLowerCase();\n if (role === \"assistant\") {\n openRouterMessages.push({\n role: \"assistant\",\n content: message.content as string,\n });\n } else {\n openRouterMessages.push({\n role: \"user\",\n content: convertContentToOpenRouter(\n message.content as string | LlmInputContent[],\n ),\n });\n }\n } else if (message.type === LlmMessageType.FunctionCall) {\n // Handle FunctionCall messages from StreamLoop (issue #165)\n openRouterMessages.push({\n role: \"assistant\",\n content: null,\n toolCalls: [\n {\n id: message.call_id as string,\n type: \"function\" as const,\n function: {\n name: message.name as string,\n arguments: (message.arguments as string) || \"{}\",\n },\n },\n ],\n });\n } else if (message.type === LlmMessageType.FunctionCallOutput) {\n // Handle FunctionCallOutput messages from StreamLoop (issue #165)\n openRouterMessages.push({\n role: \"tool\",\n toolCallId: message.call_id as string,\n content: (message.output as string) || \"\",\n });\n }\n }\n\n return openRouterMessages;\n }\n}\n\n// Export singleton instance\nexport const openRouterAdapter = new OpenRouterAdapter();\n","import { type LlmEffort, PROVIDER } from \"../../constants.js\";\nimport { BadRequestError } from \"../../providers/openai/client.js\";\nimport { type LlmEffortMapping, toXaiEffort } from \"../../util/effort.js\";\nimport { ClassifiedError, ErrorCategory } from \"../types.js\";\nimport { OpenAiAdapter } from \"./OpenAiAdapter.js\";\n\n/**\n * Error-message substrings that indicate a transient xAI media-ingest flake.\n * The xAI ingest service enters a bad state after ~12 consecutive file-bearing\n * calls and rejects subsequent requests with HTTP 400. The condition is\n * self-clearing, so these errors should be retried with backoff rather than\n * surfaced as unrecoverable.\n *\n * See: github.com/finlaysonstudio/jaypie issue #301\n */\nconst TRANSIENT_INGEST_MESSAGE_PATTERNS = [\n \"failed to ingest inline file bytes\",\n] as const;\n\nfunction isTransientIngestError(error: unknown): boolean {\n if (!(error instanceof BadRequestError)) return false;\n const message = (error.message ?? \"\").toLowerCase();\n return TRANSIENT_INGEST_MESSAGE_PATTERNS.some((pattern) =>\n message.includes(pattern),\n );\n}\n\n/**\n * XaiAdapter extends OpenAiAdapter since xAI (Grok) uses an OpenAI-compatible API.\n * Name, default model, and transient-ingest-error detection are overridden;\n * all request building, response parsing, tool handling, and streaming are\n * inherited.\n */\nexport class XaiAdapter extends OpenAiAdapter {\n // @ts-expect-error Narrowing override: xAI name differs from parent's literal \"openai\"\n readonly name = PROVIDER.XAI.NAME;\n readonly defaultModel = PROVIDER.XAI.DEFAULT;\n\n /**\n * Grok gates reasoning effort by model, not by the OpenAI `gpt-*`/`o*`\n * patterns. Only explicit `*-reasoning` models accept `reasoning_effort`;\n * bare grok-4 reasons implicitly and rejects it, so we stay conservative and\n * only opt in models whose name advertises reasoning.\n */\n protected supportsReasoningEffort(model: string): boolean {\n if (/non-reasoning/.test(model)) return false;\n return /reasoning/.test(model);\n }\n\n protected mapReasoningEffort(effort: LlmEffort): LlmEffortMapping {\n return toXaiEffort(effort);\n }\n\n classifyError(error: unknown): ClassifiedError {\n if (isTransientIngestError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n return super.classifyError(error);\n }\n}\n\n// Export singleton instance\nexport const xaiAdapter = new XaiAdapter();\n","import { JAYPIE, resolveValue } from \"@jaypie/kit\";\nimport { log as jaypieLog } from \"@jaypie/logger\";\nimport { JsonObject } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { LlmTool } from \"../types/LlmTool.interface\";\n\nconst DEFAULT_TOOL_TYPE = \"function\";\n\nconst log = jaypieLog.lib({ lib: JAYPIE.LIB.LLM });\n\ntype LogFunction = (\n message: string,\n context: { name: string; args: any },\n) => void | Promise<void>;\n\nfunction logToolMessage(message: string, context: { name: string; args: any }) {\n log.trace.var({ [context.name]: message });\n}\n\nexport interface ToolkitOptions {\n explain?: boolean;\n log?: boolean | LogFunction;\n}\n\nexport class Toolkit {\n private readonly _tools: LlmTool[];\n private readonly _options: ToolkitOptions;\n private readonly explain: boolean;\n private readonly log: boolean | LogFunction;\n\n constructor(tools: LlmTool[], options?: ToolkitOptions) {\n this._tools = tools;\n this._options = options || {};\n this.explain = this._options.explain ? true : false;\n this.log = this._options.log !== undefined ? this._options.log : true;\n }\n\n get tools(): Omit<LlmTool, \"call\">[] {\n return this._tools.map((tool) => {\n const toolCopy: any = { ...tool };\n delete toolCopy.call;\n delete toolCopy.message;\n\n // Convert Zod schema to JSON Schema if needed\n if (toolCopy.parameters instanceof z.ZodType) {\n const jsonSchema = z.toJSONSchema(toolCopy.parameters) as JsonObject;\n // Remove $schema property (causes issues with some providers)\n if (jsonSchema.$schema) {\n delete jsonSchema.$schema;\n }\n toolCopy.parameters = jsonSchema;\n }\n\n if (this.explain && toolCopy.parameters?.type === \"object\") {\n if (toolCopy.parameters?.properties) {\n if (!toolCopy.parameters.properties.__Explanation) {\n toolCopy.parameters.properties.__Explanation = {\n type: \"string\",\n description: `Clearly state why the tool is being called and what larger question it helps answer. For example, \"I am checking the location API because the user asked for nearby pizza and I need coordinates to proceed\"`,\n };\n }\n }\n }\n\n // Set default type if not provided\n if (!toolCopy.type) {\n toolCopy.type = DEFAULT_TOOL_TYPE;\n }\n\n return toolCopy;\n });\n }\n\n private parseArgs(args: string) {\n let parsedArgs;\n try {\n parsedArgs = JSON.parse(args);\n if (this.explain) {\n delete parsedArgs.__Explanation;\n }\n } catch {\n parsedArgs = args;\n }\n return parsedArgs;\n }\n\n /**\n * Resolve a tool's `message` (static string or function of args) without\n * calling the tool. Returns undefined when the tool is missing or defines\n * no message. Never throws; resolution errors log at warn.\n */\n async resolveMessage({\n name,\n arguments: args,\n }: {\n name: string;\n arguments: string;\n }): Promise<string | undefined> {\n const tool = this._tools.find((t) => t.name === name);\n if (!tool || !tool.message) {\n return undefined;\n }\n\n try {\n if (typeof tool.message === \"string\") {\n return tool.message;\n }\n const parsedArgs = this.parseArgs(args);\n if (typeof tool.message === \"function\") {\n return await resolveValue(tool.message(parsedArgs, { name }));\n }\n log.warn(\"[Toolkit] Tool provided unknown message type\");\n return String(tool.message);\n } catch (error) {\n log.warn(\"[Toolkit] Caught error resolving tool message\");\n log.var({ error });\n return undefined;\n }\n }\n\n async call({\n name,\n arguments: args,\n message: resolvedMessage,\n }: {\n name: string;\n arguments: string;\n /** Pre-resolved tool message; skips re-resolving `tool.message` for logging */\n message?: string;\n }) {\n const tool = this._tools.find((t) => t.name === name);\n if (!tool) {\n throw new Error(`Tool '${name}' not found`);\n }\n\n const parsedArgs = this.parseArgs(args);\n\n if (this.log !== false) {\n try {\n const context: { name: string; args: any; explanation?: string } = {\n name,\n args: parsedArgs,\n };\n\n if (this.explain) {\n context.explanation = parsedArgs.__Explanation;\n }\n\n const message =\n resolvedMessage ??\n (await this.resolveMessage({ arguments: args, name })) ??\n `${tool.name}:${JSON.stringify(parsedArgs)}`;\n\n if (typeof this.log === \"function\") {\n log.trace(\"[Toolkit] Log tool call with custom logger\");\n await resolveValue(this.log(message, context));\n } else {\n log.trace(\"[Toolkit] Log tool call with default logger\");\n logToolMessage(message, context);\n }\n } catch (error) {\n log.error(\"[Toolkit] Caught error during logToolCall\");\n log.var({ error });\n log.debug(\"[Toolkit] Continuing...\");\n }\n }\n\n return await resolveValue(tool.call(parsedArgs));\n }\n\n extend(\n tools: LlmTool[],\n options: {\n warn?: boolean;\n replace?: boolean;\n log?: boolean | LogFunction;\n explain?: boolean;\n } = {},\n ): this {\n for (const tool of tools) {\n const existingIndex = this._tools.findIndex((t) => t.name === tool.name);\n if (existingIndex !== -1) {\n if (options.replace === false) {\n continue;\n }\n if (options.warn !== false) {\n if (typeof this.log === \"function\") {\n this.log(\n `[Toolkit] Tool '${tool.name}' already exists, replacing with new tool`,\n { name: tool.name, args: {} },\n );\n } else if (this.log) {\n log.warn(\n `[Toolkit] Tool '${tool.name}' already exists, replacing with new tool`,\n );\n }\n }\n this._tools[existingIndex] = tool;\n } else {\n this._tools.push(tool);\n }\n }\n if (Object.prototype.hasOwnProperty.call(options, \"log\")) {\n (this as any).log = options.log;\n }\n if (Object.prototype.hasOwnProperty.call(options, \"explain\")) {\n (this as any).explain = options.explain;\n }\n return this;\n }\n}\n","import { createRequire } from \"module\";\nimport { pathToFileURL } from \"url\";\n\nimport { getLogger } from \"../util/index.js\";\n\n//\n//\n// Types\n//\n\n/**\n * LLM Observability span kinds supported by Datadog's `llmobs` SDK.\n * @see https://docs.datadoghq.com/llm_observability/setup/sdk/nodejs/\n */\nexport type LlmObsSpanKind =\n \"agent\" | \"embedding\" | \"llm\" | \"retrieval\" | \"task\" | \"tool\" | \"workflow\";\n\nexport interface LlmObsSpanOptions {\n kind: LlmObsSpanKind;\n modelName?: string;\n modelProvider?: string;\n name: string;\n}\n\nexport interface LlmObsAnnotation {\n inputData?: unknown;\n metadata?: Record<string, unknown>;\n metrics?: Record<string, number>;\n outputData?: unknown;\n tags?: Record<string, unknown>;\n}\n\n/** Manual span handle for streaming, where a callback cannot enclose the work. */\nexport interface LlmObsSpanHandle {\n annotate: (annotation: LlmObsAnnotation) => void;\n finish: () => void;\n}\n\n/** Minimal shape of the dd-trace `llmobs` SDK surface this module uses. */\ninterface LlmObsSdk {\n annotate: (span: unknown, annotation: LlmObsAnnotation) => void;\n trace: (\n options: LlmObsSpanOptions,\n fn: (span: unknown) => unknown,\n ) => unknown;\n}\n\n//\n//\n// Constants\n//\n\nconst ENV = {\n DD_LLMOBS_ENABLED: \"DD_LLMOBS_ENABLED\",\n};\n\nconst MODULE = {\n // Computed at runtime so bundlers (esbuild) do not attempt to include\n // dd-trace, which is provided by the Datadog Lambda layer at runtime.\n DD_TRACE: [\"dd\", \"trace\"].join(\"-\"),\n};\n\n//\n//\n// Helpers\n//\n\n// CJS/ESM compatible require - handles bundling to CJS where import.meta.url\n// becomes undefined (mirrors packages/testkit/src/mock/original.ts).\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore - __filename exists in CJS context when ESM is bundled to CJS\nconst requireModule =\n typeof __filename !== \"undefined\"\n ? createRequire(pathToFileURL(__filename).href)\n : createRequire(import.meta.url);\n\nlet resolved = false;\nlet cachedSdk: LlmObsSdk | null = null;\nlet injectedSdk: LlmObsSdk | null = null;\n\n/**\n * Lazily resolve the dd-trace `llmobs` SDK. Returns null (and never throws)\n * when dd-trace is absent or the SDK surface is unexpected. Cached after the\n * first attempt.\n */\nfunction resolveLlmObs(): LlmObsSdk | null {\n if (resolved) {\n return cachedSdk;\n }\n resolved = true;\n try {\n const ddTrace = requireModule(MODULE.DD_TRACE);\n const tracer = ddTrace?.default ?? ddTrace;\n const llmobs = tracer?.llmobs;\n if (\n llmobs &&\n typeof llmobs.trace === \"function\" &&\n typeof llmobs.annotate === \"function\"\n ) {\n cachedSdk = llmobs as LlmObsSdk;\n }\n } catch {\n cachedSdk = null;\n }\n return cachedSdk;\n}\n\n/** Reset the cached SDK resolution. Exposed for tests. */\nexport function _resetLlmObs(): void {\n resolved = false;\n cachedSdk = null;\n injectedSdk = null;\n}\n\n/**\n * Inject an SDK to bypass dd-trace resolution. Test-only: dd-trace is not a\n * dependency, so the enabled path cannot otherwise be exercised in unit tests.\n */\nexport function _setLlmObs(sdk: LlmObsSdk | null): void {\n injectedSdk = sdk;\n}\n\n//\n//\n// Main\n//\n\n/**\n * True when LLM Observability emission is opted in via `DD_LLMOBS_ENABLED`.\n * Accepts any truthy value except \"false\"/\"0\".\n */\nexport function isLlmObsEnabled(): boolean {\n const value = process.env[ENV.DD_LLMOBS_ENABLED];\n if (!value) {\n return false;\n }\n const normalized = value.trim().toLowerCase();\n return normalized !== \"\" && normalized !== \"false\" && normalized !== \"0\";\n}\n\n/** Resolve the SDK only when enabled and available. */\nfunction activeSdk(): LlmObsSdk | null {\n if (!isLlmObsEnabled()) {\n return null;\n }\n return injectedSdk ?? resolveLlmObs();\n}\n\n/**\n * Run `fn` inside an LLM Observability span. When emission is disabled or\n * dd-trace is absent, `fn` is invoked directly with no overhead. The active\n * span is established for the duration of `fn`, so nested `withLlmObsSpan`\n * calls (and `annotateLlmObs`) attach as children/annotations automatically.\n */\nexport async function withLlmObsSpan<T>(\n options: LlmObsSpanOptions,\n fn: () => Promise<T>,\n): Promise<T> {\n const sdk = activeSdk();\n if (!sdk) {\n return fn();\n }\n let started = false;\n try {\n return (await sdk.trace(options, () => {\n started = true;\n return fn();\n })) as T;\n } catch (error) {\n // If `fn` ran, propagate its error (the SDK re-throws after finishing the\n // span). Only swallow failures from the instrumentation itself, re-running\n // `fn` so observability never breaks the underlying call.\n if (started) {\n throw error;\n }\n getLogger().warn(\"[llmobs] span emission failed\");\n getLogger().var({ error });\n return fn();\n }\n}\n\n/**\n * Annotate the currently active LLM Observability span. No-op when disabled.\n */\nexport function annotateLlmObs(annotation: LlmObsAnnotation): void {\n const sdk = activeSdk();\n if (!sdk) {\n return;\n }\n try {\n sdk.annotate(undefined, annotation);\n } catch (error) {\n getLogger().warn(\"[llmobs] annotate failed\");\n getLogger().var({ error });\n }\n}\n\n/**\n * Open a manual span that is finished later. Used by streaming, where work is\n * yielded incrementally and cannot be enclosed in a single callback. The span\n * is kept open via a deferred promise resolved by `finish()`. Returns null when\n * emission is disabled or dd-trace is absent.\n *\n * Note: because the span is held open across `yield` boundaries (outside the\n * SDK's AsyncLocalStorage scope), manual spans are emitted flat rather than\n * nested. Annotations are applied to the explicit span reference.\n */\nexport function openLlmObsSpan(\n options: LlmObsSpanOptions,\n): LlmObsSpanHandle | null {\n const sdk = activeSdk();\n if (!sdk) {\n return null;\n }\n try {\n let capturedSpan: unknown;\n let release: (() => void) | undefined;\n const held = new Promise<void>((resolve) => {\n release = resolve;\n });\n // trace() runs the callback synchronously, capturing the span; the returned\n // pending promise keeps the span open until finish() resolves it.\n void sdk.trace(options, (span) => {\n capturedSpan = span;\n return held;\n });\n let finished = false;\n return {\n annotate: (annotation: LlmObsAnnotation) => {\n try {\n sdk.annotate(capturedSpan, annotation);\n } catch (error) {\n getLogger().warn(\"[llmobs] annotate failed\");\n getLogger().var({ error });\n }\n },\n finish: () => {\n if (finished) {\n return;\n }\n finished = true;\n release?.();\n },\n };\n } catch (error) {\n getLogger().warn(\"[llmobs] span emission failed\");\n getLogger().var({ error });\n return null;\n }\n}\n\n//\n//\n// Mapping Helpers\n//\n\n/**\n * Sum an `LlmUsage` array into LLM Observability metric keys. Returns undefined\n * when there is no usage data so callers can omit the `metrics` field.\n */\nexport function usageToLlmObsMetrics(\n usage?: Array<{ input?: number; output?: number; total?: number }>,\n): Record<string, number> | undefined {\n if (!usage || usage.length === 0) {\n return undefined;\n }\n const metrics = usage.reduce(\n (sum, item) => ({\n input_tokens: sum.input_tokens + (item.input ?? 0),\n output_tokens: sum.output_tokens + (item.output ?? 0),\n total_tokens: sum.total_tokens + (item.total ?? 0),\n }),\n { input_tokens: 0, output_tokens: 0, total_tokens: 0 },\n );\n return metrics;\n}\n","import { resolveValue } from \"@jaypie/kit\";\nimport { JsonObject } from \"@jaypie/types\";\n\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmOperateOptions,\n LlmUsage,\n} from \"../../types/LlmProvider.interface.js\";\n\n//\n//\n// Types\n//\n\nexport interface BeforeModelRequestContext {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: unknown;\n}\n\nexport interface AfterModelResponseContext {\n content: string | JsonObject;\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: unknown;\n providerResponse: unknown;\n usage: LlmUsage;\n}\n\nexport interface BeforeToolContext {\n args: string;\n message?: string;\n toolName: string;\n}\n\nexport interface AfterToolContext {\n args: string;\n message?: string;\n result: unknown;\n toolName: string;\n}\n\nexport interface ToolErrorContext {\n args: string;\n error: Error;\n message?: string;\n toolName: string;\n}\n\nexport interface RetryableErrorContext {\n error: unknown;\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: unknown;\n}\n\nexport interface UnrecoverableErrorContext {\n error: unknown;\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: unknown;\n}\n\nexport type LlmHooks = LlmOperateOptions[\"hooks\"];\n\n//\n//\n// Main\n//\n\n/**\n * HookRunner provides a centralized, consistent way to execute lifecycle hooks\n * during the LLM operate loop. It handles async resolution and provides error\n * isolation for hook execution.\n */\nexport class HookRunner {\n /**\n * Execute the beforeEachModelRequest hook if defined\n */\n async runBeforeModelRequest(\n hooks: LlmHooks,\n context: BeforeModelRequestContext,\n ): Promise<void> {\n if (hooks?.beforeEachModelRequest) {\n await resolveValue(hooks.beforeEachModelRequest(context));\n }\n }\n\n /**\n * Execute the afterEachModelResponse hook if defined\n */\n async runAfterModelResponse(\n hooks: LlmHooks,\n context: AfterModelResponseContext,\n ): Promise<void> {\n if (hooks?.afterEachModelResponse) {\n await resolveValue(hooks.afterEachModelResponse(context));\n }\n }\n\n /**\n * Execute the beforeEachTool hook if defined\n */\n async runBeforeTool(\n hooks: LlmHooks,\n context: BeforeToolContext,\n ): Promise<void> {\n if (hooks?.beforeEachTool) {\n await resolveValue(hooks.beforeEachTool(context));\n }\n }\n\n /**\n * Execute the afterEachTool hook if defined\n */\n async runAfterTool(\n hooks: LlmHooks,\n context: AfterToolContext,\n ): Promise<void> {\n if (hooks?.afterEachTool) {\n await resolveValue(hooks.afterEachTool(context));\n }\n }\n\n /**\n * Execute the onToolError hook if defined\n */\n async runOnToolError(\n hooks: LlmHooks,\n context: ToolErrorContext,\n ): Promise<void> {\n if (hooks?.onToolError) {\n await resolveValue(hooks.onToolError(context));\n }\n }\n\n /**\n * Execute the onRetryableModelError hook if defined\n */\n async runOnRetryableError(\n hooks: LlmHooks,\n context: RetryableErrorContext,\n ): Promise<void> {\n if (hooks?.onRetryableModelError) {\n await resolveValue(hooks.onRetryableModelError(context));\n }\n }\n\n /**\n * Execute the onUnrecoverableModelError hook if defined\n */\n async runOnUnrecoverableError(\n hooks: LlmHooks,\n context: UnrecoverableErrorContext,\n ): Promise<void> {\n if (hooks?.onUnrecoverableModelError) {\n await resolveValue(hooks.onUnrecoverableModelError(context));\n }\n }\n}\n\n// Export singleton instance for convenience\nexport const hookRunner = new HookRunner();\n","import type {\n LlmOperateInput,\n LlmOperateInputContent,\n LlmOperateInputFile,\n LlmOperateInputImage,\n} from \"./LlmProvider.interface.js\";\n\n/**\n * Type guard to check if an item is an LlmOperateInputFile\n */\nexport function isLlmOperateInputFile(\n item: unknown,\n): item is LlmOperateInputFile {\n return (\n typeof item === \"object\" &&\n item !== null &&\n \"file\" in item &&\n typeof (item as LlmOperateInputFile).file === \"string\"\n );\n}\n\n/**\n * Type guard to check if an item is an LlmOperateInputImage\n */\nexport function isLlmOperateInputImage(\n item: unknown,\n): item is LlmOperateInputImage {\n return (\n typeof item === \"object\" &&\n item !== null &&\n \"image\" in item &&\n typeof (item as LlmOperateInputImage).image === \"string\"\n );\n}\n\n/**\n * Type guard to check if an item is an LlmOperateInputContent\n */\nexport function isLlmOperateInputContent(\n item: unknown,\n): item is LlmOperateInputContent {\n return (\n typeof item === \"string\" ||\n isLlmOperateInputFile(item) ||\n isLlmOperateInputImage(item)\n );\n}\n\n/**\n * Type guard to check if input is an LlmOperateInput array\n */\nexport function isLlmOperateInput(input: unknown): input is LlmOperateInput {\n return (\n Array.isArray(input) &&\n input.length > 0 &&\n input.every(isLlmOperateInputContent)\n );\n}\n","/**\n * Image extensions that are auto-detected from file paths\n */\nconst IMAGE_EXTENSIONS = new Set([\n \"avif\",\n \"bmp\",\n \"gif\",\n \"ico\",\n \"jpeg\",\n \"jpg\",\n \"png\",\n \"svg\",\n \"tiff\",\n \"webp\",\n]);\n\n/**\n * Mapping of file extensions to MIME types\n */\nconst EXTENSION_TO_MIME: Record<string, string> = {\n // Images\n avif: \"image/avif\",\n bmp: \"image/bmp\",\n gif: \"image/gif\",\n ico: \"image/x-icon\",\n jpeg: \"image/jpeg\",\n jpg: \"image/jpeg\",\n png: \"image/png\",\n svg: \"image/svg+xml\",\n tiff: \"image/tiff\",\n webp: \"image/webp\",\n\n // Documents\n pdf: \"application/pdf\",\n\n // Text\n json: \"application/json\",\n txt: \"text/plain\",\n};\n\n/**\n * Extract file extension from a path or filename\n */\nexport function getFileExtension(filePath: string): string | undefined {\n const match = filePath.match(/\\.(\\w+)$/);\n return match ? match[1].toLowerCase() : undefined;\n}\n\n/**\n * Determine MIME type from file extension\n */\nexport function getMimeType(filePath: string): string | undefined {\n const ext = getFileExtension(filePath);\n return ext ? EXTENSION_TO_MIME[ext] : undefined;\n}\n\n/**\n * Check if a file path has an image extension\n */\nexport function isImageExtension(filePath: string): boolean {\n const ext = getFileExtension(filePath);\n return ext ? IMAGE_EXTENSIONS.has(ext) : false;\n}\n\n/**\n * Check if a file path has a PDF extension\n */\nexport function isPdfExtension(filePath: string): boolean {\n const ext = getFileExtension(filePath);\n return ext === \"pdf\";\n}\n","import { PDFDocument } from \"pdf-lib\";\n\n/**\n * Extract specific pages from a PDF buffer\n * @param pdfBytes - Buffer containing the PDF data\n * @param pages - Array of page numbers to extract (1-indexed)\n * @returns Buffer containing a new PDF with only the specified pages\n */\nexport async function extractPdfPages(\n pdfBytes: Buffer,\n pages: number[],\n): Promise<Buffer> {\n const pdfDoc = await PDFDocument.load(pdfBytes);\n const totalPages = pdfDoc.getPageCount();\n\n // Validate page numbers\n for (const pageNum of pages) {\n if (pageNum < 1 || pageNum > totalPages) {\n throw new Error(\n `Page number ${pageNum} is out of range. Document has ${totalPages} pages.`,\n );\n }\n }\n\n // Create a new PDF with only the specified pages\n const newPdfDoc = await PDFDocument.create();\n\n // Convert 1-indexed page numbers to 0-indexed for pdf-lib\n const pageIndices = pages.map((p) => p - 1);\n const copiedPages = await newPdfDoc.copyPages(pdfDoc, pageIndices);\n\n for (const page of copiedPages) {\n newPdfDoc.addPage(page);\n }\n\n const newPdfBytes = await newPdfDoc.save();\n return Buffer.from(newPdfBytes);\n}\n\n/**\n * Get the total number of pages in a PDF\n * @param pdfBytes - Buffer containing the PDF data\n * @returns Total number of pages\n */\nexport async function getPdfPageCount(pdfBytes: Buffer): Promise<number> {\n const pdfDoc = await PDFDocument.load(pdfBytes);\n return pdfDoc.getPageCount();\n}\n","import { readFile } from \"fs/promises\";\nimport { resolve } from \"path\";\n\n/**\n * Load a file from the local filesystem\n * @param filePath - Path to the file (relative paths resolve from process.cwd())\n * @returns Buffer containing the file contents\n */\nexport async function loadLocalFile(filePath: string): Promise<Buffer> {\n const absolutePath = resolve(process.cwd(), filePath);\n return readFile(absolutePath);\n}\n","import { getS3FileBuffer } from \"@jaypie/aws\";\n\n/**\n * Load a file from S3\n * @param bucket - S3 bucket name\n * @param key - S3 object key\n * @returns Buffer containing the file contents\n */\nexport async function loadS3File(bucket: string, key: string): Promise<Buffer> {\n return getS3FileBuffer({ bucket, key });\n}\n","import {\n LlmInputContent,\n LlmInputContentFile,\n LlmInputContentImage,\n LlmInputContentText,\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateInput,\n LlmOperateInputContent,\n LlmOperateInputFile,\n LlmOperateInputImage,\n} from \"../types/LlmProvider.interface.js\";\nimport {\n isLlmOperateInputFile,\n isLlmOperateInputImage,\n} from \"../types/LlmOperateInput.guards.js\";\nimport {\n getMimeType,\n isImageExtension,\n isPdfExtension,\n} from \"./detectMimeType.js\";\nimport { extractPdfPages } from \"./extractPdfPages.js\";\nimport { loadLocalFile } from \"./loadLocalFile.js\";\nimport { loadS3File } from \"./loadS3File.js\";\n\n/**\n * Resolved content ready for LLM providers\n */\ninterface ResolvedContent {\n data: string; // base64 data\n mimeType: string;\n filename: string;\n}\n\n/**\n * Load file data from source (provided data, S3, or local filesystem)\n */\nasync function loadFileData(\n item: LlmOperateInputFile | LlmOperateInputImage,\n): Promise<Buffer> {\n // Get the path from either file or image property\n const path = \"file\" in item ? item.file : item.image;\n\n // Priority 1: Use provided data directly\n if (item.data) {\n return Buffer.from(item.data, \"base64\");\n }\n\n // Priority 2: Load from S3 (explicit bucket or CDK_ENV_BUCKET fallback)\n const bucket = item.bucket ?? process.env.CDK_ENV_BUCKET;\n if (bucket) {\n return loadS3File(bucket, path);\n }\n\n // Priority 3: Load from local filesystem\n return loadLocalFile(path);\n}\n\n/**\n * Resolve a file input to content ready for LLM\n */\nasync function resolveFileInput(\n item: LlmOperateInputFile,\n): Promise<ResolvedContent> {\n let buffer = await loadFileData(item);\n const mimeType = getMimeType(item.file) || \"application/octet-stream\";\n const filename = item.file.split(\"/\").pop() || item.file;\n\n // Handle PDF page extraction\n if (isPdfExtension(item.file) && item.pages && item.pages.length > 0) {\n buffer = await extractPdfPages(buffer, item.pages);\n }\n\n return {\n data: buffer.toString(\"base64\"),\n filename,\n mimeType,\n };\n}\n\n/**\n * Resolve an image input to content ready for LLM\n */\nasync function resolveImageInput(\n item: LlmOperateInputImage,\n): Promise<ResolvedContent> {\n const buffer = await loadFileData(item);\n const mimeType = getMimeType(item.image) || \"image/png\";\n const filename = item.image.split(\"/\").pop() || item.image;\n\n return {\n data: buffer.toString(\"base64\"),\n filename,\n mimeType,\n };\n}\n\n/**\n * Convert resolved content to LlmInputContent\n */\nfunction toInputContent(\n resolved: ResolvedContent,\n isImage: boolean,\n): LlmInputContent {\n if (isImage) {\n const imageContent: LlmInputContentImage = {\n image_url: `data:${resolved.mimeType};base64,${resolved.data}`,\n type: LlmMessageType.InputImage,\n };\n return imageContent;\n }\n\n const fileContent: LlmInputContentFile = {\n file_data: `data:${resolved.mimeType};base64,${resolved.data}`,\n filename: resolved.filename,\n type: LlmMessageType.InputFile,\n };\n return fileContent;\n}\n\n/**\n * Resolve a single content item\n */\nasync function resolveContentItem(\n item: LlmOperateInputContent,\n): Promise<LlmInputContent> {\n // String becomes text content\n if (typeof item === \"string\") {\n const textContent: LlmInputContentText = {\n text: item,\n type: LlmMessageType.InputText,\n };\n return textContent;\n }\n\n // Image input\n if (isLlmOperateInputImage(item)) {\n const resolved = await resolveImageInput(item);\n return toInputContent(resolved, true);\n }\n\n // File input\n if (isLlmOperateInputFile(item)) {\n const resolved = await resolveFileInput(item);\n // Check if the file is actually an image based on extension\n const isImage = isImageExtension(item.file);\n return toInputContent(resolved, isImage);\n }\n\n // Fallback - shouldn't reach here if types are correct\n throw new Error(`Unknown content item type: ${JSON.stringify(item)}`);\n}\n\n/**\n * Resolve LlmOperateInput to LlmInputMessage\n *\n * This function takes the simplified LlmOperateInput format and resolves\n * all files/images from their sources (provided data, S3, or local filesystem),\n * converting them to the standard LlmInputMessage format.\n *\n * @param input - LlmOperateInput array\n * @returns LlmInputMessage ready for LLM providers\n */\nexport async function resolveOperateInput(\n input: LlmOperateInput,\n): Promise<LlmInputMessage> {\n const content: LlmInputContent[] = await Promise.all(\n input.map(resolveContentItem),\n );\n\n return {\n content,\n role: LlmMessageRole.User,\n type: LlmMessageType.Message,\n };\n}\n","import { placeholders } from \"@jaypie/kit\";\n\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateInput,\n LlmOperateOptions,\n} from \"../../types/LlmProvider.interface.js\";\nimport { isLlmOperateInput } from \"../../types/LlmOperateInput.guards.js\";\nimport { resolveOperateInput } from \"../../upload/resolveOperateInput.js\";\nimport { formatOperateInput } from \"../../util/index.js\";\n\n//\n//\n// Types\n//\n\nexport interface ProcessedInput {\n /** The processed history with all messages formatted */\n history: LlmHistory;\n /** Processed instructions with placeholders applied */\n instructions?: string;\n /** Processed system prompt with placeholders applied */\n system?: string;\n}\n\n//\n//\n// Main\n//\n\n/**\n * InputProcessor handles input normalization, placeholder substitution,\n * and history merging for the operate loop.\n */\nexport class InputProcessor {\n /**\n * Process input with placeholders, history merging, and system message handling\n *\n * @param input - The raw input (string, message, history, or LlmOperateInput)\n * @param options - The operate options containing data, history, system, etc.\n * @returns Processed input with all transformations applied\n */\n async process(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions = {},\n ): Promise<ProcessedInput> {\n // Handle LlmOperateInput by resolving files first\n let resolvedInput: string | LlmHistory | LlmInputMessage = input as\n string | LlmHistory | LlmInputMessage;\n if (isLlmOperateInput(input)) {\n resolvedInput = await resolveOperateInput(input);\n }\n\n // Convert input to history format with placeholder substitution\n let history: LlmHistory = this.formatInputWithPlaceholders(\n resolvedInput,\n options,\n );\n\n // Process instructions with placeholders\n const instructions = this.processInstructions(options);\n\n // Process system prompt with placeholders\n const system = this.processSystem(options);\n\n // Merge with provided history\n if (options.history) {\n history = [...options.history, ...history];\n }\n\n // Handle system message prepending\n if (system) {\n history = this.prependSystemMessage(history, system);\n }\n\n return {\n history,\n instructions,\n system,\n };\n }\n\n /**\n * Format input and apply placeholders if data is provided\n */\n private formatInputWithPlaceholders(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions,\n ): LlmHistory {\n // Apply placeholders to input if data is provided and placeholders.input is not false\n if (\n options.data &&\n (options.placeholders?.input === undefined || options.placeholders?.input)\n ) {\n return formatOperateInput(input, { data: options.data });\n }\n\n return formatOperateInput(input);\n }\n\n /**\n * Process instructions with placeholder substitution\n */\n private processInstructions(options: LlmOperateOptions): string | undefined {\n if (!options.instructions) {\n return undefined;\n }\n\n // Apply placeholders to instructions if data is provided and placeholders.instructions is not false\n if (\n options.data &&\n (options.placeholders?.instructions === undefined ||\n options.placeholders?.instructions)\n ) {\n return placeholders(options.instructions, options.data);\n }\n\n return options.instructions;\n }\n\n /**\n * Process system prompt with placeholder substitution\n */\n private processSystem(options: LlmOperateOptions): string | undefined {\n if (!options.system) {\n return undefined;\n }\n\n // Apply placeholders to system if data is provided and placeholders.system is not false\n if (options.data && options.placeholders?.system !== false) {\n return placeholders(options.system, options.data);\n }\n\n return options.system;\n }\n\n /**\n * Prepend system message to history, handling duplicates\n */\n private prependSystemMessage(\n history: LlmHistory,\n systemContent: string,\n ): LlmHistory {\n // Create system message\n const systemMessage: LlmInputMessage = {\n content: systemContent,\n role: LlmMessageRole.System,\n type: LlmMessageType.Message,\n };\n\n // Check if history starts with an identical system message\n const firstMessage = history[0] as LlmInputMessage | undefined;\n const isIdenticalSystemMessage =\n firstMessage?.type === LlmMessageType.Message &&\n firstMessage?.role === LlmMessageRole.System &&\n firstMessage?.content === systemContent;\n\n // If identical, return as-is\n if (isIdenticalSystemMessage) {\n return history;\n }\n\n // Remove any existing system message from the beginning\n if (\n firstMessage?.type === LlmMessageType.Message &&\n firstMessage?.role === LlmMessageRole.System\n ) {\n return [systemMessage, ...history.slice(1)];\n }\n\n // Prepend new system message\n return [systemMessage, ...history];\n }\n}\n\n// Export singleton instance for convenience\nexport const inputProcessor = new InputProcessor();\n","import {\n LlmProgressCallback,\n LlmProgressEvent,\n} from \"../../types/LlmProvider.interface.js\";\nimport { getLogger } from \"../../util/index.js\";\n\n/**\n * Deliver a progress event to the caller's onProgress callback.\n * Errors thrown by the callback are logged and swallowed — progress\n * reporting must never interrupt the operate loop.\n */\nexport async function emitProgress({\n event,\n onProgress,\n}: {\n event: LlmProgressEvent;\n onProgress?: LlmProgressCallback;\n}): Promise<void> {\n if (!onProgress) {\n return;\n }\n try {\n await onProgress(event);\n } catch (error) {\n const log = getLogger();\n log.warn(`[operate] onProgress callback threw on \"${event.type}\" event`);\n log.var({ error });\n }\n}\n","import { JsonObject, JsonReturn } from \"@jaypie/types\";\n\nimport {\n LlmHistory,\n LlmOperateResponse,\n LlmResponseStatus,\n LlmUsage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { extractReasoning } from \"../../util/extractReasoning.js\";\n\n// Derive LlmOutput type from LlmOperateResponse since it's not exported\ntype LlmOutput = LlmOperateResponse[\"output\"];\n\n//\n//\n// Types\n//\n\nexport interface ResponseBuilderConfig {\n model: string;\n provider: string;\n}\n\nexport interface LlmError {\n detail?: string;\n status: number | string;\n title: string;\n}\n\n//\n//\n// Main\n//\n\n/**\n * ResponseBuilder provides a fluent API for constructing LlmOperateResponse objects.\n * It standardizes response construction across providers.\n */\nexport class ResponseBuilder {\n private response: LlmOperateResponse;\n\n constructor(config: ResponseBuilderConfig) {\n this.response = {\n content: undefined,\n error: undefined,\n history: [],\n model: config.model,\n output: [],\n provider: config.provider,\n reasoning: [],\n responses: [],\n status: LlmResponseStatus.InProgress,\n usage: [],\n };\n }\n\n /**\n * Set the response content\n */\n setContent(content: string | JsonObject | undefined): this {\n this.response.content = content;\n return this;\n }\n\n /**\n * Set the response status\n */\n setStatus(status: LlmResponseStatus): this {\n this.response.status = status;\n return this;\n }\n\n /**\n * Set an error on the response\n */\n setError(error: LlmError): this {\n this.response.error = error;\n return this;\n }\n\n /**\n * Set the history\n */\n setHistory(history: LlmHistory): this {\n this.response.history = history;\n return this;\n }\n\n /**\n * Append items to the history\n */\n appendToHistory(...items: LlmHistory): this {\n this.response.history.push(...items);\n return this;\n }\n\n /**\n * Set the output\n */\n setOutput(output: LlmOutput): this {\n this.response.output = output;\n return this;\n }\n\n /**\n * Append items to the output\n */\n appendToOutput(...items: LlmOutput): this {\n this.response.output.push(...items);\n return this;\n }\n\n /**\n * Set the reasoning array\n */\n setReasoning(reasoning: string[]): this {\n this.response.reasoning = reasoning;\n return this;\n }\n\n /**\n * Append reasoning text items\n */\n appendToReasoning(...items: string[]): this {\n this.response.reasoning.push(...items);\n return this;\n }\n\n /**\n * Get the current reasoning array\n */\n getReasoning(): string[] {\n return this.response.reasoning;\n }\n\n /**\n * Add a raw provider response\n */\n addResponse(response: JsonReturn): this {\n this.response.responses.push(response);\n return this;\n }\n\n /**\n * Add a usage entry for a single API call\n */\n addUsage(usage: LlmUsageItem): this {\n this.response.usage.push(usage);\n return this;\n }\n\n /**\n * Set the entire usage array\n */\n setUsage(usage: LlmUsage): this {\n this.response.usage = usage;\n return this;\n }\n\n /**\n * Get the current usage array for modifications\n */\n getUsage(): LlmUsage {\n return this.response.usage;\n }\n\n /**\n * Get the current history for modifications\n */\n getHistory(): LlmHistory {\n return this.response.history;\n }\n\n /**\n * Get the current output for modifications\n */\n getOutput(): LlmOutput {\n return this.response.output;\n }\n\n /**\n * Mark response as completed\n */\n complete(): this {\n this.response.status = LlmResponseStatus.Completed;\n return this;\n }\n\n /**\n * Mark response as incomplete (e.g., max turns exceeded)\n */\n incomplete(): this {\n this.response.status = LlmResponseStatus.Incomplete;\n return this;\n }\n\n /**\n * Build and return the final response object.\n * Automatically extracts reasoning from history if not already set.\n */\n build(): LlmOperateResponse {\n // Extract reasoning from history if not already populated\n if (this.response.reasoning.length === 0) {\n this.response.reasoning = extractReasoning(this.response.history);\n }\n return { ...this.response };\n }\n}\n\n/**\n * Factory function to create a new ResponseBuilder\n */\nexport function createResponseBuilder(\n config: ResponseBuilderConfig,\n): ResponseBuilder {\n return new ResponseBuilder(config);\n}\n","//\n//\n// Constants\n//\n\nexport const DEFAULT_INITIAL_DELAY_MS = 1000; // 1 second\nexport const DEFAULT_MAX_DELAY_MS = 32000; // 32 seconds\nexport const DEFAULT_BACKOFF_FACTOR = 2; // Exponential backoff multiplier\nexport const DEFAULT_MAX_RETRIES = 6;\nexport const MAX_RETRIES_ABSOLUTE_LIMIT = 72;\n\n//\n//\n// Types\n//\n\nexport interface RetryPolicyConfig {\n /** Initial delay in milliseconds before first retry. Default: 1000 */\n initialDelayMs?: number;\n /** Maximum delay in milliseconds between retries. Default: 32000 */\n maxDelayMs?: number;\n /** Backoff multiplier for exponential backoff. Default: 2 */\n backoffFactor?: number;\n /** Maximum number of retries. Default: 6 */\n maxRetries?: number;\n}\n\n//\n//\n// Main\n//\n\n/**\n * RetryPolicy encapsulates retry configuration and delay calculation\n * for the operate loop's retry logic.\n */\nexport class RetryPolicy {\n readonly initialDelayMs: number;\n readonly maxDelayMs: number;\n readonly backoffFactor: number;\n readonly maxRetries: number;\n\n constructor(config: RetryPolicyConfig = {}) {\n this.initialDelayMs = config.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n this.maxDelayMs = config.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n this.backoffFactor = config.backoffFactor ?? DEFAULT_BACKOFF_FACTOR;\n this.maxRetries = Math.min(\n config.maxRetries ?? DEFAULT_MAX_RETRIES,\n MAX_RETRIES_ABSOLUTE_LIMIT,\n );\n }\n\n /**\n * Calculate the delay for a given attempt number (0-indexed)\n */\n getDelayForAttempt(attempt: number): number {\n const delay = this.initialDelayMs * Math.pow(this.backoffFactor, attempt);\n return Math.min(delay, this.maxDelayMs);\n }\n\n /**\n * Check if another retry should be attempted\n */\n shouldRetry(currentAttempt: number): boolean {\n return currentAttempt < this.maxRetries;\n }\n}\n\n// Export a default policy instance\nexport const defaultRetryPolicy = new RetryPolicy();\n","import { getLogger } from \"../../util/index.js\";\nimport { isTransientNetworkError } from \"./isTransientNetworkError.js\";\n\n//\n//\n// Types\n//\n\nexport interface StaleRejectionGuard {\n /** Install the unhandledRejection listener (idempotent) */\n install(): void;\n /** Remove the listener and forget recorded errors */\n remove(): void;\n /** Record an error the retry loop has caught and is handling */\n recordCaught(error: unknown): void;\n}\n\n//\n//\n// Helpers\n//\n\n/**\n * Compare an unhandled rejection reason against errors the retry loop has\n * already caught. Reference equality first, then fall back to message + name\n * — providers sometimes surface twin rejections as fresh Error instances\n * rebuilt from the same upstream failure.\n */\nfunction matchesCaughtError(\n reason: unknown,\n caught: ReadonlySet<unknown>,\n): boolean {\n if (caught.has(reason)) return true;\n if (!(reason instanceof Error)) return false;\n for (const handled of caught) {\n if (\n handled instanceof Error &&\n handled.name === reason.name &&\n handled.message === reason.message\n ) {\n return true;\n }\n }\n return false;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Create a guard that suppresses unhandled rejections firing as siblings of\n * an error the retry loop has already caught. Provider SDKs occasionally\n * surface a single upstream failure as twin rejections — the retry layer\n * accepts responsibility for the first; this guard prevents the second from\n * crashing the host while the retry is in flight.\n *\n * The guard also continues to suppress transient socket teardown errors\n * (e.g. undici `TypeError: terminated`) emitted between attempts.\n */\nexport function createStaleRejectionGuard(): StaleRejectionGuard {\n const log = getLogger();\n const caughtErrors = new Set<unknown>();\n let listener:\n ((reason: unknown, promise: Promise<unknown>) => void) | undefined;\n\n return {\n install() {\n if (listener) return;\n listener = (reason, promise) => {\n if (isTransientNetworkError(reason)) {\n promise?.catch?.(() => {});\n log.trace(\"Suppressed stale socket error during retry\");\n return;\n }\n if (matchesCaughtError(reason, caughtErrors)) {\n promise?.catch?.(() => {});\n log.trace(\"Suppressed sibling rejection of already-handled error\");\n }\n };\n process.on(\"unhandledRejection\", listener);\n },\n remove() {\n if (listener) {\n process.removeListener(\"unhandledRejection\", listener);\n listener = undefined;\n }\n caughtErrors.clear();\n },\n recordCaught(error) {\n caughtErrors.add(error);\n },\n };\n}\n","import { JaypieError } from \"@jaypie/errors\";\nimport { ErrorCategory } from \"../operate/types.js\";\n\n//\n//\n// Types\n//\n\nexport interface LlmErrorOptions {\n /** Provider name that produced the error (e.g. \"anthropic\", \"google\") */\n provider?: string;\n /** Model in use when the error occurred */\n model?: string;\n /** Milliseconds to wait before retrying, when the provider suggests one */\n retryAfterMs?: number;\n /** The original provider error, preserved for inspection */\n cause?: unknown;\n}\n\n//\n//\n// Base\n//\n\n/**\n * Normalized, provider-agnostic LLM error. Thrown by the operate/stream retry\n * layer when a request cannot be completed, so consumers can `catch` a stable\n * type regardless of which provider failed. Extends {@link JaypieError} so\n * `isJaypieError()` and `.status` continue to work; the original provider error\n * is preserved on `.cause`.\n */\nexport class LlmError extends JaypieError {\n readonly category: ErrorCategory;\n readonly provider?: string;\n readonly model?: string;\n readonly retryAfterMs?: number;\n readonly cause?: unknown;\n\n constructor(\n message: string,\n category: ErrorCategory,\n {\n status = 502,\n title = \"Bad Gateway\",\n provider,\n model,\n retryAfterMs,\n cause,\n }: LlmErrorOptions & { status?: number; title?: string } = {},\n ) {\n super(message, { status, title }, { _type: \"LlmError\" });\n this.name = \"LlmError\";\n this.category = category;\n this.provider = provider;\n this.model = model;\n this.retryAfterMs = retryAfterMs;\n this.cause = cause;\n }\n}\n\n//\n//\n// Subclasses\n//\n\n/**\n * Short-term rate limiting (per-minute 429). Terminal within the request\n * budget; `retryAfterMs` carries the provider's suggested wait when available.\n */\nexport class LlmRateLimitError extends LlmError {\n constructor(message: string, options: LlmErrorOptions = {}) {\n super(message, ErrorCategory.RateLimit, {\n status: 429,\n title: \"Too Many Requests\",\n ...options,\n });\n this.name = \"LlmRateLimitError\";\n }\n}\n\n/**\n * Provider quota is exhausted or the account cannot be billed. Terminal and\n * actionable. `reason` distinguishes an exhausted usage quota from insufficient\n * funds.\n */\nexport class LlmQuotaError extends LlmError {\n readonly reason: \"quota\" | \"billing\";\n\n constructor(\n message: string,\n {\n reason = \"quota\",\n ...options\n }: LlmErrorOptions & {\n reason?: \"quota\" | \"billing\";\n } = {},\n ) {\n super(message, ErrorCategory.Quota, {\n status: 402,\n title: \"Payment Required\",\n ...options,\n });\n this.name = \"LlmQuotaError\";\n this.reason = reason;\n }\n}\n\n/**\n * The request cannot be recovered from (bad request, authentication,\n * permission, not found). Terminal.\n */\nexport class LlmUnrecoverableError extends LlmError {\n constructor(message: string, options: LlmErrorOptions = {}) {\n super(message, ErrorCategory.Unrecoverable, {\n status: 502,\n title: \"Bad Gateway\",\n ...options,\n });\n this.name = \"LlmUnrecoverableError\";\n }\n}\n\n/**\n * A transient or unknown error survived the retry budget. Terminal only because\n * retries were exhausted; the underlying condition may succeed later.\n */\nexport class LlmTransientError extends LlmError {\n constructor(message: string, options: LlmErrorOptions = {}) {\n super(message, ErrorCategory.Retryable, {\n status: 504,\n title: \"Gateway Timeout\",\n ...options,\n });\n this.name = \"LlmTransientError\";\n }\n}\n","import { ClassifiedError, ErrorCategory } from \"../operate/types.js\";\nimport {\n LlmError,\n LlmErrorOptions,\n LlmQuotaError,\n LlmRateLimitError,\n LlmTransientError,\n LlmUnrecoverableError,\n} from \"./LlmError.js\";\n\n/**\n * Map a {@link ClassifiedError} to the matching {@link LlmError} subclass,\n * preserving the original error as `cause`. Used by the retry layer to throw a\n * stable, catchable type instead of a bare gateway error.\n */\nexport function toLlmError(\n classified: ClassifiedError,\n context: { provider?: string; model?: string } = {},\n): LlmError {\n const original = classified.error;\n const message =\n original instanceof Error ? original.message : String(original);\n const options: LlmErrorOptions = {\n cause: original,\n model: context.model,\n provider: context.provider,\n retryAfterMs: classified.suggestedDelayMs,\n };\n\n switch (classified.category) {\n case ErrorCategory.RateLimit:\n return new LlmRateLimitError(message, options);\n case ErrorCategory.Quota:\n return new LlmQuotaError(message, {\n ...options,\n reason: classified.reason ?? \"quota\",\n });\n case ErrorCategory.Unrecoverable:\n return new LlmUnrecoverableError(message, options);\n case ErrorCategory.Retryable:\n case ErrorCategory.Unknown:\n default:\n return new LlmTransientError(message, options);\n }\n}\n","import { sleep } from \"@jaypie/kit\";\n\nimport { getLogger } from \"../../util/index.js\";\nimport { createStaleRejectionGuard } from \"./createStaleRejectionGuard.js\";\nimport {\n HookRunner,\n hookRunner as defaultHookRunner,\n LlmHooks,\n} from \"../hooks/HookRunner.js\";\nimport { RetryPolicy, defaultRetryPolicy } from \"./RetryPolicy.js\";\nimport { ClassifiedError } from \"../types.js\";\nimport { toLlmError } from \"../../errors/toLlmError.js\";\n\n//\n//\n// Types\n//\n\nexport interface RetryContext {\n input: unknown;\n options?: unknown;\n providerRequest: unknown;\n /** Provider name, carried onto the thrown LlmError */\n provider?: string;\n /** Model in use, carried onto the thrown LlmError */\n model?: string;\n}\n\nexport interface ErrorClassifier {\n isRetryable(error: unknown): boolean;\n isKnownError(error: unknown): boolean;\n /** Full classification, used to throw a typed LlmError on terminal failure */\n classify(error: unknown): ClassifiedError;\n}\n\nexport interface RetryExecutorConfig {\n errorClassifier: ErrorClassifier;\n hookRunner?: HookRunner;\n policy?: RetryPolicy;\n}\n\nexport interface ExecuteOptions {\n context: RetryContext;\n hooks?: LlmHooks;\n}\n\n//\n//\n// Main\n//\n\n/**\n * RetryExecutor handles the retry loop logic for LLM API calls.\n * It provides exponential backoff, error classification, and hook execution.\n */\nexport class RetryExecutor {\n private readonly policy: RetryPolicy;\n private readonly hookRunner: HookRunner;\n private readonly errorClassifier: ErrorClassifier;\n\n constructor(config: RetryExecutorConfig) {\n this.policy = config.policy ?? defaultRetryPolicy;\n this.hookRunner = config.hookRunner ?? defaultHookRunner;\n this.errorClassifier = config.errorClassifier;\n }\n\n /**\n * Build the typed, provider-agnostic error thrown when a request cannot be\n * completed — classified (rate limit / quota / unrecoverable / transient)\n * and carrying the provider, model, and original error as `cause`.\n */\n private toTerminalError(error: unknown, context: RetryContext) {\n const classified = this.errorClassifier.classify(error);\n return toLlmError(classified, {\n model: context.model,\n provider: context.provider,\n });\n }\n\n /**\n * Execute an operation with retry logic.\n * Each attempt receives an AbortSignal. On failure, the signal is aborted\n * before sleeping — this kills lingering socket callbacks from the previous\n * request and prevents stale async errors from escaping the retry loop.\n *\n * @param operation - The async operation to execute (receives AbortSignal)\n * @param options - Execution options including context and hooks\n * @returns The result of the operation\n * @throws BadGatewayError if all retries are exhausted or error is not retryable\n */\n async execute<T>(\n operation: ((signal: AbortSignal) => Promise<T>) | (() => Promise<T>),\n options: ExecuteOptions,\n ): Promise<T> {\n const log = getLogger();\n let attempt = 0;\n\n // Guard against stale rejections firing on a subsequent microtask after\n // the retry layer has already caught the originating error: undici socket\n // teardown (TypeError: terminated) and twin upstream-SDK rejections\n // (e.g. issue #336 — OpenRouter SyntaxError siblings).\n const guard = createStaleRejectionGuard();\n\n try {\n while (true) {\n const controller = new AbortController();\n\n try {\n const result = await operation(controller.signal);\n\n if (attempt > 0) {\n log.debug(`API call succeeded after ${attempt} retries`);\n }\n\n return result;\n } catch (error: unknown) {\n controller.abort(\"retry\");\n\n guard.recordCaught(error);\n guard.install();\n\n // Check if we've exhausted retries\n if (!this.policy.shouldRetry(attempt)) {\n log.error(\n `API call failed after ${this.policy.maxRetries} retries`,\n );\n log.var({ error });\n\n await this.hookRunner.runOnUnrecoverableError(options.hooks, {\n input: options.context.input as never,\n options: options.context.options as never,\n providerRequest: options.context.providerRequest,\n error,\n });\n\n throw this.toTerminalError(error, options.context);\n }\n\n // Check if error is not retryable\n if (!this.errorClassifier.isRetryable(error)) {\n log.error(\"API call failed with non-retryable error\");\n log.var({ error });\n\n await this.hookRunner.runOnUnrecoverableError(options.hooks, {\n input: options.context.input as never,\n options: options.context.options as never,\n providerRequest: options.context.providerRequest,\n error,\n });\n\n throw this.toTerminalError(error, options.context);\n }\n\n // Warn if this is an unknown error type\n if (!this.errorClassifier.isKnownError(error)) {\n log.warn(\"API returned unknown error type, will retry\");\n log.var({ error });\n }\n\n const delay = this.policy.getDelayForAttempt(attempt);\n log.warn(`API call failed. Retrying in ${delay}ms...`);\n\n await this.hookRunner.runOnRetryableError(options.hooks, {\n input: options.context.input as never,\n options: options.context.options as never,\n providerRequest: options.context.providerRequest,\n error,\n });\n\n await sleep(delay);\n attempt++;\n }\n }\n } finally {\n guard.remove();\n }\n }\n}\n","import { BadGatewayError, TooManyRequestsError } from \"@jaypie/errors\";\nimport { JsonObject } from \"@jaypie/types\";\n\nimport { Toolkit } from \"../tools/Toolkit.class.js\";\nimport {\n LlmExchangeEnvelope,\n LlmHistory,\n LlmHistoryItem,\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateInput,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmOutputMessage,\n LlmProgressEventType,\n LlmResponseStatus,\n LlmToolCall,\n LlmToolResult,\n} from \"../types/LlmProvider.interface.js\";\nimport {\n annotateLlmObs,\n usageToLlmObsMetrics,\n withLlmObsSpan,\n} from \"../observability/llmobs.js\";\nimport {\n fillFormatArrays,\n getLogger,\n maxTurnsFromOptions,\n repairFormatKeys,\n tallyOperate,\n} from \"../util/index.js\";\nimport { ProviderAdapter } from \"./adapters/ProviderAdapter.interface.js\";\nimport {\n buildExchangeEnvelope,\n isExchangeRequested,\n} from \"./exchange/index.js\";\nimport { HookRunner, hookRunner, LlmHooks } from \"./hooks/index.js\";\nimport { InputProcessor, inputProcessor } from \"./input/index.js\";\nimport { emitProgress } from \"./progress/index.js\";\nimport {\n createResponseBuilder,\n ResponseBuilderConfig,\n} from \"./response/index.js\";\nimport {\n defaultRetryPolicy,\n ErrorClassifier,\n RetryExecutor,\n RetryPolicy,\n} from \"./retry/index.js\";\nimport {\n OperateContext,\n OperateLoopState,\n OperateRequest,\n ProviderToolDefinition,\n StandardToolResult,\n} from \"./types.js\";\n\n//\n//\n// Types\n//\n\nexport interface OperateLoopConfig {\n adapter: ProviderAdapter;\n client: unknown;\n hookRunner?: HookRunner;\n inputProcessor?: InputProcessor;\n retryPolicy?: RetryPolicy;\n}\n\n//\n//\n// Constants\n//\n\nconst ERROR = {\n BAD_FUNCTION_CALL: \"Bad Function Call\",\n};\n\nexport const MAX_CONSECUTIVE_TOOL_ERRORS = 6;\n\n//\n//\n// Helpers\n//\n\n/**\n * Create an ErrorClassifier from a ProviderAdapter\n */\nfunction createErrorClassifier(adapter: ProviderAdapter): ErrorClassifier {\n return {\n classify: (error: unknown) => adapter.classifyError(error),\n isRetryable: (error: unknown) => adapter.isRetryableError(error),\n isKnownError: (error: unknown) => {\n const classified = adapter.classifyError(error);\n return classified.category !== \"unknown\";\n },\n };\n}\n\n/**\n * Attempt to read a prose response as the structured payload itself: parse the\n * text (stripping a Markdown code fence if present) and return the object, or\n * undefined when the text is not a JSON object.\n */\nfunction tryParseJsonObject(text: string): JsonObject | undefined {\n let candidate = text.trim();\n const fence = candidate.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```$/);\n if (fence) {\n candidate = fence[1].trim();\n }\n if (!candidate.startsWith(\"{\")) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(candidate);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as JsonObject;\n }\n } catch {\n // Not JSON; caller falls through to the corrective-turn path.\n }\n return undefined;\n}\n\n//\n//\n// Main\n//\n\n/**\n * OperateLoop implements the core multi-turn conversation loop.\n * It orchestrates provider adapters, retry logic, hook execution, and tool calling.\n *\n * This class uses Template Method + Strategy patterns:\n * - Template Method: The execute() method defines the algorithm skeleton\n * - Strategy: Provider adapters handle provider-specific operations\n */\nexport class OperateLoop {\n private readonly adapter: ProviderAdapter;\n private readonly client: unknown;\n private readonly hookRunnerInstance: HookRunner;\n private readonly inputProcessorInstance: InputProcessor;\n private readonly retryPolicy: RetryPolicy;\n\n constructor(config: OperateLoopConfig) {\n this.adapter = config.adapter;\n this.client = config.client;\n this.hookRunnerInstance = config.hookRunner ?? hookRunner;\n this.inputProcessorInstance = config.inputProcessor ?? inputProcessor;\n this.retryPolicy = config.retryPolicy ?? defaultRetryPolicy;\n }\n\n /**\n * Execute the operate loop for multi-turn conversations with tool calling.\n */\n async execute(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const log = getLogger();\n // Log what was passed to operate\n log.trace(\"[operate] Starting operate loop\");\n log.trace.var({ \"operate.input\": input });\n log.trace.var({ \"operate.options\": options });\n\n const startedAt = new Date().toISOString();\n const startMs = Date.now();\n\n // Initialize state\n const state = await this.initializeState(input, options);\n const context = this.createContext(options);\n const modelName = options.model ?? this.adapter.defaultModel;\n const exchangeRequested = isExchangeRequested(options);\n const initialHistoryLength = state.responseBuilder.getHistory().length;\n\n await emitProgress({\n event: {\n maxTurns: state.maxTurns,\n model: modelName,\n provider: this.adapter.name,\n type: LlmProgressEventType.Start,\n },\n onProgress: options.onProgress,\n });\n\n // Enclosing LLM Observability span (no-op when DD_LLMOBS_ENABLED is unset).\n // Child llm/tool spans nest under it via the SDK's active-span context.\n try {\n return await withLlmObsSpan(\n {\n kind: state.toolkit ? \"agent\" : \"llm\",\n modelName,\n modelProvider: this.adapter.name,\n name: \"jaypie.llm.operate\",\n },\n async () => {\n // Build initial request\n let request = this.buildInitialRequest(state, options);\n\n // Multi-turn loop\n while (state.currentTurn < state.maxTurns) {\n state.currentTurn++;\n\n // Execute one turn with retry logic\n const shouldContinue = await this.executeOneTurn(\n request,\n state,\n context,\n options,\n );\n\n if (!shouldContinue) {\n break;\n }\n\n // Rebuild request with updated history for next turn\n request = {\n effort: options.effort,\n format: state.formattedFormat,\n instructions: options.instructions,\n messages: state.currentInput,\n model: modelName,\n providerOptions: options.providerOptions,\n structuredOutputRetry: state.structuredOutputRetry,\n system: options.system,\n temperature: options.temperature,\n tools: state.formattedTools,\n user: options.user,\n };\n }\n\n const response = state.responseBuilder.build();\n if (exchangeRequested) {\n response.exchange = buildExchangeEnvelope({\n duration: Date.now() - startMs,\n initialHistoryLength,\n input,\n options,\n response,\n startedAt,\n state,\n });\n }\n annotateLlmObs({\n inputData: input,\n metrics: usageToLlmObsMetrics(response.usage),\n outputData: response.content,\n });\n tallyOperate({\n toolCallNames: state.toolCallNames,\n turns: state.currentTurn,\n usage: response.usage,\n });\n await emitProgress({\n event: {\n content: response.content,\n turn: state.currentTurn,\n type: LlmProgressEventType.Done,\n usage: response.usage,\n },\n onProgress: options.onProgress,\n });\n return response;\n },\n );\n } catch (error) {\n // A hard failure (retry budget exhausted, unrecoverable) still settles\n // the exchange: attach the envelope to the thrown error so the facade\n // can emit it before rethrowing to the caller.\n if (exchangeRequested) {\n const response = state.responseBuilder.build();\n if (!response.error) {\n const thrown = error as {\n detail?: string;\n message?: string;\n status?: number | string;\n title?: string;\n name?: string;\n };\n response.error = {\n detail: thrown.detail ?? thrown.message,\n status: thrown.status ?? 500,\n title: thrown.title ?? thrown.name ?? \"Error\",\n };\n }\n if (response.status === LlmResponseStatus.InProgress) {\n response.status = LlmResponseStatus.Incomplete;\n }\n (error as { exchange?: LlmExchangeEnvelope }).exchange =\n buildExchangeEnvelope({\n duration: Date.now() - startMs,\n initialHistoryLength,\n input,\n options,\n response,\n startedAt,\n state,\n });\n }\n throw error;\n }\n }\n\n //\n // Private Methods\n //\n\n private async initializeState(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions,\n ): Promise<OperateLoopState> {\n // Process input with placeholders\n const processedInput = await this.inputProcessorInstance.process(\n input,\n options,\n );\n\n // Determine max turns\n const maxTurns = maxTurnsFromOptions(options);\n\n // Initialize response builder\n const responseBuilderConfig: ResponseBuilderConfig = {\n model: options.model ?? this.adapter.defaultModel,\n provider: this.adapter.name,\n };\n const responseBuilder = createResponseBuilder(responseBuilderConfig);\n\n // Set initial history\n responseBuilder.setHistory([...processedInput.history]);\n\n // Get toolkit\n let toolkit: Toolkit | undefined;\n if (options.tools) {\n if (options.tools instanceof Toolkit) {\n toolkit = options.tools;\n } else if (Array.isArray(options.tools) && options.tools.length > 0) {\n const explain = options.explain ?? false;\n toolkit = new Toolkit(options.tools, { explain });\n }\n }\n\n // Format output schema through adapter if provided\n let formattedFormat: JsonObject | undefined;\n if (options.format) {\n formattedFormat = this.adapter.formatOutputSchema(\n options.format,\n ) as JsonObject;\n }\n\n // Format tools through adapter\n // If format is provided but no toolkit, create an empty toolkit\n // so that structured_output tool can be added for providers that need it\n // (Anthropic, OpenRouter use tool-based structured output)\n let formattedTools: ProviderToolDefinition[] | undefined;\n if (toolkit) {\n formattedTools = this.adapter.formatTools(toolkit, formattedFormat);\n } else if (formattedFormat) {\n // Create empty toolkit just for structured output\n const emptyToolkit = new Toolkit([]);\n formattedTools = this.adapter.formatTools(emptyToolkit, formattedFormat);\n // Only include if there are tools (structured_output was added)\n if (formattedTools.length === 0) {\n formattedTools = undefined;\n }\n }\n\n return {\n consecutiveToolErrors: 0,\n currentInput: processedInput.history,\n currentTurn: 0,\n formattedFormat,\n formattedTools,\n maxTurns,\n responseBuilder,\n retries: 0,\n toolCallNames: [],\n toolkit,\n };\n }\n\n private createContext(options: LlmOperateOptions): OperateContext {\n return {\n hooks: options.hooks ?? {},\n options,\n };\n }\n\n private buildInitialRequest(\n state: OperateLoopState,\n options: LlmOperateOptions,\n ): OperateRequest {\n return {\n cache: options.cache,\n effort: options.effort,\n format: state.formattedFormat,\n instructions: options.instructions,\n messages: state.currentInput,\n model: options.model ?? this.adapter.defaultModel,\n providerOptions: options.providerOptions,\n system: options.system,\n temperature: options.temperature,\n tools: state.formattedTools,\n user: options.user,\n };\n }\n\n private async executeOneTurn(\n request: OperateRequest,\n state: OperateLoopState,\n context: OperateContext,\n options: LlmOperateOptions,\n ): Promise<boolean> {\n const log = getLogger();\n // Create error classifier from adapter\n const errorClassifier = createErrorClassifier(this.adapter);\n\n // Create retry executor for this turn\n const retryExecutor = new RetryExecutor({\n errorClassifier,\n hookRunner: this.hookRunnerInstance,\n policy: this.retryPolicy,\n });\n\n // Build provider-specific request\n const providerRequest = this.adapter.buildRequest(request);\n\n // Log a draconian subset of the request; the full payload is available\n // via the beforeEachModelRequest hook\n log.trace(\"[operate] Calling model\");\n log.trace.var({\n \"operate.request\": {\n latest: this.summarizeHistoryItem(\n request.messages[request.messages.length - 1],\n ),\n messages: request.messages.length,\n model: request.model,\n turn: state.currentTurn,\n },\n });\n\n await emitProgress({\n event: {\n model: request.model,\n turn: state.currentTurn,\n type: LlmProgressEventType.ModelRequest,\n },\n onProgress: options.onProgress,\n });\n\n // Execute beforeEachModelRequest hook\n await this.hookRunnerInstance.runBeforeModelRequest(context.hooks, {\n input: state.currentInput,\n options,\n providerRequest,\n });\n\n // Count retries for the exchange envelope and emit retry progress\n // alongside the caller's onRetryableModelError hook\n const hooks = context.hooks as LlmHooks;\n const hooksWithProgress: LlmHooks = {\n ...hooks,\n onRetryableModelError: async (retryContext) => {\n state.retries++;\n await emitProgress({\n event: {\n error:\n retryContext.error instanceof Error\n ? retryContext.error.message\n : String(retryContext.error),\n turn: state.currentTurn,\n type: LlmProgressEventType.Retry,\n },\n onProgress: options.onProgress,\n });\n return hooks?.onRetryableModelError?.(retryContext);\n },\n };\n\n // Execute with retry inside a child llm span (no-op when llmobs disabled).\n // RetryExecutor handles error hooks and throws appropriate errors.\n const { parsed, response, toolCalls } = await withLlmObsSpan(\n {\n kind: \"llm\",\n modelName: options.model ?? this.adapter.defaultModel,\n modelProvider: this.adapter.name,\n name: \"jaypie.llm.model\",\n },\n async () => {\n const response = await retryExecutor.execute(\n (signal) =>\n this.adapter.executeRequest(this.client, providerRequest, signal),\n {\n context: {\n input: state.currentInput,\n model: options.model ?? this.adapter.defaultModel,\n options,\n provider: this.adapter.name,\n providerRequest,\n },\n hooks: hooksWithProgress,\n },\n );\n\n // Parse response\n const parsed = this.adapter.parseResponse(response, options);\n const toolCalls = parsed.hasToolCalls\n ? this.adapter.extractToolCalls(response)\n : [];\n\n // Log only the text or tool calls; the full payload is available\n // via the afterEachModelResponse hook\n log.trace(\"[operate] Model response received\");\n log.trace.var({\n \"operate.response\":\n toolCalls.length > 0\n ? toolCalls.map(({ arguments: args, name }) => ({\n arguments: args,\n name,\n }))\n : parsed.content,\n });\n\n annotateLlmObs({\n inputData: state.currentInput,\n metrics: usageToLlmObsMetrics(\n parsed.usage ? [parsed.usage] : undefined,\n ),\n outputData: parsed.content ?? \"\",\n });\n\n return { parsed, response, toolCalls };\n },\n );\n\n await emitProgress({\n event: {\n content: parsed.content,\n toolCalls: toolCalls.map(({ arguments: args, name }) => ({\n arguments: args,\n name,\n })),\n turn: state.currentTurn,\n type: LlmProgressEventType.ModelResponse,\n usage: parsed.usage ? [parsed.usage] : undefined,\n },\n onProgress: options.onProgress,\n });\n\n // Track usage\n if (parsed.usage) {\n state.responseBuilder.addUsage(parsed.usage);\n }\n\n // Track stop reason for the exchange envelope\n if (parsed.stopReason) {\n state.lastStopReason = parsed.stopReason;\n }\n\n // Add raw response\n\n state.responseBuilder.addResponse(parsed.raw as any);\n\n // Execute afterEachModelResponse hook\n const currentUsage = state.responseBuilder.build().usage;\n await this.hookRunnerInstance.runAfterModelResponse(context.hooks, {\n content: parsed.content ?? \"\",\n input: state.currentInput,\n options,\n providerRequest,\n providerResponse: response,\n usage: currentUsage,\n });\n\n // Check for structured output (Anthropic magic tool pattern)\n if (this.adapter.hasStructuredOutput(response)) {\n const structuredOutput = this.adapter.extractStructuredOutput(response);\n if (structuredOutput) {\n state.responseBuilder.setContent(\n this.applyFormatArrayDefaults(structuredOutput, options),\n );\n state.responseBuilder.complete();\n return false; // Stop loop\n }\n }\n\n // Handle tool calls\n if (parsed.hasToolCalls) {\n if (toolCalls.length > 0 && state.toolkit && state.maxTurns > 1) {\n // Track updated provider request for tool results\n let currentProviderRequest = providerRequest;\n\n // Add all response output items to the request BEFORE processing tool calls\n // This is critical for OpenAI which requires reasoning items to be present\n // when function_call items reference them\n const responseItems = this.adapter.responseToHistoryItems(response);\n this.appendResponseItemsToRequest(\n currentProviderRequest,\n responseItems,\n );\n\n // Process each tool call\n for (const toolCall of toolCalls) {\n state.toolCallNames.push(toolCall.name);\n // Resolved once per call; never throws (undefined when tool has no message)\n const toolMessage = await state.toolkit!.resolveMessage({\n arguments: toolCall.arguments,\n name: toolCall.name,\n });\n try {\n await emitProgress({\n event: {\n tool: {\n arguments: toolCall.arguments,\n message: toolMessage,\n name: toolCall.name,\n },\n turn: state.currentTurn,\n type: LlmProgressEventType.ToolCall,\n },\n onProgress: options.onProgress,\n });\n\n // Execute beforeEachTool hook\n await this.hookRunnerInstance.runBeforeTool(context.hooks, {\n args: toolCall.arguments,\n message: toolMessage,\n toolName: toolCall.name,\n });\n\n // Call the tool inside a child tool span (no-op when disabled)\n log.trace(`[operate] Calling tool - ${toolCall.name}`);\n const result = await withLlmObsSpan(\n { kind: \"tool\", name: toolCall.name },\n async () => {\n const result = await state.toolkit!.call({\n arguments: toolCall.arguments,\n message: toolMessage,\n name: toolCall.name,\n });\n annotateLlmObs({\n inputData: toolCall.arguments,\n metadata: { tool: toolCall.name },\n outputData: result,\n });\n return result;\n },\n );\n\n await emitProgress({\n event: {\n tool: { name: toolCall.name },\n turn: state.currentTurn,\n type: LlmProgressEventType.ToolResult,\n },\n onProgress: options.onProgress,\n });\n\n // Execute afterEachTool hook\n await this.hookRunnerInstance.runAfterTool(context.hooks, {\n args: toolCall.arguments,\n message: toolMessage,\n result,\n toolName: toolCall.name,\n });\n\n // Format result and append to request\n const formattedResult = {\n callId: toolCall.callId,\n output: JSON.stringify(result),\n success: true,\n };\n\n // Reset consecutive error counter on success\n state.consecutiveToolErrors = 0;\n\n // Update provider request with tool result\n currentProviderRequest = this.adapter.appendToolResult(\n currentProviderRequest,\n toolCall,\n formattedResult,\n );\n\n // Sync state from updated request\n this.syncInputFromRequest(state, currentProviderRequest);\n\n // Add tool result to history\n const toolResultFormatted = this.adapter.formatToolResult(\n toolCall,\n formattedResult,\n );\n state.responseBuilder.appendToHistory(\n toolResultFormatted as LlmInputMessage,\n );\n } catch (error) {\n await emitProgress({\n event: {\n error: (error as Error).message,\n tool: { name: toolCall.name },\n turn: state.currentTurn,\n type: LlmProgressEventType.ToolError,\n },\n onProgress: options.onProgress,\n });\n\n // Execute onToolError hook\n await this.hookRunnerInstance.runOnToolError(context.hooks, {\n args: toolCall.arguments,\n error: error as Error,\n message: toolMessage,\n toolName: toolCall.name,\n });\n\n // Set error on response\n const jaypieError = new BadGatewayError();\n const detail = [\n `Error executing function call ${toolCall.name}.`,\n (error as Error).message,\n ].join(\"\\n\");\n state.responseBuilder.setError({\n detail,\n status: jaypieError.status,\n title: ERROR.BAD_FUNCTION_CALL,\n });\n\n // Add error tool_result to history so the tool_use block is not orphaned.\n // Without this, the next turn's request would have a tool_use without a\n // matching tool_result, causing Anthropic API to reject with 400.\n const errorResult: StandardToolResult = {\n callId: toolCall.callId,\n output: JSON.stringify({\n error: (error as Error).message || \"Tool execution failed\",\n }),\n success: false,\n error: (error as Error).message,\n };\n const toolResultFormatted = this.adapter.formatToolResult(\n toolCall,\n errorResult,\n );\n state.responseBuilder.appendToHistory(\n toolResultFormatted as LlmInputMessage,\n );\n\n log.warn(`Error executing function call ${toolCall.name}`);\n log.var({ error });\n\n // Track consecutive errors and stop if threshold reached\n state.consecutiveToolErrors++;\n if (state.consecutiveToolErrors >= MAX_CONSECUTIVE_TOOL_ERRORS) {\n const detail = `Stopped after ${MAX_CONSECUTIVE_TOOL_ERRORS} consecutive tool errors`;\n log.warn(detail);\n state.responseBuilder.setError({\n detail,\n status: 502,\n title: ERROR.BAD_FUNCTION_CALL,\n });\n state.responseBuilder.incomplete();\n return false; // Stop loop\n }\n }\n }\n\n // Check if we've reached max turns\n if (state.currentTurn >= state.maxTurns) {\n const error = new TooManyRequestsError();\n const detail = `Model requested function call but exceeded ${state.maxTurns} turns`;\n log.warn(detail);\n state.responseBuilder.setError({\n detail,\n status: error.status,\n title: error.title,\n });\n state.responseBuilder.incomplete();\n return false; // Stop loop\n }\n\n return true; // Continue to next turn\n }\n }\n\n // Format contract enforcement: the loop is about to complete but the\n // model answered with prose instead of structured output.\n if (state.formattedFormat && typeof parsed.content === \"string\") {\n // First salvage attempt: the text may be the JSON itself (with or\n // without a code fence).\n const salvaged = tryParseJsonObject(parsed.content);\n if (salvaged) {\n state.responseBuilder.setContent(\n this.applyFormatArrayDefaults(salvaged, options),\n );\n state.responseBuilder.complete();\n for (const item of this.adapter.responseToHistoryItems(parsed.raw)) {\n state.responseBuilder.appendToHistory(item);\n }\n return false; // Stop loop\n }\n\n // Corrective turn: for adapters whose structured output rides a tool\n // emulation, take another turn offering only the structured_output tool\n // and demand it be called. Bounded by maxTurns.\n if (\n this.adapter.supportsStructuredOutputRetry &&\n state.currentTurn < state.maxTurns\n ) {\n log.warn(\n `[operate] Model returned text despite format on turn ${state.currentTurn}; retrying with structured_output tool only`,\n );\n for (const item of this.adapter.responseToHistoryItems(parsed.raw)) {\n state.currentInput.push(item);\n state.responseBuilder.appendToHistory(item);\n }\n const corrective: LlmInputMessage = {\n content:\n \"You must provide your final answer by calling the structured_output tool \" +\n \"with arguments matching the required schema. Do not respond with text.\",\n role: LlmMessageRole.User,\n type: LlmMessageType.Message,\n };\n state.currentInput.push(corrective);\n state.responseBuilder.appendToHistory(corrective);\n state.structuredOutputRetry = true;\n return true; // Continue to corrective turn\n }\n }\n\n // No tool calls or no toolkit - we're done\n state.responseBuilder.setContent(\n this.applyFormatArrayDefaults(parsed.content, options),\n );\n state.responseBuilder.complete();\n\n // Add final history items\n const historyItems = this.adapter.responseToHistoryItems(parsed.raw);\n for (const item of historyItems) {\n state.responseBuilder.appendToHistory(item);\n }\n\n return false; // Stop loop\n }\n\n /**\n * Draconian summary of a history item for trace logging: string message\n * content is kept; everything else is reduced to its type.\n */\n private summarizeHistoryItem(item?: LlmHistoryItem): unknown {\n if (!item) {\n return undefined;\n }\n const record = item as unknown as Record<string, unknown>;\n if (typeof record.content === \"string\") {\n return { content: record.content, role: record.role };\n }\n return { type: record.type ?? \"message\" };\n }\n\n /**\n * Reconcile structured output against the declared `format` contract. A\n * declared `format` is a schema contract: returned keys should match the\n * declared names exactly and every declared array field should be present.\n * First repairs keys a provider/model corrupted by wrapping them in literal\n * double quotes (observed on OpenAI for multi-word keys), then backfills any\n * declared array field a provider/model omitted, surfacing it as `[]`.\n */\n private applyFormatArrayDefaults(\n content: string | JsonObject | undefined,\n options: LlmOperateOptions,\n ): string | JsonObject | undefined {\n if (!options.format) {\n return content;\n }\n if (typeof content !== \"object\" || content === null) {\n return content;\n }\n const repaired = repairFormatKeys({ content, format: options.format });\n return fillFormatArrays({ content: repaired, format: options.format });\n }\n\n /**\n * Sync the current input state from the updated provider request.\n * This is necessary because appendToolResult modifies the provider-specific request,\n * and we need to keep our state in sync.\n */\n private syncInputFromRequest(\n state: OperateLoopState,\n updatedRequest: unknown,\n ): void {\n // Extract input/messages from the updated request\n // This is provider-specific but follows common patterns\n const request = updatedRequest as Record<string, unknown>;\n\n if (Array.isArray(request.input)) {\n // OpenAI format\n state.currentInput = request.input as LlmHistory;\n } else if (Array.isArray(request.messages)) {\n // Anthropic format\n state.currentInput = request.messages as LlmHistory;\n } else if (Array.isArray(request.contents)) {\n // Gemini format - convert contents to history items\n state.currentInput = this.convertGeminiContentsToHistory(\n request.contents as Array<{\n role: string;\n parts?: Array<Record<string, unknown>>;\n }>,\n );\n }\n }\n\n /**\n * Convert Gemini contents format to internal history format.\n */\n private convertGeminiContentsToHistory(\n contents: Array<{ role: string; parts?: Array<Record<string, unknown>> }>,\n ): LlmHistory {\n const history: LlmHistory = [];\n\n for (const content of contents) {\n if (!content.parts) continue;\n\n for (const part of content.parts) {\n if (part.text && typeof part.text === \"string\") {\n // Regular text message\n history.push({\n role:\n content.role === \"model\"\n ? LlmMessageRole.Assistant\n : LlmMessageRole.User,\n content: part.text,\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n } else if (part.functionCall) {\n // Function call\n const fc = part.functionCall as {\n name?: string;\n args?: Record<string, unknown>;\n id?: string;\n };\n // Preserve thoughtSignature for Gemini 3 models (required for tool calls)\n const thoughtSignature = (part as { thoughtSignature?: string })\n .thoughtSignature;\n history.push({\n type: LlmMessageType.FunctionCall,\n name: fc.name || \"\",\n arguments: JSON.stringify(fc.args || {}),\n call_id: fc.id || \"\",\n id: fc.id || \"\",\n ...(thoughtSignature && { thoughtSignature }),\n } as unknown as LlmToolCall);\n } else if (part.functionResponse) {\n // Function response\n const fr = part.functionResponse as {\n name?: string;\n response?: Record<string, unknown>;\n };\n // Store name in the object even though it's not part of LlmToolResult type\n // This allows round-trip conversion back to Gemini format\n history.push({\n type: LlmMessageType.FunctionCallOutput,\n output: JSON.stringify(fr.response || {}),\n call_id: \"\",\n name: fr.name || \"\",\n } as LlmToolResult & { name: string });\n }\n }\n }\n\n return history;\n }\n\n /**\n * Append response items to the provider request.\n * This adds all output items from a response (including reasoning, function_calls, etc.)\n * to the request's input/messages array.\n *\n * This is critical for OpenAI which requires reasoning items to be present\n * when function_call items reference them.\n */\n private appendResponseItemsToRequest(\n request: unknown,\n responseItems: LlmHistory,\n ): void {\n const requestObj = request as Record<string, unknown>;\n\n if (Array.isArray(requestObj.input)) {\n // OpenAI format\n requestObj.input.push(...responseItems);\n } else if (Array.isArray(requestObj.messages)) {\n // Anthropic format\n requestObj.messages.push(...responseItems);\n }\n }\n}\n\n//\n//\n// Factory\n//\n\n/**\n * Create an OperateLoop instance with the specified configuration.\n */\nexport function createOperateLoop(config: OperateLoopConfig): OperateLoop {\n return new OperateLoop(config);\n}\n","import { BadGatewayError, TooManyRequestsError } from \"@jaypie/errors\";\nimport { sleep } from \"@jaypie/kit\";\nimport { JsonObject } from \"@jaypie/types\";\n\nimport { MAX_CONSECUTIVE_TOOL_ERRORS } from \"./OperateLoop.js\";\nimport { toLlmError } from \"../errors/toLlmError.js\";\nimport { createStaleRejectionGuard } from \"./retry/createStaleRejectionGuard.js\";\nimport { Toolkit } from \"../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateInput,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmToolCall,\n LlmToolResult,\n LlmUsageItem,\n} from \"../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../types/LlmStreamChunk.interface.js\";\nimport {\n annotateLlmObs,\n openLlmObsSpan,\n usageToLlmObsMetrics,\n withLlmObsSpan,\n} from \"../observability/llmobs.js\";\nimport { getLogger, maxTurnsFromOptions, tallyOperate } from \"../util/index.js\";\nimport { ProviderAdapter } from \"./adapters/ProviderAdapter.interface.js\";\nimport { HookRunner, hookRunner } from \"./hooks/index.js\";\nimport { InputProcessor, inputProcessor } from \"./input/index.js\";\nimport { defaultRetryPolicy, RetryPolicy } from \"./retry/index.js\";\nimport {\n OperateContext,\n OperateRequest,\n ProviderToolDefinition,\n StandardToolCall,\n} from \"./types.js\";\n\n//\n//\n// Types\n//\n\nexport interface StreamLoopConfig {\n adapter: ProviderAdapter;\n client: unknown;\n hookRunner?: HookRunner;\n inputProcessor?: InputProcessor;\n retryPolicy?: RetryPolicy;\n}\n\ninterface StreamLoopState {\n consecutiveToolErrors: number;\n currentInput: LlmHistory;\n currentTurn: number;\n formattedFormat?: JsonObject;\n formattedTools?: ProviderToolDefinition[];\n maxTurns: number;\n toolCallNames: string[];\n toolkit?: Toolkit;\n usageItems: LlmUsageItem[];\n}\n\n//\n//\n// Constants\n//\n\nconst ERROR = {\n BAD_FUNCTION_CALL: \"Bad Function Call\",\n};\n\n//\n//\n// Main\n//\n\n/**\n * StreamLoop implements streaming multi-turn conversation loop.\n * It orchestrates provider adapters and tool calling while yielding\n * stream chunks as they become available.\n */\nexport class StreamLoop {\n private readonly adapter: ProviderAdapter;\n private readonly client: unknown;\n private readonly hookRunnerInstance: HookRunner;\n private readonly inputProcessorInstance: InputProcessor;\n private readonly retryPolicy: RetryPolicy;\n\n constructor(config: StreamLoopConfig) {\n this.adapter = config.adapter;\n this.client = config.client;\n this.hookRunnerInstance = config.hookRunner ?? hookRunner;\n this.inputProcessorInstance = config.inputProcessor ?? inputProcessor;\n this.retryPolicy = config.retryPolicy ?? defaultRetryPolicy;\n }\n\n /**\n * Execute the streaming loop for multi-turn conversations with tool calling.\n * Yields stream chunks as they become available.\n */\n async *execute(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const log = getLogger();\n // Verify adapter supports streaming\n if (!this.adapter.executeStreamRequest) {\n throw new BadGatewayError(\n `Provider ${this.adapter.name} does not support streaming`,\n );\n }\n\n // Initialize state\n const state = await this.initializeState(input, options);\n const context = this.createContext(options);\n\n // Build initial request\n let request = this.buildInitialRequest(state, options);\n\n // Multi-turn loop\n while (state.currentTurn < state.maxTurns) {\n state.currentTurn++;\n\n // Execute one streaming turn\n const { shouldContinue, toolCalls } = yield* this.executeOneStreamingTurn(\n request,\n state,\n context,\n options,\n );\n\n if (!shouldContinue) {\n break;\n }\n\n // If we have tool calls, process them\n if (toolCalls && toolCalls.length > 0 && state.toolkit) {\n yield* this.processToolCalls(toolCalls, state, context);\n\n // Check if we've reached max turns\n if (state.currentTurn >= state.maxTurns) {\n const error = new TooManyRequestsError();\n const detail = `Model requested function call but exceeded ${state.maxTurns} turns`;\n log.warn(detail);\n yield {\n type: LlmStreamChunkType.Error,\n error: {\n detail,\n status: error.status,\n title: error.title,\n },\n };\n break;\n }\n\n // Rebuild request with updated history for next turn\n request = {\n effort: options.effort,\n format: state.formattedFormat,\n instructions: options.instructions,\n messages: state.currentInput,\n model: options.model ?? this.adapter.defaultModel,\n providerOptions: options.providerOptions,\n stream: true,\n system: options.system,\n temperature: options.temperature,\n tools: state.formattedTools,\n user: options.user,\n };\n } else {\n break;\n }\n }\n\n // Emit final done chunk with accumulated usage\n tallyOperate({\n toolCallNames: state.toolCallNames,\n turns: state.currentTurn,\n usage: state.usageItems,\n });\n yield {\n type: LlmStreamChunkType.Done,\n usage: state.usageItems,\n };\n }\n\n //\n // Private Methods\n //\n\n private async initializeState(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions,\n ): Promise<StreamLoopState> {\n // Process input with placeholders\n const processedInput = await this.inputProcessorInstance.process(\n input,\n options,\n );\n\n // Determine max turns\n const maxTurns = maxTurnsFromOptions(options);\n\n // Get toolkit\n let toolkit: Toolkit | undefined;\n if (options.tools) {\n if (options.tools instanceof Toolkit) {\n toolkit = options.tools;\n } else if (Array.isArray(options.tools) && options.tools.length > 0) {\n const explain = options.explain ?? false;\n toolkit = new Toolkit(options.tools, { explain });\n }\n }\n\n // Format output schema through adapter if provided\n let formattedFormat: JsonObject | undefined;\n if (options.format) {\n formattedFormat = this.adapter.formatOutputSchema(\n options.format,\n ) as JsonObject;\n }\n\n // Format tools through adapter\n const formattedTools = toolkit\n ? this.adapter.formatTools(toolkit, formattedFormat)\n : undefined;\n\n return {\n consecutiveToolErrors: 0,\n currentInput: processedInput.history,\n currentTurn: 0,\n formattedFormat,\n formattedTools,\n maxTurns,\n toolCallNames: [],\n toolkit,\n usageItems: [],\n };\n }\n\n private createContext(options: LlmOperateOptions): OperateContext {\n return {\n hooks: options.hooks ?? {},\n options,\n };\n }\n\n private buildInitialRequest(\n state: StreamLoopState,\n options: LlmOperateOptions,\n ): OperateRequest {\n return {\n cache: options.cache,\n effort: options.effort,\n format: state.formattedFormat,\n instructions: options.instructions,\n messages: state.currentInput,\n model: options.model ?? this.adapter.defaultModel,\n providerOptions: options.providerOptions,\n stream: true,\n system: options.system,\n temperature: options.temperature,\n tools: state.formattedTools,\n user: options.user,\n };\n }\n\n private async *executeOneStreamingTurn(\n request: OperateRequest,\n state: StreamLoopState,\n context: OperateContext,\n options: LlmOperateOptions,\n ): AsyncGenerator<\n LlmStreamChunk,\n { shouldContinue: boolean; toolCalls?: StandardToolCall[] }\n > {\n const log = getLogger();\n // Build provider-specific request\n const providerRequest = this.adapter.buildRequest(request);\n\n // Execute beforeEachModelRequest hook\n await this.hookRunnerInstance.runBeforeModelRequest(context.hooks, {\n input: state.currentInput,\n options,\n providerRequest,\n });\n\n // Open a manual llm span held open across the streamed turn. Flat (not\n // nested) because it spans yield boundaries; no-op when llmobs disabled.\n const llmSpan = openLlmObsSpan({\n kind: \"llm\",\n modelName: options.model ?? this.adapter.defaultModel,\n modelProvider: this.adapter.name,\n name: \"jaypie.llm.model\",\n });\n const inputSnapshot = [...state.currentInput];\n let streamedText = \"\";\n\n // Collect tool calls from the stream\n const collectedToolCalls: StandardToolCall[] = [];\n\n // Retry loop for connection-level failures\n let attempt = 0;\n let chunksYielded = false;\n\n // Guard against stale rejections firing after the stream loop has already\n // caught the originating error: undici socket teardown and twin\n // upstream-SDK rejections (issue #336).\n const guard = createStaleRejectionGuard();\n\n try {\n while (true) {\n const controller = new AbortController();\n\n try {\n // Execute streaming request\n const streamGenerator = this.adapter.executeStreamRequest!(\n this.client,\n providerRequest,\n controller.signal,\n );\n\n for await (const chunk of streamGenerator) {\n // Pass through text chunks\n if (chunk.type === LlmStreamChunkType.Text) {\n chunksYielded = true;\n streamedText += chunk.content ?? \"\";\n yield chunk;\n }\n\n // Collect tool calls\n if (chunk.type === LlmStreamChunkType.ToolCall) {\n chunksYielded = true;\n collectedToolCalls.push({\n callId: chunk.toolCall.id,\n name: chunk.toolCall.name,\n arguments: chunk.toolCall.arguments,\n raw: chunk.toolCall,\n });\n yield chunk;\n }\n\n // Track usage from done chunk (but don't yield it yet - we'll emit our own)\n if (chunk.type === LlmStreamChunkType.Done && chunk.usage) {\n state.usageItems.push(...chunk.usage);\n }\n\n // Pass through error chunks\n if (chunk.type === LlmStreamChunkType.Error) {\n chunksYielded = true;\n yield chunk;\n }\n }\n\n // Stream completed successfully\n if (attempt > 0) {\n log.debug(`Stream request succeeded after ${attempt} retries`);\n }\n break;\n } catch (error: unknown) {\n controller.abort(\"retry\");\n\n guard.recordCaught(error);\n guard.install();\n\n // If chunks were already yielded, we can't transparently retry\n if (chunksYielded) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n log.error(\"Stream failed after partial data was delivered\");\n log.var({ error });\n yield {\n type: LlmStreamChunkType.Error,\n error: {\n detail: errorMessage,\n status: 502,\n title: \"Stream Error\",\n },\n };\n llmSpan?.annotate({\n inputData: inputSnapshot,\n metrics: usageToLlmObsMetrics(state.usageItems),\n outputData: streamedText,\n });\n llmSpan?.finish();\n return { shouldContinue: false };\n }\n\n // Check if we've exhausted retries or error is not retryable\n if (\n !this.retryPolicy.shouldRetry(attempt) ||\n !this.adapter.isRetryableError(error)\n ) {\n log.error(\n `Stream request failed after ${this.retryPolicy.maxRetries} retries`,\n );\n log.var({ error });\n llmSpan?.finish();\n throw toLlmError(this.adapter.classifyError(error), {\n model: options.model ?? this.adapter.defaultModel,\n provider: this.adapter.name,\n });\n }\n\n const delay = this.retryPolicy.getDelayForAttempt(attempt);\n log.warn(`Stream request failed. Retrying in ${delay}ms...`);\n log.var({ error });\n\n await sleep(delay);\n attempt++;\n }\n }\n } finally {\n guard.remove();\n }\n\n // Annotate and finish the streamed llm span (no-op when disabled)\n llmSpan?.annotate({\n inputData: inputSnapshot,\n metrics: usageToLlmObsMetrics(state.usageItems),\n outputData: streamedText,\n });\n llmSpan?.finish();\n\n // Execute afterEachModelResponse hook\n await this.hookRunnerInstance.runAfterModelResponse(context.hooks, {\n content: \"\",\n input: state.currentInput,\n options,\n providerRequest,\n providerResponse: null,\n usage: state.usageItems,\n });\n\n // If we have tool calls and a toolkit, continue the loop\n if (collectedToolCalls.length > 0 && state.toolkit && state.maxTurns > 1) {\n // Add tool calls to history\n for (const toolCall of collectedToolCalls) {\n // Extract provider-specific metadata from the stream chunk\n const metadata = (toolCall.raw as Record<string, unknown>)?.metadata as\n Record<string, unknown> | undefined;\n\n const historyItem: Record<string, unknown> = {\n type: LlmMessageType.FunctionCall,\n name: toolCall.name,\n arguments: toolCall.arguments,\n call_id: toolCall.callId,\n // Use provider item ID if available (e.g., OpenAI fc_... prefix),\n // otherwise fall back to callId\n id: (metadata?.itemId as string) || toolCall.callId,\n };\n\n // Preserve provider-specific fields (e.g., Gemini thoughtSignature)\n if (metadata?.thoughtSignature) {\n historyItem.thoughtSignature = metadata.thoughtSignature;\n }\n\n state.currentInput.push(historyItem as unknown as LlmToolCall);\n }\n\n return { shouldContinue: true, toolCalls: collectedToolCalls };\n }\n\n return { shouldContinue: false };\n }\n\n private async *processToolCalls(\n toolCalls: StandardToolCall[],\n state: StreamLoopState,\n context: OperateContext,\n ): AsyncGenerator<LlmStreamChunk, void> {\n const log = getLogger();\n for (const toolCall of toolCalls) {\n state.toolCallNames.push(toolCall.name);\n // Resolved once per call; never throws (undefined when tool has no message)\n const toolMessage = await state.toolkit!.resolveMessage({\n arguments: toolCall.arguments,\n name: toolCall.name,\n });\n try {\n // Execute beforeEachTool hook\n await this.hookRunnerInstance.runBeforeTool(context.hooks, {\n args: toolCall.arguments,\n message: toolMessage,\n toolName: toolCall.name,\n });\n\n // Call the tool inside a child tool span (no-op when disabled)\n log.trace(`[stream] Calling tool - ${toolCall.name}`);\n const result = await withLlmObsSpan(\n { kind: \"tool\", name: toolCall.name },\n async () => {\n const result = await state.toolkit!.call({\n arguments: toolCall.arguments,\n message: toolMessage,\n name: toolCall.name,\n });\n annotateLlmObs({\n inputData: toolCall.arguments,\n metadata: { tool: toolCall.name },\n outputData: result,\n });\n return result;\n },\n );\n\n // Execute afterEachTool hook\n await this.hookRunnerInstance.runAfterTool(context.hooks, {\n args: toolCall.arguments,\n message: toolMessage,\n result,\n toolName: toolCall.name,\n });\n\n // Reset consecutive error counter on success\n state.consecutiveToolErrors = 0;\n\n // Yield tool result chunk\n yield {\n type: LlmStreamChunkType.ToolResult,\n toolResult: {\n id: toolCall.callId,\n name: toolCall.name,\n result,\n },\n };\n\n // Add tool result to history\n state.currentInput.push({\n type: LlmMessageType.FunctionCallOutput,\n output: JSON.stringify(result),\n call_id: toolCall.callId,\n name: toolCall.name,\n } as LlmToolResult & { name: string });\n } catch (error) {\n // Execute onToolError hook\n await this.hookRunnerInstance.runOnToolError(context.hooks, {\n args: toolCall.arguments,\n error: error as Error,\n message: toolMessage,\n toolName: toolCall.name,\n });\n\n // Yield error chunk\n const jaypieError = new BadGatewayError();\n const detail = [\n `Error executing function call ${toolCall.name}.`,\n (error as Error).message,\n ].join(\"\\n\");\n\n yield {\n type: LlmStreamChunkType.Error,\n error: {\n detail,\n status: jaypieError.status,\n title: ERROR.BAD_FUNCTION_CALL,\n },\n };\n\n // Add error tool_result to history so the tool_use block is not orphaned.\n // Without this, the next turn's request would have a tool_use without a\n // matching tool_result, causing Anthropic API to reject with 400.\n const errorOutput = JSON.stringify({\n error: (error as Error).message || \"Tool execution failed\",\n });\n state.currentInput.push({\n type: LlmMessageType.FunctionCallOutput,\n output: errorOutput,\n call_id: toolCall.callId,\n name: toolCall.name,\n } as LlmToolResult & { name: string });\n\n log.warn(`Error executing function call ${toolCall.name}`);\n log.var({ error });\n\n // Track consecutive errors and stop if threshold reached\n state.consecutiveToolErrors++;\n if (state.consecutiveToolErrors >= MAX_CONSECUTIVE_TOOL_ERRORS) {\n const stopDetail = `Stopped after ${MAX_CONSECUTIVE_TOOL_ERRORS} consecutive tool errors`;\n log.warn(stopDetail);\n yield {\n type: LlmStreamChunkType.Error,\n error: {\n detail: stopDetail,\n status: 502,\n title: ERROR.BAD_FUNCTION_CALL,\n },\n };\n return; // Stop processing tools\n }\n }\n }\n }\n\n /**\n * Convert Gemini contents format to internal history format.\n */\n private convertGeminiContentsToHistory(\n contents: Array<{ role: string; parts?: Array<Record<string, unknown>> }>,\n ): LlmHistory {\n const history: LlmHistory = [];\n\n for (const content of contents) {\n if (!content.parts) continue;\n\n for (const part of content.parts) {\n if (part.text && typeof part.text === \"string\") {\n history.push({\n role:\n content.role === \"model\"\n ? LlmMessageRole.Assistant\n : LlmMessageRole.User,\n content: part.text,\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n } else if (part.functionCall) {\n const fc = part.functionCall as {\n name?: string;\n args?: Record<string, unknown>;\n id?: string;\n };\n history.push({\n type: LlmMessageType.FunctionCall,\n name: fc.name || \"\",\n arguments: JSON.stringify(fc.args || {}),\n call_id: fc.id || \"\",\n id: fc.id || \"\",\n } as unknown as LlmToolCall);\n } else if (part.functionResponse) {\n const fr = part.functionResponse as {\n name?: string;\n response?: Record<string, unknown>;\n };\n history.push({\n type: LlmMessageType.FunctionCallOutput,\n output: JSON.stringify(fr.response || {}),\n call_id: \"\",\n name: fr.name || \"\",\n } as LlmToolResult & { name: string });\n }\n }\n }\n\n return history;\n }\n}\n\n//\n//\n// Factory\n//\n\n/**\n * Create a StreamLoop instance with the specified configuration.\n */\nexport function createStreamLoop(config: StreamLoopConfig): StreamLoop {\n return new StreamLoop(config);\n}\n","import { parseSseStream } from \"../../util/sse.js\";\nimport { Anthropic } from \"./types.js\";\n\n//\n//\n// Constants\n//\n\nconst ANTHROPIC_BASE_URL = \"https://api.anthropic.com/v1\";\n\nconst ANTHROPIC_VERSION = \"2023-06-01\";\n\n//\n//\n// Errors\n//\n// The adapter's `classifyError` keys off `error.constructor.name` (the SDK's\n// class names), so the client throws errors whose class names match. Status →\n// class mapping mirrors the SDK.\n//\n\nexport class AnthropicApiError extends Error {\n readonly status: number;\n readonly error?: { message?: string };\n\n constructor(status: number, message: string, error?: { message?: string }) {\n super(message);\n this.name = this.constructor.name;\n this.status = status;\n this.error = error;\n }\n}\n\nexport class BadRequestError extends AnthropicApiError {}\nexport class AuthenticationError extends AnthropicApiError {}\nexport class PermissionDeniedError extends AnthropicApiError {}\nexport class NotFoundError extends AnthropicApiError {}\nexport class RateLimitError extends AnthropicApiError {}\nexport class InternalServerError extends AnthropicApiError {}\nexport class APIConnectionError extends AnthropicApiError {}\n\nfunction errorForStatus(\n status: number,\n message: string,\n error?: { message?: string },\n): AnthropicApiError {\n if (status === 400) return new BadRequestError(status, message, error);\n if (status === 401) return new AuthenticationError(status, message, error);\n if (status === 403) return new PermissionDeniedError(status, message, error);\n if (status === 404) return new NotFoundError(status, message, error);\n if (status === 429) return new RateLimitError(status, message, error);\n if (status >= 500) return new InternalServerError(status, message, error);\n return new AnthropicApiError(status, message, error);\n}\n\n//\n//\n// Types\n//\n\nexport interface AnthropicClientOptions {\n apiKey: string;\n baseURL?: string;\n}\n\nexport interface CreateOptions {\n signal?: AbortSignal;\n}\n\ninterface MessagesApi {\n create(\n params: Anthropic.MessageCreateParamsStreaming,\n options?: CreateOptions,\n ): Promise<AsyncIterable<Anthropic.MessageStreamEvent>>;\n create(\n params: Anthropic.MessageCreateParams,\n options?: CreateOptions,\n ): Promise<Anthropic.Message>;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Minimal `fetch`-based client for Anthropic's Messages API. Replaces\n * `@anthropic-ai/sdk` — the adapter only needs `messages.create` (streaming and\n * non-streaming), header auth, and HTTP errors whose class names drive\n * `classifyError`. Internal request params are already Anthropic's wire shape,\n * so they serialize verbatim. Exposes a `messages` facade mirroring the SDK so\n * the adapter call sites are unchanged.\n */\nexport class AnthropicClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n readonly messages: MessagesApi;\n\n constructor({\n apiKey,\n baseURL = ANTHROPIC_BASE_URL,\n }: AnthropicClientOptions) {\n this.apiKey = apiKey;\n this.baseURL = baseURL;\n this.messages = {\n create: ((\n params: Anthropic.MessageCreateParams,\n options?: CreateOptions,\n ) =>\n params.stream\n ? this.createStream(params, options)\n : this.createMessage(params, options)) as MessagesApi[\"create\"],\n };\n }\n\n private headers(): Record<string, string> {\n return {\n \"anthropic-version\": ANTHROPIC_VERSION,\n \"content-type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n };\n }\n\n private async toError(response: Response): Promise<AnthropicApiError> {\n let message = `Anthropic request failed with status ${response.status}`;\n let error: { message?: string } | undefined;\n try {\n const body = (await response.json()) as { error?: { message?: string } };\n if (body?.error?.message) {\n message = body.error.message;\n error = body.error;\n }\n } catch {\n // Non-JSON error body; keep the status-based message.\n }\n return errorForStatus(response.status, message, error);\n }\n\n private async createMessage(\n params: Anthropic.MessageCreateParams,\n { signal }: CreateOptions = {},\n ): Promise<Anthropic.Message> {\n const response = await fetch(`${this.baseURL}/messages`, {\n method: \"POST\",\n headers: this.headers(),\n body: JSON.stringify(params),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n return (await response.json()) as Anthropic.Message;\n }\n\n private async createStream(\n params: Anthropic.MessageCreateParams,\n { signal }: CreateOptions = {},\n ): Promise<AsyncIterable<Anthropic.MessageStreamEvent>> {\n const response = await fetch(`${this.baseURL}/messages`, {\n method: \"POST\",\n headers: { ...this.headers(), accept: \"text/event-stream\" },\n body: JSON.stringify(params),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n if (!response.body) return (async function* () {})();\n\n return parseSseStream(\n response.body,\n ) as AsyncIterable<Anthropic.MessageStreamEvent>;\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog, log } from \"@jaypie/logger\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { naturalZodSchema } from \"../../util/index.js\";\nimport { z } from \"zod/v4\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { AnthropicClient } from \"./client.js\";\nimport type { Anthropic } from \"./types.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<AnthropicClient> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"ANTHROPIC_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the required API key: ANTHROPIC_API_KEY\",\n );\n }\n\n const client = new AnthropicClient({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized Anthropic client\");\n return client;\n}\n\n// Message formatting functions\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): string {\n return placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): Anthropic.MessageParam {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: PROVIDER.ANTHROPIC.ROLE.USER,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { data, placeholders }: LlmMessageOptions = {},\n): Anthropic.MessageParam[] {\n const logger = getLogger();\n const messages: Anthropic.MessageParam[] = [];\n\n // Add user message (necessary for all requests)\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content.length} characters`);\n\n return messages;\n}\n\n// Basic text completion\nexport async function createTextCompletion(\n client: AnthropicClient,\n messages: Anthropic.MessageParam[],\n model: string,\n systemMessage?: string,\n): Promise<string> {\n log.trace(\"Using text output (unstructured)\");\n\n const params: Anthropic.MessageCreateParams = {\n model,\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n };\n\n // Add system instruction if provided\n if (systemMessage) {\n params.system = systemMessage;\n log.trace(`System message: ${systemMessage.length} characters`);\n }\n\n const response = await client.messages.create(params);\n\n const firstContent = response.content[0];\n const text = firstContent && \"text\" in firstContent ? firstContent.text : \"\";\n\n log.trace(`Assistant reply: ${text.length} characters`);\n\n return text;\n}\n\n// Structured output completion using Anthropic's native `output_config.format`\n// field. Returns a JsonObject parsed and validated against the caller's\n// Zod schema.\nexport async function createStructuredCompletion(\n client: AnthropicClient,\n messages: Anthropic.MessageParam[],\n model: string,\n responseSchema: z.ZodType | NaturalSchema,\n systemMessage?: string,\n): Promise<JsonObject> {\n log.trace(\"Using native structured output\");\n\n const schema =\n responseSchema instanceof z.ZodType\n ? responseSchema\n : naturalZodSchema(responseSchema as NaturalSchema);\n\n // Type extension: SDK 0.71 doesn't type `output_config` on\n // `MessageCreateParams`. The GA endpoint accepts the field; the older\n // `output_format` field is now deprecated.\n type StructuredOutputParams = Anthropic.MessageCreateParams & {\n output_config?: {\n format: {\n type: \"json_schema\";\n schema: JsonObject;\n };\n };\n };\n\n const jsonSchema = z.toJSONSchema(schema) as JsonObject;\n const params: StructuredOutputParams = {\n model,\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n output_config: {\n format: { type: \"json_schema\", schema: jsonSchema },\n },\n };\n if (systemMessage) {\n params.system = systemMessage;\n }\n\n const response = (await client.messages.create(\n params as Anthropic.MessageCreateParams,\n )) as Anthropic.Message;\n\n if (response.stop_reason === \"refusal\") {\n throw new Error(\n \"Anthropic refused the structured-output request (stop_reason=refusal)\",\n );\n }\n if (response.stop_reason === \"max_tokens\") {\n throw new Error(\n \"Anthropic structured-output response was truncated (stop_reason=max_tokens); increase max_tokens\",\n );\n }\n\n const textBlock = response.content.find(\n (block): block is Anthropic.TextBlock => block.type === \"text\",\n );\n if (!textBlock) {\n throw new Error(\"Failed to parse structured response from Anthropic\");\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(textBlock.text);\n } catch {\n throw new Error(\n \"Failed to parse structured response from Anthropic: \" + textBlock.text,\n );\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n throw new Error(\n `JSON response from Anthropic does not match schema: ${textBlock.text}`,\n );\n }\n log.trace(\"Received structured response\", { result: validation.data });\n return validation.data as JsonObject;\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { LlmMessageRole } from \"../../types/LlmProvider.interface.js\";\nimport { PROVIDER } from \"../../constants.js\";\n\n// Maps Jaypie roles to Anthropic roles\nexport const ROLE_MAP: Record<LlmMessageRole, string> = {\n [LlmMessageRole.User]: PROVIDER.ANTHROPIC.ROLE.USER,\n [LlmMessageRole.System]: PROVIDER.ANTHROPIC.ROLE.SYSTEM,\n [LlmMessageRole.Assistant]: PROVIDER.ANTHROPIC.ROLE.ASSISTANT,\n [LlmMessageRole.Developer]: PROVIDER.ANTHROPIC.ROLE.SYSTEM,\n};\n\n//\n//\n// Anthropic API types\n//\n// Local mirror of the subset of `@anthropic-ai/sdk`'s `Anthropic` namespace the\n// adapter and utils use. Defining it here lets us drop the SDK dependency while\n// keeping every `Anthropic.X` reference unchanged. The internal request shapes\n// are already Anthropic's snake_case wire format, so the HTTP client serializes\n// them verbatim.\n//\n\n/* eslint-disable @typescript-eslint/no-namespace */\nexport namespace Anthropic {\n export interface CacheControlEphemeral {\n type: \"ephemeral\";\n ttl?: \"5m\" | \"1h\";\n }\n\n export interface TextBlock {\n type: \"text\";\n text: string;\n }\n\n /** Top-level `system` block form that can carry a cache breakpoint */\n export interface SystemTextBlockParam {\n type: \"text\";\n text: string;\n cache_control?: CacheControlEphemeral;\n }\n\n export interface ToolUseBlock {\n type: \"tool_use\";\n id: string;\n name: string;\n input: unknown;\n }\n\n export interface ThinkingBlock {\n type: \"thinking\";\n thinking: string;\n signature?: string;\n }\n\n export type ContentBlock = TextBlock | ToolUseBlock | ThinkingBlock;\n\n export interface Base64ImageSource {\n type: \"base64\";\n media_type: string;\n data: string;\n }\n\n export interface Base64PDFSource {\n type: \"base64\";\n media_type: string;\n data: string;\n }\n\n export interface ToolResultBlockParam {\n type: \"tool_result\";\n tool_use_id: string;\n content: string;\n }\n\n export type ContentBlockParam =\n | { type: \"text\"; text: string }\n | {\n type: \"image\";\n source: Base64ImageSource | { type: \"url\"; url: string };\n }\n | {\n type: \"document\";\n source: Base64PDFSource | { type: \"url\"; url: string };\n }\n | ToolUseBlock\n | ToolResultBlockParam;\n\n export interface MessageParam {\n role: \"user\" | \"assistant\";\n content: string | ContentBlockParam[];\n }\n\n export namespace Messages {\n export namespace Tool {\n export type InputSchema = JsonObject;\n }\n }\n\n export interface Tool {\n name: string;\n description?: string;\n input_schema: Messages.Tool.InputSchema;\n type?: \"custom\";\n cache_control?: CacheControlEphemeral;\n }\n\n export interface Usage {\n input_tokens: number;\n output_tokens: number;\n thinking_tokens?: number;\n cache_read_input_tokens?: number;\n cache_creation_input_tokens?: number;\n }\n\n export interface MessageCreateParams {\n model: string;\n messages: MessageParam[];\n max_tokens: number;\n system?: string | SystemTextBlockParam[];\n tools?: Tool[];\n tool_choice?: { type: \"auto\" | \"any\" | \"tool\"; name?: string };\n temperature?: number;\n stream?: boolean;\n // Allow `output_config` and arbitrary providerOptions passthrough.\n [key: string]: unknown;\n }\n\n export type MessageCreateParamsStreaming = MessageCreateParams & {\n stream: true;\n };\n\n export interface Message {\n id: string;\n type: \"message\";\n role: \"assistant\";\n model: string;\n content: ContentBlock[];\n stop_reason: string | null;\n stop_sequence?: string | null;\n usage: Usage;\n }\n\n export type ContentBlockDelta =\n | { type: \"text_delta\"; text: string }\n | { type: \"input_json_delta\"; partial_json: string };\n\n export type MessageStreamEvent =\n | { type: \"message_start\"; message: Message }\n | {\n type: \"content_block_start\";\n index: number;\n content_block: ContentBlock;\n }\n | { type: \"content_block_delta\"; index: number; delta: ContentBlockDelta }\n | { type: \"content_block_stop\"; index: number }\n | { type: \"message_delta\"; delta: Record<string, unknown>; usage: Usage }\n | { type: \"message_stop\" }\n | { type: \"ping\" };\n}\n/* eslint-enable @typescript-eslint/no-namespace */\n","import type { AnthropicClient } from \"./client.js\";\nimport { JsonObject } from \"@jaypie/types\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n anthropicAdapter,\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n createStructuredCompletion,\n createTextCompletion,\n formatSystemMessage,\n getLogger,\n initializeClient,\n prepareMessages,\n} from \"./index.js\";\n\n// Main class implementation\nexport class AnthropicProvider implements LlmProvider {\n private model: string;\n private _client?: AnthropicClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.ANTHROPIC.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<AnthropicClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: anthropicAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: anthropicAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n // Main send method\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options || {});\n const modelToUse = options?.model || this.model;\n\n // Process system message if provided\n let systemMessage: string | undefined;\n if (options?.system) {\n systemMessage = formatSystemMessage(options.system, {\n data: options.data,\n placeholders: options.placeholders,\n });\n }\n\n if (options?.response) {\n return createStructuredCompletion(\n client,\n messages,\n modelToUse,\n options.response,\n systemMessage,\n );\n }\n\n return createTextCompletion(client, messages, modelToUse, systemMessage);\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { JAYPIE } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport type { BedrockRuntimeClient } from \"@aws-sdk/client-bedrock-runtime\";\n\nlet cachedSdk: typeof import(\"@aws-sdk/client-bedrock-runtime\") | null = null;\n\nexport async function loadSdk(): Promise<\n typeof import(\"@aws-sdk/client-bedrock-runtime\")\n> {\n if (cachedSdk) return cachedSdk;\n try {\n cachedSdk = await import(\"@aws-sdk/client-bedrock-runtime\");\n return cachedSdk;\n } catch {\n throw new ConfigurationError(\n \"@aws-sdk/client-bedrock-runtime is required but not installed. Run: npm install @aws-sdk/client-bedrock-runtime\",\n );\n }\n}\n\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\nexport async function initializeClient({\n region,\n}: { region?: string } = {}): Promise<BedrockRuntimeClient> {\n const logger = getLogger();\n const resolvedRegion = region || process.env.AWS_REGION || \"us-east-1\";\n\n const sdk = await loadSdk();\n const client = new sdk.BedrockRuntimeClient({ region: resolvedRegion });\n logger.trace(\"Initialized Bedrock client\");\n return client;\n}\n","import type { BedrockRuntimeClient } from \"@aws-sdk/client-bedrock-runtime\";\nimport { JsonObject } from \"@jaypie/types\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n bedrockAdapter,\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmHistoryItem,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport { getLogger, initializeClient } from \"./utils.js\";\n\nexport class BedrockProvider implements LlmProvider {\n private model: string;\n private region?: string;\n private _client?: BedrockRuntimeClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.BEDROCK.DEFAULT,\n { region }: { region?: string } = {},\n ) {\n this.model = model;\n this.region = region;\n }\n\n private async getClient(): Promise<BedrockRuntimeClient> {\n if (this._client) return this._client;\n this._client = await initializeClient({ region: this.region });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) return this._operateLoop;\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({ adapter: bedrockAdapter, client });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) return this._streamLoop;\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({ adapter: bedrockAdapter, client });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options?.model ?? this.model };\n const response = await operateLoop.execute(message, mergedOptions);\n return response.content ?? \"\";\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n const response = await operateLoop.execute(input, mergedOptions);\n\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { parseSseStream } from \"../../util/sse.js\";\n\n//\n//\n// Types\n//\n\nexport interface FireworksClientOptions {\n apiKey: string;\n baseURL?: string;\n}\n\nexport interface ChatCompletionOptions {\n signal?: AbortSignal;\n}\n\n/**\n * HTTP error carrying the upstream status and parsed API message. The\n * FireworksAdapter classifies errors by reading `.status` / `.statusCode` and\n * `.message` / `.error.message`.\n */\nexport class FireworksHttpError extends Error {\n readonly status: number;\n readonly statusCode: number;\n readonly error?: { message?: string };\n\n constructor(status: number, message: string, error?: { message?: string }) {\n super(message);\n this.name = \"FireworksHttpError\";\n this.status = status;\n this.statusCode = status;\n this.error = error;\n }\n}\n\n//\n//\n// Helpers\n//\n\n/**\n * Normalize the snake_case wire response into the camelCase shape the adapter\n * readers expect. Only protocol fields are touched — user content (schema\n * property names, tool argument JSON) is left untouched.\n */\nfunction normalizeResponse(json: JsonObject): JsonObject {\n const choices = json.choices as Array<Record<string, unknown>> | undefined;\n if (Array.isArray(choices)) {\n for (const choice of choices) {\n if (\n choice.finish_reason !== undefined &&\n choice.finishReason === undefined\n ) {\n choice.finishReason = choice.finish_reason;\n }\n const message = choice.message as Record<string, unknown> | undefined;\n if (\n message?.tool_calls !== undefined &&\n message.toolCalls === undefined\n ) {\n message.toolCalls = message.tool_calls;\n }\n }\n }\n\n const usage = json.usage as Record<string, unknown> | undefined;\n if (usage) {\n if (usage.promptTokens === undefined)\n usage.promptTokens = usage.prompt_tokens;\n if (usage.completionTokens === undefined) {\n usage.completionTokens = usage.completion_tokens;\n }\n if (usage.totalTokens === undefined) usage.totalTokens = usage.total_tokens;\n const details = usage.completion_tokens_details as\n { reasoning_tokens?: number } | undefined;\n if (\n details?.reasoning_tokens !== undefined &&\n !usage.completionTokensDetails\n ) {\n usage.completionTokensDetails = {\n reasoningTokens: details.reasoning_tokens,\n };\n }\n }\n\n return json;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Minimal `fetch`-based client for Fireworks AI's OpenAI-compatible Chat\n * Completions endpoint. The adapter only needs a single POST (streaming and\n * non-streaming), header auth, and HTTP error surfacing.\n */\nexport class FireworksClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n\n constructor({\n apiKey,\n baseURL = PROVIDER.FIREWORKS.BASE_URL,\n }: FireworksClientOptions) {\n this.apiKey = apiKey;\n this.baseURL = baseURL;\n }\n\n private headers(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n }\n\n private async toError(response: Response): Promise<FireworksHttpError> {\n let message = `Fireworks request failed with status ${response.status}`;\n let error: { message?: string } | undefined;\n try {\n const body = (await response.json()) as { error?: { message?: string } };\n if (body?.error?.message) {\n message = body.error.message;\n error = body.error;\n }\n } catch {\n // Non-JSON error body; keep the status-based message.\n }\n return new FireworksHttpError(response.status, message, error);\n }\n\n async chatCompletion(\n body: Record<string, unknown>,\n { signal }: ChatCompletionOptions = {},\n ): Promise<JsonObject> {\n const response = await fetch(`${this.baseURL}/chat/completions`, {\n method: \"POST\",\n headers: this.headers(),\n body: JSON.stringify(body),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n\n const json = (await response.json()) as JsonObject;\n return normalizeResponse(json);\n }\n\n async *streamChatCompletion(\n body: Record<string, unknown>,\n { signal }: ChatCompletionOptions = {},\n ): AsyncIterable<JsonObject> {\n const response = await fetch(`${this.baseURL}/chat/completions`, {\n method: \"POST\",\n headers: { ...this.headers(), Accept: \"text/event-stream\" },\n // OpenAI-style streams only include usage when explicitly requested.\n body: JSON.stringify({\n ...body,\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n if (!response.body) return;\n\n yield* parseSseStream(response.body);\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { FireworksClient } from \"./client.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<FireworksClient> {\n const logger = getLogger();\n const resolvedApiKey =\n apiKey || (await getEnvSecret(PROVIDER.FIREWORKS.API_KEY));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new FireworksClient({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized Fireworks client\");\n return client;\n}\n\n// Get default model from environment or constants\nexport function getDefaultModel(): string {\n return process.env.FIREWORKS_MODEL || PROVIDER.FIREWORKS.DEFAULT;\n}\n\n// Message formatting\nexport interface ChatMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n\n return {\n role: \"system\" as const,\n content,\n };\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: \"user\" as const,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { system, data, placeholders }: LlmMessageOptions = {},\n): ChatMessage[] {\n const logger = getLogger();\n const messages: ChatMessage[] = [];\n\n if (system) {\n const systemMessage = formatSystemMessage(system, { data, placeholders });\n messages.push(systemMessage);\n logger.trace(`System message: ${systemMessage.content?.length} characters`);\n }\n\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content?.length} characters`);\n\n return messages;\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport type { FireworksClient } from \"./client.js\";\nimport {\n createOperateLoop,\n createStreamLoop,\n fireworksAdapter,\n OperateLoop,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n getDefaultModel,\n getLogger,\n initializeClient,\n prepareMessages,\n} from \"./utils.js\";\n\nexport class FireworksProvider implements LlmProvider {\n private model: string;\n private _client?: FireworksClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = getDefaultModel(),\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<FireworksClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: fireworksAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: fireworksAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options);\n const modelToUse = options?.model || this.model;\n\n // OpenAI-compatible Chat Completions body; messages are already wire-shaped.\n const response = await client.chatCompletion({\n model: modelToUse,\n messages,\n });\n\n const choices = response.choices as\n Array<{ message?: { content?: unknown } }> | undefined;\n const rawContent = choices?.[0]?.message?.content;\n // Extract text content - content could be string or array of content items\n const content =\n typeof rawContent === \"string\"\n ? rawContent\n : Array.isArray(rawContent)\n ? rawContent\n .filter((item) => item.type === \"text\")\n .map((item) => (item as { text: string }).text)\n .join(\"\")\n : \"\";\n\n this.log.trace(`Assistant reply: ${content?.length || 0} characters`);\n\n // If structured output was requested, try to parse the response\n if (options?.response && content) {\n try {\n return JSON.parse(content);\n } catch {\n return content || \"\";\n }\n }\n\n return content || \"\";\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\n\nimport { parseSseStream } from \"../../util/sse.js\";\nimport {\n GeminiContent,\n GeminiGenerateContentConfig,\n GeminiRawResponse,\n} from \"./types.js\";\n\n//\n//\n// Constants\n//\n\nconst GOOGLE_BASE_URL = \"https://generativelanguage.googleapis.com/v1beta\";\n\n// Config keys the REST API expects at the top level of the request body. Every\n// other key in the SDK-style `config` object belongs under `generationConfig`.\nconst TOP_LEVEL_CONFIG_KEYS = new Set([\n \"systemInstruction\",\n \"tools\",\n \"toolConfig\",\n \"safetySettings\",\n \"cachedContent\",\n]);\n\n//\n//\n// Types\n//\n\nexport interface GoogleClientOptions {\n apiKey: string;\n baseURL?: string;\n}\n\nexport interface GenerateContentParams {\n model: string;\n contents: GeminiContent[];\n config?: GeminiGenerateContentConfig;\n}\n\nexport interface GenerateContentOptions {\n signal?: AbortSignal;\n}\n\n/**\n * HTTP error carrying the upstream status and parsed API message. The\n * GoogleAdapter classifies errors by reading `.status` / `.code` and\n * `.message`, so this shape keeps `classifyError` working unchanged after\n * dropping the SDK.\n */\nexport class GoogleHttpError extends Error {\n readonly status: number;\n readonly code: number;\n\n constructor(status: number, message: string) {\n super(message);\n this.name = \"GoogleHttpError\";\n this.status = status;\n this.code = status;\n }\n}\n\n//\n//\n// Helpers\n//\n\n/**\n * Translate the SDK-style `{ model, contents, config }` request into the REST\n * `generateContent` body. `systemInstruction` (a string) becomes a Content;\n * top-level config keys pass through; all remaining config keys (temperature,\n * responseMimeType, responseSchema, responseJsonSchema, ...) move under\n * `generationConfig`.\n */\nfunction toRestBody(params: GenerateContentParams): JsonObject {\n const body: JsonObject = {\n contents: params.contents as unknown as JsonObject[],\n };\n const config = params.config;\n if (!config) return body;\n\n const generationConfig: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(config)) {\n if (value === undefined) continue;\n if (key === \"systemInstruction\") {\n body.systemInstruction =\n typeof value === \"string\"\n ? { parts: [{ text: value }] }\n : (value as JsonObject);\n } else if (TOP_LEVEL_CONFIG_KEYS.has(key)) {\n body[key] = value as JsonObject;\n } else {\n generationConfig[key] = value;\n }\n }\n if (Object.keys(generationConfig).length > 0) {\n body.generationConfig = generationConfig as JsonObject;\n }\n return body;\n}\n\n/**\n * Concatenate the non-thought text parts of the first candidate, matching the\n * SDK's `response.text` convenience getter (consumed by `GoogleProvider.send`).\n */\nfunction responseText(response: GeminiRawResponse): string | undefined {\n const parts = response.candidates?.[0]?.content?.parts;\n if (!parts) return undefined;\n const text = parts\n .filter((part) => part.text && !part.thought)\n .map((part) => part.text)\n .join(\"\");\n return text.length > 0 ? text : undefined;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Minimal `fetch`-based client for Google's Generative Language (Gemini) REST\n * API. Replaces `@google/genai` — the adapter only needs `generateContent`\n * (streaming and non-streaming), an api-key header, and HTTP error surfacing.\n * Exposes a `models` facade mirroring the SDK so the adapter call sites are\n * unchanged.\n */\nexport class GoogleClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n readonly models: {\n generateContent: (\n params: GenerateContentParams,\n options?: GenerateContentOptions,\n ) => Promise<GeminiRawResponse>;\n generateContentStream: (\n params: GenerateContentParams,\n options?: GenerateContentOptions,\n ) => Promise<AsyncIterable<GeminiRawResponse>>;\n };\n\n constructor({ apiKey, baseURL = GOOGLE_BASE_URL }: GoogleClientOptions) {\n this.apiKey = apiKey;\n this.baseURL = baseURL;\n this.models = {\n generateContent: (params, options) =>\n this.generateContent(params, options),\n generateContentStream: (params, options) =>\n this.generateContentStream(params, options),\n };\n }\n\n private headers(): Record<string, string> {\n return {\n \"Content-Type\": \"application/json\",\n \"x-goog-api-key\": this.apiKey,\n };\n }\n\n private async toError(response: Response): Promise<GoogleHttpError> {\n let message = `Google request failed with status ${response.status}`;\n try {\n const body = (await response.json()) as { error?: { message?: string } };\n if (body?.error?.message) message = body.error.message;\n } catch {\n // Non-JSON error body; keep the status-based message.\n }\n return new GoogleHttpError(response.status, message);\n }\n\n private async generateContent(\n params: GenerateContentParams,\n { signal }: GenerateContentOptions = {},\n ): Promise<GeminiRawResponse> {\n const url = `${this.baseURL}/models/${params.model}:generateContent`;\n const response = await fetch(url, {\n method: \"POST\",\n headers: this.headers(),\n body: JSON.stringify(toRestBody(params)),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n\n const json = (await response.json()) as GeminiRawResponse;\n json.text = responseText(json);\n return json;\n }\n\n private async generateContentStream(\n params: GenerateContentParams,\n { signal }: GenerateContentOptions = {},\n ): Promise<AsyncIterable<GeminiRawResponse>> {\n const url = `${this.baseURL}/models/${params.model}:streamGenerateContent?alt=sse`;\n const response = await fetch(url, {\n method: \"POST\",\n headers: { ...this.headers(), Accept: \"text/event-stream\" },\n body: JSON.stringify(toRestBody(params)),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n if (!response.body) return (async function* () {})();\n\n return parseSseStream(response.body) as AsyncIterable<GeminiRawResponse>;\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { GoogleClient } from \"./client.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<GoogleClient> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"GEMINI_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new GoogleClient({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized Gemini client\");\n return client;\n}\n\n// Message formatting\nexport interface ChatMessage {\n role: \"user\" | \"model\";\n content: string;\n}\n\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): string {\n const content =\n placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n\n return content;\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: \"user\" as const,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { data, placeholders }: LlmMessageOptions = {},\n): { messages: ChatMessage[]; systemInstruction?: string } {\n const logger = getLogger();\n const messages: ChatMessage[] = [];\n\n // Note: Gemini handles system prompts differently via systemInstruction config\n // This function is kept for compatibility but system prompts should be passed\n // via the systemInstruction parameter in generateContent\n\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content?.length} characters`);\n\n return { messages, systemInstruction: undefined };\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport type { GoogleClient } from \"./client.js\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n googleAdapter,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport { getLogger, initializeClient, prepareMessages } from \"./utils.js\";\n\nexport class GoogleProvider implements LlmProvider {\n private model: string;\n private _client?: GoogleClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.GOOGLE.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<GoogleClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: googleAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: googleAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const { messages } = prepareMessages(message, options);\n const modelToUse = options?.model || this.model;\n\n // Build the request config\n const config: Record<string, unknown> = {};\n\n if (options?.system) {\n config.systemInstruction = options.system;\n }\n\n // Handle structured output via responseSchema\n if (options?.response) {\n config.responseMimeType = \"application/json\";\n // Convert the response schema to JSON schema format\n // Note: For simple send() calls, we'll use Gemini's native JSON response\n }\n\n const response = await client.models.generateContent({\n model: modelToUse,\n contents: messages.map((m) => ({\n role: m.role,\n parts: [{ text: m.content }],\n })),\n config: Object.keys(config).length > 0 ? config : undefined,\n });\n\n const text = response.text;\n this.log.trace(`Assistant reply: ${text?.length || 0} characters`);\n\n // If structured output was requested, try to parse the response\n if (options?.response && text) {\n try {\n return JSON.parse(text);\n } catch {\n // Strip markdown code fences and retry (Gemini sometimes wraps JSON in fences)\n const jsonMatch =\n text.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/) ||\n text.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n return JSON.parse(jsonMatch[1] || jsonMatch[0]);\n } catch {\n // Fall through to return original text\n }\n }\n return text || \"\";\n }\n }\n\n return text || \"\";\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { naturalZodSchema } from \"../../util\";\nimport { OpenAIClient } from \"./client.js\";\nimport { zodResponseFormat } from \"./responseFormat.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenAIClient> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"OPENAI_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new OpenAIClient({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized OpenAI client\");\n return client;\n}\n\n// Message formatting\nexport interface ChatMessage {\n role: \"user\" | \"developer\";\n content: string;\n}\n\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n\n return {\n role: \"developer\" as const,\n content,\n };\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: \"user\" as const,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { system, data, placeholders }: LlmMessageOptions = {},\n): ChatMessage[] {\n const logger = getLogger();\n const messages: ChatMessage[] = [];\n\n if (system) {\n const systemMessage = formatSystemMessage(system, { data, placeholders });\n messages.push(systemMessage);\n logger.trace(`System message: ${systemMessage.content?.length} characters`);\n }\n\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content?.length} characters`);\n\n return messages;\n}\n\n// Completion requests\nexport async function createStructuredCompletion(\n client: OpenAIClient,\n {\n messages,\n responseSchema,\n model,\n }: {\n messages: ChatMessage[];\n responseSchema: z.ZodType | NaturalSchema;\n model: string;\n },\n): Promise<JsonObject> {\n const logger = getLogger();\n logger.trace(\"Using structured output\");\n\n const zodSchema =\n responseSchema instanceof z.ZodType\n ? responseSchema\n : naturalZodSchema(responseSchema as NaturalSchema);\n\n const responseFormat = zodResponseFormat(zodSchema as any, \"response\");\n\n const jsonSchema = z.toJSONSchema(zodSchema);\n\n // Temporary hack because OpenAI requires additional_properties to be false on all objects\n const checks = [jsonSchema];\n while (checks.length > 0) {\n const current = checks[0];\n if (current.type == \"object\") {\n current.additionalProperties = false;\n }\n Object.keys(current).forEach((key) => {\n if (typeof current[key] == \"object\" && current[key] !== null) {\n checks.push(current[key] as any);\n }\n });\n checks.shift();\n }\n responseFormat.json_schema.schema = jsonSchema as JsonObject;\n\n const completion = (await client.chat.completions.parse({\n messages,\n model,\n response_format: responseFormat,\n })) as { choices: Array<{ message: { parsed: JsonObject } }> };\n\n logger.var({ assistantReply: completion.choices[0].message.parsed });\n return completion.choices[0].message.parsed;\n}\n\nexport async function createTextCompletion(\n client: OpenAIClient,\n {\n messages,\n model,\n }: {\n messages: ChatMessage[];\n model: string;\n },\n): Promise<string> {\n const logger = getLogger();\n logger.trace(\"Using text output (unstructured)\");\n\n const completion = (await client.chat.completions.create({\n messages,\n model,\n })) as { choices?: Array<{ message?: { content?: string } }> };\n\n logger.trace(\n `Assistant reply: ${completion.choices?.[0]?.message?.content?.length} characters`,\n );\n\n return completion.choices?.[0]?.message?.content || \"\";\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n openAiAdapter,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport { OpenAIClient } from \"./client.js\";\nimport {\n createStructuredCompletion,\n createTextCompletion,\n getLogger,\n initializeClient,\n prepareMessages,\n} from \"./utils.js\";\n\nexport class OpenAiProvider implements LlmProvider {\n private model: string;\n private _client?: OpenAIClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.OPENAI.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenAIClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: openAiAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: openAiAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options || {});\n const modelToUse = options?.model || this.model;\n\n if (options?.response) {\n return createStructuredCompletion(client, {\n messages,\n responseSchema: options.response,\n model: modelToUse,\n });\n }\n\n return createTextCompletion(client, {\n messages,\n model: modelToUse,\n });\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\n\nimport { parseSseStream } from \"../../util/sse.js\";\n\n//\n//\n// Constants\n//\n\nconst OPENROUTER_BASE_URL = \"https://openrouter.ai/api/v1\";\n\n//\n//\n// Types\n//\n\nexport interface OpenRouterClientOptions {\n apiKey: string;\n baseURL?: string;\n}\n\nexport interface ChatCompletionOptions {\n signal?: AbortSignal;\n}\n\n/**\n * HTTP error carrying the upstream status and parsed API message. The\n * OpenRouterAdapter classifies errors by reading `.status` / `.statusCode` and\n * `.message` / `.error.message`, so this shape keeps `classifyError`,\n * `isTemperatureDeprecationError`, and `isStructuredOutputUnsupportedError`\n * working unchanged after dropping the SDK.\n */\nexport class OpenRouterHttpError extends Error {\n readonly status: number;\n readonly statusCode: number;\n readonly error?: { message?: string };\n\n constructor(status: number, message: string, error?: { message?: string }) {\n super(message);\n this.name = \"OpenRouterHttpError\";\n this.status = status;\n this.statusCode = status;\n this.error = error;\n }\n}\n\n//\n//\n// Helpers\n//\n\n/**\n * Normalize the snake_case wire response into the camelCase shape the adapter\n * readers expect (the SDK previously returned camelCase). Only protocol fields\n * are touched — user content (schema property names, tool argument JSON) is\n * left untouched.\n */\nfunction normalizeResponse(json: JsonObject): JsonObject {\n const choices = json.choices as Array<Record<string, unknown>> | undefined;\n if (Array.isArray(choices)) {\n for (const choice of choices) {\n if (\n choice.finish_reason !== undefined &&\n choice.finishReason === undefined\n ) {\n choice.finishReason = choice.finish_reason;\n }\n const message = choice.message as Record<string, unknown> | undefined;\n if (\n message?.tool_calls !== undefined &&\n message.toolCalls === undefined\n ) {\n message.toolCalls = message.tool_calls;\n }\n }\n }\n\n const usage = json.usage as Record<string, unknown> | undefined;\n if (usage) {\n if (usage.promptTokens === undefined)\n usage.promptTokens = usage.prompt_tokens;\n if (usage.completionTokens === undefined) {\n usage.completionTokens = usage.completion_tokens;\n }\n if (usage.totalTokens === undefined) usage.totalTokens = usage.total_tokens;\n const details = usage.completion_tokens_details as\n { reasoning_tokens?: number } | undefined;\n if (\n details?.reasoning_tokens !== undefined &&\n !usage.completionTokensDetails\n ) {\n usage.completionTokensDetails = {\n reasoningTokens: details.reasoning_tokens,\n };\n }\n }\n\n return json;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Minimal `fetch`-based client for OpenRouter's OpenAI-compatible Chat\n * Completions endpoint. Replaces `@openrouter/sdk` — the adapter only needs a\n * single POST (streaming and non-streaming), header auth, and HTTP error\n * surfacing.\n */\nexport class OpenRouterClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n\n constructor({\n apiKey,\n baseURL = OPENROUTER_BASE_URL,\n }: OpenRouterClientOptions) {\n this.apiKey = apiKey;\n this.baseURL = baseURL;\n }\n\n private headers(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n }\n\n private async toError(response: Response): Promise<OpenRouterHttpError> {\n let message = `OpenRouter request failed with status ${response.status}`;\n let error: { message?: string } | undefined;\n try {\n const body = (await response.json()) as { error?: { message?: string } };\n if (body?.error?.message) {\n message = body.error.message;\n error = body.error;\n }\n } catch {\n // Non-JSON error body; keep the status-based message.\n }\n return new OpenRouterHttpError(response.status, message, error);\n }\n\n async chatCompletion(\n body: Record<string, unknown>,\n { signal }: ChatCompletionOptions = {},\n ): Promise<JsonObject> {\n const response = await fetch(`${this.baseURL}/chat/completions`, {\n method: \"POST\",\n headers: this.headers(),\n body: JSON.stringify(body),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n\n const json = (await response.json()) as JsonObject;\n return normalizeResponse(json);\n }\n\n async *streamChatCompletion(\n body: Record<string, unknown>,\n { signal }: ChatCompletionOptions = {},\n ): AsyncIterable<JsonObject> {\n const response = await fetch(`${this.baseURL}/chat/completions`, {\n method: \"POST\",\n headers: { ...this.headers(), Accept: \"text/event-stream\" },\n // OpenAI-style streams only include usage when explicitly requested.\n body: JSON.stringify({\n ...body,\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n if (!response.body) return;\n\n yield* parseSseStream(response.body);\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { OpenRouterClient } from \"./client.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenRouterClient> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"OPENROUTER_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new OpenRouterClient({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized OpenRouter client\");\n return client;\n}\n\n// Get default model from environment or constants\nexport function getDefaultModel(): string {\n return process.env.OPENROUTER_MODEL || PROVIDER.OPENROUTER.DEFAULT;\n}\n\n// Message formatting\nexport interface ChatMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n\n return {\n role: \"system\" as const,\n content,\n };\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: \"user\" as const,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { system, data, placeholders }: LlmMessageOptions = {},\n): ChatMessage[] {\n const logger = getLogger();\n const messages: ChatMessage[] = [];\n\n if (system) {\n const systemMessage = formatSystemMessage(system, { data, placeholders });\n messages.push(systemMessage);\n logger.trace(`System message: ${systemMessage.content?.length} characters`);\n }\n\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content?.length} characters`);\n\n return messages;\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport type { OpenRouterClient } from \"./client.js\";\nimport {\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n openRouterAdapter,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n getDefaultModel,\n getLogger,\n initializeClient,\n prepareMessages,\n} from \"./utils.js\";\n\nexport class OpenRouterProvider implements LlmProvider {\n private model: string;\n private _client?: OpenRouterClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = getDefaultModel(),\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenRouterClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: openRouterAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: openRouterAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options);\n const modelToUse = options?.model || this.model;\n\n // OpenAI-compatible Chat Completions body; messages are already wire-shaped.\n const response = await client.chatCompletion({\n model: modelToUse,\n messages,\n });\n\n const choices = response.choices as\n Array<{ message?: { content?: unknown } }> | undefined;\n const rawContent = choices?.[0]?.message?.content;\n // Extract text content - content could be string or array of content items\n const content =\n typeof rawContent === \"string\"\n ? rawContent\n : Array.isArray(rawContent)\n ? rawContent\n .filter((item) => item.type === \"text\")\n .map((item) => (item as { text: string }).text)\n .join(\"\")\n : \"\";\n\n this.log.trace(`Assistant reply: ${content?.length || 0} characters`);\n\n // If structured output was requested, try to parse the response\n if (options?.response && content) {\n try {\n return JSON.parse(content);\n } catch {\n return content || \"\";\n }\n }\n\n return content || \"\";\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { OpenAIClient } from \"../openai/client.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenAIClient> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(PROVIDER.XAI.API_KEY));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new OpenAIClient({\n apiKey: resolvedApiKey,\n baseURL: PROVIDER.XAI.BASE_URL,\n });\n logger.trace(\"Initialized xAI client\");\n return client;\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n StreamLoop,\n xaiAdapter,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport { OpenAIClient } from \"../openai/client.js\";\nimport {\n createStructuredCompletion,\n createTextCompletion,\n getLogger,\n prepareMessages,\n} from \"../openai/utils.js\";\nimport { initializeClient } from \"./utils.js\";\n\nexport class XaiProvider implements LlmProvider {\n private model: string;\n private _client?: OpenAIClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.XAI.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenAIClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: xaiAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: xaiAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options || {});\n const modelToUse = options?.model || this.model;\n\n if (options?.response) {\n return createStructuredCompletion(client, {\n messages,\n responseSchema: options.response,\n model: modelToUse,\n });\n }\n\n return createTextCompletion(client, {\n messages,\n model: modelToUse,\n });\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { ConfigurationError, NotImplementedError } from \"@jaypie/errors\";\nimport log from \"@jaypie/logger\";\nimport { DEFAULT, LlmProviderName, PROVIDER } from \"./constants.js\";\nimport { determineModelProvider } from \"./util/determineModelProvider.js\";\nimport { resolveModelChain } from \"./util/resolveModelChain.js\";\nimport { emitExchange } from \"./operate/exchange/index.js\";\nimport { persistExchange } from \"./observability/exchangeStore.js\";\nimport {\n LlmExchangeCallback,\n LlmExchangeEnvelope,\n LlmFallbackConfig,\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmModelOption,\n LlmOperateInput,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmOptions,\n LlmProvider,\n} from \"./types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"./types/LlmStreamChunk.interface.js\";\nimport { AnthropicProvider } from \"./providers/anthropic/AnthropicProvider.class.js\";\nimport { BedrockProvider } from \"./providers/bedrock/index.js\";\nimport { FireworksProvider } from \"./providers/fireworks/index.js\";\nimport { GoogleProvider } from \"./providers/google/GoogleProvider.class.js\";\nimport { OpenAiProvider } from \"./providers/openai/index.js\";\nimport { OpenRouterProvider } from \"./providers/openrouter/index.js\";\nimport { XaiProvider } from \"./providers/xai/index.js\";\n\nclass Llm implements LlmProvider {\n private _fallbackConfig?: LlmFallbackConfig[];\n private _llm: LlmProvider;\n private _options: LlmOptions;\n private _provider: LlmProviderName;\n\n constructor(\n providerName: LlmProviderName | string = DEFAULT.PROVIDER.NAME,\n options: Omit<LlmOptions, \"model\"> & { model?: LlmModelOption } = {},\n ) {\n const { fallback: fallbackOption, model: modelOption } = options;\n // A `model` array is sugar for a preference-ordered fallback chain:\n // index 0 is primary, the rest become fallback entries (provider\n // auto-detected). Any explicit `fallback` is appended after the chain.\n const { fallback: modelFallback, model } = resolveModelChain(modelOption);\n const fallback =\n modelFallback.length || fallbackOption\n ? [...modelFallback, ...(fallbackOption ?? [])]\n : undefined;\n let finalProvider = providerName;\n let finalModel = model;\n\n // Legacy: accept \"gemini\" but warn\n if (providerName === \"gemini\") {\n log.warn(\n `Provider \"gemini\" is deprecated, use \"${PROVIDER.GOOGLE.NAME}\" instead`,\n );\n }\n\n if (model) {\n const modelDetermined = determineModelProvider(model);\n finalModel = modelDetermined.model;\n if (modelDetermined.provider) {\n finalProvider = modelDetermined.provider as LlmProviderName;\n }\n }\n\n // Only determine provider from providerName if we don't have a provider from model\n if (!model || !determineModelProvider(model).provider) {\n const providerDetermined = determineModelProvider(providerName);\n if (!providerDetermined.provider) {\n throw new ConfigurationError(\n `Unable to determine provider from: ${providerName}`,\n );\n }\n finalProvider = providerDetermined.provider;\n // When providerName is actually a model name, extract the model (#213)\n if (!finalModel && providerName !== providerDetermined.provider) {\n finalModel = providerDetermined.model;\n }\n }\n\n // Handle conflicts: if both providerName and model specify different providers\n if (model && providerName !== DEFAULT.PROVIDER.NAME) {\n const modelDetermined = determineModelProvider(model);\n const providerDetermined = determineModelProvider(providerName);\n if (\n modelDetermined.provider &&\n providerDetermined.provider &&\n modelDetermined.provider !== providerDetermined.provider\n ) {\n // Model's provider conflicts with explicit provider, don't pass model\n finalModel = undefined;\n }\n }\n\n this._fallbackConfig = fallback;\n this._provider = finalProvider as LlmProviderName;\n this._options = { ...options, model: finalModel };\n this._llm = this.createProvider(\n finalProvider as LlmProviderName,\n this._options,\n );\n }\n\n private createProvider(\n providerName: LlmProviderName,\n options: LlmOptions = {},\n ): LlmProvider {\n const { apiKey, model } = options;\n\n switch (providerName) {\n case PROVIDER.ANTHROPIC.NAME:\n return new AnthropicProvider(model || PROVIDER.ANTHROPIC.DEFAULT, {\n apiKey,\n });\n case PROVIDER.BEDROCK.NAME:\n return new BedrockProvider(model || PROVIDER.BEDROCK.DEFAULT);\n case PROVIDER.FIREWORKS.NAME:\n return new FireworksProvider(model || PROVIDER.FIREWORKS.DEFAULT, {\n apiKey,\n });\n case PROVIDER.GOOGLE.NAME:\n return new GoogleProvider(model || PROVIDER.GOOGLE.DEFAULT, {\n apiKey,\n });\n case PROVIDER.OPENAI.NAME:\n return new OpenAiProvider(model || PROVIDER.OPENAI.DEFAULT, {\n apiKey,\n });\n case PROVIDER.OPENROUTER.NAME:\n return new OpenRouterProvider(model || PROVIDER.OPENROUTER.DEFAULT, {\n apiKey,\n });\n case PROVIDER.XAI.NAME:\n return new XaiProvider(model || PROVIDER.XAI.DEFAULT, {\n apiKey,\n });\n default:\n throw new ConfigurationError(`Unsupported provider: ${providerName}`);\n }\n }\n\n async send(\n message: string,\n options?: Omit<LlmMessageOptions, \"model\"> & { model?: LlmModelOption },\n ): Promise<string | JsonObject> {\n if (options && Array.isArray(options.model)) {\n // `send` has no fallback machinery; use the primary model only\n const { model } = resolveModelChain(options.model);\n return this._llm.send(message, { ...options, model });\n }\n return this._llm.send(message, options as LlmMessageOptions | undefined);\n }\n\n /**\n * Resolves the fallback chain from instance config and per-call options.\n * Per-call options take precedence over instance config.\n * Returns empty array if fallback is disabled.\n */\n private resolveFallbackChain(\n options: LlmOperateOptions,\n ): LlmFallbackConfig[] {\n // Per-call `fallback: false` disables fallback entirely\n if (options.fallback === false) {\n return [];\n }\n // Per-call fallback array overrides instance config\n if (Array.isArray(options.fallback)) {\n return options.fallback;\n }\n // Use instance config if available\n return this._fallbackConfig || [];\n }\n\n /**\n * Creates a fallback Llm instance lazily when needed.\n */\n private createFallbackInstance(config: LlmFallbackConfig): Llm {\n return new Llm(config.provider, {\n apiKey: config.apiKey,\n model: config.model,\n });\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: Omit<LlmOperateOptions, \"model\"> & { model?: LlmModelOption } = {},\n ): Promise<LlmOperateResponse> {\n if (!this._llm.operate) {\n throw new NotImplementedError(\n `Provider ${this._provider} does not support operate method`,\n );\n }\n\n // A per-call `model` array becomes primary + a derived fallback chain\n // prepended to any resolved chain.\n const { fallback: modelFallback, model: perCallModel } = resolveModelChain(\n options.model,\n );\n const resolvedOptions: LlmOperateOptions = {\n ...options,\n model: perCallModel,\n };\n\n const fallbackChain = [\n ...modelFallback,\n ...this.resolveFallbackChain(resolvedOptions),\n ];\n const optionsWithoutFallback = {\n ...resolvedOptions,\n fallback: false as const,\n };\n\n let lastError: Error | undefined;\n let attempts = 0;\n\n // Try primary provider first\n attempts++;\n try {\n const response = await this._llm.operate(input, optionsWithoutFallback);\n const settled = {\n ...response,\n fallbackAttempts: attempts,\n fallbackUsed: false,\n provider: response.provider || this._provider,\n };\n await this.settleExchange({\n onExchange: resolvedOptions.onExchange,\n response: settled,\n });\n return settled;\n } catch (error) {\n lastError = error as Error;\n log.warn(`Provider ${this._provider} failed`, {\n error: lastError.message,\n fallbacksRemaining: fallbackChain.length,\n });\n }\n\n // Try fallback providers. The fallback instance's underlying provider is\n // called directly so the nested facade does not settle the exchange —\n // exactly one settlement per operate() happens here.\n for (const fallbackConfig of fallbackChain) {\n attempts++;\n try {\n const fallbackInstance = this.createFallbackInstance(fallbackConfig);\n if (!fallbackInstance._llm.operate) {\n throw new NotImplementedError(\n `Provider ${fallbackConfig.provider} does not support operate method`,\n );\n }\n const response = await fallbackInstance._llm.operate(\n input,\n optionsWithoutFallback,\n );\n const settled = {\n ...response,\n fallbackAttempts: attempts,\n fallbackUsed: true,\n provider: response.provider || fallbackConfig.provider,\n };\n await this.settleExchange({\n onExchange: resolvedOptions.onExchange,\n response: settled,\n });\n return settled;\n } catch (error) {\n lastError = error as Error;\n log.warn(`Fallback provider ${fallbackConfig.provider} failed`, {\n error: lastError.message,\n fallbacksRemaining: fallbackChain.length - attempts + 1,\n });\n }\n }\n\n // All providers failed: settle the exchange from the envelope the loop\n // attached to the last error, then throw\n const failureEnvelope = (lastError as { exchange?: LlmExchangeEnvelope })\n ?.exchange;\n if (failureEnvelope) {\n failureEnvelope.resolution = {\n ...failureEnvelope.resolution,\n fallbackAttempts: attempts,\n fallbackUsed: attempts > 1,\n };\n await emitExchange({\n envelope: failureEnvelope,\n onExchange: resolvedOptions.onExchange,\n });\n await persistExchange(failureEnvelope);\n }\n throw lastError;\n }\n\n /**\n * Stamp fallback resolution onto the envelope the operate loop attached to\n * the response and deliver it to the caller's onExchange. Fires once per\n * operate() settlement; callback errors are logged and never thrown.\n */\n private async settleExchange({\n onExchange,\n response,\n }: {\n onExchange?: LlmExchangeCallback;\n response: LlmOperateResponse;\n }): Promise<void> {\n const envelope = response.exchange;\n if (!envelope) {\n return;\n }\n envelope.resolution = {\n ...envelope.resolution,\n fallbackAttempts: response.fallbackAttempts,\n fallbackUsed: response.fallbackUsed,\n model: response.model,\n provider: response.provider,\n };\n await emitExchange({ envelope, onExchange });\n await persistExchange(envelope);\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: Omit<LlmOperateOptions, \"model\"> & { model?: LlmModelOption } = {},\n ): AsyncIterable<LlmStreamChunk> {\n if (!this._llm.stream) {\n throw new NotImplementedError(\n `Provider ${this._provider} does not support stream method`,\n );\n }\n // `stream` has no instance-level fallback machinery; an array model uses\n // the primary and ignores the rest.\n const { model } = resolveModelChain(options.model);\n const streamOptions: LlmOperateOptions = { ...options, model };\n yield* this._llm.stream(input, streamOptions);\n }\n\n static async send(\n message: string,\n options?: Omit<LlmMessageOptions, \"model\"> & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string | string[];\n },\n ): Promise<string | JsonObject> {\n const { llm, apiKey, model, ...messageOptions } = options || {};\n // A `model` array derives a fallback chain; `send` has no fallback\n // machinery, so the primary model is used and the chain is ignored.\n const { model: primaryModel } = resolveModelChain(model);\n const instance = new Llm(llm, { apiKey, model: primaryModel });\n return instance.send(message, messageOptions);\n }\n\n static async operate(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options?: Omit<LlmOperateOptions, \"model\"> & {\n apiKey?: string;\n fallback?: LlmFallbackConfig[] | false;\n llm?: LlmProviderName;\n model?: string | string[];\n },\n ): Promise<LlmOperateResponse> {\n const { apiKey, fallback, llm, model, ...operateOptions } = options || {};\n\n // A `model` array becomes primary + derived fallback chain\n const { fallback: modelFallback, model: primaryModel } =\n resolveModelChain(model);\n\n let finalLlm = llm;\n let finalModel = primaryModel;\n\n if (!llm && primaryModel) {\n const determined = determineModelProvider(primaryModel);\n if (determined.provider) {\n finalLlm = determined.provider as LlmProviderName;\n }\n } else if (llm && primaryModel) {\n // When both llm and model are provided, check if they conflict\n const determined = determineModelProvider(primaryModel);\n if (determined.provider && determined.provider !== llm) {\n // Don't pass the conflicting model to the constructor\n finalModel = undefined;\n }\n }\n\n // Resolve fallback for static method: pass to instance if array, pass to operate options if false\n const explicitFallback = Array.isArray(fallback) ? fallback : [];\n const instanceFallback =\n modelFallback.length || explicitFallback.length\n ? [...modelFallback, ...explicitFallback]\n : undefined;\n const operateFallback = fallback === false ? false : undefined;\n\n const instance = new Llm(finalLlm, {\n apiKey,\n fallback: instanceFallback,\n model: finalModel,\n });\n return instance.operate(input, {\n ...operateOptions,\n ...(operateFallback !== undefined && { fallback: operateFallback }),\n });\n }\n\n static stream(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options?: Omit<LlmOperateOptions, \"model\"> & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string | string[];\n },\n ): AsyncIterable<LlmStreamChunk> {\n const { llm, apiKey, model, ...streamOptions } = options || {};\n\n // A `model` array becomes primary + derived fallback chain\n const { fallback: modelFallback, model: primaryModel } =\n resolveModelChain(model);\n\n let finalLlm = llm;\n let finalModel = primaryModel;\n\n if (!llm && primaryModel) {\n const determined = determineModelProvider(primaryModel);\n if (determined.provider) {\n finalLlm = determined.provider as LlmProviderName;\n }\n } else if (llm && primaryModel) {\n // When both llm and model are provided, check if they conflict\n const determined = determineModelProvider(primaryModel);\n if (determined.provider && determined.provider !== llm) {\n // Don't pass the conflicting model to the constructor\n finalModel = undefined;\n }\n }\n\n const instance = new Llm(finalLlm, {\n apiKey,\n fallback: modelFallback.length ? modelFallback : undefined,\n model: finalModel,\n });\n return instance.stream(input, streamOptions);\n }\n}\n\nexport default Llm;\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { random as randomUtil } from \"../util/random.js\";\n\nexport const random: LlmTool = {\n description:\n \"Generate a random number with optional distribution, precision, range, and seeding\",\n\n name: \"random\",\n parameters: {\n type: \"object\",\n properties: {\n min: {\n type: \"number\",\n description:\n \"Minimum value (inclusive). Default: 0. When used with mean/stddev, acts as a clamp on the normal distribution\",\n },\n max: {\n type: \"number\",\n description:\n \"Maximum value (inclusive). Default: 1. When used with mean/stddev, acts as a clamp on the normal distribution\",\n },\n mean: {\n type: \"number\",\n description:\n \"Mean value for normal distribution. When set with stddev, uses normal distribution (clamped by min/max if provided)\",\n },\n stddev: {\n type: \"number\",\n description:\n \"Standard deviation for normal distribution. When set with mean, uses normal distribution (clamped by min/max if provided)\",\n },\n integer: {\n type: \"boolean\",\n description: \"Whether to return an integer value. Default: false\",\n },\n seed: {\n type: \"string\",\n description:\n \"Seed string for consistent random generation. Default: undefined (uses default RNG)\",\n },\n precision: {\n type: \"number\",\n description:\n \"Number of decimal places for the result. Default: undefined (full precision)\",\n },\n currency: {\n type: \"boolean\",\n description:\n \"Whether to format as currency (2 decimal places). Default: false\",\n },\n },\n required: [],\n },\n type: \"function\",\n call: (options) => {\n const rng = randomUtil();\n return rng(options);\n },\n message: ({\n min,\n max,\n mean,\n stddev,\n integer,\n seed,\n precision,\n currency,\n } = {}) => {\n let description = \"Generating\";\n if (seed) {\n description += ` seeded`;\n } else {\n description += \" random\";\n }\n if (integer) {\n description += \" integer\";\n } else if (currency) {\n description += \" currency\";\n } else if (precision) {\n description += ` with precision \\`${precision}\\``;\n } else {\n description += \" number\";\n }\n if (min && max) {\n description += ` between \\`${min}\\` and \\`${max}\\``;\n }\n if (mean && stddev) {\n description += ` with normal distribution around \\`${mean}\\` with standard deviation \\`${stddev}\\``;\n }\n return description;\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { getLogger, random, tryParseNumber } from \"../util\";\n\nexport const roll: LlmTool = {\n description: \"Roll one or more dice with a specified number of sides\",\n name: \"roll\",\n parameters: {\n type: \"object\",\n properties: {\n number: {\n type: \"number\",\n description: \"Number of dice to roll. Default: 1\",\n },\n sides: {\n type: \"number\",\n description: \"Number of sides on each die. Default: 6\",\n },\n },\n required: [\"number\", \"sides\"],\n },\n type: \"function\",\n call: ({ number = 1, sides = 6 } = {}): {\n rolls: number[];\n total: number;\n } => {\n const log = getLogger();\n const rng = random();\n const rolls: number[] = [];\n let total = 0;\n\n const parsedNumber = tryParseNumber(number, {\n defaultValue: 1,\n warnFunction: log.warn,\n }) as number;\n const parsedSides = tryParseNumber(sides, {\n defaultValue: 6,\n warnFunction: log.warn,\n }) as number;\n\n for (let i = 0; i < parsedNumber; i++) {\n const rollValue = rng({ min: 1, max: parsedSides, integer: true });\n rolls.push(rollValue);\n total += rollValue;\n }\n\n return { rolls, total };\n },\n message: ({ number = 1, sides = 6 } = {}) => {\n return `Rolling ${number} ${sides}-sided dice`;\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\n\nexport const time: LlmTool = {\n description:\n \"Returns the provided date as an ISO UTC string or the current time if no date provided.\",\n name: \"time\",\n parameters: {\n type: \"object\",\n properties: {\n date: {\n type: \"string\",\n description:\n \"Date string to convert to ISO UTC format. Default: current time\",\n },\n },\n required: [],\n },\n type: \"function\",\n call: ({ date } = {}) => {\n if (typeof date === \"number\" || typeof date === \"string\") {\n const parsedDate = new Date(date);\n if (isNaN(parsedDate.getTime())) {\n throw new Error(`Invalid date format: ${date}`);\n }\n return parsedDate.toISOString();\n }\n return new Date().toISOString();\n },\n message: ({ date } = {}) => {\n if (typeof date === \"number\" || typeof date === \"string\") {\n return `Converting date to ISO UTC format`;\n }\n return \"Checking current time\";\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { fetchWeatherApi } from \"openmeteo\";\nimport { JsonObject } from \"@jaypie/types\";\n\nexport const weather: LlmTool = {\n description: \"Get current weather and forecast data for a specific location\",\n name: \"weather\",\n parameters: {\n type: \"object\",\n properties: {\n latitude: {\n type: \"number\",\n description:\n \"Latitude of the location. Default: 42.051554533384866 (Evanston, IL)\",\n },\n location: {\n type: \"string\",\n description:\n \"Human-readable description of the location, not used for the API call. Default: Evanston, IL\",\n },\n longitude: {\n type: \"number\",\n description:\n \"Longitude of the location. Default: -87.6759911441785 (Evanston, IL)\",\n },\n timezone: {\n type: \"string\",\n description: \"Timezone for the results. Default: America/Chicago\",\n },\n past_days: {\n type: \"number\",\n description:\n \"Number of past days to include in the forecast. Default: 1\",\n },\n forecast_days: {\n type: \"number\",\n description: \"Number of forecast days to include. Default: 1\",\n },\n },\n required: [\"latitude\", \"location\", \"longitude\"],\n },\n type: \"function\",\n call: async ({\n latitude = 42.051554533384866,\n longitude = -87.6759911441785,\n timezone = \"America/Chicago\",\n past_days = 1,\n forecast_days = 1,\n } = {}): Promise<JsonObject> => {\n try {\n const params = {\n latitude,\n longitude,\n hourly: [\n \"temperature_2m\",\n \"precipitation_probability\",\n \"precipitation\",\n ],\n current: [\n \"temperature_2m\",\n \"is_day\",\n \"showers\",\n \"cloud_cover\",\n \"wind_speed_10m\",\n \"relative_humidity_2m\",\n \"precipitation\",\n \"snowfall\",\n \"rain\",\n \"apparent_temperature\",\n ],\n timezone,\n past_days,\n forecast_days,\n wind_speed_unit: \"mph\",\n temperature_unit: \"fahrenheit\",\n precipitation_unit: \"inch\",\n };\n\n const url = \"https://api.open-meteo.com/v1/forecast\";\n const responses = await fetchWeatherApi(url, params);\n\n // Helper function to form time ranges\n const range = (start: number, stop: number, step: number) =>\n Array.from(\n { length: (stop - start) / step },\n (_, i) => start + i * step,\n );\n\n // Process first location\n const response = responses[0];\n\n // Attributes for timezone and location\n const utcOffsetSeconds = response.utcOffsetSeconds();\n const timezoneAbbreviation = response.timezoneAbbreviation();\n\n const current = response.current()!;\n const hourly = response.hourly()!;\n\n // Create weather data object\n const weatherData = {\n location: {\n latitude: response.latitude(),\n longitude: response.longitude(),\n timezone: response.timezone(),\n timezoneAbbreviation,\n utcOffsetSeconds,\n },\n current: {\n time: new Date(\n (Number(current.time()) + utcOffsetSeconds) * 1000,\n ).toISOString(),\n temperature2m: current.variables(0)!.value(),\n isDay: current.variables(1)!.value(),\n showers: current.variables(2)!.value(),\n cloudCover: current.variables(3)!.value(),\n windSpeed10m: current.variables(4)!.value(),\n relativeHumidity2m: current.variables(5)!.value(),\n precipitation: current.variables(6)!.value(),\n snowfall: current.variables(7)!.value(),\n rain: current.variables(8)!.value(),\n apparentTemperature: current.variables(9)!.value(),\n },\n hourly: {\n time: range(\n Number(hourly.time()),\n Number(hourly.timeEnd()),\n hourly.interval(),\n ).map((t) => new Date((t + utcOffsetSeconds) * 1000).toISOString()),\n temperature2m: Array.from(hourly.variables(0)!.valuesArray()!),\n precipitationProbability: Array.from(\n hourly.variables(1)!.valuesArray()!,\n ),\n precipitation: Array.from(hourly.variables(2)!.valuesArray()!),\n },\n };\n\n return weatherData;\n } catch (error) {\n if (error instanceof Error) {\n // eslint-disable-next-line preserve-caught-error -- package targets ES2020; Error `cause` option requires ES2022\n throw new Error(`Weather API error: ${error.message}`);\n }\n // eslint-disable-next-line preserve-caught-error -- package targets ES2020; Error `cause` option requires ES2022\n throw new Error(\"Unknown error occurred while fetching weather data\");\n }\n },\n message: ({\n latitude = 42.051554533384866,\n longitude = -87.6759911441785,\n location = \"Evanston, IL\",\n } = {}) => {\n return `Getting weather for ${location} (${latitude}, ${longitude})`;\n },\n};\n","import { Toolkit } from \"./Toolkit.class.js\";\nimport type { LlmTool } from \"../types/LlmTool.interface.js\";\n\nimport { random } from \"./random.js\";\nimport { roll } from \"./roll.js\";\nimport { time } from \"./time.js\";\nimport { weather } from \"./weather.js\";\n\nexport const tools = [random, roll, time, weather];\n\nexport class JaypieToolkit extends Toolkit {\n public readonly random: LlmTool;\n public readonly roll: LlmTool;\n public readonly time: LlmTool;\n public readonly weather: LlmTool;\n\n constructor(tools: LlmTool[], options?: any) {\n super(tools, options);\n this.random = random;\n this.roll = roll;\n this.time = time;\n this.weather = weather;\n }\n}\n\nexport const toolkit = new JaypieToolkit(tools);\n\nexport { Toolkit };\n","import { JsonObject } from \"@jaypie/types\";\nimport { LlmMessageRole } from \"../../types/LlmProvider.interface.js\";\n\n//\n//\n// Role Mapping\n//\n\nexport const ROLE_MAP: Record<LlmMessageRole, \"user\" | \"model\"> = {\n [LlmMessageRole.User]: \"user\",\n [LlmMessageRole.System]: \"user\", // Gemini doesn't have system role in contents\n [LlmMessageRole.Assistant]: \"model\",\n [LlmMessageRole.Developer]: \"user\",\n};\n\n//\n//\n// Gemini API Types\n//\n\n/**\n * A part of content - can be text, function call, or function response\n */\nexport interface GeminiPart {\n text?: string;\n thought?: boolean;\n thoughtSignature?: string;\n functionCall?: GeminiFunctionCall;\n functionResponse?: GeminiFunctionResponse;\n inlineData?: {\n mimeType: string;\n data: string;\n };\n fileData?: {\n mimeType?: string;\n fileUri: string;\n };\n}\n\n/**\n * A function call made by the model\n */\nexport interface GeminiFunctionCall {\n name?: string;\n args?: Record<string, unknown>;\n id?: string;\n}\n\n/**\n * A response to a function call\n */\nexport interface GeminiFunctionResponse {\n name: string;\n response: Record<string, unknown>;\n}\n\n/**\n * Content represents a message in the conversation\n */\nexport interface GeminiContent {\n role: \"user\" | \"model\";\n parts?: GeminiPart[];\n}\n\n/**\n * Function declaration for tools\n */\nexport interface GeminiFunctionDeclaration {\n name: string;\n description: string;\n parameters: JsonObject;\n}\n\n/**\n * Tool definition containing function declarations\n */\nexport interface GeminiTool {\n functionDeclarations?: GeminiFunctionDeclaration[];\n googleSearch?: Record<string, unknown>;\n codeExecution?: Record<string, unknown>;\n}\n\n/**\n * Configuration for a generate content request\n * This is a simplified internal type - we use the SDK's actual types at runtime\n */\nexport interface GeminiGenerateContentConfig {\n systemInstruction?: string;\n tools?: GeminiTool[];\n toolConfig?: {\n functionCallingConfig?: {\n mode?: \"AUTO\" | \"ANY\" | \"NONE\";\n allowedFunctionNames?: string[];\n };\n };\n responseMimeType?: string;\n responseJsonSchema?: JsonObject;\n responseSchema?: JsonObject;\n thinkingConfig?: {\n thinkingLevel?: string;\n thinkingBudget?: number;\n includeThoughts?: boolean;\n };\n temperature?: number;\n topP?: number;\n topK?: number;\n maxOutputTokens?: number;\n stopSequences?: string[];\n candidateCount?: number;\n}\n\n/**\n * Request structure for generateContent API\n */\nexport interface GeminiRequest {\n model: string;\n contents: GeminiContent[];\n config?: GeminiGenerateContentConfig;\n}\n\n/**\n * Usage metadata from the response\n */\nexport interface GeminiUsageMetadata {\n promptTokenCount?: number;\n candidatesTokenCount?: number;\n totalTokenCount?: number;\n thoughtsTokenCount?: number;\n cachedContentTokenCount?: number;\n}\n\n/**\n * A response candidate from the model\n */\nexport interface GeminiCandidate {\n content?: GeminiContent;\n finishReason?: string;\n index?: number;\n safetyRatings?: Array<{\n category: string;\n probability: string;\n blocked?: boolean;\n }>;\n citationMetadata?: {\n citations?: Array<{\n startIndex?: number;\n endIndex?: number;\n uri?: string;\n title?: string;\n license?: string;\n publicationDate?: {\n year?: number;\n month?: number;\n day?: number;\n };\n }>;\n };\n tokenCount?: number;\n avgLogprobs?: number;\n}\n\n/**\n * Prompt feedback from the API\n */\nexport interface GeminiPromptFeedback {\n blockReason?: string;\n safetyRatings?: Array<{\n category: string;\n probability: string;\n blocked?: boolean;\n }>;\n}\n\n/**\n * Raw response from Gemini API\n */\nexport interface GeminiRawResponse {\n candidates?: GeminiCandidate[];\n promptFeedback?: GeminiPromptFeedback;\n usageMetadata?: GeminiUsageMetadata;\n modelVersion?: string;\n responseId?: string;\n createTime?: string;\n text?: string;\n functionCalls?: GeminiFunctionCall[];\n}\n\n/**\n * Error information from Gemini API\n */\nexport interface GeminiErrorInfo {\n status?: number;\n code?: number;\n message?: string;\n details?: Array<{\n \"@type\"?: string;\n reason?: string;\n domain?: string;\n metadata?: Record<string, string>;\n }>;\n}\n\n/**\n * Finish reasons returned by Gemini\n */\nexport const FINISH_REASON = {\n FINISH_REASON_UNSPECIFIED: \"FINISH_REASON_UNSPECIFIED\",\n STOP: \"STOP\",\n MAX_TOKENS: \"MAX_TOKENS\",\n SAFETY: \"SAFETY\",\n RECITATION: \"RECITATION\",\n LANGUAGE: \"LANGUAGE\",\n OTHER: \"OTHER\",\n BLOCKLIST: \"BLOCKLIST\",\n PROHIBITED_CONTENT: \"PROHIBITED_CONTENT\",\n SPII: \"SPII\",\n MALFORMED_FUNCTION_CALL: \"MALFORMED_FUNCTION_CALL\",\n IMAGE_SAFETY: \"IMAGE_SAFETY\",\n UNEXPECTED_TOOL_CALL: \"UNEXPECTED_TOOL_CALL\",\n} as const;\n\nexport type GeminiFinishReason =\n (typeof FINISH_REASON)[keyof typeof FINISH_REASON];\n"],"names":["isPlainObject","formatToJsonSchema","isJsonSchema","log","getLogger","defaultLog","random","MODULE","resolved","cachedSdk","STRUCTURED_OUTPUT_TOOL_NAME","DATA_URL_REGEX","MODELS_WITHOUT_TEMPERATURE","isTemperatureDeprecationError","isStructuredOutputUnsupportedError","isBareJsonSchema","STRUCTURED_OUTPUT_SCHEMA_NAME","contentToWire","messageToWire","RETRYABLE_STATUS_CODES","RATE_LIMIT_STATUS_CODE","enforceAdditionalPropertiesFalse","errorForStatus","BadRequestError","AuthenticationError","PermissionDeniedError","NotFoundError","RateLimitError","InternalServerError","jaypieLog","defaultHookRunner","ERROR","initializeClient","formatSystemMessage","placeholders","replacePlaceholders","formatUserMessage","prepareMessages","createTextCompletion","createStructuredCompletion","normalizeResponse","getDefaultModel","randomUtil"],"mappings":";;;;;;;;;;;;;AAAA;;;;;;;;AAQG;AACI,MAAM,MAAM,GAAG;AACpB,IAAA,MAAM,EAAE,QAAQ;AAChB,IAAA,GAAG,EAAE,KAAK;AACV,IAAA,MAAM,EAAE,QAAQ;AAChB,IAAA,IAAI,EAAE,MAAM;AACZ,IAAA,OAAO,EAAE,SAAS;CACV;AAIH,MAAM,KAAK,GAAG;;AAEnB,IAAA,KAAK,EAAE,gBAAgB;AACvB,IAAA,IAAI,EAAE,iBAAiB;AACvB,IAAA,MAAM,EAAE,iBAAiB;AACzB,IAAA,KAAK,EAAE,kBAAkB;AACzB,I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AC1B,GAAG,EAAE,KAAI;AACR,QAAA,OAAO,uBAAuB,QAAQ,CAAA,EAAA,EAAK,QAAQ,CAAA,EAAA,EAAK,SAAS,GAAG;IACtE,CAAC;CACF;;ACjJM,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO;AAE3C,MAAO,aAAc,SAAQ,OAAO,CAAA;IAMxC,WAAA,CAAY,KAAgB,EAAE,OAAa,EAAA;AACzC,QAAA,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC;AACrB,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;AACpB,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI;AAChB,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI;AAChB,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;IACxB;AACD;MAEY,OAAO,GAAG,IAAI,aAAa,CAAC,KAAK;;ACtB9C;AACA;AACA;AACA;CAEkE;AAChE,IAAA,CAAC,cAAc,CAAC,IAAI,GAAG,MAAM;AAC7B,IAAA,CAAC,cAAc,CAAC,MAAM,GAAG,MAAM;AAC/B,IAAA,CAAC,cAAc,CAAC,SAAS,GAAG,OAAO;AACnC,IAAA,CAAC,cAAc,CAAC,SAAS,GAAG,MAAM;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/constants.ts","../../../src/util/determineModelProvider.ts","../../../src/util/resolveModelChain.ts","../../../src/operate/exchange/buildExchangeEnvelope.ts","../../../src/util/cacheControl.ts","../../../src/util/extractReasoning.ts","../../../src/util/naturalZodSchema.ts","../../../src/util/fillFormatArrays.ts","../../../src/types/LlmProvider.interface.ts","../../../src/util/formatOperateMessage.ts","../../../src/util/formatOperateInput.ts","../../../src/util/jsonSchema.ts","../../../src/util/jsonSchemaToOpenApi3.ts","../../../src/util/logger.ts","../../../src/util/maxOutputTokens.ts","../../../src/util/maxTurnsFromOptions.ts","../../../src/util/random.ts","../../../src/util/repairFormatKeys.ts","../../../src/util/sse.ts","../../../src/util/tallyOperate.ts","../../../src/util/tryParseNumber.ts","../../../src/operate/exchange/emitExchange.ts","../../../src/observability/exchangeStore.ts","../../../src/operate/adapters/ProviderAdapter.interface.ts","../../../src/util/effort.ts","../../../src/types/LlmStreamChunk.interface.ts","../../../src/operate/types.ts","../../../src/operate/retry/isTransientNetworkError.ts","../../../src/util/classifyProviderError.ts","../../../src/operate/adapters/AnthropicAdapter.ts","../../../src/operate/adapters/BedrockAdapter.ts","../../../src/operate/adapters/FireworksAdapter.ts","../../../src/operate/adapters/GoogleAdapter.ts","../../../src/providers/openai/client.ts","../../../src/providers/openai/responseFormat.ts","../../../src/operate/adapters/OpenAiAdapter.ts","../../../src/operate/adapters/OpenRouterAdapter.ts","../../../src/operate/adapters/XaiAdapter.ts","../../../src/tools/Toolkit.class.ts","../../../src/observability/llmobs.ts","../../../src/operate/hooks/HookRunner.ts","../../../src/types/LlmOperateInput.guards.ts","../../../src/upload/detectMimeType.ts","../../../src/upload/extractPdfPages.ts","../../../src/upload/loadLocalFile.ts","../../../src/upload/loadS3File.ts","../../../src/upload/resolveOperateInput.ts","../../../src/operate/input/InputProcessor.ts","../../../src/operate/progress/emitProgress.ts","../../../src/operate/response/ResponseBuilder.ts","../../../src/operate/retry/RetryPolicy.ts","../../../src/operate/retry/createStaleRejectionGuard.ts","../../../src/errors/LlmError.ts","../../../src/errors/toLlmError.ts","../../../src/operate/retry/RetryExecutor.ts","../../../src/operate/OperateLoop.ts","../../../src/operate/StreamLoop.ts","../../../src/providers/anthropic/client.ts","../../../src/providers/anthropic/utils.ts","../../../src/providers/anthropic/types.ts","../../../src/providers/anthropic/AnthropicProvider.class.ts","../../../src/providers/bedrock/utils.ts","../../../src/providers/bedrock/BedrockProvider.class.ts","../../../src/providers/fireworks/client.ts","../../../src/providers/fireworks/utils.ts","../../../src/providers/fireworks/FireworksProvider.class.ts","../../../src/providers/google/client.ts","../../../src/providers/google/utils.ts","../../../src/providers/google/GoogleProvider.class.ts","../../../src/providers/openai/utils.ts","../../../src/providers/openai/OpenAiProvider.class.ts","../../../src/providers/openrouter/client.ts","../../../src/providers/openrouter/utils.ts","../../../src/providers/openrouter/OpenRouterProvider.class.ts","../../../src/providers/xai/utils.ts","../../../src/providers/xai/XaiProvider.class.ts","../../../src/Llm.ts","../../../src/tools/random.ts","../../../src/tools/roll.ts","../../../src/tools/time.ts","../../../src/tools/weather.ts","../../../src/tools/index.ts","../../../src/providers/google/types.ts"],"sourcesContent":["/**\n * Provider-neutral reasoning-effort levels — a five-point relative scale that\n * deliberately borrows no provider's vocabulary. Each adapter translates these\n * to its provider's native control (OpenAI `reasoning.effort`, Anthropic\n * `output_config.effort`, Gemini `thinkingLevel`/`thinkingBudget`, Grok\n * `reasoning_effort`, OpenRouter `reasoning.effort`), spreading the scale across\n * the provider's available range. Omitting `effort` leaves the provider default\n * untouched, so it is safe to set across a fallback chain.\n */\nexport const EFFORT = {\n LOWEST: \"lowest\",\n LOW: \"low\",\n MEDIUM: \"medium\",\n HIGH: \"high\",\n HIGHEST: \"highest\",\n} as const;\n\nexport type LlmEffort = (typeof EFFORT)[keyof typeof EFFORT];\n\nexport const MODEL = {\n // Anthropic\n FABLE: \"claude-fable-5\",\n OPUS: \"claude-opus-4-8\",\n SONNET: \"claude-sonnet-5\",\n HAIKU: \"claude-haiku-4-5\",\n MYTHOS: \"claude-mythos-5\",\n // Fireworks (serverless open models; ids provided by operator)\n FIREWORKS: {\n DEEPSEEK: \"accounts/fireworks/models/deepseek-v4-pro\",\n GLM: \"accounts/fireworks/models/glm-5p2\",\n KIMI: \"accounts/fireworks/models/kimi-k2p7-code\",\n MINIMAX: \"accounts/fireworks/models/minimax-m2p7\",\n QWEN: \"accounts/fireworks/models/qwen3p7-plus\",\n },\n // Google\n GEMINI_FLASH: \"gemini-3.6-flash\",\n GEMINI_FLASH_LITE: \"gemini-3.5-flash-lite\",\n GEMINI_PRO: \"gemini-3.1-pro-preview\",\n // OpenAI\n SOL: \"gpt-5.6-sol\",\n TERRA: \"gpt-5.6-terra\",\n LUNA: \"gpt-5.6-luna\",\n /** @deprecated use MODEL.SOL (gpt-5.6-sol) */\n GPT: \"gpt-5.5\",\n /** @deprecated use MODEL.TERRA (gpt-5.6-terra) */\n GPT_MINI: \"gpt-5.4-mini\",\n /** @deprecated use MODEL.LUNA (gpt-5.6-luna) */\n GPT_NANO: \"gpt-5.4-nano\",\n // xAI\n GROK: \"grok-latest\",\n // OpenRouter (provider-prefixed routes; traversed by the OpenRouter hot test)\n OPENROUTER: {\n GLM: \"z-ai/glm-5.2\",\n LUNA: \"openai/gpt-5.6-luna\",\n SONNET: \"anthropic/claude-sonnet-5\",\n },\n};\n\n/** Price of one million tokens, in US dollars. */\nexport interface LlmModelCost {\n /**\n * Cache-read (cached input) tokens. Omitted when the provider does not price\n * cache reads separately from uncached input.\n */\n cachedInputRead?: number;\n /**\n * Cache-write tokens. A scalar when the rate does not vary by TTL; keyed by\n * the same `\"5m\"` / `\"1h\"` literals as `LlmCache` when it does, so a cost\n * calculation reads the TTL straight off `OperateRequest.cache`. Omitted\n * means cache writes bill at the `input` rate.\n */\n cachedInputWrite?: number | { \"1h\": number; \"5m\": number };\n /** Uncached input tokens. */\n input: number;\n /** Output tokens. */\n output: number;\n /**\n * Reasoning tokens, when billed at a rate other than `output`. Omitted means\n * reasoning bills as output, which is true of every provider listed here.\n */\n reasoning?: number;\n}\n\n/**\n * Standard list price per million tokens, keyed by literal model id (verified\n * 2026-07-21). Keys are string literals rather than `MODEL.*` references so a\n * model retired from the catalog keeps its price here: historic ids stay\n * priceable after they leave `MODEL.*`, which is what makes replaying old\n * usage records possible.\n *\n * Caveats the numbers cannot carry:\n * - **Standard rate only.** Introductory, batch, flex, priority, fast-mode, and\n * data-residency rates are excluded. Sonnet 5 is listed at its standard\n * $3/$15, not the introductory rate.\n * - **Cache writes are Anthropic-only.** Fireworks writes bill at the input\n * rate. OpenAI and xAI discount reads automatically and publish no write\n * premium. Google charges nothing to write an implicit cache; explicit\n * caching bills storage per hour, a unit this table does not carry (and one\n * `@jaypie/llm` does not wire).\n * - **Short-context tier.** Long-prompt surcharges are not modeled: Gemini 3.1\n * Pro doubles above 200K, Grok doubles at 200K, GPT-5.5 is 2x in / 1.5x out\n * above 272K.\n * - **Text rates.** Gemini prices audio input higher than text/image/video.\n * - **Proxies are deliberately absent.** Bedrock (`PROVIDER.BEDROCK.*`) and\n * OpenRouter (`MODEL.OPENROUTER.*`) resell many vendors and price per backend\n * route, so no single rate is correct for a proxy id. Price those against the\n * backend model, or against the proxy's own published rate.\n *\n * Unlisted ids return `undefined` — callers must handle a miss.\n */\nexport const COST: Record<string, LlmModelCost> = {\n // Anthropic — https://platform.claude.com/docs/en/about-claude/pricing\n \"claude-3-5-haiku-20241022\": {\n cachedInputRead: 0.08,\n cachedInputWrite: { \"1h\": 1.6, \"5m\": 1.0 },\n input: 0.8,\n output: 4.0,\n },\n \"claude-fable-5\": {\n cachedInputRead: 1.0,\n cachedInputWrite: { \"1h\": 20.0, \"5m\": 12.5 },\n input: 10.0,\n output: 50.0,\n },\n \"claude-haiku-4-5\": {\n cachedInputRead: 0.1,\n cachedInputWrite: { \"1h\": 2.0, \"5m\": 1.25 },\n input: 1.0,\n output: 5.0,\n },\n \"claude-mythos-5\": {\n cachedInputRead: 1.0,\n cachedInputWrite: { \"1h\": 20.0, \"5m\": 12.5 },\n input: 10.0,\n output: 50.0,\n },\n \"claude-opus-4-1\": {\n cachedInputRead: 1.5,\n cachedInputWrite: { \"1h\": 30.0, \"5m\": 18.75 },\n input: 15.0,\n output: 75.0,\n },\n \"claude-opus-4-5\": {\n cachedInputRead: 0.5,\n cachedInputWrite: { \"1h\": 10.0, \"5m\": 6.25 },\n input: 5.0,\n output: 25.0,\n },\n \"claude-opus-4-6\": {\n cachedInputRead: 0.5,\n cachedInputWrite: { \"1h\": 10.0, \"5m\": 6.25 },\n input: 5.0,\n output: 25.0,\n },\n \"claude-opus-4-7\": {\n cachedInputRead: 0.5,\n cachedInputWrite: { \"1h\": 10.0, \"5m\": 6.25 },\n input: 5.0,\n output: 25.0,\n },\n \"claude-opus-4-8\": {\n cachedInputRead: 0.5,\n cachedInputWrite: { \"1h\": 10.0, \"5m\": 6.25 },\n input: 5.0,\n output: 25.0,\n },\n \"claude-sonnet-4-20250514\": {\n cachedInputRead: 0.3,\n cachedInputWrite: { \"1h\": 6.0, \"5m\": 3.75 },\n input: 3.0,\n output: 15.0,\n },\n \"claude-sonnet-4-5\": {\n cachedInputRead: 0.3,\n cachedInputWrite: { \"1h\": 6.0, \"5m\": 3.75 },\n input: 3.0,\n output: 15.0,\n },\n \"claude-sonnet-4-6\": {\n cachedInputRead: 0.3,\n cachedInputWrite: { \"1h\": 6.0, \"5m\": 3.75 },\n input: 3.0,\n output: 15.0,\n },\n \"claude-sonnet-5\": {\n cachedInputRead: 0.3,\n cachedInputWrite: { \"1h\": 6.0, \"5m\": 3.75 },\n input: 3.0,\n output: 15.0,\n },\n // Fireworks — https://docs.fireworks.ai/serverless/pricing\n \"accounts/fireworks/models/deepseek-v4-pro\": {\n cachedInputRead: 0.145,\n input: 1.74,\n output: 3.48,\n },\n \"accounts/fireworks/models/glm-5p2\": {\n cachedInputRead: 0.14,\n input: 1.4,\n output: 4.4,\n },\n \"accounts/fireworks/models/kimi-k2p7-code\": {\n cachedInputRead: 0.19,\n input: 0.95,\n output: 4.0,\n },\n \"accounts/fireworks/models/minimax-m2p7\": {\n cachedInputRead: 0.06,\n input: 0.3,\n output: 1.2,\n },\n \"accounts/fireworks/models/qwen3p7-plus\": {\n cachedInputRead: 0.08,\n input: 0.4,\n output: 1.6,\n },\n // Google — https://ai.google.dev/gemini-api/docs/pricing\n \"gemini-2.5-flash\": { cachedInputRead: 0.03, input: 0.3, output: 2.5 },\n \"gemini-3.1-flash-lite\": {\n cachedInputRead: 0.025,\n input: 0.25,\n output: 1.5,\n },\n \"gemini-3.1-flash-lite-preview\": {\n cachedInputRead: 0.025,\n input: 0.25,\n output: 1.5,\n },\n \"gemini-3.1-pro-preview\": { cachedInputRead: 0.2, input: 2.0, output: 12.0 },\n \"gemini-3.5-flash\": { cachedInputRead: 0.15, input: 1.5, output: 9.0 },\n // Flash-Lite 3.5 has no separate cache-read rate on the standard tier\n \"gemini-3.5-flash-lite\": { input: 0.3, output: 2.5 },\n \"gemini-3.6-flash\": { cachedInputRead: 0.15, input: 1.5, output: 7.5 },\n // OpenAI — https://developers.openai.com/api/docs/pricing\n \"gpt-5.4\": { cachedInputRead: 0.25, input: 2.5, output: 15.0 },\n \"gpt-5.4-mini\": { cachedInputRead: 0.075, input: 0.75, output: 4.5 },\n \"gpt-5.4-nano\": { cachedInputRead: 0.02, input: 0.2, output: 1.25 },\n \"gpt-5.5\": { cachedInputRead: 0.5, input: 5.0, output: 30.0 },\n \"gpt-5.6-luna\": { cachedInputRead: 0.1, input: 1.0, output: 6.0 },\n \"gpt-5.6-sol\": { cachedInputRead: 0.5, input: 5.0, output: 30.0 },\n \"gpt-5.6-terra\": { cachedInputRead: 0.25, input: 2.5, output: 15.0 },\n // xAI — https://docs.x.ai/docs/models (\"grok-latest\" aliases grok-4.3-latest)\n \"grok-4-1-fast-non-reasoning\": {\n cachedInputRead: 0.05,\n input: 0.2,\n output: 0.5,\n },\n \"grok-4-1-fast-reasoning\": {\n cachedInputRead: 0.05,\n input: 0.2,\n output: 0.5,\n },\n \"grok-latest\": { cachedInputRead: 0.2, input: 1.25, output: 2.5 },\n};\n\nconst GOOGLE_PROVIDER = {\n // https://ai.google.dev/gemini-api/docs/models\n DEFAULT: MODEL.GEMINI_FLASH,\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.GOOGLE.DEFAULT, or pick a specific model from MODEL.*. */\n MODEL: {\n DEFAULT: \"gemini-3.1-pro-preview\",\n LARGE: \"gemini-3.1-pro-preview\",\n SMALL: \"gemini-3.5-flash\",\n TINY: \"gemini-3.1-flash-lite\",\n },\n MODEL_MATCH_WORDS: [\"gemini\", \"google\"] as const,\n NAME: \"google\" as const,\n ROLE: {\n MODEL: \"model\" as const,\n USER: \"user\" as const,\n },\n} as const;\n\nexport const PROVIDER = {\n // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html\n BEDROCK: {\n // Bedrock has no MODEL.* catalog entry yet; keep the literal default id.\n // nova-pro is the Amazon-native model that reliably does tools+structured.\n DEFAULT: \"amazon.nova-pro-v1:0\" as const,\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.BEDROCK.DEFAULT. */\n MODEL: {\n DEFAULT: \"amazon.nova-lite-v1:0\" as const,\n LARGE: \"amazon.nova-pro-v1:0\" as const,\n SMALL: \"amazon.nova-lite-v1:0\" as const,\n TINY: \"amazon.nova-micro-v1:0\" as const,\n },\n MODEL_MATCH_WORDS: [\n \"amazon.nova\",\n \"amazon.titan\",\n \"anthropic.claude\",\n \"cohere.command\",\n \"meta.llama\",\n \"mistral.mistral\",\n \"ai21.\",\n ] as const,\n NAME: \"bedrock\" as const,\n REGION: \"AWS_REGION\" as const,\n },\n ANTHROPIC: {\n // https://docs.anthropic.com/en/docs/about-claude/models/overview\n DEFAULT: MODEL.SONNET,\n MAX_TOKENS: {\n // Non-streaming ceiling: responses above ~16K output tokens risk HTTP\n // timeouts; streaming requests resolve to the model maximum instead\n // (see util/maxOutputTokens.ts)\n DEFAULT: 16384 as const,\n },\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.ANTHROPIC.DEFAULT, or pick a specific model from MODEL.*. */\n MODEL: {\n DEFAULT: \"claude-sonnet-4-6\",\n LARGE: \"claude-opus-4-8\",\n SMALL: \"claude-sonnet-4-6\",\n TINY: \"claude-haiku-4-5\",\n },\n MODEL_MATCH_WORDS: [\n \"anthropic\",\n \"claude\",\n \"fable\",\n \"haiku\",\n \"mythos\",\n \"opus\",\n \"sonnet\",\n ] as const,\n NAME: \"anthropic\" as const,\n PROMPT: {\n AI: \"\\n\\nAssistant:\" as const,\n HUMAN: \"\\n\\nHuman:\" as const,\n },\n ROLE: {\n ASSISTANT: \"assistant\" as const,\n SYSTEM: \"system\" as const,\n USER: \"user\" as const,\n },\n TOOLS: {\n SCHEMA_VERSION: \"v2\" as const,\n },\n },\n FIREWORKS: {\n // https://docs.fireworks.ai/\n API_KEY: \"FIREWORKS_API_KEY\" as const,\n BASE_URL: \"https://api.fireworks.ai/inference/v1\" as const,\n DEFAULT: MODEL.FIREWORKS.GLM,\n MODEL_MATCH_WORDS: [\"fireworks\"] as const,\n NAME: \"fireworks\" as const,\n },\n /** @deprecated Use PROVIDER.GOOGLE — \"Google\" is the provider; Gemini is the model family */\n GEMINI: GOOGLE_PROVIDER,\n GOOGLE: GOOGLE_PROVIDER,\n OPENAI: {\n // https://platform.openai.com/docs/models\n DEFAULT: MODEL.SOL,\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.OPENAI.DEFAULT, or pick a specific model from MODEL.*. */\n MODEL: {\n DEFAULT: \"gpt-5.4\",\n LARGE: \"gpt-5.5\",\n SMALL: \"gpt-5.4-mini\",\n TINY: \"gpt-5.4-nano\",\n },\n MODEL_MATCH_WORDS: [\"gpt\", \"luna\", \"openai\", \"sol\", \"terra\", /^o\\d/],\n NAME: \"openai\" as const,\n },\n OPENROUTER: {\n DEFAULT: MODEL.OPENROUTER.SONNET,\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.OPENROUTER.DEFAULT, or pick a specific route from MODEL.OPENROUTER.*. */\n MODEL: {\n DEFAULT: \"anthropic/claude-sonnet-4-6\" as const,\n LARGE: \"anthropic/claude-opus-4-8\" as const,\n SMALL: \"anthropic/claude-sonnet-4-6\" as const,\n TINY: \"anthropic/claude-haiku-4-5\" as const,\n },\n MODEL_MATCH_WORDS: [\"openrouter\"] as const,\n NAME: \"openrouter\" as const,\n ROLE: {\n ASSISTANT: \"assistant\" as const,\n SYSTEM: \"system\" as const,\n TOOL: \"tool\" as const,\n USER: \"user\" as const,\n },\n },\n XAI: {\n // https://docs.x.ai/docs/models\n API_KEY: \"XAI_API_KEY\" as const,\n BASE_URL: \"https://api.x.ai/v1\" as const,\n DEFAULT: MODEL.GROK,\n /** @deprecated Size tiers are retired in 2.0. Use PROVIDER.XAI.DEFAULT, or pick a specific model from MODEL.*. */\n MODEL: {\n DEFAULT: \"grok-latest\",\n LARGE: \"grok-latest\",\n SMALL: \"grok-4-1-fast-reasoning\",\n TINY: \"grok-4-1-fast-non-reasoning\",\n },\n MODEL_MATCH_WORDS: [\"grok\", \"xai\"] as const,\n NAME: \"xai\" as const,\n },\n} as const;\n\nexport type LlmProviderName =\n | typeof PROVIDER.ANTHROPIC.NAME\n | typeof PROVIDER.BEDROCK.NAME\n | typeof PROVIDER.FIREWORKS.NAME\n | typeof PROVIDER.GOOGLE.NAME\n | typeof PROVIDER.OPENAI.NAME\n | typeof PROVIDER.OPENROUTER.NAME\n | typeof PROVIDER.XAI.NAME;\n\n// Last: Defaults\nexport const DEFAULT = {\n /** @deprecated Size tiers are retired in 2.0. Use DEFAULT.PROVIDER.DEFAULT, or pick a specific model from MODEL.*. */\n MODEL: {\n BASE: PROVIDER.OPENAI.MODEL.DEFAULT,\n LARGE: PROVIDER.OPENAI.MODEL.LARGE,\n SMALL: PROVIDER.OPENAI.MODEL.SMALL,\n TINY: PROVIDER.OPENAI.MODEL.TINY,\n },\n PROVIDER: PROVIDER.OPENAI,\n} as const;\n\n/**\n * @deprecated Size-tier catalogs are retired in 2.0. Pick specific models from\n * MODEL.* (grouped by provider via MODEL_MATCH_WORDS / determineModelProvider).\n */\n// Only include \"first class\" models, not OpenRouter or other proxy services\nexport const ALL = {\n BASE: [\n PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n PROVIDER.GOOGLE.MODEL.DEFAULT,\n PROVIDER.OPENAI.MODEL.DEFAULT,\n PROVIDER.XAI.MODEL.DEFAULT,\n ],\n COMBINED: [\n ...new Set([\n PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n PROVIDER.ANTHROPIC.MODEL.LARGE,\n PROVIDER.ANTHROPIC.MODEL.SMALL,\n PROVIDER.ANTHROPIC.MODEL.TINY,\n PROVIDER.GOOGLE.MODEL.DEFAULT,\n PROVIDER.GOOGLE.MODEL.LARGE,\n PROVIDER.GOOGLE.MODEL.SMALL,\n PROVIDER.GOOGLE.MODEL.TINY,\n PROVIDER.OPENAI.MODEL.DEFAULT,\n PROVIDER.OPENAI.MODEL.LARGE,\n PROVIDER.OPENAI.MODEL.SMALL,\n PROVIDER.OPENAI.MODEL.TINY,\n PROVIDER.XAI.MODEL.DEFAULT,\n PROVIDER.XAI.MODEL.LARGE,\n PROVIDER.XAI.MODEL.SMALL,\n PROVIDER.XAI.MODEL.TINY,\n ]),\n ],\n LARGE: [\n PROVIDER.ANTHROPIC.MODEL.LARGE,\n PROVIDER.GOOGLE.MODEL.LARGE,\n PROVIDER.OPENAI.MODEL.LARGE,\n PROVIDER.XAI.MODEL.LARGE,\n ],\n SMALL: [\n PROVIDER.ANTHROPIC.MODEL.SMALL,\n PROVIDER.GOOGLE.MODEL.SMALL,\n PROVIDER.OPENAI.MODEL.SMALL,\n PROVIDER.XAI.MODEL.SMALL,\n ],\n TINY: [\n PROVIDER.ANTHROPIC.MODEL.TINY,\n PROVIDER.GOOGLE.MODEL.TINY,\n PROVIDER.OPENAI.MODEL.TINY,\n PROVIDER.XAI.MODEL.TINY,\n ],\n} as const;\n","import { DEFAULT, PROVIDER } from \"../constants\";\n\nexport function determineModelProvider(input?: string): {\n model: string;\n provider?: string;\n} {\n if (!input) {\n return {\n model: DEFAULT.PROVIDER.DEFAULT,\n provider: DEFAULT.PROVIDER.NAME,\n };\n }\n\n // Check for explicit openrouter: prefix\n if (input.startsWith(\"openrouter:\")) {\n const model = input.slice(\"openrouter:\".length);\n return {\n model,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n\n // Check for explicit fireworks: prefix\n if (input.startsWith(\"fireworks:\")) {\n const model = input.slice(\"fireworks:\".length);\n return {\n model,\n provider: PROVIDER.FIREWORKS.NAME,\n };\n }\n\n // Check for explicit bedrock: prefix\n if (input.startsWith(\"bedrock:\")) {\n const model = input.slice(\"bedrock:\".length);\n return {\n model,\n provider: PROVIDER.BEDROCK.NAME,\n };\n }\n\n // Check if input is a provider name\n if (input === PROVIDER.BEDROCK.NAME) {\n return {\n model: PROVIDER.BEDROCK.DEFAULT,\n provider: PROVIDER.BEDROCK.NAME,\n };\n }\n if (input === PROVIDER.FIREWORKS.NAME) {\n return {\n model: PROVIDER.FIREWORKS.DEFAULT,\n provider: PROVIDER.FIREWORKS.NAME,\n };\n }\n if (input === PROVIDER.ANTHROPIC.NAME) {\n return {\n model: PROVIDER.ANTHROPIC.DEFAULT,\n provider: PROVIDER.ANTHROPIC.NAME,\n };\n }\n if (input === PROVIDER.GOOGLE.NAME || input === \"gemini\") {\n return {\n model: PROVIDER.GOOGLE.DEFAULT,\n provider: PROVIDER.GOOGLE.NAME,\n };\n }\n if (input === PROVIDER.OPENAI.NAME) {\n return {\n model: PROVIDER.OPENAI.DEFAULT,\n provider: PROVIDER.OPENAI.NAME,\n };\n }\n if (input === PROVIDER.OPENROUTER.NAME) {\n return {\n model: PROVIDER.OPENROUTER.DEFAULT,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n if (input === PROVIDER.XAI.NAME) {\n return {\n model: PROVIDER.XAI.DEFAULT,\n provider: PROVIDER.XAI.NAME,\n };\n }\n\n // Exact model ids are classified by the \"/\" rule and MODEL_MATCH_WORDS below,\n // so no per-provider id catalog is consulted here.\n\n // Check Fireworks match words before the \"/\" rule — Fireworks ids contain\n // \"/\" (e.g., \"accounts/fireworks/models/glm-5p2\") and would otherwise route\n // to OpenRouter\n const lowerInputEarly = input.toLowerCase();\n for (const matchWord of PROVIDER.FIREWORKS.MODEL_MATCH_WORDS) {\n if (lowerInputEarly.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.FIREWORKS.NAME,\n };\n }\n }\n\n // Assume OpenRouter for models containing \"/\" (e.g., \"openai/gpt-4\", \"anthropic/claude-3-opus\")\n // This check must come before match words so that \"openai/gpt-4\" is not matched by \"openai\" keyword\n if (input.includes(\"/\")) {\n return {\n model: input,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n\n // Check Bedrock match words (before Anthropic — \"anthropic.claude-*\" is a Bedrock model ID)\n const lowerInput = input.toLowerCase();\n for (const matchWord of PROVIDER.BEDROCK.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.BEDROCK.NAME,\n };\n }\n }\n\n // Check Anthropic match words\n for (const matchWord of PROVIDER.ANTHROPIC.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.ANTHROPIC.NAME,\n };\n }\n }\n\n // Check Gemini match words\n for (const matchWord of PROVIDER.GOOGLE.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.GOOGLE.NAME,\n };\n }\n }\n\n // Check OpenAI match words\n for (const matchWord of PROVIDER.OPENAI.MODEL_MATCH_WORDS) {\n if (typeof matchWord === \"string\") {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.OPENAI.NAME,\n };\n }\n } else if (matchWord instanceof RegExp) {\n if (matchWord.test(input)) {\n return {\n model: input,\n provider: PROVIDER.OPENAI.NAME,\n };\n }\n }\n }\n\n // Check xAI match words\n for (const matchWord of PROVIDER.XAI.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.XAI.NAME,\n };\n }\n }\n\n // Check OpenRouter match words\n for (const matchWord of PROVIDER.OPENROUTER.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n }\n\n // Default fallback if model not recognized\n return {\n model: input,\n };\n}\n","import { ConfigurationError } from \"@jaypie/errors\";\nimport { LlmFallbackConfig } from \"../types/LlmProvider.interface.js\";\nimport { determineModelProvider } from \"./determineModelProvider.js\";\n\n/**\n * Normalizes a `model` option that may be a single model name or a\n * preference-ordered array of model names.\n *\n * A `string[]` is interpreted as a fallback chain: index `0` is the primary\n * model, indices `1..` become fallback entries with an auto-detected provider\n * (reusing `determineModelProvider`, exactly as the constructor's first\n * argument does).\n *\n * Returns the primary model plus the derived fallback chain. A bare string\n * yields an empty chain and is unchanged.\n */\nexport function resolveModelChain(model?: string | string[]): {\n model?: string;\n fallback: LlmFallbackConfig[];\n} {\n if (!Array.isArray(model)) {\n return { fallback: [], model };\n }\n\n if (model.length === 0) {\n throw new ConfigurationError(\n \"model array must contain at least one model name\",\n );\n }\n\n const [primary, ...rest] = model;\n const fallback = rest.map((name) => {\n const determined = determineModelProvider(name);\n if (!determined.provider) {\n throw new ConfigurationError(\n `Unable to determine provider from model: ${name}`,\n );\n }\n return { model: determined.model, provider: determined.provider };\n });\n\n return { fallback, model: primary };\n}\n","import {\n LlmExchangeEnvelope,\n LlmHistory,\n LlmInputMessage,\n LlmOperateInput,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { OperateLoopState } from \"../types.js\";\n\n//\n//\n// Helpers\n//\n\nfunction sumUsageByProviderModel(\n usage: LlmUsageItem[],\n): Record<string, LlmUsageItem> | undefined {\n if (!usage.length) {\n return undefined;\n }\n const totals: Record<string, LlmUsageItem> = {};\n for (const item of usage) {\n const key = `${item.provider ?? \"unknown\"}:${item.model ?? \"unknown\"}`;\n if (!totals[key]) {\n totals[key] = {\n input: 0,\n model: item.model,\n output: 0,\n provider: item.provider,\n reasoning: 0,\n total: 0,\n };\n }\n totals[key].input += item.input;\n totals[key].output += item.output;\n totals[key].reasoning += item.reasoning;\n totals[key].total += item.total;\n if (item.cacheRead !== undefined) {\n totals[key].cacheRead = (totals[key].cacheRead ?? 0) + item.cacheRead;\n }\n if (item.cacheWrite !== undefined) {\n totals[key].cacheWrite = (totals[key].cacheWrite ?? 0) + item.cacheWrite;\n }\n }\n return totals;\n}\n\nfunction extractResponseIds(responses: unknown[]): string[] | undefined {\n const ids = responses\n .map((response) =>\n response && typeof response === \"object\"\n ? (response as { id?: unknown }).id\n : undefined,\n )\n .filter((id): id is string => typeof id === \"string\");\n return ids.length ? ids : undefined;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Assemble the serializable exchange envelope for one operate() settlement.\n * The `resolution` block is stamped by the Llm facade, which is the layer\n * that knows fallback outcome; the loop fills provider/model best-effort.\n */\nexport function buildExchangeEnvelope({\n duration,\n initialHistoryLength,\n input,\n options,\n response,\n startedAt,\n state,\n}: {\n duration: number;\n initialHistoryLength: number;\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput;\n options: LlmOperateOptions;\n response: LlmOperateResponse;\n startedAt: string;\n state: OperateLoopState;\n}): LlmExchangeEnvelope {\n const historyDelta = response.history.slice(initialHistoryLength);\n return {\n ids: extractResponseIds(response.responses),\n request: {\n cache: options.cache,\n data: options.data,\n effort: options.effort,\n explain: options.explain,\n format: state.formattedFormat,\n input,\n instructions: options.instructions,\n model: options.model,\n placeholders: options.placeholders,\n providerOptions: options.providerOptions,\n system: options.system,\n temperature: options.temperature,\n tools: state.formattedTools?.map(({ name }) => name),\n turns: options.turns,\n user: options.user,\n },\n resolution: {\n model: response.model,\n provider: response.provider,\n retries: state.retries,\n },\n response: {\n content: response.content,\n error: response.error,\n historyDelta,\n reasoning: response.reasoning,\n status: response.status,\n stopReason: state.lastStopReason,\n usage: response.usage,\n usageTotals: sumUsageByProviderModel(response.usage),\n },\n timing: {\n duration,\n startedAt,\n },\n };\n}\n","import { type LlmCache } from \"../types/LlmProvider.interface.js\";\n\nexport const CACHE_TTL_DEFAULT = \"5m\" as const;\n\nexport type CacheTtl = \"5m\" | \"1h\";\n\nexport interface ResolvedCache {\n enabled: boolean;\n ttl: CacheTtl;\n}\n\n/**\n * Normalize the caller-facing `cache` option into a concrete decision.\n * - `undefined` / `true` → enabled at the default TTL\n * - `false` / `0` → disabled\n * - `\"5m\"` / `\"1h\"` → enabled at that TTL\n */\nexport function resolveCache(cache: LlmCache | undefined): ResolvedCache {\n if (cache === false || cache === 0) {\n return { enabled: false, ttl: CACHE_TTL_DEFAULT };\n }\n if (cache === \"5m\" || cache === \"1h\") {\n return { enabled: true, ttl: cache };\n }\n // undefined or true\n return { enabled: true, ttl: CACHE_TTL_DEFAULT };\n}\n\n/**\n * Deterministic short key for providers with automatic, prefix-based caching\n * (e.g. OpenAI `prompt_cache_key`). Derived from the stable prefix so the same\n * system prompt + tools + model always routes to the same cache. Dependency-\n * free FNV-1a; not cryptographic.\n */\nexport function promptCacheKey(seed: string): string {\n let hash = 0x811c9dc5;\n for (let i = 0; i < seed.length; i += 1) {\n hash ^= seed.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return `jaypie-${(hash >>> 0).toString(16)}`;\n}\n","import { LlmHistory } from \"../types/LlmProvider.interface.js\";\n\n/**\n * Represents a reasoning item with optional summary array (OpenAI format).\n * This type is used internally for type-safe access to reasoning-specific properties.\n */\ninterface ReasoningItem {\n content?: string;\n id?: string;\n summary?: Array<{ text?: string }>;\n type: \"reasoning\";\n}\n\n/**\n * Represents a thinking item (Anthropic format).\n * Anthropic extended thinking uses `thinking` blocks with type \"thinking\".\n */\ninterface ThinkingItem {\n thinking?: string;\n type: \"thinking\";\n}\n\n/**\n * Represents a message item that may contain a reasoning property.\n * Used by some providers like OpenRouter/z-ai that include reasoning as a message property.\n */\ninterface MessageWithReasoning {\n reasoning?: string;\n role?: string;\n type?: string;\n}\n\n/**\n * Type guard to check if an item is a dedicated reasoning item (OpenAI)\n */\nfunction isReasoningItem(item: unknown): item is ReasoningItem {\n return (\n typeof item === \"object\" &&\n item !== null &&\n (item as { type?: string }).type === \"reasoning\"\n );\n}\n\n/**\n * Type guard to check if an item is a thinking item (Anthropic)\n */\nfunction isThinkingItem(item: unknown): item is ThinkingItem {\n return (\n typeof item === \"object\" &&\n item !== null &&\n (item as { type?: string }).type === \"thinking\" &&\n typeof (item as ThinkingItem).thinking === \"string\"\n );\n}\n\n/**\n * Type guard to check if an item has a reasoning property\n */\nfunction hasReasoningProperty(item: unknown): item is MessageWithReasoning {\n return (\n typeof item === \"object\" &&\n item !== null &&\n typeof (item as MessageWithReasoning).reasoning === \"string\" &&\n (item as MessageWithReasoning).reasoning !== \"\"\n );\n}\n\n/**\n * Extracts reasoning text from LLM history items.\n *\n * Reasoning items may have text in different locations depending on the provider:\n * - OpenAI: `summary` array with objects containing `text` property (type: \"reasoning\")\n * - OpenAI: `content` property on reasoning items (type: \"reasoning\")\n * - Anthropic: `thinking` property on thinking items (type: \"thinking\")\n * - OpenRouter/z-ai: `reasoning` property on message items\n *\n * @param history - The LLM history array to extract reasoning from\n * @returns Array of reasoning text strings\n */\nexport function extractReasoning(history: LlmHistory): string[] {\n const reasoningTexts: string[] = [];\n\n for (const item of history) {\n // Cast to unknown first for type checking\n const entry = item as unknown;\n\n // Handle dedicated reasoning items (OpenAI extended thinking)\n if (isReasoningItem(entry)) {\n // Handle summary array format\n if (Array.isArray(entry.summary)) {\n for (const summaryItem of entry.summary) {\n if (summaryItem?.text && typeof summaryItem.text === \"string\") {\n reasoningTexts.push(summaryItem.text);\n }\n }\n }\n\n // Handle direct content format\n if (entry.content && typeof entry.content === \"string\") {\n reasoningTexts.push(entry.content);\n }\n }\n\n // Handle thinking items (Anthropic extended thinking)\n if (isThinkingItem(entry)) {\n reasoningTexts.push(entry.thinking!);\n }\n\n // Handle reasoning property on message items (OpenRouter/z-ai format)\n if (hasReasoningProperty(entry)) {\n reasoningTexts.push(entry.reasoning!);\n }\n }\n\n return reasoningTexts;\n}\n","import { z } from \"zod/v4\";\nimport { NaturalSchema } from \"@jaypie/types\";\n\nexport function naturalZodSchema(definition: NaturalSchema): z.ZodTypeAny {\n if (Array.isArray(definition)) {\n if (definition.length === 0) {\n // Handle empty array - accept any[]\n return z.array(z.any());\n } else if (definition.length === 1) {\n // Handle array types\n const itemType = definition[0];\n switch (itemType) {\n case String:\n return z.array(z.string());\n case Number:\n return z.array(z.number());\n case Boolean:\n return z.array(z.boolean());\n default:\n if (typeof itemType === \"object\") {\n // Handle array of objects\n return z.array(naturalZodSchema(itemType));\n }\n // Handle enum arrays\n return z.enum(definition as [string, ...string[]]);\n }\n } else {\n // Handle enum arrays\n return z.enum(definition as [string, ...string[]]);\n }\n } else if (definition && typeof definition === \"object\") {\n if (Object.keys(definition).length === 0) {\n // Handle empty object - accept any key-value pairs\n return z.record(z.string(), z.any());\n } else {\n // Handle object with properties\n const schemaShape: Record<string, z.ZodTypeAny> = {};\n for (const [key, value] of Object.entries(definition)) {\n schemaShape[key] = naturalZodSchema(value);\n }\n return z.object(schemaShape);\n }\n } else {\n switch (definition) {\n case String:\n return z.string();\n case Number:\n return z.number();\n case Boolean:\n return z.boolean();\n case Object:\n return z.record(z.string(), z.any());\n case Array:\n return z.array(z.any());\n default:\n throw new Error(`Unsupported type: ${definition}`);\n }\n }\n}\n","import { z } from \"zod/v4\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\n\nimport { naturalZodSchema } from \"./naturalZodSchema.js\";\n\n//\n//\n// Types\n//\n\ntype Format = JsonObject | NaturalSchema | z.ZodType;\n\n//\n//\n// Helpers\n//\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Convert a `format` declaration (Zod schema, NaturalSchema, or a JSON Schema\n * JsonObject) into a plain JSON Schema we can walk. Mirrors the conversion the\n * provider adapters perform in `formatOutputSchema`, but without any\n * provider-specific sanitization.\n */\nfunction formatToJsonSchema(format: Format): JsonObject | undefined {\n if (format instanceof z.ZodType) {\n return z.toJSONSchema(format) as JsonObject;\n }\n if (isPlainObject(format) && (format as JsonObject).type === \"json_schema\") {\n const clone = structuredClone(format) as JsonObject;\n clone.type = \"object\";\n return clone;\n }\n try {\n return z.toJSONSchema(\n naturalZodSchema(format as NaturalSchema),\n ) as JsonObject;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Walk a JSON Schema alongside a parsed value, filling any declared array field\n * that is absent (`undefined`/`null`) with `[]`. Recurses into object\n * properties and array items so nested declared arrays are also backfilled.\n */\nfunction fillFromSchema(schema: unknown, value: unknown): unknown {\n if (!isPlainObject(schema)) {\n return value;\n }\n\n const type = schema.type;\n const isArray = type === \"array\" || (type === undefined && \"items\" in schema);\n if (isArray) {\n if (value === undefined || value === null) {\n return [];\n }\n const items = schema.items;\n if (Array.isArray(value) && isPlainObject(items)) {\n return value.map((entry) => fillFromSchema(items, entry));\n }\n return value;\n }\n\n const isObject =\n type === \"object\" || (type === undefined && \"properties\" in schema);\n if (isObject) {\n if (!isPlainObject(value)) {\n return value;\n }\n const properties = schema.properties;\n if (isPlainObject(properties)) {\n for (const [key, propSchema] of Object.entries(properties)) {\n value[key] = fillFromSchema(propSchema, value[key]);\n }\n }\n return value;\n }\n\n return value;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Ensure every array field declared in `format` is present in `content` as an\n * array. A declared `format` is a schema contract: an empty list should surface\n * as `[]`, not be dropped from the response. Some providers/models omit empty\n * array fields entirely, leaving consumers to read `.length` on `undefined`.\n *\n * Only mutates a (cloned) structured object; strings and non-objects pass\n * through untouched.\n */\nexport function fillFormatArrays({\n content,\n format,\n}: {\n content: JsonObject;\n format: Format;\n}): JsonObject {\n const schema = formatToJsonSchema(format);\n if (!schema) {\n return content;\n }\n return fillFromSchema(schema, structuredClone(content)) as JsonObject;\n}\n","import {\n AnyValue,\n JsonObject,\n JsonReturn,\n NaturalMap,\n NaturalSchema,\n} from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\nimport { type LlmEffort } from \"../constants.js\";\nimport { LlmTool } from \"./LlmTool.interface.js\";\nimport { LlmStreamChunk } from \"./LlmStreamChunk.interface.js\";\nimport { Toolkit } from \"../tools/Toolkit.class.js\";\n\n// Enums\n\nexport enum LlmMessageRole {\n Assistant = \"assistant\",\n Developer = \"developer\",\n System = \"system\",\n User = \"user\",\n}\n\nexport enum LlmMessageType {\n FunctionCall = \"function_call\",\n FunctionCallOutput = \"function_call_output\",\n InputFile = \"input_file\",\n InputImage = \"input_image\",\n InputText = \"input_text\",\n ItemReference = \"item_reference\",\n Message = \"message\",\n OutputText = \"output_text\",\n Refusal = \"refusal\",\n}\n\nexport enum LlmResponseStatus {\n Completed = \"completed\",\n Incomplete = \"incomplete\",\n InProgress = \"in_progress\",\n}\n\n// Errors\n\nexport interface LlmError {\n detail?: string;\n status: number | string;\n title: string;\n}\n\n// Input\n\nexport interface LlmInputContentFile {\n type: LlmMessageType.InputFile;\n file_data: File | string;\n file_id?: string;\n filename?: string;\n}\n\nexport interface LlmInputContentImage {\n type: LlmMessageType.InputImage;\n detail?: File;\n file_id?: string;\n image_url?: string;\n}\n\nexport interface LlmInputContentText {\n type: LlmMessageType.InputText;\n text: string;\n}\n\nexport type LlmInputContent =\n LlmInputContentFile | LlmInputContentImage | LlmInputContentText;\n\n/**\n * Represents the \"Input message object\" in the \"input item list\"\n * from [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses/create)\n */\nexport interface LlmInputMessage {\n content: string | Array<LlmInputContent>;\n role: LlmMessageRole;\n type?: LlmMessageType.Message;\n}\n\n// LlmOperateInput - Simplified input format with automatic file resolution\n\n/**\n * File input that can be loaded from local filesystem, S3, or provided as base64 data.\n * For PDFs, specific pages can be extracted via the `pages` property.\n * If the file extension is an image type, it will be treated as an image internally.\n */\nexport interface LlmOperateInputFile {\n /** Path or filename (extension determines type via /\\.(\\w+)$/) */\n file: string;\n /** S3 bucket name (if present, load from S3) */\n bucket?: string;\n /** Specific pages to extract from PDF (omit = all pages) */\n pages?: number[];\n /** Base64 data (if present, use directly instead of loading from file) */\n data?: string;\n}\n\n/**\n * Image input that can be loaded from local filesystem, S3, or provided as base64 data.\n */\nexport interface LlmOperateInputImage {\n /** Path or filename */\n image: string;\n /** S3 bucket name (if present, load from S3) */\n bucket?: string;\n /** Base64 data (if present, use directly instead of loading from file) */\n data?: string;\n}\n\n/**\n * Content item in LlmOperateInput array.\n * Can be a string (text), file object, or image object.\n */\nexport type LlmOperateInputContent =\n string | LlmOperateInputFile | LlmOperateInputImage;\n\n/**\n * Simplified input format for operate() that supports automatic file resolution.\n * Files/images are loaded from local filesystem, S3, or provided data.\n *\n * @example\n * ```typescript\n * const input: LlmOperateInput = [\n * \"Extract text from these documents\",\n * { file: \"document.pdf\", bucket: \"my-bucket\", pages: [1, 2, 3] },\n * { image: \"photo.png\" }, // loads from local filesystem\n * ];\n * ```\n */\nexport type LlmOperateInput = LlmOperateInputContent[];\n\n// Output\nexport interface LlmOutputContentText {\n annotations?: AnyValue[];\n text: string;\n type: LlmMessageType.OutputText;\n}\n\ninterface LlmOutputRefusal {\n refusal: string;\n type: LlmMessageType.Refusal;\n}\n\ntype LlmOutputContent = LlmOutputContentText | LlmOutputRefusal;\n\n/**\n * Represents the \"Output message object\" in the \"input item list\"\n * from [OpenAI Responses API](https://platform.openai.com/docs/api-reference/responses/create)\n */\nexport interface LlmOutputMessage {\n content: string | Array<LlmOutputContent>;\n id?: string;\n role: LlmMessageRole.Assistant;\n status?: LlmResponseStatus;\n type?: LlmMessageType.Message;\n}\n\ntype LlmOutputItem = LlmToolCall | LlmToolResult | LlmOutputMessage;\n\ntype LlmOutput = LlmOutputItem[];\n\n// Tools\n\nexport interface LlmToolCall {\n arguments: string;\n call_id: string;\n id: string;\n name: string;\n type: LlmMessageType.FunctionCall;\n status: LlmResponseStatus;\n}\nexport interface LlmToolResult {\n call_id: string;\n output: string;\n status?: LlmResponseStatus;\n type: LlmMessageType.FunctionCallOutput;\n}\n\ninterface LlmItemReference {\n type: LlmMessageType.ItemReference;\n id: string;\n}\n\n// Options\n\nexport type LlmHistoryItem =\n LlmInputMessage | LlmItemReference | LlmOutputItem | LlmToolResult;\n\nexport type LlmHistory = LlmHistoryItem[];\n\n/**\n * Configuration for a fallback provider.\n * Used when the primary provider fails with an unrecoverable error.\n */\nexport interface LlmFallbackConfig {\n /** Provider name (e.g., \"openai\", \"anthropic\", \"google\") */\n provider: string;\n /** Model to use with this provider (optional, uses provider default if not specified) */\n model?: string;\n /** API key for this provider (optional, uses environment variable if not specified) */\n apiKey?: string;\n}\n\nexport interface LlmMessageOptions {\n data?: NaturalMap;\n model?: string;\n placeholders?: {\n message?: boolean;\n system?: boolean;\n };\n response?: NaturalSchema | z.ZodType;\n system?: string;\n}\n\n// Progress\n\nexport enum LlmProgressEventType {\n Done = \"done\",\n ModelRequest = \"model_request\",\n ModelResponse = \"model_response\",\n Retry = \"retry\",\n Start = \"start\",\n ToolCall = \"tool_call\",\n ToolError = \"tool_error\",\n ToolResult = \"tool_result\",\n}\n\nexport interface LlmProgressToolCall {\n /** JSON string of arguments (tool_call events only) */\n arguments?: string;\n /** Resolved `LlmTool.message`, when the tool defines one (tool_call events only) */\n message?: string;\n /** Tool name */\n name: string;\n}\n\n/**\n * Lightweight, serializable progress event emitted by the operate loop.\n * Suitable for forwarding directly to websockets, queues, or UI updates.\n */\nexport interface LlmProgressEvent {\n /** Text or structured content (model_response, done) */\n content?: string | JsonObject;\n /** Error message (tool_error, retry) */\n error?: string;\n /** Maximum turns allowed for the loop (start) */\n maxTurns?: number;\n /** Model handling the request (start, model_request) */\n model?: string;\n /** Provider name (start) */\n provider?: string;\n /** The tool involved (tool_call, tool_result, tool_error) */\n tool?: LlmProgressToolCall;\n /** Tools the model requested (model_response) */\n toolCalls?: LlmProgressToolCall[];\n /** Current turn, 1-indexed */\n turn?: number;\n /** Event type */\n type: LlmProgressEventType;\n /** Usage: this turn for model_response, cumulative for done */\n usage?: LlmUsage;\n}\n\nexport type LlmProgressCallback = (\n event: LlmProgressEvent,\n) => unknown | Promise<unknown>;\n\n// Exchange\n\n/**\n * Serializable snapshot of the request side of one operate() call.\n * `input` is the raw, pre-interpolation input with multimodal parts preserved.\n */\nexport interface LlmExchangeRequest {\n cache?: LlmCache;\n data?: NaturalMap;\n effort?: LlmEffort;\n explain?: boolean;\n /** Format normalized to JSON Schema (Zod/Natural already rendered) */\n format?: JsonObject;\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput;\n instructions?: string;\n /** Requested model (pre-fallback) */\n model?: string;\n placeholders?: {\n input?: boolean;\n instructions?: boolean;\n system?: boolean;\n };\n providerOptions?: JsonObject;\n system?: string;\n temperature?: number;\n /** Names of tools offered to the model */\n tools?: string[];\n turns?: boolean | number;\n user?: string;\n}\n\n/**\n * Serializable snapshot of the response side of one operate() call.\n */\nexport interface LlmExchangeResponse {\n content?: string | JsonObject;\n error?: LlmError;\n /** Turns this call added to history (tool calls/results included); never the resent history */\n historyDelta: LlmHistory;\n reasoning?: string[];\n status: LlmResponseStatus;\n stopReason?: string;\n /** Per-model-call usage items (provider/model on each item) */\n usage: LlmUsage;\n /** Cumulative usage keyed `provider:model` */\n usageTotals?: Record<string, LlmUsageItem>;\n}\n\n/**\n * How the call was actually served after fallback and retry resolution.\n */\nexport interface LlmExchangeResolution {\n fallbackAttempts?: number;\n fallbackUsed?: boolean;\n /** Served model */\n model?: string;\n /** Served provider */\n provider?: string;\n /** Model-request retries within the served attempt */\n retries?: number;\n}\n\nexport interface LlmExchangeTiming {\n /** Milliseconds from start to settlement */\n duration: number;\n /** ISO 8601 */\n startedAt: string;\n}\n\n/**\n * One serializable request/response envelope per operate() settlement\n * (success or failure). Contains no functions.\n */\nexport interface LlmExchangeEnvelope {\n /** Provider response id(s) per model turn, when available */\n ids?: string[];\n request: LlmExchangeRequest;\n resolution: LlmExchangeResolution;\n response: LlmExchangeResponse;\n timing: LlmExchangeTiming;\n}\n\nexport type LlmExchangeCallback = (\n envelope: LlmExchangeEnvelope,\n) => unknown | Promise<unknown>;\n\n/**\n * Prompt-caching control for operate()/stream().\n * - `true` / omitted → caching enabled at the default `\"5m\"` TTL\n * - `false` / `0` → caching disabled\n * - `\"5m\"` / `\"1h\"` → enabled at that TTL (TTL honored by Anthropic/OpenRouter;\n * other providers ignore it and cache with their own defaults)\n */\nexport type LlmCache = boolean | 0 | \"5m\" | \"1h\";\n\nexport interface LlmOperateOptions {\n /**\n * Prompt caching for the stable request prefix (system prompt + tools).\n * Enabled by default; pass `false`/`0` to opt out, or `\"5m\"`/`\"1h\"` to set\n * the TTL. See {@link LlmCache}.\n */\n cache?: LlmCache;\n data?: NaturalMap;\n /**\n * Provider-neutral reasoning effort (lowest | low | medium | high | highest).\n * Each provider translates it to its native control, spreading the scale\n * across the provider's range; omitting it leaves the provider default\n * untouched, so it is safe across a fallback chain. Providers without\n * reasoning control ignore it.\n */\n effort?: LlmEffort;\n explain?: boolean;\n /** Chain of fallback providers to try if primary fails. Set to false to disable instance-level fallback. */\n fallback?: LlmFallbackConfig[] | false;\n format?: JsonObject | NaturalSchema | z.ZodType;\n history?: LlmHistory;\n hooks?: {\n afterEachModelResponse?: ({\n input,\n options,\n providerRequest,\n providerResponse,\n content,\n usage,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n providerResponse: any;\n content: string | JsonObject;\n usage: LlmUsage;\n }) => unknown | Promise<unknown>;\n afterEachTool?: ({\n result,\n toolName,\n args,\n message,\n }: {\n result: unknown;\n toolName: string;\n args: string;\n /** Resolved `LlmTool.message`, when the tool defines one */\n message?: string;\n }) => unknown | Promise<unknown>;\n beforeEachModelRequest?: ({\n input,\n options,\n providerRequest,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n }) => unknown | Promise<unknown>;\n beforeEachTool?: ({\n toolName,\n args,\n message,\n }: {\n toolName: string;\n args: string;\n /** Resolved `LlmTool.message`, when the tool defines one */\n message?: string;\n }) => unknown | Promise<unknown>;\n onRetryableModelError?: ({\n input,\n options,\n providerRequest,\n error,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n error: any;\n }) => unknown | Promise<unknown>;\n onToolError?: ({\n error,\n toolName,\n args,\n message,\n }: {\n error: Error;\n toolName: string;\n args: string;\n /** Resolved `LlmTool.message`, when the tool defines one */\n message?: string;\n }) => unknown | Promise<unknown>;\n onUnrecoverableModelError?: ({\n input,\n options,\n providerRequest,\n error,\n }: {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: any;\n error: any;\n }) => unknown | Promise<unknown>;\n };\n instructions?: string;\n model?: string;\n /**\n * Fires once per operate() settlement (success or failure) with a fully\n * serializable request/response envelope. Errors thrown by the callback\n * are logged and never interrupt the call.\n */\n onExchange?: LlmExchangeCallback;\n /**\n * Receives lightweight progress events as the operate loop runs:\n * start, model_request, model_response, tool_call, tool_result,\n * tool_error, retry, done. Errors thrown by the callback are logged\n * and never interrupt the loop.\n */\n onProgress?: LlmProgressCallback;\n placeholders?: {\n input?: boolean;\n instructions?: boolean;\n system?: boolean;\n };\n providerOptions?: JsonObject;\n system?: string;\n temperature?: number;\n tools?: LlmTool[] | Toolkit;\n turns?: boolean | number;\n user?: string;\n}\n\n/**\n * A single model name, or a preference-ordered array of model names.\n * An array is interpreted as a fallback chain: index 0 is primary, later\n * entries are tried in order when earlier ones fail (provider auto-detected\n * per entry). Accepted by the `Llm` constructor and static/instance\n * `operate`/`send`/`stream` methods; normalized to a scalar model plus a\n * derived fallback chain before reaching providers.\n */\nexport type LlmModelOption = string | string[];\n\nexport interface LlmOptions {\n apiKey?: string;\n /** Chain of fallback providers to try if primary fails */\n fallback?: LlmFallbackConfig[];\n model?: string;\n}\n\n// Responses\n\nexport interface LlmUsageItem {\n input: number;\n output: number;\n reasoning: number;\n total: number;\n /** Prompt-cache tokens served from cache this call (billed at ~0.1x input) */\n cacheRead?: number;\n /** Prompt-cache tokens written to cache this call (billed at ~1.25x input) */\n cacheWrite?: number;\n provider?: string;\n model?: string;\n}\n\nexport type LlmUsage = LlmUsageItem[];\n\nexport interface LlmOperateResponse {\n content?: string | JsonObject;\n error?: LlmError;\n /**\n * Serializable exchange envelope for this call. Present only when\n * `onExchange` was passed or exchange persistence is enabled.\n */\n exchange?: LlmExchangeEnvelope;\n /** Number of providers attempted (1 = primary only, >1 = fallback(s) used) */\n fallbackAttempts?: number;\n /** Whether a fallback provider was used instead of the primary */\n fallbackUsed?: boolean;\n history: LlmHistory;\n model?: string;\n output: LlmOutput;\n /** Which provider actually handled the request */\n provider?: string;\n reasoning: string[];\n responses: JsonReturn[];\n status: LlmResponseStatus;\n usage: LlmUsage;\n}\n\n// Main\n\nexport interface LlmProvider {\n operate?(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options?: LlmOperateOptions,\n ): Promise<LlmOperateResponse>;\n send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject>;\n stream?(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options?: LlmOperateOptions,\n ): AsyncIterable<LlmStreamChunk>;\n}\n","import { placeholders } from \"@jaypie/kit\";\nimport {\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n} from \"../types/LlmProvider.interface.js\";\nimport { NaturalMap } from \"@jaypie/types\";\n\n/**\n * Options for formatOperateMessage function\n */\nexport interface FormatOperateMessageOptions {\n /**\n * Data to use for placeholder substitution\n */\n data?: NaturalMap;\n\n /**\n * Role to use for the message\n */\n role?: LlmMessageRole;\n}\n\n/**\n * Converts a string to a standardized LlmInputMessage\n * @param input - String to format\n * @param options - Optional configuration\n * @param options.data - Data to use for placeholder substitution\n * @param options.role - Role to use for the message (defaults to User)\n * @returns LlmInputMessage\n */\nexport function formatOperateMessage(\n input: string,\n options?: FormatOperateMessageOptions,\n): LlmInputMessage {\n const content = options?.data ? placeholders(input, options.data) : input;\n\n return {\n content,\n role: options?.role || LlmMessageRole.User,\n type: LlmMessageType.Message,\n };\n}\n","import {\n LlmHistory,\n LlmInputMessage,\n LlmMessageRole,\n} from \"../types/LlmProvider.interface.js\";\nimport { NaturalMap } from \"@jaypie/types\";\nimport { formatOperateMessage } from \"./formatOperateMessage.js\";\n\n/**\n * Options for formatOperateInput function\n */\nexport interface FormatOperateInputOptions {\n /**\n * Data to use for placeholder substitution\n */\n data?: NaturalMap;\n\n /**\n * Role to use when converting a string to LlmInputMessage\n */\n role?: LlmMessageRole;\n}\n\n/**\n * Converts various input types to a standardized LlmHistory format\n * @param input - String, LlmInputMessage, or LlmHistory to format\n * @param options - Optional configuration\n * @param options.data - Data to use for placeholder substitution\n * @param options.role - Role to use when converting a string to LlmInputMessage (defaults to User)\n * @returns Standardized LlmHistory array\n */\nexport function formatOperateInput(\n input: string | LlmInputMessage | LlmHistory,\n options?: FormatOperateInputOptions,\n): LlmHistory {\n // If input is already LlmHistory, return it\n if (Array.isArray(input)) {\n return input;\n }\n\n // If input is a string, convert it to LlmInputMessage\n if (typeof input === \"string\") {\n return [formatOperateMessage(input, options)];\n }\n\n // If input is LlmInputMessage, apply placeholders if data is provided\n if (options?.data && typeof input.content === \"string\") {\n return [\n formatOperateMessage(input.content, {\n data: options.data,\n role: input.role || options?.role,\n }),\n ];\n }\n\n // Otherwise, just wrap the input in an array\n return [input];\n}\n","import log from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema, NaturalSchemaObject } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { naturalZodSchema } from \"./naturalZodSchema.js\";\n\n// Keywords a JSON Schema object node can carry that Natural Schema has no\n// representation for. Anything present here (or any other unrecognized key)\n// is dropped silently and logged, never thrown.\nconst LOSSY_OBJECT_KEYWORDS = [\n \"$defs\",\n \"$id\",\n \"$ref\",\n \"$schema\",\n \"additionalProperties\",\n \"const\",\n \"default\",\n \"description\",\n \"format\",\n \"maxLength\",\n \"maximum\",\n \"minLength\",\n \"minimum\",\n \"multipleOf\",\n \"nullable\",\n \"allOf\",\n \"anyOf\",\n \"oneOf\",\n \"pattern\",\n] as const;\n\nconst KNOWN_KEYWORDS = new Set<string>([\n \"type\",\n \"properties\",\n \"required\",\n \"items\",\n \"enum\",\n ...LOSSY_OBJECT_KEYWORDS,\n]);\n\n/**\n * Duck-type check for a bare JSON Schema object node: `{ type: \"object\", properties: {...} }`.\n * Does not require the OpenAI-style `{ type: \"json_schema\", ... }` envelope.\n */\nexport function isJsonSchema(value: unknown): value is JsonObject {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const schema = value as JsonObject;\n return (\n schema.type === \"object\" &&\n typeof schema.properties === \"object\" &&\n schema.properties !== null &&\n !Array.isArray(schema.properties)\n );\n}\n\n/**\n * Convert a Natural Schema to JSON Schema. Lossless: Natural Schema is a\n * strict subset of what JSON Schema can express.\n */\nexport function naturalSchemaToJsonSchema(schema: NaturalSchema): JsonObject {\n return z.toJSONSchema(naturalZodSchema(schema)) as JsonObject;\n}\n\nfunction logDroppedKeywords(schema: JsonObject, path: string): void {\n for (const key of Object.keys(schema)) {\n if (!KNOWN_KEYWORDS.has(key)) {\n log.debug(\n `[jsonSchemaToNaturalSchema] Dropping unrecognized keyword \"${key}\" at \"${path}\"`,\n );\n } else if (\n (LOSSY_OBJECT_KEYWORDS as readonly string[]).includes(key) &&\n schema[key] !== undefined\n ) {\n log.debug(\n `[jsonSchemaToNaturalSchema] Dropping unsupported keyword \"${key}\" at \"${path}\"`,\n );\n }\n }\n}\n\nfunction convertNode(schema: JsonObject, path: string): NaturalSchema {\n logDroppedKeywords(schema, path);\n\n if (Array.isArray(schema.enum)) {\n return schema.enum as string[];\n }\n\n switch (schema.type) {\n case \"string\":\n return String;\n case \"number\":\n case \"integer\":\n return Number;\n case \"boolean\":\n return Boolean;\n case \"array\": {\n const items = schema.items;\n if (typeof items !== \"object\" || items === null || Array.isArray(items)) {\n return Array;\n }\n return [convertNode(items as JsonObject, `${path}[]`)];\n }\n case \"object\": {\n const properties = schema.properties as\n Record<string, JsonObject> | undefined;\n if (!properties || Object.keys(properties).length === 0) {\n return Object;\n }\n const required = new Set(\n Array.isArray(schema.required) ? (schema.required as string[]) : [],\n );\n const result: NaturalSchemaObject = {};\n for (const [key, value] of Object.entries(properties)) {\n if (!required.has(key)) {\n log.debug(\n `[jsonSchemaToNaturalSchema] Field \"${path}.${key}\" is optional; Natural Schema has no optional marker — treating as required`,\n );\n }\n result[key] = convertNode(value, `${path}.${key}`);\n }\n return result;\n }\n default:\n log.debug(\n `[jsonSchemaToNaturalSchema] Unsupported type \"${String(schema.type)}\" at \"${path}\"; defaulting to Object`,\n );\n return Object;\n }\n}\n\n/**\n * Convert a JSON Schema object node to Natural Schema. Lossy: constraints,\n * descriptions, defaults, unions, and optionality have no Natural Schema\n * representation. Dropped keywords are logged at debug level, never thrown.\n */\nexport function jsonSchemaToNaturalSchema(schema: JsonObject): NaturalSchema {\n return convertNode(schema, \"$\");\n}\n","import { JsonObject } from \"@jaypie/types\";\n\n/**\n * Converts a JSON Schema (Draft 2020-12) object to the OpenAPI 3.0 schema subset\n * that Gemini's `responseSchema` accepts. This constrains generation (not just validation)\n * and avoids the `items`-keyword leakage bug in `responseJsonSchema`.\n *\n * Strips: $schema, additionalProperties, $defs, $ref (inlines where possible), const\n * Preserves: type, properties, required, items, enum, description, nullable\n */\nexport function jsonSchemaToOpenApi3(schema: JsonObject): JsonObject {\n if (typeof schema !== \"object\" || schema === null || Array.isArray(schema)) {\n return schema;\n }\n\n const result: JsonObject = {};\n\n for (const [key, value] of Object.entries(schema)) {\n // Strip JSON Schema keywords not in OpenAPI 3.0 subset\n if (\n key === \"$schema\" ||\n key === \"$defs\" ||\n key === \"additionalProperties\" ||\n key === \"const\" ||\n key === \"$ref\"\n ) {\n continue;\n }\n\n if (\n key === \"properties\" &&\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value)\n ) {\n const convertedProps: JsonObject = {};\n for (const [propKey, propValue] of Object.entries(\n value as Record<string, JsonObject>,\n )) {\n convertedProps[propKey] = jsonSchemaToOpenApi3(propValue);\n }\n result[key] = convertedProps;\n } else if (key === \"items\" && typeof value === \"object\" && value !== null) {\n result[key] = jsonSchemaToOpenApi3(value as JsonObject);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n","import { JAYPIE } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\n\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n","import { PROVIDER } from \"../constants.js\";\n\n//\n//\n// Constants\n//\n\n// Non-streaming requests above ~16K output tokens risk HTTP timeouts\n// (Anthropic guidance is to stream anything larger), so non-streaming\n// defaults are capped here and only streaming requests resolve to the\n// full model maximum.\nconst NON_STREAMING_MAX_TOKENS = PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT;\n\n// Maximum output tokens by model; first match wins.\n// Providers without low output ceilings (OpenAI, xAI) are intentionally\n// absent — their requests leave the limit unset.\nconst MODEL_MAX_OUTPUT_TOKENS: { pattern: RegExp; tokens: number }[] = [\n // Anthropic — https://platform.claude.com/docs/en/about-claude/models/overview\n { pattern: /^claude-opus-4-(0$|1$|1-|2025)/, tokens: 32_000 },\n { pattern: /^claude-opus-4-5/, tokens: 64_000 },\n { pattern: /^claude-sonnet-4-(0$|5$|5-|2025)/, tokens: 64_000 },\n { pattern: /haiku/, tokens: 64_000 },\n { pattern: /claude|fable|mythos|opus|sonnet/, tokens: 128_000 },\n // Google — https://ai.google.dev/gemini-api/docs/models\n { pattern: /gemini-(2\\.5|3)/, tokens: 65_536 },\n { pattern: /gemini/, tokens: 8_192 },\n];\n\n//\n//\n// Main\n//\n\n/**\n * Maximum output tokens the model supports, or undefined when unknown.\n */\nexport function maxOutputTokens(model: string): number | undefined {\n const match = MODEL_MAX_OUTPUT_TOKENS.find(({ pattern }) =>\n pattern.test(model),\n );\n return match?.tokens;\n}\n\n/**\n * Default output token limit for a request: the model maximum when\n * streaming, capped at the non-streaming maximum otherwise. Returns\n * undefined when the model's maximum is unknown.\n */\nexport function resolveMaxOutputTokens(\n model: string,\n { stream = false }: { stream?: boolean } = {},\n): number | undefined {\n const max = maxOutputTokens(model);\n if (max === undefined) return undefined;\n return stream ? max : Math.min(max, NON_STREAMING_MAX_TOKENS);\n}\n","import { LlmOperateOptions } from \"../types/LlmProvider.interface.js\";\n\n// Turn policy constants\nexport const MAX_TURNS_ABSOLUTE_LIMIT = 72;\nexport const MAX_TURNS_DEFAULT_LIMIT = 24;\n\n/**\n * Determines the maximum number of turns based on the provided options\n *\n * @param options - The LLM operate options\n * @returns The maximum number of turns\n */\nexport function maxTurnsFromOptions(options: LlmOperateOptions): number {\n // Default to single turn (1) when turns are disabled\n\n // Handle the turns parameter\n if (options.turns === undefined) {\n // Default to default limit when undefined\n return MAX_TURNS_DEFAULT_LIMIT;\n } else if (options.turns === true) {\n // Explicitly set to true\n return MAX_TURNS_DEFAULT_LIMIT;\n } else if (typeof options.turns === \"number\") {\n if (options.turns > 0) {\n // Positive number - use that limit (capped at absolute limit)\n return Math.min(options.turns, MAX_TURNS_ABSOLUTE_LIMIT);\n } else if (options.turns < 0) {\n // Negative number - use default limit\n return MAX_TURNS_DEFAULT_LIMIT;\n }\n // If turns is 0, return 1 (disabled)\n return 1;\n }\n // All other values (false, null, etc.) will return 1 (disabled)\n return 1;\n}\n","import RandomLib from \"random\";\nimport { ConfigurationError } from \"@jaypie/errors\";\n\n//\n// Types\n//\n\ninterface RandomOptions {\n min?: number;\n max?: number;\n mean?: number;\n stddev?: number;\n integer?: boolean;\n start?: number;\n seed?: string;\n precision?: number;\n currency?: boolean;\n}\n\ntype RandomFunction = {\n (options?: RandomOptions): number;\n};\n\n//\n// Constants\n//\n\nexport const DEFAULT_MIN = 0;\nexport const DEFAULT_MAX = 1;\n\n//\n// Helper Functions\n//\n\n/**\n * Clamps a number between optional minimum and maximum values\n * @param num - The number to clamp\n * @param min - Optional minimum value\n * @param max - Optional maximum value\n * @returns The clamped number\n */\nconst clamp = (num: number, min?: number, max?: number): number => {\n let result = num;\n if (typeof min === \"number\") result = Math.max(result, min);\n if (typeof max === \"number\") result = Math.min(result, max);\n return result;\n};\n\n/**\n * Validates that min is not greater than max\n * @param min - Optional minimum value\n * @param max - Optional maximum value\n * @throws {ConfigurationError} If min is greater than max\n */\nconst validateBounds = (\n min: number | undefined,\n max: number | undefined,\n): void => {\n if (typeof min === \"number\" && typeof max === \"number\" && min > max) {\n throw new ConfigurationError(\n `Invalid bounds: min (${min}) cannot be greater than max (${max})`,\n );\n }\n};\n\n//\n// Main\n//\n\n/**\n * Creates a random number generator with optional seeding\n *\n * @param defaultSeed - Seed string for the default RNG\n * @returns A function that generates random numbers based on provided options\n *\n * @example\n * const rng = random(\"default-seed\");\n *\n * // Generate a random float between 0 and 1\n * const basic = rng();\n *\n * // Generate an integer between 1 and 10\n * const integer = rng({ min: 1, max: 10, integer: true });\n *\n * // Generate from normal distribution\n * const normal = rng({ mean: 50, stddev: 10 });\n *\n * // Use consistent seeding\n * const seeded = rng({ seed: \"my-seed\" });\n */\nexport function random(defaultSeed?: string): RandomFunction {\n // Initialize default seeded RNG\n const defaultRng = RandomLib.clone(defaultSeed);\n\n // Store per-seed RNGs\n const seedMap = new Map<string, ReturnType<typeof RandomLib.clone>>();\n\n const rngFn = ({\n min,\n max: providedMax,\n mean,\n stddev,\n integer = false,\n start = 0,\n seed,\n precision,\n currency = false,\n }: RandomOptions = {}): number => {\n // Select the appropriate RNG based on seed\n const rng = seed\n ? seedMap.get(seed) ||\n (() => {\n const newRng = RandomLib.clone(seed);\n seedMap.set(seed, newRng);\n return newRng;\n })()\n : defaultRng;\n\n // If only min is set, set max to min*2, but keep track of whether max was provided\n let max = providedMax;\n if (typeof min === \"number\" && typeof max !== \"number\") {\n max = min * 2;\n }\n\n validateBounds(min, max);\n\n // Determine effective precision based on parameters\n const getEffectivePrecision = (): number | undefined => {\n if (integer) return 0;\n\n const precisions: number[] = [];\n if (typeof precision === \"number\" && precision >= 0) {\n precisions.push(precision);\n }\n if (currency) {\n precisions.push(2);\n }\n\n // Return the lowest precision if any are set, undefined otherwise\n return precisions.length > 0 ? Math.min(...precisions) : undefined;\n };\n\n // Helper function to apply precision\n const applyPrecision = (value: number): number => {\n const effectivePrecision = getEffectivePrecision();\n if (typeof effectivePrecision === \"number\") {\n const factor = Math.pow(10, effectivePrecision);\n return Math.round(value * factor) / factor;\n }\n return value;\n };\n\n // Use normal distribution if both mean and stddev are provided\n if (typeof mean === \"number\" && typeof stddev === \"number\") {\n const normalDist = rng.normal(mean, stddev);\n const value = normalDist();\n\n // Only clamp if min/max are defined\n const clampedValue = clamp(value, min, providedMax);\n\n // Switch to uniform distribution only if both bounds were explicitly provided and exceeded\n if (\n typeof min === \"number\" &&\n typeof providedMax === \"number\" &&\n clampedValue !== value\n ) {\n const baseValue = integer ? rng.int(min, max) : rng.float(min, max);\n return applyPrecision(start + baseValue);\n }\n\n return applyPrecision(\n start + (integer ? Math.round(clampedValue) : clampedValue),\n );\n }\n\n // For uniform distribution, use defaults if min/max are undefined\n const uniformMin = typeof min === \"number\" ? min : DEFAULT_MIN;\n const uniformMax = typeof max === \"number\" ? max : DEFAULT_MAX;\n\n const baseValue = integer\n ? rng.int(uniformMin, uniformMax)\n : rng.float(uniformMin, uniformMax);\n return applyPrecision(start + baseValue);\n };\n\n return rngFn;\n}\n","import { z } from \"zod/v4\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\n\nimport { naturalZodSchema } from \"./naturalZodSchema.js\";\n\n//\n//\n// Types\n//\n\ntype Format = JsonObject | NaturalSchema | z.ZodType;\n\n//\n//\n// Helpers\n//\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Convert a `format` declaration (Zod schema, NaturalSchema, or a JSON Schema\n * JsonObject) into a plain JSON Schema we can walk. Mirrors the conversion the\n * provider adapters perform in `formatOutputSchema`, but without any\n * provider-specific sanitization.\n */\nfunction formatToJsonSchema(format: Format): JsonObject | undefined {\n if (format instanceof z.ZodType) {\n return z.toJSONSchema(format) as JsonObject;\n }\n if (isPlainObject(format) && (format as JsonObject).type === \"json_schema\") {\n const clone = structuredClone(format) as JsonObject;\n clone.type = \"object\";\n return clone;\n }\n try {\n return z.toJSONSchema(\n naturalZodSchema(format as NaturalSchema),\n ) as JsonObject;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Strip a single pair of surrounding double quotes from a key, if present.\n * `\"Merchant Request\"` -> `Merchant Request`; `Confidence` -> `Confidence`.\n */\nfunction dequoteKey(key: string): string {\n if (key.length >= 2 && key.startsWith('\"') && key.endsWith('\"')) {\n return key.slice(1, -1);\n }\n return key;\n}\n\n/**\n * Walk a JSON Schema alongside a parsed value, renaming any object key whose\n * de-quoted form matches a declared property name. Recurses into declared\n * object properties and array items so nested corrupted keys are also repaired.\n */\nfunction repairFromSchema(schema: unknown, value: unknown): unknown {\n if (!isPlainObject(schema)) {\n return value;\n }\n\n const type = schema.type;\n const isArray = type === \"array\" || (type === undefined && \"items\" in schema);\n if (isArray) {\n const items = schema.items;\n if (Array.isArray(value) && isPlainObject(items)) {\n return value.map((entry) => repairFromSchema(items, entry));\n }\n return value;\n }\n\n const isObject =\n type === \"object\" || (type === undefined && \"properties\" in schema);\n if (isObject && isPlainObject(value)) {\n const properties = schema.properties;\n if (isPlainObject(properties)) {\n const declared = new Set(Object.keys(properties));\n // Repair keys: rename a quote-wrapped key to its declared form, unless\n // the correct key is already present (then drop the corrupted duplicate).\n for (const key of Object.keys(value)) {\n if (declared.has(key)) {\n continue;\n }\n const repaired = dequoteKey(key);\n if (repaired !== key && declared.has(repaired)) {\n if (!(repaired in value)) {\n value[repaired] = value[key];\n }\n delete value[key];\n }\n }\n // Recurse into declared properties now that keys are aligned.\n for (const [key, propSchema] of Object.entries(properties)) {\n if (key in value) {\n value[key] = repairFromSchema(propSchema, value[key]);\n }\n }\n }\n return value;\n }\n\n return value;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Repair structured-output keys that a provider/model corrupted by wrapping\n * them in literal double quotes (observed on OpenAI for multi-word `format`\n * keys: `Merchant Request` returned as `\"Merchant Request\"`). A declared\n * `format` is a schema contract: returned keys should match the declared names\n * exactly. Any returned key whose de-quoted form matches a declared key is\n * renamed back to the declared key.\n *\n * Only mutates a (cloned) structured object; strings and non-objects pass\n * through untouched.\n */\nexport function repairFormatKeys({\n content,\n format,\n}: {\n content: JsonObject;\n format: Format;\n}): JsonObject {\n const schema = formatToJsonSchema(format);\n if (!schema) {\n return content;\n }\n return repairFromSchema(schema, structuredClone(content)) as JsonObject;\n}\n","import { JsonObject } from \"@jaypie/types\";\n\nconst DEFAULT_DONE_SENTINEL = \"[DONE]\";\n\n/**\n * Parse a Server-Sent Events stream into decoded JSON chunks. Buffers across\n * network reads, dispatches on newline-delimited `data:` lines, and stops at\n * the done sentinel (OpenAI-style `[DONE]`; Gemini omits it and simply ends\n * the stream). Comment lines (`: ...`, used for keep-alive) are ignored.\n *\n * Shared by the provider HTTP clients that replaced their vendor SDKs.\n */\nexport async function* parseSseStream(\n body: ReadableStream<Uint8Array>,\n { doneSentinel = DEFAULT_DONE_SENTINEL }: { doneSentinel?: string } = {},\n): AsyncIterable<JsonObject> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let newlineIndex: number;\n while ((newlineIndex = buffer.indexOf(\"\\n\")) !== -1) {\n const line = buffer.slice(0, newlineIndex).replace(/\\r$/, \"\");\n buffer = buffer.slice(newlineIndex + 1);\n\n if (line === \"\" || line.startsWith(\":\")) continue;\n if (!line.startsWith(\"data:\")) continue;\n\n const data = line.slice(\"data:\".length).trim();\n if (data === doneSentinel) return;\n\n yield JSON.parse(data) as JsonObject;\n }\n }\n } finally {\n reader.releaseLock();\n }\n}\n","import { log } from \"@jaypie/logger\";\n\nimport { LlmUsageItem } from \"../types/LlmProvider.interface.js\";\n\nconst UNKNOWN = \"unknown\";\n\ninterface TallyOperateOptions {\n toolCallNames?: string[];\n turns: number;\n usage?: LlmUsageItem[];\n}\n\n/**\n * Tally loop totals onto the root logger's report session so handlers\n * (express, lambda) include llm activity in the report emitted at teardown.\n * Silently no-ops outside an active session or when the logger predates\n * tally support.\n */\nexport function tallyOperate({\n toolCallNames = [],\n turns,\n usage = [],\n}: TallyOperateOptions): void {\n if (typeof log.tally !== \"function\") return;\n const llm: Record<string, unknown> = {\n operates: 1,\n toolCalls: toolCallNames.length,\n turns,\n };\n if (toolCallNames.length > 0) {\n const tools: Record<string, number> = {};\n for (const name of toolCallNames) {\n tools[name] = (tools[name] ?? 0) + 1;\n }\n llm.tools = tools;\n }\n if (usage.length > 0) {\n const usageByModel: Record<string, Record<string, number>> = {};\n for (const item of usage) {\n const key =\n [item.provider, item.model].filter(Boolean).join(\":\") || UNKNOWN;\n usageByModel[key] ??= { input: 0, output: 0, reasoning: 0, total: 0 };\n usageByModel[key].input += item.input;\n usageByModel[key].output += item.output;\n usageByModel[key].reasoning += item.reasoning;\n usageByModel[key].total += item.total;\n if (item.cacheRead !== undefined) {\n usageByModel[key].cacheRead =\n (usageByModel[key].cacheRead ?? 0) + item.cacheRead;\n }\n if (item.cacheWrite !== undefined) {\n usageByModel[key].cacheWrite =\n (usageByModel[key].cacheWrite ?? 0) + item.cacheWrite;\n }\n }\n llm.usage = usageByModel;\n }\n log.tally({ llm });\n}\n","/**\n * Options for tryParseNumber function\n */\nexport interface TryParseNumberOptions {\n /**\n * Default value to return if parsing fails or results in NaN\n */\n defaultValue?: number;\n /**\n * Function to call with warning message if parsing fails or results in NaN\n */\n warnFunction?: (message: string) => void;\n}\n\n/**\n * Helper function to safely call a function that might throw\n * @param fn Function to call safely\n */\nfunction callSafely(fn: () => void): void {\n try {\n fn();\n } catch {\n // Silently catch any errors from the function\n }\n}\n\n/**\n * Attempts to parse a value as a number. Returns the original input if parsing fails or results in NaN.\n * @param input - The value to attempt to parse as a number\n * @param options - Optional configuration\n * @param options.defaultValue - Default value to return if parsing fails or results in NaN\n * @param options.warnFunction - Function to call with warning message if parsing fails or results in NaN\n * @returns The parsed number, defaultValue (if specified and parsing fails), or the original input\n */\nexport function tryParseNumber(\n input: unknown,\n options?: TryParseNumberOptions,\n): number | unknown {\n if (input === null || input === undefined) {\n return input;\n }\n\n try {\n const parsed = Number(input);\n\n if (Number.isNaN(parsed)) {\n if (options?.warnFunction) {\n const warningMessage = `Failed to parse \"${String(input)}\" as number`;\n callSafely(() => options.warnFunction!(warningMessage));\n }\n\n return typeof options?.defaultValue === \"number\"\n ? options.defaultValue\n : input;\n }\n\n return parsed;\n } catch (error: unknown) {\n if (options?.warnFunction) {\n let errorMessage = \"\";\n if (error instanceof Error) {\n errorMessage = error.message;\n }\n const warningMessage = `Error parsing \"${String(input)}\" as number${errorMessage ? \"; \" + errorMessage : \"\"}`;\n callSafely(() => options.warnFunction!(warningMessage));\n }\n\n return typeof options?.defaultValue === \"number\"\n ? options.defaultValue\n : input;\n }\n}\n","import {\n LlmExchangeCallback,\n LlmExchangeEnvelope,\n} from \"../../types/LlmProvider.interface.js\";\nimport { getLogger } from \"../../util/index.js\";\n\n/**\n * Truthy-except-\"false\"/\"0\" gate on LLM_EXCHANGE_ENABLED, matching the\n * DD_LLMOBS_ENABLED convention in observability/llmobs.ts.\n */\nexport function isExchangeStoreEnabled(): boolean {\n const flag = process.env.LLM_EXCHANGE_ENABLED;\n if (!flag) {\n return false;\n }\n return flag.toLowerCase() !== \"false\" && flag !== \"0\";\n}\n\n/**\n * Whether the loop should assemble an exchange envelope at settlement.\n */\nexport function isExchangeRequested({\n onExchange,\n}: {\n onExchange?: LlmExchangeCallback;\n}): boolean {\n return Boolean(onExchange) || isExchangeStoreEnabled();\n}\n\n/**\n * Deliver an exchange envelope to a callback. Errors thrown by the callback\n * are logged and swallowed — exchange capture must never interrupt the call.\n */\nexport async function emitExchange({\n envelope,\n onExchange,\n}: {\n envelope: LlmExchangeEnvelope;\n onExchange?: LlmExchangeCallback;\n}): Promise<void> {\n if (!onExchange) {\n return;\n }\n try {\n await onExchange(envelope);\n } catch (error) {\n const log = getLogger();\n log.warn(\"[operate] onExchange callback threw\");\n log.var({ error });\n }\n}\n","import { LlmExchangeEnvelope } from \"../types/LlmProvider.interface.js\";\nimport { getLogger } from \"../util/index.js\";\nimport { isExchangeStoreEnabled } from \"../operate/exchange/emitExchange.js\";\n\n//\n//\n// Types\n//\n\n/** Minimal shape of the @jaypie/dynamodb surface this module uses. */\ninterface ExchangeStoreSdk {\n storeExchange: (envelope: LlmExchangeEnvelope) => Promise<unknown>;\n}\n\n//\n//\n// Constants\n//\n\nconst MODULE = {\n // Computed at runtime so bundlers (esbuild) do not attempt to include\n // @jaypie/dynamodb, which is an optional peer dependency.\n JAYPIE_DYNAMODB: [\"@jaypie\", \"dynamodb\"].join(\"/\"),\n};\n\n//\n//\n// Helpers\n//\n\n// Native dynamic import that neither rollup nor tsc rewrites to require(), so\n// a CJS-bundled build still loads @jaypie/dynamodb's ESM entry and shares the\n// host's initialized module instance. A require()-based resolution would load\n// the CJS build, whose module-level client state is separate from the ESM\n// instance an ESM host initializes (dual-package hazard, issue #429).\nconst dynamicImport = new Function(\"s\", \"return import(s)\") as (\n s: string,\n) => Promise<Record<string, unknown>>;\n\nlet resolved = false;\nlet cachedSdk: ExchangeStoreSdk | null = null;\nlet injectedSdk: ExchangeStoreSdk | null = null;\n\n/**\n * Lazily resolve @jaypie/dynamodb's storeExchange. Returns null (and never\n * throws) when the peer is absent. Cached after the first attempt.\n */\nasync function resolveExchangeStore(): Promise<ExchangeStoreSdk | null> {\n if (resolved) {\n return cachedSdk;\n }\n resolved = true;\n try {\n const dynamodb = await dynamicImport(MODULE.JAYPIE_DYNAMODB);\n const sdk = (dynamodb?.default ?? dynamodb) as Partial<ExchangeStoreSdk>;\n if (sdk && typeof sdk.storeExchange === \"function\") {\n cachedSdk = sdk as ExchangeStoreSdk;\n }\n } catch {\n cachedSdk = null;\n }\n return cachedSdk;\n}\n\n/** Reset the cached resolution. Exposed for tests. */\nexport function _resetExchangeStore(): void {\n resolved = false;\n cachedSdk = null;\n injectedSdk = null;\n}\n\n/**\n * Inject a store to bypass @jaypie/dynamodb resolution. Test-only: the peer\n * is optional, so the enabled path cannot otherwise be exercised in unit\n * tests without it installed.\n */\nexport function _setExchangeStore(sdk: ExchangeStoreSdk | null): void {\n injectedSdk = sdk;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Persist an exchange envelope via @jaypie/dynamodb when\n * LLM_EXCHANGE_ENABLED is set. Silent no-op when the flag is unset or the\n * peer is absent; persister failures are logged and never thrown.\n */\nexport async function persistExchange(\n envelope: LlmExchangeEnvelope,\n): Promise<void> {\n if (!isExchangeStoreEnabled()) {\n return;\n }\n const sdk = injectedSdk ?? (await resolveExchangeStore());\n if (!sdk) {\n return;\n }\n try {\n await sdk.storeExchange(envelope);\n } catch (error) {\n const log = getLogger();\n log.warn(\"[operate] Exchange persistence failed\");\n log.var({ error });\n }\n}\n","import { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport {\n LlmHistory,\n LlmOperateOptions,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n ClassifiedError,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\n\n//\n//\n// Provider Adapter Interface\n//\n\n/**\n * ProviderAdapter defines the contract that each LLM provider must implement\n * to work with the shared operate loop.\n *\n * The adapter pattern allows the core operate loop to be provider-agnostic\n * while each provider handles its specific API format and quirks.\n */\nexport interface ProviderAdapter {\n //\n // Provider Identification\n //\n\n /**\n * Unique identifier for this provider (e.g., \"openai\", \"anthropic\")\n */\n readonly name: string;\n\n /**\n * Default model for this provider\n */\n readonly defaultModel: string;\n\n /**\n * Whether OperateLoop may take a corrective turn when a `format` request\n * completes with prose instead of structured output (tool-emulation\n * providers opt in).\n */\n readonly supportsStructuredOutputRetry?: boolean;\n\n //\n // Request Building\n //\n\n /**\n * Build a provider-specific request from the standardized format\n *\n * @param request - Standardized request options\n * @returns Provider-specific request object ready for the API\n */\n buildRequest(request: OperateRequest): unknown;\n\n /**\n * Convert a Toolkit to provider-specific tool definitions\n *\n * @param toolkit - The toolkit containing tool definitions\n * @param outputSchema - Optional JSON schema for structured output\n * @returns Array of provider-specific tool definitions\n */\n formatTools(\n toolkit: Toolkit,\n outputSchema?: JsonObject,\n ): ProviderToolDefinition[];\n\n /**\n * Format a structured output schema for the provider\n *\n * @param schema - JSON schema, NaturalSchema, or Zod schema for the expected output\n * @returns Provider-specific format configuration\n */\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject;\n\n //\n // API Execution\n //\n\n /**\n * Execute an API request to the provider\n *\n * @param client - The provider's SDK client instance\n * @param request - Provider-specific request object (from buildRequest)\n * @param signal - Optional AbortSignal to cancel the request on retry\n * @returns Raw provider response\n */\n executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<unknown>;\n\n /**\n * Execute a streaming API request to the provider\n *\n * @param client - The provider's SDK client instance\n * @param request - Provider-specific request object (from buildRequest)\n * @param signal - Optional AbortSignal to cancel the request on retry\n * @returns AsyncIterable of stream chunks\n */\n executeStreamRequest?(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk>;\n\n //\n // Response Parsing\n //\n\n /**\n * Parse a provider response into standardized format\n *\n * @param response - Raw provider response\n * @param options - Original operate options (for context)\n * @returns Parsed response with content, tool calls, usage, etc.\n */\n parseResponse(response: unknown, options?: LlmOperateOptions): ParsedResponse;\n\n /**\n * Extract tool calls from a provider response\n *\n * @param response - Raw provider response\n * @returns Array of standardized tool calls\n */\n extractToolCalls(response: unknown): StandardToolCall[];\n\n /**\n * Extract usage information from a provider response\n *\n * @param response - Raw provider response\n * @param model - The model used (for tracking)\n * @returns Usage item with token counts\n */\n extractUsage(response: unknown, model: string): LlmUsageItem;\n\n //\n // Tool Result Handling\n //\n\n /**\n * Format a tool result to append to the conversation\n *\n * @param toolCall - The original tool call\n * @param result - The standardized tool result\n * @returns Provider-specific message/item to add to history\n */\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): unknown;\n\n /**\n * Append tool call and result to the request for the next turn\n *\n * @param request - Current provider request\n * @param toolCall - The tool call that was made\n * @param result - The result of the tool call\n * @returns Updated request with tool result appended\n */\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): unknown;\n\n //\n // History Management\n //\n\n /**\n * Convert provider response items to LlmHistory format for storage\n *\n * @param response - Raw provider response\n * @returns History items to append\n */\n responseToHistoryItems(response: unknown): LlmHistory;\n\n //\n // Error Classification\n //\n\n /**\n * Classify an error for retry logic\n *\n * @param error - The error that occurred\n * @returns Classified error with retry recommendation\n */\n classifyError(error: unknown): ClassifiedError;\n\n /**\n * Check if an error is retryable\n *\n * @param error - The error to check\n * @returns True if the error can be retried\n */\n isRetryableError(error: unknown): boolean;\n\n /**\n * Check if an error is due to rate limiting\n *\n * @param error - The error to check\n * @returns True if this is a rate limit error\n */\n isRateLimitError(error: unknown): boolean;\n\n //\n // Provider-Specific Features\n //\n\n /**\n * Check if a response indicates the model wants to stop (vs tool use)\n *\n * @param response - Raw provider response\n * @returns True if the model has finished responding\n */\n isComplete(response: unknown): boolean;\n\n /**\n * Check if a response contains a structured output result\n *\n * @param response - Raw provider response\n * @returns True if structured output was returned\n */\n hasStructuredOutput(response: unknown): boolean;\n\n /**\n * Extract structured output from a response\n *\n * @param response - Raw provider response\n * @returns Parsed JSON object\n */\n extractStructuredOutput(response: unknown): JsonObject | undefined;\n}\n\n//\n//\n// Abstract Base Adapter\n//\n\n/**\n * BaseProviderAdapter provides default implementations for common adapter methods.\n * Providers can extend this class to reduce boilerplate.\n */\nexport abstract class BaseProviderAdapter implements ProviderAdapter {\n abstract readonly name: string;\n abstract readonly defaultModel: string;\n\n abstract buildRequest(request: OperateRequest): unknown;\n abstract formatTools(\n toolkit: Toolkit,\n outputSchema?: JsonObject,\n ): ProviderToolDefinition[];\n abstract formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject;\n abstract executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<unknown>;\n abstract parseResponse(\n response: unknown,\n options?: LlmOperateOptions,\n ): ParsedResponse;\n abstract extractToolCalls(response: unknown): StandardToolCall[];\n abstract extractUsage(response: unknown, model: string): LlmUsageItem;\n abstract formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): unknown;\n abstract appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): unknown;\n abstract responseToHistoryItems(response: unknown): LlmHistory;\n abstract classifyError(error: unknown): ClassifiedError;\n abstract isComplete(response: unknown): boolean;\n\n /**\n * Whether OperateLoop may take a corrective turn when a `format` request\n * completes with prose instead of structured output. Providers whose\n * structured output rides a tool emulation (where compliance is a model\n * decision) opt in; native grammar-constrained providers do not need it.\n */\n readonly supportsStructuredOutputRetry: boolean = false;\n\n /**\n * Default implementation checks if error is retryable via classifyError\n */\n isRetryableError(error: unknown): boolean {\n const classified = this.classifyError(error);\n return classified.shouldRetry;\n }\n\n /**\n * Default implementation checks error category via classifyError\n */\n isRateLimitError(error: unknown): boolean {\n const classified = this.classifyError(error);\n return classified.category === \"rate_limit\";\n }\n\n /**\n * Default implementation returns false - override for providers with native structured output\n */\n\n hasStructuredOutput(_response: unknown): boolean {\n return false;\n }\n\n /**\n * Default implementation returns undefined - override for providers with native structured output\n */\n\n extractStructuredOutput(_response: unknown): JsonObject | undefined {\n return undefined;\n }\n}\n","import { EFFORT, type LlmEffort } from \"../constants.js\";\n\n/**\n * Result of translating the provider-neutral {@link LlmEffort} scale to a\n * provider's native reasoning control.\n */\nexport interface LlmEffortMapping<T extends string | number = string> {\n /**\n * True when the requested neutral level had no distinct native rung and was\n * collapsed or clamped onto a neighbor (e.g. `highest` -> Grok `high`, or\n * `highest` -> OpenAI `high` on a model predating `xhigh`). Adapters log\n * these at debug so a papered-over request stays on the record.\n */\n papered: boolean;\n /** Native effort value for the target provider. */\n value: T;\n}\n\n/**\n * Per-provider translation of the provider-neutral {@link LlmEffort} scale.\n *\n * The neutral enum (lowest → low → medium → high → highest) is a relative\n * five-point scale. Each table below maps it onto the target provider's native\n * effort control, keeping `medium`/`high` semantically aligned across providers\n * and using each provider's extra bottom (`minimal`) or top (`xhigh`/`max`)\n * rung where one exists. Providers with fewer levels collapse the ends and mark\n * the result `papered`. A single `effort` value is therefore safe to reuse\n * across providers and fallback chains.\n */\n\n/** Consistent debug message for a papered-over effort level. */\nexport function paperedEffortMessage({\n model,\n provider,\n requested,\n value,\n}: {\n model: string;\n provider: string;\n requested: LlmEffort;\n value: string | number;\n}): string {\n return `[llm] effort '${requested}' has no distinct tier on ${provider} model '${model}'; using '${value}'`;\n}\n\n// OpenAI Responses API `reasoning.effort`.\n// Full ladder: minimal | low | medium | high | xhigh (plus `none`). Availability\n// is not uniform across the gpt-5 line:\n// - `xhigh` was introduced at gpt-5.2 and has been continuous since, so it is\n// safe for our gpt-5.4 default and everything newer.\n// - `minimal` shipped on gpt-5/5.1, was dropped at gpt-5.2, and returned on\n// the current line; because that history is non-monotonic we only trust it\n// from gpt-5.4 (our default floor) onward.\n// Outside those windows (older gpt-5, o-series) the extreme rung is clamped and\n// the mapping reports `papered: true`.\nconst OPENAI_EFFORT: Record<LlmEffort, string> = {\n [EFFORT.LOWEST]: \"minimal\",\n [EFFORT.LOW]: \"low\",\n [EFFORT.MEDIUM]: \"medium\",\n [EFFORT.HIGH]: \"high\",\n [EFFORT.HIGHEST]: \"xhigh\",\n};\n\ninterface GptVersion {\n major: number;\n minor: number;\n}\n\nfunction openAiGptVersion(model: string): GptVersion | null {\n const match = model.match(/^gpt-(\\d+)(?:\\.(\\d+))?/);\n if (!match) return null;\n return { major: Number(match[1]), minor: match[2] ? Number(match[2]) : 0 };\n}\n\nfunction atLeast(\n version: GptVersion | null,\n major: number,\n minor: number,\n): boolean {\n if (!version) return false;\n return (\n version.major > major || (version.major === major && version.minor >= minor)\n );\n}\n\nexport function toOpenAiEffort(\n effort: LlmEffort,\n { model }: { model: string },\n): LlmEffortMapping {\n const native = OPENAI_EFFORT[effort];\n const version = openAiGptVersion(model);\n // `minimal` only from gpt-5.4 (non-monotonic history; absent on o-series)\n if (native === \"minimal\" && !atLeast(version, 5, 4)) {\n return { papered: true, value: \"low\" };\n }\n // `xhigh` from gpt-5.2 onward (absent on older gpt-5 and o-series)\n if (native === \"xhigh\" && !atLeast(version, 5, 2)) {\n return { papered: true, value: \"high\" };\n }\n return { papered: false, value: native };\n}\n\n// xAI Grok `reasoning_effort` — low | medium | high. No sub-low or top rung, so\n// `lowest` collapses onto `low` and `highest` onto `high`.\nconst XAI_EFFORT: Record<LlmEffort, LlmEffortMapping> = {\n [EFFORT.LOWEST]: { papered: true, value: \"low\" },\n [EFFORT.LOW]: { papered: false, value: \"low\" },\n [EFFORT.MEDIUM]: { papered: false, value: \"medium\" },\n [EFFORT.HIGH]: { papered: false, value: \"high\" },\n [EFFORT.HIGHEST]: { papered: true, value: \"high\" },\n};\n\nexport function toXaiEffort(effort: LlmEffort): LlmEffortMapping {\n return XAI_EFFORT[effort];\n}\n\n// Anthropic `output_config.effort` — low | medium | high | xhigh | max. No\n// sub-low rung, so `lowest` collapses onto `low`; `highest` reaches `max`.\nconst ANTHROPIC_EFFORT: Record<LlmEffort, LlmEffortMapping> = {\n [EFFORT.LOWEST]: { papered: true, value: \"low\" },\n [EFFORT.LOW]: { papered: false, value: \"low\" },\n [EFFORT.MEDIUM]: { papered: false, value: \"medium\" },\n [EFFORT.HIGH]: { papered: false, value: \"high\" },\n [EFFORT.HIGHEST]: { papered: false, value: \"max\" },\n};\n\nexport function toAnthropicEffort(effort: LlmEffort): LlmEffortMapping {\n return ANTHROPIC_EFFORT[effort];\n}\n\n// Gemini 3.x `thinkingConfig.thinkingLevel` — MINIMAL | LOW | MEDIUM | HIGH. No\n// top rung above HIGH, so `highest` collapses onto HIGH.\nconst GEMINI_THINKING_LEVEL: Record<LlmEffort, LlmEffortMapping> = {\n [EFFORT.LOWEST]: { papered: false, value: \"MINIMAL\" },\n [EFFORT.LOW]: { papered: false, value: \"LOW\" },\n [EFFORT.MEDIUM]: { papered: false, value: \"MEDIUM\" },\n [EFFORT.HIGH]: { papered: false, value: \"HIGH\" },\n [EFFORT.HIGHEST]: { papered: true, value: \"HIGH\" },\n};\n\nexport function toGeminiThinkingLevel(effort: LlmEffort): LlmEffortMapping {\n return GEMINI_THINKING_LEVEL[effort];\n}\n\n// Gemini 2.5 `thinkingConfig.thinkingBudget` — every tier is a distinct token\n// budget, so nothing is papered over. Floor (512) clears every 2.5 minimum;\n// ceiling (24,576) is valid across 2.5 Pro (max 32,768) and Flash (max 24,576).\nconst GEMINI_THINKING_BUDGET: Record<LlmEffort, number> = {\n [EFFORT.LOWEST]: 512,\n [EFFORT.LOW]: 4096,\n [EFFORT.MEDIUM]: 8192,\n [EFFORT.HIGH]: 16384,\n [EFFORT.HIGHEST]: 24576,\n};\n\nexport function toGeminiThinkingBudget(\n effort: LlmEffort,\n): LlmEffortMapping<number> {\n return { papered: false, value: GEMINI_THINKING_BUDGET[effort] };\n}\n\n// Fireworks `reasoning_effort` — low | medium | high. Accepted on every model\n// (the API no-ops where unsupported). No sub-low or top rung, so `lowest`\n// collapses onto `low` and `highest` onto `high`.\nconst FIREWORKS_EFFORT: Record<LlmEffort, LlmEffortMapping> = {\n [EFFORT.LOWEST]: { papered: true, value: \"low\" },\n [EFFORT.LOW]: { papered: false, value: \"low\" },\n [EFFORT.MEDIUM]: { papered: false, value: \"medium\" },\n [EFFORT.HIGH]: { papered: false, value: \"high\" },\n [EFFORT.HIGHEST]: { papered: true, value: \"high\" },\n};\n\nexport function toFireworksEffort(effort: LlmEffort): LlmEffortMapping {\n return FIREWORKS_EFFORT[effort];\n}\n\n// OpenRouter `reasoning.effort` — accepts the full minimal..xhigh ladder and\n// maps to the routed provider's nearest supported level itself, so nothing is\n// papered here.\nconst OPENROUTER_EFFORT: Record<LlmEffort, string> = {\n [EFFORT.LOWEST]: \"minimal\",\n [EFFORT.LOW]: \"low\",\n [EFFORT.MEDIUM]: \"medium\",\n [EFFORT.HIGH]: \"high\",\n [EFFORT.HIGHEST]: \"xhigh\",\n};\n\nexport function toOpenRouterEffort(effort: LlmEffort): LlmEffortMapping {\n return { papered: false, value: OPENROUTER_EFFORT[effort] };\n}\n","import { LlmUsage } from \"./LlmProvider.interface.js\";\n\n//\n//\n// Types\n//\n\nexport enum LlmStreamChunkType {\n Done = \"done\",\n Error = \"error\",\n Text = \"text\",\n ToolCall = \"tool_call\",\n ToolResult = \"tool_result\",\n}\n\nexport interface LlmStreamChunkText {\n type: LlmStreamChunkType.Text;\n content: string;\n}\n\nexport interface LlmStreamChunkToolCall {\n type: LlmStreamChunkType.ToolCall;\n toolCall: {\n id: string;\n name: string;\n arguments: string;\n /** Provider-specific metadata preserved through tool-call roundtrip */\n metadata?: Record<string, unknown>;\n };\n}\n\nexport interface LlmStreamChunkToolResult {\n type: LlmStreamChunkType.ToolResult;\n toolResult: {\n id: string;\n name: string;\n result: unknown;\n };\n}\n\nexport interface LlmStreamChunkDone {\n type: LlmStreamChunkType.Done;\n usage: LlmUsage;\n}\n\nexport interface LlmStreamChunkError {\n type: LlmStreamChunkType.Error;\n error: {\n detail?: string;\n status: number | string;\n title: string;\n };\n}\n\nexport type LlmStreamChunk =\n | LlmStreamChunkDone\n | LlmStreamChunkError\n | LlmStreamChunkText\n | LlmStreamChunkToolCall\n | LlmStreamChunkToolResult;\n","import { JsonObject } from \"@jaypie/types\";\n\nimport { type LlmEffort } from \"../constants.js\";\n\nimport {\n LlmCache,\n LlmHistory,\n LlmMessageType,\n LlmOperateOptions,\n LlmUsageItem,\n} from \"../types/LlmProvider.interface.js\";\nimport { Toolkit } from \"../tools/Toolkit.class.js\";\n\n//\n//\n// Provider-Agnostic Types\n//\n\n/**\n * Standardized tool call representation across providers\n */\nexport interface StandardToolCall {\n /** Unique identifier for this tool call */\n callId: string;\n /** Name of the tool being called */\n name: string;\n /** JSON string of arguments */\n arguments: string;\n /** Original provider-specific tool call object */\n raw: unknown;\n}\n\n/**\n * Standardized tool result to send back to the provider\n */\nexport interface StandardToolResult {\n /** The call ID this result corresponds to */\n callId: string;\n /** JSON string of the result */\n output: string;\n /** Whether the tool call was successful */\n success: boolean;\n /** Error message if the tool call failed */\n error?: string;\n}\n\n/**\n * Parsed response from a provider API call\n */\nexport interface ParsedResponse {\n /** The text content of the response, if any */\n content?: string | JsonObject;\n /** Whether the response contains tool calls */\n hasToolCalls: boolean;\n /** The stop reason from the provider */\n stopReason?: string;\n /** Usage information for this response */\n usage?: LlmUsageItem;\n /** Raw provider response for storage */\n raw: unknown;\n}\n\n/**\n * Context passed to hooks and utilities during the operate loop\n */\nexport interface OperateContext {\n /** The hooks configuration */\n hooks: LlmOperateOptions[\"hooks\"];\n /** The operate options */\n options: LlmOperateOptions;\n}\n\n//\n//\n// Provider Request/Response Types\n//\n\n/**\n * Provider-agnostic request options\n * Each adapter will convert this to provider-specific format\n */\nexport interface OperateRequest {\n /** The model to use */\n model: string;\n /** The conversation history/messages */\n messages: LlmHistory;\n /** System instructions (if separate from messages) */\n system?: string;\n /** Additional instructions to append */\n instructions?: string;\n /** Tools available for the model */\n tools?: ProviderToolDefinition[];\n /** Structured output format */\n format?: JsonObject;\n /** Normalized reasoning effort; adapters translate to provider-native control */\n effort?: LlmEffort;\n /** Provider-specific options */\n providerOptions?: JsonObject;\n /**\n * Prompt-caching control for the stable prefix (system + tools). `true`/\n * omitted = enabled@5m, `false`/`0` = disabled, `\"5m\"`/`\"1h\"` = enabled@ttl.\n */\n cache?: LlmCache;\n /** Whether the request will execute over a streaming transport */\n stream?: boolean;\n /** Sampling temperature (0-2 for most providers) */\n temperature?: number;\n /**\n * Set by OperateLoop on a corrective turn after a format request came back\n * as prose. Adapters that support the retry (see\n * `ProviderAdapter.supportsStructuredOutputRetry`) should offer only the\n * structured-output mechanism on this turn.\n */\n structuredOutputRetry?: boolean;\n /** User identifier for tracking */\n user?: string;\n}\n\n/**\n * Tool definition in provider-agnostic format\n */\nexport interface ProviderToolDefinition {\n /** Tool name */\n name: string;\n /** Tool description */\n description: string;\n /** JSON Schema for parameters */\n parameters: JsonObject;\n}\n\n//\n//\n// Error Classification Types\n//\n\n/**\n * Categories of errors for retry logic\n */\nexport enum ErrorCategory {\n /** Error is transient and can be retried */\n Retryable = \"retryable\",\n /** Error is due to short-term rate limiting (retry after a delay) */\n RateLimit = \"rate_limit\",\n /**\n * Provider quota is exhausted or the account cannot be billed\n * (insufficient funds, daily quota, plan limit). Terminal and actionable —\n * retrying within the request budget will not help.\n */\n Quota = \"quota\",\n /** Error cannot be recovered from */\n Unrecoverable = \"unrecoverable\",\n /** Error type is unknown */\n Unknown = \"unknown\",\n}\n\n/**\n * Classified error with metadata\n */\nexport interface ClassifiedError {\n /** The original error */\n error: unknown;\n /** Category of the error */\n category: ErrorCategory;\n /** Whether a retry should be attempted */\n shouldRetry: boolean;\n /** Suggested delay before retry (if applicable) */\n suggestedDelayMs?: number;\n /**\n * For {@link ErrorCategory.Quota}, distinguishes an exhausted usage quota\n * from an account that cannot be billed (insufficient funds).\n */\n reason?: \"quota\" | \"billing\";\n}\n\n//\n//\n// Operate Loop State\n//\n\n// Import ResponseBuilder for type declaration\nimport type { ResponseBuilder } from \"./response/ResponseBuilder.js\";\n\n/**\n * Internal state of the operate loop\n */\nexport interface OperateLoopState {\n /** Count of consecutive tool errors (resets on success) */\n consecutiveToolErrors: number;\n /** Set when the loop has taken a corrective structured-output turn */\n structuredOutputRetry?: boolean;\n /** Current conversation input/messages */\n currentInput: LlmHistory;\n /** Current turn number (0-indexed, incremented at start of each turn) */\n currentTurn: number;\n /** Formatted output schema for structured output */\n formattedFormat?: JsonObject;\n /** Stop reason from the most recent model response */\n lastStopReason?: string;\n /** Model-request retries across all turns (exchange envelope) */\n retries: number;\n /** Formatted tools for the provider */\n formattedTools?: ProviderToolDefinition[];\n /** Maximum allowed turns */\n maxTurns: number;\n /** Response builder instance */\n responseBuilder: ResponseBuilder;\n /** Names of tool calls executed across all turns (report tally) */\n toolCallNames: string[];\n /** The toolkit for tool calls */\n toolkit?: Toolkit;\n}\n\n//\n//\n// Message Type Constants\n//\n\n/**\n * Re-export message type for convenience in adapters\n */\nexport { LlmMessageType };\n","/**\n * Transient network error detection utility.\n *\n * Detects low-level Node.js/undici network errors that indicate\n * a temporary network issue (not a provider API error).\n * These errors should always be retried.\n */\n\n//\n//\n// Constants\n//\n\n/** Error codes from Node.js net/dns subsystems that indicate transient failures */\nconst TRANSIENT_ERROR_CODES = new Set([\n \"ECONNREFUSED\",\n \"ECONNRESET\",\n \"EAI_AGAIN\",\n \"ENETRESET\",\n \"ENETUNREACH\",\n \"ENOTFOUND\",\n \"EPIPE\",\n \"ETIMEDOUT\",\n]);\n\n/** Substrings in error messages that indicate transient network issues */\nconst TRANSIENT_MESSAGE_PATTERNS = [\n \"network\",\n \"socket hang up\",\n \"terminated\",\n] as const;\n\n//\n//\n// Helpers\n//\n\n/**\n * Check a single error (without walking the cause chain)\n */\nfunction matchesSingleError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n\n // Check error code (e.g., ECONNRESET)\n const code = (error as { code?: string }).code;\n if (code && TRANSIENT_ERROR_CODES.has(code)) {\n return true;\n }\n\n // Check error message for transient patterns\n const message = error.message.toLowerCase();\n for (const pattern of TRANSIENT_MESSAGE_PATTERNS) {\n if (message.includes(pattern)) {\n return true;\n }\n }\n\n return false;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Detect transient network errors by inspecting the error and its cause chain.\n *\n * Undici (Node.js fetch) wraps low-level errors like ECONNRESET inside\n * `TypeError: terminated`. This function recursively walks `error.cause`\n * to detect these wrapped errors.\n *\n * @param error - The error to inspect\n * @returns true if the error (or any cause in its chain) is a transient network error\n */\nexport function isTransientNetworkError(error: unknown): boolean {\n let current: unknown = error;\n\n while (current) {\n if (matchesSingleError(current)) {\n return true;\n }\n\n // Walk the cause chain (cause is ES2022, cast for compatibility)\n const cause = (current as { cause?: unknown }).cause;\n if (current instanceof Error && cause) {\n current = cause;\n } else {\n break;\n }\n }\n\n return false;\n}\n","import { ClassifiedError, ErrorCategory } from \"../operate/types.js\";\n\n//\n//\n// Constants\n//\n\n/**\n * Transient structured-output compile failures. The provider caches the\n * compiled grammar after a successful compile, so an immediate retry of the\n * identical request typically succeeds (issue #422).\n */\nconst RETRYABLE_MESSAGE_PATTERNS = [\n \"grammar compilation timed out\",\n \"grammar compilation timeout\",\n] as const;\n\n/** Billing / insufficient-funds signals — the account cannot be charged. */\nconst BILLING_MESSAGE_PATTERNS = [\n \"insufficient_quota\",\n \"insufficient funds\",\n \"insufficient credit\",\n \"credit balance\",\n \"billing\",\n \"payment required\",\n \"plan and billing\",\n] as const;\n\n/** Exhausted usage quota (per-day / per-model limits). */\nconst QUOTA_MESSAGE_PATTERNS = [\n \"quota exceeded\",\n \"exceeded your current quota\",\n \"resource_exhausted\",\n \"quota_exceeded\",\n] as const;\n\n//\n//\n// Helpers\n//\n\nfunction extractMessage(error: unknown): string {\n if (error instanceof Error) return error.message.toLowerCase();\n if (typeof error === \"string\") return error.toLowerCase();\n if (error && typeof error === \"object\") {\n const message = (error as { message?: unknown }).message;\n if (typeof message === \"string\") return message.toLowerCase();\n }\n return \"\";\n}\n\n//\n//\n// Main\n//\n\n/**\n * Shared, provider-agnostic first pass over an error. Returns a\n * {@link ClassifiedError} when the message unambiguously identifies a\n * cross-provider condition (retryable structured-output timeout, exhausted\n * quota, or a billing failure), or `undefined` to defer to the adapter's own\n * status/name classification.\n *\n * Adapters call this before their existing logic so that, for example, a\n * `429` carrying a daily-quota message is classified as {@link\n * ErrorCategory.Quota} rather than {@link ErrorCategory.RateLimit}.\n */\nexport function classifyProviderError(\n error: unknown,\n): ClassifiedError | undefined {\n const message = extractMessage(error);\n if (!message) return undefined;\n\n for (const pattern of RETRYABLE_MESSAGE_PATTERNS) {\n if (message.includes(pattern)) {\n return { category: ErrorCategory.Retryable, error, shouldRetry: true };\n }\n }\n\n for (const pattern of BILLING_MESSAGE_PATTERNS) {\n if (message.includes(pattern)) {\n return {\n category: ErrorCategory.Quota,\n error,\n reason: \"billing\",\n shouldRetry: false,\n };\n }\n }\n\n for (const pattern of QUOTA_MESSAGE_PATTERNS) {\n if (message.includes(pattern)) {\n return {\n category: ErrorCategory.Quota,\n error,\n reason: \"quota\",\n shouldRetry: false,\n };\n }\n }\n\n return undefined;\n}\n","import { log } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { paperedEffortMessage, toAnthropicEffort } from \"../../util/effort.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmInputContent,\n LlmMessageType,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n isJsonSchema as isBareJsonSchema,\n naturalZodSchema,\n resolveCache,\n resolveMaxOutputTokens,\n} from \"../../util/index.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { AnthropicClient } from \"../../providers/anthropic/client.js\";\nimport { Anthropic } from \"../../providers/anthropic/types.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\n/**\n * Local extension of the SDK's `MessageCreateParams` to carry\n * `output_config.format` (Anthropic native structured outputs). The SDK 0.71\n * shipped with the older `output_format` field which the API has since\n * deprecated in favor of `output_config.format`. We send the new shape via\n * an untyped passthrough so callers don't need a newer SDK; remove this\n * extension once the SDK types `output_config` directly.\n */\ntype AnthropicRequestParams = Anthropic.MessageCreateParams & {\n output_config?: {\n effort?: string;\n format?: {\n type: \"json_schema\";\n schema: JsonObject;\n };\n };\n};\n\n/**\n * Whether `output_config.effort` may be sent for this model. Anthropic added\n * the effort control on the Claude 4.5 line and up (the 5 family); older models\n * reject it. Parsing major/minor avoids matching a minor \"5\" in legacy ids\n * like `claude-3-5-sonnet`.\n */\nfunction supportsAnthropicEffort(model: string): boolean {\n const match = model.match(/claude-[a-z]+-(\\d+)(?:-(\\d+))?/);\n if (!match) return false;\n const major = Number(match[1]);\n const minor = match[2] !== undefined ? Number(match[2]) : 0;\n if (major >= 5) return true;\n return major === 4 && minor >= 5;\n}\n\n/**\n * Anthropic responses we annotate at receive time so downstream stateless\n * methods (`hasStructuredOutput`, `extractStructuredOutput`) can tell whether\n * the request asked for structured output without re-threading the request.\n */\ntype AnnotatedAnthropicMessage = Anthropic.Message & {\n __jaypieStructuredOutput?: boolean;\n};\n\nconst STRUCTURED_OUTPUT_NON_PARSE_STOP_REASONS = new Set([\n \"refusal\",\n \"max_tokens\",\n]);\n\n// Regular expression to parse data URLs: data:mime/type;base64,data\nconst DATA_URL_REGEX = /^data:([^;]+);base64,(.+)$/;\n\n// String formats accepted by Anthropic's structured-output grammar compiler.\n// Other formats are stripped (move to description) so the API does not 400.\nconst SUPPORTED_STRING_FORMATS = new Set([\n \"date\",\n \"date-time\",\n \"duration\",\n \"email\",\n \"hostname\",\n \"ipv4\",\n \"ipv6\",\n \"time\",\n \"uri\",\n \"uuid\",\n]);\n\n// Top-level keywords stripped wholesale before sending: not part of the spec\n// the API enforces and the validator can reject them.\nconst STRIPPED_TOP_LEVEL_KEYWORDS = new Set([\"$schema\", \"$id\"]);\n\n// Keywords Anthropic's structured-output grammar does not support. They are\n// removed from the schema and appended to `description` so the model still\n// sees the intent.\nconst UNSUPPORTED_CONSTRAINT_KEYWORDS = new Set([\n \"exclusiveMaximum\",\n \"exclusiveMinimum\",\n \"maxItems\",\n \"maxLength\",\n \"maxProperties\",\n \"maximum\",\n \"minLength\",\n \"minProperties\",\n \"minimum\",\n \"multipleOf\",\n \"pattern\",\n \"patternProperties\",\n \"uniqueItems\",\n]);\n\n/**\n * Recursively transform a JSON Schema into the strict shape Anthropic's\n * structured-output grammar accepts: object types must have\n * `additionalProperties: false`, unsupported numeric/string/array\n * constraints are appended to `description`, and unsupported string\n * formats are stripped. Mirrors @anthropic-ai/sdk's `transformJSONSchema`\n * but inline so we do not take a runtime dependency on the optional\n * peer SDK.\n */\nfunction sanitizeJsonSchemaForAnthropic(\n schema: JsonObject,\n isRoot = true,\n): JsonObject {\n const result: JsonObject = {};\n const carriedConstraints: string[] = [];\n\n for (const [key, value] of Object.entries(schema)) {\n if (isRoot && STRIPPED_TOP_LEVEL_KEYWORDS.has(key)) {\n continue;\n }\n\n if (UNSUPPORTED_CONSTRAINT_KEYWORDS.has(key)) {\n carriedConstraints.push(`${key}: ${JSON.stringify(value)}`);\n continue;\n }\n\n if (key === \"format\" && typeof value === \"string\") {\n if (SUPPORTED_STRING_FORMATS.has(value)) {\n result[key] = value;\n } else {\n carriedConstraints.push(`format: ${JSON.stringify(value)}`);\n }\n continue;\n }\n\n if (key === \"minItems\" && typeof value === \"number\") {\n if (value === 0 || value === 1) {\n result[key] = value;\n } else {\n carriedConstraints.push(`minItems: ${value}`);\n }\n continue;\n }\n\n if (\n key === \"properties\" &&\n value &&\n typeof value === \"object\" &&\n !Array.isArray(value)\n ) {\n const transformedProps: JsonObject = {};\n for (const [propName, propSchema] of Object.entries(\n value as JsonObject,\n )) {\n transformedProps[propName] = isJsonSchema(propSchema)\n ? sanitizeJsonSchemaForAnthropic(propSchema, false)\n : propSchema;\n }\n result[key] = transformedProps;\n continue;\n }\n\n if (\n (key === \"items\" || key === \"additionalItems\" || key === \"contains\") &&\n isJsonSchema(value)\n ) {\n result[key] = sanitizeJsonSchemaForAnthropic(value, false);\n continue;\n }\n\n if (\n (key === \"anyOf\" || key === \"oneOf\" || key === \"allOf\") &&\n Array.isArray(value)\n ) {\n const targetKey = key === \"oneOf\" ? \"anyOf\" : key;\n result[targetKey] = value.map((entry) =>\n isJsonSchema(entry)\n ? sanitizeJsonSchemaForAnthropic(entry, false)\n : entry,\n );\n continue;\n }\n\n if (key === \"$defs\" && value && typeof value === \"object\") {\n const transformedDefs: JsonObject = {};\n for (const [defName, defSchema] of Object.entries(value as JsonObject)) {\n transformedDefs[defName] = isJsonSchema(defSchema)\n ? sanitizeJsonSchemaForAnthropic(defSchema, false)\n : defSchema;\n }\n result[key] = transformedDefs;\n continue;\n }\n\n if (key === \"additionalProperties\") {\n // Always force `false` on objects below; ignore caller-supplied value.\n continue;\n }\n\n result[key] = value;\n }\n\n if (result.type === \"object\") {\n result.additionalProperties = false;\n }\n\n if (carriedConstraints.length > 0) {\n const existing =\n typeof result.description === \"string\" ? result.description : \"\";\n const suffix = `{${carriedConstraints.join(\", \")}}`;\n result.description = existing ? `${existing}\\n\\n${suffix}` : suffix;\n }\n\n return result;\n}\n\nfunction isJsonSchema(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Parse a data URL into its components\n */\nfunction parseDataUrl(\n dataUrl: string,\n): { data: string; mediaType: string } | null {\n const match = dataUrl.match(DATA_URL_REGEX);\n if (!match) return null;\n return { mediaType: match[1], data: match[2] };\n}\n\n/**\n * Convert standardized content items to Anthropic format\n */\nfunction convertContentToAnthropic(\n content: string | LlmInputContent[],\n): Anthropic.ContentBlockParam[] | string {\n if (typeof content === \"string\") {\n return content;\n }\n\n return content.map((item): Anthropic.ContentBlockParam => {\n // Text content\n if (item.type === LlmMessageType.InputText) {\n return { type: \"text\", text: item.text };\n }\n\n // Image content\n if (item.type === LlmMessageType.InputImage) {\n const imageUrl = item.image_url || \"\";\n const parsed = parseDataUrl(imageUrl);\n if (parsed) {\n return {\n type: \"image\",\n source: {\n type: \"base64\",\n media_type:\n parsed.mediaType as Anthropic.Base64ImageSource[\"media_type\"],\n data: parsed.data,\n },\n };\n }\n // Fallback for URL-based images (not base64)\n return {\n type: \"image\",\n source: {\n type: \"url\",\n url: imageUrl,\n },\n };\n }\n\n // File/Document content (PDF, etc.)\n if (item.type === LlmMessageType.InputFile) {\n const fileData = typeof item.file_data === \"string\" ? item.file_data : \"\";\n const parsed = parseDataUrl(fileData);\n if (parsed) {\n return {\n type: \"document\",\n source: {\n type: \"base64\",\n media_type:\n parsed.mediaType as Anthropic.Base64PDFSource[\"media_type\"],\n data: parsed.data,\n },\n };\n }\n // Fallback - return as text with the filename\n return { type: \"text\", text: `[File: ${item.filename || \"unknown\"}]` };\n }\n\n // Unknown type - return as text\n return { type: \"text\", text: JSON.stringify(item) };\n });\n}\n\n// Error names for classification (using string names since SDK is optional)\nconst RETRYABLE_ERROR_NAMES = [\n \"APIConnectionError\",\n \"APIConnectionTimeoutError\",\n \"InternalServerError\",\n];\n\nconst NOT_RETRYABLE_ERROR_NAMES = [\n \"AuthenticationError\",\n \"BadRequestError\",\n \"NotFoundError\",\n \"PermissionDeniedError\",\n];\n\n// Models known not to accept `temperature`.\n// Patterns (not exact names) so dated variants and future releases are covered\n// without code changes — Anthropic is trending toward removing temperature on\n// newer Claude models.\nconst MODELS_WITHOUT_TEMPERATURE: RegExp[] = [\n /^claude-opus-4-[789]/,\n /^claude-opus-[5-9]/,\n];\n\nfunction isTemperatureDeprecationError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n message?: string;\n error?: { message?: string };\n };\n const name = (error as Error)?.constructor?.name;\n if (name !== \"BadRequestError\" && err.status !== 400) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) => m.toLowerCase().includes(\"temperature\"));\n}\n\n/**\n * Detect 400 errors that indicate the model itself does not support native\n * structured outputs (`output_config.format`). Citations + structured output\n * is also a 400 case but is a caller error rather than a model-capability\n * gap, so we explicitly skip it to avoid masking the real problem under a\n * tool-emulation retry. The deprecated-`output_format` 400 (API renamed the\n * field) is also explicitly excluded — that's a code-path bug, not a model\n * gap; it should propagate so we notice and fix it.\n */\nfunction isStructuredOutputUnsupportedError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n message?: string;\n error?: { message?: string };\n };\n const name = (error as Error)?.constructor?.name;\n if (name !== \"BadRequestError\" && err.status !== 400) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n if (messages.some((m) => /citation/i.test(m))) return false;\n if (messages.some((m) => /deprecated/i.test(m))) return false;\n return messages.some((m) =>\n /output_config|output_format|json[_ ]schema|structured/i.test(m),\n );\n}\n\n//\n//\n// Main\n//\n\n/**\n * AnthropicAdapter implements the ProviderAdapter interface for Anthropic's API.\n * It handles request building, response parsing, and error classification\n * specific to Anthropic's Messages API.\n */\nexport class AnthropicAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.ANTHROPIC.NAME;\n readonly defaultModel = PROVIDER.ANTHROPIC.DEFAULT;\n\n // Session-level cache of models observed to reject `temperature` at runtime.\n // Populated by executeRequest on 400 errors so repeat calls skip the param.\n private runtimeNoTemperatureModels = new Set<string>();\n\n // Session-level cache of models observed to reject `output_format`. When a\n // model is in this set, buildRequest engages the legacy fake-tool path\n // instead of native structured output.\n private runtimeNoStructuredOutputModels = new Set<string>();\n\n rememberModelRejectsTemperature(model: string): void {\n this.runtimeNoTemperatureModels.add(model);\n }\n\n clearRuntimeNoTemperatureModels(): void {\n this.runtimeNoTemperatureModels.clear();\n }\n\n rememberModelRejectsStructuredOutput(model: string): void {\n this.runtimeNoStructuredOutputModels.add(model);\n }\n\n clearRuntimeNoStructuredOutputModels(): void {\n this.runtimeNoStructuredOutputModels.clear();\n }\n\n private supportsTemperature(model: string): boolean {\n if (this.runtimeNoTemperatureModels.has(model)) return false;\n return !MODELS_WITHOUT_TEMPERATURE.some((pattern) => pattern.test(model));\n }\n\n private supportsStructuredOutput(model: string): boolean {\n return !this.runtimeNoStructuredOutputModels.has(model);\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): AnthropicRequestParams {\n // Convert messages to Anthropic format\n // Handle different message types: regular messages, function calls, and function outputs\n const messages: Anthropic.MessageParam[] = [];\n\n for (const msg of request.messages) {\n const typedMsg = msg as {\n type?: string;\n role?: string;\n content?: string | LlmInputContent[];\n name?: string;\n arguments?: string;\n call_id?: string;\n output?: string;\n };\n\n // Skip system messages - Anthropic only accepts system as a top-level field\n if (typedMsg.role === \"system\") {\n continue;\n }\n\n // Handle FunctionCall messages - convert to assistant message with tool_use\n if (typedMsg.type === LlmMessageType.FunctionCall) {\n messages.push({\n role: \"assistant\",\n content: [\n {\n type: \"tool_use\",\n id: typedMsg.call_id || \"\",\n name: typedMsg.name || \"\",\n input: JSON.parse(typedMsg.arguments || \"{}\"),\n },\n ],\n });\n continue;\n }\n\n // Handle FunctionCallOutput messages - convert to user message with tool_result\n if (typedMsg.type === LlmMessageType.FunctionCallOutput) {\n messages.push({\n role: \"user\",\n content: [\n {\n type: \"tool_result\",\n tool_use_id: typedMsg.call_id || \"\",\n content: typedMsg.output || \"\",\n },\n ],\n });\n continue;\n }\n\n // Handle regular messages with role and content\n if (typedMsg.role && typedMsg.content !== undefined) {\n messages.push({\n role: typedMsg.role as \"user\" | \"assistant\",\n content: convertContentToAnthropic(typedMsg.content),\n } as Anthropic.MessageParam);\n }\n }\n\n // Append instructions to last message if provided\n if (request.instructions && messages.length > 0) {\n const lastMsg = messages[messages.length - 1];\n if (typeof lastMsg.content === \"string\") {\n lastMsg.content = lastMsg.content + \"\\n\\n\" + request.instructions;\n }\n }\n\n const model = (request.model ||\n this.defaultModel) as Anthropic.MessageCreateParams[\"model\"];\n const anthropicRequest: AnthropicRequestParams = {\n model,\n messages,\n max_tokens:\n resolveMaxOutputTokens(model as string, { stream: request.stream }) ??\n PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n stream: false,\n };\n\n const cache = resolveCache(request.cache);\n const cacheControl: Anthropic.CacheControlEphemeral | undefined =\n cache.enabled\n ? {\n type: \"ephemeral\",\n ...(cache.ttl === \"1h\" ? { ttl: \"1h\" as const } : {}),\n }\n : undefined;\n\n if (request.system) {\n // A cache breakpoint on the system block caches tools+system together\n // (render order is tools -> system -> messages).\n anthropicRequest.system = cacheControl\n ? [{ type: \"text\", text: request.system, cache_control: cacheControl }]\n : request.system;\n }\n\n const useFallbackStructuredOutput =\n Boolean(request.format) &&\n !this.supportsStructuredOutput(anthropicRequest.model as string);\n\n const allTools: ProviderToolDefinition[] = request.tools\n ? [...request.tools]\n : [];\n if (useFallbackStructuredOutput && request.format) {\n log.warn(\n `[AnthropicAdapter] Using legacy structured_output tool fallback for model ${anthropicRequest.model as string}; native output_config previously rejected for this model.`,\n );\n allTools.push({\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"Output a structured JSON object, \" +\n \"use this before your final response to give structured outputs to the user\",\n parameters: request.format,\n });\n }\n\n if (allTools.length > 0) {\n anthropicRequest.tools = allTools.map((tool, index) => ({\n name: tool.name,\n description: tool.description,\n input_schema: {\n ...tool.parameters,\n type: \"object\",\n } as Anthropic.Messages.Tool.InputSchema,\n type: \"custom\" as const,\n // Breakpoint on the last tool caches the tool list (which renders\n // before system) when there is no system prompt to anchor it.\n ...(cacheControl && index === allTools.length - 1\n ? { cache_control: cacheControl }\n : {}),\n }));\n\n anthropicRequest.tool_choice = useFallbackStructuredOutput\n ? { type: \"any\" }\n : { type: \"auto\" };\n }\n\n // Native structured output: send schema as `output_config.format`. The\n // legacy tool-emulation path is engaged only as a runtime fallback for\n // models the API has flagged as not supporting native structured output.\n if (request.format && !useFallbackStructuredOutput) {\n anthropicRequest.output_config = {\n format: {\n type: \"json_schema\",\n schema: request.format,\n },\n };\n }\n\n if (request.providerOptions) {\n Object.assign(anthropicRequest, request.providerOptions);\n }\n\n // Normalized reasoning effort -> output_config.effort (merged so a format\n // config above survives). First-class effort wins over providerOptions.\n if (\n request.effort &&\n supportsAnthropicEffort(anthropicRequest.model as string)\n ) {\n const mapping = toAnthropicEffort(request.effort);\n if (mapping.papered) {\n log.debug(\n paperedEffortMessage({\n model: anthropicRequest.model as string,\n provider: this.name,\n requested: request.effort,\n value: mapping.value,\n }),\n );\n }\n anthropicRequest.output_config = {\n ...anthropicRequest.output_config,\n effort: mapping.value,\n };\n }\n\n // First-class temperature takes precedence over providerOptions\n if (request.temperature !== undefined) {\n anthropicRequest.temperature = request.temperature;\n }\n\n // Strip temperature for models that don't support it (denylist + runtime cache)\n if (\n anthropicRequest.temperature !== undefined &&\n !this.supportsTemperature(anthropicRequest.model as string)\n ) {\n delete anthropicRequest.temperature;\n }\n\n return anthropicRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n // outputSchema is part of the interface contract but Anthropic now uses\n // native `output_format` (set in buildRequest), so we no longer inject a\n // synthetic structured-output tool here.\n\n _outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: {\n ...tool.parameters,\n type: \"object\",\n } as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n let jsonSchema: JsonObject;\n\n // Check if schema is already a JsonObject — either the OpenAI-style\n // `{ type: \"json_schema\", ... }` envelope or a bare `{ type: \"object\", properties }` node\n if (\n (typeof schema === \"object\" &&\n schema !== null &&\n !Array.isArray(schema) &&\n (schema as JsonObject).type === \"json_schema\") ||\n isBareJsonSchema(schema)\n ) {\n jsonSchema = structuredClone(schema) as JsonObject;\n jsonSchema.type = \"object\"; // Validator does not recognize \"json_schema\"\n } else {\n // Convert NaturalSchema to JSON schema through Zod\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n jsonSchema = z.toJSONSchema(zodSchema) as JsonObject;\n }\n\n return sanitizeJsonSchemaForAnthropic(jsonSchema);\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<Anthropic.Message> {\n const anthropic = client as AnthropicClient;\n const anthropicRequest = request as AnthropicRequestParams;\n const wantsStructuredOutput = Boolean(anthropicRequest.output_config);\n try {\n const response = (await anthropic.messages.create(\n anthropicRequest as Anthropic.MessageCreateParams,\n signal ? { signal } : undefined,\n )) as AnnotatedAnthropicMessage;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as Anthropic.Message;\n\n // If the model rejected `temperature`, cache it and retry without the param\n if (\n anthropicRequest.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(anthropicRequest.model as string);\n const retryRequest = { ...anthropicRequest };\n delete retryRequest.temperature;\n const response = (await anthropic.messages.create(\n retryRequest as Anthropic.MessageCreateParams,\n signal ? { signal } : undefined,\n )) as AnnotatedAnthropicMessage;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n }\n\n // If the model rejected native structured output, cache it and retry\n // via the legacy fake-tool emulation path.\n if (wantsStructuredOutput && isStructuredOutputUnsupportedError(error)) {\n const model = anthropicRequest.model as string;\n this.rememberModelRejectsStructuredOutput(model);\n log.warn(\n `[AnthropicAdapter] Model ${model} rejected native output_config; falling back to legacy structured_output tool emulation.`,\n );\n const fallbackRequest =\n this.toFallbackStructuredOutputRequest(anthropicRequest);\n return (await anthropic.messages.create(\n fallbackRequest as Anthropic.MessageCreateParams,\n signal ? { signal } : undefined,\n )) as Anthropic.Message;\n }\n\n throw error;\n }\n }\n\n /**\n * Rebuild a structured-output request without `output_format`, swapping in\n * the legacy fake-tool emulation. Used as a runtime fallback when a model\n * rejects native `output_config.format`.\n */\n private toFallbackStructuredOutputRequest(\n request: AnthropicRequestParams,\n ): AnthropicRequestParams {\n const { output_config, ...rest } = request;\n if (!output_config?.format) return request;\n const fallbackRequest: AnthropicRequestParams = { ...rest };\n // Preserve an effort setting; only the structured-output format falls back.\n if (output_config.effort) {\n fallbackRequest.output_config = { effort: output_config.effort };\n }\n const fakeTool = {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"Output a structured JSON object, \" +\n \"use this before your final response to give structured outputs to the user\",\n input_schema: {\n ...output_config.format.schema,\n type: \"object\",\n } as Anthropic.Messages.Tool.InputSchema,\n type: \"custom\" as const,\n };\n fallbackRequest.tools = [...(fallbackRequest.tools ?? []), fakeTool];\n fallbackRequest.tool_choice = { type: \"any\" };\n return fallbackRequest;\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const anthropic = client as AnthropicClient;\n // Preserve `output_config` when passing through to the SDK by typing\n // through the local extension instead of the upstream\n // MessageCreateParams shape.\n let streamRequest = {\n ...(request as AnthropicRequestParams),\n stream: true,\n } as AnthropicRequestParams & { stream: true };\n\n let stream;\n try {\n stream = await anthropic.messages.create(\n streamRequest as Anthropic.MessageCreateParamsStreaming,\n signal ? { signal } : undefined,\n );\n } catch (error) {\n if (\n streamRequest.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(streamRequest.model as string);\n streamRequest = {\n ...streamRequest,\n };\n delete streamRequest.temperature;\n stream = await anthropic.messages.create(\n streamRequest as Anthropic.MessageCreateParamsStreaming,\n signal ? { signal } : undefined,\n );\n } else {\n throw error;\n }\n }\n\n // Track current tool call being built\n let currentToolCall: {\n id: string;\n name: string;\n arguments: string;\n } | null = null;\n\n // Track usage for final chunk\n let inputTokens = 0;\n let outputTokens = 0;\n let thinkingTokens = 0;\n let model = streamRequest.model;\n\n for await (const event of stream) {\n if (event.type === \"message_start\") {\n // Extract initial usage and model info\n const message = event.message;\n if (message.usage) {\n inputTokens = message.usage.input_tokens;\n }\n model = message.model;\n } else if (event.type === \"content_block_start\") {\n const contentBlock = event.content_block;\n if (contentBlock.type === \"tool_use\") {\n // Start building a tool call\n currentToolCall = {\n id: contentBlock.id,\n name: contentBlock.name,\n arguments: \"\",\n };\n }\n } else if (event.type === \"content_block_delta\") {\n const delta = event.delta;\n if (delta.type === \"text_delta\") {\n yield {\n type: LlmStreamChunkType.Text,\n content: delta.text,\n };\n } else if (delta.type === \"input_json_delta\" && currentToolCall) {\n // Accumulate tool call arguments\n currentToolCall.arguments += delta.partial_json;\n }\n } else if (event.type === \"content_block_stop\") {\n // If we were building a tool call, emit it now\n if (currentToolCall) {\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.id,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n currentToolCall = null;\n }\n } else if (event.type === \"message_delta\") {\n // Extract final usage\n if (event.usage) {\n outputTokens = event.usage.output_tokens;\n // Check for thinking tokens in extended thinking responses\n const extendedUsage = event.usage as { thinking_tokens?: number };\n if (extendedUsage.thinking_tokens) {\n thinkingTokens = extendedUsage.thinking_tokens;\n }\n }\n } else if (event.type === \"message_stop\") {\n // Emit done chunk with usage\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: thinkingTokens,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n }\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n _options?: LlmOperateOptions,\n ): ParsedResponse {\n const anthropicResponse = response as Anthropic.Message;\n\n const content = this.extractContent(anthropicResponse);\n const hasToolCalls = anthropicResponse.stop_reason === \"tool_use\";\n\n return {\n content,\n hasToolCalls,\n stopReason: anthropicResponse.stop_reason ?? undefined,\n usage: this.extractUsage(anthropicResponse, anthropicResponse.model),\n raw: anthropicResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const anthropicResponse = response as Anthropic.Message;\n const toolCalls: StandardToolCall[] = [];\n\n for (const block of anthropicResponse.content) {\n if (block.type === \"tool_use\") {\n toolCalls.push({\n callId: block.id,\n name: block.name,\n arguments: JSON.stringify(block.input),\n raw: block,\n });\n }\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const anthropicResponse = response as Anthropic.Message;\n\n // Check for thinking tokens in the usage (extended thinking feature)\n // Anthropic includes thinking tokens in a separate field when enabled\n const usage = anthropicResponse.usage as {\n input_tokens: number;\n output_tokens: number;\n thinking_tokens?: number;\n cache_read_input_tokens?: number;\n cache_creation_input_tokens?: number;\n };\n\n return {\n input: usage.input_tokens,\n output: usage.output_tokens,\n reasoning: usage.thinking_tokens || 0,\n total: usage.input_tokens + usage.output_tokens,\n ...(usage.cache_read_input_tokens !== undefined\n ? { cacheRead: usage.cache_read_input_tokens }\n : {}),\n ...(usage.cache_creation_input_tokens !== undefined\n ? { cacheWrite: usage.cache_creation_input_tokens }\n : {}),\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): Anthropic.ToolResultBlockParam {\n return {\n type: \"tool_result\",\n tool_use_id: toolCall.callId,\n content: result.output,\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): Anthropic.MessageCreateParams {\n const anthropicRequest = request as Anthropic.MessageCreateParams;\n const toolCallRaw = toolCall.raw as Anthropic.ToolUseBlock;\n\n // Add assistant message with the tool use\n anthropicRequest.messages.push({\n role: \"assistant\",\n content: [toolCallRaw],\n });\n\n // Add user message with the tool result\n anthropicRequest.messages.push({\n role: \"user\",\n content: [this.formatToolResult(toolCall, result)],\n });\n\n return anthropicRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const anthropicResponse = response as Anthropic.Message;\n const historyItems: LlmHistory = [];\n\n // Check if this is a tool use response\n if (anthropicResponse.stop_reason === \"tool_use\") {\n // Don't add to history yet - will be added after tool execution\n return historyItems;\n }\n\n // Include thinking blocks for extended thinking support\n // Thinking blocks are preserved in history so extractReasoning can find them\n for (const block of anthropicResponse.content) {\n if (block.type === \"thinking\") {\n // Push raw block - types are loosely checked at runtime\n // This allows extractReasoning to access the thinking property\n historyItems.push(block as unknown as LlmOutputMessage);\n }\n }\n\n // Extract text content for non-tool responses\n const textBlock = anthropicResponse.content.find(\n (block) => block.type === \"text\",\n ) as Anthropic.TextBlock | undefined;\n\n if (textBlock) {\n historyItems.push({\n content: textBlock.text,\n role: PROVIDER.ANTHROPIC.ROLE.ASSISTANT,\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n const errorName = (error as Error)?.constructor?.name;\n\n // Check for rate limit error\n if (errorName === \"RateLimitError\") {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Check for retryable errors\n if (RETRYABLE_ERROR_NAMES.includes(errorName)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Check for non-retryable errors\n if (NOT_RETRYABLE_ERROR_NAMES.includes(errorName)) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n\n // Check for transient network errors (ECONNRESET, etc.)\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Unknown error - treat as potentially retryable\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Provider-Specific Features\n //\n\n isComplete(response: unknown): boolean {\n const anthropicResponse = response as Anthropic.Message;\n return anthropicResponse.stop_reason !== \"tool_use\";\n }\n\n override hasStructuredOutput(response: unknown): boolean {\n const anthropicResponse = response as AnnotatedAnthropicMessage;\n\n // Native path: executeRequest annotates the response when we sent\n // `output_format`, so we can detect intent statelessly.\n if (anthropicResponse.__jaypieStructuredOutput) {\n return this.extractStructuredOutput(response) !== undefined;\n }\n\n // Fallback path: legacy fake-tool emulation, kept for models that the\n // runtime has cached as not supporting `output_format`.\n const lastBlock =\n anthropicResponse.content[anthropicResponse.content.length - 1];\n return (\n lastBlock?.type === \"tool_use\" &&\n (lastBlock as Anthropic.ToolUseBlock).name === STRUCTURED_OUTPUT_TOOL_NAME\n );\n }\n\n override extractStructuredOutput(response: unknown): JsonObject | undefined {\n const anthropicResponse = response as AnnotatedAnthropicMessage;\n\n if (anthropicResponse.__jaypieStructuredOutput) {\n // Refusal and truncation are explicit non-JSON outcomes per Anthropic\n // structured-outputs docs — surface the text upstream instead of\n // forcing a JSON.parse on what is not JSON.\n if (\n anthropicResponse.stop_reason &&\n STRUCTURED_OUTPUT_NON_PARSE_STOP_REASONS.has(\n anthropicResponse.stop_reason,\n )\n ) {\n return undefined;\n }\n\n const textBlock = anthropicResponse.content.find(\n (block) => block.type === \"text\",\n ) as Anthropic.TextBlock | undefined;\n if (!textBlock) return undefined;\n\n try {\n const parsed = JSON.parse(textBlock.text);\n return parsed as JsonObject;\n } catch {\n return undefined;\n }\n }\n\n // Fallback path: legacy fake-tool emulation\n const lastBlock =\n anthropicResponse.content[anthropicResponse.content.length - 1];\n if (\n lastBlock?.type === \"tool_use\" &&\n (lastBlock as Anthropic.ToolUseBlock).name === STRUCTURED_OUTPUT_TOOL_NAME\n ) {\n return (lastBlock as Anthropic.ToolUseBlock).input as JsonObject;\n }\n\n return undefined;\n }\n\n //\n // Private Helpers\n //\n\n private extractContent(\n response: Anthropic.Message,\n ): string | JsonObject | undefined {\n // Check for structured output first\n if (this.hasStructuredOutput(response)) {\n return this.extractStructuredOutput(response);\n }\n\n // Extract text content\n const textBlock = response.content.find(\n (block) => block.type === \"text\",\n ) as Anthropic.TextBlock | undefined;\n\n return textBlock?.text;\n }\n}\n\n// Export singleton instance\nexport const anthropicAdapter = new AnthropicAdapter();\n","import type {\n BedrockRuntimeClient,\n ConverseCommandInput,\n ConverseCommandOutput,\n DocumentFormat,\n} from \"@aws-sdk/client-bedrock-runtime\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmInputContent,\n LlmMessageType,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n isJsonSchema,\n naturalZodSchema,\n resolveCache,\n} from \"../../util/index.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\n\n//\n//\n// Types\n//\n\ntype BedrockContentBlock =\n | { text: string }\n | { toolUse: { toolUseId: string; name: string; input: JsonObject } }\n | { toolResult: { toolUseId: string; content: Array<{ text: string }> } }\n | { image: { format: string; source: { bytes: Uint8Array } } }\n | {\n document: {\n format: DocumentFormat;\n name: string;\n source: { bytes: Uint8Array };\n };\n };\n\ntype BedrockMessage = {\n role: \"user\" | \"assistant\";\n content: BedrockContentBlock[];\n};\n\ntype BedrockRequest = Omit<ConverseCommandInput, \"messages\"> & {\n messages: BedrockMessage[];\n};\n\n//\n//\n// Helpers\n//\n\n// Regular expression to parse data URLs\nconst DATA_URL_REGEX = /^data:([^;]+);base64,(.+)$/;\n\nconst MIME_TO_DOCUMENT_FORMAT: Record<string, DocumentFormat> = {\n \"application/pdf\": \"pdf\",\n \"text/csv\": \"csv\",\n \"application/msword\": \"doc\",\n \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":\n \"docx\",\n \"application/vnd.ms-excel\": \"xls\",\n \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\": \"xlsx\",\n \"text/html\": \"html\",\n \"text/plain\": \"txt\",\n \"text/markdown\": \"md\",\n};\n\nfunction convertContentToBedrock(\n content: string | LlmInputContent[],\n): BedrockContentBlock[] {\n if (typeof content === \"string\") {\n return [{ text: content }];\n }\n\n return content.map((item): BedrockContentBlock => {\n if (item.type === LlmMessageType.InputText) {\n return { text: item.text };\n }\n\n if (item.type === LlmMessageType.InputImage) {\n const imageUrl = item.image_url || \"\";\n const match = imageUrl.match(DATA_URL_REGEX);\n if (match) {\n const format = match[1].split(\"/\")[1] || \"jpeg\";\n const bytes = Buffer.from(match[2], \"base64\");\n return {\n image: {\n format,\n source: { bytes: new Uint8Array(bytes) },\n },\n };\n }\n return { text: `[Image: ${imageUrl}]` };\n }\n\n if (item.type === LlmMessageType.InputFile) {\n const fileData = typeof item.file_data === \"string\" ? item.file_data : \"\";\n const match = fileData.match(DATA_URL_REGEX);\n if (match) {\n const mimeType = match[1];\n const documentFormat = MIME_TO_DOCUMENT_FORMAT[mimeType];\n if (documentFormat) {\n const bytes = Buffer.from(match[2], \"base64\");\n const rawName = item.filename || \"document\";\n const name = rawName.replace(/[^a-zA-Z0-9 \\-()[\\]]/g, \"_\");\n return {\n document: {\n format: documentFormat,\n name,\n source: { bytes: new Uint8Array(bytes) },\n },\n };\n }\n }\n return { text: `[File: ${item.filename || \"unknown\"}]` };\n }\n\n return { text: JSON.stringify(item) };\n });\n}\n\n//\n//\n// Constants / helpers\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\ntype AnnotatedBedrockResponse = ConverseCommandOutput & {\n __jaypieStructuredOutput?: boolean;\n};\n\nfunction isOutputConfigUnsupportedError(error: unknown): boolean {\n const msg = (error as Error)?.message ?? \"\";\n return /outputConfig|output_config/i.test(msg);\n}\n\nfunction isTemperatureDeprecationError(error: unknown): boolean {\n const msg = (error as Error)?.message ?? \"\";\n return /temperature.*deprecated|deprecated.*temperature/i.test(msg);\n}\n\n/** Exported for tests; not part of the package's public surface. */\nexport function isCachePointUnsupportedError(error: unknown): boolean {\n const name = (error as Error)?.constructor?.name ?? \"\";\n const msg = (error as Error)?.message ?? \"\";\n // A model that cannot cache rejects the cachePoint block with a\n // ValidationException naming caching / cachePoint. Bedrock words this as\n // \"You invoked an unsupported model or your request did not allow prompt\n // caching\" — \"unsupported\" is one word, so it must be matched separately\n // from \"not support\".\n return (\n /ValidationException|invalid|not support|unsupported/i.test(\n name + \" \" + msg,\n ) && /cachePoint|cache_point|prompt caching|caching/i.test(msg)\n );\n}\n\nfunction extractJson(text: string): JsonObject | undefined {\n // Try direct parse first\n try {\n const parsed = JSON.parse(text) as JsonObject;\n if (typeof parsed === \"object\" && parsed !== null) return parsed;\n } catch {\n // fall through\n }\n // Try stripping markdown code fences\n const fenceMatch = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (fenceMatch) {\n try {\n const parsed = JSON.parse(fenceMatch[1].trim()) as JsonObject;\n if (typeof parsed === \"object\" && parsed !== null) return parsed;\n } catch {\n // fall through\n }\n }\n return undefined;\n}\n\n//\n//\n// Main\n//\n\nexport class BedrockAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.BEDROCK.NAME;\n readonly defaultModel = PROVIDER.BEDROCK.DEFAULT;\n\n private _modelsFallbackToStructuredOutputTool = new Set<string>();\n private _modelsWithoutTemperature = new Set<string>();\n private _modelsWithoutCachePoint = new Set<string>();\n\n private rememberModelRejectsCachePoint(model: string): void {\n this._modelsWithoutCachePoint.add(model);\n }\n\n private supportsCachePoint(model: string): boolean {\n return !this._modelsWithoutCachePoint.has(model);\n }\n\n private rememberModelRejectsOutputConfig(model: string): void {\n this._modelsFallbackToStructuredOutputTool.add(model);\n }\n\n private useFakeToolForStructuredOutput(model: string): boolean {\n return this._modelsFallbackToStructuredOutputTool.has(model);\n }\n\n private rememberModelRejectsTemperature(model: string): void {\n this._modelsWithoutTemperature.add(model);\n }\n\n private supportsTemperature(model: string): boolean {\n return !this._modelsWithoutTemperature.has(model);\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): BedrockRequest {\n const messages: BedrockMessage[] = [];\n\n for (const msg of request.messages) {\n const typedMsg = msg as {\n type?: string;\n role?: string;\n content?: string | LlmInputContent[];\n name?: string;\n arguments?: string;\n call_id?: string;\n output?: string;\n };\n\n if (typedMsg.role === \"system\") continue;\n\n if (typedMsg.type === LlmMessageType.FunctionCall) {\n let parsedInput: JsonObject;\n try {\n parsedInput = JSON.parse(typedMsg.arguments || \"{}\") as JsonObject;\n } catch {\n parsedInput = {};\n }\n messages.push({\n role: \"assistant\",\n content: [\n {\n toolUse: {\n toolUseId: typedMsg.call_id || \"\",\n name: typedMsg.name || \"\",\n input: parsedInput,\n },\n },\n ],\n });\n continue;\n }\n\n if (typedMsg.type === LlmMessageType.FunctionCallOutput) {\n messages.push({\n role: \"user\",\n content: [\n {\n toolResult: {\n toolUseId: typedMsg.call_id || \"\",\n content: [{ text: typedMsg.output || \"\" }],\n },\n },\n ],\n });\n continue;\n }\n\n if (typedMsg.role && typedMsg.content !== undefined) {\n messages.push({\n role: typedMsg.role as \"user\" | \"assistant\",\n content: convertContentToBedrock(typedMsg.content),\n });\n }\n }\n\n const model = request.model || this.defaultModel;\n const bedrockRequest: BedrockRequest = {\n modelId: model,\n messages,\n inferenceConfig: {\n maxTokens: 4096,\n },\n };\n\n if (request.system) {\n bedrockRequest.system = [{ text: request.system }];\n }\n\n if (request.temperature !== undefined && this.supportsTemperature(model)) {\n bedrockRequest.inferenceConfig = {\n ...bedrockRequest.inferenceConfig,\n temperature: request.temperature,\n };\n }\n\n if (request.tools && request.tools.length > 0) {\n bedrockRequest.toolConfig = {\n tools: request.tools.map((tool) => ({\n toolSpec: {\n name: tool.name,\n description: tool.description,\n inputSchema: {\n json: tool.parameters as Record<string, unknown>,\n },\n },\n })) as NonNullable<ConverseCommandInput[\"toolConfig\"]>[\"tools\"],\n };\n }\n\n if (request.instructions && messages.length > 0) {\n const lastMsg = messages[messages.length - 1];\n if (lastMsg.content.length > 0) {\n const firstBlock = lastMsg.content[0];\n if (\"text\" in firstBlock) {\n firstBlock.text = firstBlock.text + \"\\n\\n\" + request.instructions;\n }\n }\n }\n\n if (request.format) {\n if (this.useFakeToolForStructuredOutput(model)) {\n const fakeTool = {\n toolSpec: {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n inputSchema: { json: request.format as Record<string, unknown> },\n },\n };\n bedrockRequest.toolConfig = {\n tools: [\n ...(bedrockRequest.toolConfig?.tools ?? []),\n fakeTool,\n ] as NonNullable<ConverseCommandInput[\"toolConfig\"]>[\"tools\"],\n };\n } else {\n bedrockRequest.outputConfig = {\n textFormat: {\n type: \"json_schema\",\n structure: {\n jsonSchema: {\n schema: JSON.stringify(request.format),\n name: \"structured_output\",\n },\n },\n },\n };\n }\n }\n\n // Prompt caching via Converse cachePoint blocks (5-min default TTL; the\n // `ttl` option does not apply). Gated per model — cachePoint 400s on\n // unsupported models, which executeRequest catches and denylists.\n if (resolveCache(request.cache).enabled && this.supportsCachePoint(model)) {\n const cachePoint = { cachePoint: { type: \"default\" as const } };\n if (bedrockRequest.system && bedrockRequest.system.length > 0) {\n bedrockRequest.system = [\n ...bedrockRequest.system,\n cachePoint,\n ] as BedrockRequest[\"system\"];\n }\n if (bedrockRequest.toolConfig?.tools?.length) {\n bedrockRequest.toolConfig = {\n ...bedrockRequest.toolConfig,\n tools: [\n ...bedrockRequest.toolConfig.tools,\n cachePoint,\n ] as NonNullable<ConverseCommandInput[\"toolConfig\"]>[\"tools\"],\n };\n }\n }\n\n if (request.providerOptions) {\n Object.assign(bedrockRequest, request.providerOptions);\n }\n\n return bedrockRequest;\n }\n\n /** Remove any cachePoint blocks so the request can be retried unsupported. */\n private stripCachePoints(request: BedrockRequest): BedrockRequest {\n const stripped: BedrockRequest = { ...request };\n if (stripped.system) {\n stripped.system = stripped.system.filter(\n (block) => !(\"cachePoint\" in block),\n ) as BedrockRequest[\"system\"];\n }\n if (stripped.toolConfig?.tools) {\n stripped.toolConfig = {\n ...stripped.toolConfig,\n tools: stripped.toolConfig.tools.filter(\n (tool) => !(\"cachePoint\" in tool),\n ) as NonNullable<ConverseCommandInput[\"toolConfig\"]>[\"tools\"],\n };\n }\n return stripped;\n }\n\n private requestHasCachePoints(request: BedrockRequest): boolean {\n const inSystem = (request.system ?? []).some(\n (block) => \"cachePoint\" in block,\n );\n const inTools = (request.toolConfig?.tools ?? []).some(\n (tool) => \"cachePoint\" in tool,\n );\n return inSystem || inTools;\n }\n\n formatTools(toolkit: Toolkit): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: {\n ...tool.parameters,\n type: \"object\",\n } as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n // Bare JSON Schema node: `{ type: \"object\", properties: {...} }`\n if (isJsonSchema(schema)) {\n return structuredClone(schema);\n }\n\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n return z.toJSONSchema(zodSchema) as JsonObject;\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<AnnotatedBedrockResponse> {\n const bedrockClient = client as BedrockRuntimeClient;\n const bedrockRequest = request as BedrockRequest;\n\n const { ConverseCommand } = await import(\"@aws-sdk/client-bedrock-runtime\");\n const wantsStructuredOutput = Boolean(bedrockRequest.outputConfig);\n\n try {\n const response = (await bedrockClient.send(\n new ConverseCommand(bedrockRequest as ConverseCommandInput),\n signal ? { abortSignal: signal } : undefined,\n )) as AnnotatedBedrockResponse;\n if (wantsStructuredOutput) response.__jaypieStructuredOutput = true;\n return response;\n } catch (error) {\n if (\n bedrockRequest.inferenceConfig?.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(\n bedrockRequest.modelId || this.defaultModel,\n );\n const retryRequest: BedrockRequest = {\n ...bedrockRequest,\n inferenceConfig: { ...bedrockRequest.inferenceConfig },\n };\n delete retryRequest.inferenceConfig!.temperature;\n const response = (await bedrockClient.send(\n new ConverseCommand(retryRequest as ConverseCommandInput),\n signal ? { abortSignal: signal } : undefined,\n )) as AnnotatedBedrockResponse;\n if (wantsStructuredOutput) response.__jaypieStructuredOutput = true;\n return response;\n }\n\n if (wantsStructuredOutput && isOutputConfigUnsupportedError(error)) {\n const model = bedrockRequest.modelId || this.defaultModel;\n this.rememberModelRejectsOutputConfig(model);\n const fallbackRequest =\n this.toFallbackStructuredOutputRequest(bedrockRequest);\n return (await bedrockClient.send(\n new ConverseCommand(fallbackRequest as ConverseCommandInput),\n signal ? { abortSignal: signal } : undefined,\n )) as AnnotatedBedrockResponse;\n }\n\n if (\n this.requestHasCachePoints(bedrockRequest) &&\n isCachePointUnsupportedError(error)\n ) {\n this.rememberModelRejectsCachePoint(\n bedrockRequest.modelId || this.defaultModel,\n );\n const retryRequest = this.stripCachePoints(bedrockRequest);\n const response = (await bedrockClient.send(\n new ConverseCommand(retryRequest as ConverseCommandInput),\n signal ? { abortSignal: signal } : undefined,\n )) as AnnotatedBedrockResponse;\n if (wantsStructuredOutput) response.__jaypieStructuredOutput = true;\n return response;\n }\n throw error;\n }\n }\n\n private toFallbackStructuredOutputRequest(\n request: BedrockRequest,\n ): BedrockRequest {\n const { outputConfig, ...rest } = request;\n if (!outputConfig?.textFormat?.structure) return request;\n let schema: Record<string, unknown>;\n try {\n schema = JSON.parse(\n (\n outputConfig.textFormat.structure as {\n jsonSchema?: { schema?: string };\n }\n ).jsonSchema?.schema ?? \"{}\",\n ) as Record<string, unknown>;\n } catch {\n schema = {};\n }\n const fakeTool = {\n toolSpec: {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n inputSchema: { json: schema },\n },\n };\n return {\n ...rest,\n toolConfig: {\n tools: [...(rest.toolConfig?.tools ?? []), fakeTool] as NonNullable<\n ConverseCommandInput[\"toolConfig\"]\n >[\"tools\"],\n },\n };\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const bedrockClient = client as BedrockRuntimeClient;\n const bedrockRequest = request as BedrockRequest;\n\n const { ConverseStreamCommand } =\n await import(\"@aws-sdk/client-bedrock-runtime\");\n\n const response = await bedrockClient.send(\n new ConverseStreamCommand(bedrockRequest as ConverseCommandInput),\n signal ? { abortSignal: signal } : undefined,\n );\n\n if (!response.stream) return;\n\n let currentToolCall: {\n toolUseId: string;\n name: string;\n arguments: string;\n } | null = null;\n\n let inputTokens = 0;\n let outputTokens = 0;\n const model = bedrockRequest.modelId || this.defaultModel;\n\n for await (const event of response.stream) {\n if (event.contentBlockStart?.start?.toolUse) {\n const toolUse = event.contentBlockStart.start.toolUse;\n currentToolCall = {\n toolUseId: toolUse.toolUseId || \"\",\n name: toolUse.name || \"\",\n arguments: \"\",\n };\n } else if (event.contentBlockDelta?.delta) {\n const delta = event.contentBlockDelta.delta;\n if (delta.text !== undefined) {\n yield { type: LlmStreamChunkType.Text, content: delta.text };\n } else if (delta.toolUse?.input && currentToolCall) {\n currentToolCall.arguments += delta.toolUse.input;\n }\n } else if (event.contentBlockStop && currentToolCall) {\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.toolUseId,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n currentToolCall = null;\n } else if (event.metadata?.usage) {\n inputTokens = event.metadata.usage.inputTokens ?? 0;\n outputTokens = event.metadata.usage.outputTokens ?? 0;\n } else if (event.messageStop) {\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: 0,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n }\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n options?: LlmOperateOptions,\n ): ParsedResponse {\n const bedrockResponse = response as ConverseCommandOutput;\n const message = bedrockResponse.output?.message;\n const rawContent = this.extractContentFromMessage(message);\n\n let content: string | JsonObject | undefined = rawContent;\n if (options?.format && typeof rawContent === \"string\") {\n content = extractJson(rawContent) ?? rawContent;\n }\n\n // Don't surface structured_output fake tool as a real tool call\n const allToolUses = (\n (bedrockResponse.output?.message?.content ?? []) as BedrockContentBlock[]\n ).filter((b) => \"toolUse\" in b) as {\n toolUse: { name: string };\n }[];\n const hasOnlyStructuredOutputTool =\n allToolUses.length > 0 &&\n allToolUses.every((b) => b.toolUse.name === STRUCTURED_OUTPUT_TOOL_NAME);\n const hasToolCalls =\n bedrockResponse.stopReason === \"tool_use\" && !hasOnlyStructuredOutputTool;\n\n return {\n content,\n hasToolCalls,\n stopReason: bedrockResponse.stopReason ?? undefined,\n usage: this.extractUsage(\n bedrockResponse,\n (bedrockResponse as unknown as BedrockRequest).modelId ||\n this.defaultModel,\n ),\n raw: bedrockResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const bedrockResponse = response as ConverseCommandOutput;\n const content = bedrockResponse.output?.message?.content ?? [];\n const toolCalls: StandardToolCall[] = [];\n\n for (const block of content) {\n const typedBlock = block as BedrockContentBlock;\n if (\"toolUse\" in typedBlock && typedBlock.toolUse) {\n const toolUse = typedBlock.toolUse;\n toolCalls.push({\n callId: toolUse.toolUseId,\n name: toolUse.name,\n arguments: JSON.stringify(toolUse.input),\n raw: typedBlock,\n });\n }\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const bedrockResponse = response as ConverseCommandOutput;\n const usage = bedrockResponse.usage as\n | {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n cacheReadInputTokens?: number;\n cacheWriteInputTokens?: number;\n }\n | undefined;\n\n return {\n input: usage?.inputTokens ?? 0,\n output: usage?.outputTokens ?? 0,\n reasoning: 0,\n total:\n usage?.totalTokens ??\n (usage?.inputTokens ?? 0) + (usage?.outputTokens ?? 0),\n ...(usage?.cacheReadInputTokens !== undefined\n ? { cacheRead: usage.cacheReadInputTokens }\n : {}),\n ...(usage?.cacheWriteInputTokens !== undefined\n ? { cacheWrite: usage.cacheWriteInputTokens }\n : {}),\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): BedrockContentBlock {\n return {\n toolResult: {\n toolUseId: toolCall.callId,\n content: [{ text: result.output }],\n },\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): BedrockRequest {\n const bedrockRequest = request as BedrockRequest;\n const toolCallRaw = toolCall.raw as BedrockContentBlock;\n\n bedrockRequest.messages.push({\n role: \"assistant\",\n content: [toolCallRaw],\n });\n\n bedrockRequest.messages.push({\n role: \"user\",\n content: [this.formatToolResult(toolCall, result)],\n });\n\n return bedrockRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const bedrockResponse = response as ConverseCommandOutput;\n const historyItems: LlmHistory = [];\n\n if (bedrockResponse.stopReason === \"tool_use\") {\n return historyItems;\n }\n\n const content = bedrockResponse.output?.message?.content ?? [];\n const textBlock = (content as BedrockContentBlock[]).find(\n (block) => \"text\" in block,\n ) as { text: string } | undefined;\n\n if (textBlock) {\n historyItems.push({\n content: textBlock.text,\n role: \"assistant\",\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n const errorName = (error as Error)?.constructor?.name;\n const errorMessage = (error as Error)?.message ?? \"\";\n\n if (\n errorName === \"ThrottlingException\" ||\n errorMessage.includes(\"ThrottlingException\") ||\n errorMessage.includes(\"Too Many Requests\")\n ) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n if (\n errorName === \"ServiceUnavailableException\" ||\n errorName === \"InternalServerException\" ||\n errorMessage.includes(\"ServiceUnavailableException\") ||\n errorMessage.includes(\"InternalServerException\")\n ) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n if (\n errorName === \"AccessDeniedException\" ||\n errorName === \"ValidationException\" ||\n errorName === \"ResourceNotFoundException\" ||\n errorMessage.includes(\"AccessDeniedException\") ||\n errorMessage.includes(\"ValidationException\")\n ) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Structured Output\n //\n\n override hasStructuredOutput(response: unknown): boolean {\n const bedrockResponse = response as AnnotatedBedrockResponse;\n if (bedrockResponse.__jaypieStructuredOutput) {\n return this.extractStructuredOutput(response) !== undefined;\n }\n // Fake-tool path: last content block is a structured_output toolUse\n const content = (bedrockResponse.output?.message?.content ??\n []) as BedrockContentBlock[];\n const last = content[content.length - 1];\n return (\n !!last &&\n \"toolUse\" in last &&\n last.toolUse.name === STRUCTURED_OUTPUT_TOOL_NAME\n );\n }\n\n override extractStructuredOutput(response: unknown): JsonObject | undefined {\n const bedrockResponse = response as AnnotatedBedrockResponse;\n\n if (bedrockResponse.__jaypieStructuredOutput) {\n const content = (bedrockResponse.output?.message?.content ??\n []) as BedrockContentBlock[];\n const textBlock = content.find((b) => \"text\" in b) as\n { text: string } | undefined;\n if (!textBlock) return undefined;\n return extractJson(textBlock.text);\n }\n\n // Fake-tool path\n const content = (bedrockResponse.output?.message?.content ??\n []) as BedrockContentBlock[];\n const last = content[content.length - 1];\n if (\n last &&\n \"toolUse\" in last &&\n last.toolUse.name === STRUCTURED_OUTPUT_TOOL_NAME\n ) {\n return last.toolUse.input as JsonObject;\n }\n return undefined;\n }\n\n //\n // Completion Detection\n //\n\n isComplete(response: unknown): boolean {\n const bedrockResponse = response as ConverseCommandOutput;\n return bedrockResponse.stopReason !== \"tool_use\";\n }\n\n //\n // Private Helpers\n //\n\n private extractContentFromMessage(\n message: { content?: unknown[] } | undefined,\n ): string | JsonObject | undefined {\n if (!message?.content) return undefined;\n\n const content = message.content as BedrockContentBlock[];\n const textBlock = content.find((block) => \"text\" in block) as\n { text: string } | undefined;\n\n return textBlock?.text;\n }\n}\n\nexport const bedrockAdapter = new BedrockAdapter();\n","import { log } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { paperedEffortMessage, toFireworksEffort } from \"../../util/effort.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmInputContent,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport { isJsonSchema, naturalZodSchema } from \"../../util/index.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { FireworksClient } from \"../../providers/fireworks/client.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\n\n//\n//\n// Types\n//\n\ninterface FireworksMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content?: string | FireworksContentPart[] | null;\n toolCalls?: FireworksToolCall[];\n toolCallId?: string;\n}\n\ninterface FireworksToolCall {\n id: string;\n type: \"function\";\n function: {\n name: string;\n arguments: string;\n };\n}\n\ninterface FireworksResponseMessage {\n role: \"assistant\";\n content?: string | null;\n toolCalls?: FireworksToolCall[];\n refusal?: string | null;\n reasoning?: string | null;\n reasoning_content?: string | null;\n}\n\ninterface FireworksChoice {\n index: number;\n message: FireworksResponseMessage;\n finishReason: string | null;\n finish_reason?: string | null;\n}\n\ninterface FireworksUsage {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n completionTokensDetails?: {\n reasoningTokens?: number;\n };\n}\n\ninterface FireworksResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: FireworksChoice[];\n usage?: FireworksUsage;\n}\n\ninterface FireworksTool {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: JsonObject;\n };\n}\n\ninterface FireworksJsonSchemaConfig {\n name: string;\n description?: string;\n schema: JsonObject;\n strict?: boolean;\n}\n\ntype FireworksResponseFormat =\n | { type: \"json_schema\"; json_schema: FireworksJsonSchemaConfig }\n | { type: \"json_object\" }\n | { type: \"text\" };\n\ninterface FireworksRequest {\n model: string;\n messages: FireworksMessage[];\n tools?: FireworksTool[];\n tool_choice?: \"auto\" | \"none\" | \"required\";\n response_format?: FireworksResponseFormat;\n reasoning_effort?: string;\n user?: string;\n}\n\n/**\n * Fireworks responses we annotate at receive time so downstream stateless\n * methods (`hasStructuredOutput`, `extractStructuredOutput`) can tell whether\n * the request asked for native structured output without re-threading the\n * request.\n */\ntype AnnotatedFireworksResponse = FireworksResponse & {\n __jaypieStructuredOutput?: boolean;\n};\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\nconst STRUCTURED_OUTPUT_SCHEMA_NAME = \"response\";\n\n/**\n * Detect 4xx errors that indicate the model itself does not support\n * `response_format: json_schema`. We only trigger the fake-tool fallback when\n * the failure is plausibly a capability gap, not a generic 400.\n */\nfunction isStructuredOutputUnsupportedError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n statusCode?: number;\n message?: string;\n error?: { message?: string };\n };\n const status = err.status ?? err.statusCode;\n if (status !== 400 && status !== 422) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) =>\n /response[_ ]format|json[_ ]schema|structured[_ ]output/i.test(m),\n );\n}\n\nfunction isTemperatureDeprecationError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n statusCode?: number;\n message?: string;\n error?: { message?: string };\n };\n const status = err.status ?? err.statusCode;\n if (status !== 400) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) => m.toLowerCase().includes(\"temperature\"));\n}\n\n/**\n * Fireworks content part types. Fireworks follows the OpenAI Chat Completions\n * multimodal schema for `image_url` parts (URL or base64 data URI). There is\n * no OpenAI-style `file` part, and the API rejects `data:` URIs for documents\n * (\"Unsupported URL scheme 'data'\"), so file inputs cannot be delivered.\n */\ntype FireworksContentPart =\n | { type: \"text\"; text: string }\n | { type: \"image_url\"; imageUrl: { url: string } };\n\n/**\n * Convert standardized content items to Fireworks format. Images become\n * `image_url` parts (vision models only; non-vision models 4xx — a\n * model-capability mismatch surfaced by the call). File inputs are warned\n * and discarded: Fireworks has no `file` part and rejects document `data:`\n * URIs outright, so there is no wire shape that can carry them.\n */\nfunction convertContentToFireworks(\n content: string | LlmInputContent[],\n): string | FireworksContentPart[] {\n if (typeof content === \"string\") {\n return content;\n }\n\n const parts: FireworksContentPart[] = [];\n\n for (const item of content) {\n if (item.type === LlmMessageType.InputText) {\n parts.push({ type: \"text\", text: item.text });\n continue;\n }\n\n if (item.type === LlmMessageType.InputImage) {\n const url = item.image_url ?? \"\";\n if (!url) {\n log.warn(\"Fireworks image content missing image_url; image discarded\");\n continue;\n }\n parts.push({ type: \"image_url\", imageUrl: { url } });\n continue;\n }\n\n if (item.type === LlmMessageType.InputFile) {\n log.warn(\n { filename: item.filename },\n \"Fireworks does not support file inputs (no file part; document data: URIs rejected); file discarded\",\n );\n continue;\n }\n\n // Unknown type - warn and skip\n log.warn({ item }, \"Unknown content type for Fireworks; discarded\");\n }\n\n // If no parts remain, return empty string to avoid empty array\n if (parts.length === 0) {\n return \"\";\n }\n\n return parts;\n}\n\n/**\n * Convert internal content parts to the OpenAI-compatible wire shape. The\n * internal representation uses camelCase keys (`imageUrl`); the REST API wants\n * snake_case (`image_url`).\n */\nfunction contentToWire(\n content: string | FireworksContentPart[] | null | undefined,\n): unknown {\n if (\n content === null ||\n content === undefined ||\n typeof content === \"string\"\n ) {\n return content;\n }\n return content.map((part) => {\n if (part.type === \"image_url\") {\n return { type: \"image_url\", image_url: part.imageUrl };\n }\n return part;\n });\n}\n\n/**\n * Serialize an internal message to the OpenAI-compatible wire shape, mapping\n * camelCase tool fields (`toolCalls`, `toolCallId`) to snake_case. Tool-call\n * objects are already wire-shaped (`{ id, type, function: { name, arguments } }`).\n */\nfunction messageToWire(message: FireworksMessage): Record<string, unknown> {\n const wire: Record<string, unknown> = { role: message.role };\n if (message.content !== undefined) {\n wire.content = contentToWire(message.content);\n }\n if (message.toolCalls) {\n wire.tool_calls = message.toolCalls;\n }\n if (message.toolCallId) {\n wire.tool_call_id = message.toolCallId;\n }\n return wire;\n}\n\n// Fireworks error types based on HTTP status codes\nconst RETRYABLE_STATUS_CODES = [408, 500, 502, 503, 524, 529];\nconst RATE_LIMIT_STATUS_CODE = 429;\n\n/**\n * Walk the JSON schema and force `additionalProperties: false` on every\n * object node. Required by the OpenAI-style json_schema response_format when\n * `strict: true`.\n */\nfunction enforceAdditionalPropertiesFalse(schema: JsonObject): void {\n const stack: JsonObject[] = [schema];\n while (stack.length > 0) {\n const node = stack.pop() as JsonObject;\n if (node.type === \"object\") {\n node.additionalProperties = false;\n }\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const entry of value) {\n if (entry && typeof entry === \"object\" && !Array.isArray(entry)) {\n stack.push(entry as JsonObject);\n }\n }\n } else if (value && typeof value === \"object\") {\n stack.push(value as JsonObject);\n }\n }\n }\n}\n\n//\n//\n// Main\n//\n\n/**\n * FireworksAdapter implements the ProviderAdapter interface for Fireworks AI's\n * OpenAI-compatible Chat Completions API. It handles request building,\n * response parsing, and error classification specific to Fireworks.\n */\nexport class FireworksAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.FIREWORKS.NAME;\n readonly defaultModel = PROVIDER.FIREWORKS.DEFAULT;\n\n // Structured output with tools rides the structured_output tool emulation\n // (Fireworks rejects response_format + tools), and emulation compliance is\n // a model decision — opt in to OperateLoop's corrective retry turn.\n override readonly supportsStructuredOutputRetry = true;\n\n // Session-level cache of models observed to reject native\n // `response_format: json_schema`. When a model is in this set, buildRequest\n // engages the legacy fake-tool path instead of native structured output.\n private runtimeNoStructuredOutputModels = new Set<string>();\n\n rememberModelRejectsStructuredOutput(model: string): void {\n this.runtimeNoStructuredOutputModels.add(model);\n }\n\n clearRuntimeNoStructuredOutputModels(): void {\n this.runtimeNoStructuredOutputModels.clear();\n }\n\n private supportsStructuredOutput(model: string): boolean {\n return !this.runtimeNoStructuredOutputModels.has(model);\n }\n\n // Session-level cache of models observed to reject `temperature`. Populated\n // by executeRequest on 400 errors so repeat calls skip the param.\n private runtimeNoTemperatureModels = new Set<string>();\n\n rememberModelRejectsTemperature(model: string): void {\n this.runtimeNoTemperatureModels.add(model);\n }\n\n clearRuntimeNoTemperatureModels(): void {\n this.runtimeNoTemperatureModels.clear();\n }\n\n private supportsTemperature(model: string): boolean {\n return !this.runtimeNoTemperatureModels.has(model);\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): FireworksRequest {\n // Convert messages to Fireworks format (OpenAI-compatible)\n const messages: FireworksMessage[] = this.convertMessagesToFireworks(\n request.messages,\n request.system,\n );\n\n // Append instructions to last message if provided\n if (request.instructions && messages.length > 0) {\n const lastMsg = messages[messages.length - 1];\n if (lastMsg.content && typeof lastMsg.content === \"string\") {\n lastMsg.content = lastMsg.content + \"\\n\\n\" + request.instructions;\n }\n }\n\n const fireworksRequest: FireworksRequest = {\n model: request.model || this.defaultModel,\n messages,\n };\n\n if (request.user) {\n fireworksRequest.user = request.user;\n }\n\n // Fireworks rejects `response_format` combined with `tools` (\"You cannot\n // specify response format and function call at the same time\"), so a\n // request with both preemptively uses the structured_output tool\n // emulation — same approach as Gemini 2.5.\n const hasCallerTools = Boolean(request.tools?.length);\n const useFallbackStructuredOutput =\n Boolean(request.format) &&\n (hasCallerTools ||\n !this.supportsStructuredOutput(fireworksRequest.model));\n\n // On a corrective retry turn (the model answered a format request with\n // prose), offer only the structured_output tool so the demanded call is\n // the sole option.\n const allTools: ProviderToolDefinition[] =\n request.tools && !request.structuredOutputRetry ? [...request.tools] : [];\n if (useFallbackStructuredOutput && request.format) {\n log.warn(\n hasCallerTools\n ? `[FireworksAdapter] Fireworks does not support response_format combined with tools; using structured_output tool emulation for model ${fireworksRequest.model}.`\n : `[FireworksAdapter] Using legacy structured_output tool fallback for model ${fireworksRequest.model}; native response_format previously rejected for this model.`,\n );\n allTools.push({\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n parameters: request.format,\n });\n }\n\n if (allTools.length > 0) {\n fireworksRequest.tools = allTools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n\n // Use \"auto\" for tool_choice - not all Fireworks models support \"required\"\n // The structured_output tool prompt already emphasizes it must be called\n fireworksRequest.tool_choice = \"auto\";\n }\n\n // Native structured output: send schema as `response_format`. The legacy\n // tool-emulation path is engaged only as a runtime fallback for models the\n // API has flagged as not supporting native json_schema.\n if (request.format && !useFallbackStructuredOutput) {\n fireworksRequest.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: STRUCTURED_OUTPUT_SCHEMA_NAME,\n schema: request.format,\n strict: true,\n },\n };\n }\n\n if (request.providerOptions) {\n Object.assign(fireworksRequest, request.providerOptions);\n }\n\n // Normalized reasoning effort -> reasoning_effort. Fireworks accepts the\n // param on every model and no-ops where unsupported, so no per-model\n // gating. First-class effort wins over providerOptions.\n if (request.effort) {\n const mapping = toFireworksEffort(request.effort);\n if (mapping.papered) {\n log.debug(\n paperedEffortMessage({\n model: fireworksRequest.model,\n provider: this.name,\n requested: request.effort,\n value: mapping.value,\n }),\n );\n }\n fireworksRequest.reasoning_effort = mapping.value as string;\n }\n\n // First-class temperature takes precedence over providerOptions\n if (request.temperature !== undefined) {\n (fireworksRequest as unknown as Record<string, unknown>).temperature =\n request.temperature;\n }\n\n // Strip temperature for models the runtime has cached as rejecting it\n const requestRecord = fireworksRequest as unknown as Record<\n string,\n unknown\n >;\n if (\n requestRecord.temperature !== undefined &&\n !this.supportsTemperature(fireworksRequest.model)\n ) {\n delete requestRecord.temperature;\n }\n\n return fireworksRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n // outputSchema is part of the interface contract but Fireworks uses native\n // `response_format` (set in buildRequest); the legacy fake-tool injection\n // happens in buildRequest only as a runtime fallback.\n\n _outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n let jsonSchema: JsonObject;\n\n // Check if schema is already a JsonObject — either the OpenAI-style\n // `{ type: \"json_schema\", ... }` envelope or a bare `{ type: \"object\", properties }` node\n if (\n (typeof schema === \"object\" &&\n schema !== null &&\n !Array.isArray(schema) &&\n (schema as JsonObject).type === \"json_schema\") ||\n isJsonSchema(schema)\n ) {\n jsonSchema = structuredClone(schema) as JsonObject;\n jsonSchema.type = \"object\"; // Normalize type\n } else {\n // Convert NaturalSchema to JSON schema through Zod. Re-spread into a\n // plain object to drop Zod v4's non-enumerable `~standard` marker.\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n jsonSchema = { ...(z.toJSONSchema(zodSchema) as JsonObject) };\n }\n\n // Remove $schema property (can cause issues with some providers)\n if (jsonSchema.$schema) {\n delete jsonSchema.$schema;\n }\n\n // Strict json_schema response_format requires additionalProperties: false\n // on every object.\n enforceAdditionalPropertiesFalse(jsonSchema);\n\n return jsonSchema;\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<FireworksResponse> {\n const fireworks = client as FireworksClient;\n const fireworksRequest = request as FireworksRequest;\n const wantsStructuredOutput = Boolean(fireworksRequest.response_format);\n\n try {\n const response = (await fireworks.chatCompletion(\n this.toWireBody(fireworksRequest),\n signal ? { signal } : undefined,\n )) as unknown as AnnotatedFireworksResponse;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as FireworksResponse;\n\n // If the model rejected `temperature`, cache it and retry without the param.\n const requestRecord = fireworksRequest as unknown as Record<\n string,\n unknown\n >;\n if (\n requestRecord.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(fireworksRequest.model);\n const retryRequest = { ...fireworksRequest } as FireworksRequest;\n delete (retryRequest as unknown as Record<string, unknown>).temperature;\n const response = (await fireworks.chatCompletion(\n this.toWireBody(retryRequest),\n signal ? { signal } : undefined,\n )) as unknown as AnnotatedFireworksResponse;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n }\n\n // If the model rejected `response_format`, cache it and retry with the\n // legacy fake-tool emulation path.\n if (wantsStructuredOutput && isStructuredOutputUnsupportedError(error)) {\n const model = fireworksRequest.model;\n this.rememberModelRejectsStructuredOutput(model);\n log.warn(\n `[FireworksAdapter] Model ${model} rejected native response_format; falling back to legacy structured_output tool emulation.`,\n );\n const fallbackRequest =\n this.toFallbackStructuredOutputRequest(fireworksRequest);\n return (await fireworks.chatCompletion(\n this.toWireBody(fallbackRequest),\n signal ? { signal } : undefined,\n )) as unknown as FireworksResponse;\n }\n\n throw error;\n }\n }\n\n /**\n * Serialize the internal request into the OpenAI-compatible wire body for\n * Fireworks' Chat Completions endpoint. Top-level fields (model, tools,\n * tool_choice, response_format, reasoning_effort, user, temperature, and any\n * providerOptions) are already wire-shaped (snake_case); only messages carry\n * camelCase tool fields that must become snake_case on the wire.\n */\n private toWireBody(\n fireworksRequest: FireworksRequest,\n ): Record<string, unknown> {\n return {\n ...fireworksRequest,\n messages: fireworksRequest.messages.map(messageToWire),\n };\n }\n\n /**\n * Rebuild a structured-output request without `response_format`, swapping in\n * the legacy fake-tool emulation. Used as a runtime fallback when a model\n * rejects native json_schema.\n */\n private toFallbackStructuredOutputRequest(\n request: FireworksRequest,\n ): FireworksRequest {\n if (\n !request.response_format ||\n request.response_format.type !== \"json_schema\"\n ) {\n return request;\n }\n const { response_format, ...rest } = request;\n const fallbackRequest: FireworksRequest = { ...rest };\n const schema = response_format.json_schema.schema;\n const fakeTool: FireworksTool = {\n type: \"function\" as const,\n function: {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n parameters: schema,\n },\n };\n fallbackRequest.tools = [...(fallbackRequest.tools ?? []), fakeTool];\n fallbackRequest.tool_choice = \"auto\";\n return fallbackRequest;\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const fireworks = client as FireworksClient;\n const fireworksRequest = request as FireworksRequest;\n\n // streamChatCompletion adds `stream: true` + `stream_options.include_usage`\n // and yields decoded SSE chunks in OpenAI-compatible (snake_case) shape.\n const stream = fireworks.streamChatCompletion(\n this.toWireBody(fireworksRequest),\n signal ? { signal } : undefined,\n ) as AsyncIterable<unknown>;\n\n // Track current tool call being built\n let currentToolCall: {\n id: string;\n name: string;\n arguments: string;\n } | null = null;\n\n // Track usage for final chunk\n let inputTokens = 0;\n let outputTokens = 0;\n const model = fireworksRequest.model || this.defaultModel;\n\n for await (const chunk of stream) {\n // Handle different chunk types from Fireworks (OpenAI-compatible format)\n interface StreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n // Reasoning deltas arrive on reasoning_content; kept out of the\n // text stream so `content` remains the final answer only.\n reasoning_content?: string;\n tool_calls?: Array<{\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason?: string;\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n promptTokens?: number;\n completionTokens?: number;\n };\n }\n const typedChunk = chunk as StreamChunk;\n const choices = typedChunk.choices;\n\n if (choices && choices.length > 0) {\n const delta = choices[0].delta;\n\n // Handle text content\n if (delta?.content) {\n yield {\n type: LlmStreamChunkType.Text,\n content: delta.content,\n };\n }\n\n // Handle tool calls\n if (delta?.tool_calls && delta.tool_calls.length > 0) {\n for (const toolCallDelta of delta.tool_calls) {\n if (toolCallDelta.id) {\n // New tool call starting\n if (currentToolCall) {\n // Emit the previous tool call\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.id,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n }\n currentToolCall = {\n id: toolCallDelta.id,\n name: toolCallDelta.function?.name || \"\",\n arguments: toolCallDelta.function?.arguments || \"\",\n };\n } else if (currentToolCall) {\n // Continuing existing tool call\n if (toolCallDelta.function?.name) {\n currentToolCall.name += toolCallDelta.function.name;\n }\n if (toolCallDelta.function?.arguments) {\n currentToolCall.arguments += toolCallDelta.function.arguments;\n }\n }\n }\n }\n\n // Check for finish reason\n if (choices[0].finish_reason) {\n // Emit any pending tool call\n if (currentToolCall) {\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.id,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n currentToolCall = null;\n }\n }\n }\n\n // Extract usage if present (usually in the final chunk)\n if (typedChunk.usage) {\n inputTokens =\n typedChunk.usage.prompt_tokens || typedChunk.usage.promptTokens || 0;\n outputTokens =\n typedChunk.usage.completion_tokens ||\n typedChunk.usage.completionTokens ||\n 0;\n }\n }\n\n // Emit done chunk with final usage\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: 0,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n _options?: LlmOperateOptions,\n ): ParsedResponse {\n const fireworksResponse = response as FireworksResponse;\n const choice = fireworksResponse.choices[0];\n\n const content = this.extractContent(fireworksResponse);\n const hasToolCalls = this.hasToolCalls(fireworksResponse);\n\n const stopReason =\n choice?.finishReason ?? choice?.finish_reason ?? undefined;\n\n return {\n content,\n hasToolCalls,\n stopReason,\n usage: this.extractUsage(fireworksResponse, fireworksResponse.model),\n raw: fireworksResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const fireworksResponse = response as FireworksResponse;\n const toolCalls: StandardToolCall[] = [];\n const choice = fireworksResponse.choices[0];\n\n if (!choice?.message?.toolCalls) {\n return toolCalls;\n }\n\n for (const toolCall of choice.message.toolCalls) {\n toolCalls.push({\n callId: toolCall.id,\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n raw: toolCall,\n });\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const fireworksResponse = response as FireworksResponse;\n\n if (!fireworksResponse.usage) {\n return {\n input: 0,\n output: 0,\n reasoning: 0,\n total: 0,\n provider: this.name,\n model,\n };\n }\n\n const usage = fireworksResponse.usage;\n return {\n input: usage.promptTokens || usage.prompt_tokens || 0,\n output: usage.completionTokens || usage.completion_tokens || 0,\n reasoning: usage.completionTokensDetails?.reasoningTokens || 0,\n total: usage.totalTokens || usage.total_tokens || 0,\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): FireworksMessage {\n return {\n role: \"tool\",\n toolCallId: toolCall.callId,\n content: result.output,\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): FireworksRequest {\n const fireworksRequest = request as FireworksRequest;\n const toolCallRaw = toolCall.raw as FireworksToolCall;\n\n // Add assistant message with the tool call\n fireworksRequest.messages.push({\n role: \"assistant\",\n content: null,\n toolCalls: [toolCallRaw],\n });\n\n // Add tool result message\n fireworksRequest.messages.push(this.formatToolResult(toolCall, result));\n\n return fireworksRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const fireworksResponse = response as FireworksResponse;\n const historyItems: LlmHistory = [];\n const choice = fireworksResponse.choices[0];\n\n if (!choice?.message) {\n return historyItems;\n }\n\n // Check if this is a tool use response\n if (choice.message.toolCalls && choice.message.toolCalls.length > 0) {\n // Don't add to history yet - will be added after tool execution\n return historyItems;\n }\n\n // Extract text content for non-tool responses\n if (choice.message.content) {\n const historyItem: LlmOutputMessage & { reasoning?: string } = {\n content: choice.message.content,\n role: LlmMessageRole.Assistant,\n type: LlmMessageType.Message,\n };\n\n // Preserve reasoning if present. Fireworks reasoning models return it in\n // reasoning_content; some routes use reasoning.\n const reasoning =\n choice.message.reasoning_content ?? choice.message.reasoning;\n if (reasoning) {\n historyItem.reasoning = reasoning;\n }\n\n historyItems.push(historyItem as LlmOutputMessage);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n // Check if error has a status code (HTTP error)\n const errorWithStatus = error as { status?: number; statusCode?: number };\n const statusCode = errorWithStatus.status || errorWithStatus.statusCode;\n\n if (statusCode) {\n // Rate limit error\n if (statusCode === RATE_LIMIT_STATUS_CODE) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Retryable errors (server errors, timeouts, etc.)\n if (RETRYABLE_STATUS_CODES.includes(statusCode)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Client errors (4xx except 429) are unrecoverable\n if (statusCode >= 400 && statusCode < 500) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n }\n\n // Check error message for rate limit indicators\n const errorMessage =\n error instanceof Error ? error.message.toLowerCase() : \"\";\n if (\n errorMessage.includes(\"rate limit\") ||\n errorMessage.includes(\"too many requests\")\n ) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Check for transient network errors (ECONNRESET, etc.)\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Unknown error - treat as potentially retryable\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Provider-Specific Features\n //\n\n isComplete(response: unknown): boolean {\n const fireworksResponse = response as FireworksResponse;\n const choice = fireworksResponse.choices[0];\n\n // Complete if no tool calls\n if (!choice?.message?.toolCalls?.length) {\n return true;\n }\n\n return false;\n }\n\n override hasStructuredOutput(response: unknown): boolean {\n const fireworksResponse = response as AnnotatedFireworksResponse;\n\n // Native path: executeRequest annotates the response when we sent\n // `response_format`, so we can detect intent statelessly.\n if (fireworksResponse.__jaypieStructuredOutput) {\n return this.extractStructuredOutput(response) !== undefined;\n }\n\n // Fallback path: legacy fake-tool emulation, kept for models that the\n // runtime has cached as not supporting native `response_format`.\n const choice = fireworksResponse.choices[0];\n\n if (!choice?.message?.toolCalls?.length) {\n return false;\n }\n\n // Check if the last tool call is structured_output\n const lastToolCall =\n choice.message.toolCalls[choice.message.toolCalls.length - 1];\n return lastToolCall?.function?.name === STRUCTURED_OUTPUT_TOOL_NAME;\n }\n\n override extractStructuredOutput(response: unknown): JsonObject | undefined {\n const fireworksResponse = response as AnnotatedFireworksResponse;\n\n if (fireworksResponse.__jaypieStructuredOutput) {\n const choice = fireworksResponse.choices[0];\n const content = choice?.message?.content;\n if (typeof content !== \"string\" || content.length === 0) {\n return undefined;\n }\n try {\n return JSON.parse(content) as JsonObject;\n } catch {\n return undefined;\n }\n }\n\n // Fallback path: legacy fake-tool emulation\n const choice = fireworksResponse.choices[0];\n\n if (!choice?.message?.toolCalls?.length) {\n return undefined;\n }\n\n const lastToolCall =\n choice.message.toolCalls[choice.message.toolCalls.length - 1];\n if (lastToolCall?.function?.name === STRUCTURED_OUTPUT_TOOL_NAME) {\n try {\n return JSON.parse(lastToolCall.function.arguments) as JsonObject;\n } catch {\n return undefined;\n }\n }\n\n return undefined;\n }\n\n //\n // Private Helpers\n //\n\n private hasToolCalls(response: FireworksResponse): boolean {\n const choice = response.choices[0];\n return (choice?.message?.toolCalls?.length ?? 0) > 0;\n }\n\n private extractContent(\n response: FireworksResponse,\n ): string | JsonObject | undefined {\n // Check for structured output first\n if (this.hasStructuredOutput(response)) {\n return this.extractStructuredOutput(response);\n }\n\n const choice = response.choices[0];\n return choice?.message?.content ?? undefined;\n }\n\n private convertMessagesToFireworks(\n messages: LlmHistory,\n system?: string,\n ): FireworksMessage[] {\n const fireworksMessages: FireworksMessage[] = [];\n\n // Add system message if provided\n if (system) {\n fireworksMessages.push({\n role: \"system\",\n content: system,\n });\n }\n\n for (const msg of messages) {\n const message = msg as unknown as Record<string, unknown>;\n\n // Handle different message types\n if (message.role === \"system\") {\n fireworksMessages.push({\n role: \"system\",\n content: message.content as string,\n });\n } else if (message.role === \"user\") {\n fireworksMessages.push({\n role: \"user\",\n content: convertContentToFireworks(\n message.content as string | LlmInputContent[],\n ),\n });\n } else if (message.role === \"assistant\") {\n const assistantMsg: FireworksMessage = {\n role: \"assistant\",\n content: (message.content as string) || null,\n };\n\n // Include toolCalls if present (check both camelCase and snake_case for compatibility)\n if (message.toolCalls) {\n assistantMsg.toolCalls = message.toolCalls as FireworksToolCall[];\n } else if (message.tool_calls) {\n assistantMsg.toolCalls = message.tool_calls as FireworksToolCall[];\n }\n\n fireworksMessages.push(assistantMsg);\n } else if (message.role === \"tool\") {\n fireworksMessages.push({\n role: \"tool\",\n toolCallId:\n (message.toolCallId as string) || (message.tool_call_id as string),\n content: message.content as string,\n });\n } else if (message.type === LlmMessageType.Message) {\n // Handle internal message format\n const role = (message.role as string)?.toLowerCase();\n if (role === \"assistant\") {\n fireworksMessages.push({\n role: \"assistant\",\n content: message.content as string,\n });\n } else {\n fireworksMessages.push({\n role: \"user\",\n content: convertContentToFireworks(\n message.content as string | LlmInputContent[],\n ),\n });\n }\n } else if (message.type === LlmMessageType.FunctionCall) {\n fireworksMessages.push({\n role: \"assistant\",\n content: null,\n toolCalls: [\n {\n id: message.call_id as string,\n type: \"function\" as const,\n function: {\n name: message.name as string,\n arguments: (message.arguments as string) || \"{}\",\n },\n },\n ],\n });\n } else if (message.type === LlmMessageType.FunctionCallOutput) {\n fireworksMessages.push({\n role: \"tool\",\n toolCallId: message.call_id as string,\n content: (message.output as string) || \"\",\n });\n }\n }\n\n return fireworksMessages;\n }\n}\n\n// Export singleton instance\nexport const fireworksAdapter = new FireworksAdapter();\n","import { log } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n paperedEffortMessage,\n toGeminiThinkingBudget,\n toGeminiThinkingLevel,\n} from \"../../util/effort.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n isJsonSchema,\n jsonSchemaToOpenApi3,\n naturalZodSchema,\n resolveMaxOutputTokens,\n} from \"../../util/index.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { GoogleClient } from \"../../providers/google/client.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\nimport {\n GeminiContent,\n GeminiErrorInfo,\n GeminiFunctionCall,\n GeminiFunctionDeclaration,\n GeminiPart,\n GeminiRawResponse,\n GeminiRequest,\n} from \"../../providers/google/types.js\";\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\n// Gemini 3 family supports combining tools (function calling) with native\n// structured output via `responseJsonSchema`. Earlier Gemini families\n// (including 2.5 thinking) do not support the combo and fall back to the\n// legacy `structured_output` fake-tool emulation.\nconst GEMINI_3_PATTERN = /^gemini-3/;\n\n// Reasoning-effort control differs by generation: Gemini 3.x takes the\n// `thinkingLevel` enum, Gemini 2.5 takes an integer `thinkingBudget`. Sending\n// the wrong one errors, and models outside these families have no thinking\n// control, so effort is only applied when one of these matches.\nconst GEMINI_25_PATTERN = /^gemini-2\\.5/;\n\n/**\n * Detect 4xx errors that indicate the model itself does not support the\n * `responseJsonSchema` + tools combo. Triggers the runtime fallback to the\n * fake-tool emulation path. Other 400s propagate.\n */\nfunction isStructuredOutputComboUnsupportedError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n code?: number;\n message?: string;\n error?: { message?: string };\n };\n const status = err.status ?? err.code;\n if (status !== 400) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) =>\n /response[_ ]?json[_ ]?schema|response[_ ]?schema|response[_ ]?mime|function[_ ]?call|tools/i.test(\n m,\n ),\n );\n}\n\n// Gemini uses HTTP status codes for error classification\n// Documented at: https://ai.google.dev/api/rest/v1beta/Status\nconst RETRYABLE_STATUS_CODES = [\n 408, // Request Timeout\n 429, // Too Many Requests (Rate Limit)\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n];\n\nconst NOT_RETRYABLE_STATUS_CODES = [\n 400, // Bad Request\n 401, // Unauthorized\n 403, // Forbidden\n 404, // Not Found\n 409, // Conflict\n 422, // Unprocessable Entity\n];\n\n//\n//\n// Main\n//\n\n/**\n * GoogleAdapter implements the ProviderAdapter interface for Google's Gemini API.\n * It handles request building, response parsing, and error classification\n * specific to Gemini's generateContent API.\n */\nexport class GoogleAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.GOOGLE.NAME;\n readonly defaultModel = PROVIDER.GOOGLE.DEFAULT;\n\n // Session-level cache of Gemini 3 models observed to reject the native\n // `responseJsonSchema` + tools combo. When a model is in this set,\n // buildRequest engages the legacy fake-tool path instead.\n private runtimeNoStructuredOutputComboModels = new Set<string>();\n\n rememberModelRejectsStructuredOutputCombo(model: string): void {\n this.runtimeNoStructuredOutputComboModels.add(model);\n }\n\n clearRuntimeNoStructuredOutputComboModels(): void {\n this.runtimeNoStructuredOutputComboModels.clear();\n }\n\n private supportsStructuredOutputCombo(model: string): boolean {\n if (this.runtimeNoStructuredOutputComboModels.has(model)) return false;\n return GEMINI_3_PATTERN.test(model);\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): GeminiRequest {\n // Convert messages to Gemini format (Content[])\n const contents: GeminiContent[] = this.convertMessagesToContents(\n request.messages,\n );\n\n const geminiRequest: GeminiRequest = {\n model: request.model || this.defaultModel,\n contents,\n };\n\n // Add system instruction if provided\n if (request.system) {\n geminiRequest.config = {\n ...geminiRequest.config,\n systemInstruction: request.system,\n };\n }\n\n // Append instructions to the last user message if provided\n if (request.instructions && contents.length > 0) {\n const lastContent = contents[contents.length - 1];\n if (lastContent.role === \"user\" && lastContent.parts) {\n const lastPart = lastContent.parts[lastContent.parts.length - 1];\n if (lastPart.text) {\n lastPart.text = lastPart.text + \"\\n\\n\" + request.instructions;\n }\n }\n }\n\n const hasUserTools = !!(request.tools && request.tools.length > 0);\n const useNativeCombo =\n Boolean(request.format) &&\n hasUserTools &&\n this.supportsStructuredOutputCombo(geminiRequest.model);\n\n // When tools+format are combined and the model does not support the native\n // combo, inject the legacy `structured_output` fake tool here so the model\n // is forced to call it before its final answer.\n const allTools: ProviderToolDefinition[] = request.tools\n ? [...request.tools]\n : [];\n if (request.format && hasUserTools && !useNativeCombo) {\n log.warn(\n `[GoogleAdapter] Using legacy structured_output tool fallback for model ${geminiRequest.model}; native responseJsonSchema + tools combo is only available on Gemini 3.`,\n );\n allTools.push({\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"Output a structured JSON object, \" +\n \"use this before your final response to give structured outputs to the user\",\n parameters: request.format,\n });\n }\n\n if (allTools.length > 0) {\n const functionDeclarations: GeminiFunctionDeclaration[] = allTools.map(\n (tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n }),\n );\n\n geminiRequest.config = {\n ...geminiRequest.config,\n tools: [{ functionDeclarations }],\n };\n }\n\n // Native structured output: send schema as `responseJsonSchema`\n // (or `responseSchema` for Gemini 2.5+ no-tools path). The legacy\n // fake-tool emulation only runs when format+tools is combined on a model\n // that doesn't support the native combo.\n const wantsNativeStructured =\n Boolean(request.format) && (!hasUserTools || useNativeCombo);\n\n if (wantsNativeStructured) {\n const useJsonSchema =\n useNativeCombo || request.providerOptions?.useJsonSchema === true;\n\n if (useJsonSchema) {\n geminiRequest.config = {\n ...geminiRequest.config,\n responseMimeType: \"application/json\",\n responseJsonSchema: request.format,\n };\n } else {\n geminiRequest.config = {\n ...geminiRequest.config,\n responseMimeType: \"application/json\",\n responseSchema: jsonSchemaToOpenApi3(request.format!),\n };\n }\n }\n\n // Legacy fake-tool path needs a system-prompt nudge so the model actually\n // calls the synthetic tool before its final answer.\n if (request.format && hasUserTools && !useNativeCombo) {\n const structuredOutputInstruction =\n \"IMPORTANT: Before providing your final response, you MUST use the structured_output tool \" +\n \"to output your answer in the required JSON format.\";\n\n const existingSystem = geminiRequest.config?.systemInstruction || \"\";\n geminiRequest.config = {\n ...geminiRequest.config,\n systemInstruction: existingSystem\n ? `${existingSystem}\\n\\n${structuredOutputInstruction}`\n : structuredOutputInstruction,\n };\n }\n\n // Default output ceiling: Google's own default (8,192) silently\n // truncates long generations, so resolve to the model maximum (capped\n // for non-streaming); providerOptions below override\n const maxOutputTokens = resolveMaxOutputTokens(geminiRequest.model, {\n stream: request.stream,\n });\n if (maxOutputTokens !== undefined) {\n geminiRequest.config = {\n ...geminiRequest.config,\n maxOutputTokens,\n };\n }\n\n // Add provider-specific options\n if (request.providerOptions) {\n geminiRequest.config = {\n ...geminiRequest.config,\n ...request.providerOptions,\n };\n }\n\n // Normalized reasoning effort -> thinkingConfig. Gemini 3.x uses the\n // thinkingLevel enum; 2.5 uses an integer thinkingBudget. Merged so a\n // providerOptions.thinkingConfig survives; first-class effort wins.\n if (request.effort) {\n const model = geminiRequest.model;\n let thinkingConfig:\n { thinkingLevel?: string; thinkingBudget?: number } | undefined;\n let papered = false;\n let value: string | number | undefined;\n if (GEMINI_3_PATTERN.test(model)) {\n const mapping = toGeminiThinkingLevel(request.effort);\n ({ papered, value } = mapping);\n thinkingConfig = { thinkingLevel: mapping.value };\n } else if (GEMINI_25_PATTERN.test(model)) {\n const mapping = toGeminiThinkingBudget(request.effort);\n ({ papered, value } = mapping);\n thinkingConfig = { thinkingBudget: mapping.value };\n }\n if (thinkingConfig) {\n if (papered) {\n log.debug(\n paperedEffortMessage({\n model,\n provider: this.name,\n requested: request.effort,\n value: value!,\n }),\n );\n }\n geminiRequest.config = {\n ...geminiRequest.config,\n thinkingConfig: {\n ...geminiRequest.config?.thinkingConfig,\n ...thinkingConfig,\n },\n };\n }\n }\n\n // First-class temperature takes precedence over providerOptions\n if (request.temperature !== undefined) {\n geminiRequest.config = {\n ...geminiRequest.config,\n temperature: request.temperature,\n };\n }\n\n return geminiRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n // outputSchema is part of the interface contract but Gemini now handles\n // structured output via `responseJsonSchema`/`responseSchema` (or the\n // legacy fake-tool injected in buildRequest as a fallback). We no longer\n // inject a synthetic structured-output tool here.\n\n _outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: {\n ...tool.parameters,\n type: \"object\",\n } as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n let jsonSchema: JsonObject;\n\n // Check if schema is already a JsonObject — either the OpenAI-style\n // `{ type: \"json_schema\", ... }` envelope or a bare `{ type: \"object\", properties }` node\n if (\n (typeof schema === \"object\" &&\n schema !== null &&\n !Array.isArray(schema) &&\n (schema as JsonObject).type === \"json_schema\") ||\n isJsonSchema(schema)\n ) {\n jsonSchema = structuredClone(schema) as JsonObject;\n jsonSchema.type = \"object\";\n } else {\n // Convert NaturalSchema to JSON schema through Zod\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n jsonSchema = z.toJSONSchema(zodSchema) as JsonObject;\n }\n\n return jsonSchemaToOpenApi3(jsonSchema);\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<GeminiRawResponse> {\n const genAI = client as GoogleClient;\n const geminiRequest = request as GeminiRequest;\n const wantsNativeCombo =\n !!geminiRequest.config?.responseJsonSchema &&\n !!geminiRequest.config?.tools;\n\n try {\n // Cast config to any to bypass strict type checking between our internal types\n // and the SDK's types. The SDK will validate at runtime.\n const response = await genAI.models.generateContent({\n model: geminiRequest.model,\n contents: geminiRequest.contents as any,\n config: geminiRequest.config as any,\n });\n\n return response as unknown as GeminiRawResponse;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as GeminiRawResponse;\n\n // If the model rejected the native responseJsonSchema + tools combo,\n // cache it and retry with the legacy fake-tool emulation path.\n if (wantsNativeCombo && isStructuredOutputComboUnsupportedError(error)) {\n const model = geminiRequest.model;\n this.rememberModelRejectsStructuredOutputCombo(model);\n log.warn(\n `[GoogleAdapter] Model ${model} rejected native responseJsonSchema + tools combo; falling back to legacy structured_output tool emulation.`,\n );\n const fallbackRequest =\n this.toFallbackStructuredOutputRequest(geminiRequest);\n const response = await genAI.models.generateContent({\n model: fallbackRequest.model,\n contents: fallbackRequest.contents as any,\n config: fallbackRequest.config as any,\n });\n return response as unknown as GeminiRawResponse;\n }\n\n throw error;\n }\n }\n\n /**\n * Rebuild a Gemini 3 native-combo request without `responseJsonSchema`/\n * `responseMimeType`, swapping in the legacy fake-tool emulation. Used as\n * a runtime fallback when a Gemini 3 model rejects the combo.\n */\n private toFallbackStructuredOutputRequest(\n request: GeminiRequest,\n ): GeminiRequest {\n if (!request.config?.responseJsonSchema) return request;\n const schema = request.config.responseJsonSchema as JsonObject;\n const newConfig: GeminiRequest[\"config\"] = { ...request.config };\n delete (newConfig as Record<string, unknown>).responseJsonSchema;\n delete (newConfig as Record<string, unknown>).responseMimeType;\n\n const fakeTool: GeminiFunctionDeclaration = {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"Output a structured JSON object, \" +\n \"use this before your final response to give structured outputs to the user\",\n parameters: schema,\n };\n const existingDeclarations =\n newConfig.tools?.[0]?.functionDeclarations ?? [];\n newConfig.tools = [\n { functionDeclarations: [...existingDeclarations, fakeTool] },\n ];\n\n const structuredOutputInstruction =\n \"IMPORTANT: Before providing your final response, you MUST use the structured_output tool \" +\n \"to output your answer in the required JSON format.\";\n const existingSystem = newConfig.systemInstruction || \"\";\n newConfig.systemInstruction = existingSystem\n ? `${existingSystem}\\n\\n${structuredOutputInstruction}`\n : structuredOutputInstruction;\n\n return {\n ...request,\n config: newConfig,\n };\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n // signal is accepted for interface conformance; Gemini SDK does not natively support it\n void signal;\n const genAI = client as GoogleClient;\n const geminiRequest = request as GeminiRequest;\n\n // Use generateContentStream for streaming\n const stream = await genAI.models.generateContentStream({\n model: geminiRequest.model,\n contents: geminiRequest.contents as any,\n config: geminiRequest.config as any,\n });\n\n // Track usage for final chunk\n let inputTokens = 0;\n let outputTokens = 0;\n let reasoningTokens = 0;\n const model = geminiRequest.model || this.defaultModel;\n\n for await (const chunk of stream) {\n // Extract text content from the chunk\n const candidate = chunk.candidates?.[0];\n if (candidate?.content?.parts) {\n for (const part of candidate.content.parts) {\n // Handle text content (excluding thought parts)\n if (part.text && !part.thought) {\n yield {\n type: LlmStreamChunkType.Text,\n content: part.text,\n };\n }\n\n // Handle function calls\n if (part.functionCall) {\n const functionCall = part.functionCall as GeminiFunctionCall;\n const currentFunctionCall = {\n id: functionCall.id || this.generateCallId(),\n name: functionCall.name || \"\",\n arguments: functionCall.args || {},\n };\n\n // Preserve thoughtSignature for Gemini 3 models\n // Required to maintain tool call context between turns\n const metadata: Record<string, unknown> | undefined =\n part.thoughtSignature\n ? { thoughtSignature: part.thoughtSignature }\n : undefined;\n\n // Emit the function call immediately\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentFunctionCall.id,\n name: currentFunctionCall.name,\n arguments: JSON.stringify(currentFunctionCall.arguments),\n metadata,\n },\n };\n }\n }\n }\n\n // Extract usage metadata if present\n if (chunk.usageMetadata) {\n inputTokens = chunk.usageMetadata.promptTokenCount || 0;\n outputTokens = chunk.usageMetadata.candidatesTokenCount || 0;\n reasoningTokens = chunk.usageMetadata.thoughtsTokenCount || 0;\n }\n }\n\n // Emit done chunk with final usage\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: reasoningTokens,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n options?: LlmOperateOptions,\n ): ParsedResponse {\n const geminiResponse = response as GeminiRawResponse;\n\n const content = this.extractContent(geminiResponse, options);\n const hasToolCalls = this.hasToolCalls(geminiResponse);\n\n return {\n content,\n hasToolCalls,\n stopReason: this.getFinishReason(geminiResponse),\n usage: this.extractUsage(\n geminiResponse,\n options?.model || this.defaultModel,\n ),\n raw: geminiResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const geminiResponse = response as GeminiRawResponse;\n const toolCalls: StandardToolCall[] = [];\n\n const candidate = geminiResponse.candidates?.[0];\n if (!candidate?.content?.parts) {\n return toolCalls;\n }\n\n for (const part of candidate.content.parts) {\n if (part.functionCall) {\n const functionCall = part.functionCall as GeminiFunctionCall;\n toolCalls.push({\n callId: functionCall.id || this.generateCallId(),\n name: functionCall.name || \"\",\n arguments: JSON.stringify(functionCall.args || {}),\n raw: part,\n });\n }\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const geminiResponse = response as GeminiRawResponse;\n\n if (!geminiResponse.usageMetadata) {\n return {\n input: 0,\n output: 0,\n reasoning: 0,\n total: 0,\n provider: this.name,\n model,\n };\n }\n\n const usage = geminiResponse.usageMetadata;\n\n return {\n input: usage.promptTokenCount || 0,\n output: usage.candidatesTokenCount || 0,\n reasoning: usage.thoughtsTokenCount || 0,\n total: usage.totalTokenCount || 0,\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): GeminiPart {\n // Gemini's `function_response.response` is a protobuf Struct, which only\n // accepts plain objects. Some models (e.g. gemini-3.1-pro) accept scalar\n // values silently; gemini-3.1-flash-lite rejects them. Parse the output\n // and wrap any non-object value (string, number, boolean, array, null)\n // in `{ result: value }` so every tool result is a valid Struct.\n let responseData: Record<string, unknown>;\n try {\n const parsed = JSON.parse(result.output);\n if (\n parsed !== null &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ) {\n responseData = parsed as Record<string, unknown>;\n } else {\n responseData = { result: parsed };\n }\n } catch {\n responseData = { result: result.output };\n }\n\n return {\n functionResponse: {\n name: toolCall.name,\n response: responseData,\n },\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): GeminiRequest {\n const geminiRequest = request as GeminiRequest;\n const toolCallRaw = toolCall.raw as GeminiPart;\n const toolResponse = this.formatToolResult(toolCall, result);\n\n // Get the last two contents to check for existing tool call/response pattern\n const lastContent =\n geminiRequest.contents[geminiRequest.contents.length - 1];\n const secondLastContent =\n geminiRequest.contents[geminiRequest.contents.length - 2];\n\n // Check if we're adding to an existing tool call batch\n // Pattern: [..., model (with functionCall), user (with functionResponse)]\n const hasExistingToolBatch =\n lastContent?.role === \"user\" &&\n lastContent?.parts?.some((p) => p.functionResponse) &&\n secondLastContent?.role === \"model\" &&\n secondLastContent?.parts?.some((p) => p.functionCall);\n\n if (hasExistingToolBatch) {\n // Append to existing batch\n secondLastContent.parts!.push(toolCallRaw);\n lastContent.parts!.push(toolResponse);\n } else {\n // Create new batch\n geminiRequest.contents.push({\n role: \"model\",\n parts: [toolCallRaw],\n });\n geminiRequest.contents.push({\n role: \"user\",\n parts: [toolResponse],\n });\n }\n\n return geminiRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const geminiResponse = response as GeminiRawResponse;\n const historyItems: LlmHistory = [];\n\n const candidate = geminiResponse.candidates?.[0];\n if (!candidate?.content?.parts) {\n return historyItems;\n }\n\n // Check if this is a function call response\n const hasFunctionCalls = candidate.content.parts.some(\n (part) => part.functionCall,\n );\n\n if (hasFunctionCalls) {\n // Don't add to history yet - will be added after tool execution\n return historyItems;\n }\n\n // Extract text content for non-tool responses\n const textParts = candidate.content.parts.filter(\n (part) => part.text && !part.thought,\n );\n\n if (textParts.length > 0) {\n const textContent = textParts.map((part) => part.text).join(\"\");\n historyItems.push({\n content: textContent,\n role: LlmMessageRole.Assistant,\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n const geminiError = error as GeminiErrorInfo;\n\n // Extract status code from error\n const statusCode = geminiError.status || geminiError.code;\n\n // Check for rate limit error (429)\n if (statusCode === 429) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Check for retryable errors\n if (\n typeof statusCode === \"number\" &&\n RETRYABLE_STATUS_CODES.includes(statusCode)\n ) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Check for non-retryable errors\n if (\n typeof statusCode === \"number\" &&\n NOT_RETRYABLE_STATUS_CODES.includes(statusCode)\n ) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n\n // Check error message for common patterns\n const errorMessage = geminiError.message || String(error) || \"\";\n\n if (\n errorMessage.includes(\"rate limit\") ||\n errorMessage.includes(\"quota exceeded\")\n ) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n if (\n errorMessage.includes(\"timeout\") ||\n errorMessage.includes(\"connection\") ||\n errorMessage.includes(\"ECONNREFUSED\")\n ) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Check for transient network errors (ECONNRESET, etc.)\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Unknown error - treat as potentially retryable\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Provider-Specific Features\n //\n\n isComplete(response: unknown): boolean {\n const geminiResponse = response as GeminiRawResponse;\n\n const candidate = geminiResponse.candidates?.[0];\n if (!candidate?.content?.parts) {\n return true;\n }\n\n // Check if there are any function calls\n const hasFunctionCalls = candidate.content.parts.some(\n (part) => part.functionCall,\n );\n\n return !hasFunctionCalls;\n }\n\n override hasStructuredOutput(response: unknown): boolean {\n const geminiResponse = response as GeminiRawResponse;\n\n const candidate = geminiResponse.candidates?.[0];\n if (!candidate?.content?.parts) {\n return false;\n }\n\n // Check if the last part is a function call with structured_output\n const lastPart =\n candidate.content.parts[candidate.content.parts.length - 1];\n return lastPart?.functionCall?.name === STRUCTURED_OUTPUT_TOOL_NAME;\n }\n\n override extractStructuredOutput(response: unknown): JsonObject | undefined {\n const geminiResponse = response as GeminiRawResponse;\n\n const candidate = geminiResponse.candidates?.[0];\n if (!candidate?.content?.parts) {\n return undefined;\n }\n\n const lastPart =\n candidate.content.parts[candidate.content.parts.length - 1];\n if (lastPart?.functionCall?.name === STRUCTURED_OUTPUT_TOOL_NAME) {\n return lastPart.functionCall.args as JsonObject;\n }\n\n return undefined;\n }\n\n //\n // Private Helpers\n //\n\n private convertMessagesToContents(messages: LlmHistory): GeminiContent[] {\n const contents: GeminiContent[] = [];\n\n for (const message of messages) {\n // Handle input/output messages\n if (\"role\" in message && \"content\" in message) {\n const role = this.mapRole(message.role as LlmMessageRole);\n const parts = this.convertContentToParts(message.content);\n\n contents.push({\n role,\n parts,\n });\n }\n // Handle function call items\n else if (\n \"type\" in message &&\n message.type === LlmMessageType.FunctionCall\n ) {\n // Build the function call part, including thoughtSignature if present\n // (required for Gemini 3 models)\n const functionCallPart: GeminiPart = {\n functionCall: {\n name: (message as any).name,\n args: JSON.parse((message as any).arguments || \"{}\"),\n id: (message as any).call_id,\n },\n };\n // Preserve thoughtSignature for Gemini 3 models\n if ((message as any).thoughtSignature) {\n functionCallPart.thoughtSignature = (message as any).thoughtSignature;\n }\n contents.push({\n role: \"model\",\n parts: [functionCallPart],\n });\n }\n // Handle function call output items\n else if (\n \"type\" in message &&\n message.type === LlmMessageType.FunctionCallOutput\n ) {\n // Parse the output to get the actual response object\n let responseData: Record<string, unknown>;\n try {\n responseData = JSON.parse((message as any).output || \"{}\");\n } catch {\n responseData = { result: (message as any).output };\n }\n\n contents.push({\n role: \"user\",\n parts: [\n {\n functionResponse: {\n name: (message as any).name || \"function\",\n response: responseData,\n },\n },\n ],\n });\n }\n }\n\n return contents;\n }\n\n private convertContentToParts(content: unknown): GeminiPart[] {\n // Handle string content\n if (typeof content === \"string\") {\n return [{ text: content }];\n }\n\n // Handle array content\n if (Array.isArray(content)) {\n const parts: GeminiPart[] = [];\n\n for (const item of content) {\n // Handle Gemini-native parts (already have inlineData, text, etc.)\n if (item.inlineData) {\n parts.push({ inlineData: item.inlineData });\n continue;\n }\n\n if (item.text && !item.type) {\n // Plain text part\n parts.push({ text: item.text });\n continue;\n }\n\n if (item.fileData) {\n parts.push({ fileData: item.fileData });\n continue;\n }\n\n // Handle standardized LlmInputContentText\n if (item.type === LlmMessageType.InputText) {\n parts.push({ text: item.text });\n continue;\n }\n\n // Handle standardized LlmInputContentImage\n if (item.type === LlmMessageType.InputImage) {\n const imageUrl = item.image_url as string;\n // Parse data URL format: data:image/png;base64,<data>\n if (imageUrl?.startsWith(\"data:\")) {\n const match = imageUrl.match(/^data:([^;]+);base64,(.+)$/);\n if (match) {\n parts.push({\n inlineData: {\n mimeType: match[1],\n data: match[2],\n },\n });\n continue;\n }\n }\n // If not a data URL, try to use as file URI\n if (imageUrl) {\n parts.push({\n fileData: {\n mimeType: \"image/png\",\n fileUri: imageUrl,\n },\n });\n }\n continue;\n }\n\n // Handle standardized LlmInputContentFile\n if (item.type === LlmMessageType.InputFile) {\n const fileData = item.file_data as string;\n // Parse data URL format: data:application/pdf;base64,<data>\n if (fileData?.startsWith(\"data:\")) {\n const match = fileData.match(/^data:([^;]+);base64,(.+)$/);\n if (match) {\n parts.push({\n inlineData: {\n mimeType: match[1],\n data: match[2],\n },\n });\n continue;\n }\n }\n // If not a data URL, just add as text (fallback)\n if (typeof fileData === \"string\") {\n parts.push({ text: `[File: ${item.filename || \"unknown\"}]` });\n }\n continue;\n }\n\n // Fallback: stringify unknown content\n parts.push({ text: JSON.stringify(item) });\n }\n\n return parts;\n }\n\n // Fallback for other types\n return [{ text: JSON.stringify(content) }];\n }\n\n private mapRole(role: LlmMessageRole): \"user\" | \"model\" {\n switch (role) {\n case LlmMessageRole.User:\n case LlmMessageRole.System:\n case LlmMessageRole.Developer:\n return \"user\";\n case LlmMessageRole.Assistant:\n return \"model\";\n default:\n return \"user\";\n }\n }\n\n private hasToolCalls(response: GeminiRawResponse): boolean {\n const candidate = response.candidates?.[0];\n if (!candidate?.content?.parts) {\n return false;\n }\n\n return candidate.content.parts.some((part) => part.functionCall);\n }\n\n private getFinishReason(response: GeminiRawResponse): string | undefined {\n const candidate = response.candidates?.[0];\n return candidate?.finishReason;\n }\n\n private extractContent(\n response: GeminiRawResponse,\n options?: LlmOperateOptions,\n ): string | JsonObject | undefined {\n // Check for structured output first\n if (this.hasStructuredOutput(response)) {\n return this.extractStructuredOutput(response);\n }\n\n const candidate = response.candidates?.[0];\n if (!candidate?.content?.parts) {\n return undefined;\n }\n\n // Extract text content (excluding thought parts)\n const textParts = candidate.content.parts.filter(\n (part) => part.text && !part.thought,\n );\n\n if (textParts.length === 0) {\n return undefined;\n }\n\n const textContent = textParts.map((part) => part.text).join(\"\");\n\n // If format is provided, try to parse the content as JSON\n if (options?.format && typeof textContent === \"string\") {\n try {\n return JSON.parse(textContent);\n } catch {\n // Strip markdown code fences and retry (Gemini sometimes wraps JSON in fences)\n const jsonMatch =\n textContent.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/) ||\n textContent.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n return JSON.parse(jsonMatch[1] || jsonMatch[0]);\n } catch {\n // Fall through to return original string\n }\n }\n return textContent;\n }\n }\n\n return textContent;\n }\n\n private generateCallId(): string {\n return `call_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;\n }\n}\n\n// Export singleton instance\nexport const googleAdapter = new GoogleAdapter();\n","import { JsonObject } from \"@jaypie/types\";\n\nimport { parseSseStream } from \"../../util/sse.js\";\n\n//\n//\n// Constants\n//\n\nconst OPENAI_BASE_URL = \"https://api.openai.com/v1\";\n\n//\n//\n// Errors\n//\n// The adapter's `classifyError` uses `instanceof` against these classes, so the\n// client throws them directly. Status → class mapping mirrors the SDK; the\n// non-HTTP classes (connection/abort) are thrown when `fetch` itself rejects.\n//\n\nexport class OpenAiApiError extends Error {\n readonly status: number;\n readonly error?: { message?: string };\n\n constructor(status: number, message: string, error?: { message?: string }) {\n super(message);\n this.name = this.constructor.name;\n this.status = status;\n this.error = error;\n }\n}\n\nexport class BadRequestError extends OpenAiApiError {}\nexport class AuthenticationError extends OpenAiApiError {}\nexport class PermissionDeniedError extends OpenAiApiError {}\nexport class NotFoundError extends OpenAiApiError {}\nexport class ConflictError extends OpenAiApiError {}\nexport class UnprocessableEntityError extends OpenAiApiError {}\nexport class RateLimitError extends OpenAiApiError {}\nexport class InternalServerError extends OpenAiApiError {}\nexport class APIConnectionError extends OpenAiApiError {}\nexport class APIConnectionTimeoutError extends APIConnectionError {}\nexport class APIUserAbortError extends OpenAiApiError {}\n\nfunction errorForStatus(\n status: number,\n message: string,\n error?: { message?: string },\n): OpenAiApiError {\n if (status === 400) return new BadRequestError(status, message, error);\n if (status === 401) return new AuthenticationError(status, message, error);\n if (status === 403) return new PermissionDeniedError(status, message, error);\n if (status === 404) return new NotFoundError(status, message, error);\n if (status === 409) return new ConflictError(status, message, error);\n if (status === 422) {\n return new UnprocessableEntityError(status, message, error);\n }\n if (status === 429) return new RateLimitError(status, message, error);\n if (status >= 500) return new InternalServerError(status, message, error);\n return new OpenAiApiError(status, message, error);\n}\n\n//\n//\n// Types\n//\n\nexport interface OpenAIClientOptions {\n apiKey: string;\n baseURL?: string;\n}\n\nexport interface RequestOptions {\n signal?: AbortSignal;\n}\n\ninterface ResponsesApi {\n create(\n params: Record<string, unknown> & { stream: true },\n options?: RequestOptions,\n ): Promise<AsyncIterable<Record<string, unknown>>>;\n create(\n params: Record<string, unknown>,\n options?: RequestOptions,\n ): Promise<JsonObject>;\n}\n\ninterface ChatCompletionsApi {\n create(\n params: Record<string, unknown>,\n options?: RequestOptions,\n ): Promise<JsonObject>;\n parse(\n params: Record<string, unknown>,\n options?: RequestOptions,\n ): Promise<JsonObject>;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Minimal `fetch`-based client for the OpenAI API. Replaces the `openai` SDK —\n * the adapters and provider utilities only need the Responses API\n * (`/responses`, streaming and non-streaming) for `operate`/`stream` and the\n * Chat Completions API (`/chat/completions`, plus a `parse` helper for\n * structured output) for `send`. Mirrors the SDK's `responses.create` and\n * `chat.completions.create` / `chat.completions.parse` surface so call sites are\n * unchanged. Also serves xAI via a custom `baseURL`.\n */\nexport class OpenAIClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n readonly responses: ResponsesApi;\n readonly chat: { completions: ChatCompletionsApi };\n\n constructor({ apiKey, baseURL = OPENAI_BASE_URL }: OpenAIClientOptions) {\n this.apiKey = apiKey;\n this.baseURL = baseURL;\n this.responses = {\n create: ((params: Record<string, unknown>, options?: RequestOptions) =>\n params.stream\n ? this.createResponseStream(params, options)\n : this.createResponse(params, options)) as ResponsesApi[\"create\"],\n };\n this.chat = {\n completions: {\n create: (params, options) =>\n this.chatCompletion(params, options, { parse: false }),\n parse: (params, options) =>\n this.chatCompletion(params, options, { parse: true }),\n },\n };\n }\n\n private headers(extra?: Record<string, string>): Record<string, string> {\n return {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...extra,\n };\n }\n\n private async post(\n path: string,\n body: Record<string, unknown>,\n { signal }: RequestOptions = {},\n { stream = false }: { stream?: boolean } = {},\n ): Promise<Response> {\n let response: Response;\n try {\n response = await fetch(`${this.baseURL}${path}`, {\n method: \"POST\",\n headers: this.headers(\n stream ? { Accept: \"text/event-stream\" } : undefined,\n ),\n body: JSON.stringify(body),\n signal,\n });\n } catch (cause) {\n if (signal?.aborted) {\n throw new APIUserAbortError(0, \"Request was aborted\");\n }\n const message =\n cause instanceof Error ? cause.message : \"Connection error\";\n const error = new APIConnectionError(0, message);\n (error as { cause?: unknown }).cause = cause;\n throw error;\n }\n if (!response.ok) throw await this.toError(response);\n return response;\n }\n\n private async toError(response: Response): Promise<OpenAiApiError> {\n let message = `OpenAI request failed with status ${response.status}`;\n let error: { message?: string } | undefined;\n try {\n const body = (await response.json()) as { error?: { message?: string } };\n if (body?.error?.message) {\n message = body.error.message;\n error = body.error;\n }\n } catch {\n // Non-JSON error body; keep the status-based message.\n }\n return errorForStatus(response.status, message, error);\n }\n\n private async createResponse(\n params: Record<string, unknown>,\n options?: RequestOptions,\n ): Promise<JsonObject> {\n const response = await this.post(\"/responses\", params, options);\n return (await response.json()) as JsonObject;\n }\n\n private async createResponseStream(\n params: Record<string, unknown>,\n options?: RequestOptions,\n ): Promise<AsyncIterable<Record<string, unknown>>> {\n const response = await this.post(\"/responses\", params, options, {\n stream: true,\n });\n if (!response.body) return (async function* () {})();\n // The Responses API streams typed events and does not emit a `[DONE]`\n // sentinel; the empty default sentinel never matches, so the stream ends\n // when the connection closes.\n return parseSseStream(response.body);\n }\n\n private async chatCompletion(\n params: Record<string, unknown>,\n options: RequestOptions | undefined,\n { parse }: { parse: boolean },\n ): Promise<JsonObject> {\n const response = await this.post(\"/chat/completions\", params, options);\n const json = (await response.json()) as JsonObject;\n // `chat.completions.parse` surfaces parsed JSON on each message; replicate\n // the SDK by JSON-parsing the assistant content into `message.parsed`.\n if (parse) {\n const choices = json.choices as\n Array<Record<string, unknown>> | undefined;\n if (Array.isArray(choices)) {\n for (const choice of choices) {\n const message = choice.message as Record<string, unknown> | undefined;\n if (\n message &&\n typeof message.content === \"string\" &&\n !message.refusal\n ) {\n try {\n message.parsed = JSON.parse(message.content);\n } catch {\n message.parsed = null;\n }\n }\n }\n }\n }\n return json;\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\n//\n//\n// Types\n//\n\nexport interface JsonSchemaResponseFormat {\n type: \"json_schema\";\n json_schema: {\n name: string;\n strict: boolean;\n schema: JsonObject;\n };\n}\n\n//\n//\n// Main\n//\n\n/**\n * Local replacement for `openai/helpers/zod`'s `zodResponseFormat`. Builds the\n * `response_format` payload OpenAI's Chat Completions / Responses APIs expect\n * from a Zod schema. The SDK always emits `strict: true`; callers re-derive or\n * sanitize `schema` as needed (e.g. forcing `additionalProperties: false`).\n */\nexport function zodResponseFormat(\n schema: z.ZodType,\n name: string,\n): JsonSchemaResponseFormat {\n return {\n type: \"json_schema\",\n json_schema: {\n name,\n strict: true,\n schema: z.toJSONSchema(schema) as JsonObject,\n },\n };\n}\n","import { log } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { type LlmEffort, PROVIDER } from \"../../constants.js\";\nimport {\n type LlmEffortMapping,\n paperedEffortMessage,\n toOpenAiEffort,\n} from \"../../util/effort.js\";\nimport {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n InternalServerError,\n NotFoundError,\n OpenAIClient,\n PermissionDeniedError,\n RateLimitError,\n UnprocessableEntityError,\n} from \"../../providers/openai/client.js\";\nimport { zodResponseFormat } from \"../../providers/openai/responseFormat.js\";\n\n// Patterns for OpenAI reasoning models that support extended thinking\nconst REASONING_MODEL_PATTERNS = [\n /^gpt-[5-9]/, // GPT-5 and above (gpt-5, gpt-5.1, gpt-5.2, gpt-6, etc.)\n /^o\\d/, // O-series (o1, o3, o4, o5, etc.)\n] as const;\n\n/**\n * Check if a model is a reasoning model that supports extended thinking\n */\nfunction isReasoningModel(model: string): boolean {\n return REASONING_MODEL_PATTERNS.some((pattern) => pattern.test(model));\n}\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmMessageType,\n LlmOperateOptions,\n LlmToolResult,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n isJsonSchema,\n naturalZodSchema,\n promptCacheKey,\n resolveCache,\n} from \"../../util/index.js\";\nimport { OpenAIRawResponse } from \"../../providers/openai/types.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\n\n//\n//\n// Constants\n//\n\nconst RETRYABLE_ERROR_TYPES = [\n APIConnectionError,\n APIConnectionTimeoutError,\n InternalServerError,\n];\n\nconst NOT_RETRYABLE_ERROR_TYPES = [\n APIUserAbortError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n NotFoundError,\n PermissionDeniedError,\n RateLimitError,\n UnprocessableEntityError,\n];\n\n// Models known not to accept `temperature`.\n// Patterns (not exact names) so dated variants and future releases are covered\n// without code changes — OpenAI is removing temperature on newer reasoning\n// models.\nconst MODELS_WITHOUT_TEMPERATURE: RegExp[] = [\n /^gpt-5\\.5/, // gpt-5.5 series deprecated temperature\n /^o\\d/, // o-series reasoning models (o1, o3, o4, ...)\n];\n\nfunction isTemperatureDeprecationError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n if (\n !(error instanceof BadRequestError) &&\n (error as { status?: number }).status !== 400\n ) {\n return false;\n }\n const messages = [\n (error as { message?: string }).message,\n (error as { error?: { message?: string } }).error?.message,\n ].filter((m): m is string => typeof m === \"string\");\n return messages.some((m) => m.toLowerCase().includes(\"temperature\"));\n}\n\n//\n//\n// Main\n//\n\n/**\n * OpenAiAdapter implements the ProviderAdapter interface for OpenAI's API.\n * It handles request building, response parsing, and error classification\n * specific to OpenAI's Responses API.\n */\nexport class OpenAiAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.OPENAI.NAME;\n readonly defaultModel = PROVIDER.OPENAI.DEFAULT;\n\n // Session-level cache of models observed to reject `temperature` at runtime.\n // Populated by executeRequest on 400 errors so repeat calls skip the param.\n private runtimeNoTemperatureModels = new Set<string>();\n\n rememberModelRejectsTemperature(model: string): void {\n this.runtimeNoTemperatureModels.add(model);\n }\n\n clearRuntimeNoTemperatureModels(): void {\n this.runtimeNoTemperatureModels.clear();\n }\n\n private supportsTemperature(model: string): boolean {\n if (this.runtimeNoTemperatureModels.has(model)) return false;\n return !MODELS_WITHOUT_TEMPERATURE.some((pattern) => pattern.test(model));\n }\n\n /** Whether `reasoning.effort` may be sent for this model. Overridden by xAI. */\n protected supportsReasoningEffort(model: string): boolean {\n return isReasoningModel(model);\n }\n\n /**\n * Whether to emit `prompt_cache_key` (OpenAI Responses API). Overridable by\n * OpenAI-compatible subclasses whose backend rejects the field.\n */\n protected supportsPromptCacheKey(): boolean {\n return true;\n }\n\n /** Translate a normalized effort to this provider's `reasoning.effort` value. */\n protected mapReasoningEffort(\n effort: LlmEffort,\n model: string,\n ): LlmEffortMapping {\n return toOpenAiEffort(effort, { model });\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): unknown {\n const model = request.model || this.defaultModel;\n const openaiRequest: Record<string, unknown> = {\n model,\n input: this.sanitizeInputItems(request.messages),\n };\n\n if (request.user) {\n openaiRequest.user = request.user;\n }\n\n if (request.instructions) {\n openaiRequest.instructions = request.instructions;\n }\n\n if (request.tools && request.tools.length > 0) {\n openaiRequest.tools = request.tools.map((tool) => ({\n type: \"function\",\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n }));\n }\n\n if (request.format) {\n openaiRequest.text = {\n format: request.format,\n };\n }\n\n // Enable reasoning summary for reasoning models (o1, o3, etc.)\n // This allows us to extract reasoning text from the response\n if (isReasoningModel(model)) {\n openaiRequest.reasoning = {\n summary: \"auto\",\n };\n }\n\n // OpenAI prompt caching is automatic (prefix-based). Setting a stable\n // prompt_cache_key routes repeat traffic to the same cache across\n // instances. Keyed on the stable prefix only (system + instructions +\n // tools + model), never the volatile user turn.\n if (this.supportsPromptCacheKey() && resolveCache(request.cache).enabled) {\n openaiRequest.prompt_cache_key = promptCacheKey(\n JSON.stringify([\n model,\n request.system ?? \"\",\n request.instructions ?? \"\",\n request.tools ?? [],\n ]),\n );\n }\n\n if (request.providerOptions) {\n Object.assign(openaiRequest, request.providerOptions);\n }\n\n // Normalized reasoning effort -> reasoning.effort (merged so the\n // summary:auto above survives). First-class effort wins over providerOptions.\n if (request.effort && this.supportsReasoningEffort(model)) {\n const mapping = this.mapReasoningEffort(request.effort, model);\n if (mapping.papered) {\n log.debug(\n paperedEffortMessage({\n model,\n provider: this.name,\n requested: request.effort,\n value: mapping.value,\n }),\n );\n }\n const existingReasoning =\n (openaiRequest.reasoning as Record<string, unknown> | undefined) ?? {};\n openaiRequest.reasoning = {\n ...existingReasoning,\n effort: mapping.value,\n };\n }\n\n // First-class temperature takes precedence over providerOptions\n if (request.temperature !== undefined) {\n openaiRequest.temperature = request.temperature;\n }\n\n // Strip temperature for models that don't support it (denylist + runtime cache)\n if (\n openaiRequest.temperature !== undefined &&\n !this.supportsTemperature(openaiRequest.model as string)\n ) {\n delete openaiRequest.temperature;\n }\n\n return openaiRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n _outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n // Check if schema is already a JsonObject with type \"json_schema\"\n if (\n typeof schema === \"object\" &&\n schema !== null &&\n !Array.isArray(schema) &&\n (schema as JsonObject).type === \"json_schema\"\n ) {\n return schema as JsonObject;\n }\n\n // Bare JSON Schema node: `{ type: \"object\", properties: {...} }`\n // Skip the zod round-trip and use it directly (still needs the\n // additionalProperties + envelope treatment below).\n let jsonSchema: Record<string, unknown>;\n let name = \"response\";\n let strict = true;\n if (isJsonSchema(schema)) {\n jsonSchema = { ...structuredClone(schema) };\n delete jsonSchema.$schema;\n } else {\n // Convert NaturalSchema to Zod schema if needed\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n\n const responseFormat = zodResponseFormat(zodSchema as any, \"response\");\n // Re-spread to drop zod v4's non-enumerable `~standard` Standard-Schema\n // interop marker, then strip `$schema`: OpenAI's strict json_schema subset\n // does not recognize the draft-2020-12 `$schema` keyword, and shipping it\n // can leave strict structured-output enforcement silently disabled (the\n // model then free-forms, omitting required fields and corrupting keys).\n // Mirrors the OpenRouter adapter's sanitization.\n jsonSchema = {\n ...(z.toJSONSchema(zodSchema) as Record<string, unknown>),\n };\n delete jsonSchema.$schema;\n name = responseFormat.json_schema.name;\n strict = responseFormat.json_schema.strict as boolean;\n }\n\n // OpenAI requires additionalProperties to be false on all objects\n const checks = [jsonSchema];\n while (checks.length > 0) {\n const current = checks[0] as Record<string, unknown>;\n if (current.type === \"object\") {\n current.additionalProperties = false;\n }\n Object.keys(current).forEach((key) => {\n if (typeof current[key] === \"object\" && current[key] !== null) {\n checks.push(current[key] as Record<string, unknown>);\n }\n });\n checks.shift();\n }\n\n return {\n name,\n schema: jsonSchema as JsonObject,\n strict,\n type: \"json_schema\",\n };\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<unknown> {\n const openai = client as OpenAIClient;\n const openaiRequest = request as Record<string, unknown>;\n try {\n return await openai.responses.create(\n openaiRequest,\n signal ? { signal } : undefined,\n );\n } catch (error) {\n if (signal?.aborted) return undefined;\n\n // If the model rejected `temperature`, cache it and retry without the param\n if (\n openaiRequest.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(openaiRequest.model as string);\n const retryRequest = { ...openaiRequest };\n delete retryRequest.temperature;\n return await openai.responses.create(\n retryRequest,\n signal ? { signal } : undefined,\n );\n }\n\n throw error;\n }\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const openai = client as OpenAIClient;\n const baseRequest = request as Record<string, unknown>;\n const streamRequest = {\n ...baseRequest,\n stream: true as const,\n };\n\n const stream = await openai.responses.create(\n streamRequest,\n signal ? { signal } : undefined,\n );\n\n // Track current function call being built\n let currentFunctionCall: {\n id: string;\n callId: string;\n name: string;\n arguments: string;\n } | null = null;\n\n // Track usage for final chunk\n let inputTokens = 0;\n let outputTokens = 0;\n let reasoningTokens = 0;\n const model = (baseRequest.model as string) || this.defaultModel;\n\n // Cast to async iterable - when stream: true, this is always a Stream<ResponseStreamEvent>\n const asyncStream = stream as AsyncIterable<Record<string, unknown>>;\n for await (const event of asyncStream) {\n const eventType = event.type as string;\n\n if (eventType === \"response.output_text.delta\") {\n // Text content delta\n const delta = (event as { delta?: string }).delta;\n if (delta) {\n yield {\n type: LlmStreamChunkType.Text,\n content: delta,\n };\n }\n } else if (eventType === \"response.function_call_arguments.delta\") {\n // Function call arguments delta - accumulate\n const delta = (event as { delta?: string }).delta;\n if (delta && currentFunctionCall) {\n currentFunctionCall.arguments += delta;\n }\n } else if (eventType === \"response.output_item.added\") {\n // New output item - check if it's a function call\n const item = (\n event as {\n item?: {\n type?: string;\n id?: string;\n call_id?: string;\n name?: string;\n };\n }\n ).item;\n if (item?.type === \"function_call\") {\n currentFunctionCall = {\n id: item.id || \"\",\n callId: item.call_id || \"\",\n name: item.name || \"\",\n arguments: \"\",\n };\n }\n } else if (eventType === \"response.output_item.done\") {\n // Output item completed - emit function call if that's what we were building\n if (currentFunctionCall) {\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentFunctionCall.callId,\n name: currentFunctionCall.name,\n arguments: currentFunctionCall.arguments,\n // Preserve the item ID (fc_...) separately from call_id (call_...)\n // OpenAI Responses API requires both with correct prefixes\n metadata: { itemId: currentFunctionCall.id },\n },\n };\n currentFunctionCall = null;\n }\n } else if (eventType === \"response.completed\") {\n // Response completed - extract final usage\n const response = (event as { response?: OpenAIRawResponse }).response;\n if (response?.usage) {\n inputTokens = response.usage.input_tokens || 0;\n outputTokens = response.usage.output_tokens || 0;\n reasoningTokens =\n response.usage.output_tokens_details?.reasoning_tokens || 0;\n }\n } else if (eventType === \"response.done\") {\n // Stream done - emit final chunk with usage\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: reasoningTokens,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n }\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n options?: LlmOperateOptions,\n ): ParsedResponse {\n const openaiResponse = response as OpenAIRawResponse;\n\n const content = this.extractContent(openaiResponse, options);\n const hasToolCalls = this.hasToolCalls(openaiResponse);\n\n return {\n content,\n hasToolCalls,\n stopReason: openaiResponse.status as string | undefined,\n usage: this.extractUsage(\n openaiResponse,\n options?.model || this.defaultModel,\n ),\n raw: openaiResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const openaiResponse = response as OpenAIRawResponse;\n const toolCalls: StandardToolCall[] = [];\n\n if (!openaiResponse.output || !Array.isArray(openaiResponse.output)) {\n return toolCalls;\n }\n\n for (const output of openaiResponse.output) {\n if (output.type === LlmMessageType.FunctionCall) {\n toolCalls.push({\n callId: output.call_id,\n name: output.name,\n arguments: output.arguments,\n raw: output,\n });\n }\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const openaiResponse = response as OpenAIRawResponse;\n\n if (!openaiResponse.usage) {\n return {\n input: 0,\n output: 0,\n reasoning: 0,\n total: 0,\n provider: this.name,\n model,\n };\n }\n\n const cachedTokens =\n openaiResponse.usage.input_tokens_details?.cached_tokens;\n return {\n input: openaiResponse.usage.input_tokens || 0,\n output: openaiResponse.usage.output_tokens || 0,\n reasoning:\n openaiResponse.usage.output_tokens_details?.reasoning_tokens || 0,\n total: openaiResponse.usage.total_tokens || 0,\n ...(cachedTokens !== undefined ? { cacheRead: cachedTokens } : {}),\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): LlmToolResult {\n return {\n call_id: toolCall.callId,\n output: result.output,\n type: LlmMessageType.FunctionCallOutput,\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): unknown {\n const openaiRequest = request as Record<string, unknown>;\n const input = openaiRequest.input as unknown[];\n\n // Note: The function_call item has already been added via responseToHistoryItems\n // which is called before processing tool calls. This includes any required\n // reasoning items that precede the function_call.\n\n // Add only the function call result\n input.push({\n call_id: toolCall.callId,\n output: result.output,\n type: LlmMessageType.FunctionCallOutput,\n });\n\n return openaiRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const openaiResponse = response as OpenAIRawResponse;\n const historyItems: LlmHistory = [];\n\n if (!openaiResponse.output || !Array.isArray(openaiResponse.output)) {\n return historyItems;\n }\n\n // Include all output items, including reasoning items\n // OpenAI requires reasoning items to be present when a function_call references them\n for (const output of openaiResponse.output) {\n historyItems.push(output);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n // Check for rate limit error\n if (error instanceof RateLimitError) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false, // Rate limit requires waiting, not immediate retry\n suggestedDelayMs: 60000, // 1 minute default\n };\n }\n\n // Check for retryable errors\n for (const ErrorType of RETRYABLE_ERROR_TYPES) {\n if (error instanceof ErrorType) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n }\n\n // Check for non-retryable errors\n for (const ErrorType of NOT_RETRYABLE_ERROR_TYPES) {\n if (error instanceof ErrorType) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n }\n\n // Check for transient network errors (ECONNRESET, etc.)\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Unknown error - treat as potentially retryable\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Provider-Specific Features\n //\n\n isComplete(response: unknown): boolean {\n const openaiResponse = response as OpenAIRawResponse;\n\n // Check if there are any function calls in the output\n if (!openaiResponse.output || !Array.isArray(openaiResponse.output)) {\n return true;\n }\n\n for (const output of openaiResponse.output) {\n if (output.type === LlmMessageType.FunctionCall) {\n return false;\n }\n }\n\n return true;\n }\n\n //\n // Private Helpers\n //\n\n /**\n * Sanitize history items for the OpenAI Responses API.\n * Strips fields not accepted by specific item types (e.g., `name` on\n * function_call_output items) to prevent 400 \"Unknown parameter\" errors.\n */\n private sanitizeInputItems(messages: LlmHistory): unknown[] {\n return messages.map((item) => {\n const typedItem = item as unknown as Record<string, unknown>;\n\n // function_call_output only accepts: type, call_id, output, id, status\n if (typedItem.type === LlmMessageType.FunctionCallOutput) {\n const sanitized: Record<string, unknown> = {\n type: typedItem.type,\n call_id: typedItem.call_id,\n output: typedItem.output,\n };\n if (typedItem.id) sanitized.id = typedItem.id;\n if (typedItem.status) sanitized.status = typedItem.status;\n return sanitized;\n }\n\n // All other items pass through as-is\n return item;\n });\n }\n\n private hasToolCalls(response: OpenAIRawResponse): boolean {\n if (!response.output || !Array.isArray(response.output)) {\n return false;\n }\n\n return response.output.some(\n (output) => output.type === LlmMessageType.FunctionCall,\n );\n }\n\n private extractContent(\n response: OpenAIRawResponse,\n options?: LlmOperateOptions,\n ): string | JsonObject | undefined {\n if (!response.output || !Array.isArray(response.output)) {\n return undefined;\n }\n\n for (const output of response.output) {\n if (output.type === LlmMessageType.Message) {\n if (\n output.content?.[0] &&\n output.content[0].type === LlmMessageType.OutputText\n ) {\n const rawContent = output.content[0].text;\n\n // If format is provided, try to parse the content as JSON\n if (options?.format && typeof rawContent === \"string\") {\n try {\n return JSON.parse(rawContent);\n } catch {\n // If parsing fails, return the original string\n return rawContent;\n }\n }\n\n return rawContent;\n }\n }\n\n // Skip reasoning and function call items when extracting content\n if (\n output.type === \"reasoning\" ||\n output.type === LlmMessageType.FunctionCall\n ) {\n continue;\n }\n }\n\n return undefined;\n }\n}\n\n// Export singleton instance\nexport const openAiAdapter = new OpenAiAdapter();\n","import { log } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { toOpenRouterEffort } from \"../../util/effort.js\";\nimport { Toolkit } from \"../../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmInputContent,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n isJsonSchema,\n naturalZodSchema,\n resolveCache,\n} from \"../../util/index.js\";\nimport {\n ClassifiedError,\n ErrorCategory,\n OperateRequest,\n ParsedResponse,\n ProviderToolDefinition,\n StandardToolCall,\n StandardToolResult,\n} from \"../types.js\";\nimport { isTransientNetworkError } from \"../retry/isTransientNetworkError.js\";\nimport { classifyProviderError } from \"../../util/classifyProviderError.js\";\nimport { OpenRouterClient } from \"../../providers/openrouter/client.js\";\nimport { BaseProviderAdapter } from \"./ProviderAdapter.interface.js\";\n\n//\n//\n// Types\n//\n\n// Request types - SDK validates using camelCase internally\ninterface OpenRouterMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content?: string | OpenRouterContentPart[] | null;\n toolCalls?: OpenRouterToolCall[];\n toolCallId?: string;\n}\n\ninterface OpenRouterToolCall {\n id: string;\n type: \"function\";\n function: {\n name: string;\n arguments: string;\n };\n}\n\n// Response types (camelCase - what SDK returns)\ninterface OpenRouterResponseMessage {\n role: \"assistant\";\n content?: string | null;\n toolCalls?: OpenRouterToolCall[];\n refusal?: string | null;\n reasoning?: string | null;\n}\n\ninterface OpenRouterChoice {\n index: number;\n message: OpenRouterResponseMessage;\n finishReason: string | null;\n finish_reason?: string | null; // Some responses may use snake_case\n}\n\ninterface OpenRouterUsage {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n // Also support snake_case for backward compatibility\n prompt_tokens?: number;\n completion_tokens?: number;\n total_tokens?: number;\n // Reasoning tokens (some models like z-ai/glm include this)\n completionTokensDetails?: {\n reasoningTokens?: number;\n };\n // Cache-read tokens forwarded from Anthropic/Gemini backends\n promptTokensDetails?: {\n cachedTokens?: number;\n cached_tokens?: number;\n };\n prompt_tokens_details?: {\n cached_tokens?: number;\n };\n}\n\ninterface OpenRouterResponse {\n id: string;\n object: string;\n created: number;\n model: string;\n choices: OpenRouterChoice[];\n usage?: OpenRouterUsage;\n}\n\ninterface OpenRouterTool {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: JsonObject;\n };\n}\n\ninterface OpenRouterJsonSchemaConfig {\n name: string;\n description?: string;\n schema: JsonObject;\n strict?: boolean;\n}\n\ntype OpenRouterResponseFormat =\n | { type: \"json_schema\"; json_schema: OpenRouterJsonSchemaConfig }\n | { type: \"json_object\" }\n | { type: \"text\" };\n\ninterface OpenRouterRequest {\n model: string;\n messages: OpenRouterMessage[];\n tools?: OpenRouterTool[];\n tool_choice?: \"auto\" | \"none\" | \"required\";\n response_format?: OpenRouterResponseFormat;\n reasoning?: { effort?: string; max_tokens?: number };\n user?: string;\n}\n\n/**\n * OpenRouter responses we annotate at receive time so downstream stateless\n * methods (`hasStructuredOutput`, `extractStructuredOutput`) can tell whether\n * the request asked for native structured output without re-threading the\n * request.\n */\ntype AnnotatedOpenRouterResponse = OpenRouterResponse & {\n __jaypieStructuredOutput?: boolean;\n};\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\nconst STRUCTURED_OUTPUT_SCHEMA_NAME = \"response\";\n\n/**\n * Detect 4xx errors that indicate the model itself does not support\n * `response_format: json_schema`. Mirrors the Anthropic pattern: we only\n * trigger the fake-tool fallback when the failure is plausibly a capability\n * gap, not a generic 400.\n */\nfunction isStructuredOutputUnsupportedError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n statusCode?: number;\n message?: string;\n error?: { message?: string };\n };\n const status = err.status ?? err.statusCode;\n if (status !== 400 && status !== 422) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) =>\n /response_format|json[_ ]schema|structured[_ ]output|require[_ ]parameters/i.test(\n m,\n ),\n );\n}\n\n// OpenRouter routes that don't accept `temperature`. Patterns match the\n// vendor-prefixed route id (e.g. `openai/gpt-5.5`) so dated variants are\n// covered without code changes.\nconst MODELS_WITHOUT_TEMPERATURE: RegExp[] = [\n /^openai\\/gpt-5\\.5/,\n /^openai\\/o\\d/,\n /^anthropic\\/claude-opus-4-[789]/,\n /^anthropic\\/claude-opus-[5-9]/,\n];\n\nfunction isTemperatureDeprecationError(error: unknown): boolean {\n if (!error || typeof error !== \"object\") return false;\n const err = error as {\n status?: number;\n statusCode?: number;\n message?: string;\n error?: { message?: string };\n };\n const status = err.status ?? err.statusCode;\n if (status !== 400) return false;\n const messages = [err.message, err.error?.message].filter(\n (m): m is string => typeof m === \"string\",\n );\n return messages.some((m) => m.toLowerCase().includes(\"temperature\"));\n}\n\n/**\n * OpenRouter content part types. OpenRouter follows the OpenAI Chat\n * Completions multimodal schema and forwards `image_url` and `file` parts\n * to vision/PDF-capable backends. The SDK accepts camelCase fields at the\n * input boundary (`imageUrl`, `fileData`) and transforms to snake_case on\n * the wire.\n */\ntype OpenRouterContentPart =\n | {\n type: \"text\";\n text: string;\n cache_control?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" };\n }\n | { type: \"image_url\"; imageUrl: { url: string } }\n | { type: \"file\"; file: { filename?: string; fileData: string } };\n\n/**\n * Convert standardized content items to OpenRouter format. Images become\n * `image_url` parts and files become `file` parts; both pass through to\n * OpenRouter which routes to the selected backend. Backends that don't\n * support the modality 4xx — that's a model-capability mismatch, surfaced\n * by the call rather than silently dropped here.\n */\nfunction convertContentToOpenRouter(\n content: string | LlmInputContent[],\n): string | OpenRouterContentPart[] {\n if (typeof content === \"string\") {\n return content;\n }\n\n const parts: OpenRouterContentPart[] = [];\n\n for (const item of content) {\n if (item.type === LlmMessageType.InputText) {\n parts.push({ type: \"text\", text: item.text });\n continue;\n }\n\n if (item.type === LlmMessageType.InputImage) {\n const url = item.image_url ?? \"\";\n if (!url) {\n log.warn(\"OpenRouter image content missing image_url; image discarded\");\n continue;\n }\n parts.push({ type: \"image_url\", imageUrl: { url } });\n continue;\n }\n\n if (item.type === LlmMessageType.InputFile) {\n const fileData = typeof item.file_data === \"string\" ? item.file_data : \"\";\n if (!fileData) {\n log.warn(\n { filename: item.filename },\n \"OpenRouter file content missing file_data; file discarded\",\n );\n continue;\n }\n parts.push({\n type: \"file\",\n file: {\n filename: item.filename,\n fileData,\n },\n });\n continue;\n }\n\n // Unknown type - warn and skip\n log.warn({ item }, \"Unknown content type for OpenRouter; discarded\");\n }\n\n // If no parts remain, return empty string to avoid empty array\n if (parts.length === 0) {\n return \"\";\n }\n\n return parts;\n}\n\n/**\n * Convert internal content parts to the OpenAI-compatible wire shape. The\n * internal representation uses camelCase keys (`imageUrl`, `fileData`) that the\n * SDK accepted; the REST API wants snake_case (`image_url`, `file_data`).\n */\nfunction contentToWire(\n content: string | OpenRouterContentPart[] | null | undefined,\n): unknown {\n if (\n content === null ||\n content === undefined ||\n typeof content === \"string\"\n ) {\n return content;\n }\n return content.map((part) => {\n if (part.type === \"image_url\") {\n return { type: \"image_url\", image_url: part.imageUrl };\n }\n if (part.type === \"file\") {\n return {\n type: \"file\",\n file: { filename: part.file.filename, file_data: part.file.fileData },\n };\n }\n return part;\n });\n}\n\n/**\n * Serialize an internal message to the OpenAI-compatible wire shape, mapping\n * camelCase tool fields (`toolCalls`, `toolCallId`) to snake_case. Tool-call\n * objects are already wire-shaped (`{ id, type, function: { name, arguments } }`).\n */\nfunction messageToWire(message: OpenRouterMessage): Record<string, unknown> {\n const wire: Record<string, unknown> = { role: message.role };\n if (message.content !== undefined) {\n wire.content = contentToWire(message.content);\n }\n if (message.toolCalls) {\n wire.tool_calls = message.toolCalls;\n }\n if (message.toolCallId) {\n wire.tool_call_id = message.toolCallId;\n }\n return wire;\n}\n\n// OpenRouter error types based on HTTP status codes\nconst RETRYABLE_STATUS_CODES = [408, 500, 502, 503, 524, 529];\nconst RATE_LIMIT_STATUS_CODE = 429;\n\n/**\n * Walk the JSON schema and force `additionalProperties: false` on every\n * object node. Required by the OpenAI-style json_schema response_format\n * (which OpenRouter accepts) when `strict: true`.\n */\nfunction enforceAdditionalPropertiesFalse(schema: JsonObject): void {\n const stack: JsonObject[] = [schema];\n while (stack.length > 0) {\n const node = stack.pop() as JsonObject;\n if (node.type === \"object\") {\n node.additionalProperties = false;\n }\n for (const value of Object.values(node)) {\n if (Array.isArray(value)) {\n for (const entry of value) {\n if (entry && typeof entry === \"object\" && !Array.isArray(entry)) {\n stack.push(entry as JsonObject);\n }\n }\n } else if (value && typeof value === \"object\") {\n stack.push(value as JsonObject);\n }\n }\n }\n}\n\n//\n//\n// Main\n//\n\n/**\n * OpenRouterAdapter implements the ProviderAdapter interface for OpenRouter's API.\n * OpenRouter provides a unified API to access hundreds of AI models through OpenAI-compatible endpoints.\n * It handles request building, response parsing, and error classification\n * specific to OpenRouter's Chat Completions API.\n */\nexport class OpenRouterAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.OPENROUTER.NAME;\n readonly defaultModel = PROVIDER.OPENROUTER.DEFAULT;\n\n // Session-level cache of models observed to reject native\n // `response_format: json_schema`. When a model is in this set, buildRequest\n // engages the legacy fake-tool path instead of native structured output.\n private runtimeNoStructuredOutputModels = new Set<string>();\n\n rememberModelRejectsStructuredOutput(model: string): void {\n this.runtimeNoStructuredOutputModels.add(model);\n }\n\n clearRuntimeNoStructuredOutputModels(): void {\n this.runtimeNoStructuredOutputModels.clear();\n }\n\n private supportsStructuredOutput(model: string): boolean {\n return !this.runtimeNoStructuredOutputModels.has(model);\n }\n\n // Session-level cache of routes observed to reject `temperature`. Populated\n // by executeRequest on 400 errors so repeat calls skip the param.\n private runtimeNoTemperatureModels = new Set<string>();\n\n rememberModelRejectsTemperature(model: string): void {\n this.runtimeNoTemperatureModels.add(model);\n }\n\n clearRuntimeNoTemperatureModels(): void {\n this.runtimeNoTemperatureModels.clear();\n }\n\n private supportsTemperature(model: string): boolean {\n if (this.runtimeNoTemperatureModels.has(model)) return false;\n return !MODELS_WITHOUT_TEMPERATURE.some((pattern) => pattern.test(model));\n }\n\n //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): OpenRouterRequest {\n // Convert messages to OpenRouter format (OpenAI-compatible)\n const cache = resolveCache(request.cache);\n const messages: OpenRouterMessage[] = this.convertMessagesToOpenRouter(\n request.messages,\n request.system,\n cache.enabled\n ? {\n type: \"ephemeral\",\n ...(cache.ttl === \"1h\" ? { ttl: \"1h\" as const } : {}),\n }\n : undefined,\n );\n\n // Append instructions to last message if provided\n if (request.instructions && messages.length > 0) {\n const lastMsg = messages[messages.length - 1];\n if (lastMsg.content && typeof lastMsg.content === \"string\") {\n lastMsg.content = lastMsg.content + \"\\n\\n\" + request.instructions;\n }\n }\n\n const openRouterRequest: OpenRouterRequest = {\n model: request.model || this.defaultModel,\n messages,\n };\n\n if (request.user) {\n openRouterRequest.user = request.user;\n }\n\n const useFallbackStructuredOutput =\n Boolean(request.format) &&\n !this.supportsStructuredOutput(openRouterRequest.model);\n\n const allTools: ProviderToolDefinition[] = request.tools\n ? [...request.tools]\n : [];\n if (useFallbackStructuredOutput && request.format) {\n log.warn(\n `[OpenRouterAdapter] Using legacy structured_output tool fallback for model ${openRouterRequest.model}; native response_format previously rejected for this model.`,\n );\n allTools.push({\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n parameters: request.format,\n });\n }\n\n if (allTools.length > 0) {\n openRouterRequest.tools = allTools.map((tool) => ({\n type: \"function\" as const,\n function: {\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n },\n }));\n\n // Use \"auto\" for tool_choice - many OpenRouter models don't support \"required\"\n // The structured_output tool prompt already emphasizes it must be called\n openRouterRequest.tool_choice = \"auto\";\n }\n\n // Native structured output: send schema as `response_format`. The legacy\n // tool-emulation path is engaged only as a runtime fallback for models the\n // API has flagged as not supporting native json_schema.\n if (request.format && !useFallbackStructuredOutput) {\n openRouterRequest.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: STRUCTURED_OUTPUT_SCHEMA_NAME,\n schema: request.format,\n strict: true,\n },\n };\n }\n\n if (request.providerOptions) {\n Object.assign(openRouterRequest, request.providerOptions);\n }\n\n // Normalized reasoning effort -> reasoning.effort. OpenRouter accepts the\n // full ladder and maps to the routed provider's nearest supported level.\n // First-class effort wins over providerOptions.\n if (request.effort) {\n openRouterRequest.reasoning = {\n ...openRouterRequest.reasoning,\n effort: toOpenRouterEffort(request.effort).value,\n };\n }\n\n // First-class temperature takes precedence over providerOptions\n if (request.temperature !== undefined) {\n (openRouterRequest as unknown as Record<string, unknown>).temperature =\n request.temperature;\n }\n\n // Strip temperature for routes that don't support it (denylist + runtime cache)\n const requestRecord = openRouterRequest as unknown as Record<\n string,\n unknown\n >;\n if (\n requestRecord.temperature !== undefined &&\n !this.supportsTemperature(openRouterRequest.model)\n ) {\n delete requestRecord.temperature;\n }\n\n return openRouterRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n // outputSchema is part of the interface contract but OpenRouter now uses\n // native `response_format` (set in buildRequest), so we no longer inject a\n // synthetic structured-output tool here. The legacy fake-tool injection\n // happens in buildRequest only as a runtime fallback.\n\n _outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n return toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters as JsonObject,\n }));\n }\n\n formatOutputSchema(\n schema: JsonObject | NaturalSchema | z.ZodType,\n ): JsonObject {\n let jsonSchema: JsonObject;\n\n // Check if schema is already a JsonObject — either the OpenAI-style\n // `{ type: \"json_schema\", ... }` envelope or a bare `{ type: \"object\", properties }` node\n if (\n (typeof schema === \"object\" &&\n schema !== null &&\n !Array.isArray(schema) &&\n (schema as JsonObject).type === \"json_schema\") ||\n isJsonSchema(schema)\n ) {\n jsonSchema = structuredClone(schema) as JsonObject;\n jsonSchema.type = \"object\"; // Normalize type\n } else {\n // Convert NaturalSchema to JSON schema through Zod. Re-spread into a\n // plain object: Zod v4's z.toJSONSchema returns an object that carries\n // a non-configurable `~standard` Standard-Schema interop marker as a\n // non-enumerable own property. Anthropic's output_config.format\n // validation is strict and rejects unknown properties when OpenRouter\n // forwards the schema, so we drop the marker here. JSON.stringify\n // already skips it but the OpenRouter SDK enumerates own properties\n // during serialization.\n const zodSchema =\n schema instanceof z.ZodType\n ? schema\n : naturalZodSchema(schema as NaturalSchema);\n jsonSchema = { ...(z.toJSONSchema(zodSchema) as JsonObject) };\n }\n\n // Remove $schema property (can cause issues with some providers)\n if (jsonSchema.$schema) {\n delete jsonSchema.$schema;\n }\n\n // OpenRouter (and most backends behind it) require additionalProperties:\n // false on every object when using strict json_schema response_format.\n enforceAdditionalPropertiesFalse(jsonSchema);\n\n return jsonSchema;\n }\n\n //\n // API Execution\n //\n\n async executeRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): Promise<OpenRouterResponse> {\n const openRouter = client as OpenRouterClient;\n const openRouterRequest = request as OpenRouterRequest;\n const wantsStructuredOutput = Boolean(openRouterRequest.response_format);\n\n try {\n const response = (await openRouter.chatCompletion(\n this.toWireBody(openRouterRequest),\n signal ? { signal } : undefined,\n )) as unknown as AnnotatedOpenRouterResponse;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as OpenRouterResponse;\n\n // If the route rejected `temperature` (e.g., openai/gpt-5.5 forwarding),\n // cache it and retry without the param.\n const requestRecord = openRouterRequest as unknown as Record<\n string,\n unknown\n >;\n if (\n requestRecord.temperature !== undefined &&\n isTemperatureDeprecationError(error)\n ) {\n this.rememberModelRejectsTemperature(openRouterRequest.model);\n const retryRequest = { ...openRouterRequest } as OpenRouterRequest;\n delete (retryRequest as unknown as Record<string, unknown>).temperature;\n const response = (await openRouter.chatCompletion(\n this.toWireBody(retryRequest),\n signal ? { signal } : undefined,\n )) as unknown as AnnotatedOpenRouterResponse;\n if (wantsStructuredOutput) {\n response.__jaypieStructuredOutput = true;\n }\n return response;\n }\n\n // If the model rejected `response_format`, cache it and retry with the\n // legacy fake-tool emulation path.\n if (wantsStructuredOutput && isStructuredOutputUnsupportedError(error)) {\n const model = openRouterRequest.model;\n this.rememberModelRejectsStructuredOutput(model);\n log.warn(\n `[OpenRouterAdapter] Model ${model} rejected native response_format; falling back to legacy structured_output tool emulation.`,\n );\n const fallbackRequest =\n this.toFallbackStructuredOutputRequest(openRouterRequest);\n return (await openRouter.chatCompletion(\n this.toWireBody(fallbackRequest),\n signal ? { signal } : undefined,\n )) as unknown as OpenRouterResponse;\n }\n\n throw error;\n }\n }\n\n /**\n * Translate our internal snake_case `OpenRouterRequest` into the SDK's\n * camelCase shape, forwarding only the fields we care about (the SDK\n * silently strips unknown fields).\n */\n /**\n * Serialize the internal request into the OpenAI-compatible wire body for\n * OpenRouter's Chat Completions endpoint. Top-level fields (model, tools,\n * tool_choice, response_format, user, temperature, and any providerOptions)\n * are already wire-shaped (snake_case); only messages carry camelCase tool\n * fields that must become snake_case on the wire.\n */\n private toWireBody(\n openRouterRequest: OpenRouterRequest,\n ): Record<string, unknown> {\n return {\n ...openRouterRequest,\n messages: openRouterRequest.messages.map(messageToWire),\n };\n }\n\n /**\n * Rebuild a structured-output request without `response_format`, swapping in\n * the legacy fake-tool emulation. Used as a runtime fallback when a model\n * rejects native json_schema.\n */\n private toFallbackStructuredOutputRequest(\n request: OpenRouterRequest,\n ): OpenRouterRequest {\n if (\n !request.response_format ||\n request.response_format.type !== \"json_schema\"\n ) {\n return request;\n }\n const { response_format, ...rest } = request;\n const fallbackRequest: OpenRouterRequest = { ...rest };\n const schema = response_format.json_schema.schema;\n const fakeTool: OpenRouterTool = {\n type: \"function\" as const,\n function: {\n name: STRUCTURED_OUTPUT_TOOL_NAME,\n description:\n \"REQUIRED: You MUST call this tool to provide your final response. \" +\n \"After gathering all necessary information (including results from other tools), \" +\n \"call this tool with the structured data to complete the request.\",\n parameters: schema,\n },\n };\n fallbackRequest.tools = [...(fallbackRequest.tools ?? []), fakeTool];\n fallbackRequest.tool_choice = \"auto\";\n return fallbackRequest;\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const openRouter = client as OpenRouterClient;\n const openRouterRequest = request as OpenRouterRequest;\n\n // streamChatCompletion adds `stream: true` + `stream_options.include_usage`\n // and yields decoded SSE chunks in OpenAI-compatible (snake_case) shape.\n const stream = openRouter.streamChatCompletion(\n this.toWireBody(openRouterRequest),\n signal ? { signal } : undefined,\n ) as AsyncIterable<unknown>;\n\n // Track current tool call being built\n let currentToolCall: {\n id: string;\n name: string;\n arguments: string;\n } | null = null;\n\n // Track usage for final chunk\n let inputTokens = 0;\n let outputTokens = 0;\n const model = openRouterRequest.model || this.defaultModel;\n\n for await (const chunk of stream) {\n // Handle different chunk types from OpenRouter (OpenAI-compatible format)\n interface StreamChunk {\n choices?: Array<{\n delta?: {\n content?: string;\n tool_calls?: Array<{\n id?: string;\n function?: { name?: string; arguments?: string };\n }>;\n };\n finish_reason?: string;\n }>;\n usage?: {\n prompt_tokens?: number;\n completion_tokens?: number;\n promptTokens?: number;\n completionTokens?: number;\n };\n }\n const typedChunk = chunk as StreamChunk;\n const choices = typedChunk.choices;\n\n if (choices && choices.length > 0) {\n const delta = choices[0].delta;\n\n // Handle text content\n if (delta?.content) {\n yield {\n type: LlmStreamChunkType.Text,\n content: delta.content,\n };\n }\n\n // Handle tool calls\n if (delta?.tool_calls && delta.tool_calls.length > 0) {\n for (const toolCallDelta of delta.tool_calls) {\n if (toolCallDelta.id) {\n // New tool call starting\n if (currentToolCall) {\n // Emit the previous tool call\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.id,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n }\n currentToolCall = {\n id: toolCallDelta.id,\n name: toolCallDelta.function?.name || \"\",\n arguments: toolCallDelta.function?.arguments || \"\",\n };\n } else if (currentToolCall) {\n // Continuing existing tool call\n if (toolCallDelta.function?.name) {\n currentToolCall.name += toolCallDelta.function.name;\n }\n if (toolCallDelta.function?.arguments) {\n currentToolCall.arguments += toolCallDelta.function.arguments;\n }\n }\n }\n }\n\n // Check for finish reason\n if (choices[0].finish_reason) {\n // Emit any pending tool call\n if (currentToolCall) {\n yield {\n type: LlmStreamChunkType.ToolCall,\n toolCall: {\n id: currentToolCall.id,\n name: currentToolCall.name,\n arguments: currentToolCall.arguments,\n },\n };\n currentToolCall = null;\n }\n }\n }\n\n // Extract usage if present (usually in the final chunk)\n if (typedChunk.usage) {\n inputTokens =\n typedChunk.usage.prompt_tokens || typedChunk.usage.promptTokens || 0;\n outputTokens =\n typedChunk.usage.completion_tokens ||\n typedChunk.usage.completionTokens ||\n 0;\n }\n }\n\n // Emit done chunk with final usage\n yield {\n type: LlmStreamChunkType.Done,\n usage: [\n {\n input: inputTokens,\n output: outputTokens,\n reasoning: 0,\n total: inputTokens + outputTokens,\n provider: this.name,\n model,\n },\n ],\n };\n }\n\n //\n // Response Parsing\n //\n\n parseResponse(\n response: unknown,\n _options?: LlmOperateOptions,\n ): ParsedResponse {\n const openRouterResponse = response as OpenRouterResponse;\n const choice = openRouterResponse.choices[0];\n\n const content = this.extractContent(openRouterResponse);\n const hasToolCalls = this.hasToolCalls(openRouterResponse);\n\n // SDK returns camelCase (finishReason), but support snake_case as fallback\n const stopReason =\n choice?.finishReason ?? choice?.finish_reason ?? undefined;\n\n return {\n content,\n hasToolCalls,\n stopReason,\n usage: this.extractUsage(openRouterResponse, openRouterResponse.model),\n raw: openRouterResponse,\n };\n }\n\n extractToolCalls(response: unknown): StandardToolCall[] {\n const openRouterResponse = response as OpenRouterResponse;\n const toolCalls: StandardToolCall[] = [];\n const choice = openRouterResponse.choices[0];\n\n // SDK returns camelCase (toolCalls)\n if (!choice?.message?.toolCalls) {\n return toolCalls;\n }\n\n for (const toolCall of choice.message.toolCalls) {\n toolCalls.push({\n callId: toolCall.id,\n name: toolCall.function.name,\n arguments: toolCall.function.arguments,\n raw: toolCall,\n });\n }\n\n return toolCalls;\n }\n\n extractUsage(response: unknown, model: string): LlmUsageItem {\n const openRouterResponse = response as OpenRouterResponse;\n\n if (!openRouterResponse.usage) {\n return {\n input: 0,\n output: 0,\n reasoning: 0,\n total: 0,\n provider: this.name,\n model,\n };\n }\n\n // SDK returns camelCase, but support snake_case as fallback\n const usage = openRouterResponse.usage;\n const cachedTokens =\n usage.promptTokensDetails?.cachedTokens ??\n usage.promptTokensDetails?.cached_tokens ??\n usage.prompt_tokens_details?.cached_tokens;\n return {\n input: usage.promptTokens || usage.prompt_tokens || 0,\n output: usage.completionTokens || usage.completion_tokens || 0,\n reasoning: usage.completionTokensDetails?.reasoningTokens || 0,\n total: usage.totalTokens || usage.total_tokens || 0,\n ...(cachedTokens !== undefined ? { cacheRead: cachedTokens } : {}),\n provider: this.name,\n model,\n };\n }\n\n //\n // Tool Result Handling\n //\n\n formatToolResult(\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): OpenRouterMessage {\n return {\n role: \"tool\",\n toolCallId: toolCall.callId,\n content: result.output,\n };\n }\n\n appendToolResult(\n request: unknown,\n toolCall: StandardToolCall,\n result: StandardToolResult,\n ): OpenRouterRequest {\n const openRouterRequest = request as OpenRouterRequest;\n const toolCallRaw = toolCall.raw as OpenRouterToolCall;\n\n // Add assistant message with the tool call (SDK uses camelCase)\n openRouterRequest.messages.push({\n role: \"assistant\",\n content: null,\n toolCalls: [toolCallRaw],\n });\n\n // Add tool result message\n openRouterRequest.messages.push(this.formatToolResult(toolCall, result));\n\n return openRouterRequest;\n }\n\n //\n // History Management\n //\n\n responseToHistoryItems(response: unknown): LlmHistory {\n const openRouterResponse = response as OpenRouterResponse;\n const historyItems: LlmHistory = [];\n const choice = openRouterResponse.choices[0];\n\n if (!choice?.message) {\n return historyItems;\n }\n\n // Check if this is a tool use response (SDK returns camelCase)\n if (choice.message.toolCalls && choice.message.toolCalls.length > 0) {\n // Don't add to history yet - will be added after tool execution\n return historyItems;\n }\n\n // Extract text content for non-tool responses\n if (choice.message.content) {\n const historyItem: LlmOutputMessage & { reasoning?: string } = {\n content: choice.message.content,\n role: LlmMessageRole.Assistant,\n type: LlmMessageType.Message,\n };\n\n // Preserve reasoning if present (z-ai/glm models include this)\n if (choice.message.reasoning) {\n historyItem.reasoning = choice.message.reasoning;\n }\n\n historyItems.push(historyItem as LlmOutputMessage);\n }\n\n return historyItems;\n }\n\n //\n // Error Classification\n //\n\n classifyError(error: unknown): ClassifiedError {\n // Shared first pass: retryable structured-output timeouts (#422),\n // quota exhaustion, and billing failures classify the same across providers.\n const shared = classifyProviderError(error);\n if (shared) return shared;\n\n // Check if error has a status code (HTTP error)\n const errorWithStatus = error as { status?: number; statusCode?: number };\n const statusCode = errorWithStatus.status || errorWithStatus.statusCode;\n\n if (statusCode) {\n // Rate limit error\n if (statusCode === RATE_LIMIT_STATUS_CODE) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Retryable errors (server errors, timeouts, etc.)\n if (RETRYABLE_STATUS_CODES.includes(statusCode)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Client errors (4xx except 429) are unrecoverable\n if (statusCode >= 400 && statusCode < 500) {\n return {\n error,\n category: ErrorCategory.Unrecoverable,\n shouldRetry: false,\n };\n }\n }\n\n // Check error message for rate limit indicators\n const errorMessage =\n error instanceof Error ? error.message.toLowerCase() : \"\";\n if (\n errorMessage.includes(\"rate limit\") ||\n errorMessage.includes(\"too many requests\")\n ) {\n return {\n error,\n category: ErrorCategory.RateLimit,\n shouldRetry: false,\n suggestedDelayMs: 60000,\n };\n }\n\n // Check for transient network errors (ECONNRESET, etc.)\n if (isTransientNetworkError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n\n // Unknown error - treat as potentially retryable\n return {\n error,\n category: ErrorCategory.Unknown,\n shouldRetry: true,\n };\n }\n\n //\n // Provider-Specific Features\n //\n\n isComplete(response: unknown): boolean {\n const openRouterResponse = response as OpenRouterResponse;\n const choice = openRouterResponse.choices[0];\n\n // Complete if no tool calls (SDK returns camelCase)\n if (!choice?.message?.toolCalls?.length) {\n return true;\n }\n\n return false;\n }\n\n override hasStructuredOutput(response: unknown): boolean {\n const openRouterResponse = response as AnnotatedOpenRouterResponse;\n\n // Native path: executeRequest annotates the response when we sent\n // `response_format`, so we can detect intent statelessly.\n if (openRouterResponse.__jaypieStructuredOutput) {\n return this.extractStructuredOutput(response) !== undefined;\n }\n\n // Fallback path: legacy fake-tool emulation, kept for models that the\n // runtime has cached as not supporting native `response_format`.\n const choice = openRouterResponse.choices[0];\n\n // SDK returns camelCase (toolCalls)\n if (!choice?.message?.toolCalls?.length) {\n return false;\n }\n\n // Check if the last tool call is structured_output\n const lastToolCall =\n choice.message.toolCalls[choice.message.toolCalls.length - 1];\n return lastToolCall?.function?.name === STRUCTURED_OUTPUT_TOOL_NAME;\n }\n\n override extractStructuredOutput(response: unknown): JsonObject | undefined {\n const openRouterResponse = response as AnnotatedOpenRouterResponse;\n\n if (openRouterResponse.__jaypieStructuredOutput) {\n const choice = openRouterResponse.choices[0];\n const content = choice?.message?.content;\n if (typeof content !== \"string\" || content.length === 0) {\n return undefined;\n }\n try {\n return JSON.parse(content) as JsonObject;\n } catch {\n return undefined;\n }\n }\n\n // Fallback path: legacy fake-tool emulation\n const choice = openRouterResponse.choices[0];\n\n // SDK returns camelCase (toolCalls)\n if (!choice?.message?.toolCalls?.length) {\n return undefined;\n }\n\n const lastToolCall =\n choice.message.toolCalls[choice.message.toolCalls.length - 1];\n if (lastToolCall?.function?.name === STRUCTURED_OUTPUT_TOOL_NAME) {\n try {\n return JSON.parse(lastToolCall.function.arguments) as JsonObject;\n } catch {\n return undefined;\n }\n }\n\n return undefined;\n }\n\n //\n // Private Helpers\n //\n\n private hasToolCalls(response: OpenRouterResponse): boolean {\n const choice = response.choices[0];\n // SDK returns camelCase (toolCalls)\n return (choice?.message?.toolCalls?.length ?? 0) > 0;\n }\n\n private extractContent(\n response: OpenRouterResponse,\n ): string | JsonObject | undefined {\n // Check for structured output first\n if (this.hasStructuredOutput(response)) {\n return this.extractStructuredOutput(response);\n }\n\n const choice = response.choices[0];\n return choice?.message?.content ?? undefined;\n }\n\n private convertMessagesToOpenRouter(\n messages: LlmHistory,\n system?: string,\n cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" },\n ): OpenRouterMessage[] {\n const openRouterMessages: OpenRouterMessage[] = [];\n\n // Add system message if provided. A cache_control breakpoint on the system\n // content is forwarded by OpenRouter to Anthropic/Gemini backends (and\n // ignored by others), caching the stable system prefix.\n if (system) {\n openRouterMessages.push({\n role: \"system\",\n content: cacheControl\n ? [{ type: \"text\", text: system, cache_control: cacheControl }]\n : system,\n });\n }\n\n for (const msg of messages) {\n const message = msg as unknown as Record<string, unknown>;\n\n // Handle different message types\n if (message.role === \"system\") {\n openRouterMessages.push({\n role: \"system\",\n content: message.content as string,\n });\n } else if (message.role === \"user\") {\n openRouterMessages.push({\n role: \"user\",\n content: convertContentToOpenRouter(\n message.content as string | LlmInputContent[],\n ),\n });\n } else if (message.role === \"assistant\") {\n const assistantMsg: OpenRouterMessage = {\n role: \"assistant\",\n content: (message.content as string) || null,\n };\n\n // Include toolCalls if present (check both camelCase and snake_case for compatibility)\n if (message.toolCalls) {\n assistantMsg.toolCalls = message.toolCalls as OpenRouterToolCall[];\n } else if (message.tool_calls) {\n assistantMsg.toolCalls = message.tool_calls as OpenRouterToolCall[];\n }\n\n openRouterMessages.push(assistantMsg);\n } else if (message.role === \"tool\") {\n openRouterMessages.push({\n role: \"tool\",\n toolCallId:\n (message.toolCallId as string) || (message.tool_call_id as string),\n content: message.content as string,\n });\n } else if (message.type === LlmMessageType.Message) {\n // Handle internal message format\n const role = (message.role as string)?.toLowerCase();\n if (role === \"assistant\") {\n openRouterMessages.push({\n role: \"assistant\",\n content: message.content as string,\n });\n } else {\n openRouterMessages.push({\n role: \"user\",\n content: convertContentToOpenRouter(\n message.content as string | LlmInputContent[],\n ),\n });\n }\n } else if (message.type === LlmMessageType.FunctionCall) {\n // Handle FunctionCall messages from StreamLoop (issue #165)\n openRouterMessages.push({\n role: \"assistant\",\n content: null,\n toolCalls: [\n {\n id: message.call_id as string,\n type: \"function\" as const,\n function: {\n name: message.name as string,\n arguments: (message.arguments as string) || \"{}\",\n },\n },\n ],\n });\n } else if (message.type === LlmMessageType.FunctionCallOutput) {\n // Handle FunctionCallOutput messages from StreamLoop (issue #165)\n openRouterMessages.push({\n role: \"tool\",\n toolCallId: message.call_id as string,\n content: (message.output as string) || \"\",\n });\n }\n }\n\n return openRouterMessages;\n }\n}\n\n// Export singleton instance\nexport const openRouterAdapter = new OpenRouterAdapter();\n","import { type LlmEffort, PROVIDER } from \"../../constants.js\";\nimport { BadRequestError } from \"../../providers/openai/client.js\";\nimport { type LlmEffortMapping, toXaiEffort } from \"../../util/effort.js\";\nimport { ClassifiedError, ErrorCategory } from \"../types.js\";\nimport { OpenAiAdapter } from \"./OpenAiAdapter.js\";\n\n/**\n * Error-message substrings that indicate a transient xAI media-ingest flake.\n * The xAI ingest service enters a bad state after ~12 consecutive file-bearing\n * calls and rejects subsequent requests with HTTP 400. The condition is\n * self-clearing, so these errors should be retried with backoff rather than\n * surfaced as unrecoverable.\n *\n * See: github.com/finlaysonstudio/jaypie issue #301\n */\nconst TRANSIENT_INGEST_MESSAGE_PATTERNS = [\n \"failed to ingest inline file bytes\",\n] as const;\n\nfunction isTransientIngestError(error: unknown): boolean {\n if (!(error instanceof BadRequestError)) return false;\n const message = (error.message ?? \"\").toLowerCase();\n return TRANSIENT_INGEST_MESSAGE_PATTERNS.some((pattern) =>\n message.includes(pattern),\n );\n}\n\n/**\n * XaiAdapter extends OpenAiAdapter since xAI (Grok) uses an OpenAI-compatible API.\n * Name, default model, and transient-ingest-error detection are overridden;\n * all request building, response parsing, tool handling, and streaming are\n * inherited.\n */\nexport class XaiAdapter extends OpenAiAdapter {\n // @ts-expect-error Narrowing override: xAI name differs from parent's literal \"openai\"\n readonly name = PROVIDER.XAI.NAME;\n readonly defaultModel = PROVIDER.XAI.DEFAULT;\n\n /**\n * Grok gates reasoning effort by model, not by the OpenAI `gpt-*`/`o*`\n * patterns. Only explicit `*-reasoning` models accept `reasoning_effort`;\n * bare grok-4 reasons implicitly and rejects it, so we stay conservative and\n * only opt in models whose name advertises reasoning.\n */\n protected supportsReasoningEffort(model: string): boolean {\n if (/non-reasoning/.test(model)) return false;\n return /reasoning/.test(model);\n }\n\n protected mapReasoningEffort(effort: LlmEffort): LlmEffortMapping {\n return toXaiEffort(effort);\n }\n\n classifyError(error: unknown): ClassifiedError {\n if (isTransientIngestError(error)) {\n return {\n error,\n category: ErrorCategory.Retryable,\n shouldRetry: true,\n };\n }\n return super.classifyError(error);\n }\n}\n\n// Export singleton instance\nexport const xaiAdapter = new XaiAdapter();\n","import { JAYPIE, resolveValue } from \"@jaypie/kit\";\nimport { log as jaypieLog } from \"@jaypie/logger\";\nimport { JsonObject } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\n\nimport { LlmTool } from \"../types/LlmTool.interface\";\n\nconst DEFAULT_TOOL_TYPE = \"function\";\n\nconst log = jaypieLog.lib({ lib: JAYPIE.LIB.LLM });\n\ntype LogFunction = (\n message: string,\n context: { name: string; args: any },\n) => void | Promise<void>;\n\nfunction logToolMessage(message: string, context: { name: string; args: any }) {\n log.trace.var({ [context.name]: message });\n}\n\nexport interface ToolkitOptions {\n explain?: boolean;\n log?: boolean | LogFunction;\n}\n\nexport class Toolkit {\n private readonly _tools: LlmTool[];\n private readonly _options: ToolkitOptions;\n private readonly explain: boolean;\n private readonly log: boolean | LogFunction;\n\n constructor(tools: LlmTool[], options?: ToolkitOptions) {\n this._tools = tools;\n this._options = options || {};\n this.explain = this._options.explain ? true : false;\n this.log = this._options.log !== undefined ? this._options.log : true;\n }\n\n get tools(): Omit<LlmTool, \"call\">[] {\n return this._tools.map((tool) => {\n const toolCopy: any = { ...tool };\n delete toolCopy.call;\n delete toolCopy.message;\n\n // Convert Zod schema to JSON Schema if needed\n if (toolCopy.parameters instanceof z.ZodType) {\n const jsonSchema = z.toJSONSchema(toolCopy.parameters) as JsonObject;\n // Remove $schema property (causes issues with some providers)\n if (jsonSchema.$schema) {\n delete jsonSchema.$schema;\n }\n toolCopy.parameters = jsonSchema;\n }\n\n if (this.explain && toolCopy.parameters?.type === \"object\") {\n if (toolCopy.parameters?.properties) {\n if (!toolCopy.parameters.properties.__Explanation) {\n toolCopy.parameters.properties.__Explanation = {\n type: \"string\",\n description: `Clearly state why the tool is being called and what larger question it helps answer. For example, \"I am checking the location API because the user asked for nearby pizza and I need coordinates to proceed\"`,\n };\n }\n }\n }\n\n // Set default type if not provided\n if (!toolCopy.type) {\n toolCopy.type = DEFAULT_TOOL_TYPE;\n }\n\n return toolCopy;\n });\n }\n\n private parseArgs(args: string) {\n let parsedArgs;\n try {\n parsedArgs = JSON.parse(args);\n if (this.explain) {\n delete parsedArgs.__Explanation;\n }\n } catch {\n parsedArgs = args;\n }\n return parsedArgs;\n }\n\n /**\n * Resolve a tool's `message` (static string or function of args) without\n * calling the tool. Returns undefined when the tool is missing or defines\n * no message. Never throws; resolution errors log at warn.\n */\n async resolveMessage({\n name,\n arguments: args,\n }: {\n name: string;\n arguments: string;\n }): Promise<string | undefined> {\n const tool = this._tools.find((t) => t.name === name);\n if (!tool || !tool.message) {\n return undefined;\n }\n\n try {\n if (typeof tool.message === \"string\") {\n return tool.message;\n }\n const parsedArgs = this.parseArgs(args);\n if (typeof tool.message === \"function\") {\n return await resolveValue(tool.message(parsedArgs, { name }));\n }\n log.warn(\"[Toolkit] Tool provided unknown message type\");\n return String(tool.message);\n } catch (error) {\n log.warn(\"[Toolkit] Caught error resolving tool message\");\n log.var({ error });\n return undefined;\n }\n }\n\n async call({\n name,\n arguments: args,\n message: resolvedMessage,\n }: {\n name: string;\n arguments: string;\n /** Pre-resolved tool message; skips re-resolving `tool.message` for logging */\n message?: string;\n }) {\n const tool = this._tools.find((t) => t.name === name);\n if (!tool) {\n throw new Error(`Tool '${name}' not found`);\n }\n\n const parsedArgs = this.parseArgs(args);\n\n if (this.log !== false) {\n try {\n const context: { name: string; args: any; explanation?: string } = {\n name,\n args: parsedArgs,\n };\n\n if (this.explain) {\n context.explanation = parsedArgs.__Explanation;\n }\n\n const message =\n resolvedMessage ??\n (await this.resolveMessage({ arguments: args, name })) ??\n `${tool.name}:${JSON.stringify(parsedArgs)}`;\n\n if (typeof this.log === \"function\") {\n log.trace(\"[Toolkit] Log tool call with custom logger\");\n await resolveValue(this.log(message, context));\n } else {\n log.trace(\"[Toolkit] Log tool call with default logger\");\n logToolMessage(message, context);\n }\n } catch (error) {\n log.error(\"[Toolkit] Caught error during logToolCall\");\n log.var({ error });\n log.debug(\"[Toolkit] Continuing...\");\n }\n }\n\n return await resolveValue(tool.call(parsedArgs));\n }\n\n extend(\n tools: LlmTool[],\n options: {\n warn?: boolean;\n replace?: boolean;\n log?: boolean | LogFunction;\n explain?: boolean;\n } = {},\n ): this {\n for (const tool of tools) {\n const existingIndex = this._tools.findIndex((t) => t.name === tool.name);\n if (existingIndex !== -1) {\n if (options.replace === false) {\n continue;\n }\n if (options.warn !== false) {\n if (typeof this.log === \"function\") {\n this.log(\n `[Toolkit] Tool '${tool.name}' already exists, replacing with new tool`,\n { name: tool.name, args: {} },\n );\n } else if (this.log) {\n log.warn(\n `[Toolkit] Tool '${tool.name}' already exists, replacing with new tool`,\n );\n }\n }\n this._tools[existingIndex] = tool;\n } else {\n this._tools.push(tool);\n }\n }\n if (Object.prototype.hasOwnProperty.call(options, \"log\")) {\n (this as any).log = options.log;\n }\n if (Object.prototype.hasOwnProperty.call(options, \"explain\")) {\n (this as any).explain = options.explain;\n }\n return this;\n }\n}\n","import { createRequire } from \"module\";\nimport { pathToFileURL } from \"url\";\n\nimport { getLogger } from \"../util/index.js\";\n\n//\n//\n// Types\n//\n\n/**\n * LLM Observability span kinds supported by Datadog's `llmobs` SDK.\n * @see https://docs.datadoghq.com/llm_observability/setup/sdk/nodejs/\n */\nexport type LlmObsSpanKind =\n \"agent\" | \"embedding\" | \"llm\" | \"retrieval\" | \"task\" | \"tool\" | \"workflow\";\n\nexport interface LlmObsSpanOptions {\n kind: LlmObsSpanKind;\n modelName?: string;\n modelProvider?: string;\n name: string;\n}\n\nexport interface LlmObsAnnotation {\n inputData?: unknown;\n metadata?: Record<string, unknown>;\n metrics?: Record<string, number>;\n outputData?: unknown;\n tags?: Record<string, unknown>;\n}\n\n/** Manual span handle for streaming, where a callback cannot enclose the work. */\nexport interface LlmObsSpanHandle {\n annotate: (annotation: LlmObsAnnotation) => void;\n finish: () => void;\n}\n\n/** Minimal shape of the dd-trace `llmobs` SDK surface this module uses. */\ninterface LlmObsSdk {\n annotate: (span: unknown, annotation: LlmObsAnnotation) => void;\n trace: (\n options: LlmObsSpanOptions,\n fn: (span: unknown) => unknown,\n ) => unknown;\n}\n\n//\n//\n// Constants\n//\n\nconst ENV = {\n DD_LLMOBS_ENABLED: \"DD_LLMOBS_ENABLED\",\n};\n\nconst MODULE = {\n // Computed at runtime so bundlers (esbuild) do not attempt to include\n // dd-trace, which is provided by the Datadog Lambda layer at runtime.\n DD_TRACE: [\"dd\", \"trace\"].join(\"-\"),\n};\n\n//\n//\n// Helpers\n//\n\n// CJS/ESM compatible require - handles bundling to CJS where import.meta.url\n// becomes undefined (mirrors packages/testkit/src/mock/original.ts).\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore - __filename exists in CJS context when ESM is bundled to CJS\nconst requireModule =\n typeof __filename !== \"undefined\"\n ? createRequire(pathToFileURL(__filename).href)\n : createRequire(import.meta.url);\n\nlet resolved = false;\nlet cachedSdk: LlmObsSdk | null = null;\nlet injectedSdk: LlmObsSdk | null = null;\n\n/**\n * Lazily resolve the dd-trace `llmobs` SDK. Returns null (and never throws)\n * when dd-trace is absent or the SDK surface is unexpected. Cached after the\n * first attempt.\n */\nfunction resolveLlmObs(): LlmObsSdk | null {\n if (resolved) {\n return cachedSdk;\n }\n resolved = true;\n try {\n const ddTrace = requireModule(MODULE.DD_TRACE);\n const tracer = ddTrace?.default ?? ddTrace;\n const llmobs = tracer?.llmobs;\n if (\n llmobs &&\n typeof llmobs.trace === \"function\" &&\n typeof llmobs.annotate === \"function\"\n ) {\n cachedSdk = llmobs as LlmObsSdk;\n }\n } catch {\n cachedSdk = null;\n }\n return cachedSdk;\n}\n\n/** Reset the cached SDK resolution. Exposed for tests. */\nexport function _resetLlmObs(): void {\n resolved = false;\n cachedSdk = null;\n injectedSdk = null;\n}\n\n/**\n * Inject an SDK to bypass dd-trace resolution. Test-only: dd-trace is not a\n * dependency, so the enabled path cannot otherwise be exercised in unit tests.\n */\nexport function _setLlmObs(sdk: LlmObsSdk | null): void {\n injectedSdk = sdk;\n}\n\n//\n//\n// Main\n//\n\n/**\n * True when LLM Observability emission is opted in via `DD_LLMOBS_ENABLED`.\n * Accepts any truthy value except \"false\"/\"0\".\n */\nexport function isLlmObsEnabled(): boolean {\n const value = process.env[ENV.DD_LLMOBS_ENABLED];\n if (!value) {\n return false;\n }\n const normalized = value.trim().toLowerCase();\n return normalized !== \"\" && normalized !== \"false\" && normalized !== \"0\";\n}\n\n/** Resolve the SDK only when enabled and available. */\nfunction activeSdk(): LlmObsSdk | null {\n if (!isLlmObsEnabled()) {\n return null;\n }\n return injectedSdk ?? resolveLlmObs();\n}\n\n/**\n * Run `fn` inside an LLM Observability span. When emission is disabled or\n * dd-trace is absent, `fn` is invoked directly with no overhead. The active\n * span is established for the duration of `fn`, so nested `withLlmObsSpan`\n * calls (and `annotateLlmObs`) attach as children/annotations automatically.\n */\nexport async function withLlmObsSpan<T>(\n options: LlmObsSpanOptions,\n fn: () => Promise<T>,\n): Promise<T> {\n const sdk = activeSdk();\n if (!sdk) {\n return fn();\n }\n let started = false;\n try {\n return (await sdk.trace(options, () => {\n started = true;\n return fn();\n })) as T;\n } catch (error) {\n // If `fn` ran, propagate its error (the SDK re-throws after finishing the\n // span). Only swallow failures from the instrumentation itself, re-running\n // `fn` so observability never breaks the underlying call.\n if (started) {\n throw error;\n }\n getLogger().warn(\"[llmobs] span emission failed\");\n getLogger().var({ error });\n return fn();\n }\n}\n\n/**\n * Annotate the currently active LLM Observability span. No-op when disabled.\n */\nexport function annotateLlmObs(annotation: LlmObsAnnotation): void {\n const sdk = activeSdk();\n if (!sdk) {\n return;\n }\n try {\n sdk.annotate(undefined, annotation);\n } catch (error) {\n getLogger().warn(\"[llmobs] annotate failed\");\n getLogger().var({ error });\n }\n}\n\n/**\n * Open a manual span that is finished later. Used by streaming, where work is\n * yielded incrementally and cannot be enclosed in a single callback. The span\n * is kept open via a deferred promise resolved by `finish()`. Returns null when\n * emission is disabled or dd-trace is absent.\n *\n * Note: because the span is held open across `yield` boundaries (outside the\n * SDK's AsyncLocalStorage scope), manual spans are emitted flat rather than\n * nested. Annotations are applied to the explicit span reference.\n */\nexport function openLlmObsSpan(\n options: LlmObsSpanOptions,\n): LlmObsSpanHandle | null {\n const sdk = activeSdk();\n if (!sdk) {\n return null;\n }\n try {\n let capturedSpan: unknown;\n let release: (() => void) | undefined;\n const held = new Promise<void>((resolve) => {\n release = resolve;\n });\n // trace() runs the callback synchronously, capturing the span; the returned\n // pending promise keeps the span open until finish() resolves it.\n void sdk.trace(options, (span) => {\n capturedSpan = span;\n return held;\n });\n let finished = false;\n return {\n annotate: (annotation: LlmObsAnnotation) => {\n try {\n sdk.annotate(capturedSpan, annotation);\n } catch (error) {\n getLogger().warn(\"[llmobs] annotate failed\");\n getLogger().var({ error });\n }\n },\n finish: () => {\n if (finished) {\n return;\n }\n finished = true;\n release?.();\n },\n };\n } catch (error) {\n getLogger().warn(\"[llmobs] span emission failed\");\n getLogger().var({ error });\n return null;\n }\n}\n\n//\n//\n// Mapping Helpers\n//\n\n/**\n * Sum an `LlmUsage` array into LLM Observability metric keys. Returns undefined\n * when there is no usage data so callers can omit the `metrics` field.\n */\nexport function usageToLlmObsMetrics(\n usage?: Array<{ input?: number; output?: number; total?: number }>,\n): Record<string, number> | undefined {\n if (!usage || usage.length === 0) {\n return undefined;\n }\n const metrics = usage.reduce(\n (sum, item) => ({\n input_tokens: sum.input_tokens + (item.input ?? 0),\n output_tokens: sum.output_tokens + (item.output ?? 0),\n total_tokens: sum.total_tokens + (item.total ?? 0),\n }),\n { input_tokens: 0, output_tokens: 0, total_tokens: 0 },\n );\n return metrics;\n}\n","import { resolveValue } from \"@jaypie/kit\";\nimport { JsonObject } from \"@jaypie/types\";\n\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmOperateOptions,\n LlmUsage,\n} from \"../../types/LlmProvider.interface.js\";\n\n//\n//\n// Types\n//\n\nexport interface BeforeModelRequestContext {\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: unknown;\n}\n\nexport interface AfterModelResponseContext {\n content: string | JsonObject;\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: unknown;\n providerResponse: unknown;\n usage: LlmUsage;\n}\n\nexport interface BeforeToolContext {\n args: string;\n message?: string;\n toolName: string;\n}\n\nexport interface AfterToolContext {\n args: string;\n message?: string;\n result: unknown;\n toolName: string;\n}\n\nexport interface ToolErrorContext {\n args: string;\n error: Error;\n message?: string;\n toolName: string;\n}\n\nexport interface RetryableErrorContext {\n error: unknown;\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: unknown;\n}\n\nexport interface UnrecoverableErrorContext {\n error: unknown;\n input: string | LlmHistory | LlmInputMessage;\n options?: LlmOperateOptions;\n providerRequest: unknown;\n}\n\nexport type LlmHooks = LlmOperateOptions[\"hooks\"];\n\n//\n//\n// Main\n//\n\n/**\n * HookRunner provides a centralized, consistent way to execute lifecycle hooks\n * during the LLM operate loop. It handles async resolution and provides error\n * isolation for hook execution.\n */\nexport class HookRunner {\n /**\n * Execute the beforeEachModelRequest hook if defined\n */\n async runBeforeModelRequest(\n hooks: LlmHooks,\n context: BeforeModelRequestContext,\n ): Promise<void> {\n if (hooks?.beforeEachModelRequest) {\n await resolveValue(hooks.beforeEachModelRequest(context));\n }\n }\n\n /**\n * Execute the afterEachModelResponse hook if defined\n */\n async runAfterModelResponse(\n hooks: LlmHooks,\n context: AfterModelResponseContext,\n ): Promise<void> {\n if (hooks?.afterEachModelResponse) {\n await resolveValue(hooks.afterEachModelResponse(context));\n }\n }\n\n /**\n * Execute the beforeEachTool hook if defined\n */\n async runBeforeTool(\n hooks: LlmHooks,\n context: BeforeToolContext,\n ): Promise<void> {\n if (hooks?.beforeEachTool) {\n await resolveValue(hooks.beforeEachTool(context));\n }\n }\n\n /**\n * Execute the afterEachTool hook if defined\n */\n async runAfterTool(\n hooks: LlmHooks,\n context: AfterToolContext,\n ): Promise<void> {\n if (hooks?.afterEachTool) {\n await resolveValue(hooks.afterEachTool(context));\n }\n }\n\n /**\n * Execute the onToolError hook if defined\n */\n async runOnToolError(\n hooks: LlmHooks,\n context: ToolErrorContext,\n ): Promise<void> {\n if (hooks?.onToolError) {\n await resolveValue(hooks.onToolError(context));\n }\n }\n\n /**\n * Execute the onRetryableModelError hook if defined\n */\n async runOnRetryableError(\n hooks: LlmHooks,\n context: RetryableErrorContext,\n ): Promise<void> {\n if (hooks?.onRetryableModelError) {\n await resolveValue(hooks.onRetryableModelError(context));\n }\n }\n\n /**\n * Execute the onUnrecoverableModelError hook if defined\n */\n async runOnUnrecoverableError(\n hooks: LlmHooks,\n context: UnrecoverableErrorContext,\n ): Promise<void> {\n if (hooks?.onUnrecoverableModelError) {\n await resolveValue(hooks.onUnrecoverableModelError(context));\n }\n }\n}\n\n// Export singleton instance for convenience\nexport const hookRunner = new HookRunner();\n","import type {\n LlmOperateInput,\n LlmOperateInputContent,\n LlmOperateInputFile,\n LlmOperateInputImage,\n} from \"./LlmProvider.interface.js\";\n\n/**\n * Type guard to check if an item is an LlmOperateInputFile\n */\nexport function isLlmOperateInputFile(\n item: unknown,\n): item is LlmOperateInputFile {\n return (\n typeof item === \"object\" &&\n item !== null &&\n \"file\" in item &&\n typeof (item as LlmOperateInputFile).file === \"string\"\n );\n}\n\n/**\n * Type guard to check if an item is an LlmOperateInputImage\n */\nexport function isLlmOperateInputImage(\n item: unknown,\n): item is LlmOperateInputImage {\n return (\n typeof item === \"object\" &&\n item !== null &&\n \"image\" in item &&\n typeof (item as LlmOperateInputImage).image === \"string\"\n );\n}\n\n/**\n * Type guard to check if an item is an LlmOperateInputContent\n */\nexport function isLlmOperateInputContent(\n item: unknown,\n): item is LlmOperateInputContent {\n return (\n typeof item === \"string\" ||\n isLlmOperateInputFile(item) ||\n isLlmOperateInputImage(item)\n );\n}\n\n/**\n * Type guard to check if input is an LlmOperateInput array\n */\nexport function isLlmOperateInput(input: unknown): input is LlmOperateInput {\n return (\n Array.isArray(input) &&\n input.length > 0 &&\n input.every(isLlmOperateInputContent)\n );\n}\n","/**\n * Image extensions that are auto-detected from file paths\n */\nconst IMAGE_EXTENSIONS = new Set([\n \"avif\",\n \"bmp\",\n \"gif\",\n \"ico\",\n \"jpeg\",\n \"jpg\",\n \"png\",\n \"svg\",\n \"tiff\",\n \"webp\",\n]);\n\n/**\n * Mapping of file extensions to MIME types\n */\nconst EXTENSION_TO_MIME: Record<string, string> = {\n // Images\n avif: \"image/avif\",\n bmp: \"image/bmp\",\n gif: \"image/gif\",\n ico: \"image/x-icon\",\n jpeg: \"image/jpeg\",\n jpg: \"image/jpeg\",\n png: \"image/png\",\n svg: \"image/svg+xml\",\n tiff: \"image/tiff\",\n webp: \"image/webp\",\n\n // Documents\n pdf: \"application/pdf\",\n\n // Text\n json: \"application/json\",\n txt: \"text/plain\",\n};\n\n/**\n * Extract file extension from a path or filename\n */\nexport function getFileExtension(filePath: string): string | undefined {\n const match = filePath.match(/\\.(\\w+)$/);\n return match ? match[1].toLowerCase() : undefined;\n}\n\n/**\n * Determine MIME type from file extension\n */\nexport function getMimeType(filePath: string): string | undefined {\n const ext = getFileExtension(filePath);\n return ext ? EXTENSION_TO_MIME[ext] : undefined;\n}\n\n/**\n * Check if a file path has an image extension\n */\nexport function isImageExtension(filePath: string): boolean {\n const ext = getFileExtension(filePath);\n return ext ? IMAGE_EXTENSIONS.has(ext) : false;\n}\n\n/**\n * Check if a file path has a PDF extension\n */\nexport function isPdfExtension(filePath: string): boolean {\n const ext = getFileExtension(filePath);\n return ext === \"pdf\";\n}\n","import { PDFDocument } from \"pdf-lib\";\n\n/**\n * Extract specific pages from a PDF buffer\n * @param pdfBytes - Buffer containing the PDF data\n * @param pages - Array of page numbers to extract (1-indexed)\n * @returns Buffer containing a new PDF with only the specified pages\n */\nexport async function extractPdfPages(\n pdfBytes: Buffer,\n pages: number[],\n): Promise<Buffer> {\n const pdfDoc = await PDFDocument.load(pdfBytes);\n const totalPages = pdfDoc.getPageCount();\n\n // Validate page numbers\n for (const pageNum of pages) {\n if (pageNum < 1 || pageNum > totalPages) {\n throw new Error(\n `Page number ${pageNum} is out of range. Document has ${totalPages} pages.`,\n );\n }\n }\n\n // Create a new PDF with only the specified pages\n const newPdfDoc = await PDFDocument.create();\n\n // Convert 1-indexed page numbers to 0-indexed for pdf-lib\n const pageIndices = pages.map((p) => p - 1);\n const copiedPages = await newPdfDoc.copyPages(pdfDoc, pageIndices);\n\n for (const page of copiedPages) {\n newPdfDoc.addPage(page);\n }\n\n const newPdfBytes = await newPdfDoc.save();\n return Buffer.from(newPdfBytes);\n}\n\n/**\n * Get the total number of pages in a PDF\n * @param pdfBytes - Buffer containing the PDF data\n * @returns Total number of pages\n */\nexport async function getPdfPageCount(pdfBytes: Buffer): Promise<number> {\n const pdfDoc = await PDFDocument.load(pdfBytes);\n return pdfDoc.getPageCount();\n}\n","import { readFile } from \"fs/promises\";\nimport { resolve } from \"path\";\n\n/**\n * Load a file from the local filesystem\n * @param filePath - Path to the file (relative paths resolve from process.cwd())\n * @returns Buffer containing the file contents\n */\nexport async function loadLocalFile(filePath: string): Promise<Buffer> {\n const absolutePath = resolve(process.cwd(), filePath);\n return readFile(absolutePath);\n}\n","import { getS3FileBuffer } from \"@jaypie/aws\";\n\n/**\n * Load a file from S3\n * @param bucket - S3 bucket name\n * @param key - S3 object key\n * @returns Buffer containing the file contents\n */\nexport async function loadS3File(bucket: string, key: string): Promise<Buffer> {\n return getS3FileBuffer({ bucket, key });\n}\n","import {\n LlmInputContent,\n LlmInputContentFile,\n LlmInputContentImage,\n LlmInputContentText,\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateInput,\n LlmOperateInputContent,\n LlmOperateInputFile,\n LlmOperateInputImage,\n} from \"../types/LlmProvider.interface.js\";\nimport {\n isLlmOperateInputFile,\n isLlmOperateInputImage,\n} from \"../types/LlmOperateInput.guards.js\";\nimport {\n getMimeType,\n isImageExtension,\n isPdfExtension,\n} from \"./detectMimeType.js\";\nimport { extractPdfPages } from \"./extractPdfPages.js\";\nimport { loadLocalFile } from \"./loadLocalFile.js\";\nimport { loadS3File } from \"./loadS3File.js\";\n\n/**\n * Resolved content ready for LLM providers\n */\ninterface ResolvedContent {\n data: string; // base64 data\n mimeType: string;\n filename: string;\n}\n\n/**\n * Load file data from source (provided data, S3, or local filesystem)\n */\nasync function loadFileData(\n item: LlmOperateInputFile | LlmOperateInputImage,\n): Promise<Buffer> {\n // Get the path from either file or image property\n const path = \"file\" in item ? item.file : item.image;\n\n // Priority 1: Use provided data directly\n if (item.data) {\n return Buffer.from(item.data, \"base64\");\n }\n\n // Priority 2: Load from S3 (explicit bucket or CDK_ENV_BUCKET fallback)\n const bucket = item.bucket ?? process.env.CDK_ENV_BUCKET;\n if (bucket) {\n return loadS3File(bucket, path);\n }\n\n // Priority 3: Load from local filesystem\n return loadLocalFile(path);\n}\n\n/**\n * Resolve a file input to content ready for LLM\n */\nasync function resolveFileInput(\n item: LlmOperateInputFile,\n): Promise<ResolvedContent> {\n let buffer = await loadFileData(item);\n const mimeType = getMimeType(item.file) || \"application/octet-stream\";\n const filename = item.file.split(\"/\").pop() || item.file;\n\n // Handle PDF page extraction\n if (isPdfExtension(item.file) && item.pages && item.pages.length > 0) {\n buffer = await extractPdfPages(buffer, item.pages);\n }\n\n return {\n data: buffer.toString(\"base64\"),\n filename,\n mimeType,\n };\n}\n\n/**\n * Resolve an image input to content ready for LLM\n */\nasync function resolveImageInput(\n item: LlmOperateInputImage,\n): Promise<ResolvedContent> {\n const buffer = await loadFileData(item);\n const mimeType = getMimeType(item.image) || \"image/png\";\n const filename = item.image.split(\"/\").pop() || item.image;\n\n return {\n data: buffer.toString(\"base64\"),\n filename,\n mimeType,\n };\n}\n\n/**\n * Convert resolved content to LlmInputContent\n */\nfunction toInputContent(\n resolved: ResolvedContent,\n isImage: boolean,\n): LlmInputContent {\n if (isImage) {\n const imageContent: LlmInputContentImage = {\n image_url: `data:${resolved.mimeType};base64,${resolved.data}`,\n type: LlmMessageType.InputImage,\n };\n return imageContent;\n }\n\n const fileContent: LlmInputContentFile = {\n file_data: `data:${resolved.mimeType};base64,${resolved.data}`,\n filename: resolved.filename,\n type: LlmMessageType.InputFile,\n };\n return fileContent;\n}\n\n/**\n * Resolve a single content item\n */\nasync function resolveContentItem(\n item: LlmOperateInputContent,\n): Promise<LlmInputContent> {\n // String becomes text content\n if (typeof item === \"string\") {\n const textContent: LlmInputContentText = {\n text: item,\n type: LlmMessageType.InputText,\n };\n return textContent;\n }\n\n // Image input\n if (isLlmOperateInputImage(item)) {\n const resolved = await resolveImageInput(item);\n return toInputContent(resolved, true);\n }\n\n // File input\n if (isLlmOperateInputFile(item)) {\n const resolved = await resolveFileInput(item);\n // Check if the file is actually an image based on extension\n const isImage = isImageExtension(item.file);\n return toInputContent(resolved, isImage);\n }\n\n // Fallback - shouldn't reach here if types are correct\n throw new Error(`Unknown content item type: ${JSON.stringify(item)}`);\n}\n\n/**\n * Resolve LlmOperateInput to LlmInputMessage\n *\n * This function takes the simplified LlmOperateInput format and resolves\n * all files/images from their sources (provided data, S3, or local filesystem),\n * converting them to the standard LlmInputMessage format.\n *\n * @param input - LlmOperateInput array\n * @returns LlmInputMessage ready for LLM providers\n */\nexport async function resolveOperateInput(\n input: LlmOperateInput,\n): Promise<LlmInputMessage> {\n const content: LlmInputContent[] = await Promise.all(\n input.map(resolveContentItem),\n );\n\n return {\n content,\n role: LlmMessageRole.User,\n type: LlmMessageType.Message,\n };\n}\n","import { placeholders } from \"@jaypie/kit\";\n\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateInput,\n LlmOperateOptions,\n} from \"../../types/LlmProvider.interface.js\";\nimport { isLlmOperateInput } from \"../../types/LlmOperateInput.guards.js\";\nimport { resolveOperateInput } from \"../../upload/resolveOperateInput.js\";\nimport { formatOperateInput } from \"../../util/index.js\";\n\n//\n//\n// Types\n//\n\nexport interface ProcessedInput {\n /** The processed history with all messages formatted */\n history: LlmHistory;\n /** Processed instructions with placeholders applied */\n instructions?: string;\n /** Processed system prompt with placeholders applied */\n system?: string;\n}\n\n//\n//\n// Main\n//\n\n/**\n * InputProcessor handles input normalization, placeholder substitution,\n * and history merging for the operate loop.\n */\nexport class InputProcessor {\n /**\n * Process input with placeholders, history merging, and system message handling\n *\n * @param input - The raw input (string, message, history, or LlmOperateInput)\n * @param options - The operate options containing data, history, system, etc.\n * @returns Processed input with all transformations applied\n */\n async process(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions = {},\n ): Promise<ProcessedInput> {\n // Handle LlmOperateInput by resolving files first\n let resolvedInput: string | LlmHistory | LlmInputMessage = input as\n string | LlmHistory | LlmInputMessage;\n if (isLlmOperateInput(input)) {\n resolvedInput = await resolveOperateInput(input);\n }\n\n // Convert input to history format with placeholder substitution\n let history: LlmHistory = this.formatInputWithPlaceholders(\n resolvedInput,\n options,\n );\n\n // Process instructions with placeholders\n const instructions = this.processInstructions(options);\n\n // Process system prompt with placeholders\n const system = this.processSystem(options);\n\n // Merge with provided history\n if (options.history) {\n history = [...options.history, ...history];\n }\n\n // Handle system message prepending\n if (system) {\n history = this.prependSystemMessage(history, system);\n }\n\n return {\n history,\n instructions,\n system,\n };\n }\n\n /**\n * Format input and apply placeholders if data is provided\n */\n private formatInputWithPlaceholders(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions,\n ): LlmHistory {\n // Apply placeholders to input if data is provided and placeholders.input is not false\n if (\n options.data &&\n (options.placeholders?.input === undefined || options.placeholders?.input)\n ) {\n return formatOperateInput(input, { data: options.data });\n }\n\n return formatOperateInput(input);\n }\n\n /**\n * Process instructions with placeholder substitution\n */\n private processInstructions(options: LlmOperateOptions): string | undefined {\n if (!options.instructions) {\n return undefined;\n }\n\n // Apply placeholders to instructions if data is provided and placeholders.instructions is not false\n if (\n options.data &&\n (options.placeholders?.instructions === undefined ||\n options.placeholders?.instructions)\n ) {\n return placeholders(options.instructions, options.data);\n }\n\n return options.instructions;\n }\n\n /**\n * Process system prompt with placeholder substitution\n */\n private processSystem(options: LlmOperateOptions): string | undefined {\n if (!options.system) {\n return undefined;\n }\n\n // Apply placeholders to system if data is provided and placeholders.system is not false\n if (options.data && options.placeholders?.system !== false) {\n return placeholders(options.system, options.data);\n }\n\n return options.system;\n }\n\n /**\n * Prepend system message to history, handling duplicates\n */\n private prependSystemMessage(\n history: LlmHistory,\n systemContent: string,\n ): LlmHistory {\n // Create system message\n const systemMessage: LlmInputMessage = {\n content: systemContent,\n role: LlmMessageRole.System,\n type: LlmMessageType.Message,\n };\n\n // Check if history starts with an identical system message\n const firstMessage = history[0] as LlmInputMessage | undefined;\n const isIdenticalSystemMessage =\n firstMessage?.type === LlmMessageType.Message &&\n firstMessage?.role === LlmMessageRole.System &&\n firstMessage?.content === systemContent;\n\n // If identical, return as-is\n if (isIdenticalSystemMessage) {\n return history;\n }\n\n // Remove any existing system message from the beginning\n if (\n firstMessage?.type === LlmMessageType.Message &&\n firstMessage?.role === LlmMessageRole.System\n ) {\n return [systemMessage, ...history.slice(1)];\n }\n\n // Prepend new system message\n return [systemMessage, ...history];\n }\n}\n\n// Export singleton instance for convenience\nexport const inputProcessor = new InputProcessor();\n","import {\n LlmProgressCallback,\n LlmProgressEvent,\n} from \"../../types/LlmProvider.interface.js\";\nimport { getLogger } from \"../../util/index.js\";\n\n/**\n * Deliver a progress event to the caller's onProgress callback.\n * Errors thrown by the callback are logged and swallowed — progress\n * reporting must never interrupt the operate loop.\n */\nexport async function emitProgress({\n event,\n onProgress,\n}: {\n event: LlmProgressEvent;\n onProgress?: LlmProgressCallback;\n}): Promise<void> {\n if (!onProgress) {\n return;\n }\n try {\n await onProgress(event);\n } catch (error) {\n const log = getLogger();\n log.warn(`[operate] onProgress callback threw on \"${event.type}\" event`);\n log.var({ error });\n }\n}\n","import { JsonObject, JsonReturn } from \"@jaypie/types\";\n\nimport {\n LlmHistory,\n LlmOperateResponse,\n LlmResponseStatus,\n LlmUsage,\n LlmUsageItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { extractReasoning } from \"../../util/extractReasoning.js\";\n\n// Derive LlmOutput type from LlmOperateResponse since it's not exported\ntype LlmOutput = LlmOperateResponse[\"output\"];\n\n//\n//\n// Types\n//\n\nexport interface ResponseBuilderConfig {\n model: string;\n provider: string;\n}\n\nexport interface LlmError {\n detail?: string;\n status: number | string;\n title: string;\n}\n\n//\n//\n// Main\n//\n\n/**\n * ResponseBuilder provides a fluent API for constructing LlmOperateResponse objects.\n * It standardizes response construction across providers.\n */\nexport class ResponseBuilder {\n private response: LlmOperateResponse;\n\n constructor(config: ResponseBuilderConfig) {\n this.response = {\n content: undefined,\n error: undefined,\n history: [],\n model: config.model,\n output: [],\n provider: config.provider,\n reasoning: [],\n responses: [],\n status: LlmResponseStatus.InProgress,\n usage: [],\n };\n }\n\n /**\n * Set the response content\n */\n setContent(content: string | JsonObject | undefined): this {\n this.response.content = content;\n return this;\n }\n\n /**\n * Set the response status\n */\n setStatus(status: LlmResponseStatus): this {\n this.response.status = status;\n return this;\n }\n\n /**\n * Set an error on the response\n */\n setError(error: LlmError): this {\n this.response.error = error;\n return this;\n }\n\n /**\n * Set the history\n */\n setHistory(history: LlmHistory): this {\n this.response.history = history;\n return this;\n }\n\n /**\n * Append items to the history\n */\n appendToHistory(...items: LlmHistory): this {\n this.response.history.push(...items);\n return this;\n }\n\n /**\n * Set the output\n */\n setOutput(output: LlmOutput): this {\n this.response.output = output;\n return this;\n }\n\n /**\n * Append items to the output\n */\n appendToOutput(...items: LlmOutput): this {\n this.response.output.push(...items);\n return this;\n }\n\n /**\n * Set the reasoning array\n */\n setReasoning(reasoning: string[]): this {\n this.response.reasoning = reasoning;\n return this;\n }\n\n /**\n * Append reasoning text items\n */\n appendToReasoning(...items: string[]): this {\n this.response.reasoning.push(...items);\n return this;\n }\n\n /**\n * Get the current reasoning array\n */\n getReasoning(): string[] {\n return this.response.reasoning;\n }\n\n /**\n * Add a raw provider response\n */\n addResponse(response: JsonReturn): this {\n this.response.responses.push(response);\n return this;\n }\n\n /**\n * Add a usage entry for a single API call\n */\n addUsage(usage: LlmUsageItem): this {\n this.response.usage.push(usage);\n return this;\n }\n\n /**\n * Set the entire usage array\n */\n setUsage(usage: LlmUsage): this {\n this.response.usage = usage;\n return this;\n }\n\n /**\n * Get the current usage array for modifications\n */\n getUsage(): LlmUsage {\n return this.response.usage;\n }\n\n /**\n * Get the current history for modifications\n */\n getHistory(): LlmHistory {\n return this.response.history;\n }\n\n /**\n * Get the current output for modifications\n */\n getOutput(): LlmOutput {\n return this.response.output;\n }\n\n /**\n * Mark response as completed\n */\n complete(): this {\n this.response.status = LlmResponseStatus.Completed;\n return this;\n }\n\n /**\n * Mark response as incomplete (e.g., max turns exceeded)\n */\n incomplete(): this {\n this.response.status = LlmResponseStatus.Incomplete;\n return this;\n }\n\n /**\n * Build and return the final response object.\n * Automatically extracts reasoning from history if not already set.\n */\n build(): LlmOperateResponse {\n // Extract reasoning from history if not already populated\n if (this.response.reasoning.length === 0) {\n this.response.reasoning = extractReasoning(this.response.history);\n }\n return { ...this.response };\n }\n}\n\n/**\n * Factory function to create a new ResponseBuilder\n */\nexport function createResponseBuilder(\n config: ResponseBuilderConfig,\n): ResponseBuilder {\n return new ResponseBuilder(config);\n}\n","//\n//\n// Constants\n//\n\nexport const DEFAULT_INITIAL_DELAY_MS = 1000; // 1 second\nexport const DEFAULT_MAX_DELAY_MS = 32000; // 32 seconds\nexport const DEFAULT_BACKOFF_FACTOR = 2; // Exponential backoff multiplier\nexport const DEFAULT_MAX_RETRIES = 6;\nexport const MAX_RETRIES_ABSOLUTE_LIMIT = 72;\n\n//\n//\n// Types\n//\n\nexport interface RetryPolicyConfig {\n /** Initial delay in milliseconds before first retry. Default: 1000 */\n initialDelayMs?: number;\n /** Maximum delay in milliseconds between retries. Default: 32000 */\n maxDelayMs?: number;\n /** Backoff multiplier for exponential backoff. Default: 2 */\n backoffFactor?: number;\n /** Maximum number of retries. Default: 6 */\n maxRetries?: number;\n}\n\n//\n//\n// Main\n//\n\n/**\n * RetryPolicy encapsulates retry configuration and delay calculation\n * for the operate loop's retry logic.\n */\nexport class RetryPolicy {\n readonly initialDelayMs: number;\n readonly maxDelayMs: number;\n readonly backoffFactor: number;\n readonly maxRetries: number;\n\n constructor(config: RetryPolicyConfig = {}) {\n this.initialDelayMs = config.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n this.maxDelayMs = config.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n this.backoffFactor = config.backoffFactor ?? DEFAULT_BACKOFF_FACTOR;\n this.maxRetries = Math.min(\n config.maxRetries ?? DEFAULT_MAX_RETRIES,\n MAX_RETRIES_ABSOLUTE_LIMIT,\n );\n }\n\n /**\n * Calculate the delay for a given attempt number (0-indexed)\n */\n getDelayForAttempt(attempt: number): number {\n const delay = this.initialDelayMs * Math.pow(this.backoffFactor, attempt);\n return Math.min(delay, this.maxDelayMs);\n }\n\n /**\n * Check if another retry should be attempted\n */\n shouldRetry(currentAttempt: number): boolean {\n return currentAttempt < this.maxRetries;\n }\n}\n\n// Export a default policy instance\nexport const defaultRetryPolicy = new RetryPolicy();\n","import { getLogger } from \"../../util/index.js\";\nimport { isTransientNetworkError } from \"./isTransientNetworkError.js\";\n\n//\n//\n// Types\n//\n\nexport interface StaleRejectionGuard {\n /** Install the unhandledRejection listener (idempotent) */\n install(): void;\n /** Remove the listener and forget recorded errors */\n remove(): void;\n /** Record an error the retry loop has caught and is handling */\n recordCaught(error: unknown): void;\n}\n\n//\n//\n// Helpers\n//\n\n/**\n * Compare an unhandled rejection reason against errors the retry loop has\n * already caught. Reference equality first, then fall back to message + name\n * — providers sometimes surface twin rejections as fresh Error instances\n * rebuilt from the same upstream failure.\n */\nfunction matchesCaughtError(\n reason: unknown,\n caught: ReadonlySet<unknown>,\n): boolean {\n if (caught.has(reason)) return true;\n if (!(reason instanceof Error)) return false;\n for (const handled of caught) {\n if (\n handled instanceof Error &&\n handled.name === reason.name &&\n handled.message === reason.message\n ) {\n return true;\n }\n }\n return false;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Create a guard that suppresses unhandled rejections firing as siblings of\n * an error the retry loop has already caught. Provider SDKs occasionally\n * surface a single upstream failure as twin rejections — the retry layer\n * accepts responsibility for the first; this guard prevents the second from\n * crashing the host while the retry is in flight.\n *\n * The guard also continues to suppress transient socket teardown errors\n * (e.g. undici `TypeError: terminated`) emitted between attempts.\n */\nexport function createStaleRejectionGuard(): StaleRejectionGuard {\n const log = getLogger();\n const caughtErrors = new Set<unknown>();\n let listener:\n ((reason: unknown, promise: Promise<unknown>) => void) | undefined;\n\n return {\n install() {\n if (listener) return;\n listener = (reason, promise) => {\n if (isTransientNetworkError(reason)) {\n promise?.catch?.(() => {});\n log.trace(\"Suppressed stale socket error during retry\");\n return;\n }\n if (matchesCaughtError(reason, caughtErrors)) {\n promise?.catch?.(() => {});\n log.trace(\"Suppressed sibling rejection of already-handled error\");\n }\n };\n process.on(\"unhandledRejection\", listener);\n },\n remove() {\n if (listener) {\n process.removeListener(\"unhandledRejection\", listener);\n listener = undefined;\n }\n caughtErrors.clear();\n },\n recordCaught(error) {\n caughtErrors.add(error);\n },\n };\n}\n","import { JaypieError } from \"@jaypie/errors\";\nimport { ErrorCategory } from \"../operate/types.js\";\n\n//\n//\n// Types\n//\n\nexport interface LlmErrorOptions {\n /** Provider name that produced the error (e.g. \"anthropic\", \"google\") */\n provider?: string;\n /** Model in use when the error occurred */\n model?: string;\n /** Milliseconds to wait before retrying, when the provider suggests one */\n retryAfterMs?: number;\n /** The original provider error, preserved for inspection */\n cause?: unknown;\n}\n\n//\n//\n// Base\n//\n\n/**\n * Normalized, provider-agnostic LLM error. Thrown by the operate/stream retry\n * layer when a request cannot be completed, so consumers can `catch` a stable\n * type regardless of which provider failed. Extends {@link JaypieError} so\n * `isJaypieError()` and `.status` continue to work; the original provider error\n * is preserved on `.cause`.\n */\nexport class LlmError extends JaypieError {\n readonly category: ErrorCategory;\n readonly provider?: string;\n readonly model?: string;\n readonly retryAfterMs?: number;\n readonly cause?: unknown;\n\n constructor(\n message: string,\n category: ErrorCategory,\n {\n status = 502,\n title = \"Bad Gateway\",\n provider,\n model,\n retryAfterMs,\n cause,\n }: LlmErrorOptions & { status?: number; title?: string } = {},\n ) {\n super(message, { status, title }, { _type: \"LlmError\" });\n this.name = \"LlmError\";\n this.category = category;\n this.provider = provider;\n this.model = model;\n this.retryAfterMs = retryAfterMs;\n this.cause = cause;\n }\n}\n\n//\n//\n// Subclasses\n//\n\n/**\n * Short-term rate limiting (per-minute 429). Terminal within the request\n * budget; `retryAfterMs` carries the provider's suggested wait when available.\n */\nexport class LlmRateLimitError extends LlmError {\n constructor(message: string, options: LlmErrorOptions = {}) {\n super(message, ErrorCategory.RateLimit, {\n status: 429,\n title: \"Too Many Requests\",\n ...options,\n });\n this.name = \"LlmRateLimitError\";\n }\n}\n\n/**\n * Provider quota is exhausted or the account cannot be billed. Terminal and\n * actionable. `reason` distinguishes an exhausted usage quota from insufficient\n * funds.\n */\nexport class LlmQuotaError extends LlmError {\n readonly reason: \"quota\" | \"billing\";\n\n constructor(\n message: string,\n {\n reason = \"quota\",\n ...options\n }: LlmErrorOptions & {\n reason?: \"quota\" | \"billing\";\n } = {},\n ) {\n super(message, ErrorCategory.Quota, {\n status: 402,\n title: \"Payment Required\",\n ...options,\n });\n this.name = \"LlmQuotaError\";\n this.reason = reason;\n }\n}\n\n/**\n * The request cannot be recovered from (bad request, authentication,\n * permission, not found). Terminal.\n */\nexport class LlmUnrecoverableError extends LlmError {\n constructor(message: string, options: LlmErrorOptions = {}) {\n super(message, ErrorCategory.Unrecoverable, {\n status: 502,\n title: \"Bad Gateway\",\n ...options,\n });\n this.name = \"LlmUnrecoverableError\";\n }\n}\n\n/**\n * A transient or unknown error survived the retry budget. Terminal only because\n * retries were exhausted; the underlying condition may succeed later.\n */\nexport class LlmTransientError extends LlmError {\n constructor(message: string, options: LlmErrorOptions = {}) {\n super(message, ErrorCategory.Retryable, {\n status: 504,\n title: \"Gateway Timeout\",\n ...options,\n });\n this.name = \"LlmTransientError\";\n }\n}\n","import { ClassifiedError, ErrorCategory } from \"../operate/types.js\";\nimport {\n LlmError,\n LlmErrorOptions,\n LlmQuotaError,\n LlmRateLimitError,\n LlmTransientError,\n LlmUnrecoverableError,\n} from \"./LlmError.js\";\n\n/**\n * Map a {@link ClassifiedError} to the matching {@link LlmError} subclass,\n * preserving the original error as `cause`. Used by the retry layer to throw a\n * stable, catchable type instead of a bare gateway error.\n */\nexport function toLlmError(\n classified: ClassifiedError,\n context: { provider?: string; model?: string } = {},\n): LlmError {\n const original = classified.error;\n const message =\n original instanceof Error ? original.message : String(original);\n const options: LlmErrorOptions = {\n cause: original,\n model: context.model,\n provider: context.provider,\n retryAfterMs: classified.suggestedDelayMs,\n };\n\n switch (classified.category) {\n case ErrorCategory.RateLimit:\n return new LlmRateLimitError(message, options);\n case ErrorCategory.Quota:\n return new LlmQuotaError(message, {\n ...options,\n reason: classified.reason ?? \"quota\",\n });\n case ErrorCategory.Unrecoverable:\n return new LlmUnrecoverableError(message, options);\n case ErrorCategory.Retryable:\n case ErrorCategory.Unknown:\n default:\n return new LlmTransientError(message, options);\n }\n}\n","import { sleep } from \"@jaypie/kit\";\n\nimport { getLogger } from \"../../util/index.js\";\nimport { createStaleRejectionGuard } from \"./createStaleRejectionGuard.js\";\nimport {\n HookRunner,\n hookRunner as defaultHookRunner,\n LlmHooks,\n} from \"../hooks/HookRunner.js\";\nimport { RetryPolicy, defaultRetryPolicy } from \"./RetryPolicy.js\";\nimport { ClassifiedError } from \"../types.js\";\nimport { toLlmError } from \"../../errors/toLlmError.js\";\n\n//\n//\n// Types\n//\n\nexport interface RetryContext {\n input: unknown;\n options?: unknown;\n providerRequest: unknown;\n /** Provider name, carried onto the thrown LlmError */\n provider?: string;\n /** Model in use, carried onto the thrown LlmError */\n model?: string;\n}\n\nexport interface ErrorClassifier {\n isRetryable(error: unknown): boolean;\n isKnownError(error: unknown): boolean;\n /** Full classification, used to throw a typed LlmError on terminal failure */\n classify(error: unknown): ClassifiedError;\n}\n\nexport interface RetryExecutorConfig {\n errorClassifier: ErrorClassifier;\n hookRunner?: HookRunner;\n policy?: RetryPolicy;\n}\n\nexport interface ExecuteOptions {\n context: RetryContext;\n hooks?: LlmHooks;\n}\n\n//\n//\n// Main\n//\n\n/**\n * RetryExecutor handles the retry loop logic for LLM API calls.\n * It provides exponential backoff, error classification, and hook execution.\n */\nexport class RetryExecutor {\n private readonly policy: RetryPolicy;\n private readonly hookRunner: HookRunner;\n private readonly errorClassifier: ErrorClassifier;\n\n constructor(config: RetryExecutorConfig) {\n this.policy = config.policy ?? defaultRetryPolicy;\n this.hookRunner = config.hookRunner ?? defaultHookRunner;\n this.errorClassifier = config.errorClassifier;\n }\n\n /**\n * Build the typed, provider-agnostic error thrown when a request cannot be\n * completed — classified (rate limit / quota / unrecoverable / transient)\n * and carrying the provider, model, and original error as `cause`.\n */\n private toTerminalError(error: unknown, context: RetryContext) {\n const classified = this.errorClassifier.classify(error);\n return toLlmError(classified, {\n model: context.model,\n provider: context.provider,\n });\n }\n\n /**\n * Execute an operation with retry logic.\n * Each attempt receives an AbortSignal. On failure, the signal is aborted\n * before sleeping — this kills lingering socket callbacks from the previous\n * request and prevents stale async errors from escaping the retry loop.\n *\n * @param operation - The async operation to execute (receives AbortSignal)\n * @param options - Execution options including context and hooks\n * @returns The result of the operation\n * @throws BadGatewayError if all retries are exhausted or error is not retryable\n */\n async execute<T>(\n operation: ((signal: AbortSignal) => Promise<T>) | (() => Promise<T>),\n options: ExecuteOptions,\n ): Promise<T> {\n const log = getLogger();\n let attempt = 0;\n\n // Guard against stale rejections firing on a subsequent microtask after\n // the retry layer has already caught the originating error: undici socket\n // teardown (TypeError: terminated) and twin upstream-SDK rejections\n // (e.g. issue #336 — OpenRouter SyntaxError siblings).\n const guard = createStaleRejectionGuard();\n\n try {\n while (true) {\n const controller = new AbortController();\n\n try {\n const result = await operation(controller.signal);\n\n if (attempt > 0) {\n log.debug(`API call succeeded after ${attempt} retries`);\n }\n\n return result;\n } catch (error: unknown) {\n controller.abort(\"retry\");\n\n guard.recordCaught(error);\n guard.install();\n\n // Check if we've exhausted retries\n if (!this.policy.shouldRetry(attempt)) {\n log.error(\n `API call failed after ${this.policy.maxRetries} retries`,\n );\n log.var({ error });\n\n await this.hookRunner.runOnUnrecoverableError(options.hooks, {\n input: options.context.input as never,\n options: options.context.options as never,\n providerRequest: options.context.providerRequest,\n error,\n });\n\n throw this.toTerminalError(error, options.context);\n }\n\n // Check if error is not retryable\n if (!this.errorClassifier.isRetryable(error)) {\n log.error(\"API call failed with non-retryable error\");\n log.var({ error });\n\n await this.hookRunner.runOnUnrecoverableError(options.hooks, {\n input: options.context.input as never,\n options: options.context.options as never,\n providerRequest: options.context.providerRequest,\n error,\n });\n\n throw this.toTerminalError(error, options.context);\n }\n\n // Warn if this is an unknown error type\n if (!this.errorClassifier.isKnownError(error)) {\n log.warn(\"API returned unknown error type, will retry\");\n log.var({ error });\n }\n\n const delay = this.policy.getDelayForAttempt(attempt);\n log.warn(`API call failed. Retrying in ${delay}ms...`);\n\n await this.hookRunner.runOnRetryableError(options.hooks, {\n input: options.context.input as never,\n options: options.context.options as never,\n providerRequest: options.context.providerRequest,\n error,\n });\n\n await sleep(delay);\n attempt++;\n }\n }\n } finally {\n guard.remove();\n }\n }\n}\n","import { BadGatewayError, TooManyRequestsError } from \"@jaypie/errors\";\nimport { JsonObject } from \"@jaypie/types\";\n\nimport { Toolkit } from \"../tools/Toolkit.class.js\";\nimport {\n LlmExchangeEnvelope,\n LlmHistory,\n LlmHistoryItem,\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateInput,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmOutputMessage,\n LlmProgressEventType,\n LlmResponseStatus,\n LlmToolCall,\n LlmToolResult,\n} from \"../types/LlmProvider.interface.js\";\nimport {\n annotateLlmObs,\n usageToLlmObsMetrics,\n withLlmObsSpan,\n} from \"../observability/llmobs.js\";\nimport {\n fillFormatArrays,\n getLogger,\n maxTurnsFromOptions,\n repairFormatKeys,\n tallyOperate,\n} from \"../util/index.js\";\nimport { ProviderAdapter } from \"./adapters/ProviderAdapter.interface.js\";\nimport {\n buildExchangeEnvelope,\n isExchangeRequested,\n} from \"./exchange/index.js\";\nimport { HookRunner, hookRunner, LlmHooks } from \"./hooks/index.js\";\nimport { InputProcessor, inputProcessor } from \"./input/index.js\";\nimport { emitProgress } from \"./progress/index.js\";\nimport {\n createResponseBuilder,\n ResponseBuilderConfig,\n} from \"./response/index.js\";\nimport {\n defaultRetryPolicy,\n ErrorClassifier,\n RetryExecutor,\n RetryPolicy,\n} from \"./retry/index.js\";\nimport {\n OperateContext,\n OperateLoopState,\n OperateRequest,\n ProviderToolDefinition,\n StandardToolResult,\n} from \"./types.js\";\n\n//\n//\n// Types\n//\n\nexport interface OperateLoopConfig {\n adapter: ProviderAdapter;\n client: unknown;\n hookRunner?: HookRunner;\n inputProcessor?: InputProcessor;\n retryPolicy?: RetryPolicy;\n}\n\n//\n//\n// Constants\n//\n\nconst ERROR = {\n BAD_FUNCTION_CALL: \"Bad Function Call\",\n};\n\nexport const MAX_CONSECUTIVE_TOOL_ERRORS = 6;\n\n//\n//\n// Helpers\n//\n\n/**\n * Create an ErrorClassifier from a ProviderAdapter\n */\nfunction createErrorClassifier(adapter: ProviderAdapter): ErrorClassifier {\n return {\n classify: (error: unknown) => adapter.classifyError(error),\n isRetryable: (error: unknown) => adapter.isRetryableError(error),\n isKnownError: (error: unknown) => {\n const classified = adapter.classifyError(error);\n return classified.category !== \"unknown\";\n },\n };\n}\n\n/**\n * Attempt to read a prose response as the structured payload itself: parse the\n * text (stripping a Markdown code fence if present) and return the object, or\n * undefined when the text is not a JSON object.\n */\nfunction tryParseJsonObject(text: string): JsonObject | undefined {\n let candidate = text.trim();\n const fence = candidate.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```$/);\n if (fence) {\n candidate = fence[1].trim();\n }\n if (!candidate.startsWith(\"{\")) {\n return undefined;\n }\n try {\n const parsed = JSON.parse(candidate);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as JsonObject;\n }\n } catch {\n // Not JSON; caller falls through to the corrective-turn path.\n }\n return undefined;\n}\n\n//\n//\n// Main\n//\n\n/**\n * OperateLoop implements the core multi-turn conversation loop.\n * It orchestrates provider adapters, retry logic, hook execution, and tool calling.\n *\n * This class uses Template Method + Strategy patterns:\n * - Template Method: The execute() method defines the algorithm skeleton\n * - Strategy: Provider adapters handle provider-specific operations\n */\nexport class OperateLoop {\n private readonly adapter: ProviderAdapter;\n private readonly client: unknown;\n private readonly hookRunnerInstance: HookRunner;\n private readonly inputProcessorInstance: InputProcessor;\n private readonly retryPolicy: RetryPolicy;\n\n constructor(config: OperateLoopConfig) {\n this.adapter = config.adapter;\n this.client = config.client;\n this.hookRunnerInstance = config.hookRunner ?? hookRunner;\n this.inputProcessorInstance = config.inputProcessor ?? inputProcessor;\n this.retryPolicy = config.retryPolicy ?? defaultRetryPolicy;\n }\n\n /**\n * Execute the operate loop for multi-turn conversations with tool calling.\n */\n async execute(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const log = getLogger();\n // Log what was passed to operate\n log.trace(\"[operate] Starting operate loop\");\n log.trace.var({ \"operate.input\": input });\n log.trace.var({ \"operate.options\": options });\n\n const startedAt = new Date().toISOString();\n const startMs = Date.now();\n\n // Initialize state\n const state = await this.initializeState(input, options);\n const context = this.createContext(options);\n const modelName = options.model ?? this.adapter.defaultModel;\n const exchangeRequested = isExchangeRequested(options);\n const initialHistoryLength = state.responseBuilder.getHistory().length;\n\n await emitProgress({\n event: {\n maxTurns: state.maxTurns,\n model: modelName,\n provider: this.adapter.name,\n type: LlmProgressEventType.Start,\n },\n onProgress: options.onProgress,\n });\n\n // Enclosing LLM Observability span (no-op when DD_LLMOBS_ENABLED is unset).\n // Child llm/tool spans nest under it via the SDK's active-span context.\n try {\n return await withLlmObsSpan(\n {\n kind: state.toolkit ? \"agent\" : \"llm\",\n modelName,\n modelProvider: this.adapter.name,\n name: \"jaypie.llm.operate\",\n },\n async () => {\n // Build initial request\n let request = this.buildInitialRequest(state, options);\n\n // Multi-turn loop\n while (state.currentTurn < state.maxTurns) {\n state.currentTurn++;\n\n // Execute one turn with retry logic\n const shouldContinue = await this.executeOneTurn(\n request,\n state,\n context,\n options,\n );\n\n if (!shouldContinue) {\n break;\n }\n\n // Rebuild request with updated history for next turn\n request = {\n effort: options.effort,\n format: state.formattedFormat,\n instructions: options.instructions,\n messages: state.currentInput,\n model: modelName,\n providerOptions: options.providerOptions,\n structuredOutputRetry: state.structuredOutputRetry,\n system: options.system,\n temperature: options.temperature,\n tools: state.formattedTools,\n user: options.user,\n };\n }\n\n const response = state.responseBuilder.build();\n if (exchangeRequested) {\n response.exchange = buildExchangeEnvelope({\n duration: Date.now() - startMs,\n initialHistoryLength,\n input,\n options,\n response,\n startedAt,\n state,\n });\n }\n annotateLlmObs({\n inputData: input,\n metrics: usageToLlmObsMetrics(response.usage),\n outputData: response.content,\n });\n tallyOperate({\n toolCallNames: state.toolCallNames,\n turns: state.currentTurn,\n usage: response.usage,\n });\n await emitProgress({\n event: {\n content: response.content,\n turn: state.currentTurn,\n type: LlmProgressEventType.Done,\n usage: response.usage,\n },\n onProgress: options.onProgress,\n });\n return response;\n },\n );\n } catch (error) {\n // A hard failure (retry budget exhausted, unrecoverable) still settles\n // the exchange: attach the envelope to the thrown error so the facade\n // can emit it before rethrowing to the caller.\n if (exchangeRequested) {\n const response = state.responseBuilder.build();\n if (!response.error) {\n const thrown = error as {\n detail?: string;\n message?: string;\n status?: number | string;\n title?: string;\n name?: string;\n };\n response.error = {\n detail: thrown.detail ?? thrown.message,\n status: thrown.status ?? 500,\n title: thrown.title ?? thrown.name ?? \"Error\",\n };\n }\n if (response.status === LlmResponseStatus.InProgress) {\n response.status = LlmResponseStatus.Incomplete;\n }\n (error as { exchange?: LlmExchangeEnvelope }).exchange =\n buildExchangeEnvelope({\n duration: Date.now() - startMs,\n initialHistoryLength,\n input,\n options,\n response,\n startedAt,\n state,\n });\n }\n throw error;\n }\n }\n\n //\n // Private Methods\n //\n\n private async initializeState(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions,\n ): Promise<OperateLoopState> {\n // Process input with placeholders\n const processedInput = await this.inputProcessorInstance.process(\n input,\n options,\n );\n\n // Determine max turns\n const maxTurns = maxTurnsFromOptions(options);\n\n // Initialize response builder\n const responseBuilderConfig: ResponseBuilderConfig = {\n model: options.model ?? this.adapter.defaultModel,\n provider: this.adapter.name,\n };\n const responseBuilder = createResponseBuilder(responseBuilderConfig);\n\n // Set initial history\n responseBuilder.setHistory([...processedInput.history]);\n\n // Get toolkit\n let toolkit: Toolkit | undefined;\n if (options.tools) {\n if (options.tools instanceof Toolkit) {\n toolkit = options.tools;\n } else if (Array.isArray(options.tools) && options.tools.length > 0) {\n const explain = options.explain ?? false;\n toolkit = new Toolkit(options.tools, { explain });\n }\n }\n\n // Format output schema through adapter if provided\n let formattedFormat: JsonObject | undefined;\n if (options.format) {\n formattedFormat = this.adapter.formatOutputSchema(\n options.format,\n ) as JsonObject;\n }\n\n // Format tools through adapter\n // If format is provided but no toolkit, create an empty toolkit\n // so that structured_output tool can be added for providers that need it\n // (Anthropic, OpenRouter use tool-based structured output)\n let formattedTools: ProviderToolDefinition[] | undefined;\n if (toolkit) {\n formattedTools = this.adapter.formatTools(toolkit, formattedFormat);\n } else if (formattedFormat) {\n // Create empty toolkit just for structured output\n const emptyToolkit = new Toolkit([]);\n formattedTools = this.adapter.formatTools(emptyToolkit, formattedFormat);\n // Only include if there are tools (structured_output was added)\n if (formattedTools.length === 0) {\n formattedTools = undefined;\n }\n }\n\n return {\n consecutiveToolErrors: 0,\n currentInput: processedInput.history,\n currentTurn: 0,\n formattedFormat,\n formattedTools,\n maxTurns,\n responseBuilder,\n retries: 0,\n toolCallNames: [],\n toolkit,\n };\n }\n\n private createContext(options: LlmOperateOptions): OperateContext {\n return {\n hooks: options.hooks ?? {},\n options,\n };\n }\n\n private buildInitialRequest(\n state: OperateLoopState,\n options: LlmOperateOptions,\n ): OperateRequest {\n return {\n cache: options.cache,\n effort: options.effort,\n format: state.formattedFormat,\n instructions: options.instructions,\n messages: state.currentInput,\n model: options.model ?? this.adapter.defaultModel,\n providerOptions: options.providerOptions,\n system: options.system,\n temperature: options.temperature,\n tools: state.formattedTools,\n user: options.user,\n };\n }\n\n private async executeOneTurn(\n request: OperateRequest,\n state: OperateLoopState,\n context: OperateContext,\n options: LlmOperateOptions,\n ): Promise<boolean> {\n const log = getLogger();\n // Create error classifier from adapter\n const errorClassifier = createErrorClassifier(this.adapter);\n\n // Create retry executor for this turn\n const retryExecutor = new RetryExecutor({\n errorClassifier,\n hookRunner: this.hookRunnerInstance,\n policy: this.retryPolicy,\n });\n\n // Build provider-specific request\n const providerRequest = this.adapter.buildRequest(request);\n\n // Log a draconian subset of the request; the full payload is available\n // via the beforeEachModelRequest hook\n log.trace(\"[operate] Calling model\");\n log.trace.var({\n \"operate.request\": {\n latest: this.summarizeHistoryItem(\n request.messages[request.messages.length - 1],\n ),\n messages: request.messages.length,\n model: request.model,\n turn: state.currentTurn,\n },\n });\n\n await emitProgress({\n event: {\n model: request.model,\n turn: state.currentTurn,\n type: LlmProgressEventType.ModelRequest,\n },\n onProgress: options.onProgress,\n });\n\n // Execute beforeEachModelRequest hook\n await this.hookRunnerInstance.runBeforeModelRequest(context.hooks, {\n input: state.currentInput,\n options,\n providerRequest,\n });\n\n // Count retries for the exchange envelope and emit retry progress\n // alongside the caller's onRetryableModelError hook\n const hooks = context.hooks as LlmHooks;\n const hooksWithProgress: LlmHooks = {\n ...hooks,\n onRetryableModelError: async (retryContext) => {\n state.retries++;\n await emitProgress({\n event: {\n error:\n retryContext.error instanceof Error\n ? retryContext.error.message\n : String(retryContext.error),\n turn: state.currentTurn,\n type: LlmProgressEventType.Retry,\n },\n onProgress: options.onProgress,\n });\n return hooks?.onRetryableModelError?.(retryContext);\n },\n };\n\n // Execute with retry inside a child llm span (no-op when llmobs disabled).\n // RetryExecutor handles error hooks and throws appropriate errors.\n const { parsed, response, toolCalls } = await withLlmObsSpan(\n {\n kind: \"llm\",\n modelName: options.model ?? this.adapter.defaultModel,\n modelProvider: this.adapter.name,\n name: \"jaypie.llm.model\",\n },\n async () => {\n const response = await retryExecutor.execute(\n (signal) =>\n this.adapter.executeRequest(this.client, providerRequest, signal),\n {\n context: {\n input: state.currentInput,\n model: options.model ?? this.adapter.defaultModel,\n options,\n provider: this.adapter.name,\n providerRequest,\n },\n hooks: hooksWithProgress,\n },\n );\n\n // Parse response\n const parsed = this.adapter.parseResponse(response, options);\n const toolCalls = parsed.hasToolCalls\n ? this.adapter.extractToolCalls(response)\n : [];\n\n // Log only the text or tool calls; the full payload is available\n // via the afterEachModelResponse hook\n log.trace(\"[operate] Model response received\");\n log.trace.var({\n \"operate.response\":\n toolCalls.length > 0\n ? toolCalls.map(({ arguments: args, name }) => ({\n arguments: args,\n name,\n }))\n : parsed.content,\n });\n\n annotateLlmObs({\n inputData: state.currentInput,\n metrics: usageToLlmObsMetrics(\n parsed.usage ? [parsed.usage] : undefined,\n ),\n outputData: parsed.content ?? \"\",\n });\n\n return { parsed, response, toolCalls };\n },\n );\n\n await emitProgress({\n event: {\n content: parsed.content,\n toolCalls: toolCalls.map(({ arguments: args, name }) => ({\n arguments: args,\n name,\n })),\n turn: state.currentTurn,\n type: LlmProgressEventType.ModelResponse,\n usage: parsed.usage ? [parsed.usage] : undefined,\n },\n onProgress: options.onProgress,\n });\n\n // Track usage\n if (parsed.usage) {\n state.responseBuilder.addUsage(parsed.usage);\n }\n\n // Track stop reason for the exchange envelope\n if (parsed.stopReason) {\n state.lastStopReason = parsed.stopReason;\n }\n\n // Add raw response\n\n state.responseBuilder.addResponse(parsed.raw as any);\n\n // Execute afterEachModelResponse hook\n const currentUsage = state.responseBuilder.build().usage;\n await this.hookRunnerInstance.runAfterModelResponse(context.hooks, {\n content: parsed.content ?? \"\",\n input: state.currentInput,\n options,\n providerRequest,\n providerResponse: response,\n usage: currentUsage,\n });\n\n // Check for structured output (Anthropic magic tool pattern)\n if (this.adapter.hasStructuredOutput(response)) {\n const structuredOutput = this.adapter.extractStructuredOutput(response);\n if (structuredOutput) {\n state.responseBuilder.setContent(\n this.applyFormatArrayDefaults(structuredOutput, options),\n );\n state.responseBuilder.complete();\n return false; // Stop loop\n }\n }\n\n // Handle tool calls\n if (parsed.hasToolCalls) {\n if (toolCalls.length > 0 && state.toolkit && state.maxTurns > 1) {\n // Track updated provider request for tool results\n let currentProviderRequest = providerRequest;\n\n // Add all response output items to the request BEFORE processing tool calls\n // This is critical for OpenAI which requires reasoning items to be present\n // when function_call items reference them\n const responseItems = this.adapter.responseToHistoryItems(response);\n this.appendResponseItemsToRequest(\n currentProviderRequest,\n responseItems,\n );\n\n // Process each tool call\n for (const toolCall of toolCalls) {\n state.toolCallNames.push(toolCall.name);\n // Resolved once per call; never throws (undefined when tool has no message)\n const toolMessage = await state.toolkit!.resolveMessage({\n arguments: toolCall.arguments,\n name: toolCall.name,\n });\n try {\n await emitProgress({\n event: {\n tool: {\n arguments: toolCall.arguments,\n message: toolMessage,\n name: toolCall.name,\n },\n turn: state.currentTurn,\n type: LlmProgressEventType.ToolCall,\n },\n onProgress: options.onProgress,\n });\n\n // Execute beforeEachTool hook\n await this.hookRunnerInstance.runBeforeTool(context.hooks, {\n args: toolCall.arguments,\n message: toolMessage,\n toolName: toolCall.name,\n });\n\n // Call the tool inside a child tool span (no-op when disabled)\n log.trace(`[operate] Calling tool - ${toolCall.name}`);\n const result = await withLlmObsSpan(\n { kind: \"tool\", name: toolCall.name },\n async () => {\n const result = await state.toolkit!.call({\n arguments: toolCall.arguments,\n message: toolMessage,\n name: toolCall.name,\n });\n annotateLlmObs({\n inputData: toolCall.arguments,\n metadata: { tool: toolCall.name },\n outputData: result,\n });\n return result;\n },\n );\n\n await emitProgress({\n event: {\n tool: { name: toolCall.name },\n turn: state.currentTurn,\n type: LlmProgressEventType.ToolResult,\n },\n onProgress: options.onProgress,\n });\n\n // Execute afterEachTool hook\n await this.hookRunnerInstance.runAfterTool(context.hooks, {\n args: toolCall.arguments,\n message: toolMessage,\n result,\n toolName: toolCall.name,\n });\n\n // Format result and append to request\n const formattedResult = {\n callId: toolCall.callId,\n output: JSON.stringify(result),\n success: true,\n };\n\n // Reset consecutive error counter on success\n state.consecutiveToolErrors = 0;\n\n // Update provider request with tool result\n currentProviderRequest = this.adapter.appendToolResult(\n currentProviderRequest,\n toolCall,\n formattedResult,\n );\n\n // Sync state from updated request\n this.syncInputFromRequest(state, currentProviderRequest);\n\n // Add tool result to history\n const toolResultFormatted = this.adapter.formatToolResult(\n toolCall,\n formattedResult,\n );\n state.responseBuilder.appendToHistory(\n toolResultFormatted as LlmInputMessage,\n );\n } catch (error) {\n await emitProgress({\n event: {\n error: (error as Error).message,\n tool: { name: toolCall.name },\n turn: state.currentTurn,\n type: LlmProgressEventType.ToolError,\n },\n onProgress: options.onProgress,\n });\n\n // Execute onToolError hook\n await this.hookRunnerInstance.runOnToolError(context.hooks, {\n args: toolCall.arguments,\n error: error as Error,\n message: toolMessage,\n toolName: toolCall.name,\n });\n\n // Set error on response\n const jaypieError = new BadGatewayError();\n const detail = [\n `Error executing function call ${toolCall.name}.`,\n (error as Error).message,\n ].join(\"\\n\");\n state.responseBuilder.setError({\n detail,\n status: jaypieError.status,\n title: ERROR.BAD_FUNCTION_CALL,\n });\n\n // Add error tool_result to history so the tool_use block is not orphaned.\n // Without this, the next turn's request would have a tool_use without a\n // matching tool_result, causing Anthropic API to reject with 400.\n const errorResult: StandardToolResult = {\n callId: toolCall.callId,\n output: JSON.stringify({\n error: (error as Error).message || \"Tool execution failed\",\n }),\n success: false,\n error: (error as Error).message,\n };\n const toolResultFormatted = this.adapter.formatToolResult(\n toolCall,\n errorResult,\n );\n state.responseBuilder.appendToHistory(\n toolResultFormatted as LlmInputMessage,\n );\n\n log.warn(`Error executing function call ${toolCall.name}`);\n log.var({ error });\n\n // Track consecutive errors and stop if threshold reached\n state.consecutiveToolErrors++;\n if (state.consecutiveToolErrors >= MAX_CONSECUTIVE_TOOL_ERRORS) {\n const detail = `Stopped after ${MAX_CONSECUTIVE_TOOL_ERRORS} consecutive tool errors`;\n log.warn(detail);\n state.responseBuilder.setError({\n detail,\n status: 502,\n title: ERROR.BAD_FUNCTION_CALL,\n });\n state.responseBuilder.incomplete();\n return false; // Stop loop\n }\n }\n }\n\n // Check if we've reached max turns\n if (state.currentTurn >= state.maxTurns) {\n const error = new TooManyRequestsError();\n const detail = `Model requested function call but exceeded ${state.maxTurns} turns`;\n log.warn(detail);\n state.responseBuilder.setError({\n detail,\n status: error.status,\n title: error.title,\n });\n state.responseBuilder.incomplete();\n return false; // Stop loop\n }\n\n return true; // Continue to next turn\n }\n }\n\n // Format contract enforcement: the loop is about to complete but the\n // model answered with prose instead of structured output.\n if (state.formattedFormat && typeof parsed.content === \"string\") {\n // First salvage attempt: the text may be the JSON itself (with or\n // without a code fence).\n const salvaged = tryParseJsonObject(parsed.content);\n if (salvaged) {\n state.responseBuilder.setContent(\n this.applyFormatArrayDefaults(salvaged, options),\n );\n state.responseBuilder.complete();\n for (const item of this.adapter.responseToHistoryItems(parsed.raw)) {\n state.responseBuilder.appendToHistory(item);\n }\n return false; // Stop loop\n }\n\n // Corrective turn: for adapters whose structured output rides a tool\n // emulation, take another turn offering only the structured_output tool\n // and demand it be called. Bounded by maxTurns.\n if (\n this.adapter.supportsStructuredOutputRetry &&\n state.currentTurn < state.maxTurns\n ) {\n log.warn(\n `[operate] Model returned text despite format on turn ${state.currentTurn}; retrying with structured_output tool only`,\n );\n for (const item of this.adapter.responseToHistoryItems(parsed.raw)) {\n state.currentInput.push(item);\n state.responseBuilder.appendToHistory(item);\n }\n const corrective: LlmInputMessage = {\n content:\n \"You must provide your final answer by calling the structured_output tool \" +\n \"with arguments matching the required schema. Do not respond with text.\",\n role: LlmMessageRole.User,\n type: LlmMessageType.Message,\n };\n state.currentInput.push(corrective);\n state.responseBuilder.appendToHistory(corrective);\n state.structuredOutputRetry = true;\n return true; // Continue to corrective turn\n }\n }\n\n // No tool calls or no toolkit - we're done\n state.responseBuilder.setContent(\n this.applyFormatArrayDefaults(parsed.content, options),\n );\n state.responseBuilder.complete();\n\n // Add final history items\n const historyItems = this.adapter.responseToHistoryItems(parsed.raw);\n for (const item of historyItems) {\n state.responseBuilder.appendToHistory(item);\n }\n\n return false; // Stop loop\n }\n\n /**\n * Draconian summary of a history item for trace logging: string message\n * content is kept; everything else is reduced to its type.\n */\n private summarizeHistoryItem(item?: LlmHistoryItem): unknown {\n if (!item) {\n return undefined;\n }\n const record = item as unknown as Record<string, unknown>;\n if (typeof record.content === \"string\") {\n return { content: record.content, role: record.role };\n }\n return { type: record.type ?? \"message\" };\n }\n\n /**\n * Reconcile structured output against the declared `format` contract. A\n * declared `format` is a schema contract: returned keys should match the\n * declared names exactly and every declared array field should be present.\n * First repairs keys a provider/model corrupted by wrapping them in literal\n * double quotes (observed on OpenAI for multi-word keys), then backfills any\n * declared array field a provider/model omitted, surfacing it as `[]`.\n */\n private applyFormatArrayDefaults(\n content: string | JsonObject | undefined,\n options: LlmOperateOptions,\n ): string | JsonObject | undefined {\n if (!options.format) {\n return content;\n }\n if (typeof content !== \"object\" || content === null) {\n return content;\n }\n const repaired = repairFormatKeys({ content, format: options.format });\n return fillFormatArrays({ content: repaired, format: options.format });\n }\n\n /**\n * Sync the current input state from the updated provider request.\n * This is necessary because appendToolResult modifies the provider-specific request,\n * and we need to keep our state in sync.\n */\n private syncInputFromRequest(\n state: OperateLoopState,\n updatedRequest: unknown,\n ): void {\n // Extract input/messages from the updated request\n // This is provider-specific but follows common patterns\n const request = updatedRequest as Record<string, unknown>;\n\n if (Array.isArray(request.input)) {\n // OpenAI format\n state.currentInput = request.input as LlmHistory;\n } else if (Array.isArray(request.messages)) {\n // Anthropic format\n state.currentInput = request.messages as LlmHistory;\n } else if (Array.isArray(request.contents)) {\n // Gemini format - convert contents to history items\n state.currentInput = this.convertGeminiContentsToHistory(\n request.contents as Array<{\n role: string;\n parts?: Array<Record<string, unknown>>;\n }>,\n );\n }\n }\n\n /**\n * Convert Gemini contents format to internal history format.\n */\n private convertGeminiContentsToHistory(\n contents: Array<{ role: string; parts?: Array<Record<string, unknown>> }>,\n ): LlmHistory {\n const history: LlmHistory = [];\n\n for (const content of contents) {\n if (!content.parts) continue;\n\n for (const part of content.parts) {\n if (part.text && typeof part.text === \"string\") {\n // Regular text message\n history.push({\n role:\n content.role === \"model\"\n ? LlmMessageRole.Assistant\n : LlmMessageRole.User,\n content: part.text,\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n } else if (part.functionCall) {\n // Function call\n const fc = part.functionCall as {\n name?: string;\n args?: Record<string, unknown>;\n id?: string;\n };\n // Preserve thoughtSignature for Gemini 3 models (required for tool calls)\n const thoughtSignature = (part as { thoughtSignature?: string })\n .thoughtSignature;\n history.push({\n type: LlmMessageType.FunctionCall,\n name: fc.name || \"\",\n arguments: JSON.stringify(fc.args || {}),\n call_id: fc.id || \"\",\n id: fc.id || \"\",\n ...(thoughtSignature && { thoughtSignature }),\n } as unknown as LlmToolCall);\n } else if (part.functionResponse) {\n // Function response\n const fr = part.functionResponse as {\n name?: string;\n response?: Record<string, unknown>;\n };\n // Store name in the object even though it's not part of LlmToolResult type\n // This allows round-trip conversion back to Gemini format\n history.push({\n type: LlmMessageType.FunctionCallOutput,\n output: JSON.stringify(fr.response || {}),\n call_id: \"\",\n name: fr.name || \"\",\n } as LlmToolResult & { name: string });\n }\n }\n }\n\n return history;\n }\n\n /**\n * Append response items to the provider request.\n * This adds all output items from a response (including reasoning, function_calls, etc.)\n * to the request's input/messages array.\n *\n * This is critical for OpenAI which requires reasoning items to be present\n * when function_call items reference them.\n */\n private appendResponseItemsToRequest(\n request: unknown,\n responseItems: LlmHistory,\n ): void {\n const requestObj = request as Record<string, unknown>;\n\n if (Array.isArray(requestObj.input)) {\n // OpenAI format\n requestObj.input.push(...responseItems);\n } else if (Array.isArray(requestObj.messages)) {\n // Anthropic format\n requestObj.messages.push(...responseItems);\n }\n }\n}\n\n//\n//\n// Factory\n//\n\n/**\n * Create an OperateLoop instance with the specified configuration.\n */\nexport function createOperateLoop(config: OperateLoopConfig): OperateLoop {\n return new OperateLoop(config);\n}\n","import { BadGatewayError, TooManyRequestsError } from \"@jaypie/errors\";\nimport { sleep } from \"@jaypie/kit\";\nimport { JsonObject } from \"@jaypie/types\";\n\nimport { MAX_CONSECUTIVE_TOOL_ERRORS } from \"./OperateLoop.js\";\nimport { toLlmError } from \"../errors/toLlmError.js\";\nimport { createStaleRejectionGuard } from \"./retry/createStaleRejectionGuard.js\";\nimport { Toolkit } from \"../tools/Toolkit.class.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateInput,\n LlmOperateOptions,\n LlmOutputMessage,\n LlmToolCall,\n LlmToolResult,\n LlmUsageItem,\n} from \"../types/LlmProvider.interface.js\";\nimport {\n LlmStreamChunk,\n LlmStreamChunkType,\n} from \"../types/LlmStreamChunk.interface.js\";\nimport {\n annotateLlmObs,\n openLlmObsSpan,\n usageToLlmObsMetrics,\n withLlmObsSpan,\n} from \"../observability/llmobs.js\";\nimport { getLogger, maxTurnsFromOptions, tallyOperate } from \"../util/index.js\";\nimport { ProviderAdapter } from \"./adapters/ProviderAdapter.interface.js\";\nimport { HookRunner, hookRunner } from \"./hooks/index.js\";\nimport { InputProcessor, inputProcessor } from \"./input/index.js\";\nimport { defaultRetryPolicy, RetryPolicy } from \"./retry/index.js\";\nimport {\n OperateContext,\n OperateRequest,\n ProviderToolDefinition,\n StandardToolCall,\n} from \"./types.js\";\n\n//\n//\n// Types\n//\n\nexport interface StreamLoopConfig {\n adapter: ProviderAdapter;\n client: unknown;\n hookRunner?: HookRunner;\n inputProcessor?: InputProcessor;\n retryPolicy?: RetryPolicy;\n}\n\ninterface StreamLoopState {\n consecutiveToolErrors: number;\n currentInput: LlmHistory;\n currentTurn: number;\n formattedFormat?: JsonObject;\n formattedTools?: ProviderToolDefinition[];\n maxTurns: number;\n toolCallNames: string[];\n toolkit?: Toolkit;\n usageItems: LlmUsageItem[];\n}\n\n//\n//\n// Constants\n//\n\nconst ERROR = {\n BAD_FUNCTION_CALL: \"Bad Function Call\",\n};\n\n//\n//\n// Main\n//\n\n/**\n * StreamLoop implements streaming multi-turn conversation loop.\n * It orchestrates provider adapters and tool calling while yielding\n * stream chunks as they become available.\n */\nexport class StreamLoop {\n private readonly adapter: ProviderAdapter;\n private readonly client: unknown;\n private readonly hookRunnerInstance: HookRunner;\n private readonly inputProcessorInstance: InputProcessor;\n private readonly retryPolicy: RetryPolicy;\n\n constructor(config: StreamLoopConfig) {\n this.adapter = config.adapter;\n this.client = config.client;\n this.hookRunnerInstance = config.hookRunner ?? hookRunner;\n this.inputProcessorInstance = config.inputProcessor ?? inputProcessor;\n this.retryPolicy = config.retryPolicy ?? defaultRetryPolicy;\n }\n\n /**\n * Execute the streaming loop for multi-turn conversations with tool calling.\n * Yields stream chunks as they become available.\n */\n async *execute(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const log = getLogger();\n // Verify adapter supports streaming\n if (!this.adapter.executeStreamRequest) {\n throw new BadGatewayError(\n `Provider ${this.adapter.name} does not support streaming`,\n );\n }\n\n // Initialize state\n const state = await this.initializeState(input, options);\n const context = this.createContext(options);\n\n // Build initial request\n let request = this.buildInitialRequest(state, options);\n\n // Multi-turn loop\n while (state.currentTurn < state.maxTurns) {\n state.currentTurn++;\n\n // Execute one streaming turn\n const { shouldContinue, toolCalls } = yield* this.executeOneStreamingTurn(\n request,\n state,\n context,\n options,\n );\n\n if (!shouldContinue) {\n break;\n }\n\n // If we have tool calls, process them\n if (toolCalls && toolCalls.length > 0 && state.toolkit) {\n yield* this.processToolCalls(toolCalls, state, context);\n\n // Check if we've reached max turns\n if (state.currentTurn >= state.maxTurns) {\n const error = new TooManyRequestsError();\n const detail = `Model requested function call but exceeded ${state.maxTurns} turns`;\n log.warn(detail);\n yield {\n type: LlmStreamChunkType.Error,\n error: {\n detail,\n status: error.status,\n title: error.title,\n },\n };\n break;\n }\n\n // Rebuild request with updated history for next turn\n request = {\n effort: options.effort,\n format: state.formattedFormat,\n instructions: options.instructions,\n messages: state.currentInput,\n model: options.model ?? this.adapter.defaultModel,\n providerOptions: options.providerOptions,\n stream: true,\n system: options.system,\n temperature: options.temperature,\n tools: state.formattedTools,\n user: options.user,\n };\n } else {\n break;\n }\n }\n\n // Emit final done chunk with accumulated usage\n tallyOperate({\n toolCallNames: state.toolCallNames,\n turns: state.currentTurn,\n usage: state.usageItems,\n });\n yield {\n type: LlmStreamChunkType.Done,\n usage: state.usageItems,\n };\n }\n\n //\n // Private Methods\n //\n\n private async initializeState(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions,\n ): Promise<StreamLoopState> {\n // Process input with placeholders\n const processedInput = await this.inputProcessorInstance.process(\n input,\n options,\n );\n\n // Determine max turns\n const maxTurns = maxTurnsFromOptions(options);\n\n // Get toolkit\n let toolkit: Toolkit | undefined;\n if (options.tools) {\n if (options.tools instanceof Toolkit) {\n toolkit = options.tools;\n } else if (Array.isArray(options.tools) && options.tools.length > 0) {\n const explain = options.explain ?? false;\n toolkit = new Toolkit(options.tools, { explain });\n }\n }\n\n // Format output schema through adapter if provided\n let formattedFormat: JsonObject | undefined;\n if (options.format) {\n formattedFormat = this.adapter.formatOutputSchema(\n options.format,\n ) as JsonObject;\n }\n\n // Format tools through adapter\n const formattedTools = toolkit\n ? this.adapter.formatTools(toolkit, formattedFormat)\n : undefined;\n\n return {\n consecutiveToolErrors: 0,\n currentInput: processedInput.history,\n currentTurn: 0,\n formattedFormat,\n formattedTools,\n maxTurns,\n toolCallNames: [],\n toolkit,\n usageItems: [],\n };\n }\n\n private createContext(options: LlmOperateOptions): OperateContext {\n return {\n hooks: options.hooks ?? {},\n options,\n };\n }\n\n private buildInitialRequest(\n state: StreamLoopState,\n options: LlmOperateOptions,\n ): OperateRequest {\n return {\n cache: options.cache,\n effort: options.effort,\n format: state.formattedFormat,\n instructions: options.instructions,\n messages: state.currentInput,\n model: options.model ?? this.adapter.defaultModel,\n providerOptions: options.providerOptions,\n stream: true,\n system: options.system,\n temperature: options.temperature,\n tools: state.formattedTools,\n user: options.user,\n };\n }\n\n private async *executeOneStreamingTurn(\n request: OperateRequest,\n state: StreamLoopState,\n context: OperateContext,\n options: LlmOperateOptions,\n ): AsyncGenerator<\n LlmStreamChunk,\n { shouldContinue: boolean; toolCalls?: StandardToolCall[] }\n > {\n const log = getLogger();\n // Build provider-specific request\n const providerRequest = this.adapter.buildRequest(request);\n\n // Execute beforeEachModelRequest hook\n await this.hookRunnerInstance.runBeforeModelRequest(context.hooks, {\n input: state.currentInput,\n options,\n providerRequest,\n });\n\n // Open a manual llm span held open across the streamed turn. Flat (not\n // nested) because it spans yield boundaries; no-op when llmobs disabled.\n const llmSpan = openLlmObsSpan({\n kind: \"llm\",\n modelName: options.model ?? this.adapter.defaultModel,\n modelProvider: this.adapter.name,\n name: \"jaypie.llm.model\",\n });\n const inputSnapshot = [...state.currentInput];\n let streamedText = \"\";\n\n // Collect tool calls from the stream\n const collectedToolCalls: StandardToolCall[] = [];\n\n // Retry loop for connection-level failures\n let attempt = 0;\n let chunksYielded = false;\n\n // Guard against stale rejections firing after the stream loop has already\n // caught the originating error: undici socket teardown and twin\n // upstream-SDK rejections (issue #336).\n const guard = createStaleRejectionGuard();\n\n try {\n while (true) {\n const controller = new AbortController();\n\n try {\n // Execute streaming request\n const streamGenerator = this.adapter.executeStreamRequest!(\n this.client,\n providerRequest,\n controller.signal,\n );\n\n for await (const chunk of streamGenerator) {\n // Pass through text chunks\n if (chunk.type === LlmStreamChunkType.Text) {\n chunksYielded = true;\n streamedText += chunk.content ?? \"\";\n yield chunk;\n }\n\n // Collect tool calls\n if (chunk.type === LlmStreamChunkType.ToolCall) {\n chunksYielded = true;\n collectedToolCalls.push({\n callId: chunk.toolCall.id,\n name: chunk.toolCall.name,\n arguments: chunk.toolCall.arguments,\n raw: chunk.toolCall,\n });\n yield chunk;\n }\n\n // Track usage from done chunk (but don't yield it yet - we'll emit our own)\n if (chunk.type === LlmStreamChunkType.Done && chunk.usage) {\n state.usageItems.push(...chunk.usage);\n }\n\n // Pass through error chunks\n if (chunk.type === LlmStreamChunkType.Error) {\n chunksYielded = true;\n yield chunk;\n }\n }\n\n // Stream completed successfully\n if (attempt > 0) {\n log.debug(`Stream request succeeded after ${attempt} retries`);\n }\n break;\n } catch (error: unknown) {\n controller.abort(\"retry\");\n\n guard.recordCaught(error);\n guard.install();\n\n // If chunks were already yielded, we can't transparently retry\n if (chunksYielded) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n log.error(\"Stream failed after partial data was delivered\");\n log.var({ error });\n yield {\n type: LlmStreamChunkType.Error,\n error: {\n detail: errorMessage,\n status: 502,\n title: \"Stream Error\",\n },\n };\n llmSpan?.annotate({\n inputData: inputSnapshot,\n metrics: usageToLlmObsMetrics(state.usageItems),\n outputData: streamedText,\n });\n llmSpan?.finish();\n return { shouldContinue: false };\n }\n\n // Check if we've exhausted retries or error is not retryable\n if (\n !this.retryPolicy.shouldRetry(attempt) ||\n !this.adapter.isRetryableError(error)\n ) {\n log.error(\n `Stream request failed after ${this.retryPolicy.maxRetries} retries`,\n );\n log.var({ error });\n llmSpan?.finish();\n throw toLlmError(this.adapter.classifyError(error), {\n model: options.model ?? this.adapter.defaultModel,\n provider: this.adapter.name,\n });\n }\n\n const delay = this.retryPolicy.getDelayForAttempt(attempt);\n log.warn(`Stream request failed. Retrying in ${delay}ms...`);\n log.var({ error });\n\n await sleep(delay);\n attempt++;\n }\n }\n } finally {\n guard.remove();\n }\n\n // Annotate and finish the streamed llm span (no-op when disabled)\n llmSpan?.annotate({\n inputData: inputSnapshot,\n metrics: usageToLlmObsMetrics(state.usageItems),\n outputData: streamedText,\n });\n llmSpan?.finish();\n\n // Execute afterEachModelResponse hook\n await this.hookRunnerInstance.runAfterModelResponse(context.hooks, {\n content: \"\",\n input: state.currentInput,\n options,\n providerRequest,\n providerResponse: null,\n usage: state.usageItems,\n });\n\n // If we have tool calls and a toolkit, continue the loop\n if (collectedToolCalls.length > 0 && state.toolkit && state.maxTurns > 1) {\n // Add tool calls to history\n for (const toolCall of collectedToolCalls) {\n // Extract provider-specific metadata from the stream chunk\n const metadata = (toolCall.raw as Record<string, unknown>)?.metadata as\n Record<string, unknown> | undefined;\n\n const historyItem: Record<string, unknown> = {\n type: LlmMessageType.FunctionCall,\n name: toolCall.name,\n arguments: toolCall.arguments,\n call_id: toolCall.callId,\n // Use provider item ID if available (e.g., OpenAI fc_... prefix),\n // otherwise fall back to callId\n id: (metadata?.itemId as string) || toolCall.callId,\n };\n\n // Preserve provider-specific fields (e.g., Gemini thoughtSignature)\n if (metadata?.thoughtSignature) {\n historyItem.thoughtSignature = metadata.thoughtSignature;\n }\n\n state.currentInput.push(historyItem as unknown as LlmToolCall);\n }\n\n return { shouldContinue: true, toolCalls: collectedToolCalls };\n }\n\n return { shouldContinue: false };\n }\n\n private async *processToolCalls(\n toolCalls: StandardToolCall[],\n state: StreamLoopState,\n context: OperateContext,\n ): AsyncGenerator<LlmStreamChunk, void> {\n const log = getLogger();\n for (const toolCall of toolCalls) {\n state.toolCallNames.push(toolCall.name);\n // Resolved once per call; never throws (undefined when tool has no message)\n const toolMessage = await state.toolkit!.resolveMessage({\n arguments: toolCall.arguments,\n name: toolCall.name,\n });\n try {\n // Execute beforeEachTool hook\n await this.hookRunnerInstance.runBeforeTool(context.hooks, {\n args: toolCall.arguments,\n message: toolMessage,\n toolName: toolCall.name,\n });\n\n // Call the tool inside a child tool span (no-op when disabled)\n log.trace(`[stream] Calling tool - ${toolCall.name}`);\n const result = await withLlmObsSpan(\n { kind: \"tool\", name: toolCall.name },\n async () => {\n const result = await state.toolkit!.call({\n arguments: toolCall.arguments,\n message: toolMessage,\n name: toolCall.name,\n });\n annotateLlmObs({\n inputData: toolCall.arguments,\n metadata: { tool: toolCall.name },\n outputData: result,\n });\n return result;\n },\n );\n\n // Execute afterEachTool hook\n await this.hookRunnerInstance.runAfterTool(context.hooks, {\n args: toolCall.arguments,\n message: toolMessage,\n result,\n toolName: toolCall.name,\n });\n\n // Reset consecutive error counter on success\n state.consecutiveToolErrors = 0;\n\n // Yield tool result chunk\n yield {\n type: LlmStreamChunkType.ToolResult,\n toolResult: {\n id: toolCall.callId,\n name: toolCall.name,\n result,\n },\n };\n\n // Add tool result to history\n state.currentInput.push({\n type: LlmMessageType.FunctionCallOutput,\n output: JSON.stringify(result),\n call_id: toolCall.callId,\n name: toolCall.name,\n } as LlmToolResult & { name: string });\n } catch (error) {\n // Execute onToolError hook\n await this.hookRunnerInstance.runOnToolError(context.hooks, {\n args: toolCall.arguments,\n error: error as Error,\n message: toolMessage,\n toolName: toolCall.name,\n });\n\n // Yield error chunk\n const jaypieError = new BadGatewayError();\n const detail = [\n `Error executing function call ${toolCall.name}.`,\n (error as Error).message,\n ].join(\"\\n\");\n\n yield {\n type: LlmStreamChunkType.Error,\n error: {\n detail,\n status: jaypieError.status,\n title: ERROR.BAD_FUNCTION_CALL,\n },\n };\n\n // Add error tool_result to history so the tool_use block is not orphaned.\n // Without this, the next turn's request would have a tool_use without a\n // matching tool_result, causing Anthropic API to reject with 400.\n const errorOutput = JSON.stringify({\n error: (error as Error).message || \"Tool execution failed\",\n });\n state.currentInput.push({\n type: LlmMessageType.FunctionCallOutput,\n output: errorOutput,\n call_id: toolCall.callId,\n name: toolCall.name,\n } as LlmToolResult & { name: string });\n\n log.warn(`Error executing function call ${toolCall.name}`);\n log.var({ error });\n\n // Track consecutive errors and stop if threshold reached\n state.consecutiveToolErrors++;\n if (state.consecutiveToolErrors >= MAX_CONSECUTIVE_TOOL_ERRORS) {\n const stopDetail = `Stopped after ${MAX_CONSECUTIVE_TOOL_ERRORS} consecutive tool errors`;\n log.warn(stopDetail);\n yield {\n type: LlmStreamChunkType.Error,\n error: {\n detail: stopDetail,\n status: 502,\n title: ERROR.BAD_FUNCTION_CALL,\n },\n };\n return; // Stop processing tools\n }\n }\n }\n }\n\n /**\n * Convert Gemini contents format to internal history format.\n */\n private convertGeminiContentsToHistory(\n contents: Array<{ role: string; parts?: Array<Record<string, unknown>> }>,\n ): LlmHistory {\n const history: LlmHistory = [];\n\n for (const content of contents) {\n if (!content.parts) continue;\n\n for (const part of content.parts) {\n if (part.text && typeof part.text === \"string\") {\n history.push({\n role:\n content.role === \"model\"\n ? LlmMessageRole.Assistant\n : LlmMessageRole.User,\n content: part.text,\n type: LlmMessageType.Message,\n } as LlmOutputMessage);\n } else if (part.functionCall) {\n const fc = part.functionCall as {\n name?: string;\n args?: Record<string, unknown>;\n id?: string;\n };\n history.push({\n type: LlmMessageType.FunctionCall,\n name: fc.name || \"\",\n arguments: JSON.stringify(fc.args || {}),\n call_id: fc.id || \"\",\n id: fc.id || \"\",\n } as unknown as LlmToolCall);\n } else if (part.functionResponse) {\n const fr = part.functionResponse as {\n name?: string;\n response?: Record<string, unknown>;\n };\n history.push({\n type: LlmMessageType.FunctionCallOutput,\n output: JSON.stringify(fr.response || {}),\n call_id: \"\",\n name: fr.name || \"\",\n } as LlmToolResult & { name: string });\n }\n }\n }\n\n return history;\n }\n}\n\n//\n//\n// Factory\n//\n\n/**\n * Create a StreamLoop instance with the specified configuration.\n */\nexport function createStreamLoop(config: StreamLoopConfig): StreamLoop {\n return new StreamLoop(config);\n}\n","import { parseSseStream } from \"../../util/sse.js\";\nimport { Anthropic } from \"./types.js\";\n\n//\n//\n// Constants\n//\n\nconst ANTHROPIC_BASE_URL = \"https://api.anthropic.com/v1\";\n\nconst ANTHROPIC_VERSION = \"2023-06-01\";\n\n//\n//\n// Errors\n//\n// The adapter's `classifyError` keys off `error.constructor.name` (the SDK's\n// class names), so the client throws errors whose class names match. Status →\n// class mapping mirrors the SDK.\n//\n\nexport class AnthropicApiError extends Error {\n readonly status: number;\n readonly error?: { message?: string };\n\n constructor(status: number, message: string, error?: { message?: string }) {\n super(message);\n this.name = this.constructor.name;\n this.status = status;\n this.error = error;\n }\n}\n\nexport class BadRequestError extends AnthropicApiError {}\nexport class AuthenticationError extends AnthropicApiError {}\nexport class PermissionDeniedError extends AnthropicApiError {}\nexport class NotFoundError extends AnthropicApiError {}\nexport class RateLimitError extends AnthropicApiError {}\nexport class InternalServerError extends AnthropicApiError {}\nexport class APIConnectionError extends AnthropicApiError {}\n\nfunction errorForStatus(\n status: number,\n message: string,\n error?: { message?: string },\n): AnthropicApiError {\n if (status === 400) return new BadRequestError(status, message, error);\n if (status === 401) return new AuthenticationError(status, message, error);\n if (status === 403) return new PermissionDeniedError(status, message, error);\n if (status === 404) return new NotFoundError(status, message, error);\n if (status === 429) return new RateLimitError(status, message, error);\n if (status >= 500) return new InternalServerError(status, message, error);\n return new AnthropicApiError(status, message, error);\n}\n\n//\n//\n// Types\n//\n\nexport interface AnthropicClientOptions {\n apiKey: string;\n baseURL?: string;\n}\n\nexport interface CreateOptions {\n signal?: AbortSignal;\n}\n\ninterface MessagesApi {\n create(\n params: Anthropic.MessageCreateParamsStreaming,\n options?: CreateOptions,\n ): Promise<AsyncIterable<Anthropic.MessageStreamEvent>>;\n create(\n params: Anthropic.MessageCreateParams,\n options?: CreateOptions,\n ): Promise<Anthropic.Message>;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Minimal `fetch`-based client for Anthropic's Messages API. Replaces\n * `@anthropic-ai/sdk` — the adapter only needs `messages.create` (streaming and\n * non-streaming), header auth, and HTTP errors whose class names drive\n * `classifyError`. Internal request params are already Anthropic's wire shape,\n * so they serialize verbatim. Exposes a `messages` facade mirroring the SDK so\n * the adapter call sites are unchanged.\n */\nexport class AnthropicClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n readonly messages: MessagesApi;\n\n constructor({\n apiKey,\n baseURL = ANTHROPIC_BASE_URL,\n }: AnthropicClientOptions) {\n this.apiKey = apiKey;\n this.baseURL = baseURL;\n this.messages = {\n create: ((\n params: Anthropic.MessageCreateParams,\n options?: CreateOptions,\n ) =>\n params.stream\n ? this.createStream(params, options)\n : this.createMessage(params, options)) as MessagesApi[\"create\"],\n };\n }\n\n private headers(): Record<string, string> {\n return {\n \"anthropic-version\": ANTHROPIC_VERSION,\n \"content-type\": \"application/json\",\n \"x-api-key\": this.apiKey,\n };\n }\n\n private async toError(response: Response): Promise<AnthropicApiError> {\n let message = `Anthropic request failed with status ${response.status}`;\n let error: { message?: string } | undefined;\n try {\n const body = (await response.json()) as { error?: { message?: string } };\n if (body?.error?.message) {\n message = body.error.message;\n error = body.error;\n }\n } catch {\n // Non-JSON error body; keep the status-based message.\n }\n return errorForStatus(response.status, message, error);\n }\n\n private async createMessage(\n params: Anthropic.MessageCreateParams,\n { signal }: CreateOptions = {},\n ): Promise<Anthropic.Message> {\n const response = await fetch(`${this.baseURL}/messages`, {\n method: \"POST\",\n headers: this.headers(),\n body: JSON.stringify(params),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n return (await response.json()) as Anthropic.Message;\n }\n\n private async createStream(\n params: Anthropic.MessageCreateParams,\n { signal }: CreateOptions = {},\n ): Promise<AsyncIterable<Anthropic.MessageStreamEvent>> {\n const response = await fetch(`${this.baseURL}/messages`, {\n method: \"POST\",\n headers: { ...this.headers(), accept: \"text/event-stream\" },\n body: JSON.stringify(params),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n if (!response.body) return (async function* () {})();\n\n return parseSseStream(\n response.body,\n ) as AsyncIterable<Anthropic.MessageStreamEvent>;\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog, log } from \"@jaypie/logger\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { naturalZodSchema } from \"../../util/index.js\";\nimport { z } from \"zod/v4\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { AnthropicClient } from \"./client.js\";\nimport type { Anthropic } from \"./types.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<AnthropicClient> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"ANTHROPIC_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the required API key: ANTHROPIC_API_KEY\",\n );\n }\n\n const client = new AnthropicClient({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized Anthropic client\");\n return client;\n}\n\n// Message formatting functions\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): string {\n return placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): Anthropic.MessageParam {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: PROVIDER.ANTHROPIC.ROLE.USER,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { data, placeholders }: LlmMessageOptions = {},\n): Anthropic.MessageParam[] {\n const logger = getLogger();\n const messages: Anthropic.MessageParam[] = [];\n\n // Add user message (necessary for all requests)\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content.length} characters`);\n\n return messages;\n}\n\n// Basic text completion\nexport async function createTextCompletion(\n client: AnthropicClient,\n messages: Anthropic.MessageParam[],\n model: string,\n systemMessage?: string,\n): Promise<string> {\n log.trace(\"Using text output (unstructured)\");\n\n const params: Anthropic.MessageCreateParams = {\n model,\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n };\n\n // Add system instruction if provided\n if (systemMessage) {\n params.system = systemMessage;\n log.trace(`System message: ${systemMessage.length} characters`);\n }\n\n const response = await client.messages.create(params);\n\n const firstContent = response.content[0];\n const text = firstContent && \"text\" in firstContent ? firstContent.text : \"\";\n\n log.trace(`Assistant reply: ${text.length} characters`);\n\n return text;\n}\n\n// Structured output completion using Anthropic's native `output_config.format`\n// field. Returns a JsonObject parsed and validated against the caller's\n// Zod schema.\nexport async function createStructuredCompletion(\n client: AnthropicClient,\n messages: Anthropic.MessageParam[],\n model: string,\n responseSchema: z.ZodType | NaturalSchema,\n systemMessage?: string,\n): Promise<JsonObject> {\n log.trace(\"Using native structured output\");\n\n const schema =\n responseSchema instanceof z.ZodType\n ? responseSchema\n : naturalZodSchema(responseSchema as NaturalSchema);\n\n // Type extension: SDK 0.71 doesn't type `output_config` on\n // `MessageCreateParams`. The GA endpoint accepts the field; the older\n // `output_format` field is now deprecated.\n type StructuredOutputParams = Anthropic.MessageCreateParams & {\n output_config?: {\n format: {\n type: \"json_schema\";\n schema: JsonObject;\n };\n };\n };\n\n const jsonSchema = z.toJSONSchema(schema) as JsonObject;\n const params: StructuredOutputParams = {\n model,\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n output_config: {\n format: { type: \"json_schema\", schema: jsonSchema },\n },\n };\n if (systemMessage) {\n params.system = systemMessage;\n }\n\n const response = (await client.messages.create(\n params as Anthropic.MessageCreateParams,\n )) as Anthropic.Message;\n\n if (response.stop_reason === \"refusal\") {\n throw new Error(\n \"Anthropic refused the structured-output request (stop_reason=refusal)\",\n );\n }\n if (response.stop_reason === \"max_tokens\") {\n throw new Error(\n \"Anthropic structured-output response was truncated (stop_reason=max_tokens); increase max_tokens\",\n );\n }\n\n const textBlock = response.content.find(\n (block): block is Anthropic.TextBlock => block.type === \"text\",\n );\n if (!textBlock) {\n throw new Error(\"Failed to parse structured response from Anthropic\");\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(textBlock.text);\n } catch {\n throw new Error(\n \"Failed to parse structured response from Anthropic: \" + textBlock.text,\n );\n }\n\n const validation = schema.safeParse(parsed);\n if (!validation.success) {\n throw new Error(\n `JSON response from Anthropic does not match schema: ${textBlock.text}`,\n );\n }\n log.trace(\"Received structured response\", { result: validation.data });\n return validation.data as JsonObject;\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { LlmMessageRole } from \"../../types/LlmProvider.interface.js\";\nimport { PROVIDER } from \"../../constants.js\";\n\n// Maps Jaypie roles to Anthropic roles\nexport const ROLE_MAP: Record<LlmMessageRole, string> = {\n [LlmMessageRole.User]: PROVIDER.ANTHROPIC.ROLE.USER,\n [LlmMessageRole.System]: PROVIDER.ANTHROPIC.ROLE.SYSTEM,\n [LlmMessageRole.Assistant]: PROVIDER.ANTHROPIC.ROLE.ASSISTANT,\n [LlmMessageRole.Developer]: PROVIDER.ANTHROPIC.ROLE.SYSTEM,\n};\n\n//\n//\n// Anthropic API types\n//\n// Local mirror of the subset of `@anthropic-ai/sdk`'s `Anthropic` namespace the\n// adapter and utils use. Defining it here lets us drop the SDK dependency while\n// keeping every `Anthropic.X` reference unchanged. The internal request shapes\n// are already Anthropic's snake_case wire format, so the HTTP client serializes\n// them verbatim.\n//\n\n/* eslint-disable @typescript-eslint/no-namespace */\nexport namespace Anthropic {\n export interface CacheControlEphemeral {\n type: \"ephemeral\";\n ttl?: \"5m\" | \"1h\";\n }\n\n export interface TextBlock {\n type: \"text\";\n text: string;\n }\n\n /** Top-level `system` block form that can carry a cache breakpoint */\n export interface SystemTextBlockParam {\n type: \"text\";\n text: string;\n cache_control?: CacheControlEphemeral;\n }\n\n export interface ToolUseBlock {\n type: \"tool_use\";\n id: string;\n name: string;\n input: unknown;\n }\n\n export interface ThinkingBlock {\n type: \"thinking\";\n thinking: string;\n signature?: string;\n }\n\n export type ContentBlock = TextBlock | ToolUseBlock | ThinkingBlock;\n\n export interface Base64ImageSource {\n type: \"base64\";\n media_type: string;\n data: string;\n }\n\n export interface Base64PDFSource {\n type: \"base64\";\n media_type: string;\n data: string;\n }\n\n export interface ToolResultBlockParam {\n type: \"tool_result\";\n tool_use_id: string;\n content: string;\n }\n\n export type ContentBlockParam =\n | { type: \"text\"; text: string }\n | {\n type: \"image\";\n source: Base64ImageSource | { type: \"url\"; url: string };\n }\n | {\n type: \"document\";\n source: Base64PDFSource | { type: \"url\"; url: string };\n }\n | ToolUseBlock\n | ToolResultBlockParam;\n\n export interface MessageParam {\n role: \"user\" | \"assistant\";\n content: string | ContentBlockParam[];\n }\n\n export namespace Messages {\n export namespace Tool {\n export type InputSchema = JsonObject;\n }\n }\n\n export interface Tool {\n name: string;\n description?: string;\n input_schema: Messages.Tool.InputSchema;\n type?: \"custom\";\n cache_control?: CacheControlEphemeral;\n }\n\n export interface Usage {\n input_tokens: number;\n output_tokens: number;\n thinking_tokens?: number;\n cache_read_input_tokens?: number;\n cache_creation_input_tokens?: number;\n }\n\n export interface MessageCreateParams {\n model: string;\n messages: MessageParam[];\n max_tokens: number;\n system?: string | SystemTextBlockParam[];\n tools?: Tool[];\n tool_choice?: { type: \"auto\" | \"any\" | \"tool\"; name?: string };\n temperature?: number;\n stream?: boolean;\n // Allow `output_config` and arbitrary providerOptions passthrough.\n [key: string]: unknown;\n }\n\n export type MessageCreateParamsStreaming = MessageCreateParams & {\n stream: true;\n };\n\n export interface Message {\n id: string;\n type: \"message\";\n role: \"assistant\";\n model: string;\n content: ContentBlock[];\n stop_reason: string | null;\n stop_sequence?: string | null;\n usage: Usage;\n }\n\n export type ContentBlockDelta =\n | { type: \"text_delta\"; text: string }\n | { type: \"input_json_delta\"; partial_json: string };\n\n export type MessageStreamEvent =\n | { type: \"message_start\"; message: Message }\n | {\n type: \"content_block_start\";\n index: number;\n content_block: ContentBlock;\n }\n | { type: \"content_block_delta\"; index: number; delta: ContentBlockDelta }\n | { type: \"content_block_stop\"; index: number }\n | { type: \"message_delta\"; delta: Record<string, unknown>; usage: Usage }\n | { type: \"message_stop\" }\n | { type: \"ping\" };\n}\n/* eslint-enable @typescript-eslint/no-namespace */\n","import type { AnthropicClient } from \"./client.js\";\nimport { JsonObject } from \"@jaypie/types\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n anthropicAdapter,\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n createStructuredCompletion,\n createTextCompletion,\n formatSystemMessage,\n getLogger,\n initializeClient,\n prepareMessages,\n} from \"./index.js\";\n\n// Main class implementation\nexport class AnthropicProvider implements LlmProvider {\n private model: string;\n private _client?: AnthropicClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.ANTHROPIC.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<AnthropicClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: anthropicAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: anthropicAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n // Main send method\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options || {});\n const modelToUse = options?.model || this.model;\n\n // Process system message if provided\n let systemMessage: string | undefined;\n if (options?.system) {\n systemMessage = formatSystemMessage(options.system, {\n data: options.data,\n placeholders: options.placeholders,\n });\n }\n\n if (options?.response) {\n return createStructuredCompletion(\n client,\n messages,\n modelToUse,\n options.response,\n systemMessage,\n );\n }\n\n return createTextCompletion(client, messages, modelToUse, systemMessage);\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { JAYPIE } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport type { BedrockRuntimeClient } from \"@aws-sdk/client-bedrock-runtime\";\n\nlet cachedSdk: typeof import(\"@aws-sdk/client-bedrock-runtime\") | null = null;\n\nexport async function loadSdk(): Promise<\n typeof import(\"@aws-sdk/client-bedrock-runtime\")\n> {\n if (cachedSdk) return cachedSdk;\n try {\n cachedSdk = await import(\"@aws-sdk/client-bedrock-runtime\");\n return cachedSdk;\n } catch {\n throw new ConfigurationError(\n \"@aws-sdk/client-bedrock-runtime is required but not installed. Run: npm install @aws-sdk/client-bedrock-runtime\",\n );\n }\n}\n\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\nexport async function initializeClient({\n region,\n}: { region?: string } = {}): Promise<BedrockRuntimeClient> {\n const logger = getLogger();\n const resolvedRegion = region || process.env.AWS_REGION || \"us-east-1\";\n\n const sdk = await loadSdk();\n const client = new sdk.BedrockRuntimeClient({ region: resolvedRegion });\n logger.trace(\"Initialized Bedrock client\");\n return client;\n}\n","import type { BedrockRuntimeClient } from \"@aws-sdk/client-bedrock-runtime\";\nimport { JsonObject } from \"@jaypie/types\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n bedrockAdapter,\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmHistoryItem,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport { getLogger, initializeClient } from \"./utils.js\";\n\nexport class BedrockProvider implements LlmProvider {\n private model: string;\n private region?: string;\n private _client?: BedrockRuntimeClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.BEDROCK.DEFAULT,\n { region }: { region?: string } = {},\n ) {\n this.model = model;\n this.region = region;\n }\n\n private async getClient(): Promise<BedrockRuntimeClient> {\n if (this._client) return this._client;\n this._client = await initializeClient({ region: this.region });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) return this._operateLoop;\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({ adapter: bedrockAdapter, client });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) return this._streamLoop;\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({ adapter: bedrockAdapter, client });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options?.model ?? this.model };\n const response = await operateLoop.execute(message, mergedOptions);\n return response.content ?? \"\";\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n const response = await operateLoop.execute(input, mergedOptions);\n\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { parseSseStream } from \"../../util/sse.js\";\n\n//\n//\n// Types\n//\n\nexport interface FireworksClientOptions {\n apiKey: string;\n baseURL?: string;\n}\n\nexport interface ChatCompletionOptions {\n signal?: AbortSignal;\n}\n\n/**\n * HTTP error carrying the upstream status and parsed API message. The\n * FireworksAdapter classifies errors by reading `.status` / `.statusCode` and\n * `.message` / `.error.message`.\n */\nexport class FireworksHttpError extends Error {\n readonly status: number;\n readonly statusCode: number;\n readonly error?: { message?: string };\n\n constructor(status: number, message: string, error?: { message?: string }) {\n super(message);\n this.name = \"FireworksHttpError\";\n this.status = status;\n this.statusCode = status;\n this.error = error;\n }\n}\n\n//\n//\n// Helpers\n//\n\n/**\n * Normalize the snake_case wire response into the camelCase shape the adapter\n * readers expect. Only protocol fields are touched — user content (schema\n * property names, tool argument JSON) is left untouched.\n */\nfunction normalizeResponse(json: JsonObject): JsonObject {\n const choices = json.choices as Array<Record<string, unknown>> | undefined;\n if (Array.isArray(choices)) {\n for (const choice of choices) {\n if (\n choice.finish_reason !== undefined &&\n choice.finishReason === undefined\n ) {\n choice.finishReason = choice.finish_reason;\n }\n const message = choice.message as Record<string, unknown> | undefined;\n if (\n message?.tool_calls !== undefined &&\n message.toolCalls === undefined\n ) {\n message.toolCalls = message.tool_calls;\n }\n }\n }\n\n const usage = json.usage as Record<string, unknown> | undefined;\n if (usage) {\n if (usage.promptTokens === undefined)\n usage.promptTokens = usage.prompt_tokens;\n if (usage.completionTokens === undefined) {\n usage.completionTokens = usage.completion_tokens;\n }\n if (usage.totalTokens === undefined) usage.totalTokens = usage.total_tokens;\n const details = usage.completion_tokens_details as\n { reasoning_tokens?: number } | undefined;\n if (\n details?.reasoning_tokens !== undefined &&\n !usage.completionTokensDetails\n ) {\n usage.completionTokensDetails = {\n reasoningTokens: details.reasoning_tokens,\n };\n }\n }\n\n return json;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Minimal `fetch`-based client for Fireworks AI's OpenAI-compatible Chat\n * Completions endpoint. The adapter only needs a single POST (streaming and\n * non-streaming), header auth, and HTTP error surfacing.\n */\nexport class FireworksClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n\n constructor({\n apiKey,\n baseURL = PROVIDER.FIREWORKS.BASE_URL,\n }: FireworksClientOptions) {\n this.apiKey = apiKey;\n this.baseURL = baseURL;\n }\n\n private headers(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n }\n\n private async toError(response: Response): Promise<FireworksHttpError> {\n let message = `Fireworks request failed with status ${response.status}`;\n let error: { message?: string } | undefined;\n try {\n const body = (await response.json()) as { error?: { message?: string } };\n if (body?.error?.message) {\n message = body.error.message;\n error = body.error;\n }\n } catch {\n // Non-JSON error body; keep the status-based message.\n }\n return new FireworksHttpError(response.status, message, error);\n }\n\n async chatCompletion(\n body: Record<string, unknown>,\n { signal }: ChatCompletionOptions = {},\n ): Promise<JsonObject> {\n const response = await fetch(`${this.baseURL}/chat/completions`, {\n method: \"POST\",\n headers: this.headers(),\n body: JSON.stringify(body),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n\n const json = (await response.json()) as JsonObject;\n return normalizeResponse(json);\n }\n\n async *streamChatCompletion(\n body: Record<string, unknown>,\n { signal }: ChatCompletionOptions = {},\n ): AsyncIterable<JsonObject> {\n const response = await fetch(`${this.baseURL}/chat/completions`, {\n method: \"POST\",\n headers: { ...this.headers(), Accept: \"text/event-stream\" },\n // OpenAI-style streams only include usage when explicitly requested.\n body: JSON.stringify({\n ...body,\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n if (!response.body) return;\n\n yield* parseSseStream(response.body);\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { FireworksClient } from \"./client.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<FireworksClient> {\n const logger = getLogger();\n const resolvedApiKey =\n apiKey || (await getEnvSecret(PROVIDER.FIREWORKS.API_KEY));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new FireworksClient({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized Fireworks client\");\n return client;\n}\n\n// Get default model from environment or constants\nexport function getDefaultModel(): string {\n return process.env.FIREWORKS_MODEL || PROVIDER.FIREWORKS.DEFAULT;\n}\n\n// Message formatting\nexport interface ChatMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n\n return {\n role: \"system\" as const,\n content,\n };\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: \"user\" as const,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { system, data, placeholders }: LlmMessageOptions = {},\n): ChatMessage[] {\n const logger = getLogger();\n const messages: ChatMessage[] = [];\n\n if (system) {\n const systemMessage = formatSystemMessage(system, { data, placeholders });\n messages.push(systemMessage);\n logger.trace(`System message: ${systemMessage.content?.length} characters`);\n }\n\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content?.length} characters`);\n\n return messages;\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport type { FireworksClient } from \"./client.js\";\nimport {\n createOperateLoop,\n createStreamLoop,\n fireworksAdapter,\n OperateLoop,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n getDefaultModel,\n getLogger,\n initializeClient,\n prepareMessages,\n} from \"./utils.js\";\n\nexport class FireworksProvider implements LlmProvider {\n private model: string;\n private _client?: FireworksClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = getDefaultModel(),\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<FireworksClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: fireworksAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: fireworksAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options);\n const modelToUse = options?.model || this.model;\n\n // OpenAI-compatible Chat Completions body; messages are already wire-shaped.\n const response = await client.chatCompletion({\n model: modelToUse,\n messages,\n });\n\n const choices = response.choices as\n Array<{ message?: { content?: unknown } }> | undefined;\n const rawContent = choices?.[0]?.message?.content;\n // Extract text content - content could be string or array of content items\n const content =\n typeof rawContent === \"string\"\n ? rawContent\n : Array.isArray(rawContent)\n ? rawContent\n .filter((item) => item.type === \"text\")\n .map((item) => (item as { text: string }).text)\n .join(\"\")\n : \"\";\n\n this.log.trace(`Assistant reply: ${content?.length || 0} characters`);\n\n // If structured output was requested, try to parse the response\n if (options?.response && content) {\n try {\n return JSON.parse(content);\n } catch {\n return content || \"\";\n }\n }\n\n return content || \"\";\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\n\nimport { parseSseStream } from \"../../util/sse.js\";\nimport {\n GeminiContent,\n GeminiGenerateContentConfig,\n GeminiRawResponse,\n} from \"./types.js\";\n\n//\n//\n// Constants\n//\n\nconst GOOGLE_BASE_URL = \"https://generativelanguage.googleapis.com/v1beta\";\n\n// Config keys the REST API expects at the top level of the request body. Every\n// other key in the SDK-style `config` object belongs under `generationConfig`.\nconst TOP_LEVEL_CONFIG_KEYS = new Set([\n \"systemInstruction\",\n \"tools\",\n \"toolConfig\",\n \"safetySettings\",\n \"cachedContent\",\n]);\n\n//\n//\n// Types\n//\n\nexport interface GoogleClientOptions {\n apiKey: string;\n baseURL?: string;\n}\n\nexport interface GenerateContentParams {\n model: string;\n contents: GeminiContent[];\n config?: GeminiGenerateContentConfig;\n}\n\nexport interface GenerateContentOptions {\n signal?: AbortSignal;\n}\n\n/**\n * HTTP error carrying the upstream status and parsed API message. The\n * GoogleAdapter classifies errors by reading `.status` / `.code` and\n * `.message`, so this shape keeps `classifyError` working unchanged after\n * dropping the SDK.\n */\nexport class GoogleHttpError extends Error {\n readonly status: number;\n readonly code: number;\n\n constructor(status: number, message: string) {\n super(message);\n this.name = \"GoogleHttpError\";\n this.status = status;\n this.code = status;\n }\n}\n\n//\n//\n// Helpers\n//\n\n/**\n * Translate the SDK-style `{ model, contents, config }` request into the REST\n * `generateContent` body. `systemInstruction` (a string) becomes a Content;\n * top-level config keys pass through; all remaining config keys (temperature,\n * responseMimeType, responseSchema, responseJsonSchema, ...) move under\n * `generationConfig`.\n */\nfunction toRestBody(params: GenerateContentParams): JsonObject {\n const body: JsonObject = {\n contents: params.contents as unknown as JsonObject[],\n };\n const config = params.config;\n if (!config) return body;\n\n const generationConfig: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(config)) {\n if (value === undefined) continue;\n if (key === \"systemInstruction\") {\n body.systemInstruction =\n typeof value === \"string\"\n ? { parts: [{ text: value }] }\n : (value as JsonObject);\n } else if (TOP_LEVEL_CONFIG_KEYS.has(key)) {\n body[key] = value as JsonObject;\n } else {\n generationConfig[key] = value;\n }\n }\n if (Object.keys(generationConfig).length > 0) {\n body.generationConfig = generationConfig as JsonObject;\n }\n return body;\n}\n\n/**\n * Concatenate the non-thought text parts of the first candidate, matching the\n * SDK's `response.text` convenience getter (consumed by `GoogleProvider.send`).\n */\nfunction responseText(response: GeminiRawResponse): string | undefined {\n const parts = response.candidates?.[0]?.content?.parts;\n if (!parts) return undefined;\n const text = parts\n .filter((part) => part.text && !part.thought)\n .map((part) => part.text)\n .join(\"\");\n return text.length > 0 ? text : undefined;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Minimal `fetch`-based client for Google's Generative Language (Gemini) REST\n * API. Replaces `@google/genai` — the adapter only needs `generateContent`\n * (streaming and non-streaming), an api-key header, and HTTP error surfacing.\n * Exposes a `models` facade mirroring the SDK so the adapter call sites are\n * unchanged.\n */\nexport class GoogleClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n readonly models: {\n generateContent: (\n params: GenerateContentParams,\n options?: GenerateContentOptions,\n ) => Promise<GeminiRawResponse>;\n generateContentStream: (\n params: GenerateContentParams,\n options?: GenerateContentOptions,\n ) => Promise<AsyncIterable<GeminiRawResponse>>;\n };\n\n constructor({ apiKey, baseURL = GOOGLE_BASE_URL }: GoogleClientOptions) {\n this.apiKey = apiKey;\n this.baseURL = baseURL;\n this.models = {\n generateContent: (params, options) =>\n this.generateContent(params, options),\n generateContentStream: (params, options) =>\n this.generateContentStream(params, options),\n };\n }\n\n private headers(): Record<string, string> {\n return {\n \"Content-Type\": \"application/json\",\n \"x-goog-api-key\": this.apiKey,\n };\n }\n\n private async toError(response: Response): Promise<GoogleHttpError> {\n let message = `Google request failed with status ${response.status}`;\n try {\n const body = (await response.json()) as { error?: { message?: string } };\n if (body?.error?.message) message = body.error.message;\n } catch {\n // Non-JSON error body; keep the status-based message.\n }\n return new GoogleHttpError(response.status, message);\n }\n\n private async generateContent(\n params: GenerateContentParams,\n { signal }: GenerateContentOptions = {},\n ): Promise<GeminiRawResponse> {\n const url = `${this.baseURL}/models/${params.model}:generateContent`;\n const response = await fetch(url, {\n method: \"POST\",\n headers: this.headers(),\n body: JSON.stringify(toRestBody(params)),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n\n const json = (await response.json()) as GeminiRawResponse;\n json.text = responseText(json);\n return json;\n }\n\n private async generateContentStream(\n params: GenerateContentParams,\n { signal }: GenerateContentOptions = {},\n ): Promise<AsyncIterable<GeminiRawResponse>> {\n const url = `${this.baseURL}/models/${params.model}:streamGenerateContent?alt=sse`;\n const response = await fetch(url, {\n method: \"POST\",\n headers: { ...this.headers(), Accept: \"text/event-stream\" },\n body: JSON.stringify(toRestBody(params)),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n if (!response.body) return (async function* () {})();\n\n return parseSseStream(response.body) as AsyncIterable<GeminiRawResponse>;\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { GoogleClient } from \"./client.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<GoogleClient> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"GEMINI_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new GoogleClient({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized Gemini client\");\n return client;\n}\n\n// Message formatting\nexport interface ChatMessage {\n role: \"user\" | \"model\";\n content: string;\n}\n\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): string {\n const content =\n placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n\n return content;\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: \"user\" as const,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { data, placeholders }: LlmMessageOptions = {},\n): { messages: ChatMessage[]; systemInstruction?: string } {\n const logger = getLogger();\n const messages: ChatMessage[] = [];\n\n // Note: Gemini handles system prompts differently via systemInstruction config\n // This function is kept for compatibility but system prompts should be passed\n // via the systemInstruction parameter in generateContent\n\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content?.length} characters`);\n\n return { messages, systemInstruction: undefined };\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport type { GoogleClient } from \"./client.js\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n googleAdapter,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport { getLogger, initializeClient, prepareMessages } from \"./utils.js\";\n\nexport class GoogleProvider implements LlmProvider {\n private model: string;\n private _client?: GoogleClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.GOOGLE.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<GoogleClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: googleAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: googleAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const { messages } = prepareMessages(message, options);\n const modelToUse = options?.model || this.model;\n\n // Build the request config\n const config: Record<string, unknown> = {};\n\n if (options?.system) {\n config.systemInstruction = options.system;\n }\n\n // Handle structured output via responseSchema\n if (options?.response) {\n config.responseMimeType = \"application/json\";\n // Convert the response schema to JSON schema format\n // Note: For simple send() calls, we'll use Gemini's native JSON response\n }\n\n const response = await client.models.generateContent({\n model: modelToUse,\n contents: messages.map((m) => ({\n role: m.role,\n parts: [{ text: m.content }],\n })),\n config: Object.keys(config).length > 0 ? config : undefined,\n });\n\n const text = response.text;\n this.log.trace(`Assistant reply: ${text?.length || 0} characters`);\n\n // If structured output was requested, try to parse the response\n if (options?.response && text) {\n try {\n return JSON.parse(text);\n } catch {\n // Strip markdown code fences and retry (Gemini sometimes wraps JSON in fences)\n const jsonMatch =\n text.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/) ||\n text.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n return JSON.parse(jsonMatch[1] || jsonMatch[0]);\n } catch {\n // Fall through to return original text\n }\n }\n return text || \"\";\n }\n }\n\n return text || \"\";\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { naturalZodSchema } from \"../../util\";\nimport { OpenAIClient } from \"./client.js\";\nimport { zodResponseFormat } from \"./responseFormat.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenAIClient> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"OPENAI_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new OpenAIClient({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized OpenAI client\");\n return client;\n}\n\n// Message formatting\nexport interface ChatMessage {\n role: \"user\" | \"developer\";\n content: string;\n}\n\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n\n return {\n role: \"developer\" as const,\n content,\n };\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: \"user\" as const,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { system, data, placeholders }: LlmMessageOptions = {},\n): ChatMessage[] {\n const logger = getLogger();\n const messages: ChatMessage[] = [];\n\n if (system) {\n const systemMessage = formatSystemMessage(system, { data, placeholders });\n messages.push(systemMessage);\n logger.trace(`System message: ${systemMessage.content?.length} characters`);\n }\n\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content?.length} characters`);\n\n return messages;\n}\n\n// Completion requests\nexport async function createStructuredCompletion(\n client: OpenAIClient,\n {\n messages,\n responseSchema,\n model,\n }: {\n messages: ChatMessage[];\n responseSchema: z.ZodType | NaturalSchema;\n model: string;\n },\n): Promise<JsonObject> {\n const logger = getLogger();\n logger.trace(\"Using structured output\");\n\n const zodSchema =\n responseSchema instanceof z.ZodType\n ? responseSchema\n : naturalZodSchema(responseSchema as NaturalSchema);\n\n const responseFormat = zodResponseFormat(zodSchema as any, \"response\");\n\n const jsonSchema = z.toJSONSchema(zodSchema);\n\n // Temporary hack because OpenAI requires additional_properties to be false on all objects\n const checks = [jsonSchema];\n while (checks.length > 0) {\n const current = checks[0];\n if (current.type == \"object\") {\n current.additionalProperties = false;\n }\n Object.keys(current).forEach((key) => {\n if (typeof current[key] == \"object\" && current[key] !== null) {\n checks.push(current[key] as any);\n }\n });\n checks.shift();\n }\n responseFormat.json_schema.schema = jsonSchema as JsonObject;\n\n const completion = (await client.chat.completions.parse({\n messages,\n model,\n response_format: responseFormat,\n })) as { choices: Array<{ message: { parsed: JsonObject } }> };\n\n logger.var({ assistantReply: completion.choices[0].message.parsed });\n return completion.choices[0].message.parsed;\n}\n\nexport async function createTextCompletion(\n client: OpenAIClient,\n {\n messages,\n model,\n }: {\n messages: ChatMessage[];\n model: string;\n },\n): Promise<string> {\n const logger = getLogger();\n logger.trace(\"Using text output (unstructured)\");\n\n const completion = (await client.chat.completions.create({\n messages,\n model,\n })) as { choices?: Array<{ message?: { content?: string } }> };\n\n logger.trace(\n `Assistant reply: ${completion.choices?.[0]?.message?.content?.length} characters`,\n );\n\n return completion.choices?.[0]?.message?.content || \"\";\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n openAiAdapter,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport { OpenAIClient } from \"./client.js\";\nimport {\n createStructuredCompletion,\n createTextCompletion,\n getLogger,\n initializeClient,\n prepareMessages,\n} from \"./utils.js\";\n\nexport class OpenAiProvider implements LlmProvider {\n private model: string;\n private _client?: OpenAIClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.OPENAI.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenAIClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: openAiAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: openAiAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options || {});\n const modelToUse = options?.model || this.model;\n\n if (options?.response) {\n return createStructuredCompletion(client, {\n messages,\n responseSchema: options.response,\n model: modelToUse,\n });\n }\n\n return createTextCompletion(client, {\n messages,\n model: modelToUse,\n });\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\n\nimport { parseSseStream } from \"../../util/sse.js\";\n\n//\n//\n// Constants\n//\n\nconst OPENROUTER_BASE_URL = \"https://openrouter.ai/api/v1\";\n\n//\n//\n// Types\n//\n\nexport interface OpenRouterClientOptions {\n apiKey: string;\n baseURL?: string;\n}\n\nexport interface ChatCompletionOptions {\n signal?: AbortSignal;\n}\n\n/**\n * HTTP error carrying the upstream status and parsed API message. The\n * OpenRouterAdapter classifies errors by reading `.status` / `.statusCode` and\n * `.message` / `.error.message`, so this shape keeps `classifyError`,\n * `isTemperatureDeprecationError`, and `isStructuredOutputUnsupportedError`\n * working unchanged after dropping the SDK.\n */\nexport class OpenRouterHttpError extends Error {\n readonly status: number;\n readonly statusCode: number;\n readonly error?: { message?: string };\n\n constructor(status: number, message: string, error?: { message?: string }) {\n super(message);\n this.name = \"OpenRouterHttpError\";\n this.status = status;\n this.statusCode = status;\n this.error = error;\n }\n}\n\n//\n//\n// Helpers\n//\n\n/**\n * Normalize the snake_case wire response into the camelCase shape the adapter\n * readers expect (the SDK previously returned camelCase). Only protocol fields\n * are touched — user content (schema property names, tool argument JSON) is\n * left untouched.\n */\nfunction normalizeResponse(json: JsonObject): JsonObject {\n const choices = json.choices as Array<Record<string, unknown>> | undefined;\n if (Array.isArray(choices)) {\n for (const choice of choices) {\n if (\n choice.finish_reason !== undefined &&\n choice.finishReason === undefined\n ) {\n choice.finishReason = choice.finish_reason;\n }\n const message = choice.message as Record<string, unknown> | undefined;\n if (\n message?.tool_calls !== undefined &&\n message.toolCalls === undefined\n ) {\n message.toolCalls = message.tool_calls;\n }\n }\n }\n\n const usage = json.usage as Record<string, unknown> | undefined;\n if (usage) {\n if (usage.promptTokens === undefined)\n usage.promptTokens = usage.prompt_tokens;\n if (usage.completionTokens === undefined) {\n usage.completionTokens = usage.completion_tokens;\n }\n if (usage.totalTokens === undefined) usage.totalTokens = usage.total_tokens;\n const details = usage.completion_tokens_details as\n { reasoning_tokens?: number } | undefined;\n if (\n details?.reasoning_tokens !== undefined &&\n !usage.completionTokensDetails\n ) {\n usage.completionTokensDetails = {\n reasoningTokens: details.reasoning_tokens,\n };\n }\n }\n\n return json;\n}\n\n//\n//\n// Main\n//\n\n/**\n * Minimal `fetch`-based client for OpenRouter's OpenAI-compatible Chat\n * Completions endpoint. Replaces `@openrouter/sdk` — the adapter only needs a\n * single POST (streaming and non-streaming), header auth, and HTTP error\n * surfacing.\n */\nexport class OpenRouterClient {\n private readonly apiKey: string;\n private readonly baseURL: string;\n\n constructor({\n apiKey,\n baseURL = OPENROUTER_BASE_URL,\n }: OpenRouterClientOptions) {\n this.apiKey = apiKey;\n this.baseURL = baseURL;\n }\n\n private headers(): Record<string, string> {\n return {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n };\n }\n\n private async toError(response: Response): Promise<OpenRouterHttpError> {\n let message = `OpenRouter request failed with status ${response.status}`;\n let error: { message?: string } | undefined;\n try {\n const body = (await response.json()) as { error?: { message?: string } };\n if (body?.error?.message) {\n message = body.error.message;\n error = body.error;\n }\n } catch {\n // Non-JSON error body; keep the status-based message.\n }\n return new OpenRouterHttpError(response.status, message, error);\n }\n\n async chatCompletion(\n body: Record<string, unknown>,\n { signal }: ChatCompletionOptions = {},\n ): Promise<JsonObject> {\n const response = await fetch(`${this.baseURL}/chat/completions`, {\n method: \"POST\",\n headers: this.headers(),\n body: JSON.stringify(body),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n\n const json = (await response.json()) as JsonObject;\n return normalizeResponse(json);\n }\n\n async *streamChatCompletion(\n body: Record<string, unknown>,\n { signal }: ChatCompletionOptions = {},\n ): AsyncIterable<JsonObject> {\n const response = await fetch(`${this.baseURL}/chat/completions`, {\n method: \"POST\",\n headers: { ...this.headers(), Accept: \"text/event-stream\" },\n // OpenAI-style streams only include usage when explicitly requested.\n body: JSON.stringify({\n ...body,\n stream: true,\n stream_options: { include_usage: true },\n }),\n signal,\n });\n\n if (!response.ok) throw await this.toError(response);\n if (!response.body) return;\n\n yield* parseSseStream(response.body);\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { PROVIDER } from \"../../constants.js\";\nimport { OpenRouterClient } from \"./client.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenRouterClient> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(\"OPENROUTER_API_KEY\"));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new OpenRouterClient({ apiKey: resolvedApiKey });\n logger.trace(\"Initialized OpenRouter client\");\n return client;\n}\n\n// Get default model from environment or constants\nexport function getDefaultModel(): string {\n return process.env.OPENROUTER_MODEL || PROVIDER.OPENROUTER.DEFAULT;\n}\n\n// Message formatting\nexport interface ChatMessage {\n role: \"system\" | \"user\" | \"assistant\";\n content: string;\n}\n\nexport function formatSystemMessage(\n systemPrompt: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.system === false\n ? systemPrompt\n : replacePlaceholders(systemPrompt, data);\n\n return {\n role: \"system\" as const,\n content,\n };\n}\n\nexport function formatUserMessage(\n message: string,\n { data, placeholders }: Pick<LlmMessageOptions, \"data\" | \"placeholders\"> = {},\n): ChatMessage {\n const content =\n placeholders?.message === false\n ? message\n : replacePlaceholders(message, data);\n\n return {\n role: \"user\" as const,\n content,\n };\n}\n\nexport function prepareMessages(\n message: string,\n { system, data, placeholders }: LlmMessageOptions = {},\n): ChatMessage[] {\n const logger = getLogger();\n const messages: ChatMessage[] = [];\n\n if (system) {\n const systemMessage = formatSystemMessage(system, { data, placeholders });\n messages.push(systemMessage);\n logger.trace(`System message: ${systemMessage.content?.length} characters`);\n }\n\n const userMessage = formatUserMessage(message, { data, placeholders });\n messages.push(userMessage);\n logger.trace(`User message: ${userMessage.content?.length} characters`);\n\n return messages;\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport type { OpenRouterClient } from \"./client.js\";\nimport {\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n openRouterAdapter,\n StreamLoop,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport {\n getDefaultModel,\n getLogger,\n initializeClient,\n prepareMessages,\n} from \"./utils.js\";\n\nexport class OpenRouterProvider implements LlmProvider {\n private model: string;\n private _client?: OpenRouterClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = getDefaultModel(),\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenRouterClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: openRouterAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: openRouterAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options);\n const modelToUse = options?.model || this.model;\n\n // OpenAI-compatible Chat Completions body; messages are already wire-shaped.\n const response = await client.chatCompletion({\n model: modelToUse,\n messages,\n });\n\n const choices = response.choices as\n Array<{ message?: { content?: unknown } }> | undefined;\n const rawContent = choices?.[0]?.message?.content;\n // Extract text content - content could be string or array of content items\n const content =\n typeof rawContent === \"string\"\n ? rawContent\n : Array.isArray(rawContent)\n ? rawContent\n .filter((item) => item.type === \"text\")\n .map((item) => (item as { text: string }).text)\n .join(\"\")\n : \"\";\n\n this.log.trace(`Assistant reply: ${content?.length || 0} characters`);\n\n // If structured output was requested, try to parse the response\n if (options?.response && content) {\n try {\n return JSON.parse(content);\n } catch {\n return content || \"\";\n }\n }\n\n return content || \"\";\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE } from \"@jaypie/kit\";\nimport { createLogger, log as defaultLog } from \"@jaypie/logger\";\n\nimport { PROVIDER } from \"../../constants.js\";\nimport { OpenAIClient } from \"../openai/client.js\";\n\n// Logger\nexport const getLogger = (): ReturnType<typeof createLogger> =>\n defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenAIClient> {\n const logger = getLogger();\n const resolvedApiKey = apiKey || (await getEnvSecret(PROVIDER.XAI.API_KEY));\n\n if (!resolvedApiKey) {\n throw new ConfigurationError(\n \"The application could not resolve the requested keys\",\n );\n }\n\n const client = new OpenAIClient({\n apiKey: resolvedApiKey,\n baseURL: PROVIDER.XAI.BASE_URL,\n });\n logger.trace(\"Initialized xAI client\");\n return client;\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { PROVIDER } from \"../../constants.js\";\nimport {\n createOperateLoop,\n createStreamLoop,\n OperateLoop,\n StreamLoop,\n xaiAdapter,\n} from \"../../operate/index.js\";\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmProvider,\n LlmHistoryItem,\n} from \"../../types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"../../types/LlmStreamChunk.interface.js\";\nimport { OpenAIClient } from \"../openai/client.js\";\nimport {\n createStructuredCompletion,\n createTextCompletion,\n getLogger,\n prepareMessages,\n} from \"../openai/utils.js\";\nimport { initializeClient } from \"./utils.js\";\n\nexport class XaiProvider implements LlmProvider {\n private model: string;\n private _client?: OpenAIClient;\n private _operateLoop?: OperateLoop;\n private _streamLoop?: StreamLoop;\n private apiKey?: string;\n private log = getLogger();\n private conversationHistory: LlmHistoryItem[] = [];\n\n constructor(\n model: string = PROVIDER.XAI.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenAIClient> {\n if (this._client) {\n return this._client;\n }\n\n this._client = await initializeClient({ apiKey: this.apiKey });\n return this._client;\n }\n\n private async getOperateLoop(): Promise<OperateLoop> {\n if (this._operateLoop) {\n return this._operateLoop;\n }\n\n const client = await this.getClient();\n this._operateLoop = createOperateLoop({\n adapter: xaiAdapter,\n client,\n });\n return this._operateLoop;\n }\n\n private async getStreamLoop(): Promise<StreamLoop> {\n if (this._streamLoop) {\n return this._streamLoop;\n }\n\n const client = await this.getClient();\n this._streamLoop = createStreamLoop({\n adapter: xaiAdapter,\n client,\n });\n return this._streamLoop;\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n const client = await this.getClient();\n const messages = prepareMessages(message, options || {});\n const modelToUse = options?.model || this.model;\n\n if (options?.response) {\n return createStructuredCompletion(client, {\n messages,\n responseSchema: options.response,\n model: modelToUse,\n });\n }\n\n return createTextCompletion(client, {\n messages,\n model: modelToUse,\n });\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): Promise<LlmOperateResponse> {\n const operateLoop = await this.getOperateLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n // If options.history exists, merge with instance history, otherwise use instance history\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute operate loop\n const response = await operateLoop.execute(input, mergedOptions);\n\n // Update conversation history with the new history from the response\n if (response.history && response.history.length > 0) {\n this.conversationHistory = response.history;\n }\n\n return response;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n const streamLoop = await this.getStreamLoop();\n const mergedOptions = { ...options, model: options.model ?? this.model };\n\n // Create a merged history including both the tracked history and any explicitly provided history\n if (this.conversationHistory.length > 0) {\n mergedOptions.history = options.history\n ? [...this.conversationHistory, ...options.history]\n : [...this.conversationHistory];\n }\n\n // Execute stream loop\n yield* streamLoop.execute(input, mergedOptions);\n }\n}\n","import { JsonObject } from \"@jaypie/types\";\nimport { ConfigurationError, NotImplementedError } from \"@jaypie/errors\";\nimport log from \"@jaypie/logger\";\nimport { DEFAULT, LlmProviderName, PROVIDER } from \"./constants.js\";\nimport { determineModelProvider } from \"./util/determineModelProvider.js\";\nimport { resolveModelChain } from \"./util/resolveModelChain.js\";\nimport { emitExchange } from \"./operate/exchange/index.js\";\nimport { persistExchange } from \"./observability/exchangeStore.js\";\nimport {\n LlmExchangeCallback,\n LlmExchangeEnvelope,\n LlmFallbackConfig,\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\n LlmModelOption,\n LlmOperateInput,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmOptions,\n LlmProvider,\n} from \"./types/LlmProvider.interface.js\";\nimport { LlmStreamChunk } from \"./types/LlmStreamChunk.interface.js\";\nimport { AnthropicProvider } from \"./providers/anthropic/AnthropicProvider.class.js\";\nimport { BedrockProvider } from \"./providers/bedrock/index.js\";\nimport { FireworksProvider } from \"./providers/fireworks/index.js\";\nimport { GoogleProvider } from \"./providers/google/GoogleProvider.class.js\";\nimport { OpenAiProvider } from \"./providers/openai/index.js\";\nimport { OpenRouterProvider } from \"./providers/openrouter/index.js\";\nimport { XaiProvider } from \"./providers/xai/index.js\";\n\nclass Llm implements LlmProvider {\n private _fallbackConfig?: LlmFallbackConfig[];\n private _llm: LlmProvider;\n private _options: LlmOptions;\n private _provider: LlmProviderName;\n\n constructor(\n providerName: LlmProviderName | string = DEFAULT.PROVIDER.NAME,\n options: Omit<LlmOptions, \"model\"> & { model?: LlmModelOption } = {},\n ) {\n const { fallback: fallbackOption, model: modelOption } = options;\n // A `model` array is sugar for a preference-ordered fallback chain:\n // index 0 is primary, the rest become fallback entries (provider\n // auto-detected). Any explicit `fallback` is appended after the chain.\n const { fallback: modelFallback, model } = resolveModelChain(modelOption);\n const fallback =\n modelFallback.length || fallbackOption\n ? [...modelFallback, ...(fallbackOption ?? [])]\n : undefined;\n let finalProvider = providerName;\n let finalModel = model;\n\n // Legacy: accept \"gemini\" but warn\n if (providerName === \"gemini\") {\n log.warn(\n `Provider \"gemini\" is deprecated, use \"${PROVIDER.GOOGLE.NAME}\" instead`,\n );\n }\n\n if (model) {\n const modelDetermined = determineModelProvider(model);\n finalModel = modelDetermined.model;\n if (modelDetermined.provider) {\n finalProvider = modelDetermined.provider as LlmProviderName;\n }\n }\n\n // Only determine provider from providerName if we don't have a provider from model\n if (!model || !determineModelProvider(model).provider) {\n const providerDetermined = determineModelProvider(providerName);\n if (!providerDetermined.provider) {\n throw new ConfigurationError(\n `Unable to determine provider from: ${providerName}`,\n );\n }\n finalProvider = providerDetermined.provider;\n // When providerName is actually a model name, extract the model (#213)\n if (!finalModel && providerName !== providerDetermined.provider) {\n finalModel = providerDetermined.model;\n }\n }\n\n // Handle conflicts: if both providerName and model specify different providers\n if (model && providerName !== DEFAULT.PROVIDER.NAME) {\n const modelDetermined = determineModelProvider(model);\n const providerDetermined = determineModelProvider(providerName);\n if (\n modelDetermined.provider &&\n providerDetermined.provider &&\n modelDetermined.provider !== providerDetermined.provider\n ) {\n // Model's provider conflicts with explicit provider, don't pass model\n finalModel = undefined;\n }\n }\n\n this._fallbackConfig = fallback;\n this._provider = finalProvider as LlmProviderName;\n this._options = { ...options, model: finalModel };\n this._llm = this.createProvider(\n finalProvider as LlmProviderName,\n this._options,\n );\n }\n\n private createProvider(\n providerName: LlmProviderName,\n options: LlmOptions = {},\n ): LlmProvider {\n const { apiKey, model } = options;\n\n switch (providerName) {\n case PROVIDER.ANTHROPIC.NAME:\n return new AnthropicProvider(model || PROVIDER.ANTHROPIC.DEFAULT, {\n apiKey,\n });\n case PROVIDER.BEDROCK.NAME:\n return new BedrockProvider(model || PROVIDER.BEDROCK.DEFAULT);\n case PROVIDER.FIREWORKS.NAME:\n return new FireworksProvider(model || PROVIDER.FIREWORKS.DEFAULT, {\n apiKey,\n });\n case PROVIDER.GOOGLE.NAME:\n return new GoogleProvider(model || PROVIDER.GOOGLE.DEFAULT, {\n apiKey,\n });\n case PROVIDER.OPENAI.NAME:\n return new OpenAiProvider(model || PROVIDER.OPENAI.DEFAULT, {\n apiKey,\n });\n case PROVIDER.OPENROUTER.NAME:\n return new OpenRouterProvider(model || PROVIDER.OPENROUTER.DEFAULT, {\n apiKey,\n });\n case PROVIDER.XAI.NAME:\n return new XaiProvider(model || PROVIDER.XAI.DEFAULT, {\n apiKey,\n });\n default:\n throw new ConfigurationError(`Unsupported provider: ${providerName}`);\n }\n }\n\n async send(\n message: string,\n options?: Omit<LlmMessageOptions, \"model\"> & { model?: LlmModelOption },\n ): Promise<string | JsonObject> {\n if (options && Array.isArray(options.model)) {\n // `send` has no fallback machinery; use the primary model only\n const { model } = resolveModelChain(options.model);\n return this._llm.send(message, { ...options, model });\n }\n return this._llm.send(message, options as LlmMessageOptions | undefined);\n }\n\n /**\n * Resolves the fallback chain from instance config and per-call options.\n * Per-call options take precedence over instance config.\n * Returns empty array if fallback is disabled.\n */\n private resolveFallbackChain(\n options: LlmOperateOptions,\n ): LlmFallbackConfig[] {\n // Per-call `fallback: false` disables fallback entirely\n if (options.fallback === false) {\n return [];\n }\n // Per-call fallback array overrides instance config\n if (Array.isArray(options.fallback)) {\n return options.fallback;\n }\n // Use instance config if available\n return this._fallbackConfig || [];\n }\n\n /**\n * Creates a fallback Llm instance lazily when needed.\n */\n private createFallbackInstance(config: LlmFallbackConfig): Llm {\n return new Llm(config.provider, {\n apiKey: config.apiKey,\n model: config.model,\n });\n }\n\n async operate(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: Omit<LlmOperateOptions, \"model\"> & { model?: LlmModelOption } = {},\n ): Promise<LlmOperateResponse> {\n if (!this._llm.operate) {\n throw new NotImplementedError(\n `Provider ${this._provider} does not support operate method`,\n );\n }\n\n // A per-call `model` array becomes primary + a derived fallback chain\n // prepended to any resolved chain.\n const { fallback: modelFallback, model: perCallModel } = resolveModelChain(\n options.model,\n );\n const resolvedOptions: LlmOperateOptions = {\n ...options,\n model: perCallModel,\n };\n\n const fallbackChain = [\n ...modelFallback,\n ...this.resolveFallbackChain(resolvedOptions),\n ];\n const optionsWithoutFallback = {\n ...resolvedOptions,\n fallback: false as const,\n };\n\n let lastError: Error | undefined;\n let attempts = 0;\n\n // Try primary provider first\n attempts++;\n try {\n const response = await this._llm.operate(input, optionsWithoutFallback);\n const settled = {\n ...response,\n fallbackAttempts: attempts,\n fallbackUsed: false,\n provider: response.provider || this._provider,\n };\n await this.settleExchange({\n onExchange: resolvedOptions.onExchange,\n response: settled,\n });\n return settled;\n } catch (error) {\n lastError = error as Error;\n log.warn(`Provider ${this._provider} failed`, {\n error: lastError.message,\n fallbacksRemaining: fallbackChain.length,\n });\n }\n\n // Try fallback providers. The fallback instance's underlying provider is\n // called directly so the nested facade does not settle the exchange —\n // exactly one settlement per operate() happens here.\n for (const fallbackConfig of fallbackChain) {\n attempts++;\n try {\n const fallbackInstance = this.createFallbackInstance(fallbackConfig);\n if (!fallbackInstance._llm.operate) {\n throw new NotImplementedError(\n `Provider ${fallbackConfig.provider} does not support operate method`,\n );\n }\n const response = await fallbackInstance._llm.operate(\n input,\n optionsWithoutFallback,\n );\n const settled = {\n ...response,\n fallbackAttempts: attempts,\n fallbackUsed: true,\n provider: response.provider || fallbackConfig.provider,\n };\n await this.settleExchange({\n onExchange: resolvedOptions.onExchange,\n response: settled,\n });\n return settled;\n } catch (error) {\n lastError = error as Error;\n log.warn(`Fallback provider ${fallbackConfig.provider} failed`, {\n error: lastError.message,\n fallbacksRemaining: fallbackChain.length - attempts + 1,\n });\n }\n }\n\n // All providers failed: settle the exchange from the envelope the loop\n // attached to the last error, then throw\n const failureEnvelope = (lastError as { exchange?: LlmExchangeEnvelope })\n ?.exchange;\n if (failureEnvelope) {\n failureEnvelope.resolution = {\n ...failureEnvelope.resolution,\n fallbackAttempts: attempts,\n fallbackUsed: attempts > 1,\n };\n await emitExchange({\n envelope: failureEnvelope,\n onExchange: resolvedOptions.onExchange,\n });\n await persistExchange(failureEnvelope);\n }\n throw lastError;\n }\n\n /**\n * Stamp fallback resolution onto the envelope the operate loop attached to\n * the response and deliver it to the caller's onExchange. Fires once per\n * operate() settlement; callback errors are logged and never thrown.\n */\n private async settleExchange({\n onExchange,\n response,\n }: {\n onExchange?: LlmExchangeCallback;\n response: LlmOperateResponse;\n }): Promise<void> {\n const envelope = response.exchange;\n if (!envelope) {\n return;\n }\n envelope.resolution = {\n ...envelope.resolution,\n fallbackAttempts: response.fallbackAttempts,\n fallbackUsed: response.fallbackUsed,\n model: response.model,\n provider: response.provider,\n };\n await emitExchange({ envelope, onExchange });\n await persistExchange(envelope);\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: Omit<LlmOperateOptions, \"model\"> & { model?: LlmModelOption } = {},\n ): AsyncIterable<LlmStreamChunk> {\n if (!this._llm.stream) {\n throw new NotImplementedError(\n `Provider ${this._provider} does not support stream method`,\n );\n }\n // `stream` has no instance-level fallback machinery; an array model uses\n // the primary and ignores the rest.\n const { model } = resolveModelChain(options.model);\n const streamOptions: LlmOperateOptions = { ...options, model };\n yield* this._llm.stream(input, streamOptions);\n }\n\n static async send(\n message: string,\n options?: Omit<LlmMessageOptions, \"model\"> & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string | string[];\n },\n ): Promise<string | JsonObject> {\n const { llm, apiKey, model, ...messageOptions } = options || {};\n // A `model` array derives a fallback chain; `send` has no fallback\n // machinery, so the primary model is used and the chain is ignored.\n const { model: primaryModel } = resolveModelChain(model);\n const instance = new Llm(llm, { apiKey, model: primaryModel });\n return instance.send(message, messageOptions);\n }\n\n static async operate(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options?: Omit<LlmOperateOptions, \"model\"> & {\n apiKey?: string;\n fallback?: LlmFallbackConfig[] | false;\n llm?: LlmProviderName;\n model?: string | string[];\n },\n ): Promise<LlmOperateResponse> {\n const { apiKey, fallback, llm, model, ...operateOptions } = options || {};\n\n // A `model` array becomes primary + derived fallback chain\n const { fallback: modelFallback, model: primaryModel } =\n resolveModelChain(model);\n\n let finalLlm = llm;\n let finalModel = primaryModel;\n\n if (!llm && primaryModel) {\n const determined = determineModelProvider(primaryModel);\n if (determined.provider) {\n finalLlm = determined.provider as LlmProviderName;\n }\n } else if (llm && primaryModel) {\n // When both llm and model are provided, check if they conflict\n const determined = determineModelProvider(primaryModel);\n if (determined.provider && determined.provider !== llm) {\n // Don't pass the conflicting model to the constructor\n finalModel = undefined;\n }\n }\n\n // Resolve fallback for static method: pass to instance if array, pass to operate options if false\n const explicitFallback = Array.isArray(fallback) ? fallback : [];\n const instanceFallback =\n modelFallback.length || explicitFallback.length\n ? [...modelFallback, ...explicitFallback]\n : undefined;\n const operateFallback = fallback === false ? false : undefined;\n\n const instance = new Llm(finalLlm, {\n apiKey,\n fallback: instanceFallback,\n model: finalModel,\n });\n return instance.operate(input, {\n ...operateOptions,\n ...(operateFallback !== undefined && { fallback: operateFallback }),\n });\n }\n\n static stream(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options?: Omit<LlmOperateOptions, \"model\"> & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string | string[];\n },\n ): AsyncIterable<LlmStreamChunk> {\n const { llm, apiKey, model, ...streamOptions } = options || {};\n\n // A `model` array becomes primary + derived fallback chain\n const { fallback: modelFallback, model: primaryModel } =\n resolveModelChain(model);\n\n let finalLlm = llm;\n let finalModel = primaryModel;\n\n if (!llm && primaryModel) {\n const determined = determineModelProvider(primaryModel);\n if (determined.provider) {\n finalLlm = determined.provider as LlmProviderName;\n }\n } else if (llm && primaryModel) {\n // When both llm and model are provided, check if they conflict\n const determined = determineModelProvider(primaryModel);\n if (determined.provider && determined.provider !== llm) {\n // Don't pass the conflicting model to the constructor\n finalModel = undefined;\n }\n }\n\n const instance = new Llm(finalLlm, {\n apiKey,\n fallback: modelFallback.length ? modelFallback : undefined,\n model: finalModel,\n });\n return instance.stream(input, streamOptions);\n }\n}\n\nexport default Llm;\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { random as randomUtil } from \"../util/random.js\";\n\nexport const random: LlmTool = {\n description:\n \"Generate a random number with optional distribution, precision, range, and seeding\",\n\n name: \"random\",\n parameters: {\n type: \"object\",\n properties: {\n min: {\n type: \"number\",\n description:\n \"Minimum value (inclusive). Default: 0. When used with mean/stddev, acts as a clamp on the normal distribution\",\n },\n max: {\n type: \"number\",\n description:\n \"Maximum value (inclusive). Default: 1. When used with mean/stddev, acts as a clamp on the normal distribution\",\n },\n mean: {\n type: \"number\",\n description:\n \"Mean value for normal distribution. When set with stddev, uses normal distribution (clamped by min/max if provided)\",\n },\n stddev: {\n type: \"number\",\n description:\n \"Standard deviation for normal distribution. When set with mean, uses normal distribution (clamped by min/max if provided)\",\n },\n integer: {\n type: \"boolean\",\n description: \"Whether to return an integer value. Default: false\",\n },\n seed: {\n type: \"string\",\n description:\n \"Seed string for consistent random generation. Default: undefined (uses default RNG)\",\n },\n precision: {\n type: \"number\",\n description:\n \"Number of decimal places for the result. Default: undefined (full precision)\",\n },\n currency: {\n type: \"boolean\",\n description:\n \"Whether to format as currency (2 decimal places). Default: false\",\n },\n },\n required: [],\n },\n type: \"function\",\n call: (options) => {\n const rng = randomUtil();\n return rng(options);\n },\n message: ({\n min,\n max,\n mean,\n stddev,\n integer,\n seed,\n precision,\n currency,\n } = {}) => {\n let description = \"Generating\";\n if (seed) {\n description += ` seeded`;\n } else {\n description += \" random\";\n }\n if (integer) {\n description += \" integer\";\n } else if (currency) {\n description += \" currency\";\n } else if (precision) {\n description += ` with precision \\`${precision}\\``;\n } else {\n description += \" number\";\n }\n if (min && max) {\n description += ` between \\`${min}\\` and \\`${max}\\``;\n }\n if (mean && stddev) {\n description += ` with normal distribution around \\`${mean}\\` with standard deviation \\`${stddev}\\``;\n }\n return description;\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { getLogger, random, tryParseNumber } from \"../util\";\n\nexport const roll: LlmTool = {\n description: \"Roll one or more dice with a specified number of sides\",\n name: \"roll\",\n parameters: {\n type: \"object\",\n properties: {\n number: {\n type: \"number\",\n description: \"Number of dice to roll. Default: 1\",\n },\n sides: {\n type: \"number\",\n description: \"Number of sides on each die. Default: 6\",\n },\n },\n required: [\"number\", \"sides\"],\n },\n type: \"function\",\n call: ({ number = 1, sides = 6 } = {}): {\n rolls: number[];\n total: number;\n } => {\n const log = getLogger();\n const rng = random();\n const rolls: number[] = [];\n let total = 0;\n\n const parsedNumber = tryParseNumber(number, {\n defaultValue: 1,\n warnFunction: log.warn,\n }) as number;\n const parsedSides = tryParseNumber(sides, {\n defaultValue: 6,\n warnFunction: log.warn,\n }) as number;\n\n for (let i = 0; i < parsedNumber; i++) {\n const rollValue = rng({ min: 1, max: parsedSides, integer: true });\n rolls.push(rollValue);\n total += rollValue;\n }\n\n return { rolls, total };\n },\n message: ({ number = 1, sides = 6 } = {}) => {\n return `Rolling ${number} ${sides}-sided dice`;\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\n\nexport const time: LlmTool = {\n description:\n \"Returns the provided date as an ISO UTC string or the current time if no date provided.\",\n name: \"time\",\n parameters: {\n type: \"object\",\n properties: {\n date: {\n type: \"string\",\n description:\n \"Date string to convert to ISO UTC format. Default: current time\",\n },\n },\n required: [],\n },\n type: \"function\",\n call: ({ date } = {}) => {\n if (typeof date === \"number\" || typeof date === \"string\") {\n const parsedDate = new Date(date);\n if (isNaN(parsedDate.getTime())) {\n throw new Error(`Invalid date format: ${date}`);\n }\n return parsedDate.toISOString();\n }\n return new Date().toISOString();\n },\n message: ({ date } = {}) => {\n if (typeof date === \"number\" || typeof date === \"string\") {\n return `Converting date to ISO UTC format`;\n }\n return \"Checking current time\";\n },\n};\n","import { LlmTool } from \"../types/LlmTool.interface.js\";\nimport { fetchWeatherApi } from \"openmeteo\";\nimport { JsonObject } from \"@jaypie/types\";\n\nexport const weather: LlmTool = {\n description: \"Get current weather and forecast data for a specific location\",\n name: \"weather\",\n parameters: {\n type: \"object\",\n properties: {\n latitude: {\n type: \"number\",\n description:\n \"Latitude of the location. Default: 42.051554533384866 (Evanston, IL)\",\n },\n location: {\n type: \"string\",\n description:\n \"Human-readable description of the location, not used for the API call. Default: Evanston, IL\",\n },\n longitude: {\n type: \"number\",\n description:\n \"Longitude of the location. Default: -87.6759911441785 (Evanston, IL)\",\n },\n timezone: {\n type: \"string\",\n description: \"Timezone for the results. Default: America/Chicago\",\n },\n past_days: {\n type: \"number\",\n description:\n \"Number of past days to include in the forecast. Default: 1\",\n },\n forecast_days: {\n type: \"number\",\n description: \"Number of forecast days to include. Default: 1\",\n },\n },\n required: [\"latitude\", \"location\", \"longitude\"],\n },\n type: \"function\",\n call: async ({\n latitude = 42.051554533384866,\n longitude = -87.6759911441785,\n timezone = \"America/Chicago\",\n past_days = 1,\n forecast_days = 1,\n } = {}): Promise<JsonObject> => {\n try {\n const params = {\n latitude,\n longitude,\n hourly: [\n \"temperature_2m\",\n \"precipitation_probability\",\n \"precipitation\",\n ],\n current: [\n \"temperature_2m\",\n \"is_day\",\n \"showers\",\n \"cloud_cover\",\n \"wind_speed_10m\",\n \"relative_humidity_2m\",\n \"precipitation\",\n \"snowfall\",\n \"rain\",\n \"apparent_temperature\",\n ],\n timezone,\n past_days,\n forecast_days,\n wind_speed_unit: \"mph\",\n temperature_unit: \"fahrenheit\",\n precipitation_unit: \"inch\",\n };\n\n const url = \"https://api.open-meteo.com/v1/forecast\";\n const responses = await fetchWeatherApi(url, params);\n\n // Helper function to form time ranges\n const range = (start: number, stop: number, step: number) =>\n Array.from(\n { length: (stop - start) / step },\n (_, i) => start + i * step,\n );\n\n // Process first location\n const response = responses[0];\n\n // Attributes for timezone and location\n const utcOffsetSeconds = response.utcOffsetSeconds();\n const timezoneAbbreviation = response.timezoneAbbreviation();\n\n const current = response.current()!;\n const hourly = response.hourly()!;\n\n // Create weather data object\n const weatherData = {\n location: {\n latitude: response.latitude(),\n longitude: response.longitude(),\n timezone: response.timezone(),\n timezoneAbbreviation,\n utcOffsetSeconds,\n },\n current: {\n time: new Date(\n (Number(current.time()) + utcOffsetSeconds) * 1000,\n ).toISOString(),\n temperature2m: current.variables(0)!.value(),\n isDay: current.variables(1)!.value(),\n showers: current.variables(2)!.value(),\n cloudCover: current.variables(3)!.value(),\n windSpeed10m: current.variables(4)!.value(),\n relativeHumidity2m: current.variables(5)!.value(),\n precipitation: current.variables(6)!.value(),\n snowfall: current.variables(7)!.value(),\n rain: current.variables(8)!.value(),\n apparentTemperature: current.variables(9)!.value(),\n },\n hourly: {\n time: range(\n Number(hourly.time()),\n Number(hourly.timeEnd()),\n hourly.interval(),\n ).map((t) => new Date((t + utcOffsetSeconds) * 1000).toISOString()),\n temperature2m: Array.from(hourly.variables(0)!.valuesArray()!),\n precipitationProbability: Array.from(\n hourly.variables(1)!.valuesArray()!,\n ),\n precipitation: Array.from(hourly.variables(2)!.valuesArray()!),\n },\n };\n\n return weatherData;\n } catch (error) {\n if (error instanceof Error) {\n // eslint-disable-next-line preserve-caught-error -- package targets ES2020; Error `cause` option requires ES2022\n throw new Error(`Weather API error: ${error.message}`);\n }\n // eslint-disable-next-line preserve-caught-error -- package targets ES2020; Error `cause` option requires ES2022\n throw new Error(\"Unknown error occurred while fetching weather data\");\n }\n },\n message: ({\n latitude = 42.051554533384866,\n longitude = -87.6759911441785,\n location = \"Evanston, IL\",\n } = {}) => {\n return `Getting weather for ${location} (${latitude}, ${longitude})`;\n },\n};\n","import { Toolkit } from \"./Toolkit.class.js\";\nimport type { LlmTool } from \"../types/LlmTool.interface.js\";\n\nimport { random } from \"./random.js\";\nimport { roll } from \"./roll.js\";\nimport { time } from \"./time.js\";\nimport { weather } from \"./weather.js\";\n\nexport const tools = [random, roll, time, weather];\n\nexport class JaypieToolkit extends Toolkit {\n public readonly random: LlmTool;\n public readonly roll: LlmTool;\n public readonly time: LlmTool;\n public readonly weather: LlmTool;\n\n constructor(tools: LlmTool[], options?: any) {\n super(tools, options);\n this.random = random;\n this.roll = roll;\n this.time = time;\n this.weather = weather;\n }\n}\n\nexport const toolkit = new JaypieToolkit(tools);\n\nexport { Toolkit };\n","import { JsonObject } from \"@jaypie/types\";\nimport { LlmMessageRole } from \"../../types/LlmProvider.interface.js\";\n\n//\n//\n// Role Mapping\n//\n\nexport const ROLE_MAP: Record<LlmMessageRole, \"user\" | \"model\"> = {\n [LlmMessageRole.User]: \"user\",\n [LlmMessageRole.System]: \"user\", // Gemini doesn't have system role in contents\n [LlmMessageRole.Assistant]: \"model\",\n [LlmMessageRole.Developer]: \"user\",\n};\n\n//\n//\n// Gemini API Types\n//\n\n/**\n * A part of content - can be text, function call, or function response\n */\nexport interface GeminiPart {\n text?: string;\n thought?: boolean;\n thoughtSignature?: string;\n functionCall?: GeminiFunctionCall;\n functionResponse?: GeminiFunctionResponse;\n inlineData?: {\n mimeType: string;\n data: string;\n };\n fileData?: {\n mimeType?: string;\n fileUri: string;\n };\n}\n\n/**\n * A function call made by the model\n */\nexport interface GeminiFunctionCall {\n name?: string;\n args?: Record<string, unknown>;\n id?: string;\n}\n\n/**\n * A response to a function call\n */\nexport interface GeminiFunctionResponse {\n name: string;\n response: Record<string, unknown>;\n}\n\n/**\n * Content represents a message in the conversation\n */\nexport interface GeminiContent {\n role: \"user\" | \"model\";\n parts?: GeminiPart[];\n}\n\n/**\n * Function declaration for tools\n */\nexport interface GeminiFunctionDeclaration {\n name: string;\n description: string;\n parameters: JsonObject;\n}\n\n/**\n * Tool definition containing function declarations\n */\nexport interface GeminiTool {\n functionDeclarations?: GeminiFunctionDeclaration[];\n googleSearch?: Record<string, unknown>;\n codeExecution?: Record<string, unknown>;\n}\n\n/**\n * Configuration for a generate content request\n * This is a simplified internal type - we use the SDK's actual types at runtime\n */\nexport interface GeminiGenerateContentConfig {\n systemInstruction?: string;\n tools?: GeminiTool[];\n toolConfig?: {\n functionCallingConfig?: {\n mode?: \"AUTO\" | \"ANY\" | \"NONE\";\n allowedFunctionNames?: string[];\n };\n };\n responseMimeType?: string;\n responseJsonSchema?: JsonObject;\n responseSchema?: JsonObject;\n thinkingConfig?: {\n thinkingLevel?: string;\n thinkingBudget?: number;\n includeThoughts?: boolean;\n };\n temperature?: number;\n topP?: number;\n topK?: number;\n maxOutputTokens?: number;\n stopSequences?: string[];\n candidateCount?: number;\n}\n\n/**\n * Request structure for generateContent API\n */\nexport interface GeminiRequest {\n model: string;\n contents: GeminiContent[];\n config?: GeminiGenerateContentConfig;\n}\n\n/**\n * Usage metadata from the response\n */\nexport interface GeminiUsageMetadata {\n promptTokenCount?: number;\n candidatesTokenCount?: number;\n totalTokenCount?: number;\n thoughtsTokenCount?: number;\n cachedContentTokenCount?: number;\n}\n\n/**\n * A response candidate from the model\n */\nexport interface GeminiCandidate {\n content?: GeminiContent;\n finishReason?: string;\n index?: number;\n safetyRatings?: Array<{\n category: string;\n probability: string;\n blocked?: boolean;\n }>;\n citationMetadata?: {\n citations?: Array<{\n startIndex?: number;\n endIndex?: number;\n uri?: string;\n title?: string;\n license?: string;\n publicationDate?: {\n year?: number;\n month?: number;\n day?: number;\n };\n }>;\n };\n tokenCount?: number;\n avgLogprobs?: number;\n}\n\n/**\n * Prompt feedback from the API\n */\nexport interface GeminiPromptFeedback {\n blockReason?: string;\n safetyRatings?: Array<{\n category: string;\n probability: string;\n blocked?: boolean;\n }>;\n}\n\n/**\n * Raw response from Gemini API\n */\nexport interface GeminiRawResponse {\n candidates?: GeminiCandidate[];\n promptFeedback?: GeminiPromptFeedback;\n usageMetadata?: GeminiUsageMetadata;\n modelVersion?: string;\n responseId?: string;\n createTime?: string;\n text?: string;\n functionCalls?: GeminiFunctionCall[];\n}\n\n/**\n * Error information from Gemini API\n */\nexport interface GeminiErrorInfo {\n status?: number;\n code?: number;\n message?: string;\n details?: Array<{\n \"@type\"?: string;\n reason?: string;\n domain?: string;\n metadata?: Record<string, string>;\n }>;\n}\n\n/**\n * Finish reasons returned by Gemini\n */\nexport const FINISH_REASON = {\n FINISH_REASON_UNSPECIFIED: \"FINISH_REASON_UNSPECIFIED\",\n STOP: \"STOP\",\n MAX_TOKENS: \"MAX_TOKENS\",\n SAFETY: \"SAFETY\",\n RECITATION: \"RECITATION\",\n LANGUAGE: \"LANGUAGE\",\n OTHER: \"OTHER\",\n BLOCKLIST: \"BLOCKLIST\",\n PROHIBITED_CONTENT: \"PROHIBITED_CONTENT\",\n SPII: \"SPII\",\n MALFORMED_FUNCTION_CALL: \"MALFORMED_FUNCTION_CALL\",\n IMAGE_SAFETY: \"IMAGE_SAFETY\",\n UNEXPECTED_TOOL_CALL: \"UNEXPECTED_TOOL_CALL\",\n} as const;\n\nexport type GeminiFinishReason =\n (typeof FINISH_REASON)[keyof typeof FINISH_REASON];\n"],"names":["isPlainObject","formatToJsonSchema","isJsonSchema","log","getLogger","defaultLog","random","MODULE","resolved","cachedSdk","STRUCTURED_OUTPUT_TOOL_NAME","DATA_URL_REGEX","MODELS_WITHOUT_TEMPERATURE","isTemperatureDeprecationError","isStructuredOutputUnsupportedError","isBareJsonSchema","STRUCTURED_OUTPUT_SCHEMA_NAME","contentToWire","messageToWire","RETRYABLE_STATUS_CODES","RATE_LIMIT_STATUS_CODE","enforceAdditionalPropertiesFalse","errorForStatus","BadRequestError","AuthenticationError","PermissionDeniedError","NotFoundError","RateLimitError","InternalServerError","jaypieLog","defaultHookRunner","ERROR","initializeClient","formatSystemMessage","placeholders","replacePlaceholders","formatUserMessage","prepareMessages","createTextCompletion","createStructuredCompletion","normalizeResponse","getDefaultModel","randomUtil"],"mappings":";;;;;;;;;;;;;AAAA;;;;;;;;AAQG;AACI,MAAM,MAAM,GAAG;AACpB,IAAA,MAAM,EAAE,QAAQ;AAChB,IAAA,GAAG,EAAE,KAAK;AACV,IAAA,MAAM,EAAE,QAAQ;AAChB,IAAA,IAAI,EAAE,MAAM;AACZ,IAAA,OAAO,EAAE,SAAS;CACV;AAIH,MAAM,KAAK,GAAG;;AAEnB,IAAA,KAAK,EAAE,gBAAgB;AACvB,IAAA,IAAI,EAAE,iBAAiB;AACvB,IAAA,MAAM,EAAE,iBAAiB;AACzB,IAAA,KAAK,EAAE,kBAAkB;AACzB,IAAA,MAAM,EAAE,iBAAiB;;AAEzB,IAAA,SAAS,EAAE;AACT,QAAA,QAAQ,EAAE,2CAA2C;AACrD,QAAA,GAAG,EAAE,mCAAmC;AACxC,QAAA,IAAI,EAAE,0CAA0C;AAChD,QAAA,OAAO,EAAE,wCAAwC;AACjD,QAAA,IAAI,EAAE,wCAAwC;AAC/C,KAAA;;AAED,IAAA,YAAY,EAAE,kBAAkB;AAChC,IAAA,iBAAiB,EAAE,uBAAuB;AAC1C,IAAA,UAAU,EAAE,wBAAwB;;A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