@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
@@ -28,19 +28,22 @@ import { settleThread, threadRecovery } from "./threads.js";
28
28
  import { composeAbortSignalsScoped, createTimeoutController, } from "../../utils/timeout.js";
29
29
  import { sanitizeAnthropicMessagesForTrace } from "../../utils/anthropicTraceSanitizer.js";
30
30
  import { NeuroLinkError } from "../../utils/errorHandling.js";
31
+ import { getRequestFields, getToolResultRules, } from "../rules/requestFields.js";
31
32
  import { ErrorCategory, ErrorSeverity } from "../../constants/enums.js";
33
+ import { getFinishReasonMap, translateFinishReason, } from "../rules/finishReasons.js";
34
+ // The Anthropic Messages wire rules, from anthropic.json (shared by direct
35
+ // Anthropic and Claude on Vertex).
36
+ const REQUEST_FIELDS = getRequestFields("anthropic");
37
+ const TOOL_RESULTS = getToolResultRules("anthropic");
38
+ /** A request parameter read back by its neutral name. */
39
+ function readWireParam(params, key) {
40
+ const value = params[REQUEST_FIELDS[key]];
41
+ return typeof value === "number" ? value : undefined;
42
+ }
43
+ const ANTHROPIC_FINISH_REASONS = getFinishReasonMap("anthropic", "messages");
32
44
  /** Map Anthropic's stop_reason onto the unified finish reason. */
33
45
  function mapAnthropicFinishReason(rawStopReason, hadToolCallsAtCap) {
34
- switch (rawStopReason) {
35
- case "max_tokens":
36
- return "length";
37
- case "tool_use":
38
- return "tool-calls";
39
- case "refusal":
40
- return "content-filter";
41
- default:
42
- return hadToolCallsAtCap ? "tool-calls" : "stop";
43
- }
46
+ return (translateFinishReason(ANTHROPIC_FINISH_REASONS, rawStopReason, hadToolCallsAtCap) ?? "stop");
44
47
  }
45
48
  /**
46
49
  * Read one streamed Anthropic step off the wire.
@@ -407,9 +410,9 @@ export function createAnthropicLoopAdapter(config) {
407
410
  provider: config.provider,
408
411
  model: params.model,
409
412
  modelParameters: {
410
- temperature: params.temperature,
411
- maxTokens: params.max_tokens,
412
- topP: params.top_p,
413
+ temperature: readWireParam(params, "temperature"),
414
+ maxTokens: readWireParam(params, "maxTokens"),
415
+ topP: readWireParam(params, "topP"),
413
416
  thinkingBudget: params.thinking?.type === "enabled"
414
417
  ? params.thinking.budget_tokens
415
418
  : undefined,
@@ -524,13 +527,10 @@ export function createAnthropicLoopAdapter(config) {
524
527
  buildToolResultMessages(conversation, stepResult, toolResults) {
525
528
  const assistantMessage = {
526
529
  role: "assistant",
527
- // server_tool_use blocks are stripped before the turn is replayed:
528
- // the API emits them on the way out but REJECTS them on the way back
529
- // in, so echoing one fails the next request outright rather than
530
- // degrading. Both Claude-on-Vertex loops filtered these by hand; doing
531
- // it here means a caller cannot forget to. A provider that never emits
532
- // them sees no change.
533
- content: stepResult.raw.filter((block) => block.type !== "server_tool_use"),
530
+ // The turn is replayed as rebuilt from the stream: only thinking,
531
+ // redacted_thinking, text and tool_use blocks are collected, so a block
532
+ // the API emits but rejects on input (server_tool_use) never reaches here.
533
+ content: stepResult.raw,
534
534
  };
535
535
  const resultMessage = {
536
536
  role: "user",
@@ -538,9 +538,11 @@ export function createAnthropicLoopAdapter(config) {
538
538
  type: "tool_result",
539
539
  tool_use_id: result.id,
540
540
  content: result.error
541
- ? `Error executing tool ${result.name}: ${result.error}`
541
+ ? TOOL_RESULTS.errorTemplate
542
+ .replaceAll("{name}", result.name)
543
+ .replaceAll("{error}", String(result.error))
542
544
  : stringifyAnthropicToolOutput(result.output),
543
- ...(result.error ? { is_error: true } : {}),
545
+ ...(result.error ? { [TOOL_RESULTS.errorFlag]: true } : {}),
544
546
  })),
545
547
  };
546
548
  // The two messages are built in the SDK's own shape and handed back as
@@ -15,8 +15,6 @@ import type Anthropic from "@anthropic-ai/sdk";
15
15
  * Claude-on-Vertex loop in `googleVertex/client.ts`, which has used the same
16
16
  * tool name, description, and instruction wording since it shipped.
17
17
  */
