@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,8 @@
1
1
  import { ProviderFactory } from "./providerFactory.js";
2
2
  import { logger } from "../utils/logger.js";
3
- import { AIProviderName, GoogleAIModels, OpenAIModels, AnthropicModels, VertexModels, OllamaModels, LiteLLMModels, NvidiaNimModels, OpenRouterModels, CohereModels, VoyageModels, JinaModels, StabilityModels, IdeogramModels, RecraftModels, TypeSafeModels, PerplexityDeciderModels, CloudflareClefModels, ReplicateModels, } from "../constants/enums.js";
3
+ import { AIProviderName, GoogleAIModels, OpenAIModels, AnthropicModels, VertexModels, LiteLLMModels, NvidiaNimModels, OpenRouterModels, CohereModels, VoyageModels, JinaModels, StabilityModels, IdeogramModels, RecraftModels, TypeSafeModels, PerplexityDeciderModels, CloudflareClefModels, ReplicateModels, } from "../constants/enums.js";
4
4
  import { PROVIDER_DESCRIPTORS_BY_NAME } from "./providerDescriptors.js";
5
+ import { getDefaultModel } from "../providers/rules/fallbackModel.js";
5
6
  import { OPENAI_COMPAT_CATALOG } from "../providers/openaiCompatCatalog.js";
6
7
  import { providerChoicesFor } from "./mediaHandlerCatalog.js";
7
8
  import { catalogEnvVar, getDecideCatalogEntries, } from "../providers/catalog/loader.js";
@@ -143,7 +144,7 @@ export class ProviderRegistry {
143
144
  const ollamaCreds = credentials;
144
145
  const { OllamaProvider } = await import("../providers/ollama/index.js");
145
146
  return new OllamaProvider(modelName, sdk, undefined, ollamaCreds);
146
- }, process.env.OLLAMA_MODEL || OllamaModels.LLAMA3_2_LATEST, ["ollama", "local"], PROVIDER_DESCRIPTORS_BY_NAME.get(AIProviderName.OLLAMA));
147
+ }, process.env.OLLAMA_MODEL || getDefaultModel("ollama"), ["ollama", "local"], PROVIDER_DESCRIPTORS_BY_NAME.get(AIProviderName.OLLAMA));
147
148
  // Register LiteLLM provider
