@yuva-devlab/ai-client 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -629,26 +629,28 @@ interface ILLMProvider {
629
629
 
630
630
  /**
631
631
  * @file packages/ai-client/src/config/env-resolver.ts
632
- * @description Safe runtime environment credential loader for opt-in consumer usage.
632
+ * @description Consumer environment credential loader mapping a supplied env dictionary into provider credentials.
633
633
  *
634
634
  * Utilizes centralized endpoints and default models from the constants module.
635
+ * Never accesses ambient process.env directly.
635
636
  *
636
637
  * @module @yuva-devlab/ai-client
637
638
  */
638
639
 
639
640
  /**
640
- * Maps standard environment variables for supported AI providers into a typed credentials object.
641
+ * Maps environment dictionary supplied by consumer for supported AI providers into a typed credentials object.
641
642
  *
642
643
  * @example
643
644
  * ```typescript
644
- * const creds = resolveEnvCredentials("groq");
645
+ * const creds = resolveEnvCredentials("groq", process.env);
645
646
  * console.log(creds.apiKey);
646
647
  * ```
647
648
  *
648
649
  * @param provider - Name of the provider (case-insensitive).
649
- * @returns Resolved ProviderCredentials from ambient environment if available.
650
+ * @param env - Consumer environment key-value map.
651
+ * @returns Resolved ProviderCredentials mapped from the consumer dictionary.
650
652
  */
651
- declare function resolveEnvCredentials(provider: string): ProviderCredentials;
653
+ declare function resolveEnvCredentials(provider: string, env?: Record<string, string | undefined>): ProviderCredentials;
652
654
 
653
655
  /**
654
656
  * @file packages/ai-client/src/adapters/ollama/ollama.types.ts
@@ -1227,30 +1229,50 @@ type ProviderType = "ollama" | "groq" | "google" | "openai" | "anthropic" | "cas
1227
1229
  */
1228
1230
  declare function createProvider(type: ProviderType, config?: Record<string, unknown>): ILLMProvider;
1229
1231
  /**
1230
- * Automatically inspects ambient environment and builds an ordered cascade of available providers.
1231
- *
1232
- * Priority order:
1233
- * 1. Local Ollama (always registered as offline/local tier)
1234
- * 2. Groq (if GROQ_API_KEY is present)
1235
- * 3. Google Gemini (if GEMINI_API_KEY is present)
1236
- * 4. OpenAI (if OPENAI_API_KEY is present)
1237
- * 5. Anthropic (if ANTHROPIC_API_KEY is present)
1232
+ * Configuration options for assembling a cascade of provider adapters.
1233
+ */
1234
+ interface CascadeCandidatesConfig {
1235
+ /** Optional Ollama configuration */
1236
+ ollama?: Record<string, unknown>;
1237
+ /** Optional Groq credentials and configuration */
1238
+ groq?: Record<string, unknown>;
1239
+ /** Optional Google Gemini credentials and configuration */
1240
+ google?: Record<string, unknown>;
1241
+ /** Optional OpenAI credentials and configuration */
1242
+ openai?: Record<string, unknown>;
1243
+ /** Optional Anthropic credentials and configuration */
1244
+ anthropic?: Record<string, unknown>;
1245
+ }
1246
+ /**
1247
+ * Builds an ordered cascade of provider candidates based on explicit consumer configuration.
1238
1248
  *
1249
+ * @param config - Provider configuration parameters supplied by consumer.
1239
1250
  * @returns Ordered array of configured ILLMProvider adapters.
1240
1251
  */
1241
- declare function createCascadeCandidates(): ILLMProvider[];
1252
+ declare function createCascadeCandidates(config?: CascadeCandidatesConfig): ILLMProvider[];
1253
+ /**
1254
+ * Options for instantiating the default provider.
1255
+ */
1256
+ interface DefaultProviderOptions {
1257
+ /** Explicit provider type name */
1258
+ provider?: ProviderType;
1259
+ /** Direct adapter configuration dictionary */
1260
+ config?: Record<string, unknown>;
1261
+ /** Cascade candidate options if falling back to multi-tier cascade */
1262
+ cascade?: CascadeCandidatesConfig;
1263
+ }
1242
1264
  /**
1243
- * Creates the default provider for the current environment.
1244
- * If specific AI_PROVIDER env var is specified, uses that; otherwise returns a robust FallbackCascade.
1265
+ * Creates the default provider based on explicit consumer options.
1245
1266
  *
1246
1267
  * @example
1247
1268
  * ```typescript
1248
- * const client = createDefaultProvider();
1269
+ * const client = createDefaultProvider({ provider: "groq", config: { apiKey: "gsk_..." } });
1249
1270
  * const response = await client.complete(request);
1250
1271
  * ```
1251
1272
  *
1273
+ * @param options - Consumer-provided configuration and provider selection.
1252
1274
  * @returns Instantiated ILLMProvider ready for completion.
1253
1275
  */
1254
- declare function createDefaultProvider(): ILLMProvider;
1276
+ declare function createDefaultProvider(options?: DefaultProviderOptions): ILLMProvider;
1255
1277
 
1256
- export { type AIMessage, AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, type AnthropicAdapterConfig, type AnthropicResponse, type CredentialResolver, type ExtractStructuredOutputOptions, FallbackCascade, type FallbackCascadeOptions, FinishReason, type GeminiCandidate, type GeminiResponse, GoogleAdapter, type GoogleAdapterConfig, GroqAdapter, type GroqAdapterConfig, type GroqCompletionResponse, type ILLMProvider, type LLMRequest, type LLMRequestOptions, LLMRequestOptionsSchema, LLMRequestSchema, type LLMResponse, LLMResponseSchema, type LLMStreamChunk, type LLMUsage, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, type OllamaAdapterConfig, type OllamaChatResponseChunk, type OllamaWireMessage, OpenAIAdapter, type OpenAIAdapterConfig, type OpenAiCompletionResponse, type OpenAiWireMessage, type ProviderCredentials, type ProviderType, type ToolCall, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractStructuredOutput, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials };
1278
+ export { type AIMessage, AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, type AnthropicAdapterConfig, type AnthropicResponse, type CascadeCandidatesConfig, type CredentialResolver, type DefaultProviderOptions, type ExtractStructuredOutputOptions, FallbackCascade, type FallbackCascadeOptions, FinishReason, type GeminiCandidate, type GeminiResponse, GoogleAdapter, type GoogleAdapterConfig, GroqAdapter, type GroqAdapterConfig, type GroqCompletionResponse, type ILLMProvider, type LLMRequest, type LLMRequestOptions, LLMRequestOptionsSchema, LLMRequestSchema, type LLMResponse, LLMResponseSchema, type LLMStreamChunk, type LLMUsage, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, type OllamaAdapterConfig, type OllamaChatResponseChunk, type OllamaWireMessage, OpenAIAdapter, type OpenAIAdapterConfig, type OpenAiCompletionResponse, type OpenAiWireMessage, type ProviderCredentials, type ProviderType, type ToolCall, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractStructuredOutput, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials };
package/dist/index.d.ts CHANGED
@@ -629,26 +629,28 @@ interface ILLMProvider {
629
629
 
630
630
  /**
631
631
  * @file packages/ai-client/src/config/env-resolver.ts
632
- * @description Safe runtime environment credential loader for opt-in consumer usage.
632
+ * @description Consumer environment credential loader mapping a supplied env dictionary into provider credentials.
633
633
  *
634
634
  * Utilizes centralized endpoints and default models from the constants module.
635
+ * Never accesses ambient process.env directly.
635
636
  *
636
637
  * @module @yuva-devlab/ai-client
637
638
  */
638
639
 
639
640
  /**
640
- * Maps standard environment variables for supported AI providers into a typed credentials object.
641
+ * Maps environment dictionary supplied by consumer for supported AI providers into a typed credentials object.
641
642
  *
642
643
  * @example
643
644
  * ```typescript
644
- * const creds = resolveEnvCredentials("groq");
645
+ * const creds = resolveEnvCredentials("groq", process.env);
645
646
  * console.log(creds.apiKey);
646
647
  * ```
647
648
  *
648
649
  * @param provider - Name of the provider (case-insensitive).
649
- * @returns Resolved ProviderCredentials from ambient environment if available.
650
+ * @param env - Consumer environment key-value map.
651
+ * @returns Resolved ProviderCredentials mapped from the consumer dictionary.
650
652
  */
651
- declare function resolveEnvCredentials(provider: string): ProviderCredentials;
653
+ declare function resolveEnvCredentials(provider: string, env?: Record<string, string | undefined>): ProviderCredentials;
652
654
 
653
655
  /**
654
656
  * @file packages/ai-client/src/adapters/ollama/ollama.types.ts
@@ -1227,30 +1229,50 @@ type ProviderType = "ollama" | "groq" | "google" | "openai" | "anthropic" | "cas
1227
1229
  */
1228
1230
  declare function createProvider(type: ProviderType, config?: Record<string, unknown>): ILLMProvider;
1229
1231
  /**
1230
- * Automatically inspects ambient environment and builds an ordered cascade of available providers.
1231
- *
1232
- * Priority order:
1233
- * 1. Local Ollama (always registered as offline/local tier)
1234
- * 2. Groq (if GROQ_API_KEY is present)
1235
- * 3. Google Gemini (if GEMINI_API_KEY is present)
1236
- * 4. OpenAI (if OPENAI_API_KEY is present)
1237
- * 5. Anthropic (if ANTHROPIC_API_KEY is present)
1232
+ * Configuration options for assembling a cascade of provider adapters.
1233
+ */
1234
+ interface CascadeCandidatesConfig {
1235
+ /** Optional Ollama configuration */
1236
+ ollama?: Record<string, unknown>;
1237
+ /** Optional Groq credentials and configuration */
1238
+ groq?: Record<string, unknown>;
1239
+ /** Optional Google Gemini credentials and configuration */
1240
+ google?: Record<string, unknown>;
1241
+ /** Optional OpenAI credentials and configuration */
1242
+ openai?: Record<string, unknown>;
1243
+ /** Optional Anthropic credentials and configuration */
1244
+ anthropic?: Record<string, unknown>;
1245
+ }
1246
+ /**
1247
+ * Builds an ordered cascade of provider candidates based on explicit consumer configuration.
1238
1248
  *
1249
+ * @param config - Provider configuration parameters supplied by consumer.
1239
1250
  * @returns Ordered array of configured ILLMProvider adapters.
1240
1251
  */
1241
- declare function createCascadeCandidates(): ILLMProvider[];
1252
+ declare function createCascadeCandidates(config?: CascadeCandidatesConfig): ILLMProvider[];
1253
+ /**
1254
+ * Options for instantiating the default provider.
1255
+ */
1256
+ interface DefaultProviderOptions {
1257
+ /** Explicit provider type name */
1258
+ provider?: ProviderType;
1259
+ /** Direct adapter configuration dictionary */
1260
+ config?: Record<string, unknown>;
1261
+ /** Cascade candidate options if falling back to multi-tier cascade */
1262
+ cascade?: CascadeCandidatesConfig;
1263
+ }
1242
1264
  /**
1243
- * Creates the default provider for the current environment.
1244
- * If specific AI_PROVIDER env var is specified, uses that; otherwise returns a robust FallbackCascade.
1265
+ * Creates the default provider based on explicit consumer options.
1245
1266
  *
1246
1267
  * @example
1247
1268
  * ```typescript
1248
- * const client = createDefaultProvider();
1269
+ * const client = createDefaultProvider({ provider: "groq", config: { apiKey: "gsk_..." } });
1249
1270
  * const response = await client.complete(request);
1250
1271
  * ```
1251
1272
  *
1273
+ * @param options - Consumer-provided configuration and provider selection.
1252
1274
  * @returns Instantiated ILLMProvider ready for completion.
1253
1275
  */
1254
- declare function createDefaultProvider(): ILLMProvider;
1276
+ declare function createDefaultProvider(options?: DefaultProviderOptions): ILLMProvider;
1255
1277
 
1256
- export { type AIMessage, AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, type AnthropicAdapterConfig, type AnthropicResponse, type CredentialResolver, type ExtractStructuredOutputOptions, FallbackCascade, type FallbackCascadeOptions, FinishReason, type GeminiCandidate, type GeminiResponse, GoogleAdapter, type GoogleAdapterConfig, GroqAdapter, type GroqAdapterConfig, type GroqCompletionResponse, type ILLMProvider, type LLMRequest, type LLMRequestOptions, LLMRequestOptionsSchema, LLMRequestSchema, type LLMResponse, LLMResponseSchema, type LLMStreamChunk, type LLMUsage, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, type OllamaAdapterConfig, type OllamaChatResponseChunk, type OllamaWireMessage, OpenAIAdapter, type OpenAIAdapterConfig, type OpenAiCompletionResponse, type OpenAiWireMessage, type ProviderCredentials, type ProviderType, type ToolCall, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractStructuredOutput, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials };
1278
+ export { type AIMessage, AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, type AnthropicAdapterConfig, type AnthropicResponse, type CascadeCandidatesConfig, type CredentialResolver, type DefaultProviderOptions, type ExtractStructuredOutputOptions, FallbackCascade, type FallbackCascadeOptions, FinishReason, type GeminiCandidate, type GeminiResponse, GoogleAdapter, type GoogleAdapterConfig, GroqAdapter, type GroqAdapterConfig, type GroqCompletionResponse, type ILLMProvider, type LLMRequest, type LLMRequestOptions, LLMRequestOptionsSchema, LLMRequestSchema, type LLMResponse, LLMResponseSchema, type LLMStreamChunk, type LLMUsage, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, type OllamaAdapterConfig, type OllamaChatResponseChunk, type OllamaWireMessage, OpenAIAdapter, type OpenAIAdapterConfig, type OpenAiCompletionResponse, type OpenAiWireMessage, type ProviderCredentials, type ProviderType, type ToolCall, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractStructuredOutput, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials };
package/dist/index.js CHANGED
@@ -162,42 +162,36 @@ var MissingCredentialError = class extends DomainError {
162
162
  };
163
163
 
164
164
  // src/config/env-resolver.ts
165
- function safeGetEnv(key) {
166
- if (typeof process !== "undefined" && process?.env) {
167
- return process.env[key];
168
- }
169
- return void 0;
170
- }
171
- function resolveEnvCredentials(provider) {
165
+ function resolveEnvCredentials(provider, env = {}) {
172
166
  const norm = provider.toLowerCase();
173
167
  switch (norm) {
174
168
  case "ollama":
175
169
  return {
176
- baseUrl: safeGetEnv("OLLAMA_BASE_URL") ?? AI_ENDPOINTS.OLLAMA_DEFAULT_BASE_URL,
177
- defaultModel: safeGetEnv("OLLAMA_MODEL") ?? AI_DEFAULT_MODELS.OLLAMA
170
+ baseUrl: env.OLLAMA_BASE_URL ?? AI_ENDPOINTS.OLLAMA_DEFAULT_BASE_URL,
171
+ defaultModel: env.OLLAMA_MODEL ?? AI_DEFAULT_MODELS.OLLAMA
178
172
  };
179
173
  case "groq":
180
174
  return {
181
- apiKey: safeGetEnv("GROQ_API_KEY"),
182
- baseUrl: safeGetEnv("GROQ_BASE_URL") ?? AI_ENDPOINTS.GROQ_DEFAULT_BASE_URL,
183
- defaultModel: safeGetEnv("GROQ_MODEL") ?? AI_DEFAULT_MODELS.GROQ
175
+ apiKey: env.GROQ_API_KEY,
176
+ baseUrl: env.GROQ_BASE_URL ?? AI_ENDPOINTS.GROQ_DEFAULT_BASE_URL,
177
+ defaultModel: env.GROQ_MODEL ?? AI_DEFAULT_MODELS.GROQ
184
178
  };
185
179
  case "google":
186
180
  return {
187
- apiKey: safeGetEnv("GEMINI_API_KEY") ?? safeGetEnv("GOOGLE_AI_API_KEY"),
188
- defaultModel: safeGetEnv("GEMINI_MODEL") ?? AI_DEFAULT_MODELS.GOOGLE
181
+ apiKey: env.GEMINI_API_KEY ?? env.GOOGLE_AI_API_KEY,
182
+ defaultModel: env.GEMINI_MODEL ?? AI_DEFAULT_MODELS.GOOGLE
189
183
  };
190
184
  case "openai":
191
185
  return {
192
- apiKey: safeGetEnv("OPENAI_API_KEY"),
193
- baseUrl: safeGetEnv("OPENAI_BASE_URL") ?? AI_ENDPOINTS.OPENAI_DEFAULT_BASE_URL,
194
- defaultModel: safeGetEnv("OPENAI_MODEL") ?? AI_DEFAULT_MODELS.OPENAI
186
+ apiKey: env.OPENAI_API_KEY,
187
+ baseUrl: env.OPENAI_BASE_URL ?? AI_ENDPOINTS.OPENAI_DEFAULT_BASE_URL,
188
+ defaultModel: env.OPENAI_MODEL ?? AI_DEFAULT_MODELS.OPENAI
195
189
  };
196
190
  case "anthropic":
197
191
  return {
198
- apiKey: safeGetEnv("ANTHROPIC_API_KEY"),
199
- baseUrl: safeGetEnv("ANTHROPIC_BASE_URL") ?? AI_ENDPOINTS.ANTHROPIC_DEFAULT_BASE_URL,
200
- defaultModel: safeGetEnv("ANTHROPIC_MODEL") ?? AI_DEFAULT_MODELS.ANTHROPIC
192
+ apiKey: env.ANTHROPIC_API_KEY,
193
+ baseUrl: env.ANTHROPIC_BASE_URL ?? AI_ENDPOINTS.ANTHROPIC_DEFAULT_BASE_URL,
194
+ defaultModel: env.ANTHROPIC_MODEL ?? AI_DEFAULT_MODELS.ANTHROPIC
201
195
  };
202
196
  default:
203
197
  return {};
@@ -235,9 +229,8 @@ var OllamaAdapter = class {
235
229
  */
236
230
  async resolveCredentials() {
237
231
  const dynamic = this.config.credentials ? await this.config.credentials() : {};
238
- const env = resolveEnvCredentials(this.name);
239
- const baseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? env.baseUrl ?? AI_ENDPOINTS.OLLAMA_DEFAULT_BASE_URL).replace(/\/+$/, "");
240
- const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? env.defaultModel ?? AI_DEFAULT_MODELS.OLLAMA;
232
+ const baseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? AI_ENDPOINTS.OLLAMA_DEFAULT_BASE_URL).replace(/\/+$/, "");
233
+ const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? AI_DEFAULT_MODELS.OLLAMA;
241
234
  return { baseUrl, defaultModel };
242
235
  }
243
236
  /**
@@ -411,12 +404,11 @@ var GroqAdapter = class {
411
404
  */
412
405
  async resolveCredentials() {
413
406
  const dynamic = this.config.credentials ? await this.config.credentials() : {};
414
- const env = resolveEnvCredentials(this.name);
415
- const apiKey = this.config.apiKey ?? dynamic.apiKey ?? env.apiKey;
416
- const baseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? env.baseUrl ?? AI_ENDPOINTS.GROQ_DEFAULT_BASE_URL).replace(/\/+$/, "");
417
- const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? env.defaultModel ?? AI_DEFAULT_MODELS.GROQ;
407
+ const apiKey = this.config.apiKey ?? dynamic.apiKey;
408
+ const baseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? AI_ENDPOINTS.GROQ_DEFAULT_BASE_URL).replace(/\/+$/, "");
409
+ const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? AI_DEFAULT_MODELS.GROQ;
418
410
  if (!apiKey) {
419
- throw new MissingCredentialError("Groq", "GROQ_API_KEY");
411
+ throw new MissingCredentialError("Groq", "apiKey");
420
412
  }
421
413
  return { apiKey, baseUrl, defaultModel };
422
414
  }
@@ -599,12 +591,12 @@ var GoogleAdapter = class {
599
591
  */
600
592
  async resolveCredentials() {
601
593
  const dynamic = this.config.credentials ? await this.config.credentials() : {};
602
- const env = resolveEnvCredentials(this.name);
603
- const apiKey = this.config.apiKey ?? dynamic.apiKey ?? env.apiKey;
604
- const baseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? env.baseUrl ?? AI_ENDPOINTS.GOOGLE_GEMINI_DEFAULT_BASE_URL).replace(/\/+$/, "");
605
- const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? env.defaultModel ?? "gemini-2.5-flash";
594
+ const apiKey = this.config.apiKey ?? dynamic.apiKey;
595
+ const rawBaseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? AI_ENDPOINTS.GOOGLE_GEMINI_DEFAULT_BASE_URL).replace(/\/+$/, "");
596
+ const baseUrl = rawBaseUrl.endsWith("/v1beta") ? rawBaseUrl : `${rawBaseUrl}/v1beta`;
597
+ const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? "gemini-3.8-flash";
606
598
  if (!apiKey) {
607
- throw new MissingCredentialError("Google Gemini", "GEMINI_API_KEY");
599
+ throw new MissingCredentialError("Google Gemini", "apiKey");
608
600
  }
609
601
  return { apiKey, baseUrl, defaultModel };
610
602
  }
@@ -684,11 +676,24 @@ var GoogleAdapter = class {
684
676
  const { apiKey, baseUrl, defaultModel } = await this.resolveCredentials();
685
677
  const model = request.model || defaultModel;
686
678
  const url = `${baseUrl}/models/${model}:streamGenerateContent?alt=sse&key=${apiKey}`;
687
- const response = await fetch(url, {
679
+ let response = await fetch(url, {
688
680
  method: "POST",
689
681
  headers: { "Content-Type": "application/json" },
690
- body: JSON.stringify(buildGeminiRequestBody(request))
691
- });
682
+ body: JSON.stringify(buildGeminiRequestBody(request)),
683
+ signal: AbortSignal.timeout(6e3)
684
+ }).catch(() => null);
685
+ if (!response || !response.ok && (response.status === 503 || response.status === 404)) {
686
+ logger3.warn("[stream] Primary model unavailable, using fallback", {
687
+ model,
688
+ status: response?.status
689
+ });
690
+ const fallbackUrl = `${baseUrl}/models/gemini-3.1-flash-lite:streamGenerateContent?alt=sse&key=${apiKey}`;
691
+ response = await fetch(fallbackUrl, {
692
+ method: "POST",
693
+ headers: { "Content-Type": "application/json" },
694
+ body: JSON.stringify(buildGeminiRequestBody(request))
695
+ });
696
+ }
692
697
  if (!response.ok || !response.body) {
693
698
  throw new DomainError(
694
699
  `Gemini streaming error HTTP ${response.status}`,
@@ -750,12 +755,11 @@ var OpenAIAdapter = class {
750
755
  */
751
756
  async resolveCredentials() {
752
757
  const dynamic = this.config.credentials ? await this.config.credentials() : {};
753
- const env = resolveEnvCredentials(this.name);
754
- const apiKey = this.config.apiKey ?? dynamic.apiKey ?? env.apiKey;
755
- const baseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? env.baseUrl ?? AI_ENDPOINTS.OPENAI_DEFAULT_BASE_URL).replace(/\/+$/, "");
756
- const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? env.defaultModel ?? AI_DEFAULT_MODELS.OPENAI;
758
+ const apiKey = this.config.apiKey ?? dynamic.apiKey;
759
+ const baseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? AI_ENDPOINTS.OPENAI_DEFAULT_BASE_URL).replace(/\/+$/, "");
760
+ const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? AI_DEFAULT_MODELS.OPENAI;
757
761
  if (!apiKey) {
758
- throw new MissingCredentialError("OpenAI", "OPENAI_API_KEY");
762
+ throw new MissingCredentialError("OpenAI", "apiKey");
759
763
  }
760
764
  return { apiKey, baseUrl, defaultModel };
761
765
  }
@@ -930,12 +934,11 @@ var AnthropicAdapter = class {
930
934
  */
931
935
  async resolveCredentials() {
932
936
  const dynamic = this.config.credentials ? await this.config.credentials() : {};
933
- const env = resolveEnvCredentials(this.name);
934
- const apiKey = this.config.apiKey ?? dynamic.apiKey ?? env.apiKey;
935
- const baseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? env.baseUrl ?? AI_ENDPOINTS.ANTHROPIC_DEFAULT_BASE_URL).replace(/\/+$/, "");
936
- const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? env.defaultModel ?? AI_DEFAULT_MODELS.ANTHROPIC;
937
+ const apiKey = this.config.apiKey ?? dynamic.apiKey;
938
+ const baseUrl = (this.config.baseUrl ?? dynamic.baseUrl ?? AI_ENDPOINTS.ANTHROPIC_DEFAULT_BASE_URL).replace(/\/+$/, "");
939
+ const defaultModel = this.config.defaultModel ?? dynamic.defaultModel ?? AI_DEFAULT_MODELS.ANTHROPIC;
937
940
  if (!apiKey) {
938
- throw new MissingCredentialError("Anthropic", "ANTHROPIC_API_KEY");
941
+ throw new MissingCredentialError("Anthropic", "apiKey");
939
942
  }
940
943
  return { apiKey, baseUrl, defaultModel };
941
944
  }
@@ -1200,32 +1203,38 @@ function createProvider(type, config = {}) {
1200
1203
  );
1201
1204
  }
1202
1205
  }
1203
- function createCascadeCandidates() {
1206
+ function createCascadeCandidates(config = {}) {
1204
1207
  const candidates = [];
1205
- candidates.push(new OllamaAdapter());
1206
- if (typeof process !== "undefined" && process?.env?.GROQ_API_KEY) {
1207
- candidates.push(new GroqAdapter());
1208
+ if (config.ollama) {
1209
+ candidates.push(new OllamaAdapter(config.ollama));
1208
1210
  }
1209
- if (typeof process !== "undefined" && (process?.env?.GEMINI_API_KEY || process?.env?.GOOGLE_AI_API_KEY)) {
1210
- candidates.push(new GoogleAdapter());
1211
+ if (config.groq) {
1212
+ candidates.push(new GroqAdapter(config.groq));
1211
1213
  }
1212
- if (typeof process !== "undefined" && process?.env?.OPENAI_API_KEY) {
1213
- candidates.push(new OpenAIAdapter());
1214
+ if (config.google) {
1215
+ candidates.push(new GoogleAdapter(config.google));
1214
1216
  }
1215
- if (typeof process !== "undefined" && process?.env?.ANTHROPIC_API_KEY) {
1216
- candidates.push(new AnthropicAdapter());
1217
+ if (config.openai) {
1218
+ candidates.push(new OpenAIAdapter(config.openai));
1219
+ }
1220
+ if (config.anthropic) {
1221
+ candidates.push(new AnthropicAdapter(config.anthropic));
1222
+ }
1223
+ if (candidates.length === 0) {
1224
+ candidates.push(new OllamaAdapter(config.ollama ?? {}));
1217
1225
  }
1218
1226
  return candidates;
1219
1227
  }
1220
- function createDefaultProvider() {
1221
- const envProvider = typeof process !== "undefined" ? process?.env?.AI_PROVIDER : void 0;
1222
- if (envProvider) {
1228
+ function createDefaultProvider(options = {}) {
1229
+ if (options.provider) {
1223
1230
  logger8.info(
1224
- `[createDefaultProvider] Using explicitly configured provider: ${envProvider}`
1231
+ `[createDefaultProvider] Using explicitly configured provider: ${options.provider}`
1225
1232
  );
1226
- return createProvider(envProvider);
1233
+ return createProvider(options.provider, options.config);
1227
1234
  }
1228
- return new FallbackCascade({ providers: createCascadeCandidates() });
1235
+ return new FallbackCascade({
1236
+ providers: createCascadeCandidates(options.cascade)
1237
+ });
1229
1238
  }
1230
1239
 
1231
1240
  export { AIMessageSchema, AI_DEFAULT_MODELS, AI_ENDPOINTS, AI_EXECUTION_DEFAULTS, AnthropicAdapter, FallbackCascade, FinishReason, GoogleAdapter, GroqAdapter, LLMRequestOptionsSchema, LLMRequestSchema, LLMResponseSchema, LLMUsageSchema, MessageRole, MissingCredentialError, OllamaAdapter, OpenAIAdapter, ToolCallSchema, buildGeminiRequestBody, createAssistantMessage, createCascadeCandidates, createDefaultProvider, createProvider, createSystemMessage, createToolResultMessage, createUserMessage, extractAnthropicSystemAndMessages, extractStructuredOutput, mapGroqMessages, mapOllamaMessages, mapOpenAiMessages, resolveEnvCredentials };