@juspay/neurolink 13.16.1 → 13.17.0

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 (121) hide show
  1. package/CHANGELOG.md +3 -3
  2. package/dist/adapters/providerImageAdapter.js +29 -495
  3. package/dist/browser/neurolink.min.js +464 -470
  4. package/dist/constants/contextWindows.js +13 -328
  5. package/dist/constants/enums.d.ts +1 -0
  6. package/dist/constants/enums.js +2 -1
  7. package/dist/context/anthropicLoopGuard.d.ts +1 -1
  8. package/dist/context/anthropicLoopGuard.js +2 -1
  9. package/dist/core/constants.js +6 -53
  10. package/dist/core/geminiLoopAdapter.js +8 -6
  11. package/dist/core/modules/structuredOutputPolicy.d.ts +0 -21
  12. package/dist/core/modules/structuredOutputPolicy.js +4 -54
  13. package/dist/factories/providerDescriptors.js +3 -2
  14. package/dist/factories/providerRegistry.js +3 -2
  15. package/dist/models/manifests/anthropic.d.ts +1 -1
  16. package/dist/models/manifests/anthropic.js +1 -1
  17. package/dist/models/manifests/azure.js +9 -9
  18. package/dist/models/manifests/ollama.js +13 -0
  19. package/dist/models/manifests/openai.d.ts +1 -1
  20. package/dist/models/manifests/openai.js +1 -1
  21. package/dist/models/modelRegistry.js +17 -42
  22. package/dist/providers/amazonBedrock/client.js +9 -37
  23. package/dist/providers/amazonBedrock/loopAdapter.js +3 -11
  24. package/dist/providers/anthropic/client.js +42 -97
  25. package/dist/providers/anthropic/loopAdapter.js +24 -22
  26. package/dist/providers/anthropic/structuredOutput.d.ts +0 -2
  27. package/dist/providers/anthropic/structuredOutput.js +3 -5
  28. package/dist/providers/azureOpenai.js +4 -22
  29. package/dist/providers/catalog/loader.js +12 -25
  30. package/dist/providers/cohere.js +5 -30
  31. package/dist/providers/googleAiStudio/client.js +12 -61
  32. package/dist/providers/googleNativeGemini3/utils.js +43 -102
  33. package/dist/providers/googleVertex/client.js +123 -184
  34. package/dist/providers/litellm/client.js +10 -50
  35. package/dist/providers/llamaCpp.js +4 -15
  36. package/dist/providers/lmStudio.js +9 -14
  37. package/dist/providers/nvidiaNim/client.js +4 -62
  38. package/dist/providers/ollama/client.js +14 -54
  39. package/dist/providers/ollama/constants.d.ts +1 -3
  40. package/dist/providers/ollama/constants.js +2 -3
  41. package/dist/providers/openAI/client.js +5 -57
  42. package/dist/providers/openRouter/client.js +4 -65
  43. package/dist/providers/openaiChatCompletionsBase.js +34 -58
  44. package/dist/providers/openaiChatCompletionsClient.js +17 -57
  45. package/dist/providers/openaiCompatible/client.js +9 -36
  46. package/dist/providers/rules/README.md +100 -0
  47. package/dist/providers/rules/anthropic.json +104 -0
  48. package/dist/providers/rules/azure.json +13 -0
  49. package/dist/providers/rules/bedrock.json +48 -0
  50. package/dist/providers/rules/cohere.json +32 -0
  51. package/dist/providers/rules/credentials.json +34 -0
  52. package/dist/providers/rules/errorRules.d.ts +17 -0
  53. package/dist/providers/rules/errorRules.js +197 -0
  54. package/dist/providers/rules/errorSignals.d.ts +2 -0
  55. package/dist/providers/rules/errorSignals.js +28 -0
  56. package/dist/providers/rules/fallbackModel.d.ts +4 -0
  57. package/dist/providers/rules/fallbackModel.js +21 -0
  58. package/dist/providers/rules/finalResultTool.d.ts +11 -0
  59. package/dist/providers/rules/finalResultTool.js +17 -0
  60. package/dist/providers/rules/finishReasons.d.ts +10 -0
  61. package/dist/providers/rules/finishReasons.js +28 -0
  62. package/dist/providers/rules/gemini.json +92 -0
  63. package/dist/providers/rules/google-ai.json +55 -0
  64. package/dist/providers/rules/limits.json +338 -0
  65. package/dist/providers/rules/litellm.json +36 -0
  66. package/dist/providers/rules/llamacpp.json +23 -0
  67. package/dist/providers/rules/lm-studio.json +21 -0
  68. package/dist/providers/rules/model-families.json +109 -0
  69. package/dist/providers/rules/modelFamilies.d.ts +10 -0
  70. package/dist/providers/rules/modelFamilies.js +45 -0
  71. package/dist/providers/rules/nvidia-nim.json +43 -0
  72. package/dist/providers/rules/ollama.json +37 -0
  73. package/dist/providers/rules/openai-chat.json +66 -0
  74. package/dist/providers/rules/openai-compatible.json +31 -0
  75. package/dist/providers/rules/openai.json +38 -0
  76. package/dist/providers/rules/openrouter.json +57 -0
  77. package/dist/providers/rules/proxy.json +44 -0
  78. package/dist/providers/rules/registry.d.ts +7 -0
  79. package/dist/providers/rules/registry.js +76 -0
  80. package/dist/providers/rules/requestDefaults.d.ts +7 -0
  81. package/dist/providers/rules/requestDefaults.js +9 -0
  82. package/dist/providers/rules/requestFields.d.ts +18 -0
  83. package/dist/providers/rules/requestFields.js +38 -0
  84. package/dist/providers/rules/sagemaker.json +88 -0
  85. package/dist/providers/rules/schema.d.ts +234 -0
  86. package/dist/providers/rules/schema.js +352 -0
  87. package/dist/providers/rules/structured-output.json +36 -0
  88. package/dist/providers/rules/thinkingLimits.d.ts +7 -0
  89. package/dist/providers/rules/thinkingLimits.js +9 -0
  90. package/dist/providers/rules/toolRules.d.ts +16 -0
  91. package/dist/providers/rules/toolRules.js +95 -0
  92. package/dist/providers/rules/usage.json +51 -0
  93. package/dist/providers/rules/vertex.json +65 -0
  94. package/dist/providers/rules/vision.json +505 -0
  95. package/dist/providers/rules/wireUsage.d.ts +38 -0
  96. package/dist/providers/rules/wireUsage.js +82 -0
  97. package/dist/providers/sagemaker/language-model.js +6 -33
  98. package/dist/providers/sagemaker/parsers.js +13 -48
  99. package/dist/providers/sagemaker/streaming.js +9 -16
  100. package/dist/proxy/claudeFormat.js +3 -16
  101. package/dist/proxy/geminiFormat.js +3 -9
  102. package/dist/proxy/openaiFormat.js +3 -16
  103. package/dist/types/index.d.ts +1 -0
  104. package/dist/types/index.js +2 -0
  105. package/dist/types/providerRules.d.ts +407 -0
  106. package/dist/types/providerRules.js +10 -0
  107. package/dist/utils/errorClassifier.d.ts +2 -2
  108. package/dist/utils/errorClassifier.js +3 -2
  109. package/dist/utils/modelDetection.d.ts +1 -1
  110. package/dist/utils/modelDetection.js +30 -71
  111. package/dist/utils/providerConfig.d.ts +10 -9
  112. package/dist/utils/providerConfig.js +26 -25
  113. package/dist/utils/providerHealth.js +1 -0
  114. package/dist/utils/thinkingConfig.d.ts +1 -1
  115. package/dist/utils/thinkingConfig.js +8 -8
  116. package/dist/utils/tokenUtils.d.ts +12 -38
  117. package/dist/utils/tokenUtils.js +44 -127
  118. package/docs-site/static/search-index.json +5 -5
  119. package/package.json +2 -1
  120. package/dist/providers/localRuntimeOpenAICompat.d.ts +0 -16
  121. package/dist/providers/localRuntimeOpenAICompat.js +0 -26