18
- /** Internal tool name — filtered out of every returned tool call / execution. */
19
- export declare const FINAL_RESULT_TOOL_NAME = "final_result";
20
18
  /** The system-prompt instruction to answer through the named tool. */
21
19
  export declare function toolAnswerInstruction(toolName: string): string;
22
20
  /** Appended to the system prompt whenever the final_result tool is in play. */
@@ -1,5 +1,6 @@
1
1
  import { logger } from "../../utils/logger.js";
2
2
  import { inlineJsonSchema } from "../../utils/schemaConversion.js";
3
+ import { FINAL_RESULT_TOOL_DESCRIPTION, FINAL_RESULT_TOOL_NAME, finalResultToolInstruction, } from "../rules/finalResultTool.js";
3
4
  /**
4
5
  * Additive structured output for the native Anthropic Messages API.
5
6
  *
@@ -16,12 +17,9 @@ import { inlineJsonSchema } from "../../utils/schemaConversion.js";
16
17
  * Claude-on-Vertex loop in `googleVertex/client.ts`, which has used the same
17
18
  * tool name, description, and instruction wording since it shipped.
18
19
  */
19
- /** Internal tool name — filtered out of every returned tool call / execution. */
20
- export const FINAL_RESULT_TOOL_NAME = "final_result";
21
- const FINAL_RESULT_TOOL_DESCRIPTION = "Return the final structured result. You MUST call this tool when you have gathered all information and are ready to provide the final answer. The arguments should contain the structured data matching the expected schema.";
22
20
  /** The system-prompt instruction to answer through the named tool. */
23
21
  export function toolAnswerInstruction(toolName) {
24
- return `\n\nIMPORTANT: You MUST call the '${toolName}' tool to return your response in the required structured format. Do not respond with plain text - always use the ${toolName} tool.`;
22
+ return finalResultToolInstruction("mustCall", toolName);
25
23
  }
26
24
  /** Appended to the system prompt whenever the final_result tool is in play. */
27
25
  export const FINAL_RESULT_INSTRUCTION = toolAnswerInstruction(FINAL_RESULT_TOOL_NAME);
@@ -61,7 +59,7 @@ export function appendFinalResultTool(tools, jsonSchema) {
61
59
  return { tools, applied: false };
62
60
  }
63
61
  if (tools.some((tool) => tool.name === FINAL_RESULT_TOOL_NAME)) {
64
- logger.warn("[Anthropic] A caller tool is already named 'final_result'; skipping the additive structured-output tool");
62
+ logger.warn(`[Anthropic] A caller tool is already named '${FINAL_RESULT_TOOL_NAME}'; skipping the additive structured-output tool`);
65
63
  return { tools, applied: false };
66
64
  }
67
65
  // Appended LAST so any cache_control breakpoint an upstream layer placed on
@@ -1,11 +1,12 @@
1
1
  import { APIVersions } from "../constants/enums.js";
2
- import { AuthenticationError } from "../types/index.js";
3
2
  import { logger } from "../utils/logger.js";
4
- import { classifyProviderError, DEFAULT_ERROR_RULES, messageNamesStatus, } from "../utils/errorClassifier.js";
5
3
  import { createAzureAPIKeyConfig, createAzureEndpointConfig, validateApiKey, } from "../utils/providerConfig.js";
6
4
  import { transformParamsForLogging } from "../utils/transformationUtils.js";
7
5
  import { OpenAIChatCompletionsProvider } from "./openaiChatCompletionsBase.js";
8
6
  import { requiresMaxCompletionTokens } from "./openaiChatCompletionsClient.js";
7
+ import { classifyWithProviderRules } from "./rules/errorRules.js";
8
+ import { getProviderErrorRules } from "./rules/registry.js";
9
+ const AZURE_ERROR_RULES = getProviderErrorRules("azure");
9
10
  /**
10
11
  * Azure OpenAI Provider — direct HTTP, no AI SDK.
11
12
  *
@@ -158,26 +159,7 @@ export class AzureOpenAIProvider extends OpenAIChatCompletionsProvider {
158
159
  return this.azureDeployment;
159
160
  }
160
161
  formatProviderError(error) {
161
- // RULING 1 fix: previously only a "401" in the message text was
162
- // special-cased — everything else (429, 404, network errors, 5xx) fell
163
- // through to one generic ProviderError. The 401 branch below keeps its
164
- // message text byte-for-byte; DEFAULT_ERROR_RULES now gives
165
- // 429/404/network/5xx their correct classifications instead of the old
166
- // undifferentiated catch-all. The branch still reads the text, not the
167
- // structured status, so a 401 whose message names no status still falls
168
- // through to DEFAULT_ERROR_RULES as before. What changed is the match: a
169
- // status-shaped "401" ("status code 401", a leading "401 ...") rather than
170
- // any three digits, so a request id or token count no longer reads as an
171
- // auth failure.
172
- const rules = [
173
- {
174
- match: (ctx) => messageNamesStatus(ctx.message, 401),
175
- errorClass: AuthenticationError,
176
- message: "Invalid Azure OpenAI API key or endpoint.",
177
- },
178
- ...DEFAULT_ERROR_RULES,
179
- ];
180
- return classifyProviderError(error, rules, this.providerName, this.modelName);
162
+ return classifyWithProviderRules(error, AZURE_ERROR_RULES, this.providerName, this.modelName);
181
163
  }
182
164
  // ===========================================================================
183
165
  // New overridable hooks (provided by the base-enhancement branch)
@@ -6,14 +6,8 @@
6
6
  */
