@juspay/neurolink 13.16.2 → 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
@@ -47,6 +47,8 @@ import { isResponseFormatUnsupportedError, isSchemaComplexityError, isToolsSchem
47
47
  import { resolveDeferredTool } from "../tools/toolDiscovery.js";
48
48
  import { buildAPIError, buildBody, buildToolsForOpenAI, buildWireToolNameMaps, createDeferredAnalytics, ensureJsonWordInBody, estimateWireTokens, mapNeuroLinkToolChoice, mergeUsage, messageBuilderToOpenAI, parseSSEStream, stringifyToolOutput, stripTrailingSlash, v3ResponseFormatToOpenAI, v3ToolChoiceToOpenAI, v3ToolsToOpenAI, } from "./openaiChatCompletionsClient.js";
49
49
  import { createStreamChannel } from "../core/streamChannel.js";
50
+ import { getFinishReasonMap, translateFinishReason, } from "./rules/finishReasons.js";
51
+ import { getWireUsage, readWireUsage, splitIncludedCount, splitIncludedPart, } from "./rules/wireUsage.js";
50
52
  /**
51
53
  * Safety margin (tokens) when fitting `max_tokens` to a runtime-discovered
52
54
  * context window: the char-based input estimate and the backend's own prompt
@@ -108,21 +110,9 @@ const resolveAgainstSchema = (text, schema) => {
108
110
  * absent value, reads as `stop`. A wire `error` finish never gets here: the SSE
109
111
  * parser throws on it, and on a stream that ended with no terminal marker.
110
112
  */
111
- const toUnifiedFinishReason = (reason) => {
112
- switch (reason) {
113
- case "length":
114
- return "length";
115
- case "tool_calls":
116
- case "function_call":
117
- case "tool-calls":
118
- return "tool-calls";
119
- case "content_filter":
120
- case "content-filter":
121
- return "content-filter";
122
- default:
123
- return "stop";
124
- }
125
- };
113
+ const CHAT_USAGE = getWireUsage("openai-chat");
114
+ const CHAT_FINISH_REASONS = getFinishReasonMap("openai-chat", "chatCompletions");
115
+ const toUnifiedFinishReason = (reason) => translateFinishReason(CHAT_FINISH_REASONS, reason);
126
116
  // Pull one native chunk at a time and forward cancellation to its iterator.
127
117
  const chunksToV3Stream = (source, completion, cancel) => {
128
118
  const iterator = source[Symbol.asyncIterator]();
@@ -816,40 +806,26 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
816
806
  }
817
807
  const rawFinish = choice?.finish_reason;
818
808
  const unified = toUnifiedFinishReason(rawFinish);
809
+ const counts = readWireUsage(CHAT_USAGE, json.usage);
810
+ const cachedSplit = splitIncludedPart(counts.input, counts.cacheRead);
811
+ const reasoningSplit = splitIncludedPart(counts.output, counts.reasoning);
819
812
  return {
820
813
  content,
821
814
  finishReason: { unified, raw: rawFinish ?? "stop" },
822
815
  usage: {
823
816
  inputTokens: {
824
- total: json.usage?.prompt_tokens,
825
- // cached_tokens is OVERLAPPING (a subset of prompt_tokens), so
826
- // noCache is the remainder and cacheRead is clamped to the
827
- // prompt total — some gateways report inconsistent usage where
828
- // cached_tokens exceeds prompt_tokens (mirrors the
829
- // reasoning_tokens clamp on the output side below).
830
- noCache: json.usage?.prompt_tokens !== undefined &&
831
- json.usage?.prompt_tokens_details?.cached_tokens !== undefined
832
- ? Math.max(0, json.usage.prompt_tokens -
833
- json.usage.prompt_tokens_details.cached_tokens)
834
- : json.usage?.prompt_tokens,
835
- cacheRead: json.usage?.prompt_tokens !== undefined &&
836
- json.usage?.prompt_tokens_details?.cached_tokens !== undefined
837
- ? Math.min(json.usage.prompt_tokens_details.cached_tokens, json.usage.prompt_tokens)
838
- : json.usage?.prompt_tokens_details?.cached_tokens,
817
+ total: counts.input,
818
+ // cached_tokens is a subset of prompt_tokens: noCache is the
819
+ // remainder, and cacheRead is clamped to the prompt total.
820
+ noCache: cachedSplit.rest,
821
+ cacheRead: cachedSplit.part,
839
822
  // OpenAI-style APIs do not report cache writes.
840
823
  cacheWrite: undefined,
841
824
  },
842
825
  outputTokens: {
843
- total: json.usage?.completion_tokens,
844
- // Clamped at 0 — some gateways report inconsistent usage where
845
- // reasoning_tokens exceeds completion_tokens.
846
- text: json.usage?.completion_tokens !== undefined &&
847
- json.usage?.completion_tokens_details?.reasoning_tokens !==
848
- undefined
849
- ? Math.max(0, json.usage.completion_tokens -
850
- json.usage.completion_tokens_details.reasoning_tokens)
851
- : json.usage?.completion_tokens,
852
- reasoning: json.usage?.completion_tokens_details?.reasoning_tokens,
826
+ total: counts.output,
827
+ text: reasoningSplit.rest,
828
+ reasoning: counts.reasoning,
853
829
  },
854
830
  },
855
831
  warnings: [],
@@ -1818,9 +1794,9 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
1818
1794
  // cached tokens at the full input rate instead of the cheaper
1819
1795
  // cacheRead rate. Clamped like the other call sites in this file
1820
1796
  // in case a gateway reports cacheRead > total.
1821
- const cacheRead = Math.min(part.usage.inputTokens.cacheRead ?? 0, input);
1797
+ const { rest: uncachedInput, part: cacheRead } = splitIncludedCount(input, part.usage.inputTokens.cacheRead ?? 0);
1822
1798
  resolveUsage({
1823
- promptTokens: input - cacheRead,
1799
+ promptTokens: uncachedInput,
1824
1800
  completionTokens: output,
1825
1801
  totalTokens: input + output,
1826
1802
  ...(cacheRead > 0 ? { cacheReadTokens: cacheRead } : {}),
@@ -2082,17 +2058,17 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2082
2058
  // and calculateCost expect. reasoning_tokens stays a subset of
2083
2059
  // completionTokens (informational).
2084
2060
  const toDeferredUsage = () => {
2085
- const promptTokens = stepUsage?.prompt_tokens ?? 0;
2086
- const completionTokens = stepUsage?.completion_tokens ?? 0;
2087
- const cachedTokens = Math.min(stepUsage?.prompt_tokens_details?.cached_tokens ?? 0, promptTokens);
2088
- // Clamped like cached_tokens above: reasoning is a SUBSET of
2089
- // completion_tokens, but some gateways report inconsistent values.
2090
- const reasoningTokens = Math.min(Math.max(0, stepUsage?.completion_tokens_details?.reasoning_tokens ?? 0), completionTokens);
2061
+ const counts = readWireUsage(CHAT_USAGE, stepUsage);
2062
+ const promptTokens = counts.input ?? 0;
2063
+ const completionTokens = counts.output ?? 0;
2064
+ const { rest: uncachedPromptTokens, part: cachedTokens } = splitIncludedCount(promptTokens, counts.cacheRead ?? 0);
2065
+ // Reasoning is a subset of completion_tokens; a negative count reads as 0.
2066
+ const reasoningTokens = splitIncludedCount(completionTokens, Math.max(0, counts.reasoning ?? 0)).part;
2091
2067
  return {
2092
- promptTokens: promptTokens - cachedTokens,
2068
+ promptTokens: uncachedPromptTokens,
2093
2069
  completionTokens,
2094
2070
  // Gateways that omit total_tokens must not collapse to 0.
2095
- totalTokens: stepUsage?.total_tokens || promptTokens + completionTokens,
2071
+ totalTokens: counts.total || promptTokens + completionTokens,
2096
2072
  ...(cachedTokens > 0 ? { cacheReadTokens: cachedTokens } : {}),
2097
2073
  ...(reasoningTokens > 0 ? { reasoningTokens } : {}),
2098
2074
  };
@@ -2208,6 +2184,10 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2208
2184
  abortSignal,
2209
2185
  }));
2210
2186
  const executed = toolExecutionSummaries.slice(-stepResult.toolCalls.size);
2187
+ // prompt_tokens includes cached_tokens; report the disjoint figures so
2188
+ // a prepareStep hook sees the same numbers from stream() and generate().
2189
+ const stepCounts = readWireUsage(CHAT_USAGE, stepResult.usage);
2190
+ const stepCachedSplit = splitIncludedCount(stepCounts.input ?? 0, stepCounts.cacheRead ?? 0);
2211
2191
  stepRecords.push(toPrepareStepRecord({
2212
2192
  stepNumber: step,
2213
2193
  content: [
@@ -2240,14 +2220,10 @@ export class OpenAIChatCompletionsProvider extends BaseProvider {
2240
2220
  // here, once in cacheReadTokens) and a prepareStep hook that
2241
2221
  // budgets on steps[].usage sees different numbers from
2242
2222
  // stream() and generate() for the same step.
2243
- inputTokens: Math.max(0, (stepResult.usage?.prompt_tokens ?? 0) -
2244
- (stepResult.usage?.prompt_tokens_details?.cached_tokens ?? 0)),
2245
- outputTokens: stepResult.usage?.completion_tokens ?? 0,
2246
- ...(stepResult.usage?.prompt_tokens_details?.cached_tokens !==
2247
- undefined
2248
- ? {
2249
- cacheReadTokens: Math.min(stepResult.usage.prompt_tokens_details.cached_tokens, stepResult.usage.prompt_tokens ?? 0),
2250
- }
2223
+ inputTokens: stepCachedSplit.rest,
2224
+ outputTokens: stepCounts.output ?? 0,
2225
+ ...(stepCounts.cacheRead !== undefined
2226
+ ? { cacheReadTokens: stepCachedSplit.part }
2251
2227
  : {}),
2252
2228
  }));
2253
2229
  }
@@ -16,19 +16,19 @@
16
16
  import { createParser } from "eventsource-parser";
17
17
  import { ErrorCategory, ErrorSeverity } from "../constants/enums.js";
18
18
  import { NeuroLinkError } from "../utils/errorHandling.js";
19
- import { sanitizeToolName } from "../mcp/toolConverter.js";
19
+ import { compileToolNameRules, getToolChoiceMap, getToolNameRules, translateToolChoice, } from "./rules/toolRules.js";
20
20
  import { resolveSamplingParams } from "../models/modelRegistry.js";
21
21
  import { convertZodToJsonSchema, normalizeWireToolSchema, } from "../utils/schemaConversion.js";
22
22
  import { estimateTokens, IMAGE_TOKEN_ESTIMATE, TOKENS_PER_MESSAGE, } from "../utils/tokenEstimation.js";
23
+ import { inModelFamily } from "./rules/modelFamilies.js";
23
24
  export const stripTrailingSlash = (s) => s.replace(/\/+$/, "");
24
- // OpenAI-compatible wire tool names: first char letter/underscore (some
25
- // chat templates treat a leading digit or hyphen as invalid identifiers),
26
- // then letters/digits/underscore/hyphen, 64 chars total — exactly the
27
- // pattern below, which mirrors sanitizeToolName's output alphabet. MCP
28
- // servers can register names outside it (dots, colons, spaces); sent
29
- // verbatim they make backends reject the tools block or emit tool_calls
25
+ // OpenAI-compatible wire tool names (openai-chat.json `toolNames`). MCP
26
+ // servers can register names outside that alphabet (dots, colons, spaces);
27
+ // sent verbatim they make backends reject the tools block or emit tool_calls
30
28
  // that no longer match the registry.
31
- const WIRE_TOOL_NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/;
29
+ const WIRE_TOOL_NAMES = compileToolNameRules(getToolNameRules("openai-chat"));
30
+ const CHAT_TOOL_CHOICE = getToolChoiceMap("openai-chat", "neurolink");
31
+ const V3_TOOL_CHOICE = getToolChoiceMap("openai-chat", "v3");
32
32
  /**
33
33
  * Build a bijective original ↔ wire tool-name map. Returns undefined when
34
34
  * every name is already wire-valid and unreserved (the common case — the
@@ -43,23 +43,13 @@ const WIRE_TOOL_NAME_RE = /^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/;
43
43
  * making the reverse mapping ambiguous.
44
44
  */
45
45
  export const buildWireToolNameMaps = (names, reservedWireNames) => {
46
- if (names.every((name) => WIRE_TOOL_NAME_RE.test(name) && !reservedWireNames?.has(name))) {
46
+ if (names.every((name) => WIRE_TOOL_NAMES.isValid(name) && !reservedWireNames?.has(name))) {
47
47
  return undefined;
48
48
  }
49
49
  const toWire = new Map();
50
50
  const fromWire = new Map();
51
51
  for (const name of names) {
52
- let wire = WIRE_TOOL_NAME_RE.test(name) ? name : sanitizeToolName(name);
53
- if (fromWire.has(wire) || reservedWireNames?.has(wire)) {
54
- let suffix = 2;
55
- let candidate;
56
- do {
57
- const tail = `_${suffix}`;
58
- candidate = `${wire.slice(0, 64 - tail.length)}${tail}`;
59
- suffix++;
60
- } while (fromWire.has(candidate) || reservedWireNames?.has(candidate));
61
- wire = candidate;
62
- }
52
+ const wire = WIRE_TOOL_NAMES.unique(WIRE_TOOL_NAMES.sanitize(name), (candidate) => fromWire.has(candidate) || !!reservedWireNames?.has(candidate));
63
53
  toWire.set(name, wire);
64
54
  fromWire.set(wire, name);
65
55
  }
@@ -407,21 +397,7 @@ export const v3ToolsToOpenAI = (tools, toolNameToWire) => {
407
397
  }
408
398
  return out.length > 0 ? out : undefined;
409
399
  };
410
- export const v3ToolChoiceToOpenAI = (choice, toolNameToWire) => {
411
- switch (choice.type) {
412
- case "auto":
413
- case "none":
414
- case "required":
415
- return choice.type;
416
- case "tool":
417
- return {
418
- type: "function",
419
- function: {
420
- name: toolNameToWire?.get(choice.toolName) ?? choice.toolName,
421
- },
422
- };
423
- }
424
- };
400
+ export const v3ToolChoiceToOpenAI = (choice, toolNameToWire) => translateToolChoice(V3_TOOL_CHOICE, choice, (name) => toolNameToWire?.get(name) ?? name);
425
401
  /**
426
402
  * OpenAI's strict structured-output mode rejects a schema unless every object
427
403
  * node carries `additionalProperties: false` AND lists every one of its
@@ -594,24 +570,7 @@ export const v3ResponseFormatToOpenAI = (rf) => {
594
570
  },
595
571
  };
596
572
  };
597
- export const mapNeuroLinkToolChoice = (choice, toolNameToWire) => {
598
- if (!choice) {
599
- return undefined;
600
- }
601
- if (choice === "auto" || choice === "none" || choice === "required") {
602
- return choice;
603
- }
604
- if (typeof choice === "object" && choice !== null) {
605
- const c = choice;
606
- if (c.type === "tool" && c.toolName) {
607
- return {
608
- type: "function",
609
- function: { name: toolNameToWire?.get(c.toolName) ?? c.toolName },
610
- };
611
- }
612
- }
613
- return undefined;
614
- };
573
+ export const mapNeuroLinkToolChoice = (choice, toolNameToWire) => translateToolChoice(CHAT_TOOL_CHOICE, choice, (name) => toolNameToWire?.get(name) ?? name);
615
574
  // OpenAI-compatible endpoints (OpenAI, DeepSeek, …) reject
616
575
  // `response_format: { type: "json_object" }` unless the literal word "json"
617
576
  // appears somewhere in the messages. The `@ai-sdk/openai-compatible` wrapper
@@ -647,10 +606,11 @@ export const ensureJsonWordInBody = (body) => body.response_format?.type === "js
647
606
  }
648
607
  : body;
649
608
  // Reasoning-class OpenAI models (o-series, gpt-5+) reject `max_tokens` and
650
- // require `max_completion_tokens`. The OpenAI + Azure providers use this to
651
- // rename the field on the wire body; third-party OpenAI-compatible endpoints
652
- // keep `max_tokens`, so it is opt-in per provider, never applied by default.
653
- export const requiresMaxCompletionTokens = (modelId) => /^(o\d|gpt-5)/i.test(modelId.replace(/^.*\//, ""));
609
+ // require `max_completion_tokens` (model-families.json maxCompletionTokens).
610
+ // Only the Azure provider uses this to rename the field on the wire body;
611
+ // third-party OpenAI-compatible endpoints keep `max_tokens`, so it is opt-in
612
+ // per provider, never applied by default.
613
+ export const requiresMaxCompletionTokens = (modelId) => inModelFamily("maxCompletionTokens", modelId.replace(/^.*\//, ""));
654
614
  export const buildBody = (args) => {
655
615
  const { modelId, messages, options, tools, toolChoice, streaming, responseFormat, } = args;
656
616
  const body = {
@@ -1,10 +1,11 @@
1
- import { AuthenticationError, InvalidModelError, NetworkError, } from "../../types/index.js";
2
1
  import { logger } from "../../utils/logger.js";
3
2
  import { redactUrlCredentials } from "../../utils/logSanitize.js";
4
- import { classifyProviderError, DEFAULT_ERROR_RULES, } from "../../utils/errorClassifier.js";
5
3
  import { OpenAIChatCompletionsProvider } from "../openaiChatCompletionsBase.js";
6
4
  import { FALLBACK_OPENAI_COMPATIBLE_MODEL } from "./constants.js";
7
5
  import { getDefaultOpenAICompatibleModel, getOpenAICompatibleConfig, } from "./utils.js";
6
+ import { classifyWithProviderRules } from "../rules/errorRules.js";
7
+ import { getProviderErrorRules } from "../rules/registry.js";
8
+ const OPENAI_COMPATIBLE_ERROR_RULES = getProviderErrorRules("openai-compatible");
8
9
  /**
9
10
  * OpenAI Compatible Provider — direct HTTP, no AI SDK.
10
11
  *
@@ -52,39 +53,11 @@ export class OpenAICompatibleProvider extends OpenAIChatCompletionsProvider {
52
53
  ];
53
54
  }
54
55
  formatProviderError(error) {
55
- const rules = [
56
- // Duck-typed timeout check (name === "TimeoutError" or a "Timeout"
57
- // substring) — broader than classifyProviderError's built-in
58
- // `instanceof TimeoutError` handling, so it's preserved as an
59
- // explicit rule rather than relying on the default.
60
- {
61
- match: (ctx) => ctx.errorName === "TimeoutError" || /Timeout/.test(ctx.message),
62
- errorClass: NetworkError,
63
- message: (ctx) => `Request timed out: ${ctx.message}`,
64
- },
65
- {
66
- match: (ctx) => /ECONNREFUSED|Failed to fetch/i.test(ctx.message),
67
- errorClass: NetworkError,
68
- message: () => `OpenAI Compatible endpoint not available. Please check your OPENAI_COMPATIBLE_BASE_URL: ${redactUrlCredentials(this.config.baseURL)}`,
69
- },
70
- {
71
- match: (ctx) => ctx.statusCode === 401 ||
72
- /API_KEY_INVALID|Invalid API key|Unauthorized/i.test(ctx.message),
73
- errorClass: AuthenticationError,
74
- message: "Invalid OpenAI Compatible API key. Please check your OPENAI_COMPATIBLE_API_KEY environment variable.",
75
- },
76
- // "does not exist" isn't covered by DEFAULT_ERROR_RULES's
77
- // model_not_found/"model not found" pattern — preserved verbatim.
78
- {
79
- match: (ctx) => /model/i.test(ctx.message) &&
80
- (/not found/i.test(ctx.message) ||
81
- /does not exist/i.test(ctx.message)),
82
- errorClass: InvalidModelError,
83
- message: (ctx) => `Model '${ctx.modelName}' not available on OpenAI Compatible endpoint. ` +
84
- "Please check available models or use getAvailableModels() to see supported models.",
85
- },
86
- ...DEFAULT_ERROR_RULES,
87
- ];
88
- return classifyProviderError(error, rules, this.providerName, this.modelName);
56
+ return classifyWithProviderRules(error, OPENAI_COMPATIBLE_ERROR_RULES, this.providerName, this.modelName, {
57
+ vars: () => ({
58
+ model: `${this.modelName}`,
59
+ baseURL: redactUrlCredentials(this.config.baseURL),
60
+ }),
61
+ });
89
62
  }
90
63
  }
@@ -0,0 +1,100 @@
1
+ # Provider rules
2
+
3
+ Provider-specific behaviour, written as data. Each `<provider-id>.json` file is
4
+ read by the shared rule engines in this folder instead of being hard-coded in
5
+ the provider class.
6
+
7
+ A file can hold these blocks today. `schema.ts` defines each one; the
8
+ types are in `src/lib/types/providerRules.ts`.
9
+
10
+ - `errors`: error classification, which `errorRules.ts` compiles into the
11
+ matchers `classifyProviderError` runs. The catalog providers in
12
+ `../catalog/` use the same engine.
13
+ - `finishReasons`: named tables that translate a wire's finish (stop) reason,
14
+ read through `finishReasons.ts`. A wire shared by several providers has its
15
+ own file: `openai-chat.json` (every OpenAI Chat Completions provider),
16
+ `gemini.json` (Vertex and AI Studio), `sagemaker.json`, and `proxy.json`
17
+ (the proxy's translations into the OpenAI, Claude and Gemini vocabularies).
18
+ - `usage`: where a wire reports each token count (dotted paths), read through
19
+ `wireUsage.ts`. `splitIncludedPart` is the one formula wires share: a count
20
+ reported inside another (cache reads inside `prompt_tokens`, reasoning
21
+ inside `completion_tokens`) is split out and clamped to its total.
22
+ `openai-chat.json` carries the OpenAI Chat Completions field names and
23
+ `gemini.json` the Gemini ones; `reasoningInOutput` says whether a wire's
24
+ output count already includes its reasoning tokens (OpenAI) or not (Gemini).
25
+ - `usageDialects` (in `sagemaker.json`): named prompt/completion/total
26
+ layouts for wires that have several, read through `readUsageCounts`.
27
+ - `contextWindows`, `contextWindowNotes` and `providerAliases` (only in
28
+ `limits.json`): each provider's context window per model, the reasons
29
+ behind specific values, and the provider spellings that map onto a table
30
+ key. `src/lib/constants/contextWindows.ts` reads them and adds the catalog
31
+ providers' windows after them. Key order matters: the lookup takes the
32
+ first matching prefix. A model manifest, when one exists, wins over this
33
+ table; `test:provider-rules` names the entries where that happens.
34
+ - `usageFields` and `usageRebase` (only in `usage.json`): the field names the
35
+ shared normalizer `extractTokenUsage` (src/lib/utils/tokenUtils.ts) tries,
36
+ in priority order, and when a cache-inclusive input count is rebased.
37
+ - `toolChoices`: named tables that spell a NeuroLink tool choice for one wire
38
+ (`"auto"` / `"none"` / `"required"` or `{ type: "tool", toolName }`), read
39
+ through `translateToolChoice` in `toolRules.ts`. `null` sends nothing, and
40
+ `"{toolName}"` in the `tool` template becomes the wire's tool name. Tables
41
+ live in `openai-chat.json`, `anthropic.json` and `sagemaker.json`.
42
+ - `toolNames`: the tool names a wire accepts (first characters, allowed
43
+ characters, maximum length), compiled by `compileToolNameRules` into a
44
+ check, a sanitizer and a `_2`, `_3`, … de-duplicator. In
45
+ `openai-chat.json` (64 characters) and `gemini.json` (128).
46
+ - `modelFamilies` and `modelFamilyNotes` (only in `model-families.json`):
47
+ named lists of case-insensitive model-id patterns, read through
48
+ `getModelFamilyPatterns` and `inModelFamily`: models that reject sampling
49
+ parameters or a forced tool choice, Claude models with vision, Gemini 3 and
50
+ 2.5, and the models that take a thinking config, prompt caching or a capped
51
+ output.
52
+ - `modelFamilyLabels`, `modelLists` and `modelListNotes` (only in
53
+ `model-families.json`): the family label per model (first match wins), and
54
+ exact model-id lists read through `getModelList`: image-generation models,
55
+ PDF image-generation models, and the Gemini text models Vertex serves only
56
+ on the global endpoint.
57
+ - `reasoning` and `reasoningNotes` (in `gemini.json`): the default thinking
58
+ level and budget, the budget fraction per level, each model's maximum
59
+ budget and accepted `thinkingBudget` range (first match wins), and the
60
+ restricted output-token cap.
61
+ - `apiKeyFormats`, `apiKeyLengths`, `oauthTokenFormats` and `credentialFormatNotes` (only in
62
+ `credentials.json`): the regex each provider's API key or OAuth token must
63
+ match, and the key lengths quoted in configuration hints (`apiKeyLengths`),
64
+ read by `src/lib/utils/providerConfig.ts`.
65
+ - `thinkingLimits` and `thinkingLimitNotes` (in `anthropic.json`): the
66
+ smallest extended-thinking `budget_tokens` Anthropic accepts and the tokens
67
+ kept free for the answer. The direct Anthropic and Vertex Claude paths clamp
68
+ the budget with them, read through `getThinkingLimits` in
69
+ `thinkingLimits.ts`.
70
+ - `defaultModel` and `defaultModelNote` (in `ollama.json`): the model a
71
+ provider uses when neither the call nor the environment names one, read
72
+ through `getDefaultModel` in `fallbackModel.ts`.
73
+ - `fallbackModel` and `fallbackModelNote` (in `ollama.json`): the model a
74
+ provider suggests when the requested one is not installed, read through
75
+ `getFallbackModel` in `fallbackModel.ts`.
76
+ - `errorSignals` and `errorSignalNotes` (only in `structured-output.json`):
77
+ case-insensitive patterns that recognise a structured-output rejection from
78
+ its message, whichever vendor sent it (tools and JSON schema cannot be
79
+ combined, a schema too complex to enforce, `response_format` unsupported by
80
+ the model). `src/lib/core/modules/structuredOutputPolicy.ts` reads them
81
+ through `matchesErrorSignal` in `errorSignals.ts`.
82
+ - `requestDefaults` and `requestDefaultNotes` (in `anthropic.json` and
83
+ `bedrock.json`): values a provider fills in when the caller leaves them
84
+ out, such as Bedrock's default temperature and the longer generate timeout
85
+ Anthropic uses above a large `max_tokens`. Read through `getRequestDefault`
86
+ in `requestDefaults.ts`.
87
+ - `imageLimits`, `imageLimitDefault`, `proxyProviders`, `providerAliases`,
88
+ `visionModels` and `visionFamilies` (only in `vision.json`): images per
89
+ request, the providers that route to arbitrary models, provider spellings,
90
+ vision-capable model ids (substring match) and which model family counts
91
+ as vision-capable. `src/lib/adapters/providerImageAdapter.ts` reads them
92
+ and puts the catalog's vision models first.
93
+
94
+ To change how a provider classifies an error, edit its JSON file. Then run
95
+ `pnpm run test:provider-rules`: it validates every file against `schema.ts`
96
+ and checks, against the built package, that each rule a real HTTP response can
97
+ reach produces the class and message its file states.
98
+
99
+ A rule whose message needs logic names a `messageHook`; the provider passes
100
+ that function when it calls `classifyWithProviderRules`.
@@ -0,0 +1,104 @@
1
+ {
2
+ "$schema": "./provider-rules.schema.json",
3
+ "id": "anthropic",
4
+ "errors": {
5
+ "useDefaults": false,
6
+ "rules": [
7
+ {
8
+ "status": 401,
9
+ "pattern": "API_KEY_INVALID|Invalid API key",
10
+ "class": "authentication",
11
+ "message": "Invalid Anthropic API key. Please check your ANTHROPIC_API_KEY environment variable."
12
+ },
13
+ {
14
+ "status": 429,
15
+ "messageStatus": 429,
16
+ "pattern": "rate limit|too_many_requests",
17
+ "class": "rate-limit",
18
+ "message": "Anthropic rate limit exceeded. Please try again later."
19
+ },
20
+ {
21
+ "pattern": "ECONNRESET|ENOTFOUND|ECONNREFUSED|network|connection",
22
+ "class": "network",
23
+ "message": "Connection error: {message}"
24
+ },
25
+ {
26
+ "statusRange": [500, 599],
27
+ "pattern": "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",
28
+ "class": "provider",
29
+ "message": "Server error: {message}"
30
+ },
31
+ {
32
+ "always": true,
33
+ "class": "provider",
34
+ "message": "Anthropic error: {message}"
35
+ }
36
+ ]
37
+ },
38
+ "finishReasons": {
39
+ "messages": {
40
+ "map": {
41
+ "max_tokens": "length",
42
+ "tool_use": "tool-calls",
43
+ "refusal": "content-filter"
44
+ },
45
+ "default": "stop",
46
+ "defaultAtToolCap": "tool-calls"
47
+ }
48
+ },
49
+ "toolChoices": {
50
+ "messages": {
51
+ "modes": {
52
+ "auto": null,
53
+ "none": {
54
+ "type": "none"
55
+ },
56
+ "required": {
57
+ "type": "any"
58
+ }
59
+ },
60
+ "acceptStrings": true,
61
+ "acceptModeObjects": false,
62
+ "tool": {
63
+ "type": "tool",
64
+ "name": "{toolName}"
65
+ },
66
+ "toolRequiresName": true,
67
+ "fallback": null
68
+ }
69
+ },
70
+ "thinkingLimits": {
71
+ "minBudgetTokens": 1024,
72
+ "answerReserveTokens": 1024
73
+ },
74
+ "thinkingLimitNotes": {
75
+ "minBudgetTokens": "Anthropic rejects a budget_tokens below 1024 with a 400. When no budget of at least this size fits, thinking is omitted rather than coerced.",
76
+ "answerReserveTokens": "budget_tokens must stay below max_tokens (a 400 otherwise), so the budget is clamped to max_tokens minus this reserve, leaving room for the answer. Used by the direct Anthropic and Vertex Claude paths."
77
+ },
78
+ "requestDefaults": {
79
+ "largeOutputThresholdTokens": 8192,
80
+ "largeOutputTimeoutFloorMs": 300000,
81
+ "clientTimeoutMs": 600000
82
+ },
83
+ "requestDefaultNotes": {
84
+ "largeOutputThresholdTokens": "Above 8192 max_tokens a non-streaming call can run for minutes, so the generate timeout is raised (unless the caller forwarded one).",
85
+ "largeOutputTimeoutFloorMs": "Five minutes: the floor the raised timeout never goes below.",
86
+ "clientTimeoutMs": "An explicit SDK client timeout. With one set, the SDK skips its 'streaming is required for long requests' pre-flight, which would otherwise reject a large max_tokens on a non-streaming call."
87
+ },
88
+ "requestFields": {
89
+ "maxTokens": "max_tokens",
90
+ "temperature": "temperature",
91
+ "topP": "top_p",
92
+ "stopSequences": "stop_sequences"
93
+ },
94
+ "requestFieldNotes": {
95
+ "scope": "The Anthropic Messages wire, used by direct Anthropic and by Claude on Vertex. toWireParams() writes a request from neutral names; unset values and empty lists are left out."
96
+ },
97
+ "toolResults": {
98
+ "errorTemplate": "Error executing tool {name}: {error}",
99
+ "errorFlag": "is_error"
100
+ },
101
+ "contextTexts": {
102
+ "elisionNote": "[Earlier tool exchanges were removed to fit the context window.]"
103
+ }
104
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "$schema": "./provider-rules.schema.json",
3
+ "id": "azure",
4
+ "errors": {
5
+ "rules": [
6
+ {
7
+ "messageStatus": 401,
8
+ "class": "authentication",
9
+ "message": "Invalid Azure OpenAI API key or endpoint."
10
+ }
11
+ ]
12
+ }
13
+ }
@@ -0,0 +1,48 @@
1
+ {
2
+ "$schema": "./provider-rules.schema.json",
3
+ "id": "bedrock",
4
+ "errors": {
5
+ "useDefaults": false,
6
+ "rules": [
7
+ {
8
+ "pattern": "AccessDeniedException",
9
+ "class": "authentication",
10
+ "message": "AWS Bedrock access denied. Check your credentials and permissions."
11
+ },
12
+ {
13
+ "errorName": "ThrottlingException",
14
+ "errorCode": "ThrottlingException",
15
+ "class": "rate-limit",
16
+ "message": "Bedrock rate limit (throttled): {message}"
17
+ },
18
+ {
19
+ "pattern": "ValidationException",
20
+ "class": "provider",
21
+ "message": "Validation error: {message}"
22
+ },
23
+ {
24
+ "always": true,
25
+ "class": "provider",
26
+ "message": "AWS Bedrock error: {message}"
27
+ }
28
+ ]
29
+ },
30
+ "finishReasons": {
31
+ "converse": {
32
+ "map": {
33
+ "end_turn": "stop",
34
+ "stop_sequence": "stop",
35
+ "max_tokens": "length",
36
+ "tool_use": "tool-calls"
37
+ },
38
+ "default": "stop",
39
+ "defaultAtToolCap": "tool-calls"
40
+ }
41
+ },
42
+ "requestDefaults": {
43
+ "temperature": 0.7
44
+ },
45
+ "requestDefaultNotes": {
46
+ "temperature": "Sent on Converse and ConverseStream when the caller gives no temperature."
47
+ }
48
+ }
@@ -0,0 +1,32 @@
1
+ {
2
+ "$schema": "./provider-rules.schema.json",
3
+ "id": "cohere",
4
+ "errors": {
5
+ "rules": [
6
+ {
7
+ "pattern": "invalid api token|Authentication|401|invalid_api_token",
8
+ "caseSensitive": true,
9
+ "class": "authentication",
10
+ "message": "Invalid Cohere API key. Check COHERE_API_KEY. Get one at https://dashboard.cohere.com/api-keys"
11
+ },
12
+ {
13
+ "pattern": "rate limit|429",
14
+ "caseSensitive": true,
15
+ "class": "rate-limit",
16
+ "message": "Cohere rate limit exceeded. Back off and retry."
17
+ },
18
+ {
19
+ "pattern": "model_not_found|404",
20
+ "caseSensitive": true,
21
+ "class": "invalid-model",
22
+ "message": "Cohere model '{model}' not found. Use command-r, command-r-plus, or command-r7b-12-2024."
23
+ },
24
+ {
25
+ "pattern": "trial limit|trial_limit",
26
+ "caseSensitive": true,
27
+ "class": "provider",
28
+ "message": "Cohere trial usage limit exceeded. Upgrade at https://dashboard.cohere.com/billing."
29
+ }
30
+ ]
31
+ }
32
+ }