@juspay/neurolink 13.16.2 → 13.17.1

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 (126) hide show
  1. package/CHANGELOG.md +2 -2
  2. package/dist/adapters/providerImageAdapter.js +29 -495
  3. package/dist/browser/neurolink.min.js +465 -471
  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/core/nativeGenerateLoop.js +5 -0
  14. package/dist/factories/providerDescriptors.js +3 -2
  15. package/dist/factories/providerRegistry.js +3 -2
  16. package/dist/models/manifests/anthropic.d.ts +1 -1
  17. package/dist/models/manifests/anthropic.js +1 -1
  18. package/dist/models/manifests/azure.js +9 -9
  19. package/dist/models/manifests/ollama.js +13 -0
  20. package/dist/models/manifests/openai.d.ts +1 -1
  21. package/dist/models/manifests/openai.js +1 -1
  22. package/dist/models/modelRegistry.js +25 -42
  23. package/dist/neurolink.js +1 -0
  24. package/dist/providers/amazonBedrock/client.js +9 -37
  25. package/dist/providers/amazonBedrock/loopAdapter.js +3 -11
  26. package/dist/providers/amazonSagemaker.js +6 -0
  27. package/dist/providers/anthropic/client.js +57 -100
  28. package/dist/providers/anthropic/loopAdapter.js +24 -22
  29. package/dist/providers/anthropic/structuredOutput.d.ts +0 -2
  30. package/dist/providers/anthropic/structuredOutput.js +3 -5
  31. package/dist/providers/azureOpenai.js +4 -22
  32. package/dist/providers/catalog/loader.js +12 -25
  33. package/dist/providers/cohere.js +5 -30
  34. package/dist/providers/googleAiStudio/client.js +12 -61
  35. package/dist/providers/googleNativeGemini3/utils.js +43 -102
  36. package/dist/providers/googleVertex/client.d.ts +7 -0
  37. package/dist/providers/googleVertex/client.js +150 -192
  38. package/dist/providers/litellm/client.js +10 -50
  39. package/dist/providers/llamaCpp.js +4 -15
  40. package/dist/providers/lmStudio.js +9 -14
  41. package/dist/providers/nvidiaNim/client.js +4 -62
  42. package/dist/providers/ollama/client.js +14 -54
  43. package/dist/providers/ollama/constants.d.ts +1 -3
  44. package/dist/providers/ollama/constants.js +2 -3
  45. package/dist/providers/openAI/client.js +5 -57
  46. package/dist/providers/openRouter/client.js +4 -65
  47. package/dist/providers/openaiChatCompletionsBase.js +53 -62
  48. package/dist/providers/openaiChatCompletionsClient.js +17 -57
  49. package/dist/providers/openaiCompatible/client.js +9 -36
  50. package/dist/providers/rules/README.md +100 -0
  51. package/dist/providers/rules/anthropic.json +108 -0
  52. package/dist/providers/rules/azure.json +13 -0
  53. package/dist/providers/rules/bedrock.json +48 -0
  54. package/dist/providers/rules/cohere.json +32 -0
  55. package/dist/providers/rules/credentials.json +34 -0
  56. package/dist/providers/rules/errorRules.d.ts +17 -0
  57. package/dist/providers/rules/errorRules.js +197 -0
  58. package/dist/providers/rules/errorSignals.d.ts +2 -0
  59. package/dist/providers/rules/errorSignals.js +28 -0
  60. package/dist/providers/rules/fallbackModel.d.ts +4 -0
  61. package/dist/providers/rules/fallbackModel.js +21 -0
  62. package/dist/providers/rules/finalResultTool.d.ts +11 -0
  63. package/dist/providers/rules/finalResultTool.js +17 -0
  64. package/dist/providers/rules/finishReasons.d.ts +10 -0
  65. package/dist/providers/rules/finishReasons.js +28 -0
  66. package/dist/providers/rules/gemini.json +92 -0
  67. package/dist/providers/rules/google-ai.json +55 -0
  68. package/dist/providers/rules/limits.json +338 -0
  69. package/dist/providers/rules/litellm.json +36 -0
  70. package/dist/providers/rules/llamacpp.json +23 -0
  71. package/dist/providers/rules/lm-studio.json +21 -0
  72. package/dist/providers/rules/model-families.json +115 -0
  73. package/dist/providers/rules/modelFamilies.d.ts +10 -0
  74. package/dist/providers/rules/modelFamilies.js +45 -0
  75. package/dist/providers/rules/nvidia-nim.json +43 -0
  76. package/dist/providers/rules/ollama.json +37 -0
  77. package/dist/providers/rules/openai-chat.json +66 -0
  78. package/dist/providers/rules/openai-compatible.json +31 -0
  79. package/dist/providers/rules/openai.json +38 -0
  80. package/dist/providers/rules/openrouter.json +57 -0
  81. package/dist/providers/rules/proxy.json +44 -0
  82. package/dist/providers/rules/registry.d.ts +7 -0
  83. package/dist/providers/rules/registry.js +76 -0
  84. package/dist/providers/rules/requestDefaults.d.ts +7 -0
  85. package/dist/providers/rules/requestDefaults.js +9 -0
  86. package/dist/providers/rules/requestFields.d.ts +21 -0
  87. package/dist/providers/rules/requestFields.js +42 -0
  88. package/dist/providers/rules/sagemaker.json +88 -0
  89. package/dist/providers/rules/schema.d.ts +242 -0
  90. package/dist/providers/rules/schema.js +359 -0
  91. package/dist/providers/rules/structured-output.json +36 -0
  92. package/dist/providers/rules/thinkingLimits.d.ts +7 -0
  93. package/dist/providers/rules/thinkingLimits.js +9 -0
  94. package/dist/providers/rules/toolRules.d.ts +16 -0
  95. package/dist/providers/rules/toolRules.js +95 -0
  96. package/dist/providers/rules/usage.json +51 -0
  97. package/dist/providers/rules/vertex.json +65 -0
  98. package/dist/providers/rules/vision.json +505 -0
  99. package/dist/providers/rules/wireUsage.d.ts +38 -0
  100. package/dist/providers/rules/wireUsage.js +82 -0
  101. package/dist/providers/sagemaker/language-model.js +6 -33
  102. package/dist/providers/sagemaker/parsers.js +13 -48
  103. package/dist/providers/sagemaker/streaming.js +9 -16
  104. package/dist/proxy/claudeFormat.js +3 -16
  105. package/dist/proxy/geminiFormat.js +3 -9
  106. package/dist/proxy/openaiFormat.js +3 -16
  107. package/dist/types/generate.d.ts +2 -0
  108. package/dist/types/index.d.ts +1 -0
  109. package/dist/types/index.js +2 -0
  110. package/dist/types/providerRules.d.ts +414 -0
  111. package/dist/types/providerRules.js +10 -0
  112. package/dist/utils/errorClassifier.d.ts +2 -2
  113. package/dist/utils/errorClassifier.js +3 -2
  114. package/dist/utils/modelDetection.d.ts +1 -1
  115. package/dist/utils/modelDetection.js +30 -71
  116. package/dist/utils/providerConfig.d.ts +10 -9
  117. package/dist/utils/providerConfig.js +26 -25
  118. package/dist/utils/providerHealth.js +1 -0
  119. package/dist/utils/thinkingConfig.d.ts +1 -1
  120. package/dist/utils/thinkingConfig.js +8 -8
  121. package/dist/utils/tokenUtils.d.ts +12 -38
  122. package/dist/utils/tokenUtils.js +44 -127
  123. package/docs-site/static/search-index.json +5 -5
  124. package/package.json +2 -1
  125. package/dist/providers/localRuntimeOpenAICompat.d.ts +0 -16
  126. package/dist/providers/localRuntimeOpenAICompat.js +0 -26
@@ -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
  /**
@@ -270,6 +270,13 @@ export declare class GoogleVertexProvider extends BaseProvider {
270
270
  * tool use — it forces the opposite — so it is not gated here, consistent
271
271
  * with oauthFetch.ts leaving `"none"` alone too.
272
272
  */
273
+ /**
274
+ * max_tokens, sampling and thinking for a forced finalization call, sized to
275
+ * its own token limit. Thinking is rebuilt for that limit, so the sampling
276
+ * the first request left out while thinking was on is sent again when
277
+ * thinking no longer fits.
278
+ */
279
+ private buildClaudeFinalizationParams;
273
280
  private buildClaudeThinkingParam;
274
281
  private executeNativeAnthropicStream;
275
282
  /**