7
7
  import { CATALOG_JSON_ENTRIES, DECIDE_CATALOG_JSON_ENTRIES, } from "./index.generated.js";
8
8
  import { DEFAULT_ERROR_RULES } from "../../utils/errorClassifier.js";
9
- import { AuthenticationError, RateLimitError, InvalidModelError, NetworkError, ProviderError, } from "../../types/index.js";
10
- const ERROR_CLASS_MAP = {
11
- authentication: AuthenticationError,
12
- "rate-limit": RateLimitError,
13
- "invalid-model": InvalidModelError,
14
- network: NetworkError,
15
- provider: ProviderError,
16
- };
9
+ import { ProviderError } from "../../types/index.js";
10
+ import { compileErrorRules } from "../rules/errorRules.js";
17
11
  // Duplicated from tools/codegen-catalog.ts intentionally: src/ must not
18
12
  // import from tools/ (build-time tooling depends on runtime source, not the
19
13
  // reverse).
@@ -61,23 +55,16 @@ export function buildCatalogConfigOptions(entry) {
61
55
  };
62
56
  }
63
57
  function buildErrorRules(entry) {
64
- const bespoke = entry.errorRules.map((rule) => {
65
- const regex = rule.pattern ? new RegExp(rule.pattern, "i") : undefined;
66
- const needsContext = rule.message.includes("{model}") || rule.message.includes("{message}");
67
- return {
68
- match: (ctx) => (rule.status !== undefined && ctx.statusCode === rule.status) ||
69
- (regex !== undefined &&
70
- (rule.patternStatuses === undefined ||
71
- (ctx.statusCode !== undefined &&
72
- rule.patternStatuses.includes(ctx.statusCode))) &&
73
- regex.test(ctx.message)),
74
- errorClass: ERROR_CLASS_MAP[rule.class],
75
- message: needsContext
76
- ? (ctx) => interpolate(rule.message, entry, ctx.modelName, ctx.message)
77
- : interpolate(rule.message, entry),
78
- };
79
- });
80
- return [...bespoke, ...DEFAULT_ERROR_RULES];
58
+ // Catalog rules are a subset of the provider-rules format, so they compile
59
+ // through the same engine as every provider's rules file.
60
+ const vars = {
61
+ apiKeyEnvVar: catalogEnvVar(entry, "apiKey"),
62
+ setupUrl: entry.setup.url,
63
+ };
64
+ return [
65
+ ...compileErrorRules(entry.errorRules, { vars: () => vars }),
66
+ ...DEFAULT_ERROR_RULES,
67
+ ];
81
68
  }
82
69
  // Recursively freezes a value in place and returns it. Used only on a
83
70
  // structuredClone()d graph below — never on CATALOG_JSON_ENTRIES itself —
@@ -1,6 +1,5 @@
1
1
  import { CohereModels } from "../constants/enums.js";
2
- import { AuthenticationError, InvalidModelError, ProviderError, RateLimitError, } from "../types/index.js";
3
- import { classifyProviderError, DEFAULT_ERROR_RULES, } from "../utils/errorClassifier.js";
2
+ import { ProviderError } from "../types/index.js";
4
3
  import { logger } from "../utils/logger.js";
5
4
  import { redactUrlCredentials } from "../utils/logSanitize.js";
6
5
  import { createProxyFetch } from "../proxy/proxyFetch.js";
@@ -9,6 +8,9 @@ import { createTimeoutController } from "../utils/timeout.js";
9
8
  import { stripTrailingSlash } from "./openaiChatCompletionsClient.js";
10
9
  import { OpenAIChatCompletionsProvider } from "./openaiChatCompletionsBase.js";
11
10
  import { isFiniteEmbeddingVector } from "./embeddingResponseParsing.js";