@@ -1,7 +1,6 @@
1
1
  import { registerRuntimeContextWindow, registerRuntimeOutputCeiling, } from "../../constants/contextWindows.js";
2
2
  import { createProxyFetch } from "../../proxy/proxyFetch.js";
3
- import { AuthenticationError, InvalidModelError, ModelAccessDeniedError, NetworkError, ProviderError, RateLimitError, isModelAccessDeniedMessage, parseAllowedModels, } from "../../types/index.js";
4
- import { classifyProviderError, DEFAULT_ERROR_RULES, } from "../../utils/errorClassifier.js";
3
+ import { ModelAccessDeniedError, NetworkError, ProviderError, isModelAccessDeniedMessage, parseAllowedModels, } from "../../types/index.js";
5
4
  import { isAbortError } from "../../utils/errorHandling.js";
6
5
  import { logger } from "../../utils/logger.js";
7
6
  import { redactUrlCredentials } from "../../utils/logSanitize.js";
@@ -10,6 +9,9 @@ import { getProviderModel } from "../../utils/providerConfig.js";
10
9
  import { createTimeoutController } from "../../utils/timeout.js";
11
10
  import { stripTrailingSlash } from "../openaiChatCompletionsClient.js";
12
11
  import { OpenAIChatCompletionsProvider } from "../openaiChatCompletionsBase.js";
12
+ import { classifyWithProviderRules } from "../rules/errorRules.js";
13
+ import { getProviderErrorRules } from "../rules/registry.js";
14
+ const LITELLM_ERROR_RULES = getProviderErrorRules("litellm");
13
15
  const FALLBACK_LITELLM_MODEL = "openai/gpt-5.4-mini";
