universal-llm-client 4.3.0 → 4.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +34 -19
  2. package/README.md +62 -11
  3. package/dist/ai-model.d.ts +12 -2
  4. package/dist/ai-model.js +36 -2
  5. package/dist/auditor.d.ts +0 -1
  6. package/dist/auditor.js +0 -1
  7. package/dist/client.d.ts +0 -1
  8. package/dist/client.js +0 -1
  9. package/dist/gemma-channel.d.ts +13 -0
  10. package/dist/gemma-channel.js +37 -0
  11. package/dist/gemma-diffusion.d.ts +48 -0
  12. package/dist/gemma-diffusion.js +146 -0
  13. package/dist/http.d.ts +4 -1
  14. package/dist/http.js +14 -2
  15. package/dist/index.d.ts +2 -2
  16. package/dist/index.js +4 -1
  17. package/dist/interfaces.d.ts +163 -8
  18. package/dist/interfaces.js +0 -1
  19. package/dist/mcp.d.ts +0 -1
  20. package/dist/mcp.js +0 -1
  21. package/dist/providers/anthropic.d.ts +0 -1
  22. package/dist/providers/anthropic.js +28 -4
  23. package/dist/providers/google.d.ts +22 -2
  24. package/dist/providers/google.js +223 -14
  25. package/dist/providers/index.d.ts +0 -1
  26. package/dist/providers/index.js +0 -1
  27. package/dist/providers/ollama.d.ts +2 -1
  28. package/dist/providers/ollama.js +59 -31
  29. package/dist/providers/openai.d.ts +16 -1
  30. package/dist/providers/openai.js +488 -81
  31. package/dist/router.d.ts +2 -1
  32. package/dist/router.js +4 -1
  33. package/dist/stream-decoder.d.ts +12 -1
  34. package/dist/stream-decoder.js +182 -6
  35. package/dist/structured-output.d.ts +0 -1
  36. package/dist/structured-output.js +0 -1
  37. package/dist/thinking.d.ts +35 -0
  38. package/dist/thinking.js +51 -0
  39. package/dist/tools.d.ts +0 -1
  40. package/dist/tools.js +0 -1
  41. package/dist/zod-adapter.d.ts +0 -1
  42. package/dist/zod-adapter.js +0 -1
  43. package/package.json +3 -1
  44. package/dist/ai-model.d.ts.map +0 -1
  45. package/dist/ai-model.js.map +0 -1
  46. package/dist/auditor.d.ts.map +0 -1
  47. package/dist/auditor.js.map +0 -1
  48. package/dist/client.d.ts.map +0 -1
  49. package/dist/client.js.map +0 -1
  50. package/dist/http.d.ts.map +0 -1
  51. package/dist/http.js.map +0 -1
  52. package/dist/index.d.ts.map +0 -1
  53. package/dist/index.js.map +0 -1
  54. package/dist/interfaces.d.ts.map +0 -1
  55. package/dist/interfaces.js.map +0 -1
  56. package/dist/mcp.d.ts.map +0 -1
  57. package/dist/mcp.js.map +0 -1
  58. package/dist/providers/anthropic.d.ts.map +0 -1
  59. package/dist/providers/anthropic.js.map +0 -1
  60. package/dist/providers/google.d.ts.map +0 -1
  61. package/dist/providers/google.js.map +0 -1
  62. package/dist/providers/index.d.ts.map +0 -1
  63. package/dist/providers/index.js.map +0 -1
  64. package/dist/providers/ollama.d.ts.map +0 -1
  65. package/dist/providers/ollama.js.map +0 -1
  66. package/dist/providers/openai.d.ts.map +0 -1
  67. package/dist/providers/openai.js.map +0 -1
  68. package/dist/router.d.ts.map +0 -1
  69. package/dist/router.js.map +0 -1
  70. package/dist/stream-decoder.d.ts.map +0 -1
  71. package/dist/stream-decoder.js.map +0 -1
  72. package/dist/structured-output.d.ts.map +0 -1
  73. package/dist/structured-output.js.map +0 -1
  74. package/dist/tools.d.ts.map +0 -1
  75. package/dist/tools.js.map +0 -1
  76. package/dist/zod-adapter.d.ts.map +0 -1
  77. package/dist/zod-adapter.js.map +0 -1
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,+EAA+E;AAC/E,oCAAoC;AACpC,+EAA+E;AAE/E,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAExC,+EAA+E;AAC/E,qBAAqB;AACrB,+EAA+E;AAE/E,OAAO;AACH,QAAQ;AACR,cAAc,EACd,WAAW;AA6BX,UAAU;AACV,WAAW,EACX,YAAY,EACZ,iBAAiB,EACjB,kBAAkB,EAClB,SAAS,EACT,YAAY,EACZ,QAAQ,GACX,MAAM,iBAAiB,CAAC;AAEzB,+EAA+E;AAC/E,gBAAgB;AAChB,+EAA+E;AAE/E,OAAO,EAIH,WAAW,EACX,cAAc,EACd,eAAe,GAClB,MAAM,cAAc,CAAC;AAEtB,+EAA+E;AAC/E,kBAAkB;AAClB,+EAA+E;AAE/E,OAAO,EAOH,aAAa,EACb,eAAe,EACf,qBAAqB,EACrB,kBAAkB,EAClB,mBAAmB,EACnB,2BAA2B,GAC9B,MAAM,qBAAqB,CAAC;AAE7B,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E,OAAO,EACH,WAAW,EACX,YAAY,EACZ,cAAc,EACd,sBAAsB,GACzB,MAAM,YAAY,CAAC;AAEpB,+EAA+E;AAC/E,0CAA0C;AAC1C,+EAA+E;AAE/E,OAAO,EACH,WAAW,EACX,UAAU,EACV,WAAW,EACX,QAAQ,EACR,YAAY,GAGf,MAAM,WAAW,CAAC;AAEnB,+EAA+E;AAC/E,kBAAkB;AAClB,+EAA+E;AAE/E,OAAO,EACH,aAAa,GAIhB,MAAM,UAAU,CAAC;AAElB,+EAA+E;AAC/E,oBAAoB;AACpB,+EAA+E;AAE/E,OAAO,EACH,qBAAqB,EAUrB,yBAAyB,EACzB,yBAAyB;AACzB,8BAA8B;AAC9B,mBAAmB,EACnB,uBAAuB,EACvB,wBAAwB,EACxB,aAAa,EACb,uBAAuB;AACvB,uBAAuB;AACvB,eAAe,EACf,kBAAkB,EAClB,wBAAwB,EACxB,eAAe;AACf,mBAAmB;AACnB,mBAAmB,GAEtB,MAAM,wBAAwB,CAAC","sourcesContent":["/**\r\n * Universal LLM Client v3\r\n *\r\n * A universal LLM client with transparent provider failover,\r\n * streaming tool execution, pluggable reasoning, and native observability.\r\n *\r\n * @module universal-llm-client\r\n */\r\n\r\n// ============================================================================\r\n// Public API — The Universal Client\r\n// ============================================================================\r\n\r\nexport { AIModel } from './ai-model.js';\r\n\r\n// ============================================================================\r\n// Types & Interfaces\r\n// ============================================================================\r\n\r\nexport {\r\n // Enums\r\n AIModelApiType,\r\n AIModelType,\r\n // Config\r\n type AIModelConfig,\r\n type ProviderConfig,\r\n type LLMClientOptions,\r\n // Messages\r\n type LLMChatMessage,\r\n type LLMMessageContent,\r\n type LLMContentPart,\r\n type LLMTextContent,\r\n type LLMImageContent,\r\n type LLMAudioContent,\r\n // Responses\r\n type LLMChatResponse,\r\n type TokenUsageInfo,\r\n // Tools\r\n type LLMToolCall,\r\n type LLMToolDefinition,\r\n type LLMFunction,\r\n type ToolHandler,\r\n type ToolExecutionResult,\r\n type ToolRegistry,\r\n type ToolRegistryEntry,\r\n // Options\r\n type ChatOptions,\r\n type ResponseFormat,\r\n type OutputOptions,\r\n // Model info\r\n type ModelMetadata,\r\n // Helpers\r\n textContent,\r\n imageContent,\r\n multimodalMessage,\r\n extractTextContent,\r\n hasImages,\r\n audioContent,\r\n hasAudio,\r\n} from './interfaces.js';\r\n\r\n// ============================================================================\r\n// Observability\r\n// ============================================================================\r\n\r\nexport {\r\n type Auditor,\r\n type AuditEvent,\r\n type AuditEventType,\r\n NoopAuditor,\r\n ConsoleAuditor,\r\n BufferedAuditor,\r\n} from './auditor.js';\r\n\r\n// ============================================================================\r\n// Stream Decoding\r\n// ============================================================================\r\n\r\nexport {\r\n type StreamDecoder,\r\n type DecodedEvent,\r\n type DecoderCallback,\r\n type DecoderType,\r\n type DecoderOptions,\r\n type DecoderFactory,\r\n createDecoder,\r\n registerDecoder,\r\n getRegisteredDecoders,\r\n PassthroughDecoder,\r\n StandardChatDecoder,\r\n InterleavedReasoningDecoder,\r\n} from './stream-decoder.js';\r\n\r\n// ============================================================================\r\n// Tool Utilities\r\n// ============================================================================\r\n\r\nexport {\r\n ToolBuilder,\r\n ToolExecutor,\r\n createTimeTool,\r\n createRandomNumberTool,\r\n} from './tools.js';\r\n\r\n// ============================================================================\r\n// HTTP Utilities (for advanced use cases)\r\n// ============================================================================\r\n\r\nexport {\r\n httpRequest,\r\n httpStream,\r\n parseNDJSON,\r\n parseSSE,\r\n buildHeaders,\r\n type HttpRequestOptions,\r\n type HttpResponse,\r\n} from './http.js';\r\n\r\n// ============================================================================\r\n// MCP Integration\r\n// ============================================================================\r\n\r\nexport {\r\n MCPToolBridge,\r\n type MCPBridgeConfig,\r\n type MCPServerConfig,\r\n type MCPTool,\r\n} from './mcp.js';\r\n\r\n// ============================================================================\r\n// Structured Output\r\n// ============================================================================\r\n\r\nexport {\r\n StructuredOutputError,\r\n type StructuredOutputErrorOptions,\r\n type StructuredOutputOptions,\r\n type StructuredOutputResult,\r\n type StructuredOutputSuccess,\r\n type StructuredOutputFailure,\r\n type JSONSchema,\r\n type SchemaProvider,\r\n type ProviderSchema,\r\n type SchemaConfig,\r\n isStructuredOutputSuccess,\r\n isStructuredOutputFailure,\r\n // Schema conversion utilities\r\n normalizeJsonSchema,\r\n convertToProviderSchema,\r\n stripUnsupportedFeatures,\r\n getJsonSchema,\r\n getJsonSchemaFromConfig,\r\n // Validation functions\r\n parseStructured,\r\n tryParseStructured,\r\n validateStructuredOutput,\r\n stripJsonFences,\r\n // Streaming parser\r\n StreamingJsonParser,\r\n type StreamingStructuredResult,\r\n} from './structured-output.js';\r\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"interfaces.d.ts","sourceRoot":"","sources":["../src/interfaces.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH,oBAAY,WAAW;IACnB,IAAI,SAAS;IACb,SAAS,cAAc;CAC1B;AAED,oBAAY,cAAc;IACtB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,MAAM,WAAW;IACjB,QAAQ,aAAa;IACrB,SAAS,cAAc;CAC1B;AAMD,MAAM,WAAW,aAAa;IAC1B,yCAAyC;IACzC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,oCAAoC;IACpC,aAA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CAAC,IAAI,CAAC,IAAI,CAAC;SACtB,IAAI,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC;AAED,+CAA+C;AAC/C,MAAM,UAAU,SAAS,CAAC,OAA0B;IAChD,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC9C,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC;AAC3D,CAAC;AAED,wDAAwD;AACxD,MAAM,UAAU,YAAY,CAAC,UAAkB,EAAE,QAAgB;IAC7D,OAAO;QACH,IAAI,EAAE,OAAO;QACb,KAAK,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE;KACxC,CAAC;AACN,CAAC;AAED,8CAA8C;AAC9C,MAAM,UAAU,QAAQ,CAAC,OAA0B;IAC/C,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC9C,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC;AACvD,CAAC","sourcesContent":["/**\r\n * Universal LLM Client v3 — Core Interfaces\r\n *\r\n * All types, enums, and helper functions used throughout the library.\r\n * Zero dependencies — pure TypeScript types.\r\n */\r\n\r\n// ============================================================================\r\n// Enums\r\n// ============================================================================\r\n\r\nexport enum AIModelType {\r\n Chat = 'chat',\r\n Embedding = 'embedding',\r\n}\r\n\r\nexport enum AIModelApiType {\r\n Ollama = 'ollama',\r\n OpenAI = 'openai',\r\n Google = 'google',\r\n Vertex = 'vertex',\r\n LlamaCpp = 'llamacpp',\r\n Anthropic = 'anthropic',\r\n}\r\n\r\n// ============================================================================\r\n// Model Metadata\r\n// ============================================================================\r\n\r\nexport interface ModelMetadata {\r\n /** Model name as reported by provider */\r\n model?: string;\r\n /** Context window size in tokens */\r\n contextLength: number;\r\n /** Model architecture (e.g., \"llama\", \"mistral3\") */\r\n architecture?: string;\r\n /** Parameter count */\r\n parameterCount?: number;\r\n /** Model capabilities reported by provider (e.g., \"tools\", \"vision\", \"thinking\") */\r\n capabilities?: string[];\r\n}\r\n\r\n// ============================================================================\r\n// Provider Configuration (user-facing)\r\n// ============================================================================\r\n\r\nexport interface ProviderConfig {\r\n /** Provider type */\r\n type: AIModelApiType | 'ollama' | 'openai' | 'google' | 'vertex' | 'llamacpp' | 'anthropic';\r\n /** Provider endpoint URL (has sensible defaults per type) */\r\n url?: string;\r\n /** API key or Bearer token */\r\n apiKey?: string;\r\n /** Override model name for this specific provider */\r\n model?: string;\r\n /** Explicit priority (default: array order, lower = higher priority) */\r\n priority?: number;\r\n /** Vertex AI region (e.g., \"us-central1\") */\r\n region?: string;\r\n /** Google API version (default: \"v1beta\") */\r\n apiVersion?: 'v1' | 'v1beta';\r\n}\r\n\r\n// ============================================================================\r\n// AIModel Configuration (user-facing)\r\n// ============================================================================\r\n\r\nexport interface AIModelConfig {\r\n /** Model name (used across all providers unless overridden) */\r\n model: string;\r\n /** Ordered list of providers (first = highest priority) */\r\n providers: ProviderConfig[];\r\n /** Default parameters for all requests (temperature, top_p, etc.) */\r\n defaultParameters?: Record<string, unknown>;\r\n /** Enable thinking/reasoning mode */\r\n thinking?: boolean;\r\n /** Request timeout in ms (default: 30000) */\r\n timeout?: number;\r\n /** Retries per provider before failover (default: 2) */\r\n retries?: number;\r\n /** Observability hooks */\r\n auditor?: import('./auditor.js').Auditor;\r\n /** Enable debug logging */\r\n debug?: boolean;\r\n}\r\n\r\n// ============================================================================\r\n// Internal Client Options\r\n// ============================================================================\r\n\r\nexport interface LLMClientOptions {\r\n /** Model name */\r\n model: string;\r\n /** Base URL for the API */\r\n url: string;\r\n /** API type for protocol variations */\r\n apiType: AIModelApiType;\r\n /** Model type (chat or embedding) */\r\n modelType?: AIModelType;\r\n /** Default parameters for requests */\r\n defaultParameters?: Record<string, unknown>;\r\n /** Enable thinking/reasoning mode */\r\n thinking?: boolean;\r\n /** Request timeout in ms */\r\n timeout?: number;\r\n /** Number of retries for failed requests */\r\n retries?: number;\r\n /** API key for authenticated endpoints */\r\n apiKey?: string;\r\n /** Enable debug logging */\r\n debug?: boolean;\r\n /** Vertex AI region */\r\n region?: string;\r\n /** Google API version */\r\n apiVersion?: 'v1' | 'v1beta';\r\n}\r\n\r\n// ============================================================================\r\n// Multimodal Content Types\r\n// ============================================================================\r\n\r\nexport interface LLMTextContent {\r\n type: 'text';\r\n text: string;\r\n}\r\n\r\nexport interface LLMImageContent {\r\n type: 'image_url';\r\n image_url: {\r\n url: string;\r\n detail?: 'auto' | 'low' | 'high';\r\n };\r\n}\r\n\r\nexport interface LLMAudioContent {\r\n type: 'audio';\r\n audio: {\r\n /** Raw base64-encoded audio data */\r\n data: string;\r\n /** MIME type (e.g. 'audio/ogg', 'audio/wav', 'audio/mp3') */\r\n mimeType: string;\r\n };\r\n}\r\n\r\nexport type LLMContentPart = LLMTextContent | LLMImageContent | LLMAudioContent;\r\nexport type LLMMessageContent = string | LLMContentPart[];\r\n\r\n// ============================================================================\r\n// Chat Message Types\r\n// ============================================================================\r\n\r\nexport interface LLMChatMessage {\r\n role: 'system' | 'user' | 'assistant' | 'tool';\r\n content: LLMMessageContent;\r\n tool_call_id?: string;\r\n tool_calls?: LLMToolCall[];\r\n}\r\n\r\n// ============================================================================\r\n// Tool Types\r\n// ============================================================================\r\n\r\nexport interface LLMToolCall {\r\n id: string;\r\n type: 'function';\r\n function: {\r\n name: string;\r\n arguments: string;\r\n };\r\n /**\r\n * Gemini 3.x thought signature — encrypted reasoning context.\r\n * Must be echoed back exactly when sending conversation history\r\n * during multi-turn function calling. Mandatory for Gemini 3,\r\n * optional for Gemini 2.5, ignored by other providers.\r\n */\r\n thoughtSignature?: string;\r\n}\r\n\r\nexport interface LLMFunction {\r\n name: string;\r\n description: string;\r\n parameters: {\r\n type: 'object';\r\n properties?: Record<string, unknown>;\r\n required?: string[];\r\n };\r\n}\r\n\r\nexport interface LLMToolDefinition {\r\n type: 'function';\r\n function: LLMFunction;\r\n}\r\n\r\nexport interface ToolExecutionResult {\r\n tool_call_id: string;\r\n output: unknown;\r\n error?: string;\r\n duration?: number;\r\n}\r\n\r\nexport type ToolHandler = (args: unknown) => Promise<unknown> | unknown;\r\n\r\nexport interface ToolRegistryEntry {\r\n definition: LLMFunction;\r\n handler: ToolHandler;\r\n}\r\n\r\nexport interface ToolRegistry {\r\n [toolName: string]: ToolRegistryEntry;\r\n}\r\n\r\n// ============================================================================\r\n// Chat Options (per-call overrides)\r\n// ============================================================================\r\n\r\n/**\r\n * Response format for structured output.\r\n * \r\n * For json_schema mode, use: { type: 'json_schema', json_schema: { name, schema, strict } }\r\n * For json_object mode (legacy), use: { type: 'json_object' }\r\n */\r\nexport interface ResponseFormat {\r\n /** Response format type */\r\n type: 'json_object' | 'json_schema';\r\n /** JSON Schema definition (required for json_schema type) */\r\n json_schema?: {\r\n /** Name of the schema (for LLM guidance) */\r\n name: string;\r\n /** Schema description (optional, for LLM guidance) */\r\n description?: string;\r\n /** The JSON Schema */\r\n schema: Record<string, unknown>;\r\n /** Enable strict mode (required for reliable structured output) */\r\n strict?: boolean;\r\n };\r\n}\r\n\r\n/**\r\n * Output options for structured output in chat responses.\r\n * \r\n * When provided, the response will include a `structured` property with\r\n * the validated, typed result. This is the recommended way to request\r\n * structured output via the chat() method.\r\n * \r\n * @example\r\n * ```typescript\r\n * const UserSchema = z.object({\r\n * name: z.string(),\r\n * age: z.number(),\r\n * });\r\n * \r\n * const response = await model.chat(messages, {\r\n * output: { schema: UserSchema },\r\n * });\r\n * \r\n * // response.structured is typed as { name: string, age: number }\r\n * console.log(response.structured?.name);\r\n * ```\r\n */\r\nexport interface OutputOptions<T = unknown> {\r\n /**\r\n * Schema configuration for structured output.\r\n * Use `fromZod()` from `universal-llm-client/zod` to create from a Zod schema,\r\n * or provide a raw SchemaConfig with jsonSchema + optional validate function.\r\n */\r\n schema?: import('./structured-output.js').SchemaConfig<T>;\r\n \r\n /**\r\n * Raw JSON Schema for structured output.\r\n * Alternative to `schema` when you have a pre-defined schema.\r\n */\r\n jsonSchema?: import('./structured-output.js').JSONSchema;\r\n \r\n /**\r\n * Optional name for the schema.\r\n * Used by providers like OpenAI for better LLM guidance.\r\n */\r\n name?: string;\r\n \r\n /**\r\n * Optional description for the schema.\r\n * Used by providers like OpenAI for better LLM guidance.\r\n */\r\n description?: string;\r\n\r\n /**\r\n * Whether to use strict mode for schema validation (OpenAI only).\r\n * When true, OpenAI enforces the schema exactly (no additional properties,\r\n * limited schema subset). Defaults to `true`.\r\n */\r\n strict?: boolean;\r\n}\r\n\r\nexport interface ChatOptions {\r\n /** Override temperature */\r\n temperature?: number;\r\n /** Max tokens to generate */\r\n maxTokens?: number;\r\n /** Tool definitions (auto-populated from registry if not set) */\r\n tools?: LLMToolDefinition[];\r\n /** Tool choice mode */\r\n toolChoice?: 'none' | 'auto' | 'required';\r\n /** Additional provider-specific parameters */\r\n parameters?: Record<string, unknown>;\r\n /** Abort signal for cancellation (forwarded to HTTP layer) */\r\n signal?: AbortSignal;\r\n /** Enable/disable tool execution for chatWithTools */\r\n executeTools?: boolean;\r\n /** Enable prompt caching (Provider specific feature, opt-in for Anthropic) */\r\n enablePromptCaching?: boolean;\r\n /** Maximum tool execution rounds (default: 10) */\r\n maxIterations?: number;\r\n /**\r\n * Stream decoder selection. Accepts:\r\n * - A built-in type name: 'passthrough' | 'standard-chat' | 'interleaved-reasoning'\r\n * - A custom type name registered via `registerDecoder()`\r\n * - A pre-built `StreamDecoder` instance for full control\r\n */\r\n decoder?: import('./stream-decoder.js').DecoderType | string | import('./stream-decoder.js').StreamDecoder;\r\n \r\n // ========================================================================\r\n // Structured Output Options\r\n // ========================================================================\r\n \r\n /**\r\n * Structured output options for chat responses.\r\n * When provided, the response will include a `structured` property\r\n * with the validated result.\r\n * \r\n * **Note**: `output` and `tools` cannot be used together.\r\n * If both are provided, an error will be thrown.\r\n * \r\n * @example\r\n * ```typescript\r\n * const response = await model.chat(messages, {\r\n * output: { schema: UserSchema },\r\n * });\r\n * console.log(response.structured);\r\n * ```\r\n */\r\n output?: OutputOptions;\r\n \r\n /**\r\n * Schema configuration for structured output.\r\n * When provided, the response is validated against this schema.\r\n * \r\n * @deprecated Use `output.schema` or `generateStructured()` instead.\r\n */\r\n schema?: import('./structured-output.js').SchemaConfig<unknown>;\r\n \r\n /**\r\n * Raw JSON Schema for structured output.\r\n * Alternative to `schema` when you have a pre-defined schema.\r\n * \r\n * @deprecated Use `output.jsonSchema` or `generateStructured()` instead.\r\n */\r\n jsonSchema?: import('./structured-output.js').JSONSchema;\r\n \r\n /**\r\n * Name for the schema (optional, used for LLM guidance).\r\n * Required by some providers (e.g., OpenAI strict mode).\r\n * \r\n * @deprecated Use `output.name` or `generateStructured()` instead.\r\n */\r\n schemaName?: string;\r\n \r\n /**\r\n * Description for the schema (optional, used for LLM guidance).\r\n * \r\n * @deprecated Use `output.description` or `generateStructured()` instead.\r\n */\r\n schemaDescription?: string;\r\n \r\n /**\r\n * Response format for structured output (legacy json_object mode).\r\n * For new code, prefer `output` or `generateStructured()`.\r\n * \r\n * Use { type: 'json_object' } for legacy JSON mode without schema validation.\r\n */\r\n responseFormat?: ResponseFormat;\r\n\r\n // ========================================================================\r\n // Inference Tier Selection\r\n // ========================================================================\r\n\r\n /** Inference tier selection (provider-specific; Google supports 'flex' and 'priority').\r\n * - 'flex': 50% cost reduction, best-effort, higher latency (background tasks)\r\n * - 'priority': Premium pricing, lowest latency, highest reliability (interactive)\r\n * - 'standard': Default behavior (omitted from request) */\r\n serviceTier?: 'flex' | 'priority' | 'standard';\r\n}\r\n\r\n// ============================================================================\r\n// Token Usage\r\n// ============================================================================\r\n\r\nexport interface TokenUsageInfo {\r\n inputTokens: number;\r\n /**\r\n * Visible output tokens (the streamed `text` content). For providers\r\n * that bill thinking separately (Google Gemini), this excludes the\r\n * reasoning trace — see `reasoningTokens`.\r\n */\r\n outputTokens: number;\r\n totalTokens: number;\r\n cachedTokens?: number;\r\n /**\r\n * Server-side reasoning/thinking tokens that were generated but not\r\n * yielded as visible text. Currently populated by the Google provider\r\n * from `usageMetadata.thoughtsTokenCount` for thinking-enabled models.\r\n * Other providers may roll thinking into `outputTokens` (Ollama) or\r\n * stream it as `thinking` events (the universal client surfaces these\r\n * via `DecodedEvent { type: 'thinking' }`); consult the provider.\r\n */\r\n reasoningTokens?: number;\r\n}\r\n\r\n// ============================================================================\r\n// Response Types\r\n// ============================================================================\r\n\r\nexport interface LLMChatResponse<T = unknown> {\r\n message: LLMChatMessage;\r\n /** Reasoning/thinking content from the model (if supported) */\r\n reasoning?: string;\r\n /** Token usage info */\r\n usage?: TokenUsageInfo;\r\n /** Tool execution trace (populated by chatWithTools) */\r\n toolExecutions?: ToolExecutionResult[];\r\n /** Which provider served this response */\r\n provider?: string;\r\n /**\r\n * Validated structured output when `output` parameter is provided to chat().\r\n * This is the same type as inferred from the schema provided in `output.schema`.\r\n * \r\n * Undefined when:\r\n * - No `output` parameter was provided\r\n * - Structured output validation failed (throws StructuredOutputError instead)\r\n * \r\n * @example\r\n * ```typescript\r\n * const response = await model.chat(messages, {\r\n * output: { schema: UserSchema },\r\n * });\r\n * if (response.structured) {\r\n * console.log(response.structured.name); // Fully typed!\r\n * }\r\n * ```\r\n */\r\n structured?: T;\r\n /** Which inference tier actually served this response (from provider response headers, e.g. x-gemini-service-tier) */\r\n serviceTier?: 'flex' | 'priority' | 'standard';\r\n}\r\n\r\n// ============================================================================\r\n// Provider Response Types (internal)\r\n// ============================================================================\r\n\r\nexport interface OllamaResponse {\r\n model: string;\r\n created_at: string;\r\n message: {\r\n role: string;\r\n content: string;\r\n thinking?: string;\r\n tool_calls?: LLMToolCall[];\r\n };\r\n done: boolean;\r\n prompt_eval_count?: number;\r\n eval_count?: number;\r\n prompt_eval_duration?: number;\r\n eval_duration?: number;\r\n}\r\n\r\nexport interface OpenAIResponse {\r\n id: string;\r\n object: string;\r\n created: number;\r\n model: string;\r\n choices: Array<{\r\n index: number;\r\n message: {\r\n role: string;\r\n content: string | null;\r\n tool_calls?: LLMToolCall[];\r\n };\r\n finish_reason: string;\r\n }>;\r\n usage?: {\r\n prompt_tokens: number;\r\n completion_tokens: number;\r\n total_tokens: number;\r\n prompt_tokens_details?: {\r\n cached_tokens?: number;\r\n audio_tokens?: number;\r\n };\r\n };\r\n}\r\n\r\nexport interface OllamaModelInfo {\r\n name: string;\r\n size: number;\r\n digest: string;\r\n details: {\r\n format: string;\r\n family: string;\r\n families: string[];\r\n parameter_size: string;\r\n quantization_level: string;\r\n };\r\n modified_at: string;\r\n}\r\n\r\nexport interface OpenAIModelInfo {\r\n id: string;\r\n object: string;\r\n created: number;\r\n owned_by: string;\r\n}\r\n\r\n// ============================================================================\r\n// Google API Types\r\n// ============================================================================\r\n\r\nexport interface GooglePart {\r\n text?: string;\r\n functionCall?: {\r\n name: string;\r\n args: Record<string, unknown>;\r\n };\r\n functionResponse?: {\r\n name: string;\r\n response: Record<string, unknown>;\r\n };\r\n inlineData?: {\r\n mimeType: string;\r\n data: string;\r\n };\r\n /** Gemini 3.x thought signature — must be echoed back on functionCall parts */\r\n thoughtSignature?: string;\r\n}\r\n\r\nexport interface GoogleContent {\r\n role: 'user' | 'model' | 'function';\r\n parts: GooglePart[];\r\n}\r\n\r\nexport interface GoogleGenerationConfig {\r\n responseMimeType?: string;\r\n temperature?: number;\r\n maxOutputTokens?: number;\r\n topK?: number;\r\n topP?: number;\r\n thinkingConfig?: {\r\n thinkingBudget?: number;\r\n };\r\n}\r\n\r\nexport interface GoogleFunctionDeclaration {\r\n name: string;\r\n description: string;\r\n parameters: {\r\n type: 'object';\r\n properties: Record<string, unknown>;\r\n required?: string[];\r\n };\r\n}\r\n\r\nexport interface GoogleToolConfig {\r\n functionCallingConfig?: {\r\n mode: 'AUTO' | 'ANY' | 'NONE';\r\n allowedFunctionNames?: string[];\r\n };\r\n}\r\n\r\nexport interface GoogleRequest {\r\n contents: GoogleContent[];\r\n generationConfig?: GoogleGenerationConfig;\r\n systemInstruction?: { parts: Array<{ text: string }> };\r\n tools?: Array<{\r\n functionDeclarations: GoogleFunctionDeclaration[];\r\n }>;\r\n toolConfig?: GoogleToolConfig;\r\n /** Inference tier: FLEX (50% off, best-effort) or PRIORITY (premium, highest reliability) */\r\n service_tier?: 'FLEX' | 'PRIORITY' | 'STANDARD';\r\n}\r\n\r\nexport interface GoogleCandidate {\r\n content: {\r\n parts: GooglePart[];\r\n role: string;\r\n };\r\n finishReason?: string;\r\n index: number;\r\n}\r\n\r\nexport interface GoogleResponse {\r\n candidates: GoogleCandidate[];\r\n usageMetadata?: {\r\n promptTokenCount: number;\r\n candidatesTokenCount: number;\r\n totalTokenCount: number;\r\n cachedContentTokenCount?: number;\r\n /**\r\n * Server-side reasoning tokens emitted by Gemini thinking models\r\n * (e.g. 2.5 Pro / 3.x Pro). Counted toward billing as output but\r\n * not included in `candidatesTokenCount` and not streamed as text.\r\n */\r\n thoughtsTokenCount?: number;\r\n };\r\n}\r\n\r\n// ============================================================================\r\n// Helper Functions\r\n// ============================================================================\r\n\r\n/** Create a text content part */\r\nexport function textContent(text: string): LLMTextContent {\r\n return { type: 'text', text };\r\n}\r\n\r\n/** Create an image content part from base64 data or URL */\r\nexport function imageContent(\r\n base64DataOrUrl: string,\r\n mimeType: string = 'image/jpeg',\r\n detail?: 'auto' | 'low' | 'high',\r\n): LLMImageContent {\r\n const url = base64DataOrUrl.startsWith('data:') || base64DataOrUrl.startsWith('http')\r\n ? base64DataOrUrl\r\n : `data:${mimeType};base64,${base64DataOrUrl}`;\r\n return {\r\n type: 'image_url',\r\n image_url: { url, detail },\r\n };\r\n}\r\n\r\n/** Create a multimodal user message with text and images */\r\nexport function multimodalMessage(\r\n text: string,\r\n images: string[],\r\n mimeType: string = 'image/jpeg',\r\n): LLMChatMessage {\r\n const content: LLMContentPart[] = [\r\n textContent(text),\r\n ...images.map(img => imageContent(img, mimeType)),\r\n ];\r\n return { role: 'user', content };\r\n}\r\n\r\n/** Extract text content from a message content value */\r\nexport function extractTextContent(content: LLMMessageContent): string {\r\n if (typeof content === 'string') return content;\r\n return content\r\n .filter((part): part is LLMTextContent => part.type === 'text')\r\n .map(part => part.text)\r\n .join('');\r\n}\r\n\r\n/** Check if message content contains images */\r\nexport function hasImages(content: LLMMessageContent): boolean {\r\n if (typeof content === 'string') return false;\r\n return content.some(part => part.type === 'image_url');\r\n}\r\n\r\n/** Create an audio content part from raw base64 data */\r\nexport function audioContent(base64Data: string, mimeType: string): LLMAudioContent {\r\n return {\r\n type: 'audio',\r\n audio: { data: base64Data, mimeType },\r\n };\r\n}\r\n\r\n/** Check if message content contains audio */\r\nexport function hasAudio(content: LLMMessageContent): boolean {\r\n if (typeof content === 'string') return false;\r\n return content.some(part => part.type === 'audio');\r\n}\r\n"]}
package/dist/mcp.d.ts.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../src/mcp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAE7C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAO5C,MAAM,WAAW,eAAe;IAC5B,uDAAuD;IACvD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,iDAAiD;IACjD,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,qEAAqE;IACrE,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,mDAAmD;IACnD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,sDAAsD;IACtD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACpC;AAED,MAAM,WAAW,eAAe;IAC5B,sCAAsC;IACtC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IACzC,gCAAgC;IACh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wBAC1B,IAAI,EAAE,OAAO,CAAC,IAAI;qBACrB;iBACJ,CAAC,CAAC;gBACH,MAAM,KAAK,CAAC;YAChB,CAAC;QACL,CAAC,CAAC;IACN,CAAC;IAEO,kBAAkB,CAAC,MAA+B;QACtD,OAAO;YACH,IAAI,EAAE,QAAQ;YACd,UAAU,EAAG,MAAM,CAAC,YAAY,CAA6B,IAAI,EAAE;YACnE,QAAQ,EAAE,MAAM,CAAC,UAAU,CAAyB;SACvD,CAAC;IACN,CAAC;CACJ","sourcesContent":["/**\r\n * Universal LLM Client v3 — MCP Integration\r\n *\r\n * Native MCP tool discovery and execution bridge.\r\n * Uses @modelcontextprotocol/sdk as a peer dependency.\r\n *\r\n * Supports:\r\n * - Stdio transport (Node/Bun/Deno — spawns server processes)\r\n * - Streamable HTTP transport (all runtimes including browsers)\r\n *\r\n * Usage:\r\n * const mcp = new MCPToolBridge({\r\n * servers: {\r\n * filesystem: { command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', './'] },\r\n * weather: { url: 'https://mcp.example.com/weather' },\r\n * }\r\n * });\r\n * await mcp.connect();\r\n * await mcp.registerTools(model); // or registerTools(model)\r\n * // ... use model.chatWithTools() — MCP tools are now callable\r\n * await mcp.disconnect();\r\n */\r\n\r\nimport type { AIModel } from './ai-model.js';\r\nimport type { LLMFunction, ToolHandler } from './interfaces.js';\r\nimport type { Auditor } from './auditor.js';\r\nimport { NoopAuditor } from './auditor.js';\r\n\r\n// ============================================================================\r\n// MCP Types\r\n// ============================================================================\r\n\r\nexport interface MCPServerConfig {\r\n /** Stdio transport: command to spawn the MCP server */\r\n command?: string;\r\n /** Stdio transport: arguments for the command */\r\n args?: string[];\r\n /** Stdio transport: environment variables for the spawned process */\r\n env?: Record<string, string>;\r\n /** HTTP transport: URL of the remote MCP server */\r\n url?: string;\r\n /** HTTP transport: additional headers for requests */\r\n headers?: Record<string, string>;\r\n}\r\n\r\nexport interface MCPBridgeConfig {\r\n /** Named MCP server configurations */\r\n servers: Record<string, MCPServerConfig>;\r\n /** Auditor for observability */\r\n auditor?: Auditor;\r\n}\r\n\r\nexport interface MCPTool {\r\n /** Server this tool came from */\r\n serverName: string;\r\n /** Tool name (as reported by the server) */\r\n name: string;\r\n /** Full qualified name (serverName:toolName) */\r\n qualifiedName: string;\r\n /** Tool description */\r\n description: string;\r\n /** JSON Schema for tool input */\r\n inputSchema: Record<string, unknown>;\r\n}\r\n\r\n// ============================================================================\r\n// Internal: SDK types (to avoid hard dependency)\r\n// ============================================================================\r\n\r\ninterface MCPClientLike {\r\n connect(transport: unknown): Promise<void>;\r\n close(): Promise<void>;\r\n listTools(): Promise<{ tools: Array<{ name: string; description?: string; inputSchema: Record<string, unknown> }> }>;\r\n callTool(params: { name: string; arguments?: Record<string, unknown> }): Promise<{ content: Array<{ type: string; text?: string }> }>;\r\n}\r\n\r\n// ============================================================================\r\n// MCPToolBridge\r\n// ============================================================================\r\n\r\nexport class MCPToolBridge {\r\n private config: MCPBridgeConfig;\r\n private auditor: Auditor;\r\n private clients: Map<string, MCPClientLike> = new Map();\r\n private transports: Map<string, unknown> = new Map();\r\n private discoveredTools: MCPTool[] = [];\r\n private connected = false;\r\n\r\n constructor(config: MCPBridgeConfig) {\r\n this.config = config;\r\n this.auditor = config.auditor ?? new NoopAuditor();\r\n }\r\n\r\n // ========================================================================\r\n // Connection Lifecycle\r\n // ========================================================================\r\n\r\n /**\r\n * Connect to all configured MCP servers and discover their tools.\r\n * Requires @modelcontextprotocol/sdk to be installed.\r\n */\r\n async connect(): Promise<void> {\r\n if (this.connected) return;\r\n\r\n // Dynamic import of MCP SDK (peer dependency)\r\n let sdk: {\r\n Client: new (info: { name: string; version: string }, opts?: { capabilities?: Record<string, unknown> }) => MCPClientLike;\r\n StdioClientTransport?: new (opts: { command: string; args?: string[]; env?: Record<string, string> }) => unknown;\r\n StreamableHTTPClientTransport?: new (url: URL, opts?: { requestInit?: { headers: Record<string, string> } }) => unknown;\r\n };\r\n\r\n try {\r\n // @ts-ignore — peer dependency, may not be installed\r\n sdk = await import('@modelcontextprotocol/sdk/client/index.js');\r\n } catch {\r\n throw new Error(\r\n 'MCP integration requires @modelcontextprotocol/sdk.\\n' +\r\n 'Install it: bun add @modelcontextprotocol/sdk'\r\n );\r\n }\r\n\r\n const entries = Object.entries(this.config.servers);\r\n\r\n for (const [serverName, serverConfig] of entries) {\r\n try {\r\n const client = new sdk.Client(\r\n { name: 'universal-llm-client', version: '3.0.0' },\r\n { capabilities: {} },\r\n );\r\n\r\n let transport: unknown;\r\n\r\n if (serverConfig.url) {\r\n // HTTP transport (all runtimes)\r\n if (!sdk.StreamableHTTPClientTransport) {\r\n // Try separate import path\r\n // @ts-ignore — peer dependency, may not be installed\r\n const httpModule = await import('@modelcontextprotocol/sdk/client/streamableHttp.js').catch(() => null);\r\n if (!httpModule?.StreamableHTTPClientTransport) {\r\n throw new Error('StreamableHTTPClientTransport not available in this SDK version');\r\n }\r\n transport = new httpModule.StreamableHTTPClientTransport(\r\n new URL(serverConfig.url),\r\n serverConfig.headers ? { requestInit: { headers: serverConfig.headers } } : undefined,\r\n );\r\n } else {\r\n transport = new sdk.StreamableHTTPClientTransport(\r\n new URL(serverConfig.url),\r\n serverConfig.headers ? { requestInit: { headers: serverConfig.headers } } : undefined,\r\n );\r\n }\r\n } else if (serverConfig.command) {\r\n // Stdio transport (Node/Bun/Deno only)\r\n if (!sdk.StdioClientTransport) {\r\n // @ts-ignore — peer dependency, may not be installed\r\n const stdioModule = await import('@modelcontextprotocol/sdk/client/stdio.js').catch(() => null);\r\n if (!stdioModule?.StdioClientTransport) {\r\n throw new Error(\r\n 'Stdio transport not available. This is expected in browser environments.\\n' +\r\n 'Use HTTP transport (url) instead, or run in Node/Bun/Deno.'\r\n );\r\n }\r\n transport = new stdioModule.StdioClientTransport({\r\n command: serverConfig.command,\r\n args: serverConfig.args,\r\n env: serverConfig.env,\r\n });\r\n } else {\r\n transport = new sdk.StdioClientTransport({\r\n command: serverConfig.command,\r\n args: serverConfig.args,\r\n env: serverConfig.env,\r\n });\r\n }\r\n } else {\r\n throw new Error(`MCP server \"${serverName}\" must have either \"url\" or \"command\" configured`);\r\n }\r\n\r\n await client.connect(transport);\r\n this.clients.set(serverName, client);\r\n this.transports.set(serverName, transport);\r\n\r\n // Discover tools\r\n const toolList = await client.listTools();\r\n for (const tool of toolList.tools) {\r\n this.discoveredTools.push({\r\n serverName,\r\n name: tool.name,\r\n qualifiedName: `${serverName}:${tool.name}`,\r\n description: tool.description ?? '',\r\n inputSchema: tool.inputSchema,\r\n });\r\n }\r\n\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'response',\r\n metadata: {\r\n event: 'mcp_connected',\r\n server: serverName,\r\n toolCount: toolList.tools.length,\r\n },\r\n });\r\n } catch (error) {\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'error',\r\n error: error instanceof Error ? error.message : String(error),\r\n metadata: { event: 'mcp_connect_failed', server: serverName },\r\n });\r\n throw error;\r\n }\r\n }\r\n\r\n this.connected = true;\r\n }\r\n\r\n // ========================================================================\r\n // Tool Registration\r\n // ========================================================================\r\n\r\n /**\r\n * Register all discovered MCP tools with an AIModel instance.\r\n * Each MCP tool becomes a callable tool that forwards execution\r\n * to the appropriate MCP server.\r\n */\r\n async registerTools(model: AIModel): Promise<void> {\r\n if (!this.connected) {\r\n await this.connect();\r\n }\r\n\r\n const tools = this.discoveredTools.map(mcpTool => ({\r\n name: mcpTool.qualifiedName,\r\n description: mcpTool.description,\r\n parameters: this.convertInputSchema(mcpTool.inputSchema),\r\n handler: this.createToolHandler(mcpTool),\r\n }));\r\n\r\n model.registerTools(tools);\r\n }\r\n\r\n /**\r\n * Get all discovered MCP tools (for inspection).\r\n */\r\n getTools(): ReadonlyArray<MCPTool> {\r\n return this.discoveredTools;\r\n }\r\n\r\n // ========================================================================\r\n // Disconnect\r\n // ========================================================================\r\n\r\n /**\r\n * Disconnect from all MCP servers and clean up.\r\n */\r\n async disconnect(): Promise<void> {\r\n for (const [serverName, client] of this.clients) {\r\n try {\r\n await client.close();\r\n } catch (error) {\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'error',\r\n error: error instanceof Error ? error.message : String(error),\r\n metadata: { event: 'mcp_disconnect_failed', server: serverName },\r\n });\r\n }\r\n }\r\n this.clients.clear();\r\n this.transports.clear();\r\n this.discoveredTools = [];\r\n this.connected = false;\r\n }\r\n\r\n // ========================================================================\r\n // Internal\r\n // ========================================================================\r\n\r\n private createToolHandler(mcpTool: MCPTool): ToolHandler {\r\n return async (args: unknown) => {\r\n const client = this.clients.get(mcpTool.serverName);\r\n if (!client) {\r\n throw new Error(`MCP server \"${mcpTool.serverName}\" is not connected`);\r\n }\r\n\r\n const start = Date.now();\r\n this.auditor.record({\r\n timestamp: start,\r\n type: 'tool_call',\r\n metadata: {\r\n event: 'mcp_tool_call',\r\n server: mcpTool.serverName,\r\n tool: mcpTool.name,\r\n },\r\n });\r\n\r\n try {\r\n const result = await client.callTool({\r\n name: mcpTool.name,\r\n arguments: args as Record<string, unknown> | undefined,\r\n });\r\n\r\n // Extract text content from MCP response\r\n const textParts = result.content\r\n .filter(c => c.type === 'text' && c.text)\r\n .map(c => c.text);\r\n\r\n const output = textParts.length === 1 ? textParts[0] : textParts.join('\\n');\r\n\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'tool_result',\r\n metadata: {\r\n event: 'mcp_tool_result',\r\n server: mcpTool.serverName,\r\n tool: mcpTool.name,\r\n duration: Date.now() - start,\r\n },\r\n });\r\n\r\n return output;\r\n } catch (error) {\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'error',\r\n error: error instanceof Error ? error.message : String(error),\r\n metadata: {\r\n event: 'mcp_tool_error',\r\n server: mcpTool.serverName,\r\n tool: mcpTool.name,\r\n },\r\n });\r\n throw error;\r\n }\r\n };\r\n }\r\n\r\n private convertInputSchema(schema: Record<string, unknown>): LLMFunction['parameters'] {\r\n return {\r\n type: 'object',\r\n properties: (schema['properties'] as Record<string, unknown>) ?? {},\r\n required: schema['required'] as string[] | undefined,\r\n };\r\n }\r\n}\r\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../src/providers/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAG7C,OAAO,KAAK,EACR,gBAAgB,EAChB,cAAc,EACd,eAAe,EAGf,WAAW,EAEX,aAAa,EAGhB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AA8J7C,qBAAa,eAAgB,SAAQ,aAAa;IAC9C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;gBAErB,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,OAAO;IAUxD,OAAO,CAAC,qBAAqB;IAed,IAAI,CACf,QAAQ,EAAE,cAAc,EAAE,EAC1B,OAAO,CAAC,EAAE,WAAW,GACtB,OAAO,CAAC,eAAe,CAAC;IAsCX,UAAU,CACtB,QAAQ,EAAE,cAAc,EAAE,EAC1B,OAAO,CAAC,EAAE,WAAW,GACtB,cAAc,CAAC,YAAY,EAAE,eAAe,GAAG,IAAI,EAAE,OAAO,CAAC;IAoKjD,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAQvC,SAAS,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAoB9B,YAAY,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC;IAyBxE,OAAO,CAAC,gBAAgB;IAiDxB;;;;;;OAMG;IACH,OAAO,CAAC,eAAe;IA2EvB;;OAEG;IACH,OAAO,CAAC,kBAAkB;IA0C1B;;;OAGG;IACH,OAAO,CAAC,iBAAiB;I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I,OAAO,OAAO,KAAK,QAAQ;YAAE,OAAO,OAAO,CAAC;QAChD,OAAQ,OAA4B;aAC/B,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;aACrE,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;aAChB,IAAI,CAAC,EAAE,CAAC,CAAC;IAClB,CAAC;CACJ","sourcesContent":["/**\r\n * Universal LLM Client v3 — Anthropic Messages API Provider\r\n *\r\n * Implements BaseLLMClient for Anthropic's Messages API (Claude).\r\n * Uses the custom Anthropic protocol — NOT OpenAI-compatible.\r\n *\r\n * Key differences from OpenAI:\r\n * - Endpoint: POST /v1/messages (not /chat/completions)\r\n * - Auth: x-api-key header (not Authorization: Bearer)\r\n * - System prompt: top-level `system` field, not a message\r\n * - Messages: content is always an array of content blocks\r\n * - Tool calls: `tool_use` content blocks (not tool_calls array)\r\n * - Tool results: `tool_result` content blocks in user messages\r\n * - Streaming: content_block_start/delta/stop events with typed deltas\r\n */\r\n\r\nimport { BaseLLMClient } from '../client.js';\r\nimport { httpRequest, httpStream, parseSSE } from '../http.js';\r\nimport { StandardChatDecoder } from '../stream-decoder.js';\r\nimport type {\r\n LLMClientOptions,\r\n LLMChatMessage,\r\n LLMChatResponse,\r\n LLMToolCall,\r\n LLMToolDefinition,\r\n ChatOptions,\r\n TokenUsageInfo,\r\n ModelMetadata,\r\n LLMContentPart,\r\n LLMMessageContent,\r\n} from '../interfaces.js';\r\nimport type { DecodedEvent } from '../stream-decoder.js';\r\nimport type { Auditor } from '../auditor.js';\r\n\r\n// ============================================================================\r\n// Anthropic-Specific Types\r\n// ============================================================================\r\n\r\n/** Anthropic content block types */\r\ninterface AnthropicTextBlock {\r\n readonly type: 'text';\r\n readonly text: string;\r\n}\r\n\r\ninterface AnthropicImageBlock {\r\n readonly type: 'image';\r\n readonly source: {\r\n readonly type: 'base64' | 'url';\r\n readonly media_type?: string;\r\n readonly data?: string;\r\n readonly url?: string;\r\n };\r\n}\r\n\r\ninterface AnthropicToolUseBlock {\r\n readonly type: 'tool_use';\r\n readonly id: string;\r\n readonly name: string;\r\n readonly input: Record<string, unknown>;\r\n}\r\n\r\ninterface AnthropicToolResultBlock {\r\n readonly type: 'tool_result';\r\n readonly tool_call_id: string;\r\n readonly content: string | AnthropicTextBlock[];\r\n}\r\n\r\ninterface AnthropicThinkingBlock {\r\n readonly type: 'thinking';\r\n readonly thinking: string;\r\n readonly signature: string;\r\n}\r\n\r\ntype AnthropicContentBlock =\r\n | AnthropicTextBlock\r\n | AnthropicImageBlock\r\n | AnthropicToolUseBlock\r\n | AnthropicToolResultBlock\r\n | AnthropicThinkingBlock;\r\n\r\n/** Anthropic message format */\r\ninterface AnthropicMessage {\r\n readonly role: 'user' | 'assistant';\r\n readonly content: string | AnthropicContentBlock[];\r\n}\r\n\r\n/** Anthropic tool definition (uses input_schema, not parameters) */\r\ninterface AnthropicToolDef {\r\n readonly name: string;\r\n readonly description: string;\r\n readonly input_schema: {\r\n readonly type: 'object';\r\n readonly properties?: Record<string, unknown>;\r\n readonly required?: string[];\r\n };\r\n}\r\n\r\n/** Anthropic request body */\r\ninterface AnthropicRequest {\r\n readonly model: string;\r\n readonly messages: AnthropicMessage[];\r\n readonly max_tokens: number;\r\n readonly system?: string;\r\n readonly tools?: AnthropicToolDef[];\r\n readonly tool_choice?: { readonly type: 'auto' | 'any' | 'tool'; readonly name?: string };\r\n readonly stream?: boolean;\r\n readonly temperature?: number;\r\n}\r\n\r\n/** Anthropic non-streaming response */\r\ninterface AnthropicResponse {\r\n readonly id: string;\r\n readonly type: 'message';\r\n readonly role: 'assistant';\r\n readonly content: AnthropicContentBlock[];\r\n readonly model: string;\r\n readonly stop_reason: 'end_turn' | 'max_tokens' | 'stop_sequence' | 'tool_use' | null;\r\n readonly usage: {\r\n readonly input_tokens: number;\r\n readonly output_tokens: number;\r\n };\r\n}\r\n\r\n/** Anthropic model from models list */\r\ninterface AnthropicModelInfo {\r\n readonly id: string;\r\n readonly display_name: string;\r\n readonly created_at: string;\r\n readonly type: 'model';\r\n}\r\n\r\n// ============================================================================\r\n// Streaming Event Types\r\n// ============================================================================\r\n\r\ninterface StreamMessageStart {\r\n readonly type: 'message_start';\r\n readonly message: AnthropicResponse;\r\n}\r\n\r\ninterface StreamContentBlockStart {\r\n readonly type: 'content_block_start';\r\n readonly index: number;\r\n readonly content_block: AnthropicContentBlock;\r\n}\r\n\r\ninterface StreamContentBlockDelta {\r\n readonly type: 'content_block_delta';\r\n readonly index: number;\r\n readonly delta:\r\n | { readonly type: 'text_delta'; readonly text: string }\r\n | { readonly type: 'input_json_delta'; readonly partial_json: string }\r\n | { readonly type: 'thinking_delta'; readonly thinking: string }\r\n | { readonly type: 'signature_delta'; readonly signature: string };\r\n}\r\n\r\ninterface StreamContentBlockStop {\r\n readonly type: 'content_block_stop';\r\n readonly index: number;\r\n}\r\n\r\ninterface StreamMessageDelta {\r\n readonly type: 'message_delta';\r\n readonly delta: {\r\n readonly stop_reason: string | null;\r\n readonly stop_sequence?: string | null;\r\n };\r\n readonly usage: {\r\n readonly output_tokens: number;\r\n };\r\n}\r\n\r\ninterface StreamMessageStop {\r\n readonly type: 'message_stop';\r\n}\r\n\r\ntype AnthropicStreamEvent =\r\n | StreamMessageStart\r\n | StreamContentBlockStart\r\n | StreamContentBlockDelta\r\n | StreamContentBlockStop\r\n | StreamMessageDelta\r\n | StreamMessageStop\r\n | { readonly type: 'ping' }\r\n | { readonly type: 'error'; readonly error: { readonly type: string; readonly message: string } };\r\n\r\n// ============================================================================\r\n// Anthropic Client\r\n// ============================================================================\r\n\r\nexport class AnthropicClient extends BaseLLMClient {\r\n private readonly baseUrl: string;\r\n\r\n constructor(options: LLMClientOptions, auditor?: Auditor) {\r\n const url = (options.url || 'https://api.anthropic.com').replace(/\\/+$/, '');\r\n super({ ...options, url }, auditor);\r\n this.baseUrl = url;\r\n }\r\n\r\n // ========================================================================\r\n // Headers\r\n // ========================================================================\r\n\r\n private buildAnthropicHeaders(): Record<string, string> {\r\n const headers: Record<string, string> = {\r\n 'Content-Type': 'application/json',\r\n 'anthropic-version': '2023-06-01',\r\n };\r\n if (this.options.apiKey) {\r\n headers['x-api-key'] = this.options.apiKey;\r\n }\r\n return headers;\r\n }\r\n\r\n // ========================================================================\r\n // Chat (non-streaming)\r\n // ========================================================================\r\n\r\n override async chat(\r\n messages: LLMChatMessage[],\r\n options?: ChatOptions,\r\n ): Promise<LLMChatResponse> {\r\n const url = `${this.baseUrl}/v1/messages`;\r\n const body = this.buildRequestBody(messages, options, false);\r\n\r\n const start = Date.now();\r\n this.auditor.record({\r\n timestamp: start,\r\n type: 'request',\r\n provider: 'anthropic',\r\n model: this.options.model,\r\n });\r\n\r\n const response = await httpRequest<AnthropicResponse>(url, {\r\n method: 'POST',\r\n headers: this.buildAnthropicHeaders(),\r\n body,\r\n timeout: this.options.timeout ?? 60000,\r\n });\r\n\r\n const data = response.data;\r\n const result = this.parseAnthropicResponse(data);\r\n\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'response',\r\n provider: 'anthropic',\r\n model: this.options.model,\r\n duration: Date.now() - start,\r\n usage: result.usage,\r\n });\r\n\r\n return result;\r\n }\r\n\r\n // ========================================================================\r\n // Streaming\r\n // ========================================================================\r\n\r\n override async *chatStream(\r\n messages: LLMChatMessage[],\r\n options?: ChatOptions,\r\n ): AsyncGenerator<DecodedEvent, LLMChatResponse | void, unknown> {\r\n const url = `${this.baseUrl}/v1/messages`;\r\n const body = this.buildRequestBody(messages, options, true);\r\n\r\n const start = Date.now();\r\n this.auditor.record({\r\n timestamp: start,\r\n type: 'stream_start',\r\n provider: 'anthropic',\r\n model: this.options.model,\r\n });\r\n\r\n const decoder = new StandardChatDecoder(() => {});\r\n\r\n // Track content blocks as they stream in\r\n const contentBlocks: Map<number, {\r\n type: string;\r\n text: string;\r\n toolId?: string;\r\n toolName?: string;\r\n inputJson?: string;\r\n thinking?: string;\r\n signature?: string;\r\n }> = new Map();\r\n\r\n let usage: TokenUsageInfo | undefined;\r\n let inputTokens = 0;\r\n\r\n const stream = httpStream(url, {\r\n method: 'POST',\r\n headers: this.buildAnthropicHeaders(),\r\n body,\r\n timeout: this.options.timeout ?? 120000,\r\n });\r\n\r\n for await (const { data } of parseSSE(stream)) {\r\n try {\r\n const event = JSON.parse(data) as AnthropicStreamEvent;\r\n\r\n switch (event.type) {\r\n case 'message_start': {\r\n inputTokens = event.message.usage?.input_tokens ?? 0;\r\n break;\r\n }\r\n\r\n case 'content_block_start': {\r\n const block = event.content_block;\r\n if (block.type === 'text') {\r\n contentBlocks.set(event.index, { type: 'text', text: '' });\r\n } else if (block.type === 'tool_use') {\r\n contentBlocks.set(event.index, {\r\n type: 'tool_use',\r\n text: '',\r\n toolId: block.id,\r\n toolName: block.name,\r\n inputJson: '',\r\n });\r\n } else if (block.type === 'thinking') {\r\n contentBlocks.set(event.index, { type: 'thinking', text: '', thinking: '' });\r\n }\r\n break;\r\n }\r\n\r\n case 'content_block_delta': {\r\n const block = contentBlocks.get(event.index);\r\n if (!block) break;\r\n\r\n if (event.delta.type === 'text_delta') {\r\n block.text += event.delta.text;\r\n decoder.push(event.delta.text);\r\n yield { type: 'text', content: event.delta.text };\r\n } else if (event.delta.type === 'input_json_delta') {\r\n block.inputJson = (block.inputJson ?? '') + event.delta.partial_json;\r\n } else if (event.delta.type === 'thinking_delta') {\r\n block.thinking = (block.thinking ?? '') + event.delta.thinking;\r\n decoder.pushReasoning(event.delta.thinking);\r\n yield { type: 'thinking', content: event.delta.thinking };\r\n } else if (event.delta.type === 'signature_delta') {\r\n block.signature = event.delta.signature;\r\n }\r\n break;\r\n }\r\n\r\n case 'content_block_stop': {\r\n const block = contentBlocks.get(event.index);\r\n if (block?.type === 'tool_use' && block.toolId && block.toolName) {\r\n // Parse accumulated JSON and emit tool call\r\n const toolCall: LLMToolCall = {\r\n id: block.toolId,\r\n type: 'function',\r\n function: {\r\n name: block.toolName,\r\n arguments: block.inputJson ?? '{}',\r\n },\r\n };\r\n yield { type: 'tool_call', calls: [toolCall] };\r\n }\r\n break;\r\n }\r\n\r\n case 'message_delta': {\r\n const outputTokens = event.usage?.output_tokens ?? 0;\r\n usage = {\r\n inputTokens,\r\n outputTokens,\r\n totalTokens: inputTokens + outputTokens,\r\n };\r\n break;\r\n }\r\n\r\n case 'error': {\r\n throw new Error(`Anthropic stream error: ${event.error.type} — ${event.error.message}`);\r\n }\r\n }\r\n } catch (e) {\r\n if (e instanceof Error && e.message.startsWith('Anthropic stream error')) {\r\n throw e;\r\n }\r\n // Skip unparseable SSE data\r\n }\r\n }\r\n\r\n decoder.flush();\r\n\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'stream_end',\r\n provider: 'anthropic',\r\n model: this.options.model,\r\n duration: Date.now() - start,\r\n usage,\r\n });\r\n\r\n // Build final tool calls from accumulated content blocks\r\n const toolCalls: LLMToolCall[] = [];\r\n for (const block of contentBlocks.values()) {\r\n if (block.type === 'tool_use' && block.toolId && block.toolName) {\r\n toolCalls.push({\r\n id: block.toolId,\r\n type: 'function',\r\n function: {\r\n name: block.toolName,\r\n arguments: block.inputJson ?? '{}',\r\n },\r\n });\r\n }\r\n }\r\n\r\n return {\r\n message: {\r\n role: 'assistant',\r\n content: decoder.getCleanContent(),\r\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\r\n },\r\n reasoning: decoder.getReasoning(),\r\n usage,\r\n provider: 'anthropic',\r\n };\r\n }\r\n\r\n // ========================================================================\r\n // Embeddings (not supported by Anthropic)\r\n // ========================================================================\r\n\r\n override async embed(_text: string): Promise<number[]> {\r\n throw new Error('Anthropic does not support embeddings. Use a different provider.');\r\n }\r\n\r\n // ========================================================================\r\n // Model Discovery\r\n // ========================================================================\r\n\r\n override async getModels(): Promise<string[]> {\r\n const url = `${this.baseUrl}/v1/models`;\r\n try {\r\n const response = await httpRequest<{\r\n data: AnthropicModelInfo[];\r\n }>(url, {\r\n headers: this.buildAnthropicHeaders(),\r\n timeout: 5000,\r\n });\r\n return response.data.data.map(m => m.id);\r\n } catch {\r\n // Fallback: return well-known Claude models\r\n return [\r\n 'claude-sonnet-4-20250514',\r\n 'claude-haiku-4-20250514',\r\n 'claude-opus-4-20250514',\r\n ];\r\n }\r\n }\r\n\r\n override async getModelInfo(_modelName?: string): Promise<ModelMetadata> {\r\n // Claude models support large context windows\r\n const model = _modelName ?? this.options.model;\r\n\r\n // Claude 4 models have 200K context\r\n if (model.includes('claude-4') || model.includes('claude-opus') ||\r\n model.includes('claude-sonnet') || model.includes('claude-haiku')) {\r\n return {\r\n model,\r\n contextLength: 200_000,\r\n capabilities: ['tools', 'vision', 'thinking'],\r\n };\r\n }\r\n\r\n return {\r\n model,\r\n contextLength: 200_000,\r\n capabilities: ['tools', 'vision'],\r\n };\r\n }\r\n\r\n // ========================================================================\r\n // Internal: Request Building\r\n // ========================================================================\r\n\r\n private buildRequestBody(\r\n messages: LLMChatMessage[],\r\n options: ChatOptions | undefined,\r\n stream: boolean,\r\n ): AnthropicRequest {\r\n // Extract system prompt from messages\r\n const systemMessages = messages.filter(m => m.role === 'system');\r\n const nonSystemMessages = messages.filter(m => m.role !== 'system');\r\n\r\n const systemPrompt = systemMessages.length > 0\r\n ? systemMessages\r\n .map(m => typeof m.content === 'string' ? m.content : this.extractText(m.content))\r\n .join('\\n\\n')\r\n : undefined;\r\n\r\n // Convert tools from OpenAI format to Anthropic format\r\n const tools = options?.tools ?? (\r\n Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined\r\n );\r\n const anthropicTools = tools?.map(t => this.convertToolDef(t));\r\n\r\n // Map tool_choice\r\n let toolChoice: AnthropicRequest['tool_choice'];\r\n if (options?.toolChoice === 'required') {\r\n toolChoice = { type: 'any' };\r\n } else if (options?.toolChoice === 'none') {\r\n toolChoice = { type: 'auto' }; // Anthropic doesn't have 'none', closest is 'auto'\r\n } else if (options?.toolChoice === 'auto') {\r\n toolChoice = { type: 'auto' };\r\n }\r\n\r\n const body: AnthropicRequest = {\r\n model: this.options.model,\r\n messages: this.convertMessages(nonSystemMessages),\r\n max_tokens: options?.maxTokens ?? 4096,\r\n ...(systemPrompt && { system: systemPrompt }),\r\n ...(anthropicTools?.length && { tools: anthropicTools }),\r\n ...(toolChoice && { tool_choice: toolChoice }),\r\n ...(stream && { stream: true }),\r\n ...(options?.temperature !== undefined && { temperature: options.temperature }),\r\n };\r\n\r\n return body;\r\n }\r\n\r\n // ========================================================================\r\n // Internal: Message Conversion\r\n // ========================================================================\r\n\r\n /**\r\n * Convert our canonical LLMChatMessage[] to Anthropic's message format.\r\n * Key conversions:\r\n * - 'tool' role messages → merged into preceding user message as tool_result blocks\r\n * - assistant messages with tool_calls → assistant message with tool_use blocks\r\n * - multimodal content → Anthropic image blocks\r\n */\r\n private convertMessages(messages: LLMChatMessage[]): AnthropicMessage[] {\r\n const result: AnthropicMessage[] = [];\r\n\r\n for (let i = 0; i < messages.length; i++) {\r\n const msg = messages[i]!;\r\n\r\n if (msg.role === 'assistant') {\r\n // Build content blocks for assistant\r\n const blocks: AnthropicContentBlock[] = [];\r\n\r\n // Add text content if present\r\n const text = typeof msg.content === 'string'\r\n ? msg.content\r\n : this.extractText(msg.content);\r\n if (text) {\r\n blocks.push({ type: 'text', text });\r\n }\r\n\r\n // Convert tool_calls to tool_use blocks\r\n if (msg.tool_calls) {\r\n for (const tc of msg.tool_calls) {\r\n let input: Record<string, unknown> = {};\r\n try {\r\n input = JSON.parse(tc.function.arguments);\r\n } catch {\r\n // Keep empty object if parse fails\r\n }\r\n blocks.push({\r\n type: 'tool_use',\r\n id: tc.id,\r\n name: tc.function.name,\r\n input,\r\n });\r\n }\r\n }\r\n\r\n if (blocks.length > 0) {\r\n result.push({ role: 'assistant', content: blocks });\r\n }\r\n } else if (msg.role === 'tool') {\r\n // Anthropic needs tool results inside user messages\r\n const toolResultBlock: AnthropicToolResultBlock = {\r\n type: 'tool_result',\r\n tool_call_id: msg.tool_call_id ?? '',\r\n content: typeof msg.content === 'string'\r\n ? msg.content\r\n : this.extractText(msg.content),\r\n };\r\n\r\n // Collect consecutive tool results\r\n const toolResults: AnthropicContentBlock[] = [toolResultBlock];\r\n while (i + 1 < messages.length && messages[i + 1]!.role === 'tool') {\r\n i++;\r\n const nextMsg = messages[i]!;\r\n toolResults.push({\r\n type: 'tool_result',\r\n tool_call_id: nextMsg.tool_call_id ?? '',\r\n content: typeof nextMsg.content === 'string'\r\n ? nextMsg.content\r\n : this.extractText(nextMsg.content),\r\n });\r\n }\r\n\r\n result.push({ role: 'user', content: toolResults });\r\n } else if (msg.role === 'user') {\r\n const blocks = this.convertUserContent(msg.content);\r\n result.push({ role: 'user', content: blocks });\r\n }\r\n }\r\n\r\n // Anthropic requires alternating user/assistant messages.\r\n // Merge consecutive same-role messages if needed.\r\n return this.ensureAlternating(result);\r\n }\r\n\r\n /**\r\n * Convert user message content (string or multimodal) to Anthropic blocks.\r\n */\r\n private convertUserContent(content: LLMMessageContent): AnthropicContentBlock[] {\r\n if (typeof content === 'string') {\r\n return [{ type: 'text', text: content }];\r\n }\r\n\r\n const blocks: AnthropicContentBlock[] = [];\r\n for (const part of content as LLMContentPart[]) {\r\n if (part.type === 'text') {\r\n blocks.push({ type: 'text', text: part.text });\r\n } else if (part.type === 'audio') {\r\n // Anthropic does not yet support audio input — skip silently\r\n this.debugLog('[Anthropic] Audio content dropped — not supported');\r\n } else if (part.type === 'image_url') {\r\n const url = part.image_url.url;\r\n if (url.startsWith('data:')) {\r\n // Extract base64 data from data URI\r\n const match = url.match(/^data:([^;]+);base64,(.+)$/);\r\n if (match) {\r\n blocks.push({\r\n type: 'image',\r\n source: {\r\n type: 'base64',\r\n media_type: match[1],\r\n data: match[2],\r\n },\r\n });\r\n }\r\n } else {\r\n // URL-based image\r\n blocks.push({\r\n type: 'image',\r\n source: {\r\n type: 'url',\r\n url,\r\n },\r\n });\r\n }\r\n }\r\n }\r\n return blocks.length > 0 ? blocks : [{ type: 'text', text: '' }];\r\n }\r\n\r\n /**\r\n * Ensure messages alternate between user and assistant roles.\r\n * Anthropic requires strict alternation. Merge consecutive same-role messages.\r\n */\r\n private ensureAlternating(messages: AnthropicMessage[]): AnthropicMessage[] {\r\n if (messages.length <= 1) return messages;\r\n\r\n const merged: AnthropicMessage[] = [messages[0]!];\r\n\r\n for (let i = 1; i < messages.length; i++) {\r\n const current = messages[i]!;\r\n const last = merged[merged.length - 1]!;\r\n\r\n if (current.role === last.role) {\r\n // Merge content arrays\r\n const lastContent = Array.isArray(last.content)\r\n ? last.content\r\n : [{ type: 'text' as const, text: last.content }];\r\n const currentContent = Array.isArray(current.content)\r\n ? current.content\r\n : [{ type: 'text' as const, text: current.content }];\r\n\r\n merged[merged.length - 1] = {\r\n role: current.role,\r\n content: [...lastContent, ...currentContent],\r\n };\r\n } else {\r\n merged.push(current);\r\n }\r\n }\r\n\r\n return merged;\r\n }\r\n\r\n // ========================================================================\r\n // Internal: Response Parsing\r\n // ========================================================================\r\n\r\n /**\r\n * Parse Anthropic's response format into our canonical LLMChatResponse.\r\n */\r\n private parseAnthropicResponse(data: AnthropicResponse): LLMChatResponse {\r\n let textContent = '';\r\n let reasoning: string | undefined;\r\n const toolCalls: LLMToolCall[] = [];\r\n\r\n for (const block of data.content) {\r\n if (block.type === 'text') {\r\n textContent += block.text;\r\n } else if (block.type === 'tool_use') {\r\n toolCalls.push({\r\n id: block.id,\r\n type: 'function',\r\n function: {\r\n name: block.name,\r\n arguments: JSON.stringify(block.input),\r\n },\r\n });\r\n } else if (block.type === 'thinking') {\r\n reasoning = (reasoning ?? '') + block.thinking;\r\n }\r\n }\r\n\r\n const usage: TokenUsageInfo = {\r\n inputTokens: data.usage.input_tokens,\r\n outputTokens: data.usage.output_tokens,\r\n totalTokens: data.usage.input_tokens + data.usage.output_tokens,\r\n };\r\n\r\n return {\r\n message: {\r\n role: 'assistant',\r\n content: textContent,\r\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\r\n },\r\n reasoning,\r\n usage,\r\n provider: 'anthropic',\r\n };\r\n }\r\n\r\n // ========================================================================\r\n // Internal: Helpers\r\n // ========================================================================\r\n\r\n /** Convert OpenAI-format tool definition to Anthropic format */\r\n private convertToolDef(tool: LLMToolDefinition): AnthropicToolDef {\r\n return {\r\n name: tool.function.name,\r\n description: tool.function.description,\r\n input_schema: {\r\n type: 'object',\r\n properties: tool.function.parameters.properties,\r\n required: tool.function.parameters.required,\r\n },\r\n };\r\n }\r\n\r\n /** Extract text from multimodal content */\r\n private extractText(content: LLMMessageContent): string {\r\n if (typeof content === 'string') return content;\r\n return (content as LLMContentPart[])\r\n .filter((p): p is { type: 'text'; text: string } => p.type === 'text')\r\n .map(p => p.text)\r\n .join('');\r\n }\r\n}\r\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"google.d.ts","sourceRoot":"","sources":["../../src/providers/google.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAS7C,OAAO,KAAK,EACR,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,WAAW,EAYd,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAE7C,qBAAa,YAAa,SAAQ,aAAa;IAC3C,OAAO,CAAC,QAAQ,CAAU;IAC1B,OAAO,CAAC,UAAU,CAAS;gBAEf,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,OAAO;IAUxD,OAAO,CAAC,UAAU;IASlB,OAAO,CAAC,UAAU;IAQlB,OAAO,CAAC,YAAY;IAQpB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,UAAU;IAcZ,IAAI,CACN,QAAQ,EAAE,cAAc,EAAE,EAC1B,OAAO,CAAC,EAAE,WAAW,GACtB,OAAO,CAAC,eAAe,CAAC;IAuDpB,UA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C;YACjD,CAAC;QACL,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;IACnC,CAAC;CAEJ","sourcesContent":["/**\r\n * Universal LLM Client v3 — Google Provider\r\n *\r\n * Implements BaseLLMClient for Google AI Studio and Vertex AI.\r\n * Supports Gemini and Gemma models with full tool calling,\r\n * streaming, embeddings, and system prompt handling.\r\n */\r\n\r\nimport { BaseLLMClient } from '../client.js';\r\nimport { httpRequest, httpStream } from '../http.js';\r\nimport { StandardChatDecoder } from '../stream-decoder.js';\r\nimport {\r\n normalizeJsonSchema,\r\n stripUnsupportedFeatures,\r\n getJsonSchemaFromConfig,\r\n type JSONSchema,\r\n} from '../structured-output.js';\r\nimport type {\r\n LLMClientOptions,\r\n LLMChatMessage,\r\n LLMChatResponse,\r\n ChatOptions,\r\n LLMToolDefinition,\r\n LLMToolCall,\r\n LLMContentPart,\r\n LLMTextContent,\r\n GooglePart,\r\n GoogleContent,\r\n GoogleRequest,\r\n GoogleResponse,\r\n GoogleFunctionDeclaration,\r\n TokenUsageInfo,\r\n AIModelApiType,\r\n} from '../interfaces.js';\r\nimport type { DecodedEvent } from '../stream-decoder.js';\r\nimport type { Auditor } from '../auditor.js';\r\n\r\nexport class GoogleClient extends BaseLLMClient {\r\n private isVertex: boolean;\r\n private apiVersion: string;\r\n\r\n constructor(options: LLMClientOptions, auditor?: Auditor) {\r\n super(options, auditor);\r\n this.isVertex = options.apiType === ('vertex' as AIModelApiType);\r\n this.apiVersion = options.apiVersion ?? 'v1beta';\r\n }\r\n\r\n // ========================================================================\r\n // URL Building\r\n // ========================================================================\r\n\r\n private getBaseUrl(): string {\r\n if (this.isVertex) {\r\n const region = this.options.region ?? 'us-central1';\r\n return `https://${region}-aiplatform.googleapis.com/${this.apiVersion}/projects/-/locations/${region}/publishers/google/models/${this.options.model}`;\r\n }\r\n if (this.options.url) return this.options.url.replace(/\\/+$/, '');\r\n return `https://generativelanguage.googleapis.com/${this.apiVersion}/models/${this.options.model}`;\r\n }\r\n\r\n private getChatUrl(): string {\r\n const base = this.getBaseUrl();\r\n if (this.isVertex) {\r\n return `${base}:generateContent`;\r\n }\r\n return `${base}:generateContent?key=${this.options.apiKey}`;\r\n }\r\n\r\n private getStreamUrl(): string {\r\n const base = this.getBaseUrl();\r\n if (this.isVertex) {\r\n return `${base}:streamGenerateContent?alt=sse`;\r\n }\r\n return `${base}:streamGenerateContent?alt=sse&key=${this.options.apiKey}`;\r\n }\r\n\r\n private getEmbedUrl(): string {\r\n if (this.isVertex) {\r\n const region = this.options.region ?? 'us-central1';\r\n return `https://${region}-aiplatform.googleapis.com/${this.apiVersion}/projects/-/locations/${region}/publishers/google/models/${this.options.model}:embedContent`;\r\n }\r\n return `https://generativelanguage.googleapis.com/${this.apiVersion}/models/${this.options.model}:embedContent?key=${this.options.apiKey}`;\r\n }\r\n\r\n private getHeaders(): Record<string, string> {\r\n const headers: Record<string, string> = {\r\n 'Content-Type': 'application/json',\r\n };\r\n if (this.isVertex && this.options.apiKey) {\r\n headers['Authorization'] = `Bearer ${this.options.apiKey}`;\r\n }\r\n return headers;\r\n }\r\n\r\n // ========================================================================\r\n // Chat\r\n // ========================================================================\r\n\r\n async chat(\r\n messages: LLMChatMessage[],\r\n options?: ChatOptions,\r\n ): Promise<LLMChatResponse> {\r\n // Structured output and tools can now be used together.\\n // The provider sends both responseSchema and tools in the request.\\n // The Router handles skipping validation when the response contains tool calls.\r\n\r\n const url = this.getChatUrl();\r\n const body = this.buildRequestBody(messages, options);\r\n\r\n // Flex tier: increase timeout (Google recommends 600s+) and use retry logic\r\n const tier = options?.serviceTier;\r\n const effectiveTimeout = tier === 'flex'\r\n ? Math.max(this.options.timeout ?? 60000, 600_000)\r\n : (this.options.timeout ?? 60000);\r\n\r\n const start = Date.now();\r\n this.auditor.record({\r\n timestamp: start,\r\n type: 'request',\r\n provider: this.isVertex ? 'vertex' : 'google',\r\n model: this.options.model,\r\n });\r\n\r\n const reqOptions = {\r\n method: 'POST' as const,\r\n headers: this.getHeaders(),\r\n body,\r\n timeout: effectiveTimeout,\r\n };\r\n\r\n const response = tier === 'flex'\r\n ? await this.fetchWithFlexRetry<GoogleResponse>(url, reqOptions)\r\n : await httpRequest<GoogleResponse>(url, reqOptions);\r\n\r\n const result = this.parseGoogleResponse(response.data);\r\n\r\n // Surface the tier that actually served the request\r\n const resolvedTier = response.headers?.get('x-gemini-service-tier');\r\n if (resolvedTier) {\r\n result.serviceTier = resolvedTier.toLowerCase() as 'flex' | 'priority' | 'standard';\r\n }\r\n\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'response',\r\n provider: this.isVertex ? 'vertex' : 'google',\r\n model: this.options.model,\r\n duration: Date.now() - start,\r\n usage: result.usage,\r\n });\r\n\r\n return result;\r\n }\r\n\r\n // ========================================================================\r\n // Streaming\r\n // ========================================================================\r\n\r\n async *chatStream(\r\n messages: LLMChatMessage[],\r\n options?: ChatOptions,\r\n ): AsyncGenerator<DecodedEvent, LLMChatResponse | void, unknown> {\r\n const url = this.getStreamUrl();\r\n const body = this.buildRequestBody(messages, options);\r\n\r\n // Flex tier: increase timeout (Google recommends 600s+)\r\n const tier = options?.serviceTier;\r\n const effectiveTimeout = tier === 'flex'\r\n ? Math.max(this.options.timeout ?? 120000, 600_000)\r\n : (this.options.timeout ?? 120000);\r\n\r\n const start = Date.now();\r\n this.auditor.record({\r\n timestamp: start,\r\n type: 'stream_start',\r\n provider: this.isVertex ? 'vertex' : 'google',\r\n model: this.options.model,\r\n });\r\n\r\n const decoder = new StandardChatDecoder(() => {});\r\n let usage: TokenUsageInfo | undefined;\r\n const allToolCalls: LLMToolCall[] = [];\r\n\r\n const stream = httpStream(url, {\r\n method: 'POST',\r\n headers: this.getHeaders(),\r\n body,\r\n timeout: effectiveTimeout,\r\n });\r\n\r\n // Google streams SSE with JSON payloads\r\n let buffer = '';\r\n for await (const chunk of stream) {\r\n buffer += chunk;\r\n\r\n // Google SSE uses \"data: \" prefix\r\n const lines = buffer.split('\\n');\r\n buffer = lines.pop() ?? '';\r\n\r\n for (const line of lines) {\r\n if (!line.startsWith('data: ')) continue;\r\n const jsonStr = line.slice(6).trim();\r\n if (!jsonStr || jsonStr === '[DONE]') continue;\r\n\r\n try {\r\n const data = JSON.parse(jsonStr) as GoogleResponse;\r\n\r\n if (data.usageMetadata) {\r\n usage = {\r\n inputTokens: data.usageMetadata.promptTokenCount ?? 0,\r\n outputTokens: data.usageMetadata.candidatesTokenCount ?? 0,\r\n totalTokens: data.usageMetadata.totalTokenCount ?? 0,\r\n cachedTokens: data.usageMetadata.cachedContentTokenCount,\r\n reasoningTokens: data.usageMetadata.thoughtsTokenCount,\r\n };\r\n }\r\n\r\n const candidate = data.candidates?.[0];\r\n if (!candidate?.content?.parts) continue;\r\n\r\n for (const part of candidate.content.parts) {\r\n if (part.text) {\r\n decoder.push(part.text);\r\n yield { type: 'text', content: part.text };\r\n }\r\n if (part.functionCall) {\r\n const toolCall = this.convertFunctionCallToToolCall(\r\n part.functionCall,\r\n part.thoughtSignature,\r\n );\r\n allToolCalls.push(toolCall);\r\n yield { type: 'tool_call', calls: [toolCall] };\r\n }\r\n }\r\n } catch {\r\n // Skip unparseable JSON\r\n }\r\n }\r\n }\r\n\r\n decoder.flush();\r\n\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'stream_end',\r\n provider: this.isVertex ? 'vertex' : 'google',\r\n model: this.options.model,\r\n duration: Date.now() - start,\r\n usage,\r\n });\r\n\r\n return {\r\n message: {\r\n role: 'assistant',\r\n content: decoder.getCleanContent(),\r\n tool_calls: allToolCalls.length > 0 ? allToolCalls : undefined,\r\n },\r\n reasoning: decoder.getReasoning(),\r\n usage,\r\n provider: this.isVertex ? 'vertex' : 'google',\r\n };\r\n }\r\n\r\n // ========================================================================\r\n // Embeddings\r\n // ========================================================================\r\n\r\n async embed(text: string): Promise<number[]> {\r\n const url = this.getEmbedUrl();\r\n const response = await httpRequest<{\r\n embedding: { values: number[] };\r\n }>(url, {\r\n method: 'POST',\r\n headers: this.getHeaders(),\r\n body: {\r\n content: {\r\n parts: [{ text }],\r\n },\r\n },\r\n timeout: this.options.timeout ?? 30000,\r\n });\r\n return response.data.embedding.values;\r\n }\r\n\r\n // ========================================================================\r\n // Model Discovery\r\n // ========================================================================\r\n\r\n async getModels(): Promise<string[]> {\r\n const baseUrl = this.isVertex\r\n ? `https://${this.options.region ?? 'us-central1'}-aiplatform.googleapis.com/${this.apiVersion}/models`\r\n : `https://generativelanguage.googleapis.com/${this.apiVersion}/models?key=${this.options.apiKey}`;\r\n\r\n try {\r\n const response = await httpRequest<{\r\n models: Array<{ name: string }>;\r\n }>(baseUrl, {\r\n headers: this.getHeaders(),\r\n timeout: 10000,\r\n });\r\n return response.data.models.map(m =>\r\n m.name.replace(/^models\\//, ''),\r\n );\r\n } catch {\r\n return [];\r\n }\r\n }\r\n\r\n // ========================================================================\r\n // Request Building\r\n // ========================================================================\r\n\r\n private buildRequestBody(\r\n messages: LLMChatMessage[],\r\n options?: ChatOptions,\r\n ): GoogleRequest {\r\n const isGemma = this.options.model.toLowerCase().includes('gemma');\r\n const { systemInstruction, contents } = this.convertToGoogleMessages(messages, isGemma);\r\n\r\n const tools = options?.tools ?? (Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined);\r\n\r\n const body: GoogleRequest = {\r\n contents,\r\n generationConfig: this.buildGenerationConfig(options),\r\n };\r\n\r\n // System instruction (Gemini supports it, Gemma doesn't)\r\n if (systemInstruction && !isGemma) {\r\n body.systemInstruction = {\r\n parts: [{ text: systemInstruction }],\r\n };\r\n }\r\n\r\n // Tools\r\n if (tools?.length) {\r\n body.tools = [{\r\n functionDeclarations: tools.map(t => this.convertToGoogleTool(t)),\r\n }];\r\n }\r\n\r\n // Inference tier (Flex / Priority)\r\n const tier = options?.serviceTier;\r\n if (tier && tier !== 'standard') {\r\n body.service_tier = tier.toUpperCase() as 'FLEX' | 'PRIORITY';\r\n }\r\n\r\n return body;\r\n }\r\n\r\n private buildGenerationConfig(options?: ChatOptions): Record<string, unknown> {\r\n const config: Record<string, unknown> = {\r\n ...this.options.defaultParameters,\r\n ...options?.parameters,\r\n };\r\n if (options?.temperature !== undefined) config['temperature'] = options.temperature;\r\n if (options?.maxTokens !== undefined) config['maxOutputTokens'] = options.maxTokens;\r\n if (this.options.thinking) {\r\n config['thinkingConfig'] = { thinkingBudget: 8192 };\r\n }\r\n\r\n // Structured output: add responseMimeType and responseSchema\r\n const schemaOptions = this.extractSchemaOptions(options);\r\n if (schemaOptions) {\r\n config['responseMimeType'] = 'application/json';\r\n\r\n // Convert schema to Google-compatible format\r\n let jsonSchema: JSONSchema;\r\n if (schemaOptions.jsonSchema) {\r\n jsonSchema = normalizeJsonSchema(schemaOptions.jsonSchema);\r\n } else if (schemaOptions.schemaConfig) {\r\n jsonSchema = getJsonSchemaFromConfig(schemaOptions.schemaConfig);\r\n } else {\r\n throw new Error('Either schemaConfig or jsonSchema must be provided');\r\n }\r\n\r\n // Strip unsupported features for Google\r\n const googleSchema = stripUnsupportedFeatures(jsonSchema, 'google');\r\n config['responseSchema'] = googleSchema;\r\n }\r\n\r\n return config;\r\n }\r\n\r\n // ========================================================================\r\n // Message Conversion\r\n // ========================================================================\r\n\r\n private convertToGoogleMessages(\r\n messages: LLMChatMessage[],\r\n isGemma: boolean,\r\n ): { systemInstruction?: string; contents: GoogleContent[] } {\r\n let systemInstruction: string | undefined;\r\n const contents: GoogleContent[] = [];\r\n\r\n for (const msg of messages) {\r\n if (msg.role === 'system') {\r\n if (isGemma) {\r\n // Gemma: prepend system message to first user message\r\n systemInstruction = typeof msg.content === 'string'\r\n ? msg.content\r\n : msg.content.filter((p): p is LLMTextContent => p.type === 'text').map(p => p.text).join('');\r\n } else {\r\n systemInstruction = typeof msg.content === 'string'\r\n ? msg.content\r\n : msg.content.filter((p): p is LLMTextContent => p.type === 'text').map(p => p.text).join('');\r\n }\r\n continue;\r\n }\r\n\r\n if (msg.role === 'tool') {\r\n // Convert tool result to Google functionResponse\r\n let responseData: Record<string, unknown>;\r\n try {\r\n responseData = typeof msg.content === 'string'\r\n ? JSON.parse(msg.content)\r\n : { result: msg.content };\r\n } catch {\r\n responseData = { result: typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content) };\r\n }\r\n\r\n contents.push({\r\n role: 'function',\r\n parts: [{\r\n functionResponse: {\r\n name: msg.tool_call_id ?? 'unknown',\r\n response: responseData,\r\n },\r\n }],\r\n });\r\n continue;\r\n }\r\n\r\n if (msg.role === 'assistant') {\r\n const parts: GooglePart[] = [];\r\n const textContent = typeof msg.content === 'string' ? msg.content : '';\r\n if (textContent) parts.push({ text: textContent });\r\n\r\n // Convert tool calls to functionCall parts\r\n if (msg.tool_calls) {\r\n for (const tc of msg.tool_calls) {\r\n const part: GooglePart = {\r\n functionCall: {\r\n name: tc.function.name,\r\n args: typeof tc.function.arguments === 'string'\r\n ? JSON.parse(tc.function.arguments)\r\n : tc.function.arguments as Record<string, unknown>,\r\n },\r\n };\r\n // Echo thought signature back (required by Gemini 3.x)\r\n if (tc.thoughtSignature) {\r\n part.thoughtSignature = tc.thoughtSignature;\r\n }\r\n parts.push(part);\r\n }\r\n }\r\n\r\n contents.push({ role: 'model', parts });\r\n continue;\r\n }\r\n\r\n // User messages\r\n const parts = this.convertContentToGoogleParts(msg.content);\r\n\r\n // Gemma: prepend system instruction to first user message\r\n if (isGemma && systemInstruction && contents.length === 0) {\r\n const systemParts = [{ text: `[System Instructions]\\n${systemInstruction}\\n\\n[User Message]\\n` }];\r\n contents.push({\r\n role: 'user',\r\n parts: [...systemParts, ...parts],\r\n });\r\n systemInstruction = undefined; // Consumed\r\n } else {\r\n contents.push({ role: 'user', parts });\r\n }\r\n }\r\n\r\n return { systemInstruction, contents };\r\n }\r\n\r\n private convertContentToGoogleParts(content: string | LLMContentPart[]): GooglePart[] {\r\n if (typeof content === 'string') {\r\n return [{ text: content }];\r\n }\r\n\r\n return content.map(part => {\r\n if (part.type === 'text') {\r\n return { text: part.text };\r\n }\r\n if (part.type === 'audio') {\r\n return {\r\n inlineData: {\r\n mimeType: part.audio.mimeType,\r\n data: part.audio.data,\r\n },\r\n };\r\n }\r\n // Image content\r\n const url = part.image_url.url;\r\n if (url.startsWith('data:')) {\r\n const match = url.match(/^data:([^;]+);base64,(.+)$/);\r\n if (match) {\r\n return {\r\n inlineData: {\r\n mimeType: match[1]!,\r\n data: match[2]!,\r\n },\r\n };\r\n }\r\n }\r\n // For regular URLs, try inline data format\r\n return { text: `[Image: ${url}]` };\r\n });\r\n }\r\n\r\n // ========================================================================\r\n // Tool Conversion\r\n // ========================================================================\r\n\r\n private convertToGoogleTool(tool: LLMToolDefinition): GoogleFunctionDeclaration {\r\n return {\r\n name: tool.function.name,\r\n description: tool.function.description,\r\n parameters: {\r\n type: 'object',\r\n properties: tool.function.parameters.properties ?? {},\r\n required: tool.function.parameters.required,\r\n },\r\n };\r\n }\r\n\r\n private convertFunctionCallToToolCall(\r\n fc: { name: string; args: Record<string, unknown> },\r\n thoughtSignature?: string,\r\n ): LLMToolCall {\r\n const toolCall: LLMToolCall = {\r\n id: this.generateToolCallId(),\r\n type: 'function',\r\n function: {\r\n name: fc.name,\r\n arguments: JSON.stringify(fc.args),\r\n },\r\n };\r\n if (thoughtSignature) {\r\n toolCall.thoughtSignature = thoughtSignature;\r\n }\r\n return toolCall;\r\n }\r\n\r\n // ========================================================================\r\n // Response Parsing\r\n // ========================================================================\r\n\r\n private parseGoogleResponse(data: GoogleResponse): LLMChatResponse {\r\n const candidate = data.candidates?.[0];\r\n if (!candidate?.content?.parts) {\r\n return {\r\n message: { role: 'assistant', content: '' },\r\n provider: this.isVertex ? 'vertex' : 'google',\r\n };\r\n }\r\n\r\n let textContent = '';\r\n const toolCalls: LLMToolCall[] = [];\r\n\r\n for (const part of candidate.content.parts) {\r\n if (part.text) textContent += part.text;\r\n if (part.functionCall) {\r\n toolCalls.push(this.convertFunctionCallToToolCall(\r\n part.functionCall,\r\n part.thoughtSignature,\r\n ));\r\n }\r\n }\r\n\r\n const usage: TokenUsageInfo | undefined = data.usageMetadata\r\n ? {\r\n inputTokens: data.usageMetadata.promptTokenCount,\r\n outputTokens: data.usageMetadata.candidatesTokenCount,\r\n totalTokens: data.usageMetadata.totalTokenCount,\r\n cachedTokens: data.usageMetadata.cachedContentTokenCount,\r\n reasoningTokens: data.usageMetadata.thoughtsTokenCount,\r\n }\r\n : undefined;\r\n\r\n return {\r\n message: {\r\n role: 'assistant',\r\n content: textContent,\r\n tool_calls: toolCalls.length > 0 ? toolCalls : undefined,\r\n },\r\n usage,\r\n provider: this.isVertex ? 'vertex' : 'google',\r\n };\r\n }\r\n\r\n // ========================================================================\r\n // Flex Retry Logic\r\n // ========================================================================\r\n\r\n /**\r\n * Retry HTTP requests for Flex tier when receiving 503/429 errors.\r\n * Uses exponential backoff (5s → 10s → 20s) as recommended by Google.\r\n */\r\n private async fetchWithFlexRetry<T>(\r\n url: string,\r\n reqOptions: { method: 'POST'; headers: Record<string, string>; body: unknown; timeout: number },\r\n maxRetries = 3,\r\n baseDelay = 5000,\r\n ): Promise<import('../http.js').HttpResponse<T>> {\r\n for (let attempt = 0; attempt < maxRetries; attempt++) {\r\n try {\r\n return await httpRequest<T>(url, reqOptions);\r\n } catch (error) {\r\n const isRetryable = error instanceof Error\r\n && (error.message.includes('HTTP 503') || error.message.includes('HTTP 429'));\r\n if (!isRetryable || attempt >= maxRetries - 1) throw error;\r\n const delay = baseDelay * (2 ** attempt);\r\n await new Promise(r => setTimeout(r, delay));\r\n }\r\n }\r\n throw new Error('Unreachable');\r\n }\r\n\r\n}\r\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/providers/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/providers/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC","sourcesContent":["/**\r\n * Universal LLM Client v3 — Provider Barrel Export\r\n */\r\n\r\nexport { OllamaClient } from './ollama.js';\r\nexport { OpenAICompatibleClient } from './openai.js';\r\nexport { GoogleClient } from './google.js';\r\nexport { AnthropicClient } from './anthropic.js';\r\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ollama.d.ts","sourceRoot":"","sources":["../../src/providers/ollama.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAO7C,OAAO,KAAK,EACR,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,WAAW,EACX,aAAa,EAKhB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAE7C,qBAAa,YAAa,SAAQ,aAAa;gBAC/B,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,OAAO;IAWlD,IAAI,CACN,QAAQ,EAAE,cAAc,EAAE,EAC1B,OAAO,CAAC,EAAE,WAAW,GACtB,OAAO,CAAC,eAAe,CAAC;IAgGpB,UAAU,CACb,QAAQ,EAAE,cAAc,EAAE,EAC1B,OAAO,CAAC,EAAE,WAAW,GACtB,cAAc,CAAC,YAAY,EAAE,eAAe,GAAG,IAAI,E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zB,CAAC;QACF,IAAI,OAAO,EAAE,WAAW,KAAK,SAAS;YAAE,MAAM,CAAC,aAAa,CAAC,GAAG,OAAO,CAAC,WAAW,CAAC;QACpF,IAAI,OAAO,EAAE,SAAS,KAAK,SAAS;YAAE,MAAM,CAAC,aAAa,CAAC,GAAG,OAAO,CAAC,SAAS,CAAC;QAChF,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,2EAA2E;IAC3E,4BAA4B;IAC5B,2EAA2E;IAE3E;;;;;OAKG;IACK,oBAAoB,CAAC,OAA8I;QACvK,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YACrB,OAAO,mBAAmB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;QACnD,CAAC;QAED,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YACvB,OAAO,uBAAuB,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QACzD,CAAC;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ","sourcesContent":["/**\r\n * Universal LLM Client v3 — Ollama Provider\r\n *\r\n * Implements BaseLLMClient for Ollama's native API.\r\n * Supports chat, streaming (NDJSON), embeddings, model discovery,\r\n * context length detection via /api/show, and structured output.\r\n *\r\n * Structured Output Assertions:\r\n * - VAL-PROVIDER-OLLAMA-001: format parameter with JSON Schema\r\n * - VAL-PROVIDER-OLLAMA-003: Vision with base64 extraction alongside format\r\n * - VAL-PROVIDER-OLLAMA-004: format \"json\" vs schema modes\r\n */\r\n\r\nimport { BaseLLMClient } from '../client.js';\r\nimport { httpRequest, httpStream, parseNDJSON, buildHeaders } from '../http.js';\r\nimport { StandardChatDecoder } from '../stream-decoder.js';\r\nimport {\r\n normalizeJsonSchema,\r\n getJsonSchemaFromConfig,\r\n} from '../structured-output.js';\r\nimport type {\r\n LLMClientOptions,\r\n LLMChatMessage,\r\n LLMChatResponse,\r\n ChatOptions,\r\n ModelMetadata,\r\n OllamaResponse,\r\n OllamaModelInfo,\r\n LLMToolDefinition,\r\n TokenUsageInfo,\r\n} from '../interfaces.js';\r\nimport type { DecodedEvent } from '../stream-decoder.js';\r\nimport type { Auditor } from '../auditor.js';\r\n\r\nexport class OllamaClient extends BaseLLMClient {\r\n constructor(options: LLMClientOptions, auditor?: Auditor) {\r\n super({\r\n ...options,\r\n url: (options.url || 'http://localhost:11434').replace(/\\/+$/, ''),\r\n }, auditor);\r\n }\r\n\r\n // ========================================================================\r\n // Chat\r\n // ========================================================================\r\n\r\n async chat(\r\n messages: LLMChatMessage[],\r\n options?: ChatOptions,\r\n ): Promise<LLMChatResponse> {\r\n // Structured output and tools can now be used together.\\n // The provider sends both format and tools in the request.\\n // The Router handles skipping validation when the response contains tool calls.\r\n\r\n const url = `${this.options.url}/api/chat`;\r\n const tools = options?.tools ?? (Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined);\r\n\r\n const body: Record<string, unknown> = {\r\n model: this.options.model,\r\n messages: this.convertMessages(messages),\r\n stream: false,\r\n options: this.buildOllamaOptions(options),\r\n };\r\n\r\n if (tools?.length) {\r\n body['tools'] = this.convertToolsToOllama(tools);\r\n }\r\n\r\n // Enable native thinking by default — thinking models produce better\r\n // tool selections and reasoning when allowed to think before acting.\r\n body['think'] = this.options.thinking ?? true;\r\n\r\n // Handle structured output via format parameter\r\n const schemaOptions = this.extractSchemaOptions(options);\r\n if (schemaOptions) {\r\n body['format'] = this.buildFormatParameter(schemaOptions);\r\n } else if (options?.responseFormat) {\r\n // Legacy json_object mode - map to Ollama's \"json\" format\r\n body['format'] = 'json';\r\n }\r\n\r\n const start = Date.now();\r\n this.auditor.record({\r\n timestamp: start,\r\n type: 'request',\r\n provider: 'ollama',\r\n model: this.options.model,\r\n });\r\n\r\n const response = await httpRequest<OllamaResponse>(url, {\r\n method: 'POST',\r\n headers: buildHeaders(this.options),\r\n body,\r\n timeout: this.options.timeout ?? 30000,\r\n });\r\n\r\n const data = response.data;\r\n const usage: TokenUsageInfo | undefined = (data.prompt_eval_count || data.eval_count)\r\n ? {\r\n inputTokens: data.prompt_eval_count ?? 0,\r\n outputTokens: data.eval_count ?? 0,\r\n totalTokens: (data.prompt_eval_count ?? 0) + (data.eval_count ?? 0),\r\n }\r\n : undefined;\r\n\r\n // Normalize tool call IDs (Ollama sometimes omits them)\r\n const toolCalls = data.message.tool_calls?.map(tc => ({\r\n ...tc,\r\n id: tc.id || this.generateToolCallId(),\r\n function: {\r\n ...tc.function,\r\n arguments: typeof tc.function.arguments === 'string'\r\n ? tc.function.arguments\r\n : JSON.stringify(tc.function.arguments),\r\n },\r\n }));\r\n\r\n // Get content, handling potential null\r\n const content = data.message.content || data.message.thinking || '';\r\n\r\n const result: LLMChatResponse = {\r\n message: {\r\n role: 'assistant',\r\n content,\r\n tool_calls: toolCalls,\r\n },\r\n reasoning: data.message.content ? data.message.thinking : undefined,\r\n usage,\r\n provider: 'ollama',\r\n };\r\n\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'response',\r\n provider: 'ollama',\r\n model: this.options.model,\r\n duration: Date.now() - start,\r\n usage,\r\n });\r\n\r\n return result;\r\n }\r\n\r\n // ========================================================================\r\n // Streaming\r\n // ========================================================================\r\n\r\n async *chatStream(\r\n messages: LLMChatMessage[],\r\n options?: ChatOptions,\r\n ): AsyncGenerator<DecodedEvent, LLMChatResponse | void, unknown> {\r\n const url = `${this.options.url}/api/chat`;\r\n const tools = options?.tools ?? (Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined);\r\n\r\n const body: Record<string, unknown> = {\r\n model: this.options.model,\r\n messages: this.convertMessages(messages),\r\n stream: true,\r\n options: this.buildOllamaOptions(options),\r\n };\r\n\r\n if (tools?.length) {\r\n body['tools'] = this.convertToolsToOllama(tools);\r\n }\r\n\r\n body['think'] = this.options.thinking ?? true;\r\n\r\n const start = Date.now();\r\n this.auditor.record({\r\n timestamp: start,\r\n type: 'stream_start',\r\n provider: 'ollama',\r\n model: this.options.model,\r\n });\r\n\r\n const decoder = new StandardChatDecoder(() => {});\r\n let lastResponse: OllamaResponse | undefined;\r\n const streamedToolCalls: import('../interfaces.js').LLMToolCall[] = [];\r\n\r\n // Stream idle timeout: thinking models can pause for minutes between chunks.\r\n // Ensure at least 5 minutes regardless of the base request timeout.\r\n const streamTimeout = Math.max(this.options.timeout ?? 300000, 300000);\r\n\r\n const stream = httpStream(url, {\r\n method: 'POST',\r\n headers: buildHeaders(this.options),\r\n body,\r\n timeout: streamTimeout,\r\n });\r\n\r\n for await (const chunk of parseNDJSON<OllamaResponse>(stream)) {\r\n lastResponse = chunk;\r\n\r\n if (chunk.message?.thinking) {\r\n decoder.pushReasoning(chunk.message.thinking);\r\n yield { type: 'thinking', content: chunk.message.thinking };\r\n }\r\n\r\n if (chunk.message?.content) {\r\n decoder.push(chunk.message.content);\r\n yield { type: 'text', content: chunk.message.content };\r\n }\r\n\r\n if (chunk.message?.tool_calls?.length) {\r\n const normalized = chunk.message.tool_calls.map(tc => ({\r\n ...tc,\r\n id: tc.id || this.generateToolCallId(),\r\n function: {\r\n ...tc.function,\r\n arguments: typeof tc.function.arguments === 'string'\r\n ? tc.function.arguments\r\n : JSON.stringify(tc.function.arguments),\r\n },\r\n }));\r\n streamedToolCalls.push(...normalized);\r\n yield { type: 'tool_call', calls: normalized };\r\n }\r\n }\r\n\r\n decoder.flush();\r\n\r\n const usage: TokenUsageInfo | undefined = lastResponse?.prompt_eval_count\r\n ? {\r\n inputTokens: lastResponse.prompt_eval_count ?? 0,\r\n outputTokens: lastResponse.eval_count ?? 0,\r\n totalTokens: (lastResponse.prompt_eval_count ?? 0) + (lastResponse.eval_count ?? 0),\r\n }\r\n : undefined;\r\n\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'stream_end',\r\n provider: 'ollama',\r\n model: this.options.model,\r\n duration: Date.now() - start,\r\n usage,\r\n });\r\n\r\n return {\r\n message: {\r\n role: 'assistant',\r\n content: decoder.getCleanContent(),\r\n tool_calls: streamedToolCalls.length > 0 ? streamedToolCalls : undefined,\r\n },\r\n reasoning: decoder.getReasoning(),\r\n usage,\r\n provider: 'ollama',\r\n };\r\n }\r\n\r\n // ========================================================================\r\n // Embeddings\r\n // ========================================================================\r\n\r\n async embed(text: string): Promise<number[]> {\r\n const url = `${this.options.url}/api/embed`;\r\n const response = await httpRequest<{ embeddings: number[][] }>(url, {\r\n method: 'POST',\r\n headers: buildHeaders(this.options),\r\n body: { model: this.options.model, input: text },\r\n timeout: this.options.timeout ?? 30000,\r\n });\r\n return response.data.embeddings[0] ?? [];\r\n }\r\n\r\n override async embedArray(texts: string[]): Promise<number[][]> {\r\n const url = `${this.options.url}/api/embed`;\r\n const response = await httpRequest<{ embeddings: number[][] }>(url, {\r\n method: 'POST',\r\n headers: buildHeaders(this.options),\r\n body: { model: this.options.model, input: texts },\r\n timeout: this.options.timeout ?? 30000,\r\n });\r\n return response.data.embeddings;\r\n }\r\n\r\n // ========================================================================\r\n // Model Discovery\r\n // ========================================================================\r\n\r\n async getModels(): Promise<string[]> {\r\n const url = `${this.options.url}/api/tags`;\r\n const response = await httpRequest<{ models: OllamaModelInfo[] }>(url, {\r\n timeout: 5000,\r\n });\r\n return response.data.models.map(m => m.name);\r\n }\r\n\r\n override async getModelInfo(modelName?: string): Promise<ModelMetadata> {\r\n const url = `${this.options.url}/api/show`;\r\n try {\r\n const targetModel = modelName ?? this.options.model;\r\n const response = await httpRequest<Record<string, unknown>>(url, {\r\n method: 'POST',\r\n body: { name: targetModel },\r\n timeout: 5000,\r\n });\r\n\r\n const modelInfo = response.data['model_info'] as Record<string, unknown> | undefined;\r\n if (!modelInfo) return { contextLength: 8192 };\r\n\r\n // Extract architecture-specific context length\r\n const arch = modelInfo['general.architecture'] as string | undefined;\r\n let contextLength = 8192;\r\n\r\n if (arch) {\r\n const ctxKey = `${arch}.context_length`;\r\n const ctxValue = modelInfo[ctxKey] as number | undefined;\r\n if (ctxValue) contextLength = ctxValue;\r\n }\r\n\r\n // Prefer the live deployment context when available. /api/show reports\r\n // the trained maximum; /api/ps reports what the daemon has actually loaded.\r\n try {\r\n const psResponse = await httpRequest<{ models?: Array<{ name?: string; context_length?: number }> }>(\r\n `${this.options.url}/api/ps`,\r\n { timeout: 5000 },\r\n );\r\n const liveModel = psResponse.data.models?.find(\r\n model => model.name?.toLowerCase() === targetModel.toLowerCase(),\r\n );\r\n if (liveModel?.context_length && liveModel.context_length > 0) {\r\n contextLength = Math.min(contextLength, liveModel.context_length);\r\n }\r\n } catch {\r\n // Ignore /api/ps failures — /api/show is still a valid fallback\r\n }\r\n\r\n const paramCountRaw = modelInfo['general.parameter_count'] as number | undefined;\r\n const capabilities = response.data['capabilities'] as string[] | undefined;\r\n\r\n return {\r\n model: targetModel,\r\n contextLength,\r\n architecture: arch,\r\n parameterCount: paramCountRaw,\r\n capabilities,\r\n };\r\n } catch {\r\n return { contextLength: 8192 };\r\n }\r\n }\r\n\r\n // ========================================================================\r\n // Readiness\r\n // ========================================================================\r\n\r\n /** Ensure model is available, pull if missing */\r\n async ensureReady(): Promise<void> {\r\n try {\r\n await this.getModelInfo();\r\n } catch {\r\n // Try pulling the model\r\n this.debugLog(`Model not found, attempting pull: ${this.options.model}`);\r\n await httpRequest(`${this.options.url}/api/pull`, {\r\n method: 'POST',\r\n body: { name: this.options.model },\r\n timeout: 300000, // 5 min for pull\r\n });\r\n }\r\n }\r\n\r\n // ========================================================================\r\n // Internals\r\n // ========================================================================\r\n\r\n private convertMessages(messages: LLMChatMessage[]): Record<string, unknown>[] {\r\n return messages.map(msg => {\r\n const converted: Record<string, unknown> = { role: msg.role };\r\n\r\n // Handle multimodal content (array of text + image parts)\r\n if (Array.isArray(msg.content)) {\r\n const textParts: string[] = [];\r\n const images: string[] = [];\r\n\r\n for (const part of msg.content) {\r\n if (part.type === 'text') {\r\n textParts.push(part.text);\r\n } else if (part.type === 'audio') {\r\n this.debugLog('Ollama: skipping audio content (not supported)');\r\n } else if (part.type === 'image_url' && part.image_url?.url) {\r\n // Extract base64 data from data URL or use raw base64\r\n const url = part.image_url.url;\r\n if (url.startsWith('data:')) {\r\n // data:image/jpeg;base64,XXXX → extract XXXX\r\n const base64Data = url.split(',')[1];\r\n if (base64Data) images.push(base64Data);\r\n } else if (url.startsWith('http')) {\r\n // Ollama doesn't support URLs directly — skip\r\n // (caller should download and convert to base64)\r\n this.debugLog('Ollama vision: skipping URL image, use base64 instead');\r\n } else {\r\n // Assume raw base64\r\n images.push(url);\r\n }\r\n }\r\n }\r\n\r\n converted['content'] = textParts.join('\\n');\r\n if (images.length > 0) {\r\n converted['images'] = images;\r\n }\r\n } else {\r\n converted['content'] = msg.content ?? '';\r\n }\r\n\r\n // Ollama needs tool call arguments as objects, not strings\r\n if (msg.tool_calls?.length) {\r\n converted['tool_calls'] = msg.tool_calls.map(tc => ({\r\n ...tc,\r\n function: {\r\n ...tc.function,\r\n arguments: typeof tc.function.arguments === 'string'\r\n ? (() => { try { return JSON.parse(tc.function.arguments); } catch { return tc.function.arguments; } })()\r\n : tc.function.arguments,\r\n },\r\n }));\r\n }\r\n\r\n // Preserve tool_call_id for tool result messages\r\n if (msg.tool_call_id) {\r\n converted['tool_call_id'] = msg.tool_call_id;\r\n }\r\n\r\n return converted;\r\n });\r\n }\r\n\r\n private convertToolsToOllama(tools: LLMToolDefinition[]): unknown[] {\r\n return tools.map(t => ({\r\n type: 'function',\r\n function: {\r\n name: t.function.name,\r\n description: t.function.description,\r\n parameters: t.function.parameters,\r\n },\r\n }));\r\n }\r\n\r\n private buildOllamaOptions(options?: ChatOptions): Record<string, unknown> {\r\n const params: Record<string, unknown> = {\r\n ...this.options.defaultParameters,\r\n ...options?.parameters,\r\n };\r\n if (options?.temperature !== undefined) params['temperature'] = options.temperature;\r\n if (options?.maxTokens !== undefined) params['num_predict'] = options.maxTokens;\r\n return params;\r\n }\r\n\r\n // ========================================================================\r\n // Structured Output Helpers\r\n // ========================================================================\r\n\r\n /**\r\n * Build Ollama format parameter from schema options.\r\n * Ollama accepts:\r\n * - format: \"json\" for simple JSON mode\r\n * - format: { ...schema } for structured output with JSON Schema\r\n */\r\n private buildFormatParameter(options: { schemaConfig?: import('../structured-output.js').SchemaConfig<unknown>, jsonSchema?: import('../structured-output.js').JSONSchema }): string | import('../structured-output.js').JSONSchema {\r\n if (options.jsonSchema) {\r\n return normalizeJsonSchema(options.jsonSchema);\r\n }\r\n\r\n if (options.schemaConfig) {\r\n return getJsonSchemaFromConfig(options.schemaConfig);\r\n }\r\n\r\n return 'json';\r\n }\r\n}\r\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../src/providers/openai.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAS7C,OAAO,KAAK,EACR,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,WAAW,EAId,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAE7C,qBAAa,sBAAuB,SAAQ,aAAa;gBACzC,OAAO,EAAE,gBAAgB,EAAE,OAAO,CAAC,EAAE,OAAO;IAalD,IAAI,CACN,QAAQ,EAAE,cAAc,EAAE,EAC1B,OAAO,CAAC,EAAE,WAAW,GACtB,OAAO,CAAC,eAAe,CAAC;IA6FpB,UAAU,CACb,QAAQ,EAAE,cAAc,EAAE,EAC1B,OAAO,CAAC,EAAE,WAAW,GACtB,cAAc,CAAC,YAAY,EAAE,eAAe,GAAG,IAAI,EAAE,OAAO,CAAC;IAyJ1D,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAoBtC,SAAS,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAmBpC,OAAO,CAAC,eAAe;IASvB,OAAO,CAAC,kBAAkB;IAc1B;;OAEG;IACH,OAAO,CAAC,mBAAmB;CAgC9B"}
@@ -1 +0,0 @@
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DAA+D;QAC/D,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YACrB,sBAAsB;YACtB,UAAU,GAAG,mBAAmB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;YACrD,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,UAAU,CAAC;YAClC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;QACtC,CAAC;aAAM,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YAC9B,0CAA0C;YAC1C,UAAU,GAAG,uBAAuB,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC3D,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,OAAO,CAAC,YAAY,CAAC,IAAI,IAAI,UAAU,CAAC;YAC/D,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,YAAY,CAAC,WAAW,CAAC;QAC1E,CAAC;aAAM,CAAC;YACJ,4DAA4D;YAC5D,MAAM,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAAC;QAC1E,CAAC;QAED,qFAAqF;QACrF,OAAO;YACH,IAAI,EAAE,aAAa;YACnB,WAAW,EAAE;gBACT,IAAI;gBACJ,GAAG,CAAC,WAAW,IAAI,EAAE,WAAW,EAAE,CAAC;gBACnC,MAAM,EAAE,UAAU;gBAClB,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,IAAI;aACjC;SACJ,CAAC;IACN,CAAC;CACJ","sourcesContent":["/**\r\n * Universal LLM Client v3 — OpenAI-Compatible Provider\r\n *\r\n * Implements BaseLLMClient for OpenAI-compatible APIs.\r\n * Works with: OpenAI, OpenRouter, LM Studio, LlamaCpp, vLLM, Groq, Together.\r\n */\r\n\r\nimport { BaseLLMClient } from '../client.js';\r\nimport { httpRequest, httpStream, parseSSE, buildHeaders } from '../http.js';\r\nimport { StandardChatDecoder } from '../stream-decoder.js';\r\nimport {\r\n normalizeJsonSchema,\r\n getJsonSchemaFromConfig,\r\n type JSONSchema,\r\n type StructuredOutputOptions,\r\n} from '../structured-output.js';\r\nimport type {\r\n LLMClientOptions,\r\n LLMChatMessage,\r\n LLMChatResponse,\r\n ChatOptions,\r\n OpenAIResponse,\r\n OpenAIModelInfo,\r\n TokenUsageInfo,\r\n} from '../interfaces.js';\r\nimport type { DecodedEvent } from '../stream-decoder.js';\r\nimport type { Auditor } from '../auditor.js';\r\n\r\nexport class OpenAICompatibleClient extends BaseLLMClient {\r\n constructor(options: LLMClientOptions, auditor?: Auditor) {\r\n // Ensure URL ends with /v1 for standard endpoints\r\n let url = (options.url || 'https://api.openai.com').replace(/\\/+$/, '');\r\n if (!url.endsWith('/v1')) {\r\n url += '/v1';\r\n }\r\n super({ ...options, url }, auditor);\r\n }\r\n\r\n // ========================================================================\r\n // Chat\r\n // ========================================================================\r\n\r\n async chat(\r\n messages: LLMChatMessage[],\r\n options?: ChatOptions,\r\n ): Promise<LLMChatResponse> {\r\n // Structured output and tools can now be used together.\\n // The provider sends both response_format and tools in the request.\\n // The Router handles skipping validation when the response contains tool calls.\r\n\r\n const url = `${this.options.url}/chat/completions`;\r\n const tools = options?.tools ?? (Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined);\r\n\r\n const body: Record<string, unknown> = {\r\n model: this.options.model,\r\n messages: this.convertMessages(messages),\r\n ...this.buildRequestParams(options),\r\n };\r\n\r\n // Handle structured output\r\n const schemaOptions = this.extractSchemaOptions(options);\r\n if (schemaOptions) {\r\n body['response_format'] = this.buildResponseFormat(schemaOptions);\r\n } else if (options?.responseFormat) {\r\n body['response_format'] = options.responseFormat;\r\n }\r\n\r\n if (tools?.length) {\r\n body['tools'] = tools;\r\n if (options?.toolChoice) {\r\n body['tool_choice'] = options.toolChoice;\r\n }\r\n }\r\n\r\n const start = Date.now();\r\n this.auditor.record({\r\n timestamp: start,\r\n type: 'request',\r\n provider: 'openai',\r\n model: this.options.model,\r\n });\r\n\r\n const response = await httpRequest<OpenAIResponse>(url, {\r\n method: 'POST',\r\n headers: buildHeaders(this.options),\r\n body,\r\n timeout: this.options.timeout ?? 30000,\r\n });\r\n\r\n const data = response.data;\r\n const choice = data.choices[0];\r\n\r\n if (!choice) {\r\n throw new Error('No choices returned from OpenAI API');\r\n }\r\n\r\n const usage: TokenUsageInfo | undefined = data.usage\r\n ? {\r\n inputTokens: data.usage.prompt_tokens,\r\n outputTokens: data.usage.completion_tokens,\r\n totalTokens: data.usage.total_tokens,\r\n cachedTokens: data.usage.prompt_tokens_details?.cached_tokens,\r\n }\r\n : undefined;\r\n\r\n // Normalize tool calls (ensure IDs exist)\r\n const toolCalls = choice.message.tool_calls?.map(tc => ({\r\n ...tc,\r\n id: tc.id || this.generateToolCallId(),\r\n }));\r\n\r\n // Get content, handling null case\r\n const content = choice.message.content || '';\r\n\r\n const result: LLMChatResponse = {\r\n message: {\r\n role: 'assistant',\r\n content,\r\n tool_calls: toolCalls,\r\n },\r\n usage,\r\n provider: 'openai',\r\n };\r\n\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'response',\r\n provider: 'openai',\r\n model: this.options.model,\r\n duration: Date.now() - start,\r\n usage,\r\n });\r\n\r\n return result;\r\n }\r\n\r\n // ========================================================================\r\n // Streaming\r\n // ========================================================================\r\n\r\n async *chatStream(\r\n messages: LLMChatMessage[],\r\n options?: ChatOptions,\r\n ): AsyncGenerator<DecodedEvent, LLMChatResponse | void, unknown> {\r\n const url = `${this.options.url}/chat/completions`;\r\n const tools = options?.tools ?? (Object.keys(this.toolRegistry).length > 0 ? this.getToolDefinitions() : undefined);\r\n\r\n const body: Record<string, unknown> = {\r\n model: this.options.model,\r\n messages: this.convertMessages(messages),\r\n stream: true,\r\n ...this.buildRequestParams(options),\r\n };\r\n\r\n if (tools?.length) {\r\n body['tools'] = tools;\r\n if (options?.toolChoice) {\r\n body['tool_choice'] = options.toolChoice;\r\n }\r\n }\r\n\r\n const start = Date.now();\r\n this.auditor.record({\r\n timestamp: start,\r\n type: 'stream_start',\r\n provider: 'openai',\r\n model: this.options.model,\r\n });\r\n\r\n const decoder = new StandardChatDecoder(() => {});\r\n\r\n // Track accumulated tool calls across chunks\r\n const toolCallAccum: Map<number, {\r\n id: string;\r\n type: 'function';\r\n function: { name: string; arguments: string };\r\n }> = new Map();\r\n\r\n const stream = httpStream(url, {\r\n method: 'POST',\r\n headers: buildHeaders(this.options),\r\n body,\r\n timeout: this.options.timeout ?? 120000,\r\n });\r\n\r\n let usage: TokenUsageInfo | undefined;\r\n\r\n for await (const { data } of parseSSE(stream)) {\r\n try {\r\n const parsed = JSON.parse(data) as {\r\n choices?: Array<{\r\n delta?: {\r\n content?: string;\r\n tool_calls?: Array<{\r\n index: number;\r\n id?: string;\r\n type?: string;\r\n function?: { name?: string; arguments?: string };\r\n }>;\r\n };\r\n finish_reason?: string;\r\n }>;\r\n usage?: {\r\n prompt_tokens: number;\r\n completion_tokens: number;\r\n total_tokens: number;\r\n prompt_tokens_details?: {\r\n cached_tokens?: number;\r\n };\r\n };\r\n };\r\n\r\n if (parsed.usage) {\r\n usage = {\r\n inputTokens: parsed.usage.prompt_tokens,\r\n outputTokens: parsed.usage.completion_tokens,\r\n totalTokens: parsed.usage.total_tokens,\r\n cachedTokens: parsed.usage.prompt_tokens_details?.cached_tokens,\r\n };\r\n }\r\n\r\n const delta = parsed.choices?.[0]?.delta;\r\n if (!delta) continue;\r\n\r\n if (delta.content) {\r\n decoder.push(delta.content);\r\n yield { type: 'text', content: delta.content };\r\n }\r\n\r\n // Accumulate streamed tool calls\r\n if (delta.tool_calls) {\r\n for (const tc of delta.tool_calls) {\r\n const existing = toolCallAccum.get(tc.index);\r\n if (!existing) {\r\n toolCallAccum.set(tc.index, {\r\n id: tc.id || this.generateToolCallId(),\r\n type: 'function',\r\n function: {\r\n name: tc.function?.name || '',\r\n arguments: tc.function?.arguments || '',\r\n },\r\n });\r\n } else {\r\n if (tc.function?.arguments) {\r\n existing.function.arguments += tc.function.arguments;\r\n }\r\n if (tc.function?.name) {\r\n existing.function.name += tc.function.name;\r\n }\r\n }\r\n }\r\n }\r\n\r\n // Emit tool calls when stream finishes\r\n if (parsed.choices?.[0]?.finish_reason === 'tool_calls' || parsed.choices?.[0]?.finish_reason === 'stop') {\r\n if (toolCallAccum.size > 0) {\r\n const calls = Array.from(toolCallAccum.values());\r\n yield { type: 'tool_call', calls };\r\n }\r\n }\r\n } catch {\r\n // Skip unparseable SSE data\r\n }\r\n }\r\n\r\n decoder.flush();\r\n\r\n this.auditor.record({\r\n timestamp: Date.now(),\r\n type: 'stream_end',\r\n provider: 'openai',\r\n model: this.options.model,\r\n duration: Date.now() - start,\r\n usage,\r\n });\r\n\r\n const finalToolCalls = toolCallAccum.size > 0\r\n ? Array.from(toolCallAccum.values())\r\n : undefined;\r\n\r\n return {\r\n message: {\r\n role: 'assistant',\r\n content: decoder.getCleanContent(),\r\n tool_calls: finalToolCalls,\r\n },\r\n reasoning: decoder.getReasoning(),\r\n usage,\r\n provider: 'openai',\r\n };\r\n }\r\n\r\n // ========================================================================\r\n // Embeddings\r\n // ========================================================================\r\n\r\n async embed(text: string): Promise<number[]> {\r\n const url = `${this.options.url}/embeddings`;\r\n const response = await httpRequest<{\r\n data: Array<{ embedding: number[] }>;\r\n }>(url, {\r\n method: 'POST',\r\n headers: buildHeaders(this.options),\r\n body: {\r\n model: this.options.model,\r\n input: text,\r\n },\r\n timeout: this.options.timeout ?? 30000,\r\n });\r\n return response.data.data[0]?.embedding ?? [];\r\n }\r\n\r\n // ========================================================================\r\n // Model Discovery\r\n // ========================================================================\r\n\r\n async getModels(): Promise<string[]> {\r\n const url = `${this.options.url}/models`;\r\n try {\r\n const response = await httpRequest<{\r\n data: OpenAIModelInfo[];\r\n }>(url, {\r\n headers: buildHeaders(this.options),\r\n timeout: 5000,\r\n });\r\n return response.data.data.map(m => m.id);\r\n } catch {\r\n return [];\r\n }\r\n }\r\n\r\n // ========================================================================\r\n // Internals\r\n // ========================================================================\r\n\r\n private convertMessages(messages: LLMChatMessage[]): LLMChatMessage[] {\r\n // OpenAI format is our canonical format, minimal conversion needed\r\n return messages.map(msg => ({\r\n ...msg,\r\n // Ensure content is never null/undefined\r\n content: msg.content ?? '',\r\n }));\r\n }\r\n\r\n private buildRequestParams(options?: ChatOptions): Record<string, unknown> {\r\n const params: Record<string, unknown> = {\r\n ...this.options.defaultParameters,\r\n ...options?.parameters,\r\n };\r\n if (options?.temperature !== undefined) params['temperature'] = options.temperature;\r\n if (options?.maxTokens !== undefined) params['max_tokens'] = options.maxTokens;\r\n return params;\r\n }\r\n\r\n // ========================================================================\r\n // Structured Output Helpers\r\n // ========================================================================\r\n\r\n /**\r\n * Build OpenAI response_format for structured output.\r\n */\r\n private buildResponseFormat(options: StructuredOutputOptions<unknown> & { strict?: boolean }): Record<string, unknown> {\r\n let jsonSchema: JSONSchema;\r\n let name: string;\r\n let description: string | undefined;\r\n\r\n // Prefer jsonSchema if provided (handles raw JSON Schema case)\r\n if (options.jsonSchema) {\r\n // Use raw JSON Schema\r\n jsonSchema = normalizeJsonSchema(options.jsonSchema);\r\n name = options.name || 'response';\r\n description = options.description;\r\n } else if (options.schemaConfig) {\r\n // Use SchemaConfig's embedded JSON Schema\r\n jsonSchema = getJsonSchemaFromConfig(options.schemaConfig);\r\n name = options.name || options.schemaConfig.name || 'response';\r\n description = options.description || options.schemaConfig.description;\r\n } else {\r\n // Should not happen - we check this in extractSchemaOptions\r\n throw new Error('Either schemaConfig or jsonSchema must be provided');\r\n }\r\n\r\n // OpenAI strict mode — configurable, defaults to true for reliable structured output\r\n return {\r\n type: 'json_schema',\r\n json_schema: {\r\n name,\r\n ...(description && { description }),\r\n schema: jsonSchema,\r\n strict: options.strict ?? true,\r\n },\r\n };\r\n }\r\n}\r\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../src/router.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,KAAK,EAAE,OAAO,EAAE,M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