11
+ import { classifyWithProviderRules } from "./rules/errorRules.js";
12
+ import { getProviderErrorRules } from "./rules/registry.js";
13
+ const COHERE_ERROR_RULES = getProviderErrorRules("cohere");
12
14
  const COHERE_DEFAULT_BASE_URL = "https://api.cohere.com/compatibility/v1";
13
15
  const getCohereApiKey = () => validateApiKey(createCohereConfig());
14
16
  const getDefaultCohereModel = () => getProviderModel("COHERE_MODEL", CohereModels.COMMAND_R_PLUS);
@@ -61,34 +63,7 @@ export class CohereProvider extends OpenAIChatCompletionsProvider {
61
63
  ];
62
64
  }
63
65
  formatProviderError(error) {
64
- const rules = [
65
- // "invalid api token" is checked lowercase (case-sensitive substring, as
66
- // in the original) — deliberately NOT normalized to match the family's
67
- // more common "Invalid API key" capitalization, since Cohere's actual
68
- // wire message differs.
69
- {
70
- match: (ctx) => /invalid api token|Authentication|401|invalid_api_token/.test(ctx.message),
71
- errorClass: AuthenticationError,
72
- message: "Invalid Cohere API key. Check COHERE_API_KEY. Get one at https://dashboard.cohere.com/api-keys",
73
- },
74
- {
75
- match: (ctx) => /rate limit|429/.test(ctx.message),
76
- errorClass: RateLimitError,
77
- message: "Cohere rate limit exceeded. Back off and retry.",
78
- },
79
- {
80
- match: (ctx) => /model_not_found|404/.test(ctx.message),
81
- errorClass: InvalidModelError,
82
- message: () => `Cohere model '${this.modelName}' not found. Use command-r, command-r-plus, or command-r7b-12-2024.`,
83
- },
84
- {
85
- match: (ctx) => /trial limit|trial_limit/.test(ctx.message),
86
- errorClass: ProviderError,
87
- message: "Cohere trial usage limit exceeded. Upgrade at https://dashboard.cohere.com/billing.",
88
- },
89
- ...DEFAULT_ERROR_RULES,
90
- ];
91
- return classifyProviderError(error, rules, this.providerName, this.modelName);
66
+ return classifyWithProviderRules(error, COHERE_ERROR_RULES, this.providerName, this.modelName, { vars: () => ({ model: `${this.modelName}` }) });
92
67
  }