14
16
  const getLiteLLMConfig = () => ({
15
17
  baseURL: process.env.LITELLM_BASE_URL || "http://localhost:4000",
@@ -273,15 +275,6 @@ export class LiteLLMProvider extends OpenAIChatCompletionsProvider {
273
275
  return opts;
274
276
  }
275
277
  formatProviderError(error) {
276
- // Curator P1-1: detect "team not allowed to access model" responses and
277
- // surface as ModelAccessDeniedError with the allowed_models array parsed
278
- // from the body. Must run before classification (not just before the
279
- // "API key" rule) because ModelAccessDeniedError's constructor takes an
280
- // `{ provider, requestedModel, allowedModels }` options object rather
281
- // than the `(message, provider?)` shape ProviderErrorRule expects, so it
282
- // can't be expressed as a declarative rule. No realistic overlap with the
283
- // timeout/ECONNREFUSED checks below (disjoint wording), so running this
284
- // first is behaviorally identical to the original nesting order.
285
278
  const errorRecord = error;
286
279
  if (typeof errorRecord?.message === "string" &&
287
280
  isModelAccessDeniedMessage(errorRecord.message)) {
@@ -291,45 +284,12 @@ export class LiteLLMProvider extends OpenAIChatCompletionsProvider {
291
284
  allowedModels: parseAllowedModels(errorRecord.message),
292
285
  });
293
286
  }
294
- const rules = [
295
- // Duck-typed timeout detection (name === "TimeoutError" OR message
296
- // contains "timeout") distinct from the `instanceof TimeoutError` check
297
- // classifyProviderError already performs first — preserved because
298
- // some rejection paths produce a plain object/Error with that shape
299
- // rather than a real TimeoutError instance.
300
- {
301
- match: (ctx) => ctx.errorName === "TimeoutError" || /timeout/i.test(ctx.message),
302
- errorClass: NetworkError,
303
- message: (ctx) => `Request timed out: ${ctx.message}`,
304
- },
305
- {
306
- match: (ctx) => /ECONNREFUSED|Failed to fetch/.test(ctx.message),
307
- errorClass: NetworkError,
308
- // Name the base URL this instance actually dialed — per-request
309
- // credentials can override LITELLM_BASE_URL, and an error pointing
310
- // at the env value sends the caller debugging the wrong host.
311
- message: () => "LiteLLM proxy server not available. Please start the LiteLLM proxy server at " +
312
- redactUrlCredentials(this.config.baseURL),
313
- },
314
- {
315
- match: (ctx) => /API_KEY_INVALID|Invalid API key/.test(ctx.message),
316
- errorClass: AuthenticationError,
317
- message: "Invalid LiteLLM configuration. Please check your LITELLM_API_KEY environment variable.",
318
- },
319
- {
320
- match: (ctx) => /rate limit/i.test(ctx.message),
321
- errorClass: RateLimitError,
322
- message: "LiteLLM rate limit exceeded. Please try again later.",
323
- },
324
- {
325
- match: (ctx) => /model/i.test(ctx.message) && /not found/i.test(ctx.message),
326
- errorClass: InvalidModelError,
327
- message: () => `Model '${this.modelName}' not available in LiteLLM proxy. ` +
328
- "Please check your LiteLLM configuration and ensure the model is configured.",
329
- },
330
- ...DEFAULT_ERROR_RULES,
331
- ];
332
- return classifyProviderError(error, rules, this.providerName, this.modelName);
287
+ return classifyWithProviderRules(error, LITELLM_ERROR_RULES, this.providerName, this.modelName, {
288
+ vars: () => ({
289
+ model: `${this.modelName}`,
290
+ baseURL: redactUrlCredentials(this.config.baseURL),
291
+ }),
292
+ });
333
293
  }
334
294
  /**
335
295
  * Get available models from LiteLLM proxy `/v1/models` endpoint.
@@ -1,9 +1,9 @@
1
- import { ProviderError } from "../types/index.js";
2
- import { classifyProviderError, DEFAULT_ERROR_RULES, } from "../utils/errorClassifier.js";
3
1
  import { logger } from "../utils/logger.js";
4
2
  import { redactUrlCredentials } from "../utils/logSanitize.js";
5
3
  import { OpenAIChatCompletionsProvider } from "./openaiChatCompletionsBase.js";
6
- import { buildLocalUnreachableErrorRule } from "./localRuntimeOpenAICompat.js";
4
+ import { classifyWithProviderRules } from "./rules/errorRules.js";
5
+ import { getProviderErrorRules } from "./rules/registry.js";
6
+ const LLAMACPP_ERROR_RULES = getProviderErrorRules("llamacpp");
7
7
  const LLAMACPP_DEFAULT_BASE_URL = "http://localhost:8080/v1";
8
8
  const LLAMACPP_PLACEHOLDER_KEY = "llamacpp";
9
9
  const getLlamaCppBaseURL = () => {
@@ -53,17 +53,6 @@ export class LlamaCppProvider extends OpenAIChatCompletionsProvider {
53
53
  return ["loaded-model"];
54
54
  }
55
55
  formatProviderError(error) {
56
- const rules = [
57
- buildLocalUnreachableErrorRule(error, () => `llama.cpp server not reachable at ${redactUrlCredentials(this.config.baseURL)}. ` +
58
- "Start it with: ./llama-server -m model.gguf --port 8080"),
59
- {
60
- match: (ctx) => ctx.statusCode === 400 ||
61
- (ctx.statusCode === undefined && /\b400\b/.test(ctx.message)),
62
- errorClass: ProviderError,
63
- message: "llama.cpp rejected the request. Common cause: model doesn't support tools (start llama-server with --jinja for tool support).",
64
- },
65
- ...DEFAULT_ERROR_RULES,
66
- ];
67
- return classifyProviderError(error, rules, this.providerName, this.modelName);
56
+ return classifyWithProviderRules(error, LLAMACPP_ERROR_RULES, this.providerName, this.modelName, { vars: () => ({ baseURL: redactUrlCredentials(this.config.baseURL) }) });
68
57
  }
69
58
  }
@@ -1,9 +1,9 @@
1
- import { InvalidModelError } from "../types/index.js";
2
- import { classifyProviderError, DEFAULT_ERROR_RULES, } from "../utils/errorClassifier.js";
3
1
  import { logger } from "../utils/logger.js";
4
2
  import { redactUrlCredentials } from "../utils/logSanitize.js";
5
3
  import { OpenAIChatCompletionsProvider } from "./openaiChatCompletionsBase.js";
6
- import { buildLocalUnreachableErrorRule } from "./localRuntimeOpenAICompat.js";
4
+ import { classifyWithProviderRules } from "./rules/errorRules.js";
5
+ import { getProviderErrorRules } from "./rules/registry.js";
6
+ const LM_STUDIO_ERROR_RULES = getProviderErrorRules("lm-studio");
7
7
  const LM_STUDIO_DEFAULT_BASE_URL = "http://localhost:1234/v1";
8
8
  const LM_STUDIO_PLACEHOLDER_KEY = "lm-studio";
9
9
  const FALLBACK_MODEL = "local-model";
@@ -48,17 +48,12 @@ export class LMStudioProvider extends OpenAIChatCompletionsProvider {
48
48
  return FALLBACK_MODEL;
49
49
  }
50
50
  formatProviderError(error) {
51
- const rules = [
52
- buildLocalUnreachableErrorRule(error, () => `LM Studio server not reachable at ${redactUrlCredentials(this.config.baseURL)}. ` +
53
- `Open the LM Studio app, load a model, and click "Start Server".`),
54
- {
55
- match: (ctx) => /model_not_found|404/.test(ctx.message),
56
- errorClass: InvalidModelError,
57
- message: () => `LM Studio model '${this.modelName}' is not loaded. Load it in the LM Studio app first.`,
58
- },
59
- ...DEFAULT_ERROR_RULES,
60
- ];
61
- return classifyProviderError(error, rules, this.providerName, this.modelName);
51
+ return classifyWithProviderRules(error, LM_STUDIO_ERROR_RULES, this.providerName, this.modelName, {
52
+ vars: () => ({
53
+ model: `${this.modelName}`,
54
+ baseURL: redactUrlCredentials(this.config.baseURL),
55
+ }),
56
+ });
62
57
  }
63
58
  async validateConfiguration() {
64
59
  return this.probeModelsEndpoint(this.config.apiKey && this.config.apiKey !== LM_STUDIO_PLACEHOLDER_KEY
@@ -1,11 +1,12 @@
1
1
  import { AIProviderName, NvidiaNimModels } from "../../constants/enums.js";
2
- import { AuthenticationError, InvalidModelError, ProviderError, RateLimitError, } from "../../types/index.js";
3
- import { classifyProviderError, DEFAULT_ERROR_RULES, messageNamesStatus, } from "../../utils/errorClassifier.js";
4
2
  import { logger } from "../../utils/logger.js";
5
3
  import { redactUrlCredentials } from "../../utils/logSanitize.js";
6
4
  import { createNvidiaNimConfig, getProviderModel, validateApiKey, } from "../../utils/providerConfig.js";
7
5
  import { OpenAIChatCompletionsProvider } from "../openaiChatCompletionsBase.js";
8
6
  import { PROVIDER_DESCRIPTORS_BY_NAME } from "../../factories/providerDescriptors.js";
7
+ import { classifyWithProviderRules } from "../rules/errorRules.js";
8
+ import { getProviderErrorRules } from "../rules/registry.js";
9
+ const NVIDIA_NIM_ERROR_RULES = getProviderErrorRules("nvidia-nim");
9
10
  /**
10
11
  * Decide whether a NIM 400 response body is a rejection of the named
11
12
  * field (as opposed to an unrelated 400 that happens to mention the
@@ -247,66 +248,7 @@ export class NvidiaNimProvider extends OpenAIChatCompletionsProvider {
247
248
  return JSON.parse(serialized);
248
249
  }
249
250
  formatProviderError(error) {
250
- const rules = [
251
- // NIM canonically returns HTTP 401/Unauthorized for invalid API keys,
252
- // but its OpenAI-compatible gateway sometimes surfaces a bare 400 +
253
- // "Bad Request" with no body details for both malformed-credentials
254
- // and bad-parameter cases. Because the two are indistinguishable from
255
- // the message alone, bare 400/"Bad Request" is deliberately NOT
256
- // promoted to "invalid key" here — that would mis-classify legitimate
257
- // parameter errors (e.g. unsupported `reasoning_budget`, unsupported
258
- // `chat_template`) as auth failures. Tests that probe the auth path
259
- // (K1) detect "bad request" / "400" themselves; tests that probe
260
- // parameter retry (K5) need the original "Bad Request" message to
261
- // surface.
262
- {
263
- match: (ctx) => /Invalid API key|Unauthorized/.test(ctx.message) ||
264
- messageNamesStatus(ctx.message, 401),
265
- errorClass: AuthenticationError,
266
- message: "Invalid NVIDIA NIM API key. Get one at https://build.nvidia.com/settings/api-keys",
267
- },
268
- {
269
- match: (ctx) => /rate limit/.test(ctx.message) ||
270
- messageNamesStatus(ctx.message, 429),
271
- errorClass: RateLimitError,
272
- message: "NVIDIA NIM rate limit exceeded",
273
- },
274
- {
275
- // An invalid key now reaches the gateway as HTTP 403
276
- // {"status":403,"title":"Forbidden","detail":"Authorization failed"},
277
- // not a 401 (probed live: a well-formed bad key gets this body, a
278
- // missing header or a malformed JWT still gets a 401). The same body is
279
- // reported for a valid key whose organization lacks Public API
280
- // Endpoints access. The text is what identifies it — the structured 403
281
- // alone does not, and the quota rule below would take a relayed
282
- // "403 Authorization failed" because that text names status 403. A
283
- // message that also says "quota" is left for the quota rule.
284
- match: (ctx) => /authori[sz]ation failed/i.test(ctx.message) &&
285
- !/quota/i.test(ctx.message),
286
- errorClass: AuthenticationError,
287
- message: "NVIDIA NIM rejected the credentials (HTTP 403 Authorization failed). Check the API key at https://build.nvidia.com/settings/api-keys; a valid key is also refused when its organization lacks Public API Endpoints access.",
288
- },
289
- {
290
- // NIM answers most of its roster with a 404 whose text ("Function …
291
- // not found for account …") names no model, so the status decides.
292
- match: (ctx) => ctx.statusCode === 404 ||
293
- /model_not_found/.test(ctx.message) ||
294
- messageNamesStatus(ctx.message, 404),
295
- errorClass: InvalidModelError,
296
- message: () => `NVIDIA NIM model '${this.modelName}' not available. Browse the catalog at https://build.nvidia.com/models`,
297
- },
298
- {
299
- // NVIDIA's throttle is a 429 {"status":429,"title":"Too Many Requests"}
300
- // (46 of 70 concurrent probes, no Retry-After); no source seen sends a
301
- // quota stop as a 403. This rule keeps the older text-keyed behaviour
302
- // for a relay that names the quota or a 403 in its message.
303
- match: (ctx) => /quota/.test(ctx.message) || messageNamesStatus(ctx.message, 403),
304
- errorClass: ProviderError,
305
- message: "NVIDIA NIM quota exceeded for your account",
306
- },
307
- ...DEFAULT_ERROR_RULES,
308
- ];
309
- return classifyProviderError(error, rules, this.providerName, this.modelName);
251
+ return classifyWithProviderRules(error, NVIDIA_NIM_ERROR_RULES, this.providerName, this.modelName, { vars: () => ({ model: `${this.modelName}` }) });
310
252
  }
311
253
  async validateConfiguration() {
312
254
  return (typeof this.config.apiKey === "string" &&
@@ -1,14 +1,16 @@
1
1
  import { modelConfig } from "../../core/modelConfiguration.js";
2
2
  import { createProxyFetch } from "../../proxy/proxyFetch.js";
3
- import { InvalidModelError, NetworkError, ProviderError, } from "../../types/index.js";
4
- import { classifyProviderError, DEFAULT_ERROR_RULES, } from "../../utils/errorClassifier.js";
3
+ import { ProviderError } from "../../types/index.js";
5
4
  import { logger } from "../../utils/logger.js";
6
5
  import { redactUrlCredentials } from "../../utils/logSanitize.js";
7
- import { createTimeoutController, parseTimeout, TimeoutError, } from "../../utils/timeout.js";
6
+ import { createTimeoutController, parseTimeout } from "../../utils/timeout.js";
8
7
  import { OpenAIChatCompletionsProvider } from "../openaiChatCompletionsBase.js";
9
- import { buildLocalUnreachableErrorRule } from "../localRuntimeOpenAICompat.js";
10
8
  import { stripTrailingSlash } from "../openaiChatCompletionsClient.js";
11
9
  import { DEFAULT_OLLAMA_MODEL } from "./constants.js";
10
+ import { classifyWithProviderRules } from "../rules/errorRules.js";
11
+ import { getFallbackModel } from "../rules/fallbackModel.js";
12
+ import { getProviderErrorRules } from "../rules/registry.js";
13
+ const OLLAMA_ERROR_RULES = getProviderErrorRules("ollama");
12
14
  // Ollama serves its OpenAI-compatible surface under `/v1` (/v1/chat/completions,
13
15
  // /v1/models, /v1/embeddings). The base client appends `/chat/completions` to
14
16
  // config.baseURL, so the base URL must already carry the `/v1` suffix.
@@ -17,7 +19,7 @@ const OLLAMA_DEFAULT_BASE_URL = "http://localhost:11434/v1";
17
19
  // requires a non-empty apiKey. A real key (OLLAMA_API_KEY) is only needed for
18
20
  // Ollama Cloud / an auth-proxying reverse proxy.
19
21
  const OLLAMA_PLACEHOLDER_KEY = "ollama";
20
- const FALLBACK_OLLAMA_MODEL = "llama3.1:8b";
22
+ const FALLBACK_OLLAMA_MODEL = getFallbackModel("ollama");
21
23
  const DEFAULT_EMBEDDING_MODEL = "nomic-embed-text";
22
24
  const EMBEDDINGS_TIMEOUT_MS = 30_000;
23
25
  const getDefaultOllamaModel = () => process.env.OLLAMA_MODEL || DEFAULT_OLLAMA_MODEL;
@@ -82,55 +84,13 @@ export class OllamaProvider extends OpenAIChatCompletionsProvider {
82
84
  return FALLBACK_OLLAMA_MODEL;
83
85
  }
84
86
  formatProviderError(error) {
85
- if (error instanceof TimeoutError) {
86
- // Custom message (not classifyProviderError's built-in "Request timed
87
- // out: ..." default). TimeoutError is handled unconditionally inside
88
- // classifyProviderError ahead of any rule table, so this quirk can only
89
- // be preserved via a pre-delegate intercept (same pattern used for
90
- // groq's TimeoutError override).
91
- return new NetworkError(`Ollama request timed out. The model may be loading or the request is too large.`, "ollama");
92
- }
93
- // `responseBody` isn't part of ProviderErrorContext, so it's read off the
94
- // raw error here (mirrors openAI's `errorType` extraction) for the
95
- // missing-model / 404 rules below, which match against message+body
96
- // combined exactly as the pre-migration code did.
97
- const errorRecord = error;
98
- const responseBody = typeof errorRecord?.responseBody === "string"
99
- ? errorRecord.responseBody
100
- : "";
101
- const rules = [
102
- buildLocalUnreachableErrorRule(error, () => `Cannot connect to Ollama at ${redactUrlCredentials(this.config.baseURL)}. ` +
103
- `Install Ollama (https://ollama.com), start it with 'ollama serve', then try again.`),
104
- // The base client (buildAPIError) attaches statusCode + responseBody to
105
- // HTTP failures. Distinguish a genuine missing-model error (give 'ollama
106
- // pull' guidance) from a bare endpoint-mismatch 404 (wrong base URL / not
107
- // the OpenAI-compatible /v1 surface) so the advice is actionable. Match
108
- // on wording, not a bare "404" substring, to avoid misclassifying
109
- // unrelated messages that merely contain those digits.
110
- {
111
- match: (ctx) => {
112
- const haystack = `${ctx.message} ${responseBody}`.toLowerCase();
113
- return (haystack.includes("model_not_found") ||
114
- (haystack.includes("model") && haystack.includes("not found")));
115
- },
116
- errorClass: InvalidModelError,
117
- message: () => `Ollama model '${this.modelName}' is not available locally. ` +
118
- `Pull it first with 'ollama pull ${this.modelName}' (or try '${FALLBACK_OLLAMA_MODEL}'); ` +
119
- `list installed models with 'ollama list'.`,
120
- },
121
- {
122
- match: (ctx) => {
123
- const haystack = `${ctx.message} ${responseBody}`.toLowerCase();
124
- return ctx.statusCode === 404 || haystack.includes("status 404");
125
- },
126
- errorClass: ProviderError,
127
- message: () => `Ollama returned HTTP 404 from ${redactUrlCredentials(this.config.baseURL)}. ` +
128
- `Verify the base URL serves the OpenAI-compatible /v1 API and that the ` +
129
- `model is installed ('ollama list').`,
130
- },
131
- ...DEFAULT_ERROR_RULES,
132
- ];
133
- return classifyProviderError(error, rules, this.providerName, this.modelName);
87
+ return classifyWithProviderRules(error, OLLAMA_ERROR_RULES, this.providerName, this.modelName, {
88
+ vars: () => ({
89
+ model: `${this.modelName}`,
90
+ baseURL: redactUrlCredentials(this.config.baseURL),
91
+ fallbackModel: FALLBACK_OLLAMA_MODEL,
92
+ }),
93
+ });
134
94
  }
135
95
  // ===========================================================================
136
96
  // Optional hooks — Ollama-specific behaviour
@@ -1,4 +1,2 @@
1
- import { OllamaModels } from "../../constants/enums.js";
2
- export declare const DEFAULT_OLLAMA_MODEL = OllamaModels.LLAMA3_2_LATEST;
3
- export declare const FALLBACK_OLLAMA_MODEL = "llama3.2:latest";
1
+ export declare const DEFAULT_OLLAMA_MODEL: string;
4
2
  export declare const proxyFetch: typeof fetch;
@@ -1,5 +1,4 @@
1
- import { OllamaModels } from "../../constants/enums.js";
2
1
  import { createProxyFetch } from "../../proxy/proxyFetch.js";
3
- export const DEFAULT_OLLAMA_MODEL = OllamaModels.LLAMA3_2_LATEST;
4
- export const FALLBACK_OLLAMA_MODEL = "llama3.2:latest";
2
+ import { getDefaultModel } from "../rules/fallbackModel.js";
3
+ export const DEFAULT_OLLAMA_MODEL = getDefaultModel("ollama");
5
4
  export const proxyFetch = createProxyFetch();
@@ -1,16 +1,17 @@
1
1
  import { AIProviderName as AIProviderNameEnum } from "../../constants/enums.js";
2
2
  import { createProxyFetch } from "../../proxy/proxyFetch.js";
3
- import { AuthenticationError, InvalidModelError, ProviderError, RateLimitError, } from "../../types/index.js";
3
+ import { ProviderError } from "../../types/index.js";
4
4
  import { logger } from "../../utils/logger.js";
5
5
  import { redactUrlCredentials } from "../../utils/logSanitize.js";
6
- import { classifyProviderError, DEFAULT_ERROR_RULES, } from "../../utils/errorClassifier.js";
7
6
  import { createOpenAIConfig, getProviderModel, validateApiKey, } from "../../utils/providerConfig.js";
8
7
  import { safeDownload } from "../../utils/safeFetch.js";
9
8
  import { MAX_IMAGE_BYTES } from "../../utils/sizeGuard.js";
10
9
  import { createTimeoutController } from "../../utils/timeout.js";
11
10
  import { stripTrailingSlash } from "../openaiChatCompletionsClient.js";
12
11
  import { OpenAIChatCompletionsProvider } from "../openaiChatCompletionsBase.js";
13
- import { isOpenAIQuotaExhaustedError, readOpenAIBodyErrorType, } from "../../utils/providerRetry.js";
12
+ import { classifyWithProviderRules } from "../rules/errorRules.js";
13
+ import { getProviderErrorRules } from "../rules/registry.js";
14
+ const OPENAI_ERROR_RULES = getProviderErrorRules("openai");
14
15
  const OPENAI_DEFAULT_BASE_URL = "https://api.openai.com/v1";
15
16
  /**
16
17
  * Resolve the effective OpenAI base URL from optional credential / env
@@ -87,60 +88,7 @@ export class OpenAIProvider extends OpenAIChatCompletionsProvider {
87
88
  return getOpenAIModel();
88
89
  }
89
90
  formatProviderError(error) {
90
- // Chat errors retain the JSON in responseBody; embedding errors stamp
91
- // type onto the raw error. Keep both paths available to the rule closures.
92
- const errorObj = error;
93
- const errorType = errorObj?.type && typeof errorObj.type === "string"
94
- ? errorObj.type
95
- : readOpenAIBodyErrorType(errorObj?.responseBody);
96
- const rules = [
97
- // Curator P1-1 / Reviewer Finding #4: only the explicit auth markers
98
- // map to AuthenticationError. Earlier we treated every
99
- // `invalid_request_error` as an auth failure — that's OpenAI's
100
- // catch-all for any bad request (unsupported parameter, malformed
101
- // JSON, etc.) and mislabelled them as "invalid API key". Use
102
- // credential-specific signals only.
103
- {
104
- match: (ctx) => ctx.statusCode === 401 ||
105
- errorType === "invalid_api_key" ||
106
- /API_KEY_INVALID|Invalid API key|Incorrect API key|invalid_api_key/i.test(ctx.message),
107
- errorClass: AuthenticationError,
108
- message: (ctx) => /Incorrect API key|Invalid API key/i.test(ctx.message)
109
- ? ctx.message
110
- : "Invalid OpenAI API key. Please check your OPENAI_API_KEY environment variable.",
111
- },
112
- // MUST precede the 429 rule below. OpenAI returns 429 for two
113
- // unrelated conditions: transient throttling, and a permanently
114
- // exhausted quota (out of credit, or a spend cap reached). Matching on
115
- // the status code alone collapses them, and the resulting advice —
116
- // "try again later" — is the one thing that can never resolve the
117
- // second. The signal is the error TYPE, not the wording.
118
- {
119
- // One definition of "permanent billing state", in the helper. The
120
- // earlier cut also tested `errorType === "insufficient_quota"` here,
121
- // which is precisely the helper's own first branch — two places to
122
- // keep in step for no benefit.
123
- match: (ctx) => isOpenAIQuotaExhaustedError(ctx.error),
124
- errorClass: ProviderError,
125
- message: "OpenAI quota exhausted — this will not resolve by retrying. " +
126
- "Check your plan and billing details at " +
127
- "https://platform.openai.com/account/billing",
128
- },
129
- {
130
- match: (ctx) => ctx.statusCode === 429 ||
131
- errorType === "rate_limit_error" ||
132
- /rate limit/i.test(ctx.message),
133
- errorClass: RateLimitError,
134
- message: "OpenAI rate limit exceeded. Please try again later.",
135
- },
136
- {
137
- match: (ctx) => /model_not_found/i.test(ctx.message),
138
- errorClass: InvalidModelError,
139
- message: (ctx) => `Model not found: ${ctx.modelName}`,
140
- },
141
- ...DEFAULT_ERROR_RULES,
142
- ];
143
- return classifyProviderError(error, rules, this.providerName, this.modelName);
91
+ return classifyWithProviderRules(error, OPENAI_ERROR_RULES, this.providerName, this.modelName, { vars: () => ({ model: `${this.modelName}` }) });
144
92
  }
145
93
  // ===========================================================================
146
94
  // Embeddings — native POST /v1/embeddings
@@ -1,13 +1,14 @@
1
1
  import { AIProviderName } from "../../constants/enums.js";
2
- import { AuthenticationError, InvalidModelError, NetworkError, ProviderError, RateLimitError, } from "../../types/index.js";
3
2
  import { createProxyFetch } from "../../proxy/proxyFetch.js";
4
- import { classifyProviderError, DEFAULT_ERROR_RULES, } from "../../utils/errorClassifier.js";
5
3
  import { isAbortError } from "../../utils/errorHandling.js";
6
4
  import { logger } from "../../utils/logger.js";
7
5
  import { redactUrlCredentials } from "../../utils/logSanitize.js";
8
6
  import { OpenAIChatCompletionsProvider } from "../openaiChatCompletionsBase.js";
9
7
  import { stripTrailingSlash } from "../openaiChatCompletionsClient.js";
10
8
  import { getDefaultOpenRouterModel } from "./utils.js";
9
+ import { classifyWithProviderRules } from "../rules/errorRules.js";
10
+ import { getProviderErrorRules } from "../rules/registry.js";
11
+ const OPENROUTER_ERROR_RULES = getProviderErrorRules("openrouter");
11
12
  // OpenRouter's OpenAI-compatible gateway. `${baseURL}/chat/completions` and
12
13
  // `${baseURL}/models` both resolve correctly off this root.
13
14
  const OPENROUTER_DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
@@ -87,69 +88,7 @@ export class OpenRouterProvider extends OpenAIChatCompletionsProvider {
87
88
  return getDefaultOpenRouterModel();
88
89
  }
89
90
  formatProviderError(error) {
90
- const rules = [
91
- // Duck-typed timeout detection (name === "TimeoutError" OR message
92
- // contains "Timeout", case-sensitive — matches the original's
93
- // `.includes("Timeout")`) distinct from the `instanceof TimeoutError`
94
- // check classifyProviderError already performs first.
95
- {
96
- match: (ctx) => ctx.errorName === "TimeoutError" || /Timeout/.test(ctx.message),
97
- errorClass: NetworkError,
98
- message: (ctx) => `Request timed out: ${ctx.message}`,
99
- },
100
- {
101
- match: (ctx) => /ECONNREFUSED|Failed to fetch/.test(ctx.message),
102
- errorClass: NetworkError,
103
- message: "OpenRouter API not available. Please check your network connection and try again.",
104
- },
105
- {
106
- match: (ctx) => /API_KEY_INVALID|Invalid API key|invalid_api_key|Unauthorized/.test(ctx.message),
107
- errorClass: AuthenticationError,
108
- message: "Invalid OpenRouter API key. Please check your OPENROUTER_API_KEY environment variable. " +
109
- "Get your key at https://openrouter.ai/keys",
110
- },
111
- {
112
- match: (ctx) => /rate limit/.test(ctx.message),
113
- errorClass: RateLimitError,
114
- message: "OpenRouter rate limit exceeded. Please try again later or upgrade your account at https://openrouter.ai/credits",
115
- },
116
- {
117
- match: (ctx) => /model/.test(ctx.message) && /not found/.test(ctx.message),
118
- errorClass: InvalidModelError,
119
- message: () => `Model '${this.modelName}' not available on OpenRouter. ` +
120
- "Browse available models at https://openrouter.ai/models",
121
- },
122
- {
123
- match: (ctx) => /insufficient_credits/.test(ctx.message),
124
- errorClass: ProviderError,
125
- message: "Insufficient OpenRouter credits. Add credits at https://openrouter.ai/credits",
126
- },
127
- // "No endpoints found" — model temporarily unavailable or unsupported
128
- // parameters. Distinct from tool errors: it can happen on any request
129
- // when the model has no available providers on OpenRouter.
130
- {
131
- match: (ctx) => /No endpoints found/.test(ctx.message),
132
- errorClass: InvalidModelError,
133
- message: () => `No endpoints found for model '${this.modelName}' on OpenRouter. ` +
134
- "The model may be temporarily unavailable or does not support the requested parameters. " +
135
- "Try a different model or check availability at https://openrouter.ai/models",
136
- },
137
- // Tool/function calling errors
138
- {
139
- match: (ctx) => /tool use|tool_use|function_call|tools are not supported/.test(ctx.message),
140
- errorClass: ProviderError,
141
- message: () => `Model '${this.modelName}' does not support tool calling. ` +
142
- "Use a tool-capable model like:\n" +
143
- " • google/gemini-2.0-flash-exp:free (free)\n" +
144
- " • meta-llama/llama-3.3-70b-instruct:free (free)\n" +
145
- " • anthropic/claude-3.7-sonnet (paid)\n" +
146
- " • openai/gpt-4o (paid)\n" +
147
- "Or use --disableTools flag. " +
148
- "See all tool-capable models at https://openrouter.ai/models?supported_parameters=tools",
149
- },
150
- ...DEFAULT_ERROR_RULES,
151
- ];
152
- return classifyProviderError(error, rules, this.providerName, this.modelName);
91
+ return classifyWithProviderRules(error, OPENROUTER_ERROR_RULES, this.providerName, this.modelName, { vars: () => ({ model: `${this.modelName}` }) });
153
92
  }
154
93
  // ===========================================================================
155
94
  // Optional hooks — provider-specific quirks