@jaypie/llm 1.3.1 → 1.3.2
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/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +661 -0
- package/dist/cjs/providers/anthropic/utils.d.ts +2 -1
- package/dist/cjs/providers/bedrock/utils.d.ts +2 -1
- package/dist/cjs/providers/google/utils.d.ts +2 -1
- package/dist/cjs/providers/openai/utils.d.ts +2 -1
- package/dist/cjs/providers/openrouter/utils.d.ts +2 -1
- package/dist/cjs/providers/xai/utils.d.ts +2 -1
- package/dist/cjs/util/logger.d.ts +2 -1
- package/dist/esm/index.d.ts +661 -16
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/providers/anthropic/utils.d.ts +2 -1
- package/dist/esm/providers/bedrock/utils.d.ts +2 -1
- package/dist/esm/providers/google/utils.d.ts +2 -1
- package/dist/esm/providers/openai/utils.d.ts +2 -1
- package/dist/esm/providers/openrouter/utils.d.ts +2 -1
- package/dist/esm/providers/xai/utils.d.ts +2 -1
- package/dist/esm/util/logger.d.ts +2 -1
- package/package.json +11 -5
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/constants.ts","../../../src/util/determineModelProvider.ts","../../../src/operate/adapters/ProviderAdapter.interface.ts","../../../src/types/LlmProvider.interface.ts","../../../src/types/LlmStreamChunk.interface.ts","../../../src/util/extractReasoning.ts","../../../src/util/naturalZodSchema.ts","../../../src/util/fillFormatArrays.ts","../../../src/util/formatOperateMessage.ts","../../../src/util/formatOperateInput.ts","../../../src/util/jsonSchemaToOpenApi3.ts","../../../src/util/logger.ts","../../../src/util/maxTurnsFromOptions.ts","../../../src/util/random.ts","../../../src/util/tryParseNumber.ts","../../../src/operate/types.ts","../../../src/operate/retry/isTransientNetworkError.ts","../../../src/operate/adapters/AnthropicAdapter.ts","../../../src/operate/adapters/BedrockAdapter.ts","../../../src/operate/adapters/GoogleAdapter.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/response/ResponseBuilder.ts","../../../src/operate/retry/RetryPolicy.ts","../../../src/operate/retry/createStaleRejectionGuard.ts","../../../src/operate/retry/RetryExecutor.ts","../../../src/operate/OperateLoop.ts","../../../src/operate/StreamLoop.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/google/utils.ts","../../../src/providers/google/GoogleProvider.class.ts","../../../src/providers/openai/utils.ts","../../../src/providers/openai/OpenAiProvider.class.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":["const FIRST_CLASS_PROVIDER = {\n // https://docs.anthropic.com/en/docs/about-claude/models/overview\n ANTHROPIC: {\n DEFAULT: \"claude-sonnet-4-6\" as const,\n LARGE: \"claude-opus-4-8\" as const,\n SMALL: \"claude-sonnet-4-6\" as const,\n TINY: \"claude-haiku-4-5\" as const,\n },\n // https://ai.google.dev/gemini-api/docs/models\n GOOGLE: {\n DEFAULT: \"gemini-3.1-pro-preview\" as const,\n LARGE: \"gemini-3.1-pro-preview\" as const,\n SMALL: \"gemini-3.5-flash\" as const,\n TINY: \"gemini-3.1-flash-lite\" as const,\n },\n // https://developers.openai.com/api/docs/models\n OPENAI: {\n DEFAULT: \"gpt-5.4\" as const,\n LARGE: \"gpt-5.5\" as const,\n SMALL: \"gpt-5.4-mini\" as const,\n TINY: \"gpt-5.4-nano\" as const,\n },\n // https://docs.x.ai/developers/models\n XAI: {\n DEFAULT: \"grok-latest\" as const,\n LARGE: \"grok-4.3-latest\" as const,\n SMALL: \"grok-4-1-fast-reasoning\" as const,\n TINY: \"grok-4-1-fast-non-reasoning\" as const,\n },\n};\n\nexport const MODEL = {\n // Anthropic\n OPUS: \"claude-opus-4-8\",\n SONNET: \"claude-sonnet-4-6\",\n HAIKU: \"claude-haiku-4-5\",\n FABLE: \"claude-fable-5\",\n MYTHOS: \"claude-mythos-5\",\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 GPT: \"gpt-5.5\",\n GPT_MINI: \"gpt-5.4-mini\",\n GPT_NANO: \"gpt-5.4-nano\",\n // xAI\n GROK: \"grok-latest\",\n};\n\nconst GOOGLE_PROVIDER = {\n // https://ai.google.dev/gemini-api/docs/models\n MODEL: {\n DEFAULT: FIRST_CLASS_PROVIDER.GOOGLE.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.GOOGLE.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.GOOGLE.SMALL,\n TINY: FIRST_CLASS_PROVIDER.GOOGLE.TINY,\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 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 MAX_TOKENS: {\n DEFAULT: 4096 as const,\n },\n MODEL: {\n DEFAULT: FIRST_CLASS_PROVIDER.ANTHROPIC.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.ANTHROPIC.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.ANTHROPIC.SMALL,\n TINY: FIRST_CLASS_PROVIDER.ANTHROPIC.TINY,\n },\n MODEL_MATCH_WORDS: [\n \"anthropic\",\n \"claude\",\n \"haiku\",\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 /** @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 MODEL: {\n DEFAULT: FIRST_CLASS_PROVIDER.OPENAI.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.OPENAI.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.OPENAI.SMALL,\n TINY: FIRST_CLASS_PROVIDER.OPENAI.TINY,\n },\n MODEL_MATCH_WORDS: [\"openai\", \"gpt\", /^o\\d/],\n NAME: \"openai\" as const,\n },\n OPENROUTER: {\n MODEL: {\n DEFAULT: `anthropic/${FIRST_CLASS_PROVIDER.ANTHROPIC.DEFAULT}` as const,\n LARGE: `anthropic/${FIRST_CLASS_PROVIDER.ANTHROPIC.LARGE}` as const,\n SMALL: `anthropic/${FIRST_CLASS_PROVIDER.ANTHROPIC.SMALL}` as const,\n TINY: `anthropic/${FIRST_CLASS_PROVIDER.ANTHROPIC.TINY}` 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 MODEL: {\n DEFAULT: FIRST_CLASS_PROVIDER.XAI.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.XAI.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.XAI.SMALL,\n TINY: FIRST_CLASS_PROVIDER.XAI.TINY,\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.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 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// 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.MODEL.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 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.MODEL.DEFAULT,\n provider: PROVIDER.BEDROCK.NAME,\n };\n }\n if (input === PROVIDER.ANTHROPIC.NAME) {\n return {\n model: PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n provider: PROVIDER.ANTHROPIC.NAME,\n };\n }\n if (input === PROVIDER.GOOGLE.NAME || input === \"gemini\") {\n return {\n model: PROVIDER.GOOGLE.MODEL.DEFAULT,\n provider: PROVIDER.GOOGLE.NAME,\n };\n }\n if (input === PROVIDER.OPENAI.NAME) {\n return {\n model: PROVIDER.OPENAI.MODEL.DEFAULT,\n provider: PROVIDER.OPENAI.NAME,\n };\n }\n if (input === PROVIDER.OPENROUTER.NAME) {\n return {\n model: PROVIDER.OPENROUTER.MODEL.DEFAULT,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n if (input === PROVIDER.XAI.NAME) {\n return {\n model: PROVIDER.XAI.MODEL.DEFAULT,\n provider: PROVIDER.XAI.NAME,\n };\n }\n\n // Check if input matches an Anthropic model exactly\n for (const [, modelValue] of Object.entries(PROVIDER.ANTHROPIC.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.ANTHROPIC.NAME,\n };\n }\n }\n\n // Check if input matches a Gemini model exactly\n for (const [, modelValue] of Object.entries(PROVIDER.GOOGLE.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.GOOGLE.NAME,\n };\n }\n }\n\n // Check if input matches an OpenAI model exactly\n for (const [, modelValue] of Object.entries(PROVIDER.OPENAI.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.OPENAI.NAME,\n };\n }\n }\n\n // Check if input matches an OpenRouter model exactly\n for (const [, modelValue] of Object.entries(PROVIDER.OPENROUTER.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n }\n\n // Check if input matches an xAI model exactly\n for (const [, modelValue] of Object.entries(PROVIDER.XAI.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.XAI.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 { 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 // 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 * 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\n extractStructuredOutput(_response: unknown): JsonObject | undefined {\n return undefined;\n }\n}\n","import {\n AnyValue,\n JsonObject,\n JsonReturn,\n NaturalMap,\n NaturalSchema,\n} from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\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\ninterface 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\n | LlmInputContentImage\n | 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\n | LlmOperateInputFile\n | 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\n | LlmItemReference\n | LlmOutputItem\n | 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\nexport interface LlmOperateOptions {\n data?: NaturalMap;\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 }: {\n result: unknown;\n toolName: string;\n args: 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 }: {\n toolName: string;\n args: 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 }: {\n error: Error;\n toolName: string;\n args: 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 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\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 provider?: string;\n model?: string;\n}\n\nexport type LlmUsage = LlmUsageItem[];\n\nexport interface LlmOperateResponse {\n content?: string | JsonObject;\n error?: LlmError;\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 { 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 { 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 { 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 { 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 { log as defaultLog } from \"@jaypie/logger\";\n\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\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","/**\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 { JsonObject } from \"@jaypie/types\";\n\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageType,\n LlmOperateOptions,\n LlmResponseStatus,\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 /** Provider-specific options */\n providerOptions?: JsonObject;\n /** Sampling temperature (0-2 for most providers) */\n temperature?: number;\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 rate limiting */\n RateLimit = \"rate_limit\",\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\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 /** 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 /** Formatted tools for the provider */\n formattedTools?: ProviderToolDefinition[];\n /** Maximum allowed turns */\n maxTurns: number;\n /** Response builder instance */\n responseBuilder: ResponseBuilder;\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 type { Anthropic } from \"@anthropic-ai/sdk\";\nimport log from \"@jaypie/logger\";\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 { 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 { 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 format: {\n type: \"json_schema\";\n schema: JsonObject;\n };\n };\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.MODEL.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 anthropicRequest: AnthropicRequestParams = {\n model: (request.model ||\n this.defaultModel) as Anthropic.MessageCreateParams[\"model\"],\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n stream: false,\n };\n\n if (request.system) {\n anthropicRequest.system = 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) => ({\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 }));\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 // 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 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 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 Anthropic;\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) return request;\n const fallbackRequest: AnthropicRequestParams = { ...rest };\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 Anthropic;\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 };\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 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 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 { 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 { 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 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.MODEL.DEFAULT;\n\n private _modelsFallbackToStructuredOutputTool = new Set<string>();\n private _modelsWithoutTemperature = new Set<string>();\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 if (request.providerOptions) {\n Object.assign(bedrockRequest, request.providerOptions);\n }\n\n return bedrockRequest;\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 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 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;\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 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 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 }\n | 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 }\n | undefined;\n\n return textBlock?.text;\n }\n}\n\nexport const bedrockAdapter = new BedrockAdapter();\n","import type { GoogleGenAI } from \"@google/genai\";\nimport log from \"@jaypie/logger\";\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 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 { jsonSchemaToOpenApi3, 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 { 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/**\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.MODEL.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 // Add provider-specific options\n if (request.providerOptions) {\n geminiRequest.config = {\n ...geminiRequest.config,\n ...request.providerOptions,\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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 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 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 GoogleGenAI;\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 GoogleGenAI;\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 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, NaturalSchema } from \"@jaypie/types\";\nimport {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n InternalServerError,\n NotFoundError,\n OpenAI,\n PermissionDeniedError,\n RateLimitError,\n UnprocessableEntityError,\n} from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.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 { naturalZodSchema } 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 { 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.MODEL.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 //\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 if (request.providerOptions) {\n Object.assign(openaiRequest, request.providerOptions);\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 // 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 const jsonSchema = z.toJSONSchema(zodSchema) as Record<string, unknown>;\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: responseFormat.json_schema.name,\n schema: jsonSchema as JsonObject,\n strict: responseFormat.json_schema.strict,\n type: responseFormat.type,\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 OpenAI;\n const openaiRequest = request as Record<string, unknown>;\n type CreateParams = Parameters<typeof openai.responses.create>[0];\n try {\n return await openai.responses.create(\n openaiRequest as CreateParams,\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 as CreateParams,\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 OpenAI;\n const baseRequest = request as Record<string, unknown>;\n const streamRequest = {\n ...baseRequest,\n stream: true,\n };\n\n const stream = await openai.responses.create(\n streamRequest as Parameters<typeof openai.responses.create>[0],\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 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 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 // 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 type { OpenRouter } from \"@openrouter/sdk\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.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 { 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 { 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}\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 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 | { type: \"text\"; text: string }\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// OpenRouter SDK 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.MODEL.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 messages: OpenRouterMessage[] = this.convertMessagesToOpenRouter(\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 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 // 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 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 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 OpenRouter;\n const openRouterRequest = request as OpenRouterRequest;\n const wantsStructuredOutput = Boolean(openRouterRequest.response_format);\n\n try {\n const response = (await openRouter.chat.send(\n this.toSdkChatParams(openRouterRequest) as Parameters<\n typeof openRouter.chat.send\n >[0],\n signal ? { signal } : undefined,\n )) 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.chat.send(\n this.toSdkChatParams(retryRequest) as Parameters<\n typeof openRouter.chat.send\n >[0],\n signal ? { signal } : undefined,\n )) 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.chat.send(\n this.toSdkChatParams(fallbackRequest) as Parameters<\n typeof openRouter.chat.send\n >[0],\n signal ? { signal } : undefined,\n )) 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 private toSdkChatParams(\n openRouterRequest: OpenRouterRequest,\n ): Record<string, unknown> {\n const params: Record<string, unknown> = {\n model: openRouterRequest.model,\n messages: openRouterRequest.messages,\n tools: openRouterRequest.tools,\n toolChoice: openRouterRequest.tool_choice,\n user: openRouterRequest.user,\n };\n if (openRouterRequest.response_format) {\n const format = openRouterRequest.response_format;\n if (format.type === \"json_schema\") {\n params.responseFormat = {\n type: \"json_schema\",\n jsonSchema: format.json_schema,\n };\n } else {\n params.responseFormat = format;\n }\n }\n const temperature = (\n openRouterRequest as unknown as { temperature?: number }\n ).temperature;\n if (temperature !== undefined) {\n params.temperature = temperature;\n }\n return params;\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 OpenRouter;\n const openRouterRequest = request as OpenRouterRequest;\n\n // Use chat.send with stream: true for streaming responses.\n // Cast the result to AsyncIterable: when stream: true, the SDK returns a\n // stream we can iterate, but the typed result is the union with the\n // non-stream response.\n const streamParams = {\n ...this.toSdkChatParams(openRouterRequest),\n stream: true,\n };\n const stream = (await openRouter.chat.send(\n streamParams as Parameters<typeof openRouter.chat.send>[0],\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 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 ): 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 // 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 ): OpenRouterMessage[] {\n const openRouterMessages: OpenRouterMessage[] = [];\n\n // Add system message if provided\n if (system) {\n openRouterMessages.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 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 { BadRequestError } from \"openai\";\n\nimport { PROVIDER } from \"../../constants.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 // @ts-expect-error Narrowing override: xAI default model differs from parent's literal\n readonly defaultModel = PROVIDER.XAI.MODEL.DEFAULT;\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 async call({ name, arguments: args }: { name: string; arguments: string }) {\n const tool = this._tools.find((t) => t.name === name);\n if (!tool) {\n throw new Error(`Tool '${name}' not found`);\n }\n\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\n if (this.log !== false) {\n try {\n const context: { name: string; args: any; explanation?: string } = {\n name,\n args: parsedArgs,\n };\n let message: string;\n\n if (this.explain) {\n context.explanation = parsedArgs.__Explanation;\n }\n\n if (tool.message) {\n if (typeof tool.message === \"string\") {\n log.trace(\"[Toolkit] Tool provided string message\");\n message = tool.message;\n } else if (typeof tool.message === \"function\") {\n log.trace(\"[Toolkit] Tool provided function message\");\n log.trace(\"[Toolkit] Resolving message result\");\n message = await resolveValue(tool.message(parsedArgs, { name }));\n } else {\n log.warn(\"[Toolkit] Tool provided unknown message type\");\n message = String(tool.message);\n }\n } else {\n log.trace(\"[Toolkit] Log tool call with default message\");\n message = `${tool.name}:${JSON.stringify(parsedArgs)}`;\n }\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\"\n | \"embedding\"\n | \"llm\"\n | \"retrieval\"\n | \"task\"\n | \"tool\"\n | \"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 toolName: string;\n}\n\nexport interface AfterToolContext {\n args: string;\n result: unknown;\n toolName: string;\n}\n\nexport interface ToolErrorContext {\n args: string;\n error: Error;\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\n | LlmHistory\n | 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 { 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)\n | 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 { sleep } from \"@jaypie/kit\";\nimport { BadGatewayError } from \"@jaypie/errors\";\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\";\n\n//\n//\n// Types\n//\n\nexport interface RetryContext {\n input: unknown;\n options?: unknown;\n providerRequest: unknown;\n}\n\nexport interface ErrorClassifier {\n isRetryable(error: unknown): boolean;\n isKnownError(error: unknown): boolean;\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 * 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 const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new BadGatewayError(errorMessage);\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 const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new BadGatewayError(errorMessage);\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 LlmHistory,\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateInput,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmOutputMessage,\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} from \"../util/index.js\";\nimport { ProviderAdapter } from \"./adapters/ProviderAdapter.interface.js\";\nimport { HookRunner, hookRunner, LlmHooks } from \"./hooks/index.js\";\nimport { InputProcessor, inputProcessor } from \"./input/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 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//\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.var({ \"operate.input\": input });\n log.var({ \"operate.options\": options });\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\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 return 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 format: state.formattedFormat,\n instructions: options.instructions,\n messages: state.currentInput,\n model: modelName,\n providerOptions: options.providerOptions,\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 annotateLlmObs({\n inputData: input,\n metrics: usageToLlmObsMetrics(response.usage),\n outputData: response.content,\n });\n return response;\n },\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 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 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 what was passed to the model\n log.trace(\"[operate] Calling model\");\n log.var({ \"operate.request\": providerRequest });\n\n // Execute beforeEachModelRequest hook\n await this.hookRunnerInstance.runBeforeModelRequest(context.hooks, {\n input: state.currentInput,\n options,\n providerRequest,\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 } = 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 options,\n providerRequest,\n },\n hooks: context.hooks as LlmHooks,\n },\n );\n\n // Log what was returned from the model\n log.trace(\"[operate] Model response received\");\n log.var({ \"operate.response\": response });\n\n // Parse response\n const parsed = this.adapter.parseResponse(response, options);\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 };\n },\n );\n\n // Track usage\n if (parsed.usage) {\n state.responseBuilder.addUsage(parsed.usage);\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 const toolCalls = this.adapter.extractToolCalls(response);\n\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 try {\n // Execute beforeEachTool hook\n await this.hookRunnerInstance.runBeforeTool(context.hooks, {\n args: toolCall.arguments,\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 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 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 // Execute onToolError hook\n await this.hookRunnerInstance.runOnToolError(context.hooks, {\n args: toolCall.arguments,\n error: error as Error,\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 // 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 * Backfill declared array fields when a `format` is supplied. A declared\n * `format` is a schema contract: an empty array field should surface as `[]`\n * rather than be dropped by a provider/model that omits empty lists.\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 return fillFormatArrays({ content, 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 { 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 } 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 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 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 } else {\n break;\n }\n }\n\n // Emit final done chunk with accumulated usage\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 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 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 *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 const errorMessage =\n error instanceof Error ? error.message : String(error);\n llmSpan?.finish();\n throw new BadGatewayError(errorMessage);\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>\n | 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 try {\n // Execute beforeEachTool hook\n await this.hookRunnerInstance.runBeforeTool(context.hooks, {\n args: toolCall.arguments,\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 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 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 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 { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { log as defaultLog, log } from \"@jaypie/logger\";\nimport type Anthropic from \"@anthropic-ai/sdk\";\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\";\n\n// SDK loader with caching\nlet cachedSdk: typeof import(\"@anthropic-ai/sdk\") | null = null;\n\nexport async function loadSdk(): Promise<typeof import(\"@anthropic-ai/sdk\")> {\n if (cachedSdk) return cachedSdk;\n try {\n cachedSdk = await import(\"@anthropic-ai/sdk\");\n return cachedSdk;\n } catch {\n throw new ConfigurationError(\n \"@anthropic-ai/sdk is required but not installed. Run: npm install @anthropic-ai/sdk\",\n );\n }\n}\n\n// Logger\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<Anthropic> {\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 sdk = await loadSdk();\n const client = new sdk.default({ 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: Anthropic,\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: Anthropic,\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 { 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","import type Anthropic from \"@anthropic-ai/sdk\";\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?: Anthropic;\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.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<Anthropic> {\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 { 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 = () => 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.MODEL.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 { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { log as defaultLog } from \"@jaypie/logger\";\nimport type { GoogleGenAI } from \"@google/genai\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\n\n// SDK loader with caching\nlet cachedSdk: typeof import(\"@google/genai\") | null = null;\n\nexport async function loadSdk(): Promise<typeof import(\"@google/genai\")> {\n if (cachedSdk) return cachedSdk;\n try {\n cachedSdk = await import(\"@google/genai\");\n return cachedSdk;\n } catch {\n throw new ConfigurationError(\n \"@google/genai is required but not installed. Run: npm install @google/genai\",\n );\n }\n}\n\n// Logger\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<GoogleGenAI> {\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 sdk = await loadSdk();\n const client = new sdk.GoogleGenAI({ 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 { GoogleGenAI } from \"@google/genai\";\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?: GoogleGenAI;\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.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<GoogleGenAI> {\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 { log as defaultLog } from \"@jaypie/logger\";\nimport { JsonObject, NaturalSchema } from \"@jaypie/types\";\nimport { OpenAI } from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod/v4\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { naturalZodSchema } from \"../../util\";\n\n// Logger\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenAI> {\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 OpenAI({ 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: OpenAI,\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;\n\n const completion = await client.chat.completions.parse({\n messages,\n model,\n response_format: responseFormat,\n });\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: OpenAI,\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 });\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 { OpenAI } from \"openai\";\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 {\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?: OpenAI;\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.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenAI> {\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 { getEnvSecret } from \"@jaypie/aws\";\nimport { ConfigurationError } from \"@jaypie/errors\";\nimport { JAYPIE, placeholders as replacePlaceholders } from \"@jaypie/kit\";\nimport { log as defaultLog } from \"@jaypie/logger\";\nimport type { OpenRouter } from \"@openrouter/sdk\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { PROVIDER } from \"../../constants.js\";\n\n// SDK loader with caching\nlet cachedSdk: typeof import(\"@openrouter/sdk\") | null = null;\n\nexport async function loadSdk(): Promise<typeof import(\"@openrouter/sdk\")> {\n if (cachedSdk) return cachedSdk;\n try {\n cachedSdk = await import(\"@openrouter/sdk\");\n return cachedSdk;\n } catch {\n throw new ConfigurationError(\n \"@openrouter/sdk is required but not installed. Run: npm install @openrouter/sdk\",\n );\n }\n}\n\n// Logger\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenRouter> {\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 sdk = await loadSdk();\n const client = new sdk.OpenRouter({ 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.MODEL.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 { OpenRouter } from \"@openrouter/sdk\";\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?: OpenRouter;\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<OpenRouter> {\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 // Build the request\n const response = await client.chat.send({\n model: modelToUse,\n messages: messages as Parameters<typeof client.chat.send>[0][\"messages\"],\n });\n\n const rawContent = response.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 { log as defaultLog } from \"@jaypie/logger\";\nimport { OpenAI } from \"openai\";\n\nimport { PROVIDER } from \"../../constants.js\";\n\n// Logger\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\n// Client initialization\nexport async function initializeClient({\n apiKey,\n}: {\n apiKey?: string;\n} = {}): Promise<OpenAI> {\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 OpenAI({\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 { OpenAI } from \"openai\";\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 {\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?: OpenAI;\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.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenAI> {\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 {\n LlmFallbackConfig,\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\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 { 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: LlmOptions = {},\n ) {\n const { fallback, model } = options;\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(\n model || PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n { apiKey },\n );\n case PROVIDER.BEDROCK.NAME:\n return new BedrockProvider(model || PROVIDER.BEDROCK.MODEL.DEFAULT);\n case PROVIDER.GOOGLE.NAME:\n return new GoogleProvider(model || PROVIDER.GOOGLE.MODEL.DEFAULT, {\n apiKey,\n });\n case PROVIDER.OPENAI.NAME:\n return new OpenAiProvider(model || PROVIDER.OPENAI.MODEL.DEFAULT, {\n apiKey,\n });\n case PROVIDER.OPENROUTER.NAME:\n return new OpenRouterProvider(\n model || PROVIDER.OPENROUTER.MODEL.DEFAULT,\n {\n apiKey,\n },\n );\n case PROVIDER.XAI.NAME:\n return new XaiProvider(model || PROVIDER.XAI.MODEL.DEFAULT, {\n apiKey,\n });\n default:\n throw new ConfigurationError(`Unsupported provider: ${providerName}`);\n }\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n return this._llm.send(message, options);\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: LlmOperateOptions = {},\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 const fallbackChain = this.resolveFallbackChain(options);\n const optionsWithoutFallback = { ...options, fallback: false as const };\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 return {\n ...response,\n fallbackAttempts: attempts,\n fallbackUsed: false,\n provider: response.provider || this._provider,\n };\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\n for (const fallbackConfig of fallbackChain) {\n attempts++;\n try {\n const fallbackInstance = this.createFallbackInstance(fallbackConfig);\n const response = await fallbackInstance.operate(\n input,\n optionsWithoutFallback,\n );\n return {\n ...response,\n fallbackAttempts: attempts,\n fallbackUsed: true,\n provider: response.provider || fallbackConfig.provider,\n };\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, throw the last error\n throw lastError;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n if (!this._llm.stream) {\n throw new NotImplementedError(\n `Provider ${this._provider} does not support stream method`,\n );\n }\n yield* this._llm.stream(input, options);\n }\n\n static async send(\n message: string,\n options?: LlmMessageOptions & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string;\n },\n ): Promise<string | JsonObject> {\n const { llm, apiKey, model, ...messageOptions } = options || {};\n const instance = new Llm(llm, { apiKey, model });\n return instance.send(message, messageOptions);\n }\n\n static async operate(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options?: LlmOperateOptions & {\n apiKey?: string;\n fallback?: LlmFallbackConfig[] | false;\n llm?: LlmProviderName;\n model?: string;\n },\n ): Promise<LlmOperateResponse> {\n const { apiKey, fallback, llm, model, ...operateOptions } = options || {};\n\n let finalLlm = llm;\n let finalModel = model;\n\n if (!llm && model) {\n const determined = determineModelProvider(model);\n if (determined.provider) {\n finalLlm = determined.provider as LlmProviderName;\n }\n } else if (llm && model) {\n // When both llm and model are provided, check if they conflict\n const determined = determineModelProvider(model);\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 instanceFallback = Array.isArray(fallback) ? fallback : 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?: LlmOperateOptions & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string;\n },\n ): AsyncIterable<LlmStreamChunk> {\n const { llm, apiKey, model, ...streamOptions } = options || {};\n\n let finalLlm = llm;\n let finalModel = model;\n\n if (!llm && model) {\n const determined = determineModelProvider(model);\n if (determined.provider) {\n finalLlm = determined.provider as LlmProviderName;\n }\n } else if (llm && model) {\n // When both llm and model are provided, check if they conflict\n const determined = determineModelProvider(model);\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, { apiKey, model: finalModel });\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 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":["getLogger","defaultLog","random","STRUCTURED_OUTPUT_TOOL_NAME","DATA_URL_REGEX","MODELS_WITHOUT_TEMPERATURE","isTemperatureDeprecationError","isStructuredOutputUnsupportedError","log","RETRYABLE_STATUS_CODES","jaypieLog","cachedSdk","defaultHookRunner","ERROR","loadSdk","initializeClient","formatSystemMessage","placeholders","replacePlaceholders","formatUserMessage","prepareMessages","createTextCompletion","createStructuredCompletion","randomUtil"],"mappings":";;;;;;;;;;;;;;;AAAA,MAAM,oBAAoB,GAAG;;AAE3B,IAAA,SAAS,EAAE;AACT,QAAA,OAAO,EAAE,mBAA4B;AACrC,QAAA,KAAK,EAAE,iBAA0B;AACjC,QAAA,KAAK,EAAE,mBAA4B;AACnC,QAAA,IAAI,EAAE,kBAA2B;AAClC,KAAA;;AAED,IAAA,MAAM,EAAE;AACN,QAAA,OAAO,EAAE,wBAAiC;AAC1C,QAAA,KAAK,EAAE,wBAAiC;AACxC,QAAA,KAAK,EAAE,kBAA2B;AAClC,QAAA,IAAI,EAAE,uBAAgC;AACvC,KAAA;;AAED,IAAA,MAAM,EAAE;AACN,QAAA,OAAO,EAAE,SAAkB;AAC3B,QAAA,KAAK,EAAE,SAAkB;AACzB,QAAA,KAAK,EAAE,cAAuB;AAC9B,QAAA,IAAI,EAAE,cAAuB;AAC9B,KAAA;;AAED,IAAA,GAAG,EAAE;AACH,QAAA,OAAO,EAAE,aAAsB;AAC/B,QAAA,KAAK,EAAE,iBAA0B;AACjC,QAAA,KAAK,EAAE,yBAAkC;AACzC,QAAA,IAAI,EAAE,6BAAsC;A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constants.ts","../../../src/util/determineModelProvider.ts","../../../src/operate/adapters/ProviderAdapter.interface.ts","../../../src/types/LlmProvider.interface.ts","../../../src/types/LlmStreamChunk.interface.ts","../../../src/util/extractReasoning.ts","../../../src/util/naturalZodSchema.ts","../../../src/util/fillFormatArrays.ts","../../../src/util/formatOperateMessage.ts","../../../src/util/formatOperateInput.ts","../../../src/util/jsonSchemaToOpenApi3.ts","../../../src/util/logger.ts","../../../src/util/maxTurnsFromOptions.ts","../../../src/util/random.ts","../../../src/util/tryParseNumber.ts","../../../src/operate/types.ts","../../../src/operate/retry/isTransientNetworkError.ts","../../../src/operate/adapters/AnthropicAdapter.ts","../../../src/operate/adapters/BedrockAdapter.ts","../../../src/operate/adapters/GoogleAdapter.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/response/ResponseBuilder.ts","../../../src/operate/retry/RetryPolicy.ts","../../../src/operate/retry/createStaleRejectionGuard.ts","../../../src/operate/retry/RetryExecutor.ts","../../../src/operate/OperateLoop.ts","../../../src/operate/StreamLoop.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/google/utils.ts","../../../src/providers/google/GoogleProvider.class.ts","../../../src/providers/openai/utils.ts","../../../src/providers/openai/OpenAiProvider.class.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":["const FIRST_CLASS_PROVIDER = {\n // https://docs.anthropic.com/en/docs/about-claude/models/overview\n ANTHROPIC: {\n DEFAULT: \"claude-sonnet-4-6\" as const,\n LARGE: \"claude-opus-4-8\" as const,\n SMALL: \"claude-sonnet-4-6\" as const,\n TINY: \"claude-haiku-4-5\" as const,\n },\n // https://ai.google.dev/gemini-api/docs/models\n GOOGLE: {\n DEFAULT: \"gemini-3.1-pro-preview\" as const,\n LARGE: \"gemini-3.1-pro-preview\" as const,\n SMALL: \"gemini-3.5-flash\" as const,\n TINY: \"gemini-3.1-flash-lite\" as const,\n },\n // https://developers.openai.com/api/docs/models\n OPENAI: {\n DEFAULT: \"gpt-5.4\" as const,\n LARGE: \"gpt-5.5\" as const,\n SMALL: \"gpt-5.4-mini\" as const,\n TINY: \"gpt-5.4-nano\" as const,\n },\n // https://docs.x.ai/developers/models\n XAI: {\n DEFAULT: \"grok-latest\" as const,\n LARGE: \"grok-4.3-latest\" as const,\n SMALL: \"grok-4-1-fast-reasoning\" as const,\n TINY: \"grok-4-1-fast-non-reasoning\" as const,\n },\n};\n\nexport const MODEL = {\n // Anthropic\n OPUS: \"claude-opus-4-8\",\n SONNET: \"claude-sonnet-4-6\",\n HAIKU: \"claude-haiku-4-5\",\n FABLE: \"claude-fable-5\",\n MYTHOS: \"claude-mythos-5\",\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 GPT: \"gpt-5.5\",\n GPT_MINI: \"gpt-5.4-mini\",\n GPT_NANO: \"gpt-5.4-nano\",\n // xAI\n GROK: \"grok-latest\",\n};\n\nconst GOOGLE_PROVIDER = {\n // https://ai.google.dev/gemini-api/docs/models\n MODEL: {\n DEFAULT: FIRST_CLASS_PROVIDER.GOOGLE.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.GOOGLE.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.GOOGLE.SMALL,\n TINY: FIRST_CLASS_PROVIDER.GOOGLE.TINY,\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 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 MAX_TOKENS: {\n DEFAULT: 4096 as const,\n },\n MODEL: {\n DEFAULT: FIRST_CLASS_PROVIDER.ANTHROPIC.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.ANTHROPIC.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.ANTHROPIC.SMALL,\n TINY: FIRST_CLASS_PROVIDER.ANTHROPIC.TINY,\n },\n MODEL_MATCH_WORDS: [\n \"anthropic\",\n \"claude\",\n \"haiku\",\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 /** @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 MODEL: {\n DEFAULT: FIRST_CLASS_PROVIDER.OPENAI.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.OPENAI.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.OPENAI.SMALL,\n TINY: FIRST_CLASS_PROVIDER.OPENAI.TINY,\n },\n MODEL_MATCH_WORDS: [\"openai\", \"gpt\", /^o\\d/],\n NAME: \"openai\" as const,\n },\n OPENROUTER: {\n MODEL: {\n DEFAULT: `anthropic/${FIRST_CLASS_PROVIDER.ANTHROPIC.DEFAULT}` as const,\n LARGE: `anthropic/${FIRST_CLASS_PROVIDER.ANTHROPIC.LARGE}` as const,\n SMALL: `anthropic/${FIRST_CLASS_PROVIDER.ANTHROPIC.SMALL}` as const,\n TINY: `anthropic/${FIRST_CLASS_PROVIDER.ANTHROPIC.TINY}` 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 MODEL: {\n DEFAULT: FIRST_CLASS_PROVIDER.XAI.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.XAI.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.XAI.SMALL,\n TINY: FIRST_CLASS_PROVIDER.XAI.TINY,\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.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 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// 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.MODEL.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 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.MODEL.DEFAULT,\n provider: PROVIDER.BEDROCK.NAME,\n };\n }\n if (input === PROVIDER.ANTHROPIC.NAME) {\n return {\n model: PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n provider: PROVIDER.ANTHROPIC.NAME,\n };\n }\n if (input === PROVIDER.GOOGLE.NAME || input === \"gemini\") {\n return {\n model: PROVIDER.GOOGLE.MODEL.DEFAULT,\n provider: PROVIDER.GOOGLE.NAME,\n };\n }\n if (input === PROVIDER.OPENAI.NAME) {\n return {\n model: PROVIDER.OPENAI.MODEL.DEFAULT,\n provider: PROVIDER.OPENAI.NAME,\n };\n }\n if (input === PROVIDER.OPENROUTER.NAME) {\n return {\n model: PROVIDER.OPENROUTER.MODEL.DEFAULT,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n if (input === PROVIDER.XAI.NAME) {\n return {\n model: PROVIDER.XAI.MODEL.DEFAULT,\n provider: PROVIDER.XAI.NAME,\n };\n }\n\n // Check if input matches an Anthropic model exactly\n for (const [, modelValue] of Object.entries(PROVIDER.ANTHROPIC.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.ANTHROPIC.NAME,\n };\n }\n }\n\n // Check if input matches a Gemini model exactly\n for (const [, modelValue] of Object.entries(PROVIDER.GOOGLE.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.GOOGLE.NAME,\n };\n }\n }\n\n // Check if input matches an OpenAI model exactly\n for (const [, modelValue] of Object.entries(PROVIDER.OPENAI.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.OPENAI.NAME,\n };\n }\n }\n\n // Check if input matches an OpenRouter model exactly\n for (const [, modelValue] of Object.entries(PROVIDER.OPENROUTER.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.OPENROUTER.NAME,\n };\n }\n }\n\n // Check if input matches an xAI model exactly\n for (const [, modelValue] of Object.entries(PROVIDER.XAI.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.XAI.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 { 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 // 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 * 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\n extractStructuredOutput(_response: unknown): JsonObject | undefined {\n return undefined;\n }\n}\n","import {\n AnyValue,\n JsonObject,\n JsonReturn,\n NaturalMap,\n NaturalSchema,\n} from \"@jaypie/types\";\nimport { z } from \"zod/v4\";\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\ninterface 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\n | LlmInputContentImage\n | 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\n | LlmOperateInputFile\n | 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\n | LlmItemReference\n | LlmOutputItem\n | 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\nexport interface LlmOperateOptions {\n data?: NaturalMap;\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 }: {\n result: unknown;\n toolName: string;\n args: 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 }: {\n toolName: string;\n args: 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 }: {\n error: Error;\n toolName: string;\n args: 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 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\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 provider?: string;\n model?: string;\n}\n\nexport type LlmUsage = LlmUsageItem[];\n\nexport interface LlmOperateResponse {\n content?: string | JsonObject;\n error?: LlmError;\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 { 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 { 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 { 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 { 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 { 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","/**\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 { JsonObject } from \"@jaypie/types\";\n\nimport {\n LlmHistory,\n LlmInputMessage,\n LlmMessageType,\n LlmOperateOptions,\n LlmResponseStatus,\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 /** Provider-specific options */\n providerOptions?: JsonObject;\n /** Sampling temperature (0-2 for most providers) */\n temperature?: number;\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 rate limiting */\n RateLimit = \"rate_limit\",\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\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 /** 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 /** Formatted tools for the provider */\n formattedTools?: ProviderToolDefinition[];\n /** Maximum allowed turns */\n maxTurns: number;\n /** Response builder instance */\n responseBuilder: ResponseBuilder;\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 type { Anthropic } from \"@anthropic-ai/sdk\";\nimport log from \"@jaypie/logger\";\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 { 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 { 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 format: {\n type: \"json_schema\";\n schema: JsonObject;\n };\n };\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.MODEL.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 anthropicRequest: AnthropicRequestParams = {\n model: (request.model ||\n this.defaultModel) as Anthropic.MessageCreateParams[\"model\"],\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n stream: false,\n };\n\n if (request.system) {\n anthropicRequest.system = 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) => ({\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 }));\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 // 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 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 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 Anthropic;\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) return request;\n const fallbackRequest: AnthropicRequestParams = { ...rest };\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 Anthropic;\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 };\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 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 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 { 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 { 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 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.MODEL.DEFAULT;\n\n private _modelsFallbackToStructuredOutputTool = new Set<string>();\n private _modelsWithoutTemperature = new Set<string>();\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 if (request.providerOptions) {\n Object.assign(bedrockRequest, request.providerOptions);\n }\n\n return bedrockRequest;\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 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 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;\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 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 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 }\n | 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 }\n | undefined;\n\n return textBlock?.text;\n }\n}\n\nexport const bedrockAdapter = new BedrockAdapter();\n","import type { GoogleGenAI } from \"@google/genai\";\nimport log from \"@jaypie/logger\";\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 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 { jsonSchemaToOpenApi3, 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 { 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/**\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.MODEL.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 // Add provider-specific options\n if (request.providerOptions) {\n geminiRequest.config = {\n ...geminiRequest.config,\n ...request.providerOptions,\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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 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 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 GoogleGenAI;\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 GoogleGenAI;\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 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, NaturalSchema } from \"@jaypie/types\";\nimport {\n APIConnectionError,\n APIConnectionTimeoutError,\n APIUserAbortError,\n AuthenticationError,\n BadRequestError,\n ConflictError,\n InternalServerError,\n NotFoundError,\n OpenAI,\n PermissionDeniedError,\n RateLimitError,\n UnprocessableEntityError,\n} from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.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 { naturalZodSchema } 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 { 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.MODEL.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 //\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 if (request.providerOptions) {\n Object.assign(openaiRequest, request.providerOptions);\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 // 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 const jsonSchema = z.toJSONSchema(zodSchema) as Record<string, unknown>;\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: responseFormat.json_schema.name,\n schema: jsonSchema as JsonObject,\n strict: responseFormat.json_schema.strict,\n type: responseFormat.type,\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 OpenAI;\n const openaiRequest = request as Record<string, unknown>;\n type CreateParams = Parameters<typeof openai.responses.create>[0];\n try {\n return await openai.responses.create(\n openaiRequest as CreateParams,\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 as CreateParams,\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 OpenAI;\n const baseRequest = request as Record<string, unknown>;\n const streamRequest = {\n ...baseRequest,\n stream: true,\n };\n\n const stream = await openai.responses.create(\n streamRequest as Parameters<typeof openai.responses.create>[0],\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 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 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 // 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 type { OpenRouter } from \"@openrouter/sdk\";\nimport { z } from \"zod/v4\";\n\nimport { PROVIDER } from \"../../constants.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 { 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 { 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}\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 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 | { type: \"text\"; text: string }\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// OpenRouter SDK 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.MODEL.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 messages: OpenRouterMessage[] = this.convertMessagesToOpenRouter(\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 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 // 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 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 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 OpenRouter;\n const openRouterRequest = request as OpenRouterRequest;\n const wantsStructuredOutput = Boolean(openRouterRequest.response_format);\n\n try {\n const response = (await openRouter.chat.send(\n this.toSdkChatParams(openRouterRequest) as Parameters<\n typeof openRouter.chat.send\n >[0],\n signal ? { signal } : undefined,\n )) 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.chat.send(\n this.toSdkChatParams(retryRequest) as Parameters<\n typeof openRouter.chat.send\n >[0],\n signal ? { signal } : undefined,\n )) 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.chat.send(\n this.toSdkChatParams(fallbackRequest) as Parameters<\n typeof openRouter.chat.send\n >[0],\n signal ? { signal } : undefined,\n )) 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 private toSdkChatParams(\n openRouterRequest: OpenRouterRequest,\n ): Record<string, unknown> {\n const params: Record<string, unknown> = {\n model: openRouterRequest.model,\n messages: openRouterRequest.messages,\n tools: openRouterRequest.tools,\n toolChoice: openRouterRequest.tool_choice,\n user: openRouterRequest.user,\n };\n if (openRouterRequest.response_format) {\n const format = openRouterRequest.response_format;\n if (format.type === \"json_schema\") {\n params.responseFormat = {\n type: \"json_schema\",\n jsonSchema: format.json_schema,\n };\n } else {\n params.responseFormat = format;\n }\n }\n const temperature = (\n openRouterRequest as unknown as { temperature?: number }\n ).temperature;\n if (temperature !== undefined) {\n params.temperature = temperature;\n }\n return params;\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 OpenRouter;\n const openRouterRequest = request as OpenRouterRequest;\n\n // Use chat.send with stream: true for streaming responses.\n // Cast the result to AsyncIterable: when stream: true, the SDK returns a\n // stream we can iterate, but the typed result is the union with the\n // non-stream response.\n const streamParams = {\n ...this.toSdkChatParams(openRouterRequest),\n stream: true,\n };\n const stream = (await openRouter.chat.send(\n streamParams as Parameters<typeof openRouter.chat.send>[0],\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 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 ): 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 // 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 ): OpenRouterMessage[] {\n const openRouterMessages: OpenRouterMessage[] = [];\n\n // Add system message if provided\n if (system) {\n openRouterMessages.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 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 { BadRequestError } from \"openai\";\n\nimport { PROVIDER } from \"../../constants.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 // @ts-expect-error Narrowing override: xAI default model differs from parent's literal\n readonly defaultModel = PROVIDER.XAI.MODEL.DEFAULT;\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 async call({ name, arguments: args }: { name: string; arguments: string }) {\n const tool = this._tools.find((t) => t.name === name);\n if (!tool) {\n throw new Error(`Tool '${name}' not found`);\n }\n\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\n if (this.log !== false) {\n try {\n const context: { name: string; args: any; explanation?: string } = {\n name,\n args: parsedArgs,\n };\n let message: string;\n\n if (this.explain) {\n context.explanation = parsedArgs.__Explanation;\n }\n\n if (tool.message) {\n if (typeof tool.message === \"string\") {\n log.trace(\"[Toolkit] Tool provided string message\");\n message = tool.message;\n } else if (typeof tool.message === \"function\") {\n log.trace(\"[Toolkit] Tool provided function message\");\n log.trace(\"[Toolkit] Resolving message result\");\n message = await resolveValue(tool.message(parsedArgs, { name }));\n } else {\n log.warn(\"[Toolkit] Tool provided unknown message type\");\n message = String(tool.message);\n }\n } else {\n log.trace(\"[Toolkit] Log tool call with default message\");\n message = `${tool.name}:${JSON.stringify(parsedArgs)}`;\n }\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\"\n | \"embedding\"\n | \"llm\"\n | \"retrieval\"\n | \"task\"\n | \"tool\"\n | \"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 toolName: string;\n}\n\nexport interface AfterToolContext {\n args: string;\n result: unknown;\n toolName: string;\n}\n\nexport interface ToolErrorContext {\n args: string;\n error: Error;\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\n | LlmHistory\n | 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 { 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)\n | 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 { sleep } from \"@jaypie/kit\";\nimport { BadGatewayError } from \"@jaypie/errors\";\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\";\n\n//\n//\n// Types\n//\n\nexport interface RetryContext {\n input: unknown;\n options?: unknown;\n providerRequest: unknown;\n}\n\nexport interface ErrorClassifier {\n isRetryable(error: unknown): boolean;\n isKnownError(error: unknown): boolean;\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 * 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 const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new BadGatewayError(errorMessage);\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 const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new BadGatewayError(errorMessage);\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 LlmHistory,\n LlmInputMessage,\n LlmMessageRole,\n LlmMessageType,\n LlmOperateInput,\n LlmOperateOptions,\n LlmOperateResponse,\n LlmOutputMessage,\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} from \"../util/index.js\";\nimport { ProviderAdapter } from \"./adapters/ProviderAdapter.interface.js\";\nimport { HookRunner, hookRunner, LlmHooks } from \"./hooks/index.js\";\nimport { InputProcessor, inputProcessor } from \"./input/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 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//\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.var({ \"operate.input\": input });\n log.var({ \"operate.options\": options });\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\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 return 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 format: state.formattedFormat,\n instructions: options.instructions,\n messages: state.currentInput,\n model: modelName,\n providerOptions: options.providerOptions,\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 annotateLlmObs({\n inputData: input,\n metrics: usageToLlmObsMetrics(response.usage),\n outputData: response.content,\n });\n return response;\n },\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 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 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 what was passed to the model\n log.trace(\"[operate] Calling model\");\n log.var({ \"operate.request\": providerRequest });\n\n // Execute beforeEachModelRequest hook\n await this.hookRunnerInstance.runBeforeModelRequest(context.hooks, {\n input: state.currentInput,\n options,\n providerRequest,\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 } = 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 options,\n providerRequest,\n },\n hooks: context.hooks as LlmHooks,\n },\n );\n\n // Log what was returned from the model\n log.trace(\"[operate] Model response received\");\n log.var({ \"operate.response\": response });\n\n // Parse response\n const parsed = this.adapter.parseResponse(response, options);\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 };\n },\n );\n\n // Track usage\n if (parsed.usage) {\n state.responseBuilder.addUsage(parsed.usage);\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 const toolCalls = this.adapter.extractToolCalls(response);\n\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 try {\n // Execute beforeEachTool hook\n await this.hookRunnerInstance.runBeforeTool(context.hooks, {\n args: toolCall.arguments,\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 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 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 // Execute onToolError hook\n await this.hookRunnerInstance.runOnToolError(context.hooks, {\n args: toolCall.arguments,\n error: error as Error,\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 // 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 * Backfill declared array fields when a `format` is supplied. A declared\n * `format` is a schema contract: an empty array field should surface as `[]`\n * rather than be dropped by a provider/model that omits empty lists.\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 return fillFormatArrays({ content, 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 { 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 } 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 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 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 } else {\n break;\n }\n }\n\n // Emit final done chunk with accumulated usage\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 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 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 *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 const errorMessage =\n error instanceof Error ? error.message : String(error);\n llmSpan?.finish();\n throw new BadGatewayError(errorMessage);\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>\n | 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 try {\n // Execute beforeEachTool hook\n await this.hookRunnerInstance.runBeforeTool(context.hooks, {\n args: toolCall.arguments,\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 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 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 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 { 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 type Anthropic from \"@anthropic-ai/sdk\";\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\";\n\n// SDK loader with caching\nlet cachedSdk: typeof import(\"@anthropic-ai/sdk\") | null = null;\n\nexport async function loadSdk(): Promise<typeof import(\"@anthropic-ai/sdk\")> {\n if (cachedSdk) return cachedSdk;\n try {\n cachedSdk = await import(\"@anthropic-ai/sdk\");\n return cachedSdk;\n } catch {\n throw new ConfigurationError(\n \"@anthropic-ai/sdk is required but not installed. Run: npm install @anthropic-ai/sdk\",\n );\n }\n}\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<Anthropic> {\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 sdk = await loadSdk();\n const client = new sdk.default({ 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: Anthropic,\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: Anthropic,\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 { 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","import type Anthropic from \"@anthropic-ai/sdk\";\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?: Anthropic;\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.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<Anthropic> {\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.MODEL.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 { 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 type { GoogleGenAI } from \"@google/genai\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\n\n// SDK loader with caching\nlet cachedSdk: typeof import(\"@google/genai\") | null = null;\n\nexport async function loadSdk(): Promise<typeof import(\"@google/genai\")> {\n if (cachedSdk) return cachedSdk;\n try {\n cachedSdk = await import(\"@google/genai\");\n return cachedSdk;\n } catch {\n throw new ConfigurationError(\n \"@google/genai is required but not installed. Run: npm install @google/genai\",\n );\n }\n}\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<GoogleGenAI> {\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 sdk = await loadSdk();\n const client = new sdk.GoogleGenAI({ 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 { GoogleGenAI } from \"@google/genai\";\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?: GoogleGenAI;\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.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<GoogleGenAI> {\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 { OpenAI } from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod/v4\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { naturalZodSchema } from \"../../util\";\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<OpenAI> {\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 OpenAI({ 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: OpenAI,\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;\n\n const completion = await client.chat.completions.parse({\n messages,\n model,\n response_format: responseFormat,\n });\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: OpenAI,\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 });\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 { OpenAI } from \"openai\";\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 {\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?: OpenAI;\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.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenAI> {\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 { 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 type { OpenRouter } from \"@openrouter/sdk\";\nimport { LlmMessageOptions } from \"../../types/LlmProvider.interface.js\";\nimport { PROVIDER } from \"../../constants.js\";\n\n// SDK loader with caching\nlet cachedSdk: typeof import(\"@openrouter/sdk\") | null = null;\n\nexport async function loadSdk(): Promise<typeof import(\"@openrouter/sdk\")> {\n if (cachedSdk) return cachedSdk;\n try {\n cachedSdk = await import(\"@openrouter/sdk\");\n return cachedSdk;\n } catch {\n throw new ConfigurationError(\n \"@openrouter/sdk is required but not installed. Run: npm install @openrouter/sdk\",\n );\n }\n}\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<OpenRouter> {\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 sdk = await loadSdk();\n const client = new sdk.OpenRouter({ 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.MODEL.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 { OpenRouter } from \"@openrouter/sdk\";\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?: OpenRouter;\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<OpenRouter> {\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 // Build the request\n const response = await client.chat.send({\n model: modelToUse,\n messages: messages as Parameters<typeof client.chat.send>[0][\"messages\"],\n });\n\n const rawContent = response.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\";\nimport { OpenAI } from \"openai\";\n\nimport { PROVIDER } from \"../../constants.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<OpenAI> {\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 OpenAI({\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 { OpenAI } from \"openai\";\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 {\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?: OpenAI;\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.MODEL.DEFAULT,\n { apiKey }: { apiKey?: string } = {},\n ) {\n this.model = model;\n this.apiKey = apiKey;\n }\n\n private async getClient(): Promise<OpenAI> {\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 {\n LlmFallbackConfig,\n LlmHistory,\n LlmInputMessage,\n LlmMessageOptions,\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 { 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: LlmOptions = {},\n ) {\n const { fallback, model } = options;\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(\n model || PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n { apiKey },\n );\n case PROVIDER.BEDROCK.NAME:\n return new BedrockProvider(model || PROVIDER.BEDROCK.MODEL.DEFAULT);\n case PROVIDER.GOOGLE.NAME:\n return new GoogleProvider(model || PROVIDER.GOOGLE.MODEL.DEFAULT, {\n apiKey,\n });\n case PROVIDER.OPENAI.NAME:\n return new OpenAiProvider(model || PROVIDER.OPENAI.MODEL.DEFAULT, {\n apiKey,\n });\n case PROVIDER.OPENROUTER.NAME:\n return new OpenRouterProvider(\n model || PROVIDER.OPENROUTER.MODEL.DEFAULT,\n {\n apiKey,\n },\n );\n case PROVIDER.XAI.NAME:\n return new XaiProvider(model || PROVIDER.XAI.MODEL.DEFAULT, {\n apiKey,\n });\n default:\n throw new ConfigurationError(`Unsupported provider: ${providerName}`);\n }\n }\n\n async send(\n message: string,\n options?: LlmMessageOptions,\n ): Promise<string | JsonObject> {\n return this._llm.send(message, options);\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: LlmOperateOptions = {},\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 const fallbackChain = this.resolveFallbackChain(options);\n const optionsWithoutFallback = { ...options, fallback: false as const };\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 return {\n ...response,\n fallbackAttempts: attempts,\n fallbackUsed: false,\n provider: response.provider || this._provider,\n };\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\n for (const fallbackConfig of fallbackChain) {\n attempts++;\n try {\n const fallbackInstance = this.createFallbackInstance(fallbackConfig);\n const response = await fallbackInstance.operate(\n input,\n optionsWithoutFallback,\n );\n return {\n ...response,\n fallbackAttempts: attempts,\n fallbackUsed: true,\n provider: response.provider || fallbackConfig.provider,\n };\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, throw the last error\n throw lastError;\n }\n\n async *stream(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options: LlmOperateOptions = {},\n ): AsyncIterable<LlmStreamChunk> {\n if (!this._llm.stream) {\n throw new NotImplementedError(\n `Provider ${this._provider} does not support stream method`,\n );\n }\n yield* this._llm.stream(input, options);\n }\n\n static async send(\n message: string,\n options?: LlmMessageOptions & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string;\n },\n ): Promise<string | JsonObject> {\n const { llm, apiKey, model, ...messageOptions } = options || {};\n const instance = new Llm(llm, { apiKey, model });\n return instance.send(message, messageOptions);\n }\n\n static async operate(\n input: string | LlmHistory | LlmInputMessage | LlmOperateInput,\n options?: LlmOperateOptions & {\n apiKey?: string;\n fallback?: LlmFallbackConfig[] | false;\n llm?: LlmProviderName;\n model?: string;\n },\n ): Promise<LlmOperateResponse> {\n const { apiKey, fallback, llm, model, ...operateOptions } = options || {};\n\n let finalLlm = llm;\n let finalModel = model;\n\n if (!llm && model) {\n const determined = determineModelProvider(model);\n if (determined.provider) {\n finalLlm = determined.provider as LlmProviderName;\n }\n } else if (llm && model) {\n // When both llm and model are provided, check if they conflict\n const determined = determineModelProvider(model);\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 instanceFallback = Array.isArray(fallback) ? fallback : 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?: LlmOperateOptions & {\n llm?: LlmProviderName;\n apiKey?: string;\n model?: string;\n },\n ): AsyncIterable<LlmStreamChunk> {\n const { llm, apiKey, model, ...streamOptions } = options || {};\n\n let finalLlm = llm;\n let finalModel = model;\n\n if (!llm && model) {\n const determined = determineModelProvider(model);\n if (determined.provider) {\n finalLlm = determined.provider as LlmProviderName;\n }\n } else if (llm && model) {\n // When both llm and model are provided, check if they conflict\n const determined = determineModelProvider(model);\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, { apiKey, model: finalModel });\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 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":["getLogger","defaultLog","random","STRUCTURED_OUTPUT_TOOL_NAME","DATA_URL_REGEX","MODELS_WITHOUT_TEMPERATURE","isTemperatureDeprecationError","isStructuredOutputUnsupportedError","log","RETRYABLE_STATUS_CODES","jaypieLog","cachedSdk","defaultHookRunner","ERROR","loadSdk","initializeClient","formatSystemMessage","placeholders","replacePlaceholders","formatUserMessage","prepareMessages","createTextCompletion","createStructuredCompletion","randomUtil"],"mappings":";;;;;;;;;;;;;;;AAAA,MAAM,oBAAoB,GAAG;;AAE3B,IAAA,SAAS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