@jaypie/llm 1.2.17 → 1.2.19
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/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/formatOperateMessage.ts","../../../src/util/formatOperateInput.ts","../../../src/util/logger.ts","../../../src/util/maxTurnsFromOptions.ts","../../../src/util/naturalZodSchema.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/GeminiAdapter.ts","../../../src/operate/adapters/OpenAiAdapter.ts","../../../src/operate/adapters/OpenRouterAdapter.ts","../../../src/operate/adapters/XaiAdapter.ts","../../../src/tools/Toolkit.class.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/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/gemini/utils.ts","../../../src/providers/gemini/GeminiProvider.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/gemini/types.ts"],"sourcesContent":["const FIRST_CLASS_PROVIDER = {\n ANTHROPIC: {\n DEFAULT: \"claude-sonnet-4-5\" as const,\n LARGE: \"claude-opus-4-5\" as const,\n SMALL: \"claude-sonnet-4-5\" as const,\n TINY: \"claude-haiku-4-5\" as const,\n },\n GEMINI: {\n DEFAULT: \"gemini-3-pro-preview\" as const,\n LARGE: \"gemini-3-pro-preview\" as const,\n SMALL: \"gemini-3-flash-preview\" as const,\n TINY: \"gemini-3-flash-preview\" as const,\n },\n OPENAI: {\n DEFAULT: \"gpt-5.2\" as const,\n LARGE: \"gpt-5.2-pro\" as const,\n SMALL: \"gpt-5-mini\" as const,\n TINY: \"gpt-5-nano\" as const,\n },\n OPENROUTER: {\n DEFAULT: \"z-ai/glm-4.7\" as const,\n LARGE: \"z-ai/glm-4.7\" as const,\n SMALL: \"z-ai/glm-4.7\" as const,\n TINY: \"z-ai/glm-4.7\" as const,\n },\n XAI: {\n DEFAULT: \"grok-4-1-fast-reasoning\" as const,\n LARGE: \"grok-4-1-fast-reasoning\" as const,\n SMALL: \"grok-3\" as const,\n TINY: \"grok-3-mini\" as const,\n },\n};\n\nexport const PROVIDER = {\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 GEMINI: {\n // https://ai.google.dev/gemini-api/docs/models\n MODEL: {\n DEFAULT: FIRST_CLASS_PROVIDER.GEMINI.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.GEMINI.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.GEMINI.SMALL,\n TINY: FIRST_CLASS_PROVIDER.GEMINI.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 },\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 // https://openrouter.ai/models\n // OpenRouter provides access to hundreds of models from various providers\n // The model format is: provider/model-name (e.g., \"openai/gpt-4\", \"anthropic/claude-3-opus\")\n MODEL: {\n // Default uses env var OPENROUTER_MODEL if set, otherwise a reasonable default\n DEFAULT: FIRST_CLASS_PROVIDER.OPENROUTER.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.OPENROUTER.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.OPENROUTER.SMALL,\n TINY: FIRST_CLASS_PROVIDER.OPENROUTER.TINY,\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.GEMINI.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.GEMINI.MODEL.DEFAULT,\n PROVIDER.OPENAI.MODEL.DEFAULT,\n PROVIDER.XAI.MODEL.DEFAULT,\n ],\n COMBINED: [\n PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n PROVIDER.ANTHROPIC.MODEL.LARGE,\n PROVIDER.ANTHROPIC.MODEL.SMALL,\n PROVIDER.ANTHROPIC.MODEL.TINY,\n PROVIDER.GEMINI.MODEL.DEFAULT,\n PROVIDER.GEMINI.MODEL.LARGE,\n PROVIDER.GEMINI.MODEL.SMALL,\n PROVIDER.GEMINI.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 LARGE: [\n PROVIDER.ANTHROPIC.MODEL.LARGE,\n PROVIDER.GEMINI.MODEL.LARGE,\n PROVIDER.OPENAI.MODEL.LARGE,\n PROVIDER.XAI.MODEL.LARGE,\n ],\n SMALL: [\n PROVIDER.ANTHROPIC.MODEL.SMALL,\n PROVIDER.GEMINI.MODEL.SMALL,\n PROVIDER.OPENAI.MODEL.SMALL,\n PROVIDER.XAI.MODEL.SMALL,\n ],\n TINY: [\n PROVIDER.ANTHROPIC.MODEL.TINY,\n PROVIDER.GEMINI.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 if input is a provider name\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.GEMINI.NAME || input === \"gemini\") {\n return {\n model: PROVIDER.GEMINI.MODEL.DEFAULT,\n provider: PROVIDER.GEMINI.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.GEMINI.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.GEMINI.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 Anthropic match words\n const lowerInput = input.toLowerCase();\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.GEMINI.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.GEMINI.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\", \"gemini\") */\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 { 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 { JAYPIE } from \"@jaypie/kit\";\nimport { log as defaultLog } from \"@jaypie/logger\";\n\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\nexport const log = getLogger();\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 = 12;\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 { 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 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 /** 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 { 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// Regular expression to parse data URLs: data:mime/type;base64,data\nconst DATA_URL_REGEX = /^data:([^;]+);base64,(.+)$/;\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//\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 //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): Anthropic.MessageCreateParams {\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: Anthropic.MessageCreateParams = {\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 if (request.tools && request.tools.length > 0) {\n anthropicRequest.tools = request.tools.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 // Determine tool choice based on whether structured output is requested\n const hasStructuredOutput = request.tools.some(\n (t) => t.name === STRUCTURED_OUTPUT_TOOL_NAME,\n );\n anthropicRequest.tool_choice = {\n type: hasStructuredOutput ? \"any\" : \"auto\",\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 return anthropicRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n const tools: ProviderToolDefinition[] = 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 // Add structured output tool if schema is provided\n if (outputSchema) {\n tools.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: outputSchema,\n });\n }\n\n return tools;\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 // Remove $schema property (causes issues with validator)\n if (jsonSchema.$schema) {\n delete jsonSchema.$schema;\n }\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<Anthropic.Message> {\n const anthropic = client as Anthropic;\n try {\n return (await anthropic.messages.create(\n request as Anthropic.MessageCreateParams,\n signal ? { signal } : undefined,\n )) as Anthropic.Message;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as Anthropic.Message;\n throw error;\n }\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const anthropic = client as Anthropic;\n const streamRequest = {\n ...(request as Anthropic.MessageCreateParams),\n stream: true,\n } as Anthropic.MessageCreateParamsStreaming;\n\n const stream = await anthropic.messages.create(\n streamRequest,\n signal ? { signal } : undefined,\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 Anthropic.Message;\n\n // Check if the last content block is a tool_use with structured_output\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 Anthropic.Message;\n\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 { GoogleGenAI } from \"@google/genai\";\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 { 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/gemini/types.js\";\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\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 * GeminiAdapter 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 GeminiAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.GEMINI.NAME;\n readonly defaultModel = PROVIDER.GEMINI.MODEL.DEFAULT;\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 // Add tools if provided\n if (request.tools && request.tools.length > 0) {\n const functionDeclarations: GeminiFunctionDeclaration[] =\n request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n }));\n\n geminiRequest.config = {\n ...geminiRequest.config,\n tools: [{ functionDeclarations }],\n };\n }\n\n // Add structured output format if provided (but NOT when tools are present)\n // Gemini doesn't support combining function calling with responseMimeType: 'application/json'\n // When tools are present, structured output is handled via the structured_output tool\n if (request.format && !(request.tools && request.tools.length > 0)) {\n geminiRequest.config = {\n ...geminiRequest.config,\n responseMimeType: \"application/json\",\n responseJsonSchema: request.format,\n };\n }\n\n // When format is specified with tools, add instruction to use structured_output tool\n if (request.format && request.tools && request.tools.length > 0) {\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 // Add to system instruction if it exists, otherwise create one\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?: JsonObject,\n ): ProviderToolDefinition[] {\n const tools: ProviderToolDefinition[] = 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 // Add structured output tool if schema is provided\n if (outputSchema) {\n tools.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: outputSchema,\n });\n }\n\n return tools;\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 // Remove $schema property (Gemini doesn't need it)\n if (jsonSchema.$schema) {\n delete jsonSchema.$schema;\n }\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<GeminiRawResponse> {\n const genAI = client as GoogleGenAI;\n const geminiRequest = request as GeminiRequest;\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 throw error;\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 current function call being built\n let currentFunctionCall: {\n id: string;\n name: string;\n arguments: Record<string, unknown>;\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 = 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 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 currentFunctionCall = null;\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 expects the response to be the actual result object, not wrapped in \"result\"\n // The output from StandardToolResult is JSON-stringified, so we need to parse it\n let responseData: Record<string, unknown>;\n try {\n responseData = JSON.parse(result.output);\n } catch {\n // If parsing fails, wrap the output as a string result\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 geminiAdapter = new GeminiAdapter();\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//\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 //\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: 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 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 try {\n // @ts-expect-error OpenAI SDK types don't match our request format exactly\n return await openai.responses.create(request, signal ? { signal } : undefined);\n } catch (error) {\n if (signal?.aborted) return undefined;\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 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 OpenRouterRequest {\n model: string;\n messages: OpenRouterMessage[];\n tools?: OpenRouterTool[];\n tool_choice?: \"auto\" | \"none\" | \"required\";\n response_format?: { type: \"json_object\" | \"text\" };\n user?: string;\n}\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\n/**\n * OpenRouter content part types (text only - images/files not supported)\n */\ntype OpenRouterContentPart = { type: \"text\"; text: string };\n\n/**\n * Convert standardized content items to OpenRouter format\n * Note: OpenRouter does not support native file/image uploads.\n * Images and files are discarded with a warning.\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 // Text content - pass through\n if (item.type === LlmMessageType.InputText) {\n parts.push({ type: \"text\", text: item.text });\n continue;\n }\n\n // Image content - warn and discard\n if (item.type === LlmMessageType.InputImage) {\n log.warn(\"OpenRouter does not support image uploads; image discarded\");\n continue;\n }\n\n // File/Document content - warn and discard\n if (item.type === LlmMessageType.InputFile) {\n log.warn(\n { filename: item.filename },\n \"OpenRouter does not support file uploads; file discarded\",\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 text 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//\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 //\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 if (request.tools && request.tools.length > 0) {\n openRouterRequest.tools = request.tools.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 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 return openRouterRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n const tools: ProviderToolDefinition[] = toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters as JsonObject,\n }));\n\n // Add structured output tool if schema is provided\n // (OpenRouter doesn't have native structured output like OpenAI, so use tool approach)\n if (outputSchema) {\n tools.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: outputSchema,\n });\n }\n\n return tools;\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\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 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\n try {\n const response = await openRouter.chat.send(\n {\n model: openRouterRequest.model,\n messages: openRouterRequest.messages as Parameters<\n typeof openRouter.chat.send\n >[0][\"messages\"],\n tools: openRouterRequest.tools as Parameters<\n typeof openRouter.chat.send\n >[0][\"tools\"],\n toolChoice: openRouterRequest.tool_choice,\n user: openRouterRequest.user,\n },\n signal ? { signal } : undefined,\n );\n\n return response as unknown as OpenRouterResponse;\n } catch (error) {\n if (signal?.aborted)\n return undefined as unknown as OpenRouterResponse;\n throw error;\n }\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 const stream = await openRouter.chat.send(\n {\n model: openRouterRequest.model,\n messages: openRouterRequest.messages as Parameters<\n typeof openRouter.chat.send\n >[0][\"messages\"],\n tools: openRouterRequest.tools as Parameters<\n typeof openRouter.chat.send\n >[0][\"tools\"],\n toolChoice: openRouterRequest.tool_choice,\n user: openRouterRequest.user,\n stream: true,\n },\n signal ? { signal } : undefined,\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 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 OpenRouterResponse;\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 OpenRouterResponse;\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 { PROVIDER } from \"../../constants.js\";\nimport { OpenAiAdapter } from \"./OpenAiAdapter.js\";\n\n/**\n * XaiAdapter extends OpenAiAdapter since xAI (Grok) uses an OpenAI-compatible API.\n * Only the name and default model are overridden; all request building, response parsing,\n * error classification, tool handling, and streaming are 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\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 { 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 { sleep } from \"@jaypie/kit\";\nimport { BadGatewayError } from \"@jaypie/errors\";\n\nimport { log } from \"../../util/index.js\";\nimport { isTransientNetworkError } from \"./isTransientNetworkError.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 let attempt = 0;\n\n // Persistent guard against stale socket errors (TypeError: terminated).\n // Installed after the first abort and kept alive through subsequent attempts\n // so that asynchronous undici socket teardown errors that fire between\n // sleep completion and the next operation's await are caught.\n let staleGuard: ((reason: unknown) => void) | undefined;\n\n const installGuard = () => {\n if (staleGuard) return;\n staleGuard = (reason: unknown) => {\n if (isTransientNetworkError(reason)) {\n log.trace(\"Suppressed stale socket error during retry\");\n }\n };\n process.on(\"unhandledRejection\", staleGuard);\n };\n\n const removeGuard = () => {\n if (staleGuard) {\n process.removeListener(\"unhandledRejection\", staleGuard);\n staleGuard = undefined;\n }\n };\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 // Abort the previous request to kill lingering socket callbacks\n controller.abort(\"retry\");\n\n // Install the guard immediately after abort — stale socket errors\n // can fire on any subsequent microtask boundary (during hook calls,\n // sleep, or the next operation attempt)\n installGuard();\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 removeGuard();\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 { log, maxTurnsFromOptions } 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} 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\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 // 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\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: 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 return state.responseBuilder.build();\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 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 // 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 (RetryExecutor handles error hooks and throws appropriate errors)\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 // 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(structuredOutput);\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\n log.trace(`[operate] Calling tool - ${toolCall.name}`);\n const result = await state.toolkit.call({\n arguments: toolCall.arguments,\n name: toolCall.name,\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 // 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 log.error(`Error executing function call ${toolCall.name}`);\n log.var({ error });\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(parsed.content);\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 * 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 { isTransientNetworkError } from \"./retry/isTransientNetworkError.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 { log, 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 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 // 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, options);\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 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 // 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 // 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 // Persistent guard against stale socket errors (TypeError: terminated).\n // Installed after the first abort and kept alive through subsequent attempts.\n let staleGuard: ((reason: unknown) => void) | undefined;\n\n const installGuard = () => {\n if (staleGuard) return;\n staleGuard = (reason: unknown) => {\n if (isTransientNetworkError(reason)) {\n log.trace(\"Suppressed stale socket error during retry\");\n }\n };\n process.on(\"unhandledRejection\", staleGuard);\n };\n\n const removeGuard = () => {\n if (staleGuard) {\n process.removeListener(\"unhandledRejection\", staleGuard);\n staleGuard = undefined;\n }\n };\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 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 // Abort the previous request to kill lingering socket callbacks\n controller.abort(\"retry\");\n\n // Install the guard immediately after abort\n installGuard();\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 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 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 removeGuard();\n }\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 =\n (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 _options: LlmOperateOptions,\n ): AsyncGenerator<LlmStreamChunk, void> {\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\n log.trace(`[stream] Calling tool - ${toolCall.name}`);\n const result = await state.toolkit!.call({\n arguments: toolCall.arguments,\n name: toolCall.name,\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 // 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 log.error(`Error executing function call ${toolCall.name}`);\n log.var({ error });\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\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 structured output\");\n\n // Get the JSON schema for the response\n const schema =\n responseSchema instanceof z.ZodType\n ? responseSchema\n : naturalZodSchema(responseSchema as NaturalSchema);\n\n // Set system message with JSON instructions\n const defaultSystemPrompt =\n \"You will be responding with structured JSON data. \" +\n \"Format your entire response as a valid JSON object with the following structure: \" +\n JSON.stringify(z.toJSONSchema(schema));\n\n const systemPrompt = systemMessage || defaultSystemPrompt;\n\n try {\n // Use standard Anthropic API to get response\n const params: Anthropic.MessageCreateParams = {\n model,\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n system: systemPrompt,\n };\n\n const response = await client.messages.create(params);\n\n // Extract text from response\n const firstContent = response.content[0];\n const responseText =\n firstContent && \"text\" in firstContent ? firstContent.text : \"\";\n\n // Find JSON in response\n const jsonMatch =\n responseText.match(/```json\\s*([\\s\\S]*?)\\s*```/) ||\n responseText.match(/\\{[\\s\\S]*\\}/);\n\n if (jsonMatch) {\n try {\n // Parse the JSON response\n const jsonStr = jsonMatch[1] || jsonMatch[0];\n const result = JSON.parse(jsonStr);\n if (!schema.parse(result)) {\n throw new Error(\n `JSON response from Anthropic does not match schema: ${responseText}`,\n );\n }\n log.trace(\"Received structured response\", { result });\n return result;\n } catch {\n throw new Error(\n `Failed to parse JSON response from Anthropic: ${responseText}`,\n );\n }\n }\n\n // If we can't extract JSON\n throw new Error(\"Failed to parse structured response from Anthropic\");\n } catch (error: unknown) {\n log.error(\"Error creating structured completion\", { error });\n throw error;\n }\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 { 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 let systemInstruction: string | undefined;\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 };\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 geminiAdapter,\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 GeminiProvider 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.GEMINI.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: geminiAdapter,\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: geminiAdapter,\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 { GeminiProvider } from \"./providers/gemini/GeminiProvider.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.GEMINI.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.GEMINI.NAME:\n return new GeminiProvider(model || PROVIDER.GEMINI.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 { log, 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 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 throw new Error(`Weather API error: ${error.message}`);\n }\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 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","log","random","STRUCTURED_OUTPUT_TOOL_NAME","RETRYABLE_STATUS_CODES","jaypieLog","defaultHookRunner","ERROR","cachedSdk","loadSdk","initializeClient","formatSystemMessage","placeholders","replacePlaceholders","formatUserMessage","prepareMessages","createTextCompletion","createStructuredCompletion","randomUtil"],"mappings":";;;;;;;;;;;;;AAAA,MAAM,oBAAoB,GAAG;AAC3B,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;AACD,IAAA,MAAM,EAAE;AACN,QAAA,OAAO,EAAE,sBAA+B;AACxC,QAAA,KAAK,EAAE,sBAA+B;AACtC,QAAA,KAAK,EAAE,wBAAiC;AACxC,QAAA,IAAI,EAAE,wBAAiC;AACxC,KAAA;AACD,IAAA,MAAM,EAAE;AACN,QAAA,OAAO,EAAE,SAAkB;AAC3B,QAAA,KAAK,EAAE,aAAsB;AAC7B,QAAA,KAAK,EAAE,YAAqB;AAC5B,QAAA,IAAI,EAAE,YAAqB;AAC5B,KAAA;AACD,IAAA,UAAU,EAAE;AACV,QAAA,OAAO,EAAE,cAAuB;AAChC,QAAA,KAAK,EAAE,cAAuB;AAC9B,QAAA,KAAK,EAAE,cAAuB;AAC9B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AC7B,QAAQ,GAAG,cAAc,GAC1B,GAAG,EAAE,KAAI;AACR,QAAA,OAAO,uBAAuB,QAAQ,CAAA,EAAA,EAAK,QAAQ,CAAA,EAAA,EAAK,SAAS,GAAG;IACtE,CAAC;CACF;;AC/IM,MAAM,KAAK,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO;AAE3C,MAAO,aAAc,SAAQ,OAAO,CAAA;IAMxC,WAAA,CAAY,KAAgB,EAAE,OAAa,EAAA;AACzC,QAAA,KAAK,CAAC,KAAK,EAAE,OAAO,CAAC;AACrB,QAAA,IAAI,CAAC,MAAM,GAAG,MAAM;AACpB,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI;AAChB,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI;AAChB,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO;IACxB;AACD;MAEY,OAAO,GAAG,IAAI,aAAa,CAAC,KAAK;;ACtB9C;AACA;AACA;AACA;CAEkE;AAChE,IAAA,CAAC,cAAc,CAAC,IAAI,GAAG,MAAM;AAC7B,IAAA,CAAC,cAAc,CAAC,MAAM,GAAG,MAAM;AAC/B,IAAA,CAAC,cAAc,CAAC,SAAS,GAAG,OAAO;AACnC,IAAA,CAAC,cAAc,CAAC,SAAS,GAAG,MAAM;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/constants.ts","../../../src/util/determineModelProvider.ts","../../../src/operate/adapters/ProviderAdapter.interface.ts","../../../src/types/LlmProvider.interface.ts","../../../src/types/LlmStreamChunk.interface.ts","../../../src/util/extractReasoning.ts","../../../src/util/formatOperateMessage.ts","../../../src/util/formatOperateInput.ts","../../../src/util/logger.ts","../../../src/util/maxTurnsFromOptions.ts","../../../src/util/naturalZodSchema.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/GeminiAdapter.ts","../../../src/operate/adapters/OpenAiAdapter.ts","../../../src/operate/adapters/OpenRouterAdapter.ts","../../../src/operate/adapters/XaiAdapter.ts","../../../src/tools/Toolkit.class.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/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/gemini/utils.ts","../../../src/providers/gemini/GeminiProvider.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/gemini/types.ts"],"sourcesContent":["const FIRST_CLASS_PROVIDER = {\n ANTHROPIC: {\n DEFAULT: \"claude-sonnet-4-5\" as const,\n LARGE: \"claude-opus-4-5\" as const,\n SMALL: \"claude-sonnet-4-5\" as const,\n TINY: \"claude-haiku-4-5\" as const,\n },\n GEMINI: {\n DEFAULT: \"gemini-3-pro-preview\" as const,\n LARGE: \"gemini-3-pro-preview\" as const,\n SMALL: \"gemini-3-flash-preview\" as const,\n TINY: \"gemini-3-flash-preview\" as const,\n },\n OPENAI: {\n DEFAULT: \"gpt-5.2\" as const,\n LARGE: \"gpt-5.2-pro\" as const,\n SMALL: \"gpt-5-mini\" as const,\n TINY: \"gpt-5-nano\" as const,\n },\n OPENROUTER: {\n DEFAULT: \"z-ai/glm-4.7\" as const,\n LARGE: \"z-ai/glm-4.7\" as const,\n SMALL: \"z-ai/glm-4.7\" as const,\n TINY: \"z-ai/glm-4.7\" as const,\n },\n XAI: {\n DEFAULT: \"grok-4-1-fast-reasoning\" as const,\n LARGE: \"grok-4-1-fast-reasoning\" as const,\n SMALL: \"grok-3\" as const,\n TINY: \"grok-3-mini\" as const,\n },\n};\n\nexport const PROVIDER = {\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 GEMINI: {\n // https://ai.google.dev/gemini-api/docs/models\n MODEL: {\n DEFAULT: FIRST_CLASS_PROVIDER.GEMINI.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.GEMINI.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.GEMINI.SMALL,\n TINY: FIRST_CLASS_PROVIDER.GEMINI.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 },\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 // https://openrouter.ai/models\n // OpenRouter provides access to hundreds of models from various providers\n // The model format is: provider/model-name (e.g., \"openai/gpt-4\", \"anthropic/claude-3-opus\")\n MODEL: {\n // Default uses env var OPENROUTER_MODEL if set, otherwise a reasonable default\n DEFAULT: FIRST_CLASS_PROVIDER.OPENROUTER.DEFAULT,\n LARGE: FIRST_CLASS_PROVIDER.OPENROUTER.LARGE,\n SMALL: FIRST_CLASS_PROVIDER.OPENROUTER.SMALL,\n TINY: FIRST_CLASS_PROVIDER.OPENROUTER.TINY,\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.GEMINI.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.GEMINI.MODEL.DEFAULT,\n PROVIDER.OPENAI.MODEL.DEFAULT,\n PROVIDER.XAI.MODEL.DEFAULT,\n ],\n COMBINED: [\n PROVIDER.ANTHROPIC.MODEL.DEFAULT,\n PROVIDER.ANTHROPIC.MODEL.LARGE,\n PROVIDER.ANTHROPIC.MODEL.SMALL,\n PROVIDER.ANTHROPIC.MODEL.TINY,\n PROVIDER.GEMINI.MODEL.DEFAULT,\n PROVIDER.GEMINI.MODEL.LARGE,\n PROVIDER.GEMINI.MODEL.SMALL,\n PROVIDER.GEMINI.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 LARGE: [\n PROVIDER.ANTHROPIC.MODEL.LARGE,\n PROVIDER.GEMINI.MODEL.LARGE,\n PROVIDER.OPENAI.MODEL.LARGE,\n PROVIDER.XAI.MODEL.LARGE,\n ],\n SMALL: [\n PROVIDER.ANTHROPIC.MODEL.SMALL,\n PROVIDER.GEMINI.MODEL.SMALL,\n PROVIDER.OPENAI.MODEL.SMALL,\n PROVIDER.XAI.MODEL.SMALL,\n ],\n TINY: [\n PROVIDER.ANTHROPIC.MODEL.TINY,\n PROVIDER.GEMINI.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 if input is a provider name\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.GEMINI.NAME || input === \"gemini\") {\n return {\n model: PROVIDER.GEMINI.MODEL.DEFAULT,\n provider: PROVIDER.GEMINI.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.GEMINI.MODEL)) {\n if (input === modelValue) {\n return {\n model: input,\n provider: PROVIDER.GEMINI.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 Anthropic match words\n const lowerInput = input.toLowerCase();\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.GEMINI.MODEL_MATCH_WORDS) {\n if (lowerInput.includes(matchWord)) {\n return {\n model: input,\n provider: PROVIDER.GEMINI.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\", \"gemini\") */\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 { 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 { JAYPIE } from \"@jaypie/kit\";\nimport { log as defaultLog } from \"@jaypie/logger\";\n\nexport const getLogger = () => defaultLog.lib({ lib: JAYPIE.LIB.LLM });\n\nexport const log = getLogger();\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 = 12;\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 { 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 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 /** 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 { 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// Regular expression to parse data URLs: data:mime/type;base64,data\nconst DATA_URL_REGEX = /^data:([^;]+);base64,(.+)$/;\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//\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 //\n // Request Building\n //\n\n buildRequest(request: OperateRequest): Anthropic.MessageCreateParams {\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: Anthropic.MessageCreateParams = {\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 if (request.tools && request.tools.length > 0) {\n anthropicRequest.tools = request.tools.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 // Determine tool choice based on whether structured output is requested\n const hasStructuredOutput = request.tools.some(\n (t) => t.name === STRUCTURED_OUTPUT_TOOL_NAME,\n );\n anthropicRequest.tool_choice = {\n type: hasStructuredOutput ? \"any\" : \"auto\",\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 return anthropicRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n const tools: ProviderToolDefinition[] = 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 // Add structured output tool if schema is provided\n if (outputSchema) {\n tools.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: outputSchema,\n });\n }\n\n return tools;\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 // Remove $schema property (causes issues with validator)\n if (jsonSchema.$schema) {\n delete jsonSchema.$schema;\n }\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<Anthropic.Message> {\n const anthropic = client as Anthropic;\n try {\n return (await anthropic.messages.create(\n request as Anthropic.MessageCreateParams,\n signal ? { signal } : undefined,\n )) as Anthropic.Message;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as Anthropic.Message;\n throw error;\n }\n }\n\n async *executeStreamRequest(\n client: unknown,\n request: unknown,\n signal?: AbortSignal,\n ): AsyncIterable<LlmStreamChunk> {\n const anthropic = client as Anthropic;\n const streamRequest = {\n ...(request as Anthropic.MessageCreateParams),\n stream: true,\n } as Anthropic.MessageCreateParamsStreaming;\n\n const stream = await anthropic.messages.create(\n streamRequest,\n signal ? { signal } : undefined,\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 Anthropic.Message;\n\n // Check if the last content block is a tool_use with structured_output\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 Anthropic.Message;\n\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 { GoogleGenAI } from \"@google/genai\";\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 { 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/gemini/types.js\";\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\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 * GeminiAdapter 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 GeminiAdapter extends BaseProviderAdapter {\n readonly name = PROVIDER.GEMINI.NAME;\n readonly defaultModel = PROVIDER.GEMINI.MODEL.DEFAULT;\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 // Add tools if provided\n if (request.tools && request.tools.length > 0) {\n const functionDeclarations: GeminiFunctionDeclaration[] =\n request.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters,\n }));\n\n geminiRequest.config = {\n ...geminiRequest.config,\n tools: [{ functionDeclarations }],\n };\n }\n\n // Add structured output format if provided (but NOT when tools are present)\n // Gemini doesn't support combining function calling with responseMimeType: 'application/json'\n // When tools are present, structured output is handled via the structured_output tool\n if (request.format && !(request.tools && request.tools.length > 0)) {\n geminiRequest.config = {\n ...geminiRequest.config,\n responseMimeType: \"application/json\",\n responseJsonSchema: request.format,\n };\n }\n\n // When format is specified with tools, add instruction to use structured_output tool\n if (request.format && request.tools && request.tools.length > 0) {\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 // Add to system instruction if it exists, otherwise create one\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?: JsonObject,\n ): ProviderToolDefinition[] {\n const tools: ProviderToolDefinition[] = 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 // Add structured output tool if schema is provided\n if (outputSchema) {\n tools.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: outputSchema,\n });\n }\n\n return tools;\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 // Remove $schema property (Gemini doesn't need it)\n if (jsonSchema.$schema) {\n delete jsonSchema.$schema;\n }\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<GeminiRawResponse> {\n const genAI = client as GoogleGenAI;\n const geminiRequest = request as GeminiRequest;\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 throw error;\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 current function call being built\n let currentFunctionCall: {\n id: string;\n name: string;\n arguments: Record<string, unknown>;\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 = 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 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 currentFunctionCall = null;\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 expects the response to be the actual result object, not wrapped in \"result\"\n // The output from StandardToolResult is JSON-stringified, so we need to parse it\n let responseData: Record<string, unknown>;\n try {\n responseData = JSON.parse(result.output);\n } catch {\n // If parsing fails, wrap the output as a string result\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 geminiAdapter = new GeminiAdapter();\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//\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 //\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 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 try {\n return await openai.responses.create(\n // @ts-expect-error OpenAI SDK types don't match our request format exactly\n request,\n signal ? { signal } : undefined,\n );\n } catch (error) {\n if (signal?.aborted) return undefined;\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 OpenRouterRequest {\n model: string;\n messages: OpenRouterMessage[];\n tools?: OpenRouterTool[];\n tool_choice?: \"auto\" | \"none\" | \"required\";\n response_format?: { type: \"json_object\" | \"text\" };\n user?: string;\n}\n\n//\n//\n// Constants\n//\n\nconst STRUCTURED_OUTPUT_TOOL_NAME = \"structured_output\";\n\n/**\n * OpenRouter content part types (text only - images/files not supported)\n */\ntype OpenRouterContentPart = { type: \"text\"; text: string };\n\n/**\n * Convert standardized content items to OpenRouter format\n * Note: OpenRouter does not support native file/image uploads.\n * Images and files are discarded with a warning.\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 // Text content - pass through\n if (item.type === LlmMessageType.InputText) {\n parts.push({ type: \"text\", text: item.text });\n continue;\n }\n\n // Image content - warn and discard\n if (item.type === LlmMessageType.InputImage) {\n log.warn(\"OpenRouter does not support image uploads; image discarded\");\n continue;\n }\n\n // File/Document content - warn and discard\n if (item.type === LlmMessageType.InputFile) {\n log.warn(\n { filename: item.filename },\n \"OpenRouter does not support file uploads; file discarded\",\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 text 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//\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 //\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 if (request.tools && request.tools.length > 0) {\n openRouterRequest.tools = request.tools.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 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 return openRouterRequest;\n }\n\n formatTools(\n toolkit: Toolkit,\n outputSchema?: JsonObject,\n ): ProviderToolDefinition[] {\n const tools: ProviderToolDefinition[] = toolkit.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n parameters: tool.parameters as JsonObject,\n }));\n\n // Add structured output tool if schema is provided\n // (OpenRouter doesn't have native structured output like OpenAI, so use tool approach)\n if (outputSchema) {\n tools.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: outputSchema,\n });\n }\n\n return tools;\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\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 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\n try {\n const response = await openRouter.chat.send(\n {\n model: openRouterRequest.model,\n messages: openRouterRequest.messages as Parameters<\n typeof openRouter.chat.send\n >[0][\"messages\"],\n tools: openRouterRequest.tools as Parameters<\n typeof openRouter.chat.send\n >[0][\"tools\"],\n toolChoice: openRouterRequest.tool_choice,\n user: openRouterRequest.user,\n },\n signal ? { signal } : undefined,\n );\n\n return response as unknown as OpenRouterResponse;\n } catch (error) {\n if (signal?.aborted) return undefined as unknown as OpenRouterResponse;\n throw error;\n }\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 const stream = await openRouter.chat.send(\n {\n model: openRouterRequest.model,\n messages: openRouterRequest.messages as Parameters<\n typeof openRouter.chat.send\n >[0][\"messages\"],\n tools: openRouterRequest.tools as Parameters<\n typeof openRouter.chat.send\n >[0][\"tools\"],\n toolChoice: openRouterRequest.tool_choice,\n user: openRouterRequest.user,\n stream: true,\n },\n signal ? { signal } : undefined,\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 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 OpenRouterResponse;\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 OpenRouterResponse;\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 { PROVIDER } from \"../../constants.js\";\nimport { OpenAiAdapter } from \"./OpenAiAdapter.js\";\n\n/**\n * XaiAdapter extends OpenAiAdapter since xAI (Grok) uses an OpenAI-compatible API.\n * Only the name and default model are overridden; all request building, response parsing,\n * error classification, tool handling, and streaming are 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\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 { 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 { sleep } from \"@jaypie/kit\";\nimport { BadGatewayError } from \"@jaypie/errors\";\n\nimport { log } from \"../../util/index.js\";\nimport { isTransientNetworkError } from \"./isTransientNetworkError.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 let attempt = 0;\n\n // Persistent guard against stale socket errors (TypeError: terminated).\n // Installed after the first abort and kept alive through subsequent attempts\n // so that asynchronous undici socket teardown errors that fire between\n // sleep completion and the next operation's await are caught.\n let staleGuard: ((reason: unknown) => void) | undefined;\n\n const installGuard = () => {\n if (staleGuard) return;\n staleGuard = (reason: unknown) => {\n if (isTransientNetworkError(reason)) {\n log.trace(\"Suppressed stale socket error during retry\");\n }\n };\n process.on(\"unhandledRejection\", staleGuard);\n };\n\n const removeGuard = () => {\n if (staleGuard) {\n process.removeListener(\"unhandledRejection\", staleGuard);\n staleGuard = undefined;\n }\n };\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 // Abort the previous request to kill lingering socket callbacks\n controller.abort(\"retry\");\n\n // Install the guard immediately after abort — stale socket errors\n // can fire on any subsequent microtask boundary (during hook calls,\n // sleep, or the next operation attempt)\n installGuard();\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 removeGuard();\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 { log, maxTurnsFromOptions } 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} 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\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 // 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\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: 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 return state.responseBuilder.build();\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 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 // 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 (RetryExecutor handles error hooks and throws appropriate errors)\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 // 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(structuredOutput);\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\n log.trace(`[operate] Calling tool - ${toolCall.name}`);\n const result = await state.toolkit.call({\n arguments: toolCall.arguments,\n name: toolCall.name,\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 // 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 log.error(`Error executing function call ${toolCall.name}`);\n log.var({ error });\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(parsed.content);\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 * 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 { isTransientNetworkError } from \"./retry/isTransientNetworkError.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 { log, 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 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 // 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, options);\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 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 // 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 // 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 // Persistent guard against stale socket errors (TypeError: terminated).\n // Installed after the first abort and kept alive through subsequent attempts.\n let staleGuard: ((reason: unknown) => void) | undefined;\n\n const installGuard = () => {\n if (staleGuard) return;\n staleGuard = (reason: unknown) => {\n if (isTransientNetworkError(reason)) {\n log.trace(\"Suppressed stale socket error during retry\");\n }\n };\n process.on(\"unhandledRejection\", staleGuard);\n };\n\n const removeGuard = () => {\n if (staleGuard) {\n process.removeListener(\"unhandledRejection\", staleGuard);\n staleGuard = undefined;\n }\n };\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 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 // Abort the previous request to kill lingering socket callbacks\n controller.abort(\"retry\");\n\n // Install the guard immediately after abort\n installGuard();\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 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 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 removeGuard();\n }\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 _options: LlmOperateOptions,\n ): AsyncGenerator<LlmStreamChunk, void> {\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\n log.trace(`[stream] Calling tool - ${toolCall.name}`);\n const result = await state.toolkit!.call({\n arguments: toolCall.arguments,\n name: toolCall.name,\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 // 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 log.error(`Error executing function call ${toolCall.name}`);\n log.var({ error });\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\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 structured output\");\n\n // Get the JSON schema for the response\n const schema =\n responseSchema instanceof z.ZodType\n ? responseSchema\n : naturalZodSchema(responseSchema as NaturalSchema);\n\n // Set system message with JSON instructions\n const defaultSystemPrompt =\n \"You will be responding with structured JSON data. \" +\n \"Format your entire response as a valid JSON object with the following structure: \" +\n JSON.stringify(z.toJSONSchema(schema));\n\n const systemPrompt = systemMessage || defaultSystemPrompt;\n\n try {\n // Use standard Anthropic API to get response\n const params: Anthropic.MessageCreateParams = {\n model,\n messages,\n max_tokens: PROVIDER.ANTHROPIC.MAX_TOKENS.DEFAULT,\n system: systemPrompt,\n };\n\n const response = await client.messages.create(params);\n\n // Extract text from response\n const firstContent = response.content[0];\n const responseText =\n firstContent && \"text\" in firstContent ? firstContent.text : \"\";\n\n // Find JSON in response\n const jsonMatch =\n responseText.match(/```json\\s*([\\s\\S]*?)\\s*```/) ||\n responseText.match(/\\{[\\s\\S]*\\}/);\n\n if (jsonMatch) {\n try {\n // Parse the JSON response\n const jsonStr = jsonMatch[1] || jsonMatch[0];\n const result = JSON.parse(jsonStr);\n if (!schema.parse(result)) {\n throw new Error(\n `JSON response from Anthropic does not match schema: ${responseText}`,\n );\n }\n log.trace(\"Received structured response\", { result });\n return result;\n } catch {\n throw new Error(\n `Failed to parse JSON response from Anthropic: ${responseText}`,\n );\n }\n }\n\n // If we can't extract JSON\n throw new Error(\"Failed to parse structured response from Anthropic\");\n } catch (error: unknown) {\n log.error(\"Error creating structured completion\", { error });\n throw error;\n }\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 { 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 let systemInstruction: string | undefined;\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 };\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 geminiAdapter,\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 GeminiProvider 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.GEMINI.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: geminiAdapter,\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: geminiAdapter,\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 { GeminiProvider } from \"./providers/gemini/GeminiProvider.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.GEMINI.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.GEMINI.NAME:\n return new GeminiProvider(model || PROVIDER.GEMINI.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 { log, 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 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 throw new Error(`Weather API error: ${error.message}`);\n }\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 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","log","random","STRUCTURED_OUTPUT_TOOL_NAME","RETRYABLE_STATUS_CODES","jaypieLog","defaultHookRunner","ERROR","cachedSdk","loadSdk","initializeClient","formatSystemMessage","placeholders","replacePlaceholders","formatUserMessage","prepareMessages","createTextCompletion","createStructuredCompletion","randomUtil"],"mappings":";;;;;;;;;;;;;AAAA,MAAM,oBAAoB,GAAG;AAC3B,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;AACD,IAAA,MAAM,EAAE;AACN,QAAA,OAAO,EAAE,sBAA+B;AACxC,QAAA,KAAK,EAAE,sBAA+B;AACtC,QAAA,KAAK,EAAE,wBAAiC;AACxC,QAAA,IAAI,EAAE,wBAAiC;AACxC,KAAA;AACD,IAAA,MAAM,EAAE;AACN,QAAA,OAAO,EAAE,SAAkB;AAC3B,QAAA,KAAK,EAAE,aAAsB;AAC7B,QAAA,KAAK,EAAE,YAAqB;AAC5B,QAAA,IAAI,EAAE,YAAqB;AAC5B,KAAA;AACD,IAAA,UAAU,EAAE;AACV,QAAA,OAAO,EAAE,cAAuB;AAChC,QAAA,KAAK,EAAE,cAAuB;AAC9B,QAAA,KAAK,EAAE,cAAuB;AAC9B,QAAA,IAAI,EAAE,cAAuB;AAC9B,KAAA;AACD,IAAA,GAAG,EAAE;AACH,QAAA,OAAO,EAAE,yBAAkC;AAC3C,QAAA,KAAK,EAAE,yBAAk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