148
149
  ProviderFactory.registerProvider(AIProviderName.LITELLM, async (modelName, _providerName, sdk, _region, credentials) => {
149
150
  const litellmCreds = credentials;
@@ -2,7 +2,7 @@ import type { ProviderModelManifest } from "../../types/index.js";
2
2
  /**
3
3
  * Anthropic model manifest. Canonical ids match AnthropicModels
4
4
  * (src/lib/constants/enums.ts:524+) and MODEL_CONTEXT_WINDOWS.anthropic
5
- * (src/lib/constants/contextWindows.ts:160-182). maxOutputTokens values
5
+ * (src/lib/providers/rules/limits.json). maxOutputTokens values
6
6
  * come from getClaudeMaxOutputTokens (src/lib/utils/tokenLimits.ts) — the
7
7
  * regex ladder already authoritative for native Claude request paths.
8
8
  */
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Anthropic model manifest. Canonical ids match AnthropicModels
3
3
  * (src/lib/constants/enums.ts:524+) and MODEL_CONTEXT_WINDOWS.anthropic
4
- * (src/lib/constants/contextWindows.ts:160-182). maxOutputTokens values
4
+ * (src/lib/providers/rules/limits.json). maxOutputTokens values
5
5
  * come from getClaudeMaxOutputTokens (src/lib/utils/tokenLimits.ts) — the
6
6
  * regex ladder already authoritative for native Claude request paths.
7
7
  */
@@ -4,8 +4,8 @@ export const azureManifest = {
4
4
  "gpt-5.1": {
5
5
  aliases: ["azure-gpt-5.1", "gpt51-azure", "azure-flagship"],
6
6
  displayName: "GPT-5.1 (Azure)",
7
- contextWindow: 300000,
8
- maxOutputTokens: 64000,
7
+ contextWindow: 400000,
8
+ maxOutputTokens: 128000,
9
9
  pricingPerMTok: { input: 0.625, output: 5 },
10
10
  vision: true,
11
11
  functionCalling: true,
@@ -15,8 +15,8 @@ export const azureManifest = {
15
15
  "gpt-5.1-chat": {
16
16
  aliases: ["azure-gpt-5.1-chat", "gpt51-chat-azure"],
17
17
  displayName: "GPT-5.1 Chat (Azure)",
18
- contextWindow: 300000,
19
- maxOutputTokens: 32000,
18
+ contextWindow: 128000,
19
+ maxOutputTokens: 16384,
20
20
  pricingPerMTok: { input: 0.625, output: 5 },
21
21
  vision: true,
22
22
  functionCalling: true,
@@ -26,8 +26,8 @@ export const azureManifest = {
26
26
  "gpt-5.1-codex": {
27
27
  aliases: ["azure-gpt-5.1-codex", "gpt51-codex-azure", "azure-code"],
28
28
  displayName: "GPT-5.1 Codex (Azure)",
29
- contextWindow: 300000,
30
- maxOutputTokens: 64000,
29
+ contextWindow: 400000,
30
+ maxOutputTokens: 128000,
31
31
  pricingPerMTok: { input: 1.25, output: 10 },
32
32
  vision: true,
33
33
  functionCalling: true,
@@ -37,8 +37,8 @@ export const azureManifest = {
37
37
  "gpt-5.1-codex-mini": {
38
38
  aliases: ["azure-gpt-5.1-codex-mini", "gpt51-codex-mini-azure"],
39
39
  displayName: "GPT-5.1 Codex Mini (Azure)",
40
- contextWindow: 200000,
41
- maxOutputTokens: 32000,
40
+ contextWindow: 400000,
41
+ maxOutputTokens: 128000,
42
42
  pricingPerMTok: { input: 1.25, output: 10 },
43
43
  vision: true,
44
44
  functionCalling: true,
@@ -52,7 +52,7 @@ export const azureManifest = {
52
52
  "azure-enterprise",
53
53
  ],
54
54
  displayName: "GPT-5.1 Codex Max (Azure)",
55
- contextWindow: 500000,
55
+ contextWindow: 400000,
56
56
  maxOutputTokens: 128000,
57
57
  pricingPerMTok: { input: 1.25, output: 10 },
58
58
  vision: true,
@@ -1,6 +1,19 @@
1
1
  export const ollamaManifest = {
2
2
  defaultContextWindow: 128000,
3
3
  models: {
4
+ "gemma4:e2b": {
5
+ aliases: ["gemma4", "gemma4-local"],
6
+ displayName: "Gemma 4 E2B",
7
+ // ollama.com/library/gemma4: 128K context; tools, vision and thinking.
8
+ contextWindow: 131072,
9
+ // Ollama publishes no output cap; this matches its default in tokens.ts.
10
+ maxOutputTokens: 8192,
11
+ // pricingPerMTok omitted: hasPricing() reports no verified rate
12
+ vision: true,
13
+ functionCalling: true,
14
+ reasoning: true,
15
+ jsonMode: true,
16
+ },
4
17
  "llama4:latest": {
5
18
  aliases: ["llama4", "llama4-local"],
6
19
  displayName: "Llama 4",
@@ -1,7 +1,7 @@
1
1
  import type { ProviderModelManifest } from "../../types/index.js";
2
2
  /**
3
3
  * OpenAI model manifest. contextWindow values come from
4
- * MODEL_CONTEXT_WINDOWS.openai (src/lib/constants/contextWindows.ts), which
4
+ * MODEL_CONTEXT_WINDOWS.openai (src/lib/providers/rules/limits.json), which
5
5
  * disagrees with MODEL_REGISTRY.limits.maxContextTokens for several ids
6
6
  * (e.g. gpt-5: 400_000 here vs 256_000 there) — MODEL_CONTEXT_WINDOWS wins
7
7
  * as the more actively-maintained store. maxOutputTokens/aliases/capability
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * OpenAI model manifest. contextWindow values come from
3
- * MODEL_CONTEXT_WINDOWS.openai (src/lib/constants/contextWindows.ts), which
3
+ * MODEL_CONTEXT_WINDOWS.openai (src/lib/providers/rules/limits.json), which
4
4
  * disagrees with MODEL_REGISTRY.limits.maxContextTokens for several ids
5
5
  * (e.g. gpt-5: 400_000 here vs 256_000 there) — MODEL_CONTEXT_WINDOWS wins
6
6
  * as the more actively-maintained store. maxOutputTokens/aliases/capability
@@ -7,6 +7,7 @@ import { DEFAULT_MODEL_ALIASES } from "../types/index.js";
7
7
  import { logger } from "../utils/logger.js";
8
8
  import { AIProviderName, OpenAIModels, AzureOpenAIModels, GoogleAIModels, AnthropicModels, BedrockModels, MistralModels, OllamaModels, } from "../constants/enums.js";
9
9
  import { getAllManifestProviders, getManifestForProvider, } from "./manifestRegistry.js";
10
+ import { getModelFamilyPatterns } from "../providers/rules/modelFamilies.js";
10
11
  /**
11
12
  * Comprehensive model registry — hand-authored base. Every id defined here
12
13
  * that the manifest doesn't also carry a priced entry for stays exactly as
@@ -2205,8 +2206,8 @@ const LEGACY_MODEL_REGISTRY = {
2205
2206
  accuracy: "high",
2206
2207
  },
2207
2208
  limits: {
2208
- maxContextTokens: 300000,
2209
- maxOutputTokens: 64000,
2209
+ maxContextTokens: 400000,
2210
+ maxOutputTokens: 128000,
2210
2211
  maxRequestsPerMinute: 100,
2211
2212
  },
2212
2213
  useCases: {
@@ -2249,8 +2250,8 @@ const LEGACY_MODEL_REGISTRY = {
2249
2250
  accuracy: "high",
2250
2251
  },
2251
2252
  limits: {
2252
- maxContextTokens: 300000,
2253
- maxOutputTokens: 32000,
2253
+ maxContextTokens: 128000,
2254
+ maxOutputTokens: 16384,
2254
2255
  maxRequestsPerMinute: 150,
2255
2256
  },
2256
2257
  useCases: {
@@ -2293,8 +2294,8 @@ const LEGACY_MODEL_REGISTRY = {
2293
2294
  accuracy: "high",
2294
2295
  },
2295
2296
  limits: {
2296
- maxContextTokens: 300000,
2297
- maxOutputTokens: 64000,
2297
+ maxContextTokens: 400000,
2298
+ maxOutputTokens: 128000,
2298
2299
  maxRequestsPerMinute: 100,
2299
2300
  },
2300
2301
  useCases: {
@@ -2337,8 +2338,8 @@ const LEGACY_MODEL_REGISTRY = {
2337
2338
  accuracy: "high",
2338
2339
  },
2339
2340
  limits: {
2340
- maxContextTokens: 200000,
2341
- maxOutputTokens: 32000,
2341
+ maxContextTokens: 400000,
2342
+ maxOutputTokens: 128000,
2342
2343
  maxRequestsPerMinute: 300,
2343
2344
  },
2344
2345
  useCases: {
@@ -2381,7 +2382,7 @@ const LEGACY_MODEL_REGISTRY = {
2381
2382
  accuracy: "high",
2382
2383
  },
2383
2384
  limits: {
2384
- maxContextTokens: 500000,
2385
+ maxContextTokens: 400000,
2385
2386
  maxOutputTokens: 128000,
2386
2387
  maxRequestsPerMinute: 50,
2387
2388
  },
@@ -2788,20 +2789,10 @@ export function modelSupports(capability, provider, model) {
2788
2789
  return modelInfo.capabilities[capability] ?? true;
2789
2790
  }
2790
2791
  /**
2791
- * Model families known to reject classic sampling parameters
2792
- * (`temperature` / `topP`) in favour of reasoning-effort controls:
2793
- * Claude Sonnet 5, Opus 4.7+ (including Opus 5), and the Fable/Mythos 5
2794
- * tier — notably as served through Vertex. Kept as patterns because gateway
2795
- * model ids carry arbitrary prefixes/suffixes
2796
- * (`vertex_ai/claude-sonnet-5@20260203`) that exact registry ids can't cover.
2792
+ * Model families that reject classic sampling parameters (`temperature` /
2793
+ * `topP`) in favour of reasoning-effort controls (model-families.json).
2797
2794
  */
2798
- const SAMPLING_PARAM_REJECTING_FAMILIES = [
2799
- /sonnet[-_.]?5(?![0-9])/i,
2800
- /opus[-_.]?4[-_.]?(?:[7-9]|\d{2,})(?![0-9])/i,
2801
- /opus[-_.]?5(?![0-9])/i,
2802
- /fable/i,
2803
- /mythos/i,
2804
- ];
2795
+ const SAMPLING_PARAM_REJECTING_FAMILIES = getModelFamilyPatterns("samplingParamsRejected");
2805
2796
  /**
2806
2797
  * Whether a model accepts classic sampling parameters
2807
2798
  * (`temperature` / `topP`).
@@ -2846,26 +2837,10 @@ export function resolveSamplingParams(provider, model, params, site) {
2846
2837
  }
2847
2838
  return {};
2848
2839
  }
2849
- /**
2850
- * Claude models that answer a forced `tool_choice` (`any` or `tool`) with a
2851
- * 400: "tool_choice: type "tool" and "any" are not supported for this model."
2852
- * Sonnet 5.5 and Opus 5.5 were probed live on Vertex; the Fable 5.1 docs state
2853
- * the same, and Mythos 5.1 shares Fable 5.1's capabilities. The same families
2854
- * also refuse `thinking: {type: "disabled"}`.
2855
- */
2856
- const FORCED_TOOL_CHOICE_REJECTING_FAMILIES = [
2857
- /sonnet[-_.]?5[-_.]5(?![0-9])/i,
2858
- /opus[-_.]?5[-_.]5(?![0-9])/i,
2859
- /(?:fable|mythos)[-_.]?5[-_.]1(?![0-9])/i,
2860
- ];
2861
- /**
2862
- * Of those, the ones that accept `thinking: {type: "between_tools"}` as their
2863
- * lowest setting. The rest think adaptively, always on, and take no
2864
- * `thinking` field in its place.
2865
- */
2866
- const BETWEEN_TOOLS_THINKING_FAMILIES = [
2867
- /sonnet[-_.]?5[-_.]5(?![0-9])/i,
2868
- ];
2840
+ /** Claude models that answer a forced `tool_choice` with a 400 (model-families.json). */
2841
+ const FORCED_TOOL_CHOICE_REJECTING_FAMILIES = getModelFamilyPatterns("forcedToolChoiceRejected");
2842
+ /** Of those, the ones whose lowest thinking setting is `between_tools`. */
2843
+ const BETWEEN_TOOLS_THINKING_FAMILIES = getModelFamilyPatterns("betweenToolsThinking");
2869
2844
  function matchesClaudeFamily(families, model) {
2870
2845
  const normalizedModel = (model ?? "").toLowerCase();
2871
2846
  if (!normalizedModel) {
@@ -9,8 +9,7 @@ import { transformToolExecutions } from "../../utils/transformationUtils.js";
9
9
  import { composeAbortSignals } from "../../utils/timeout.js";
10
10
  import { createBedrockLoopAdapter } from "./loopAdapter.js";
11
11
  import { bedrockChunksToV3Stream, bedrockConversationFromV3Prompt, bedrockV3StreamToChunks, buildV3PromptFromBedrock, isTextOnlyBedrockConversation, unsentBedrockMiddlewareOptions, unwrapBedrockToolInputSchema, } from "./modelBridge.js";
12
- import { AuthenticationError, ProviderError, RateLimitError, } from "../../types/index.js";
13
- import { classifyProviderError } from "../../utils/errorClassifier.js";
12
+ import { ProviderError } from "../../types/index.js";
14
13
  import { isAbortError, withTimeout } from "../../utils/errorHandling.js";
15
14
  import { abortSignalOf, pauseDeadlineOf } from "../../utils/async/index.js";
16
15
  import { ImageProcessor } from "../../utils/imageProcessor.js";
@@ -22,6 +21,11 @@ import { convertZodToJsonSchema } from "../../utils/schemaConversion.js";
22
21
  import { SpanKind, SpanStatusCode } from "@opentelemetry/api";
23
22
  import { bedrockTracer } from "./constants.js";
24
23
  import { loadBedrockControl } from "./utils.js";
24
+ import { classifyWithProviderRules } from "../rules/errorRules.js";
25
+ import { getProviderErrorRules } from "../rules/registry.js";
26
+ import { getRequestDefault } from "../rules/requestDefaults.js";
27
+ const BEDROCK_ERROR_RULES = getProviderErrorRules("bedrock");
28
+ const DEFAULT_TEMPERATURE = getRequestDefault("bedrock", "temperature");
25
29
  /**
26
30
  * The only image formats Nova Multimodal Embeddings accepts.
27
31
  *
@@ -357,7 +361,7 @@ export class AmazonBedrockProvider extends BaseProvider {
357
361
  const maxSteps = options.maxSteps || DEFAULT_MAX_STEPS;
358
362
  const tools = await this.resolveTurnTools(options.tools, options.disableTools);
359
363
  const toolConfig = this.formatToolsForBedrock(tools);
360
- const sampling = resolveSamplingParams(this.providerName, this.modelName || this.getDefaultModel(), { temperature: options.temperature ?? 0.7 }, "bedrock.converse");
364
+ const sampling = resolveSamplingParams(this.providerName, this.modelName || this.getDefaultModel(), { temperature: options.temperature ?? DEFAULT_TEMPERATURE }, "bedrock.converse");
361
365
  const systemPromptText = options.systemPrompt ||
362
366
  "You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information.";
363
367
  // Builds a fresh adapter per turn — the generate model's `doGenerate` may
@@ -1211,7 +1215,7 @@ export class AmazonBedrockProvider extends BaseProvider {
1211
1215
  // discovery, so nothing here would need re-resolving per step.
1212
1216
  const tools = await this.resolveTurnTools(options.tools, options.disableTools);
1213
1217
  const toolConfig = this.formatToolsForBedrock(tools);
1214
- const sampling = resolveSamplingParams(this.providerName, this.modelName || this.getDefaultModel(), { temperature: options.temperature ?? 0.7 }, "bedrock.converseStream");
1218
+ const sampling = resolveSamplingParams(this.providerName, this.modelName || this.getDefaultModel(), { temperature: options.temperature ?? DEFAULT_TEMPERATURE }, "bedrock.converseStream");
1215
1219
  const systemPromptText = options.systemPrompt ||
1216
1220
  "You are a helpful assistant with access to external tools. Use tools when necessary to provide accurate information.";
1217
1221
  // executeStream() falls back to non-streaming generate() when the first
@@ -1488,39 +1492,7 @@ export class AmazonBedrockProvider extends BaseProvider {
1488
1492
  }
1489
1493
  }
1490
1494
  formatProviderError(error) {
1491
- const rules = [
1492
- {
1493
- match: (ctx) => /AccessDeniedException/i.test(ctx.message),
1494
- errorClass: AuthenticationError,
1495
- message: "AWS Bedrock access denied. Check your credentials and permissions.",
1496
- },
1497
- {
1498
- // Checked before the generic ValidationException fallback — a
1499
- // throttling error can be shaped like a validation error in some
1500
- // AWS SDK error message templates, but .name/.code are authoritative.
1501
- match: (ctx) => ctx.errorName === "ThrottlingException" ||
1502
- ctx.errorCode === "ThrottlingException",
1503
- errorClass: RateLimitError,
1504
- message: (ctx) => `Bedrock rate limit (throttled): ${ctx.message}`,
1505
- },
1506
- {
1507
- match: (ctx) => /ValidationException/i.test(ctx.message),
1508
- errorClass: ProviderError,
1509
- message: (ctx) => `Validation error: ${ctx.message}`,
1510
- },
1511
- {
1512
- match: () => true,
1513
- errorClass: ProviderError,
1514
- message: (ctx) => `AWS Bedrock error: ${ctx.message}`,
1515
- },
1516
- ];
1517
- // this.providerName resolves to the literal "bedrock" (getProviderName()
1518
- // returns it directly, and the constructor only overrides providerName
1519
- // when an explicit providerName is passed in) — verified matches the
1520
- // pre-migration hardcoded "bedrock" literal in the throttling branch, so
1521
- // a single classifyProviderError call using this.providerName for every
1522
- // rule (rather than a per-rule literal) is not a behavior change.
1523
- return classifyProviderError(error, rules, this.providerName, this.modelName);
1495
+ return classifyWithProviderRules(error, BEDROCK_ERROR_RULES, this.providerName, this.modelName);
1524
1496
  }
1525
1497
  /**
1526
1498
  * Generate embeddings for text or multi-modal input using Amazon Bedrock.
@@ -19,6 +19,8 @@
19
19
  import { ConverseCommand, ConverseStreamCommand, } from "@aws-sdk/client-bedrock-runtime";
20
20
  import { withTimeout } from "../../utils/errorHandling.js";
21
21
  import { withInferenceProfileFallback } from "./inferenceProfile.js";
22
+ import { getFinishReasonMap, translateFinishReason, } from "../rules/finishReasons.js";
23
+ const BEDROCK_FINISH_REASONS = getFinishReasonMap("bedrock", "converse");
22
24
  const STEP_TIMEOUT_MS = 120_000;
23
25
  function newToolUseId() {
24
26
  return `tool_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
@@ -286,17 +288,7 @@ export function createBedrockLoopAdapter(config) {
286
288
  return [...conversation, assistantMessage, toolResultMessage];
287
289
  },
288
290
  mapFinishReason(rawStopReason, hadToolCallsAtCap) {
289
- switch (rawStopReason) {
290
- case "end_turn":
291
- case "stop_sequence":
292
- return "stop";
293
- case "max_tokens":
294
- return "length";
295
- case "tool_use":
296
- return "tool-calls";
297
- default:
298
- return hadToolCallsAtCap ? "tool-calls" : "stop";
299
- }
291
+ return (translateFinishReason(BEDROCK_FINISH_REASONS, rawStopReason, hadToolCallsAtCap) ?? "stop");
300
292
  },
301
293
  };
302
294
  }
@@ -12,8 +12,7 @@ import { getModelCapabilities, getRecommendedModelForTier, isModelAvailableForTi
12
12
  import { createOAuthFetch } from "../../proxy/oauthFetch.js";
13
13
  import { createProxyFetch, fetchProxyAware } from "../../proxy/proxyFetch.js";
14
14
  import { getCapturedLimitSnapshot, getCapturedResponseHeaders, logClaudeLimitSnapshot, runInLimitCaptureScope, setLimitSpanAttributes, withLimitCapture, wrapFetchWithLimitCapture, } from "./rateLimitCapture.js";
15
- import { AuthenticationError, NetworkError, ProviderError, RateLimitError, } from "../../types/index.js";
16
- import { classifyProviderError, messageNamesStatus, } from "../../utils/errorClassifier.js";
15
+ import { AuthenticationError } from "../../types/index.js";
17
16
  import { logger } from "../../utils/logger.js";
18
17
  import { drainDetachedPump } from "../../utils/drainDetachedPump.js";
19
18
  import { ANTHROPIC_ELISION_NOTE, planAnthropicLoopReclaim, previewAnthropicToolResultText, } from "../../context/anthropicLoopGuard.js";
@@ -23,6 +22,7 @@ import { redactUrlCredentials } from "../../utils/logSanitize.js";
23
22
  import { ANTHROPIC_MAX_CACHE_BREAKPOINTS, applyAnthropicHistoryCacheBreakpoints, countAnthropicCacheMarkers, } from "../../utils/anthropicCacheBreakpoints.js";
24
23
  import { stringifyAnthropicToolOutput } from "./toolOutput.js";
25
24
  import { createAnthropicLoopAdapter } from "./loopAdapter.js";
25
+ import { getToolChoiceMap, translateToolChoice } from "../rules/toolRules.js";
26
26
  import { AsyncLocalStorage } from "node:async_hooks";
27
27
  import { AnthropicThreadStore, createAnthropicThreadSession, settleThread, threadRecovery, } from "./threads.js";
28
28
  import { DEFAULT_BEFORE_STEP_TIMEOUT_MS } from "../../utils/parameterValidation.js";
@@ -48,7 +48,16 @@ import { toNativeToolDeclarations } from "../../core/nativeToolFormat.js";
48
48
  import { ANTHROPIC_API_VERSION, ANTHROPIC_BETA_HEADERS } from "./constants.js";
49
49
  import { cacheControlOf, withLastToolCacheBreakpoint } from "./cacheControl.js";
50
50
  import { createNativeGenerateGuard } from "../../context/nativeGenerateGuard.js";
51
- import { appendFinalResultInstruction, appendFinalResultTool, appendToolAnswerInstruction, FINAL_RESULT_TOOL_NAME, } from "./structuredOutput.js";
51
+ import { appendFinalResultInstruction, appendFinalResultTool, appendToolAnswerInstruction, } from "./structuredOutput.js";
52
+ import { FINAL_RESULT_TOOL_NAME } from "../rules/finalResultTool.js";
53
+ import { classifyWithProviderRules } from "../rules/errorRules.js";
54
+ import { getProviderErrorRules } from "../rules/registry.js";
55
+ import { getRequestDefault } from "../rules/requestDefaults.js";
56
+ import { toWireParams } from "../rules/requestFields.js";
57
+ import { getThinkingLimits } from "../rules/thinkingLimits.js";
58
+ import { getFinishReasonMap, translateFinishReason, } from "../rules/finishReasons.js";
59
+ const ANTHROPIC_FINISH_REASONS = getFinishReasonMap("anthropic", "messages");
60
+ const ANTHROPIC_ERROR_RULES = getProviderErrorRules("anthropic");
52
61
  // AnthropicProviderConfig is imported from types/providers.ts
53
62
  // Re-export for backward compatibility
54
63
  // Configuration helpers - now using consolidated utility
@@ -429,25 +438,9 @@ const messagesToAnthropic = (msgs) => {
429
438
  messages,
430
439
  };
431
440
  };
432
- /** Map a NeuroLink tool choice onto Anthropic's tool_choice shape. */
433
- const toolChoiceToAnthropic = (choice) => {
434
- if (!choice || choice === "auto") {
435
- return undefined; // Anthropic defaults to auto when tools are present
436
- }
437
- if (choice === "none") {
438
- return { type: "none" };
439
- }
440
- if (choice === "required") {
441
- return { type: "any" };
442
- }
443
- if (typeof choice === "object") {
444
- const c = choice;
445
- if (c.type === "tool" && c.toolName) {
446
- return { type: "tool", name: c.toolName };
447
- }
448
- }
449
- return undefined;
450
- };
441
+ const ANTHROPIC_TOOL_CHOICE = getToolChoiceMap("anthropic", "messages");
442
+ /** Map a NeuroLink tool choice onto Anthropic's tool_choice shape (anthropic.json). */
443
+ const toolChoiceToAnthropic = (choice) => translateToolChoice(ANTHROPIC_TOOL_CHOICE, choice);
451
444
  /**
452
445
  * Claude 5.5 / 5.1 models answer a forced choice with a 400, so for them it
453
446
  * becomes `auto`: the tool stays declared and the model still picks it.
@@ -501,9 +494,10 @@ const continuesToolTurnWithoutThinking = (messages) => {
501
494
  * tool_choice forces tool use." with a 400. The forced choice wins and
502
495
  * thinking is omitted, as on the Vertex schema path and in oauthFetch.ts.
503
496
  * `none` and `auto` do not force tool use and leave thinking alone.
504
- * - `budget_tokens` must be at least 1024 and below `max_tokens`. As on the
505
- * Vertex path, it is clamped to leave 1024 tokens for the answer, and
506
- * thinking is omitted when no budget of at least 1024 fits.
497
+ * - `budget_tokens` must be at least `minBudgetTokens` and below
498
+ * `max_tokens` (anthropic.json `thinkingLimits`). As on the Vertex path, it
499
+ * is clamped to leave `answerReserveTokens` for the answer, and thinking is
500
+ * omitted when no budget of at least the minimum fits.
507
501
  *
508
502
  * - Thinking cannot be switched on partway through a tool-use turn: when the
509
503
  * final assistant message calls a tool and does not start with a thinking
@@ -516,6 +510,9 @@ const continuesToolTurnWithoutThinking = (messages) => {
516
510
  * `{ type: "disabled" }` and an absent block pass through unchanged. Every
517
511
  * omission is logged, since the caller asked for thinking.
518
512
  */
513
+ const THINKING_LIMITS = getThinkingLimits("anthropic");
514
+ const LARGE_OUTPUT_THRESHOLD_TOKENS = getRequestDefault("anthropic", "largeOutputThresholdTokens");
515
+ const LARGE_OUTPUT_TIMEOUT_FLOOR_MS = getRequestDefault("anthropic", "largeOutputTimeoutFloorMs");
519
516
  const fitThinkingToRequest = (thinking, toolChoice, maxTokens, messages) => {
520
517
  if (thinking?.type !== "enabled") {
521
518
  return thinking;
@@ -537,9 +534,9 @@ const fitThinkingToRequest = (thinking, toolChoice, maxTokens, messages) => {
537
534
  logger.warn(`[anthropic] Omitting extended thinking: budget_tokens ${String(thinking.budget_tokens)} (max_tokens ${String(maxTokens)}) is not a finite number`);
538
535
  return undefined;
539
536
  }
540
- const budget = Math.floor(Math.min(thinking.budget_tokens, maxTokens - 1024));
541
- if (budget < 1024) {
542
- logger.warn(`[anthropic] Omitting extended thinking: max_tokens ${maxTokens} leaves no room for a thinking budget of at least 1024 tokens plus an answer`);
537
+ const budget = Math.floor(Math.min(thinking.budget_tokens, maxTokens - THINKING_LIMITS.answerReserveTokens));
538
+ if (budget < THINKING_LIMITS.minBudgetTokens) {
539
+ logger.warn(`[anthropic] Omitting extended thinking: max_tokens ${maxTokens} leaves no room for a thinking budget of at least ${THINKING_LIMITS.minBudgetTokens} tokens plus an answer`);
543
540
  return undefined;
544
541
  }
545
542
  if (budget !== thinking.budget_tokens) {
@@ -549,18 +546,7 @@ const fitThinkingToRequest = (thinking, toolChoice, maxTokens, messages) => {
549
546
  return thinking;
550
547
  };
551
548
  /** Map Anthropic stop_reason onto the V3 unified finish reason. */
552
- const mapAnthropicStopReason = (raw) => {
553
- switch (raw) {
554
- case "max_tokens":
555
- return "length";
556
- case "tool_use":
557
- return "tool-calls";
558
- case "refusal":
559
- return "content-filter";
560
- default:
561
- return "stop";
562
- }
563
- };
549
+ const mapAnthropicStopReason = (raw) => translateFinishReason(ANTHROPIC_FINISH_REASONS, raw);
564
550
  // Anthropic's Messages API requires max_tokens on every request. When the
565
551
  // caller omits it, default to the model's real output ceiling via
566
552
  // resolveClaudeMaxTokens (e.g. 64K for Sonnet 4.x) instead of the legacy 4096,
@@ -573,7 +559,7 @@ const mapAnthropicStopReason = (raw) => {
573
559
  // for the non-throwing path — suppresses that pre-flight throw so large
574
560
  // max_tokens (our model-ceiling default) works. Per-request duration is still
575
561
  // bounded by the abort signal NeuroLink composes for each call.
576
- const ANTHROPIC_CLIENT_TIMEOUT_MS = 600_000;
562
+ const ANTHROPIC_CLIENT_TIMEOUT_MS = getRequestDefault("anthropic", "clientTimeoutMs");
577
563
  /**
578
564
  * Send one non-streaming step of a thread. The SDK's request type does not know
579
565
  * the beta `thread` field, so this is the one place it is added to the body,
@@ -1403,7 +1389,6 @@ export class AnthropicProvider extends BaseProvider {
1403
1389
  const params = {
1404
1390
  model: modelId,
1405
1391
  messages: cachedMessages,
1406
- max_tokens: maxTokens,
1407
1392
  ...(system ? { system } : {}),
1408
1393
  // Extended thinking fixes sampling: Anthropic rejects any
1409
1394
  // temperature but 1 while `thinking` is set, and does not honour
@@ -1411,15 +1396,12 @@ export class AnthropicProvider extends BaseProvider {
1411
1396
  // forwarding it alongside thinking turns a call that used to work
1412
1397
  // into a 400. Drop the sampling knobs for exactly those turns and
1413
1398
  // let Anthropic's thinking defaults stand.
1414
- ...(!thinkingOn && samplingParams.temperature !== undefined
1415
- ? { temperature: samplingParams.temperature }
1416
- : {}),
1417
- ...(!thinkingOn && samplingParams.topP !== undefined
1418
- ? { top_p: samplingParams.topP }
1419
- : {}),
1420
- ...(options.stopSequences && options.stopSequences.length > 0
1421
- ? { stop_sequences: options.stopSequences }
1422
- : {}),
1399
+ ...toWireParams("anthropic", {
1400
+ maxTokens,
1401
+ temperature: thinkingOn ? undefined : samplingParams.temperature,
1402
+ topP: thinkingOn ? undefined : samplingParams.topP,
1403
+ stopSequences: options.stopSequences,
1404
+ }),
1423
1405
  ...(tools ? { tools } : {}),
1424
1406
  ...(toolChoice ? { tool_choice: toolChoice } : {}),
1425
1407
  ...(thinking ? { thinking } : {}),
@@ -1440,8 +1422,8 @@ export class AnthropicProvider extends BaseProvider {
1440
1422
  : undefined;
1441
1423
  const generateTimeoutMs = forwardedTimeoutMs !== undefined
1442
1424
  ? forwardedTimeoutMs
1443
- : params.max_tokens > 8192
1444
- ? Math.max(getTimeoutForOptions(options), 300_000)
1425
+ : maxTokens > LARGE_OUTPUT_THRESHOLD_TOKENS
1426
+ ? Math.max(getTimeoutForOptions(options), LARGE_OUTPUT_TIMEOUT_FLOOR_MS)
1445
1427
  : getTimeoutForOptions(options);
1446
1428
  const timeoutController = createTimeoutController(generateTimeoutMs, providerName, "generate");
1447
1429
  const requestSignal = composeAbortSignals(options.abortSignal, timeoutController?.controller.signal);
@@ -1653,46 +1635,7 @@ export class AnthropicProvider extends BaseProvider {
1653
1635
  return delegatingModel;
1654
1636
  }
1655
1637
  formatProviderError(error) {
1656
- const rules = [
1657
- {
1658
- // Plan 02's mocked-contract work documented a pre-existing gap: the
1659
- // Anthropic SDK formats auth failures as a bare "401 <msg>" string,
1660
- // which the message-text regex alone does not catch — mirrors
1661
- // Vertex's statusCode === 401 fallback in this same task.
1662
- match: (ctx) => ctx.statusCode === 401 ||
1663
- /API_KEY_INVALID|Invalid API key/i.test(ctx.message),
1664
- errorClass: AuthenticationError,
1665
- message: "Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable.",
1666
- },
1667
- {
1668
- match: (ctx) => ctx.statusCode === 429 ||
1669
- /rate limit|too_many_requests/i.test(ctx.message) ||
1670
- messageNamesStatus(ctx.message, 429),
1671
- errorClass: RateLimitError,
1672
- message: "Anthropic rate limit exceeded. Please try again later.",
1673
- },
1674
- {
1675
- match: (ctx) => /ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection/i.test(ctx.message),
1676
- errorClass: NetworkError,
1677
- message: (ctx) => `Connection error: ${ctx.message}`,
1678
- },
1679
- {
1680
- // Match the shared 5xx predicate: HTTP status or a bounded phrase,
1681
- // rather than digits embedded in an unrelated value.
1682
- match: (ctx) => (ctx.statusCode !== undefined &&
1683
- ctx.statusCode >= 500 &&
1684
- ctx.statusCode <= 599) ||
1685
- /server error|bad gateway|service unavailable|gateway timeout|\berror\b\D{0,12}\b5\d\d\b|\b5\d\d\b\D{0,12}\berror\b|\bstatus(?:\s*code)?\b\D{0,12}\b5\d\d\b/i.test(ctx.message),
1686
- errorClass: ProviderError,
1687
- message: (ctx) => `Server error: ${ctx.message}`,
1688
- },
1689
- {
1690
- match: () => true,
1691
- errorClass: ProviderError,
1692
- message: (ctx) => `Anthropic error: ${ctx.message}`,
1693
- },
1694
- ];
1695
- return classifyProviderError(error, rules, this.providerName, this.modelName);
1638
+ return classifyWithProviderRules(error, ANTHROPIC_ERROR_RULES, this.providerName, this.modelName);
1696
1639
  }
1697
1640
  // executeGenerate removed - BaseProvider handles all generation with tools
1698
1641
  /**
@@ -2263,7 +2206,6 @@ export class AnthropicProvider extends BaseProvider {
2263
2206
  return {
2264
2207
  model: modelId,
2265
2208
  messages: cachedConversation,
2266
- max_tokens: maxTokens,
2267
2209
  // No `stream: true` here: executeStep sets it when it calls
2268
2210
  // messages.create, so declaring it made the caller assert a literal
2269
2211
  // the adapter immediately overwrites — and forced this whole params
@@ -2271,9 +2213,12 @@ export class AnthropicProvider extends BaseProvider {
2271
2213
  ...(payload.system ? { system: payload.system } : {}),
2272
2214
  // Same constraint on the streaming path: a temperature alongside
2273
2215
  // `thinking` is rejected outright.
2274
- ...(!thinkingOn && streamSamplingParams.temperature !== undefined
2275
- ? { temperature: streamSamplingParams.temperature }
2276
- : {}),
2216
+ ...toWireParams("anthropic", {
2217
+ maxTokens,
2218
+ temperature: thinkingOn
2219
+ ? undefined
2220
+ : streamSamplingParams.temperature,
2221
+ }),
2277
2222
  ...(cachedTools && cachedTools.length > 0
2278
2223
  ? { tools: cachedTools }
2279
2224
  : {}),