93
68
  async validateConfiguration() {
94
69
  return (typeof this.config.apiKey === "string" &&
@@ -3,7 +3,7 @@ import { BaseProvider } from "../../core/baseProvider.js";
3
3
  import { IMAGE_GENERATION_MODELS, TOOL_STORAGE_TIMEOUT_MS, } from "../../core/constants.js";
4
4
  import { mergeMediaFileAliases, normalizeVisionImageFormats, processUnifiedFilesArray, } from "../../utils/messageBuilder.js";
5
5
  import { ATTR, tracers, withClientSpan, withClientStreamSpan, withSpan, } from "../../telemetry/index.js";
6
- import { AuthenticationError, InvalidModelError, NetworkError, ProviderError, RateLimitError, } from "../../types/index.js";
6
+ import { AuthenticationError, ProviderError } from "../../types/index.js";
7
7
  import { ERROR_CODES, NeuroLinkError } from "../../utils/errorHandling.js";
8
8
  import { logger } from "../../utils/logger.js";
9
9
  import { drainDetachedPump } from "../../utils/drainDetachedPump.js";
@@ -17,7 +17,7 @@ import { DEFAULT_TOOL_MAX_RETRIES, resolveToolTimeoutMs, } from "../../core/cons
17
17
  import { isToolsSchemaExclusionInForce } from "../../core/modules/structuredOutputPolicy.js";
18
18
  import { GEMINI_ELISION_NOTE, planGeminiLoopReclaim, previewGeminiToolResponseText, } from "../../context/geminiLoopGuard.js";
19
19
  import { getAvailableInputTokens, getContextWindowSize, } from "../../constants/contextWindows.js";
20
- import { composeAbortSignals, createTimeoutController, TimeoutError, } from "../../utils/timeout.js";
20
+ import { composeAbortSignals, createTimeoutController, } from "../../utils/timeout.js";
21
21
  import { withTimeout } from "../../utils/async/index.js";
22
22
  import { estimateTokens } from "../../utils/tokenEstimation.js";
23
23
  import { transformToolExecutions } from "../../utils/transformationUtils.js";
@@ -26,6 +26,11 @@ import { buildDedupedEngineTools, buildGeminiResponseSchema, buildLoopExitMessag
26
26
  import { createStreamChannel } from "../../core/streamChannel.js";
27
27
  import { toNativeToolDeclarations } from "../../core/nativeToolFormat.js";
28
28
  import { googleSdkProxyHttpOptions } from "../../proxy/proxyFetch.js";
29
+ import { classifyWithProviderRules } from "../rules/errorRules.js";
30
+ import { getProviderErrorRules } from "../rules/registry.js";
31
+ import { getWireUsage, outputWithReasoning, splitIncludedCount, } from "../rules/wireUsage.js";
32
+ const GEMINI_USAGE = getWireUsage("gemini");
33
+ const GOOGLE_AI_ERROR_RULES = getProviderErrorRules("google-ai");
29
34
  // ── Model middleware stream/generate bridges ──
30
35
  //
31
36
  // Caller model middleware (transformParams / wrapGenerate / wrapStream) is
@@ -299,61 +304,7 @@ export class GoogleAIStudioProvider extends BaseProvider {
299
304
  });
300
305
  }
301
306
  formatProviderError(error) {
302
- if (error instanceof TimeoutError) {
303
- return new NetworkError(error.message, this.providerName);
304
- }
305
- const errorRecord = error;
306
- const message = typeof errorRecord?.message === "string"
307
- ? errorRecord.message
308
- : "Unknown error";
309
- const statusCode = typeof errorRecord?.status === "number"
310
- ? errorRecord.status
311
- : typeof errorRecord?.statusCode === "number"
312
- ? errorRecord.statusCode
313
- : undefined;
314
- // Authentication errors
315
- if (message.includes("API_KEY_INVALID") ||
316
- message.includes("Invalid API key") ||
317
- statusCode === 401) {
318
- return new AuthenticationError("Invalid Google AI API key. Please check your GOOGLE_AI_API_KEY environment variable.", this.providerName);
319
- }
320
- // Rate limit errors
321
- if (message.includes("RATE_LIMIT_EXCEEDED") ||
322
- message.includes("rate limit") ||
323
- message.includes("429") ||
324
- statusCode === 429) {
325
- return new RateLimitError("Google AI rate limit exceeded. Please try again later.", this.providerName);
326
- }
327
- // Model not found errors — gate on a 404 status when available; fall
328
- // back to literal phrase matching only when we have no status code at
329
- // all. Avoids misclassifying permission/validation errors that happen
330
- // to mention model resource paths (e.g. "...models/foo permission...").
331
- if (statusCode === 404 ||
332
- (statusCode === undefined &&
333
- (message.includes("model not found") ||
334
- message.includes("Model not found")))) {
335
- return new InvalidModelError(`Model '${this.modelName}' not found. Please check the model name and ensure it is available.`, this.providerName);
336
- }
337
- // Network connectivity errors
338
- if (message.includes("ECONNRESET") ||
339
- message.includes("ENOTFOUND") ||
340
- message.includes("ETIMEDOUT") ||
341
- message.includes("ECONNREFUSED") ||
342
- message.includes("network") ||
343
- message.includes("connection")) {
344
- return new NetworkError(`Connection error: ${message}`, this.providerName);
345
- }
346
- // Server errors (5xx)
347
- if (message.includes("500") ||
348
- message.includes("502") ||
349
- message.includes("503") ||
350
- message.includes("504") ||
351
- message.includes("server error") ||
352
- message.includes("Internal Server Error") ||
353
- (statusCode && statusCode >= 500 && statusCode < 600)) {
354
- return new ProviderError(`Google AI server error: ${message}. Please try again later.`, this.providerName);
355
- }
356
- return new ProviderError(`Google AI error: ${message}`, this.providerName);
307
+ return classifyWithProviderRules(error, GOOGLE_AI_ERROR_RULES, this.providerName, this.modelName, { vars: () => ({ model: `${this.modelName}` }) });
357
308
  }
358
309
  /**
359
310
  * Overrides the BaseProvider's image generation method to implement it for Google AI.
@@ -1236,7 +1187,7 @@ export class GoogleAIStudioProvider extends BaseProvider {
1236
1187
  // cachedContentTokenCount. Subtract once here so calculateCost
1237
1188
  // bills the cached portion at the cheaper cacheRead rate without
1238
1189
  // double-counting. Total billable tokens are conserved.
1239
- const adjustedInputTokens = Math.max(0, totalInputTokens - totalCacheReadTokens);
1190
+ const adjustedInputTokens = splitIncludedCount(totalInputTokens, totalCacheReadTokens).rest;
1240
1191
  analyticsResolve({
1241
1192
  provider: this.providerName,
1242
1193
  model: modelName,
@@ -1246,7 +1197,7 @@ export class GoogleAIStudioProvider extends BaseProvider {
1246
1197
  // does NOT include them in candidatesTokenCount, so they
1247
1198
  // are folded into `output` — what calculateCost bills at
1248
1199
  // the output rate — with `reasoning` as the subset.
1249
- output: totalOutputTokens + totalReasoningTokens,
1200
+ output: outputWithReasoning(GEMINI_USAGE, totalOutputTokens, totalReasoningTokens),
1250
1201
  total: adjustedInputTokens +
1251
1202
  totalCacheReadTokens +
1252
1203
  totalOutputTokens +
@@ -1845,7 +1796,7 @@ export class GoogleAIStudioProvider extends BaseProvider {
1845
1796
  // Gemini promptTokenCount is OVERLAPPING (already includes
1846
1797
  // cachedContentTokenCount). Subtract once so the cached portion is
1847
1798
  // billed at the cheaper cacheRead rate without double-counting.
1848
- const adjustedInputTokens = Math.max(0, totalInputTokens - totalCacheReadTokens);
1799
+ const adjustedInputTokens = splitIncludedCount(totalInputTokens, totalCacheReadTokens).rest;
1849
1800
  const baseResult = {
1850
1801
  content: finalText,
1851
1802
  provider: this.providerName,
@@ -1864,7 +1815,7 @@ export class GoogleAIStudioProvider extends BaseProvider {
1864
1815
  // does NOT include them in candidatesTokenCount, so they are
1865
1816
  // folded into `output` — what calculateCost bills at the
1866
1817
  // output rate — with `reasoning` as the subset.
1867
- output: totalOutputTokens + totalReasoningTokens,
1818
+ output: outputWithReasoning(GEMINI_USAGE, totalOutputTokens, totalReasoningTokens),
1868
1819
  total: adjustedInputTokens +
1869
1820
  totalCacheReadTokens +
1870
1821
  totalOutputTokens +
@@ -21,6 +21,12 @@ import { resolveSamplingParams } from "../../models/modelRegistry.js";
21
21
  import { convertZodToJsonSchema, ensureNestedSchemaTypes, inlineJsonSchema, isZodSchema, } from "../../utils/schemaConversion.js";
22
22
  import { createNativeThinkingConfig } from "../../utils/thinkingConfig.js";
23
23
  import { resolveLiveTool } from "../../tools/toolDiscovery.js";
24
+ import { getFinishReasonMap, translateFinishReason, } from "../rules/finishReasons.js";
25
+ import { getWireUsage, readWireUsage } from "../rules/wireUsage.js";
26
+ import { compileToolNameRules, getToolNameRules } from "../rules/toolRules.js";
27
+ import { FINAL_RESULT_TOOL_NAME } from "../rules/finalResultTool.js";
28
+ const GEMINI_FINISH_REASONS = getFinishReasonMap("gemini", "generateContent");
29
+ const GEMINI_USAGE = getWireUsage("gemini");
24
30
  // ── Functions ──
25
31
  /** Stable, key-order-independent serialization of tool args for the dedup key. */
26
32
  function stableStringifyForDedup(value) {
@@ -72,60 +78,16 @@ export class DedupExecuteMap extends Map {
72
78
  }
73
79
  }
74
80
  /**
75
- * Google's `function_declarations[].name` validator regex.
76
- *
77
- * Empirically (and per the Vertex/AI Studio API error message), the server
78
- * enforces `[A-Za-z_][A-Za-z0-9_.:-]{0,127}`. Tool names that don't match
79
- * fail with HTTP 400 "Invalid function name", which surfaces as a misleading
80
- * tool-calling failure for the whole request.
81
- *
82
- * MCP-imported or user-registered tools may legally contain characters
83
- * outside this set (e.g. `/`, spaces, unicode), so we sanitize defensively
84
- * before sending to Google. The sanitized name is also used as the
85
- * `executeMap` key so the round-trip from Google's function-call response
86
- * back to our executor still works.
81
+ * Google's `function_declarations[].name` rules (gemini.json `toolNames`).
82
+ * A name outside them fails with HTTP 400 "Invalid function name", which
83
+ * surfaces as a misleading tool-calling failure for the whole request.
84
+ * MCP-imported or user-registered tools may legally contain other characters
85
+ * (`/`, spaces, unicode), so names are sanitized before sending; the
86
+ * sanitized name is also the `executeMap` key, so Google's function-call
87
+ * response still reaches our executor. Colliding names get `_2`, `_3`, …
88
+ * with room reserved so the result never exceeds the length limit.
87
89
  */
88
- const GOOGLE_FN_NAME_REGEX = /^[A-Za-z_][A-Za-z0-9_.:-]{0,127}$/;
89
- const GOOGLE_FN_NAME_MAX_LENGTH = 128;
90
- function sanitizeForGoogleFunctionName(name) {
91
- if (GOOGLE_FN_NAME_REGEX.test(name)) {
92
- return name;
93
- }
94
- let sanitized = name.replace(/[^A-Za-z0-9_.:-]/g, "_");
95
- if (!/^[A-Za-z_]/.test(sanitized)) {
96
- sanitized = `_${sanitized}`;
97
- }
98
- if (sanitized.length > GOOGLE_FN_NAME_MAX_LENGTH) {
99
- sanitized = sanitized.slice(0, GOOGLE_FN_NAME_MAX_LENGTH);
100
- }
101
- return sanitized;
102
- }
103
- /**
104
- * Resolve a sanitized Gemini tool name to one that is both unique within
105
- * the current request and at most 128 characters. When the candidate
106
- * collides with an already-used name we append `_2`, `_3`, … — but
107
- * reserve room for the suffix by truncating the base first so the
108
- * resolved name never exceeds Google's `function_declarations[].name`
109
- * limit.
110
- *
111
- * @param base The already-sanitized candidate name.
112
- * @param isTaken Predicate that returns true if `name` is already used.
113
- */
114
- function resolveUniqueGoogleFunctionName(base, isTaken) {
115
- if (!isTaken(base)) {
116
- return base;
117
- }
118
- let suffix = 2;
119
- while (true) {
120
- const suffixStr = `_${suffix}`;
121
- const trimmedBase = base.slice(0, GOOGLE_FN_NAME_MAX_LENGTH - suffixStr.length);
122
- const candidate = `${trimmedBase}${suffixStr}`;
123
- if (!isTaken(candidate)) {
124
- return candidate;
125
- }
126
- suffix++;
127
- }
128
- }
90
+ const GOOGLE_FN_NAMES = compileToolNameRules(getToolNameRules("gemini"));
129
91
  /**
130
92
  * Sanitize a JSON Schema for Gemini's proto-based API.
131
93
  *
@@ -259,7 +221,7 @@ export function buildNativeToolDeclarations(tools, reservedNames) {
259
221
  const renamedTools = [];
260
222
  // Disambiguate distinct originals that collapse onto the same sanitized
261
223
  // name (e.g. "my/tool" and "my-tool" both → "my_tool") via
262
- // resolveUniqueGoogleFunctionName, which appends `_N` while keeping the
224
+ // GOOGLE_FN_NAMES.unique, which appends `_N` while keeping the
263
225
  // final string within Google's 128-char limit. Track all assigned names
264
226
  // regardless of whether the tool has an `execute` function (tools without
265
227
  // execute are still pushed to functionDeclarations). The originalNameMap
@@ -272,8 +234,8 @@ export function buildNativeToolDeclarations(tools, reservedNames) {
272
234
  const originalNameMap = new Map();
273
235
  for (const [name, tool] of Object.entries(tools)) {
274
236
  try {
275
- const candidate = sanitizeForGoogleFunctionName(name);
276
- const safeName = resolveUniqueGoogleFunctionName(candidate, (n) => usedNames.has(n));
237
+ const candidate = GOOGLE_FN_NAMES.sanitize(name);
238
+ const safeName = GOOGLE_FN_NAMES.unique(candidate, (n) => usedNames.has(n));
277
239
  originalNameMap.set(safeName, name);
278
240
  if (safeName !== name) {
279
241
  renamedTools.push({ from: name, to: safeName });
@@ -491,6 +453,23 @@ export function computeMaxSteps(rawMaxSteps) {
491
453
  ? Math.min(Math.floor(value), GEMINI3_NATIVE_MAX_STEPS)
492
454
  : Math.min(DEFAULT_MAX_STEPS, GEMINI3_NATIVE_MAX_STEPS);
493
455
  }
456
+ /**
457
+ * Fold one chunk's `usageMetadata` into a step's running counts. Field names
458
+ * come from gemini.json's `usage` block. The cached count is a subset of the
459
+ * prompt count; the thinking count comes on top of the output count.
460
+ */
461
+ function foldGeminiChunkUsage(running, usageMetadata) {
462
+ if (!usageMetadata) {
463
+ return running;
464
+ }
465
+ const counts = readWireUsage(GEMINI_USAGE, usageMetadata);
466
+ return {
467
+ inputTokens: Math.max(running.inputTokens, counts.input || 0),
468
+ outputTokens: Math.max(running.outputTokens, counts.output || 0),
469
+ cacheReadTokens: Math.max(running.cacheReadTokens, counts.cacheRead || 0),
470
+ reasoningTokens: Math.max(running.reasoningTokens, counts.reasoning || 0),
471
+ };
472
+ }
494
473
  /**
495
474
  * Map a `@google/genai` `Candidate.finishReason` enum value onto NeuroLink's
496
475
  * unified finish reason, mirroring anthropic.ts `mapAnthropicStopReason`.
@@ -526,28 +505,7 @@ export function computeMaxSteps(rawMaxSteps) {
526
505
  * not run out.
527
506
  */
528
507
  export function mapGeminiFinishReason(raw) {
529
- switch (raw) {
530
- case "MAX_TOKENS":
531
- case "CONTINUATION":
532
- return "length";
533
- case "TOO_MANY_TOOL_CALLS":
534
- return "tool-calls";
535
- case "MALFORMED_FUNCTION_CALL":
536
- case "UNEXPECTED_TOOL_CALL":
537
- return "error";
538
- case "SAFETY":
539
- case "RECITATION":
540
- case "BLOCKLIST":
541
- case "PROHIBITED_CONTENT":
542
- case "SPII":
543
- case "LANGUAGE":
544
- case "IMAGE_SAFETY":
545
- case "IMAGE_PROHIBITED_CONTENT":
546
- case "IMAGE_RECITATION":
547
- return "content-filter";
548
- default:
549
- return "stop";
550
- }
508
+ return translateFinishReason(GEMINI_FINISH_REASONS, raw);
551
509
  }
552
510
  /**
553
511
  * Append a step's text to a running cross-step accumulator, ignoring empty
@@ -591,18 +549,9 @@ export async function collectStreamChunks(stream) {
591
549
  if (chunk.functionCalls) {
592
550
  stepFunctionCalls.push(...chunk.functionCalls);
593
551
  }
594
- // Accumulate usage metadata from chunks
595
- const usage = chunkRecord.usageMetadata;
596
- if (usage) {
597
- inputTokens = Math.max(inputTokens, usage.promptTokenCount || 0);
598
- outputTokens = Math.max(outputTokens, usage.candidatesTokenCount || 0);
599
- // cachedContentTokenCount is OVERLAPPING (a subset already inside
600
- // promptTokenCount). Surface it so the call site subtracts once.
601
- cacheReadTokens = Math.max(cacheReadTokens, usage.cachedContentTokenCount || 0);
602
- // thoughtsTokenCount (thinking tokens, billed at the output rate) is
603
- // NOT part of candidatesTokenCount — surface it separately.
604
- reasoningTokens = Math.max(reasoningTokens, usage.thoughtsTokenCount || 0);
605
- }
552
+ // Each chunk reports the step's running totals, so keep the largest.
553
+ ({ inputTokens, outputTokens, cacheReadTokens, reasoningTokens } =
554
+ foldGeminiChunkUsage({ inputTokens, outputTokens, cacheReadTokens, reasoningTokens }, chunkRecord.usageMetadata));
606
555
  }
607
556
  return {
608
557
  rawResponseParts,
@@ -656,17 +605,9 @@ export async function collectStreamChunksIncremental(stream, channel) {
656
605
  if (chunk.functionCalls) {
657
606
  stepFunctionCalls.push(...chunk.functionCalls);
658
607
  }
659
- const usage = chunkRecord.usageMetadata;
660
- if (usage) {
661
- inputTokens = Math.max(inputTokens, usage.promptTokenCount || 0);
662
- outputTokens = Math.max(outputTokens, usage.candidatesTokenCount || 0);
663
- // cachedContentTokenCount is OVERLAPPING (a subset already inside
664
- // promptTokenCount). Surface it so the call site subtracts once.
665
- cacheReadTokens = Math.max(cacheReadTokens, usage.cachedContentTokenCount || 0);
666
- // thoughtsTokenCount (thinking tokens, billed at the output rate) is
667
- // NOT part of candidatesTokenCount — surface it separately.
668
- reasoningTokens = Math.max(reasoningTokens, usage.thoughtsTokenCount || 0);
669
- }
608
+ // Each chunk reports the step's running totals, so keep the largest.
609
+ ({ inputTokens, outputTokens, cacheReadTokens, reasoningTokens } =
610
+ foldGeminiChunkUsage({ inputTokens, outputTokens, cacheReadTokens, reasoningTokens }, chunkRecord.usageMetadata));
670
611
  }
671
612
  return {
672
613
  rawResponseParts,
@@ -991,7 +932,7 @@ export function buildLoopExitMessage(params) {
991
932
  export function buildWrapupNudgeText(useFinalResultTool) {
992
933
  return ("NOTE: processing time for this turn is nearly up. Consolidate what you have and " +
993
934
  (useFinalResultTool
994
- ? "call final_result with your best answer now."
935
+ ? `call ${FINAL_RESULT_TOOL_NAME} with your best answer now.`
995
936
  : "provide your final answer now."));
996
937
  }
997
938
  /**